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 |
|---|---|---|---|---|---|---|---|---|---|
How to parse dates for incomplete dates in Python | 39,653,042 | <p>I am using dateutil.parser to parse dates and I want to throw an exception if the date is incomplete i.e January 1 (missing year) or January 2016 (missing day). So far I have the following </p>
<pre><code>try:
parse(date)
return parse(date).isoformat()
except ValueError:
return 'invalid'
</code></pre>
| 0 | 2016-09-23T05:14:47Z | 39,655,241 | <p>Parse takes a default argument from which it takes the unspecified parts. So the easiest solution (apart from using a different library) would be to call the function with two <em>different</em> default parameters.</p>
<p>If both calls return the same value the datetime is valid, otherwise some default value was us... | 0 | 2016-09-23T07:36:59Z | [
"python"
] |
AES-CBC 128, 192 and 256 encryption decryption in Python 3 using PKCS#7 padding | 39,653,074 | <p>I have searched a lot on SO about complete encryption decryption example with my requirement. In fact, I've got many links and examples but None is working for me for AES-192-CBC mode and AES-256-CBC.</p>
<p>I have got following example which is supposed to be working with all types but it is working only with AES-... | 1 | 2016-09-23T05:17:15Z | 39,657,872 | <p>Made it working by padding of 16 bytes for any encryption types. For that I used AES.block_size which is 16 by default for AES.</p>
<pre><code>import base64
from Crypto.Cipher import AES
class AESCipher:
class InvalidBlockSizeError(Exception):
"""Raised for invalid block sizes"""
pass
def ... | 1 | 2016-09-23T09:55:17Z | [
"python",
"aes",
"pycrypto",
"pkcs#7",
"cbc-mode"
] |
Difficulty in defining a higher-order function to mimic if statement | 39,653,296 | <p>I have been hard pressed to answer a question we were recently asked as part of an exercise on higher-order functions in Python.</p>
<p>The question is to define two functions, one which takes no arguments, and passes three globally defined functions, c(), t() and f(), through if/else statements (if <code>c()</code... | -1 | 2016-09-23T05:36:28Z | 39,666,014 | <p>You may easily pass callable as function arguments, without calling them.</p>
<pre><code>def cond():
return True
def f():
return 2
def g():
time.sleep(60)
def if_function(condition_callable, call_if_true, call_if_false):
if condition_callable():
return call_if_true()
else:
ret... | 0 | 2016-09-23T17:00:23Z | [
"python",
"if-statement",
"higher-order-functions"
] |
How to create key value data type in django 1.7 models | 39,653,328 | <p>I want to store key-value pair in one column.</p>
<p>Above >Django-1.7 provides hstore to do that.</p>
<p>But I want to same functionality in Django-1.7.</p>
<p>How can I create custom datatype to store key-value pair in one column.</p>
<p>I am using postgres-9.5 database.</p>
<p>I want to store below json in k... | 0 | 2016-09-23T05:39:09Z | 39,653,572 | <p>There's a nice package exactly for this purpose:</p>
<p><a href="http://djangonauts.github.io/django-hstore/" rel="nofollow">http://djangonauts.github.io/django-hstore/</a></p>
<p>So just install using pip:</p>
<pre><code>pip install django-hstore
</code></pre>
| 3 | 2016-09-23T06:00:24Z | [
"python",
"django",
"postgresql",
"django-models",
"django-custom-field"
] |
Update a text file with python only if it has changed | 39,653,608 | <p>Ok, I have my raspberry pi hooked up to a magnetic sensor on my garage door. I have a python script that update a website (initailstate.com) every second and reports changes, but it costs money after 25k requests and I killed that very quickly lol.
I want to instead to update a text file every time the state of the... | -2 | 2016-09-23T06:02:12Z | 39,655,225 | <p>Maybe you could try something like this:</p>
<pre><code>f = open("state.txt", "w+") # state.txt contains "True" or "False"
def get_door_status():
# get_door_status() returns door_status, a bool
return door_status
while True:
door_status = str(get_door_status())
file_status = f.read()
if file_s... | 0 | 2016-09-23T07:36:16Z | [
"python",
"linux"
] |
Update a text file with python only if it has changed | 39,653,608 | <p>Ok, I have my raspberry pi hooked up to a magnetic sensor on my garage door. I have a python script that update a website (initailstate.com) every second and reports changes, but it costs money after 25k requests and I killed that very quickly lol.
I want to instead to update a text file every time the state of the... | -2 | 2016-09-23T06:02:12Z | 39,656,302 | <p>When working with small files that are exclusive to you, simply cache their content. This is faster and healthier for your storage.</p>
<pre><code># start of the script
# load the current value
import ast
status, status_file = False, "state.txt"
with open(status_file) as stat_file:
status = ast.literal_eval(nex... | 0 | 2016-09-23T08:35:03Z | [
"python",
"linux"
] |
How to make label and entry start blank | 39,653,729 | <p>Any idea on how to make all the entry and labels in my GUI start blank but then update when the calculate function happens? They currently start with a 0. I have tried many things but nothing has worked. </p>
<p>Here is code: </p>
<pre><code>from tkinter import *
root = Tk(className="Page Calculator")
root.title(... | 0 | 2016-09-23T06:10:55Z | 39,654,301 | <p><code>IntVar()</code> has a default value of 0. Even though they are IntVar, you can <code>set</code> strings as their value (note that when you try to <code>get</code> its value, you'll get an error if they still contain strings). </p>
<p>So you can simply do</p>
<pre><code>read = IntVar()
read.set("")
</code><... | 1 | 2016-09-23T06:47:49Z | [
"python",
"tkinter",
"label",
"entry"
] |
i'm doing a project for class and i can't understand why the last line is being flaged as unindented? | 39,653,784 | <p>This is a class thing im doing and in the last line when i run my program it says unexpected unindent. I cant understand. Help.</p>
<pre><code>b = 0
maxpass = 68
minpass = 0
fn = "FNO123"
amount = 0
seatsremain = 68 - b
print ("Welcome to Flight Booking Program")
print ("Please enter the flight number you want to... | -2 | 2016-09-23T06:14:36Z | 39,653,896 | <p>Your second 'try' doesn't have an 'except'. Because this is missing your final line is unexpectedly unindented. Python is trying to find something indented equal to the try statement since 'except' is required.</p>
<pre><code>while True:
try:
amount = int(input())
if amount <1 or amount >... | 2 | 2016-09-23T06:23:19Z | [
"python"
] |
How to sort/ group a Pandas data frame by class label or any specific column | 39,653,812 | <pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
<p>I have used hypothetical data in the example. The shape of the real DataFrame is 6680x1900. I have clustered these data into <code>50</code> label... | 3 | 2016-09-23T06:16:50Z | 39,653,849 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="nofollow"><code>DataFrame.sort_values</code></a> if <code>class</code> is <code>Series</code>:</p>
<pre><code>print (type(df['class']))
<class 'pandas.core.series.Series'>
print (df.sor... | 2 | 2016-09-23T06:19:54Z | [
"python",
"sorting",
"pandas",
"dataframe",
"group-by"
] |
How to sort/ group a Pandas data frame by class label or any specific column | 39,653,812 | <pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
<p>I have used hypothetical data in the example. The shape of the real DataFrame is 6680x1900. I have clustered these data into <code>50</code> label... | 3 | 2016-09-23T06:16:50Z | 39,653,884 | <p>If you are starting with the data in your question:</p>
<blockquote>
<pre><code>class col2 col3 col4 col5
1 4 5 5 5
4 4 4.5 5.5 6
1 3.5 5 6 4.5
3 3 4 4 4
2 3 3.5 3.8 6.1
</code></pre>
</blockquote>
<p>And want to sort that, then it depends on whether <code>'... | 0 | 2016-09-23T06:22:07Z | [
"python",
"sorting",
"pandas",
"dataframe",
"group-by"
] |
AttributeError: 'NoneType' object has no attribute 'data' Linked List | 39,653,832 | <p>Current code, I am trying to make a linked list and then sort the linked list in ascending order. </p>
<pre><code>import random
random_nums = random.sample(range(100), 10)
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = None
def __str__(self):
retu... | 0 | 2016-09-23T06:18:13Z | 39,655,897 | <p>While the lines of your posted code and error don't quite match, the issue is likely here:</p>
<pre><code> if data > current_node.data and data <= current_node.next.data:
</code></pre>
<p>While you check that <code>current_node</code> is not <code>None</code>, you never check that <code>current_node.next<... | 1 | 2016-09-23T08:13:26Z | [
"python"
] |
With inheritance and access to the parent is something wrong? | 39,653,851 | <p>With inheritance and access to the parent, widgets are some weird wrong. I Need to make three section with the same widget as shown in the code. </p>
<p>I don't know how could do that really makes sense. Have you an idea how could this be done in the smartest way ? </p>
<pre><code>import Tkinter as tk
class Inter... | 1 | 2016-09-23T06:20:06Z | 39,660,159 | <p>You are giving one of your widgets a parent of <code>parent</code> rather than <code>self</code>.</p>
<p>Change this line:</p>
<pre><code>self.frame = tk.LabelFrame(parent, text="Verification Part - %s"%ver_part)
</code></pre>
<p>to this:</p>
<pre><code>self.frame = tk.LabelFrame(self, text="Verification Part - ... | 2 | 2016-09-23T11:54:38Z | [
"python",
"python-2.7",
"class",
"tkinter"
] |
Teardown action in Robot Framework | 39,654,007 | <p>I have a 3 test cases in robot framework and I need to run Teardown actions only Once at last after execution 3 test cases.
How to handle?</p>
<pre><code>*** Settings ***
Test Teardown Teardown Actions
Library abc.py
*** Variables ***
*** Test Cases ***
testcase1
Run Keyword func1
testcase2
... | 0 | 2016-09-23T06:29:13Z | 39,654,137 | <p>There is "Suite Teardown" in robotframework which will run after the execution of all test cases.</p>
<p><a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#suite-setup-and-teardown" rel="nofollow">Check this link for more info.</a></p>
<p>Can be use like this.</p>
<pre><code>***... | 2 | 2016-09-23T06:37:37Z | [
"python",
"python-2.7",
"robotframework"
] |
Trying to create a crude send/receive through TCP in python | 39,654,060 | <p>So far I can send files to my "fileserver" and retrieve files from there as well. But i can't do both at the same time. I have to comment out one of the other threads for them to work. As you will see in my code.</p>
<p>SERVER CODE
</p>
<pre class="lang-py prettyprint-override"><code>from socket import *
import th... | 2 | 2016-09-23T06:32:35Z | 39,655,847 | <p>On the serverside, you're trying to use the same connection for your two threads t and u.</p>
<p>I think it might work if you listened for another connection in your <code>while True:</code> loop on the server, after you started your first thread.</p>
<p>I always use the more high-level <code>socketserver</code> m... | 0 | 2016-09-23T08:10:50Z | [
"python",
"tcp"
] |
Upper method doesn't make sense | 39,654,133 | <p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if ... | 0 | 2016-09-23T06:37:29Z | 39,654,234 | <p>The upper method returns <em>new</em> string in uppercase. So use</p>
<pre><code>split_port = split_result[1].upper()
</code></pre>
| 2 | 2016-09-23T06:43:37Z | [
"python"
] |
Upper method doesn't make sense | 39,654,133 | <p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if ... | 0 | 2016-09-23T06:37:29Z | 39,654,319 | <p>Couple of points </p>
<ul>
<li><code>split_port.upper()</code> return is not assigned back to <code>split_port</code></li>
<li>No need to split on <code>'0x'</code>. You can use <code>replace</code> function instead. Will be less complicated.</li>
</ul>
<p><strong>Code with replace function:</strong></p>
<pre><co... | 1 | 2016-09-23T06:48:36Z | [
"python"
] |
Upper method doesn't make sense | 39,654,133 | <p><strong>Code</strong>:</p>
<pre><code>def solve_the_input(port):
port = hex(int(port))
split_result = port.split("0x")
split_port = split_result[1]
print 'input port is ',split_port
split_port.upper()
print 'input port is ',split_port
return split_port
if __name__ == "__main__":
if ... | 0 | 2016-09-23T06:37:29Z | 39,654,349 | <p>Upper method returning new string but you need to store that string.</p>
<pre><code>split_port = split_result[1].upper()
</code></pre>
| 0 | 2016-09-23T06:49:42Z | [
"python"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework} | 39,654,153 | <p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
... | 1 | 2016-09-23T06:38:34Z | 39,654,664 | <p>If I understand it correctly you want two trees next to each other.</p>
<pre><code>|........./\................../\.........|
|......../\/\................/\/\........|
|......./\/\/\............../\/\/\.......|
|....../\/\/\/\............/\/\/\/\......|
|...../\/\/\/\/\........../\/\/\/\/\.....|
|..../\/\/\/\/\/\.... | 2 | 2016-09-23T07:06:15Z | [
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework} | 39,654,153 | <p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
... | 1 | 2016-09-23T06:38:34Z | 39,654,967 | <p>I think this would work for you.</p>
<pre><code>def middle1(size):
count_middle1 = 0
size_m1 = (size * 2)
mid_1 = 1
mid_2 = 1
dots_a = int(size_m1 / 2)
bslsh = "\\"
fslsh = "/"
while (count_middle1 != size):
print("|"+("."*dots_a)+((fslsh+bslsh)*mid_1)+("."*size_m1)+((fsl... | 0 | 2016-09-23T07:22:38Z | [
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Can't figure out why this code runs perfect for input of 3 and breaks on 5. {homework} | 39,654,153 | <p>When I input 3 into the below code it prints perfectly in the shape I need. But when the input is > 3 the code seems to break as you can see in the pictures below. I think I've probably just been staring at this for too long and can't find the obvious stupid error. I'm somewhat new to python so please go easy. </p>
... | 1 | 2016-09-23T06:38:34Z | 39,655,255 | <p>This will work for any input</p>
<pre><code>size = int(input("Size: "))
def middle1():
count_middle1 = 0
size_m1 = (size - 1)*2
mid_1 = 2
mid_2 = 2
dots_a = size-1
bslsh = "\\"
fslsh = "/"
while (count_middle1 < size):
print("|"+("."*(dots_a))+((fslsh+bslsh)*(mid_1-1))+("... | 0 | 2016-09-23T07:37:29Z | [
"python",
"python-3.x",
"python-3.5",
"python-3.5.2"
] |
Add tag to cartridge admin panel | 39,654,201 | <p>I want to add one new field 'tag' in my Product class. I added that field and now I want to add that tag manually from cartridge admin panel. </p>
<p>So, to do that I am importing one admin class in my settings.py,</p>
<pre><code>from cartridge.shop.admin import ProductAdmin
</code></pre>
<p>When I am importing a... | 0 | 2016-09-23T06:41:21Z | 39,654,847 | <p><code>ProductAdmin</code> looks like it requires the secret key setting which it is unable to get since it is loaded before settings, so you cannot include this in settings (nor can I think of a reason you'd need to)</p>
<p>Whatever it is you're trying to do, you need to do it elsewhere.</p>
| 0 | 2016-09-23T07:16:21Z | [
"python",
"django",
"cartridge"
] |
How to concatenate strings in numpy (to create percentages)? | 39,654,212 | <p>I have a matrix created by the following code:</p>
<pre><code>import numpy as np
table_vals = np.random.randn(4,4).round(4) * 100
</code></pre>
<p>and I've tried to convert numbers into percentages like this:</p>
<pre><code>>>> table_vals.astype(np.string_) + '%'
TypeError: ufunc 'add' did not contain a ... | 0 | 2016-09-23T06:42:22Z | 39,654,378 | <p>You can use the formatting as:</p>
<pre><code>[["%.2f%%" % number for number in row] for row in table_vals]
</code></pre>
<p>If you want it as a numpy array, then wrap it in <code>np.array</code> method so it becomes:</p>
<pre><code>np.array([["%.2f%%" % number for number in row] for row in table_vals])
</code></... | 0 | 2016-09-23T06:51:38Z | [
"python",
"numpy"
] |
How to concatenate strings in numpy (to create percentages)? | 39,654,212 | <p>I have a matrix created by the following code:</p>
<pre><code>import numpy as np
table_vals = np.random.randn(4,4).round(4) * 100
</code></pre>
<p>and I've tried to convert numbers into percentages like this:</p>
<pre><code>>>> table_vals.astype(np.string_) + '%'
TypeError: ufunc 'add' did not contain a ... | 0 | 2016-09-23T06:42:22Z | 39,657,487 | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/routines.char.html" rel="nofollow"><code>np.char</code> module</a> can help here:</p>
<pre><code>np.char.add(table_vals.astype(np.bytes_), b'%')
</code></pre>
<p>Using an object array also works well:</p>
<pre><code>np.array("%.2f%%") % table_vals.astype(np.o... | 0 | 2016-09-23T09:37:30Z | [
"python",
"numpy"
] |
Create a list from an existing list of key value pairs in python | 39,654,224 | <p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numeri... | -1 | 2016-09-23T06:42:52Z | 39,654,326 | <pre><code>from collections import defaultdict
data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
if __name__ == '__main__':
result = defaultdict(list)
for alphabet, number in data:
result[alphabet].append(number)
</code></pre>
<p>or without collections module:</p>
<pre>... | 2 | 2016-09-23T06:48:56Z | [
"python"
] |
Create a list from an existing list of key value pairs in python | 39,654,224 | <p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numeri... | -1 | 2016-09-23T06:42:52Z | 39,654,463 | <p>You can use <code>defaultdict</code> from the <code>collections</code> module for this:</p>
<pre><code>from collections import defaultdict
l = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
d = defaultdict(list)
for k,v in l:
d[k].append(v)
for k,v in d.items():
exec(k + "list=" ... | -1 | 2016-09-23T06:56:27Z | [
"python"
] |
Create a list from an existing list of key value pairs in python | 39,654,224 | <p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numeri... | -1 | 2016-09-23T06:42:52Z | 39,654,740 | <p>If you want to avoid using a <code>defaultdict</code> but are comfortable using <code>itertools</code>, you can do it with a one-liner</p>
<pre><code>from itertools import groupby
data = [('a',1),('a',2),('a',3),('b',10),('b',100),('c',99),('d',-1),('d',-2)]
grouped = dict((key, list(pair[1] for pair in values)) f... | 1 | 2016-09-23T07:10:11Z | [
"python"
] |
Create a list from an existing list of key value pairs in python | 39,654,224 | <p>I am trying to come up with a neat way of doing this in python.</p>
<p>I have a list of pairs of alphabets and numbers that look like this :</p>
<pre><code>[(a,1),(a,2),(a,3),(b,10),(b,100),(c,99),(d,-1),(d,-2)]
</code></pre>
<p>What I want to do is to create a new list for each alphabet and append all the numeri... | -1 | 2016-09-23T06:42:52Z | 39,654,930 | <p>After seeing the responses in the thread and reading the implementation of defaultdict, I implemented my own version of it since I didn't want to use the collections library. </p>
<pre><code> mydict = {}
for alphabet, value in data:
try:
mydict[alphabet].append(value)
except Ke... | 0 | 2016-09-23T07:20:36Z | [
"python"
] |
string parameter passing not working in django1.9 | 39,654,265 | <p>I am passing a string parameter in view but its not working.</p>
<pre><code>url(r'^users/(?P<user_type>\w+)/$', views.users, name='users'),
url(r'^users/$', views.users, name='users')
</code></pre>
<p><strong>view is:-</strong> </p>
<pre><code>def users(request, user_type=None):
</code></pre>
<p><strong>Li... | 0 | 2016-09-23T06:45:34Z | 39,654,514 | <p>Use this and check</p>
<pre><code>url(r'^users/(?P<user_type>\w+)/$', views.users, name='users_type'),
url(r'^users/$', views.users, name='users')
</code></pre>
<p>Link is:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre ... | 1 | 2016-09-23T06:58:37Z | [
"python",
"django"
] |
Python - Beautifulsoup count only outer tag children of a tag | 39,654,376 | <p>HTML of page:</p>
<pre><code><form name="compareprd" action="">
<div class="gridBox product " id="quickLookItem-1">
<div class="gridItemTop">
</div>
</div>
<div class="gridBox product " id="quickLookItem-2">
<div class="gridItemTop">
... | 1 | 2016-09-23T06:51:35Z | 39,658,013 | <p>You can use a single <em>css selector</em> <code>form[name=compareprd] > div</code> which will find <em>div's</em> that are immediate children of the form:</p>
<pre><code>html = """<form name="compareprd" action="">
<div class="gridBox product " id="quickLookItem-1">
<div class="gridItemTop"... | 1 | 2016-09-23T10:03:00Z | [
"python",
"html",
"web-scraping",
"beautifulsoup"
] |
Finding multiple repetitions of smaller lists in a large cumulative list | 39,654,646 | <p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>... | 3 | 2016-09-23T07:05:24Z | 39,655,184 | <p>You can use <a href="https://docs.python.org/2/library/sets.html" rel="nofollow">Set</a> for pattern matching:</p>
<pre><code>from sets import Set
full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
se... | 0 | 2016-09-23T07:34:15Z | [
"python",
"list"
] |
Finding multiple repetitions of smaller lists in a large cumulative list | 39,654,646 | <p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>... | 3 | 2016-09-23T07:05:24Z | 39,655,284 | <p>You need to create a map (dictionary) of the elements of your small list:</p>
<pre><code>m = {k: v for k, v in zip(map(tuple, [tc1, tc2, tc3, tc4])), ["tc1", "tc2", "tc3", "tc4"])}
>>> {('KK02', 'FE34'): 'tc3', ('AB21', 'BG54'): 'tc2', ('CF54', 'SD62'): 'tc4', ('HG89', 'NS72'): 'tc1'}
</code></pre>
<p>You... | 3 | 2016-09-23T07:39:03Z | [
"python",
"list"
] |
Finding multiple repetitions of smaller lists in a large cumulative list | 39,654,646 | <p>I have a large list of strings, for eg:</p>
<pre><code>full_log = ['AB21','BG54','HG89','NS72','Error','CF54','SD62','KK02','FE34']
</code></pre>
<p>and multiple small list of strings, for eg:</p>
<pre><code>tc1 = ['HG89','NS72']
tc2 = ['AB21','BG54']
tc3 = ['KK02','FE34']
tc4 = ['CF54','SD62']
</code></pre>
<p>... | 3 | 2016-09-23T07:05:24Z | 39,655,476 | <p>In case all your short lists are equal length you could just create a <code>dict</code> where key is <code>tuple</code> of strings and value is one of the labels. The you could go through <code>full_log</code>, take a block with suitable length and see if that can be found from <code>dict</code>.</p>
<p>In case the... | 2 | 2016-09-23T07:50:00Z | [
"python",
"list"
] |
Checking a word starts with specific alphabets python | 39,654,703 | <p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) /... | -1 | 2016-09-23T07:07:54Z | 39,654,737 | <p>you can use the regex.</p>
<pre><code>pat = re.compile(r'^test.*')
</code></pre>
<p>then you can use this pattern for checking each line.</p>
| 0 | 2016-09-23T07:10:02Z | [
"python"
] |
Checking a word starts with specific alphabets python | 39,654,703 | <p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) /... | -1 | 2016-09-23T07:07:54Z | 39,654,764 | <p>Simply use:</p>
<pre><code>String.startswith(str, beg=0,end=len(string))
</code></pre>
<p>In your case, it'll be</p>
<pre><code>word.startswith('test', 0, 4)
</code></pre>
| 1 | 2016-09-23T07:11:07Z | [
"python"
] |
Checking a word starts with specific alphabets python | 39,654,703 | <p>I have a string test_file1. I want to check taking a string from user if the string he/she enters starts with 'test'. How to do this in python?
let args be =['test_file']</p>
<pre><code>for suite in args:
if suite.startswith('test'):
suite="hello.tests."+suite
print(suite) /... | -1 | 2016-09-23T07:07:54Z | 39,655,072 | <p>Problem with code is you are not replacing the suite in args list with new created suite name .</p>
<p><strong>Check this out</strong></p>
<pre><code>args = ['test_file']
print "Before args are -",args
for suite in args:
#Checks test word
if suite.startswith('test'):
#If yes, append "hello.tests"
... | 0 | 2016-09-23T07:28:25Z | [
"python"
] |
Making GUI with only python without framework? | 39,654,954 | <ol>
<li>Is it possible to create a user interface without the help of python framework (like tinker or pygame) and use only vanilla python code? If yes, how?</li>
<li>Can you briefly explain how python framework works?</li>
<li>Is the code of different python framework different?</li>
<li>If the computer did not have ... | 0 | 2016-09-23T07:21:51Z | 39,655,710 | <ol>
<li>Yes, after all tinker and pygame are just python classes packaged as modules.</li>
<li>Python frameworks are a bunch of pre-tested and reusable modules that allow you to use and extend upon so you don't have to reinvent the wheel. </li>
<li>Yes, frameworks will have differences in usability and code.</li>
<li>... | 1 | 2016-09-23T08:02:49Z | [
"python",
"user-interface",
"frameworks"
] |
Making GUI with only python without framework? | 39,654,954 | <ol>
<li>Is it possible to create a user interface without the help of python framework (like tinker or pygame) and use only vanilla python code? If yes, how?</li>
<li>Can you briefly explain how python framework works?</li>
<li>Is the code of different python framework different?</li>
<li>If the computer did not have ... | 0 | 2016-09-23T07:21:51Z | 39,657,647 | <p>If you want as few external dependencies as possible (but still a GUI) I would strongly suggest using a Web-Microframework like <a href="http://bottlepy.org/docs/dev/index.html" rel="nofollow">bottle</a> (single file) and utilize the user's browser for rendering.</p>
<ol>
<li>You can make a GUI without any external... | 0 | 2016-09-23T09:44:26Z | [
"python",
"user-interface",
"frameworks"
] |
Time complexity of zlib's deflate algorithm | 39,654,986 | <p>What is the time complexity of Zlib's deflate algorithm?</p>
<p>I understand that in Python this algorithm is made available via the <code>zlib.compress</code> function.</p>
<p>Presumably the corresponding decompression algorithm has the same or better complexity.</p>
| 1 | 2016-09-23T07:23:43Z | 39,662,445 | <p>Time complexity is how the processing time scales with the size of the input. For zlib, and any other compression scheme I know of, it is O(<em>n</em>) for both compression and decompression. The time scales linearly with the size of the input.</p>
<p>If you are thinking that the time complexity of decompression is... | 1 | 2016-09-23T13:47:49Z | [
"python",
"compression",
"complexity-theory",
"zlib"
] |
Accessing users groups through attributes / foreign keys in Django | 39,655,053 | <p>I'm trying to access my users groups in Django, but keep getting</p>
<pre><code>auth.Group.None
</code></pre>
<p>as the result.</p>
<p>When in the django shell I'll first create a group, then a user and add the user to the group. After this, I try to print the users groups, like so:</p>
<pre><code>from django.co... | 0 | 2016-09-23T07:27:25Z | 39,655,200 | <p>You added user to group in group object, but your user object does not have update state for this.</p>
<p>Try access groups like this:</p>
<pre><code>print Rihanna.groups.all()
</code></pre>
<p>or add group in user model:</p>
<pre><code>Rihanna.groups.add(Artists)
</code></pre>
| 0 | 2016-09-23T07:35:08Z | [
"python",
"django"
] |
Stuff spaces at end of lines in file | 39,655,340 | <p>I am trying to read a fixed with file that has lines/records of different lengths. I need to stuff spaces at the end of the lines which are less than the standard length specified.</p>
<p>Any help appreciated.</p>
<p><a href="http://i.stack.imgur.com/N5Kbd.png" rel="nofollow">enter image description here</a></p>
| -1 | 2016-09-23T07:42:11Z | 39,655,568 | <p>You can use <a href="https://docs.python.org/3.3/library/string.html" rel="nofollow">string.format</a> to pad a string to a specific length.</p>
<p>The documentation says that <code><</code> pads to the right so to pad a string with spaces to the right to a specific length you can do something like this:</p>
<p... | 2 | 2016-09-23T07:55:32Z | [
"python",
"fixed-width"
] |
Stuff spaces at end of lines in file | 39,655,340 | <p>I am trying to read a fixed with file that has lines/records of different lengths. I need to stuff spaces at the end of the lines which are less than the standard length specified.</p>
<p>Any help appreciated.</p>
<p><a href="http://i.stack.imgur.com/N5Kbd.png" rel="nofollow">enter image description here</a></p>
| -1 | 2016-09-23T07:42:11Z | 39,655,745 | <p>You could consider to use ljust string method.
If line is a line read from your file:</p>
<pre><code>line = line.ljust(50)
</code></pre>
<p>will stuff the end of the line with spaces to get a 50 characters long line. If line is longer that 50, line is simply copied without any change.</p>
| 1 | 2016-09-23T08:04:58Z | [
"python",
"fixed-width"
] |
Calculate z-score in data bunch but excluding N.A | 39,655,397 | <p>So I got this bunch of data with N.A. values in them:</p>
<p><a href="http://i.stack.imgur.com/XVlKo.jpg" rel="nofollow">Data Dump</a></p>
<p>So how do I get the z-score of each column while excluding the N.A. values? Such that the z-score output looks like this?</p>
<p><a href="http://i.stack.imgur.com/S5XiW.jpg... | 0 | 2016-09-23T07:45:16Z | 39,655,617 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>replace</code></a> first <code>N.A.</code> to <code>NaN</code> and convert values to <code>float</code>:</p>
<pre><code>df = df.replace({'N.A.': np.nan}).astype(float)
for col in df.colu... | 1 | 2016-09-23T07:57:58Z | [
"python",
"pandas"
] |
For half-hourly intervals can I use Pandas TimeDeltaIndex, PeriodIndex or DateTimeIndex? | 39,655,448 | <p>I have a table of data values that should be indexed with half-hourly intervals, and I've been processing them with Pandas and Numpy. Currently they're in CSV files and I import them using <code>read_csv</code> to a dataframe with only the interval-endpoint as an index. I am uncomfortable with that and want to have ... | 0 | 2016-09-23T07:48:14Z | 39,707,398 | <p>if you only need a series with time interval of 30 minutes you can do this:</p>
<pre><code>import pandas as pd
import datetime as dt
today = dt.datetime.date()
yesterday = dt.datetime.date()-dt.timedelta(days=1)
time_range = pd.date_range(yesterday,today, freq='30T')
</code></pre>
<p>now you could use it to set a... | 0 | 2016-09-26T16:00:54Z | [
"python",
"datetime",
"pandas",
"intervals"
] |
What are the conversion rules in the SoftLayer_Virtual_Guest::getBillingCyclePublicBandwidthUsageâs return value? | 39,655,607 | <p>Iâm developing total usage for bandwidth. And I tried a lot of method to get total usage for bandwidth. The result always different from portal site while they are nearly. I donât know whether the rules is wrong or not. Because the return value of API SoftLayer_Virtual_Guest::getBillingCyclePublicBandwidthUsage(... | 1 | 2016-09-23T07:57:29Z | 39,662,304 | <p>That is the expected behavior the values are not exactly the same, this is because the portal uses another method to get that value, if you want to get the same value you need to use the same method.</p>
<p>check out these related forums.</p>
<ul>
<li><a href="http://stackoverflow.com/questions/36308040/bandwidth-... | 0 | 2016-09-23T13:40:45Z | [
"python",
"api",
"bandwidth",
"result",
"softlayer"
] |
Uploading User Details from an excel file using pandas in python to postgres Database | 39,655,688 | <p>I am uploading user details(username,email,password) from a .csv file to postgres DB using pandas in python. It is all fine till the dataframe gets generated but once I run the code for uploading the user details the substring-"@gmail.com" from their emai-id gets converted to/stored as lowercase in postgres DB.
Thi... | 0 | 2016-09-23T08:01:46Z | 39,655,954 | <p>This has nothing to do with postgres, it's django that is <a href="https://github.com/django/django/blob/1.10/django/contrib/auth/base_user.py#L23" rel="nofollow">normalizing the email address</a> when a new user <a href="https://github.com/django/django/blob/1.10/django/contrib/auth/models.py#L147" rel="nofollow">i... | 0 | 2016-09-23T08:16:36Z | [
"python",
"django",
"postgresql",
"pandas"
] |
Parameters like width, align, justify won't work in Tkinter Message | 39,655,854 | <p>I'm trying to change the width of a Message widget in Tkinter by using the width parameter. I couldn't get it to work so I tried align, justify and aspect which all produced the same result - the box remains centred and the width of the text.</p>
<p>Here is my code:</p>
<pre><code>console_Fetch = Message(text="tes... | -1 | 2016-09-23T08:11:07Z | 39,656,549 | <h3>Pragmatic answer</h3>
<p>Often setting <code>width</code> in widgets is not working as expected, depending on priority of other aspects, cell width, you name it. It gets easily overruled, or depends on other conditions.</p>
<p>What I always do is give the grid a "skeleton" of canvases in adjecent cells, with heig... | 2 | 2016-09-23T08:49:23Z | [
"python",
"tkinter"
] |
How to make a for loop with exception handling when key not in dictionary? | 39,656,012 | <p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happ... | 0 | 2016-09-23T08:20:06Z | 39,656,122 | <p>Your break is not in the if scope... so it will break on the first attempt.</p>
| 0 | 2016-09-23T08:26:10Z | [
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary? | 39,656,012 | <p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happ... | 0 | 2016-09-23T08:20:06Z | 39,656,205 | <p>There will be no <code>KeyError</code> here because your code never tires to access the dictionary, just checks if the key is in <code>keys</code>. You could simply do this to achieve the same logic:</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina':... | 2 | 2016-09-23T08:29:51Z | [
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary? | 39,656,012 | <p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happ... | 0 | 2016-09-23T08:20:06Z | 39,656,223 | <p>From the <a href="https://wiki.python.org/moin/KeyError" rel="nofollow">doc</a></p>
<blockquote>
<p>Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.</p>
</blockquote>
<p>In your piece of code if you want print a message when us... | 0 | 2016-09-23T08:30:26Z | [
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary? | 39,656,012 | <p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happ... | 0 | 2016-09-23T08:20:06Z | 39,656,268 | <p>Couple of points:</p>
<ul>
<li>You code never going to hit exception since you are checking key existence using <code>if key in dict.keys()</code> </li>
<li><p>Also, there are so many loops. I think <code>for i in range(0,5)</code> is enough.Will be <strong>less complicated</strong>.</p>
<pre><code>ex_dict = {'Uni... | 0 | 2016-09-23T08:33:31Z | [
"python",
"for-loop",
"dictionary",
"exception"
] |
How to make a for loop with exception handling when key not in dictionary? | 39,656,012 | <p>So, I have a dictionary with country names and corresponding stock index. The user is asked to enter five different countries and the program takes the five corresponding stock indexes and does something with the data.</p>
<p>When asked for input I check against the dictionary if the country can be found, this happ... | 0 | 2016-09-23T08:20:06Z | 39,656,283 | <p>I am assuming you want it to give you a message if the stock is not in the dictionary ex_dict, I have modified the code to do the same.</p>
<pre><code>ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose
countries = []
print('Please ch... | 0 | 2016-09-23T08:34:19Z | [
"python",
"for-loop",
"dictionary",
"exception"
] |
Pythonic way to wrap a subprocess call that takes a lot of parameters? | 39,656,035 | <p>I am writing a python script that provides a more user friendly API to a command line tool. Some of the necessary command calls take a lot of parameters (up to around 10 sometimes), but that is not good practice in Python. They can't just be defaults; it has to be possible to set all the parameters for a given call.... | 1 | 2016-09-23T08:21:32Z | 39,656,293 | <p>It is commendable that you want to build a Pythonic API rather than just an API for this command.</p>
<p>I'm not sure why you disregard default parameters though? If the default is <code>None</code>, you could treat that as a guide to not add things to the command line.</p>
<p>For example, suppose you want to call... | 2 | 2016-09-23T08:34:30Z | [
"python",
"subprocess",
"parameter-passing",
"args",
"kwargs"
] |
Pythonic way to wrap a subprocess call that takes a lot of parameters? | 39,656,035 | <p>I am writing a python script that provides a more user friendly API to a command line tool. Some of the necessary command calls take a lot of parameters (up to around 10 sometimes), but that is not good practice in Python. They can't just be defaults; it has to be possible to set all the parameters for a given call.... | 1 | 2016-09-23T08:21:32Z | 39,656,738 | <p>Like you said, <code>**</code> of kvargs are convenient way to <em>pass</em> several arguments to your function, however it always better to declare arguments explicitly in the function definition:</p>
<pre><code>def store(data, database,
user, password,
host=DEFAULT_HOST,
port=PG_DEFA... | 2 | 2016-09-23T08:58:56Z | [
"python",
"subprocess",
"parameter-passing",
"args",
"kwargs"
] |
Can't save and instantiate a child class in my django model | 39,656,071 | <p>Ok now I changed my models as follow:</p>
<pre><code>from django.contrib.auth.models import User
class Company(User):
company_name = models.CharField(max_length = 20)
class Employee(User):
pass
</code></pre>
<p>When I run from pytho manage.py shell the following commands:</p>
<pre><code>u = Employee(fi... | -1 | 2016-09-23T08:23:14Z | 39,995,827 | <p>when writing:</p>
<pre><code>class x(y)
</code></pre>
<p>in Python this means x extends (inherit from) y.</p>
<p>while</p>
<blockquote>
<p>class Employee(User):<br>
pass</p>
</blockquote>
<p>makes a little sense (an employee is a user), this</p>
<blockquote>
<p>class Company... | 0 | 2016-10-12T10:02:27Z | [
"python",
"django",
"database",
"django-models"
] |
Python dropbox - Opening spreadsheets | 39,656,180 | <p>I was testing with the dropbox provided API for python..my target was to read a Spreadsheet in my dropbox without downloading it to my local storage. </p>
<pre><code>import dropbox
dbx = dropbox.Dropbox('my-token')
print dbx.users_get_current_account()
fl = dbx.files_get_preview('/CGPA.xlsx')[1] # returns a Respons... | 0 | 2016-09-23T08:28:45Z | 39,666,433 | <p>No, the Dropbox API doesn't offer the ability to selectively query parts of a spreadsheet file like this without downloading the whole file, but we'll consider it a feature request.</p>
| 0 | 2016-09-23T17:27:34Z | [
"python",
"dropbox",
"xls"
] |
How to download outlook attachment from Python Script? | 39,656,433 | <p>I need to download incoming attachment without past attachment from mail using Python Script.</p>
<p>For example:If anyone send mail at this time(now) then just download that attachment only into local drive not past attachments.</p>
<p>Please anyone help me to download attachment using python script or java.</p>
| 2 | 2016-09-23T08:42:59Z | 39,872,935 | <pre><code>import email
import imaplib
import os
class FetchEmail():
connection = None
error = None
mail_server="host_name"
username="outlook_username"
password="password"
self.save_attachment(self,msg,download_folder)
def __init__(self, mail_server, username, password):
self.connection = imaplib.IMAP4_SSL(mail_s... | 2 | 2016-10-05T11:37:04Z | [
"java",
"python",
"email",
"outlook"
] |
ValueError: I/O operation on closed file when using **generator** over **list** | 39,656,437 | <p>I have the two following functions to extract data from a csv file, one returns a list and the other a generator:</p>
<p>List:</p>
<pre><code>def data_extraction(filename,start_line,node_num,span_start,span_end):
with open(filename, "r") as myfile:
file_= csv.reader(myfile, delimiter=',') #extracts da... | 0 | 2016-09-23T08:43:05Z | 39,656,712 | <p>Note that the <code>with</code> statement closes the file at its end. That means no more data can be read from it.</p>
<p>The list version actually reads in all data, since the list elements must be created.</p>
<p>The generator version instead never reads any data until you actual fetch data from the generator. S... | 1 | 2016-09-23T08:57:22Z | [
"python",
"list",
"python-2.7",
"csv",
"generator"
] |
Copying column from CSV to CSV with python | 39,656,546 | <p>I'm new with python and I would like to know if it's possible to copy the first column from a .csv file to another .csv file. The reason is that I have a lot of .csv and instead of opening each one manually and copying to only one .csv I would like to automate this step.</p>
<p>Thank you very much!</p>
| -1 | 2016-09-23T08:49:18Z | 39,657,833 | <p><strong>Code Snipet:</strong>
<strong>You need to configure source and destination</strong> </p>
<pre><code>import os
from os import listdir
from os.path import isfile, join
import csv
mypath="sourcePath"
newcsv="destination"
# for just files in a directory and not the subDirectory
onlyfiles = [f for f in listdi... | 0 | 2016-09-23T09:53:03Z | [
"python"
] |
pyqtgraph - Background color loads only after reloading | 39,656,627 | <p>I see I'm not <a href="https://stackoverflow.com/questions/31567573/issue-in-setting-the-background-color-in-pyqtgraph">the only one</a> having a problem with background color in pyqtgraph - I'm writing a QGIS software plugin which has an additional dialog box with a graph. I'm trying to set the background color and... | 0 | 2016-09-23T08:52:59Z | 39,658,042 | <p>The <a href="http://www.pyqtgraph.org/documentation/style.html#default-background-and-foreground-colors" rel="nofollow">pyqtgraph documentation</a> says about <code>setConfigOption</code> settings, that:</p>
<blockquote>
<p>Note that this must be set before creating any widgets</p>
</blockquote>
<p>In my code I ... | 0 | 2016-09-23T10:04:15Z | [
"python",
"qgis",
"pyqtgraph"
] |
Python random while multiple conditions | 39,656,722 | <p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
... | 0 | 2016-09-23T08:57:53Z | 39,656,768 | <p>You could change the logically slightly and use an infinite loop that you then <code>break</code> out of when your conditions are met:</p>
<pre><code>while True:
# do stuff
if a >= 190 and b >= 140 and c >=110:
break
</code></pre>
<p>Your original logic terminated if <em>any</em> of the co... | 4 | 2016-09-23T09:00:36Z | [
"python",
"random",
"multiple-conditions"
] |
Python random while multiple conditions | 39,656,722 | <p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
... | 0 | 2016-09-23T08:57:53Z | 39,656,775 | <p>You are resetting <code>a</code>, <code>b</code> and <code>c</code> in the body of the loop.
Try this:</p>
<pre><code>>>> count = 0
>>> while a < 190 and b < 140 and c < 110 and count < 10: # <-- This condition here
... count += 1
... a = 0
... b = 0
... c = 0
... print(co... | 1 | 2016-09-23T09:00:51Z | [
"python",
"random",
"multiple-conditions"
] |
Python random while multiple conditions | 39,656,722 | <p>Cheers, my problem is that I don't know how to do a while with multiple conditions. I really don't get it why this won't work:</p>
<pre><code>import random
a = 0
b = 0
c = 0
while a < 190 and b < 140 and c < 110: # <-- This condition here
a = 0
b = 0
c = 0
for i in range(1, 465):
... | 0 | 2016-09-23T08:57:53Z | 39,657,141 | <p>Actually you are only showing "a,b,c" when the while loop iterates and you incrementing in each loop 465 times. This means if your while loop works 4 times its gonna increment a, b, c randomly 465*4 times. and your values too way small for this kinda increment. As a solution you can decrease 465 number if you make i... | 0 | 2016-09-23T09:20:53Z | [
"python",
"random",
"multiple-conditions"
] |
Python Pandas Debugging on to_datetime | 39,656,781 | <p>Millions of records of data is in my dataframe. I have to convert of the string columns to datetime. I'm doing it as follows:</p>
<pre><code>allData['Col1'] = pd.to_datetime(allData['Col1'])
</code></pre>
<p>However some of the strings are not valid datetime strings, and thus I get a value error. I'm not very g... | 1 | 2016-09-23T09:01:04Z | 39,656,810 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> with condition where check <code>NaT</code> values by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull... | 1 | 2016-09-23T09:02:32Z | [
"python",
"string",
"datetime",
"debugging",
"pandas"
] |
Create SQL database from dict with different features in python | 39,656,800 | <p>I have the following dict:</p>
<pre><code>base = {}
base['id1'] = {'apple':2, 'banana':4,'coconut':1}
base['id2'] = {'apple':4, 'pear':8}
base['id3'] = {'banana':1, 'tomato':2}
....
base['idN'] = {'pineapple':1}
</code></pre>
<p>I want to create a SQL database to store it. I normally use <code>sqlite</code> but he... | 0 | 2016-09-23T09:02:00Z | 39,656,907 | <p>ids will get duplicated if you use the sql i would suggest use postgres as it has a jsonfield ypu can put your data there corresponding to each key. Assuming you are not constrained to use SQL.</p>
| 0 | 2016-09-23T09:06:59Z | [
"python",
"sqlite",
"dictionary"
] |
how to add href value in django view | 39,656,843 | <p>I am working on a project using django, in this i have a module which shows the listing of users in a table format, the data of users returns from django view to django template using ajax, so the action values with buttons also have to be returned from view to template in json response, as we usually do in bootstra... | 0 | 2016-09-23T09:04:06Z | 39,656,929 | <p>Here you go..</p>
<pre><code><li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
</code></pre>
| 0 | 2016-09-23T09:08:44Z | [
"python",
"django"
] |
how to add href value in django view | 39,656,843 | <p>I am working on a project using django, in this i have a module which shows the listing of users in a table format, the data of users returns from django view to django template using ajax, so the action values with buttons also have to be returned from view to template in json response, as we usually do in bootstra... | 0 | 2016-09-23T09:04:06Z | 39,658,845 | <p>Use <code>reverse()</code> function to get the url</p>
<p>If you have specified a url pattern name like</p>
<pre><code>url(r'^foo/bar/(?P<user_id>\d+)/$', some_viewfunc, name='some-view')
</code></pre>
<p><code>reverse('some-view', kwargs={'user_id': 100})</code> gives you <code>'/foo/bar/100/'</code></p>
... | 0 | 2016-09-23T10:44:56Z | [
"python",
"django"
] |
How to get print data in text file ordered by date | 39,656,974 | <p>I have following code,</p>
<pre><code>import glob,os,win32com.client,datetime,time,email.utils,ctypes,sys
import Tkinter as tk
import tkFileDialog as filedialog
sys.path.append('C:\Windows\winsxs\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.1_none_e163563597edeada')
root = tk.Tk()
root.withdraw()
file_path = ... | 1 | 2016-09-23T09:11:25Z | 39,657,930 | <p>You can use the <code>email</code> module to get the time you received the email. </p>
<pre><code>import email
# use email.message_from_string or email_message_from_file to make a email object
email_obj = email.message_from_file(my_file) # my_file is a file object
print email_obj.keys() # shows you all available... | 0 | 2016-09-23T09:58:08Z | [
"python",
"email"
] |
Is the collection in tensorflow.get_collection() cleared? | 39,657,063 | <p>I'm learning about neural nets using Tensorflow through the Stanford course. I found this while implementing a RNN and did not quite understand why the losses are accumulated:</p>
<pre class="lang-python prettyprint-override"><code># This adds a loss operation to the Graph for batch training
def add_loss_op(self, o... | 1 | 2016-09-23T09:16:32Z | 39,678,543 | <p>I believe the add_n here is actually just to make sure that any pre-existing losses in the 'total_loss' collection get added in for the final result. It's not changing any variables, just summing up its inputs and returning the total.</p>
| 0 | 2016-09-24T16:29:58Z | [
"python",
"neural-network",
"tensorflow",
"recurrent-neural-network"
] |
Python: Create an exception for a refused database conection with pymysql | 39,657,106 | <p>Today I has the problem with a down database when a programmed script were running. I would like to create an exception when this happend again to send me an email (I already create the function to do it). But I'm failing in trying to create an exception for it.</p>
<pre><code> import pymysql.cursors
#Conect... | 0 | 2016-09-23T09:19:13Z | 39,657,387 | <p>Because you haven't defined an exception.</p>
<pre><code> import pymysql.cursors
#Connection Settings....
try:
with connection.cursor() as cursor:
# Read a single record
sql = "select count(*) as total_invoices, " \
"sum(e.Montant_vente - e.Montant... | 0 | 2016-09-23T09:32:58Z | [
"python",
"mysql",
"pymysql",
"try-except"
] |
Auto-fill Django OneToOneField | 39,657,126 | <p>This maybe a simple question, but I do not have any idea how to do this.
I have two models in Django.</p>
<pre><code>class ModelA(models.Model):
some_member = models.Charfield(...)
class ModelB(models.Model):
model = OneToOneField(ModelA)
other_member = models.Charfield(...)
</code></pre>
<p><code>Mod... | 1 | 2016-09-23T09:20:15Z | 39,658,134 | <p>Maybe you can save the data from ModelForm for ModelA in request.session or request.get and redirect to the next page for ModelB, where you can get the data for model field in ModelB then fill it.</p>
| 0 | 2016-09-23T10:08:45Z | [
"python",
"django",
"forms"
] |
Auto-fill Django OneToOneField | 39,657,126 | <p>This maybe a simple question, but I do not have any idea how to do this.
I have two models in Django.</p>
<pre><code>class ModelA(models.Model):
some_member = models.Charfield(...)
class ModelB(models.Model):
model = OneToOneField(ModelA)
other_member = models.Charfield(...)
</code></pre>
<p><code>Mod... | 1 | 2016-09-23T09:20:15Z | 39,658,745 | <p>It depends on what you want exactly.</p>
<p>If you want to auto-fill the field in the second form, then you can use the <code>initial</code> keyword argument when instantiating the form for ModelB (e.g. in your view); like this:</p>
<pre><code>def my_view(request):
"""
Save data to ModelA and show the user... | 0 | 2016-09-23T10:39:12Z | [
"python",
"django",
"forms"
] |
Automatic tagging of words or phrases | 39,657,146 | <p>I want to automatically tag a word/phrase with one of the defined words/phrases from a list. My list contains about 230 words in columnA which are tagged in columnB. There are around 16 unique tags and every of those 230 words are tagged with one of these 16 tags.</p>
<p>Have a look at my list:</p>
<p><a href="htt... | 0 | 2016-09-23T09:20:59Z | 39,662,787 | <h1>Short version</h1>
<p>I think your question is a little ill-defined and doesn't have a short coding or macro answer. Given that each item contains such little information, I don't think it is possible to build a good predictive model from your source data. Instead, do the tagging exercise once and look at how you ... | 0 | 2016-09-23T14:05:11Z | [
"python",
"excel",
"nlp",
"data-modeling",
"prediction"
] |
Word2Vec: Using Gensim and Google-News dataset- Very Slow Execution Time | 39,657,215 | <p>The Code is in python. I loaded up the binary model into gensim on python, & used the "init_sims" option to make the execution faster. The OS is OS X.
It takes almost 50-60 seconds to load it up. And an equivalent time to find "most_similar". Is this normal? Before using the init_sims option, it took almost doub... | 0 | 2016-09-23T09:24:33Z | 39,718,081 | <p>Note that the memory-saving effect of <code>init_sims(replace=True)</code> doesn't persist across save/load cycles, because saving always saves the 'raw' vectors (from which the unit-normalized vectors can be recalculated). So, even after your re-load, when you call <code>most_similar()</code> for the 1st time, <cod... | 0 | 2016-09-27T07:01:49Z | [
"python",
"gensim",
"word2vec"
] |
Python: how to count the access of an instance variable | 39,657,260 | <p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>... | 1 | 2016-09-23T09:27:44Z | 39,657,348 | <p>You can use <a href="https://docs.python.org/2/howto/descriptor.html" rel="nofollow">descriptors</a> for this or just make a property which is basically is descriptor.</p>
<pre><code>class A(object):
def __init__(self, logger):
self._b = B()
self._b_counter = 0
self.logger = logger
@prop... | 1 | 2016-09-23T09:31:25Z | [
"python",
"class"
] |
Python: how to count the access of an instance variable | 39,657,260 | <p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>... | 1 | 2016-09-23T09:27:44Z | 39,657,354 | <p>make 'b' a property and and increase the counter corresponding to be in the setter.</p>
<pre><code>@property
def b(self):
self.b_counter += 1
return self._b
</code></pre>
<p>and in your class replace b with _b</p>
| 2 | 2016-09-23T09:31:40Z | [
"python",
"class"
] |
Python: how to count the access of an instance variable | 39,657,260 | <p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>... | 1 | 2016-09-23T09:27:44Z | 39,657,408 | <p>You can use property, somtehing like:</p>
<pre><code>class A(object):
def __init__(self, logger):
self._b = B()
self._count = 0
self.logger = logger
@property
def b(self):
self._count += 1
return self._b
...
...
</code></pre>
| 0 | 2016-09-23T09:33:52Z | [
"python",
"class"
] |
Python: how to count the access of an instance variable | 39,657,260 | <p>I have a python class as below.</p>
<pre><code>class A(object):
def __init__(self, logger):
self.b = B()
self.logger = logger
def meth1(self):
self.b.mymethod1()
def meth2(self):
self.meth1()
self.b.mymethod2()
.........
class B(object):
---------
</code></pre>
<p>... | 1 | 2016-09-23T09:27:44Z | 39,657,527 | <p>If you don't want to make a property, you can log the read/write access using <code>__getattribute__</code> (not <code>__getattr__</code> since <code>b</code> exists and would not be called) and <code>__setattr__</code>:</p>
<pre><code>class A(object):
def __init__(self):
# initialize counters first !
... | 1 | 2016-09-23T09:39:33Z | [
"python",
"class"
] |
Quicksort in place Python | 39,657,307 | <p>I am extremely new to Python and i am trying my hand in Algorithms. I was just trying my hands in the in place sorting of an array using quicksort algo.</p>
<p>Below is my code . When i run this there is an infinite loop as output. Can anyone kindly go through the code and let me know where i am going wrong logical... | 0 | 2016-09-23T09:29:36Z | 39,668,817 | <p>Your recursion is wrong. After doing Hoare Partition, you should do :</p>
<ul>
<li>call quicksort from start (of data that being sorted) to index that run from the end, and</li>
<li>call quicksort from end (of data that being sorted) to index that run from the start</li>
</ul>
<p>So you have to create new variable... | 0 | 2016-09-23T20:11:08Z | [
"python"
] |
How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column | 39,657,330 | <p><br>A very simple example just for understanding.</p>
<p><strong>The goal is to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column.</strong></p>
<p>I have the following DataFrame:</p>
<pre><code>import numpy as np
import pandas as pd
s = pd.Series... | 3 | 2016-09-23T09:30:40Z | 39,657,514 | <p>IIUC the explanation by @IanS (thanks again!), you can do</p>
<pre><code>In [75]: np.array([df.DATA.rolling(4).max().shift(-i) == df.DATA for i in range(4)]).T.sum(axis=1)
Out[75]: array([0, 0, 3, 0, 0, 0, 3, 0, 0])
</code></pre>
<p>To update the column:</p>
<pre><code>In [78]: df = pd.DataFrame({'DATA':s, 'POINT... | 2 | 2016-09-23T09:38:53Z | [
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
How to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column | 39,657,330 | <p><br>A very simple example just for understanding.</p>
<p><strong>The goal is to calculate the values of a pandas DataFrame column depending on the results of a rolling function from another column.</strong></p>
<p>I have the following DataFrame:</p>
<pre><code>import numpy as np
import pandas as pd
s = pd.Series... | 3 | 2016-09-23T09:30:40Z | 39,659,948 | <pre><code>import pandas as pd
s = pd.Series([1,2,3,2,1,2,3,2,1])
df = pd.DataFrame({'DATA':s, 'POINTS':0})
df.POINTS=df.DATA.rolling(4).max().shift(-1)
df.POINTS=(df.POINTS*(df.POINTS==df.DATA)).fillna(0)
</code></pre>
| 1 | 2016-09-23T11:43:08Z | [
"python",
"pandas",
"dataframe",
"calculated-columns"
] |
openpyxl: Worksheet does not exist (related to character sets) | 39,657,361 | <p>I load a worksheet with openpyxl and encounter the issue <code>Worksheet does not exist</code> raised by <code>get_sheet_by_name</code>.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from openpyxl import load_workbook
file_workbook = 'JCR2015å½±åå åï¼æææåä»é«å°ä½æåºï¼+ä¸ç§é... | 0 | 2016-09-23T09:32:04Z | 39,658,481 | <p>It seems like you need to tell python you're using unicode:
Add this declaration at the top of your file:</p>
<pre><code># -*- coding: utf-8 -*-
</code></pre>
<p>And every string which holds Characters should be prefixed with u:</p>
<pre><code>file_workbook = u'JCR2015å½±åå åï¼æææåä»é«å°ä½æåº... | 1 | 2016-09-23T10:26:20Z | [
"python",
"excel",
"character-encoding",
"openpyxl"
] |
How to draw properly networkx graphs | 39,657,395 | <p>I got this code which allows me to draw a graph like the posted below</p>
<pre><code>import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphviz_layout
G = nx.DiGraph()
G.add_node(1,level=1)
G.add_node(2,level=2)
G.add_node(3,level=2)
G.add_node(4,level=3)
G.add_edge(1,2)
G.add_edge... | 0 | 2016-09-23T09:33:19Z | 39,662,097 | <p>Since you have Graphviz you can use that to make nice drawings and control the elements of the drawing. The 'dot' layout engine does a great job of positioning digraphs like the one in your example.
For example </p>
<pre><code>import networkx as nx
import pylab as plt
from networkx.drawing.nx_agraph import graphvi... | 1 | 2016-09-23T13:31:12Z | [
"python",
"graph",
"networkx"
] |
Cythonize dynamic pyx function | 39,657,830 | <p>I've created a <code>pyx</code> file dynamically, but struggle to cythonize and use the function encoded in it.</p>
<p>I tried </p>
<pre><code>import pyximport
pyximport.install()
import imp
module = imp.load_source('module.name', pyxfilename)
</code></pre>
<p>but this doesn't seem to work. Any idea how can I do ... | 0 | 2016-09-23T09:52:57Z | 39,659,093 | <p>You could use the function <code>pyximport.load_module</code> instead of <code>imp.load_source</code> (<a href="https://github.com/cython/cython/blob/151d653d3c7ab07e9d961c9601b2ff45202e6ce2/pyximport/pyximport.py#L207" rel="nofollow">https://github.com/cython/cython/blob/151d653d3c7ab07e9d961c9601b2ff45202e6ce2/pyx... | 2 | 2016-09-23T10:57:58Z | [
"python",
"cython"
] |
Django project to domain, vps | 39,657,888 | <p>I have VPS-server (CentOS 6.8)</p>
<p>I installed Python 3.5.2 and Django 1.10.1 on virtual enviroment</p>
<p>I connected my domain to VPS-server</p>
<p>Now:</p>
<pre><code>django-project:
(venv) /home/django_user/djtest/venv/django_project/django_project
domain:
/var/www/www-root/data/www/mydomain.com
</code><... | -1 | 2016-09-23T09:55:52Z | 39,658,093 | <p>Django project can't be served like this, you need some web-server application like gunicorn or apache too. </p>
<p>Just like you use <code>./manage.py runserver</code> you need some application to execute your django project corresponsing to command theses application are <a href="https://www.google.co.in/url?sa=t... | 1 | 2016-09-23T10:06:29Z | [
"python",
"django",
"dns",
"vps"
] |
How to show dialogs at a certain position inside a QScintilla widget? | 39,657,924 | <p>I got this simple piece of mcve code:</p>
<pre><code>import sys
import re
from PyQt5 import QtGui, QtWidgets, QtCore
from PyQt5.Qsci import QsciScintilla
from PyQt5 import Qsci
class SimpleEditor(QsciScintilla):
def __init__(self, language=None, parent=None):
super().__init__(parent)
font =... | 2 | 2016-09-23T09:57:43Z | 39,665,988 | <p>The <code>cursorPositionChanged</code> signal can be used to detect whenever the mouse or keyboard moves the caret to a position within a number. A regexp can then be used to find where the number starts and ends on the current line. Once you have that, you can use some low-level functions to calculate the global po... | 2 | 2016-09-23T16:59:03Z | [
"python",
"pyqt",
"qscintilla"
] |
Fetching model instance from a multiple direct relationship | 39,658,142 | <p>Can anyone help me fetch data from this model structure? because i have a hard time doin this for hours now.</p>
<p><strong>First I would like to get all distinct <code>SubSpecialization</code> from all <code>Doctor</code> which has a given <code>Specialization.title</code></strong></p>
<p><strong>Secondly I would... | 0 | 2016-09-23T10:08:59Z | 39,658,406 | <p>Firstly, your specialization and subspecialization are both many-to-many relationships with Doctor. You should declare that explicitly, and drop those intervening models unless you need to store other information on them.</p>
<pre><code>class Doctor(models.Model):
...
specializations = models.ManyToManyFiel... | 1 | 2016-09-23T10:22:26Z | [
"python",
"django",
"django-models"
] |
'NoneType' object has no attribute 'append' | 39,658,150 | <p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'g... | -1 | 2016-09-23T10:09:25Z | 39,658,215 | <p>Your values are set to <em>None</em> in <em>fromkeys</em> unless you explicitly set a value:</p>
<p><strong>fromkeys(seq[, value])</strong></p>
<p><em>Create a new dictionary with keys from seq and values set to value.
fromkeys() is a class method that returns a new dictionary. value defaults to None.</em></p>
<p... | 3 | 2016-09-23T10:12:20Z | [
"python"
] |
'NoneType' object has no attribute 'append' | 39,658,150 | <p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'g... | -1 | 2016-09-23T10:09:25Z | 39,658,269 | <p>For a small number of keys/tests a dictionary comprehension would work as well:</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
out = {k: [v for v in tests_available if v.startswith(k)] for k in keys}
</code></pre>
<p>Demo:</p>
<pre><code>>... | 1 | 2016-09-23T10:14:41Z | [
"python"
] |
'NoneType' object has no attribute 'append' | 39,658,150 | <p>I have two lists that I'm merging into a dictionary</p>
<pre><code>keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
</code></pre>
<p>The expected output will be something like</p>
<pre><code>{'p2p': ['p2p_1', 'p2p_2', 'p2p_3'], 'groupchat': ['groupchat_1', 'g... | -1 | 2016-09-23T10:09:25Z | 39,658,370 | <p>If you use a defaultdict then the append call will work as the value type defaults to a list:</p>
<pre><code>In [269]:
from collections import defaultdict
keys = ['p2p', 'groupchat']
tests_available = ['p2p_1', 'p2p_2', 'p2p_3', 'groupchat_1', 'groupchat_2']
d = defaultdict(list)
for test in tests_available:
k ... | 2 | 2016-09-23T10:20:25Z | [
"python"
] |
Email confirm error rest-auth | 39,658,373 | <p>I use a standard form for the confirmation email:
from allauth.account.views import confirm_email as allauthemailconfirmation</p>
<pre><code>urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest-auth/', include('rest_auth.urls')),
url(r'^accounts/', include('allauth.urls')),
url(r'^rest-auth... | 0 | 2016-09-23T10:20:36Z | 39,663,046 | <p>I think I found your problem.</p>
<p>This url:</p>
<pre><code>/rest-auth/registration/account-confirm-email/MTU:1bn1OD:dQ_mCYi6Zpr8h2aKS9J9BvNdDjA/
</code></pre>
<p>is not matched by this pattern:</p>
<pre><code>url(r'^rest-auth/registration/account-confirm-email/(?P<key>\w+)/$', allauthemailconfirmation, ... | 0 | 2016-09-23T14:17:09Z | [
"python",
"django",
"django-rest-framework",
"django-allauth",
"django-rest-auth"
] |
Python - cannot import name viewkeys | 39,658,404 | <p>I'm importing a module which inturn imports <code>six</code>, but I'm getting this weird error. </p>
<pre><code>Traceback (most recent call last):
File "/Users/praful/Desktop/got/modules/categories/tests.py", line 13, in <module>
import microdata
File "build/bdist.macosx-10.10-intel/egg/microdata.py",... | 1 | 2016-09-23T10:22:11Z | 39,675,202 | <p>I had the same problem:</p>
<pre><code>> python
Python 2.7.10 (default, Oct 23 2015, 19:19:21)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import six
>>> import xhtml2pdf.pisa
Traceback (most re... | 1 | 2016-09-24T10:14:41Z | [
"python",
"python-six"
] |
postgresql sqlalchemy core define constraint to a combination of the columns at a time | 39,658,434 | <p>I have a model defined as:</p>
<pre><code>groups_categories = Table("groups_categories", metadata,
Column("id", Integer, primary_key=True),
Column("group", Integer, ForeignKey("groups.id")),
Column("dept", Integer, ForeignKey("departments.id"))... | 0 | 2016-09-23T10:23:40Z | 39,658,985 | <p>If I understood you correctly, you're looking for a <a href="http://docs.sqlalchemy.org/en/latest/core/constraints.html#check-constraint" rel="nofollow"><code>CheckConstraint</code></a> such that both <em>group</em> and <em>dept</em> cannot be non-null values at the same time:</p>
<pre><code>CHECK (NOT ("group" IS ... | 1 | 2016-09-23T10:52:04Z | [
"python",
"postgresql",
"sqlalchemy"
] |
Splice dictonary to create list of tuples in Python | 39,658,463 | <p>So I have these two dictonaries, where the key is a year (an integer), and the value a float. I want to combine these two, and as a result create a list of tuples, with the year, value1, value2. So like this:</p>
<p>Dictonary 1</p>
<pre><code> {2011: 1.0,
2012: 2.0,
2013: 3.0}
</code></pre>
<p>Dictonary 2</p>
... | 1 | 2016-09-23T10:24:57Z | 39,658,556 | <p>If both dictionaries have the same keys:</p>
<pre><code>[(k, dict1[k], dict2[k]) for k in dict1.keys()]
</code></pre>
<p>Example:</p>
<pre><code>In[33]: dict1 = {2011: 1.0,
2012: 2.0,
2013: 3.0}
In[34]: dict2 = {2011: 4.0,
2012: 5.0,
2013: 6.0}
In[35]: [(k, dict1[k], dict2[k]) for k in dict1.keys()]
Out[35]... | 2 | 2016-09-23T10:29:22Z | [
"python",
"python-2.7"
] |
Splice dictonary to create list of tuples in Python | 39,658,463 | <p>So I have these two dictonaries, where the key is a year (an integer), and the value a float. I want to combine these two, and as a result create a list of tuples, with the year, value1, value2. So like this:</p>
<p>Dictonary 1</p>
<pre><code> {2011: 1.0,
2012: 2.0,
2013: 3.0}
</code></pre>
<p>Dictonary 2</p>
... | 1 | 2016-09-23T10:24:57Z | 39,658,582 | <p>Here's few possible solutions:</p>
<pre><code>import timeit
import random
random.seed(1)
def f1(d1, d2):
return [(k, d1[k], d2[k]) for k in list(set(d1.keys() + d1.keys()))]
def f2(d1, d2):
return [(k, d1[k], d2[k]) for k in d1.viewkeys() & d2]
def f3(d1, d2):
return [(k, d1[k], d2[k]) for k ... | 4 | 2016-09-23T10:30:37Z | [
"python",
"python-2.7"
] |
How to export and import data and auth information in Django? | 39,658,476 | <p>I'm working on a project which is already public so there are some <strong>Order</strong> objects and <strong>User</strong> objects in the database (couple of people has registrated and created some orders).</p>
<p>Now I'm changing some things in this project including <strong>Order</strong> model (added some field... | 1 | 2016-09-23T10:25:54Z | 39,658,889 | <p>Fixtures can be used for this <a href="https://docs.djangoproject.com/en/dev/howto/initial-data/" rel="nofollow">https://docs.djangoproject.com/en/dev/howto/initial-data/</a> </p>
<p>To dump the data on local machine </p>
<pre><code>./manage.py dumpdata mytable > databasedump.json
</code></pre>
<p>and import... | 1 | 2016-09-23T10:47:22Z | [
"python",
"django",
"sqlite"
] |
Python/OpenCV: Using cv2.resize() I get an error | 39,658,497 | <p>I'm using python 2.7 and opencv. </p>
<p>I'm trying to use:</p>
<pre><code>cv2.resize(src, dst, Size(), 0.5, 0.5, interpolation=cv2.INTER_LINEAR);
</code></pre>
<p>taken from <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html#resize" rel="nofollow">here</a>. But when I run this... | 0 | 2016-09-23T10:26:48Z | 39,658,618 | <p>You are probably looking at the C++ api of <code>resize</code> method.</p>
<p>The python API looks something like this:</p>
<pre><code>dst = cv2.resize(src, dsize)
</code></pre>
<p>where </p>
<pre><code>src - Original image
dsize - a tuple defining the final size of the image.
</code></pre>
<p>If you want to pa... | 3 | 2016-09-23T10:32:33Z | [
"python",
"python-2.7",
"opencv"
] |
Python class variable getting altered by changing instance variable that should just take its value | 39,658,532 | <p>I'm stumbling over a weird effect when initializing a Python class. Not sure if I'm overlooking something obvious or not.</p>
<p>First things first, I'm aware that apparently lists passed to classes are passed by reference while integers are passed by value as shown in this example:</p>
<pre><code>class Test:
de... | 0 | 2016-09-23T10:28:29Z | 39,658,650 | <p>Here:</p>
<pre><code> else:
self.dataSheet[u'Item'] = self.MISSINGKEYS[u'Item']
</code></pre>
<p>You are setting <code>dataShee['Item']</code> with the list that is the value of <code>MISSINGKEYS['Item']</code>. <em>The same list.</em> Try</p>
<pre><code> else:
self.dataSheet[u'Item'] = list(self.MISSINGKEYS[... | 1 | 2016-09-23T10:34:27Z | [
"python",
"python-2.7",
"class",
"pass-by-reference"
] |
Python class variable getting altered by changing instance variable that should just take its value | 39,658,532 | <p>I'm stumbling over a weird effect when initializing a Python class. Not sure if I'm overlooking something obvious or not.</p>
<p>First things first, I'm aware that apparently lists passed to classes are passed by reference while integers are passed by value as shown in this example:</p>
<pre><code>class Test:
de... | 0 | 2016-09-23T10:28:29Z | 39,659,335 | <p>Thinking about what happens in Python function calls in terms of "pass by reference" vs "pass by value" is not generally useful; some people like to use the term "pass by object". Remember, everything in Python is an object, so even when you pass an integer to a function (in C terminology) you're actually passing a ... | 1 | 2016-09-23T11:11:02Z | [
"python",
"python-2.7",
"class",
"pass-by-reference"
] |
Modify CherryPy's shutdown procedure | 39,658,549 | <p>So I have a cherry py server which wraps a state machine. Behind the scenes this state machine does all the heavy lifting of mananging processes and threads and caching, and it is thread safe. So on start up of my cherry py I attach it to the app and the requests call into app.state_machine.methods.</p>
<p>In pseud... | 0 | 2016-09-23T10:29:08Z | 39,664,617 | <p>As suggested by web ninja, the answer was to use the plugin.</p>
<pre><code>from cherrypy.process import wspbus, plugins
class StateMachinePlugin(plugins.SimplePlugin) :
def __init__(self, bus, state_machine):
plugins.SimplePlugin.__init__(self, bus)
self.state_manager = state_machine
def... | 0 | 2016-09-23T15:35:12Z | [
"python",
"multithreading",
"webserver",
"cherrypy"
] |
How to drop columns which have same values in all rows via pandas or spark dataframe? | 39,658,574 | <p>Suppose I've data similar to following:</p>
<pre><code> index id name value value2 value3 data1 val5
0 345 name1 1 99 23 3 66
1 12 name2 1 99 23 2 66
5 2 name6 1 99 23 7 66
</code></pre>
<p>How can we drop all those colu... | 2 | 2016-09-23T10:30:25Z | 39,658,662 | <p>What we can do is <code>apply</code> <code>nunique</code> to calc the number of unique values in the df and drop the columns which only have a single unique value:</p>
<pre><code>In [285]:
cols = list(df)
nunique = df.apply(pd.Series.nunique)
cols_to_drop = nunique[nunique == 1].index
df.drop(cols_to_drop, axis=1)
... | 3 | 2016-09-23T10:35:00Z | [
"python",
"pandas",
"duplicates",
"multiple-columns",
"spark-dataframe"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.