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 r... | 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 pres... | 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 ... | 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 sof... | 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] => [1,2,3] and [4,5,6]
and [1,2,3,4,5] => [1,2] and [4,5]
</code></pre>
<p>I ... | -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] => [1,2,3] and [4,5,6]
and [1,2,3,4,5] => [1,2] and [4,5]
</code></pre>
<p>I ... | -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] => [1,2,3] and [4,5,6]
and [1,2,3,4,5] => [1,2] and [4,5]
</code></pre>
<p>I ... | -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] => [1,2,3] and [4,5,6]
and [1,2,3,4,5] => [1,2] and [4,5]
</code></pre>
<p>I ... | -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 spli... | 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 ... | 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 conten... | 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 ... | 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, t... | 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 -... | 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)... | 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 -... | 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 ex... | 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... | 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={}
f... | 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... | 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':... | 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... | 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... | 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:<... | 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().d... | 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(... | 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:
... | 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(... | 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
... | 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():
... | 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():
... | 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>... | 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():
... | 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():
... | 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... | 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 %}
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
... | 0 | 2016-09-27T14:22:01Z | 39,728,532 | <p>The problem comes from here <code><a href="{{ url_for('post')}}"></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 ba... | 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? <... | -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>>>> list1 = [1,2,3,4]
>>> list2 = list1[::2]
>>> list2
[1, 3]
</code></pre>
<p>You can use a similar technique to get the remaining elements:</p>
<pre><code>>>> list3 = list1[1::2]
>>&g... | 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? <... | -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 compr... | 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,s... | 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)
... | 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, mai... | 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. th... | 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, mai... | 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 ... | 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 becaus... | 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%... | 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 < (len(aList)-1):
newList = (aList[i] * aList[i+1])
x = print(newList,end=',')
... | -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 e... | 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 < (len(aList)-1):
newList = (aList[i] * aList[i+1])
x = print(newList,end=',')
... | -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 = v... | 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(d... | 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 =... | 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)
>> '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 follo... | 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)
s... | 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></pr... | 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... | -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... | -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.... | 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... | -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):
no... | 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\Mes... | 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 testi... | 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 va... | 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('Plea... | 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 >... | 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) ##Thi... | -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 o... | 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) ##Thi... | -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) > 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()' b... | 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 ... | 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 ... | 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... | 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... | 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() >= 5</code></p>
<p>See more here: <a href=... | 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... | 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... | 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_i... | 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> manager show commands
Action Synopsis
------ --------
AbsoluteTimeout Set absolute timeout.
AGI ... | -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_i... | 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 vertic... | 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(... | 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,... | 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.o... | 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 = {'C... | 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()... | 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&ke... | 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... | 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:
... | 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>>>>from fuzzywuzzy import fuzz
>>>fuzz.partial_ratio('Subject: Dalki Manganese Ore Mine... | 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 SequenceM... | 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) <... | 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) <... | 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></p... | 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 = []
... | 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.c... | 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 = []
... | 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... | 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 = []
... | 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.ob... | 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):
... | 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>>>> a = 2
>>> [a]
[2]
>>> [a]*3
[2, 2, 2]
>>> 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):
... | 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}... | 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):
... | 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... | 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 reac... | 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>>>> import quandl
Traceback (most recent call last):
File "<stdin>", line 1, in <... | 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... | 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>pathl... | 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... | 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>>>> filepath = 'C:\\tempdir\\1\\0cd3a8asdsdfasfasdsgvsdfc1.pdf'
>>> ... | 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.a... | 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 arriv... | 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... | 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 ... | 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 ... | 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 ... | 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 ... | 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... | 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/pytho... | 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 Axe... | 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.... | 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... | 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>>>> from operator imp... | 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... | 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 ... | 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... | 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 ... | 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: /tm... | 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.we... | 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: /tm... | 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> var... | 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://stackov... | 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.LogForma... | 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 uninstal... | 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 (... | 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 uninstal... | 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_... | 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... | -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_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':... | 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 characte... | 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':... | 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 i... | 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 ... | 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 cent... | 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):
... | 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 cent... | 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__(... | 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.</... | 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
</... | 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... | 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... | 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 you... | 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_clas... | 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 ... | 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 = fig... | 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.col... | 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 = fig... | 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 mak... | 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 d... | 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 copyin... | 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! ca... | 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 = "('=... | 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 ... | 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 ... | 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 ... | 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: K... | 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>d... | 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"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.