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 |
|---|---|---|---|---|---|---|---|---|---|
Arguments parsed by argparse are not accessible in other files | 38,029,728 | <p>I have parsed arguments using <code>argparse</code> in my <code>main.py</code> files. I have a few variables defined in the <code>global_vars.py</code> file and this file is included in <code>main.py</code> and other files.</p>
<p>I am assigning parsed arguments to global variables, but when I try to access these g... | 0 | 2016-06-25T14:53:48Z | 38,030,261 | <p>Note that any code you put inside the <code>if __name__ == "__main__":</code> will only run if you run the python file directly. So if that code is suppose to be your global_var.py, and you are simply importing global_var, then that code is not running and your variables are never initialised. Put some print stateme... | 0 | 2016-06-25T15:56:44Z | [
"python",
"argparse"
] |
Arguments parsed by argparse are not accessible in other files | 38,029,728 | <p>I have parsed arguments using <code>argparse</code> in my <code>main.py</code> files. I have a few variables defined in the <code>global_vars.py</code> file and this file is included in <code>main.py</code> and other files.</p>
<p>I am assigning parsed arguments to global variables, but when I try to access these g... | 0 | 2016-06-25T14:53:48Z | 38,030,336 | <p><code>argparse</code> isn't the only thing that has a namespace. Every module (file) and function has one. <code>argparse</code> just returns an object of class <code>argparse.Namespace</code>, which can be treated like the namespace of a module. That is, you access items in that object with the <code>args.name</... | 0 | 2016-06-25T16:04:24Z | [
"python",
"argparse"
] |
Is there a way to make this code less long but do the same thing? | 38,029,741 | <pre><code>sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
... | 0 | 2016-06-25T14:55:16Z | 38,029,804 | <p>If you want to check for special characters do:</p>
<pre><code>special_char = 0
for i in sentence:
if i.isalpha() == False and i.idigit() == False:
special_char += 1
</code></pre>
<p>For spaces:</p>
<pre><code>spaces = sentence.count(' ')
</code></pre>
<p>For vowels, make a dictionary with vowels as ... | 1 | 2016-06-25T15:04:03Z | [
"python",
"loops",
"counting"
] |
Is there a way to make this code less long but do the same thing? | 38,029,741 | <pre><code>sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
... | 0 | 2016-06-25T14:55:16Z | 38,029,823 | <pre><code>sentence = input("What is your sentence?")
vowels=['a','e','i','o','u']
</code></pre>
<p>create array for spaces and for special characters</p>
<pre><code>for i in range len(sentence):
if(sentence[i] in vowels):
count_vowel++;
else if(sentence[i] in spaces):
count_space++;
else ... | -1 | 2016-06-25T15:06:48Z | [
"python",
"loops",
"counting"
] |
Is there a way to make this code less long but do the same thing? | 38,029,741 | <pre><code>sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
... | 0 | 2016-06-25T14:55:16Z | 38,029,890 | <p>One loop to rule em all:</p>
<pre><code>sentence = raw_input()
vowels = special_char = spaces = 0
for letter in sentence.lower():
if letter in ['a', 'e', 'i', 'o', 'u']:
vowels += 1
elif letter == ' ':
spaces += 1
elif not (letter.isalpha() or letter.isdigit()):
special_char += 1... | 0 | 2016-06-25T15:14:28Z | [
"python",
"loops",
"counting"
] |
Is there a way to make this code less long but do the same thing? | 38,029,741 | <pre><code>sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
... | 0 | 2016-06-25T14:55:16Z | 38,029,975 | <p>Looking at the solutions, you have probably made up your mind already. Just to shorten it down by selecting the individual characters you want to use, try this code below.</p>
<pre><code>word = "banana"
characters = ["A", "E", "I", "O", "U"]
for letter in word:
if letter in characters:
print("Special ch... | 0 | 2016-06-25T15:23:06Z | [
"python",
"loops",
"counting"
] |
Is there a way to make this code less long but do the same thing? | 38,029,741 | <pre><code>sentence = input("What is your sentence?")
sentence=sentence.capitalize()
counta = sentence.count("a")
counte = sentence.count("e")
counti = sentence.count("i")
counto= sentence.count ("o")
countu= sentence.count ("u")
countA2 = sentence.count("A")
countE2 = sentence.count("E")
countI2 = sentence.count("I")
... | 0 | 2016-06-25T14:55:16Z | 38,030,016 | <p>In case if you like list comprehension :</p>
<pre><code>sentence = raw_input("What is your sentence ? ")
print "Vowels : " + str(len([i for i in sentence if i.lower() in ('a','e','i','o','u')]))
print "Spaces : " + str(sentence.count(' '))
print "Special Chars : " + str(len([i for i in sentence if (not i.isalpha() ... | 0 | 2016-06-25T15:27:56Z | [
"python",
"loops",
"counting"
] |
Obtaining output of a C program in python | 38,029,813 | <p>Kind of a simple question but I can't find anything near my issue so here I go, I'm trying to execute a C program in Python to get the output, problem is it doesn't work.
I've got no error but when I try to print the output I just get nothing, like a blank space or something, but if I print what is being outputed (... | -2 | 2016-06-25T15:05:09Z | 38,029,850 | <p>Two issues here:</p>
<ul>
<li><code>Popen</code> takes a <em>list</em> of arguments, not a string. Passing that when <code>shell=True</code> is a bad security hazard. Imagine if <code>width</code> equaled <code>; rm -rf /</code>.</li>
<li>The return value is a special object that contains information about the <em>... | -1 | 2016-06-25T15:10:35Z | [
"python",
"c",
"subprocess",
"popen"
] |
How to get localized day-names in django? | 38,029,827 | <p>When using djangos (or better gettext's) localization mechanism, it's hard to get the current locale's day names. Usually, i would use <code>calendar</code>:</p>
<pre><code>calendar.day_name[current_day]
</code></pre>
<p>Where <code>current_day</code> is a int between 0 and 6. This won't work, as Django does not s... | 3 | 2016-06-25T15:07:05Z | 38,029,967 | <p>You can use <code>django.utils.formats.date_format</code>.</p>
<pre><code>>>> from django.utils.formats import date_format
>>> from django.utils import translation
>>> from datetime import date
>>> date_format(date.today(), 'l')
'Saturday'
>>> translation.activate('fr')
... | 2 | 2016-06-25T15:22:41Z | [
"python",
"django",
"localization",
"calendar",
"internationalization"
] |
ODOO-8: Cannot write FLEET_ID field to invoice (from MRP REPAIR) | 38,029,883 | <p>Ok so the update now is that i dont receive any more errors (500-error and null value) </p>
<h1>But the invoice doesn't get updated with the vehicle[fleet_id] from MRP repair when the button is clicked</h1>
<p>The code i've added so far - MRP_REPAIR.PY</p>
<pre><code>def action_invoice_create(self, cr, uid, ids, ... | 0 | 2016-06-25T15:13:27Z | 38,040,180 | <p>Assumption: repair order holds the <code>fleet_id</code></p>
<p>Try to change action_invoice_create() like:</p>
<pre class="lang-py prettyprint-override"><code>def action_invoice_create(self, cr, uid, ids, group=False, context=None):
context = dict(context or {})
repair = self.browse(cr, uid, ids[0], conte... | 0 | 2016-06-26T15:39:04Z | [
"python",
"openerp",
"odoo-8"
] |
How to cast a widget to a subclass in PyQt/PySide | 38,029,960 | <pre><code> widget = self.childAt(event.x(), event.y())
selection = widget.textCursor().selectedText()
</code></pre>
<p>I <em>know</em> this is gonna be a QTextEdit, no other widgets in my window, however :</p>
<pre><code>AttributeError: 'PySide.QtGui.QWidget' object has no attribute 'textCursor'
</cod... | -1 | 2016-06-25T15:22:16Z | 38,031,419 | <p>I use native Qt/C++, but must be something similar to C++ implementation:</p>
<pre><code>CustomWidget* widget = dynamic_cast<CustomWidget*>(widget);
</code></pre>
<p>In python, you can use isinstance:</p>
<pre><code>isinstance(pax, CustomWidget)
</code></pre>
<p>Or the builtin type function:</p>
<pre><cod... | 0 | 2016-06-25T18:02:21Z | [
"python",
"qt",
"pyqt",
"pyside"
] |
Python 3.3.2 Username taken | 38,029,961 | <p>My son's trying to make and understand a code that lets the user enter the name of a file they want but if it is already taken then they get a choice of overwriting the file or to change the name of it.</p>
<p>i.e. </p>
<blockquote>
<p>Enter a name: Example<br>
If taken do you want to overwrite: No<br>
En... | -3 | 2016-06-25T15:22:18Z | 38,030,019 | <p>To write to a file / over-write an existing file name, it's pretty simple with the <code>write()</code> function.</p>
<pre><code>name = "test.txt"
f = open("test.txt", "w")
f.write(name)
f.close()
</code></pre>
<p>That's to over-write the file, even if the name already exists.</p>
<p>If you want to check if the f... | 0 | 2016-06-25T15:28:36Z | [
"python",
"username"
] |
Create Adjacency Matrix in Python for large Dataset | 38,030,054 | <p>I have a problem with representing website user behaviour in a Adjacency Matrix in Python. I want to analyze the user interaction between 43 different websites to see which websites are used together.</p>
<p>The given data set has about 13.000.000 lines with following structure:</p>
<pre><code> user website
id1 ... | 1 | 2016-06-25T15:33:27Z | 38,030,699 | <pre><code>import scipy.sparse
data = """
id1 web1
id1 web2
id1 web2
id2 web1
id2 web2
id3 web3
id3 web2
"""
data = np.array(data.split()).reshape(-1, 2)
_, i = np.unique(data[:, 0], return_inverse=True)
_, j = np.unique(data[:, 1], return_inverse=True)
incidence = scipy.sparse.coo_matrix((np.ones_like... | 4 | 2016-06-25T16:46:22Z | [
"python",
"numpy",
"matrix",
"bigdata",
"adjacency-matrix"
] |
using python regex on tuples to filter user inputs | 38,030,061 | <p>I want to use regex to filter user input based on a set of tuples. An error message should be returned if the user input isn't found in the <code>set of tuples</code> and is not <code>an alphanumeric character</code> . I don't how I can access the tuples in my python regex code. So I passed in <code>src.items()</cod... | 0 | 2016-06-25T15:33:56Z | 38,030,151 | <p>This is not a good place to use regexps, and that is nothing like a valid Python regexp.</p>
<p>You are better off just checking whether the user input (maybe forced to lower case) is equal to any of the commands, in a loop.</p>
| 0 | 2016-06-25T15:44:33Z | [
"python",
"regex",
"python-2.7",
"tuples"
] |
using python regex on tuples to filter user inputs | 38,030,061 | <p>I want to use regex to filter user input based on a set of tuples. An error message should be returned if the user input isn't found in the <code>set of tuples</code> and is not <code>an alphanumeric character</code> . I don't how I can access the tuples in my python regex code. So I passed in <code>src.items()</cod... | 0 | 2016-06-25T15:33:56Z | 38,030,657 | <p>First, there's a redundancy here:</p>
<blockquote>
<p>An error message should be returned if the user input isn't found in
the set of tuples and is not an alphanumeric character</p>
</blockquote>
<p>If the user input is in your set of tuples, how can it contain a nonalphanumeric character? Also you don't spec... | 1 | 2016-06-25T16:41:44Z | [
"python",
"regex",
"python-2.7",
"tuples"
] |
Can a Thread not be daemonized in python3.2? | 38,030,063 | <p>I am running a script in <strong>python-3.2</strong> on a <strong>Raspberry Pi 2 Model B</strong></p>
<p>The thread looks like this:</p>
<pre><code>myThread = threading.Thread(target=someFunction, args=(arg1,arg2,arg3),
daemon=True)
myThread.start()
</code></pre>
<p>Everytime this thread gets called. ... | 1 | 2016-06-25T15:34:08Z | 38,030,082 | <p>The daemon argument was added in version 3.3, <a href="https://docs.python.org/3.3/library/threading.html#threading.Thread" rel="nofollow">see</a>. Setting the flag in prior versions works like this:</p>
<pre><code>myThread = threading.Thread(target=someFunction, args=(arg1,arg2,arg3))
myThread.daemon = True
myThre... | 3 | 2016-06-25T15:37:01Z | [
"python",
"multithreading",
"python-3.2"
] |
Get started with user click analysis for ecommerce recommendations | 38,030,126 | <p>I am building a website similar to an eCommerce site. I want to implement personalization to that. To achieve this, I've been told that click stream analysis will be better. As data I plan to collect logged in user ID, click time of the day, price of the clicked item. Otherthan that user's personal information such ... | -3 | 2016-06-25T15:42:33Z | 38,146,283 | <p>you can use binary rating from users.each user that click each item you have a rate 1 and each item that you recommend user and he refuse it you earned 0 rate. for more information and make online recommendation look at this <a href="http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=6854459&url=http%3A%2... | 0 | 2016-07-01T13:08:45Z | [
"python",
"e-commerce",
"analysis",
"recommendation-engine",
"clickstream"
] |
Python: Convert list to a dictionary, where key is the index of the element of the list | 38,030,128 | <p>I have a <code>list</code> and I want to convert it to a dictionary <code>dict</code> where the key of an element is the position of the element in the list:</p>
<pre><code>>>> list_ = ['a', 'b', 'c', 'd']
>>> # I want the above list to be converted to a dict as shown below
...
>>> list_t... | 1 | 2016-06-25T15:42:39Z | 38,030,154 | <p><code>defaultdict()</code> produces default <strong>values</strong>, you are generating <em>keys</em> so it won't help you here.</p>
<p>Using <code>enumerate()</code> is the best way; you can simplify that to:</p>
<pre><code>dict(enumerate(list_, 1))
</code></pre>
<p>The second argument to <code>enumerate()</code... | 6 | 2016-06-25T15:44:57Z | [
"python",
"dictionary"
] |
Python: Convert list to a dictionary, where key is the index of the element of the list | 38,030,128 | <p>I have a <code>list</code> and I want to convert it to a dictionary <code>dict</code> where the key of an element is the position of the element in the list:</p>
<pre><code>>>> list_ = ['a', 'b', 'c', 'd']
>>> # I want the above list to be converted to a dict as shown below
...
>>> list_t... | 1 | 2016-06-25T15:42:39Z | 38,030,410 | <p>You could use defaultdict too.</p>
<pre><code>from collections import defaultdict
list_ = ['a','b','c','d']
s = (zip([i for i in range(1, len(list_) + 1)], list_))
list_to_dict = defaultdict(str)
for k, v in s:
list_to_dict[k] = v
print list_to_dict
</code></pre>
<p>or like below..</p>
<pre><code>dict(zip([... | 1 | 2016-06-25T16:12:53Z | [
"python",
"dictionary"
] |
Best way to detect a light blinking from video footage via python | 38,030,170 | <p>I have some video footage and wish to analyse when a light source blinks. The light source is at the same location, so should easy to work with the ROI. </p>
<p>I'm used to working with python, but not very strong when it comes to video analyzing - don't care that much about formats and technical stuff. Just wish t... | -1 | 2016-06-25T15:46:48Z | 38,030,271 | <p><a href="http://mahotas.readthedocs.io/en/latest/" rel="nofollow">mahotas</a> may be a good choice for analyzing the image. It loads an image as a numpy array so it would be trivial to elect a ROI. Also it has built-in methods to threshold, calculate mean brightness of picture and stuff like this. Last but not least... | 0 | 2016-06-25T15:57:38Z | [
"python",
"video",
"video-capture",
"video-processing",
"roi"
] |
Hide application icon from task bar | 38,030,277 | <p>I am trying to hide the application icon from the task bar.</p>
<p><a href="http://i.stack.imgur.com/42dER.png" rel="nofollow"><img src="http://i.stack.imgur.com/42dER.png" alt="enter image description here"></a> </p>
<p>So far I tried those</p>
<pre><code>self.window.set_skip_pager_hint(True)
</code></pre>
<p>a... | 0 | 2016-06-25T15:58:10Z | 38,030,434 | <p><code>set_skip_pager_hint()</code> is for the Alt-Tab dialog. You want <code>set_skip_taskbar_hint()</code> instead.</p>
| 2 | 2016-06-25T16:15:22Z | [
"python",
"gtk"
] |
how to find/search the values in the list that from dictionary | 38,030,381 | <pre><code>laptops = {'OIS12345':['192.168.1.10', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23415':['192.168.1.11', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23451':['192.168.1.18', 'Windows 7', 'i5', '4GB','2.6GHz', '600GB', '13-Jan-14']}
names = laptop... | 2 | 2016-06-25T16:10:06Z | 38,030,423 | <p>I guess this is what you want:</p>
<pre><code>for name, specs in laptops.items():
if int(specs[3][:-2]) < 8:
print(name)
</code></pre>
| 3 | 2016-06-25T16:14:04Z | [
"python"
] |
how to find/search the values in the list that from dictionary | 38,030,381 | <pre><code>laptops = {'OIS12345':['192.168.1.10', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23415':['192.168.1.11', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23451':['192.168.1.18', 'Windows 7', 'i5', '4GB','2.6GHz', '600GB', '13-Jan-14']}
names = laptop... | 2 | 2016-06-25T16:10:06Z | 38,030,759 | <p>Using Python dictionary comprehension</p>
<pre><code>print {k for k, v in laptops.iteritems() if int(v[3][:1]) < 8}
</code></pre>
| 0 | 2016-06-25T16:52:34Z | [
"python"
] |
how to find/search the values in the list that from dictionary | 38,030,381 | <pre><code>laptops = {'OIS12345':['192.168.1.10', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23415':['192.168.1.11', 'Windows 8', 'i7', '8GB','2.7GHz', '700GB', '15-Dec-14'],
'OIS23451':['192.168.1.18', 'Windows 7', 'i5', '4GB','2.6GHz', '600GB', '13-Jan-14']}
names = laptop... | 2 | 2016-06-25T16:10:06Z | 38,031,630 | <p>You can try this way, works with any number and GB limit.</p>
<pre><code>for key, value in laptops.items():
number = value[3]
end = number.index("GB")
if int(number[:end]) < 8:
print(key)
</code></pre>
<p>Output:</p>
<pre><code>OIS23451
</code></pre>
<p>You could also print out the compute... | 0 | 2016-06-25T18:23:46Z | [
"python"
] |
KeyError issue with dictionaries | 38,030,383 | <p>Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop... | 0 | 2016-06-25T16:10:31Z | 38,030,825 | <p>Your issue is that you haven't included quotation marks around the key <code>"model"</code>. This means that it wouldn't locate it anyway.</p>
<p>Also, why don't you just keep it to one loop? It'd be far more efficient.</p>
| 0 | 2016-06-25T16:59:28Z | [
"python",
"dictionary",
"while-loop",
"keyerror"
] |
KeyError issue with dictionaries | 38,030,383 | <p>Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop... | 0 | 2016-06-25T16:10:31Z | 38,030,828 | <p>You have both</p>
<pre><code>dtablet[model] # the key is the model variable
</code></pre>
<p>and</p>
<pre><code>dtablet["model"] # the key is the "model" string
</code></pre>
<p>in your code, is this intentional?</p>
<p>If a user presses 'enter' then <code>model</code> will be an empty string, and this expres... | 0 | 2016-06-25T16:59:42Z | [
"python",
"dictionary",
"while-loop",
"keyerror"
] |
KeyError issue with dictionaries | 38,030,383 | <p>Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop... | 0 | 2016-06-25T16:10:31Z | 38,031,078 | <p>First, you don't have a "model" key in your dictionary. You can print out <code>dtablet.keys()</code> and find if there is "model" in there. If not, then dtablet["model"] will 100% returns a KeyError.</p>
<p>Second, when you type <code>while model != (dtablet["model"]):</code>, since <code>model</code> is an empty ... | 0 | 2016-06-25T17:25:19Z | [
"python",
"dictionary",
"while-loop",
"keyerror"
] |
KeyError issue with dictionaries | 38,030,383 | <p>Im using a dictionary in my code and comparing the user's input to it, but when the user input nothing and just hits enter the program falls over and gives me a key error. I tried to use 'Try and Except' but that way the the program loops to the beginning which i dont want, i want to keep the program in the sub loop... | 0 | 2016-06-25T16:10:31Z | 38,031,499 | <p>You do realise that the <code>while</code> loop has both a <code>break</code> option and a <code>continue</code> option?<br>
If you "want to keep the program in the sub loop until the user inputs something that is within the boundary" test and <code>continue</code> if the input was not what you were looking for.</p>... | 0 | 2016-06-25T18:12:31Z | [
"python",
"dictionary",
"while-loop",
"keyerror"
] |
Logictic Regression can't fit my data | 38,030,408 | <p>I'm trying fit my data , but I couldn't fit it.Data set</p>
<pre><code>0.50,0
0.75,0
1.00,0
1.25,0
1.50,0
1.75,0
1.75,1
2.00,0
2.25,1
2.50,0
2.75,1
3.00,0
3.25,1
3.50,0
4.00,1
4.25,1
4.50,1
4.75,1
5.00,1
5.50,1
</code></pre>
<p>and my code </p>
<pre><code>data = np.loadtxt('dat', delimiter=',',dtype=None);
x=dat... | 1 | 2016-06-25T16:12:49Z | 38,059,019 | <p>Your algorithm overall looks correct, there seems to be a small issue with the <code>numpy</code> implementation, when you calculated <code>(h - y)*a</code>, you did</p>
<pre><code> q[j][0] = q[j][0] - alpha * np.sum((h - y) * a[:,j])
</code></pre>
<p>But because you are using <code>numpy.ndarray</code> types n... | 0 | 2016-06-27T16:34:36Z | [
"python",
"machine-learning",
"logistic-regression"
] |
How to run a script in python on multiple time series? | 38,030,510 | <p>I am trying to run the following script using <a href="http://statsmodels.sourceforge.net/devel/" rel="nofollow">the StatsModels library</a>:</p>
<pre><code>cadf = ts.adfuller(df1.spread)
print 'Augmented Dickey Fuller test statistic =',cadf[0]
print 'Augmented Dickey Fuller p-value =',cadf[1]
print 'Augmented Dick... | 1 | 2016-06-25T16:24:28Z | 38,030,983 | <p>To access columns individually, instead of the entire data frame, basically:</p>
<pre><code>df1['A-B']
</code></pre>
<p>will get you the first column. Round them up in a list:</p>
<pre><code>columns = ['A-B', 'B-C', 'A-C']
</code></pre>
<p>If you have 200+ columns you should access them differently. Let's say yo... | 0 | 2016-06-25T17:16:31Z | [
"python",
"dataframe",
"time-series",
"statsmodels"
] |
Basic softmax model implementation on 150x150 images | 38,030,552 | <p>I'n my learning of tensorflow I've tried to adapt the basic softmax MNIST example to work on my own image set. It's aerial photographs of buildings and I want to classify them by roof type. There are 4 such classifications that can be made.</p>
<p>The simple (maybe naive) idea was to resize the images (since they'r... | 0 | 2016-06-25T16:30:05Z | 38,043,335 | <p>Your dataset might be unbalanced, which will make the network harder to train as it will tend to predict the most probable class.</p>
<p>I think your one-layer model is just <strong>not powerful enough</strong> to train on a whole dataset. You should maybe add more layers and use convolutions along with max pooling... | 1 | 2016-06-26T21:25:34Z | [
"python",
"machine-learning",
"tensorflow"
] |
extracting a tuple from a dictionary with a key/tuple pair | 38,030,611 | <p>I know I'm close:</p>
<pre><code> for k in my_dictionary:
#print (k, my_dict[k][0],my_dict[k][1])
for v in my_dict[k]:
print (v,my_dict[k])
</code></pre>
<p>results in:</p>
<pre><code>tuple00('tuple00','tuple01')
tuple01('tuple00','tuple01')
tuple10('tuple10','tuple11')
tuple11('tup... | 1 | 2016-06-25T16:36:47Z | 38,030,662 | <p>You can do this :</p>
<pre><code> for key, value in dictd.iteritems():
print key, value[0], value[1]
</code></pre>
| 0 | 2016-06-25T16:42:19Z | [
"python",
"python-3.x",
"tuples",
"list-comprehension",
"dictionary-comprehension"
] |
extracting a tuple from a dictionary with a key/tuple pair | 38,030,611 | <p>I know I'm close:</p>
<pre><code> for k in my_dictionary:
#print (k, my_dict[k][0],my_dict[k][1])
for v in my_dict[k]:
print (v,my_dict[k])
</code></pre>
<p>results in:</p>
<pre><code>tuple00('tuple00','tuple01')
tuple01('tuple00','tuple01')
tuple10('tuple10','tuple11')
tuple11('tup... | 1 | 2016-06-25T16:36:47Z | 38,030,707 | <p>You can unpack using <code>.items</code>:</p>
<pre><code> d = {"key":("v1","v2")}
for k, (v1, v2) in d.items():
print(k, v1, v2)
</code></pre>
<p>Which would print:</p>
<pre><code>('key', 'v1', 'v2')
</code></pre>
<p>Using <code>(v1, v2)</code> unpacks each <code>tuple/value</code>.</p>
| 4 | 2016-06-25T16:46:52Z | [
"python",
"python-3.x",
"tuples",
"list-comprehension",
"dictionary-comprehension"
] |
extracting a tuple from a dictionary with a key/tuple pair | 38,030,611 | <p>I know I'm close:</p>
<pre><code> for k in my_dictionary:
#print (k, my_dict[k][0],my_dict[k][1])
for v in my_dict[k]:
print (v,my_dict[k])
</code></pre>
<p>results in:</p>
<pre><code>tuple00('tuple00','tuple01')
tuple01('tuple00','tuple01')
tuple10('tuple10','tuple11')
tuple11('tup... | 1 | 2016-06-25T16:36:47Z | 38,031,458 | <p>You can do it this way:</p>
<pre><code>d = {"key":("v1","v2")}
for key in d:
print((key,) + d[key])
</code></pre>
<p>Unpacks to:</p>
<pre><code>('key', 'v1', 'v2')
</code></pre>
| 0 | 2016-06-25T18:06:56Z | [
"python",
"python-3.x",
"tuples",
"list-comprehension",
"dictionary-comprehension"
] |
conda change python version between 2 and 3 | 38,030,649 | <p>I'm learning using <code>conda</code> to control environment of python in windows 10 powershell, following <a href="http://conda.pydata.org/docs/test-drive.html" rel="nofollow">this doc</a>.</p>
<p>It says the current environment should be shown parentheses or brackets</p>
<blockquote>
<p>Which of these environm... | 0 | 2016-06-25T16:40:40Z | 38,031,581 | <p>Full support for <code>activate</code>/<code>deactivate</code> in Windows PowerShell has not currently been implemented. There is an open Pull Request at <a href="https://github.com/conda/conda/pull/2366" rel="nofollow">https://github.com/conda/conda/pull/2366</a> that you may be interested in tracking.</p>
| 0 | 2016-06-25T18:18:46Z | [
"python",
"environment",
"conda"
] |
Python-fu script not showing in Gimp menu | 38,030,656 | <p>Iâve been at <a href="http://stackoverflow.com/questions/17334993/gimp-python-script-not-showing-in-menu">Gimp: python script not showing in menu</a> and it didnât help me. Hereâs what I tried, step by step:</p>
<p><strong>1.</strong> Iâm running Gimp 2.8.16 on Mac OS X 10.9.5 from the command line with <co... | 0 | 2016-06-25T16:41:41Z | 38,038,006 | <p>Python "scripts" are technically "plug-ins" and should therefore be in the "plug-ins" subdirectory (/Users/julio/Library/Application Support/GIMP/2.8/plug-ins).</p>
| 1 | 2016-06-26T11:22:53Z | [
"python",
"gimp",
"gimpfu",
"python-fu"
] |
How is a dictionary in Python not indexed? | 38,030,688 | <p>I was under the impression that dictionaries are not indexed. But when using <code>zip()</code> on two dictionaries it returns result that points otherwise.
For example:</p>
<pre><code>d1={'a'=1,'b'=2}
d2={'c'=1,'d'=2}
</code></pre>
<p><code>zip(d1,d2)</code> in Python 2 will always return </p>
<pre><code>[('a', ... | 0 | 2016-06-25T16:44:42Z | 38,030,758 | <p>Dictionaries are implemented using <em>hashtables</em>. All such data structures do not provide any guarantee on the <strong>order</strong> of the keys. For example:</p>
<pre><code>>>> import string
>>> d1 = {}
>>> for letter in string.ascii_lowercase:
... d1[letter] = 1
...
>>... | 3 | 2016-06-25T16:52:30Z | [
"python",
"dictionary"
] |
NLTK - Download all nltk data except corpara from command line without Downloader UI | 38,030,703 | <p>We can download all nltk data using:</p>
<pre><code>> import nltk
> nltk.download('all')
</code></pre>
<p>Or specific data using:</p>
<pre><code>> nltk.download('punkt')
> nltk.download('maxent_treebank_pos_tagger')
</code></pre>
<p>But I want to download all data except 'corpara' files,
for example... | 2 | 2016-06-25T16:46:28Z | 38,677,944 | <p>List all corpora ids and set <code>_status_cache[pkg.id] = 'installed'</code>.</p>
<p>It will set status value for all corpora as <strong>'installed'</strong> and all corpora packages will be skipped when we use <strong>download('all')</strong>.</p>
<pre><code>import nltk
dwlr = nltk.downloader.Downloader()
for ... | 0 | 2016-07-30T19:55:27Z | [
"python",
"nlp",
"nltk",
"corpus",
"nltk-trainer"
] |
Fetch the data from rows with limit | 38,030,722 | <p>I'm fetching the list of full data from a sqlite3 database. I want to pull 20 rows of data for each channel, but on my code it will fetch all of data for each channel.</p>
<p>Here is the code:</p>
<pre><code>#get the programs list
profilePath = xbmc.translatePath(os.path.join('special://userdata/addon_data/script.... | 1 | 2016-06-25T16:48:22Z | 38,031,191 | <ol>
<li><p>Please use <code>limit 20</code> in your select query.</p>
<pre><code>cur.execute('SELECT channel, title, start_date, stop_date FROM programs where channel=? limit 20', [channel])
</code></pre></li>
<li><p>We can also make it with python sqlite</p>
<pre><code>#get the programs list
profilePath = xbmc.tran... | 1 | 2016-06-25T17:37:25Z | [
"python",
"python-2.7",
"sqlite3"
] |
Open link on scatter plot in Bokeh Python but do not immediately follow link | 38,030,841 | <p>I am using the Bokeh module with Python and the following example:</p>
<pre><code>from bokeh.models import ColumnDataSource, OpenURL, TapTool
from bokeh.plotting import figure, output_file, show
output_file("openurl.html")
p = figure(plot_width=400, plot_height=400,
tools="tap", title="Click the Dots")... | 0 | 2016-06-25T17:00:53Z | 38,034,130 | <p>As of Bokeh <code>0.12</code> there is no configuration option for that. You could definitely make a custom extension to do that, or alternatively if you'd like to see it in the core library it would make an excellent small PR for a new contributor to tackle (and I'd be happy to help get you started). In any event I... | 1 | 2016-06-26T00:22:04Z | [
"python",
"plot",
"bokeh"
] |
strange random seed behavior in Python3 | 38,030,915 | <p>Outputting a <strong>set</strong> of numbers does not give the same sequence even after using <code>random.seed(myseed)</code>. This only occurs in Python3, not in Python2 (both on a Debian stable system). Is it a bug or something wrong with my code ? </p>
<pre><code>import random
seed=20.0
random.seed(seed)
print... | 0 | 2016-06-25T17:08:59Z | 38,030,985 | <p>You are actually incorrect. Python 3 is returning the same set of numbers. You are making an assumption that <code>set</code> an unordered container will have the same order each time you execute python which is incorrect. </p>
<p>For example, for the last two python3 tests:</p>
<pre><code>>>> a = set([70... | 3 | 2016-06-25T17:16:33Z | [
"python",
"debugging",
"random",
"set"
] |
ATOM - Pylama Path | 38,030,916 | <p>I have installed Linter Python packages in ATOM Tool.
This image pops up everytime i try to save my codes.</p>
<p><a href="http://i.stack.imgur.com/8XLrr.png" rel="nofollow"><img src="http://i.stack.imgur.com/8XLrr.png" alt="enter image description here"></a></p>
<p>However I'm able to compile my *.py files. I'm ... | 0 | 2016-06-25T17:09:01Z | 39,397,010 | <p>For me, reinstalling linter-python didn't help, but going into Preferences > Packages > Linter Python and explicitly providing the path to pylama (I confirmed it with <code>which pylama</code> - for me it is in <code>/usr/local/bin/pylama</code> ). The default path is only <code>pylama</code> which may or may not be... | 0 | 2016-09-08T17:31:28Z | [
"python",
"atom-editor"
] |
Anaconda cannot find win-64 endpoint | 38,030,935 | <p>I'm trying to get Anaconda to install packages after installation on my Windows 10 computer, but it's not working. It's erroring out with this:</p>
<pre><code>Fetching package metadata:
Using Anaconda Cloud api site https://api.anaconda.org
Error: Could not find URL: https://pypi.python.org/pypi/win-64/
</code></p... | 0 | 2016-06-25T17:11:28Z | 38,030,971 | <p>So...after Googling, I found a random <a href="https://groups.google.com/a/continuum.io/forum/#!topic/conda/a4sK6kZdleo" rel="nofollow">forum about linux-64</a> issues, and that solved my problem on Windows because apparently Anaconda can't use PyPi for x,y,z reasons. I removed the PyPi link from my <code>.condarc</... | 0 | 2016-06-25T17:15:23Z | [
"python",
"windows",
"anaconda"
] |
Implementing an asynchronous iterator | 38,031,066 | <p>Per <a href="https://www.python.org/dev/peps/pep-0492/#asynchronous-iterators-and-async-for">PEP-492</a> I am trying to implement an asynchronous iterator, such that I can do e.g. </p>
<pre><code>async for foo in bar:
...
</code></pre>
<p>Here is a trivial example, similar to the one in the docs, with a very b... | 11 | 2016-06-25T17:24:14Z | 38,031,740 | <p>If you read <a href="https://www.python.org/dev/peps/pep-0492/#why-aiter-does-not-return-an-awaitable">a little further down the documentation</a> it mentions that (emphasis mine):</p>
<blockquote>
<p>PEP 492 was accepted in CPython 3.5.0 with <code>__aiter__</code> defined as a
method, that was expected to ret... | 14 | 2016-06-25T18:36:26Z | [
"python",
"python-3.x",
"asynchronous",
"python-asyncio"
] |
Fixed seed random number between 0 and 1 | 38,031,129 | <p>I want to generate list of fixed random numbers by giving a seed between 0 and 1 in python. For example, l = [0.1, 0.5, 0.6, 0.9, 0.75]. I can get this by using random.random(). But every time it gives a new random number list. I want to fix it by giving some some seed. </p>
<p>How can I do that. Thanks in advance!... | 0 | 2016-06-25T17:30:03Z | 38,031,201 | <p>Check out pydocs page for <a href="https://docs.python.org/2/library/random.html#random.seed" rel="nofollow">random.seed()</a></p>
<pre><code>[>>> seed = 123
[>>> random.seed(seed)
[>>> i = [random.random() for _ in xrange(5)]
[>>> print i
[0.052363598850944326, 0.087186677522632... | 2 | 2016-06-25T17:38:46Z | [
"python",
"python-3.x",
"random"
] |
Fixed seed random number between 0 and 1 | 38,031,129 | <p>I want to generate list of fixed random numbers by giving a seed between 0 and 1 in python. For example, l = [0.1, 0.5, 0.6, 0.9, 0.75]. I can get this by using random.random(). But every time it gives a new random number list. I want to fix it by giving some some seed. </p>
<p>How can I do that. Thanks in advance!... | 0 | 2016-06-25T17:30:03Z | 38,031,237 | <p>you can do it like this:</p>
<pre><code>import random
l = []
n = 10 # you can change it to whatever you want, it is list length
for i in range(n):
random.seed(i)
l += [random.random()]
print(l)
</code></pre>
<p>it will always give same random list.</p>
| 0 | 2016-06-25T17:41:27Z | [
"python",
"python-3.x",
"random"
] |
Accessing a url in a Flask view | 38,031,132 | <p>I am trying to access an external url <a href="https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=184&format=json" rel="nofollow">https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid=184&format=json</a> in a Flask view</p>
<p>I get the error,</p>
<blockquote>
<p>Not Foun... | 0 | 2016-06-25T17:30:17Z | 38,031,416 | <p>If we assume that the HTML file is not being served by <code>flask</code>:</p>
<p>You need to enable Cross origin resource sharing. You can do this by creating a response and setting it's header <code>Access-Control-Allow-Origin</code> to <code>*</code>: that is everyone. Or you can set it to your own domain when d... | 1 | 2016-06-25T18:01:57Z | [
"python",
"api",
"flask"
] |
Tensorflow: How to give variables scope | 38,031,154 | <p>I have to first pretrain a network before training it. I do this using code in separate files with their own sessions, but the variables from the first session are still getting carried over and causing problems (as I'm running both these files within one 'main' file).</p>
<p>I could get around this problem by simp... | 1 | 2016-06-25T17:32:36Z | 38,032,072 | <p>From what I gather, pretrain_nn is initializing variables on TF (which is shared between pretrain_nn and Network). According to <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/state_ops.html#variable_scope" rel="nofollow"><code>tf.variable_scope()</code> from the documentation</a>:</p>
<blockquote... | 0 | 2016-06-25T19:12:58Z | [
"python",
"tensorflow"
] |
Tensorflow: How to give variables scope | 38,031,154 | <p>I have to first pretrain a network before training it. I do this using code in separate files with their own sessions, but the variables from the first session are still getting carried over and causing problems (as I'm running both these files within one 'main' file).</p>
<p>I could get around this problem by simp... | 1 | 2016-06-25T17:32:36Z | 38,032,088 | <p>The variables' lifetime is implicitly tied to the TensorFlow graph, and by default both of your computations will be added to the same (global) graph. You can scope them appropriately using <code>with tf.Graph().as_default():</code> blocks around each of the subcomputations:</p>
<pre><code>with tf.Graph().as_defaul... | 1 | 2016-06-25T19:14:48Z | [
"python",
"tensorflow"
] |
Python mathplotlib - overlapping texts in xticks and adding percentage symbol in yticks | 38,031,232 | <p>The following is my Python code for generating a bar chart:</p>
<pre><code>import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
objects = ('Increasing operational efficiency',
'Informing strategic direction',
'Better customer service',
'Identifyi... | 0 | 2016-06-25T17:41:04Z | 38,032,449 | <p>you would have found answers to your questions with a simple search...</p>
<p>you can rotate the x-axis labels using <code>plt.gcf().autofmt_xdate()</code></p>
<p>for the percent signs on the y-axis, use </p>
<pre><code>ax = plt.gca()
vals = ax.get_yticks()
ax.set_yticklabels(['{:.0f}%'.format(x) for x in vals])
... | 1 | 2016-06-25T20:01:41Z | [
"python",
"matplotlib",
"bar-chart"
] |
Python Saving long string in text file | 38,031,290 | <p>I have a long string that I want to save in a text file with the code: </p>
<p><code>taxtfile.write(a)</code> </p>
<p>but because the string is too long, the saved file prints as:</p>
<pre><code>"something something ..... something something"
</code></pre>
<p>how do I make sure it will save the e... | 0 | 2016-06-25T17:48:14Z | 38,031,466 | <p>I think this is just a representation in your IDE or terminal environment. Try something like the following, then open the file and see for yourself if its writing in its entirety:</p>
<pre><code>x = 'abcd'*10000
with open('test.txt', 'w+') as fh:
fh.write(x)
</code></pre>
<p>Note the the above will write a f... | 0 | 2016-06-25T18:08:16Z | [
"python",
"string",
"save"
] |
Python Saving long string in text file | 38,031,290 | <p>I have a long string that I want to save in a text file with the code: </p>
<p><code>taxtfile.write(a)</code> </p>
<p>but because the string is too long, the saved file prints as:</p>
<pre><code>"something something ..... something something"
</code></pre>
<p>how do I make sure it will save the e... | 0 | 2016-06-25T17:48:14Z | 38,031,477 | <p>it should work regardless of the string length</p>
<p>this is the code I made to show it:</p>
<pre><code>import random
a = ''
number_of_characters = 1000000
for i in range(number_of_characters):
a += chr(random.randint(97, 122))
print(len(a)) # a is now 1000000 characters long string
textfile = open('t... | 1 | 2016-06-25T18:09:49Z | [
"python",
"string",
"save"
] |
Recursive file renaming in python | 38,031,461 | <p>I'm trying to write some code to recursively renaming files in python. I've got a root folder which has another folder inside it, and yet another folder inside that folder. Each of this folders has a file named "Name.txt" and I would like to change them to "Test.txt", in order to understand how os.walk() and os.rena... | 0 | 2016-06-25T18:07:33Z | 38,031,536 | <p><code>os.rename</code> can be destructive. Use it carefully. </p>
<p>You had <code>rootstructure</code> initialised to os.walk for somereason. You need to initialize it to the path of the current directory.</p>
<pre><code>import os
def renamefiles(path):
rootstructure=os.path.abspath(path)
for root,dirs,... | 0 | 2016-06-25T18:15:43Z | [
"python",
"recursion"
] |
Recursive file renaming in python | 38,031,461 | <p>I'm trying to write some code to recursively renaming files in python. I've got a root folder which has another folder inside it, and yet another folder inside that folder. Each of this folders has a file named "Name.txt" and I would like to change them to "Test.txt", in order to understand how os.walk() and os.rena... | 0 | 2016-06-25T18:07:33Z | 38,031,548 | <p>You need to pass a string representing a path to <code>os.walk</code>. Currently, you are passing <code>rootstructure</code>, which is a generator object.</p>
<pre><code>def renamefiles(path):
for root,dirs,files in os.walk(path):
for filenames in files:
fullfilename=os.path.abspath(filenam... | 0 | 2016-06-25T18:16:40Z | [
"python",
"recursion"
] |
XPath returning empty list (namespace issue?) | 38,031,504 | <p>I expect the following code to return the text "In Stock" or "Out of Stock" (to check stock at an online store) but it returns only "[]". The XPath code was obtained from a browser's element inspector, and seems to be valid. I read online about namespaces possibly being the problem. Tips?</p>
<pre><code>from lxml i... | 1 | 2016-06-25T18:12:49Z | 38,031,594 | <p>You xpath is wrong:</p>
<pre><code> from lxml import html
import requests
url = 'http://www.thesource.ca/en-ca/computers-and-tablets/computer-accessories/mice/logitech-m310-wireless-mouse/p/2618659'
path = '//ul[@class="availability"]/li[./div[@class="availability-text in-stock"]]'
page = requests.get(url)
tree =... | 1 | 2016-06-25T18:20:19Z | [
"python",
"xpath",
"namespaces"
] |
Data exploration JSON nested data in pandas | 38,031,657 | <p>How can I get my JSON data into a reasonable data frame? I have a deeply nested file which I aim to get into a large data frame. All is <a href="https://github.com/simongraham/dataExplore/blob/master/kaido_data.ipynb" rel="nofollow">described</a> in the Github repository below:</p>
<p><a href="http://www.github.com... | 0 | 2016-06-25T18:26:12Z | 38,034,962 | <p>With nested jsons, you will need to walk through the levels, extracting needed segments. For the nutrition segment of the larger json, consider iterating through every <code>nutritionPortions</code> level and each time running the pandas normalization and concatenating to final dataframe:</p>
<pre><code>import pand... | 1 | 2016-06-26T03:29:16Z | [
"python",
"json",
"pandas",
"dataframe"
] |
Django - How do i include several elements in pagination | 38,031,692 | <p>This is my first project in django and I've been following several different tutorial, most of which are very useful. I've made a very simple blog as my first app and now I'm expanding it a bit beyond what the tutorials have shown me. Namely, I added new model, Category, which every post can belong to. The model its... | 1 | 2016-06-25T18:30:34Z | 38,031,782 | <p><strong>views.py</strong></p>
<pre><code>...
queryset_list = Post.objects.all().order_by("-published")
if request.GET.get('cat'):
queryset_list = queryset_list.filter(category__slug=request.GET.get('cat'))
...
</code></pre>
<p><strong>urls.py</strong></p>
<pre><code>from .views import (
post_list,
pos... | 1 | 2016-06-25T18:40:28Z | [
"python",
"django",
"pagination"
] |
HTTP Error 429: Too Many Requests by python geopy | 38,031,705 | <p>I have a problem that I am not sure how to solve. I want to iterate through a file where I want to convert the coordinates to the geolocation address.The code works fine but after it iteretes through a certain number of lines in the file the problem occurs. </p>
<pre><code>from __future__ import print_function
from... | 0 | 2016-06-25T18:31:59Z | 38,031,720 | <p>Looks like whatever webservice you are using has blocked you, most likely via your IP address. Wait for a while and then make sure that you are being "friendly" to the service, e.g., by inserting those sleeps.</p>
| 1 | 2016-06-25T18:33:50Z | [
"python",
"python-requests",
"geopy"
] |
How to create AWS Lambda deployment package that uses Couchbase Python client | 38,031,729 | <p>I'm trying to use AWS Lambda to transfer data from my S3 bucket to Couchbase server, and I'm writing in Python. So I need to import couchbase module in my Python script. Usually if there are external modules used in the script, I need to pip install those modules locally and zip the modules and script together, then... | 2 | 2016-06-25T18:34:58Z | 38,065,441 | <p>Unfortunately AWS Lambda does not support executing C-based python modules, like the Couchbase SDK. </p>
<p>Your best bet would be to use a pure-python client. The easiest way to do this would be to use the unofficial memcached client <a href="https://github.com/couchbase/couchbase-cli/blob/master/cb_bin_client.py"... | 1 | 2016-06-28T00:56:28Z | [
"python",
"couchbase",
"aws-lambda"
] |
Exception Type: OperationalError - Exception Value: no such column: blog_article.slug | 38,031,772 | <p>I am making a blog using django. I created an app named blog, and in <em>models.py</em> I created the following model, for articles on this blog :</p>
<pre><code>class Article(models.Model):
title = models.CharField(max_length = 100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
auth... | 0 | 2016-06-25T18:39:30Z | 38,035,734 | <p>Can you try the following?</p>
<p>Check your migrations folder. Let's say you've added Article under <code>my_project/blog/migrations/0020_...</code> Then can you try to run:</p>
<p><code>./manage.py migrate blog 0019</code>
=> that should get you an error (blog_article table doesn't exists - cannot be removed)</p... | 0 | 2016-06-26T06:12:57Z | [
"python",
"django",
"database-migration",
"slug"
] |
Calling python script from C# doesn't work, without throwing error | 38,031,777 | <p>I am writing a C# program to execute a python script with some arguments. The program is not executed(it is supposed to not only print out a message, but also to write to a file), even though there is no error and the Process ExitCode is 0(checked via the debugger). Where am I going wrong?</p>
<pre><code> static... | 1 | 2016-06-25T18:39:50Z | 38,031,886 | <p>You've put <code>myProcess.WaitForExit();</code> in the wrong place; <em>wait</em> till Python has executed the script:</p>
<pre><code>...
myProcess.Start();
StreamReader myStreamReader = myProcess.StandardOutput;
// first, wait to complete
myProcess.WaitForExit();
// only then read the results (stdout)
string m... | 1 | 2016-06-25T18:52:32Z | [
"c#",
"python"
] |
Calling python script from C# doesn't work, without throwing error | 38,031,777 | <p>I am writing a C# program to execute a python script with some arguments. The program is not executed(it is supposed to not only print out a message, but also to write to a file), even though there is no error and the Process ExitCode is 0(checked via the debugger). Where am I going wrong?</p>
<pre><code> static... | 1 | 2016-06-25T18:39:50Z | 38,031,915 | <p>Works perfectly fine with me. I think there's something with your user_name containing spaces.</p>
| 0 | 2016-06-25T18:56:31Z | [
"c#",
"python"
] |
Appropriately altering __setattr__ method for mapped objects | 38,031,779 | <p>So, I have a web application where there's a certain database object with attributes I would like to cache in a <code>redis</code> store. Relatively simple to do manually, with something like below:</p>
<pre><code>db_object.update({<attribute>: <value>})
redis.set(db_object.id, <value>)
</code></p... | 1 | 2016-06-25T18:40:06Z | 38,031,885 | <p>Found a nice way to approach this on another question. Can just call the super method instead of directly altering <code>__dict__</code></p>
<p>Method below has the desired effect:</p>
<pre><code>def __setattr__(self, name, value):
if name == <attribute>:
redis.set(self.id, value)
super(Datas... | 0 | 2016-06-25T18:52:31Z | [
"python",
"orm",
"sqlalchemy",
"flask-sqlalchemy",
"magic-methods"
] |
Python, Flask -- count page visit and write in database | 38,031,906 | <p>There is a small hello world Flask with visit statistics. I managed to count visits with redis, but I also have to add support storing date and number of visits in MySQL database. The current code is:
I was trying to access previously created database.
Currently I have no idea how to store such info in MySQL.</p>
<... | 0 | 2016-06-25T18:55:41Z | 38,065,653 | <p>Check out Flask-SQLAlchemy:
<a href="http://flask-sqlalchemy.pocoo.org/2.1/quickstart/#a-minimal-application" rel="nofollow">http://flask-sqlalchemy.pocoo.org/2.1/quickstart/#a-minimal-application</a></p>
<p>You will need to create the database with</p>
<pre><code>from yourapplication import db
db.create_all()
</... | 0 | 2016-06-28T01:24:59Z | [
"python",
"mysql",
"flask"
] |
Order of decorator for abstract method | 38,031,932 | <p>I have a base class which I have made abstract. </p>
<pre><code>class X(metaclass=ABCMeta):
@abstractmethod
@tornado.gen.coroutine
def cc(self):
# do stuff
</code></pre>
<p>What should the order of the decorators go in? And does it matter?</p>
| 1 | 2016-06-25T18:57:58Z | 38,031,982 | <p>The order of stacked function decorators usually does matter for correct interpretation (based on the flow of your program), and in this case it is stated explicitly in <a href="https://docs.python.org/3/library/abc.html#abc.abstractmethod" rel="nofollow">the docs</a>:</p>
<blockquote>
<p>When <code>abstractmetho... | 2 | 2016-06-25T19:02:52Z | [
"python",
"tornado"
] |
Aligning Kivy objects using pure Python | 38,031,951 | <p>I can't seem to figure out alignment using pure Python code. My understanding is that we reference <code>root</code> to get relational alignment. However, I haven't been able to get it to work. This code compiles, runs, and then places the button in the bottom left corner. At the 0,0 coords. What am I missing here?<... | 0 | 2016-06-25T19:00:00Z | 38,032,066 | <p>it (your floatlayout) does not know the window size ... so it uses the default size of (100,100) ... so it centers the button there</p>
<p>try telling your float layout its size</p>
<pre><code>cView = ContainerView(size=(500,350))
</code></pre>
| 0 | 2016-06-25T19:11:57Z | [
"python",
"kivy"
] |
Can I sign an X509 certificate entirely in Python? | 38,032,045 | <p>I'm working within the Google App Engine (GAE) python 2.7 runtime.</p>
<p>I need sign (and potentially also generate) an X509 certificate (.csr)</p>
<p>I found several <a href="http://www.programcreek.com/python/example/64072/OpenSSL.crypto.X509">guides</a>, that rely on <a href="https://cloud.google.com/appengine... | 5 | 2016-06-25T19:09:38Z | 38,032,217 | <p>I may have found a solution:</p>
<p><a href="https://cryptography.io/en/latest/x509/tutorial/#creating-a-self-signed-certificate" rel="nofollow">Cryptography.io</a> is entirely python based and even offers a tutorial on how to self sign a cert. </p>
<p>Happy to hear other answers.</p>
| 2 | 2016-06-25T19:30:21Z | [
"python",
"python-2.7",
"google-app-engine",
"ssl",
"x509"
] |
Can I sign an X509 certificate entirely in Python? | 38,032,045 | <p>I'm working within the Google App Engine (GAE) python 2.7 runtime.</p>
<p>I need sign (and potentially also generate) an X509 certificate (.csr)</p>
<p>I found several <a href="http://www.programcreek.com/python/example/64072/OpenSSL.crypto.X509">guides</a>, that rely on <a href="https://cloud.google.com/appengine... | 5 | 2016-06-25T19:09:38Z | 38,087,634 | <p>That will not be the direct answer, because I never use C and Cython, but maybe it is possible to use some C library for this task. </p>
<p>From <a href="http://cython.org/" rel="nofollow">Cython site</a>:</p>
<blockquote>
<p>All of this makes Cython the ideal language for wrapping external C
libraries, embedd... | 1 | 2016-06-28T23:01:42Z | [
"python",
"python-2.7",
"google-app-engine",
"ssl",
"x509"
] |
Can I sign an X509 certificate entirely in Python? | 38,032,045 | <p>I'm working within the Google App Engine (GAE) python 2.7 runtime.</p>
<p>I need sign (and potentially also generate) an X509 certificate (.csr)</p>
<p>I found several <a href="http://www.programcreek.com/python/example/64072/OpenSSL.crypto.X509">guides</a>, that rely on <a href="https://cloud.google.com/appengine... | 5 | 2016-06-25T19:09:38Z | 38,202,966 | <blockquote>
<p>Can I sign an X509 certificate entirely in Python?</p>
</blockquote>
<p>Almost certainly, but I don't think there are any existing pure Python implementations available. The closest I could find is <a href="https://github.com/wbond/oscrypto" rel="nofollow"><code>oscrypto</code></a>, but being able to... | 2 | 2016-07-05T12:02:10Z | [
"python",
"python-2.7",
"google-app-engine",
"ssl",
"x509"
] |
No window output while importing pandas and tkinter at the same time | 38,032,140 | <p>I've got this problem that I couldn't find any reason:No window output while importing pandas and tkinter at the same time. This is my code:</p>
<pre><code> from Tkinter import*
import pandas
App=Tk()
source=Entry(App).pack()
sortie=Entry(App).pack()
Button(App, text='Traiter').pack() # a com... | 0 | 2016-06-25T19:19:41Z | 38,034,263 | <pre><code>from Tkinter import*
import pandas
App=Tk()
App.geometry("500x500")
source=Entry(App).pack()
sortie=Entry(App).pack()
Button(App, text='Traiter').pack() # a command will be insert here
App.mainloop()
</code></pre>
<p>When I add the geometry to give window size it works fine. try that</p>
| 0 | 2016-06-26T00:46:51Z | [
"python",
"pandas",
"tkinter"
] |
Programming Sudoku in python | 38,032,267 | <pre><code>import turtle
strelica = turtle.getturtle()
turtle.setup(800, 600)
prozor = turtle.Screen()
prozor.title("SUDOKU")
strelica.speed(0)
def kvadrat(a): # a je duzina stranice
strelica.pendown()
strelica.forward(a)
strelica.left(90)
strelica.forward(a)
strelica.left(90)
strelica.for... | -1 | 2016-06-25T19:37:48Z | 38,041,119 | <p>To fix your problem you need to add variable which will tell you if number was found in column so there is no need to check is number in row or in box.</p>
<p>So to fix that your code should look like this:</p>
<pre><code>import turtle
strelica = turtle.getturtle()
turtle.setup(800, 600)
prozor = turtle.Screen()
... | 0 | 2016-06-26T17:18:06Z | [
"python",
"sudoku"
] |
urllib.urlopen not returning response body | 38,032,288 | <p>I'm trying to download JSON from a url as a string and parse it. This is the code I'm using:</p>
<pre><code>json_data = urllib.urlopen('http://jsonplaceholder.typicode.com/posts').read()
parsed_data = json.loads(json_data)
</code></pre>
<p>It current outputs <code><Response 27943 bytes [200 OK]></code>. Ok s... | 0 | 2016-06-25T19:40:06Z | 38,032,417 | <p>Not sure where you're seeing <code><Response 27943 bytes [200 OK]></code>. When I execute that, <code>parsed_data</code> is a list containing 100 elements. Each of these is a dictionary with the keys <code>'body', 'userId', 'id', 'title'</code>.</p>
<pre><code>>>> type(parsed_data)
<type 'list'>... | 0 | 2016-06-25T19:57:34Z | [
"python",
"python-2.7",
"urllib"
] |
Reference of copied object is changed when using copied object to assign to global variable | 38,032,321 | <p>I have a global variable that contains a numpy array for an image, in my function I first create a copy of that image using copy.copy(img) and then in the infinite loop I try to reassign the copied image to the global variable whenever a certain key is pressed, this is kind of the structure of the relevant code:</p>... | 0 | 2016-06-25T19:44:40Z | 38,032,706 | <p>It is true that you end up with the same id for both names, but the reason is that you have assigned <code>img_copy</code> to image, not the other way around. Once you make this assignment, you have two names for the same (new copy!) object. Here's a way to see this.</p>
<pre><code>img = np.arange(12).reshape((3,... | 1 | 2016-06-25T20:29:39Z | [
"python",
"numpy"
] |
Reference of copied object is changed when using copied object to assign to global variable | 38,032,321 | <p>I have a global variable that contains a numpy array for an image, in my function I first create a copy of that image using copy.copy(img) and then in the infinite loop I try to reassign the copied image to the global variable whenever a certain key is pressed, this is kind of the structure of the relevant code:</p>... | 0 | 2016-06-25T19:44:40Z | 38,032,913 | <p>To copy the values in <code>img_copy</code> into the array <code>img</code>:</p>
<pre><code>img[...] = img_copy
</code></pre>
<p>(The ellipsis is literal, not something that I left for you to fill in.)</p>
<hr>
<p><em>"Now when I press space once, img takes the values of img_copy, but as a side effect img_copy i... | 2 | 2016-06-25T20:57:55Z | [
"python",
"numpy"
] |
Having different results every run with GMM Classifier | 38,032,454 | <p>I'm currently doing a speech recognition and machine learning related project.
I have two classes now, and I create two GMM classifiers for each class, for labels 'happy' and 'sad'</p>
<p>I want to train GMM classifiers with MFCC vectors.</p>
<p>I am using two GMM classifiers for each label. (Previously it was GMM... | 0 | 2016-06-25T20:02:04Z | 38,057,895 | <blockquote>
<p>But every time I run the script I am having different results. What might be the cause for that with same test and train samples?</p>
</blockquote>
<p>scikit-learn uses random initializer. If you want reproducable results, you can set <a href="http://scikit-learn.org/stable/modules/generated/sklearn.... | 1 | 2016-06-27T15:30:37Z | [
"python",
"machine-learning",
"speech-recognition",
"svm",
"mfcc"
] |
Do I need to make two calls to listen() for a web socket, http server setup in Tornado? | 38,032,461 | <p>I have a web app that serves HTTP traffic on port 80, but also establishes a WebSocket connection on port 8888 to the client. The client issues an HTTP request for <code>index.html</code> on port 80, and the returned HTML page establishes a socket connection to my servers IP on port 8888 to retrieve real-time data f... | 0 | 2016-06-25T20:02:51Z | 38,037,143 | <p>WebSocket protocol is designed to be served from a HTTP server.<br>
You can serve both HTTP and WebSocket requests from the same port.</p>
<p>Just call</p>
<pre><code>application.listen(80)
</code></pre>
<p>and connect you WebSocket connection to port 80.</p>
| 0 | 2016-06-26T09:41:50Z | [
"python",
"websocket",
"tornado"
] |
Reset Pandas 'Series.rolling' on a daily basis | 38,032,495 | <p>Im using Pandas to analyse 1 min OHLC market data and have used the following to add a column containing a 20 period (20 minute) moving average to my data frame named 'data':</p>
<pre><code>data['maFast'] = Series.rolling(data['Last'],center=False,window=20).mean()
</code></pre>
<p>My data has a daystart = '9:30'... | 1 | 2016-06-25T20:05:32Z | 38,032,579 | <p>Here's an example with periods of 1 hour for display purpose but it shows the main idea: <strong>group by day and apply the rolling function on this grouped dataframe</strong>.</p>
<pre><code>In [62]: df = pd.DataFrame(index=pd.date_range(start='2014-03-04 09:00:00', end='2014-03-04 16:15:00', freq='1h') + pd.date_... | 1 | 2016-06-25T20:14:09Z | [
"python",
"pandas"
] |
How to filter a dataframe based on the values present in the list in the rows of a column in Python? | 38,032,524 | <p>I have a dataframe which looks like:</p>
<pre><code> business_id stars categories
0 abcd 4.0 ['Nightlife']
1 abcd1 3.5 ['Pizza', 'Restaurants']
2 abcd2 4.5 ['Groceries', 'Food']
</code></pre>
<p>I want to filter the dataframe based on the values present in the categories colum... | 1 | 2016-06-25T20:09:32Z | 38,032,709 | <p>You can use the <code>apply</code> method on the categories column and check if each element contains the <code>Food</code> or <code>Restaurants</code> based on which create a logic index array for subsetting:</p>
<pre><code>df.loc[df.categories.apply(lambda cat: 'Food' in cat or 'Restaurants' in cat)]
# busin... | 3 | 2016-06-25T20:29:55Z | [
"python",
"pandas"
] |
How to filter a dataframe based on the values present in the list in the rows of a column in Python? | 38,032,524 | <p>I have a dataframe which looks like:</p>
<pre><code> business_id stars categories
0 abcd 4.0 ['Nightlife']
1 abcd1 3.5 ['Pizza', 'Restaurants']
2 abcd2 4.5 ['Groceries', 'Food']
</code></pre>
<p>I want to filter the dataframe based on the values present in the categories colum... | 1 | 2016-06-25T20:09:32Z | 38,048,585 | <p>Just another idea. Keep strings instead of list objects.</p>
<pre><code>In [2]: import pandas as pd
In [3]: data = {'business_id':['abcd','abcd1','abcd2'],'stars': [4.0,3.5,4.5],'categories':[['Nightlife'],['Pizza', 'Restaurants'],['Groceries', 'Food']]}
# convert list to string with join() method
In [15]: df.c... | 0 | 2016-06-27T07:55:13Z | [
"python",
"pandas"
] |
What are some ideal ways to add update feature to a python project? | 38,032,558 | <p>I am working on a python project that I have hosted on github. I plan to release an initial version to the community. The problem is this: I want people to be able to update it newer versions as and when available by running some command like this:</p>
<pre><code>cf-cli.py update
</code></pre>
<p>What are some of ... | 0 | 2016-06-25T20:12:25Z | 38,032,777 | <p>Add it to PyPI - the Python Package Index.
<br>
The Python Package Index is a repository of software for the Python programming language.
<br>
Your users can install it and upgrade it as new versions come out as and when they want to without any issues.
<br><br>
You will have to do some basic work like creating a .p... | 2 | 2016-06-25T20:40:18Z | [
"python",
"python-2.7",
"command-line",
"command-line-interface"
] |
Raspberry Pi python app and nodejs socketio communication | 38,032,608 | <p>My requirement is to communicate socketio with nodejs server to Raspberry Pi running a local Python app. Please help me. I can find ways of communication with web app on google but is there any way to communicate with Python local app with above mentioned requirements.</p>
| 0 | 2016-06-25T20:17:10Z | 38,032,700 | <p>It's unclear exactly which part you need help with. To make a socket.io connection work, you do the following:</p>
<ol>
<li><p>Run a socket.io server on one of your two computers. Make sure it is listening on a known port (it can share a port with a web server if desired).</p></li>
<li><p>On the other computer, g... | 1 | 2016-06-25T20:29:10Z | [
"python",
"node.js",
"socket.io",
"raspberry-pi"
] |
Struggling with timer written in python? | 38,032,646 | <p>I wrote a program that's suppose to run for hours to do its job, The program has many functions defined and also it functions aren't in order, the user only sees the timer only when the program goes into the function that's for displaying and then the time freezes because of the other functions, is there a way to d... | -2 | 2016-06-25T20:21:56Z | 38,032,826 | <p>It sounds like you have a couple of problems and it would be great if you could post all the relevant code. For the first problem that your timer resets, you could do something like this instead, where you always keep the start variable in memory and don't overwrite it, and then just ping for time_elapsed = end- sta... | 0 | 2016-06-25T20:46:37Z | [
"python",
"python-2.7",
"timer"
] |
Get items on canvas | 38,032,667 | <p>Im working on a GUI for a board game. So I made some objects on the Canvas and I know they are somehow saved as integers because if I create it, it returns the int and if I canvas.delete(i) it gets removed. Summed up I have a mxn board and the squares are $i\in {1,__,m*n}$.
How can I configure the cells now, by only... | 0 | 2016-06-25T20:24:39Z | 38,033,447 | <p>I don't really often use Canvas quite often but this should be a workaround for what you have asking for:</p>
<pre><code>import tkinter as tk
# Defining all of your constants
width = 10
height = 10
spacing = 2
countX = 20
countY = 10
# Dictionary which will contains all rectangles
_objects = {}
# Creating the w... | 1 | 2016-06-25T22:18:45Z | [
"python",
"user-interface",
"tkinter"
] |
How can I select single item from one list and doing operation on all items of second list using Python | 38,032,674 | <p>For example if I have one list having data , and whose item should be selected one by one </p>
<pre><code>a = [0.11 , 0.22 , 0.13, 6.7, 2.5, 2.8]
</code></pre>
<p>and the other one for which all items should be selected </p>
<pre><code>b = [1.2 1.4, 2.6, 2.3, 5.7 9.9]
</code></pre>
<p>if I select <code>0.11</cod... | -1 | 2016-06-25T20:25:23Z | 38,032,719 | <p>You need a <em>nested loop</em>. You can do it in a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to produce a list of lists:</p>
<pre><code>[[item_a + item_b for item_b in b] for item_a in a]
</code></pre>
| 1 | 2016-06-25T20:30:57Z | [
"python"
] |
How can I select single item from one list and doing operation on all items of second list using Python | 38,032,674 | <p>For example if I have one list having data , and whose item should be selected one by one </p>
<pre><code>a = [0.11 , 0.22 , 0.13, 6.7, 2.5, 2.8]
</code></pre>
<p>and the other one for which all items should be selected </p>
<pre><code>b = [1.2 1.4, 2.6, 2.3, 5.7 9.9]
</code></pre>
<p>if I select <code>0.11</cod... | -1 | 2016-06-25T20:25:23Z | 38,032,761 | <p>If you want the end result to be a list of lists it could go like this:</p>
<pre><code>c = [[x + y for x in b] for y in a]
</code></pre>
<p>If you want the end result to be a single list with next sublists appended to each other you could write as such:</p>
<pre><code>c=[]
for (y in a):
c += ([y + x for x in ... | 1 | 2016-06-25T20:37:12Z | [
"python"
] |
How can I select single item from one list and doing operation on all items of second list using Python | 38,032,674 | <p>For example if I have one list having data , and whose item should be selected one by one </p>
<pre><code>a = [0.11 , 0.22 , 0.13, 6.7, 2.5, 2.8]
</code></pre>
<p>and the other one for which all items should be selected </p>
<pre><code>b = [1.2 1.4, 2.6, 2.3, 5.7 9.9]
</code></pre>
<p>if I select <code>0.11</cod... | -1 | 2016-06-25T20:25:23Z | 38,032,837 | <p>Another option is to convert your list into numpy array and then exploit the broadcasting property of numpy arrays:</p>
<pre><code>import numpy as np
npA = np.array(a)
npB = np.array(b)
npA[:, None] + npB
array([[ 1.31, 1.51, 2.71, 2.41, 5.81, 10.01],
[ 1.42, 1.62, 2.82, 2.52, 5.92, 10.1... | 0 | 2016-06-25T20:48:59Z | [
"python"
] |
Link a Span or Cursor in between plots with Bokeh in Python | 38,032,737 | <p>I would like a cursor that is linked between to plots in Bokeh. So if I move my cursor on one plot, an equivalent line shows up on an adjacent plot. I haven't figured out how to do it with the built in cursor tool. So my current solution is to draw a line on each plot that shares a source. Then when I hover over... | 1 | 2016-06-25T20:33:52Z | 38,058,953 | <p>Thanks to @bigreddot for his answer on the spans. I had tried and not gotten in to work, but figured it out with his hints. The working code is below. I implemented a span in each plot and then edit the location of each.</p>
<pre><code>from bokeh.io import gridplot, show, output_notebook, output_file
from bokeh.... | 1 | 2016-06-27T16:30:34Z | [
"python",
"plot",
"bokeh"
] |
Pandas dataframe from list with merged index | 38,032,752 | <p>I am new to python, so call me a noob but I cannot find a clear answer. I want to obtain a pandas dataframe from a list of lists with merged indices. I am running a loop and the numbe rof observations (here arbitrarily 3) could differ in each run. This holds also true for the dates. I'm sorry but I could not manage ... | 0 | 2016-06-25T20:35:58Z | 38,032,775 | <p>Unless i'm missing something, you can build directly the dataframe</p>
<pre><code>In [65]: pd.DataFrame(
index=pd.to_datetime(['2015-10-26 16:24:08.572'] * 3),
data={
'signal_0': 0,
'signal_1': 1,
'signal_2': 2
}
)
Out[65]:
signal_0 signal_1 signal_2
2... | 0 | 2016-06-25T20:39:50Z | [
"python",
"pandas",
"dataframe",
"merge"
] |
Why is my Logstash handler throwing a TypeError? | 38,032,782 | <p>I'm creating a custom logger with the following code:</p>
<pre><code>import logging
import logstash
from socket import gethostname
class CustomLogger(logging.Logger):
def _log(self, level, msg, args, exc_info=None, extra=None):
if extra is None:
extra = { 'hostname' : gethostname() }
... | -1 | 2016-06-25T20:40:41Z | 38,044,245 | <p>The problem was with the formatter. I removed the line adding the formatter to <code>logstash_handler</code> object and it successfully logged to logstash according to the config.</p>
| 0 | 2016-06-26T23:53:31Z | [
"python",
"python-3.x",
"logging",
"logstash",
"bytestream"
] |
Efficient way to to find Objects with common attributes in 2 python-lists | 38,032,808 | <p>The heading might be confusing - i will try to explain what I want to do:
I'm studying computer-science and trying to implement a small movie-recommender as a project for my lecture "Data-Warehousing & Data Mining". Right now I'm trying to compute the similarity of 2 users according to their movie-ratings.</p>
... | 2 | 2016-06-25T20:43:55Z | 38,033,007 | <p>Your approach is O(N^2) worst case. You can reduce the complexity to O(N log N) sorting the ratings lists:</p>
<pre><code>sorted_ratingsA = sorted(ratingsA, lambda x: x.movieID)
sorted_ratingsB = sorted(ratingsB, lambda x: x.movieID)
</code></pre>
<p>And now we can pop the items from these lists from the last one ... | 2 | 2016-06-25T21:11:25Z | [
"python",
"performance",
"set",
"similarity"
] |
Python: using custom comparator for sort in OrderedDict | 38,032,827 | <p>I have a dictionary which has the following content :</p>
<pre><code>dict = {'P1' :361 , 'P2' : 361, 'P3' : 391, 'P6' : 361, 'P4':361, 'P5' :361}
</code></pre>
<p>which needs to be sorted on basis of value in descending order. For any given item if the value is same to the item it is compared, it is to be sorted o... | 2 | 2016-06-25T20:46:58Z | 38,032,874 | <p>You can just use a slightly different lambda expression as the key for sorting.</p>
<pre><code>sorted_dict = OrderedDict(sorted(dict.items(), key=lambda x: (-x[1], x[0])))
</code></pre>
<p><strong>Outputs</strong>:</p>
<pre><code>OrderedDict([('P3', 391), ('P1', 361), ('P2', 361), ('P4', 361), ('P5', 361), ('P6',... | 2 | 2016-06-25T20:53:31Z | [
"python"
] |
Python: using custom comparator for sort in OrderedDict | 38,032,827 | <p>I have a dictionary which has the following content :</p>
<pre><code>dict = {'P1' :361 , 'P2' : 361, 'P3' : 391, 'P6' : 361, 'P4':361, 'P5' :361}
</code></pre>
<p>which needs to be sorted on basis of value in descending order. For any given item if the value is same to the item it is compared, it is to be sorted o... | 2 | 2016-06-25T20:46:58Z | 38,033,466 | <p>If the keys do not conatin all single digits and you don't want a lexicographical sort then you will need to add more logic:</p>
<pre><code>d = {'P1000': 361, 'P200': 361, 'P3': 391, 'P6': 361, 'P4': 361, 'P5': 361,"P100":361}
import re
patt = re.compile("[^\d]")
def cmp(x):
letts = patt.search(x).group()
... | 1 | 2016-06-25T22:21:29Z | [
"python"
] |
Python - why won't while loop end program? | 38,032,844 | <p>So this is a little game I have made but when either user_lives or comp_lives equals 0 it does not end the loop and I don't understand why.</p>
<p>It works if I set the while loop to: while user_lives > 1 or comp_lives > 1:</p>
<p>I can also fix it by putting a break in the if statements of both the elif statement... | -3 | 2016-06-25T20:50:26Z | 38,032,888 | <p>The code that you have posted has the logic as follows:</p>
<p>IF <code>user_lives</code> > 0, continue the loop. OR
IF <code>comp_lives</code> > 0, continue the loop.</p>
<p>Do you see the problem? The loop can ONLY end if BOTH <code>user</code> and <code>comp</code> lives <code><=0</code>.</p>
<p>I think per... | 2 | 2016-06-25T20:54:40Z | [
"python",
"while-loop"
] |
Python coordinate collision help wanted | 38,032,872 | <p>I wanted to make that enemies would not be on same coordinates.
I don't want any other advice like advice that would make my code more clean.
Here is that part of the code:</p>
<pre><code>class enemy(object):
def __init__(self,x,y):
self.x=x
self.y=y
def move(self):
if self.x*tilesiz... | 0 | 2016-06-25T20:53:27Z | 38,034,092 | <p>If ahead of time you do</p>
<pre><code>from itertools import product
</code></pre>
<p>then you can replace that ten-line assignment to <code>enemies</code> with</p>
<pre><code>mapxy = list(product(range(mapwidth),range(mapheight)))
enemies = [enemy(*xy) for xy in random.sample(mapxy, 10)]
</code></pre>
<p>This u... | 0 | 2016-06-26T00:13:42Z | [
"python"
] |
Calling HTTP API from script generates 400, calling from browser generates 200 | 38,032,897 | <ul>
<li>When I attempt to exercise <a href="http://stats.nba.com/stats/teamgamelog" rel="nofollow">this HTTP API endpoint</a> programmatically from a python script, the server usually (but not always) sends a 400.</li>
<li>Such responses have empty bodies -- so I don't know why the server doesn't like my requests.</li... | 2 | 2016-06-25T20:55:21Z | 38,033,190 | <p>Very simple solution,nothing to do with proxies, you need to add a user-agent:</p>
<pre><code>def sync():
head = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36"}
all_urls = urls()
for url in all_urls:
res = requests.get(u... | 4 | 2016-06-25T21:37:56Z | [
"python",
"http",
"python-requests"
] |
Attaching KafaConsumer assigned to a specific partition | 38,032,932 | <p>How to attach a python consumer script to a particular kafka partition. <br>
On running two instance of the consumer script (given below), each of them randomly picks up one partition and then consumes/prints all messages of that particular partition, As expected.<br><br>
But as I need to output these messages to a... | 0 | 2016-06-25T21:00:34Z | 38,033,030 | <p><a href="http://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html#kafka.KafkaConsumer.assign" rel="nofollow">You can use the <code>assign()</code> method</a> to manually assign one or more partitions to a consumer.</p>
<p>There <a href="https://pypi.python.org/pypi/kafka-python" rel="nofollow">is some... | 0 | 2016-06-25T21:15:13Z | [
"python",
"apache-kafka",
"kafka-consumer-api"
] |
concatenation large number of dataframes | 38,033,001 | <p>I have a dictionary <code>D</code> that contains many dataframes.
I can access every dataframe with <code>D[0], D[1]...D[i]</code>, with the integers as keys/identifier of the respective dataframe.</p>
<p>I now want to concat all the dataframes in this fashion into a new dataframe:</p>
<pre><code> new_df = pd.conc... | 1 | 2016-06-25T21:10:31Z | 38,033,122 | <p>I think the easiest thing to do is to use a dict comprehension of the dict items:</p>
<pre><code>In [14]:
d = {'a':pd.DataFrame(np.random.randn(5,3), columns=list('abc')), 'b':pd.DataFrame(np.random.randn(5,3), columns=list('def'))}
d
Out[14]:
{'a': a b c
0 0.030358 1.523752 1.040409
... | 1 | 2016-06-25T21:27:54Z | [
"python",
"pandas",
"dataframe",
"concatenation"
] |
Why won't my models won't show up on admin page in Django? | 38,033,011 | <p>I have tried everything to try and make this work. I recently tried squashing my migrations and then migrate them again. Alas, to no avail.</p>
<p>My {{ app }}/admin.py file:</p>
<pre><code>from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
</code></pre>
<p>My {{ project... | 3 | 2016-06-25T21:11:53Z | 38,033,155 | <p><em>blogs/admin.py</em>, not <em>personalblog/admin.py</em> (you can delete <em>personalblog/admin.py</em> file):</p>
<pre><code>from django.contrib import admin
from .models import BlogPost
admin.site.register(BlogPost)
</code></pre>
<p>Also, replace <code>'blogs'</code> in <code>INSTALLED_APPS</code> with <cod... | 1 | 2016-06-25T21:33:13Z | [
"python",
"django"
] |
grep and then parse, python commandline | 38,033,173 | <p>When I do, in python code,</p>
<pre><code>os.system("mpstat 1 10 | grep Average")
</code></pre>
<p>I get, at stdout:</p>
<p>"Average: all 0.00 0.00 0.00 0.00" and a bunch of other things</p>
<p>What can I add to</p>
<pre><code>mpstat 1 10 | grep Average | SOMETHING
</code></pre>
<p>to get a variable tha... | 0 | 2016-06-25T21:35:46Z | 38,033,323 | <p>Do away with <code>os.system</code> call. Use <code>subprocess.Popen</code> instead. Here's how you'd do it:</p>
<pre><code>>>> from subprocess import Popen
>>> from subprocess import PIPE
>>> mpstat = Popen(["mpstat", "1", "10"], stdout=PIPE)
>>> grep = Popen(["grep", "Average"]... | 1 | 2016-06-25T21:58:37Z | [
"python",
"shell",
"unix",
"command-line",
"grep"
] |
Django-Reversion: Accessing QuerySet Data | 38,033,259 | <p>I have a model that is under version control using Django-Reversion. Within a Terminal window I can access all of the previous versions of a model instance using:</p>
<pre><code>foo = FooModel.objects.get()
versions = Version.objects.get_for_object(foo)
</code></pre>
<p>When I check <code>versions</code> it's a se... | 0 | 2016-06-25T21:48:25Z | 38,033,294 | <p>Try calling <code>list</code> on the <code>versions</code> object. This should force the QuerySet to evaluate its items:</p>
<pre><code>versions = Version.objects.get_for_object(foo)
new_versions = list(versions)
</code></pre>
| 0 | 2016-06-25T21:53:59Z | [
"python",
"django",
"django-models",
"django-views",
"django-reversion"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.