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
numpy log with numpy arrays
38,444,245
<p>I´d like to understand why the following code:</p> <pre><code>print((hypothesis(x, theta_))) </code></pre> <p>results in a array with this format</p> <pre><code>[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ...
2
2016-07-18T19:08:41Z
38,444,318
<p>Presumably <code>hypothesis(x, theta_)</code> returns a python <em>list</em>. When you print a list, the commas are included.</p> <p><code>np.log(hypothesis(x, theta_))</code> returns a numpy array. When you print a numpy array, the commas are not included.</p> <p>For example:</p> <pre><code>In [1]: x = [1, 2, ...
2
2016-07-18T19:13:27Z
[ "python", "arrays", "numpy", "logging" ]
Adding columns of different index
38,444,271
<p>I know this adds consecutive columns of same index:</p> <p><code>df['C'] = df['A'] + df['B']</code></p> <p>But how to add columns of different index: </p> <p>Lets say I have a dataframe like this:</p> <pre><code>df A B 0 9 40 1 1 70 2 5 80 3 8 30 4 7 50 </code></pre> <p>I need to cre...
2
2016-07-18T19:10:04Z
38,444,307
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html"><code>Series.shift</code></a>.</p> <pre><code>df['C'] = df['A'] + df['B'].shift(1).fillna(0) </code></pre>
5
2016-07-18T19:12:33Z
[ "python", "pandas" ]
Adding columns of different index
38,444,271
<p>I know this adds consecutive columns of same index:</p> <p><code>df['C'] = df['A'] + df['B']</code></p> <p>But how to add columns of different index: </p> <p>Lets say I have a dataframe like this:</p> <pre><code>df A B 0 9 40 1 1 70 2 5 80 3 8 30 4 7 50 </code></pre> <p>I need to cre...
2
2016-07-18T19:10:04Z
38,444,312
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>shift</code></a>:</p> <pre><code>df['C'] = df.A + df.B.shift().fillna(0) </code></pre>
0
2016-07-18T19:12:56Z
[ "python", "pandas" ]
Adding columns of different index
38,444,271
<p>I know this adds consecutive columns of same index:</p> <p><code>df['C'] = df['A'] + df['B']</code></p> <p>But how to add columns of different index: </p> <p>Lets say I have a dataframe like this:</p> <pre><code>df A B 0 9 40 1 1 70 2 5 80 3 8 30 4 7 50 </code></pre> <p>I need to cre...
2
2016-07-18T19:10:04Z
38,444,333
<p>Amother solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.add.html" rel="nofollow"><code>Series.add</code></a>:</p> <pre><code>df['C'] = df['A'].add(df['B'].shift(), fill_value=0) print (df) A B C 0 9 40 9.0 1 1 70 41.0 2 5 80 75.0 3 8 30 88.0 4 7 50 ...
1
2016-07-18T19:14:19Z
[ "python", "pandas" ]
Trouble with adding Scrollbar to Canvas in Tkinter
38,444,299
<p>I'm attempting to add a scrollbar widget to the Canvas in my program. The program is a basically a table made by adding a Canvas to the master and then adding Frames to the Canvas using .grid(). I've included the relevant portions of code. I'm not sure what it is that I'm doing incorrectly.</p> <pre><code>from Tkin...
-1
2016-07-18T19:11:58Z
38,444,514
<p>I just added <code>side=LEFT</code> when I packed the canvas and the scrollbar is now on the right of the canvas instead of below. It is because the default side for pack is <code>TOP</code>.</p> <pre><code>from Tkinter import * master = Tk() canvas = Canvas(master) canvas.pack(side=LEFT) vbar = Scrollbar(maste...
0
2016-07-18T19:26:50Z
[ "python", "canvas", "tkinter", "scrollbar", "tkinter-canvas" ]
Python List of Dictionaries Only See Last Element
38,444,344
<p>Struggling to figure out why this doesn't work. It should. But when I create a list of dictionaries and then look through that list, I only ever see the final entry from the list:</p> <pre><code>alerts = [] alertDict = {} af=open("C:\snort.txt") for line in af: m = re.match(r'([0-9/]+)-([0-9:.]+)\s+.*?(\d{1,3}...
0
2016-07-18T19:14:56Z
38,444,367
<p>You create exactly one dict at the beginning of the script, and then append that one dict to the list multiple times.</p> <p>Try creating multiple individual dicts, by moving the initialization to the inside of the loop.</p> <pre><code>alerts = [] af=open("C:\snort.txt") for line in af: alertDict = {} #re...
4
2016-07-18T19:17:08Z
[ "python", "list", "dictionary", "elements" ]
How do I find quotes in strings - Python
38,444,389
<p>Let's say I have a String variable</p> <pre><code>temp = 'I need to "leave" this place' </code></pre> <p>How would I be able to use temp.index() to find where the quotes("") begin and end?</p>
0
2016-07-18T19:18:38Z
38,444,540
<p>I would use the <a href="http://www.tutorialspoint.com/python/string_find.htm" rel="nofollow">find</a> method.</p> <pre><code>start_pt = temp.find("\"") end_pt = temp.find("\"", start + 1) # add one to skip the opening " quote = temp[start_pt + 1: end_pt + 1] # add one to get the quote excluding the "" &gt;&gt;&...
0
2016-07-18T19:28:20Z
[ "python", "string", "indexing", "quotes" ]
How do I find quotes in strings - Python
38,444,389
<p>Let's say I have a String variable</p> <pre><code>temp = 'I need to "leave" this place' </code></pre> <p>How would I be able to use temp.index() to find where the quotes("") begin and end?</p>
0
2016-07-18T19:18:38Z
38,444,653
<p>Note: As said in the other answer, I would advise you to use the <code>find(substring)</code> function. To my knowledge both <code>index</code> and <code>find</code> work equally well, but if you use <code>index(substring)</code>, you will have to handle the possible <code>ValueError</code> exception if <code>substr...
0
2016-07-18T19:35:25Z
[ "python", "string", "indexing", "quotes" ]
kivy python flashing text
38,444,408
<p>I would like to display flashing text (every 1 sec.) in my kivy app. I have searched through google but can not find any examples / information about it.</p> <p>is it possible to do flashing text (label) in kivy at all?</p> <p>EDIT:</p> <p>The way I have done it is that I call a Clock to call a specific function ...
2
2016-07-18T19:19:53Z
38,444,584
<p>I would do this with an animation. Basically like that, with widget holding your text:</p> <pre><code>anim = Animation(alpha=0, duration=0.1) + Animation(alpha=0, duration=1) anim += Animation(alpha=1, duration=0.1) + Animation(alpha=1, duration=1) anim.repeat = True anim.start(widget) </code></pre> <p>It will qu...
4
2016-07-18T19:31:14Z
[ "python", "label", "kivy" ]
Iterating with lambda and map python
38,444,420
<p>Here is my code:</p> <pre><code>map(lambda i: 3*i, map(lambda x: x, [[1, 2],[3, 4]])) </code></pre> <p>It outputs: <code>[[1, 2, 1, 2, 1, 2], [3, 4, 3, 4, 3, 4]]</code></p> <p>How do I modify it to print <code>3, 6, 9, 12</code>?</p> <p>I do not want to use append. Just map and lambda.</p>
0
2016-07-18T19:20:50Z
38,444,468
<p>The problem you observe arises from the fact that the inner <code>map</code> returns a sequence of lists, not a sequence of numbers. This is because that <code>map</code> is iterating over a list containing smaller lists. So, if you use <code>itertools.chain.from_iterable</code> to flatten that list, you'll get a se...
2
2016-07-18T19:24:08Z
[ "python", "lambda" ]
Iterating with lambda and map python
38,444,420
<p>Here is my code:</p> <pre><code>map(lambda i: 3*i, map(lambda x: x, [[1, 2],[3, 4]])) </code></pre> <p>It outputs: <code>[[1, 2, 1, 2, 1, 2], [3, 4, 3, 4, 3, 4]]</code></p> <p>How do I modify it to print <code>3, 6, 9, 12</code>?</p> <p>I do not want to use append. Just map and lambda.</p>
0
2016-07-18T19:20:50Z
38,446,067
<p>Your code didn't work as expected because in Python the <code>*</code> operator is polymorphic. Thus if <code>x</code> and <code>n</code> are numbers, <code>x*n</code> returns the product of both numbers, but if one of the operands (say <code>n</code>) is an integer and the other is a sequence (.e. <code>x</code> is...
1
2016-07-18T21:12:18Z
[ "python", "lambda" ]
Get tag's attribute if tag exists; otherwise None
38,444,456
<p>I have a <code>td</code> tag in BeautifulSoup 4. There may be an <code>a</code> tag inside it:</p> <pre><code>row.find_all('td')[2].find('a') </code></pre> <p>If there is, I want to retrieve the <code>a</code> tag's <code>href</code> attribute. Otherwise, I'd like <code>None</code>.</p> <p>This is what I've thoug...
0
2016-07-18T19:23:23Z
38,444,727
<p>You can select the second tr and any anchor inside then check using an if:</p> <pre><code>a = soup.select_one("tr:nth-of-type(2) a[href]") if a: print(a["href"]) </code></pre> <p>If there is no anchor a will be None, if there is you can just extract the href.</p>
1
2016-07-18T19:40:06Z
[ "python", "beautifulsoup" ]
Simple way of reading a two dimensional array into Python
38,444,465
<p>The output of one of my programs is a two-dimensional array, e.g.</p> <pre><code>[[1,2,3],[4,5,6,7],[8,9]] </code></pre> <p>of indeterminate length. I write this output as a single line to a file geno_matrix, which I then need to read into another program for analysis and processing. I need to read this into the o...
1
2016-07-18T19:23:59Z
38,444,536
<p>You can use <code>ast</code>'s <code>literal_eval</code> function:</p> <pre><code>from ast import literal_eval literal_eval('[[1,2,3], [4,5,6,7], [8,9]]') </code></pre> <p>will give you <code>[[1,2,3], [4,5,6,7], [8,9]]</code> as an array.</p>
2
2016-07-18T19:28:10Z
[ "python" ]
Simple way of reading a two dimensional array into Python
38,444,465
<p>The output of one of my programs is a two-dimensional array, e.g.</p> <pre><code>[[1,2,3],[4,5,6,7],[8,9]] </code></pre> <p>of indeterminate length. I write this output as a single line to a file geno_matrix, which I then need to read into another program for analysis and processing. I need to read this into the o...
1
2016-07-18T19:23:59Z
38,444,579
<p>Doing this gives you a list of strings, each string representing a vector:</p> <pre><code>"[[1,2,3],[4,5,6,7],[8,9]]".lstrip('[[').rstrip(']]').split(r'],[') </code></pre> <p>as so: </p> <pre><code>['1,2,3', '4,5,6,7', '8,9'] </code></pre> <p>You can then split individual strings to lists.</p>
0
2016-07-18T19:31:01Z
[ "python" ]
How to prevent Pandas from converting my integers to floats when I merge two dataFrames?
38,444,480
<p>Here is my code:</p> <pre><code>import pandas as pd left = pd.DataFrame({'AID': [1, 2, 3, 4], 'D': [2011, 2011,0, 2011], 'R1': [0, 1, 0, 0], 'R2': [1, 0, 0, 0] }) right = pd.DataFrame({'AID': [1, 2, 3, 4], 'D': [2012, 0,0,...
5
2016-07-18T19:24:48Z
38,444,906
<p>I'd track what the <code>dtypes</code> were for <code>left</code> and <code>right</code></p> <pre><code>dtypes = left.dtypes.combine_first(right.dtypes) </code></pre> <p>Then I'd reconstruct <code>results</code> accordingly.</p> <pre><code>results = pd.DataFrame({k: v.astype(dtypes.loc[k]) for k, v in results.ite...
1
2016-07-18T19:50:35Z
[ "python", "pandas" ]
Generating documentation for python script with Doxygen
38,444,484
<p>I'm trying to create some documentation for some Python scripts included in my project (the rest is Fortran/C). I managed to include a brief and a detailed description for the files, but all the variables defined in the script are being listed in the documentation.</p> <p>How do I avoid them from being listed? Whic...
2
2016-07-18T19:24:58Z
38,445,854
<p>I had this similar problem while working with python-Doxygen. What worked for me is to enclose your variables between \cond and \endcond.</p> <p>For example,</p> <pre><code>## \cond some_var = "abc" ## \endcond </code></pre> <p>They won't show up in your documentation :)</p>
2
2016-07-18T20:56:29Z
[ "python", "doxygen" ]
Sympy step by step solutions
38,444,491
<p>Sympygamma offers step by step solutions for example for derivatives like this one: <a href="http://www.sympygamma.com/input/?i=diff%28log%28x%29%20%2B%202*x**2%2Cx%29" rel="nofollow">http://www.sympygamma.com/input/?i=diff%28log%28x%29+%2B+2*x**2%2Cx%29</a></p> <p>How can I use this directly with sympy (e.g. in an...
1
2016-07-18T19:25:21Z
38,445,170
<p>I just found out, that this is not a functionality provided by sympy itself but special to sympygamma. </p> <p>Here is the code: <a href="https://github.com/sympy/sympy_gamma/blob/master/app/logic/diffsteps.py" rel="nofollow">https://github.com/sympy/sympy_gamma/blob/master/app/logic/diffsteps.py</a></p>
1
2016-07-18T20:08:00Z
[ "python", "sympy" ]
User doesn't have permission to use os.chmod( )
38,444,610
<p>I am trying to open a new file and immediately give it full system read/write/execute permissions. I am doing this like so:</p> <pre><code>csvout = open("/Users/me/Google Drive/documentation/report.csv","w") os.chmod("/Users/me/Google Drive/documentation/report.csv", 0o777) </code></pre> <p>This command works for ...
0
2016-07-18T19:32:46Z
38,445,664
<p>Only the owner of a file (or the superuser) is allowed to change its permissions. When the second user runs the script, they aren't the owner (the first user is), so they get an error.</p> <p>The first user to run the script will create the file, and then give it <code>777</code> permissions, which allows anyone to...
0
2016-07-18T20:42:20Z
[ "python", "file-permissions" ]
Read user input numbers and perform a calculation in Python
38,444,658
<p>please help me... "Read in two numbers from user input without a prompt, add them, and print the result. Hint: Use int() to convert the numbers to integers. </p> <p>Note: These activities may test code with different test values. This activity will perform two tests: the first with num1 = 5 and num2 = 10, the sec...
1
2016-07-18T19:35:44Z
38,444,694
<p>The argument to the input() function is the string to display as a prompt.</p> <p>In your case, you'd want that to be simply input().</p>
4
2016-07-18T19:38:15Z
[ "python" ]
Read user input numbers and perform a calculation in Python
38,444,658
<p>please help me... "Read in two numbers from user input without a prompt, add them, and print the result. Hint: Use int() to convert the numbers to integers. </p> <p>Note: These activities may test code with different test values. This activity will perform two tests: the first with num1 = 5 and num2 = 10, the sec...
1
2016-07-18T19:35:44Z
38,444,731
<p>Don't pass parameters into <code>input</code>. You're asking the <em>user</em> for input.</p> <p>I don't think the assignment is asking you to write your own tests. I think it's saying that whatever code you give it will be tested.</p>
0
2016-07-18T19:40:15Z
[ "python" ]
Read user input numbers and perform a calculation in Python
38,444,658
<p>please help me... "Read in two numbers from user input without a prompt, add them, and print the result. Hint: Use int() to convert the numbers to integers. </p> <p>Note: These activities may test code with different test values. This activity will perform two tests: the first with num1 = 5 and num2 = 10, the sec...
1
2016-07-18T19:35:44Z
38,444,766
<p>in fact you need just:</p> <pre><code>num1 = int(input()) num2 = int(input()) num3 = num1+num2 print(num3) </code></pre>
0
2016-07-18T19:42:23Z
[ "python" ]
Is there a size limit for Pandas read_table()?
38,444,676
<p>Let's say I have a <code>.dat</code> file, <code>filename.dat</code>, and I wish to read this into a Pandas Dataframe:</p> <pre><code>import pandas as pd df = pd.read_table('filename.dat') </code></pre> <p>Is there a size limit regarding this? I was hoping to save the columns of a dataframe individually for a file...
1
2016-07-18T19:37:02Z
38,445,308
<p>To expand on the usage of <code>chunksize</code> mentioned in the comments, I'd do something like the following:</p> <pre><code>chunks = pd.read_table('filename.dat', chunksize=10**5) fileout = 'filname_{}.dat' for i, chunk in enumerate(chunks): mode = 'w' if i == 0 else 'a' header = i == 0 for col in c...
1
2016-07-18T20:17:26Z
[ "python", "pandas", "dataframe" ]
Convert several separate lists to integers and get sum
38,444,679
<p>I need to take elements produced by a list, convert them to integers, then get their sum. I would like to do this using a basic for loop to convert the lists to integers, but can't figure out how to write the code to convert the lists into integers. The data that comes out of my code so far looks like this:</p> <pr...
-1
2016-07-18T19:37:08Z
38,444,794
<p>You don't really need to use regex for this problem, you can make numbers from strings of numbers easily!</p> <pre><code>string_list = ['8370', '1014', '4870'] number_list = [int(x) for x in string_list] # using list comprehension sum(number_list) # 14254 </code></pre> <p>If you are reading it in from a file, you...
2
2016-07-18T19:43:45Z
[ "python", "regex", "list", "integer" ]
regarding loading the npy file and investigating the contents inside it
38,444,712
<p>I have been trying to output the contents of npy file, when <code>print(np.load('/home/ugwz/fcn/vgg16.npy', encoding='latin1'))</code>, part of the output looks like as follows, which is sort of hard to read. </p> <p><a href="http://i.stack.imgur.com/F7i1v.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/F7i1...
0
2016-07-18T19:39:11Z
38,447,394
<p>Based on the end of your screen shot</p> <pre><code>....], dtype=float)]} </code></pre> <p>I'd expect the start to be <code>{akey: [array(....</code>. In other words, a dictionary (one or more items), a list (of at least one item), and 1d array.</p> <p>Though your size, shape, ndim values indicate that this is a...
1
2016-07-18T23:27:21Z
[ "python", "numpy" ]
How to get log rate of change between rows in Pandas DataFrame effectively?
38,444,734
<p>Let's say I have some DataFrame (<em>with about 10000 rows in my case, this is just a minimal example</em>)</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; sample_df = pd.DataFrame( {'col1': list(range(1, 10)), 'col2': list(range(10, 19))}) &gt;&gt;&gt; sample_df col1 col2 0 1 10 ...
4
2016-07-18T19:40:28Z
38,444,928
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html" rel="nofollow">shift</a> for that, which does what you have proposed.</p> <pre><code>&gt;&gt;&gt; sample_df['col1'].shift() 0 NaN 1 1.0 2 2.0 3 3.0 4 4.0 5 5.0 6 6.0 7 7.0 8 8.0 Name: c...
1
2016-07-18T19:52:02Z
[ "python", "numpy", "pandas", "dataframe", "series" ]
How to get log rate of change between rows in Pandas DataFrame effectively?
38,444,734
<p>Let's say I have some DataFrame (<em>with about 10000 rows in my case, this is just a minimal example</em>)</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; sample_df = pd.DataFrame( {'col1': list(range(1, 10)), 'col2': list(range(10, 19))}) &gt;&gt;&gt; sample_df col1 col2 0 1 10 ...
4
2016-07-18T19:40:28Z
38,444,980
<p>just use np.log:</p> <pre><code>np.log(df.col1 / df.col1.shift()) </code></pre> <p>you can also use apply as suggested by @nikita but that will be slower. </p> <p>in addition, if you wanted to do it for the entire dataframe, you could just do:</p> <pre><code>np.log(df / df.shift()) </code></pre>
4
2016-07-18T19:55:20Z
[ "python", "numpy", "pandas", "dataframe", "series" ]
How to get log rate of change between rows in Pandas DataFrame effectively?
38,444,734
<p>Let's say I have some DataFrame (<em>with about 10000 rows in my case, this is just a minimal example</em>)</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; sample_df = pd.DataFrame( {'col1': list(range(1, 10)), 'col2': list(range(10, 19))}) &gt;&gt;&gt; sample_df col1 col2 0 1 10 ...
4
2016-07-18T19:40:28Z
38,445,027
<p>IIUC:</p> <p>log of a ratio is the difference of logs:</p> <pre><code>sample_df.apply(np.log).diff() </code></pre> <p>Or better still:</p> <pre><code>np.log(sample_df).diff() </code></pre> <p><a href="http://i.stack.imgur.com/xbnbC.png" rel="nofollow"><img src="http://i.stack.imgur.com/xbnbC.png" alt="enter ima...
4
2016-07-18T19:58:28Z
[ "python", "numpy", "pandas", "dataframe", "series" ]
How do I convert a table in notepad into CSV format?
38,444,755
<p>I have this table of data in Notepad </p> <p><a href="http://i.stack.imgur.com/yf0g3.png" rel="nofollow"><img src="http://i.stack.imgur.com/yf0g3.png" alt="enter image description here"></a></p> <p>But it's not really a table because there aren't like official columns. It's just looks like a table, but the data is...
0
2016-07-18T19:41:44Z
38,445,056
<p>Here is a hackjob python script to do exactly what you need. Just save the script as a python file and run it with the path of your input file as the only argument.</p> <p>UPDATED: After reading the comments to my answer, my script now uses regular expressions to account for any number of spaces.</p> <pre><code>im...
1
2016-07-18T20:00:19Z
[ "python", "csv" ]
How do I convert a table in notepad into CSV format?
38,444,755
<p>I have this table of data in Notepad </p> <p><a href="http://i.stack.imgur.com/yf0g3.png" rel="nofollow"><img src="http://i.stack.imgur.com/yf0g3.png" alt="enter image description here"></a></p> <p>But it's not really a table because there aren't like official columns. It's just looks like a table, but the data is...
0
2016-07-18T19:41:44Z
38,447,769
<p>So this is put into a file (if you call it csvify.py) and executed as:</p> <blockquote> <p><code>python csvify.py &lt;input_file_name&gt;</code></p> </blockquote> <h3>csvify.py:</h3> <pre><code>from sys import argv from re import finditer #Method that returns fields separated by commas def comma_delimit(line, ...
0
2016-07-19T00:19:26Z
[ "python", "csv" ]
dask.async.MemoryError while running big data computation on EC2
38,444,777
<p>I have a m4.4xlarge (64 GB ram) EC2 box. I'm running dask with pandas. I get the following memory error. </p> <p>I get this after about 24 hours of run, which is approximiately the time it should take for the task to complete so I'm not sure if the error was due to insufficient RAM, disk memory as the end of the sc...
1
2016-07-18T19:42:45Z
38,445,612
<h3>Single threaded execution</h3> <p>Sometimes tasks build up in RAM while waiting to write to a <em>single file</em> on disk. Using a sequential output like this is inherently tricky with parallel systems. If you <em>need</em> to use a single file then I recommend trying the same computation single threaded to see...
1
2016-07-18T20:37:53Z
[ "python", "pandas", "memory", "dask" ]
Selenium Python, Find element Input box problems
38,444,857
<p>I'm trying to automate some processes at work on our inventory site and I'm having trouble inputing text into a simple search box!</p> <p>Here is the website code:</p> <pre><code>&lt;td class="GJCH5BMASD" style=""&gt; &lt;input type="text" class="GJCH5BMD1C GJCH5BME1C" style="font-size: 13px; width: 100%;"&...
-1
2016-07-18T19:47:59Z
38,444,929
<p>Well nevermind!</p> <p>I fixed it by changing:</p> <pre><code>opens = driver.find_element_by_css_selector(".GJCH5BMD1C GJCH5BME1C").click() </code></pre> <p>to:</p> <pre><code>opens = driver.find_element_by_css_selector(".GJCH5BMASD").click() </code></pre>
0
2016-07-18T19:52:05Z
[ "python", "selenium" ]
Selenium Python, Find element Input box problems
38,444,857
<p>I'm trying to automate some processes at work on our inventory site and I'm having trouble inputing text into a simple search box!</p> <p>Here is the website code:</p> <pre><code>&lt;td class="GJCH5BMASD" style=""&gt; &lt;input type="text" class="GJCH5BMD1C GJCH5BME1C" style="font-size: 13px; width: 100%;"&...
-1
2016-07-18T19:47:59Z
38,448,003
<p>You need to provide <code>.</code> with every class name using <code>css_selector</code>, you can also try as below :-</p> <pre><code>opens = driver.find_element_by_css_selector(".GJCH5BMD1C.GJCH5BME1C").click() </code></pre>
0
2016-07-19T00:55:05Z
[ "python", "selenium" ]
get data from django form and print in console
38,444,874
<p>I am new to Django and what I want to do is quite simple, but I am confused:</p> <p>I want to create a Django form (simple form not ModelForm) and write a function which takes data from this form like username and password(which user types in front-end) and print it in console.</p> <p>i have tried adding a form to...
0
2016-07-18T19:48:36Z
38,446,402
<p>You should create a view that extends <code>FormView</code>:</p> <pre><code>from myapp.forms import YourForm from django.views.generic.edit import FormView class YourView(FormView): template_name = 'template.html' form_class = YourForm success_url = '/thanks/' def form_valid(self, form): print...
0
2016-07-18T21:38:04Z
[ "python", "django", "forms" ]
How to shift down columns row and re-assign column values in Pandas Dataframe?
38,444,884
<p>I have the following pandas DataFrame:</p> <pre><code>import pandas as pd import numpy as np data = 'filename.dat' df = pd.read_table(data) print(df) 0.098722 08l23252 243434214 5 True 0 0.469112 -0.282863 -1.509059 2 True 1 0.283421 1.224234 7.823421 2 False 2 -1.135632 1.21211...
0
2016-07-18T19:49:22Z
38,444,901
<p>Add parameter <code>names</code>:</p> <pre><code>df = pd.read_table(datan, names=['A1', 'B1', 'C1', 'D1', 'E1']) </code></pre> <p>But it looks like better id use <code>read_csv</code>:</p> <pre><code>import pandas as pd import io temp=u""" 9,40 1,70""" #after testing replace io.StringIO(temp) to filename df = ...
2
2016-07-18T19:50:23Z
[ "python", "pandas", "dataframe" ]
How to shift down columns row and re-assign column values in Pandas Dataframe?
38,444,884
<p>I have the following pandas DataFrame:</p> <pre><code>import pandas as pd import numpy as np data = 'filename.dat' df = pd.read_table(data) print(df) 0.098722 08l23252 243434214 5 True 0 0.469112 -0.282863 -1.509059 2 True 1 0.283421 1.224234 7.823421 2 False 2 -1.135632 1.21211...
0
2016-07-18T19:49:22Z
38,444,905
<p>try this:</p> <pre><code>df = pd.read_table(data, names=['A1', 'B1', 'C1', 'D1', 'E1'], header=None) </code></pre> <p>from <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow">docs</a>:</p> <blockquote> <p><strong>names</strong> : array-like, default None</p> ...
3
2016-07-18T19:50:35Z
[ "python", "pandas", "dataframe" ]
Conversion of numbers from one form (string) to other
38,444,915
<p>I have a data frame "df" with a column "Amount", which contains values in millions like 2.3, 17, 1.47 and so on. I want to create a new column "Amount1" in "df" which converts each value in "Amount" to the form like 2300000, 17000000, 1470000 and so on. How would I accomplish this task? The below code throws the err...
-3
2016-07-18T19:51:22Z
38,444,939
<p>Try:</p> <pre><code>df['Amount1'] = pd.to_numeric(df.Amount, errors='coerce') * 1000000 </code></pre>
2
2016-07-18T19:52:50Z
[ "python", "pandas" ]
Conversion of numbers from one form (string) to other
38,444,915
<p>I have a data frame "df" with a column "Amount", which contains values in millions like 2.3, 17, 1.47 and so on. I want to create a new column "Amount1" in "df" which converts each value in "Amount" to the form like 2300000, 17000000, 1470000 and so on. How would I accomplish this task? The below code throws the err...
-3
2016-07-18T19:51:22Z
38,445,114
<p>You can convert to <code>float</code> first by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>Series.astype</code></a>:</p> <pre><code>df['Amount1'] = df.Amount.astype(float) * 1000000 </code></pre> <p>If it doesnt work, use another <a href="http://st...
2
2016-07-18T20:04:38Z
[ "python", "pandas" ]
PyQt MainWindow background is not resizing
38,444,960
<p>Here is the code that I am using:</p> <pre><code>palette = QtGui.QPalette() myPixmap = QtGui.QPixmap('test1.jpg') myScaledPixmap = myPixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio, transformMode = QtCore.Qt.SmoothTransformation) palette.setBrush(QtGui.QPalette.Window, myScaledPixmap) self.setPalette(palette) ...
0
2016-07-18T19:54:08Z
38,464,218
<p>This line:</p> <pre><code>palette.setBrush(QtGui.QPalette.Window, myScaledPixmap) </code></pre> <p>Should be like this:</p> <pre><code>palette.setBrush(QtGui.QPalette.Window, QtGui.QBrush(myScaledPixmap)) </code></pre> <p>If you look at the docs <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qpalette.html#setBr...
1
2016-07-19T16:46:52Z
[ "python", "pyqt", "pyqt4", "pyside" ]
Fast Fibonacci computation
38,445,069
<p>I saw a comment on Google+ a few weeks ago in which someone demonstrated a straight-forward computation of Fibonacci numbers which was not based on recursion and didn't use memoization. He effectively just remembered the last 2 numbers and kept adding them. This is an O(n) algorithm, but he implemented it very cle...
3
2016-07-18T20:01:19Z
38,445,260
<p>From <a href="https://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding" rel="nofollow">Wikipedia</a>,</p> <p>For all n ≥ 0, the number Fn is the closest integer to phi^n/sqrt(5) where phi is the golden ratio. Therefore, it can be found by rounding, that is by the use of the nearest integer function<...
0
2016-07-18T20:13:51Z
[ "python", "algorithm", "performance", "fibonacci" ]
Fast Fibonacci computation
38,445,069
<p>I saw a comment on Google+ a few weeks ago in which someone demonstrated a straight-forward computation of Fibonacci numbers which was not based on recursion and didn't use memoization. He effectively just remembered the last 2 numbers and kept adding them. This is an O(n) algorithm, but he implemented it very cle...
3
2016-07-18T20:01:19Z
38,445,336
<p>Since Fibonacci sequence is a linear recurrence, its members can be evaluated in closed form. This involves computing a power, which can be done in O(logn) similarly to the matrix-multiplication solution, but the constant overhead should be lower. That's the fastest algorithm I know. </p> <p><a href="http://i.stack...
4
2016-07-18T20:19:17Z
[ "python", "algorithm", "performance", "fibonacci" ]
Fast Fibonacci computation
38,445,069
<p>I saw a comment on Google+ a few weeks ago in which someone demonstrated a straight-forward computation of Fibonacci numbers which was not based on recursion and didn't use memoization. He effectively just remembered the last 2 numbers and kept adding them. This is an O(n) algorithm, but he implemented it very cle...
3
2016-07-18T20:01:19Z
38,498,286
<p>This is too long for a comment, so I'll leave an answer.</p> <p>The answer by <a href="http://stackoverflow.com/users/3220135/aaron">Aaron</a> is correct, and I've upvoted it, as should you. I will provide the same answer, and explain <em>why</em> it is not only correct, but the best answer posted so far. <a href...
0
2016-07-21T07:56:31Z
[ "python", "algorithm", "performance", "fibonacci" ]
Could I use python to create a chrome extension?
38,445,106
<p>I would be interested in creating a roulette bot that could automatically follow a set of instructions to create a profit. The technique I would like for the bot to use would be - bet on red for y amount, if red, bet on red again for 1y, if green, bet on red for 2y dollars, if red, if green, bet on red for 4y dollar...
-3
2016-07-18T20:03:20Z
38,445,136
<p>Chrome and other browser extensiosn are usually written in Javascript. So, you can't use "Python"'s classic runtimes such as CPython or Pypy, but you can make use of one or other project that "transpiles" Python to Javascript.</p> <p>One such project is <a href="http://brython.info" rel="nofollow">Brython</a>, whic...
0
2016-07-18T20:05:55Z
[ "python", "google-chrome", "gambling" ]
Creating dictionary from CSV file, dictionary not containing all values
38,445,138
<p>For the following CSV File:</p> <pre><code>A,B,C ----- A1,B1,C1 A1,B2,C2 A2,B3,C3 A2,B4,C4 </code></pre> <p>My dictionary currently looks like this:</p> <pre><code>{'A1': {'B':'B1', 'C':'C1'}, 'A2': {'B':'B3', 'C':'C3'} </code></pre> <p>How do I get my dictionary to look like this:</p> <pre><code>'A1': {'B': ['...
0
2016-07-18T20:05:57Z
38,446,116
<p>You need to create a base case for each key, such that the dictionary inserts the first value as a list. Then you can append values for duplicate keys as they are encountered.</p> <p>The following code should do what you need:</p> <pre><code>with open('test.csv') as f: reader = csv.DictReader(f) for row i...
0
2016-07-18T21:15:29Z
[ "python", "csv", "dictionary" ]
Creating dictionary from CSV file, dictionary not containing all values
38,445,138
<p>For the following CSV File:</p> <pre><code>A,B,C ----- A1,B1,C1 A1,B2,C2 A2,B3,C3 A2,B4,C4 </code></pre> <p>My dictionary currently looks like this:</p> <pre><code>{'A1': {'B':'B1', 'C':'C1'}, 'A2': {'B':'B3', 'C':'C3'} </code></pre> <p>How do I get my dictionary to look like this:</p> <pre><code>'A1': {'B': ['...
0
2016-07-18T20:05:57Z
38,446,226
<p>You don't have to use DictReader to achieve this. You can just use regular csv.reader and fill up your own dictionary.</p> <p>Here is a commented simple solution:</p> <pre><code>from __future__ import print_function import csv csv_fpath = 'test.csv' # readcsv.py # You want this: #{'A1': {'B':['B1','B2'], 'C':['C...
0
2016-07-18T21:23:05Z
[ "python", "csv", "dictionary" ]
Creating dictionary from CSV file, dictionary not containing all values
38,445,138
<p>For the following CSV File:</p> <pre><code>A,B,C ----- A1,B1,C1 A1,B2,C2 A2,B3,C3 A2,B4,C4 </code></pre> <p>My dictionary currently looks like this:</p> <pre><code>{'A1': {'B':'B1', 'C':'C1'}, 'A2': {'B':'B3', 'C':'C3'} </code></pre> <p>How do I get my dictionary to look like this:</p> <pre><code>'A1': {'B': ['...
0
2016-07-18T20:05:57Z
38,446,307
<p>Slightly different approach:</p> <pre><code>reader = csv.DictReader(open("test.csv")) result = {} for row in reader: if reader.line_num &lt;= 2: continue key = row["A"] for subkey in [k for k in row.keys() if k != "A"]: if key not in result: result[key] = {} if subke...
0
2016-07-18T21:29:41Z
[ "python", "csv", "dictionary" ]
Why Steam OpenID redirect me to error dgango view?
38,445,158
<p>I'm using django, python social auth and Steam. For logging I sent get request to Steam ({% url social: begin steam %}), and I got Steam logging page. I passed my login and password and pressed log in. After that I was redirect to error url (not on success url). It's mean I was logged only in Steam, but not in my we...
0
2016-07-18T20:07:23Z
38,748,814
<p>I added this variables in settings.py, when I deleted them my site start working as I expect.</p> <pre><code>SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social...
0
2016-08-03T16:14:35Z
[ "python", "django", "openid", "steam", "python-social-auth" ]
Python Pygame: Fire multiple bullets for Space Invader game
38,445,248
<p>I'm trying to make a Space Invaders game using Pygame. However, I'm having trouble figuring out how to make the spaceship continuously shoot multiple bullets and have the bullets move along with it. The only way I have actually made the program shoot multiple bullets is through a <code>for loop</code>, although the ...
0
2016-07-18T20:12:52Z
38,445,550
<p>You should separate your game into a loop that contains 3 different functions:</p> <pre><code>LOOP UPDATE_LOGIC INPUT_HANDLING DRAW_ELEMENTS END-LOOP </code></pre> <p>In the <strong>input_handling</strong>, put a bullet into a list of bullets if the player is not in cool-down.</p> <p>In the <strong>up...
0
2016-07-18T20:32:57Z
[ "python", "pygame" ]
Settings.py and paths for html and static files Django
38,445,264
<p>I am using Django 1.8 and I am having trouble displaying my JavaScript and CSS when I run the development Django server. I think the main problem is not having a good understanding of what to set my static root and static root dir as. I have noticed that my folder/file paths are created differently compared to other...
0
2016-07-18T20:14:24Z
38,445,895
<p>Okay, answering your question in the reverse order of your questions.</p> <p>Firstly, its always a better convention and practice to keep your html, javascript and css in separate files. So all your HTML files goes in the templates directory and the javascript and CSS in js and css directory inside static directory...
0
2016-07-18T20:59:28Z
[ "javascript", "jquery", "python", "json", "django" ]
Settings.py and paths for html and static files Django
38,445,264
<p>I am using Django 1.8 and I am having trouble displaying my JavaScript and CSS when I run the development Django server. I think the main problem is not having a good understanding of what to set my static root and static root dir as. I have noticed that my folder/file paths are created differently compared to other...
0
2016-07-18T20:14:24Z
38,515,295
<p>This is the solution to your problem of reading data from a json file using your javascript in general i.e., it is not dependent on django or php or something like that.</p> <pre><code>function getAllSupportedItems( ) { return $.getJSON("staticfiles/json_folder/name_of_your_json_file.json").then(function (data)...
0
2016-07-21T22:20:55Z
[ "javascript", "jquery", "python", "json", "django" ]
Tweepy streamer stopping after few seconds
38,445,272
<p>Hi !</p> <p>I am experiencing some issue about tweepy library for Python. The first time I launched the below script, everything perfectly worked, and the second time... the script stop unexpectedly.</p> <p>I did not found anything about this behavior, the Listener is stopping after few seconds, and I do not have ...
0
2016-07-18T20:14:55Z
38,959,862
<p>Hi !</p> <p>I solved this weird issue by changing my Python version to 3.5 via virtualenv. For now, it works well. </p> <p>This could was due to the python version, anyway if someone have this, I just recommend to use virtualenv to test another Python version, and see what happens.</p> <p>FYI : I already opened i...
0
2016-08-15T17:25:40Z
[ "python", "twitter", "tweepy" ]
creating text file with multiple arrays of mixed types python
38,445,281
<p>I am trying to create a text file with multiple array as the columns in this file. The trick is that each array is a different datatype. For example:</p> <pre><code>a = np.zeros(100,dtype=np.int)+2 #integers all twos b = QC_String = np.array(['NA']*100) #strings all 'NA' c = np.ones(100,dtype=np.float)*99.9999 #flo...
0
2016-07-18T20:15:48Z
38,445,946
<p>I recommending using <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> to accomplish this task, which can easily handle multiple data types while writing out a new text file.</p> <pre><code>import numpy as np import pandas as pd # Create an empty DataFrame df = pd.DataFrame() # Populate columns in the...
2
2016-07-18T21:03:25Z
[ "python", "arrays", "file", "numpy", "text" ]
Manipulating Data Frame with Pandas Python
38,445,311
<p>Okay so I went through some long way of getting my dataframe to look like this so that I was able to graph it:</p> <pre><code>data_mth GROUP 201504 499 and below 0.001806 201505 499 and below 0.007375 201506 499 and below 0.000509 201507 499 and below 0.007344 201504 500 - 599 0.0...
2
2016-07-18T20:17:32Z
38,445,722
<pre><code>import io import pandas as pd data = io.StringIO('''\ 499 and below,500 - 599,800 - 899,900 and above 201504,0.001806,0.016672,0.472784,0.065144 201505,0.007375,0.011473,0.516837,0.226626 201506,0.000509,0.017733,0.169811,0.251585 201507,0.007344,0.017651,0.293966,0.299850 ''') df = pd.read_csv(data) df.in...
4
2016-07-18T20:46:32Z
[ "python", "pandas", "dataframe" ]
xdata and ydata must be the same length
38,445,354
<p>I am trying to get my plot of temperature data to update by replacing the past 10 iterations with the next 10 as seen in the code before but I keep getting a "xdata and ydata must be the same length" error. Along with fixing the error, is this the best way to do such a task of replacing a certain amount of old data ...
0
2016-07-18T20:20:27Z
38,445,459
<p>This statement is the problem:</p> <pre><code>y[-10:] = y.append(temperature[i]) &lt;-- error </code></pre> <p>Because the right-side of that statement is an iterable (<code>y.append(_something_)</code> returns a <code>None</code> type, so this is equvalent to:</p> <pre><code>y[-10:] = None </code></pre> <p>You ...
0
2016-07-18T20:27:32Z
[ "python" ]
How to parse only specific tag values
38,445,360
<p>I'm new to Python, and i've written some code for parsing data from the <a href="http://espn.go.com/nhl/statistics/player/_/stat/points/sort/points/year/2015/seasontype/2" rel="nofollow">ESPN site</a>!</p> <pre class="lang-py prettyprint-override"><code>#importing packages/modules from bs4 import BeautifulSoup impo...
0
2016-07-18T20:20:53Z
38,445,422
<p>I would use a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a> to locate only data-rows (with players data):</p> <pre><code>for tr in soup.select("#my-players-table tr[class*=player]"): player_name = tr('td')[1].get_text(strip=True) print(player_...
0
2016-07-18T20:25:28Z
[ "python", "html-parsing", "bs4" ]
Incorrect credentials with Django Rest Framework?
38,445,372
<p>I'm trying to set up token authentication with the Django Rest Framework. I'm currently writing some tests to see if I can get a token returned for a user. Below is the code for the unit test (which is inside of a test case). </p> <pre><code>def test_create_valid_request(self): u = User.objects.create(username=...
0
2016-07-18T20:21:26Z
38,445,908
<p>Okay so the error was very simple: I wanted <code>User.objects.create_user</code> rather than <code>User.objects.create</code>. </p> <p>The password that I was trying to use with my code above was problematic because it wasn't hashed or salted, and because Django doesn't store or send plain-text passwords, me sendi...
0
2016-07-18T21:00:23Z
[ "python", "django", "django-rest-framework", "token", "restful-authentication" ]
Incorrect credentials with Django Rest Framework?
38,445,372
<p>I'm trying to set up token authentication with the Django Rest Framework. I'm currently writing some tests to see if I can get a token returned for a user. Below is the code for the unit test (which is inside of a test case). </p> <pre><code>def test_create_valid_request(self): u = User.objects.create(username=...
0
2016-07-18T20:21:26Z
38,447,162
<p>As you've already stated, you need to use <code>User.objects.create_user</code>. </p> <p>To add to this, if you already have a User object instantiated and want to change their password you'll need to call the <code>user.set_password(raw_password)</code> method.</p>
0
2016-07-18T22:55:02Z
[ "python", "django", "django-rest-framework", "token", "restful-authentication" ]
Can't loop through object list in Python
38,445,373
<p>I'm appending instances of a class to a list in Python as follows:</p> <pre><code>a_list = [] a_list.append(AClass()) </code></pre> <p>(At least one append).</p> <p>When trying to loop through the list:</p> <pre><code>for a in a_list: # Do something to know if loop runs... pass </code></pre> <p>It does ...
-7
2016-07-18T20:21:28Z
38,445,464
<p>That's strange, here's what I got:</p> <pre><code>class AClass(): pass a_list = [] a_list.append(AClass()) for a in a_list: print(a) # &lt;__main__.AClass object at 0x10b510c18&gt; print(len(a_list)) # 1 a_list.append(AClass()) print(len(a_list)) # 2 </code></pre> <p>Could the issue be related to your...
0
2016-07-18T20:27:40Z
[ "python", "class", "loops", "python-3.x" ]
Can't loop through object list in Python
38,445,373
<p>I'm appending instances of a class to a list in Python as follows:</p> <pre><code>a_list = [] a_list.append(AClass()) </code></pre> <p>(At least one append).</p> <p>When trying to loop through the list:</p> <pre><code>for a in a_list: # Do something to know if loop runs... pass </code></pre> <p>It does ...
-7
2016-07-18T20:21:28Z
38,445,469
<p>hmm ... works for me:</p> <pre><code>&gt;&gt;&gt; class AClass(object): ... def __init__(self): ... self.a = "AClass" ... &gt;&gt;&gt; a_list = [] &gt;&gt;&gt; a_list.append(AClass()) &gt;&gt;&gt; a_list.append(AClass()) &gt;&gt;&gt; a_list.append(AClass()) &gt;&gt;&gt; for a in a_list: ... print a.a ... ...
0
2016-07-18T20:27:55Z
[ "python", "class", "loops", "python-3.x" ]
Dropping duplicates in Pandas excluding one column
38,445,416
<p>This seems simple, but I can not find any information on it on the internet</p> <p>I have a dataframe like below</p> <pre><code>City State Zip Date Description Earlham IA 50072-1036 2014-10-10 Postmarket Assurance: Devices Earlham IA 50072-1036 2014-10-10 Compliance: Device...
2
2016-07-18T20:25:06Z
38,445,485
<p>You've actually found the solution. For multiple columns, subset will be a list.</p> <pre><code>df.drop_duplicates(subset=['City', 'State', 'Zip', 'Date']) </code></pre> <p>Or, just by stating the column to be ignored:</p> <pre><code>df.drop_duplicates(df.columns.difference(['Description'])) </code></pre>
5
2016-07-18T20:29:00Z
[ "python", "pandas" ]
None column in csv (csv python module)
38,445,560
<p>An instrument create a CVS with this on the file header : </p> <pre><code>XLabel,Wavenumber YLabel,Response FileType,Single Beam DisplayDirection,20300 PeakDirection,20312 0.000000,-1.149420,-1.177183,-1.174535 0.964406,-1.053002,-1.083787,-1.069919 1.928811,-0.629619,-0.652436,-0.628358 </code></pre> <p>I want to...
0
2016-07-18T20:33:21Z
38,445,570
<p>Just use <code>None</code> as the key:</p> <pre><code>print(row[None]) </code></pre> <p><code>None</code> is simply the value for the <code>restkey</code> argument to <code>DictReader()</code>, and <code>None</code> is the default. You could set it to something else. It is the key into which any <em>extra</em> col...
2
2016-07-18T20:34:26Z
[ "python", "csv" ]
Regex with capturing parentheses and non-greedy matching constraints
38,445,590
<p>I just spent an hour trying to figure out the magic syntax to solve the following problem in Python with the 're' package. I have hacked around it for the moment, but would like to set out the challenge:</p> <p>The following strings represent our test:</p> <pre><code>*Structure song &amp;lt;!-- See Project:Project...
0
2016-07-18T20:35:43Z
38,445,679
<p>I would suggest using non-greedy "anything" followed by "&amp;lt;" or pipe char represented as lookahead:</p> <pre><code>\*Structure (.*?(?= &amp;lt;)|.*?(?= \|)) </code></pre> <p>Demo: <a href="https://regex101.com/r/rT3oV5/2" rel="nofollow">https://regex101.com/r/rT3oV5/2</a></p>
1
2016-07-18T20:43:17Z
[ "python", "regex" ]
Regex with capturing parentheses and non-greedy matching constraints
38,445,590
<p>I just spent an hour trying to figure out the magic syntax to solve the following problem in Python with the 're' package. I have hacked around it for the moment, but would like to set out the challenge:</p> <p>The following strings represent our test:</p> <pre><code>*Structure song &amp;lt;!-- See Project:Project...
0
2016-07-18T20:35:43Z
38,446,092
<p>I'd use a similar pattern as Dmitriy's, but a more linear one:</p> <pre><code>\*Structure\s(.*?)(?=\s(?:&amp;lt;|\|)) </code></pre> <p>See <a href="https://regex101.com/r/cF0fE7/2" rel="nofollow">regex demo</a>.</p> <p><strong>Explanation</strong>:</p> <ul> <li><code>\*Structure</code> - a literal substring <cod...
2
2016-07-18T21:14:02Z
[ "python", "regex" ]
Receive big list through TCP Sockets - Python
38,445,631
<p>Which would be the best way to receive a big list through TCP Sockets ?</p> <p>My code looks like this. When U have to receive a big list, that doesn't work obviously.</p> <pre><code> print 'connection from', client_address while True: try: data = pickle.loads(connection.recv(8192)) ...
0
2016-07-18T20:39:26Z
38,446,123
<p>The best way to do this is to transform the <code>socket</code> into a <code>file</code> object. You can do this with <code>connection.makefile()</code>. Then, instead of calling <code>pickle.loads()</code> -- which expects a complete byte string containing the entire pickled object -- call <code>pickle.load(connect...
0
2016-07-18T21:16:14Z
[ "python", "sockets", "tcp" ]
Pandas Seaborn Heatmap Error
38,445,715
<p>I have a DataFrame that looks like this when unstacked.</p> <pre><code>Start Date 2016-07-11 2016-07-12 2016-07-13 Period 0 1.000000 1.000000 1.0 1 0.684211 0.738095 NaN 2 0.592105 NaN NaN </code></pre> <p>I'm trying to plot it in Seaborn...
-1
2016-07-18T20:46:10Z
38,446,981
<p>While exact reproducible data is not available, consider below using posted snippet data. This example runs a <code>pivot_table()</code> to achieve the structure as posted with StartDates across columns. Overall, your heatmap possibly outputs the multiple color bars and overlapping figures due to the <code>unstack()...
1
2016-07-18T22:34:34Z
[ "python", "pandas", "matplotlib", "heatmap", "seaborn" ]
Python: Custom package installation not importing module
38,445,784
<p>I'm having a problem with <a href="https://github.com/pgaref/HTTP_Request_Randomizer" rel="nofollow">this package</a> that I installed in Python 3.5. After installing it, I try to run requestProxy.py but it won't import any of its own packages. Here's what I did, and what's happening. </p> <p>I cloned it and create...
0
2016-07-18T20:51:32Z
38,473,293
<p>I figured it out. I was using Ninja IDE, and even though I entered the virtualenv for the project and restarted, it still wasn't recognizing it. I was able to run it from the terminal, and also in Pycharm and Liclipse.</p>
0
2016-07-20T05:55:30Z
[ "python", "git", "pip", "virtualenv" ]
Django Integrated Test Passing When it Should Fail
38,445,828
<p>I'm in the process of creating an assessment system using Django; however, I have an integrated test that passes and I'm not sure as to why (it should be failing). In the test, I set the grade field of the bobenrollment object to "Excellent". As you can see from the models below, the Enrollment model doesn't have...
0
2016-07-18T20:54:42Z
38,446,452
<blockquote> <p>I was under the impression that dot notation of model objects would access the model fields (I'm probably incorrect about this)</p> </blockquote> <p>You're correct about this. What you're not taking into account is the fact that you can dynamically add properties to python objects. For instance:</p> ...
0
2016-07-18T21:42:44Z
[ "python", "django", "django-unittest" ]
Python: Changing boolean list values
38,445,947
<p>I've encountered some behavior that confuses me.</p> <pre><code>to_return = [[], False] for i in other_list: value, flag = i[0], i[1] to_return[0].append(value) if flag is True and to_return[1] is False: to_return[1] is True </code></pre> <p>In other words, just change the bool to True if somet...
0
2016-07-18T21:03:26Z
38,446,019
<p><code>to_return[1] is True</code> is simply a boolean expression. Perhaps you mean <code>to_return[1] = True</code>?</p>
0
2016-07-18T21:09:07Z
[ "python" ]
Python: Changing boolean list values
38,445,947
<p>I've encountered some behavior that confuses me.</p> <pre><code>to_return = [[], False] for i in other_list: value, flag = i[0], i[1] to_return[0].append(value) if flag is True and to_return[1] is False: to_return[1] is True </code></pre> <p>In other words, just change the bool to True if somet...
0
2016-07-18T21:03:26Z
38,446,842
<p>"if smth == True" can be replaced with simple "if smth", so code will look better. If you need to check for false use "if not smth", it is equal to "if smth == False"</p>
0
2016-07-18T22:19:52Z
[ "python" ]
Python Requests Cookies not stored
38,445,951
<p>I am trying to login to a page using Python requests (2.10.0). </p> <p><strong>Code</strong>:</p> <pre><code>payload = { 'user_login': 'amitg.ind@gmail.com', 'user_pass': 'xxx', 'rememberme': '1' } with requests.session() as sess: resp = sess.post(URL_LOGIN, data=payload) print resp.cookies </c...
0
2016-07-18T21:03:37Z
38,515,031
<p>Thanks @Padraic - I was using the 'id' attribute but 'name' was to be used. Thanks for that. wp-submit was not required. Thanks again.</p>
1
2016-07-21T21:57:38Z
[ "python", "python-requests", "session-cookies" ]
Common elements between columns of a DataFrame
38,445,974
<p>I have a <code>Pandas</code> <code>DataFrame</code> that looks like this:</p> <pre><code>MemberID A B C D 1 0.3 0.5 0.1 0 2 0 0.2 0.9 0.3 3 0.4 0.2 0.5 0.3 4 0.1 0 0 0.7 </code></pre> <p>I would like to have another matrix which gives me the num...
5
2016-07-18T21:05:21Z
38,446,273
<p>This should to it:</p> <pre><code>z = (df != 0) * 1 z.T.dot(z) </code></pre> <p><a href="http://i.stack.imgur.com/cjkQS.png"><img src="http://i.stack.imgur.com/cjkQS.png" alt="enter image description here"></a></p>
5
2016-07-18T21:27:09Z
[ "python", "pandas", "matrix" ]
Convert Excel file into list for basket analysis via Python
38,445,975
<p>I am teaching myself Python by working through various tutorials and then re applying it to my own custom datasets. I am having issues restructuring my data to work with this Association Rules tutorial I found</p> <p>Reference: <a href="http://aimotion.blogspot.com/2013/01/machine-learning-and-data-mining.html" re...
0
2016-07-18T21:05:30Z
38,446,241
<p>Assuming your data is on the first sheet:</p> <pre><code>import openpyxl wb = openpyxl.load_workbook('yourfile.xlsx') ws = wb.worksheets[0] final_list = [] for i,row in enumerate(ws.iter_rows()): if i == 0: continue # skip first row sub_list = [] for cell in row: if cell.value == 1: ...
0
2016-07-18T21:23:58Z
[ "python", "excel" ]
How to log Keras loss output to a file
38,445,982
<p>When you run a Keras neural network model you might see something like this in the console: </p> <pre><code>Epoch 1/3 6/1000 [..............................] - ETA: 7994s - loss: 5111.7661 </code></pre> <p>As time goes on the loss hopefully improves. I want to log these losses to a file over time so that I can ...
3
2016-07-18T21:05:58Z
38,446,890
<p>There is a simple solution to your problem. Every time any of the <code>fit</code> methods are used - as a result the special callback called <strong>History Callback</strong> is returned. It has a field <code>history</code> which is a dictionary of all metrics registered after every epoch. So to get list of loss fu...
2
2016-07-18T22:24:49Z
[ "python", "logging", "machine-learning", "neural-network", "keras" ]
How to log Keras loss output to a file
38,445,982
<p>When you run a Keras neural network model you might see something like this in the console: </p> <pre><code>Epoch 1/3 6/1000 [..............................] - ETA: 7994s - loss: 5111.7661 </code></pre> <p>As time goes on the loss hopefully improves. I want to log these losses to a file over time so that I can ...
3
2016-07-18T21:05:58Z
38,449,876
<p>You can redirect the sys.stdout object to a file before the model.fit method and reassign it to the standard console after model.fit method as follows:</p> <pre><code>import sys oldStdout = sys.stdout file = open('logFile', 'w') sys.stdout = file model.fit(Xtrain, Ytrain) sys.stdout = oldStdout </code></pre>
0
2016-07-19T04:58:39Z
[ "python", "logging", "machine-learning", "neural-network", "keras" ]
Python Sypherical volume
38,445,985
<p>"Given sphere_radius and pi, compute the volume of a sphere and assign to sphere_volume. Volume of sphere = (4.0 / 3.0) π r3 </p> <p>Sample output for the given program: 4.18878666667"</p> <p>I am to get the test to pass both when the radius of 1 is calculated and the radius of 5.5. I can get one or the other to...
-2
2016-07-18T21:06:42Z
38,446,230
<p>Try:</p> <pre><code>import math sphere_radius = float(raw_input("Input radius: ")) sphere_volume=(((4.0/3.0) * math.pi) * sphere_radius**3) print(sphere_volume) </code></pre>
0
2016-07-18T21:23:18Z
[ "python" ]
Python Sypherical volume
38,445,985
<p>"Given sphere_radius and pi, compute the volume of a sphere and assign to sphere_volume. Volume of sphere = (4.0 / 3.0) π r3 </p> <p>Sample output for the given program: 4.18878666667"</p> <p>I am to get the test to pass both when the radius of 1 is calculated and the radius of 5.5. I can get one or the other to...
-2
2016-07-18T21:06:42Z
38,446,312
<p>Just add the missing print statement. You have two volumes to report, so you have to print each as soon as calculated.</p> <pre><code>pi = 3.14159 sphere_radius = 1.0 sphere_volume = 0.0 sphere_volume=(((4.0/3.0) * 3.14159) * 1**3) print(sphere_volume) sphere_radius = 5.5 sphere_volume=(((4.0/3.0) * 3.14159) * 5....
0
2016-07-18T21:29:57Z
[ "python" ]
Python Sypherical volume
38,445,985
<p>"Given sphere_radius and pi, compute the volume of a sphere and assign to sphere_volume. Volume of sphere = (4.0 / 3.0) π r3 </p> <p>Sample output for the given program: 4.18878666667"</p> <p>I am to get the test to pass both when the radius of 1 is calculated and the radius of 5.5. I can get one or the other to...
-2
2016-07-18T21:06:42Z
39,799,810
<p>Kept it simple:</p> <pre><code>pi = 3.14159 sphere_radius = 1.0 sphere_volume = 0.0 sphere_volume = (((4.0/3.0) * pi) * sphere_radius**3) print(sphere_volume) </code></pre> <p>Testing volume with radius 1.0 Your value: 4.188786666666666 Testing volume with radius 5.5 Your value: 696.9093816666666</p>
0
2016-09-30T20:44:35Z
[ "python" ]
With Tkinter in Python. How do I call a list variable into a canvas one at a time
38,445,987
<p>With Tkinter in Python. How do I call a list variable into a canvas one at a time when a button's pressed (in this case. <em>next</em>). Here's what I tried. I'm a newby in programming.</p> <pre><code>def _next_(self): def y(self): a='hey' b='you' e=[a,b] for i in (e): ...
0
2016-07-18T21:06:52Z
38,446,731
<p>Is this what you are looking for:</p> <pre><code>from tkinter import * root = Tk() textList = ["Hey", "you", "whatsup"] mycanvas = Canvas(root) mycanvas.pack() textobj = mycanvas.create_text(100, 50) def f(): mycanvas.itemconfig(textobj, text=textList) mybutton = Button(root, text="Click", command=f) mybut...
0
2016-07-18T22:08:19Z
[ "python", "canvas", "tkinter" ]
How to return index of item in MultiDimensional Array and check attributes of those items
38,446,023
<p>I'm having trouble iterating through a multidimensional array and returning the index of the elements. What I am doing is creating a MoveUp function that moves through the multidimentional array.</p> <p>Currently my find method will return the correct index of the objects in the first array within the multidimensio...
0
2016-07-18T21:09:18Z
38,447,225
<p>First error you have because you trying to return not existed value. </p> <pre><code>#Find Index of Element in MultiDimenstional Array def find(l, elem): for row, i in enumerate(l): try: column = i.index(elem) return row, column except ValueError: #here is err...
0
2016-07-18T23:02:50Z
[ "python", "arrays", "multidimensional-array", "attributeerror" ]
Convert datetime string based on offset to datetime
38,446,029
<p>I have a datetime string and need to convert it to datetime object based on the given offset.</p> <pre><code>&gt;&gt;&gt; dt = iso8601.parse_date('2016-07-22 11:16:13+00:00') &gt;&gt;&gt; tzlocal = tz.tzoffset('local',-240) &gt;&gt;&gt; dt = dt.astimezone(tzlocal) &gt;&gt;&gt; dt datetime.datetime(2016, 7, 22, 11, ...
0
2016-07-18T21:09:41Z
38,446,119
<p>The offset is given in seconds. You indeed did get an offset, but -240 is 4 minutes. 11 hours 12 minutes 13 seconds from 11 hours 16 minutes 13 seconds. Change -240 to -4*60*60 to prevent confusion.</p>
2
2016-07-18T21:16:05Z
[ "python", "datetime" ]
Python search and replace
38,446,110
<p>I have written two functions in Python. When I run replace(), it looks at the data structure named replacements. It takes the key, iterates through the document and when it matches a key to a word in the document, it replaces the word with the value.</p> <p>Now it seems what is happening, because i also have the r...
0
2016-07-18T21:15:05Z
38,446,158
<blockquote> <p>is there an easier way to iterate through the text file and only change the word once, if found?</p> </blockquote> <p>There's a much simpler way:</p> <pre><code>output = " ".join(replacements.get(x, x) for x in fileinput.split()) out.write(output) </code></pre>
0
2016-07-18T21:18:47Z
[ "python", "string", "replace", "substring" ]
Python search and replace
38,446,110
<p>I have written two functions in Python. When I run replace(), it looks at the data structure named replacements. It takes the key, iterates through the document and when it matches a key to a word in the document, it replaces the word with the value.</p> <p>Now it seems what is happening, because i also have the r...
0
2016-07-18T21:15:05Z
38,446,601
<p>To account for punctuation, use a regular expression instead of <code>split()</code>:</p> <pre><code>output = " ".join(replacements.get(x, x) for x in re.findall(r"[\w']+|[.,!?;]", fileinput)) out.write(output) </code></pre> <p>This way, punctuation will be ignored during the replace, but will be present in the fi...
0
2016-07-18T21:54:30Z
[ "python", "string", "replace", "substring" ]
Python search and replace
38,446,110
<p>I have written two functions in Python. When I run replace(), it looks at the data structure named replacements. It takes the key, iterates through the document and when it matches a key to a word in the document, it replaces the word with the value.</p> <p>Now it seems what is happening, because i also have the r...
0
2016-07-18T21:15:05Z
38,447,022
<p>Improved version of rawbeans answer. It didn't work as expected since some of your replacement keys contain multiple words.</p> <p>Tested with your example line and it outputs: <code>the match finished because of rain a mere forty minutes after it started. it was stopped due to rain.</code></p> <pre><code>import r...
1
2016-07-18T22:38:38Z
[ "python", "string", "replace", "substring" ]
conflict with post save and __unicode__(self) in django models
38,446,147
<p>Apologies for the strange title, but caught on a funny problem involving a conflict with post.save (from a form) and the <strong>unicode</strong>(self) return in my model.</p> <p>Models.py </p> <pre><code>class NumericTraits(models.Model): feature_id = models.IntegerField(primary_key=True) species = model...
0
2016-07-18T21:18:08Z
38,447,193
<p>of course... always something simple.. I guess when I was trying to assign "post.cite_id", it was trying to assign it to the foreign key in a funny way.. Fixed this by changing. </p> <pre><code>post.cite_id = ..... </code></pre> <p>to </p> <pre><code>post.cite = ..... </code></pre>
0
2016-07-18T22:58:10Z
[ "python", "django", "unicode", "foreign-keys" ]
Python multiprocessing subclass initialization
38,446,167
<p>Is it okay to initialize the state of a <code>multiprocessing.Process</code> subclass in the <code>__init__()</code> method? Or will this result in duplicate resource utilization when the process forks? Take this example:</p> <pre><code>from multiprocessing import Process, Pipe import time class MyProcess(Proces...
0
2016-07-18T21:19:22Z
38,446,308
<p>This is easy to test. In <code>__init__</code>, add the following:</p> <pre><code> self.file = open('does_it_open.txt'.format(self.count), 'w') </code></pre> <p>Then run:</p> <pre><code> $ strace -f python youprogram.py 2&gt; test.log $ grep does_it_open test.log open("does_it_open.txt", O_WRONLY|O_CREAT|O_TRUN...
1
2016-07-18T21:29:43Z
[ "python", "python-multiprocessing" ]
How to unpack data using byte objects in python
38,446,177
<p>I am trying to unpack a specific piece of data from an encoded file. The data is a type int32.</p> <p>My approach was to try and read each line of the file and if a section of that lines size matches the size of ' <pre><code>with open(r2sFile2, encoding="latin-1") as datafile: for line in datafile: for...
0
2016-07-18T21:20:11Z
38,446,513
<p>You cannot open a file using an encoding and also read raw bytes from the same stream. Specifying an encoding will convert those bytes into unicode points. You want to open the file in binary mode so that it returns <code>byte</code>'s instead of <code>unicode</code> characters. You should also be reading fixed s...
0
2016-07-18T21:47:36Z
[ "python", "object", "struct", "byte" ]
Selenium Freezing on large pages
38,446,179
<p>I am scraping a very large document, and when I call:</p> <pre><code> page_source = driver.page_source </code></pre> <p>It freezes and isn't able to capture the full page source. Is there something I can do to mitigate this issue? The page is from an autoscroll and I can't access to the source.</p>
1
2016-07-18T21:20:25Z
38,446,245
<p>You can workaround it with an <a href="http://selenium-python.readthedocs.io/api.html#selenium.webdriver.remote.webdriver.WebDriver.execute_script" rel="nofollow"><code>execute_script()</code></a>:</p> <pre><code>driver.execute_script("return document.documentElement.outerHTML;") </code></pre> <p>You can also try ...
1
2016-07-18T21:24:27Z
[ "python", "selenium" ]
Kivy error Camera Webcam gives error VideoCapture:Resolution not found
38,446,292
<p>I have a Kivy App and I am trying to take a video from my webcam camera to put it in my application on my computer. I got this code online which was :-</p> <pre><code>from kivy.app import App from kivy.lang import Builder kv = ''' BoxLayout: orientation: 'vertical' Camera: id: camera resolu...
1
2016-07-18T21:28:12Z
38,529,975
<p>I don't have the reputation to comment so I'll leave it here. Both your scripts are working fine on my laptop. I've tried several resolutions and all of them are supported: 1920x1080, 640x480, 320x240. Check your kivy and OpenCV versions. Mine is: OpenCV 2.4.12 Kivy v1.9.0 Python v2.7.8</p>
0
2016-07-22T15:15:08Z
[ "python", "video", "camera", "kivy", "webcam" ]
Kivy error Camera Webcam gives error VideoCapture:Resolution not found
38,446,292
<p>I have a Kivy App and I am trying to take a video from my webcam camera to put it in my application on my computer. I got this code online which was :-</p> <pre><code>from kivy.app import App from kivy.lang import Builder kv = ''' BoxLayout: orientation: 'vertical' Camera: id: camera resolu...
1
2016-07-18T21:28:12Z
38,592,816
<p>Hi so I ran the program on Windows 7 and it works ! I am not sure if it was an OS problem or not but it is working. So if someone makes it working for Windows 8 or 10 please comment. I wasted a lot of time debugging this and could not get it working on those 2 OS. Well anyway thankfully got it working and thank you ...
0
2016-07-26T14:35:23Z
[ "python", "video", "camera", "kivy", "webcam" ]
Cannot animate clones of the same patch in python matplotlib
38,446,295
<p>I am currently trying to make a simulation in which multiple particle agents (blue dots) try to follow the enemy particle (red dot). I have managed to get my simulation to have one blue dot follow the red dot, but I am having trouble producing multiple version of the blue dots (also trying ot get it to appear at ran...
1
2016-07-18T21:28:15Z
38,456,625
<pre><code>import numpy as np from matplotlib import pyplot as plt from matplotlib import animation import random fig = plt.figure() fig.set_dpi(100) fig.set_size_inches(5, 4.5) ax = plt.axes(xlim=(0, 100), ylim=(0, 100)) enemy = plt.Circle((10, -10), 0.75, fc='r') agent = plt.Circle((10, -10), 0.75, fc='b') patches...
1
2016-07-19T10:58:37Z
[ "python", "animation", "matplotlib", "simulation", "particle" ]
Verify SSL Certificate in Python on Windows 7 64 bit
38,446,394
<p>I need help in verifying SSL certificate within the company's firewall when trying to access the cloud hosted application <a href="https://www.quickbase.com/" rel="nofollow">https://www.quickbase.com/</a>. The pyquickbase module works perfectly when I run the script from home. Here is my code and traceback for your ...
1
2016-07-18T21:37:26Z
38,532,141
<p>Ok, I tried setting up the proxy with OS environment variable and that did not work since the requests.get required that I pass the proxy within the call. I created a proxy Dict as</p> <pre><code>proxyDict = { "http" : http_proxy, "https" : https_proxy, "ftp" : ftp_pr...
0
2016-07-22T17:23:23Z
[ "python", "api", "quickbase" ]
Using parent method in child class | python
38,446,396
<p>Just learning Python, don't be mad.</p> <p>Consider the following code:</p> <pre><code>class Parent: def __init__(self): pass @staticmethod def print_hello(): print "hello" class Child(Parent): def __init__(self): super(Child, self).__init__() @staticmethod de...
-1
2016-07-18T21:37:33Z
38,447,391
<p><code>Child.print_hello()</code> works.</p> <p>Question is closed.</p>
0
2016-07-18T23:27:10Z
[ "python", "python-2.7", "class", "parent-child" ]
Analyzing multiple csv files
38,446,425
<p>I have data in 10 individual csv files. Each csv file just has one row of data entires (500000 data points, no headers etc.). Three questions:</p> <ol> <li>How can I transform the data to be one column with 500000 rows?</li> <li>Is it better to import them into one numpy array: 500000 x 10 to analyze them. If so, h...
-3
2016-07-18T21:39:54Z
38,446,451
<p>Assume you have a list of file names <code>files</code>. Then:</p> <pre><code>df = pd.concat([pd.read_csv(f, header=None) for f in files], ignore_index=True) </code></pre> <ol> <li><code>df</code> is a 10 x 500000 dataframe. Make it a 500000 x 10 with <code>df.T</code></li> </ol> <p>Answers to 2 and 3 depends o...
1
2016-07-18T21:42:34Z
[ "python", "csv", "numpy", "pandas" ]
Analyzing multiple csv files
38,446,425
<p>I have data in 10 individual csv files. Each csv file just has one row of data entires (500000 data points, no headers etc.). Three questions:</p> <ol> <li>How can I transform the data to be one column with 500000 rows?</li> <li>Is it better to import them into one numpy array: 500000 x 10 to analyze them. If so, h...
-3
2016-07-18T21:39:54Z
38,446,636
<p>First, read all 10 csv:</p> <pre><code>import os, csv, numpy import pandas as pd my_csvs = os.listdir('path to folder with 10 csvs') #selects all files in folder list_of_columns = [] os.chdir('path to folder with 10 csvs') for file in my_csvs: column = [] with open(file, 'r') as f: reader = csv.re...
0
2016-07-18T21:58:21Z
[ "python", "csv", "numpy", "pandas" ]
Filling dict with NA values to allow conversion to pandas dataframe
38,446,457
<p>I have a dict that holds computed values on different time lags, which means they start on different dates. For instance, the data I have may look like the following:</p> <pre><code>Date col1 col2 col3 col4 col5 01-01-15 5 12 1 -15 10 01-02-15 7 0 9 11 ...
8
2016-07-18T21:43:09Z
38,446,550
<pre><code>#dictionary of different lengths... my_dict = {'a' : [1, 2, 3, 4, 5], 'b': [1, 2, 3]} pd.DataFrame(dict([(col_name,pd.Series(values)) for col_name,values in my_dict.items() ])) </code></pre> <p>Output - </p> <pre><code> a b 0 1 1.0 1 2 2.0 2 3 3.0 3 4 NaN 4 5 NaN </code></pre>
5
2016-07-18T21:50:15Z
[ "python", "pandas" ]
Filling dict with NA values to allow conversion to pandas dataframe
38,446,457
<p>I have a dict that holds computed values on different time lags, which means they start on different dates. For instance, the data I have may look like the following:</p> <pre><code>Date col1 col2 col3 col4 col5 01-01-15 5 12 1 -15 10 01-02-15 7 0 9 11 ...
8
2016-07-18T21:43:09Z
38,446,637
<p>Another option is to use <code>from_dict</code> with <code>orient='index'</code> and then take the tranpose:</p> <pre><code>my_dict = {'a' : [1, 2, 3, 4, 5], 'b': [1, 2, 3]} df = pd.DataFrame.from_dict(my_dict, orient='index').T </code></pre> <p>Note that you could run into problems with <code>dtype</code> if your...
7
2016-07-18T21:58:24Z
[ "python", "pandas" ]
Filling dict with NA values to allow conversion to pandas dataframe
38,446,457
<p>I have a dict that holds computed values on different time lags, which means they start on different dates. For instance, the data I have may look like the following:</p> <pre><code>Date col1 col2 col3 col4 col5 01-01-15 5 12 1 -15 10 01-02-15 7 0 9 11 ...
8
2016-07-18T21:43:09Z
38,446,674
<p>Here's an approach using masking -</p> <pre><code>K = d.keys() V = d.values() mask = ~np.in1d(K,'Date') K1 = [K[i] for i,item in enumerate(V) if mask[i]] V1 = [V[i] for i,item in enumerate(V) if mask[i]] lens = np.array([len(item) for item in V1]) mask = lens[:,None] &gt; np.arange(lens.max()) out_arr = np.full(...
5
2016-07-18T22:01:39Z
[ "python", "pandas" ]
Filling dict with NA values to allow conversion to pandas dataframe
38,446,457
<p>I have a dict that holds computed values on different time lags, which means they start on different dates. For instance, the data I have may look like the following:</p> <pre><code>Date col1 col2 col3 col4 col5 01-01-15 5 12 1 -15 10 01-02-15 7 0 9 11 ...
8
2016-07-18T21:43:09Z
38,446,695
<p>With itertools (Python 3):</p> <pre><code>import itertools pd.DataFrame(list(itertools.zip_longest(*d.values())), columns=d.keys()).sort_index(axis=1) Out[728]: col1 col2 col3 col4 col5 0 5.0 12 1.0 -15.0 10.0 1 7.0 0 9.0 11.0 7.0 2 NaN 6 1.0 2.0 18.0 3 NaN 9 8.0 10.0 ...
5
2016-07-18T22:03:44Z
[ "python", "pandas" ]
handle missing tags in XML using lxml
38,446,532
<p>I'm parsing a huge xml file using the the code describe <a href="http://codereview.stackexchange.com/questions/2449/parsing-huge-xml-file-with-lxml-etree-iterparse-in-python">here</a> and it works fine. However I realized in some cases the parent element is missing. Here is one example:</p> <pre><code>&lt;?xml vers...
0
2016-07-18T21:49:12Z
38,447,404
<p>The solution is as you expect: Manually repair the broken XML.</p> <p>There is no general repair method that you can automatically apply when you encounter an arbitrary validation error. One might imagine some simple cases being covered automatically, but in general there can be multiple ways to address a validati...
1
2016-07-18T23:28:25Z
[ "python", "xml", "lxml" ]
Making a 4 digit pin in tkinker
38,446,609
<p>I'm working with tkinker python and trying to make a 4 digit pin lock screen. Im trying to draw white squares for each digit and I can not figure out how to manipulate the api in a way to get a perfect square. What am I doing wrong, how can I do this? Here is my code</p> <p><div class="snippet" data-lang="js" data-...
0
2016-07-18T21:55:45Z
38,447,671
<p>Create a square rectangle with white fill. <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_rectangle.html" rel="nofollow">This</a> is a good reference. I removed the reference to an icon I don't have.</p> <pre><code>from tkinter import * class app(Frame): def __init__(self, master=None): ...
0
2016-07-19T00:06:15Z
[ "python", "tkinter" ]
Catch both links and ips with python3
38,446,651
<p>with the help of forum, I made a script that catch all link of the topics of this page <a href="https://www.inforge.net/xi/forums/liste-proxy.1118/" rel="nofollow">https://www.inforge.net/xi/forums/liste-proxy.1118/</a> . These topics contains a list of proxies. The script is this:</p> <pre><code>import urllib.requ...
0
2016-07-18T22:00:08Z
38,461,609
<p>This code should do what you want, it's commented so you can understand all the passages:</p> <pre><code>import urllib.request, re from bs4 import BeautifulSoup url = "https://www.inforge.net/xi/forums/liste-proxy.1118/" soup = BeautifulSoup(urllib.request.urlopen(url), "lxml") base = "https://www.inforge.net/xi/...
2
2016-07-19T14:38:52Z
[ "python", "python-3.x", "hyperlink", "timeout", "try-catch" ]