title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Split CSV file using Python shows not all data in Excel
39,726,884
<p>I am trying to dump the values in my Django database to a csv, then write the contents of the csv to an Excel spreadsheet which looks like a table (one value per cell), so that my users can export a spreadsheet of all records in the database from Django admin. Right now when I export the file, I get this (only one random value out of many and not formatted correctly):</p> <p><a href="http://i.stack.imgur.com/yGdrK.png" rel="nofollow"><img src="http://i.stack.imgur.com/yGdrK.png" alt="enter image description here"></a></p> <p>What am I doing wrong? Not sure if I am using list comprehensions wrong, reading the file incorrectly, or if there is something wrong with my <code>for</code> loop. Please help! </p> <pre><code>def dump_table_to_csv(db_table, io): with connection.cursor() as cursor: cursor.execute("SELECT * FROM %s" % db_table, []) row = cursor.fetchall() writer = csv.writer(io) writer.writerow([i[0] for i in cursor.description]) writer.writerow(row) with open('/Users/nicoletorek/emarshal/myfile.csv', 'w') as f: dump_table_to_csv(Attorney._meta.db_table, f) with open('/Users/nicoletorek/emarshal/myfile.csv', 'r') as f: db_list = f.read() split_db_list = db_list.split(',') output = BytesIO() workbook = xlsxwriter.Workbook(output) worksheet_s = workbook.add_worksheet("Summary") header = workbook.add_format({ 'bg_color': '#F7F7F7', 'color': 'black', 'align': 'center', 'valign': 'top', 'border': 1 }) row = 0 col = 0 for x in split_db_list: worksheet_s.write(row + 1, col + 1, x, header) </code></pre>
0
2016-09-27T14:07:10Z
39,729,083
<p>The immediate problem with your sample code, as Jean-Francois points out, is that you aren't incrementing your counters in the loop. Also you may also find it more readable to use <code>xlsxwriter.write_row()</code> instead of <code>xlsxwriter.write()</code>. At the moment a secondary complication is you aren't preserving row information when you read in your data from the CSV.</p> <p>If your data looks like this:</p> <pre><code>row_data = [[r1c1, r1c2], [r2c1, r2c2], ... ] </code></pre> <p>You can then use:</p> <pre><code>for index, row in enumerate(row_data): worksheet_s.write_row(index, 0, row) </code></pre> <p>That said, I assume you are interested in the .xlsx because you want control over formatting. If the goal is to just to generate the .xlsx and there is no need for the intermediate .csv, why not just create the .xlsx file directly? This can be accomplished nicely in a view:</p> <pre><code>import io from django.http import HttpResponse def dump_attorneys_to_xlsx(request): output = io.BytesIO() workbook = xlsxwriter.Workbook(output, {'in_memory': True}) worksheet = workbook.add_worksheet('Summary') attorneys = Attorney.objects.all().values() # Write header worksheet.write_row(0, 0, attorneys[0].keys()) # Write data for row_index, row_dict in enumerate(attorneys, start=1): worksheet.write_row(row_index, 0, row_dict.values()) workbook.close() output.seek(0) response = HttpResponse(output.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=summary.xlsx' return response </code></pre>
1
2016-09-27T15:49:30Z
[ "python", "django", "csv", "split", "list-comprehension" ]
modify and write large file in python
39,726,921
<ol> <li><p>Say I have a data file of size 5GB in the disk, and I want to append another set of data of size 100MB at the end of the file -- Just simply append, I don't want to modify nor move the original data in the file. I know I can read the hole file into memory as a long long list and append my small new data to it, but it's too slow. How I can do this more efficiently? I mean, without reading the hole file into memory?</p></li> <li><p>I have a script that generates a large stream of data, say 5GB, as a long long list, and I need to save these data into a file. I tried to generate the list first and then output them all in once, but as the list increased, the computer got slow down very very severely. So I decided to output them by several times: each time I have a list of 100MB, then output them and clear the list. (this is why I have the first problem) I have no idea how to do this.Is there any lib or function that can do this?</p></li> </ol>
0
2016-09-27T14:09:00Z
39,727,471
<p>Let's start from the second point: if the list you store in memory is larger than the available ram, the computer starts using the hd as ram and this severely slow down everything. The optimal way of outputting in your situation is fill the ram as much as possible (always keeping enough space for the rest of the software running on your pc) and then writing on a file all in once.</p> <p>The fastest way to store a list in a file would be using <code>pickle</code> so that you store binary data that take much less space than formatted ones (so even the read/write process is much much faster). </p> <p>When you write to a file, you should keep the file always open, using something like <code>with open('namefile', 'w') as f</code>. In this way, you save the time to open/close the file and the cursor will always be at the end. If you decide to do that, use <code>f.flush()</code> once you have written the file to avoid loosing data if something bad happen. The <code>append</code> method is good alternative anyway.</p> <p>If you provide some code it would be easier to help you...</p>
0
2016-09-27T14:33:51Z
[ "python" ]
Separate list into two equal parts with slices
39,726,968
<p>I need to write a function that splits any list into two equal parts. If length of list is even, I want just split it it two parts, and if length of the list is odd, I want to ignore central element.</p> <pre><code>So [1,2,3,4,5,6] =&gt; [1,2,3] and [4,5,6] and [1,2,3,4,5] =&gt; [1,2] and [4,5] </code></pre> <p>I tried to do the following way:</p> <pre><code>list = [1,100,50,-51,1,1] s = len(list)/2 left = list[s+1:] right = list[:s] </code></pre> <p>But this approach doesnt work both for even and odd lengths. Is there a way to use slices for this purpose or there is no way and it's better to use loops/iterations?</p>
-2
2016-09-27T14:11:09Z
39,727,078
<p>Try this</p> <pre><code>length = len(list) half = int(length/2) first_half = list[:half] second_half = list[length-half:] </code></pre> <p>The trick here is cutting the decimal off of half when it's odd</p>
4
2016-09-27T14:15:35Z
[ "python" ]
Separate list into two equal parts with slices
39,726,968
<p>I need to write a function that splits any list into two equal parts. If length of list is even, I want just split it it two parts, and if length of the list is odd, I want to ignore central element.</p> <pre><code>So [1,2,3,4,5,6] =&gt; [1,2,3] and [4,5,6] and [1,2,3,4,5] =&gt; [1,2] and [4,5] </code></pre> <p>I tried to do the following way:</p> <pre><code>list = [1,100,50,-51,1,1] s = len(list)/2 left = list[s+1:] right = list[:s] </code></pre> <p>But this approach doesnt work both for even and odd lengths. Is there a way to use slices for this purpose or there is no way and it's better to use loops/iterations?</p>
-2
2016-09-27T14:11:09Z
39,727,092
<p>Use <code>divmod</code> on the length of the list and 2. Right slice is taken from sum of the quotient and the remainder:</p> <pre><code>lst = [1,100,50,-51,1,1] s = divmod(len(lst), 2) left = lst[:s[0]] right = lst[sum(s):] </code></pre>
2
2016-09-27T14:16:24Z
[ "python" ]
Separate list into two equal parts with slices
39,726,968
<p>I need to write a function that splits any list into two equal parts. If length of list is even, I want just split it it two parts, and if length of the list is odd, I want to ignore central element.</p> <pre><code>So [1,2,3,4,5,6] =&gt; [1,2,3] and [4,5,6] and [1,2,3,4,5] =&gt; [1,2] and [4,5] </code></pre> <p>I tried to do the following way:</p> <pre><code>list = [1,100,50,-51,1,1] s = len(list)/2 left = list[s+1:] right = list[:s] </code></pre> <p>But this approach doesnt work both for even and odd lengths. Is there a way to use slices for this purpose or there is no way and it's better to use loops/iterations?</p>
-2
2016-09-27T14:11:09Z
39,727,146
<p>How about using negative indexing on the right half?</p> <pre><code>def separate(seq): s = len(seq)/2 left = seq[:s] right = seq[-s:] return left, right print separate([1,2,3,4,5,6]) #result: ([1, 2, 3], [4, 5, 6]) print separate([1,2,3,4,5]) #result: ([1, 2], [4, 5]) </code></pre>
2
2016-09-27T14:18:46Z
[ "python" ]
Separate list into two equal parts with slices
39,726,968
<p>I need to write a function that splits any list into two equal parts. If length of list is even, I want just split it it two parts, and if length of the list is odd, I want to ignore central element.</p> <pre><code>So [1,2,3,4,5,6] =&gt; [1,2,3] and [4,5,6] and [1,2,3,4,5] =&gt; [1,2] and [4,5] </code></pre> <p>I tried to do the following way:</p> <pre><code>list = [1,100,50,-51,1,1] s = len(list)/2 left = list[s+1:] right = list[:s] </code></pre> <p>But this approach doesnt work both for even and odd lengths. Is there a way to use slices for this purpose or there is no way and it's better to use loops/iterations?</p>
-2
2016-09-27T14:11:09Z
39,727,211
<p><code>A = [1,2,3,4,5,6] B = A[:len(A)/2] C = A[len(A)/2:]</code></p> <p>If you want a function:</p> <p><code>def split_list(a_list): half = len(a_list)/2 return a_list[:half], a_list[half:] A = [1,2,3,4,5,6] B, C = split_list(A)</code></p> <p>If you don't care about the order...</p> <p><code>def split(list):<br> return list[::2] return list[1::2]</code></p> <p>list[::2] gets every second element in the list starting from the 0th element. list[1::2] gets every second element in the list starting from the 1st element.</p>
0
2016-09-27T14:21:11Z
[ "python" ]
tkinter - python 3 - clear the screen
39,726,998
<p>I went through the topics here at stack overflow, but could not understand anything. (yes, I've seen that the answer has been answered, but really couldnt understand.)</p> <p>So, here's the thing. I'm building small application that will pair couples from a group for a tournament we're having. I successfully built the algorithm that pair the players, and I've decided to make this a bit more approachable to everyone and started looking at ktinker.</p> <p>I've managed to get my application to show something like this:</p> <pre><code>Title info info info info info Button </code></pre> <p>The button suppose to re-run the whole thing (next round) and it works. I've managed to get it with the appropriate title, and even added a new button at the end of the screen. the only problem I'm having is that I want to get rid of all the text above. destroy it and just draw on a new page.</p> <p>Now, the code:</p> <pre><code>from tkinter import * root = Tk() root.title("Tournament") root.geomerty("50x180") app = Frame(root) app.grid() run_application() # my pairings #inside the code i'm pairing the players and then: for players in player_paired: label=Label(app, text=players[0]+' vs. '+players[1] # its a tuple label.grid() button=Button(app,text="Next Round", command=run_application) button.grid() #end of run_application root.mainloop() </code></pre> <p>So, I've tried adding to the beginning of my "run_application" the next rows:</p> <pre><code>app.destroy() app = Frame(root) app.grid() </code></pre> <p>and got "UnboundLocalError: local variable 'app' referenced before assignment"</p> <p>Would anyone help? i can't figure this out. (If able to write example, it would help a lot)</p> <p>Ofek.</p>
0
2016-09-27T14:12:28Z
39,727,805
<p>The simplest solution is to put everything you want to destroy in a frame, and then you can simply destroy and recreate the frame, or destroy all of the children in the frame. </p> <p>In your specific case, make the parent of <code>button</code> be <code>root</code>, and then you can destroy and recreate the contents of <code>app</code> each time you press the button.</p> <p>Here is an example. I took the liberty of switching the way you're importing, to be PEP8 compliant:</p> <pre><code>import tkinter as tk from random import shuffle participants = [ "Fred Flintstone", "Barney Rubble", "Wilma Flintstone", "Betty Rubble" ] def get_pairings(): '''for simulation purposes, this simply randomizes the participants''' global participants # see http://stackoverflow.com/a/23286332/7432 shuffle(participants) return zip(*[iter(participants)]*2) def reset(): '''Reset the list of participants''' for child in app.winfo_children(): child.destroy() for players in get_pairings(): label = tk.Label(app, text="%s vs. %s" % players) label.grid() root = tk.Tk() root.title("Tournament") app = tk.Frame(root) app.grid() button=tk.Button(root,text="Next Round", command=reset) button.grid() # this sets up the first round reset() root.mainloop() </code></pre>
0
2016-09-27T14:50:34Z
[ "python", "python-3.x", "tkinter" ]
tkinter - python 3 - clear the screen
39,726,998
<p>I went through the topics here at stack overflow, but could not understand anything. (yes, I've seen that the answer has been answered, but really couldnt understand.)</p> <p>So, here's the thing. I'm building small application that will pair couples from a group for a tournament we're having. I successfully built the algorithm that pair the players, and I've decided to make this a bit more approachable to everyone and started looking at ktinker.</p> <p>I've managed to get my application to show something like this:</p> <pre><code>Title info info info info info Button </code></pre> <p>The button suppose to re-run the whole thing (next round) and it works. I've managed to get it with the appropriate title, and even added a new button at the end of the screen. the only problem I'm having is that I want to get rid of all the text above. destroy it and just draw on a new page.</p> <p>Now, the code:</p> <pre><code>from tkinter import * root = Tk() root.title("Tournament") root.geomerty("50x180") app = Frame(root) app.grid() run_application() # my pairings #inside the code i'm pairing the players and then: for players in player_paired: label=Label(app, text=players[0]+' vs. '+players[1] # its a tuple label.grid() button=Button(app,text="Next Round", command=run_application) button.grid() #end of run_application root.mainloop() </code></pre> <p>So, I've tried adding to the beginning of my "run_application" the next rows:</p> <pre><code>app.destroy() app = Frame(root) app.grid() </code></pre> <p>and got "UnboundLocalError: local variable 'app' referenced before assignment"</p> <p>Would anyone help? i can't figure this out. (If able to write example, it would help a lot)</p> <p>Ofek.</p>
0
2016-09-27T14:12:28Z
39,733,470
<p>In my experience, I found it easier to delete the elements. Here is something you can do. I don't honestly have much time, so I will use examples from my code, instead of editing your code. </p> <p>So for your labels you could do this.</p> <pre><code>labels = [] for players in player_paired: label=Label(app, text=players[0]+' vs. '+players[1] # its a tuple label.grid() labels.append(label) </code></pre> <p>Then to remove the text have a method that does something like this.</p> <pre><code>for label in labels: label.destroy() </code></pre> <p>And then go back to the start after that.</p>
0
2016-09-27T20:10:04Z
[ "python", "python-3.x", "tkinter" ]
matplotlib 2D plot from x,y,z values
39,727,040
<p>I am a Python beginner.</p> <p>I have a list of X values </p> <pre><code>x_list = [-1,2,10,3] </code></pre> <p>and I have a list of Y values</p> <pre><code>y_list = [3,-3,4,7] </code></pre> <p>I then have a Z value for each couple. Schematically, this works like that:</p> <pre><code>X Y Z -1 3 5 2 -3 1 10 4 2.5 3 7 4.5 </code></pre> <p>and the Z values are stored in <code>z_list = [5,1,2.5,4.5]</code>. I need to get a 2D plot with the X values on the X axis, the Y values on the Y axis, and for each couple the Z value, represented by an intensity map. This is what I have tried, unsuccessfully:</p> <pre><code>X, Y = np.meshgrid(x_list, y_list) fig, ax = plt.subplots() extent = [x_list.min(), x_list.max(), y_list.min(), y_list.max()] im=plt.imshow(z_list, extent=extent, aspect = 'auto') plt.colorbar(im) plt.show() </code></pre> <p>How to get this done correctly?</p>
1
2016-09-27T14:14:10Z
39,727,937
<p>Here is one way of doing it:</p> <pre><code>import matplotlib.pyplot as plt import nupmy as np from matplotlib.colors import LogNorm x_list = np.array([-1,2,10,3]) y_list = np.array([3,-3,4,7]) z_list = np.array([5,1,2.5,4.5]) N = int(len(z_list)**.5) z = z_list.reshape(N, N) plt.imshow(z, extent=(np.amin(x_list), np.amax(x_list), np.amin(y_list), np.amax(y_list)), norm=LogNorm(), aspect = 'auto') plt.colorbar() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/WIIRd.png" rel="nofollow"><img src="http://i.stack.imgur.com/WIIRd.png" alt="enter image description here"></a></p> <p>I followed this link: <a href="http://stackoverflow.com/questions/24119920/how-to-plot-a-density-map-in-python">How to plot a density map in python?</a></p>
1
2016-09-27T14:56:49Z
[ "python", "matplotlib", "imshow" ]
matplotlib 2D plot from x,y,z values
39,727,040
<p>I am a Python beginner.</p> <p>I have a list of X values </p> <pre><code>x_list = [-1,2,10,3] </code></pre> <p>and I have a list of Y values</p> <pre><code>y_list = [3,-3,4,7] </code></pre> <p>I then have a Z value for each couple. Schematically, this works like that:</p> <pre><code>X Y Z -1 3 5 2 -3 1 10 4 2.5 3 7 4.5 </code></pre> <p>and the Z values are stored in <code>z_list = [5,1,2.5,4.5]</code>. I need to get a 2D plot with the X values on the X axis, the Y values on the Y axis, and for each couple the Z value, represented by an intensity map. This is what I have tried, unsuccessfully:</p> <pre><code>X, Y = np.meshgrid(x_list, y_list) fig, ax = plt.subplots() extent = [x_list.min(), x_list.max(), y_list.min(), y_list.max()] im=plt.imshow(z_list, extent=extent, aspect = 'auto') plt.colorbar(im) plt.show() </code></pre> <p>How to get this done correctly?</p>
1
2016-09-27T14:14:10Z
39,733,263
<p>The problem is that <code>imshow(z_list, ...)</code> will expect <code>z_list</code> to be an <code>(n,m)</code> type array, basically a grid of values. To use the imshow function, you need to have Z values for each grid point, which you can accomplish by collecting more data or interpolating. </p> <p>Here is an example, using your data with linear interpolation:</p> <pre><code>from scipy.interpolate import interp2d # f will be a function with two arguments (x and y coordinates), # but those can be array_like structures too, in which case the # result will be a matrix representing the values in the grid # specified by those arguments f = interp2d(x_list,y_list,z_list,kind="linear") x_coords = np.arange(min(x_list),max(x_list)+1) y_coords = np.arange(min(y_list),max(y_list)+1) Z = f(x_coords,y_coords) fig = plt.imshow(Z, extent=[min(x_list),max(x_list),min(y_list),max(y_list)], origin="lower") # Show the positions of the sample points, just to have some reference fig.axes.set_autoscale_on(False) plt.scatter(x_list,y_list,400,facecolors='none') </code></pre> <p><a href="http://i.stack.imgur.com/wtKLd.png" rel="nofollow"><img src="http://i.stack.imgur.com/wtKLd.png" alt="enter image description here"></a></p> <p>You can see that it displays the correct values at your sample points (specified by <code>x_list</code> and <code>y_list</code>, shown by the semicircles), but it has much bigger variation at other places, due to the nature of the interpolation and the small number of sample points.</p>
0
2016-09-27T19:57:25Z
[ "python", "matplotlib", "imshow" ]
Fetching all the strings in a python list of lists
39,727,065
<p>I have this list of lists</p> <pre><code>a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'ab normal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,' abnormal']] </code></pre> <p>I want to extract all the strings perse I have no idea what these strings might be, and count each string occurance. Is there a simple loop instruction to do that ? </p>
1
2016-09-27T14:15:04Z
39,727,253
<p>If you want to count the number of occurrences and keep track of the string, loop over each item and add it to a dictionary</p> <pre><code>a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal']] new={} for b in a: for item in b: if type(item) is str: if item in new: new[item]+=1 else: new[item]=1 print(new) </code></pre>
2
2016-09-27T14:23:13Z
[ "python", "list" ]
Fetching all the strings in a python list of lists
39,727,065
<p>I have this list of lists</p> <pre><code>a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'ab normal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,' abnormal']] </code></pre> <p>I want to extract all the strings perse I have no idea what these strings might be, and count each string occurance. Is there a simple loop instruction to do that ? </p>
1
2016-09-27T14:15:04Z
39,727,285
<p>I am not sure to have understood your question (word "perse" is unknown to me) If you want to count the occurence of strings normal and abnormal, I propose that:</p> <pre><code>from collections import Counter Counter([elt[4] for elt in a]) </code></pre> <p>Outputs:</p> <pre><code>Counter({'abnormal': 5, 'normal': 3}) </code></pre>
6
2016-09-27T14:24:58Z
[ "python", "list" ]
Fetching all the strings in a python list of lists
39,727,065
<p>I have this list of lists</p> <pre><code>a = [[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'normal'],[1,2,3,4,'ab normal'],[1,2,3,4,'normal'],[1,2,3,4,'abnormal'],[1,2,3,4,'abnormal'],[1,2,3,4,' abnormal']] </code></pre> <p>I want to extract all the strings perse I have no idea what these strings might be, and count each string occurance. Is there a simple loop instruction to do that ? </p>
1
2016-09-27T14:15:04Z
39,727,504
<p>Here is the solution: </p> <pre><code>count = 0 str_list = [] for arr in a: for ele in arr: if isinstance(ele, str): count += 1 str_list.append(ele) print count </code></pre> <p>The variable <code>count</code> holds the total number of strings in each list inside list a. While <code>str_list</code> will hold all strings</p> <p>Here is the code snippet on repl.it: <a href="https://repl.it/Di9L" rel="nofollow">https://repl.it/Di9L</a></p>
0
2016-09-27T14:35:03Z
[ "python", "list" ]
How to remove rows with duplicates in pandas dataframe?
39,727,129
<p>Having a dataframe which contains duplicate values in two columns (<code>A</code> and <code>B</code>):</p> <pre><code>A B 1 2 2 3 4 5 7 6 5 8 </code></pre> <p>I want to remove duplicates so that only unique values remain:</p> <pre><code>A B 1 2 4 5 7 6 </code></pre> <p>This command does not provide what I want:</p> <pre><code>df.drop_duplicates(subset=['A','B'], keep='first') </code></pre> <p>Any idea how to do this?</p>
1
2016-09-27T14:18:06Z
39,727,182
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a>:</p> <pre><code>print (df.stack().drop_duplicates().unstack().dropna().astype(int)) A B 0 1 2 2 4 5 3 7 6 </code></pre> <p>Solution with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p> <pre><code>print (df[~df.stack().duplicated().unstack().any(1)]) A B 0 1 2 2 4 5 3 7 6 </code></pre>
2
2016-09-27T14:20:10Z
[ "python", "pandas", "indexing", "duplicates", "multiple-columns" ]
How to enrich logging messages with request information in flask?
39,727,163
<p>I have a small Flask app that's used like a REST API that implements many methods like this:</p> <pre><code>@route('/do/something', methods=['POST']) def something(): app.logger.debug("got request to /do/something") result = something_implementation(request.json()) app.logger.debug("result was %s", str(result)) return flask.Response(result) </code></pre> <p>I would like to enrich these log messages automatically with information from the request object such as header information, parts of the body and whatever else is convenient. </p> <p>How do I do that in an elegant and pythonic way?</p> <p>Of course I could just wrap app.logger in my own function and pass the request object and the message along, but there's got to be a nicer and easier way I'm missing.</p>
1
2016-09-27T14:19:15Z
39,734,260
<p>I usually include something like this in my app.py file to log debug information for each request, along with handling standard errors:</p> <pre><code># Useful debugging interceptor to log all values posted to the endpoint @app.before_request def before(): values = 'values: ' if len(request.values) == 0: values += '(None)' for key in request.values: values += key + ': ' + request.values[key] + ', ' app.logger.debug(values) # Useful debugging interceptor to log all endpoint responses @app.after_request def after(response): app.logger.debug('response: ' + response.status + ', ' + response.data.decode('utf-8')) return response # Default handler for uncaught exceptions in the app @app.errorhandler(500) def internal_error(exception): app.logger.error(exception) return flask.make_response('server error', 500) # Default handler for all bad requests sent to the app @app.errorhandler(400) def handle_bad_request(e): app.logger.info('Bad request', e) return flask.make_response('bad request', 400)v </code></pre>
2
2016-09-27T21:02:27Z
[ "python", "logging", "flask" ]
How to enrich logging messages with request information in flask?
39,727,163
<p>I have a small Flask app that's used like a REST API that implements many methods like this:</p> <pre><code>@route('/do/something', methods=['POST']) def something(): app.logger.debug("got request to /do/something") result = something_implementation(request.json()) app.logger.debug("result was %s", str(result)) return flask.Response(result) </code></pre> <p>I would like to enrich these log messages automatically with information from the request object such as header information, parts of the body and whatever else is convenient. </p> <p>How do I do that in an elegant and pythonic way?</p> <p>Of course I could just wrap app.logger in my own function and pass the request object and the message along, but there's got to be a nicer and easier way I'm missing.</p>
1
2016-09-27T14:19:15Z
39,754,458
<p>I have solved this by subclassing <code>logging.Filter</code> and adding it to my handler.</p> <p>Something like this:</p> <pre><code>class ContextFilter(logging.Filter): '''Enhances log messages with contextual information''' def filter(self, record): try: record.rid = request.rid except RuntimeError as exc: if str(exc.message) == 'working outside of request context': record.rid = '' else: raise exc return True </code></pre> <p>The try/except clause is necessary for log messages outside of a request context to work. And then use it like this:</p> <pre><code>fileHandler = RotatingFileHandler(app.config['LOGFILE'], maxBytes=20971520, backupCount=5, encoding='utf-8') fileHandler.setLevel(logging.DEBUG) fileHandler.addFilter(ContextFilter()) filefmt = '%(asctime)s [%(filename)s:%(lineno)d] %(rid)s: %(message)s' fileFormatter = logging.Formatter(filefmt) fileHandler.setFormatter(fileFormatter) app.logger.addHandler(fileHandler) </code></pre> <p>In the future I can add more fields in the <code>ContextFilter.filter()</code> method and use them however I please in the formatter configuration.</p>
0
2016-09-28T17:52:28Z
[ "python", "logging", "flask" ]
Accessing object from list comprehensive search in Python
39,727,190
<p>I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.</p> <p>Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.</p> <p>This bit works</p> <pre><code>class Employee(): def __init__(self, name, age, favoriteFood): self.name = name self.age = age self.favoriteFood = favoriteFood def __repr__(self): return "Employee {0}".format(self.name) employee1 = Employee('John', 28, 'Pizza') employee2 = Employee('Kate', 27, 'Sandwiches') myList = [employee1, employee2] a = 'Sandwiches' b = 'Tuna Mayo Sandwich' matchingEmployee = [x for x in myList if x.favoriteFood == a] print matchingEmployee </code></pre> <p>This prints 'Employee Kate' from the class <strong>repr</strong></p> <p>The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.</p> <p>I was hoping to do something like </p> <pre><code>matchingEmployee.food = b </code></pre> <p>But this doesn't create a new variable in that object and give it the value b. </p> <p>Any help would be greatly received. </p>
0
2016-09-27T14:20:26Z
39,727,374
<p>Since the variable matchingEmployee is a list, and in the given context, Kate is the first in the list, you can do : </p> <pre><code>matchingEmployee[0].food = b </code></pre>
0
2016-09-27T14:29:45Z
[ "python" ]
Accessing object from list comprehensive search in Python
39,727,190
<p>I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.</p> <p>Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.</p> <p>This bit works</p> <pre><code>class Employee(): def __init__(self, name, age, favoriteFood): self.name = name self.age = age self.favoriteFood = favoriteFood def __repr__(self): return "Employee {0}".format(self.name) employee1 = Employee('John', 28, 'Pizza') employee2 = Employee('Kate', 27, 'Sandwiches') myList = [employee1, employee2] a = 'Sandwiches' b = 'Tuna Mayo Sandwich' matchingEmployee = [x for x in myList if x.favoriteFood == a] print matchingEmployee </code></pre> <p>This prints 'Employee Kate' from the class <strong>repr</strong></p> <p>The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.</p> <p>I was hoping to do something like </p> <pre><code>matchingEmployee.food = b </code></pre> <p>But this doesn't create a new variable in that object and give it the value b. </p> <p>Any help would be greatly received. </p>
0
2016-09-27T14:20:26Z
39,727,458
<p>As I've learnt that the list comprehensive produces a list (stupid as that might sound :) ) I've added a for loop to iterate over the matchingEmployee list to give the sandwich to whoever wants it.</p> <pre><code>if matchingEmployee: print 'Employee(s) found' for o in matchingEmployee: o.food = b </code></pre> <p>Thanks</p>
1
2016-09-27T14:33:32Z
[ "python" ]
Accessing object from list comprehensive search in Python
39,727,190
<p>I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.</p> <p>Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.</p> <p>This bit works</p> <pre><code>class Employee(): def __init__(self, name, age, favoriteFood): self.name = name self.age = age self.favoriteFood = favoriteFood def __repr__(self): return "Employee {0}".format(self.name) employee1 = Employee('John', 28, 'Pizza') employee2 = Employee('Kate', 27, 'Sandwiches') myList = [employee1, employee2] a = 'Sandwiches' b = 'Tuna Mayo Sandwich' matchingEmployee = [x for x in myList if x.favoriteFood == a] print matchingEmployee </code></pre> <p>This prints 'Employee Kate' from the class <strong>repr</strong></p> <p>The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.</p> <p>I was hoping to do something like </p> <pre><code>matchingEmployee.food = b </code></pre> <p>But this doesn't create a new variable in that object and give it the value b. </p> <p>Any help would be greatly received. </p>
0
2016-09-27T14:20:26Z
39,727,469
<p>If you want to append food to each employee that matched your filter you'd need to loop through the matchingEmployee list. For example:</p> <pre><code>for employee in matchingEmployee: employee.food = b </code></pre>
0
2016-09-27T14:33:47Z
[ "python" ]
Accessing object from list comprehensive search in Python
39,727,190
<p>I am using a list comprehensive 'search' to match objects of my employee class. I then want to assign a value to them based on who matched the search.</p> <p>Basically the code equivalent of asking who likes sandwiches and then giving that person a sandwich.</p> <p>This bit works</p> <pre><code>class Employee(): def __init__(self, name, age, favoriteFood): self.name = name self.age = age self.favoriteFood = favoriteFood def __repr__(self): return "Employee {0}".format(self.name) employee1 = Employee('John', 28, 'Pizza') employee2 = Employee('Kate', 27, 'Sandwiches') myList = [employee1, employee2] a = 'Sandwiches' b = 'Tuna Mayo Sandwich' matchingEmployee = [x for x in myList if x.favoriteFood == a] print matchingEmployee </code></pre> <p>This prints 'Employee Kate' from the class <strong>repr</strong></p> <p>The bit I'm stuck on is now giving Kate the Tuna Mayo Sandwich, value b.</p> <p>I was hoping to do something like </p> <pre><code>matchingEmployee.food = b </code></pre> <p>But this doesn't create a new variable in that object and give it the value b. </p> <p>Any help would be greatly received. </p>
0
2016-09-27T14:20:26Z
39,727,568
<p>Use the command line python to write a simplified expression:</p> <pre><code>[ y for y in [1,2,3,4] if y %2 ==0] </code></pre> <p>You will see that it results in a list output</p> <pre><code>[2, 4] </code></pre> <p>Your "matchingEmployee" is actually a list of matching employees. So to "give a sandwich" to the first employee found (assuming there is one):</p> <pre><code>matchingEmployee[0].food = b </code></pre> <p>To "give a sandwich" to the list of employees:</p> <pre><code>for employee in matchingEmployee: employee.food = b </code></pre>
0
2016-09-27T14:37:39Z
[ "python" ]
Creating a blog with Flask
39,727,227
<p>I'm learning flask and I have a little problem. I made an index template, where are blog post titles.</p> <pre><code>{% for title in titles %} &lt;!-- Main Content --&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"&gt; &lt;div class="post-preview"&gt; &lt;a href="{{ url_for('post')}}"&gt; &lt;h2 class="post-title"&gt; {{ title[0] }} &lt;/h2&gt; &lt;/a&gt; &lt;p class="post-meta"&gt;Posted by &lt;a href="#"&gt;{{ author }}&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} </code></pre> <p>Here is part of my post.html template.</p> <pre><code>&lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"&gt; &lt;p&gt;{{ post_text1 | safe }}&lt;/p&gt; &lt;hr&gt; &lt;div class="alert alert-info" role="alert"&gt;Posted by &lt;a href="#" class="alert-link"&gt;{{ author }}&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I'm using sqlite3. Currently every title leads to same post.html where is first text from first post. How to make every title direct to their post text? I mean, if I click on the first title it should bring up post.html and there should be first text. Second title should show second text. Should I write program, that creates new html for every post or is there any other way?</p> <pre><code>@app.route('/') def index(): db = connect_db() titles = db.execute('select title from entries') titles = titles.fetchall() author = db.execute('select author from entries order by id desc') author = author.fetchone() return render_template('index.html', titles=titles[:], author=author[0]) @app.route('/post/') def post(): db = connect_db() post_text1 = db.execute('select post_text from entries') post_text1 = post_text1.fetchone() author = db.execute('select author from entries where id=2') author = author.fetchone() return render_template('post.html', post_text1=post_text1[0], author=author[0]) </code></pre>
0
2016-09-27T14:22:01Z
39,728,532
<p>The problem comes from here <code>&lt;a href="{{ url_for('post')}}"&gt;</code>.</p> <p>What this tells Flask is to make a url for post, which is something you have defined in views as <code>def post(argument)</code> but you are not providing an argument. So if for example you are making you are taking your posts based on id, your view would would ask for <code>/&lt;int:post_id&gt;/</code> in url and <code>post_id</code> would be passed as an argument based on which you would find the specific post and pass that to the template. </p> <p>Your <code>url_for</code> should reflect this, you should have <code>{{ url_for('post', post_id=title[1]) }}</code> or wherever you are storing your equivalent of post_id (maybe that's title for you).</p> <p>Edit:</p> <p>Baed on your edit, your problem is that you are not telling Flask which post to fetch. You need either ID, or slug, or something that will go in the url and will tell you which post you are looking for. Your function right now is static and is always fetching the first entry in your database. The changes required are:</p> <pre><code>@app.route('/') def index(): db = connect_db() titles = db.execute('select title, id from entries') titles = titles.fetchall() author = db.execute('select author from entries order by id desc') author = author.fetchone() return render_template('index.html', titles=titles, author=author[0]) @app.route('/post/&lt;int:post_id&gt;/') def post(post_id): db = connect_db() post_text = db.execute('select post_text from entries where id = ?', post_id) post_text = post_text1.fetchone() author = db.execute('select author from entries where id=2') author = author.fetchone() return render_template('post.html', post_text1=post_text, author=author) &lt;a href="{{ url_for('post', post_id=title[1])}}"&gt; </code></pre> <p>Also your author fetching is weird, you should have them stored (at least their ids) next to entries. Then I'd recomend some naming changes etc. It's hard to just answer the question and not write the code for you, as this is a site for answering specific questions, not writing code on demand :) Try to understand what I wrote here, play around with it a bit more etc. to fully undnerstand.</p> <p>tl;dr: Posts have to get an argument and then fetch a post identified by that argument, the program can't magically tell which post you clicked on.</p>
3
2016-09-27T15:24:08Z
[ "python", "html", "flask" ]
How to take multiple values from a python list?
39,727,252
<p>I am creating a program that takes user input stores it in a list and then multiplies by either 5 or 1 alternating between each number. eg the first value is multiplied by 5 and the next 1 and so on. I want to remove all the values that i would multiply by 5 and add them to a separate list. How would this be done? </p> <pre><code>list1=[1,2,3,4] list2=List1[???] </code></pre>
-1
2016-09-27T14:23:10Z
39,727,289
<p>To get every other element, you could use a slice with a stride of two:</p> <pre><code>&gt;&gt;&gt; list1 = [1,2,3,4] &gt;&gt;&gt; list2 = list1[::2] &gt;&gt;&gt; list2 [1, 3] </code></pre> <p>You can use a similar technique to get the remaining elements:</p> <pre><code>&gt;&gt;&gt; list3 = list1[1::2] &gt;&gt;&gt; list3 [2, 4] </code></pre> <p>For further information, see <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">Explain Python&#39;s slice notation</a></p>
0
2016-09-27T14:25:02Z
[ "python" ]
How to take multiple values from a python list?
39,727,252
<p>I am creating a program that takes user input stores it in a list and then multiplies by either 5 or 1 alternating between each number. eg the first value is multiplied by 5 and the next 1 and so on. I want to remove all the values that i would multiply by 5 and add them to a separate list. How would this be done? </p> <pre><code>list1=[1,2,3,4] list2=List1[???] </code></pre>
-1
2016-09-27T14:23:10Z
39,727,485
<p>Here you go:</p> <pre><code>list1=[1,2,3,4] list2 = [i*5 for i in list1[1::2]] </code></pre> <p>Two methods are used here <a href="https://docs.python.org/2.3/whatsnew/section-slices.html" rel="nofollow">slicing</a> and <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>.</p>
0
2016-09-27T14:34:20Z
[ "python" ]
Pandas: aggregate data through the dataframe
39,727,271
<p>I have dataframe:</p> <pre><code>ID,"url","app_name","used_at","active_seconds","device_connection","device_os","device_type","device_usage" 1ca9bb884462c3ba2391bf669c22d4bd,"",VK Client,2016-01-01 00:00:13,5,3g,ios,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",VKontakte,2016-01-01 00:01:45,107,wifi,android,smartphone,home 1ca9bb884462c3ba2391bf669c22d4bd,"",Twitter,2016-01-01 00:02:48,20,3g,ios,smartphone,home 1ca9bb884462c3ba2391bf669c22d4bd,"",VK Client,2016-01-01 00:03:08,796,3g,ios,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",WhatsApp Messenger,2016-01-01 00:03:32,70,wifi,android,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",VKontakte,2016-01-01 00:04:42,27,wifi,android,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",VKontakte,2016-01-01 00:05:30,5,wifi,android,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",WhatsApp Messenger,2016-01-01 00:05:36,47,wifi,android,smartphone,home b8f4df3f99ad786a77897c583d98f615,"",VKontakte,2016-01-01 00:06:23,20,wifi,android,smartphone,home a703114aa8a03495c3e042647212fa63,"",Instagram,2016-01-01 00:06:41,118,3g,android,smartphone,home 1637ce5a4c4868e694004528c642d0ac,"",Camera,2016-01-01 00:06:43,16,wifi,android,smartphone,home 1637ce5a4c4868e694004528c642d0ac,"",VKontakte,2016-01-01 00:07:00,45,wifi,android,smartphone,home a703114aa8a03495c3e042647212fa63,"",VKontakte,2016-01-01 00:08:40,99,3g,android,smartphone,home 1637ce5a4c4868e694004528c642d0ac,"",VKontakte,2016-01-01 00:10:05,1,wifi,android,smartphone,home </code></pre> <p>I need to count share of every <code>app_name</code> to every <code>ID</code>. But I can't do next: sum of every app to every id I should divide to sum of all app to id and next multiple 100. (to find percent) I do:</p> <pre><code>short = df.groupby(['ID', 'app_name']).agg({'app_name': len, 'active_seconds': sum}).rename(columns={'active_seconds': 'count_sec', 'app_name': 'sum_app'}).reset_index() </code></pre> <p>but it only returns quantity to every app, when I try</p> <pre><code>short = df.groupby(['ID', 'app_name']).agg({'app_name': len, 'active_seconds': sum / df.ID.app_name.sum() * 100}).rename(columns={'active_seconds': 'count_sec', 'app_name': 'sum_app'}).reset_index() </code></pre> <p>it returns an error</p> <p>How can I fix that?</p>
2
2016-09-27T14:24:05Z
39,727,473
<p>IIUC you need:</p> <pre><code>short = df.groupby(['ID', 'app_name']) .agg({'app_name': len, 'active_seconds': lambda x: 100 * x.sum() / df.active_seconds.sum()}) .rename(columns={'active_seconds': 'count_sec', 'app_name': 'sum_app'}) .reset_index() print (short) ID app_name count_sec sum_app 0 1637ce5a4c4868e694004528c642d0ac Camera 1.162791 1 1 1637ce5a4c4868e694004528c642d0ac VKontakte 3.343023 2 2 1ca9bb884462c3ba2391bf669c22d4bd Twitter 1.453488 1 3 1ca9bb884462c3ba2391bf669c22d4bd VK Client 58.212209 2 4 a703114aa8a03495c3e042647212fa63 Instagram 8.575581 1 5 a703114aa8a03495c3e042647212fa63 VKontakte 7.194767 1 6 b8f4df3f99ad786a77897c583d98f615 VKontakte 11.555233 4 7 b8f4df3f99ad786a77897c583d98f615 WhatsApp Messenger 8.502907 2 </code></pre> <p>Another solution:</p> <pre><code>#you need another name of df, e.g. short1 short1 = df.groupby(['ID', 'app_name']) .agg({'app_name': len, 'active_seconds': sum}) .rename(columns={'active_seconds': 'count_sec', 'app_name': 'sum_app'}) .reset_index() short1.count_sec = 100 * short1.count_sec / df.active_seconds.sum() print (short1) ID app_name count_sec sum_app 0 1637ce5a4c4868e694004528c642d0ac Camera 1.162791 1 1 1637ce5a4c4868e694004528c642d0ac VKontakte 3.343023 2 2 1ca9bb884462c3ba2391bf669c22d4bd Twitter 1.453488 1 3 1ca9bb884462c3ba2391bf669c22d4bd VK Client 58.212209 2 4 a703114aa8a03495c3e042647212fa63 Instagram 8.575581 1 5 a703114aa8a03495c3e042647212fa63 VKontakte 7.194767 1 6 b8f4df3f99ad786a77897c583d98f615 VKontakte 11.555233 4 7 b8f4df3f99ad786a77897c583d98f615 WhatsApp Messenger 8.502907 2 </code></pre>
3
2016-09-27T14:34:02Z
[ "python", "pandas", "group-by", "sum", "aggregate" ]
Wrapping individual function calls in Python
39,727,321
<p>I'm writing a script that requests some data from an IMAP server using the <code>imaplib</code> library. Having initiated a connection (<code>c</code>), I make the following calls:</p> <pre><code>rv, data = c.login(EMAIL_ACCOUNT, EMAIL_PASS) if rv != 'OK': print('login error') else: print(rv, data) rv, mailboxes = c.list() if rv != 'OK': print('mailbox error') else: print(rv, data) rv, data = c.select(EMAIL_FOLDER) if rv != 'OK': print('folder error') else: print(rv, data) </code></pre> <p>How could I rewrite this to use some sort of a wrapper function to reuse the logic of checking the error code and printing the data? I assume the function would take an error message as an argument and also the command to execute (<code>select</code>, <code>login</code>, etc.). How could I call a select connection function by passing it's name in an argument?</p>
1
2016-09-27T14:26:36Z
39,727,494
<p>To re-use any code, look at the things that stay the same (e.g. the fact that <code>rv</code> and <code>data</code> come out of your <code>imaplib</code> calls in that order, and that <code>rv=='OK'</code> means things are OK) and write the logic that involves them, once. Then look at the things that change (e.g. the exact error message that needs to be printed). Parameterize the things that change, as in this example where the <code>description</code> argument changes the error message:</p> <pre><code>def check(description, rvdata): rv, data = rvdata if rv == 'OK': print(data) return data else: print(description + ' error') return None data = check('login', c.login(EMAIL_ACCOUNT, EMAIL_PASS)) mailboxes = check('mailbox', c.list()) selection = check('folder', c.select(EMAIL_FOLDER)) </code></pre>
1
2016-09-27T14:34:43Z
[ "python", "imaplib" ]
Wrapping individual function calls in Python
39,727,321
<p>I'm writing a script that requests some data from an IMAP server using the <code>imaplib</code> library. Having initiated a connection (<code>c</code>), I make the following calls:</p> <pre><code>rv, data = c.login(EMAIL_ACCOUNT, EMAIL_PASS) if rv != 'OK': print('login error') else: print(rv, data) rv, mailboxes = c.list() if rv != 'OK': print('mailbox error') else: print(rv, data) rv, data = c.select(EMAIL_FOLDER) if rv != 'OK': print('folder error') else: print(rv, data) </code></pre> <p>How could I rewrite this to use some sort of a wrapper function to reuse the logic of checking the error code and printing the data? I assume the function would take an error message as an argument and also the command to execute (<code>select</code>, <code>login</code>, etc.). How could I call a select connection function by passing it's name in an argument?</p>
1
2016-09-27T14:26:36Z
39,727,666
<p>The way I understood you would like to check Decorators for your task. </p> <pre><code>class Wrapper: def __init__(self, error_message): self.error_message = error_message def __call__(self, wrapped): def func(*args, **kwargs): rv, data = wrapped(*args, **kwargs) if rv=="OK": return(rv, data) else: print(self.error_message) return(rv, data) return func @Wrapper("Folder Error") def select(email_folder): return "OK", "OLOLO" @Wrapper("Folder Error") def select_err(email_folder): return "FAIL", "OLOLO" print select("") print select_err("") </code></pre> <p>yields </p> <pre><code>('OK', 'OLOLO') Folder Error ('FAIL', 'OLOLO') </code></pre> <p>You can check reply inside of Wrapper's <code>__call__</code> function and treat it the way you want to. For exampl you can return "False" or raise errors if <code>rv</code> not equals to "OK"</p> <p>But It might be overly complicated for your case. </p>
2
2016-09-27T14:42:16Z
[ "python", "imaplib" ]
Center non-editable QComboBox Text with PyQt
39,727,416
<p>Is it possible to change the text alignment of a QComboBox that is not not editable? This answer achieves this by making the QComboBox editable</p> <p><a href="http://stackoverflow.com/questions/23770287/how-to-center-text-in-qcombobox">How to center text in QComboBox?</a></p> <p>However, I don't want that because with that change, the clickable part of the ComboBox to trigger the list is now only the arrow on the right, whereas before the entire area was clickable and triggers the drop down menu.</p>
1
2016-09-27T14:31:18Z
39,754,285
<p>The answer is partly already given in the linked question <a href="http://stackoverflow.com/questions/23770287/how-to-center-text-in-qcombobox">How to center text in QComboBox?</a> What remains is to make the read-only object clickable. This can be done as suggested <a href="https://wiki.python.org/moin/PyQt/Making%20non-clickable%20widgets%20clickable" rel="nofollow">here</a>. ...giving you the following code:</p> <pre><code>from PyQt4 import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) layout = QtGui.QVBoxLayout(self) self.combo = QtGui.QComboBox() self.combo.setEditable(True) self.ledit = self.combo.lineEdit() self.ledit.setAlignment(QtCore.Qt.AlignCenter) # as suggested in the comment to # http://stackoverflow.com/questions/23770287/how-to-center-text-in-qcombobox self.ledit.setReadOnly(True) # self.combo.addItems('One Two Three Four Five'.split()) layout.addWidget(self.combo) self.clickable(self.combo).connect(self.combo.showPopup) self.clickable(self.ledit).connect(self.combo.showPopup) def clickable(self,widget): """ class taken from https://wiki.python.org/moin/PyQt/Making%20non-clickable%20widgets%20clickable """ class Filter(QtCore.QObject): clicked = QtCore.pyqtSignal() def eventFilter(self, obj, event): if obj == widget: if event.type() == QtCore.QEvent.MouseButtonRelease: if obj.rect().contains(event.pos()): self.clicked.emit() # The developer can opt for .emit(obj) to get the object within the slot. return True return False filter = Filter(widget) widget.installEventFilter(filter) return filter.clicked if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window() window.show() sys.exit(app.exec_()) </code></pre>
1
2016-09-28T17:41:08Z
[ "python", "css", "pyqt" ]
The argument is entered as a list (ie. [4,5,6]). But how can I get the output as a list and not just integers
39,727,653
<p>The output I was getting was just integers (ie. 2,6,9). Desired output was a list (ie. [2,6,9] ). </p> <pre><code>def multiplyNums(aList): for (i,j) in enumerate(aList): newList = [] if i &lt; (len(aList)-1): newList = (aList[i] * aList[i+1]) x = print(newList,end=',') else: newList = (aList[i] * aList[i]) x = print(newList) return x </code></pre>
-2
2016-09-27T14:41:45Z
39,727,776
<p>Is it that you would like to produce a list which contains the value of each entry multiplied by the following value (and the last value squared)?</p> <p>ie. [2,3,4] -> [2*3, 3*4, 4*4] ?</p> <p>If so then I think you should probably do:</p> <pre><code>def multiplyNums(aList): newList = [] for (i,j) in enumerate(aList): if i &lt; (len(aList)-1): newList.append(aList[i] * aList[i+1]) else: newList.append(aList[i] * aList[i]) return newList print multiplyNums( [2, 3, 4] ) </code></pre> <p>Here is a funny single line list comprehension:</p> <pre><code>def multiplyNums(a): return [x[0]*x[1] for x in zip(a,a[1:]+[a[-1]])] </code></pre>
1
2016-09-27T14:48:37Z
[ "python", "list" ]
The argument is entered as a list (ie. [4,5,6]). But how can I get the output as a list and not just integers
39,727,653
<p>The output I was getting was just integers (ie. 2,6,9). Desired output was a list (ie. [2,6,9] ). </p> <pre><code>def multiplyNums(aList): for (i,j) in enumerate(aList): newList = [] if i &lt; (len(aList)-1): newList = (aList[i] * aList[i+1]) x = print(newList,end=',') else: newList = (aList[i] * aList[i]) x = print(newList) return x </code></pre>
-2
2016-09-27T14:41:45Z
39,728,086
<p>A cleaner way to do this would be :</p> <pre><code>def multiplySuccessor(aList): newList = [] for i in range(len(aList)-1): newList.append(aList[i] * aList[i+1]) newList.append(aList[len(aList)-1]**2) return newList </code></pre>
1
2016-09-27T15:03:35Z
[ "python", "list" ]
Why is the computing of the value of pi using the Machin Formula giving a wrong value?
39,727,689
<p>For my school project I was trying to compute the value of using different methods. One of the formula I found was the Machin Formula that can be calculated using the Taylor expansion of arctan(x). </p> <p>I wrote the following code in python:</p> <pre><code>import decimal count = pi = a = b = c = d = val1 = val2 = decimal.Decimal(0) #Initializing the variables decimal.getcontext().prec = 25 #Setting percision while (decimal.Decimal(count) &lt;= decimal.Decimal(100)): a = pow(decimal.Decimal(-1), decimal.Decimal(count)) b = ((decimal.Decimal(2) * decimal.Decimal(count)) + decimal.Decimal(1)) c = pow(decimal.Decimal(1/5), decimal.Decimal(b)) d = (decimal.Decimal(a) / decimal.Decimal(b)) * decimal.Decimal(c) val1 = decimal.Decimal(val1) + decimal.Decimal(d) count = decimal.Decimal(count) + decimal.Decimal(1) #The series has been divided into multiple small parts to reduce confusion count = a = b = c = d = decimal.Decimal(0) #Resetting the variables while (decimal.Decimal(count) &lt;= decimal.Decimal(10)): a = pow(decimal.Decimal(-1), decimal.Decimal(count)) b = ((decimal.Decimal(2) * decimal.Decimal(count)) + decimal.Decimal(1)) c = pow(decimal.Decimal(1/239), decimal.Decimal(b)) d = (decimal.Decimal(a) / decimal.Decimal(b)) * decimal.Decimal(c) val2 = decimal.Decimal(val2) + decimal.Decimal(d) count = decimal.Decimal(count) + decimal.Decimal(1) #The series has been divided into multiple small parts to reduce confusion pi = (decimal.Decimal(16) * decimal.Decimal(val1)) - (decimal.Decimal(4) * decimal.Decimal(val2)) print(pi) </code></pre> <p>The problem is that I am getting the right value of pi only till 15 decimal places, no matter the number of times the loop repeats itself.</p> <p>For example:</p> <p>at 11 repetitions of the first loop</p> <p>pi = 3.141592653589793408632493</p> <p>at 100 repetitions of the first loop</p> <p>pi = 3.141592653589793410703296</p> <p>I am not increasing the repetitions of the second loop as arctan(1/239) is very small and reaches an extremely small value with a few repetitions and therefore should not affect the value of pi at only 15 decimal places.</p> <p>EXTRA INFORMATION:</p> <p>The Machin Formula states that:</p> <pre><code> π = (16 * Summation of (((-1)^n) / 2n+1) * ((1/5)^(2n+1))) - (4 * Summation of (((-1)^n) / 2n+1) * ((1/239)^(2n+1))) </code></pre>
2
2016-09-27T14:43:00Z
39,728,029
<p>That many terms is enough to get you over 50 decimal places. The problem is that you are mixing Python floats with Decimals, so your calculations are polluted with the errors in those floats, which are only precise to 53 bits (around 15 decimal digits).</p> <p>You can fix that by changing </p> <pre><code>c = pow(decimal.Decimal(1/5), decimal.Decimal(b)) </code></pre> <p>to </p> <pre><code>c = pow(1 / decimal.Decimal(5), decimal.Decimal(b)) </code></pre> <p>or</p> <pre><code>c = pow(decimal.Decimal(5), decimal.Decimal(-b)) </code></pre> <p>Obviously, a similar change needs to be made to </p> <pre><code>c = pow(decimal.Decimal(1/239), decimal.Decimal(b)) </code></pre> <hr> <p>You could make your code a <em>lot</em> more readable. For starters, you should put the stuff that calculates the arctan series into a function, rather than duplicating it for arctan(1/5) and arctan(1/239).</p> <p>Also, you don't need to use Decimal for <em>everything</em>. You can just use simple Python integers for things like <code>count</code> and <code>a</code>. Eg, your calculation for <code>a</code> can be written as</p> <pre><code>a = (-1) ** count </code></pre> <p>or you could just set <code>a</code> to 1 outside the loop and negate it each time through the loop.</p> <p>Here's a more compact version of your code.</p> <pre><code>import decimal decimal.getcontext().prec = 60 #Setting precision def arccot(n, terms): base = 1 / decimal.Decimal(n) result = 0 sign = 1 for b in range(1, 2*terms, 2): result += sign * (base ** b) / b sign = -sign return result pi = 16 * arccot(5, 50) - 4 * arccot(239, 11) print(pi) </code></pre> <p><strong>output</strong></p> <pre><code>3.14159265358979323846264338327950288419716939937510582094048 </code></pre> <p>The last 4 digits are rubbish, but the rest are fine.</p>
4
2016-09-27T15:00:52Z
[ "python", "math", "pi" ]
Python - Filename validation help needed
39,727,720
<p>Bad Filename Example: <code>foo is-not_bar-3.mp4</code> What it should be: <code>foo_is_not_bar-3.mp4</code></p> <p>I only want to keep a <code>-</code> for the last bit of the string if it is a digit followed by the extension. The closest I have gotten thus far is with the following code:</p> <pre><code>fname = 'foo is-not_bar-3.mp4' valchars = '-_. %s%s' % (string.ascii_letters, string.digits) f = ''.join(c for c in fname if c in valchars).replace(' ', '_').replace('-', '_') </code></pre>
0
2016-09-27T14:45:06Z
39,727,897
<p>You can use regex replacement with a negative lookahead:</p> <pre><code>import re fname = 'foo is-not_bar-3.mp4' f = re.sub(r'\s|-(?!\d+)', '_', fname) print(f) &gt;&gt; 'foo_is_not_bar-3.mp4' </code></pre> <p>This will replace every <code>-</code> and space with <code>_</code> <strong>unless</strong> it is followed by a number.</p>
1
2016-09-27T14:54:49Z
[ "python" ]
Keyword Not Passing in Function
39,727,876
<p>I am working with django models. I want to pass a model field as a variable. Given my function:</p> <pre><code>from django.models import models def updatetable(value, fieldtitle, tablename, uid, refname): workingobj = tablename.objects.get(refname=uid) currentvalue = getattr(workingobj, fieldtitle) setattr(workingobj, fieldtitle, currentvalue + value) workingobj.save() return </code></pre> <p>I have tried:</p> <pre><code>updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname=update_dtg_start) updatetable(len(sr), 'posts_added', managementmetrics, startdtg, refname='update_dtg_start') </code></pre> <p>and even</p> <pre><code>updatetable(len(sr), 'posts_added', managementmetrics, startdtg, {refname:update_dtg_start}) </code></pre> <p>I get the error: Cannot resolve keyword 'refname' into field. Choices are: length_of_update, update_dtg_finish, update_dtg_start</p> <p>I've tried switching out refname for **kwargs but still can't seem to get it to take the field value. </p>
0
2016-09-27T14:53:54Z
39,727,950
<p>The problem is not in how you call this function: the function itself does not do what you want.</p> <p>You need to change how you call <code>get</code>. Rather than passing in refname directly, you need to use the dict <em>there</em>:</p> <pre><code>workingobj = tablename.objects.get(**{refname: uid}) </code></pre> <p>Now you simply call the function in the normal way:</p> <pre><code>updatetable(len(sr), 'posts_added', managementmetrics, startdtg, 'update_dtg_start') </code></pre> <p>(You should also consider renaming the <code>tablename</code> parameter: you are not passing a table name, which implies a string, but a model class object.)</p>
0
2016-09-27T14:57:19Z
[ "python", "django", "django-models", "keyword" ]
Printing the current minute in a loop with python
39,727,910
<p>I'm using python 3 and trying to create a script that runs constantly, and at some time, execute a specific code. The code i have so far, verifies the current minute, and if it's above a given minute, it print's a message, otherwise, it prints the current minute and waits 5 seconds and try again. The problem is that it only prints the minute the code started.</p> <pre><code>import time from datetime import datetime now = datetime.now() hour = now.hour minute = now.minute L=1 while (L == 1): if minute &gt; 39: print ("It's past "+str(hour)+":"+str(minute)) L = 2 else: print(str(minute)) time.sleep(5) </code></pre>
-2
2016-09-27T14:55:22Z
39,727,995
<p>you have to insert the assigments</p> <pre><code>now = datetime.now() hour = now.hour minute = now.minute </code></pre> <p>inside the while loop, or they'll not be refreshed</p>
0
2016-09-27T14:59:19Z
[ "python" ]
Printing the current minute in a loop with python
39,727,910
<p>I'm using python 3 and trying to create a script that runs constantly, and at some time, execute a specific code. The code i have so far, verifies the current minute, and if it's above a given minute, it print's a message, otherwise, it prints the current minute and waits 5 seconds and try again. The problem is that it only prints the minute the code started.</p> <pre><code>import time from datetime import datetime now = datetime.now() hour = now.hour minute = now.minute L=1 while (L == 1): if minute &gt; 39: print ("It's past "+str(hour)+":"+str(minute)) L = 2 else: print(str(minute)) time.sleep(5) </code></pre>
-2
2016-09-27T14:55:22Z
39,728,315
<p>You need to refresh the value of the <code>now</code> variable in every step of the loop. Also, I removed unncessary variable <code>L</code> and replaced it with <code>while True</code> to make the code nicer.</p> <pre><code>import time from datetime import datetime while True: now = datetime.now() if now.minute &gt; 39: print ("It's past "+str(hour)+":"+str(minute)) # Run your desired code here. else: print(str(minute)) time.sleep(5) </code></pre>
0
2016-09-27T15:13:53Z
[ "python" ]
Printing the current minute in a loop with python
39,727,910
<p>I'm using python 3 and trying to create a script that runs constantly, and at some time, execute a specific code. The code i have so far, verifies the current minute, and if it's above a given minute, it print's a message, otherwise, it prints the current minute and waits 5 seconds and try again. The problem is that it only prints the minute the code started.</p> <pre><code>import time from datetime import datetime now = datetime.now() hour = now.hour minute = now.minute L=1 while (L == 1): if minute &gt; 39: print ("It's past "+str(hour)+":"+str(minute)) L = 2 else: print(str(minute)) time.sleep(5) </code></pre>
-2
2016-09-27T14:55:22Z
39,728,376
<p>Some programming pointers: </p> <p>1) To make a constant loop use the following construct:</p> <pre><code>while (True): if (...): .... break </code></pre> <p>2) The time stored in your "now" variable is static must be updated with the new time within the loop:</p> <pre><code>while (True): now = datetime.now() </code></pre> <p>So:</p> <pre><code>while True: now = datetime.now() if now.minute &gt; 39: print "Hour, Minute:", now.hour, now.minute print "All done!" break else: print ""Minute, second:", now.minute, now.second time.sleep(5) </code></pre> <p>3) In "real life" (TM) calculate the time you want to wait until your event and sleep that long.</p> <pre><code>now = time.now() if now.minute &gt;= 39: minutesToEvent = 0 else: minutesToEvent = 39 - now.minute print "Sleep seconds to next event:", minutesToEvent * 60 sleep(minutesToEvent * 60) </code></pre>
1
2016-09-27T15:17:25Z
[ "python" ]
running pyinstaller after Anaconda install results in ImportError: no Module named 'pefile'
39,728,108
<p>I did <code>conda install -c acellera pyinstaller=3.2.3</code> as per <a href="https://anaconda.org/acellera/pyinstaller" rel="nofollow">Anaconda's website</a> and it looks like it installed correctly but I get the following if I try to run it via cmd:</p> <pre><code>C:\Users\Cornelis Dirk Haupt\PycharmProjects\Mesoscale-Brain-Explorer\src&gt;pyinstaller Traceback (most recent call last): File "C:\Anaconda3\Scripts\pyinstaller-script.py", line 9, in &lt;module&gt; load_entry_point('PyInstaller==3.3.dev0+g8756735', 'console_scripts', 'pyinstaller')() File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 542, in load_entry_point File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2569, in load_entry_point File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2229, in load File "C:\Anaconda3\lib\site-packages\setuptools-23.0.0-py3.5.egg\pkg_resources\__init__.py", line 2235, in resolve File "C:\Anaconda3\lib\site-packages\PyInstaller\__main__.py", line 21, in &lt;module&gt; import PyInstaller.building.build_main File "C:\Anaconda3\lib\site-packages\PyInstaller\building\build_main.py", line 34, in &lt;module&gt; from .api import PYZ, EXE, COLLECT, MERGE File "C:\Anaconda3\lib\site-packages\PyInstaller\building\api.py", line 38, in &lt;module&gt; from PyInstaller.utils.win32 import winmanifest, icon, versioninfo, winresource File "C:\Anaconda3\lib\site-packages\PyInstaller\utils\win32\versioninfo.py", line 17, in &lt;module&gt; import pefile ImportError: No module named 'pefile' </code></pre> <p>What's going on? Pyinstaller works fine with python 2.7 without Anaconda. But I've recently decided to make the jump to Anaconda + 3.5. I cant find any module named pefile or how to install it with Anaconda. I can install pefile easily using <code>pip3</code> though.</p>
0
2016-09-27T15:04:51Z
39,986,770
<p>You can use Anaconda's pip to install it, just go to the Script folder in Anaconda and execute:</p> <pre><code>pip.exe install pefile </code></pre>
0
2016-10-11T21:09:03Z
[ "python", "anaconda", "pyinstaller" ]
Using javascript from python to set the value of a hidden input
39,728,163
<p>I'm converting an automated test case to use IE rather than FireFox. The case worked fine on Firefox, however I've found IE has a very strange behavior. It's duplicating the input for login credentials and hiding the input that I need to access. (Note this is IE doing it, not the source for the application I'm testing)</p> <p>I'm using Selenium and Python, and I need to pass the login credentials to the hidden input fields. I'm aware that you cannot access hidden fields in Selenium, however I've seen a lot of SO posts saying you could do it with Javascript. Which brings me to my question. What am I doing wrong here? I'm not very familiar with Javascript, but everything I've seen so far indicates that this should work. </p> <p><strong>My Python:</strong> (Key is a parameter for the script)</p> <p><code>driver.execute_script("document.getElementsByClassName('form-control placeholder').setAttribute('value', '" + key + "')")</code></p> <p><a href="http://i.stack.imgur.com/1cTKF.png" rel="nofollow">IE Page Source</a></p> <p><a href="http://i.stack.imgur.com/LdsH0.png" rel="nofollow">IE Error</a></p>
0
2016-09-27T15:07:16Z
39,728,965
<p>The method getElementsByClassName returns an array so, you should try: driver.execute_script("document.getElementsByClassName('form-control placeholder')[0].setAttribute('value', '" + key + "')")</p>
0
2016-09-27T15:43:18Z
[ "javascript", "python", "selenium-webdriver" ]
Write a simple looping program
39,728,496
<p>I want to write a program with this logic.</p> <pre><code>A value is presented of the user. Commence a loop Wait for user input If the user enters the displayed value less 13 then Display the value entered by the user and go to top of loop. Otherwise exit the loop </code></pre>
-1
2016-09-27T15:23:03Z
39,728,669
<p>You just need two <code>while</code> loops. One that keeps the main program going forever, and another that breaks and resets the value of <code>a</code> once an answer is wrong.</p> <pre><code>while True: a = 2363 not_wrong = True while not_wrong: their_response = int(raw_input("What is the value of {} - 13?".format(a))) if their_response == (a - 13): a = a -13 else: not_wrong = False </code></pre>
0
2016-09-27T15:29:48Z
[ "python" ]
Write a simple looping program
39,728,496
<p>I want to write a program with this logic.</p> <pre><code>A value is presented of the user. Commence a loop Wait for user input If the user enters the displayed value less 13 then Display the value entered by the user and go to top of loop. Otherwise exit the loop </code></pre>
-1
2016-09-27T15:23:03Z
39,728,691
<p>Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:</p> <pre><code>a = 2363 b = 13 while True: try: c = int(input('Subtract {0} from {1}: '.format(b, a)) except ValueError: print('Please enter an integer.') continue if a-b == c: a = a-b else: print('Incorrect. Restarting...') a = 2363 # break </code></pre> <p>(use <code>raw_input</code> instead of <code>input</code> if you're using Python2)</p> <p>This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if <code>a-b == c</code>. If so, we set the value of <code>a</code> to this new value <code>a-b</code>. Otherwise, we restart the loop. You can uncomment the <code>break</code> command if you don't want an infinite loop.</p>
0
2016-09-27T15:30:37Z
[ "python" ]
Write a simple looping program
39,728,496
<p>I want to write a program with this logic.</p> <pre><code>A value is presented of the user. Commence a loop Wait for user input If the user enters the displayed value less 13 then Display the value entered by the user and go to top of loop. Otherwise exit the loop </code></pre>
-1
2016-09-27T15:23:03Z
39,728,838
<p>Your logic is correct, might want to look into <code>while loop</code>, and <code>input</code>. While loops keeps going until a condition is met:</p> <pre><code>while (condition): # will keep doing something here until condition is met </code></pre> <p>Example of while loop:</p> <pre><code>x = 10 while x &gt;= 0: x -= 1 print(x) </code></pre> <p>This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.</p> <p><code>input</code> allows the user to enter stuff from console:</p> <pre><code>x = input("Enter your answer: ") </code></pre> <p>This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box) </p> <p>Put it all together and you get something like:</p> <pre><code>a = 2363 #change to what you want to start with b = 13 #change to minus from a while a-b &gt; 0: #keeps going until if a-b is a negative number print("%d - %d = ?" %(a, b)) #asks the question user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it if (a-b) == user_input: #compares the answer to our answer print("Correct answer!") a -= b #changes a to be new value else: print("Wrong answer") print("All done!") </code></pre> <p>Now this program stops at <code>a = 7</code> because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that. </p>
0
2016-09-27T15:37:31Z
[ "python" ]
Collect data in chunks from stdin: Python
39,728,503
<p>I have the following Python code where I collect data from standard input into a list and run syntaxnet on it. The data is in the form of json objects from which I will extract the text field and feed it to syntaxnet.</p> <pre><code>data = [] for line in sys.stdin: data.append(line) run_syntaxnet(data) ##This is a function## </code></pre> <p>I am doing this because I do not want Syntaxnet to run for every single tweet since it will take a very long time and hence decrease performance. </p> <p>Also, when I run this code on very large data, I do not want to keep collecting it forever and run out of memory. So I want to collect data in chunks- may be like 10000 tweets at a time and run Syntaxnet on them. Can someone help me how to do this?</p> <p>Also, I want to understand what can be the maximum length of the list <code>data</code> so that I do not run out of memory.</p>
-1
2016-09-27T15:23:16Z
39,728,627
<p>I think this is all you need:</p> <pre><code>data = [] for line in sys.stdin: data.append(line) if len(data) == 10000: run_syntaxnet(data) ##This is a function## data = [] </code></pre> <p>once the list get to 10000, then run the function and reset your data list. Also the maximum size of the list will vary from machine to machine, depending on how much memory you have, so it will probably be best to try it out with different lengths and find out what is optimum.</p>
0
2016-09-27T15:27:49Z
[ "python", "python-2.7", "stdin" ]
Collect data in chunks from stdin: Python
39,728,503
<p>I have the following Python code where I collect data from standard input into a list and run syntaxnet on it. The data is in the form of json objects from which I will extract the text field and feed it to syntaxnet.</p> <pre><code>data = [] for line in sys.stdin: data.append(line) run_syntaxnet(data) ##This is a function## </code></pre> <p>I am doing this because I do not want Syntaxnet to run for every single tweet since it will take a very long time and hence decrease performance. </p> <p>Also, when I run this code on very large data, I do not want to keep collecting it forever and run out of memory. So I want to collect data in chunks- may be like 10000 tweets at a time and run Syntaxnet on them. Can someone help me how to do this?</p> <p>Also, I want to understand what can be the maximum length of the list <code>data</code> so that I do not run out of memory.</p>
-1
2016-09-27T15:23:16Z
39,728,760
<p>I would gather the data into chunks and process those chunks when they get "large":</p> <pre><code>LARGE_DATA = 10 data = [] for line in sys.stdin: data.append(line) if len(data) &gt; LARGE_DATA: run_syntaxnet(data) data = [] run_syntaxnet(data) </code></pre>
0
2016-09-27T15:33:33Z
[ "python", "python-2.7", "stdin" ]
SQL Column types in Jupyter Notebook
39,728,566
<p>so I recently started using Jupyter Notebook.</p> <p>I use SQL queries and then import my results as dataframes to pandas. However, having tried everything I could find on the internet, I am not able to get the type of my table columns using SQL.</p> <p>I can get the types once imported to pandas using 'type()' but that's a different format than the one used in the database.</p> <p>Is there a way to directly get it from the database using SQL queries, or do I have to convert it from pandas type ? </p>
1
2016-09-27T15:25:28Z
39,728,794
<p>Easiest way to get column type from a SQL query is:</p> <pre><code>SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'tableName' AND COLUMN_NAME = 'columnName' </code></pre>
1
2016-09-27T15:35:33Z
[ "python", "sql", "pandas", "apache-spark-sql", "jupyter-notebook" ]
Locating a child of a child in Selenium (Python)
39,728,613
<p>I'm trying to locate two input fields on an unordered menu list, but Selenium is unable to find them. So far I've attempted to locate them by xpath and class name with an ordinal identifier </p> <pre><code>("//input[@class=x-form-text x-form-field][4]") </code></pre> <p>but it either doesn't locate the element or it says it is improperly formatted. The only success I've had is if I use the id, but the number on the end changes every time the page loads.</p> <p>Is there any way to have it locate the menu list, then the list item, and then the input field? I am totally stumped.</p> <p>Notes about the menu list: It changes size based on resolution and if it becomes much smaller a down arrow icon will appear and the fields towards the bottom of the list will disappear unless that down button is selected.</p> <p>Here's an example of the html:</p> <pre><code>&lt;ul id="ext-gen406" class="x-menu-list"&gt; &lt;li id="ext-comp-1237" class="list-item "&gt; &lt;li id="ext-comp-1238" class="list-item "&gt; &lt;li id="ext-comp-1239" class="list-item "&gt; &lt;li id="ext-comp-1240" class="list-item "&gt; &lt;li id="ext-comp-1241" class="list-item "&gt; &lt;li id="ext-comp-1242" class="list-item "&gt; &lt;li id="ext-comp-1207" class="list-item sep-li"&gt; &lt;li id="ext-comp-1243" class="list-item "&gt; &lt;li id="ext-comp-1244" class="list-item "&gt; &lt;li id="ext-comp-1208" class="list-item sep-li"&gt; &lt;li id="ext-comp-1245" class="list-item "&gt; &lt;li id="ext-comp-1246" class="list-item "&gt; &lt;li id="ext-comp-1247" class="list-item "&gt; &lt;li id="ext-comp-1248" class="list-item "&gt; &lt;div id="ext-gen424" class="x-form-field-wrap x-form-field-trigger-wrap"&gt; &lt;input id="ext-comp-1248" class="x-form-text x-form-field"name="ext-comp-1248" &lt;/div&gt; &lt;li id="ext-comp-1249" class="list-item "&gt; &lt;li id="ext-comp-1250" class="list-item "&gt; &lt;div class="x-form-field-wrap x-form-field-trigger-wrap" id="ext-gen426"&gt; &lt;input id="ext-comp-1250" name="ext-comp-1250" class="x-form-text x-form-field" &lt;/div&gt; &lt;li id="ext-comp-1251" class="list-item "&gt; &lt;li id="ext-comp-1252" class="list-item "&gt; &lt;/ul&gt; </code></pre>
1
2016-09-27T15:27:13Z
39,729,133
<p>You can use cssSelector to solve the issue,</p> <pre><code>driver.find_element_by_css_selector("ul.x-menu-list input.x-form-field:nth-child(1)") //first input box driver.find_element_by_css_selector("ul.x-menu-list input.x-form-field:nth-child(2)") //second input box </code></pre>
0
2016-09-27T15:51:32Z
[ "python", "selenium", "xpath" ]
Locating a child of a child in Selenium (Python)
39,728,613
<p>I'm trying to locate two input fields on an unordered menu list, but Selenium is unable to find them. So far I've attempted to locate them by xpath and class name with an ordinal identifier </p> <pre><code>("//input[@class=x-form-text x-form-field][4]") </code></pre> <p>but it either doesn't locate the element or it says it is improperly formatted. The only success I've had is if I use the id, but the number on the end changes every time the page loads.</p> <p>Is there any way to have it locate the menu list, then the list item, and then the input field? I am totally stumped.</p> <p>Notes about the menu list: It changes size based on resolution and if it becomes much smaller a down arrow icon will appear and the fields towards the bottom of the list will disappear unless that down button is selected.</p> <p>Here's an example of the html:</p> <pre><code>&lt;ul id="ext-gen406" class="x-menu-list"&gt; &lt;li id="ext-comp-1237" class="list-item "&gt; &lt;li id="ext-comp-1238" class="list-item "&gt; &lt;li id="ext-comp-1239" class="list-item "&gt; &lt;li id="ext-comp-1240" class="list-item "&gt; &lt;li id="ext-comp-1241" class="list-item "&gt; &lt;li id="ext-comp-1242" class="list-item "&gt; &lt;li id="ext-comp-1207" class="list-item sep-li"&gt; &lt;li id="ext-comp-1243" class="list-item "&gt; &lt;li id="ext-comp-1244" class="list-item "&gt; &lt;li id="ext-comp-1208" class="list-item sep-li"&gt; &lt;li id="ext-comp-1245" class="list-item "&gt; &lt;li id="ext-comp-1246" class="list-item "&gt; &lt;li id="ext-comp-1247" class="list-item "&gt; &lt;li id="ext-comp-1248" class="list-item "&gt; &lt;div id="ext-gen424" class="x-form-field-wrap x-form-field-trigger-wrap"&gt; &lt;input id="ext-comp-1248" class="x-form-text x-form-field"name="ext-comp-1248" &lt;/div&gt; &lt;li id="ext-comp-1249" class="list-item "&gt; &lt;li id="ext-comp-1250" class="list-item "&gt; &lt;div class="x-form-field-wrap x-form-field-trigger-wrap" id="ext-gen426"&gt; &lt;input id="ext-comp-1250" name="ext-comp-1250" class="x-form-text x-form-field" &lt;/div&gt; &lt;li id="ext-comp-1251" class="list-item "&gt; &lt;li id="ext-comp-1252" class="list-item "&gt; &lt;/ul&gt; </code></pre>
1
2016-09-27T15:27:13Z
39,731,830
<blockquote> <p>I tried this method and for some reason it only locates the first input field. It doesn't locate any of the other input fields in the list. (There are 12). Can someone provide more information on how to use nth children?</p> </blockquote> <p>In this case you should try using <code>find_elements</code> to find all <code>input</code> elements and perform certain action on particular element using index below :-</p> <pre><code>all_inputs = driver.find_elements_by_css_selector("ul.x-menu-list &gt; li.list-item input.x-form-text") </code></pre> <blockquote> <p>The two input fields that I'm trying to locate are the 9th and 10th input fields in this list. </p> </blockquote> <pre><code>#now use index to get desire input element if len(all_inputs) &gt;= 10: desire_input_9 = all_inputs[8] desire_input_10 = all_inputs[9] </code></pre>
0
2016-09-27T18:25:40Z
[ "python", "selenium", "xpath" ]
Jump weekends function? Django/python
39,728,661
<p>I need to jump Saturday and Sunday automatically everyday so I can do a count in of certain element from a model. This is an example of the table I need to create:</p> <pre class="lang-none prettyprint-override"><code>Date ------- Order Holds Today ------ 45 (wednesday) 09/09/16 --- 34 (Thursday) 10/09/16 --- 23 (Friday) -----JUMP WEEKEND --- (and keep count in) 13/09/16 --- 56 (Monday) 14/09/16 --- 14 (Tuesday) </code></pre> <p>This is how I filter to count the number of holds for today, and I can keep getting them by adding 1 day:</p> <p>This is my model(models.py):</p> <pre><code>class Data(models.Model): date = models.DateField(null=True, blank=True) ban = models.CharField(max_length=10) </code></pre> <p>This is part of my logic (views.py)</p> <pre><code>today = datetime.today() tomorrow = today + timedelta(days=1) orders = Data.objects.filter(date=today) ban = orders.filter(ban__contains="BAN").count() </code></pre> <p>As you can see in my views.py logic I can filter all the BAN status from today's date, after that I can count them with now issue. My problem is that I if I filter for tomorrow and tomorrow is Friday I need to jump Saturday and Sunday. In other words, apply that logic everyday by just jumping weekends.</p>
1
2016-09-27T15:29:25Z
39,728,811
<p>Look into the date.weekday() function. It is an instance method of the <code>date</code> and <code>datetime</code> classes in Python. It returns the day of the week as in integer, with Monday as 0 and Sunday as 6. So you would want to skip days with <code>date.weekday() &gt;= 5</code></p> <p>See more here: <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">https://docs.python.org/2/library/datetime.html</a></p>
0
2016-09-27T15:36:21Z
[ "python", "dayofweek", "weekday" ]
Jump weekends function? Django/python
39,728,661
<p>I need to jump Saturday and Sunday automatically everyday so I can do a count in of certain element from a model. This is an example of the table I need to create:</p> <pre class="lang-none prettyprint-override"><code>Date ------- Order Holds Today ------ 45 (wednesday) 09/09/16 --- 34 (Thursday) 10/09/16 --- 23 (Friday) -----JUMP WEEKEND --- (and keep count in) 13/09/16 --- 56 (Monday) 14/09/16 --- 14 (Tuesday) </code></pre> <p>This is how I filter to count the number of holds for today, and I can keep getting them by adding 1 day:</p> <p>This is my model(models.py):</p> <pre><code>class Data(models.Model): date = models.DateField(null=True, blank=True) ban = models.CharField(max_length=10) </code></pre> <p>This is part of my logic (views.py)</p> <pre><code>today = datetime.today() tomorrow = today + timedelta(days=1) orders = Data.objects.filter(date=today) ban = orders.filter(ban__contains="BAN").count() </code></pre> <p>As you can see in my views.py logic I can filter all the BAN status from today's date, after that I can count them with now issue. My problem is that I if I filter for tomorrow and tomorrow is Friday I need to jump Saturday and Sunday. In other words, apply that logic everyday by just jumping weekends.</p>
1
2016-09-27T15:29:25Z
39,729,847
<p>You can find the weekday number for a <code>datetime</code> by calling its <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.weekday" rel="nofollow"><code>weekday()</code></a> method. Once you have that value you can test it to see if its one of the days you're interested in:</p> <pre><code>from datetime import datetime, timedelta DAYS_OF_INTEREST = {0, 1, 2, 3, 4} # Monday-Friday DELTA_ONE_DAY = timedelta(days=1) today = datetime.today() day = today for _ in range(14): # next two weeks if day.weekday() in DAYS_OF_INTEREST: print(day.strftime(("%d/%m/%y --- %A"))) #orders = Report.objects.filter(current_fcd_date=day) #hold = orders.filter(order_hold__contains="HOLD").count() day += DELTA_ONE_DAY </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>27/09/16 --- Tuesday 28/09/16 --- Wednesday 29/09/16 --- Thursday 30/09/16 --- Friday 03/10/16 --- Monday 04/10/16 --- Tuesday 05/10/16 --- Wednesday 06/10/16 --- Thursday 07/10/16 --- Friday 10/10/16 --- Monday </code></pre>
1
2016-09-27T16:28:17Z
[ "python", "dayofweek", "weekday" ]
How to Hangup a call in Asterisk AMI
39,728,663
<p>Hello I'm using Python Asterisk to work on my asterisk server. I have been able to listen to current calls using the following code.</p> <pre><code> def handle_event(event, manager): with ctx: if event.name == 'CoreShowChannel': user_id = event.message['AccountCode'] user_id = int(user_id) data = { "channel":event.message['Channel'], "channel_state":event.message['ChannelStateDesc'], "duration":event.message['Duration'], 'extension': event.message['Exten'], 'line': event.message['ConnectedLineNum'], 'user_id': user_id, 'context': event.message['Context'], 'caller_id': event.message['CallerIDNum'] } system = System() user = system.getUserById(user_id) if user: profile = {"first_name":user.first_name, "last_name":user.last_name} data.update(profile) g.channels.append(data) if event.name == 'CoreShowChannelsComplete': g.complete = True @app.route('/live-calls') def live_calls(): g.complete = False g.channels = [] manager = asterisk.manager.Manager() manager.connect(hostname) manager.login(username, secret) manager.register_event('*', handle_event) res = manager.send_action({'Action':'CoreShowChannels'}) while not g.complete: time.sleep(0.1) manager.close() if len(g.channels) &lt; 1: return json.dumps({"response":g.complete}) return json.dumps(g.channels) </code></pre> <p>This code serves it purpose and works as expected, now how do I accomplish a hangup method where when I click a hangup button, the current call hangs up. The problem is I know there is an Hangup event but I do not even know the object or variables to check or where to listen to.</p>
0
2016-09-27T15:29:27Z
39,746,325
<p>You have to send command to AMI. You can list commands and their parameters in Asterisk CLI</p> <pre><code>pbx*CLI&gt; manager show commands Action Synopsis ------ -------- AbsoluteTimeout Set absolute timeout. AGI Add an AGI command to execute by Async AGI. AOCMessage Generate an Advice of Charge message on a chan Atxfer Attended transfer. BlindTransfer Blind transfer channel(s) to the given destina Bridge Bridge two channels already in the PBX. BridgeDestroy Destroy a bridge. BridgeInfo Get information about a bridge. BridgeKick Kick a channel from a bridge. BridgeList Get a list of bridges in the system. BridgeTechnologyList List available bridging technologies and their BridgeTechnologySuspend Suspend a bridging technology. BridgeTechnologyUnsuspend Unsuspend a bridging technology. (...) pbx*CLI&gt; manager show command Hangup [Syntax] Action: Hangup [ActionID:] &lt;value&gt; Channel: &lt;value&gt; [Cause:] &lt;value&gt; [Synopsis] Hangup channel. [Description] Hangup a channel. [Arguments] ActionID ActionID for this transaction. Will be returned. Channel The exact channel name to be hungup, or to use a regular expression, set this parameter to: /regex/ Example exact channel: SIP/provider-0000012a Example regular expression: /^SIP/provider-.*$/ Cause Numeric hangup cause. [See Also] Not available [Privilege] system,call,all [List Responses] None [Final Response] None </code></pre>
-1
2016-09-28T11:36:34Z
[ "python", "asterisk" ]
How to Hangup a call in Asterisk AMI
39,728,663
<p>Hello I'm using Python Asterisk to work on my asterisk server. I have been able to listen to current calls using the following code.</p> <pre><code> def handle_event(event, manager): with ctx: if event.name == 'CoreShowChannel': user_id = event.message['AccountCode'] user_id = int(user_id) data = { "channel":event.message['Channel'], "channel_state":event.message['ChannelStateDesc'], "duration":event.message['Duration'], 'extension': event.message['Exten'], 'line': event.message['ConnectedLineNum'], 'user_id': user_id, 'context': event.message['Context'], 'caller_id': event.message['CallerIDNum'] } system = System() user = system.getUserById(user_id) if user: profile = {"first_name":user.first_name, "last_name":user.last_name} data.update(profile) g.channels.append(data) if event.name == 'CoreShowChannelsComplete': g.complete = True @app.route('/live-calls') def live_calls(): g.complete = False g.channels = [] manager = asterisk.manager.Manager() manager.connect(hostname) manager.login(username, secret) manager.register_event('*', handle_event) res = manager.send_action({'Action':'CoreShowChannels'}) while not g.complete: time.sleep(0.1) manager.close() if len(g.channels) &lt; 1: return json.dumps({"response":g.complete}) return json.dumps(g.channels) </code></pre> <p>This code serves it purpose and works as expected, now how do I accomplish a hangup method where when I click a hangup button, the current call hangs up. The problem is I know there is an Hangup event but I do not even know the object or variables to check or where to listen to.</p>
0
2016-09-27T15:29:27Z
39,927,530
<p>I just called the hangup method which takes the channel name as an argument.</p> <p>I didn't know there is method for that</p> <p>manager.hangup(channel)</p>
0
2016-10-08T00:40:54Z
[ "python", "asterisk" ]
Vertical line at the end of a CDF histogram using matplotlib
39,728,723
<p>I'm trying to create a CDF but at the end of the graph, there is a vertical line, shown below:</p> <p><a href="http://i.stack.imgur.com/OIeSJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/OIeSJ.png" alt="plot"></a></p> <p>I've read that his is because matplotlib uses the end of the bins to draw the vertical lines, which makes sense, so I added into my code as:</p> <pre><code>bins = sorted(X) + [np.inf] </code></pre> <p>where X is the data set I'm using and set the bin size to this when plotting:</p> <pre><code>plt.hist(X, bins = bins, cumulative = True, histtype = 'step', color = 'b') </code></pre> <p>This does remove the line at the end and produce the desired effect, however when I normalise this graph now it produces an error:</p> <pre><code>ymin = max(ymin*0.9, minimum) if not input_empty else minimum UnboundLocalError: local variable 'ymin' referenced before assignment </code></pre> <p>Is there anyway to either normalise the data with </p> <pre><code>bins = sorted(X) + [np.inf] </code></pre> <p>in my code or is there another way to remove the line on the graph?</p>
1
2016-09-27T15:31:52Z
39,729,964
<p>An alternative way to plot a CDF would be as follows (in my example, <code>X</code> is a bunch of samples drawn from the unit normal):</p> <pre><code>import numpy as np, matplotlib.pyplot as plt X = np.random.randn(10000) n = np.arange(1,len(X)+1) / np.float(len(X)) Xs = np.sort(X) plt.plot(Xs,n) #or use plt.step(Xs,n) </code></pre> <p><a href="http://i.stack.imgur.com/Zr9pW.png" rel="nofollow"><img src="http://i.stack.imgur.com/Zr9pW.png" alt="enter image description here"></a></p>
0
2016-09-27T16:34:56Z
[ "python", "pandas", "matplotlib" ]
How to delete duplicates, but keep the first instance and a blank cell for the duplicates in Pandas?
39,728,930
<p>I have a pandas DataFrame, and I'm doing a groupby(['target']).count(). This works fine. However, one of the things I want, for each group, is the number of unique elements in the ID column. </p> <p>What I'd like to do is, for the ID column, null out all but the first copy of any ID value (IDs are unique to groups, so I don't have to worry about that issue). Then, the groupby().count() will give me the number of unique IDs in each group... But I'm not sure how to do that.</p>
0
2016-09-27T15:41:46Z
39,732,745
<p>The <code>DataFrame.duplicated()</code> method is applicable here if you want to do it the way you described. It can return a Series with the first occurrence of an ID being False and the rest being True. You can then use this as a mask to set the duplicated IDs to null. </p> <p>See: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html</a></p>
0
2016-09-27T19:23:57Z
[ "python", "pandas", "dataframe" ]
Python: Instantiate class B within a class A instantiation, <class A name> object has no attribute <class B attribute>
39,728,972
<p>Python: I'm using the requests module to work with an API and I'm looking at using classes. I'm getting an attribute error:</p> <p><strong>apic.py module:</strong> (class A)</p> <pre><code>import requests import json class Ses: def __init__(self): self = requests.Session() self.headers = {'Content-Type': 'application/json'} print(self.headers) def login(self, cname, uname, pword): res = self.post( 'https://api.dynect.net/REST/Session/', params = {'customer_name': cname, 'user_name': uname, 'password': pword} ) self.headers.update({'Auth-Token': json.loads(res.text)['data']['token']}) print( json.loads(res.text)['msgs'][0]['INFO'], '\n' ) return json.loads(res.text) </code></pre> <hr> <p><strong>script:</strong></p> <pre><code>import requests import apic sesh = apic.Ses() print(sesh.login()) </code></pre> <ul> <li>AttributeError: 'Ses' object has no attribute 'post' <hr></li> </ul> <p>If I remove the call to login() from apic:</p> <pre><code>sesh = apic.Ses() </code></pre> <p>I can see it prints self.headers (sesh.headers) just fine: </p> <ul> <li>{'Content-Type': 'application/json'}</li> </ul> <p>So it seems my syntax is the script is the issue.</p> <p>.Session is a class in requests (class B)</p> <p>.post and .headers are functions in the Session class.</p> <p>My questions:</p> <p>If I'm instantiating class B in class A instantiation, how should I be calling attributes of class B.</p> <p>Should I just not be attempting this? (I'm looking at using classes in this way to clean up my script, it's not something I necessarily need to do.)</p>
1
2016-09-27T15:43:29Z
39,729,053
<p>You can't just assign to <code>self</code>. That's just a local variable within the <code>__init__</code> method. </p> <p>I don't know why you want to do that anyway. Instead you should be defining the session as an attribute of the instance:</p> <pre><code>def __init__(self): self.session = requests.Session() self.session.headers = {'Content-Type': 'application/json'} print(self.session.headers) def login(self, cname, uname, pword): res = self.session.post('https://api.dynect.net/REST/Session/', params = {'customer_name': cname, 'user_name': uname, 'password': pword} ) ... </code></pre>
1
2016-09-27T15:47:37Z
[ "python", "class", "attributes", "instantiation" ]
How do I add public youtube videos to a playlist in Youtube using URL?
39,729,080
<p>The Youtube Data API doesn't have any option for this procedure. May be because it has got something to do with authentication. But what I'm referring is to add public videos to a playlist. How do I accomplish this using python?</p>
0
2016-09-27T15:49:17Z
39,774,255
<p>You can use the <a href="https://developers.google.com/youtube/v3/docs/playlistItems/insert" rel="nofollow"><code>PlaylistItems: insert</code></a> to insert a video inside a playlist.</p> <p>Here is the request that I used.</p> <pre><code>POST https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&amp;key={YOUR_API_KEY} { "snippet": { "playlistId": "PLgTC0orxjF5MrSEDzjT7J1lkR4zYwPEpf", "resourceId": { "videoId": "qnHyhCYOgTI", "kind": "youtube#video" } } } </code></pre> <p>Make sure that you pass <code>youtube#video</code> on the <code>kind</code> attribute of the <code>resourceId</code>. Because if you did not specify it, you will get an error <code>400 Bad request Resource type not supported</code>.</p> <p>For the Python code that you want, you can check this related <a href="http://stackoverflow.com/questions/21228815/adding-youtube-video-to-playlist-using-python">SO question</a>.</p> <blockquote> <p>NOTE: This request requires authorization with at least one of the following scopes: </p> <p><a href="https://www.googleapis.com/auth/youtubepartner" rel="nofollow">https://www.googleapis.com/auth/youtubepartner</a> </p> <p><a href="https://www.googleapis.com/auth/youtube" rel="nofollow">https://www.googleapis.com/auth/youtube</a></p> <p><a href="https://www.googleapis.com/auth/youtube.force-ssl" rel="nofollow">https://www.googleapis.com/auth/youtube.force-ssl</a></p> </blockquote>
0
2016-09-29T15:21:41Z
[ "python", "youtube-api", "youtube-data-api" ]
Is there in PyQt a signal that warns me on the presence of data in the input serial buffer?
39,729,201
<p>I'm trying to create a GUI application with PyQt for a board that send me data packets with fixed lenght. The application reads these packets and shows some values contained in them. Leaving out the structure of the packets, my first attempt was to connect a timeout signal with my <code>Update()</code> function that update the values in the GUI:</p> <pre><code>timer = pg.QtCore.QTimer() timer.timeout.connect(main.Update) timer.start(10) </code></pre> <p>This solution emits a signal every 10 ms that activates the <code>Update()</code> routine. My question now is simple.</p> <p>Since I don't like that, every some time, the application calls the <code>Update()</code> function, can I create a signal that warns on the presence of data in the input buffer? In this case the <code>Update()</code> function would be called only if necessary. Is it possible or the only solution is the polling?</p>
0
2016-09-27T15:54:55Z
39,732,488
<p>I would just create a worker <code>QObject</code> in a separate thread that constantly checks the input buffer and emits a signal to the main thread when data is available</p> <pre><code>class Worker(QObject): data_ready = pyqtSignal(object) @pyqtSlot() def forever_read(self): while True: # Check input buffer data = something.read() if data: self.data_ready.emit(data) time.sleep(0.1) </code></pre> <p>In the main thread</p> <pre><code>class WindowOrObject(...) def __init__(self): ... self.worker = Worker(self) self.thread = QThread(self) self.worker.data_ready.connect(self.handle_data) self.worker.moveToThread(self.thread) self.thread.started.connect(self.worker.forever_read) self.thread.start() @pyqtSlot(object) def handle_data(self, data): # do something with data ... </code></pre>
0
2016-09-27T19:06:11Z
[ "python", "serial-port", "pyqt", "signals" ]
Getting incorrect score from fuzzy wuzzy partial_ratio
39,729,225
<p>I am fairly new to Python and I am trying to use fuzzy wuzzy for fuzzy matching. I believe I am getting incorrect scores for matches using the partial_ratio function. Here is my exploratory code:</p> <pre><code>&gt;&gt;&gt;from fuzzywuzzy import fuzz &gt;&gt;&gt;fuzz.partial_ratio('Subject: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clearance','Barbil') 50 </code></pre> <p>I believe this should return a score of 100, since the second string, 'Barbil', is contained in the first string. When I try taking off a few characters at the end or beginning of the first string, I get a matching score of 100. </p> <pre><code>&gt;&gt;&gt;fuzz.partial_ratio('Subject: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clear','Barbil') 100 &gt;&gt;&gt; fuzz.partial_ratio('ect: Dalki Manganese Ore Mine of M/S Bharat Process and Mechanical Engineers Ltd., Villages Dalki, Soyabahal, Sading and Thakurani R.F., Tehsil Barbil, Distt, Keonjhar, Orissa environmental clearance','Orissa') 100 </code></pre> <p>It seems to switch from a score of 50 to a score of 100 when the length of the first string goes to 199. Does anyone have insight as to what might be happening?</p>
1
2016-09-27T15:56:17Z
39,760,350
<p>It's because when one of the strings is <a href="https://docs.python.org/3.4/library/difflib.html#difflib.SequenceMatcher" rel="nofollow">200 characters or longer, an automatic junk heuristic gets turned on in python's SequenceMatcher</a>. This code should work for you:</p> <pre><code>from difflib import SequenceMatcher def partial_ratio(s1, s2): """"Return the ratio of the most similar substring as a number between 0 and 100.""" if len(s1) &lt;= len(s2): shorter = s1 longer = s2 else: shorter = s2 longer = s1 m = SequenceMatcher(None, shorter, longer, autojunk=False) blocks = m.get_matching_blocks() # each block represents a sequence of matching characters in a string # of the form (idx_1, idx_2, len) # the best partial match will block align with at least one of those blocks # e.g. shorter = "abcd", longer = XXXbcdeEEE # block = (1,3,3) # best score === ratio("abcd", "Xbcd") scores = [] for (short_start, long_start, _) in blocks: long_end = long_start + len(shorter) long_substr = longer[long_start:long_end] m2 = SequenceMatcher(None, shorter, long_substr, autojunk=False) r = m2.ratio() if r &gt; .995: return 100 else: scores.append(r) return max(scores) * 100.0 </code></pre>
0
2016-09-29T02:20:31Z
[ "python", "fuzzy-comparison", "fuzzywuzzy" ]
save the file in HDFS from a pair RDD
39,729,335
<p>Below is the python script which I am using to write in HDFS. RDD is a pair RDD.The script works fine however it creates an entry as tuple in HDFS.Is is possible to remove the tuple and just create comma separated entries in HDFS.</p> <pre><code> import sys from pyspark import SparkContext if len(sys.argv) &lt; 2: print 'Insufficient arguments' sys.exit() sc = SparkContext() initialrdd1 = sc.textFile(sys.argv[1]) finalRDD1 = initialrdd1.map(lambda x:x.split(',')).map(lambda x :(x[1],x[0])).sortByKey() print finalRDD1.getNumPartitions() finalRDD1.saveAsTextFile('/export_dir/result3/') </code></pre> <p>file storing in HDFS is in below format</p> <pre><code>(u'Alpha', u'E03') (u'Beta', u'E02') (u'Gamma', u'E05') (u'Delta', u'E09') </code></pre>
0
2016-09-27T16:01:34Z
39,729,973
<p>Why not first map the tuple to string and then save it -- </p> <pre><code>finalRDD1.map(lambda x: ','.join(str(s) for s in x)).saveAsTextFile('/export_dir/result3/') </code></pre>
0
2016-09-27T16:35:35Z
[ "python", "apache-spark", "hdfs", "pyspark" ]
save the file in HDFS from a pair RDD
39,729,335
<p>Below is the python script which I am using to write in HDFS. RDD is a pair RDD.The script works fine however it creates an entry as tuple in HDFS.Is is possible to remove the tuple and just create comma separated entries in HDFS.</p> <pre><code> import sys from pyspark import SparkContext if len(sys.argv) &lt; 2: print 'Insufficient arguments' sys.exit() sc = SparkContext() initialrdd1 = sc.textFile(sys.argv[1]) finalRDD1 = initialrdd1.map(lambda x:x.split(',')).map(lambda x :(x[1],x[0])).sortByKey() print finalRDD1.getNumPartitions() finalRDD1.saveAsTextFile('/export_dir/result3/') </code></pre> <p>file storing in HDFS is in below format</p> <pre><code>(u'Alpha', u'E03') (u'Beta', u'E02') (u'Gamma', u'E05') (u'Delta', u'E09') </code></pre>
0
2016-09-27T16:01:34Z
39,783,492
<pre><code>finalRDD1 = initialrdd1.map(lambda x:x.split(',')).map(lambda x :(x[1],x[0])).sortByKey() </code></pre> <p>Understand your code. In your initial RDD, you are mapping each entry to a tuple. <strong>map(lambda x :(x[1],x[0]))</strong></p> <pre><code>finalRDD1.saveAsTextFile('/export_dir/result3/') </code></pre> <p>After the sortByKey operation, you directly proceed to save the RDD as textfile. </p> <p>In order to save entries as CSV, you must to specify it explicitly like so - </p> <pre><code>def csv_format(data): return ','.join(str(d) for d in data) # Rest of the code ... finalRDD1.map(csv_format).saveAsTextFile('/export_dir/result3/') </code></pre>
0
2016-09-30T04:03:02Z
[ "python", "apache-spark", "hdfs", "pyspark" ]
using django rest framework to return info by name
39,729,388
<p>I am using Django rest framework and I create this class to return all the name of project</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer def list(self, request): all_rows = connect_database() name_project = [] all_projects = [] for item_row in all_rows: name_project.append(item_row['project']) name_project = list(sorted(set(name_project))) for i in range(0, len(name_project)): all_projects.append({'project' : str(name_project[i])}) serializer = serializers.cpuProjectsSerializer(instance=all_projects, many=True) return Response(serializer.data) </code></pre> <p>my URL is like that <code>http://127.0.0.1:8000/cpuProjects/</code> this return all the projects, buy If now I want a particular project, Have I to create a new class?? if I want to use the same URL ... for example <code>http://127.0.0.1:8000/cpuProjects/</code> => return all project <code>http://127.0.0.1:8000/cpuProjects/nameProject</code> => return a particular project.</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer lookup_field = 'project_name' def retrieve(self, request, project_name=None): try: opc = {'name_proj' : project_name } all_rows = connect_database(opc) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True) return Response(serializer.data) </code></pre> <p>Is it possible to do in the same class? I try to use retrieve method but the need an ID of the project, no the name right? </p> <p>thanks in advance!</p>
1
2016-09-27T16:03:42Z
39,729,913
<p>If you want to use the same class you can use a viewset and define a list() and retrieve() methods</p> <p>check <a href="http://www.django-rest-framework.org/api-guide/viewsets/" rel="nofollow">http://www.django-rest-framework.org/api-guide/viewsets/</a> the first example is doing that</p> <pre><code>from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) </code></pre>
1
2016-09-27T16:32:09Z
[ "python", "django", "django-rest-framework" ]
using django rest framework to return info by name
39,729,388
<p>I am using Django rest framework and I create this class to return all the name of project</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer def list(self, request): all_rows = connect_database() name_project = [] all_projects = [] for item_row in all_rows: name_project.append(item_row['project']) name_project = list(sorted(set(name_project))) for i in range(0, len(name_project)): all_projects.append({'project' : str(name_project[i])}) serializer = serializers.cpuProjectsSerializer(instance=all_projects, many=True) return Response(serializer.data) </code></pre> <p>my URL is like that <code>http://127.0.0.1:8000/cpuProjects/</code> this return all the projects, buy If now I want a particular project, Have I to create a new class?? if I want to use the same URL ... for example <code>http://127.0.0.1:8000/cpuProjects/</code> => return all project <code>http://127.0.0.1:8000/cpuProjects/nameProject</code> => return a particular project.</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer lookup_field = 'project_name' def retrieve(self, request, project_name=None): try: opc = {'name_proj' : project_name } all_rows = connect_database(opc) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True) return Response(serializer.data) </code></pre> <p>Is it possible to do in the same class? I try to use retrieve method but the need an ID of the project, no the name right? </p> <p>thanks in advance!</p>
1
2016-09-27T16:03:42Z
39,731,786
<p>You need to add lookup_field in view class. Suppose, you want to get user by username you need to add <code>lookup_field = 'username'</code>.</p> <p>Example:</p> <pre><code>from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): lookup_field = 'username' def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, username=None): queryset = User.objects.all() user = get_object_or_404(queryset, username=username) serializer = UserSerializer(user) return Response(serializer.data) </code></pre> <p>Now your url will be </p> <pre><code>url(r'^users/$', UserViewSet.as_view({'get': 'list'})), url(r'^users/(?P&lt;username&gt;[a-zA-Z0-9]+)$', UserViewSet.as_view({'get': 'retrieve'})), </code></pre> <p>Now <code>http://127.0.0.1:8000/users/</code> will return all users and <code>http://127.0.0.1:8000/users/username</code> will return particular user details.</p> <p>You can learn more about <code>lookup_field</code> from <a href="http://www.django-rest-framework.org/api-guide/generic-views/#attributes" rel="nofollow">Django REST framework</a>.</p>
1
2016-09-27T18:23:39Z
[ "python", "django", "django-rest-framework" ]
using django rest framework to return info by name
39,729,388
<p>I am using Django rest framework and I create this class to return all the name of project</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer def list(self, request): all_rows = connect_database() name_project = [] all_projects = [] for item_row in all_rows: name_project.append(item_row['project']) name_project = list(sorted(set(name_project))) for i in range(0, len(name_project)): all_projects.append({'project' : str(name_project[i])}) serializer = serializers.cpuProjectsSerializer(instance=all_projects, many=True) return Response(serializer.data) </code></pre> <p>my URL is like that <code>http://127.0.0.1:8000/cpuProjects/</code> this return all the projects, buy If now I want a particular project, Have I to create a new class?? if I want to use the same URL ... for example <code>http://127.0.0.1:8000/cpuProjects/</code> => return all project <code>http://127.0.0.1:8000/cpuProjects/nameProject</code> => return a particular project.</p> <pre><code>class cpuProjectsViewSet(viewsets.ViewSet): serializer_class = serializers.cpuProjectsSerializer lookup_field = 'project_name' def retrieve(self, request, project_name=None): try: opc = {'name_proj' : project_name } all_rows = connect_database(opc) except KeyError: return Response(status=status.HTTP_404_NOT_FOUND) except ValueError: return Response(status=status.HTTP_400_BAD_REQUEST) serializer = serializers.cpuProjectsSerializer(instance=all_rows, many=True) return Response(serializer.data) </code></pre> <p>Is it possible to do in the same class? I try to use retrieve method but the need an ID of the project, no the name right? </p> <p>thanks in advance!</p>
1
2016-09-27T16:03:42Z
39,736,838
<p>One does not use raw queries unless absolutely needed and even then, there isn't a need to manually connect to the database because you have easy access to a connection object. Overall, your retrieve method can be improved as follows:</p> <pre><code>def retrieve(self, request, pk=None): queryset = CpuProject.objects.all() cpu = get_object_or_404(queryset, pk=pk) serializer = serializers.cpuProjectsSerializer(cpu) return Response(serializer.data) </code></pre> <p>Much shorter and easier to read. But Even this is not really needed If you use a ModelViewset! Then the default retrieve method will take care of this for you. So your viewset reduces to</p> <pre><code>class cpuProjectsViewset(viewsets.ModelViewSet): serializer_class =serializer = serializers.cpuProjectsSerializer queryset = CpuProject.objects.all() </code></pre> <p>You don't need a retrieve method here!!</p> <p>But I see that you are trying to retrieve a particular CpuProject item by it's name (rather than using it's PK). For that you need to add a route</p> <pre><code>from rest_framework.decorators import detail_route, list_route @detail_route(url_path='(?P&lt;slug&gt;[\w-]+)') def get_by_name(self, request, pk=None,slug=None): queryset = CpuProject.objects.all() cpu = get_object_or_404(queryset, name=slug) serializer = serializers.cpuProjectsSerializer(cpu) return Response(serializer.data) </code></pre>
1
2016-09-28T01:54:52Z
[ "python", "django", "django-rest-framework" ]
Nested Loop in Python Not Working
39,729,391
<p>I would like to have this output:</p> <pre><code>* * * 2 2 2 4 4 4 6 6 6 8 8 8 </code></pre> <p>I cannot get it and I've tried many ways, but my code doesn't seem to work. Here is my current code:</p> <pre><code>for row in range(3): print ("*", end = " ") print () for col in range(2,9,2): print (row, end = " ") print () print() </code></pre> <p>What do I do?</p>
0
2016-09-27T16:03:46Z
39,729,470
<pre><code>print('* * *') for col in range(2,9,2): print (*[col]*3, sep=' ') </code></pre> <p>To be more clear.</p> <pre><code>&gt;&gt;&gt; a = 2 &gt;&gt;&gt; [a] [2] &gt;&gt;&gt; [a]*3 [2, 2, 2] &gt;&gt;&gt; print(*[a]*3, sep=' ') # equal to print(a, a, a, sep=' ') 2 2 2 </code></pre>
0
2016-09-27T16:07:41Z
[ "python" ]
Nested Loop in Python Not Working
39,729,391
<p>I would like to have this output:</p> <pre><code>* * * 2 2 2 4 4 4 6 6 6 8 8 8 </code></pre> <p>I cannot get it and I've tried many ways, but my code doesn't seem to work. Here is my current code:</p> <pre><code>for row in range(3): print ("*", end = " ") print () for col in range(2,9,2): print (row, end = " ") print () print() </code></pre> <p>What do I do?</p>
0
2016-09-27T16:03:46Z
39,729,475
<p>I don't see why you are using <code>end</code> in your print statements. Keep in mind that you must print line by line. There is no way to print column by column.</p> <pre><code>print('* * *') for i in range(2, 9, 2): print('{0} {0} {0}'.format(i)) </code></pre> <p>For further explanation about the <code>{0}</code>s, look up the <code>format</code> method for strings: <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">https://docs.python.org/2/library/string.html#format-string-syntax</a></p>
2
2016-09-27T16:07:58Z
[ "python" ]
Nested Loop in Python Not Working
39,729,391
<p>I would like to have this output:</p> <pre><code>* * * 2 2 2 4 4 4 6 6 6 8 8 8 </code></pre> <p>I cannot get it and I've tried many ways, but my code doesn't seem to work. Here is my current code:</p> <pre><code>for row in range(3): print ("*", end = " ") print () for col in range(2,9,2): print (row, end = " ") print () print() </code></pre> <p>What do I do?</p>
0
2016-09-27T16:03:46Z
39,729,565
<p>For a start, you only have one row that contains <code>* * *</code> which can be printed at the very top, outside of any loops:</p> <p><code>print('* * *')</code></p> <p>Next, you would need to start your loop from values <code>2</code> (inclusive) and <code>9</code> (exclusive) in steps of <code>2</code>:</p> <p><code>for col in range(2,9,2):</code></p> <p>You don't need to use any <code>end</code> keyword here, so just printing the row multiple times is sufficient:</p> <p><code>print('{0} {0} {0}'.format(i))</code></p> <p>So the final block of code looks like:</p> <pre><code>print('* * *') for row in range(2,9,2): print('{0} {0} {0}'.format(row)) </code></pre> <p>You don't need to add another <code>print()</code>, <code>print</code> already ends with a newline anyway.</p>
0
2016-09-27T16:12:31Z
[ "python" ]
Error when trying to install Quandl module with pip
39,729,395
<p>I tried to install the <a href="https://pypi.python.org/pypi/Quandl" rel="nofollow">Python Quandl module</a> with pip by running the following code in the cmd prompt:</p> <pre><code>C:\Users\zeke\Desktop\Python\python.exe -m pip install quandl </code></pre> <p>The module began to download and install until it reached an error message:</p> <pre><code>C:\Users\zeke&gt;C:\Users\zeke\Desktop\Python\python.exe -m pip install quandl Collecting quandl Using cached Quandl-3.0.1-py2.py3-none-any.whl Collecting pyOpenSSL (from quandl) Downloading pyOpenSSL-16.1.0-py2.py3-none-any.whl (43kB) 100% |################################| 51kB 1.8MB/s Collecting ndg-httpsclient (from quandl) Using cached ndg_httpsclient-0.4.2.tar.gz Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info\ndg_httpsclient.egg-info writing dependency_links to pip-egg-info\ndg_httpsclient.egg-info\dependency_links.txt writing pip-egg-info\ndg_httpsclient.egg-info\PKG-INFO writing entry points to pip-egg-info\ndg_httpsclient.egg-info\entry_points.txt writing requirements to pip-egg-info\ndg_httpsclient.egg-info\requires.txt writing top-level names to pip-egg-info\ndg_httpsclient.egg-info\top_level.txt writing namespace_packages to pip-egg-info\ndg_httpsclient.egg-info\namespace_packages.txt writing manifest file 'pip-egg-info\ndg_httpsclient.egg-info\SOURCES.txt' warning: manifest_maker: standard file '-c' not found error: [Errno 2] No such file or directory: 'C:\\Users\\zeke\\Desktop\\Python\\python35.zip\\lib2to3\\Grammar.txt' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\zeke\AppData\Local\Temp\pip-build-emddiyej\ndg-httpsclient\ </code></pre> <p>I followed the file path 'C:\Users\zeke\Desktop\Python\python35.zip\lib2to3\Grammar.txt' and the file completely exists. Why am I getting this error?</p>
0
2016-09-27T16:04:03Z
39,752,953
<p>I was able to fix the issue by extracting .../Python/Python35.zip to a new directory within .../Python named 'Python35.zip'.</p> <p>However now I am receiving errors when trying to import the module.</p> <pre><code>&gt;&gt;&gt; import quandl Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\zeke\Desktop\Python\lib\site-packages\quandl\__init__.py", line 11, in &lt;module&gt; from .model.merged_dataset import MergedDataset File "C:\Users\zeke\Desktop\Python\lib\site-packages\quandl\model\merged_dataset.py", line 1, in &lt;module&gt; from more_itertools import unique_everseen File "C:\Users\zeke\Desktop\Python\lib\site-packages\more_itertools\__init__.py", line 1, in &lt;module&gt; from more_itertools.more import * File "C:\Users\zeke\Desktop\Python\lib\site-packages\more_itertools\more.py", line 162 min_or_max = partial(max if reverse else min, key=lambda (a, b): a) ^ SyntaxError: invalid syntax </code></pre>
0
2016-09-28T16:27:31Z
[ "python", "pip", "quandl" ]
Error 3: Renaming files in python
39,729,400
<p>Newbie Python question. </p> <p>I'm trying to rename files in a directory...</p> <p>the value of path is </p> <pre><code>C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf </code></pre> <p>while the value newfile is </p> <p><code>C:\tempdir\1\newfilename.pdf</code> </p> <pre><code>origfile = path newfile = path.split("\\") newfile = newfile[0]+"\\"+newfile[1]+"\\"+newfile[2]+"\\"+text+".pdf" os.rename(path, newfile) print origfile print newfile </code></pre> <p>im getting the following error...</p> <pre><code>os.rename(path, newfile) WindowsError: [Error 3] The system cannot find the path specified </code></pre> <p>I know the directory and file are good because i can call os.stats() on it. I have changed to value of newfile to include the new file name only but recieve the same error (after reading the python documentation on rename())</p> <p>My imported libraries are....</p> <pre><code>import sys import os import string from os import path import re from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO </code></pre> <p>I've read some other threads on this topic - pertaining to absolute vs. relative paths. Obviously, my intent is to use absolute paths. My variables are string variable, anotherwords...</p> <pre><code>origfile = "C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf" </code></pre> <p>Is that enough? or am i supposed to be using some other declaration to tell python this is a path? </p>
1
2016-09-27T16:04:16Z
39,729,576
<p>Can you try the following instead? You might find that renaming is easier while using a different API.</p> <pre><code>import pathlib parent = pathlib.Path('C:/') / 'tempdir' / '1' old = parent / '0cd3a8asdsdfasfasdsgvsdfc1.pdf' new = parent / 'newfilename.pdf' old.rename(new) </code></pre> <p>Using the <code>pathlib</code> module makes working with paths in a cross-platform fashion somewhat simpler.</p>
1
2016-09-27T16:13:10Z
[ "python" ]
Error 3: Renaming files in python
39,729,400
<p>Newbie Python question. </p> <p>I'm trying to rename files in a directory...</p> <p>the value of path is </p> <pre><code>C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf </code></pre> <p>while the value newfile is </p> <p><code>C:\tempdir\1\newfilename.pdf</code> </p> <pre><code>origfile = path newfile = path.split("\\") newfile = newfile[0]+"\\"+newfile[1]+"\\"+newfile[2]+"\\"+text+".pdf" os.rename(path, newfile) print origfile print newfile </code></pre> <p>im getting the following error...</p> <pre><code>os.rename(path, newfile) WindowsError: [Error 3] The system cannot find the path specified </code></pre> <p>I know the directory and file are good because i can call os.stats() on it. I have changed to value of newfile to include the new file name only but recieve the same error (after reading the python documentation on rename())</p> <p>My imported libraries are....</p> <pre><code>import sys import os import string from os import path import re from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO </code></pre> <p>I've read some other threads on this topic - pertaining to absolute vs. relative paths. Obviously, my intent is to use absolute paths. My variables are string variable, anotherwords...</p> <pre><code>origfile = "C:\tempdir\1\0cd3a8asdsdfasfasdsgvsdfc1.pdf" </code></pre> <p>Is that enough? or am i supposed to be using some other declaration to tell python this is a path? </p>
1
2016-09-27T16:04:16Z
39,729,640
<p>You should better use <code>ntpath</code> (explained <a href="http://stackoverflow.com/questions/8384737/python-extract-file-name-from-path-no-matter-what-the-os-path-format">here</a>) to modify only your filename:</p> <pre><code>&gt;&gt;&gt; filepath = 'C:\\tempdir\\1\\0cd3a8asdsdfasfasdsgvsdfc1.pdf' &gt;&gt;&gt; dirname, filename = ntpath.dirname(filepath), ntpath.basename(filepath) &gt;&gt;&gt; dirname 'C:\\tempdir\\1' &gt;&gt;&gt; filename '0cd3a8asdsdfasfasdsgvsdfc1.pdf' </code></pre> <p>Hence, you will probably be able to use rename as follows:</p> <pre><code>&gt;&gt;&gt; os.rename(filepath, dirname + ntpath.sep + 'newfilename.pdf') </code></pre> <p>Using <code>ntpath.sep</code> uses the appropriate separator.</p>
0
2016-09-27T16:16:22Z
[ "python" ]
Python Gtk3 Entry set placeholder text
39,729,412
<p>I tried to set a grey italic placeholder text for Gtk.Entry but the entry is empty. Using Linux Mint 17.3 / Gtk Version 3.10.8</p> <p>Whats wrong with this:</p> <pre><code>#!/usr/bin/env python import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk window = Gtk.Window() box = Gtk.Box() window.add(box) entry = Gtk.Entry() box.add(entry) entry.set_placeholder_text("Filter") window.show_all() Gtk.main() </code></pre>
1
2016-09-27T16:04:51Z
39,729,765
<p>From the docs:</p> <blockquote> <p>Note that since the placeholder text gets removed when the entry received focus, using this feature is a bit problematic if the entry is given the initial focus in a window. Sometimes this can be worked around by delaying the initial focus setting until the first key event arrives.</p> </blockquote> <p>Try to add a button and give it focus, it should work.</p>
1
2016-09-27T16:24:27Z
[ "python", "gtk3" ]
PyQt5: updating MainApplication layout after QAction through widget method
39,729,424
<p>I am trying to create my first memory game.</p> <p>I recently found out how to have it working thanks to the answer of my question <a href="http://stackoverflow.com/questions/39689134/python-using-output-from-methods-class-inside-another-class/39689457#39689457">here</a>. The working code is posted in the same link, but now I am trying to keep the widgets and the main application classes separated 1) because I think it's better, and 2) because I would like to in order to learn better how OOP works.</p> <p>So, I here post my new code, which seems to work except the very last part. The concept:</p> <ol> <li><strong>MainApplication</strong> has a menubar which permits to path to a folder of images, and instantiate the <strong>MemoryGame</strong> widget, which in turns initializes an empty QGridLayout.</li> <li>Clicking File -> open in the menubar the method <strong>showDialog</strong> is called.</li> <li>When a folder is chosen, <strong>populate_grid</strong> method (of MemoryGame obj) is called.</li> <li><strong>populate_grid</strong> "should" fill the QGridLayout with each of the image found.</li> <li>The grid should be displayed to the screen, but it's not....</li> </ol> <p>I am pretty sure the problem is in the very final row of <strong>populate_grid</strong>, where I add elements to the grid layout, but I can't find out how to solve the problem.</p> <pre><code>#!/usr/bin/python3 # -*- coding: utf-8 -*- """ Memory game 3 My first memory game in PyQt5. author: Umberto Minora last edited: September 2016 """ import os import sys import glob import math from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout, QPushButton, QApplication, QAction, QFileDialog, QLabel) from PyQt5.QtGui import QPixmap class MainApplication(QMainWindow): """This is the main application. All widgets should be put inside it.""" def __init__(self, widget): super().__init__() self.widget = widget self.initUI() def showDialog(self): folder = str(QFileDialog.getExistingDirectory(self, "Select Directory", '.', QFileDialog.ShowDirsOnly)) images = glob.glob(os.path.join(folder, '*.jpg')) if images: self.widget.populate_grid(images) def initUI(self): self.statusBar() openFile = QAction('Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Search image folder') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() self.fileMenu = menubar.addMenu('&amp;File') self.fileMenu.addAction(openFile) self.setCentralWidget(self.widget) self.setGeometry(300, 300, 350, 300) self.setWindowTitle('Memory Game!') self.show() class MemoryGame(QWidget): """This is the Memory Game Widget""" def __init__(self): super().__init__() self.gridWidget = QWidget(self) self.gridLayout = QGridLayout(self.gridWidget) def populate_grid(self, images): n_cols = math.ceil(math.sqrt(len(images))) n_rows = math.ceil(math.sqrt(len(images))) positions = [(i,j) for i in range(n_cols) for j in range(n_rows)] for position, img in zip(positions, images): if img == '': continue pixmap = QPixmap(img) scaled = pixmap.scaled(pixmap.width()/3, pixmap.height()/3) del(pixmap) lbl = QLabel(self) lbl.setPixmap(scaled) self.gridLayout.addWidget(lbl, *position) if __name__ == '__main__': app = QApplication(sys.argv) ex = MainApplication(MemoryGame()) sys.exit(app.exec_()) </code></pre>
1
2016-09-27T16:05:15Z
39,731,232
<p>The reason why the images aren't showing is because you put the <code>gridWidget</code> inside the <code>MemoryGame</code> widget, which doesn't have a layout itself. The <code>MemoryGame</code> widget should actually <em>replace</em> the <code>gridWidget</code>, so all you need to do is this:</p> <pre><code>class MemoryGame(QWidget): """This is the Memory Game Widget""" def __init__(self): super().__init__() self.gridLayout = QGridLayout(self) </code></pre> <p>I also think the way you create the <code>MemoryGame</code> widget is unnecessarily convoluted. Custom widget classes should be treated like any other. There's no need to pass it into the <code>MainApplication</code> constructor like that - just create it directly inside <code>initUi</code>:</p> <pre><code>def initUI(self): ... self.widget = MemoryGame() self.setCentralWidget(self.widget) </code></pre>
1
2016-09-27T17:49:35Z
[ "python", "python-3.x", "oop", "pyqt", "pyqt5" ]
Python List Comprehensions - Transposing
39,729,469
<p>I'm just starting out with list comprehensions by the reading the <a href="https://docs.python.org/3.5/tutorial/datastructures.html#nested-list-comprehensions" rel="nofollow">matrix transposing tutorial here</a>. I understand the example, but I'm trying to figure out a way to transpose the matrix without hardcoding the range in.</p> <pre><code>matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] lcomp = [[row[i] for row in matrix] for i in range(4)] print(lcomp) [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #result </code></pre> <p>Instead of <code>range(4)</code>, I want it to be able to figure out the the max number of elements that the largest nested array has. I tried placing a <code>lambda</code> but kept getting errors from it. Is it possible to do this in a one-liner?</p>
0
2016-09-27T16:07:36Z
39,729,519
<p>Assuming all sub lists have the same number of elements:</p> <pre><code>s = len(matrix[0]) lcomp = [[row[i] for row in matrix] for i in range(s)] </code></pre> <p>For sublists with mismatching lengths:</p> <pre><code>s = len(max(matrix, key=len)) </code></pre> <hr> <p>On a side note, you could easily transpose your matrix with <code>zip</code>:</p> <pre><code>matrix_T = zip(*matrix) # wrap with list() for Python 3 </code></pre> <p>Or use <a href="https://docs.python.org/2/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>itertools.izip_longest</code></a> for sublists with mismatching lengths.</p>
1
2016-09-27T16:10:07Z
[ "python", "matrix", "list-comprehension" ]
Python List Comprehensions - Transposing
39,729,469
<p>I'm just starting out with list comprehensions by the reading the <a href="https://docs.python.org/3.5/tutorial/datastructures.html#nested-list-comprehensions" rel="nofollow">matrix transposing tutorial here</a>. I understand the example, but I'm trying to figure out a way to transpose the matrix without hardcoding the range in.</p> <pre><code>matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ] lcomp = [[row[i] for row in matrix] for i in range(4)] print(lcomp) [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #result </code></pre> <p>Instead of <code>range(4)</code>, I want it to be able to figure out the the max number of elements that the largest nested array has. I tried placing a <code>lambda</code> but kept getting errors from it. Is it possible to do this in a one-liner?</p>
0
2016-09-27T16:07:36Z
39,729,531
<p>You can use another comprehension! They're a very powerful tool.</p> <pre><code>[[row(i) for row in matrix] for i in range(max(len(r) for r in matrix))] </code></pre>
1
2016-09-27T16:10:31Z
[ "python", "matrix", "list-comprehension" ]
Error to run a library to python
39,729,486
<p>I follow the steps according to <a href="http://npatta01.github.io/2015/08/10/dlib/" rel="nofollow">http://npatta01.github.io/2015/08/10/dlib/</a> but when I try to run (I use sudo),</p> <pre><code>python python_examples/face_detector.py examples/faces/2007_007763.jpg </code></pre> <p>take back error. Firstly, the error was</p> <pre><code>AttributeError: 'module' object has no attribute 'image_window' </code></pre> <p>to line 8. Now, the error is <code>Illegal instruction (core dumped)</code> but I don't know why. Please, help me to add the library correctly. </p> <pre><code>import sys import dlib from skimage import io detector = dlib.get_frontal_face_detector() win = dlib.image_window() for f in sys.argv[1:]: print("Processing file: {}".format(f)) img = io.imread(f) # The 1 in the second argument indicates that we should upsample the image # 1 time. This will make everything bigger and allow us to detect more # faces. dets = detector(img, 1) print("Number of faces detected: {}".format(len(dets))) for i, d in enumerate(dets): print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format( i, d.left(), d.top(), d.right(), d.bottom())) win.clear_overlay() win.set_image(img) win.add_overlay(dets) dlib.hit_enter_to_continue() # Finally, if you really want to you can ask the detector to tell you the score # for each detection. The score is bigger for more confident detections. # The third argument to run is an optional adjustment to the detection threshold, # where a negative value will return more detections and a positive value fewer. # Also, the idx tells you which of the face sub-detectors matched. This can be # used to broadly identify faces in different orientations. if (len(sys.argv[1:]) &gt; 0): img = io.imread(sys.argv[1]) dets, scores, idx = detector.run(img, 1, -1) for i, d in enumerate(dets): print("Detection {}, score: {}, face_type:{}".format( d, scores[i], idx[i])) </code></pre>
1
2016-09-27T16:08:53Z
39,739,259
<p>As I see in your code:</p> <pre><code>detector = dlib.get_frontal_face_detector() win = dlib.image_window() </code></pre> <p>First line works and the second does not. This means that dlib is installed, but it is compiled with no GUI support</p> <p><a href="https://github.com/davisking/dlib/blob/master/tools/python/src/gui.cpp#L1" rel="nofollow">In dlib's source code</a> we see that if macro DLIB_NO_GUI_SUPPORT is defined - there will be no "image_window" function in dlib module. This macro is defined automatically if CMake scripts can't find X11 libraries</p> <p>You need to ensure that dlib is compiled with GUI support. To make it, first - install libx11-dev into your system if you are working on Linux, or XQuartz for Mac</p> <p>When building dlib with running <code>python setup.py install --yes DLIB_JPEG_SUPPORT</code> - check its messages. If there are errors or warnings - fix them</p>
0
2016-09-28T06:10:31Z
[ "python", "attributeerror", "dlib", "illegal-instruction" ]
Colored 3D plot
39,729,508
<p>I found here this good <a href="http://stackoverflow.com/questions/12423601/python-the-simplest-way-to-plot-3d-surface">example</a> to plot 3D data with Python 2.7.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib import cm from mpl_toolkits.mplot3d import Axes3D import numpy as np # ====== ## data: DATA = np.array([ [-0.807237702464, 0.904373229492, 111.428744443], [-0.802470821517, 0.832159465335, 98.572957317], [-0.801052795982, 0.744231916692, 86.485869328], [-0.802505546206, 0.642324228721, 75.279804677], [-0.804158144115, 0.52882485495, 65.112895758], [-0.806418040943, 0.405733109371, 56.1627277595], [-0.808515314192, 0.275100227689, 48.508994388], [-0.809879521648, 0.139140394575, 42.1027499025], [-0.810645106092, -7.48279012695e-06, 36.8668106345], [-0.810676720161, -0.139773175337, 32.714580273], [-0.811308686707, -0.277276065449, 29.5977405865], [-0.812331692291, -0.40975978382, 27.6210856615], [-0.816075037319, -0.535615685086, 27.2420699235], [-0.823691366944, -0.654350489595, 29.1823292975], [-0.836688691603, -0.765630198427, 34.2275056775], [-0.854984518665, -0.86845932028, 43.029581434], [-0.879261949054, -0.961799684483, 55.9594146815], [-0.740499820944, 0.901631050387, 97.0261463995], [-0.735011699497, 0.82881933383, 84.971061395], [-0.733021568161, 0.740454485354, 73.733621269], [-0.732821755233, 0.638770044767, 63.3815970475], [-0.733876941678, 0.525818698874, 54.0655910105], [-0.735055978521, 0.403303715698, 45.90859502], [-0.736448900325, 0.273425879041, 38.935709456], [-0.737556181137, 0.13826504904, 33.096106049], [-0.738278724065, -9.73058423274e-06, 28.359664343], [-0.738507612286, -0.138781586244, 24.627237837], [-0.738539663773, -0.275090412979, 21.857410904], [-0.739099040189, -0.406068448513, 20.1110519655], [-0.741152200369, -0.529726022182, 19.7019157715], ]) Xs = DATA[:,0] Ys = DATA[:,1] Zs = DATA[:,2] ## plot: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') surf = ax.plot_trisurf(Xs, Ys, Zs, cmap=cm.jet, linewidth=0) fig.colorbar(surf) ax.xaxis.set_major_locator(MaxNLocator(5)) ax.yaxis.set_major_locator(MaxNLocator(6)) ax.zaxis.set_major_locator(MaxNLocator(5)) fig.tight_layout() fig.savefig('3D.png') plt.show() </code></pre> <p>The result is good:</p> <p><img src="http://i.stack.imgur.com/PWIE0.png" alt="Output"></p> <p>But, could it be possible to put this 3D map "in 2D"? I want to have only the color as the indication for the Z coordinate. As it would be to see this plot "from the top". And to notice, the data (and so z coordinate) come from a measurement, not a function.</p> <p>I have a lot of data and my computer is very slow...</p>
2
2016-09-27T16:09:42Z
39,731,215
<p>As mentioned in the comment, you can use a contour. Since you are already using a triangulation, you can use <code>tricontourf</code>. See an example below.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np ## data: DATA = np.array([ [-0.807237702464, 0.904373229492, 111.428744443], [-0.802470821517, 0.832159465335, 98.572957317], [-0.801052795982, 0.744231916692, 86.485869328], [-0.802505546206, 0.642324228721, 75.279804677], [-0.804158144115, 0.52882485495, 65.112895758], [-0.806418040943, 0.405733109371, 56.1627277595], [-0.808515314192, 0.275100227689, 48.508994388], [-0.809879521648, 0.139140394575, 42.1027499025], [-0.810645106092, -7.48279012695e-06, 36.8668106345], [-0.810676720161, -0.139773175337, 32.714580273], [-0.811308686707, -0.277276065449, 29.5977405865], [-0.812331692291, -0.40975978382, 27.6210856615], [-0.816075037319, -0.535615685086, 27.2420699235], [-0.823691366944, -0.654350489595, 29.1823292975], [-0.836688691603, -0.765630198427, 34.2275056775], [-0.854984518665, -0.86845932028, 43.029581434], [-0.879261949054, -0.961799684483, 55.9594146815], [-0.740499820944, 0.901631050387, 97.0261463995], [-0.735011699497, 0.82881933383, 84.971061395], [-0.733021568161, 0.740454485354, 73.733621269], [-0.732821755233, 0.638770044767, 63.3815970475], [-0.733876941678, 0.525818698874, 54.0655910105], [-0.735055978521, 0.403303715698, 45.90859502], [-0.736448900325, 0.273425879041, 38.935709456], [-0.737556181137, 0.13826504904, 33.096106049], [-0.738278724065, -9.73058423274e-06, 28.359664343], [-0.738507612286, -0.138781586244, 24.627237837], [-0.738539663773, -0.275090412979, 21.857410904], [-0.739099040189, -0.406068448513, 20.1110519655], [-0.741152200369, -0.529726022182, 19.7019157715], ]) Xs = DATA[:,0] Ys = DATA[:,1] Zs = DATA[:,2] ## plot: fig = plt.figure() contour = plt.tricontourf(Xs, Ys, Zs, cmap="YlGnBu_r") fig.colorbar(contour) fig.savefig('3D.png') plt.show() </code></pre> <p>The results is</p> <p><a href="http://i.stack.imgur.com/vFLyC.png" rel="nofollow"><img src="http://i.stack.imgur.com/vFLyC.png" alt="enter image description here"></a></p>
3
2016-09-27T17:48:34Z
[ "python", "numpy", "matplotlib", "mplot3d" ]
Sorting the tuples of tuples in alphabetical order
39,729,526
<p>I have a list of tuples<br> <code>[((A,B),2),((C,B),3)]</code> Which I need to sort as</p> <pre><code>[((A,B),2),((B,C),3)] </code></pre> <p>I need all the tuples to be in alphabetical order using the <code>sorted()</code> method. I have used <code>key = lambda x : x[0]</code> but doesn't work. Any ideas?</p>
-2
2016-09-27T16:10:18Z
39,729,607
<p>You can use <a href="https://docs.python.org/3/howto/sorting.html" rel="nofollow"><code>sorted</code></a> within <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>:</p> <pre><code>In [3]: tups = [(('A','B'),2),(('C','B'),3)] In [4]: [(sorted(t[0]), t[1]) for t in tups] Out[4]: [(['A', 'B'], 2), (['B', 'C'], 3)] </code></pre>
1
2016-09-27T16:14:31Z
[ "python", "python-3.x" ]
Sorting the tuples of tuples in alphabetical order
39,729,526
<p>I have a list of tuples<br> <code>[((A,B),2),((C,B),3)]</code> Which I need to sort as</p> <pre><code>[((A,B),2),((B,C),3)] </code></pre> <p>I need all the tuples to be in alphabetical order using the <code>sorted()</code> method. I have used <code>key = lambda x : x[0]</code> but doesn't work. Any ideas?</p>
-2
2016-09-27T16:10:18Z
39,729,774
<p>Since @AmiTarovy solved it, but his method not include sorting on second element of outer tuple, when there is two or more <code>tuple</code> elements with same first element.</p> <p>So here is another solution, that also make a sort for second argument of outer tuple.</p> <pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; tups = [(('A','B'),2),(('C','B'),3), (('A','B'),1)] &gt;&gt;&gt; sorted(tups, key=itemgetter(0,1)) [(('A', 'B'), 1), (('A', 'B'), 2), (('C', 'B'), 3)] </code></pre> <p>If you want to sort only by first tuple</p> <pre><code>&gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; tups = [(('A','B'),2),(('C','B'),3), (('A','B'),1)] &gt;&gt;&gt; sorted(tups, key=itemgetter(0)) [(('A', 'B'), 2), (('A', 'B'), 1), (('C', 'B'), 3)] </code></pre> <p><strong>UPDATE</strong></p> <p>Time consumption. Input data is 100 records of</p> <pre><code>((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) </code></pre> <p><em>Results</em>:</p> <p>@AmiTarovy answer with sorting <em>only by first element of tuple</em></p> <pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; [(sorted(t[0]), t[1]) for t in tups]' 10000 loops, best of 3: 42.7 usec per loop 10000 loops, best of 3: 43.2 usec per loop 10000 loops, best of 3: 43.9 usec per loop </code></pre> <p>My answer with sorting <em>only by first element of tuple</em></p> <pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; sorted(tups, key=itemgetter(0))' 10000 loops, best of 3: 36.1 usec per loop 10000 loops, best of 3: 36.6 usec per loop 10000 loops, best of 3: 37.9 usec per loop </code></pre> <p>My answer with <em>whole sorting</em>, but first element in priority</p> <pre><code>python3 -m timeit -s "import random; import string; tups = [((random.choice(string.ascii_uppercase), random.choice(string.ascii_uppercase)), random.randint(0,100)) for i in range(100)]" 'from operator import itemgetter; sorted(tups, key=itemgetter(0,1))' 10000 loops, best of 3: 61 usec per loop 10000 loops, best of 3: 60.2 usec per loop 10000 loops, best of 3: 60.6 usec per loop </code></pre>
1
2016-09-27T16:24:56Z
[ "python", "python-3.x" ]
Sorting the tuples of tuples in alphabetical order
39,729,526
<p>I have a list of tuples<br> <code>[((A,B),2),((C,B),3)]</code> Which I need to sort as</p> <pre><code>[((A,B),2),((B,C),3)] </code></pre> <p>I need all the tuples to be in alphabetical order using the <code>sorted()</code> method. I have used <code>key = lambda x : x[0]</code> but doesn't work. Any ideas?</p>
-2
2016-09-27T16:10:18Z
39,730,024
<pre><code>l = [(('A','B'),2),(('C','B'),3)] f=[(tuple(sorted(x[0])),x[1]) for x in l] </code></pre> <p>Output :</p> <pre><code>[(('A', 'B'), 2), (('B', 'C'), 3)] </code></pre>
0
2016-09-27T16:38:30Z
[ "python", "python-3.x" ]
pytest parameterized session fixtures execute too many times
39,729,558
<p>Consider the following test code, which compares a mock run result with an expected result. The value of the run result depends on a value of a parameterized fixture paramfixture, which provides two values, so there are two possible variants of the run result. Since they are all session fixtures we should expect the run_result fixture execute only two times.</p> <p>Now, please take a look at the test case test_run_result, which receives the run_result and expected_result fixtures to compare, and also receives the tolerance fixture, which is parameterized with two values. The test case checks if the difference between expected and resulted falls within the tolerance. Note that the run does not depend on the tolerance.</p> <p>For some reason, which I don’t understand Pytest executes the run_result() fixture three times. Can you explain why? </p> <p>This was tested using pytest vers. 2.9.1</p> <p>By the way, the run_result fixture would execute only two times if the test case weren't parameterized or were parameterized using a decoractor instead of a fixture i.e.: @pytest.mark.parametrize('tolerance', [1e-8, 1e-11]).</p> <pre><code>import pytest runcounter = 0 @pytest.fixture(scope="session", params=[1e-8, 1e-11]) def tolerance(request): """Precision in floating point compare.""" return request.param @pytest.fixture(scope='session', params=[1, 2]) def paramfixture(request): return request.param @pytest.fixture(scope="session") def expected_result(paramfixture): return 1 + paramfixture @pytest.fixture(scope='session') def run_result(paramfixture): global runcounter runcounter = runcounter + 1 print "Run #", runcounter, 'param:', paramfixture return 1 + paramfixture def test_run_result(run_result, expected_result, tolerance): print "run_result: %d, expected_result: %d" % (run_result, expected_result) assert abs(run_result - expected_result) &lt; tolerance </code></pre> <p>Pytest screenshot:</p> <pre><code>$ py.test -vs test/end2end/test_temp.py ===================================================== test session starts ====================================================== platform linux2 -- Python 2.7.11, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- /home/f557010/.conda/envs/sfpdev/bin/python cachedir: .cache rootdir: /home/f557010/svndev/SFP, inifile: pytest.ini collected 4 items test/end2end/test_temp.py::test_run_result[1e-08-1] Run # 1 param: 1 run_result: 2, expected_result: 2 PASSED test/end2end/test_temp.py::test_run_result[1e-08-2] Run # 2 param: 2 run_result: 3, expected_result: 3 PASSED test/end2end/test_temp.py::test_run_result[1e-11-2] run_result: 3, expected_result: 3 PASSED test/end2end/test_temp.py::test_run_result[1e-11-1] Run # 3 param: 1 run_result: 2, expected_result: 2 PASSED =================================================== 4 passed in 0.01 seconds =================================================== </code></pre>
3
2016-09-27T16:12:05Z
39,734,025
<p>It appears to be running the test 4 times, not 3, which makes sense if it's doing an all-combinations run.</p> <ul> <li>Run #1: Param 1, Tolerance 1</li> <li>Run #2: Param 2, Tolerance 1</li> <li>Run #3: Param 1, Tolerance 2</li> <li>Run #4: Param 2, Tolerance 2</li> </ul> <p>Running four times seems to me like a reasonable approach given the test definition.</p>
0
2016-09-27T20:47:42Z
[ "python", "py.test" ]
pytest parameterized session fixtures execute too many times
39,729,558
<p>Consider the following test code, which compares a mock run result with an expected result. The value of the run result depends on a value of a parameterized fixture paramfixture, which provides two values, so there are two possible variants of the run result. Since they are all session fixtures we should expect the run_result fixture execute only two times.</p> <p>Now, please take a look at the test case test_run_result, which receives the run_result and expected_result fixtures to compare, and also receives the tolerance fixture, which is parameterized with two values. The test case checks if the difference between expected and resulted falls within the tolerance. Note that the run does not depend on the tolerance.</p> <p>For some reason, which I don’t understand Pytest executes the run_result() fixture three times. Can you explain why? </p> <p>This was tested using pytest vers. 2.9.1</p> <p>By the way, the run_result fixture would execute only two times if the test case weren't parameterized or were parameterized using a decoractor instead of a fixture i.e.: @pytest.mark.parametrize('tolerance', [1e-8, 1e-11]).</p> <pre><code>import pytest runcounter = 0 @pytest.fixture(scope="session", params=[1e-8, 1e-11]) def tolerance(request): """Precision in floating point compare.""" return request.param @pytest.fixture(scope='session', params=[1, 2]) def paramfixture(request): return request.param @pytest.fixture(scope="session") def expected_result(paramfixture): return 1 + paramfixture @pytest.fixture(scope='session') def run_result(paramfixture): global runcounter runcounter = runcounter + 1 print "Run #", runcounter, 'param:', paramfixture return 1 + paramfixture def test_run_result(run_result, expected_result, tolerance): print "run_result: %d, expected_result: %d" % (run_result, expected_result) assert abs(run_result - expected_result) &lt; tolerance </code></pre> <p>Pytest screenshot:</p> <pre><code>$ py.test -vs test/end2end/test_temp.py ===================================================== test session starts ====================================================== platform linux2 -- Python 2.7.11, pytest-2.9.1, py-1.4.31, pluggy-0.3.1 -- /home/f557010/.conda/envs/sfpdev/bin/python cachedir: .cache rootdir: /home/f557010/svndev/SFP, inifile: pytest.ini collected 4 items test/end2end/test_temp.py::test_run_result[1e-08-1] Run # 1 param: 1 run_result: 2, expected_result: 2 PASSED test/end2end/test_temp.py::test_run_result[1e-08-2] Run # 2 param: 2 run_result: 3, expected_result: 3 PASSED test/end2end/test_temp.py::test_run_result[1e-11-2] run_result: 3, expected_result: 3 PASSED test/end2end/test_temp.py::test_run_result[1e-11-1] Run # 3 param: 1 run_result: 2, expected_result: 2 PASSED =================================================== 4 passed in 0.01 seconds =================================================== </code></pre>
3
2016-09-27T16:12:05Z
39,734,916
<p><strong>pytest's parameterization is all about getting a fixture and holding on to it for a reasonable lifecycle</strong>. It does not cache all of the input->output mappings. This is not what you wated here but it makes sense if you consider fixtures being things like database connections or tcp connections (like the smtp in the examples).</p> <p>You still have a decent argument to make here that enough introspection and optimization on pytest's part would have benefited you (presuming here that run_result is very expensive and you wish to minimize runs).</p> <p>Why does it do "the wrong thing" here? If you look carefully at the fixtures, tolerance is the "first order" or closest parameterized fixture. </p> <p>An ugly, inscrutable change that "works":</p> <pre><code>@pytest.fixture(scope="session", params=[0.01, 0.0002]) def tol(request): """Precision in floating point compare.""" return request.param @pytest.fixture(scope="session") def tolerance(tol): """Precision in floating point compare.""" return tol </code></pre> <p>Why in the world would that work? It removed the tolerance param to the same "level" as the param on the other fixtures. With this, pytest does in fact only run the run_tests twice.</p> <pre><code>============================================ test session starts ============================================ &lt;snip&gt; collected 4 items test_tolerance.py::test_run_result[1-0.01] Run # 1 param: 1 run_result: 2, expected_result: 2 tolerance: 0.010000 PASSED test_tolerance.py::test_run_result[1-0.0002] run_result: 2, expected_result: 2 tolerance: 0.000200 PASSED test_tolerance.py::test_run_result[2-0.0002] Run # 2 param: 2 run_result: 3, expected_result: 3 tolerance: 0.000200 PASSED test_tolerance.py::test_run_result[2-0.01] run_result: 3, expected_result: 3 tolerance: 0.010000 PASSED ========================================= 4 passed in 0.01 seconds ========================================== </code></pre> <p><strong>Should you use that code? Please try not to</strong> as it is too hard to grok, if you use a hack like that, comment heavily to 'splain yourself. </p> <p>You asked "why" and the key here is that the params for tolerance and paramfixture are at different levels of nesting with the "closest" one being the one that will iterate slowest. fixtures aren't cached here, they are just used in a logical order, innermost iterating fastest.</p>
1
2016-09-27T21:53:10Z
[ "python", "py.test" ]
Execute Python scripts with Selenium via Crontab
39,729,710
<p>I have several python scripts that use selenium webdriver on a Debian server. If I run them manually from the terminal (usually as root) everything is ok but every time I tried to run them via crontab I have an exception like this:</p> <pre><code>WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmpQ4vStP If you specified a log_file in the FirefoxBinary constructor, check it for details. </code></pre> <p>Try for example this script:</p> <pre><code>from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from pyvirtualdisplay import Display from selenium import webdriver import datetime import logging FIREFOX_PATH = '/usr/bin/firefox' if __name__ == '__main__': cur_date = datetime.datetime.now().strftime('%Y-%m-%d') logging.basicConfig(filename="./logs/download_{0}.log".format(cur_date), filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') try: display = Display(visible=0, size=(800, 600)) display.start() print 'start' logging.info('start') binary = FirefoxBinary(FIREFOX_PATH, log_file='/home/egor/dev/test/logs/firefox_binary_log.log') driver = webdriver.Firefox() driver.get("http://google.com") logging.info('title: ' + driver.title) driver.quit() display.stop() except: logging.exception('') logging.info('finish') print 'finish' </code></pre> <p>The crontab command for it:</p> <pre><code>0 13 * * * cd "/home/egor/dev/test" &amp;&amp; python test.py </code></pre> <p>The log file for this script looks like this:</p> <pre><code>2016-09-27 16:30:01,742 - DEBUG - param: "['Xvfb', '-help']" 2016-09-27 16:30:01,743 - DEBUG - command: ['Xvfb', '-help'] 2016-09-27 16:30:01,743 - DEBUG - joined command: Xvfb -help 2016-09-27 16:30:01,745 - DEBUG - process was started (pid=23042) 2016-09-27 16:30:01,747 - DEBUG - process has ended 2016-09-27 16:30:01,748 - DEBUG - return code=0 2016-09-27 16:30:01,748 - DEBUG - stdout= 2016-09-27 16:30:01,751 - DEBUG - param: "['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1724']" 2016-09-27 16:30:01,751 - DEBUG - command: ['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1724'] 2016-09-27 16:30:01,751 - DEBUG - joined command: Xvfb -br -nolisten tcp -screen 0 800x600x24 :1724 2016-09-27 16:30:01,753 - DEBUG - param: "['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1725']" 2016-09-27 16:30:01,753 - DEBUG - command: ['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1725'] 2016-09-27 16:30:01,753 - DEBUG - joined command: Xvfb -br -nolisten tcp -screen 0 800x600x24 :1725 2016-09-27 16:30:01,755 - DEBUG - process was started (pid=23043) 2016-09-27 16:30:01,755 - DEBUG - DISPLAY=:1725 2016-09-27 16:30:01,855 - INFO - start 2016-09-27 16:30:31,965 - ERROR - Traceback (most recent call last): File "test.py", line 31, in &lt;module&gt; driver = webdriver.Firefox() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 103, in __init__ self.binary, timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 51, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 106, in _wait_until_connectable % (self.profile.path)) WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmpQ4vStP If you specified a log_file in the FirefoxBinary constructor, check it for details. 2016-09-27 16:30:31,966 - INFO - finish </code></pre> <p>What I have tried:</p> <ol> <li>Ensure that the script file is owned by root</li> <li>Use export DISPLAY=:0; or export DISPLAY=:99; in crontab command</li> <li>set the HOME variable in the crontab to the path of the home directory of the user that the cronjob was being run as</li> </ol> <p>I'm really stuck with this problem.</p> <p>I have python 2.7.10, selenium 2.53.6 with Xvbf and Firefox 47.0.1 on Debian 7.7</p>
2
2016-09-27T16:20:05Z
39,731,813
<p>Try a hardcoded Firefox binary <a href="https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_binary.html" rel="nofollow">https://seleniumhq.github.io/selenium/docs/api/py/webdriver_firefox/selenium.webdriver.firefox.firefox_binary.html</a></p> <pre><code>selenium.webdriver.firefox.firefox_binary.FirefoxBinary("/your/binary/location/firefox") driver = webdriver.Firefox(firefox_binary=binary) </code></pre>
0
2016-09-27T18:25:04Z
[ "python", "selenium", "debian", "crontab" ]
Execute Python scripts with Selenium via Crontab
39,729,710
<p>I have several python scripts that use selenium webdriver on a Debian server. If I run them manually from the terminal (usually as root) everything is ok but every time I tried to run them via crontab I have an exception like this:</p> <pre><code>WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmpQ4vStP If you specified a log_file in the FirefoxBinary constructor, check it for details. </code></pre> <p>Try for example this script:</p> <pre><code>from selenium.webdriver.firefox.firefox_binary import FirefoxBinary from pyvirtualdisplay import Display from selenium import webdriver import datetime import logging FIREFOX_PATH = '/usr/bin/firefox' if __name__ == '__main__': cur_date = datetime.datetime.now().strftime('%Y-%m-%d') logging.basicConfig(filename="./logs/download_{0}.log".format(cur_date), filemode='w', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') try: display = Display(visible=0, size=(800, 600)) display.start() print 'start' logging.info('start') binary = FirefoxBinary(FIREFOX_PATH, log_file='/home/egor/dev/test/logs/firefox_binary_log.log') driver = webdriver.Firefox() driver.get("http://google.com") logging.info('title: ' + driver.title) driver.quit() display.stop() except: logging.exception('') logging.info('finish') print 'finish' </code></pre> <p>The crontab command for it:</p> <pre><code>0 13 * * * cd "/home/egor/dev/test" &amp;&amp; python test.py </code></pre> <p>The log file for this script looks like this:</p> <pre><code>2016-09-27 16:30:01,742 - DEBUG - param: "['Xvfb', '-help']" 2016-09-27 16:30:01,743 - DEBUG - command: ['Xvfb', '-help'] 2016-09-27 16:30:01,743 - DEBUG - joined command: Xvfb -help 2016-09-27 16:30:01,745 - DEBUG - process was started (pid=23042) 2016-09-27 16:30:01,747 - DEBUG - process has ended 2016-09-27 16:30:01,748 - DEBUG - return code=0 2016-09-27 16:30:01,748 - DEBUG - stdout= 2016-09-27 16:30:01,751 - DEBUG - param: "['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1724']" 2016-09-27 16:30:01,751 - DEBUG - command: ['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1724'] 2016-09-27 16:30:01,751 - DEBUG - joined command: Xvfb -br -nolisten tcp -screen 0 800x600x24 :1724 2016-09-27 16:30:01,753 - DEBUG - param: "['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1725']" 2016-09-27 16:30:01,753 - DEBUG - command: ['Xvfb', '-br', '-nolisten', 'tcp', '-screen', '0', '800x600x24', ':1725'] 2016-09-27 16:30:01,753 - DEBUG - joined command: Xvfb -br -nolisten tcp -screen 0 800x600x24 :1725 2016-09-27 16:30:01,755 - DEBUG - process was started (pid=23043) 2016-09-27 16:30:01,755 - DEBUG - DISPLAY=:1725 2016-09-27 16:30:01,855 - INFO - start 2016-09-27 16:30:31,965 - ERROR - Traceback (most recent call last): File "test.py", line 31, in &lt;module&gt; driver = webdriver.Firefox() File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py", line 103, in __init__ self.binary, timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/extension_connection.py", line 51, in __init__ self.binary.launch_browser(self.profile, timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 68, in launch_browser self._wait_until_connectable(timeout=timeout) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/firefox/firefox_binary.py", line 106, in _wait_until_connectable % (self.profile.path)) WebDriverException: Message: Can't load the profile. Profile Dir: /tmp/tmpQ4vStP If you specified a log_file in the FirefoxBinary constructor, check it for details. 2016-09-27 16:30:31,966 - INFO - finish </code></pre> <p>What I have tried:</p> <ol> <li>Ensure that the script file is owned by root</li> <li>Use export DISPLAY=:0; or export DISPLAY=:99; in crontab command</li> <li>set the HOME variable in the crontab to the path of the home directory of the user that the cronjob was being run as</li> </ol> <p>I'm really stuck with this problem.</p> <p>I have python 2.7.10, selenium 2.53.6 with Xvbf and Firefox 47.0.1 on Debian 7.7</p>
2
2016-09-27T16:20:05Z
39,906,460
<p>The problem concerns environment variables: cron is started by the system and knows nothing about user environments.</p> <p>So, the solution to a problem is to make cron run a shell script that sets the needed environment variables first and then runs the script. In my case I needed to set the <code>PATH</code> varibable like this: <code>PATH=/root/anaconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin</code> Also, it may be useful to set <code>HOME</code> or <code>DISPLAY</code> varibles in some cases.</p>
0
2016-10-06T22:16:56Z
[ "python", "selenium", "debian", "crontab" ]
One colorbar for several subplots in symmetric logarithmic scaling
39,729,776
<p>I need to share the same colorbar for a row of subplots. Each subplot has a symmetric logarithmic scaling to the color function. Each of these tasks has a nice solution explained here on stackoverflow: <a href="https://stackoverflow.com/a/38940369/6418786">For sharing the color bar</a> and <a href="https://stackoverflow.com/a/39256959/6418786">for nicely formatted symmetric logarithmic scaling</a>.</p> <p>However, when I combine both tricks in the same code, the colorbar "forgets" that is is supposed to be symmetric logarithmic. Is there a way to work around this problem? </p> <p>Testing code is the following, for which I combined the two references above in obvious ways:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import ImageGrid from matplotlib import colors, ticker # Set up figure and image grid fig = plt.figure(figsize=(9.75, 3)) grid = ImageGrid(fig, 111, # as in plt.subplot(111) nrows_ncols=(1,3), axes_pad=0.15, share_all=True, cbar_location="right", cbar_mode="single", cbar_size="7%", cbar_pad=0.15, ) data = np.random.normal(size=(3,10,10)) vmax = np.amax(np.abs(data)) logthresh=4 logstep=1 linscale=1 maxlog=int(np.ceil(np.log10(vmax))) #generate logarithmic ticks tick_locations=([-(10**x) for x in xrange(-logthresh, maxlog+1, logstep)][::-1] +[0.0] +[(10**x) for x in xrange(-logthresh,maxlog+1, logstep)] ) # Add data to image grid for ax, z in zip(grid,data): print z im = ax.imshow(z, vmin=-vmax, vmax=vmax, norm=colors.SymLogNorm(10**-logthresh, linscale=linscale)) # Colorbar ax.cax.colorbar(im,ticks=tick_locations, format=ticker.LogFormatter()) ax.cax.toggle_label(True) #plt.tight_layout() # Works, but may still require rect paramater to keep colorbar labels visible plt.show() </code></pre> <p>The generated output is the following: <a href="http://i.stack.imgur.com/9TzpH.png" rel="nofollow"><img src="http://i.stack.imgur.com/9TzpH.png" alt="enter image description here"></a></p>
2
2016-09-27T16:24:59Z
39,733,039
<p>Based on the solution by Erba Aitbayev, I found that it suffices to replace the line</p> <pre><code>ax.cax.colorbar(im,ticks=tick_locations, format=ticker.LogFormatter()) </code></pre> <p>in the example code originally posted by the line </p> <pre><code>fig.colorbar(im,ticks=tick_locations, format=ticker.LogFormatter(), cax = ax.cax) </code></pre> <p>and everything works without the need to specify explicit dimensions for the colorbar. I have no idea why one works and the other doesn't, though. It would be good to add a corresponding comment <a href="https://stackoverflow.com/a/38940369/6418786">in the post on sharing colorbars</a>. I checked and the linear color scale in that example still works if colorbar is called as in the second of the two alternatives above. (I don't have sufficient reputation to add a comment there.)</p>
0
2016-09-27T19:42:09Z
[ "python", "matplotlib", "scaling", "subplot", "colorbar" ]
Tensorflow: why 'pip uninstall tensorflow' cannot find tensorflow
39,729,787
<p>I'm using Tensorflow-0.8 on Ubuntu14.04. I first install Tensorflow from sources and then setup Tensorflow for development according to the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#setting-up-tensorflow-for-development" rel="nofollow">official tutorial</a>. When I want to uninstall tensorflow using the following command</p> <pre><code>sudo pip uninstall tensorflow </code></pre> <p>I encountered the following error:</p> <pre><code>Can't uninstall 'tensorflow'. No files were found to uninstall </code></pre> <p>Could anyone tell me where is wrong?</p> <p>For your reference, the output of <code>pip show tensorflow</code> is</p> <pre><code>Name: tensorflow Version: 0.8.0 Location: /home/AIJ/tensorflow/_python_build Requires: numpy, six, protobuf, wheel </code></pre> <p>But I actually find another Tensorflow directory at </p> <pre><code>/usr/local/lib/python2.7/dist-packages/tensorflow </code></pre> <p>Besides, I also have a question about the general usage of Python. I have seen two quite similar directories in my system, i.e.</p> <pre><code>/usr/lib/python2.7/dist-packages /usr/local/lib/python2.7/dist-packages </code></pre> <p>Could any one tell me the differences between them? I noticed that everytime I use <code>sudo pip install &lt;package&gt;</code>, the package will be installed to <code>/usr/local/lib/python2.7/dist-packages</code>, could I instead install packages into <code>/usr/lib/python2.7/dist-packages</code> using <code>pip install</code>?</p> <p>Thanks a lot for your help in advance!</p>
4
2016-09-27T16:25:24Z
39,730,131
<p>I believe pip isn't installed for python2.7</p> <p>try :</p> <pre><code>pip -V </code></pre> <p>On my system for instance it says :</p> <pre><code>pip 8.1.2 from /usr/lib/python3.4/site-packages (python 3.4) </code></pre> <p>So basically using <code>pip uninstall</code> will only remove packages for python3.4 (and not python2.7).</p> <p>So I don't use pip binary as such, and rather, call pip module from inside python.</p> <p>In your case :</p> <pre><code>python2.7 -m pip uninstall tensorflow </code></pre>
0
2016-09-27T16:44:20Z
[ "python", "tensorflow", "uninstall" ]
Tensorflow: why 'pip uninstall tensorflow' cannot find tensorflow
39,729,787
<p>I'm using Tensorflow-0.8 on Ubuntu14.04. I first install Tensorflow from sources and then setup Tensorflow for development according to the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#setting-up-tensorflow-for-development" rel="nofollow">official tutorial</a>. When I want to uninstall tensorflow using the following command</p> <pre><code>sudo pip uninstall tensorflow </code></pre> <p>I encountered the following error:</p> <pre><code>Can't uninstall 'tensorflow'. No files were found to uninstall </code></pre> <p>Could anyone tell me where is wrong?</p> <p>For your reference, the output of <code>pip show tensorflow</code> is</p> <pre><code>Name: tensorflow Version: 0.8.0 Location: /home/AIJ/tensorflow/_python_build Requires: numpy, six, protobuf, wheel </code></pre> <p>But I actually find another Tensorflow directory at </p> <pre><code>/usr/local/lib/python2.7/dist-packages/tensorflow </code></pre> <p>Besides, I also have a question about the general usage of Python. I have seen two quite similar directories in my system, i.e.</p> <pre><code>/usr/lib/python2.7/dist-packages /usr/local/lib/python2.7/dist-packages </code></pre> <p>Could any one tell me the differences between them? I noticed that everytime I use <code>sudo pip install &lt;package&gt;</code>, the package will be installed to <code>/usr/local/lib/python2.7/dist-packages</code>, could I instead install packages into <code>/usr/lib/python2.7/dist-packages</code> using <code>pip install</code>?</p> <p>Thanks a lot for your help in advance!</p>
4
2016-09-27T16:25:24Z
39,734,013
<p>It could be because you didn't <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#pip-installation" rel="nofollow">install Tensorflow using <code>pip</code></a>, but using <code>python setup.py develop</code> instead as your <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#setting-up-tensorflow-for-development" rel="nofollow">link</a> shows.</p> <p><code>pip uninstall</code> is likely to fail if the package is installed using <code>python setup.py install</code> as they do not leave behind metadata to determine what files were installed.</p> <p>Therefore, you should be able to unistall Tensorflow with the option <code>-u</code> or <code>--unistall</code> of <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode" rel="nofollow"><code>develop</code></a></p> <pre><code>cd /home/AIJ/tensorflow/_python_build python setup.py develop --uninstall </code></pre> <p>To answer for the second (interestring) question about the two <code>dist-package</code> created under <code>/usr/lib/python2.7</code> and <code>/usr/local/lib/python2.7</code> it exists already a <a href="http://stackoverflow.com/questions/9387928/whats-the-difference-between-dist-packages-and-site-packages">great Stack Overflow answer</a> on the topic.</p> <p>PS: Tensorflow is a good library, you should consider <em>not</em> uninstall it :)</p>
1
2016-09-27T20:46:43Z
[ "python", "tensorflow", "uninstall" ]
Retrieving responses from a JSON File
39,729,956
<p>I'm trying to pull some values out of an JSON file but it doesn't seem to be working. Additionally, when I try to add print statements to see where it is blowing up, nothing prints. Can anyone see any glaring reason why this isn't working? The only thing I can think of is that it has something to do with the fact that I recently switched from a PC to a Mac and the files are stored as rtf's rather than txt's. </p> <pre><code>import glob2 import json fdr = glob2.glob('/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/*.rtf') #insert all rtf files in folder into list for dr in fdr: #loop through file list print(dr) ending = str(dr[57:]) #cut filename from pathname pe = ending.replace('.rtf', '') #add filename to path f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv' #format the file as csv f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe #access rtf file print(f_n) file_path = 'f_n' file_out = 'f_quest' with open(file_path) as f_in, open(file_out) as f_out: data = json.load(f_in) print(data.keys()) # list the dicts keys q = 'vviq' response = data[q]['response'] f_out.write('response') #write responses to new .csv file </code></pre>
-1
2016-09-27T16:34:29Z
39,736,439
<p>Your code outputs nothing because you create and open an empty file named <code>f_n</code> in the directory of the python script, then attempt to load it with the json module. </p> <p>These are variables that are assigned to <em>string literals</em>, not the variables you previously defined. </p> <pre><code>file_path = 'f_n' file_out = 'f_quest' </code></pre> <p>These are variables that are assigned to <em>paths on your system</em></p> <pre><code>f_quest = '/Users/KraemerLab-Justin/Desktop/CogStylesText/CogStylesExcel/QuestEx/' + pe + '.csv' #format the file as csv f_n = '/Users/Lab-Justin/Desktop/CogStylesText/TextFiles/' + pe #access rtf file </code></pre> <p>I assume you are wanting to open the later? If that is the case, then the former variables are completely pointless. And you should give these variables to <code>open()</code>, but don't quote the variable name. </p> <p>Also, <code>open()</code> defaults to read mode, so you might want to fix that when you attempt to do <code>f_out.write('response')</code>, which should be intended under the <code>with</code>, otherwise the file is closed, and again <code>'response'</code> is a string literal of the word "response" and not the <code>response</code> variable that you assigned in the previous line </p>
1
2016-09-28T00:57:10Z
[ "python", "json" ]
Pandas - column not found in dataframe
39,729,995
<p>I'm reading a csv file, frmo which I obtain these columns:</p> <pre><code>encoding = "UTF-8-SIG" csv_file = "my/path/to/file.csv" fields_cols_mapping = { 'brand_id': 'Brand', 'custom_dashboard': 'Custom Dashboard LO', 'custom_dashboard_isfeatured': 'Custom Dashboard LO - Is Featured', 'description': 'LODescription', 'is_active': 'TrainingIsActive', 'lo_id': 'LOID', 'lo_type_id': 'LOType', 'timestamp': 'Timestamp', 'title': 'LOTitle', 'training_version_id': 'TrainingVersion' } dataframe = pd.read_csv( csv_file, encoding=encoding, sep='|', usecols=[unicode(v) for v in fields_cols_mapping.values()], dtype={ k: object for k in fields_cols_mapping.keys() }, ) </code></pre> <p>However, while inspecting with ipdb I found that the parser called with <code>read_csv</code> doesn't convert the column name <code>Custom Dashboard LO – Is Featured</code>:</p> <pre><code># debug &gt; /../../venvs/myvenv/lib/python2.7/site-packages/pandas/io/parsers.py(1140)__init__() 1138 col_indices = [] 1139 for u in self.usecols: -&gt; 1140 if isinstance(u, string_types): 1141 col_indices.append(self.names.index(u)) 1142 else: ipdb&gt; self &lt;pandas.io.parsers.CParserWrapper object at 0x10b134710&gt; ipdb&gt; self.names [u'LOType', u'LOID', u'LOTitle', u'TrainingVersion', u'LODescription', u'TrainingIsActive', u'Custom Dashboard LO', u'Brand', u'Custom Dashboard LO \u2013 Is Featured', u'Timestamp'] </code></pre> <p>Does anybody have any suggestions about what I should do?</p>
2
2016-09-27T16:36:48Z
39,730,179
<p>Your problem is that the dash in the dataframe isn't the same as the dash in the dictionary. The one in the dataframe is an en dash (<code>–</code> or <code>\u2013</code>), while the one in your dictionary is a hyphen (<code>‐</code> or <code>\u2010</code>). They look similar, but they're not the same character, so the strings don't match.</p>
1
2016-09-27T16:46:09Z
[ "python", "pandas", "utf-8" ]
Pandas - column not found in dataframe
39,729,995
<p>I'm reading a csv file, frmo which I obtain these columns:</p> <pre><code>encoding = "UTF-8-SIG" csv_file = "my/path/to/file.csv" fields_cols_mapping = { 'brand_id': 'Brand', 'custom_dashboard': 'Custom Dashboard LO', 'custom_dashboard_isfeatured': 'Custom Dashboard LO - Is Featured', 'description': 'LODescription', 'is_active': 'TrainingIsActive', 'lo_id': 'LOID', 'lo_type_id': 'LOType', 'timestamp': 'Timestamp', 'title': 'LOTitle', 'training_version_id': 'TrainingVersion' } dataframe = pd.read_csv( csv_file, encoding=encoding, sep='|', usecols=[unicode(v) for v in fields_cols_mapping.values()], dtype={ k: object for k in fields_cols_mapping.keys() }, ) </code></pre> <p>However, while inspecting with ipdb I found that the parser called with <code>read_csv</code> doesn't convert the column name <code>Custom Dashboard LO – Is Featured</code>:</p> <pre><code># debug &gt; /../../venvs/myvenv/lib/python2.7/site-packages/pandas/io/parsers.py(1140)__init__() 1138 col_indices = [] 1139 for u in self.usecols: -&gt; 1140 if isinstance(u, string_types): 1141 col_indices.append(self.names.index(u)) 1142 else: ipdb&gt; self &lt;pandas.io.parsers.CParserWrapper object at 0x10b134710&gt; ipdb&gt; self.names [u'LOType', u'LOID', u'LOTitle', u'TrainingVersion', u'LODescription', u'TrainingIsActive', u'Custom Dashboard LO', u'Brand', u'Custom Dashboard LO \u2013 Is Featured', u'Timestamp'] </code></pre> <p>Does anybody have any suggestions about what I should do?</p>
2
2016-09-27T16:36:48Z
39,733,540
<p>Thanks. I changed the dict value but:</p> <pre><code>In [130]: dataframe = pd.read_csv( ...: lo_csv_path, ...: encoding=encoding_l, ...: sep='|', ...: usecols=[unicode(v) for v in fields_cols_mapping.values()], ...: dtype={ k: object for k in fields_cols_mapping.keys() }, ...: ) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) &lt;ipython-input-130-670241506984&gt; in &lt;module&gt;() 3 encoding=encoding_l, 4 sep='|', ----&gt; 5 usecols=[unicode(v) for v in fields_cols_mapping.values()], 6 dtype={ k: object for k in fields_cols_mapping.keys() }, 7 ) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 20: ordinal not in range(128) </code></pre>
0
2016-09-27T20:14:56Z
[ "python", "pandas", "utf-8" ]
Python 3: Tkinter OptionMenu Detect Change & Pass Variables
39,730,004
<p>So I am working on my first "large" python project (second GUI), and it is a simple SQLite database manager. As of now, this is what it looks like... <a href="http://i.stack.imgur.com/GPTlJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/GPTlJ.png" alt="Current state of database manager."></a></p> <p>At the top, as you can see, there is a change table button and a drop-down to select what table you wish to switch to. </p> <p>What I want to do is to remove the button, replace it with an ordenary label(This is easy to do), and then have the OptionMenu change the table a different one is selected automatically.</p> <p>This is what I have for the changing.</p> <pre><code>def change(self, root, c, tableToChangeTo, table, list_columns): table = tableToChangeTo.get() cursor = c.execute('select Rowid, * from ' + table) list_columns = [description[0] for description in cursor.description] self.clear() self.table(root, c, table, list_columns) self.addGui(root, c, table, list_columns) self.editGui(root, c, table, list_columns) self.delGui(root, c, table, list_columns) self.changeGui(root, c, table, list_columns) def changeGui(self, root, c, table, list_columns): gridRow = self.rowTotal self.changeButton = Button(root, text="Change Table", command= lambda: self.change(root, c, var, table, list_columns)) self.changeButton.grid(row = 0 , column = 0) var = StringVar(root) var.set(table) options = {""} global tableList ta = tableList for t in ta: options.add(t) self.changeOption = OptionMenu(root, var, *options) self.changeOption.grid(row = 0, column = 1) </code></pre> <p>So to make it short and sweet, I want to make it where when you select another table, it will automatically run the change method. The big problem is I can not seem to figure out how to make a method an event while at the same time being able to pass variables to it.</p> <p>So thank you for any help, and if you need anything else, let me know!</p>
1
2016-09-27T16:37:21Z
39,760,951
<p>For anyone else having the same problem as me, I was able to get mine working by using this line of code.</p> <pre><code>self.changeOption = OptionMenu(root, var, *options, command= lambda event: self.change(event,root, c, var, table, list_columns)) </code></pre>
0
2016-09-29T03:31:17Z
[ "python", "sqlite", "python-3.x", "user-interface", "tkinter" ]
how to trigger function in another object when variable changed. Python
39,730,037
<p>As far as I know, this is like an Observer pattern. Scenario: <strong>A Center object keeps a list (queue) of all its clients.</strong> I'm using Twisted.</p> <ol> <li>One of client objects <strong>changes a variable</strong> in center object OR notify the center to change the variable, </li> <li>and then the center object <strong>detects the change</strong> immediately; </li> <li>then as soon as the detection, the center object invoke some function <strong>of next object</strong> in queue</li> <li>After the client changed the variable, <strong>the client object will be <em>eliminated.</em></strong> The center will take care of next client object. So I imagine there's no any function chain between these objects. So it's a little bit different from observer pattern. (How to address this issue? Correct me if I'm wrong.)</li> </ol> <p>following code is just for demo only:</p> <pre><code> class client(): def change(self): self.center.va = 1 def inqueue(self): self.center.queue.enqueue(self) def function(self): pass class center(): def __init__(self): self.queue = None self.va = 0 #### When the self.va changes, this func will be invoked def whenChanged(self): next = self.queue.dequeue() next.function() </code></pre>
3
2016-09-27T16:39:21Z
39,730,108
<p>Make <code>va</code> a property.</p> <pre><code>class Center(): def __init__(self): self.queue = None self._va = 0 @property def va(self): return self._va @va.setter def va(self, value): self._va = value self.whenChanged() def whenChanged(self): next = self.queue.dequeue() next.function() </code></pre>
4
2016-09-27T16:43:07Z
[ "python" ]
how to trigger function in another object when variable changed. Python
39,730,037
<p>As far as I know, this is like an Observer pattern. Scenario: <strong>A Center object keeps a list (queue) of all its clients.</strong> I'm using Twisted.</p> <ol> <li>One of client objects <strong>changes a variable</strong> in center object OR notify the center to change the variable, </li> <li>and then the center object <strong>detects the change</strong> immediately; </li> <li>then as soon as the detection, the center object invoke some function <strong>of next object</strong> in queue</li> <li>After the client changed the variable, <strong>the client object will be <em>eliminated.</em></strong> The center will take care of next client object. So I imagine there's no any function chain between these objects. So it's a little bit different from observer pattern. (How to address this issue? Correct me if I'm wrong.)</li> </ol> <p>following code is just for demo only:</p> <pre><code> class client(): def change(self): self.center.va = 1 def inqueue(self): self.center.queue.enqueue(self) def function(self): pass class center(): def __init__(self): self.queue = None self.va = 0 #### When the self.va changes, this func will be invoked def whenChanged(self): next = self.queue.dequeue() next.function() </code></pre>
3
2016-09-27T16:39:21Z
39,730,178
<p>Whenever a property of class is changed, <a href="https://docs.python.org/2/library/functions.html#setattr" rel="nofollow"><code>setattr()</code></a> function is called. You can override this by defining <a href="https://docs.python.org/3/reference/datamodel.html#object.__setattr__" rel="nofollow"><code>__setattr__(self, property, value)</code></a> function in your class.</p> <p>You need to make you required function call within this <code>__ setattr__()</code>. Below is the sample example based on your requirement:</p> <pre><code>class Centre(object): def __init__(self): self.queue = None self.va = 0 def whenChanged(self): next = self.queue.dequeue() next.function() def __setattr__(self, key, value): self.key = value self.whenChanged() &lt;-- Your function </code></pre> <p>Whenever you will attempt to change the value of any of class's property, this <code>__settattr__</code> function will be called.</p>
2
2016-09-27T16:46:09Z
[ "python" ]
how to use get_object_or_404 with order_by('?') to get random image
39,730,105
<p>I want to get random object from model but if there are no data in database I want to return 404 page.</p> <p>This line of code works for me well:</p> <pre><code> dummy_image=DummyImage.objects.order_by('?').first().image_url.url </code></pre> <p>but I want to use the <code>get_object_or_404</code> shortcut.</p> <p>So I tried this:</p> <pre><code>dummy_image = get_object_or_404(DummyImage).order('?').first().image_url.url </code></pre> <p>but it dosent't work and causes issues. It says that it returned more than two objects.</p> <p>How do I solve the problem?</p>
2
2016-09-27T16:42:43Z
39,730,200
<p>The <code>get_object_or_404</code> shortcut uses <code>get()</code>, so it will raise an error if the filtered queryset returns more than one object. </p> <p>You could slice the queryset to limit it to one object:</p> <pre><code>dummy_image = get_object_or_404(DummyImage.objects.order_by('?')[:1]).image_url.url </code></pre> <p>Alternatively, you could raise the <code>Http404</code> exception manually. This code is a bit longer but you might find it clearer what is going on.</p> <pre><code>from django.http import Http404 dummy_image = DummyImage.objects.order_by('?').first() if dummy_image is None: raise Http404 else: dummy_image = dummy_image.image_url.url </code></pre>
2
2016-09-27T16:46:59Z
[ "python", "django" ]
Skimage : rotate image and fill the new formed background
39,730,114
<p>When rotating an image using</p> <pre><code>import skimage result = skimage.transform.rotate(img, angle=some_angle, resize=True) # the result is the rotated image with black 'margins' that fill the blanks </code></pre> <p>The algorithm rotates the image but leaves the newly formed background black and there is no way - using the rotate function - to choose the color of the newly formed background.</p> <p>Do you have any idea how to do choose the color of the background before rotating an image?</p> <p>Thank you.</p>
1
2016-09-27T16:43:29Z
39,730,938
<p>I don't know how do it, but maybe this help you </p> <pre><code>http://scikit-image.org/docs/dev/api/skimage.color.html </code></pre> <p>Good luck! ;)</p>
0
2016-09-27T17:30:18Z
[ "python", "skimage" ]
Skimage : rotate image and fill the new formed background
39,730,114
<p>When rotating an image using</p> <pre><code>import skimage result = skimage.transform.rotate(img, angle=some_angle, resize=True) # the result is the rotated image with black 'margins' that fill the blanks </code></pre> <p>The algorithm rotates the image but leaves the newly formed background black and there is no way - using the rotate function - to choose the color of the newly formed background.</p> <p>Do you have any idea how to do choose the color of the background before rotating an image?</p> <p>Thank you.</p>
1
2016-09-27T16:43:29Z
39,731,489
<p>if your pic is a gray picture,use <code>cval</code> ; if pic is rgb ,no good way,blow code works:</p> <pre><code>path3=r'C:\\Users\forfa\Downloads\1111.jpg' img20=data.imread(path3) import numpy as np img3=transform.rotate(img20,45,resize=True,cval=0.1020544) #0.1020544 can be any unique float,the pixel outside your pic is [0.1020544]*3 c,r,k=img3.shape for i in range(c): for j in range(r): if np.allclose(img3[i][j],[0.1020544]*3): img3[i][j]=[1,0,0] #[1,0,0] is red pixel,replace pixel [0.1020544]*3 with red pixel [1,0,0] </code></pre>
0
2016-09-27T18:05:01Z
[ "python", "skimage" ]
How to import a simple class in working directory with python?
39,730,129
<p>I read various answer (<a href="http://stackoverflow.com/questions/16981921/relative-imports-in-python-3">relative import</a>), but none work to import a simple class. I have this structure:</p> <pre><code>__init__.py (empty) my_script.py other_script.py my_class.py </code></pre> <p>I want to use <strong>my_class.py</strong> in both script (<strong>my_script.py</strong> and <strong>other_script.py</strong>). Like all answer suggest, I just use:</p> <pre><code>from .my_class import My_class </code></pre> <p>but I always get</p> <blockquote> <p>SystemError: Parent module '' not loaded, cannot perform relative import</p> </blockquote> <p>I am using <strong>Python 3.5</strong> and <strong>PyCharm 2016.1.2</strong>. Does I need to configure the <code>__init__.py</code>? How can I import a simple class?</p> <p><strong>Edit</strong></p> <p>All the files are in the working directory. I just use the Pycharm to run and I wasn't having problem until try to import the class. </p>
1
2016-09-27T16:44:15Z
39,730,222
<p>Ensure that your current working directory is <strong><em>not</em></strong> the one that contains these files. For example, if the path to <code>__init__.py</code> is <code>spam/eggs/__init__.py</code>, make sure you are working in directory <code>spam</code>—or alternatively, that <code>/path/to/spam</code> is in <code>sys.path</code> and you are working in some third place. Either way, do not attempt to work in directory <code>eggs</code>. To test your code, you say <code>import eggs</code>.</p> <p>The reasoning is as follows. Since you're using <code>__init__.py</code> you clearly want to treat this collection of files as a <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow">package</a>. To work as a package, a directory must fulfill both the following criteria:</p> <ol> <li>it contains a file called <code>__init__.py</code></li> <li>its <strong><em>parent</em></strong> directory is part of the search path (or the parent directory is your current working directory); in effect, a package directory must masquerade as a file, i.e. be findable in exactly the same way that a single-file module might be found.</li> </ol> <p>If you're working <em>inside</em> the package directory you may not be fulfilling criterion 2. You can do a straightforward <code>import my_class</code> from there, certainly, but the "relative import" thing you're trying is a feature that only a fully-working package will support.</p>
1
2016-09-27T16:48:13Z
[ "python", "pycharm" ]
Python - Stacking two histograms with a scatter plot
39,730,184
<p>Having an example code for a scatter plot along with their histograms </p> <pre><code>x = np.random.rand(5000,1) y = np.random.rand(5000,1) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.scatter(x, y, facecolors='none') ax.set_xlim(0,1) ax.set_ylim(0,1) fig1 = plt.figure(figsize=(7,7)) ax1 = fig1.add_subplot(111) ax1.hist(x, bins=25, fill = None, facecolor='none', edgecolor='black', linewidth = 1) fig2 = plt.figure(figsize=(7,7)) ax2 = fig2.add_subplot(111) ax2.hist(y, bins=25 , fill = None, facecolor='none', edgecolor='black', linewidth = 1) </code></pre> <p>What I'm wanting to do is to create this graph with the histograms attached to their respected axis almost like this example</p> <p><a href="http://i.stack.imgur.com/ZIcFZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZIcFZ.png" alt="enter image description here"></a></p> <p>I'm familiar with stacking and merging the x-axis</p> <pre><code>f, (ax1, ax2, ax3) = plt.subplots(3) ax1.scatter(x, y) ax2.hist(x, bins=25, fill = None, facecolor='none', edgecolor='black', linewidth = 1) ax3.hist(y, bins=25 , fill = None, facecolor='none', edgecolor='black', linewidth = 1) f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) </code></pre> <p><a href="http://i.stack.imgur.com/doW0u.png" rel="nofollow"><img src="http://i.stack.imgur.com/doW0u.png" alt="enter image description here"></a></p> <p>But I have no idea how to attach the histograms to the y axis and x axis like in the picture I posted above, and on top of that, how to vary the size of the graphs (ie make the scatter plot larger and the histograms smaller in comparison)</p>
2
2016-09-27T16:46:23Z
39,730,720
<p>I think it's hard to do this solely with <code>matplotlib</code> but you can use <code>seaborn</code> which has <code>jointplot</code> function. </p> <pre><code>import numpy as np import pandas as pd import seaborn as sns sns.set(color_codes=True) x = np.random.rand(1000,1) y = np.random.rand(1000,1) data = np.column_stack((x,y)) df = pd.DataFrame(data, columns=["x", "y"]) sns.jointplot(x="x", y="y", data=df); </code></pre> <p><a href="http://i.stack.imgur.com/wSjbD.png" rel="nofollow"><img src="http://i.stack.imgur.com/wSjbD.png" alt="enter image description here"></a></p>
0
2016-09-27T17:17:54Z
[ "python", "numpy", "matplotlib", "plot" ]
Python - Stacking two histograms with a scatter plot
39,730,184
<p>Having an example code for a scatter plot along with their histograms </p> <pre><code>x = np.random.rand(5000,1) y = np.random.rand(5000,1) fig = plt.figure(figsize=(7,7)) ax = fig.add_subplot(111) ax.scatter(x, y, facecolors='none') ax.set_xlim(0,1) ax.set_ylim(0,1) fig1 = plt.figure(figsize=(7,7)) ax1 = fig1.add_subplot(111) ax1.hist(x, bins=25, fill = None, facecolor='none', edgecolor='black', linewidth = 1) fig2 = plt.figure(figsize=(7,7)) ax2 = fig2.add_subplot(111) ax2.hist(y, bins=25 , fill = None, facecolor='none', edgecolor='black', linewidth = 1) </code></pre> <p>What I'm wanting to do is to create this graph with the histograms attached to their respected axis almost like this example</p> <p><a href="http://i.stack.imgur.com/ZIcFZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZIcFZ.png" alt="enter image description here"></a></p> <p>I'm familiar with stacking and merging the x-axis</p> <pre><code>f, (ax1, ax2, ax3) = plt.subplots(3) ax1.scatter(x, y) ax2.hist(x, bins=25, fill = None, facecolor='none', edgecolor='black', linewidth = 1) ax3.hist(y, bins=25 , fill = None, facecolor='none', edgecolor='black', linewidth = 1) f.subplots_adjust(hspace=0) plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False) </code></pre> <p><a href="http://i.stack.imgur.com/doW0u.png" rel="nofollow"><img src="http://i.stack.imgur.com/doW0u.png" alt="enter image description here"></a></p> <p>But I have no idea how to attach the histograms to the y axis and x axis like in the picture I posted above, and on top of that, how to vary the size of the graphs (ie make the scatter plot larger and the histograms smaller in comparison)</p>
2
2016-09-27T16:46:23Z
39,731,383
<p>Seaborn is the way to go for quick statistical plots. But if you want to avoid another dependency you can use <a href="http://matplotlib.org/users/gridspec.html" rel="nofollow" title="subplot2grid"><code>subplot2grid</code></a> to place the subplots and the keywords <code>sharex</code> and <code>sharey</code> to make sure the axes are synchronized.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt x = np.random.randn(100) y = np.random.randn(100) scatter_axes = plt.subplot2grid((3, 3), (1, 0), rowspan=2, colspan=2) x_hist_axes = plt.subplot2grid((3, 3), (0, 0), colspan=2, sharex=scatter_axes) y_hist_axes = plt.subplot2grid((3, 3), (1, 2), rowspan=2, sharey=scatter_axes) scatter_axes.plot(x, y, '.') x_hist_axes.hist(x) y_hist_axes.hist(y, orientation='horizontal') </code></pre> <p><a href="http://i.stack.imgur.com/ZtA7q.png" rel="nofollow"><img src="http://i.stack.imgur.com/ZtA7q.png" alt="plot"></a></p> <p>You should always look at the <a href="http://matplotlib.org/gallery.html" rel="nofollow" title="Matplotlib gallery">matplotlib gallery</a> before asking how to plot something, chances are that it will save you a few keystrokes -- I mean you won't have to ask. There are actually two plots like this in the gallery. Unfortunately the code is old and does not take advantage of <code>subplot2grid</code>, <a href="http://matplotlib.org/examples/pylab_examples/scatter_hist.html" rel="nofollow">the first one</a> uses rectangles and the <a href="http://matplotlib.org/examples/axes_grid/scatter_hist.html" rel="nofollow">second one</a> uses <code>axes_grid</code>, which is a somewhat weird beast. That's why I posted this answer.</p>
2
2016-09-27T17:59:13Z
[ "python", "numpy", "matplotlib", "plot" ]
How can I update a list of lists very quickly in a thread-safe manner? - python
39,730,199
<p>I am writing a script to add a "column" to a Python list of lists at 500 Hz. Here is the code that generates test data and passes it through a separate thread:</p> <pre><code># fileA import random, time, threading data = [[] for _ in range(4)] # list with 4 empty lists (4 rows) column = [random.random() for _ in data] # synthetic column of data def synthesize_data(): while True: for x,y in zip(data,column): x.append(y) time.sleep(0.002) # equivalent to 500 Hz t1 = threading.Thread(target=synthesize_data).start() # example of data # [[0.61523098235, 0.61523098235, 0.61523098235, ... ], # [0.15090349809, 0.15090349809, 0.15090349809, ... ], # [0.92149878571, 0.92149878571, 0.92149878571, ... ], # [0.41340918409, 0.41340918409, 0.41340918409, ... ]] # fileB (in Jupyter Notebook) [1] import fileA, copy [2] # get a copy of the data at this instant. data = copy.deepcopy(fileA.data) for row in data: print len(row) </code></pre> <p>If you run cell [2] in fileB, you should see that the lengths of the "rows" in <code>data</code> are not equal. Here is example output when I run the script:</p> <pre><code>8784 8786 8787 8787 </code></pre> <p>I thought I might be grabbing the data in the middle of the <code>for</code> loop, but that would suggest that the lengths would be off by 1 at the most. The differences get more severe over time. <strong>My question: why is quickly adding columns to a list of lists unstable?</strong> Is it possible to make this process for stable?</p> <p>You might suggest I use something like Pandas, but I want to use Python lists because of their speed advantage (the code needs to be as fast as possible). I tested the <code>for</code> loop, <code>map()</code> function, and Pandas data frame. Here is my test code (in Jupyter Notebook):</p> <pre><code># Setup code import pandas as pd import random channels = ['C3','C4','C5','C2'] a = [[] for _ in channels] b = [random.random() for _ in a] def add_col((x,y)): x.append(y); df = pd.DataFrame(index=channels) b_pandas = pd.Series(b, index=df.index) %timeit for x,y in zip(a,b): x.append(y) # 1000000 loops, best of 3: 1.32 µs per loop %timeit map(add_col, zip(a,b)) # 1000000 loops, best of 3: 1.96 µs per loop %timeit df[0] = b # 10000 loops, best of 3: 82.8 µs per loop %timeit df[0] = b_pandas # 10000 loops, best of 3: 58.4 µs per loop </code></pre> <p>You might also suggest that I append the samples to <code>data</code> as rows and then transpose when it's time to analyze. I would rather not do that also in the interest of speed. This code will be used in a brain-computer interface, where analysis happens in a loop. Transposing would also have to happen in the loop, and this would get slow as the data grows.</p> <p>edit: changed title from "Why is quickly adding columns to a list of lists unstable - python" to "How can I update a list of lists very quickly in a thread-safe manner? - python" to make the title more descriptive of the post and the answer.</p>
2
2016-09-27T16:46:58Z
39,730,321
<p>The <code>deepcopy()</code> operation is copying lists <em>as they are modified by another thread</em>, and each copy operation takes a small amount of time (longer as the lists grow larger). So between copying the first of the 4 lists and copying the second, the other thread added 2 elements, indicating that copying a list of 8784 elements takes between 0.002 and 0.004 seconds.</p> <p>That's because there is nothing preventing threading to switch between executing <code>synthesize_data()</code> and the <code>deepcopy.copy()</code> call. In other words, your code is simply not thread-safe.</p> <p>You'd have to coordinate between your two threads; using a lock for example:</p> <p>In <code>fileA</code>:</p> <pre><code># ... datalock = threading.RLock() # ... def synthesize_data(): while True: with datalock: for x,y in zip(data,column): x.append(y) time.sleep(0.002) # equivalent to 500 Hz </code></pre> <p>and in <code>fileB</code>:</p> <pre><code>with fileA.datalock: data = copy.deepcopy(fileA.data) for row in data: print len(row) </code></pre> <p>This ensures that copying only takes place when the thread in <code>fileA</code> is not trying to add more to the lists.</p> <p>Using locking will slow down your operations; I suspect the pandas assignment operations are already <a href="http://stackoverflow.com/questions/13592618/python-pandas-dataframe-thread-safe">subject to locks to keep them thread-safe</a>.</p>
4
2016-09-27T16:53:58Z
[ "python", "multithreading", "list", "python-2.7" ]
Extracting certain date and time using regex
39,730,226
<p>Regex expression tested using <a href="http://pythex.org/" rel="nofollow">http://pythex.org/</a> </p> <blockquote> <p>Expression: (\d{2})/.-/.-\s([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$</p> </blockquote> <p>I only want to be able to print out 30/06/2016 17:15 as two individual variable. The above cant work! can anybody enlighten me on my expression? It seems to be matching "30/06/2016 17:15" exactly only </p>
1
2016-09-27T16:48:24Z
39,730,335
<p>It works fine using a combination of <code>ast.literal_eval</code> and <code>re</code>:</p> <p><code>ast.literal_eval</code> gets rid of the <code>tuple</code>-like structure for you. The rest is a piece of cake.</p> <p>This solution is more robust than regex-only solutions:</p> <pre><code>import ast,re a = "('=====================================', '30/06/2016 17:15 T001 201603301', 'ORDER: C002946', 'Cashier: 001', '--------------------------------------')" t=ast.literal_eval(a) z=re.compile(r"(\d\d/\d\d/\d\d\d\d)\s(\d\d:\d\d)") m = z.match(t[1]) if m: print("date: {}, time {}".format(m.group(1),m.group(2))) </code></pre> <p>Result:</p> <pre><code>date: 30/06/2016, time 17:15 </code></pre> <p>Remarks:</p> <ul> <li>The regex is not optimal, but that's not the hardest part once the tuple is read and parsed.</li> <li>Maybe it would be even better to get a real <code>time</code> structure using <code>time.strptime</code> (no need for regex in that case).</li> </ul>
0
2016-09-27T16:54:42Z
[ "python", "regex" ]
Checking that an object exists in DB (Django)
39,730,244
<p>Consider this Django code:</p> <pre><code>class User(models.Model): name = models.CharField(null=True, blank=False, verbose_name=_("Name"), help_text='User Name', max_length=256) class UsersGroup(models.Model): name = models.CharField(null=False, blank=False, verbose_name=_("Name"), help_text='Users Group Name', max_length=256) users = models.ManyToManyField(User) # ... with transaction.atomic(): group.users.add(user) </code></pre> <p>What if the user was deleted from the DB before the transaction starts? It would add an nonexistent user to <code>group.users</code>. This is an error.</p> <p>What to do in this situation to preserve DB integrity?</p>
1
2016-09-27T16:50:11Z
39,730,298
<p>You would just add the get in the <code>transaction.atomic</code> block:</p> <pre><code>with transaction.atomic(): user = User.objects.get(name='stackoverflow') group.users.add(user) </code></pre>
0
2016-09-27T16:52:52Z
[ "python", "django", "transactions", "referential-integrity" ]
Checking that an object exists in DB (Django)
39,730,244
<p>Consider this Django code:</p> <pre><code>class User(models.Model): name = models.CharField(null=True, blank=False, verbose_name=_("Name"), help_text='User Name', max_length=256) class UsersGroup(models.Model): name = models.CharField(null=False, blank=False, verbose_name=_("Name"), help_text='Users Group Name', max_length=256) users = models.ManyToManyField(User) # ... with transaction.atomic(): group.users.add(user) </code></pre> <p>What if the user was deleted from the DB before the transaction starts? It would add an nonexistent user to <code>group.users</code>. This is an error.</p> <p>What to do in this situation to preserve DB integrity?</p>
1
2016-09-27T16:50:11Z
39,730,392
<p>You can use exceptions to handle it as well:</p> <pre><code> try: group.users.add(User.objects.get(name='Julian')) except: # handle the error - user doesn't exist </code></pre>
0
2016-09-27T16:57:44Z
[ "python", "django", "transactions", "referential-integrity" ]
Checking that an object exists in DB (Django)
39,730,244
<p>Consider this Django code:</p> <pre><code>class User(models.Model): name = models.CharField(null=True, blank=False, verbose_name=_("Name"), help_text='User Name', max_length=256) class UsersGroup(models.Model): name = models.CharField(null=False, blank=False, verbose_name=_("Name"), help_text='Users Group Name', max_length=256) users = models.ManyToManyField(User) # ... with transaction.atomic(): group.users.add(user) </code></pre> <p>What if the user was deleted from the DB before the transaction starts? It would add an nonexistent user to <code>group.users</code>. This is an error.</p> <p>What to do in this situation to preserve DB integrity?</p>
1
2016-09-27T16:50:11Z
39,731,013
<p>If a user does not exist while adding into groups then the query will fail in database raising IntegrityError with message as follows:</p> <pre><code>IntegrityError: insert or update on table "app1_usersgroup_users" violates foreign key constraint "app1_usersgroup_users_user_id_96d48fc7_fk_polls_user_id" DETAIL: Key (user_id)=(3) is not present in table "polls_user". </code></pre>
1
2016-09-27T17:35:03Z
[ "python", "django", "transactions", "referential-integrity" ]
How do I find the first occurrence of a vowel and move it behind the original word (pig latin)?
39,730,254
<p>I need to find the first vowel of a string in python, and I'm a beginner. I'm instructed to move the characters before the first vowel to the end of the word and add '-ay'. For example "big" becomes "ig-bay" and "string" becomes "ing-stray" (piglatin, basically).</p> <p>This is what I have so far:</p> <pre><code>def convert(s): ssplit = s.split() beginning = "" for char in ssplit: if char in ('a','e','i','o','u'): end = ssplit[char:] strend = str(end) else: beginning = beginning + char return strend + "-" + beginning + "ay" </code></pre> <p>I need to find a way to stop the "if" statement from looking for further vowels after finding the first vowel - at least I think it's the problem. Thanks!</p>
2
2016-09-27T16:50:44Z
39,730,307
<p>Add a <code>break</code> where you want the for loop to end: <a href="https://docs.python.org/2/tutorial/controlflow.html" rel="nofollow">https://docs.python.org/2/tutorial/controlflow.html</a></p>
0
2016-09-27T16:53:30Z
[ "python", "findfirst" ]