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 |
|---|---|---|---|---|---|---|---|---|---|
How do I make an exe file from a python code under Ubuntu? | 38,627,071 | <p>I'm using Ubuntu 16 64-bit and python 3.5</p>
<p>I made a program on python and I want to distribute it as an EXE for Windows users.</p>
<p>The program I made depends on pandas and matplotlib</p>
<p>I downloaded PyInstaller.tar.gz and extracted it, but I can't find any clear info on how to make make an EXE.</p>
<p>I tried </p>
<pre><code>python ../PyInstaller/pyinstaller.py --onefile ../Project/program.py
</code></pre>
<p>But it creates a sub folder with a lot of files and none of them are exe</p>
| 0 | 2016-07-28T04:23:40Z | 38,627,995 | <p>Did you read the <a href="https://pythonhosted.org/PyInstaller/usage.html" rel="nofollow">pyinstaller Manual</a>?</p>
| 1 | 2016-07-28T05:49:08Z | [
"python",
"exe",
"pyinstaller"
] |
Not able to find file using ssh on another server using python pexpect on linux | 38,627,127 | <p>I created the simple python script using pexpect, created one spwan process using </p>
<pre><code> CurrentCommand = "ssh " + serverRootUserName + "@" + serverHostName
child = pexpect.spawn(CurrentCommand)
</code></pre>
<p>Now I am running some command like ls-a or "find /opt/license/ -name '*.xml'"
using code</p>
<pre><code> child.run(mycommand)
</code></pre>
<p>it works fine if running from Pycharm but if running from terminal it is not working it is not able to find any file, I think it is looking into my local system.</p>
<p>Can anyone suggest me something. Thanks</p>
| 0 | 2016-07-28T04:30:07Z | 38,629,922 | <p>As a suggestion, have a look at the paramiko library (or fabric, which uses it, but has a specific purpose), as this is a python interface to ssh. It might make your code a bit better and more resilient against bugs or attacks. </p>
<p>However, I think the issue comes from your use of <code>run</code>. </p>
<blockquote>
<p>This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in output. If the full path to the command is not given then the path is searched.</p>
</blockquote>
<p>What you should look at is 'expect'. I.e. your spawn with <code>spawn</code> then you should use <code>expect</code> to wait for that to get to an appropiate point (such as connected, terminal ready after motd pushed etc (because ouy might have to put a username and password in etc).</p>
<p>Then you want to run <code>sendline</code> to send a line to the program. See the example: </p>
<p><a href="http://pexpect.readthedocs.io/en/latest/overview.html" rel="nofollow">http://pexpect.readthedocs.io/en/latest/overview.html</a></p>
<p>Hope that helps, and seriously, have a look at paramiko ;)</p>
| 0 | 2016-07-28T07:37:00Z | [
"python",
"python-2.7",
"ssh",
"terminal",
"pexpect"
] |
Trying to extract portion of csv to numpy array | 38,627,130 | <p>I've been at this problem for a few days and tried a couple of different approaches, but I can't seem to get it quite right. This is the a simplified version of my csv data file: testme.csv</p>
<pre><code> "Name", "City", "State", "1996-04", "1996-05", "1996-06", "1996-07"
"Bob", "Portland", "OR", 100000, 120000, 140000, 160000
"Sally", "Eugene", "OR", 50000, 75000, 80000, 90000
"Peter", "San Francisco", "CA", , , 440000, 500000
</code></pre>
<p>I want to extract the numbers as 2D array which I wish to do some math upon. However I've got these text fields before that I need to ignore. Also, some rows won't have numbers for all of the columns, but once the numbers start they are continuous to the right (i.e. some rows have empty items for the first several columns), and this can be different per row. Additionally, the real data set has hundreds of rows and dozens of columns</p>
<p>This is some of what I've tried:</p>
<pre><code> import csv
import numpy as np
filename = "testme.csv"
ifile = open(filename, 'r')
header1 = ifile.readline()
reader = csv.reader(ifile)
A = np.array([]).reshape(0, 4)
for row in reader:
print row
print row[3:]
A = np.vstack([A, row[3:]])
print A
</code></pre>
<p>And then I get this:</p>
<pre><code> ['Bob', ' "Portland"', ' "OR"', ' 100000', ' 120000', ' 140000', ' 160000']
[' 100000', ' 120000', ' 140000', ' 160000']
['Sally', ' "Eugene"', ' "OR"', ' 50000', ' 75000', ' 80000', ' 90000']
[' 50000', ' 75000', ' 80000', ' 90000']
['Peter', ' "San Francisco"', ' "CA"', ' ', ' ', ' 440000', ' 500000']
[' ', ' ', ' 440000', ' 500000']
[[' 100000' ' 120000' ' 140000' ' 160000']
[' 50000' ' 75000' ' 80000' ' 90000']
[' ' ' ' ' 440000' ' 500000']]
</code></pre>
<p>I'm close, but the elements are all now literal strings. Is there an easier way to do this and get numbers instead or do I know go through this and convert each element to numbers? And the empty elements I could benefit from clamping them to zero.</p>
<p>Thank you for advice and help ahead of time!</p>
<h1>Aaron</h1>
<p>Update (8/1/16)
I did go with the genfromtxt method as that matched what I needed a lot. Here is the result for posterity and others</p>
<pre><code> import csv
import numpy as np
NumIgnoreFirstCols = 3
filename = "testme2.csv"
ifile = open(filename, 'r')
reader = csv.reader(ifile)
header1 = next(reader)
numcols = len(header1)
#Find number of cols for usecol in genfromtxt
print("numcols", numcols)
ifile.close()
print(range(NumIgnoreFirstCols, numcols))
aMatrix = np.genfromtxt(filename, skip_header=1, delimiter=',', usecols=range(NumIgnoreFirstCols,numcols), dtype=int)
print aMatrix
normalizedMatrix = np.where(aMatrix<0, 0, aMatrix)
print(normalizedMatrix)
minValue = np.amin(normalizedMatrix)
maxValue = np.amax(normalizedMatrix)
print (minValue, maxValue)
</code></pre>
<p>Thanks again for all the help</p>
| 3 | 2016-07-28T04:30:10Z | 38,627,282 | <p>If -- and that's a big if (I kid) -- you can use <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>:</p>
<pre><code>from StringIO import StringIO
s = StringIO(''' "Name", "City", "State", "1996-04", "1996-05", "1996-06", "1996-07"
"Bob", "Portland", "OR", 100000, 120000, 140000, 160000
"Peter", "San Francisco", "CA", , , 440000, 500000 ''')
df = pd.read_csv(s,skipinitialspace=True)
</code></pre>
<p>Getting there...</p>
<pre>
>>> df
Name City State 1996-04 1996-05 1996-06 1996-07
0 Bob Portland OR 100000.0 120000.0 140000 160000
1 Peter San Francisco CA NaN NaN 440000 500000
</pre>
<p>Clamp to zero as you say:</p>
<pre><code>df = df.fillna(0)
</code></pre>
<p>I think this is the end result you wanted:</p>
<pre>
>>> df
Name City State 1996-04 1996-05 1996-06 1996-07
0 Bob Portland OR 100000.0 120000.0 140000 160000
1 Peter San Francisco CA 0.0 0.0 440000 500000
</pre>
| 1 | 2016-07-28T04:45:25Z | [
"python",
"csv",
"numpy"
] |
Trying to extract portion of csv to numpy array | 38,627,130 | <p>I've been at this problem for a few days and tried a couple of different approaches, but I can't seem to get it quite right. This is the a simplified version of my csv data file: testme.csv</p>
<pre><code> "Name", "City", "State", "1996-04", "1996-05", "1996-06", "1996-07"
"Bob", "Portland", "OR", 100000, 120000, 140000, 160000
"Sally", "Eugene", "OR", 50000, 75000, 80000, 90000
"Peter", "San Francisco", "CA", , , 440000, 500000
</code></pre>
<p>I want to extract the numbers as 2D array which I wish to do some math upon. However I've got these text fields before that I need to ignore. Also, some rows won't have numbers for all of the columns, but once the numbers start they are continuous to the right (i.e. some rows have empty items for the first several columns), and this can be different per row. Additionally, the real data set has hundreds of rows and dozens of columns</p>
<p>This is some of what I've tried:</p>
<pre><code> import csv
import numpy as np
filename = "testme.csv"
ifile = open(filename, 'r')
header1 = ifile.readline()
reader = csv.reader(ifile)
A = np.array([]).reshape(0, 4)
for row in reader:
print row
print row[3:]
A = np.vstack([A, row[3:]])
print A
</code></pre>
<p>And then I get this:</p>
<pre><code> ['Bob', ' "Portland"', ' "OR"', ' 100000', ' 120000', ' 140000', ' 160000']
[' 100000', ' 120000', ' 140000', ' 160000']
['Sally', ' "Eugene"', ' "OR"', ' 50000', ' 75000', ' 80000', ' 90000']
[' 50000', ' 75000', ' 80000', ' 90000']
['Peter', ' "San Francisco"', ' "CA"', ' ', ' ', ' 440000', ' 500000']
[' ', ' ', ' 440000', ' 500000']
[[' 100000' ' 120000' ' 140000' ' 160000']
[' 50000' ' 75000' ' 80000' ' 90000']
[' ' ' ' ' 440000' ' 500000']]
</code></pre>
<p>I'm close, but the elements are all now literal strings. Is there an easier way to do this and get numbers instead or do I know go through this and convert each element to numbers? And the empty elements I could benefit from clamping them to zero.</p>
<p>Thank you for advice and help ahead of time!</p>
<h1>Aaron</h1>
<p>Update (8/1/16)
I did go with the genfromtxt method as that matched what I needed a lot. Here is the result for posterity and others</p>
<pre><code> import csv
import numpy as np
NumIgnoreFirstCols = 3
filename = "testme2.csv"
ifile = open(filename, 'r')
reader = csv.reader(ifile)
header1 = next(reader)
numcols = len(header1)
#Find number of cols for usecol in genfromtxt
print("numcols", numcols)
ifile.close()
print(range(NumIgnoreFirstCols, numcols))
aMatrix = np.genfromtxt(filename, skip_header=1, delimiter=',', usecols=range(NumIgnoreFirstCols,numcols), dtype=int)
print aMatrix
normalizedMatrix = np.where(aMatrix<0, 0, aMatrix)
print(normalizedMatrix)
minValue = np.amin(normalizedMatrix)
maxValue = np.amax(normalizedMatrix)
print (minValue, maxValue)
</code></pre>
<p>Thanks again for all the help</p>
| 3 | 2016-07-28T04:30:10Z | 38,627,409 | <p>You can use <strong>pandas</strong>, it has the options that you need.</p>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.18.1/10min.html#min" rel="nofollow">http://pandas.pydata.org/pandas-docs/version/0.18.1/10min.html#min</a></p>
| -1 | 2016-07-28T05:00:14Z | [
"python",
"csv",
"numpy"
] |
Trying to extract portion of csv to numpy array | 38,627,130 | <p>I've been at this problem for a few days and tried a couple of different approaches, but I can't seem to get it quite right. This is the a simplified version of my csv data file: testme.csv</p>
<pre><code> "Name", "City", "State", "1996-04", "1996-05", "1996-06", "1996-07"
"Bob", "Portland", "OR", 100000, 120000, 140000, 160000
"Sally", "Eugene", "OR", 50000, 75000, 80000, 90000
"Peter", "San Francisco", "CA", , , 440000, 500000
</code></pre>
<p>I want to extract the numbers as 2D array which I wish to do some math upon. However I've got these text fields before that I need to ignore. Also, some rows won't have numbers for all of the columns, but once the numbers start they are continuous to the right (i.e. some rows have empty items for the first several columns), and this can be different per row. Additionally, the real data set has hundreds of rows and dozens of columns</p>
<p>This is some of what I've tried:</p>
<pre><code> import csv
import numpy as np
filename = "testme.csv"
ifile = open(filename, 'r')
header1 = ifile.readline()
reader = csv.reader(ifile)
A = np.array([]).reshape(0, 4)
for row in reader:
print row
print row[3:]
A = np.vstack([A, row[3:]])
print A
</code></pre>
<p>And then I get this:</p>
<pre><code> ['Bob', ' "Portland"', ' "OR"', ' 100000', ' 120000', ' 140000', ' 160000']
[' 100000', ' 120000', ' 140000', ' 160000']
['Sally', ' "Eugene"', ' "OR"', ' 50000', ' 75000', ' 80000', ' 90000']
[' 50000', ' 75000', ' 80000', ' 90000']
['Peter', ' "San Francisco"', ' "CA"', ' ', ' ', ' 440000', ' 500000']
[' ', ' ', ' 440000', ' 500000']
[[' 100000' ' 120000' ' 140000' ' 160000']
[' 50000' ' 75000' ' 80000' ' 90000']
[' ' ' ' ' 440000' ' 500000']]
</code></pre>
<p>I'm close, but the elements are all now literal strings. Is there an easier way to do this and get numbers instead or do I know go through this and convert each element to numbers? And the empty elements I could benefit from clamping them to zero.</p>
<p>Thank you for advice and help ahead of time!</p>
<h1>Aaron</h1>
<p>Update (8/1/16)
I did go with the genfromtxt method as that matched what I needed a lot. Here is the result for posterity and others</p>
<pre><code> import csv
import numpy as np
NumIgnoreFirstCols = 3
filename = "testme2.csv"
ifile = open(filename, 'r')
reader = csv.reader(ifile)
header1 = next(reader)
numcols = len(header1)
#Find number of cols for usecol in genfromtxt
print("numcols", numcols)
ifile.close()
print(range(NumIgnoreFirstCols, numcols))
aMatrix = np.genfromtxt(filename, skip_header=1, delimiter=',', usecols=range(NumIgnoreFirstCols,numcols), dtype=int)
print aMatrix
normalizedMatrix = np.where(aMatrix<0, 0, aMatrix)
print(normalizedMatrix)
minValue = np.amin(normalizedMatrix)
maxValue = np.amax(normalizedMatrix)
print (minValue, maxValue)
</code></pre>
<p>Thanks again for all the help</p>
| 3 | 2016-07-28T04:30:10Z | 38,627,434 | <p>With your sample, <code>numpy</code> <code>genfromtxt</code> works:</p>
<pre><code>In [166]: np.genfromtxt('stack38627130.csv',names=True,delimiter=',',dtype=None)
Out[166]:
array([(b'"Bob"', b' "Portland"', b' "OR"', 100000, 120000, 140000, 160000),
(b'"Sally"', b' "Eugene"', b' "OR"', 50000, 75000, 80000, 90000),
(b'"Peter"', b' "San Francisco"', b' "CA"', -1, -1, 440000, 500000)],
dtype=[('Name', 'S7'), ('City', 'S16'), ('State', 'S5'), ('199604', '<i4'), ('199605', '<i4'), ('199606', '<i4'), ('199607', '<i4')])
</code></pre>
<p>This is a 1d structured array; you access columns by field name (here derived from your header line)</p>
<pre><code>In [167]: data=_
In [168]: data['199604']
Out[168]: array([100000, 50000, -1])
In [169]: data['199607']
Out[169]: array([160000, 90000, 500000])
</code></pre>
<p>The missing fields are filled with <code>-1</code>. I think that can be changed.</p>
<p>There are other parameters for setting field names if you don't like the deduced ones.</p>
<p>Read can be restricted to the numeric columns; different fill depending on the <code>dtype</code>. </p>
<pre><code>In [171]: np.genfromtxt('stack38627130.csv',skip_header=1,delimiter=',',usecols=
...: [3,4,5,6])
Out[171]:
array([[ 100000., 120000., 140000., 160000.],
[ 50000., 75000., 80000., 90000.],
[ nan, nan, 440000., 500000.]])
In [172]: np.genfromtxt('stack38627130.csv',skip_header=1,delimiter=',',usecols=
...: [3,4,5,6],dtype=int)
Out[172]:
array([[100000, 120000, 140000, 160000],
[ 50000, 75000, 80000, 90000],
[ -1, -1, 440000, 500000]])
</code></pre>
<p>Now we get a 2d array.</p>
<p>I believe <code>pandas</code> handles missing fields better, but as long as those fields are marked with the delimiter, <code>genfromtxt</code> shouldn't have problems.</p>
<p><code>genfromtxt</code> roughly does:</p>
<pre><code>result = []
for row in reader:
data = row[3:]
data = [float(x) for x in data]
result.append(data)
result = np.array(result)
</code></pre>
<p><code>np.array</code> can do the float conversion if all the strings convert properly; it does not handle the empty ones or <code>nan</code>. Generally collecting a list of values is better than repeated <code>vstack</code> (or concatenates).</p>
| 2 | 2016-07-28T05:02:07Z | [
"python",
"csv",
"numpy"
] |
Returning to the main menu in my game - Python | 38,627,140 | <p>I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.</p>
<p>I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
</code></pre>
<p>Currently my only test is within the onePlayer() module. The idea behing my code is to ask the user if they want to continue playing. If they don't then I want the program to bring them back to the main menu.</p>
| 0 | 2016-07-28T04:31:19Z | 38,627,249 | <p>Do a try and except command. If they say no your code should be quit(). If they say yes put a continue command and it will restart the whole thing.</p>
| 0 | 2016-07-28T04:42:25Z | [
"python",
"menu"
] |
Returning to the main menu in my game - Python | 38,627,140 | <p>I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.</p>
<p>I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
</code></pre>
<p>Currently my only test is within the onePlayer() module. The idea behing my code is to ask the user if they want to continue playing. If they don't then I want the program to bring them back to the main menu.</p>
| 0 | 2016-07-28T04:31:19Z | 38,627,481 | <p>You are using <code>player</code> variable for two works, instead of that you can use another variable to just check the condition and another to take user input.</p>
<p>Also you can check the condition like : <strong><em><code>if again in ["yes","y"]</code></em></strong></p>
<pre><code>def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
#computer = WEAPON[randint(0,2)]
#temporary
computer = "paper"
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again=="yes" or again=="y":
player = False
else:
player = True
main()
main()
</code></pre>
| 0 | 2016-07-28T05:05:52Z | [
"python",
"menu"
] |
Returning to the main menu in my game - Python | 38,627,140 | <p>I am creating a Rock, Paper, Scissors game. The game has a main menu which I need to be able to return to from each sub menu. I've tried a few different method I could think of as well as looked here and elsewhere online to determine a method of solving my problem.</p>
<p>I want the user to be able to select an option from the main menu, go to the selected sub menu, then be prompted with an option to return to the main menu. For example, Select the rules sub menu, then return to the main menu. Or, select to play a round of Rock, Paper, Scissors, then select to play again or return back to the main menu.</p>
<pre><code># random integer
from random import randint
# list for weapon
WEAPON = ["Rock", "Paper", "Scissors"]
# module to run the program
#def main():
# menu()
def main():
menuSelect = ""
print("\tRock, Paper, Scissors!")
# main menu
print("\n\t\tMain Menu")
print("\t1. See the rules")
print("\t2. Play against the computer")
print("\t3. Play a two player game")
print("\t4. Quit")
menuSelect = int(input("\nPlease select one of the four options "))
while menuSelect < 1 or menuSelect > 4:
print("The selection provided is invalid.")
menuSelect = int(input("\nPlease select one of the four options "))
if menuSelect == 1:
rules()
elif menuSelect == 2:
onePlayer()
elif menuSelect == 3:
twoPlayer()
elif menuSelect == 4:
endGame()
# display the rules to the user
def rules():
print("\n\t\tRules")
print("\tThe game is simple:")
print("\tPaper Covers Rock")
print("\tRock Smashes Scissors")
print("\tScissors Cut Paper")
print("")
# one player mode
def onePlayer():
again = ""
player = False
print("\n\tPlayer VS Computer")
while player == False:
player = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player = player.lower()
computer = WEAPON[randint(0,2)]
computer = computer.lower()
if player == computer:
print(player," vs ",computer)
print("It's a tie!\n")
elif player == "rock":
if computer == "paper":
print(player," vs ",computer)
print("Paper covers rock! You lose!\n")
else:
print("Rock smashes",computer,". You win!\n")
elif player == "paper":
if computer == "scissors":
print(player," vs ",computer)
print("Scissors cut paper! You lose!\n")
else:
print("Paper covers",computer,". You win!\n")
elif player == "scissors":
if computer == "rock":
print(player," vs ",computer)
print("Rock smashes scissors! You lose!\n")
else:
print("Scissors cut",computer,". You win!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
# two player mode
def twoPlayer():
fight = False
player1 = ""
player2 = ""
print("\n\tPlayer VS Player")
while fight == False:
player1 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player1 = player1.lower()
player2 = input("\nSelect your weapon: Rock, Paper, or Scissors\n")
player2 = player2.lower()
if player1 == player2:
print(player1," vs ",player2)
print("It's a tie!\n")
elif player1 == "rock":
if player2 == "paper":
print(player1," vs ",player2)
print("Paper covers rock! Player 2 wins!\n")
else:
print("Rock smashes",player2,". Player 1 wins!\n")
elif player1 == "paper":
if player2 == "scissors":
print(player1," vs ",player2)
print("Scissors cut paper! Player 2 wins!\n")
else:
print("Paper covers",player2,". Player 1 wins!\n")
elif player1 == "scissors":
if player2 == "rock":
print(player1," vs ",player2)
print("Rock smashes scissors! Player 2 wins!\n")
else:
print("Scissors cut",player2,". Player 1 wins!\n")
else:
print("invalid input")
again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
elif again == "no" or "n":
main()
def endGame():
print("Thank you for playing!")
main()
</code></pre>
<p>Currently my only test is within the onePlayer() module. The idea behing my code is to ask the user if they want to continue playing. If they don't then I want the program to bring them back to the main menu.</p>
| 0 | 2016-07-28T04:31:19Z | 38,627,660 | <p>put your main method in a <code>while (True):</code> loop, and if option 4 is called, use <code>break</code> like this: </p>
<pre><code>elif menuSelect == 4:
break
</code></pre>
<p>add an indent to </p>
<pre><code>again = input("Would you like to play again? Yes or no\n")
again = again.lower()
if again == "yes" or "y":
player = False
else:
main()
</code></pre>
<p>and rather than calling <code>main()</code> just set <code>player = True</code> also, your Weapon array has not been defined. easy fix, just add <code>WEAPON = ["rock", "paper", "scissors"]</code> to the beginning of your <code>onePlayer():</code> method. I can see another problem, change</p>
<pre><code>if again == "yes" or "y":
</code></pre>
<p>to </p>
<pre><code>if again == "yes" or again == "y":
</code></pre>
<p>one last thing, don't forget your imports! (put it at the top of your code.)</p>
<pre><code>from random import randint
</code></pre>
<p>BTW, the <code>break</code> statement just tells python to leave whatever for loop or while loop it's in.</p>
| 0 | 2016-07-28T05:21:40Z | [
"python",
"menu"
] |
How to turn a txt file to csv | 38,627,161 | <p>I have a txt file that has 214 columns(with the data separated by spaces) and about half a million rows.</p>
<p>I want to convert txt to csv, and have used this code:</p>
<pre><code>import csv
txt_file = r"myfile.txt"
csv_file = r"myfile.csv"
in_txt = csv.reader(open(txt_file, "r"), delimiter = " ", quotechar=" ")
out_csv = csv.writer(open(csv_file, 'w', newline='\n'),delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
out_csv.writerows(in_txt)
</code></pre>
<p>But this exports my data into a csv file where all the columns are just separated by spaces, in the 1st <code>A</code> column in excel... I'd ultimately like to be able to convert txt to csv and in the process remove the <code>10th-48th, 50-61, 65, 67, 68, 71-75, 77, 78, 80-88, 91, 93, 96-100, 102, 105-110, 112-114, 116-119, 122-126, 128-134, 136-140, 142-151, 153-155, 160-162, 165-169, 172-173, 175-177, 179-187, 189-196, 198, 199 & 201-214</code> columns. I am sure this is simple but am pulling my hair out trying to work out how to do it</p>
| 0 | 2016-07-28T04:33:46Z | 38,627,234 | <p>You must set the delimiter of the <code>writer</code> to a comma.</p>
<pre><code>import csv
txt_file = r"myfile.txt"
csv_file = r"myfile.csv"
in_txt = csv.reader(open(txt_file, "r"), delimiter = " ", quotechar=" ")
out_csv = csv.writer(open(csv_file, 'w', newline='\n'),delimiter=',', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
# changed this ^
out_csv.writerows(in_txt)
</code></pre>
<p>As for removing columns, you can just throw them away for each line. A generator expression allows you to modify each line without loading them all at once</p>
<pre><code>cleaned_column_iter = (line[0:10] + line [49:50] + line [62:65] for line in txt)
# add more elements as desired ^
out_csv.writerows(cleaned_column_iter)
</code></pre>
| 1 | 2016-07-28T04:41:01Z | [
"python",
"csv"
] |
How to turn a txt file to csv | 38,627,161 | <p>I have a txt file that has 214 columns(with the data separated by spaces) and about half a million rows.</p>
<p>I want to convert txt to csv, and have used this code:</p>
<pre><code>import csv
txt_file = r"myfile.txt"
csv_file = r"myfile.csv"
in_txt = csv.reader(open(txt_file, "r"), delimiter = " ", quotechar=" ")
out_csv = csv.writer(open(csv_file, 'w', newline='\n'),delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
out_csv.writerows(in_txt)
</code></pre>
<p>But this exports my data into a csv file where all the columns are just separated by spaces, in the 1st <code>A</code> column in excel... I'd ultimately like to be able to convert txt to csv and in the process remove the <code>10th-48th, 50-61, 65, 67, 68, 71-75, 77, 78, 80-88, 91, 93, 96-100, 102, 105-110, 112-114, 116-119, 122-126, 128-134, 136-140, 142-151, 153-155, 160-162, 165-169, 172-173, 175-177, 179-187, 189-196, 198, 199 & 201-214</code> columns. I am sure this is simple but am pulling my hair out trying to work out how to do it</p>
| 0 | 2016-07-28T04:33:46Z | 38,627,250 | <p>You have to change </p>
<pre><code>out_csv = csv.writer(open(csv_file, 'w', newline='\n'),delimiter=' ', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
</code></pre>
<p>to</p>
<pre><code>out_csv = csv.writer(open(csv_file, 'w', newline='\n'),delimiter=';', quotechar=' ', quoting=csv.QUOTE_MINIMAL)
</code></pre>
<p>since you want your writer to use ';' as a delimiter in the generated csv file.
For removing the columns, i see no other way than iterating over them in a for-loop and only writing the current column if it isn't one of these.</p>
<p>Eg.:</p>
<pre><code>first_row = next(in_read);
for x in range(0, length(first_row)):
if x not 10:
write()
</code></pre>
| 0 | 2016-07-28T04:42:32Z | [
"python",
"csv"
] |
Docker Django 404 for web static files, but fine for admin static files | 38,627,393 | <p>please help me on this docker django configuration for serving static files. </p>
<p>my <code>Django</code> project running on <code>Docker</code> got some issues with delivering <code>static files</code>. </p>
<blockquote>
<p>All static files for <strong>admin view</strong> is loading fine, but static files for client web view is throwing 404 Not found Error.</p>
</blockquote>
<p>This is my <strong><code>docker.yml</code></strong> configuration details:</p>
<pre><code>web:
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- ./web:/usr/src/app
ports:
- "8000:8000"
env_file: .env
command: python manage.py runserver 0.0.0.0:8000
postgres:
image: postgres:latest
volumes:
- /var/lib/postgresql
ports:
- "5432:5432"
</code></pre>
<h3>update</h3>
<p>This is the admin static file url will look like :
<em><a href="http://developer.com:8000/static/admin/css/base.css" rel="nofollow">http://developer.com:8000/static/admin/css/base.css</a></em>
and this is how client static file url looks like:
<em><a href="http://developer.com:8000/static/css/base.css" rel="nofollow">http://developer.com:8000/static/css/base.css</a></em>
Where those admin folder in static directory is creator by running django command <code>collectstatic</code></p>
<p>I have used this setting previously, and was working fine. But when I moved the project root folder to another directory seems have this issue.</p>
<p>I am totally stuck here, many many thanks for all your help and feedback.</p>
| 0 | 2016-07-28T04:58:21Z | 38,627,667 | <p>As you have moved your project to another directory, there is a possibility that the path of your static directories are also different now. <code>Django in most scenarios use apache, nginx or some other web servers to serve static files</code>. One point to notice is that your static directory should be accessed publicly. I had gone through a problem like this before. What I did was I <code>moved static dir to document root mentioned in apache config file</code>. </p>
<p>So move your static files to the doc root of apache and update static directories in settings.py to refer to the static directory in your apache doc root. I hope this helps. </p>
| 0 | 2016-07-28T05:22:20Z | [
"python",
"django",
"docker",
"dockerfile",
"docker-machine"
] |
Docker Django 404 for web static files, but fine for admin static files | 38,627,393 | <p>please help me on this docker django configuration for serving static files. </p>
<p>my <code>Django</code> project running on <code>Docker</code> got some issues with delivering <code>static files</code>. </p>
<blockquote>
<p>All static files for <strong>admin view</strong> is loading fine, but static files for client web view is throwing 404 Not found Error.</p>
</blockquote>
<p>This is my <strong><code>docker.yml</code></strong> configuration details:</p>
<pre><code>web:
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- ./web:/usr/src/app
ports:
- "8000:8000"
env_file: .env
command: python manage.py runserver 0.0.0.0:8000
postgres:
image: postgres:latest
volumes:
- /var/lib/postgresql
ports:
- "5432:5432"
</code></pre>
<h3>update</h3>
<p>This is the admin static file url will look like :
<em><a href="http://developer.com:8000/static/admin/css/base.css" rel="nofollow">http://developer.com:8000/static/admin/css/base.css</a></em>
and this is how client static file url looks like:
<em><a href="http://developer.com:8000/static/css/base.css" rel="nofollow">http://developer.com:8000/static/css/base.css</a></em>
Where those admin folder in static directory is creator by running django command <code>collectstatic</code></p>
<p>I have used this setting previously, and was working fine. But when I moved the project root folder to another directory seems have this issue.</p>
<p>I am totally stuck here, many many thanks for all your help and feedback.</p>
| 0 | 2016-07-28T04:58:21Z | 38,634,556 | <p>This was issue with the <strong><code>STATICFILES_DIRS</code></strong> configuration in the <strong><code>settings.py</code></strong> file.</p>
<blockquote>
<p>This setting defines the additional locations the <strong>staticfiles</strong> app will traverse if the <strong>FileSystemFinder</strong> finder is enabled, e.g. if you use the collectstatic or findstatic management command or use the static file serving view.</p>
</blockquote>
<p>Following was the configuration in my settings.py:</p>
<pre><code>STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
</code></pre>
<p>Now I updated this code to:</p>
<pre><code>STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
</code></pre>
<p>And every files is loading fine.</p>
<p>Reference <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-STATICFILES_DIRS" rel="nofollow">Link</a> </p>
| 0 | 2016-07-28T11:05:26Z | [
"python",
"django",
"docker",
"dockerfile",
"docker-machine"
] |
Python eve ?where query returns empty result | 38,627,492 | <p>I have a mongo collection called Case which has the following records:</p>
<pre><code>{
_updated: "Tue, 26 Jul 2016 10:47:34 GMT",
user_id: "ronaldo",
client: "webapp",
_links: {
self: {
href: "case/57972a253d73f156b5427ac3",
title: "case"
}
},
_created: "Tue, 26 Jul 2016 09:15:17 GMT",
_id: "57972a253d73f156b5427ac3",
_etag: "e85847955b97c2a339628071397ab4cafd959062"
},
{
_updated: "Tue, 26 Jul 2016 09:20:50 GMT",
user_id: "578ca6e4daaf452467ffa9f2",
client: "webapp",
_links: {
self: {
href: "case/57972b723d73f156b5427ac4",
title: "case"
}
},
_created: "Tue, 26 Jul 2016 09:20:50 GMT",
_id: "57972b723d73f156b5427ac4",
_etag: "6a6066ed62c91d0f79bbf3a362b567f8e7710f63"
}
</code></pre>
<p>The following query returns data correctly:</p>
<pre><code>http://localhost:8000/case?where={"user_id":"ronaldo"}
</code></pre>
<p><strong>whereas the following query returns empty result set:</strong></p>
<pre><code>http://localhost:8000/case?where={"user_id":"578ca6e4daaf452467ffa9f2"}
</code></pre>
<blockquote>
<p>Please note that If I do the query directly in mongo, it works:</p>
<pre><code>db.case.find({user_id: "578ca6e4daaf452467ffa9f2"})
</code></pre>
</blockquote>
<p>Please help!</p>
| 1 | 2016-07-28T05:06:47Z | 38,628,142 | <p>It looks like your <code>user_id</code> can sometimes contain objectid-like strings. Try setting <code>query_objectid_as_string</code> in your resource settings. Quoting the <a href="http://python-eve.org/config" rel="nofollow">docs</a>:</p>
<blockquote>
<p>When [query_objectid_as_string is] enabled the Mongo parser will avoid automatically casting electable strings to ObjectIds. This can be useful in those rare occurrences where you have string fields in the database whose values can actually be casted to ObjectId values, but shouldnât. It effects queries (?where=) and parsing of payloads. Defaults to False.</p>
</blockquote>
| 1 | 2016-07-28T05:57:39Z | [
"python",
"mongodb",
"rest",
"eve"
] |
What does "== RESTART <path> ==" in the IDLE Shell mean? | 38,627,504 | <p>I have a simple script I wrote, and when trying to run it (F5) , I get this msg:</p>
<blockquote>
<p>================== RESTART: C:\Users\***\Desktop\tst.py ==================</p>
</blockquote>
<p>I restarted the shell, reopened the script, but still, the same msg appears.
I use python 3.5.1 and I tried to simplify the script as much as possible, but I still get this result. Now my script is only one line with a simple <code>print(1)</code> command and I still get this msg.</p>
<p>Was there something wrong with the shell installation?</p>
| 0 | 2016-07-28T05:07:34Z | 38,627,619 | <blockquote>
<p>I have a simple script I wrote, and when trying to run it (F5) </p>
</blockquote>
<p>That's the hotkey for IDLE to run a file. It is not ordering to do anything. It's a log statement to explicitly declare that your namespace is being cleared and the file is going to be ran fresh again. </p>
<blockquote>
<p>no, I didn't tell it to restart</p>
</blockquote>
<p>But you did... You pressed F5</p>
| 1 | 2016-07-28T05:18:19Z | [
"python",
"python-idle"
] |
What does "== RESTART <path> ==" in the IDLE Shell mean? | 38,627,504 | <p>I have a simple script I wrote, and when trying to run it (F5) , I get this msg:</p>
<blockquote>
<p>================== RESTART: C:\Users\***\Desktop\tst.py ==================</p>
</blockquote>
<p>I restarted the shell, reopened the script, but still, the same msg appears.
I use python 3.5.1 and I tried to simplify the script as much as possible, but I still get this result. Now my script is only one line with a simple <code>print(1)</code> command and I still get this msg.</p>
<p>Was there something wrong with the shell installation?</p>
| 0 | 2016-07-28T05:07:34Z | 38,867,924 | <p>The same thing is happening with my shell. In the older versions, this does not happen. I've also noticed that when I press Python 3.5.2 Module Docs, I have my Internet browser open up and I see my directory being displayed onscreen. It looks like:</p>
<p>C:\Users\mycomputername\AppData\Local\Programs\Python\Python35-32\DLLs.</p>
<p>Is that suppose to happen? Is that secured? I don't know.</p>
<p>I've also found that this prints out whenever I "imported" something. So if I use an import command, and put it right before the line of my random name, it will print out that "RESTART" thing. It's always at the beginning. Or what it reads as the beginning.</p>
| 0 | 2016-08-10T08:23:51Z | [
"python",
"python-idle"
] |
How to open .fif file format? | 38,627,520 | <p>I want to open a .fif file of size around 800MB. I googled and found that these kind of files can be opened with photoshop. Is there a way to extract the images and store in some other standard format using python or c++. </p>
| -2 | 2016-07-28T05:09:07Z | 38,628,604 | <p>FIF stands for Fractal Image Format and seems to be output of the Genuine Fractals Plugin for Adobe's Photoshop. Unfortunately, there is no format specification available and the plugin claims to use patented algorithms so you won't be able to read these files from within your own software.</p>
<p>There however are other tools which can do fractal compression. <a href="http://www.linuxjournal.com/node/4367/print" rel="nofollow">Here's</a> some information about one example. While this won't allow you to open FIF files from the Genuine Fractals Plugin, it would allow you to compress the original file, if still available.</p>
| 0 | 2016-07-28T06:28:25Z | [
"python",
"c++",
"file-io"
] |
Optimization on Python list comprehension | 38,627,620 | <pre><code>[getattr(x, contact_field_map[communication_type])
for x in curr_role_group.contacts if
getattr(x, contact_field_map[communication_type])]
</code></pre>
<p>The above is my list comprehension. The initial function and the filter clause call getattr twice. Will Python run this twice or does it optimize the calculation internally knowing it can cache the result after the first call?</p>
<p>If Python doesn't do the optimization, how can I rewrite it to run faster?</p>
| 0 | 2016-07-28T05:18:20Z | 38,627,661 | <p>Python will run the <code>getattr</code> twice -- It doesn't do any optimization (after all, how does it know that the first attribute fetch doesn't change the value of the second one?)</p>
<p>To optimize the query, you can do it in 2 stages. The first stage computes the values using a generator expression, the second stage filters those values:</p>
<pre><code>gen = (getattr(x, contact_field_map[communication_type])
for x in curr_role_group.contacts)
result = [item for item in gen if item]
</code></pre>
| 3 | 2016-07-28T05:21:43Z | [
"python"
] |
Optimization on Python list comprehension | 38,627,620 | <pre><code>[getattr(x, contact_field_map[communication_type])
for x in curr_role_group.contacts if
getattr(x, contact_field_map[communication_type])]
</code></pre>
<p>The above is my list comprehension. The initial function and the filter clause call getattr twice. Will Python run this twice or does it optimize the calculation internally knowing it can cache the result after the first call?</p>
<p>If Python doesn't do the optimization, how can I rewrite it to run faster?</p>
| 0 | 2016-07-28T05:18:20Z | 38,627,709 | <p>Give this a try:</p>
<pre><code>[res for x in curr_role_group.contacts
for res in [getattr(x, contact_field_map[communication_type])] if res]
</code></pre>
<p>For example, instead of</p>
<pre><code>[i**2 for i in range(10) if i**2 < 10]
Out: [0, 1, 4, 9]
</code></pre>
<p>You can do</p>
<pre><code>[res for i in range(10) for res in [i**2] if res < 10]
Out: [0, 1, 4, 9]
</code></pre>
<p>Here, you are computing <code>i**2</code> only once. </p>
| 1 | 2016-07-28T05:25:38Z | [
"python"
] |
Optimization on Python list comprehension | 38,627,620 | <pre><code>[getattr(x, contact_field_map[communication_type])
for x in curr_role_group.contacts if
getattr(x, contact_field_map[communication_type])]
</code></pre>
<p>The above is my list comprehension. The initial function and the filter clause call getattr twice. Will Python run this twice or does it optimize the calculation internally knowing it can cache the result after the first call?</p>
<p>If Python doesn't do the optimization, how can I rewrite it to run faster?</p>
| 0 | 2016-07-28T05:18:20Z | 38,627,770 | <p>Could you use a generator for the entire thing? Something like:</p>
<pre><code>def gen():
for x in curr_role_group.contacts:
value = getattr(x, contact_field_map[communication_type])
if value:
yield value
result = list(gen())
</code></pre>
| 0 | 2016-07-28T05:31:12Z | [
"python"
] |
How to avoid circular reference in python - a class member creating an object of another class and passing self as parameter? | 38,627,644 | <p>I need some help in terms of 'pythonic' way of handling a specific scenario.</p>
<p>I'm writing an Ssh class (wraps paramiko) that provides the capability to connect to and executes commands on a device under test (DUT) over ssh. </p>
<pre><code>class Ssh:
def connect(some_params):
# establishes connection
def execute_command(command):
# executes command and returns response
def disconnect(some_params):
# closes connection
</code></pre>
<p>Next, I'd like to create a Dut class that represents my device under test. It has other things, besides capability to execute commands on the device over ssh. It exposes a wrapper for command execution that internally invokes the Ssh's execute_command. The Ssh may change to something else in future - hence the wrapper.</p>
<pre><code>def Dut:
def __init__(some params):
self.ssh = Ssh(blah blah)
def execute_command(command)
return self.ssh.execute_command(command)
</code></pre>
<p>Next, the device supports a custom command line interface for device under test. So, a class that accepts a DUT object as an input and exposes a method to execute the customised command.</p>
<pre><code>def CustomCli:
def __init__(dut_object):
self.dut = dut_object
def _customize(command):
# return customised command
def execute_custom_command(command):
return self.dut.execute_command(_customize(command))
</code></pre>
<p>Each of the classes can be used independently (CustomCli would need a Dut object though).</p>
<p>Now, to simplify things for user, I'd like to expose a wrapper for CustomCli in the Dut class. This'll allow the creator of the Dut class to exeute a simple or custom command.
So, I modify the Dut class as below:</p>
<pre><code>def Dut:
def __init__(some params):
self.ssh = Ssh(blah blah)
self.custom_cli = Custom_cli(self) ;# how to avoid this circular reference in a pythonic way?
def execute_command(command)
return self.ssh.execute_command(command)
def execute_custom_command(command)
return self.custom_cli.execute_custom_command(command)
</code></pre>
<p>This will work, I suppose. But, in the process I've created a circular reference - Dut is pointing to CustomCli and CustomCli has a reference to it's creator Dut instance. This doesn't seem to be the correct design.
What's the best/pythonic way to deal with this?</p>
<p>Any help would be appreciated!</p>
<p>Regards</p>
<p>Sharad</p>
| 0 | 2016-07-28T05:20:16Z | 38,628,077 | <p>In general, circular references aren't a bad thing. Many programs will have them, and people just don't notice because there's another instance in-between like <code>A->B->C->A</code>. Python's garbage collector will properly take care of such constructs (unless you <strike>use</strike> implement <code>__del__</code>).</p>
<p>You can make circular references a bit easier on your conscience by using weak references. See the <code>weakref</code> module. This won't work in your case, however.</p>
<p>If you want to get rid of the circular reference, there are two way:</p>
<ol>
<li><p>Have <code>CustomCLI</code> inherit from <code>Dut</code>, so you end up with just <em>one</em> instance. You might want to read up on Mixins.</p>
<pre><code>class CLIMerger(Dut):
def execute_custom_command(command):
return self.execute_command(_customize(command))
# use self^ instead of self.dut
class CLIMixin(object):
# inherit from object, won't work on its own
def execute_custom_command(command):
return self.execute_command(_customize(command))
# use self^ instead of self.dut
class CLIDut(Dut, CLIMixin):
# now the mixin "works", but still could enhance other Duts the same way
pass
</code></pre>
<p>The Mixin is advantageous if you need several cases of merging a CLI and Dut.</p></li>
<li><p>Have an explicit interface class that combines <code>CustomCli</code> and <code>Dut</code>.</p>
<pre><code>class DutCLI(object):
def __init__(self, *bla, **blah):
self.dut = Dut(*bla, **blah)
self.cli = CustomCLI(self.dut)
</code></pre>
<p>This requires you to write boilerplate or magic to forward every call from <code>DutCLI</code> to either <code>dut</code> or <code>cli</code>.</p></li>
</ol>
| 0 | 2016-07-28T05:54:19Z | [
"python",
"python-2.7",
"python-3.x",
"design-patterns",
"design"
] |
PLY/YACC parsing conflicts on PDF | 38,627,699 | <p>I'm trying to parse PDFs with PLY lex/yacc, and Ive hit a snag regarding yacc parsing rule that govern <code>NUMBER</code> tokens, arrays, and indirect_references. </p>
<p>The relevant source:</p>
<pre><code>def p_value_list(t):
r'''value_list : value_list value
| value'''
if t.slice[0] == 'item_list':
t[0] = {'type':'value_list', 'children' : t[0]['children'] + [t[1]] }
else:
t[0] = {'type':'value_list', 'children' : [t[1]] }
pass
def p_value(t):
r'''value : dictionary
| array
| indirect_reference
| NUMBER
| HEX
| STREAM
| TEXT
| BOOL
| empty'''
t[0] = t[1]
pass
def p_indirect_reference(t):
r'''indirect_reference : NUMBER NUMBER KEY_R'''
t[0] = {'type':'indirect_reference', 'children' : [t[1], t[2]] }
pass
def p_array(t):
r'''array : LBRACKET value_list RBRACKET'''
t[0] = {'type':'array', 'children' : t[2] }
pass
</code></pre>
<p>Which results in ambiguous rules regarding <code>NUMBERS</code> (do you have a list <code>NUMBER NUMBER</code> or do you have an indirect reference <code>NUMBER NUMBER KEY_R</code>) -- The errors I get range from unexpected <code>NUMBER</code> tokens when parsing the simple array <code>[0 0 0]</code></p>
<pre><code>ERROR: Error : obj_list NUMBER NUMBER OBJ LTLT key_value_list ID LBRACKET NUMBER NUMBER . LexToken(NUMBER,'0',1,166273)
</code></pre>
<p>to errors like this</p>
<pre><code>ERROR: Error : obj_list NUMBER NUMBER OBJ LTLT key_value_list ID LBRACKET NUMBER NUMBER . LexToken(RBRACKET,']',1,88)
</code></pre>
<p>Which I assume is expecting a <code>KEY_R</code> token when really its an array of two <code>NUMBER</code> tokens: <code>[ 486 173]</code></p>
<p>For the brave, PDF Spec and full source linked.</p>
<p>[1] <a href="https://github.com/opticaliqlusion/pypdf/blob/master/pypdf.py" rel="nofollow">https://github.com/opticaliqlusion/pypdf/blob/master/pypdf.py</a></p>
<p>[2] <a href="http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/pdf_reference_1-7.pdf" rel="nofollow">http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/pdf_reference_1-7.pdf</a></p>
| 1 | 2016-07-28T05:25:17Z | 38,629,038 | <p>It's not really an ambiguity; the grammar is perfectly unambiguous. However, it is not LR(1), and an LR(1) parser cannot figure out whether to shift or reduce an integer if it is followed by another integer. (The grammar is LR(2) since the second-next token is sufficient to decide; if it is <code>R</code>, the integer is the first token in an indirect reference and should be shifted.</p>
<p>Fixing the problem is a lot trickier. In theory, you can convert any LR(2) grammar to an LR(1) grammar, but the transformation is cumbersome and I don't know of any automated tool which does it. The basic idea is to extend productions so as to avoid the need for a reduction until enough context has been encountered, and then fix the parse tree as necessary.</p>
<p>(For some other possible solutions to this problem, see below. The last option presented is my personal favourite.)</p>
<p>Here's an illustration of the LR(2)→LR(1) technique; you can see how <code>NUMBER</code> tokens are simply accrued until their disposition is known:</p>
<pre><code>value_not_number
: dictionary
| array
| HEX
| STREAM
| TEXT
| BOOL
| empty
value_list
: value_list_ends_non_number
| value_list_ends_one_number
| value_list_ends_two_numbers
| value_list_ends_indref
|
value_list_ends_one_number
: value_list_ends_non_number NUMBER
value_list_ends_two_numbers
: value_list_ends_non_number NUMBER NUMBER
| value_list_ends_two_numbers NUMBER
value_list_ends_indref
: value_list_ends_two_numbers 'R'
value_list_ends_non_number
: value_list value_not_number
array : '[' value_list ']'
</code></pre>
<p>Note that the parse tree generated by the grammar is not quite accurate, since it will parse <code>0 0 R</code> as a <code>value_list_ends_two_numbers</code> followed by an <code>R</code>. In order to retrieve the real parse tree, the reduction action for <code>value_list_ends_indref</code> needs to steal the last two numbers from its first child, use them to manufacture an indirect reference object, and then add that to the end of the first child. So the PLY grammar with actions might look like this:</p>
<pre><code>def p_unit_productions(t):
r'''value_not_number
: dictionary
| array
| HEX
| STREAM
| TEXT
| BOOL
value_list
: value_list_ends_non_number
| value_list_ends_one_number
| value_list_ends_two_numbers
| value_list_ends_indref'''
t[0] = t[1]
def p_value_list_empty(t):
r'''value_list:'''
t[0] = []
def p_value_list_push(t):
r'''value_list_ends_one_number
: value_list_ends_non_number NUMBER
value_list_ends_two_numbers
: value_list_ends_two_numbers NUMBER
value_list_ends_non_number
: value_list value_not_number'''
t[0] = t[1]
t[0].append(t[2])
def p_value_list_push2(t):
r'''value_list_ends_two_numbers
: value_list_ends_non_number NUMBER NUMBER'''
t[0] = t[1]
t[0].append(t[2])
t[0].append(t[3])
def p_indirect_reference(t):
r'''value_list_ends_indref
: value_list_ends_two_numbers 'R' '''
t[0] = t[1]
gen = t[0].pop()
obj = t[0].pop()
t[0].append({'type': 'indirect_reference',
'children': [obj, gen] })
def p_array(t):
r'''array : '[' value_list ']' '''
t[0] = {'type':'array', 'children' : t[2] }
</code></pre>
<p>That's not quite the same as yours:</p>
<ul>
<li>It doesn't bother with the <code>value_list</code> object type (which seemed to me unnecessary).</li>
<li>The grammar organization might seem a bit odd, since the functions I've defined are organized by action rather than by non-terminal, but PLY handles this fine (<a href="http://www.dabeaz.com/ply/ply.html#ply_nn25" rel="nofollow">http://www.dabeaz.com/ply/ply.html#ply_nn25</a>) and it leads to simpler actions.</li>
<li>I removed <code>value: empty</code> on the assumption that your <code>empty</code> is an empty non-terminal, as per the PLY manual; that will lead to a real ambiguity since you can't know how many empty strings are found between two non-terminals.</li>
<li>I replaced the single-character literal tokens with single-quoted symbols (<a href="http://www.dabeaz.com/ply/ply.html#ply_nn26" rel="nofollow">http://www.dabeaz.com/ply/ply.html#ply_nn26</a>), because I personally believe that it makes grammars more readable.</li>
</ul>
<p>(I haven't tested that PLY fragment; let me know if there are problems. I could easily have made some typos.)</p>
<h2>Other possible solutions</h2>
<h3>1. Use the lexical scanner</h3>
<p>As suggested in a comment, one alternative is to use the lexical scanner to recognize the entire sequence (in this case an indirect reference) which creates the need for extended lookahead.</p>
<p>In effect, this uses the lexical scanner to implement a fall-back solution. This is a common solution when there are only a few LR(2) states in the grammar. For example, <code>bison</code> itself uses this technique to distinguish between the left-hand side of a production and the use of a symbol on the right-hand side. (You can tell the difference when you see -- or fail to see -- the colon after the symbol, but you have to know when the symbol itself is the first lookahead.)</p>
<p>In some cases that may seem like a simpler solution, but in other cases it results in simply exporting the complexity from the parser to the scanner. In this particular case, for example, you probably use the longest-match lexical disambiguation algorithm to distinguish between an <code>R</code> and an identifier token which starts with <code>R</code>, and you probably have a rule which ignores whitespace. Neither of those will help you with the rule to recognize indirect references; you need to explicitly match the whitespace, and you need to explicitly verify that whatever follows the <code>R</code> cannot form a longer identifier. That's not horribly complicated, but neither is it trivial; you'll need to do some work to create appropriate test coverage.</p>
<p>As the number of possible extended-lookahead states increases, you'll find this solution increasingly complicated. (Not that the parser solution outlined above is great, either.)</p>
<h3>2. Use a GLR parser</h3>
<p>Since the grammar itself is not ambiguous, you could use a GLR parser instead of an LR(1) parser, if you had a parser generator which could produce GLR parsers. The GLR algorithm can parse any context-free grammar, but at a cost: it is slightly slower in common cases and much slower in edge cases (in some grammars, it could require quadratic or even cubic time), and typical implementations delay semantic actions until the ambiguity is resolved, which means that they don't necessarily execute in the expected order.</p>
<p>In this case, there is a much stronger disincentive for this solution: PLY
doesn't produce GLR grammars. However, <code>bison</code> does have a GLR option, and it is relatively simple to wrap a bison parser into a python module (which will quite possible be faster than the PLY parser, if that matters).</p>
<h3>3. Use a stack instead of a CFG</h3>
<p>PDF is derived from Postscript, which is a stack language. Stack languages generally don't require parsers; they have just a lexical scanner and a stack. Each token has an associated action; for many tokens (literals, for example), the action is simply to push the token onto the stack. Other tokens may have more complicated actions.</p>
<p>The <code>]</code> token, for example, creates an array by popping the stack until it finds a <code>[</code> and placing the popped elements into a newly-created array object, which it then pushes on the stack.</p>
<p>Similarly, the <code>R</code> token's action would be to pop two things off the top of the stack; check that they are numbers; and then construct an indirect reference object using the two numbers, which it would then push onto the stack.</p>
<p>PLY won't help you much in the construction of a PDF stack parser, but it will at least build the lexer for you, which is actually the most complicated part of the parser. There are not many stack operations required, and none of them are particularly challenging.</p>
| 1 | 2016-07-28T06:52:15Z | [
"python",
"pdf",
"yacc",
"ply"
] |
Pythonic way to check if a set in list is present in a different set | 38,627,760 | <p>I have a list of sets</p>
<pre><code>lst = [s1, s2, s3]
</code></pre>
<p>where </p>
<pre><code>s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])
</code></pre>
<p>and I have another set</p>
<pre><code>set1 = set([1, 2, 3, 5])
</code></pre>
<p>So when I do <code>lst - set1</code> I should get <code>set()</code>. One way of doing this is just going through each element of <code>lst</code> and then do minus with <code>set1</code>. I want to know if there is any pythonic way of doing this.</p>
<p>For Example:</p>
<pre><code>s1 = set([1, 2, 3, 4])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])
lst = [s1,s2,s3]
set1 = set([1, 2, 3, 5, 4])
</code></pre>
<p>So I need to check if any of the element in the list <code>lst</code> is present in <code>set1</code> </p>
| -2 | 2016-07-28T05:30:09Z | 38,627,799 | <p>You can use the <code>in</code> operator. It works with any array-like container including lists, tuples, sets and dictionary keys.</p>
<pre><code>set_list = [set(1, 2, 3), set(2, 3, 4), set(2, 4, 6)]
# returns True
set([1,2,3]) in set_list
# returns False
set([5, 6, 7]) in set_list
# returns False, just to show that types must match
[1, 2, 3] in set_list
</code></pre>
| 1 | 2016-07-28T05:33:28Z | [
"python",
"set"
] |
Pythonic way to check if a set in list is present in a different set | 38,627,760 | <p>I have a list of sets</p>
<pre><code>lst = [s1, s2, s3]
</code></pre>
<p>where </p>
<pre><code>s1 = set([1, 2, 3])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])
</code></pre>
<p>and I have another set</p>
<pre><code>set1 = set([1, 2, 3, 5])
</code></pre>
<p>So when I do <code>lst - set1</code> I should get <code>set()</code>. One way of doing this is just going through each element of <code>lst</code> and then do minus with <code>set1</code>. I want to know if there is any pythonic way of doing this.</p>
<p>For Example:</p>
<pre><code>s1 = set([1, 2, 3, 4])
s2 = set([2, 3, 4])
s3 = set([2, 4, 6])
lst = [s1,s2,s3]
set1 = set([1, 2, 3, 5, 4])
</code></pre>
<p>So I need to check if any of the element in the list <code>lst</code> is present in <code>set1</code> </p>
| -2 | 2016-07-28T05:30:09Z | 38,627,938 | <p>To get a list of differences between sets you could use a <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>.</p>
<pre><code>my_set = set([1, 2, 3, 5])
set_list = [
set([1, 2, 3]),
set([2, 3, 4]),
set([2, 4, 6]),
]
# find differences between sets in list and my_set, remove empty sets
[set_item - my_set for set_item in set_list if set_item - my_set]
# returns [set([4]), set([4, 6])]
# to return only empty sets
[set_item - my_set for set_item in set_list if not set_item - my_set]
</code></pre>
<p>The list comprehension loops over your list of sets <code>for set_item in set_list</code>. It then ensures that the result set isn't empty <code>if set_item - my_set</code>. Finally, it returns the result <code>set_item - my_set</code> at the left side of the statement.</p>
| 0 | 2016-07-28T05:44:31Z | [
"python",
"set"
] |
Matrix Multiplication TypeError | 38,627,780 | <p>I'm attempting to write a backpropagation algorithm and I'm encountering an error when attempting to perform a matrix multiplication. </p>
<p>I've created the following simple example to work with</p>
<pre><code># necessary functions for this example
def sigmoid(z):
return 1.0/(1.0+np.exp(-z))
def prime(z):
return sigmoid(z) * (1-sigmoid(z))
def cost_derivative(output_activations, y):
return (output_activations-y)
# Mock weight and bias matrices
weights = [np.array([[ 1, 0, 2],
[2, -1, 0],
[4, -1, 0],
[1, 3, -2],
[0, 0, -1]]),
np.array([2, 0, -1, -1, 2])]
biases = [np.array([-1, 2, 0, 0, 4]), np.array([-2])]
# The mock training example
q = [(np.array([1, -2, 3]), np.array([0])),
(np.array([2, -3, 5]), np.array([1])),
(np.array([3, 6, -1]), np.array([1])),
(np.array([4, -1, -1]), np.array([0]))]
for x, y in q:
activation = x
activations = [x]
zs = []
for w, b in zip(weights, biases):
z = np.dot(w, activation) + b
zs.append(z)
activation = sigmoid(z)
activations.append(activation)
delta = cost_derivative(activations[-1], y) * prime(zs[-1])
print(np.dot(np.transpose(weights[-1])), delta)
</code></pre>
<p>I get the following error:</p>
<pre><code>TypeError: Required argument 'b' (pos 2) not found
</code></pre>
<p>I've printed the outputs of both the <code>weights</code> transposed which is a 5x2 matrix and <code>delta</code> is a 2x1. The outputs are:</p>
<pre><code>np.transpose(weights[-1]) = [[ 2 -3]
[ 0 2]
[-1 0]
[-1 1]
[ 2 -1]]
</code></pre>
<p>and</p>
<pre><code>delta = [-0.14342712 -0.03761959]
</code></pre>
<p>so the multiplication should work and produce a 5x1 matrix</p>
| 0 | 2016-07-28T05:31:32Z | 38,627,927 | <p>There is a misplaced parenthesis on your last line. It should be</p>
<pre><code>print(np.dot(np.transpose(weights[-1]), delta))
</code></pre>
<p>instead of</p>
<pre><code>print(np.dot(np.transpose(weights[-1])), delta)
</code></pre>
| 2 | 2016-07-28T05:43:34Z | [
"python",
"numpy",
"matrix"
] |
How should I configure BitBake to cross compile my python module? | 38,627,785 | <p>I have inherited an Open Embedded / Yocto based project for which I need to amend the OS image. I would like to add a new python module - pycrypto. The project builds just fine before I make changes.</p>
<p>I have added the following BitBake recipe for pycrypto:</p>
<pre><code>DESCRIPTION = "Python crypto"
SECTION = "devel/python"
LICENSE = "PD"
SRC_URI = "https://pypi.python.org/packages/source/p/pycrypto/pycrypto-${PV}.tar.gz"
SRC_URI[md5sum] = "55a61a054aa66812daf5161a0d5d7eda"
SRC_URI[sha256sum] = "f2ce1e989b272cfcb677616763e0a2e7ec659effa67a88aa92b3a65528f60a3c"
LIC_FILES_CHKSUM = "file://README;md5=453a552a607fd82384e25db312340e9a"
S = "${WORKDIR}/pycrypto-${PV}"
inherit setuptools
</code></pre>
<p>as python-crypto_2.6.1.bb.</p>
<p>I then use this in my main OS image recipe:</p>
<pre><code>PYTHON_INSTALL = " \
python-ctypes python-subprocess python-threading python-json \
python-pyopenssl python-audio python-bsddb python-codecs python-compile python-compiler python-compression python-core python-crypt python-curses python-datetime python-db python-debugger python-dev python-difflib python-distutils python-doctest python-elementtree python-email python-fcntl python-gdbm python-hotshot python-html python-idle python-image python-io python-lang python-logging python-mailbox python-math python-mime python-mmap python-multiprocessing python-netclient python-netserver python-numbers python-pickle python-pkgutil python-pprint python-profile python-pydoc python-re python-readline python-resource python-robotparser python-shell python-smtpd python-sqlite3 python-sqlite3-tests python-stringold python-syslog python-terminal python-tests python-textutils python-tkinter python-unittest python-unixadmin python-xml python-xmlrpc python-zlib python-modules python-pyserial python-misc python-mysql python-crypto\
"
</code></pre>
<p>When the build executes (<code>bitbake my-image</code>), everything seems to go fine retrieving the sources for pycrypto. However after compilation, configure attempts to <em>run</em> the cross compiled program - which doesn't work (it's built for a different architecture) and stops bitbake creating my image. </p>
<p>Here's the logfile:</p>
<pre><code>DEBUG: Executing shell function do_compile
running build
running build_py
running build_ext
running build_configure
checking for gcc... arm-poky-linux-gnueabi-gcc -march=armv7-a -mfloat-abi=hard -mfpu=neon -mtune=cortex-a8 --sysroot=/media/parallels/build/tmp/sysroots/overo
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... configure: error: in `/media/parallels/build/tmp/work/cortexa8hf-vfp-neon-poky-linux-gnueabi/python-crypto/2.6.1-r0/pycrypto-2.6.1':
configure: error: cannot run C compiled programs.
If you meant to cross compile, use `--host'.
See `config.log' for more details
Traceback (most recent call last):
File "setup.py", line 456, in <module>
core.setup(**kw)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/core.py", line 151, in setup
dist.run_commands()
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/dist.py", line 953, in run_commands
self.run_command(cmd)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/command/build.py", line 127, in run
self.run_command(cmd_name)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setup.py", line 251, in run
self.run_command(cmd_name)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/cmd.py", line 326, in run_command
self.distribution.run_command(command)
File "/media/parallels/build/tmp/sysroots/x86_64-linux/usr/lib/python2.7/distutils/dist.py", line 972, in run_command
cmd_obj.run()
File "setup.py", line 278, in run
raise RuntimeError("autoconf error")
RuntimeError: autoconf error
ERROR: python setup.py build_ext execution failed.
WARNING: exit code 1 from a shell command.
ERROR: Function failed: do_compile (log file is located at /media/parallels/build/tmp/work/cortexa8hf-vfp-neon-poky-linux-gnueabi/python-crypto/2.6.1-r0/temp/log.do_compile.6553)
</code></pre>
<p>I'm building from an x64 host and targeting an ARM processor. </p>
<p>The advice in the logfile seems reasonable - "If you meant to cross compile, use `--host'." - the only problem is <em>where</em> do I use --host? </p>
<p>Also, it's a bit disconcerting that a search of the existing project sources reveal no other instances of <code>--host</code> being used and it all builds for ARM just fine so maybe this message is leading me astray.</p>
<p>Can anyone help with configuring BitBake/automake/whatever-part-of-the-Open-Embedded-toolchain so that once my module has been cross compiled it doesn't then try to execute it on my host machine (wrong architecture)?</p>
<p>Thanks!</p>
| 0 | 2016-07-28T05:32:35Z | 38,631,531 | <p>layers.openembedded.org is your friend: <a href="http://git.yoctoproject.org/cgit/cgit.cgi/meta-security/tree/recipes-devtools/python/python-pycrypto_2.6.1.bb?h=master" rel="nofollow">http://git.yoctoproject.org/cgit/cgit.cgi/meta-security/tree/recipes-devtools/python/python-pycrypto_2.6.1.bb?h=master</a></p>
<p>This needs to be reviewed and ideally moved to meta-python, but it should work. Specifically I see that it includes autotools which then does the cross-compilation magic for you.</p>
| 1 | 2016-07-28T08:55:08Z | [
"python",
"cross-compiling",
"distutils",
"bitbake",
"openembedded"
] |
How do I programmatically send encrypted emails in Outlook Express using Python? | 38,627,812 | <p>I'm a new programmer and I've reached the point where my lack of knowledge (of the C# and VBA language) and experience is preventing me from continuing with my program. I only know Python and all the documentation that I've tried digging into is in C# and VB.</p>
<p>My story: I'm working on a GUI that automates and manages specialized email operations for my company using Outlook Express 2016. I've figured out that win32com is the package to use, and I've figured out how to create and send basic emails, but I'm struggling to figure out how to send emails encrypted. My company uses the McAfee SaaS Email Encryption add-in found at: <a href="http://www.mcafee.com/us/downloads/saas/encrypted-from-microsoft-outlook-addin.aspx" rel="nofollow">http://www.mcafee.com/us/downloads/saas/encrypted-from-microsoft-outlook-addin.aspx</a>. </p>
<p>Note: the site doesn't specify that this add-in is supported in the 2016 version but it indeed works. Also, the built-in Outlook option to encrypt all emails is not viable because I need some emails to not be encrypted.</p>
<p>What I've garnered from another similar post is that I need to use the PropertyAccessor method:</p>
<pre><code>mailItem.PropertyAccessor.SetProperty(
"http://schemas.microsoft.com/mapi/proptag/0xHHHHHHHH", x);
</code></pre>
<p>where <code>HHHHHHHH</code> is some hexadecimal code and <code>x</code> represents a state such as 0 = off. I tried digging into some property tag documentation but I'm having trouble understanding them.</p>
<p>Am I on the right track? There may be a completely different + easier way of doing this. I do realize a lot of my difficulty may be due to not knowing C#/VBA, but it would be highly appreciated if someone out there can point me in the right direction. </p>
| 0 | 2016-07-28T05:34:09Z | 38,664,367 | <ol>
<li><p>First you need a Secure Email certificate issued to the email address you want to use.
Lets say thisis mymail.somecompany.com. Your cert should have this in the subject name
and should be enabled for secure email. </p></li>
<li><p>Next you need to programatically get the certificate or load from a pfx file like
X509Store store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates;
X509Certificate2 certificate = null;
foreach (X509Certificate2 cert in certs)
{
if (cert.Subject.IndexOf("mymail@somecompany.com") >= 0)
{
certificate = cert;
break;
}
}</p></li>
<li><p>Next you need to have an entity that you want to sign and send.
string strbody = @"Content-Type: text/plain;charset=""iso-8859-1""
Content-Transfer-Encoding: quoted-printable</p></li>
</ol>
<p>This is a test s/mime message";
This is where it gets a little not very intuitive since there is no programatic way of creating the email entity you want to send
Note the headers and a series of two \r\n before the entity body "this is a test s/mime" message begins</p>
<ol start="3">
<li><p>Next you need to generate a signed envelope for this content</p>
<p>byte[] data = Encoding.ASCII.GetBytes(strbody);
ContentInfo content = new ContentInfo(data);
SignedCms signedCms = new SignedCms(content, false);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);<br>
signedCms.ComputeSignature(signer);
byte[] signedbytes = signedCms.Encode(); </p></li>
<li><p>Now that you have the content you want to send is signed with the certificate of your choice you need to
create a mail message object and create an alternate view and add this to your alternate view collection</p>
<p>MailMessage msg = new MailMessage();
msg.From = new MailAddress("");
msg.To.Add(new MailAddress(""));
msg.Subject = "test s/mime";</p>
<p>MemoryStream ms = new MemoryStream(signedbytes);
AlternateView av = new AlternateView(ms, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
msg.AlternateViews.Add(av);</p></li>
<li><p>Now that you have the message prepared you can just send it
SmtpClient client = new SmtpClient("smtphost", 25);
client.UseDefaultCredentials = true;
client.Send(msg);</p></li>
</ol>
<p>This is a kind of hack at this time and requires some manual preparation of the entity body
you want to sign. I need to do some more research on this and find out if there is a better way of doing this. </p>
| 0 | 2016-07-29T17:26:33Z | [
"c#",
"python",
"email",
"encryption",
"outlook"
] |
Python : How to read all files in the directory with some specific condition? | 38,627,853 | <p>I want to read all the files in one directory. Directory contains following files: </p>
<pre><code>ABC11_1.csv
ABC11_3.csv
ABC11_2.csv
ABC13_4.csv
ABC13_1.csv
ABC17_6.csv
ABC17_2.csv
ABC17_4.csv
ABC17_8.csv
</code></pre>
<p>When I'm running my script I want to give this file name on the console in the format as :
<strong>ABC11.</strong></p>
<p>After that I want to read all the files with only ABC11 extensions in the sorted order. i.e. first ABC11_1.csv,ABC11_2.csv,ABC11_3.csv like that.</p>
<p>If user gives only ABC application must have to give error message. If user gives only ABC1 then it is valid application accept this and check in the directory for files with the extension ABC1, if available then process the files in sorted order,if not then error message.</p>
<p><strong>Program-Code-</strong></p>
<pre><code>from glob import glob
import os
import sys
file_pattern = ''
files_list = list()
arguments = {'ABC', 'PQR', 'XYZ'}
if len(sys.argv[1:2]) is 1:
file_pattern = str(sys.argv[1:2])
else:
print 'run as <python test.py ABC>'
sys.exit(1)
if file_pattern in arguments:
print '<Provide LineName with some Number>'
sys.exit(1)
file_pattern = file_pattern.replace('[','').replace(']','').replace('\'','')
if file_pattern.startswith('ABC',0,3):
files_list = glob(os.path.join('<directory name>', str(file_pattern)+'_*.csv'))
else:
print 'No Such File --> ' + str(file_pattern)+ '\t <Provide appropriate Name>'
sys.exit(1)
if files_list:
for a_file in sorted(files_list):
print a_file
#process file
else:
print 'No Such File --> ' + str(file_pattern)+ '\t <Provide appropriate Name>'
sys.exit(1)
</code></pre>
<p>I'm doing like that and it work's fine for me but is that other best ways to do this stuff. Please provide all your responses?</p>
<p>Thanks.</p>
| 0 | 2016-07-28T05:37:21Z | 38,629,227 | <p>According to your question, following pseudo code should work</p>
<pre><code>import os
# Read all files from a directory, and read your input argument
files = os.listdir("your_input_directory_path")
input_argument = "ABC11"
# Sort file names by name
files = sorted(files)
relevant_files = []
for file_name in files:
# Your Conditions goes here ........
if file_name.startswith(input_argument):
relevant_files.append(file_name)
if relevant_files:
return "Error | Not Found"
else:
return relevant_files
</code></pre>
| 0 | 2016-07-28T07:02:39Z | [
"python",
"file",
"directory",
"glob"
] |
Sort within a group and add a columns indicating rows below and above | 38,627,854 | <p>I have a pandas dataframe that contains something like</p>
<p><code>+------+--------+-----+-------+
| Team | Gender | Age | Name |
+------+--------+-----+-------+
| A | M | 22 | Sam |
| A | F | 25 | Annie |
| B | M | 33 | Fred |
| B | M | 18 | James |
| A | M | 56 | Alan |
| B | F | 28 | Julie |
| A | M | 33 | Greg |
+------+--------+-----+-------+</code></p>
<p>What I'm trying to do is first group by <code>Team</code> and <code>Gender</code> (which I have been able to do so by using: <code>df.groupby(['Team'], as_index=False)</code></p>
<p>Is there a way to sort the members of the group based on their age and add extra columns in there which would indicate how many members are above any particular member and how many below?</p>
<p>eg:
For group 'Team A':</p>
<p><code>+------+--------+-----+-------+---------+---------+---------+---------+
| Team | Gender | Age | Name | M_Above | M_Below | F_Above | F_Below |
+------+--------+-----+-------+---------+---------+---------+---------+
| A | M | 22 | Sam | 0 | 2 | 0 | 1 |
| A | F | 25 | Annie | 1 | 2 | 0 | 0 |
| A | M | 33 | Greg | 1 | 1 | 1 | 0 |
| A | M | 56 | Alan | 2 | 0 | 1 | 0 |
+------+--------+-----+-------+---------+---------+---------+---------+
</code></p>
| 2 | 2016-07-28T05:37:21Z | 38,631,348 | <pre><code>import pandas as pd
df = pd.DataFrame({'Team':['A','A','B','B','A','B','A'], 'Gender':['M','F','M','M','M','F','M'],
'Age':[22,25,33,18,56,28,33], 'Name':['Sam','Annie','Fred','James','Alan','Julie','Greg']}).sort_values(['Team','Age'])
for idx, data in df.groupby(['Team'], as_index=False):
m_tot = data['Gender'].value_counts()[0] # number of males in current team
f_tot = data['Gender'].value_counts()[1] # dido^ (females)
m_seen = 0 # males seen so far for current team
f_seen = 0 # dido^ (females)
for row in data.iterrows():
(M_Above, M_below, F_Above, F_Below) = (m_seen, m_tot-m_seen, f_seen, f_tot-f_seen)
if row[1].Gender == 'M':
m_seen += 1
M_below -= 1
else:
f_seen += 1
F_Below -= 1
df.loc[row[0],'M_Above'] = M_Above
df.loc[row[0],'M_Below'] = M_below
df.loc[row[0],'F_Above'] = F_Above
df.loc[row[0],'F_Below'] = F_Below
</code></pre>
<p>And it results as:</p>
<pre><code> Age Gender Team M_Above M_below F_Above F_Below
0 22 M A 0.0 2.0 0.0 1.0
1 25 F A 1.0 2.0 0.0 0.0
6 33 M A 1.0 1.0 1.0 0.0
4 56 M A 2.0 0.0 1.0 0.0
3 18 M B 0.0 1.0 0.0 1.0
5 28 F B 1.0 1.0 0.0 0.0
2 33 M B 1.0 0.0 1.0 0.0
</code></pre>
<p>And if you wish to get the new columns as <code>int</code> (as in your example), use:</p>
<pre><code>for new_col in ['M_Above', 'M_Below', 'F_Above', 'F_Below']:
df[new_col] = df[new_col].astype(int)
</code></pre>
<p>Which results:</p>
<pre><code> Age Gender Name Team M_Above M_Below F_Above F_Below
0 22 M Sam A 0 2 0 1
1 25 F Annie A 1 2 0 0
6 33 M Greg A 1 1 1 0
4 56 M Alan A 2 0 1 0
3 18 M James B 0 1 0 1
5 28 F Julie B 1 1 0 0
2 33 M Fred B 1 0 1 0
</code></pre>
<p><strong>EDIT:</strong> (running times comparison)</p>
<p>Note that this solution is faster than using <code>ix</code> (the approved solution). Average running time (over 1000 iterations) is <em>~6 times faster</em> (which would probably matter in bigger DataFrames). Run this to check:</p>
<pre><code>import pandas as pd
from time import time
import numpy as np
def f(x):
for i,d in x.iterrows():
above = x.ix[:i, 'Gender'].drop(i).value_counts().reindex(['M','F'])
below = x.ix[i:, 'Gender'].drop(i).value_counts().reindex(['M','F'])
x.ix[i,'M_Above'] = above.ix['M']
x.ix[i,'M_Below'] = below.ix['M']
x.ix[i,'F_Above'] = above.ix['F']
x.ix[i,'F_Below'] = below.ix['F']
return x
df = pd.DataFrame({'Team':['A','A','B','B','A','B','A'], 'Gender':['M','F','M','M','M','F','M'],
'Age':[22,25,33,18,56,28,33], 'Name':['Sam','Annie','Fred','James','Alan','Julie','Greg']}).sort_values(['Team','Age'])
times = []
times2 = []
for i in range(1000):
tic = time()
for idx, data in df.groupby(['Team'], as_index=False):
m_tot = data['Gender'].value_counts()[0] # number of males in current team
f_tot = data['Gender'].value_counts()[1] # dido^ (females)
m_seen = 0 # males seen so far for current team
f_seen = 0 # dido^ (females)
for row in data.iterrows():
(M_Above, M_below, F_Above, F_Below) = (m_seen, m_tot-m_seen, f_seen, f_tot-f_seen)
if row[1].Gender == 'M':
m_seen += 1
M_below -= 1
else:
f_seen += 1
F_Below -= 1
df.loc[row[0],'M_Above'] = M_Above
df.loc[row[0],'M_Below'] = M_below
df.loc[row[0],'F_Above'] = F_Above
df.loc[row[0],'F_Below'] = F_Below
toc = time()
times.append(toc-tic)
for i in range(1000):
tic = time()
df1 = df.groupby('Team', sort=False).apply(f).fillna(0)
df1.ix[:,'M_Above':] = df1.ix[:,'M_Above':].astype(int)
toc = time()
times2.append(toc-tic)
print(np.mean(times))
print(np.mean(times2))
</code></pre>
<p>Results:</p>
<pre><code>0.0163134906292 # alternative solution
0.0622982912064 # approved solution
</code></pre>
| 2 | 2016-07-28T08:46:52Z | [
"python",
"pandas",
"dataframe"
] |
Sort within a group and add a columns indicating rows below and above | 38,627,854 | <p>I have a pandas dataframe that contains something like</p>
<p><code>+------+--------+-----+-------+
| Team | Gender | Age | Name |
+------+--------+-----+-------+
| A | M | 22 | Sam |
| A | F | 25 | Annie |
| B | M | 33 | Fred |
| B | M | 18 | James |
| A | M | 56 | Alan |
| B | F | 28 | Julie |
| A | M | 33 | Greg |
+------+--------+-----+-------+</code></p>
<p>What I'm trying to do is first group by <code>Team</code> and <code>Gender</code> (which I have been able to do so by using: <code>df.groupby(['Team'], as_index=False)</code></p>
<p>Is there a way to sort the members of the group based on their age and add extra columns in there which would indicate how many members are above any particular member and how many below?</p>
<p>eg:
For group 'Team A':</p>
<p><code>+------+--------+-----+-------+---------+---------+---------+---------+
| Team | Gender | Age | Name | M_Above | M_Below | F_Above | F_Below |
+------+--------+-----+-------+---------+---------+---------+---------+
| A | M | 22 | Sam | 0 | 2 | 0 | 1 |
| A | F | 25 | Annie | 1 | 2 | 0 | 0 |
| A | M | 33 | Greg | 1 | 1 | 1 | 0 |
| A | M | 56 | Alan | 2 | 0 | 1 | 0 |
+------+--------+-----+-------+---------+---------+---------+---------+
</code></p>
| 2 | 2016-07-28T05:37:21Z | 38,631,403 | <p>You can apply custom function <code>f</code> with <code>groupby</code> by column <code>Team</code>.</p>
<p>In function <code>f</code> for each row first filter above and below values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> value and get values desired values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow"><code>value_counts</code></a>. Some values are missing, so need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow"><code>reindex</code></a> and then select by <code>ix</code>:</p>
<pre><code>def f(x):
for i,d in x.iterrows():
above = x.ix[:i, 'Gender'].drop(i).value_counts().reindex(['M','F'])
below = x.ix[i:, 'Gender'].drop(i).value_counts().reindex(['M','F'])
x.ix[i,'M_Above'] = above.ix['M']
x.ix[i,'M_Below'] = below.ix['M']
x.ix[i,'F_Above'] = above.ix['F']
x.ix[i,'F_Below'] = below.ix['F']
return x
df1 = df.groupby('Team', sort=False).apply(f).fillna(0)
#cast float to int
df1.ix[:,'M_Above':] = df1.ix[:,'M_Above':].astype(int)
print (df1)
Age Gender Name Team M_Above M_Below F_Above F_Below
0 22 M Sam A 0 2 0 1
1 25 F Annie A 1 2 0 0
6 33 M Greg A 1 1 1 0
4 56 M Alan A 2 0 1 0
3 18 M James B 0 1 0 1
5 28 F Julie B 1 1 0 0
2 33 M Fred B 1 0 1 0
</code></pre>
| 1 | 2016-07-28T08:49:27Z | [
"python",
"pandas",
"dataframe"
] |
How to paste a PNG image with transparency to another image in PIL without white pixels? | 38,627,870 | <p>I have two images, a background and a PNG image with transparent pixels. I am trying to paste the PNG onto the background using Python-PIL but when I paste the two images I get white pixels around the PNG image where there were transparent pixels. </p>
<p>My code: </p>
<pre><code>import os
from PIL import Image, ImageDraw, ImageFont
filename='pikachu.png'
ironman = Image.open(filename, 'r')
filename1='bg.png'
bg = Image.open(filename1, 'r')
text_img = Image.new('RGBA', (600,320), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(ironman, (0,0))
text_img.save("ball.png", format="png")
</code></pre>
<p>My images:<br>
<a href="http://i.stack.imgur.com/BcUf3m.png" rel="nofollow"><img src="http://i.stack.imgur.com/BcUf3m.png" alt="enter image description here"></a> <a href="http://i.stack.imgur.com/tC7som.png" rel="nofollow"><img src="http://i.stack.imgur.com/tC7som.png" alt="enter image description here"></a> </p>
<p><strong>my output image:</strong><br>
<a href="http://i.stack.imgur.com/IZtSP.png" rel="nofollow"><img src="http://i.stack.imgur.com/IZtSP.png" alt="enter image description here"></a> </p>
<p>How can I have transparent pixels instead of white?</p>
| 0 | 2016-07-28T05:38:25Z | 38,629,258 | <p>You just need to specify the image as the mask as follows in the paste function:</p>
<pre><code>import os
from PIL import Image, ImageDraw, ImageFont
filename='pikachu.png'
ironman = Image.open(filename, 'r')
filename1='bg.png'
bg = Image.open(filename1, 'r')
text_img = Image.new('RGBA', (600,320), (0, 0, 0, 0))
text_img.paste(bg, (0,0))
text_img.paste(ironman, (0,0), mask=ironman)
text_img.save("ball.png", format="png")
</code></pre>
<p>Giving you:</p>
<p><a href="http://i.stack.imgur.com/bwoXS.png" rel="nofollow"><img src="http://i.stack.imgur.com/bwoXS.png" alt="paste with transparency"></a></p>
| 3 | 2016-07-28T07:05:00Z | [
"python",
"python-imaging-library"
] |
Add elements of two list of dictionaries based on a key value pair match | 38,627,930 | <p>Given n lists with m dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries.</p>
<pre><code>l1 = [{"index":'a', "b":2,'c':9}, {"index":'b', "b":3,"c":5}, {"index":'c', "b":8,"c":8}]
l2 = [{"index":'a', "b":4,'c':8}, {"index":'b', "b":9,"c":10},{"index":None, "b":11,"c":10}]
</code></pre>
<p>I would like to produce a joined list:</p>
<pre><code>l3 = [{"index":'a', "b":6, "c":17},
{"index":'b', "b":12, "c":15},
{"index":'c', "b":8, "c":8},
{"index":None, "b":11,"c":10}]
</code></pre>
<p>I have a method that can merge the two lists. But as you can see above, I also wish to add the elements. </p>
<pre><code>def merge_lists(l1, l2, key):
merged = {}
for item in l1+l2:
if item[key] in merged:
merged[item[key]].update(item)
else:
merged[item[key]] = item
return [val for (_, val) in merged.items()]
l3 = merge_lists(l1,l2,'index')
</code></pre>
<p>What is the most efficient way to do this in Python?</p>
| 0 | 2016-07-28T05:43:44Z | 38,628,039 | <p>You can use a <code>Counter</code> for something like this pretty easily...</p>
<pre><code>from collections import defaultdict, Counter
def merge_lists(l1, l2):
d = defaultdict(Counter)
for sdict in l1 + l2:
counter = Counter(sdict)
d[counter.pop('index')] += counter
lists = []
for k, v in d.items():
result = dict(v)
result['index'] = k
lists.append(result)
return lists
l1 = [{"index":'a', "b":2,'c':9}, {"index":'b', "b":3,"c":5}, {"index":'c', "b":8,"c":8}]
l2 = [{"index":'a', "b":4,'c':8}, {"index":'b', "b":9,"c":10},{"index":None, "b":11,"c":10}]
print(merge_lists(l1, l2))
</code></pre>
<p>The great thing about adding <code>Counter</code> instances is that it pretty much just does what you expect. If one counter doesn't have the key, it adds nothing to the sum, but if both counters have the given key, then their values are added and used as the resultant value at that key.</p>
<hr>
<p>Note that the order of the merged lists is arbitrary (based on the ordering of the <code>defaultdict</code>). If you need to preserve order in some way, you can either <code>sort</code> after the fact or create a default ordered dict which will preserve the order based on when the <code>index</code> was first seen in <code>l1</code> or <code>l2</code>:</p>
<pre><code>class DefaultOrderedDict(collections.OrderedDict):
def __init__(self, default_factory, *args, **kwargs):
self.default_factory = default_factory
super(DefaultOrderedDict, self).__init__(*args, **kwargs)
def __missing__(self, key):
self[key] = self.default_factory()
return self[key]
</code></pre>
<p>(There are more "complete" default ordered dicts floating around on ActiveState and StackOverflow, but this simple one <em>should</em> work for your problem at hand)</p>
| 4 | 2016-07-28T05:51:45Z | [
"python",
"list"
] |
How can I turn dataframe rows into headers? | 38,627,981 | <p>I have some data on each of the first 151 pokemon in 151 different dataframes.</p>
<pre><code> id identifier pokemon_id stat_id base_stat local_language_id name
36 7 Squirtle 7 1 44 9 HP
37 7 Squirtle 7 2 48 9 Attack
38 7 Squirtle 7 3 65 9 Defense
39 7 Squirtle 7 4 50 9 Special Attack
40 7 Squirtle 7 5 64 9 Special Defense
41 7 Squirtle 7 6 43 9 Speed
id identifier pokemon_id stat_id base_stat local_language_id name
18 4 Charmander 4 1 39 9 HP
19 4 Charmander 4 2 52 9 Attack
20 4 Charmander 4 3 43 9 Defense
21 4 Charmander 4 4 60 9 Special Attack
22 4 Charmander 4 5 50 9 Special Defense
23 4 Charmander 4 6 65 9 Speed
</code></pre>
<p>What I would really like is one row per pokemon with each stat as a column of a new dataframe. Something like</p>
<pre><code>id identifier pokemon_id HP Attack ...
4 Charmander 4 39 52 ...
7 Squirtle 7 44 48 ...
</code></pre>
<p>Is there an easy way to do that with a pandas dataframe?</p>
| 1 | 2016-07-28T05:47:56Z | 38,628,068 | <p>I believe this will do what you're after:</p>
<pre><code>df.groupby(['id', 'identifier', 'name']).base_stat.first().unstack('name')
</code></pre>
| 4 | 2016-07-28T05:53:47Z | [
"python",
"pandas"
] |
How can I turn dataframe rows into headers? | 38,627,981 | <p>I have some data on each of the first 151 pokemon in 151 different dataframes.</p>
<pre><code> id identifier pokemon_id stat_id base_stat local_language_id name
36 7 Squirtle 7 1 44 9 HP
37 7 Squirtle 7 2 48 9 Attack
38 7 Squirtle 7 3 65 9 Defense
39 7 Squirtle 7 4 50 9 Special Attack
40 7 Squirtle 7 5 64 9 Special Defense
41 7 Squirtle 7 6 43 9 Speed
id identifier pokemon_id stat_id base_stat local_language_id name
18 4 Charmander 4 1 39 9 HP
19 4 Charmander 4 2 52 9 Attack
20 4 Charmander 4 3 43 9 Defense
21 4 Charmander 4 4 60 9 Special Attack
22 4 Charmander 4 5 50 9 Special Defense
23 4 Charmander 4 6 65 9 Speed
</code></pre>
<p>What I would really like is one row per pokemon with each stat as a column of a new dataframe. Something like</p>
<pre><code>id identifier pokemon_id HP Attack ...
4 Charmander 4 39 52 ...
7 Squirtle 7 44 48 ...
</code></pre>
<p>Is there an easy way to do that with a pandas dataframe?</p>
| 1 | 2016-07-28T05:47:56Z | 38,628,185 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>df = df.pivot_table(index=['id','identifier'],
columns='name',
values='base_stat',
aggfunc='first')
print (df)
name Attack Defense HP Special Attack Special Defense Speed
id identifier
7 Squirtle 48 65 44 50 64 43
</code></pre>
<p>If all <code>DataFrames</code> are in list <code>dfs</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</code></a> with <code>list comprehension</code>:</p>
<pre><code>dfs = [df1, df2]
df = pd.concat([df.pivot_table(index=['id','identifier'],
columns='name',
values='base_stat',
aggfunc='first') for df in dfs])
print (df)
name Attack Defense HP Special Attack Special Defense Speed
id identifier
7 Squirtle 48 65 44 50 64 43
4 Charmander 52 43 39 60 50 65
</code></pre>
<p>Last use <code>reset_index</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>), if use <code>pandas bellow 0.18.0</code> omit <code>rename_axis</code> and use <code>df.columns.name = None</code>:</p>
<pre><code>df = pd.concat([df.pivot_table(index=['id','identifier'],
columns='name',
values='base_stat',
aggfunc='first') for df in dfs])
.reset_index()
.rename_axis(None, axis=1)
print (df)
id identifier Attack Defense HP Special Attack Special Defense Speed
0 7 Squirtle 48 65 44 50 64 43
1 4 Charmander 52 43 39 60 50 65
</code></pre>
| 1 | 2016-07-28T06:00:07Z | [
"python",
"pandas"
] |
How to update a dictionary in python with another dictionary to a specific key | 38,628,054 | <p>I have two dictionaries in python, one contains three keys and one with one key. One of the key is common to both of the dictioaries but have different data within the key. I want to update that one key to the dictionary with the three keys. The one key have to replace the existing key from the other dictionary. I dont know how to do that! dictionary.update() works but it repeats the key rather than replacing.
Here is my code:</p>
<pre><code> orders = {}
orders2 = {}
orders[int(code)] = str(name),int(current_stock),int(re_order),int(target_stock),float(price)
orders2[str(user_code)] = str(orders[user_code][0]), new_stock, orders[user_code][2], str(orders[user_code][3]), str(orders[user_code][4])
</code></pre>
<p>Now i want to update orders2 into orders but if one of the "user_code" from the orders2 matches the "code" in orders, then rather than just updating it into the code, i want to replace that whole key with "orders2"</p>
<p>PS: These dictionaries are from a .txt file and in this file there are 3 different codes, its up to the user to determine the key in "orders2".</p>
<p>IF further information needed about the code please ask. Thank you!</p>
<p>FIRST OUTPUT IS: </p>
<p>{56756777: ('100 mm bolts', 15, 5, 40, 0.2), 34512340: ('plain brackets', 20, 5, 35, 0.5), 90673412: ('L-shaped brackets', 16, 5, 45, 1.2)}</p>
<p>THE SECOND OUTPUT IS(MAY VARY):</p>
<p>{'34512340': ('plain brackets', 10, 5, '35', '0.5')}</p>
<p>SO i want to replace the "34512340" key</p>
<pre><code> orders.update(orders2)
print(orders)
</code></pre>
<p>This print(orders):</p>
<p>{56756777: ('100 mm bolts', 15, 5, 40, 0.2), </p>
<p>'34512340': ('plain brackets', 10, 5, '35', '0.5'), </p>
<p>34512340: ('plain brackets', 20, 5, 35, 0.5), </p>
<p>90673412: ('L-shaped brackets', 16, 5, 45, 1.2)}</p>
<h2>You see those two "34512340" repeated, i want it to replace it.</h2>
<p>I wanted to ask this as well as i cant post anymore in 90 minutes:</p>
<p>I have a dicionray which i want to write all the data to a .txt file.
I want the data to be in line by line according to the key.
The .txt file already have some data which i want to DELETE.</p>
<pre><code> print(orders) #This is my dictionray (This can be varied)
{56756777: ('100 mm bolts', 15, 5, 40, 0.2), 34512340: ('plain brackets', 10, 5, '35', '0.5'), 90673412: ('L-shaped brackets', 16, 5, 45, 1.2)}
</code></pre>
<p>I want to write all of this in the .txt file (which i called 'items.txt') by the key. For example:</p>
<p>i want the key "56756777" which contains: "56756777: ('100 mm bolts', 15, 5, 40, 0.2)" to be in one line like this:</p>
<p>56756777,100 mm bolts, 15, 5, 40, 0.2</p>
<p>Seprated by commas for other 2 keys too</p>
<p>Thank you, your help would be appreciated.</p>
| -1 | 2016-07-28T05:52:44Z | 38,628,301 | <p>This is the reply from smarx:</p>
<p>"@SpeedDemo Looks like the issue is that the second dictionary has '34512340' as a key (a string), and the first dictionary has 34512340 as a key (an int). If you make them both the same type, dict.update should work fine for you. â smarx 3 mins ago"</p>
<p>Thank you it worked</p>
| 1 | 2016-07-28T06:07:42Z | [
"python",
"dictionary"
] |
load CSV into MySQL table with ODO python package - date error 1292 | 38,628,135 | <p>I'm trying to import a simple CSV file that I downloaded from Quandl into a MySQL table with the odo python package</p>
<pre><code>t = odo('C:\ProgramData\MySQL\MySQL Server 5.6\Uploads\WIKI_20160725.partial.csv', 'mysql+pymysql://' + self._sql._user+':'
+ self._sql._password +'@localhost/testDB::QUANDL_DATA_WIKI')
</code></pre>
<p>The first row looks like this in the CSV:</p>
<pre><code>A 7/25/2016 46.49 46.52 45.92 46.14 1719772 0 1 46.49 46.52 45.92 46.14 1719772
</code></pre>
<p>The MySQL table is defined as follows:</p>
<pre><code>Ticker varchar(255) NOT NULL,
Date date NOT NULL,
Open numeric(15,2) NULL,
High numeric(15,2) NULL,
Low numeric(15,2) NULL,
Close numeric(15,2) NULL,
Volume bigint NULL,
ExDividend numeric(15,2),
SplitRatio int NULL,
OpenAdj numeric(15,2) NULL,
HighAdj numeric(15,2) NULL,
LowAdj numeric(15,2) NULL,
CloseAdj numeric(15,2) NULL,
VolumeAdj bigint NULL,
PRIMARY KEY(Ticker,Date)
</code></pre>
<p>It throws an exception 1292 with the following info:</p>
<p>sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1292, "Incorrect date value: '7/25/2016' for column 'Date' at row 1") [SQL: 'LOAD DATA INFILE %(path)s\n INTO TABLE <code>QUANDL_DATA_WIKI</code>\n CHARACTER SET %(encoding)s\n FIELDS\n TERMINATED BY %(delimiter)s\n ENCLOSED BY %(quotechar)s\n ESCAPED BY %(escapechar)s\n LINES TERMINATED BY %(lineterminator)s\n IGNORE %(skiprows)s LINES\n '] [parameters: {'path': 'C:\ProgramData\MySQL\MySQL Server 5.6\Uploads\WIKI_20160725.partial.csv', 'quotechar': '"', 'skiprows': 0, 'lineterminator': '\r\n', 'escapechar': '\', 'delimiter': ',', 'encoding': 'utf8'}]</p>
<p>Does anyone have an idea what is wrong with the date in the first row? It doesn't seem to match it to the MySql database</p>
| 0 | 2016-07-28T05:57:17Z | 38,967,298 | <p>mysql has problems with date conversions. I noticed when I defined the date field as a varchar </p>
<pre><code>Date varchar(255) NOT NULL
</code></pre>
<p>then the csv file was read properly</p>
<p>in my SQL the conversion of the string to date format then looks like this: </p>
<pre><code>STR_TO_DATE(Date, "%m/%d/%Y")
</code></pre>
| 0 | 2016-08-16T05:36:28Z | [
"python",
"mysql",
"csv",
"sqlalchemy",
"odo"
] |
Regular expression to find the http:// link out of the provided google search results link | 38,628,165 | <p>I have</p>
<pre><code>/url?q=http://dl.mytehranmusic.com/1392/Poya/New/1392/7/8/1/&sa=U&ved=0ahUKEwjIhcufvJXOAhWKrY8KHWjQBgQQFggTMAA&usg=AFQjCNF4phMtVM1Gmm1_kTpNOM6CXO0wIw
/url?q=http://mp3lees.org/index.php%3Fq%3DSia%2B-%2BElastic%2BHeart%2B(Feat.%2BThe%2BWeeknd%2B%2B%2BDiplo)&sa=U&ved=0ahUKEwjIhcufvJXOAhWKrY8KHWjQBgQQFggZMAE&usg=AFQjCNED4J0NRY5dmpC_cYMDJP9YM_Oxww
</code></pre>
<p>I am trying to find the <code>http://</code> link out of the provided google search results link.</p>
<p>I have tried <code>href = re.findall ('/url?q=(+/S)&', mixed)</code> where <code>mixed</code> is variable name in which the unformatted link is stored.</p>
| -5 | 2016-07-28T05:59:08Z | 38,629,034 | <p>You do not really need a regex to parse query strings. Use <code>urlparse</code>:</p>
<pre><code>import urlparse
s = '/url?q=http://dl.mytehranmusic.com/1392/Poya/New/1392/7/8/1/&sa=U&ved=0ahUKEwjIhcufvJXOAhWKrY8KHWjQBgQQFggTMAA&usg=AFQjCNF4phMtVM1Gmm1_kTpNOM6CXO0wIw'
res = urlparse.parse_qs(urlparse.urlparse(s).query)
if (res['q']):
print(res['q'][0])
</code></pre>
<p>See the <a href="https://ideone.com/k2DwOD" rel="nofollow">Python demo</a></p>
<p>If you absolutely want to have a regex solution for the reason you have not explained, I'd suggest</p>
<pre><code>r'/url\?(?:\S*?&)?q=([^&]+)'
</code></pre>
<p>See the <a href="https://regex101.com/r/aW2bM8/1" rel="nofollow">regex demo</a>.</p>
<p>The <code>(?:\S*?&)</code> part allows to match the <code>q</code> anywhere inside the query string, and <code>([^&]+)</code> will match 1 or more characters other than <code>&</code> and capture into a group returned with <code>re.findall</code>.</p>
| 0 | 2016-07-28T06:51:57Z | [
"python",
"regex"
] |
Return a string outside of a class or function with Python | 38,628,210 | <p>I'm new to OOP and am trying to figure out how to get the result of something outside of a class in order to decide what to do next in my program. </p>
<p>I'm unzipping a file, and if it takes too long then I want the process to terminate. This code will do just that:</p>
<pre><code>class Command(object):
def __init__(self,cmd):
self.cmd = cmd
self.process = None
def run(self,timeout):
def target():
print("Thread started")
self.process = subprocess.Popen(self.cmd)
self.process.communicate()
print("Thread finished")
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print("\nTerminating process")
self.process.terminate()
thread.join()
print(self.process.returncode)
def unzip_file(file,dirout,attempt):
just_name = os.path.splitext(file)[0]
print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
command = Command(zip_exe+' x '+file+' -o'+path+dirout)
command.run(timeout = 300)
</code></pre>
<p>...but what if I wanted to get the the command output, outside of the function that was called inside the Class? Say to a variable called 'tmp'. I've added two annotated lines to illustrate what I'm trying to do which of course returns an error.</p>
<pre><code>class Command(object):
def __init__(self,cmd):
self.cmd = cmd
self.process = None
def run(self,timeout):
def target():
print("Thread started")
self.process = subprocess.Popen(self.cmd)
self.tmp = self.proc.stdout.read() #get the command line output
self.process.communicate()
print("Thread finished")
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print("\nTerminating process")
self.process.terminate()
thread.join()
print(self.process.returncode)
def unzip_file(file,dirout,attempt):
just_name = os.path.splitext(file)[0]
print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
command = Command(zip_exe+' x '+file+' -o'+path+dirout)
command.run(timeout = 300)
print(self.tmp) #print the command line output (doesn't work)
</code></pre>
| 0 | 2016-07-28T06:01:35Z | 38,628,741 | <p>This line <code>self.tmp = self.proc.stdout.read()</code> puts some data into a member variable. You can then use it outside of the class by simple using a reference to the object:</p>
<pre><code>...
command.run(timeout = 300)
print(command.tmp)
</code></pre>
| 1 | 2016-07-28T06:35:59Z | [
"python"
] |
Return a string outside of a class or function with Python | 38,628,210 | <p>I'm new to OOP and am trying to figure out how to get the result of something outside of a class in order to decide what to do next in my program. </p>
<p>I'm unzipping a file, and if it takes too long then I want the process to terminate. This code will do just that:</p>
<pre><code>class Command(object):
def __init__(self,cmd):
self.cmd = cmd
self.process = None
def run(self,timeout):
def target():
print("Thread started")
self.process = subprocess.Popen(self.cmd)
self.process.communicate()
print("Thread finished")
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print("\nTerminating process")
self.process.terminate()
thread.join()
print(self.process.returncode)
def unzip_file(file,dirout,attempt):
just_name = os.path.splitext(file)[0]
print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
command = Command(zip_exe+' x '+file+' -o'+path+dirout)
command.run(timeout = 300)
</code></pre>
<p>...but what if I wanted to get the the command output, outside of the function that was called inside the Class? Say to a variable called 'tmp'. I've added two annotated lines to illustrate what I'm trying to do which of course returns an error.</p>
<pre><code>class Command(object):
def __init__(self,cmd):
self.cmd = cmd
self.process = None
def run(self,timeout):
def target():
print("Thread started")
self.process = subprocess.Popen(self.cmd)
self.tmp = self.proc.stdout.read() #get the command line output
self.process.communicate()
print("Thread finished")
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print("\nTerminating process")
self.process.terminate()
thread.join()
print(self.process.returncode)
def unzip_file(file,dirout,attempt):
just_name = os.path.splitext(file)[0]
print('unzip started at {} for {}'.format(datetime.datetime.now(),file))
command = Command(zip_exe+' x '+file+' -o'+path+dirout)
command.run(timeout = 300)
print(self.tmp) #print the command line output (doesn't work)
</code></pre>
| 0 | 2016-07-28T06:01:35Z | 38,629,142 | <p>Your problem seems to be that the identifier <code>self</code> is not defined in function <code>unzip_file</code>. Try replacing </p>
<pre><code>print(self.tmp) #print the command line output (doesn't work)
</code></pre>
<p>with </p>
<pre><code>print(command.tmp)
</code></pre>
<p>Identifier <code>self</code> has a special meaning when used in the scope of a class and refers to the instance of that class. When used elsewhere (as in <code>unzip_file</code>), the identifier has no special meaning and is just a regular undefined identifier.</p>
<p>Aside from your actual problem, you might want to research communication mechanisms between threads. <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">Queue module</a> is a good place to look at if you already understand the basics. If you are new to the topic, then <a href="http://www.slideshare.net/dabeaz/an-introduction-to-python-concurrency" rel="nofollow">this one</a> is a decent introduction.</p>
| 1 | 2016-07-28T06:57:30Z | [
"python"
] |
string mismatch in Python even if they have same value | 38,628,222 | <p>Instead of keeping keys in my application I intent to read the keys from local file system into a variable (array of strings) and use those array elements in my oAuth APIs. However, when i used keys (in plaintext) as argument to OAuth APIs, authentication succeeds. BUT authentication failed when same value in read into a variable from file & that variable is passed to OAuth API.
Tried comparing the key value and variable value t find out they don't match though they same exactly same. </p>
<p>Input file looks as below: <br></p>
<pre><code>$cat .keys
k1='jFOMZ0bI60fDAEKw53lYCj2r4'
k2='LNkyPehneIi8HeqTg1ji74H42jFkkBxZolRfzNFmaJKwLg7R7E'
</code></pre>
<p><br></p>
<pre><code>secret_keys=[]
def keys_io():
key_file = open('/Users/homie/.keys', 'r+')
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4")
keys_io()
</code></pre>
<p>Output:<br></p>
<pre><code>jFOMZ0bI60fDAEKw53lYCj2r4
False
</code></pre>
<p>What am i missing here?</p>
| 0 | 2016-07-28T06:02:25Z | 38,628,457 | <p>You should <a href="https://docs.python.org/3.4/library/stdtypes.html#str.strip" rel="nofollow"><code>strip</code></a> the key that you read from the file, as it has a trailing <code>\n</code>:</p>
<pre><code>print(secret_keys[0].strip() == "jFOMZ0bI60fDAEKw53lYCj2r4")
</code></pre>
<p>Or do it when reading it:</p>
<pre><code>for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1].strip())
</code></pre>
| 1 | 2016-07-28T06:19:22Z | [
"python",
"string",
"python-2.7",
"comparison"
] |
string mismatch in Python even if they have same value | 38,628,222 | <p>Instead of keeping keys in my application I intent to read the keys from local file system into a variable (array of strings) and use those array elements in my oAuth APIs. However, when i used keys (in plaintext) as argument to OAuth APIs, authentication succeeds. BUT authentication failed when same value in read into a variable from file & that variable is passed to OAuth API.
Tried comparing the key value and variable value t find out they don't match though they same exactly same. </p>
<p>Input file looks as below: <br></p>
<pre><code>$cat .keys
k1='jFOMZ0bI60fDAEKw53lYCj2r4'
k2='LNkyPehneIi8HeqTg1ji74H42jFkkBxZolRfzNFmaJKwLg7R7E'
</code></pre>
<p><br></p>
<pre><code>secret_keys=[]
def keys_io():
key_file = open('/Users/homie/.keys', 'r+')
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4")
keys_io()
</code></pre>
<p>Output:<br></p>
<pre><code>jFOMZ0bI60fDAEKw53lYCj2r4
False
</code></pre>
<p>What am i missing here?</p>
| 0 | 2016-07-28T06:02:25Z | 38,628,458 | <p>If leading-trailing characters are bugging you, remove them with slicing, i.e <code>[1:-1]</code> to remove first-last quotations.</p>
<p>I also refactored your function a bit:</p>
<pre><code>def keys_io():
with open('.keys', 'r+') as f:
for line in f:
secret_keys.append(line.split('=')[1].strip()[1:-1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4"
</code></pre>
<ul>
<li>Use a context manager to open/close your file automatically. </li>
<li>Use <code>for line in <opened_file></code> instead of other methods if you need to examine all lines.</li>
<li>Use <code>strip()</code> without arguments to remove unwanted space.</li>
</ul>
<p>After these changes, the <code>keys_io</code> file works like a charm for me when using the <code>.key</code> file you presented.</p>
| 1 | 2016-07-28T06:19:24Z | [
"python",
"string",
"python-2.7",
"comparison"
] |
string mismatch in Python even if they have same value | 38,628,222 | <p>Instead of keeping keys in my application I intent to read the keys from local file system into a variable (array of strings) and use those array elements in my oAuth APIs. However, when i used keys (in plaintext) as argument to OAuth APIs, authentication succeeds. BUT authentication failed when same value in read into a variable from file & that variable is passed to OAuth API.
Tried comparing the key value and variable value t find out they don't match though they same exactly same. </p>
<p>Input file looks as below: <br></p>
<pre><code>$cat .keys
k1='jFOMZ0bI60fDAEKw53lYCj2r4'
k2='LNkyPehneIi8HeqTg1ji74H42jFkkBxZolRfzNFmaJKwLg7R7E'
</code></pre>
<p><br></p>
<pre><code>secret_keys=[]
def keys_io():
key_file = open('/Users/homie/.keys', 'r+')
for key in range(1,5):
secret_keys.append(key_file.readline().split("=")[1])
print secret_keys[0]
print (secret_keys[0] == "jFOMZ0bI60fDAEKw53lYCj2r4")
keys_io()
</code></pre>
<p>Output:<br></p>
<pre><code>jFOMZ0bI60fDAEKw53lYCj2r4
False
</code></pre>
<p>What am i missing here?</p>
| 0 | 2016-07-28T06:02:25Z | 38,629,009 | <p>When you read a text file from Python, you need to escape the new line character first. Another problem is you have single quote in between the input text. So you need to make change to:</p>
<pre><code>secret_keys.append(key_file.readline().strip().split("=")[1])
</code></pre>
<p>and</p>
<pre><code>if(secret_keys[0] == "\'jFOMZ0bI60fDAEKw53lYCj2r4\'"):
</code></pre>
| 0 | 2016-07-28T06:51:04Z | [
"python",
"string",
"python-2.7",
"comparison"
] |
Python, how to move dict under itself with a new attribute? Eg dict['key'] = dict | 38,628,290 | <p>I have an array of very large dictionaries, and need to put each dict itself under a new key. </p>
<p>I know <code>dict['key'] = dict</code> won't work and will result a recursive dict in python. Currently, I'm doing something like:</p>
<pre><code>new_dict['key'] = old_dict
</code></pre>
<p>and it will waste memory, is there a better way doing it?</p>
| 0 | 2016-07-28T06:07:09Z | 38,628,318 | <p>A <code>dict</code> <em>can</em> hold a reference to itself:</p>
<pre><code>>>> d = {'foo': 'bar'}
>>> d['self'] = d
>>> d
{'self': {...}, 'foo': 'bar'}
>>> d['self']['self']['self']['self']['foo']
'bar'
</code></pre>
<p>Of course, there are <em>some</em> things that you can't do (e.g. dump it to <code>json</code>):</p>
<pre><code>>>> import json
>>> json.dumps(d)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 243, in dumps
return _default_encoder.encode(obj)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 207, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 270, in iterencode
return _iterencode(o, 0)
ValueError: Circular reference detected
</code></pre>
<p>If you actually need to persist this in some way, then you probably don't have another option other than to copy it when you add it to itself:</p>
<pre><code>d = {'foo': 'bar'}
d['self'] = d.copy()
</code></pre>
<p>Or writing some sort of custom logic so that when deserializing, you replace certain sentinel values with the <code>dict</code> itself (which may or may not work depending on why you need this particular feature)</p>
| 3 | 2016-07-28T06:09:01Z | [
"python",
"dictionary"
] |
Python, how to move dict under itself with a new attribute? Eg dict['key'] = dict | 38,628,290 | <p>I have an array of very large dictionaries, and need to put each dict itself under a new key. </p>
<p>I know <code>dict['key'] = dict</code> won't work and will result a recursive dict in python. Currently, I'm doing something like:</p>
<pre><code>new_dict['key'] = old_dict
</code></pre>
<p>and it will waste memory, is there a better way doing it?</p>
| 0 | 2016-07-28T06:07:09Z | 38,628,367 | <p>Adding a small bit to mgilson's answer:</p>
<pre><code>new_dict['key'] = old_dict
</code></pre>
<p>will not be a waste of memory. This assignment operator only assigns <em>a reference</em> to old_dict. Elements from old_dict aren't copied.</p>
<p>But regardless of how you do it - directly or via a different variable name, you'll get circular reference, which is valid for some usages and not valid for some other.</p>
| 2 | 2016-07-28T06:13:03Z | [
"python",
"dictionary"
] |
Python - Calculating frequency of products with respect to given query | 38,628,446 | <p>Suppose we are given 100 rows in a DataFrame with two columns. One is <code>QUERY</code> and other is <code>PRODUCT</code>. Both <code>QUERY</code> values and <code>PRODUCT</code> values can be repeating. like</p>
<pre><code>Sr.No QUERY PRODUCT
1 mobile samsung
2 mobile sony
3 mobile samsung
4 laptop samsung
5 laptop sony
</code></pre>
<p>Output should be</p>
<pre><code>Sr.No QUERY PRODUCT FREQUENCY
1 mobile samsung 2
2 mobile sony 1
3 mobile samsung 2
4 laptop samsung 1
5 laptop sony 1
</code></pre>
<p>Please note that duplicate values should not be omitted.
How can we do this in python? </p>
| 1 | 2016-07-28T06:18:19Z | 38,628,510 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.transform.html" rel="nofollow"><code>transform</code></a>:</p>
<pre><code>df['FREQUENCY'] = df.groupby(['QUERY', 'PRODUCT'])['PRODUCT'].transform('size')
print (df)
RangeIndex(start=0, stop=5, step=1)
Sr.No QUERY PRODUCT FREQUENCY
0 1.0 mobile samsung 2
1 2.0 mobile sony 1
2 3.0 mobile samsung 2
3 4.0 laptop samsung 1
4 5.0 laptop sony 1
</code></pre>
| 0 | 2016-07-28T06:22:28Z | [
"python",
"pandas"
] |
Python - Selecting Specific Results to Place in Excel | 38,628,499 | <p>EDIT: I'm making a lot of head way, I am now trying to parse out single columns from my JSON file, not the entire row. I am getting an error however whenever I try to manipulate my DataFrame to get the results I want.</p>
<p>The error is:
line 52, in
df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['name_display_first_last'])
KeyError: 'name_display_first_last'</p>
<p>It only happens when I try to add another parameter, for instance i took out ['row'] and added ['name_display_first_last'] to get the first and last name of each player. If I leave in ['row'] it compiles, but gives me all the data, I only want certain snippets. </p>
<p>Any help would be greatly appreciated! Thanks.</p>
<pre><code>import requests
import pandas as pd
from bs4 import BeautifulSoup
# Scraping data from MLB.com
target = [MLB JSON][1]
mlbResponse = requests.get(target)
mlbJson = mlbResponse.json()
# Placing response in variable
# Collecting data and giving it names in pandas
data = {'Team': team, 'Line': line}
# places data table format, frames the data
table = pd.DataFrame(data)
# Creates excel file named Scrape
writer = pd.ExcelWriter('Scrape.xlsx')
# Moves table to excel taking in Parameters , 'Name of DOC and Sheet on that Doc'
table.to_excel(writer, 'Lines 1')
#stats = {'Name': name, 'Games': games, 'AtBats': ab, 'Runs': runs, 'Hits': hits, 'Doubles': doubles, 'Triples': triples, 'HR': hr, 'RBI': rbi, 'Walks': walks, 'SB': sb}
df = pd.DataFrame.from_dict(mlbJson['stats_sortable_player']['queryResults']['row'])
df.to_excel(writer, 'Batting 2')
# Saves File
writer.save()
</code></pre>
| 0 | 2016-07-28T06:21:51Z | 38,629,173 | <p>It looks like the website loads the data asynchronously through another request to a different URL. The response you're getting has empty <code><datagrid><\datagrid></code> tag, and <code>soup2.select_one("#datagrid").find_next("table")</code> returns <code>None</code>.</p>
<p>You can use the developer tools in your browser under the network tab to find the URL to actually load data, it looks like :</p>
<p><a href="http://mlb.mlb.com/pubajax/wf/flow/stats.splayer?season=2016&sort_order=%27desc%27&sort_column=%27avg%27&stat_type=hitting&page_type=SortablePlayer&game_type=%27R%27&player_pool=ALL&season_type=ANY&sport_code=%27mlb%27&results=1000&recSP=1&recPP=50" rel="nofollow">http://mlb.mlb.com/pubajax/wf/flow/stats.splayer?season=2016&sort_order=%27desc%27&sort_column=%27avg%27&stat_type=hitting&page_type=SortablePlayer&game_type=%27R%27&player_pool=ALL&season_type=ANY&sport_code=%27mlb%27&results=1000&recSP=1&recPP=50</a></p>
<p>You can modify your code to make a request to this URL, which returns json</p>
<pre><code>mlbResponse = requests.get(url)
mlbJson = mlbResponse.json() # python 3, otherwise use json.loads(mlbResponse.content)
df = pd.DataFrame(doc['stats_sortable_player']['queryResults']['row'])
</code></pre>
<p>The DataFrame has 54 columns, so I can't display it here, but you should be able to pick and rename the columns you need.</p>
| 0 | 2016-07-28T06:59:05Z | [
"python",
"json",
"excel",
"pandas",
"beautifulsoup"
] |
OpenCV exception after 1 day calculation | 38,628,504 | <p>I am using opencv_traincascade for object detection. I try to find glasses on photo. For this, I've downloaded 830 pictures like this:
<a href="http://pi1.lmcdn.ru/product/V/I/VI060DWIHZ27_1_v2.jpg">http://pi1.lmcdn.ru/product/V/I/VI060DWIHZ27_1_v2.jpg</a></p>
<p>Then I've downloaded many pictures with model in dresses or just dresses photos, 1799 photos.</p>
<p>Then I've start opencv_traincascade with parameters:
opencv_traincascade -data Feature/classifier -vec samples.vec -bg negatives.txt -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 830 -numNeg 1799 -w 60 -h 90 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024</p>
<p>But after step 4, I have a message:
Train dataset for temp stage can not be filled. Branch training terminated.</p>
<p>The full stacktrace is:</p>
<pre><code>â pictureFeature opencv_traincascade -data Feature/classifier -vec samples.vec -bg negatives.txt -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 830 -numNeg 1799 -w 60 -h 90 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024
PARAMETERS:
cascadeDirName: Feature/classifier
vecFileName: samples.vec
bgFileName: negatives.txt
numPos: 830
numNeg: 1799
numStages: 10
precalcValBufSize[Mb] : 1024
precalcIdxBufSize[Mb] : 1024
acceptanceRatioBreakValue : -1
stageType: BOOST
featureType: HAAR
sampleWidth: 60
sampleHeight: 90
boostType: GAB
minHitRate: 0.999
maxFalseAlarmRate: 0.5
weightTrimRate: 0.95
maxDepth: 1
maxWeakCount: 100
mode: ALL
===== TRAINING 0-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 1
Precalculation time: 26
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 0.145636|
+----+---------+---------+
END>
Training until now has taken 0 days 5 hours 22 minutes 10 seconds.
===== TRAINING 1-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.145715
Precalculation time: 24
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 1|
+----+---------+---------+
| 4| 1| 0.762646|
+----+---------+---------+
| 5| 1| 0.432462|
+----+---------+---------+
END>
Training until now has taken 0 days 14 hours 38 minutes 28 seconds.
===== TRAINING 2-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.062696
Precalculation time: 28
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 1|
+----+---------+---------+
| 4| 1| 0.590328|
+----+---------+---------+
| 5| 1| 0.187326|
+----+---------+---------+
END>
Training until now has taken 0 days 23 hours 21 minutes 4 seconds.
===== TRAINING 3-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.0117929
Precalculation time: 21
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1|0.0944969|
+----+---------+---------+
END>
Training until now has taken 1 days 3 hours 47 minutes 34 seconds.
===== TRAINING 4-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.00112161
Precalculation time: 18
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 0|
+----+---------+---------+
END>
Training until now has taken 1 days 5 hours 4 minutes 35 seconds.
===== TRAINING 5-stage =====
<BEGIN
POS count : consumed 830 : 830
Train dataset for temp stage can not be filled. Branch training terminated.
</code></pre>
<p>I tried to use cascade.xml for object searching, but the result was completely fail.</p>
<p><a href="http://i.stack.imgur.com/wRUoZ.jpg"><img src="http://i.stack.imgur.com/wRUoZ.jpg" alt="enter image description here"></a></p>
<p>Could somebody help with my problem?</p>
| 9 | 2016-07-28T06:22:13Z | 38,777,673 | <p>That's a pretty common error. There is not much I know about this error and I can only guess a solution, since there are a lot of possible reasons for that error.</p>
<p>It could be relative to the directories structure (just notice that the path for negative examples should be relative to the current directory) </p>
<p>or because the line break in bg file (negatives.txt in your case) are bad encoded.
<em>Could you please double check that last character of each line in the 'negatives.txt' file are '\n' and not '\r' ?</em></p>
<p>Also keep trying to maintain positive to negative samples ratio around 25%-30%</p>
<p>And finaly be sure that all your positive and negative images contain the head face:</p>
<p>In the sample picture (one of the 830) there is only one sunglasses visible on it (no head , no hear, no hair) only white backgroud, so your classifier will finaly train to make recognition of sunglasses only on white backgroud, so there is no chance to recognize any sunglasses when face is visible;</p>
<p>Try to respect :</p>
<ul>
<li><p>positive picture = <strong>headface with sunglasses</strong></p></li>
<li><p>negative picture = <strong>headface only</strong></p></li>
</ul>
<p>Regards</p>
| 3 | 2016-08-04T21:27:41Z | [
"python",
"algorithm",
"opencv"
] |
OpenCV exception after 1 day calculation | 38,628,504 | <p>I am using opencv_traincascade for object detection. I try to find glasses on photo. For this, I've downloaded 830 pictures like this:
<a href="http://pi1.lmcdn.ru/product/V/I/VI060DWIHZ27_1_v2.jpg">http://pi1.lmcdn.ru/product/V/I/VI060DWIHZ27_1_v2.jpg</a></p>
<p>Then I've downloaded many pictures with model in dresses or just dresses photos, 1799 photos.</p>
<p>Then I've start opencv_traincascade with parameters:
opencv_traincascade -data Feature/classifier -vec samples.vec -bg negatives.txt -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 830 -numNeg 1799 -w 60 -h 90 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024</p>
<p>But after step 4, I have a message:
Train dataset for temp stage can not be filled. Branch training terminated.</p>
<p>The full stacktrace is:</p>
<pre><code>â pictureFeature opencv_traincascade -data Feature/classifier -vec samples.vec -bg negatives.txt -numStages 10 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 830 -numNeg 1799 -w 60 -h 90 -mode ALL -precalcValBufSize 1024 -precalcIdxBufSize 1024
PARAMETERS:
cascadeDirName: Feature/classifier
vecFileName: samples.vec
bgFileName: negatives.txt
numPos: 830
numNeg: 1799
numStages: 10
precalcValBufSize[Mb] : 1024
precalcIdxBufSize[Mb] : 1024
acceptanceRatioBreakValue : -1
stageType: BOOST
featureType: HAAR
sampleWidth: 60
sampleHeight: 90
boostType: GAB
minHitRate: 0.999
maxFalseAlarmRate: 0.5
weightTrimRate: 0.95
maxDepth: 1
maxWeakCount: 100
mode: ALL
===== TRAINING 0-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 1
Precalculation time: 26
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 0.145636|
+----+---------+---------+
END>
Training until now has taken 0 days 5 hours 22 minutes 10 seconds.
===== TRAINING 1-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.145715
Precalculation time: 24
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 1|
+----+---------+---------+
| 4| 1| 0.762646|
+----+---------+---------+
| 5| 1| 0.432462|
+----+---------+---------+
END>
Training until now has taken 0 days 14 hours 38 minutes 28 seconds.
===== TRAINING 2-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.062696
Precalculation time: 28
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 1|
+----+---------+---------+
| 4| 1| 0.590328|
+----+---------+---------+
| 5| 1| 0.187326|
+----+---------+---------+
END>
Training until now has taken 0 days 23 hours 21 minutes 4 seconds.
===== TRAINING 3-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.0117929
Precalculation time: 21
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1|0.0944969|
+----+---------+---------+
END>
Training until now has taken 1 days 3 hours 47 minutes 34 seconds.
===== TRAINING 4-stage =====
<BEGIN
POS count : consumed 830 : 830
NEG count : acceptanceRatio 1799 : 0.00112161
Precalculation time: 18
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 0|
+----+---------+---------+
END>
Training until now has taken 1 days 5 hours 4 minutes 35 seconds.
===== TRAINING 5-stage =====
<BEGIN
POS count : consumed 830 : 830
Train dataset for temp stage can not be filled. Branch training terminated.
</code></pre>
<p>I tried to use cascade.xml for object searching, but the result was completely fail.</p>
<p><a href="http://i.stack.imgur.com/wRUoZ.jpg"><img src="http://i.stack.imgur.com/wRUoZ.jpg" alt="enter image description here"></a></p>
<p>Could somebody help with my problem?</p>
| 9 | 2016-07-28T06:22:13Z | 38,802,845 | <p>If you look at the error you'll find that it stopped at 'NEG count' which means there was an issue with reading the negative training data set images at stage-5. So you need to fix the path to the negative training samples for it to work.</p>
<p>Here is a detailed discussion on this issue which might be helpful: <a href="http://answers.opencv.org/question/10872/cascade-training-error-opencv-244-train-dataset-for-temp-stage-can-not-filled-branch-training-terminated-cascade-classifier-cant-be-trained-check-the/" rel="nofollow">Cascade Training Error OpenCV 2.4.4</a></p>
<p>It can also be an issue with the bg.txt file, here is another answer: <a href="http://answers.opencv.org/question/16868/error-in-train-casacde/?answer=53164#post-id-53164" rel="nofollow">error in train casacde</a>.</p>
<p>Another post with similar <a href="http://stackoverflow.com/questions/11412655/error-train-dataset-for-temp-stage-can-not-be-filled-while-using-traincascade">error: Train dataset for temp stage can not be filled. </a></p>
<p>If nothing works try using a different version of open cv: <a href="http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip/download" rel="nofollow">http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.4.9/opencv-2.4.9.zip/download</a></p>
| 3 | 2016-08-06T09:43:57Z | [
"python",
"algorithm",
"opencv"
] |
How can I GROUP BY "identical" strings of different lengths? | 38,628,620 | <p>I have a database of hymn instances as they appear in various hymnbooks.
The table is set up roughly like this:</p>
<pre><code>CREATE TABLE `Hymns` (
`HymnID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`HymnbookID` int(11) DEFAULT NULL,
`HyNumber` int(11) DEFAULT NULL,
`HyName` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`HyFirstLine` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`HyFirstLineDif` tinyint(1) NOT NULL DEFAULT '0',
`SongID` int(11) DEFAULT NULL,
`TextID` int(11) DEFAULT NULL,
`TuneID` int(11) DEFAULT NULL,
PRIMARY KEY (`HymnID`),
KEY `HymnbookID` (`HymnbookID`),
KEY `SongID` (`SongID`)
) ENGINE=MyISAM AUTO_INCREMENT=134381 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
INSERT INTO `Hymns` (`HymnID`, `HymnbookID`, `HyNumber`, `HyName`,
`HyFirstLine`, `HyFirstLineDif`, `SongID`, `TextID`, `TuneID`)
VALUES (642, 1, 26, 'Joseph Smithâs First Prayer',
'Oh, how lovely was the morning', 1, 26, 26, 26);
</code></pre>
<p>Sometimes the first lines are the same, but cutting off at a different place â and sometimes they are different (the letters A and B aren't in the database, I just put them in to show same and different):</p>
<blockquote>
<p>Oh, how lovely was the morning [A]</p>
<p>Oh, how lovely [A]</p>
<p>Oh, how lovely was the morning! Radiant beamed [A]</p>
<p>O how lovely was the morning! [B]</p>
</blockquote>
<p>Is it possible to return only the longest version of the unique first lines, like this?:</p>
<blockquote>
<p>Oh, how lovely was the morning! Radiant beamed [A]</p>
<p>O how lovely was the morning! [B]</p>
</blockquote>
<p>Here's the query I have so far:</p>
<pre><code>SELECT HyFirstLine
FROM Hymns
WHERE TextID = 26 AND HyFirstLine IS NOT NULL
GROUP BY HyFirstLine
</code></pre>
<p>EDIT: The data is being returned to Python as a list of dictionaries. Based on the comments, maybe it's better to filter after the fact with Python? I'm not sure how I would go about doing that. Adding the Python tag.</p>
| 0 | 2016-07-28T06:29:00Z | 38,629,116 | <p><strong>EDIT</strong>: This is for MSSQL, not mySQL. My apologies. Hope the reference below could help you though.</p>
<p>Not tested but you'd probably need a stored procedure with something like this:</p>
<pre><code>DECLARE @HyFirstLine varchar(255);
DECLARE @StoredHyFirstLine varchar(255);
DECLARE @OutputTable Table(HyFirstLine varchar(255))
DECLARE hy_cursor CURSOR FOR
SELECT HyFirstLine FROM Hymns;
OPEN hy_cursor;
FETCH NEXT FROM hy_cursor
INTO @HyFirstLine;
WHILE @@FETCH_STATUS = 0
BEGIN
IF NOT EXISTS(SELECT * FROM @OutputTable WHERE HyFirstLine like @HyFirstLine+'%')
BEGIN
INSERT INTO @OutputTable(HyFirstLine) VALUES(@HyFirstLine)
END
ELSE
BEGIN
SET @StoredHyFirstLine = (SELECT HyFirstLine FROM @OutputTable WHERE HyFirstLine like @HyFirstLine+'%')
IF LEN(@HyFirstLine) > LEN(@StoredHyFirstLine)
BEGIN
UPDATE @OutputTable SET HyFirstLine = @HyFirstLine WHERE HyFirstLine like @HyFirstLine+'%'
END
END
FETCH NEXT FROM hy_cursor
INTO @HyFirstLine;
END
CLOSE hy_cursor;
DEALLOCATE hy_cursor;
SELECT * FROM @OutputTable
</code></pre>
| 0 | 2016-07-28T06:56:05Z | [
"python",
"mysql",
"group-by"
] |
How to save files to database in django | 38,628,770 | <p>I am trying to upload files using django forms and save those files in the database itself.
I have been able to save the link of the file in database and save the file itself in a directory which i specified in Media_root.Can you please help me and tell me what can i change in my code so that files are saved in the database.</p>
<p>here is my code:</p>
<h2>models.py</h2>
<pre><code>from django.db import models
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
</code></pre>
<h2>forms.py</h2>
<pre><code>from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
)
</code></pre>
<h2>views.py</h2>
<pre><code>from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from .models import Document
from .forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('upload.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request)
)
def index(request):
return render_to_response('index.html')
</code></pre>
<h2>app\urls.py</h2>
<pre><code>from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
(r'^upload/', include('upload.urls')),
(r'^$', 'upload.views.index'),
(r'^admin/', include(admin.site.urls)),) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code></pre>
<h2>project\urls.py</h2>
<pre><code>from django.conf.urls import patterns, include, url
urlpatterns = patterns('upload.views',
url(r'^$', 'list', name='list'),
url(r'^list/$', 'list', name='list'),)
</code></pre>
| 0 | 2016-07-28T06:37:39Z | 38,629,040 | <p>Django provides <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#binaryfield" rel="nofollow">BinaryField</a> that lets you store any binary data, including file contents. </p>
<p>Please do note that the documentation also says:</p>
<blockquote>
<p>Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.</p>
</blockquote>
<p>If you'd rather not store the files on your web server's file system, you can explore other options such as Amazon S3 or just an FTP server. Have a look at the <a href="http://django-storages.readthedocs.io/en/latest/" rel="nofollow">django-storages</a> library, it provides a nice bunch of options. </p>
| 3 | 2016-07-28T06:52:21Z | [
"python",
"django"
] |
Django- Jquery loops through all options | 38,628,873 | <p>Im doing server side rendering with the help of Django. In my django templates Im looping through all the values obtained from my Database. In jquery while selecting a single value, JS gives me all the values obtained from database, but I wanted only selected values</p>
<p>Views.py</p>
<pre><code>def theme(request):
context={}
context['All']=Theme.objects.all().count()
for t in ThemeCategory.objects.all():
context[t.categoryName]= t.theme_set.count()
context=collections.OrderedDict(sorted(context.items()))
return render(request,'theme-list.html',{'category_name':context})
</code></pre>
<p>In templates</p>
<pre><code><ul class="pick-tags" >
{% for category_name,count in category_name.items %}
<li id="item_cat">
<span id="item_cat_name">{{ category_name }}</span>
</li>
{% endfor %}
</ul>
</code></pre>
<p>In jquery Im selecting the required value</p>
<pre><code>$('li#item_cat').on('click', function () {
alert($('span#item_cat_name').text())
})
</code></pre>
<p>But instead of giving me a single value, It me all the value obtained from DB.</p>
<p>How should I get only one value when click on <code><li></code></p>
<p>Any help in obtaining selected value would be helpful</p>
| 2 | 2016-07-28T06:43:38Z | 38,629,251 | <p>First of all, id of each HTML element should be unique. And you are creating multiple <code>li</code> and <code>span</code> elements with the same id. Make sure it's unique to prevent undesired bugs. it's better to use class and data attributes if needed.</p>
<p>Second, you need to get text of selected element, not any element, so you need to use <code>this</code>:</p>
<pre><code>$(this).find('span').text()
</code></pre>
| 1 | 2016-07-28T07:04:41Z | [
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
Django- Jquery loops through all options | 38,628,873 | <p>Im doing server side rendering with the help of Django. In my django templates Im looping through all the values obtained from my Database. In jquery while selecting a single value, JS gives me all the values obtained from database, but I wanted only selected values</p>
<p>Views.py</p>
<pre><code>def theme(request):
context={}
context['All']=Theme.objects.all().count()
for t in ThemeCategory.objects.all():
context[t.categoryName]= t.theme_set.count()
context=collections.OrderedDict(sorted(context.items()))
return render(request,'theme-list.html',{'category_name':context})
</code></pre>
<p>In templates</p>
<pre><code><ul class="pick-tags" >
{% for category_name,count in category_name.items %}
<li id="item_cat">
<span id="item_cat_name">{{ category_name }}</span>
</li>
{% endfor %}
</ul>
</code></pre>
<p>In jquery Im selecting the required value</p>
<pre><code>$('li#item_cat').on('click', function () {
alert($('span#item_cat_name').text())
})
</code></pre>
<p>But instead of giving me a single value, It me all the value obtained from DB.</p>
<p>How should I get only one value when click on <code><li></code></p>
<p>Any help in obtaining selected value would be helpful</p>
| 2 | 2016-07-28T06:43:38Z | 38,629,417 | <p>In your template, you're giving every <code><span></code> element the same identifier (<em>item_cat_name</em>). Your second jQuery selector selects all <code><span></code> elements with that identifier.</p>
<p>To resolve this, change your jQuery to something like:</p>
<pre><code>$('li').on('click', function () {
alert($(this).children('span').text())
});
</code></pre>
<p>This would only show the texts of <code><span></code> elements directly below the clicked <code><li></code> element (using <code>$(this)</code> is the key here).</p>
<p>Also, I would advise to give every <code><span></code> element an unique identifier, e.g. the primary key of the ThemeCategory; so that you can then base your further actions on that.</p>
| 1 | 2016-07-28T07:12:30Z | [
"javascript",
"jquery",
"python",
"django",
"django-templates"
] |
Merging dataframes by date range & repeating a categorical column in python | 38,628,924 | <p>I have two dataframes:</p>
<p>df1 :</p>
<pre><code>Time A B
1469510289000 1.5 2.4
1469510290000 2.5 7.1
1469510291000 2.2 6.4
1469510292000 1.4 2.3
1469510293000 1.6 1.8
1469510294000 2.2 4.1
1469510295000 1.2 0.6
</code></pre>
<p>and so on...</p>
<p>df2:</p>
<pre><code>start end Category
1469510289000 1469510291000 A
1469510291000 1469510294000 B
1469510294000 1469510295000 A
1469510295000 NA C
</code></pre>
<p>Time in both dataframes is in epoch. Now, I want to merge the df1 & df2, based on start & end column from df2, with category. The final resultant dataframe looks like this(df1):</p>
<pre><code>Time A B Category
1469510289000 1.5 2.4 A
1469510290000 2.5 7.1 A
1469510291000 2.2 6.4 B
1469510292000 1.4 2.3 B
1469510293000 1.6 1.8 B
1469510294000 2.2 4.1 A
1469510295000 1.2 0.6 C
</code></pre>
<p>Able to solve it by converting category into float by using np.peicewise but how can I do it when my category is text or an object? Please help. Thanks</p>
| 0 | 2016-07-28T06:46:24Z | 38,630,288 | <p>Not sure what do you mean "object" but .. I think if you mean that the category is in string type, you can convert those data frame into list, in a list the string part will automatically become this form --> 'string', and append the category label to the corresponding list , probably may get you what you want.</p>
<p>Like this</p>
<pre><code>df1:
time A B
1 1.5 2.4
2 2.5 7.1
3 2.2 6.4
4 1.4 2.3
5 1.6 1.8
6 2.2 4.1
7 1.2 0.6
df2:
start end category
1 3 sthtxt1
3 6 sthtxt2
6 7 sthtxt1
7 NA C
F1 = df1.values.tolist()
F2 = df2.values.tolist()
for item1 in F1:
for item2 in F2:
if item1[0] >= item2[0] and item1[0] < item2[1]:
item1.append(item2[2])
whatuwant=pd.DataFrame(F1)
whatuwant:
time A B category
1.0 1.5 2.4 sthtxt1
2.0 2.5 7.1 sthtxt1
3.0 2.2 6.4 sthtxt2
4.0 1.4 2.3 sthtxt2
5.0 1.6 1.8 sthtxt2
6.0 2.2 4.1 sthtxt1
7.0 1.2 0.6 C
</code></pre>
| 1 | 2016-07-28T07:54:58Z | [
"python",
"python-2.7"
] |
Merging dataframes by date range & repeating a categorical column in python | 38,628,924 | <p>I have two dataframes:</p>
<p>df1 :</p>
<pre><code>Time A B
1469510289000 1.5 2.4
1469510290000 2.5 7.1
1469510291000 2.2 6.4
1469510292000 1.4 2.3
1469510293000 1.6 1.8
1469510294000 2.2 4.1
1469510295000 1.2 0.6
</code></pre>
<p>and so on...</p>
<p>df2:</p>
<pre><code>start end Category
1469510289000 1469510291000 A
1469510291000 1469510294000 B
1469510294000 1469510295000 A
1469510295000 NA C
</code></pre>
<p>Time in both dataframes is in epoch. Now, I want to merge the df1 & df2, based on start & end column from df2, with category. The final resultant dataframe looks like this(df1):</p>
<pre><code>Time A B Category
1469510289000 1.5 2.4 A
1469510290000 2.5 7.1 A
1469510291000 2.2 6.4 B
1469510292000 1.4 2.3 B
1469510293000 1.6 1.8 B
1469510294000 2.2 4.1 A
1469510295000 1.2 0.6 C
</code></pre>
<p>Able to solve it by converting category into float by using np.peicewise but how can I do it when my category is text or an object? Please help. Thanks</p>
| 0 | 2016-07-28T06:46:24Z | 38,668,708 | <p>Will this help you ?</p>
<pre><code>list = []
for time in df1['Time']:
category = None
count=-1
for start,end in zip(df2['start'],df2['end']):
count += 1
if ( time>=start and time <= end):
break
if count != -1:
category = df2.ix[count]['Category']
list.append(category)
df1['Category']=list
df1
A B Time Category
0 1.5 2.4 1469510289000 A
1 2.5 7.1 1469510290000 A
2 2.2 6.4 1469510291000 A
3 1.4 2.3 1469510292000 B
4 1.6 1.8 1469510293000 B
5 2.2 4.1 1469510294000 B
6 1.2 0.6 1469510295000 A
</code></pre>
| 0 | 2016-07-29T23:11:46Z | [
"python",
"python-2.7"
] |
finding number of root determined interval | 38,628,952 | <p>I have n degree polynomial system ,just I want to learn number of root between previously determined interval .But I do not want to find root.I need number of root.I need to write python code.
For example :
x^8+2x^6+5x^4+x^2+45x+1=0
How many root have we between 3-5?
emphasize=I do not want to find root,just I want to learn how many root I have.</p>
| -1 | 2016-07-28T06:47:53Z | 38,634,455 | <p>You can do this with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.roots.html" rel="nofollow">numpy</a></p>
<pre><code>import numpy as np
coeff = [1,0,2,0,5,0,1,45,1] #for the polynomial x^8+2x^6+5x^4+x^2+45x+1=0
np.roots(coeff)
# array([ 1.37234708+0.91495949j, 1.37234708-0.91495949j,
# 0.43013459+1.75225934j, 0.43013459-1.75225934j,
# -1.06175643+1.53395567j, -1.06175643-1.53395567j,
# -1.45921726+0.j , -0.02223323+0.j ])
</code></pre>
<p>Thus, as you can see, this one has zero real roots.</p>
<p>Edit: If you want to find the number of roots between an interval without finding the roots explicitly, you can use <a href="http://stackoverflow.com/a/4518339/6495334">sturm's theorem</a>. Using sympy,</p>
<pre><code>from sympy import Sturm,Symbol
from sympy.abc import x
sturm_seq = sturm(x**6-3*x**5+2*x**4)
limits = [2,4]; x = Symbol('x')
values_at_start = [polynomial.subs(x,limits[0]).evalf() for polynomial in sturm_seq]
values_at_end = [polynomial.subs(x,limits[1]).evalf() for polynomial in sturm_seq]
import itertools
# Count number of sign changes in values_at_start
count_start = len(list(itertools.groupby(values_at_start, lambda values_at_start: values_at_start > 0)))
count_end = len(list(itertools.groupby(values_at_end, lambda values_at_end: values_at_end > 0)))
ans = count_start - count_end
print ans # ans = 1
</code></pre>
| 0 | 2016-07-28T11:01:27Z | [
"python",
"numerical-analysis"
] |
How to figure out http and ssl version using python | 38,629,338 | <p>Is there a good way in python to check if a website/url supports http2 and which SSL versions does it support. </p>
<p>What I am looking for is achievable by the use of commands </p>
<pre><code>openssl s_client Âconnect domain:443 Ânextprotoneg ''
</code></pre>
<p>output of this openssl command contains this line : <code>Protocols advertised by server: h2, spdy/3.1, http/1.1</code> Through which I can figure out the http2 support.</p>
<pre><code>curl -v -o /dev/null --silent https://www.example.com
</code></pre>
<p>This line -> <code>TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256</code> in the output of the above command can tell me about the SSL version used.</p>
<p>I don't want to run these commands and parse the output because I feel there should be a better way to do it.</p>
| 0 | 2016-07-28T07:08:48Z | 38,631,557 | <p>You can use the <a href="https://github.com/Lukasa/hyper" rel="nofollow">Hyper</a> lib.</p>
<pre><code>from hyper import HTTPConnection
conn = HTTPConnection('google.com:443')
# If request made over http/1.1 then result will be None
if conn.request('HEAD', '/') is not None:
# Return a string identifying the protocol version used by the current SSL channel
print(conn._sock._sck.version()) # little bit dirty, but work
</code></pre>
| 0 | 2016-07-28T08:56:18Z | [
"python",
"ssl",
"http2",
"spdy"
] |
Why does the regex (.*?(?: *?\n)) capture newlines? | 38,629,424 | <p>Consider the text below: </p>
<pre><code>foobar¬
nextline
</code></pre>
<p>The regex <code>(.*?(?: *?\n))</code> matches <code>foobar¬</code>
where <code>¬</code> denotes a newline \n. </p>
<p>Why does the regex match it? shouldn't the non-capture group exclude it? </p>
<p>Tested on <a href="https://regex101.com/r/fV8nM5" rel="nofollow">Regex101</a> for the python dialect. </p>
| 0 | 2016-07-28T07:12:50Z | 38,629,523 | <p>The <code>\n</code> is captured because the non-capturing group is <strong>inside</strong> the capturing group:</p>
<pre><code>>>> s = 'foobar\nnextline'
>>> re.search(r'(.*?(?: *?\n))', s).groups()
('foobar\n',)
</code></pre>
<p>If you don't want that, place the non-capturing group <strong>outside</strong> of the capturing one:</p>
<pre><code>>>> re.search(r'(.*?)(?: *?\n)', s).groups()
('foobar',)
</code></pre>
| 2 | 2016-07-28T07:17:55Z | [
"python",
"regex"
] |
Why does the regex (.*?(?: *?\n)) capture newlines? | 38,629,424 | <p>Consider the text below: </p>
<pre><code>foobar¬
nextline
</code></pre>
<p>The regex <code>(.*?(?: *?\n))</code> matches <code>foobar¬</code>
where <code>¬</code> denotes a newline \n. </p>
<p>Why does the regex match it? shouldn't the non-capture group exclude it? </p>
<p>Tested on <a href="https://regex101.com/r/fV8nM5" rel="nofollow">Regex101</a> for the python dialect. </p>
| 0 | 2016-07-28T07:12:50Z | 38,629,584 | <p>âNon-capturing groupâ refers to the fact that matches within that group will not be available as separate groups in the resulting match object. For example:</p>
<pre><code>>>> re.search('(foo)(bar)', 'foobarbaz').groups()
('foo', 'bar')
>>> re.search('(foo)(?:bar)', 'foobarbaz').groups()
('foo',)
</code></pre>
<p>However, everything that is part of an expression is <em>matched</em> and as such appears in the resulting match (Group 0 shows the whole match):</p>
<pre><code>>>> re.search('(foo)(bar)', 'foobarbaz').group(0)
'foobar'
>>> re.search('(foo)(?:bar)', 'foobarbaz').group(0)
'foobar'
</code></pre>
<p>If you donât want to match that part but still want to make sure itâs there, you can use a lookahead expression:</p>
<pre><code>>>> re.search('(foo)(?=bar)', 'foobarbaz')
<_sre.SRE_Match object; span=(0, 3), match='foo'>
>>> re.search('(foo)(?=bar)', 'foobaz')
None
</code></pre>
<p>So in your case, you could use <code>(.*?(?= *?\n))</code>.</p>
| 6 | 2016-07-28T07:20:32Z | [
"python",
"regex"
] |
Matching a number in a file with Python | 38,629,459 | <p>I have about 15,000 files I need to parse which <em>could</em> contain one or more strings/numbers from a list I have. I need to separate the files with matching strings.</p>
<p>Given a string: 3423423987, it could appear independently as "3423423987", or as "3423423987_1" or "3423423987_1a", "3423423987-1a", but it could also be "2133423423987". However, I only want to detect the matching sequence where it is not a part of another number, only when it has a suffix of some sort.</p>
<p>So 3423423987_1 is acceptable, but 13423423987 is not.</p>
<p>I'm having trouble with regex, haven't used it much to be honest.</p>
<p>Simply speaking, if I simulate this with a list of possible positives and negatives, I should get 7 hits, for the given list. I would like to extract the text till the end of the word, so that I can record that later.</p>
<p>Here's my code:</p>
<pre><code>def check_text_for_string(text_to_parse, string_to_find):
import re
matches = []
pattern = r"%s_?[^0-9,a-z,A-Z]\W"%string_to_find
return re.findall(pattern, text_to_parse)
if __name__ =="__main__":
import re
word_to_match = "3423423987"
possible_word_list = [
"3423423987_1 the cake is a lie", #Match
"3423423987sdgg call me Ishmael", #Not a match
"3423423987 please sir, can I have some more?", #Match
"3423423987", #Match
"3423423987 ", #Match
"3423423987\t", #Match
"adsgsdzgxdzg adsgsdag\t3423423987\t", #Match
"1233423423987", #Not a match
"A3423423987", #Not a match
"3423423987-1a\t", #Match
"3423423987.0", #Not a match
"342342398743635645" #Not a match
]
print("%d words in sample list."%len(possible_word_list))
print("Only 7 should match.")
matches = check_text_for_string("\n".join(possible_word_list), word_to_match)
print("%d matched."%len(matches))
print(matches)
</code></pre>
<p>But clearly, this is wrong. Could someone help me out here?</p>
| 3 | 2016-07-28T07:14:46Z | 38,629,931 | <p>You can use this pattern:</p>
<pre><code>(?:\b|^)3423423987(?!\.)(?=\b|_|$)
</code></pre>
<p><code>(?:\b|^)</code> asserts that there are no other numbers to the left</p>
<p><code>(?!\.)</code> asserts the number isn't followed by a dot</p>
<p><code>(?=\b|_|$)</code> asserts the number is followed by a non word character, an underscore or nothing</p>
| 1 | 2016-07-28T07:37:24Z | [
"python",
"regex",
"python-3.4"
] |
Matching a number in a file with Python | 38,629,459 | <p>I have about 15,000 files I need to parse which <em>could</em> contain one or more strings/numbers from a list I have. I need to separate the files with matching strings.</p>
<p>Given a string: 3423423987, it could appear independently as "3423423987", or as "3423423987_1" or "3423423987_1a", "3423423987-1a", but it could also be "2133423423987". However, I only want to detect the matching sequence where it is not a part of another number, only when it has a suffix of some sort.</p>
<p>So 3423423987_1 is acceptable, but 13423423987 is not.</p>
<p>I'm having trouble with regex, haven't used it much to be honest.</p>
<p>Simply speaking, if I simulate this with a list of possible positives and negatives, I should get 7 hits, for the given list. I would like to extract the text till the end of the word, so that I can record that later.</p>
<p>Here's my code:</p>
<pre><code>def check_text_for_string(text_to_parse, string_to_find):
import re
matches = []
pattern = r"%s_?[^0-9,a-z,A-Z]\W"%string_to_find
return re.findall(pattern, text_to_parse)
if __name__ =="__main__":
import re
word_to_match = "3423423987"
possible_word_list = [
"3423423987_1 the cake is a lie", #Match
"3423423987sdgg call me Ishmael", #Not a match
"3423423987 please sir, can I have some more?", #Match
"3423423987", #Match
"3423423987 ", #Match
"3423423987\t", #Match
"adsgsdzgxdzg adsgsdag\t3423423987\t", #Match
"1233423423987", #Not a match
"A3423423987", #Not a match
"3423423987-1a\t", #Match
"3423423987.0", #Not a match
"342342398743635645" #Not a match
]
print("%d words in sample list."%len(possible_word_list))
print("Only 7 should match.")
matches = check_text_for_string("\n".join(possible_word_list), word_to_match)
print("%d matched."%len(matches))
print(matches)
</code></pre>
<p>But clearly, this is wrong. Could someone help me out here?</p>
| 3 | 2016-07-28T07:14:46Z | 38,630,388 | <p>It seems you just want to make sure the number is not matched as part of a, say, float number. You then need to use lookarounds, a lookbehind and a lookahead to disallow dots with digits before and after.</p>
<pre><code>(?<!\d\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)
</code></pre>
<p>See the <a href="https://regex101.com/r/sO0eK6/3" rel="nofollow">regex demo</a></p>
<p><strong>To also match the "prefixes"</strong> (or, better call them "suffixes" here), you need to add something like <code>\S*</code> (zero or more non-whitespaces) or <code>(?:[_-]\w+)?</code> (an optional sequence of a <code>-</code> or <code>_</code> followed with 1+ word chars) at the end of the pattern.</p>
<p><em>Details</em>:</p>
<ul>
<li><code>(?<!\d\.)</code> - fail the match if we have a digit and a dot before the current position</li>
<li><code>(?:\b|_)</code> - either a word boundary or a <code>_</code> (we need it as <code>_</code> is a word char)</li>
<li><code>3423423987</code> - the search string</li>
<li><code>(?:\b|_)</code> - ibid</li>
<li><code>(?!\.\d)</code> - fail the match if a dot + digit is right after the current position.</li>
</ul>
<p>So, use</p>
<pre><code>pattern = r"(?<!\d\.)(?:\b|_)%s(?:\b|_)(?!\.\d)"%string_to_find
</code></pre>
<p>See the <a href="https://ideone.com/YlNOC2" rel="nofollow">Python demo</a></p>
<p>If there can be floats like <code>Text with .3423423987 float value</code>, you will need to also add another lookbehind <code>(?<!\.)</code> after the first one: <code>(?<!\d\.)(?<!\.)(?:\b|_)3423423987(?:\b|_)(?!\.\d)</code></p>
| 3 | 2016-07-28T07:59:59Z | [
"python",
"regex",
"python-3.4"
] |
I want to pip install myFile.env | 38,629,720 | <p>I have a .env file that I used to create a virtual environment. </p>
<p>I want to install the same packages (as specified in the .env file), but this time
I dont want it to be a virtual environment. How can I do this?</p>
<p>Many thanks.</p>
<p>Note:
A .env file can be used by miniconda or anaconda to create virtual environments like so:</p>
<pre><code>conda create --name optimus --file alpha.env
</code></pre>
<p>then you can run</p>
<pre><code>source activate optimus
</code></pre>
<p>to activate your virtualEnv. But how can I do something similar to:</p>
<pre><code>pip install -r myFile.env
</code></pre>
<p>to install all packages specified in myFile.env, but not in a virtual environment.</p>
<p>Here is my alpha.env file:</p>
<pre><code>cairo=1.12.2=2
dateutil=2.1=py27_2
freetype=2.4.10=0
numpy=1.6.2=py27.4
</code></pre>
| 0 | 2016-07-28T07:27:07Z | 38,630,966 | <p>If you have access to your original virtual env or can create a new one as you describe I think a very simple solution would be to simply create a requirements.txt file. This is simply a file that names all the packages that you have installed in a specific python environment. </p>
<p>The file can be created by simply running </p>
<pre><code>pip freeze > requirements.txt
</code></pre>
<p>This will create a file in your working directory called requirements.txt. You have to have your virtual environment active. To then install the packages in your new environment you just have to enter it (deactivate your virtualenv or what ever you need to do) and run </p>
<pre><code>pip install -r requirements.txt
</code></pre>
<p>I have never seen a .env file, but by the sound of it it could actually be exactly the same as a requirements.txt file but under a different name. See if the output of
pip freeze
looks the same (as far as format etc) as what you have in your .env file. In that case you could also just run the command you would in your virtual env ie. </p>
<pre><code>pip install -r myFile.env
</code></pre>
<p>EDIT:
After seeing your .env file output I am convinced that you can simply run the
pip install -r myFile.env
command. </p>
| 0 | 2016-07-28T08:28:35Z | [
"python",
"pip",
"anaconda",
"miniconda"
] |
Python datetime weekday number code - dynamically? | 38,629,754 | <p>to get the weekday no,</p>
<pre><code>import datetime
print datetime.datetime.today().weekday()
</code></pre>
<p>The output is an Integer which is within the range of <strong>0 - 6</strong> indicating Monday as 0 at <a href="https://docs.python.org/2/library/datetime.html#datetime.date.weekday" rel="nofollow">doc-weekday</a></p>
<p>I would like to know how to get the values from Python</p>
<p>I wish to create a dictionary dynamically such as,</p>
<pre><code>{'Monday':0, 'Tuesday':1,...}
</code></pre>
| 0 | 2016-07-28T07:28:49Z | 38,629,996 | <p>The following code will create a dict d with the required values</p>
<pre><code>>>> import calendar
>>> d=dict(enumerate(calendar.day_name))
>>> d
{0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'}
</code></pre>
<p>Edit: The comment below by @mfripp gives a better method</p>
<pre><code>>>> d=dict(zip(calendar.day_name,range(7)))
>>> d
{'Monday': 0, 'Tuesday': 1, 'Friday': 4, 'Wednesday': 2, 'Thursday': 3, 'Sunday': 6, 'Saturday': 5}
</code></pre>
| 1 | 2016-07-28T07:40:48Z | [
"python",
"datetime",
"weekday"
] |
Python datetime weekday number code - dynamically? | 38,629,754 | <p>to get the weekday no,</p>
<pre><code>import datetime
print datetime.datetime.today().weekday()
</code></pre>
<p>The output is an Integer which is within the range of <strong>0 - 6</strong> indicating Monday as 0 at <a href="https://docs.python.org/2/library/datetime.html#datetime.date.weekday" rel="nofollow">doc-weekday</a></p>
<p>I would like to know how to get the values from Python</p>
<p>I wish to create a dictionary dynamically such as,</p>
<pre><code>{'Monday':0, 'Tuesday':1,...}
</code></pre>
| 0 | 2016-07-28T07:28:49Z | 38,630,022 | <p>It is unclear what you are asking for. If you want the day of the week for today, in text form, you could do this:</p>
<pre><code>import datetime
print datetime.datetime.today().strftime('%A')
</code></pre>
<p>If you want to create a dictionary like the one you showed, you could do something like this:</p>
<pre><code>import datetime
# make a list of seven arbitrary dates in a row
dates=[datetime.date.fromtimestamp(0) + datetime.timedelta(days=d) for d in range(7)]
# make a dictionary showing the names and numbers of the days of the week
print {d.strftime('%A'): d.weekday() for d in dates}
</code></pre>
| 0 | 2016-07-28T07:42:00Z | [
"python",
"datetime",
"weekday"
] |
Python datetime weekday number code - dynamically? | 38,629,754 | <p>to get the weekday no,</p>
<pre><code>import datetime
print datetime.datetime.today().weekday()
</code></pre>
<p>The output is an Integer which is within the range of <strong>0 - 6</strong> indicating Monday as 0 at <a href="https://docs.python.org/2/library/datetime.html#datetime.date.weekday" rel="nofollow">doc-weekday</a></p>
<p>I would like to know how to get the values from Python</p>
<p>I wish to create a dictionary dynamically such as,</p>
<pre><code>{'Monday':0, 'Tuesday':1,...}
</code></pre>
| 0 | 2016-07-28T07:28:49Z | 38,630,644 | <p>The simple way to do this is with a dictionary comprehension and the <code>calendar</code> module.</p>
<pre><code>import calendar
days = {name: i for i, name in enumerate(calendar.day_name)}
print(days)
</code></pre>
<p><strong>output</strong></p>
<pre><code>{'Thursday': 3, 'Friday': 4, 'Tuesday': 1, 'Monday': 0, 'Wednesday': 2, 'Saturday': 5, 'Sunday': 6}
</code></pre>
<p>Python 2.6 and older do not have the dictionary comprehension, but you can pass a generator expression to the <code>dict</code> constructor.</p>
<pre><code>days = dict((name, i) for i, name in enumerate(calendar.day_name))
</code></pre>
<hr>
<p>It's also possible to make this <code>dict</code> with <code>datetime</code>, if you really want to. Eg,</p>
<pre><code>from datetime import datetime, timedelta
oneday = timedelta(1)
day = datetime.today()
days = {}
for _ in range(7):
days[day.strftime('%A')] = day.weekday()
day += oneday
</code></pre>
<p>but using calendar is simpler & more efficient.</p>
| 0 | 2016-07-28T08:12:19Z | [
"python",
"datetime",
"weekday"
] |
How to turn off autoscaling in matplotlib.pyplot | 38,629,830 | <p>I am using matplotlib.pyplot in python to plot my data. The problem is the image it generates seems to be autoscaled. How can I turn this off so that when I plot something at (0,0) it will be placed fixed in the center?</p>
| 0 | 2016-07-28T07:32:30Z | 38,629,943 | <p>You can use <code>xlim()</code> and <code>ylim()</code> to set the limits. If you know your data goes from, say -10 to 20 on X and -50 to 30 on Y, you can do:</p>
<pre><code>plt.xlim((-20, 20))
plt.ylim((-50, 50))
</code></pre>
<p>to make 0,0 centered.</p>
<p>If your data is dynamic, you could try allowing the autoscale at first, but then set the limits to be inclusive:</p>
<pre><code>xlim = plt.xlim()
max_xlim = max(map(abs, xlim))
plt.xlim((-max_xlim, max_xlim))
ylim = plt.ylim()
max_ylim = max(map(abs, ylim))
plt.ylim((-max_ylim, max_ylim))
</code></pre>
| 0 | 2016-07-28T07:37:52Z | [
"python",
"matplotlib"
] |
How to turn off autoscaling in matplotlib.pyplot | 38,629,830 | <p>I am using matplotlib.pyplot in python to plot my data. The problem is the image it generates seems to be autoscaled. How can I turn this off so that when I plot something at (0,0) it will be placed fixed in the center?</p>
| 0 | 2016-07-28T07:32:30Z | 38,630,201 | <p>You want the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.autoscale" rel="nofollow"><code>autoscale</code></a> function:</p>
<pre><code>from matplotlib import pyplot as plt
# Set the limits of the plot
plt.xlim(-1, 1)
plt.ylim(-1, 1)
# Don't mess with the limits!
plt.autoscale(False)
# Plot anything you want
plt.plot([0, 1])
</code></pre>
| 1 | 2016-07-28T07:50:53Z | [
"python",
"matplotlib"
] |
Need help making Django + Ajax like button | 38,629,848 | <p>I am new to coding and have currently implemented the like button from the online book - Tango with django: </p>
<p><a href="http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button" rel="nofollow">http://www.tangowithdjango.com/book17/chapters/ajax.html#add-a-like-button</a></p>
<p>However for my project I need to record which users have liked what and also ensure that they can only like an item once (similar to instagram/facebook). I have looked at other related questions online but have found that there is no well laid out answer for other beginners to follow. If someone could do an easy to follow answer to help me and other people who are trying to achieve the same in the future, it would be greatly appreciated! </p>
<p>my current code is as follows:</p>
<p>models</p>
<pre><code>class UserProject(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
date_created = models.DateTimeField(auto_now_add=True)
project_likes = models.IntegerField(default=0)
slug = models.SlugField(max_length=100, unique=True)
</code></pre>
<p>views</p>
<pre><code>@login_required
def like_project(request):
proj_id = None
if request.method == 'GET':
proj_id = request.GET['project_id']
likes = 0
if proj_id:
proj = UserProject.objects.get(id=int(proj_id))
if proj:
likes = proj.project_likes + 1
proj.project_likes = likes
proj.save()
return HttpResponse(likes)
</code></pre>
<p>template</p>
<pre><code><strong id="like_count">{{ project.project_likes }}</strong> likes
{% if user.is_authenticated %}
<button id="likes" data-projid="{{project.id}}" class="btn btn-danger-outline btn-sm" type="button"> <i class="fa fa-heart-o" aria-hidden="true"></i>
like
</button>
{% endif %}
</code></pre>
<p>URL</p>
<pre><code>url(r'^like_project/$', views.like_project, name='like_project'),
</code></pre>
<p>Ajax</p>
<pre><code>$(document).ready(function() {
$('#likes').click(function(){
var projid;
projid = $(this).attr("data-projid");
$.get('/like_project/', {project_id: projid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
});
</code></pre>
| 0 | 2016-07-28T07:33:27Z | 38,630,112 | <p>If you want to make sure no <code>User</code> likes the same <code>UserProject</code> twice, you can not simply store the number of likes in the <code>project_likes</code> field, but you should rather create a separate model (e.g. <code>UserLikes</code>) with <code>ForeignKeys</code> to <code>User</code> and <code>UserProject</code>, and e.g. the time at which the User liked the <code>UserProject</code>. You can then make a function on your <code>UserProject</code> model to count the number of likes.</p>
| 0 | 2016-07-28T07:45:57Z | [
"jquery",
"python",
"ajax",
"django"
] |
Python: renaming files returns the wrong name | 38,629,902 | <p>Say I have a folder with 1000 csv files which names are <code>event_1.csv</code>, <code>event_2.csv</code>,..., <code>event_1000.csv</code>.</p>
<p>I in fact have 25 folders like this and want to rename those files in such a way that the first 4 characters are <code>0001</code> for the first folder, <code>0002</code> for the second, all the way up to <code>0025</code>. The last 4 characters represent the event, such that the 1st event is <code>0001</code>, the second <code>0002</code>, all the way to <code>1000</code>.</p>
<p>So the 1st file in the 1st folder is changed in this fashion: <code>event_1.csv = 00010001.csv</code>.</p>
<p>Anyway my code is wrong, in that the first 100 files in the 1st folder are named <code>00020000.csv</code> to <code>00020099.csv</code>, since <code>0002</code> should be used in the 2nd folder only. Then, from the 101st file to the last, I get the correct filenames: <code>00010101.csv</code> to <code>00011000.csv</code>.</p>
<p><strong>This is my code: what is wrong with that?</strong></p>
<pre><code>import os, sys
import glob
import csv
directory=r'C:\Users\MyName\Desktop\Tests'
subdir=[x[0] for x in os.walk(directory)]
subdir.pop(0)
N=['0001','0002','0003','0004','0005','0006','0007','0008','0009','0010','0011','0012','0013','0014','0015','0016','0017','0018','0019','0020','0021','0022','0023','0024','0025']
for i in subdir:
for n in N:
temp_dir=r''+i
os.chdir(temp_dir)
A=str(n)
for file in glob.glob("*.csv"):
if len(file)==11:
event='000'+str(file[6])
newname=A+event
os.rename(file, newname + '.csv')
if len(file)==12:
event='00'+str(file[6:8])
newname=A+event
os.rename(file, newname + '.csv')
if len(file)==13:
event='0'+str(file[6:9])
newname=A+event
os.rename(file, newname + '.csv')
if len(file)==14:
event=file[6:10]
newname=A+event
os.rename(file, newname + '.csv')
</code></pre>
| 0 | 2016-07-28T07:36:06Z | 38,630,504 | <p>If you're sure about all the names of your files, you could considerably simplify your code (as M.T said). Try maybe something like :</p>
<pre><code>for n,i in enumerate(subdir):
os.chdir(r''+i) # Or whatever your folders are named
for m,file in enumerate(glob.glob("*.csv")):
newname = "{0:04d}{1:04d}.csv".format(n+1,m+1)
os.rename(file, newname)
</code></pre>
<p><strong>EDIT : it's better with enumerate.</strong></p>
| 1 | 2016-07-28T08:05:15Z | [
"python",
"csv",
"directory",
"renaming"
] |
adding spaces inside string using regex sub | 38,630,228 | <p>I have a string I want to split into 2-digit pieces. I tried using regex like so:</p>
<pre><code>import re
s = "123456789"
t = re.sub('..', ".. ", s)
print(t)
</code></pre>
<p>I expected to get <code>12 34 56 78 9</code> but instead I got <code>'.. .. .. .. 9'</code>. The <code>9</code> does not bother me, because I know I will have an even number of digits, but how can I tell the <code>re.sub</code> to not replace the actual digit with a dot?</p>
<p><em>using python shell 3.5.1</em></p>
<p><strong>EDIT</strong></p>
<p>checked all 3 answers, and they all work, but the findall seems to be faster (and more elegant IMO ;p ):</p>
<pre><code>import time
import re
s = "43256711233214432"
i = 10000
start = time.time()
while i:
i -= 1
re.sub('(..)', r"\1 ", s)
end = time.time()
elapsed = end - start
print("using r\"\\1 \" : ", elapsed)
i = 10000
start = time.time()
while i:
re.sub('..', r"\g<0> ", s)
i -= 1
end = time.time()
elapsed = end - start
print("using r\"\g<0> \" : ", elapsed)
i = 10000
start = time.time()
while i:
' '.join(re.findall(r'..|.', s))
i -= 1
end = time.time()
elapsed = end - start
print("using findall : ", elapsed)
</code></pre>
<blockquote>
<p>using r"\1 " : 0.25461769104003906</p>
<p>using r"\g<0> " : 0.09374403953552246</p>
<p>using findall : 0.015610456466674805</p>
</blockquote>
<p><strong>2nd EDIT:</strong> is there a better way (or any way...) doing this <em>without</em> regex?</p>
| 1 | 2016-07-28T07:52:17Z | 38,630,285 | <p>In a regex, <code>.</code> means any character. In replacement text, it means a period. If you want to capture characters as a group in your regex, you need to put parens around them. You can reference the first such group in the replacement text by using <code>\1</code>:</p>
<pre><code>>>> re.sub('(..)', r"\1 ", s)
'12 34 56 78 9'
</code></pre>
| 2 | 2016-07-28T07:54:53Z | [
"python",
"regex"
] |
adding spaces inside string using regex sub | 38,630,228 | <p>I have a string I want to split into 2-digit pieces. I tried using regex like so:</p>
<pre><code>import re
s = "123456789"
t = re.sub('..', ".. ", s)
print(t)
</code></pre>
<p>I expected to get <code>12 34 56 78 9</code> but instead I got <code>'.. .. .. .. 9'</code>. The <code>9</code> does not bother me, because I know I will have an even number of digits, but how can I tell the <code>re.sub</code> to not replace the actual digit with a dot?</p>
<p><em>using python shell 3.5.1</em></p>
<p><strong>EDIT</strong></p>
<p>checked all 3 answers, and they all work, but the findall seems to be faster (and more elegant IMO ;p ):</p>
<pre><code>import time
import re
s = "43256711233214432"
i = 10000
start = time.time()
while i:
i -= 1
re.sub('(..)', r"\1 ", s)
end = time.time()
elapsed = end - start
print("using r\"\\1 \" : ", elapsed)
i = 10000
start = time.time()
while i:
re.sub('..', r"\g<0> ", s)
i -= 1
end = time.time()
elapsed = end - start
print("using r\"\g<0> \" : ", elapsed)
i = 10000
start = time.time()
while i:
' '.join(re.findall(r'..|.', s))
i -= 1
end = time.time()
elapsed = end - start
print("using findall : ", elapsed)
</code></pre>
<blockquote>
<p>using r"\1 " : 0.25461769104003906</p>
<p>using r"\g<0> " : 0.09374403953552246</p>
<p>using findall : 0.015610456466674805</p>
</blockquote>
<p><strong>2nd EDIT:</strong> is there a better way (or any way...) doing this <em>without</em> regex?</p>
| 1 | 2016-07-28T07:52:17Z | 38,630,324 | <p>You can just refer to the whole match with <code>\g<0></code> <strong>backreference</strong> in the replacement string pattern (where you cannot use <em>regular expression</em> patterns):</p>
<pre><code>re.sub('..', r"\g<0> ", s)
</code></pre>
<p><a href="https://ideone.com/a1Lisg" rel="nofollow">Python demo</a>:</p>
<pre><code>import re
s = "12345678"
print(re.sub('..', r"\g<0> ", s))
</code></pre>
<p>See <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub</code> reference</a>:</p>
<blockquote>
<p>The backreference <code>\g<0></code> substitutes in the entire substring matched by the RE.</p>
</blockquote>
| 3 | 2016-07-28T07:56:46Z | [
"python",
"regex"
] |
adding spaces inside string using regex sub | 38,630,228 | <p>I have a string I want to split into 2-digit pieces. I tried using regex like so:</p>
<pre><code>import re
s = "123456789"
t = re.sub('..', ".. ", s)
print(t)
</code></pre>
<p>I expected to get <code>12 34 56 78 9</code> but instead I got <code>'.. .. .. .. 9'</code>. The <code>9</code> does not bother me, because I know I will have an even number of digits, but how can I tell the <code>re.sub</code> to not replace the actual digit with a dot?</p>
<p><em>using python shell 3.5.1</em></p>
<p><strong>EDIT</strong></p>
<p>checked all 3 answers, and they all work, but the findall seems to be faster (and more elegant IMO ;p ):</p>
<pre><code>import time
import re
s = "43256711233214432"
i = 10000
start = time.time()
while i:
i -= 1
re.sub('(..)', r"\1 ", s)
end = time.time()
elapsed = end - start
print("using r\"\\1 \" : ", elapsed)
i = 10000
start = time.time()
while i:
re.sub('..', r"\g<0> ", s)
i -= 1
end = time.time()
elapsed = end - start
print("using r\"\g<0> \" : ", elapsed)
i = 10000
start = time.time()
while i:
' '.join(re.findall(r'..|.', s))
i -= 1
end = time.time()
elapsed = end - start
print("using findall : ", elapsed)
</code></pre>
<blockquote>
<p>using r"\1 " : 0.25461769104003906</p>
<p>using r"\g<0> " : 0.09374403953552246</p>
<p>using findall : 0.015610456466674805</p>
</blockquote>
<p><strong>2nd EDIT:</strong> is there a better way (or any way...) doing this <em>without</em> regex?</p>
| 1 | 2016-07-28T07:52:17Z | 38,630,475 | <p>You may use <code>re.findall</code> also,</p>
<pre><code>>>> s = "123456789"
>>> ' '.join(re.findall(r'..|.', s))
'12 34 56 78 9'
>>>
</code></pre>
<p><code>r'..|.'</code> regex matches two chars or a single character (first preference goes to <code>..</code> and then <code>.</code>)</p>
| 4 | 2016-07-28T08:04:11Z | [
"python",
"regex"
] |
adding spaces inside string using regex sub | 38,630,228 | <p>I have a string I want to split into 2-digit pieces. I tried using regex like so:</p>
<pre><code>import re
s = "123456789"
t = re.sub('..', ".. ", s)
print(t)
</code></pre>
<p>I expected to get <code>12 34 56 78 9</code> but instead I got <code>'.. .. .. .. 9'</code>. The <code>9</code> does not bother me, because I know I will have an even number of digits, but how can I tell the <code>re.sub</code> to not replace the actual digit with a dot?</p>
<p><em>using python shell 3.5.1</em></p>
<p><strong>EDIT</strong></p>
<p>checked all 3 answers, and they all work, but the findall seems to be faster (and more elegant IMO ;p ):</p>
<pre><code>import time
import re
s = "43256711233214432"
i = 10000
start = time.time()
while i:
i -= 1
re.sub('(..)', r"\1 ", s)
end = time.time()
elapsed = end - start
print("using r\"\\1 \" : ", elapsed)
i = 10000
start = time.time()
while i:
re.sub('..', r"\g<0> ", s)
i -= 1
end = time.time()
elapsed = end - start
print("using r\"\g<0> \" : ", elapsed)
i = 10000
start = time.time()
while i:
' '.join(re.findall(r'..|.', s))
i -= 1
end = time.time()
elapsed = end - start
print("using findall : ", elapsed)
</code></pre>
<blockquote>
<p>using r"\1 " : 0.25461769104003906</p>
<p>using r"\g<0> " : 0.09374403953552246</p>
<p>using findall : 0.015610456466674805</p>
</blockquote>
<p><strong>2nd EDIT:</strong> is there a better way (or any way...) doing this <em>without</em> regex?</p>
| 1 | 2016-07-28T07:52:17Z | 38,630,797 | <p>You can use List Comprehensions too,</p>
<pre><code>>>> s='123456789'
>>> res=[s[index:index+2] for index,x in enumerate(s) if index % 2==0]
['12', '34', '56', '78', '9']
</code></pre>
| 0 | 2016-07-28T08:20:40Z | [
"python",
"regex"
] |
Selenium Error: Element is not clickable at point(X,Y), other element would receive the click | 38,630,254 | <p>I am using python and selenium. On <a href="https://steemit.com/steem/@cheolwoo-kim/what-is-steemit" rel="nofollow">this</a> link I would to click <code>Reply</code> to add comment</p>
<blockquote>
<p>Element is not clickable at point (933.9500122070312,
16.666671752929688). Other element would receive the click: <code><a href="/create_account"></a></code></p>
</blockquote>
<p>Code given here:</p>
<p>import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize</p>
<p>from selenium import webdriver</p>
<pre><code>from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get(url)
sleep(4)
f = driver.find_element_by_css_selector('.PostFull__reply')
f.location_once_scrolled_into_view
f.click()
</code></pre>
<p><strong>Update</strong></p>
<p>This is how it appears in Inspector:</p>
<p><a href="http://i.stack.imgur.com/DEB1p.png" rel="nofollow"><img src="http://i.stack.imgur.com/DEB1p.png" alt="enter image description here"></a></p>
| 1 | 2016-07-28T07:53:12Z | 38,632,255 | <p>Your css is correct, the problem with the long content is that it scrolls the element to below of the <code>.Header</code> that why it can't click the element.</p>
<p>You can get the location of the element and scroll to 100px less than Y coordinate since the height of <code>.Header</code> is 49.5px and it is better to maximize the window before testing. See below: </p>
<pre><code>driver.maximize_window()
f = driver.find_element_by_css_selector('.PostFull__reply')
location = f.location["y"] - 100
driver.execute_script("window.scrollTo(0, %d);" %location)
f.click()
</code></pre>
| 1 | 2016-07-28T09:25:35Z | [
"python",
"selenium"
] |
Selenium Error: Element is not clickable at point(X,Y), other element would receive the click | 38,630,254 | <p>I am using python and selenium. On <a href="https://steemit.com/steem/@cheolwoo-kim/what-is-steemit" rel="nofollow">this</a> link I would to click <code>Reply</code> to add comment</p>
<blockquote>
<p>Element is not clickable at point (933.9500122070312,
16.666671752929688). Other element would receive the click: <code><a href="/create_account"></a></code></p>
</blockquote>
<p>Code given here:</p>
<p>import requests
from bs4 import BeautifulSoup
from gensim.summarization import summarize</p>
<p>from selenium import webdriver</p>
<pre><code>from datetime import datetime
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get(url)
sleep(4)
f = driver.find_element_by_css_selector('.PostFull__reply')
f.location_once_scrolled_into_view
f.click()
</code></pre>
<p><strong>Update</strong></p>
<p>This is how it appears in Inspector:</p>
<p><a href="http://i.stack.imgur.com/DEB1p.png" rel="nofollow"><img src="http://i.stack.imgur.com/DEB1p.png" alt="enter image description here"></a></p>
| 1 | 2016-07-28T07:53:12Z | 38,634,058 | <p>You are trying to click on <code>span</code> element while actually it should be <code>a</code> element. Here you should try to locate <code>a</code> element using <code>WebDriverWait</code> to wait until element visible and clickable on <code>DOM</code> then perform click as below :-</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.get(url)
f = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".PostFull__reply > a")))
f.location_once_scrolled_into_view
f.click()
</code></pre>
<p>If unfortunately <code>f.click()</code> does not work correctly, you can also perform click using <code>execute_script()</code> as below :-</p>
<pre><code>driver.execute_script('arguments[0].click()', f)
</code></pre>
<p>Hope it works..:)</p>
| 0 | 2016-07-28T10:43:37Z | [
"python",
"selenium"
] |
Maya Python: Accessing outer function variable from inner funtion | 38,630,356 | <p>I want to write a UI window using python, the following is my code, the function is running correctly, but there is a problem, when I choose an item in the textScrollList, it should call the inner funtion 'update()' and highlight the corresponding object in the scene.
However, the object cannot be chosen correctly and it shows an error message like this : </p>
<p>"Object 'alertWindow|formLayout164|textScrollList27' not found."</p>
<p>I think this happens because the inner function update() cannot access the variable tsl in the outer funciton, does anyone know how I can revise my code?</p>
<p>Thanks a lot!</p>
<pre><code>def alertWindow():
if(cmds.window('mainWindow', q =True, exists = True,)):
cmds.deleteUI('mainWindow')
UI = cmds.window('mainWindow', title = 'Alert!', maximizeButton = False, minimizeButton = False, resizeToFitChildren = True, widthHeight = (250, 300), sizeable = False)
myForm=cmds.formLayout( )
txt = cmds.text(label = 'Please check the following objects :')
tsl = cmds.textScrollList(width = 200, height = 200, enable = True, allowMultiSelection = True, selectCommand = 'update()')
count = len(obj)
for i in range(count):
cmds.textScrollList(tsl, edit=True, append = obj[i])
delete = cmds.button(label = 'delete', width = 100, command = 'remove()')
clz = cmds.button(label = 'Close', width = 100, command = 'cmds.deleteUI("mainWindow")')
cmds.formLayout(myForm, edit = True, attachForm = [(txt, 'top', 20),(txt, 'left', 65),(tsl, 'left', 25),(tsl, 'top', 50),(delete,'bottom',10),(delete,'left',15),(clz,'bottom',10),(clz,'right',20)])
cmds.showWindow(UI)
def update():
cmds.select(cmds.textScrollList(tsl, q=True, selectItem = True))
def remove():
cmds.DeleteHistory()
cmds.textScrollList(tsl, edit=True, removeItem = cmds.ls(sl=True))
</code></pre>
| 0 | 2016-07-28T07:58:20Z | 38,631,128 | <p>You can try with a global variable "global tsl" at the top of your code. That isn't the most beautiful however, it works :)</p>
| 0 | 2016-07-28T08:36:21Z | [
"python",
"maya"
] |
Maya Python: Accessing outer function variable from inner funtion | 38,630,356 | <p>I want to write a UI window using python, the following is my code, the function is running correctly, but there is a problem, when I choose an item in the textScrollList, it should call the inner funtion 'update()' and highlight the corresponding object in the scene.
However, the object cannot be chosen correctly and it shows an error message like this : </p>
<p>"Object 'alertWindow|formLayout164|textScrollList27' not found."</p>
<p>I think this happens because the inner function update() cannot access the variable tsl in the outer funciton, does anyone know how I can revise my code?</p>
<p>Thanks a lot!</p>
<pre><code>def alertWindow():
if(cmds.window('mainWindow', q =True, exists = True,)):
cmds.deleteUI('mainWindow')
UI = cmds.window('mainWindow', title = 'Alert!', maximizeButton = False, minimizeButton = False, resizeToFitChildren = True, widthHeight = (250, 300), sizeable = False)
myForm=cmds.formLayout( )
txt = cmds.text(label = 'Please check the following objects :')
tsl = cmds.textScrollList(width = 200, height = 200, enable = True, allowMultiSelection = True, selectCommand = 'update()')
count = len(obj)
for i in range(count):
cmds.textScrollList(tsl, edit=True, append = obj[i])
delete = cmds.button(label = 'delete', width = 100, command = 'remove()')
clz = cmds.button(label = 'Close', width = 100, command = 'cmds.deleteUI("mainWindow")')
cmds.formLayout(myForm, edit = True, attachForm = [(txt, 'top', 20),(txt, 'left', 65),(tsl, 'left', 25),(tsl, 'top', 50),(delete,'bottom',10),(delete,'left',15),(clz,'bottom',10),(clz,'right',20)])
cmds.showWindow(UI)
def update():
cmds.select(cmds.textScrollList(tsl, q=True, selectItem = True))
def remove():
cmds.DeleteHistory()
cmds.textScrollList(tsl, edit=True, removeItem = cmds.ls(sl=True))
</code></pre>
| 0 | 2016-07-28T07:58:20Z | 38,645,112 | <p>You need to define your inner functions first, then just reference them, no need to use a string for <code>command=</code> :</p>
<pre><code>def alertWindow(obj):
def update():
cmds.select(cmds.textScrollList(tsl, q=True, selectItem = True))
def remove():
cmds.DeleteHistory()
cmds.textScrollList(tsl, edit=True, removeItem = cmds.ls(sl=True))
if(cmds.window('mainWindow', q =True, exists = True,)):
cmds.deleteUI('mainWindow')
UI = cmds.window('mainWindow', title = 'Alert!', maximizeButton = False, minimizeButton = False, resizeToFitChildren = True, widthHeight = (250, 300), sizeable = False)
myForm=cmds.formLayout( )
txt = cmds.text(label = 'Please check the following objects :')
tsl = cmds.textScrollList(width = 200, height = 200, enable = True, allowMultiSelection = True, selectCommand = update)
count = len(obj)
for i in range(count):
cmds.textScrollList(tsl, edit=True, append = obj[i])
delete = cmds.button(label = 'delete', width = 100, command = remove)
clz = cmds.button(label = 'Close', width = 100, command = 'cmds.deleteUI("mainWindow")')
cmds.formLayout(myForm, edit = True, attachForm = [(txt, 'top', 20),(txt, 'left', 65),(tsl, 'left', 25),(tsl, 'top', 50),(delete,'bottom',10),(delete,'left',15),(clz,'bottom',10),(clz,'right',20)])
cmds.showWindow(UI)
cmds.polyCube()
alertWindow(['pCube1'])
</code></pre>
<p>You could also use a class to keep the state of things.</p>
| 0 | 2016-07-28T19:25:06Z | [
"python",
"maya"
] |
How to execute shell command and stream output with Python and Flask upon HTTP request? | 38,630,421 | <p>Following <a href="http://stackoverflow.com/questions/15092961/how-to-continuously-display-python-output-in-a-webpage">this post</a>, I am able to <code>tail -f</code> a log file to a webpage:</p>
<pre><code>from gevent import sleep
from gevent.wsgi import WSGIServer
import flask
import subprocess
app = flask.Flask(__name__)
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['tail -f ./log'],
shell=True,
stdout=subprocess.PIPE
)
for line in iter(proc.stdout.readline,''):
sleep(0.1)
yield line.rstrip() + '<br/>\n'
return flask.Response(inner(), mimetype='text/html')
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
</code></pre>
<p>There are two issues in this approach.</p>
<ol>
<li>The <code>tail -f log</code> process will linger after closing the webpage. There will be n tail process after visiting <a href="http://localhost:5000/yield" rel="nofollow">http://localhost:5000/yield</a> n time</li>
<li>There can only be 1 client accessing <a href="http://localhost:5000/yield" rel="nofollow">http://localhost:5000/yield</a> at a single time</li>
</ol>
<p>My question(s) is, is it possible to make flask execute a shell command when someone visit a page and terminating the command when client close the page? Like <kbd>Ctrl</kbd>+<kbd>C</kbd> after <code>tail -f log</code>. If not, what are the alternatives?
Why was I only able to have 1 client accessing the page at a time?</p>
<p>Note: I am looking into general way of starting/stoping an arbitrary shell command instead of particularly tailing a file</p>
| 0 | 2016-07-28T08:01:46Z | 38,643,387 | <p>Here is some code that should do the job. Some notes:</p>
<ol>
<li><p>You need to detect when the request disconnects, and then terminate the proc. The try/except code below will do that. However, after inner() reaches its end, Python will try to close the socket normally, which will raise an exception (I think it's socket.error, per <a href="http://stackoverflow.com/questions/180095/how-to-handle-a-broken-pipe-sigpipe-in-python">How to handle a broken pipe (SIGPIPE) in python?</a>). I can't find a way to catch this exception cleanly; e.g., it doesn't work if I explicitly raise StopIteration at the end of inner(), and surround that with a try/except socket.error block. That may be a limitation of Python's exception handling. There may be something else you can do within the generator function to tell flask to abort streaming without trying to close the socket normally, but I haven't found it.</p></li>
<li><p>Your main thread is blocking during proc.stdout.readline(), and gevent.sleep() comes too late to help. In principle gevent.monkey.patch_all() can patch the standard library so that functions that would normally block the thread will yield control to gevent instead (see <a href="http://www.gevent.org/gevent.monkey.html" rel="nofollow">http://www.gevent.org/gevent.monkey.html</a>). However, that doesn't seem to patch proc.stdout.readline(). The code below uses gevent.select.select() to wait for data to become available on proc.stdout or proc.stderr before yielding the new data. This allows gevent to run other greenlets (e.g., serve other web clients) while waiting.</p></li>
<li><p>The webserver seems to buffer the first few kB of data being sent to the client, so you may not see anything in your web browser until a number of new lines have been added to ./log. After that, it seems to send new data immediately. Not sure how to get the first part of the request to be sent right away, but it's probably a pretty common problem with streaming servers, so there should be a solution. This isn't a problem with commands that terminate quickly on their own, since their full output will be sent once they terminate.</p></li>
</ol>
<p>You may also find something useful at <a href="https://mortoray.com/2014/03/04/http-streaming-of-command-output-in-python-flask/" rel="nofollow">https://mortoray.com/2014/03/04/http-streaming-of-command-output-in-python-flask/</a> .</p>
<p>Here's the code:</p>
<pre><code>from gevent.select import select
from gevent.wsgi import WSGIServer
import flask
import subprocess
app = flask.Flask(__name__)
@app.route('/yield')
def index():
def inner():
proc = subprocess.Popen(
['tail -f ./log'],
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
# pass data until client disconnects, then terminate
# see http://stackoverflow.com/questions/18511119/stop-processing-flask-route-if-request-aborted
try:
awaiting = [proc.stdout, proc.stderr]
while awaiting:
# wait for output on one or more pipes, or for proc to close a pipe
ready, _, _ = select(awaiting, [], [])
for pipe in ready:
line = pipe.readline()
if line:
# some output to report
print "sending line:", line.replace('\n', '\\n')
yield line.rstrip() + '<br/>\n'
else:
# EOF, pipe was closed by proc
awaiting.remove(pipe)
if proc.poll() is None:
print "process closed stdout and stderr but didn't terminate; terminating now."
proc.terminate()
except GeneratorExit:
# occurs when new output is yielded to a disconnected client
print 'client disconnected, killing process'
proc.terminate()
# wait for proc to finish and get return code
ret_code = proc.wait()
print "process return code:", ret_code
return flask.Response(inner(), mimetype='text/html')
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
</code></pre>
| 0 | 2016-07-28T17:46:59Z | [
"python",
"linux",
"flask",
"subprocess"
] |
Error while installing GDAL | 38,630,474 | <p>I'm trying to install GDAL through pip. But I'm getting this error:</p>
<pre><code>extensions/gdal_wrap.cpp:3089:27: fatal error: cpl_vsi_error.h: No such file or directory
#include "cpl_vsi_error.h"
^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
</code></pre>
<p>I used these commands:</p>
<pre><code>sudo apt-get install libgdal-dev
export CPLUS_INCLUDE_PATH=/usr/include/gdal
export C_INCLUDE_PATH=/usr/include/gdal
pip install GDAL
</code></pre>
<p>Can anyone tell me how to install it ?</p>
| 0 | 2016-07-28T08:04:09Z | 38,630,941 | <p>Check that you installed GDAL using this command</p>
<pre><code>gdal-config --version
</code></pre>
<p>Then run this commands:</p>
<pre><code>pip install --download="some_path" GDAL
cd some_path
tar -xvzf GDAL-<version>.tar.gz
cd GDAL-<version>
python setup.py build_ext --include-dirs=/usr/include/gdal/
python setup.py install
</code></pre>
| 0 | 2016-07-28T08:27:04Z | [
"python",
"pip",
"gdal"
] |
Best way to avoid copy-paste and hardcoding | 38,630,613 | <p>' Hello, SO community.</p>
<p><strong>Problem:</strong> I have many regEx patterns, such as</p>
<pre><code>r'to.*school', r'built.*in'
</code></pre>
<p>and etc. In every case, I should execute a code, that varies from situation to situation.</p>
<p><strong>Example:</strong> If pattern is 'to.*school', I want to find the verb before 'to' and that's why I write something like:</p>
<pre><code>for num, part in enumerate(sentence):
if part == 'to':
result = sentence[num-1]
</code></pre>
<p>If pattern is 'built.*in', I want to find the time and that's why I write something like:</p>
<pre><code>for num, part in enumerate(sentence):
if part == 'in':
result = sentence[num+1]
</code></pre>
<p>So there's the problem - how can I avoid copy-pasting code, if there's over 500 patterns and each pattern has its own way to get result?</p>
<p><strong>My thoughts:</strong> I understand it should be some kind of database, which stores patterns and solutions, but how do I execute solution, if it's a string? I'm totally lost.</p>
| 0 | 2016-07-28T08:10:39Z | 38,634,940 | <p>If there is sufficient regularity in the code you need to write a function which accepts sentence and the other things which determine what to do with it. This is sometimes called parametrisation. For example with your above, presumably simplified examples, you'd have</p>
<pre><code>def process(sentence, parttest, offset):
for num, part in enumerate(sentence):
if part == parttest:
return sentence[num+offset]
</code></pre>
<p>and calls for first and second examples respectively</p>
<pre><code>result = process( sentence, 'to', -1)
result2 = process( sentence, 'in', +1)
</code></pre>
<p>Now you can obtain the parameters (parttest, offset) from a database. Judging from your post there may also be a regular expression in string form to be retrieved from the database as well, and <code>process</code> to be extended to include a regular expression string which is compiled on demand.</p>
<p>Optimize later: keep a local cache of compiled regular expressions in a dict, or pickle them, because repeatedly compiling the same one may be a nontrivial waste of CPU.</p>
<p>Hope this helps.</p>
| 1 | 2016-07-28T11:23:22Z | [
"python",
"design-patterns"
] |
Issue creating a Numpy NDArray from PyArray_SimpleNewFromData | 38,630,716 | <p>I try to do a python wrapper to bind some C++ functions and types to python. My issue is when I try to convert a custom matrix type to a numpy ndarray. The most convincing solution is to use <code>PyArray_SimpleNewFromData</code>.</p>
<p>To test its behaviour, as I didn't manage to do what I wanted I tried to implement a simple test:</p>
<pre><code>PyObject* ConvertToPython(...) {
uint8_t test[10] = {12, 15, 82, 254, 10, 32, 0, 8, 127, 54};
int32_t ndims = 1;
npy_intp dims[1];
dims[0] = 10;
int32_t typenum = (int32_t)NPY_UBYTE;
PyObject* python_object = PyArray_SimpleNewFromData(ndims, dims, typenum, (void*)test);
Py_XINCREF(python_object);
return python_object;
}
</code></pre>
<p>And then I got in python these results:</p>
<pre><code>type(test) = <type 'numpy.ndarray'>
test.ndim = 1
test.dtype = uint8
test.shape = (10,)
</code></pre>
<p>But the values inside the array are: </p>
<pre><code>test.values = [ 1 0 0 0 0 0 0 0 80 8]
</code></pre>
<p>I cannot figure out, what am I doing wrong ? And I am not very experienced doing a python Wrapper so any help would be appreciable !</p>
| 0 | 2016-07-28T08:16:03Z | 38,631,409 | <p>I would try with an array that has been allocated by malloc, and then perhaps settings some flag named <code>OWNDATA</code> in order to avoid a memory leak. </p>
<p>At least the garbage data can be explained if the instance of <code>numpy.ndarray</code> does not copy the data but just stores a pointer to the supplied array. After the functions returns, a pointer to stack allocated array points to memory that may change any time the stack is changed.</p>
| 2 | 2016-07-28T08:49:46Z | [
"python",
"c++",
"numpy",
"wrapper"
] |
Python import error no module named bz2 | 38,630,720 | <p>I have libbz2-dev installed however I am still getting the following import error while importing gensim :</p>
<pre><code>>>> import gensim
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/krishna/gensimenv/lib/python2.7/site-packages/gensim/__init__.py", line 6, in <module>
from gensim import parsing, matutils, interfaces, corpora, models, similarities, summarization
File "/home/krishna/gensimenv/lib/python2.7/site-packages/gensim/corpora/__init__.py", line 14, in <module>
from .wikicorpus import WikiCorpus
File "/home/krishna/gensimenv/lib/python2.7/site-packages/gensim/corpora/wikicorpus.py", line 21, in <module>
import bz2
ImportError: No module named bz2
</code></pre>
| -1 | 2016-07-28T08:16:09Z | 38,631,498 | <p>you can try to do </p>
<pre><code>pip install bz2file
</code></pre>
| 1 | 2016-07-28T08:53:30Z | [
"python",
"gensim"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,630,875 | <pre><code>out = []
for i in list1:
out.append(list2.pop(0) if i else '-')
</code></pre>
| 0 | 2016-07-28T08:24:26Z | [
"python",
"arraylist"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,631,074 | <p>Try this:</p>
<pre><code>output = [list2.pop(b-1) for b in list1]
</code></pre>
| 3 | 2016-07-28T08:33:26Z | [
"python",
"arraylist"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,631,095 | <p>Or even this one liner:</p>
<pre><code>list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a','b','c','d','e','f','-','-','-','-']
output = [list2[i] if v else '-' for i, v in enumerate(list1)]
print(output)
</code></pre>
<p><strong>UPDATE Not quite a one liner and could be more efficient in the for loop - but I prefer this readbility</strong></p>
<pre><code>list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a','b','c','d','e','f']
output = []
j = 0
for i, v in enumerate(list1):
output.append('-' if not v else list2[j])
j = j if not v else j+1
print(output)
</code></pre>
| 0 | 2016-07-28T08:34:37Z | [
"python",
"arraylist"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,631,179 | <p>Based on your code, I think this is what you want.</p>
<p>For each element in list1, if the element is a 1, add the next element in list2 to newList. If it's a 0, add a hyphen to newList.</p>
<pre><code>list1 = [ 0, 0, 1, 1, 1, 0 ]
list2 = [ 'a', 'b', 'c', 'd', 'e', 'f' ] # idk why you needed hyphens in this list
newList = [ ]
i = 0
j = 0
for i in range (len(list1)):
if list1(i) == 1:
newList += [ list2(j) ]
j++
if list1(i) == 0:
newList += [ '-' ]
return newList
# output: [ '-', '-', 'a', 'b', 'c', '-' ]
</code></pre>
<p>Unless your goal is that if the element in list1 is a 1, add the next element from the beginning of list1 to newList, and if it's a 0, add the next element from the end. This will not guarantee that the 0s create corresponding hyphens.</p>
<pre><code>list1 = [ 0, 0, 1, 1, 1, 0 ]
list2 = [ 'a', 'b', 'c', '-', '-', '-' ]
newList = [ ]
i = 0
start = 0
end = len(list2) - 1
for i in range (len(list1)):
if list1(i) == 1:
newList += [ list2(start) ]
start += 1
if list1(i) == 0
newList += [ list2(end) ]
end -= 1
return newList
# output: [ '-', '-', 'a', 'b', 'c', '-' ]
</code></pre>
| 0 | 2016-07-28T08:39:13Z | [
"python",
"arraylist"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,631,479 | <p>The logic for this program should be as follow:
1. If the current element in list1 is 1, pop the first element from list2
2. If not, pop the last element from list2</p>
<p>Here is a sample code for your reference:</p>
<pre><code>list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ["a","b","c","d","e","f","-","-","-","-"]
outList = []
for index in range(len(list1)):
# If the current value of list1 element is 1, pop from the first
if list1[index] == 1:
outList.append(list2.pop(0))
# If the current value of list1 element is 0, pop from the last
else:
outList.append(list2.pop(-1))
for item in outList:
print(item)
</code></pre>
| 0 | 2016-07-28T08:52:39Z | [
"python",
"arraylist"
] |
Python: concatenate 2 list | 38,630,766 | <p>I have 2 lists in python:</p>
<pre><code>list1 [1,1,0,0,1,1,0,0,1,1]
list2 [a,b,c,d,e,f,-,-,-,-]
</code></pre>
<p>I would like to output the follow:</p>
<p>output</p>
<pre><code>[a,b,-,-,c,d,-,-,e,f]
</code></pre>
<p>I am lost, tried multiple things without any luck.
Anyone have an idea how to do it? Here's my try:</p>
<pre><code>for e in range (0, len(stringas)):
if controllo[e] == "1":
memoria.append(stringas[e])
if controllo[e] == "0":
memoria.append("-")
blocco.append(e)
salva.append(stringas[e])
print (stringas)
print (memoria)
for f in salva:
print (blocco[c])
print (salva[c])
memoria.insert(blocco[c], salva[c])
c = c + 1
</code></pre>
<p>Thank you in advance.</p>
| -2 | 2016-07-28T08:18:50Z | 38,631,778 | <p>I can think of 2 scenarios how the output described comes:</p>
<p>1) If the first list has 0, just add '-'</p>
<pre><code>list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a', 'b', 'c', 'd', 'e', 'f', '-', '-', '-']
index =0
output = []
for element in list1:
if element != 0:
element = list2[index]
index += 1
else:
element = '-'
output.append(element)
</code></pre>
<p>2) If the '0' in list 2 represents element from the end</p>
<pre><code>list1 = [1,1,0,0,1,1,0,0,1,1]
list2 = ['a', 'b', 'c', 'd', 'e', 'f', '-', '-', '-']
list3 = list2[:]
output = []
for element in list1:
if element != 0:
element = list3.pop(0)
else:
element = list3.pop(-1)
output.append(element)
</code></pre>
| 0 | 2016-07-28T09:06:14Z | [
"python",
"arraylist"
] |
PYTHON Is there a way I can get the year difference between two dates? | 38,630,956 | <p>I'm developing a small program for an insurance company to see how old a person is (this changes the ranges of cover we can offer). I can easily calculate the different in the years but it does not take into account the days/months. I there any way of doing this without importing things from elsewhere?</p>
<p>Thanks for the help </p>
| 0 | 2016-07-28T08:28:05Z | 38,631,782 | <p>as you are working with python you <strong>must</strong> use the datetime module. Lets have a look.</p>
<pre><code>from datetime import datetime
bday = '1978/11/21'
dt = datetime.strptime(bday, '%Y/%m/%d')
diff = datetime.now() - dt
diff.days
</code></pre>
<p>Gives you 13764</p>
| 0 | 2016-07-28T09:06:28Z | [
"python",
"date"
] |
Send one file at a time? | 38,630,992 | <p>My python script:</p>
<pre><code>#!/usr/bin/python
import CameraID
import time
import os
image="/tmp/image/frame.png"
count = 1
while (count==1):
# make sure file file exists, else show an error
if ( not os.path.isfile(image)):
print("Error: %s file not found" %image)
else:
print("Sending file %s ..." % image)
print CameraID.run()
print os.remove("/tmp/image/frame.png")
</code></pre>
<p>Does anybody know how to allow the file to be send one at a time with different filename. Once the file is send, it will be removed instantly.</p>
| -1 | 2016-07-28T08:29:38Z | 38,631,149 | <p>maybe can use list to save file, like: image=["/tmp/image/frame.png",""]
then use for x in image:</p>
| 0 | 2016-07-28T08:37:35Z | [
"python",
"python-2.7"
] |
Send one file at a time? | 38,630,992 | <p>My python script:</p>
<pre><code>#!/usr/bin/python
import CameraID
import time
import os
image="/tmp/image/frame.png"
count = 1
while (count==1):
# make sure file file exists, else show an error
if ( not os.path.isfile(image)):
print("Error: %s file not found" %image)
else:
print("Sending file %s ..." % image)
print CameraID.run()
print os.remove("/tmp/image/frame.png")
</code></pre>
<p>Does anybody know how to allow the file to be send one at a time with different filename. Once the file is send, it will be removed instantly.</p>
| -1 | 2016-07-28T08:29:38Z | 38,631,471 | <p>Just make a list of files you want to transfer, then iterate over that list to send the files one by one.</p>
<p>Here a simple function to get the list of files:</p>
<pre><code>def list_of_files(folder, extension):
'''
Return a list of file-paths for each file into a folder with the target extension.
'''
import glob
return glob.glob(str(folder + '*.' + extension))
</code></pre>
<p>in your case it would be:</p>
<pre><code>files = list_of_files('/tmp/image/','png')
for image in files:
if ( not os.path.isfile(image)):
print("Error: %s file not found" %image)
else:
print("Sending file %s ..." % image)
print CameraID.run()
print os.remove(image)
</code></pre>
<p>Without function definition:</p>
<pre><code>import glob
files = glob.glob('/tmp/image/*.png')
for image in files:
if ( not os.path.isfile(image)):
print("Error: %s file not found" %image)
else:
print("Sending file %s ..." % image)
print CameraID.run()
print os.remove(image)
</code></pre>
| 0 | 2016-07-28T08:52:22Z | [
"python",
"python-2.7"
] |
assign values to list of variables in python | 38,631,003 | <p>I have made a small demo of a more complex problem</p>
<pre><code>def f(a):
return tuple([x for x in range(a)])
d = {}
[d['1'],d['2']] = f(2)
print d
# {'1': 0, '2': 1}
# Works
</code></pre>
<p>Now suppose the keys are programmatically generated<br>
How do i achieve the same thing for this case?</p>
<pre><code>n = 10
l = [x for x in range(n)]
[d[x] for x in l] = f(n)
print d
# SyntaxError: can't assign to list comprehension
</code></pre>
| 0 | 2016-07-28T08:30:17Z | 38,631,107 | <p>You can't, it's a syntactical feature of the assignment statement. If you do something dynamic, it'll use different syntax, and thus not work.</p>
<p>If you have some function results <code>f()</code> and a list of keys <code>keys</code>, you can use <code>zip</code> to create an iterable of keys and results, and loop over them:</p>
<pre><code>d = {}
for key, value in zip(keys, f()):
d[key] = value
</code></pre>
<p>That is easily rewritten as a dict comprehension:</p>
<pre><code>d = {key: value for key, value in zip(keys, f())}
</code></pre>
<p>Or, in this specific case as mentioned by @JonClements, even as</p>
<pre><code>d = dict(zip(keys, f()))
</code></pre>
| 1 | 2016-07-28T08:35:17Z | [
"python"
] |
How can i remove overlap in list? | 38,631,355 | <p>I made example python list.</p>
<pre><code>list_1 = [1,3,2,2,3,4,5,1]
print(list_1)
</code></pre>
<blockquote>
<p>[1, 3, 2, 2, 3, 4, 5, 1]</p>
</blockquote>
<p>To remove overlap, i tried to use set().</p>
<pre><code>print(set(list_1))
</code></pre>
<blockquote>
<p>{1, 2, 3, 4, 5}</p>
</blockquote>
<p>but i want make </p>
<pre><code>[1,3,2,4,5]
</code></pre>
<p>I want remove overlap in list, but i also want order not to be changed.</p>
<p>How can i do that?</p>
| 1 | 2016-07-28T08:47:10Z | 38,765,726 | <p>To have distinct values in your list, just use the following snippet:</p>
<pre><code>l = [1,3,2,2,3,4,5,1]
result = list()
map(lambda x: not x in result and result.append(x), l)
print(result) #[1,3,2,4,5]
</code></pre>
<p>As you already found out, <code>set()</code> doesn't preserve the order of your sequence. The basic idea is taken from <a href="http://stackoverflow.com/questions/4459703/how-to-make-lists-distinct">here</a>.</p>
<hr>
<p>As tobias_k mentioned in the comment, this solution won't work with Python 3. If you use Python 3, you may just iterate through your list with a simple for loop (tobias_k's idea) or use libraries like <code>OrderedDict</code>:</p>
<pre><code>from collections import OrderedDict
list(OrderedDict.fromkeys([1,3,2,2,3,4,5,1]))
</code></pre>
| 0 | 2016-08-04T11:10:30Z | [
"python"
] |
How can i remove overlap in list? | 38,631,355 | <p>I made example python list.</p>
<pre><code>list_1 = [1,3,2,2,3,4,5,1]
print(list_1)
</code></pre>
<blockquote>
<p>[1, 3, 2, 2, 3, 4, 5, 1]</p>
</blockquote>
<p>To remove overlap, i tried to use set().</p>
<pre><code>print(set(list_1))
</code></pre>
<blockquote>
<p>{1, 2, 3, 4, 5}</p>
</blockquote>
<p>but i want make </p>
<pre><code>[1,3,2,4,5]
</code></pre>
<p>I want remove overlap in list, but i also want order not to be changed.</p>
<p>How can i do that?</p>
| 1 | 2016-07-28T08:47:10Z | 38,765,825 | <p>You could (ab)use <a href="https://docs.python.org/3/library/collections.html#collections.OrderedDict" rel="nofollow"><code>collections.OrderedDict</code></a> to get just the unique elements in order:</p>
<pre><code>>>> list_1 = [1,3,2,2,3,4,5,1]
>>> from collections import OrderedDict
>>> list(OrderedDict((x, None) for x in list_1))
[1, 3, 2, 4, 5]
</code></pre>
<hr>
<p>Alternatively, you could use a list comprehension with an additional <code>set</code> of already seen items. However, list comprehensions with side-effects are not considered best style.</p>
<pre><code>>>> list_1 = [1,3,2,2,3,4,5,1]
>>> seen = set()
>>> [x for x in list_1 if not (x in seen or seen.add(x))]
[1, 3, 2, 4, 5]
</code></pre>
<p>The condition <code>not (x in seen or seen.add(x))</code> <a href="http://stackoverflow.com/a/38563651/1639625">works like this</a>: If <code>x in seen</code>, the <code>or</code> is true and thus the <code>not</code> is false, but if <code>x not in seen</code>, then the first part of the <code>or</code> is false, and thus the second part is executed and returns <code>None</code>, which is then converted to <code>True</code> by <code>not</code>.</p>
| 1 | 2016-08-04T11:14:46Z | [
"python"
] |
How can i remove overlap in list? | 38,631,355 | <p>I made example python list.</p>
<pre><code>list_1 = [1,3,2,2,3,4,5,1]
print(list_1)
</code></pre>
<blockquote>
<p>[1, 3, 2, 2, 3, 4, 5, 1]</p>
</blockquote>
<p>To remove overlap, i tried to use set().</p>
<pre><code>print(set(list_1))
</code></pre>
<blockquote>
<p>{1, 2, 3, 4, 5}</p>
</blockquote>
<p>but i want make </p>
<pre><code>[1,3,2,4,5]
</code></pre>
<p>I want remove overlap in list, but i also want order not to be changed.</p>
<p>How can i do that?</p>
| 1 | 2016-07-28T08:47:10Z | 38,765,967 | <p>Try This You can do this using reversing a <code>list</code>.without using any python libraries.</p>
<pre><code>>>> list_1 = [1,3,2,2,3,4,5,1]
>>> list_1.reverse()
>>> for i in list_1:
... if(list_1.count(i)>1):
... list_1.remove(i)
...
>>> list_1.reverse()
>>> list_1
[1, 3, 2, 4, 5]
</code></pre>
| 0 | 2016-08-04T11:20:56Z | [
"python"
] |
How can i remove overlap in list? | 38,631,355 | <p>I made example python list.</p>
<pre><code>list_1 = [1,3,2,2,3,4,5,1]
print(list_1)
</code></pre>
<blockquote>
<p>[1, 3, 2, 2, 3, 4, 5, 1]</p>
</blockquote>
<p>To remove overlap, i tried to use set().</p>
<pre><code>print(set(list_1))
</code></pre>
<blockquote>
<p>{1, 2, 3, 4, 5}</p>
</blockquote>
<p>but i want make </p>
<pre><code>[1,3,2,4,5]
</code></pre>
<p>I want remove overlap in list, but i also want order not to be changed.</p>
<p>How can i do that?</p>
| 1 | 2016-07-28T08:47:10Z | 38,767,033 | <p>I would probably do something like this:</p>
<pre><code>seen = set()
result
for i in the_list:
if i not in seen:
seen.add(i)
result.append(i)
</code></pre>
<p>I use <code>seen</code> for fast lookups, still unknown time complexity from the <code>result.append</code> method call.</p>
<p>It's possible to do this as a list comprehension as well, at the cost of mixing functional and imperative code in a horrible mish-mash:</p>
<pre><code>seen = set()
def process(e):
seen.add(e)
return e
[process(element) for element in the_list if element not in seen]
</code></pre>
<p>But! This relies on side-effects in the mapping, so it's less than ideal. </p>
| 0 | 2016-08-04T12:13:52Z | [
"python"
] |
How can i remove overlap in list? | 38,631,355 | <p>I made example python list.</p>
<pre><code>list_1 = [1,3,2,2,3,4,5,1]
print(list_1)
</code></pre>
<blockquote>
<p>[1, 3, 2, 2, 3, 4, 5, 1]</p>
</blockquote>
<p>To remove overlap, i tried to use set().</p>
<pre><code>print(set(list_1))
</code></pre>
<blockquote>
<p>{1, 2, 3, 4, 5}</p>
</blockquote>
<p>but i want make </p>
<pre><code>[1,3,2,4,5]
</code></pre>
<p>I want remove overlap in list, but i also want order not to be changed.</p>
<p>How can i do that?</p>
| 1 | 2016-07-28T08:47:10Z | 38,768,638 | <p>You can use list-comprehension with filter (initialize the empty list first, ignore the resulting list)</p>
<pre><code>list_u = []
[list_u.append(v) for v in list_1 if v not in list_u]
</code></pre>
| 0 | 2016-08-04T13:24:50Z | [
"python"
] |
In Scrapy, How to set time limit for each url? | 38,631,414 | <p>I am trying to crawl multiple websites using Scrapy link extractor and follow as TRUE (recursive) .. Looking for a solution to set the time limit to crawl for each url in start_urls list.</p>
<p>Thanks</p>
<pre><code>import scrapy
class DmozItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
</code></pre>
| 0 | 2016-07-28T08:49:59Z | 38,631,626 | <p>Use a Timeout object!</p>
<pre><code>import signal
class Timeout(object):
"""Timeout class using ALARM signal."""
class TimeoutError(Exception):
pass
def __init__(self, sec):
self.sec = sec
def __enter__(self):
signal.signal(signal.SIGALRM, self.raise_timeout)
signal.alarm(self.sec)
def __exit__(self, *args):
signal.alarm(0)# disable alarm
def raise_timeout(self, *args):
raise Timeout.TimeoutError('TimeoutError')
</code></pre>
<p>Then you can call your extractor inside a with statement like this:</p>
<pre><code>with Timeout(10): #10 seconds
try:
do_what_you_need_to_do
except Timeout.TimeoutError:
#break, continue or whatever else you may need
</code></pre>
| -1 | 2016-07-28T08:59:57Z | [
"python",
"scrapy"
] |
In Scrapy, How to set time limit for each url? | 38,631,414 | <p>I am trying to crawl multiple websites using Scrapy link extractor and follow as TRUE (recursive) .. Looking for a solution to set the time limit to crawl for each url in start_urls list.</p>
<p>Thanks</p>
<pre><code>import scrapy
class DmozItem(scrapy.Item):
title = scrapy.Field()
link = scrapy.Field()
desc = scrapy.Field()
class DmozSpider(scrapy.Spider):
name = "dmoz"
allowed_domains = ["dmoz.org"]
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Python/Books/",
"http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/"
]
def parse(self, response):
for sel in response.xpath('//ul/li'):
item = DmozItem()
item['title'] = sel.xpath('a/text()').extract()
item['link'] = sel.xpath('a/@href').extract()
item['desc'] = sel.xpath('text()').extract()
yield item
</code></pre>
| 0 | 2016-07-28T08:49:59Z | 38,634,075 | <p>You need to use <code>download_timeout</code> meta parameter for <code>scrapy.Request</code>.</p>
<p>To use it in starting urls, you need to overload <code>self.start_requests(self)</code> function, something like:</p>
<pre><code>def start_requests(self):
# 10 seconds for first url
yield Request(self.start_urls[0], meta={'donwload_timeout': 10})
# 60 seconds for first url
yield Request(self.start_urls[1], meta={'donwload_timeout': 60})
</code></pre>
<p>You can read more about Request special meta keys here: <a href="http://doc.scrapy.org/en/latest/topics/request-response.html#request-meta-special-keys" rel="nofollow">http://doc.scrapy.org/en/latest/topics/request-response.html#request-meta-special-keys</a></p>
| 0 | 2016-07-28T10:44:12Z | [
"python",
"scrapy"
] |
Python3: Continuous variable update within Mainframe | 38,631,427 | <p>Basically, I have created a thread which continuously writes a global variable in an infinite loop. Then I have the mainframe which should read and display that variable.</p>
<p>The problem is that once the mainframe runs, it only displays the value of the variable which it read at the time of startup, and does not continuously update itself. How do I get the mainframe to update it's variable values with a specified interval?</p>
<p>The variable in question is called "data":</p>
<p>Notes: if you run the code as is, the "data" variable will be set to none. Adding a "time.sleep(5)" before executing mainframe will allow time to set the variable from the http request, and you will see the data populated.</p>
<p>Thanks for the help!</p>
<pre><code>#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import time
import urllib.request
from bs4 import BeautifulSoup
import threading
from queue import Queue
data = None
class httpReq(threading.Thread):
def run(self):
global data
while True:
url = "https://twitter.com/realDonaldTrump"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, "html.parser")
data = soup.title.text
print(data)
x = httpReq()
x.start()
class Example(Frame):
global data
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Example App")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
lbl1 = Label(frame1, text="Title Data:", width= 20)
lbl1.pack(side=LEFT, padx=5, pady=5)
lbl2 = Label(frame1, text= data)
lbl2.pack(fill=X, padx=5, expand=True)
def main():
root = Tk()
root.geometry("600x200")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
</code></pre>
| 0 | 2016-07-28T08:50:39Z | 38,636,370 | <p>Save a reference to the label, and then set up a function that updates the label and then arranges for itself to be called again. In the following example the label will be updated once a second.</p>
<pre><code>class Example(Frame):
def __init__(self, parent):
...
# call this once, after the UI has been initialized
self.update_data()
...
def initUI(self):
...
# save a reference to the label that shows the data
self.lbl2 = Label(frame1, text= data)
self.lbl2.pack(fill=X, padx=5, expand=True)
...
def update_data(self):
# reset the label
self.lbl2.configure(text=data)
# call this function again in one second
self.lbl2.after(1000, self.update_data)
</code></pre>
| 0 | 2016-07-28T12:28:01Z | [
"python",
"multithreading",
"python-3.x",
"tkinter"
] |
Using $* as part of a parameter for os.system in python | 38,631,461 | <p>The command:</p>
<pre><code>make foo -f $*
</code></pre>
<p>Has different functionality when called from the command line versus when it is called from a python script as follows:</p>
<pre><code>import os
os.system(make foo -f $*)
</code></pre>
<p>As stated here: <a href="http://tldp.org/LDP/abs/html/internalvariables.html#APPREF" rel="nofollow">http://tldp.org/LDP/abs/html/internalvariables.html#APPREF</a>
$* in a bat file is basically all the positional parameters seen as a single word. </p>
<p>Python seems to be parsing it as simply "$*". Is there anyway to get around this and replicate the same functionality? </p>
<p>I realise I can write a .bat script and call that with python but I was hoping for something more eloquent. </p>
| 0 | 2016-07-28T08:52:02Z | 38,631,763 | <p>As you point out, $* has no special meaning in python. The comprehension is done entirely by whatever shell you are using. If you want to pass all positional parameters passed to your script to some command, then you can try the following</p>
<pre><code>import os, sys
os.system("make foo -f {}".format(" ".join(sys.argv[1:])))
</code></pre>
<p>Please note however that <code>os.system</code> is deprecated. You should probably use </p>
<pre><code>import subprocess, sys
subprocess.check_call("make foo -f {}".format(" ".join(sys.argv[1:])), shell=True)
</code></pre>
<p>instead.</p>
<p><strong>Edit</strong></p>
<p>As suggested in the comments, one should avoid using <code>shell=True</code> whenever the command is built from "untrusted" input, such as the command line of the program. Therefore a much better alternative is to use</p>
<pre><code>import subprocess, sys
subprocess.check_call(['make', 'foo', '-f'] + sys.argv[1:])
</code></pre>
| 1 | 2016-07-28T09:05:46Z | [
"python",
"os.system"
] |
Python NameError: name 'encrypt' is not defined | 38,631,474 | <p>When I attempt to run this it says NameError: name 'encrypt' is not defined.</p>
<pre><code>MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = input().lower()
if mode in "encrypt" 'e' 'decrypt' 'd'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
</code></pre>
| 0 | 2016-07-28T08:52:31Z | 38,631,641 | <p>From what I understand of your code, 'encrypt' is a string value. You need to create a list with your required string values and check whether the mode variable matches with a value in that list.</p>
<pre><code>MAX_KEY_SIZE=26
def getMode():
while True:
mode=input().lower()
if mode in ['encrypt','e','decrypt','d']:
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
</code></pre>
<p>If you want to use the .split() method, you could do the following:</p>
<pre><code>if mode in "encrypt e decrypt d".split()
</code></pre>
| 2 | 2016-07-28T09:00:47Z | [
"python",
"nameerror"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.