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 |
|---|---|---|---|---|---|---|---|---|---|
Django paginator with many pages | 39,088,813 | <p>I have implemented a paginator with the generic ListView. My problem is that for list with many pages it displays all the page numbers instead of for example five pages before and after the current page. Is there an easy way to fix this?</p>
<p>in the views.py:</p>
<pre><code>class CarList(LoginRequiredMixin, List... | 1 | 2016-08-22T21:13:06Z | 39,090,909 | <p>The algorithm for that is not too complicated, and can be further simplified if we assume that if there are more than 11 pages (current, 5 before, 5 after) we are always going to show 11 links. Now we have 4 cases:</p>
<ol>
<li>Number of pages < 11: show all pages;</li>
<li>Current page <= 6: show first 11 pa... | 2 | 2016-08-23T01:16:05Z | [
"python",
"django",
"python-3.x",
"pagination",
"django-views"
] |
python random shuffle while loop | 39,088,844 | <p>I'm trying to fill lists with permutations of the same initial list. I don't understand why the following is not working.</p>
<pre><code>parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval)
</code></pre>
... | 3 | 2016-08-22T21:16:06Z | 39,088,944 | <p><code>random.shuffle</code> works in-place and consequently modifies <code>newval</code>. You have to make a copy when appending to <code>part</code> otherwise the same list (or list reference) is shuffled and stored in <code>part</code>.</p>
<pre><code>import random
parts = [[],[]]
while len(parts[-1]) < 2:
... | 6 | 2016-08-22T21:22:34Z | [
"python",
"list",
"random",
"while-loop"
] |
python random shuffle while loop | 39,088,844 | <p>I'm trying to fill lists with permutations of the same initial list. I don't understand why the following is not working.</p>
<pre><code>parts = [[],[]]
while len(parts[-1]) < 2:
newval = random.choice([[1,2,3,4],[5,6,7,8]])
for part in parts:
random.shuffle(newval)
part.append(newval)
</code></pre>
... | 3 | 2016-08-22T21:16:06Z | 39,088,986 | <p>Because in Python everything is reference. When you append the value to the array, in fact you add the reference to the place in memory where the value is stored.</p>
<p>Say, you have assigned the list to the first element. When on the next iteration you re-shuffle this list, you change the value in the memory. Thu... | 3 | 2016-08-22T21:26:01Z | [
"python",
"list",
"random",
"while-loop"
] |
Python: faster alternatives to searching if an item is "in" a list | 39,088,867 | <p>I have a list of ~30 floats. I want to see if a specific float is in my list. For example:</p>
<pre><code>1 >> # For the example below my list has integers, not floats
2 >> list_a = range(30)
3 >> 5.5 in list_a
False
4 >> 1 in list_a
True
</code></pre>
<p>The bottleneck in my code is line ... | 0 | 2016-08-22T21:17:24Z | 39,088,907 | <p>The best possible time to check if an element is in list if the list is not sorted is O(n) because the element may be anywhere and you need to look at each item and check if it is what you are looking for</p>
<p>If the array was sorted, you could've used binary search to have O(log n) look up time. You also can use... | 2 | 2016-08-22T21:20:13Z | [
"python",
"list",
"optimization",
"set"
] |
Python: faster alternatives to searching if an item is "in" a list | 39,088,867 | <p>I have a list of ~30 floats. I want to see if a specific float is in my list. For example:</p>
<pre><code>1 >> # For the example below my list has integers, not floats
2 >> list_a = range(30)
3 >> 5.5 in list_a
False
4 >> 1 in list_a
True
</code></pre>
<p>The bottleneck in my code is line ... | 0 | 2016-08-22T21:17:24Z | 39,089,167 | <p>In my experience, Python indeed slows down when we search something in a long list.</p>
<p>To complement the suggestion above, my suggestion will be subsetting the list, of course only if the list can be subset and the query can be easily assigned to the correct subset. </p>
<p>Example is searching for a word in a... | 0 | 2016-08-22T21:41:02Z | [
"python",
"list",
"optimization",
"set"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.... | 0 | 2016-08-22T21:27:25Z | 39,089,077 | <p>You honestly don't need anything that fancy. Just do a min on the first item in every list. Then check if the value that is the min is in any of the lists and do a list.pop() and a print then. That's a simple way to do it that is efficient and makes sense. I could provide you the code but this should be clear en... | -2 | 2016-08-22T21:33:37Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.... | 0 | 2016-08-22T21:27:25Z | 39,089,161 | <pre><code># Create the list of all dates, combining the four lists you have. Keep
# the information about which list value comes from
all_dates = [(x, 'a') for x in a] + [(x, 'b') for x in b] + [(x, 'c') for x in c] + [(x, 'd') for x in d]
# Sort with key a simple date parser. The way it works is:
# 1. It take... | -1 | 2016-08-22T21:40:21Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.... | 0 | 2016-08-22T21:27:25Z | 39,089,346 | <p>Assuming your dates are all formatted as <code>mm-dd-yyyy</code> (unlike your example), this should do the trick:</p>
<pre><code>import itertools
lists = dict(a=['7-1-1987', '1-1-1990'],
b=['7-2-1987', '1-5-1990'],
c=['7-1-1987', '1-3-1990'],
d=['1-10-1985', '7-10-1986'])
fo... | 0 | 2016-08-22T21:57:07Z | [
"python",
"list",
"sorting"
] |
Python sort multiple lists by date and print list names | 39,089,005 | <p>Working in Python 3.5.2 I have four lists of dates, each in ascending order, where the lists are not of equal length. Each list of dates is generated by a lookup into a longer list of dates. A sample date value and data type is shown below:</p>
<pre><code>In: print (date, type(date))
Out: 725722.0 <class 'numpy.... | 0 | 2016-08-22T21:27:25Z | 39,089,492 | <p>I have a couple comments on this one:</p>
<ol>
<li><p>"Best" is ambiguous. It could mean minimized algorithmic complexity, minimized runtime, minimized memory usage, simplest to implement or read, least amount of code, etc.</p></li>
<li><p>Unless you have thousands of entries, it might not be worth optimizing your... | 3 | 2016-08-22T22:09:55Z | [
"python",
"list",
"sorting"
] |
Can you spawn a child process written in a different language than a Python or PHP server, like you would with Node.js? | 39,089,057 | <p>What are the Python (Tornado/Flask/etc) or Apache/PHP ways of spawning a child process to run a script written in a different programming language than Python or PHP, and communicate with the server over standard input and output?</p>
<p>I'm looking for the Python/PHP equivalent to Node.js "child_process" library. ... | 1 | 2016-08-22T21:31:34Z | 39,089,091 | <p>The language of the spawning process isn't relevant to the language of the spawned process. This is not a feature of Node.JS, PHP, or Python, this is a feature of the operating system.</p>
<p>In python, for example, one uses calls from the <code>subprocess</code> module. Here is an example of a Python script callin... | 1 | 2016-08-22T21:34:48Z | [
"javascript",
"php",
"python",
"node.js",
"child-process"
] |
Calling exists() in sqlalchemy with multiple values in python | 39,089,153 | <p>I am trying to find out if there is any nicer way I can check if a table
of users contains a group of names instead of checking them one at a time</p>
<p>This is what I am using to currently check the User table one at a time which gives me True or False if the user exists in the table:</p>
<pre><code>ret = sessio... | 1 | 2016-08-22T21:39:45Z | 39,089,332 | <p>You are correct to use the <code>exists()</code> expression, but combine it with a subquery that leverages the <code>in_()</code> expression.
</p>
<pre><code>q = session.query(Users).filter(Users.name.in_(['Jack', 'Bob', 'Sandy']))
# Below will return True or False
at_least_one_user_exists = session.query(q.ex... | 1 | 2016-08-22T21:55:56Z | [
"python",
"mysql",
"sqlalchemy"
] |
How to not let text overlap each other in pygame? | 39,089,185 | <p>i have two text examples, but they just appear on top of each other. how do i make it so that the second one replaces the first?</p>
<pre><code>if player_x_coor <= -2750:
text = font.render("text 1", True, WHITE)
screen.blit(text, [100, 150])
if player_x_coor <= -6310:
text = font.ren... | 1 | 2016-08-22T21:42:57Z | 39,089,370 | <p>You need to erase the first text before writing another.</p>
<p>See this similar questions <a href="http://stackoverflow.com/questions/20655828/new-text-rendered-over-older-text-in-pygame">here</a> and <a href="http://stackoverflow.com/questions/6795644/what-is-the-correct-sequence-for-bliting-surfaces-to-the-scree... | -1 | 2016-08-22T21:59:31Z | [
"python",
"text",
"pygame"
] |
How to not let text overlap each other in pygame? | 39,089,185 | <p>i have two text examples, but they just appear on top of each other. how do i make it so that the second one replaces the first?</p>
<pre><code>if player_x_coor <= -2750:
text = font.render("text 1", True, WHITE)
screen.blit(text, [100, 150])
if player_x_coor <= -6310:
text = font.ren... | 1 | 2016-08-22T21:42:57Z | 39,093,644 | <p>When you draw onto the screen, everything that is already there doesn't clear on its own. You have to blank the screen using some color, let's say black. Once the screen is clear of previous frame, you can redraw each object from bottom to top.</p>
<p>It is possible, if say you have a simple square underneath the t... | 2 | 2016-08-23T06:16:09Z | [
"python",
"text",
"pygame"
] |
TypeError: __init__() got an unexpected keyword argument 'size | 39,089,253 | <p>How do i fix this unexpected keyword argument 'size'? </p>
<hr>
<pre><code> Traceback (most recent call last):
File "H:\Documents\Astro game\astro games6.py", line 73, in <module>
main()
File "H:\Documents\Astro game\astro games6.py", line 61, in main
new_asteroid = Asteroid(x =... | -3 | 2016-08-22T21:49:30Z | 39,089,340 | <p>Remove the <code>size</code> argument in your code.</p>
<p><em>note: a Python module name shouldn't have a space: you won't be able to import it in another module.</em></p>
| -2 | 2016-08-22T21:56:52Z | [
"python"
] |
TypeError: __init__() got an unexpected keyword argument 'size | 39,089,253 | <p>How do i fix this unexpected keyword argument 'size'? </p>
<hr>
<pre><code> Traceback (most recent call last):
File "H:\Documents\Astro game\astro games6.py", line 73, in <module>
main()
File "H:\Documents\Astro game\astro games6.py", line 61, in main
new_asteroid = Asteroid(x =... | -3 | 2016-08-22T21:49:30Z | 39,089,593 | <p>Your Asteroid class defines <code>_init_</code> instead of <code>__init__</code>. You need two underscores on either side for Python magic methods.</p>
| 0 | 2016-08-22T22:21:01Z | [
"python"
] |
Passing DTS variable inside python script in ssis | 39,089,336 | <p>I am trying to using a python script using the "Execute Task" tool in ssis.However, i am not sure if i will be able to use one of the runtime variable inside the python script. Eg:</p>
<pre><code>#inputval.py
inputval = dts.value("test").toString()
print(inputval)
</code></pre>
<p>Is there any chance ? . Thanks i... | 0 | 2016-08-22T21:56:28Z | 39,089,627 | <p>Yes you can reference the value but not in that manner.</p>
<p>Python won't have access to the Variables collection so you'll have to use a different method for communication. The <a href="https://msdn.microsoft.com/en-us/library/ms141166.aspx" rel="nofollow">Execute Package Task</a> supports either a Variable for ... | 1 | 2016-08-22T22:24:58Z | [
"python",
"ssis",
"ssis-2008"
] |
Return to a function if file was not detected. (Python) | 39,089,355 | <p>So I made a retrieve if a file was found with this code:</p>
<pre><code>try:
with open('Kappa.txt') as file:
passexcept IOError as e:
print "Unable to open/detect file."
</code></pre>
<p>That works fine. So before that function the user can enter a path where this txt file is located on his computer. If Kappa.... | 0 | 2016-08-22T21:58:19Z | 39,089,427 | <p>There is not much point in doing try - except here. You can easily check if file exists and proceed only if that is the case.</p>
<pre><code>import os
file_name = raw_input("File name: ")
# Until the file user enters is existing, keep asking
while not os.path.isfile(file_name):
file_name = raw_input("File nam... | 0 | 2016-08-22T22:03:08Z | [
"python"
] |
Return to a function if file was not detected. (Python) | 39,089,355 | <p>So I made a retrieve if a file was found with this code:</p>
<pre><code>try:
with open('Kappa.txt') as file:
passexcept IOError as e:
print "Unable to open/detect file."
</code></pre>
<p>That works fine. So before that function the user can enter a path where this txt file is located on his computer. If Kappa.... | 0 | 2016-08-22T21:58:19Z | 39,089,457 | <p>Do an infinite loop:</p>
<pre><code>while True:
try:
filename = raw_input("File: ")
with io.open(filename, encoding='utf8') as fd:
content = fd.read()
break
except IOError:
print("retry!")
</code></pre>
| 0 | 2016-08-22T22:06:14Z | [
"python"
] |
Linear regression in theano | 39,089,357 | <p>What is the significance of <code>T.mean</code> in <a href="https://github.com/Newmu/Theano-Tutorials/blob/master/1_linear_regression.py" rel="nofollow">this example</a>? I think <code>T.mean</code> would have made sense if the implementation were vectorized. Here the inputs <code>x</code> and <code>y</code> to <cod... | 1 | 2016-08-22T21:58:21Z | 39,089,694 | <p>You are right, <code>T.mean</code> has no significance here. The cost function operates on a single training sample at once, so the "mean squared error" is really just the squared error of the sample.</p>
<p>This example implements linear regression via <a href="https://en.wikipedia.org/wiki/Stochastic_gradient_des... | 1 | 2016-08-22T22:31:17Z | [
"python",
"theano"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. ... | 0 | 2016-08-22T22:01:05Z | 39,089,558 | <p>To address the problems with your approach I'd need to see the full code, but I have another suggestion.</p>
<p>You can actually use the regular expressions here, which allows making the substitution in a one-liner (almost).</p>
<pre><code>In [1]: import re
In [2]: story = ''' Back t... | 2 | 2016-08-22T22:17:45Z | [
"python"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. ... | 0 | 2016-08-22T22:01:05Z | 39,089,622 | <pre><code>text = """Marty was an innocent, young (noun) and made friends with the local scientist,
Doc (name). Doc (name) was a bit off, but he was one (adjective) genius. One day,
he told Marty that he had an invented a (noun)! Of course, Marty had to see it
in action. Late that night, they met at (place)."""
match... | 0 | 2016-08-22T22:24:24Z | [
"python"
] |
Replacing keywords in parentheses with user input | 39,089,397 | <p>So, I'm making a little Python 3 applet for madlibs. So far, I have it so that it reads a text file, pulls a random story from it, and splits that story into a list for search through it. That all works great. I have the stories formatted so that, where words are needed, it uses (noun), (adverb), (name), et cetera. ... | 0 | 2016-08-22T22:01:05Z | 39,110,649 | <p>Okay, to solve my issue of only wanting to ask for each identical item once, I had to rewrite a little bit. I'm still using the regex provided by @Lex, so thanks to him for that. However, I am no longer using his <code>re.sub()</code> method.</p>
<pre><code>import re
l1 = re.findall('\(([^()]*)\)',story)
l2 = []
fo... | 0 | 2016-08-23T21:04:42Z | [
"python"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>... | 1 | 2016-08-22T22:06:40Z | 39,089,512 | <p>The problem is you are summing the list trying to use that to determine whether the list is primarily odds or evens. That doesn't work because the sum of a list of evens is even, but a sum of odds will be even or odd based on the number of items in the list.</p>
<p>Instead, just keep track of the last even and odd... | 1 | 2016-08-22T22:12:21Z | [
"python",
"algorithm"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>... | 1 | 2016-08-22T22:06:40Z | 39,089,518 | <p>Why do you care about the length at all? Here is much simpler solution:</p>
<pre><code>def find_outliner(a):
if a[0] % 2 != a[1] % 2:
return a[0] if a[2] % 2 == a[1] % 2 else a[1]
for i in a:
if i % 2 != a[0] % 2:
return i
</code></pre>
<p>How does it work?</p>
<ol>
<li>There s... | 2 | 2016-08-22T22:12:37Z | [
"python",
"algorithm"
] |
Finding the Parity Outlier in a list of odd/even integers | 39,089,459 | <p>I'm trying to find and return the single even integer in a list of odd integers or the sole odd integer in a list of even integers. My code works, however, if the length of the list for odd integers is even, it returns the first number in the list instead of the even integer. Any help is appreciated. Code below:</p>... | 1 | 2016-08-22T22:06:40Z | 39,089,968 | <p>Just an alternative, collecting the evens and odds in two lists and then using the smaller list.</p>
<pre><code>def find_outlier(x):
evenodd = [], []
for v in x:
evenodd[v & 1].append(v)
return min(evenodd, key=len)[0]
</code></pre>
<p>Demo:</p>
<pre><code>>>> for x in [2, 4, 6, 8... | 0 | 2016-08-22T22:59:55Z | [
"python",
"algorithm"
] |
Getting a TypeError when trying to send a random packet in a socket | 39,089,493 | <p>I'm trying to make a simple UDP flooder to learn a a little about sockets, however i get "TypeError: an integer is required"</p>
<pre><code>import os
import socket
import random
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
print("Python Script 1")
os.system("pause")
print("[*] Please enter parameters below... | 0 | 2016-08-22T22:10:08Z | 39,089,520 | <p><code>port</code> must be an<code>int</code>, not a <code>str</code>.</p>
<pre><code>port = int(port)
</code></pre>
| 1 | 2016-08-22T22:12:42Z | [
"python",
"python-2.7"
] |
Installing Yapsy for Python script in Windows | 39,089,544 | <p>Im trying to run a script in python 2.7 but I need Yapsy, I download from github but I dont know how to install it, I cant find any documentation in github neither in <a href="http://yapsy.sourceforge.net/" rel="nofollow" title="sourceforge">sourceforge</a><a href="http://i.stack.imgur.com/x4XHf.png" rel="nofollow">... | 0 | 2016-08-22T22:15:28Z | 39,089,777 | <p>From the <a href="https://yapsy.readthedocs.io/en/latest/" rel="nofollow">manual</a>:
<code>pip install -e "git+https://github.com/tibonihoo/yapsy.git#egg=yapsy&subdirectory=package"</code> or </p>
<p><code>pip install -e "hg+http://hg.code.sf.net/p/yapsy/code#egg=yapsy&subdirectory=package"
</code></p>
| 0 | 2016-08-22T22:40:36Z | [
"python",
"python-2.7"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array ... | 2 | 2016-08-22T22:23:42Z | 39,089,668 | <p>Those numbers get very big, fast. </p>
<pre><code>>>> np.prod(array[:25])
7034535277573963776
>>> np.prod(array[:26])
-1569523520172457984
>>> type(_)
numpy.int64
</code></pre>
<p>You're actually overflowing numpy's data type here, hence the wack results. If you stick to python ints, y... | 3 | 2016-08-22T22:28:58Z | [
"python",
"list",
"numpy",
"math"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array ... | 2 | 2016-08-22T22:23:42Z | 39,089,671 | <p>Note that <a href="http://www.gossamer-threads.com/lists/python/python/105568" rel="nofollow">Python uses "unlimited" integers</a>, but in numpy everything is typed, and so it is a "C"-style (probably 64-bit) integer here. You're probably experiencing an overflow.</p>
<p>If you look at the documentation for <a href... | 2 | 2016-08-22T22:29:02Z | [
"python",
"list",
"numpy",
"math"
] |
Why is numpy.prod() incorrectly returning negative results, or 0, for my long lists of natural numbers? | 39,089,618 | <p>I'm just working on Project Euler <a href="https://projecteuler.net/problem=12" rel="nofollow">problem 12</a>, so I need to do some testing against numbers that are multiples of over 500 unique factors.</p>
<p>I figured that the array [1, 2, 3... 500] would be a good starting point, since the product of that array ... | 2 | 2016-08-22T22:23:42Z | 39,100,107 | <p>You get the result 0 due to the large number of factors 2 in the product, there are more than 450 of those factors. Thus in a reduction modulo <code>2^64</code>, the result is zero.</p>
<p>Why the data type forces this reduction is explained in the other answers. </p>
<hr>
<pre><code>250+125+62+31+15+7+3+1 = 494 ... | 0 | 2016-08-23T11:36:56Z | [
"python",
"list",
"numpy",
"math"
] |
How to use `Dirichlet Process Gaussian Mixture Model` in Scikit-learn? (n_components?) | 39,089,637 | <p><strong>My understanding of "an infinite mixture model with the Dirichlet Process as a prior distribution on the number of clusters" is that the number of clusters is determined by the data as they converge to a certain amount of clusters.</strong> </p>
<p>This <code>R Implementation</code> <a href="https://github... | 0 | 2016-08-22T22:25:55Z | 39,623,217 | <p>As mentioned by @maxymoo in the comments, <code>n_components</code> is a truncation parameter. </p>
<p>In the context of the Chinese Restaurant Process, which is related to the Stick-breaking representation in sklearn's DP-GMM, a new data point joins an existing cluster <code>k</code> with probability <code>|k| / n... | 0 | 2016-09-21T17:42:52Z | [
"python",
"machine-learning",
"statistics",
"scikit-learn",
"bayesian"
] |
Cython compiling errors - variable referenced before assignment | 39,089,661 | <p>I'm goofing off with cython and a pretty big for loop - over a million. It takes about 40 minutes to run regular when I run as a regular python program. </p>
<p>vetdns.pyx and labeled cdef variables just below declaring the function - </p>
<pre><code>now = datetime.datetime.now()
today = now.strftime("%Y-%m-%d")
... | 0 | 2016-08-22T22:28:22Z | 39,093,072 | <p>You declare <code>outname</code> as a local variable on this line:</p>
<pre><code>cdef outname, INPUT_FILE, OUTPUT_FILE
</code></pre>
<p>but then you never assign anything to it. Python requires that variables are assigned before you can use them, there is no default value they get initialized to.</p>
<p>I see th... | 2 | 2016-08-23T05:33:59Z | [
"python",
"cython"
] |
Rolling Regression Estimation in Python dataframe | 39,089,693 | <p>I have a dataframe like this:</p>
<pre><code> Date Y X1 X2 X3
22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036
23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097
24 2004-05-14 9.732308e-09 0.000085 0.000073 0.000096
25 2004-05-... | 1 | 2016-08-22T22:31:09Z | 39,089,927 | <pre><code>model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['X1', 'X2', 'X3']],
window_type='rolling', window=100, intercept=True)
df['Y_hat'] = model.y_predict
</code></pre>
| 2 | 2016-08-22T22:55:26Z | [
"python",
"pandas",
"dataframe"
] |
How to install Python 3.5 on Raspbian Jessie | 39,089,698 | <p>I need to install Python 3.5+ on Rasbian (Debian for the Raspberry Pi). Currently only version 3.4 is supported. For the sources I want to compile I have to install:</p>
<pre><code>sudo apt-get install -y python3 python-empy python3-dev python3-empy python3-nose python3-pip python3-setuptools python3-vcstool pydocs... | 0 | 2016-08-22T22:31:53Z | 39,089,725 | <blockquote>
<p>But I think that apt-get will install more than these
packages, for example libpython3-dev</p>
</blockquote>
<p>Why is that a problem? </p>
<blockquote>
<p>I already install python3 from <a href="https://www.python.org/downloads/" rel="nofollow">https://www.python.org/downloads/</a> but I think,... | -2 | 2016-08-22T22:34:18Z | [
"python",
"raspberry-pi",
"debian",
"raspbian"
] |
How to install Python 3.5 on Raspbian Jessie | 39,089,698 | <p>I need to install Python 3.5+ on Rasbian (Debian for the Raspberry Pi). Currently only version 3.4 is supported. For the sources I want to compile I have to install:</p>
<pre><code>sudo apt-get install -y python3 python-empy python3-dev python3-empy python3-nose python3-pip python3-setuptools python3-vcstool pydocs... | 0 | 2016-08-22T22:31:53Z | 39,185,009 | <p>The suggestion of @Padraic Cunningham to install <code>libssl</code> header files was helpful.</p>
<pre><code>sudo apt-get install libssl-dev
</code></pre>
<p>But after this I further had to install <em>GCC</em> higher version 5 and <em>CMake</em> higher 3.5. The new <em>Raspian Stretch</em> comes with <em>Python ... | 0 | 2016-08-27T19:35:49Z | [
"python",
"raspberry-pi",
"debian",
"raspbian"
] |
tkinter Label Isn't showing | 39,089,726 | <p>I'm following a well reviewed python book called "Python programming" and have followed the book to the letter, until in the middle of programming I wanted to test out my label so I tried. Code runs fine but label didn't appear. Please help me. Code is down below.</p>
<pre><code>import sys
import os
from tkinter im... | -2 | 2016-08-22T22:34:20Z | 39,090,267 | <p>First, you need to instantiate the class. Root is just an empty window.</p>
<pre><code>mywindow = Safe()
mywindow.title("Password Safe")
mywindow.mainloop()
</code></pre>
<ul>
<li><code>self.create_widgets()</code> will add the widgets to the frame.</li>
<li><code>self.inst_label.grid()</code> will tell Tk how to ... | 0 | 2016-08-22T23:37:50Z | [
"python",
"tkinter"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted str... | 1 | 2016-08-22T22:38:33Z | 39,089,940 | <p>The order in alternation groups matters.</p>
<p>In the first regex the <code>[^"]</code> alternative is tried first for every character. It matches every single character up to (and including) the first <code>\</code>. On the next character (<code>"</code>) this alternative (<code>[^"]</code>) fails and the other o... | 1 | 2016-08-22T22:56:46Z | [
"python",
"regex"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted str... | 1 | 2016-08-22T22:38:33Z | 39,089,995 | <p>The regex <code>r'(A|B)'</code> will test first try to match A, and only if that fails will it try to match B (<a href="https://docs.python.org/3/library/re.html#regular-expression-syntax" rel="nofollow">docs</a>)</p>
<p>So the regex <code>([^"]|(\\\")</code> will first try to match a non-quote, and if that fails i... | 0 | 2016-08-22T23:02:14Z | [
"python",
"regex"
] |
Why do these two python regexes produce different results? | 39,089,760 | <pre><code>>>> re.match(r'"([^"]|(\\\"))*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"'
>>> re.match(r'"((\\\")|[^"])*"', r'"I do not know what \"A\" is"').group(0)
'"I do not know what \\"A\\" is"'
</code></pre>
<p>These two regexes are intended to be looking for quoted str... | 1 | 2016-08-22T22:38:33Z | 39,090,086 | <p>What you say is true, the order is different. And something else is different.<br>
The first one <code>"([^"]|(\\\"))*"</code> will match an escape, making it<br>
match <code>"asdf\"</code>sde" while the other one doesn't. </p>
<p>Also if you have to handle escape quote, you have to handle escapes as well. So, nei... | 2 | 2016-08-22T23:12:12Z | [
"python",
"regex"
] |
Running time analysis of the loops | 39,089,761 | <p>Consider following loops:</p>
<pre><code>def func1(xs, ys, zs):
for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>The running time should take <code>size of xs * (size of ys + size of zs)</code>, which could be written in big-o notation as <code>O(X) * (... | 1 | 2016-08-22T22:38:40Z | 39,089,921 | <p>You want to use <code>O(x * (y + x))</code> instead of <code>O(X) * (O(Y) + O(Z))</code> (where x is length of X, y is length of Y, etc) to describe complexity of your first loop (O should "wrap" the whole expression)</p>
<p>Why?</p>
<p>Assume that f(x) is function that returns exact number of actions required to ... | 0 | 2016-08-22T22:55:05Z | [
"python",
"algorithm"
] |
Running time analysis of the loops | 39,089,761 | <p>Consider following loops:</p>
<pre><code>def func1(xs, ys, zs):
for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>The running time should take <code>size of xs * (size of ys + size of zs)</code>, which could be written in big-o notation as <code>O(X) * (... | 1 | 2016-08-22T22:38:40Z | 39,090,124 | <p>You are measuring how long the for loops themselves take to execute, not the imaginary statement inside the loops.</p>
<p>When your loops are structured like this:</p>
<pre><code>for x in xs:
for y in ys:
pass
for z in zs:
pass
</code></pre>
<p>Consider how many times each list is iterate... | 2 | 2016-08-22T23:16:26Z | [
"python",
"algorithm"
] |
Python read named PIPE | 39,089,776 | <p>I have a named pipe in linux and i want to read it from python. The problem is that the python process 'consumes' one core (100%) continuously. My code is the following:</p>
<pre><code>FIFO = '/var/run/mypipe'
os.mkfifo(FIFO)
with open(FIFO) as fifo:
while True:
line = fifo.read()
</code></pre>
<p>I wa... | 0 | 2016-08-22T22:40:19Z | 39,089,792 | <p>In typical UNIX fashion, <code>read(2)</code> returns 0 bytes to indicate end-of-file which can mean:</p>
<ul>
<li>There are no more bytes in a file</li>
<li>The other end of a socket has shutdown the connection</li>
<li>The writer has closed a pipe</li>
</ul>
<p>In your case, <code>fifo.read()</code> is returning... | 2 | 2016-08-22T22:41:52Z | [
"python",
"linux",
"named-pipes"
] |
3 tables many to many how to create relationship | 39,089,863 | <p>I have tables name category, post and user.
Users can follow categories</p>
<blockquote>
<p>users are relationship many to many with categories
posts are relationship many to many with categories
users are relationship one to many posts
Now I want to get all posts from categories in which categories has f... | -4 | 2016-08-22T22:48:55Z | 39,094,935 | <p>So if I understand you right:</p>
<ul>
<li>You have an entity User. This user is categorized by several
categories. And a category has several Users too. </li>
<li>Also your entity Post is categorized by several categories and vice
versa.</li>
<li>And a user can make several posts and a post can belong to severa... | 0 | 2016-08-23T07:29:31Z | [
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to traverse the files in a directory and sub-directories in python | 39,089,872 | <p>I have scenario to process the files in python</p>
<p>my process tree structure is like</p>
<pre><code>dirctory
.
...subdir1
.
....sub-sub-dir1
.
. ..file1
</code></pre>
<ol>
<li><p>First I need to go the subdir1 and read one by one sub-sub-dirs (1 to n) and get the file from the s... | -2 | 2016-08-22T22:49:45Z | 39,090,067 | <p>Something like that:</p>
<pre><code>directory_dict = dict()
# Create the list of the sub_directories
dir_list = [sub_path for sub_path in os.listdir(given_path) if os.path.isdir(given_path+'/'+sub_path)]
# Loop into the list of sub_directories
for sub_dir in dir_list:
# Create an empty dict to store the infor... | 1 | 2016-08-22T23:10:11Z | [
"python",
"python-2.7"
] |
return statement vs. print statement? | 39,089,877 | <p>Can someone explain why this code only prints 6? :)</p>
<pre><code>def func(x):
result = 0
for i in range(x):
result = result + i
return result
print(func(4))
</code></pre>
| -4 | 2016-08-22T22:50:29Z | 39,089,961 | <p>First of all, since your code isn't formatted right in the question and I can't edit it due to a pending edit (which I bet fixes it), I'm going to assume your code is supposed to look like this:</p>
<pre><code>def func(x):
result = 0
for i in range(x):
result = result + i
return result
print(fu... | 0 | 2016-08-22T22:59:16Z | [
"python",
"printing",
"return"
] |
Most effective way to compile lots of information from different websites | 39,089,907 | <p>My problem is at work I have to click on a link to a website, then copy the company name, company telephone number and company address to an excel spreadsheet, each one in a different column. This information is in the same place on every website and is just time consuming as I have to click each link and then copy ... | -1 | 2016-08-22T22:53:43Z | 39,089,958 | <p>You can use <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> in combination with requests/urllib to scrape and parse the source code of the website.</p>
<p>Then you can use <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">Openpyxl</a> to write the data in... | 1 | 2016-08-22T22:59:06Z | [
"python"
] |
Most effective way to compile lots of information from different websites | 39,089,907 | <p>My problem is at work I have to click on a link to a website, then copy the company name, company telephone number and company address to an excel spreadsheet, each one in a different column. This information is in the same place on every website and is just time consuming as I have to click each link and then copy ... | -1 | 2016-08-22T22:53:43Z | 39,089,974 | <p>I have used the Beautiful Soup Python library for this type of work before. It organizes all the HTML code in a way that you can extract whatever data you want from it easily. You can see an example here: <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow">https://www.crummy.com/software/... | 0 | 2016-08-22T23:00:17Z | [
"python"
] |
Why am I getting an empty list as the answer? | 39,089,930 | <p>I am supposed to be printing out all values for r (which should be a list of 5 values) but for some reason I am getting an empty list [ ] as the answer. All of the inputs to the function are single values except for the lst variable, which is a list of 5 values. Any idea on why I am getting an empty list? All of the... | -1 | 2016-08-22T22:55:32Z | 39,090,000 | <pre><code> ...
F = [(self.T-self.T0)*self.m*self.Cp/Qt-x for x in self.lst]
self.m = solve(F,self.m)
return self.m
</code></pre>
<p>This is most probably a math problem, not a code problem. Print the value of <code>F</code> and check that it really has a solution that <code>solve()</code> should return... | 2 | 2016-08-22T23:02:57Z | [
"python",
"sympy"
] |
Websocket: javascript as client and python as server, and web host on Linux | 39,090,006 | <p>I need to build a website in which Javascript is used as the client language to communicate with a python server over websockets. The website needs to be hosted on Linux. For now, I'm using command <code>python -m SimpleHTTPServer</code> to build a simple server, and the server is also on the Linux and using python.... | -4 | 2016-08-22T23:03:41Z | 39,090,351 | <p>Assuming that your python websocket server is up an running. You can connect with it through your website through either html5:</p>
<pre><code>socket= new WebSocket('ws://www.example.com:8000/somesocket');
socket.onopen= function() {
socket.send('hello');
};
socket.onmessage= function(s) {
alert('got reply ... | 0 | 2016-08-22T23:49:58Z | [
"javascript",
"python",
"websocket",
"server",
"tcp-ip"
] |
Upgrade packages with pip from inside code | 39,090,071 | <p>I saw an older question, suggesting to use pip.main(package), however this does not <em>upgrade</em> a package. I could not find anything. Thanks in advance.</p>
| 3 | 2016-08-22T23:10:40Z | 39,090,123 | <p>Try <code>pip.main(['install', '--upgrade', package])</code> instead. <code>pip.main</code> just takes arguments exactly like the command line version.</p>
| 3 | 2016-08-22T23:16:03Z | [
"python",
"python-3.x",
"pip"
] |
python, mongoengine - do like/regex search | 39,090,178 | <p>I know I can do a glob-type search on mongodb:</p>
<pre><code>db.person.find({ name: /*.bob.*/ })
</code></pre>
<p>or </p>
<pre><code>db.person.find({ name: { $regex: '*.bob.*' }})
</code></pre>
<p>How do I do this with mongoengine without using a raw query (which is apparently the only way based on my searche... | 0 | 2016-08-22T23:24:10Z | 39,133,617 | <p>It looks like you can do it this way:</p>
<pre><code>import re
regex = re.compile('.*bob.*')
Person.objects(name=regex)
</code></pre>
| 0 | 2016-08-24T21:53:52Z | [
"python",
"mongoengine"
] |
Calling xlwings from Excel "No module named..." Error | 39,090,252 | <p>I'm trying to learn the ropes of starting a Python script from Excel VBA using xlwings 0.9.2. According to the docs, I need to change the <code>PYTHONPATH</code> to the path for my py file. I've seen several versions of this question, and various answers, but none have addressed my specific scenario. I have a basic... | 1 | 2016-08-22T23:35:23Z | 39,095,131 | <p>You have two errors: You need to import your module without the <code>.py</code> ending: </p>
<pre><code>Sub macro1()
RunPython ("import module1; module1.run_all()")
End Sub
</code></pre>
<p>And it's <code>xw.Book.caller()</code> instead of <code>wb.Book.caller()</code>.</p>
| 0 | 2016-08-23T07:38:55Z | [
"python",
"vba",
"xlwings"
] |
Calling xlwings from Excel "No module named..." Error | 39,090,252 | <p>I'm trying to learn the ropes of starting a Python script from Excel VBA using xlwings 0.9.2. According to the docs, I need to change the <code>PYTHONPATH</code> to the path for my py file. I've seen several versions of this question, and various answers, but none have addressed my specific scenario. I have a basic... | 1 | 2016-08-22T23:35:23Z | 39,474,566 | <p>I had the same error. Solved by downgrade to xlwings version 0.7.2</p>
| 0 | 2016-09-13T16:08:54Z | [
"python",
"vba",
"xlwings"
] |
How to make application urls appear throughout the project? | 39,090,298 | <p>My templates don't see URLs which are in my application, in code:</p>
<pre><code>urls.py in project:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('search.urls')),
url(r'^accounts/', include('accounts.urls')),
]
urls.py in application:
urlpatterns = [
... | 2 | 2016-08-22T23:42:15Z | 39,090,414 | <p>Need to terminate your regex strings with $, i.e,</p>
<pre><code>r'^admin/$',
</code></pre>
| 0 | 2016-08-22T23:59:36Z | [
"python",
"django"
] |
How to allow many responses for if statement and replies? | 39,090,322 | <p>I am making a sort of Siri program. But I'm not sure how to allow various responses, and various replies at random.</p>
<p>Does it involve dictionaries or a simpler alternative, or a random function? </p>
<pre><code>if greeting == "Hello", "Hi", "Hey":
print("Hello", "Hi", "Hey")
else:
print("I'm not sure ... | -1 | 2016-08-22T23:45:20Z | 39,090,408 | <p>To pick a random response you can use <code>random.choice</code>, which selects a random element from a list:</p>
<pre><code>import random
if greeting in ["Hello", "Hi", "Hey"]:
response = random.choice(["Hello", "Hi", "Hey"])
print(response)
else:
print("I'm not sure what you said there")
</code></pre... | 1 | 2016-08-22T23:58:31Z | [
"python"
] |
How to allow many responses for if statement and replies? | 39,090,322 | <p>I am making a sort of Siri program. But I'm not sure how to allow various responses, and various replies at random.</p>
<p>Does it involve dictionaries or a simpler alternative, or a random function? </p>
<pre><code>if greeting == "Hello", "Hi", "Hey":
print("Hello", "Hi", "Hey")
else:
print("I'm not sure ... | -1 | 2016-08-22T23:45:20Z | 39,090,412 | <p>If you're talking about allowing multiple inputs from the user, that would go something like this:</p>
<pre><code>if greeting in ["hello", "hi", "hey"]:
# do stuff
</code></pre>
<p>If you also want to provide a random response back to the user, you could do something like this:</p>
<pre><code>if greeting in [... | 0 | 2016-08-22T23:59:24Z | [
"python"
] |
Handling "with open()" errors? | 39,090,358 | <p>So I got this code here:</p>
<pre><code>with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
</code></pre>
<p>How can I add a function that tells the user that the file "file.txt" was not found in this directory? I get an error which is called <code>IOError [Errno 2] No such file in this dire... | -2 | 2016-08-22T23:50:30Z | 39,090,377 | <p>You use a <code>try</code> statement. This is called Exception Handling. See <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">Python docs</a> to learn more.</p>
| 0 | 2016-08-22T23:53:36Z | [
"python"
] |
Handling "with open()" errors? | 39,090,358 | <p>So I got this code here:</p>
<pre><code>with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
</code></pre>
<p>How can I add a function that tells the user that the file "file.txt" was not found in this directory? I get an error which is called <code>IOError [Errno 2] No such file in this dire... | -2 | 2016-08-22T23:50:30Z | 39,090,379 | <p>You need to catch the exception.</p>
<pre><code>try:
with open(os.path.join(Path, 'ki/lol/kappa/file.txt'), 'r') as masterfile:
print "yay"
except IOError:
print "Oops, couldn't open the file"
</code></pre>
| 0 | 2016-08-22T23:53:37Z | [
"python"
] |
Scientific notation in python | 39,090,359 | <p>Hi I know that to print a number in a scientific notation I can do the following</p>
<pre><code>"%.3e" % 123.456
</code></pre>
<p>will give</p>
<pre><code>1.234e+02
</code></pre>
<p>however how can I obtain </p>
<pre><code>12.34e+01?
</code></pre>
| 2 | 2016-08-22T23:50:41Z | 39,090,443 | <p>For clarification, most usages of <a href="https://en.wikipedia.org/wiki/Scientific_notation" rel="nofollow">Scientific Notation</a> refers to <a href="https://en.wikipedia.org/wiki/Scientific_notation#Normalized_notation" rel="nofollow">Normalized Notation</a> which requires that the leading number be at least 1 bu... | 3 | 2016-08-23T00:05:06Z | [
"python"
] |
How to parse raw HTTP request in Python 3? | 39,090,366 | <p>I am looking for a native way to parse an http request in Python 3.</p>
<p><a href="http://stackoverflow.com/questions/4685217/parse-raw-http-headers">This question</a> shows a way to do it in Python 2, but uses now deprecated modules, (and Python 2) and I am looking for a way to do it in Python 3.</p>
<p>I would ... | 1 | 2016-08-22T23:52:13Z | 39,090,882 | <p>Each one of those field names should be delimited by carriage return then newline, and then the field name and value are delimited by a colon. So assuming you already have the response as a string, it <em>should</em> be as easy as:</p>
<pre><code>fields = resp.split("\r\n")
fields = fields[1:] #ignore the GET / HTT... | 0 | 2016-08-23T01:13:08Z | [
"python",
"python-3.x",
"http"
] |
How to parse raw HTTP request in Python 3? | 39,090,366 | <p>I am looking for a native way to parse an http request in Python 3.</p>
<p><a href="http://stackoverflow.com/questions/4685217/parse-raw-http-headers">This question</a> shows a way to do it in Python 2, but uses now deprecated modules, (and Python 2) and I am looking for a way to do it in Python 3.</p>
<p>I would ... | 1 | 2016-08-22T23:52:13Z | 39,091,087 | <p>You could use the <a href="https://docs.python.org/3/library/email.message.html#email.message.Message" rel="nofollow"><code>email.message.Message</code></a> class from the <a href="https://docs.python.org/3/library/email.html" rel="nofollow"><code>email</code></a> module in the standard library. </p>
<p>By modifyin... | 1 | 2016-08-23T01:42:57Z | [
"python",
"python-3.x",
"http"
] |
Rolling Time Series AR(1) Regression Estimation in Python dataframe and MovingOLS? | 39,090,442 | <p>2 questions here:</p>
<p>First. I have a dataframe like this:</p>
<pre><code> Date Y X1 X2 X3
22 2004-05-12 9.348158e-09 0.000081 0.000028 0.000036
23 2004-05-13 9.285989e-09 0.000073 0.000081 0.000097
24 2004-05-14 9.732308e-09 0.000085 0.00... | 0 | 2016-08-23T00:05:04Z | 39,091,166 | <p>You are trying to model your samples with an equation. This equation has many parameters (called estimators). The value of the estimator will change depending on the training data that is used to calculate it. When you are estimating such model parameters using cross-validation on your data this means that you will ... | 0 | 2016-08-23T01:54:22Z | [
"python",
"pandas",
"dataframe"
] |
Json add additional payload in the request | 39,090,448 | <p>I am very new to Python. I run into this problem and hope you can help. Let me explain what I try to do and let me know if I am confusing you.</p>
<p>I have this Python script and it works fine with creating an event.</p>
<pre><code># Set the request parameters
url = 'https://outlook.office365.com/api/v1.0/me/even... | 0 | 2016-08-23T00:06:12Z | 39,090,601 | <p>It appears that you need to merge the data; for example you can add another key to your data dictionary called <code>Attachments</code> which contains an array of dictionaries and merge them that way; then serialize your data to JSON.
You don't need <code>json_payloadAttachment</code>.</p>
<pre><code>...
data["Atta... | 1 | 2016-08-23T00:31:16Z | [
"python",
"json"
] |
a python library that accepts some text, and replaces phone numbers, names, and so on with tokens | 39,090,495 | <p>I need a python library that accepts some text, and replaces phone numbers, names, and so on with tokens. Example:</p>
<p>Input: Please call Robert on 0430013454 to discuss this further.</p>
<p>Output: Please call <em>NAME</em> on <em>PHONE</em> to discuss this further.</p>
<p>In other words I need to take a sent... | -6 | 2016-08-23T00:15:19Z | 39,091,018 | <p>Not really sure about name recognition. However, if you know the names that you would be looking for it would be easy. You could have a list of all of the names that you're looking for and check to see if each one is in the string and if so just use <code>string.replace</code>. If the names are random you could mayb... | 0 | 2016-08-23T01:32:32Z | [
"python",
"python-2.7",
"pyparsing"
] |
a python library that accepts some text, and replaces phone numbers, names, and so on with tokens | 39,090,495 | <p>I need a python library that accepts some text, and replaces phone numbers, names, and so on with tokens. Example:</p>
<p>Input: Please call Robert on 0430013454 to discuss this further.</p>
<p>Output: Please call <em>NAME</em> on <em>PHONE</em> to discuss this further.</p>
<p>In other words I need to take a sent... | -6 | 2016-08-23T00:15:19Z | 39,091,553 | <p>As Harrison pointed out, nltk has named entity recognition, which is what you want for this task. <a href="https://gist.github.com/onyxfish/322906" rel="nofollow">Here</a> is a good sample to get you started.</p>
<p>From the site:</p>
<pre><code>import nltk
sentences = nltk.sent_tokenize(text)
tokenized_sentence... | 1 | 2016-08-23T02:48:54Z | [
"python",
"python-2.7",
"pyparsing"
] |
How to get z to show up properly in Pyplot math mode | 39,090,559 | <p>I'm trying to create an axis label for a graph made using matplotlib.pyplot, and I'm using math mode for subscripts and superscripts. However, whenever I try to put a z inside math mode, it instead comes out as an approximately equals sign. Anyone know how to fix it? It shows up normally if I put it outside math ... | 0 | 2016-08-23T00:24:57Z | 39,090,681 | <p>It's not really an approximately-equals sign, it's just an italic z whose diagonal stroke is invisible in the font and size you're using. Making it bigger clarifies things:</p>
<pre><code>plt.ylabel(r"$I_\nu \ (W m^{-2} \! {Hz}^{-1} \! sr^{-1})$", fontsize="x-large")
</code></pre>
| 0 | 2016-08-23T00:41:39Z | [
"python",
"matplotlib",
"tex"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>... | 1 | 2016-08-23T00:41:52Z | 39,090,775 | <p>You could load each individual dictionary with the missing keys and give them null values. So it might look like this</p>
<pre><code>for items in list:
for x in ['a','b','c','d']:
if x not in item:
item[x] = ""
</code></pre>
<p>Now that each dictionary has the same keys, you should be able ... | 2 | 2016-08-23T00:55:05Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>... | 1 | 2016-08-23T00:41:52Z | 39,090,778 | <p>You can append each JSON file to a list and then create dataframes and concatenate.</p>
<pre><code>a = {"a": 1, "c": 2}
b = {"b": 5, "d": 3}
c = {"a": 6, "b": 7}
data = [a, b, c]
>>> pd.concat([pd.DataFrame(s, index=[0]) for s in data]).reset_index()
a b c d
0 1 NaN 2 NaN
1 NaN 5 NaN 3
2... | 2 | 2016-08-23T00:55:51Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>... | 1 | 2016-08-23T00:41:52Z | 39,090,794 | <p>Assuming you know all the possible field names ahead of time <a href="https://docs.python.org/3.5/library/csv.html#csv.DictWriter" rel="nofollow"><code>csv.DictWriter</code></a> already comes with a solution for this, use the <code>restval</code> argument to the constructor:</p>
<blockquote>
<p>If the row read ha... | 2 | 2016-08-23T00:57:15Z | [
"python",
"json",
"csv"
] |
JSON to CSV in python: each JSON file has different keys | 39,090,683 | <p>I'm trying to write many JSON files to a CSV file. Each JSON file has several keys, but different files have different keys. Here are three JSON files as an example.</p>
<p>file A:</p>
<pre><code>{"a": 1, "c": 2}
</code></pre>
<p>file B: </p>
<pre><code>{"b": 5, "d": 3}
</code></pre>
<p>file C:</p>
<pre><code>... | 1 | 2016-08-23T00:41:52Z | 39,090,816 | <p>This works :</p>
<pre><code>csv_separator = ';'
data = [{"a": 1, "c": 2},
{"b": 5, "d": 3},
{"a": 6, "b": 7}]
headers = sorted(list(set(sum([list(l.keys()) for l in data], []))))
with open('output.csv', 'w+') as f:
f.write(csv_separator.join(headers))
for l in data:
line_elements = []
for... | 0 | 2016-08-23T01:00:39Z | [
"python",
"json",
"csv"
] |
about tree.DecisionTreeClassifier adjust class_weight | 39,090,706 | <p>I have a unbalanced dataset, there are totally 209 rows (samples) which include 166 rows (class0) and 43 rows (class1).
Therefore, I want to solve the unbalanced problem,
then I used the python instruction to adjust the class weight.</p>
<pre><code>tree.DecisionTreeClassifier(max_depth=4,class_weight={1:3.8})
clf.f... | 0 | 2016-08-23T00:45:27Z | 39,091,079 | <p>Class 1 doesn't "sample the digits after the decimal." I'm not sure what that even means. Instead, the samples are weighted, so the value is 43*3.8 = 163.4</p>
| 0 | 2016-08-23T01:42:21Z | [
"python",
"tree",
"classification"
] |
Webpage contained within one dynamic page, unable to use driver interactions with Selenium (Python) | 39,090,768 | <p>The homepage for the web application I'm testing has a loading screen when you first load it, then a username/password box appears. It is a dynamically generated UI element and the cursor defaults to being inside the username field.</p>
<p>I looked around and someone suggested using action chains. When I use acti... | 1 | 2016-08-23T00:53:52Z | 39,091,571 | <p>Actually if there is loading progress bar appears in you login page, You should try using <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>WebDriverWait</code></a> to wait until element is getting visible as below :-</p>
<pre><code>from selenium import webdriver
from se... | 1 | 2016-08-23T02:50:41Z | [
"python",
"selenium",
"testing"
] |
Webpage contained within one dynamic page, unable to use driver interactions with Selenium (Python) | 39,090,768 | <p>The homepage for the web application I'm testing has a loading screen when you first load it, then a username/password box appears. It is a dynamically generated UI element and the cursor defaults to being inside the username field.</p>
<p>I looked around and someone suggested using action chains. When I use acti... | 1 | 2016-08-23T00:53:52Z | 39,091,712 | <p>As suggested by saurabh , use
1 self.wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, OR.Sub_categories)))</p>
<p>Else put a sleep and see however it is not advisable to use that, may be the xpath you have changes at the time of page load</p>
| 0 | 2016-08-23T03:09:39Z | [
"python",
"selenium",
"testing"
] |
How can I make a python decorator function to reschedule a function in n seconds using asyncio? | 39,090,875 | <p>This is my current code:</p>
<pre><code>import asyncio
import serial
def repeat(seconds):
def wrap(func):
def decorated(*args):
loop = asyncio.get_event_loop()
loop.call_at(loop.time() + seconds, decorated, *args)
print('scheduled')
func(*args)
... | 3 | 2016-08-23T01:12:09Z | 39,098,000 | <p>Your code is fine (except as noted you should return func's result inside decorator), I improved it a bit.</p>
<p>It's easier to see and test with synthetic example:</p>
<pre><code>import asyncio
import functools
def repeat(seconds):
def wrap(func):
@functools.wraps(func) # see http://stackoverflow.... | 1 | 2016-08-23T09:57:48Z | [
"python",
"decorator",
"python-asyncio"
] |
Flask config import fails on Heroku | 39,090,989 | <p>My application works fine when run locally (with <code>flask run</code>), and it also works on Heroku when the <code>app.config.from_object(config.DevelopmentConfig)</code> is commented out. However, gunicorn can't find the config file when deployed on Heroku. (I can't try gunicorn locally on my Windows machine.)</p... | -1 | 2016-08-23T01:27:44Z | 39,108,483 | <p>I changed the config file's name from to <code>config_app.py</code> and leave the file in the project's root and it runs fine, both locally and on heroku. (Don't forget to modify <code>app.config.from_object()</code> accordingly.)</p>
<p>I'm not sure, but it seems that the error suggestion "duplicated package or mo... | 0 | 2016-08-23T18:38:48Z | [
"python",
"heroku",
"flask"
] |
Matplotlib graph expand the x axis | 39,091,030 | <p>I have the following <a href="http://i.stack.imgur.com/cFAL2.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFAL2.png" alt="graph"></a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468] ... | 0 | 2016-08-23T01:34:40Z | 39,091,155 | <blockquote>
<p>1)How i can delete the last gap as shown after 2^12? </p>
</blockquote>
<p>Set the limits explicitly, e.g.:</p>
<pre><code>plt.xlim(2**5.8, 2**12.2)
</code></pre>
<blockquote>
<p>2)How i can spread more the values in the x axis such that the first two values are not overlapped?</p>
</blockquote>
... | 1 | 2016-08-23T01:52:26Z | [
"python",
"matplotlib"
] |
Matplotlib graph expand the x axis | 39,091,030 | <p>I have the following <a href="http://i.stack.imgur.com/cFAL2.png" rel="nofollow"><img src="http://i.stack.imgur.com/cFAL2.png" alt="graph"></a>.</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468] ... | 0 | 2016-08-23T01:34:40Z | 39,091,184 | <p>1.Using <code>autoscale</code>, specify the axes, or alternately you can use <code>plt.axis('tight')</code> for both the axes. 2.Using log scaled x-axis. Code below:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
... | 0 | 2016-08-23T01:57:32Z | [
"python",
"matplotlib"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the ... | 2 | 2016-08-23T01:41:04Z | 39,091,388 | <p>Here is an approach that uses lazy evaluation:</p>
<pre><code>>>> def f(x):
... return 2**x
...
>>> def g(x):
... return x*2
...
>>> [f(x) for x in range(1,10)]
[2, 4, 8, 16, 32, 64, 128, 256, 512]
>>> [g(x) for x in range(1,10)]
[2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>... | 1 | 2016-08-23T02:25:41Z | [
"python",
"comparison",
"lexicographic"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the ... | 2 | 2016-08-23T01:41:04Z | 39,091,422 | <p>Try this (the extra parameters to the function are just for illustration purposes):</p>
<pre><code>import itertools
def f(a, x):
print "lazy eval of {}".format(a)
return x
a = [lambda: f('a', 1), lambda: f('b', 3), lambda: f('c', 3)]
b = [lambda: f('d', 1), lambda: f('e', 2), lambda: f('f', 2)]
c = [lambd... | 2 | 2016-08-23T02:31:11Z | [
"python",
"comparison",
"lexicographic"
] |
Lazy evaluation of variables | 39,091,071 | <p>I want to lexicographically compare two lists, but the values inside the list should be computed when needed. For instance, for these two lists</p>
<pre><code>a = list([1, 3, 3])
b = list([1, 2, 2])
(a < b) == False
(b < a) == True
</code></pre>
<p>I'd like the values in the list to be functions and in the ... | 2 | 2016-08-23T01:41:04Z | 39,135,032 | <p>I did some testing and found that @juanpa's answer and the version in my update are the fastest versions:</p>
<pre><code>import random
import itertools
import functools
num_rows = 100
data = [[random.randint(0, 2) for i in xrange(10)] for j in xrange(num_rows)]
# turn data values into functions.
def return_func(v... | 1 | 2016-08-25T00:44:21Z | [
"python",
"comparison",
"lexicographic"
] |
How to read data, apply a function and return the result with Django REST Framework? | 39,091,108 | <p>Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15.</p>
<p>Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the serv... | 0 | 2016-08-23T01:46:28Z | 39,091,286 | <p>The <a href="https://docs.djangoproject.com/en/1.9/topics/http/urls/" rel="nofollow">URL dispatcher</a> would capture the value and pass it to the view. Something like this may work:</p>
<p><code>URLconf</code></p>
<pre><code>from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^regres... | 0 | 2016-08-23T02:11:30Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
How to read data, apply a function and return the result with Django REST Framework? | 39,091,108 | <p>Consider a simple task to calculate "y = ax + b", where "a" and "b" are given by the model and "x" is given by the user through an API request, like http://someurl.com/api/15, where x=15.</p>
<p>Usually, the API would return "a" and "b" in a JSON format. But, instead, I want to solve this equation on the serv... | 0 | 2016-08-23T01:46:28Z | 39,091,287 | <p>Use <a href="http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield" rel="nofollow">Serializer Method Field</a></p>
<pre><code>from rest_framework import serializers
from .models import SimpleEquation
class SimpleEquationSerializer(serializers.ModelSerializer):
y = serializers.Serializer... | 1 | 2016-08-23T02:11:32Z | [
"python",
"json",
"django",
"django-rest-framework"
] |
How to check if Django object is None in javascript? | 39,091,167 | <p>How do you check if a Django object is None in js?</p>
<p>I currently have a variable <code>person</code> that stores a Django object or None. In my js I have:</p>
<pre><code>if ({{person}} != None) {
execute_function({{person}})
}
</code></pre>
<p>What seems to be the issue here?</p>
| 1 | 2016-08-23T01:54:24Z | 39,094,118 | <p>This worked for me:</p>
<pre><code>{% if person != None %}
var p = ...
...
{% endif %}
</code></pre>
| 0 | 2016-08-23T06:46:10Z | [
"javascript",
"python",
"django"
] |
How to check if Django object is None in javascript? | 39,091,167 | <p>How do you check if a Django object is None in js?</p>
<p>I currently have a variable <code>person</code> that stores a Django object or None. In my js I have:</p>
<pre><code>if ({{person}} != None) {
execute_function({{person}})
}
</code></pre>
<p>What seems to be the issue here?</p>
| 1 | 2016-08-23T01:54:24Z | 39,110,589 | <p>John Smiths answer makes the most sense, check it in Django's templates.
Actually better would be: </p>
<pre><code>{% if person %}
execute function
{% endif%}
</code></pre>
<p>If you need to check it using JavaScript, JavaScript uses null instead of None, so assuming that the JavaScript code is also in the Dj... | 3 | 2016-08-23T20:59:52Z | [
"javascript",
"python",
"django"
] |
How to import python module from docker | 39,091,186 | <p>I made a docker image contains nginx, uwsgi and some python module, using volumes out the docker to develop code.</p>
<p>So how should I use python environment from docker when coding?</p>
| -1 | 2016-08-23T01:57:56Z | 39,093,316 | <p>I'm not sure what you are trying to do. But here are some tips, that may help you.</p>
<ol>
<li>Python libraries for working with docker from python
<ul>
<li><a href="https://github.com/docker/docker-py" rel="nofollow">https://github.com/docker/docker-py</a> </li>
<li><a href="https://github.com/deepgram/sidomo" r... | 1 | 2016-08-23T05:52:55Z | [
"python",
"django",
"docker"
] |
Wrong output in Implementing Kruskal Algorithm in Python | 39,091,191 | <p>I am working on Krusal's Algorithm. However I failed to get the right output. I don't know where I made mistaks.</p>
<p>Here is my code:</p>
<pre><code>parent = dict()
rank = dict()
def make_set(vertice):
parent[vertice] = vertice
rank[vertice] = 0
def find(vertice):
if parent[vertice] != vertice:
... | 0 | 2016-08-23T01:59:05Z | 39,092,248 | <p>at first glance, try this:</p>
<pre><code>edges = list(graph['edges'])
</code></pre>
<p>instead</p>
<pre><code>edges = sorted(graph['edges'], key=lambda e: e[2])
</code></pre>
| 0 | 2016-08-23T04:13:42Z | [
"python",
"graph-theory",
"minimum-spanning-tree",
"kruskals-algorithm"
] |
How does Chrome "Simplify Page"? | 39,091,221 | <p>I'm trying to implement this in Python and don't know where to start. My ultimate goal is to extract the title and body from news article such as:</p>
<p><a href="http://investorplace.com/2016/08/csco-stock-2-trades-cisco-systems-earnings/" rel="nofollow">http://investorplace.com/2016/08/csco-stock-2-trades-cisco-s... | -2 | 2016-08-23T02:02:38Z | 39,091,310 | <p>The <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with-python#t=20160823021300902437">Web Scraping Documentation</a> should give you some orientation.</p>
<p>Take a look at the <code>webpage source</code> and use <code>inspect element</code> in the items that you want!</p... | 1 | 2016-08-23T02:14:38Z | [
"python",
"google-chrome",
"web-scraping",
"beautifulsoup",
"scrapy"
] |
Why are some of the values of items' fields repeating in this Scrapy spider? | 39,091,239 | <p>When my spider runs on a url like <a href="http://211sepa.org/get-help/housing/" rel="nofollow">this</a>:</p>
<pre><code>def parse_subandtaxonomy(self, response):
item = response.meta['item']
for sub in response.xpath('//div[@class = "page-content"]/section'):
item['Subcategory'] = sub.xpath('h2/text()').extrac... | -1 | 2016-08-23T02:05:05Z | 39,099,493 | <p>It might be an issue with scopes. You should always try to create your item on the highest scope possible to prevent data retention, i.e. if the current <code>item</code> doesn't have <code>Taxonomy</code> field, the object will retain data from the previous loop cycle. That's why the code should have create new obj... | 0 | 2016-08-23T11:07:23Z | [
"python",
"python-3.x",
"scrapy",
"scrapy-spider"
] |
python parse XML with multiple elements and insert into sqlite | 39,091,279 | <p>I'm very new to python so please excuse me.. I have parsed an XML file and am inserting into sqlite just fine however I now need to get text value from multiple elements with the same name(channel-category) and insert into one sql column like</p>
<pre><code>somecategory1, somecategory2
</code></pre>
<p>here is wha... | 0 | 2016-08-23T02:09:52Z | 39,091,355 | <p>How about, instead of </p>
<pre><code>chncategory = elem.findtext("channel-category")
</code></pre>
<p>You use:</p>
<pre><code>In [5]: chncategory = ', '.join(map(lambda x: x.text, elem.findall("channel-category")))
In [6]: chncategory
Out[6]: 'somecategory1, somecategory2'
</code></pre>
| 0 | 2016-08-23T02:20:48Z | [
"python",
"xml",
"database",
"list",
"sqlite"
] |
Finding row that has number instersecting two columns | 39,091,301 | <p>Data has three columns. I need to find the row that has the number intersecting between second and third columns. For example, which row has number 15 between second and third column in the data below?</p>
<pre><code>a 1 5
b 7 10
c 13 17
d 20 24
</code></pre>
<p>The ideal result should be </p>
<pre>... | 0 | 2016-08-23T02:14:03Z | 39,091,372 | <p>You mean this?</p>
<pre><code>import pandas as pd
df = pd.DataFrame([('a', 1, 5), ('b', 7, 10), ('c', 13, 17), ('d', 20, 24)],
columns=['col1', 'col2', 'col3'])
df[(df.col2 < 15) & (df.col3 > 15)]
</code></pre>
<p>yields...</p>
<pre><code> col1 col2 col3
2 c 13 17
</code>... | 1 | 2016-08-23T02:23:42Z | [
"python",
"python-2.7",
"csv",
"pandas",
"intersection"
] |
Finding row that has number instersecting two columns | 39,091,301 | <p>Data has three columns. I need to find the row that has the number intersecting between second and third columns. For example, which row has number 15 between second and third column in the data below?</p>
<pre><code>a 1 5
b 7 10
c 13 17
d 20 24
</code></pre>
<p>The ideal result should be </p>
<pre>... | 0 | 2016-08-23T02:14:03Z | 39,091,437 | <p>Another approach, using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow">query</a>:</p>
<pre><code>In [7]: df
Out[7]:
tag start end
0 a 1 5
1 b 7 10
2 c 13 17
3 d 20 24
In [8]: df.query('start < 15 < end')
Out[8... | 0 | 2016-08-23T02:33:35Z | [
"python",
"python-2.7",
"csv",
"pandas",
"intersection"
] |
Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet? | 39,091,416 | <p>I'm working on a Django 1.8.2 project.</p>
<p>This project has multiple Django applications.</p>
<p>Application <code>app_a</code> has class <code>MyClassA</code> as follows:</p>
<pre><code>class MyClassA(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
@staticmethod
def m... | 1 | 2016-08-23T02:30:26Z | 39,093,981 | <p>In this case you will get an error only if you make a mistake in the manager function. I tried the same and it worked for me. but I got the same error when I made an error in the filter() .like MyClassA.objects.filter(a_field_not_in_the_model=None).</p>
<p>I think you have to re check your original code. check if y... | 0 | 2016-08-23T06:37:41Z | [
"python",
"django"
] |
Why does doing Django query cause: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet? | 39,091,416 | <p>I'm working on a Django 1.8.2 project.</p>
<p>This project has multiple Django applications.</p>
<p>Application <code>app_a</code> has class <code>MyClassA</code> as follows:</p>
<pre><code>class MyClassA(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
@staticmethod
def m... | 1 | 2016-08-23T02:30:26Z | 39,094,241 | <p>In Django you must not run queries at import time. (See <a href="https://docs.djangoproject.com/en/dev/ref/applications/#how-applications-are-loaded" rel="nofollow">here</a> for details.)</p>
<p>Because default argument values in Python are evaluated when the function is defined (as opposed to when it is called), y... | 1 | 2016-08-23T06:54:16Z | [
"python",
"django"
] |
Python2 - How to remove characters from output? | 39,091,442 | <p>I made this script that outputs the balance of a group of addresses. The output however comes in a list of one. How do I get python to extract the value from the list, so it doesn't show the ['']?</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://blockchain.info/xpub/xpub6BfKpqjTwvH... | 0 | 2016-08-23T02:34:00Z | 39,091,459 | <p>Try this:</p>
<pre><code>balance = tree.xpath('//*[@id="final_balance"]/font/span/text()')[0]
print balance
</code></pre>
<p>When you have a list <code>foo</code>, <code>foo[0]</code> gets the first element of <code>foo</code>. Since your list has only one element, that's the <em>only</em> element of <code>foo</c... | 1 | 2016-08-23T02:36:14Z | [
"python",
"json",
"python-2.7"
] |
Python2 - How to remove characters from output? | 39,091,442 | <p>I made this script that outputs the balance of a group of addresses. The output however comes in a list of one. How do I get python to extract the value from the list, so it doesn't show the ['']?</p>
<pre><code>from lxml import html
import requests
page = requests.get('https://blockchain.info/xpub/xpub6BfKpqjTwvH... | 0 | 2016-08-23T02:34:00Z | 39,091,462 | <pre><code>In [1]: balance
Out[1]: ['0.00622801 BTC']
In [2]: type(balance)
Out[2]: list
In [3]: ''.join(balance)
Out[3]: '0.00622801 BTC'
</code></pre>
| 0 | 2016-08-23T02:36:36Z | [
"python",
"json",
"python-2.7"
] |
How to get different number of ticks and labels in matplotlib? | 39,091,451 | <p>I can't work out how to reduce a number of tick labels in my plot while preserving the number of ticks. Is there a way to do it or can I only have as many ticks as the number of labels? Thanks!</p>
| 1 | 2016-08-23T02:35:41Z | 39,092,758 | <p>Set for some ticks empty tick labels. </p>
<pre><code># based on http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 6]
labels = ['Frogs', 'Hogs', '', 'Slogs']
plt.plot(x, y, 'ro')
# You can specify a rotation for the tick lab... | 1 | 2016-08-23T05:05:45Z | [
"python",
"matplotlib"
] |
How to get different number of ticks and labels in matplotlib? | 39,091,451 | <p>I can't work out how to reduce a number of tick labels in my plot while preserving the number of ticks. Is there a way to do it or can I only have as many ticks as the number of labels? Thanks!</p>
| 1 | 2016-08-23T02:35:41Z | 39,095,066 | <p>Just to answer my comment on Serenity's answer, here's how to get the numerical labels.</p>
<pre><code>x = range(100)
labels = []
for i in x:
if i % 10 == 0:
i=i
else:
i=' '
labels.append(i)
</code></pre>
<p>And this does the job.</p>
| 1 | 2016-08-23T07:35:48Z | [
"python",
"matplotlib"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL l... | 0 | 2016-08-23T02:35:44Z | 39,091,539 | <pre><code>if results.force_edl:
force_edl = results.force_edl
</code></pre>
<p>The reason why the assignment inside the above <code>if</code> doesn't take place is because:</p>
<pre><code>>>> results
Namespace(force_edl=False)
>>> results.force_edl
False
</code></pre>
<p><code>results.force_ed... | 2 | 2016-08-23T02:46:46Z | [
"python"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL l... | 0 | 2016-08-23T02:35:44Z | 39,091,603 | <p><code>results.force_edl</code> will always be <code>False</code>. You're updating the global variable after conditional checking, which will never be executed. And the global <code>force_edl</code> will still be undefined since you didn't assign any value to it when you declared.</p>
<p>Do something like the follow... | 0 | 2016-08-23T02:55:08Z | [
"python"
] |
argparse not taking default option | 39,091,452 | <p>Can anyone tell me why the default option is being taken below?</p>
<h3>Code:</h3>
<pre><code>import argparse
parser = argparse.ArgumentParser(description='SCRIPT')
parser.add_argument('-fe','--force_edl',action='store',dest='force_edl',choices=['True', 'False'], default = False,help='<Required> Enable EDL l... | 0 | 2016-08-23T02:35:44Z | 39,091,687 | <p>The error occurred because the variable force_edl was just "<strong>DECLARED</strong>" but not "<strong>DEFINED</strong>" with some value.</p>
<p>It gets assigned in your <code>if</code> block only but that <code>if</code> block won't execute since the value by default will be a false value and hence you get this e... | 0 | 2016-08-23T03:05:14Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.