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 |
|---|---|---|---|---|---|---|---|---|---|
in Python, are statements objects? | 39,570,317 | <p>As far as I understand, everything in python is an object or a reference.
For example: in <code>x = 1</code>, <code>x</code> is a reference to the integer object <code>1</code>. If I write <code>print type(x)</code>, then Python will tell me the object that x is referencing is an integer. </p>
<p>So what about sta... | 0 | 2016-09-19T09:58:05Z | 39,570,581 | <p>When they say "everything is an object or a reference" they are referring specifically to data. So this naturally does not apply to statements. Of course, all expressions will result in data. For example <code>a == b</code> is <code><class 'bool'></code> because it is an expression.</p>
<p>There are some lang... | 2 | 2016-09-19T10:12:00Z | [
"python",
"object",
"if-statement",
"reference",
"conditional"
] |
Naming conventions for Python scripts without classes | 39,570,320 | <p>I've searched around for an answer specific to my use case, but can't find one, so apologies if this specific case has been answered before.</p>
<p>I run a number of isolated scripts which perform different functions, like assessing specific data from APIs and sending email alerts. Whilst the scripts themselves use... | 0 | 2016-09-19T09:58:09Z | 39,571,484 | <p>This is the only reference I know about module names (scripts are themselves modules so it applies to them too):</p>
<blockquote>
<p>Modules should have short, all-lowercase names. Underscores can be
used in the module name if it improves readability.</p>
</blockquote>
<p><a href="https://www.python.org/dev/pe... | 0 | 2016-09-19T10:56:49Z | [
"python",
"naming-conventions"
] |
applying a mask on a nested numpy array - numpy - python | 39,570,335 | <p>a bit embarassing to ask since the heavy documentation on Numpy but I was stuck doing this simple task, that is getting all the records for which a mask is true in a nested numpy representation (equivalent to the <code>dataframe.loc[cond]</code> in <code>pandas</code>):</p>
<pre><code>import numpy as np
a1 = np.arr... | 1 | 2016-09-19T09:58:45Z | 39,570,777 | <p>I believe you're simply missing the indexes of the other dimension:</p>
<pre><code>combination[combination[3] == 'True']
</code></pre>
<p>should be</p>
<pre><code>combination[:, combination[3] == 'True']
</code></pre>
<p>Note the colon.</p>
<p>This yields a new ndarray indexed over all of the first dimension an... | 2 | 2016-09-19T10:21:13Z | [
"python",
"arrays",
"numpy",
"indexing",
"slice"
] |
Install opencv-python under python3 ubunto 14.04 | 39,570,381 | <p>I want to use opencv under python 3 in Ubunto 14.04. I plan to use the PyCharm IDE to develop my program. </p>
<p>Inside PyCharm I choose, I set:</p>
<p><strong>File/Settings/Project:HelloWorld/Project Interpreter/3.4.3(/usr/bin/python3.4)</strong> </p>
<p>Python 3.4.3 is the default version of python in Ubunto ... | 1 | 2016-09-19T10:01:38Z | 39,570,487 | <p>As far as I can see from querying pip (using <code>pip search opencv</code>) there is no package called <code>opencv-python</code> I think the one you're looking for is <code>pyopencv</code>.</p>
<p><a href="http://stackoverflow.com/questions/25215102/installing-opencv-for-python-on-ubuntu-getting-importerror-no-mo... | 1 | 2016-09-19T10:07:06Z | [
"python",
"opencv"
] |
Using Python regex find and replace to add HTML tags around raw text | 39,570,504 | <p>I'm building a simple web app using Flask and I want to know if it is possible to use regex to find and replace the numbers in Fe2O3 + CO -> Fe + CO2 and surround them with the sub HTML tag so it becomes Fe<sub>2</sub>O<sub>3</sub> + CO -> Fe + CO<sub>2</sub> when displayed in HTML.</p>
| -4 | 2016-09-19T10:07:20Z | 39,570,893 | <p>Try something like this, Here <code>a</code> is your input string. Implemented without using regex.</p>
<pre><code>In [1]: a = 'Fe2O3 + CO -> Fe + CO2'
In [2]: ''.join(['<sub>'+i+'</sub>' if i.isdigit() else i for i in a])
Out[1]: 'Fe<sub>2</sub>O<sub>3</sub> + CO -> Fe + C... | 0 | 2016-09-19T10:26:03Z | [
"python",
"regex"
] |
split-apply-combine to sklearn pipeline | 39,570,578 | <p>I am trying to generate a pipeline using sklearn, and am not really sure how to go about it. Here is a minimal example:</p>
<pre><code>def numFeat(data):
return data[['AGE', 'WASTGIRF']]
def catFeat(data):
return pd.get_dummies(data[['PAI', 'smokenow1']])
features = FeatureUnion([('f1',FunctionTransformer... | 0 | 2016-09-19T10:11:49Z | 39,583,770 | <p>You need to initialise <code>FunctionTransformer</code> with <code>validate=False</code> (IMO this is a bad default that should be changed):</p>
<pre><code>features = FeatureUnion([('f1',FunctionTransformer(numFeat, validate=False)),
('f2',FunctionTransformer(catFeat, validate=False))] )
</... | 1 | 2016-09-20T00:02:09Z | [
"python",
"scikit-learn"
] |
ImportError: No module named requests using two versions of python | 39,570,633 | <p>I've python 3.4.1 installed, and need to run python 2 script. I've installed python 2.7.5 by running <code>make install</code>. When i run my script it writes:</p>
<pre><code>Traceback (most recent call last):
File "/root/roseltorg/run.py", line 2, in <module>
import requests
ImportError: No module name... | 0 | 2016-09-19T10:15:01Z | 39,570,783 | <p>I prefer using virtualenv in such scenario. </p>
<pre><code>virtualenv -p path_to_python2.7 .(current dir)
source bin/activate
pip install requests
</code></pre>
| 1 | 2016-09-19T10:21:27Z | [
"python",
"python-2.7",
"pip",
"python-3.4"
] |
ImportError: No module named requests using two versions of python | 39,570,633 | <p>I've python 3.4.1 installed, and need to run python 2 script. I've installed python 2.7.5 by running <code>make install</code>. When i run my script it writes:</p>
<pre><code>Traceback (most recent call last):
File "/root/roseltorg/run.py", line 2, in <module>
import requests
ImportError: No module name... | 0 | 2016-09-19T10:15:01Z | 39,571,170 | <p>It is installing to python 3.4 with <code>pip</code> which means <code>pip</code> pointing to <code>pip3</code>. Try doing this</p>
<pre><code>pip2 install requests
</code></pre>
| 1 | 2016-09-19T10:40:23Z | [
"python",
"python-2.7",
"pip",
"python-3.4"
] |
How to read columns from CSV file in Python | 39,570,849 | <pre><code>def rowfilter():
field_data = {}
try:
csv_read = csv.reader(open('sample.csv', ), delimiter=',', quotechar='|')
for row in csv_read:
for field in row[7]:
print(field)
except FileNotFoundError:
print("File not found")
rowfilter()
</... | -2 | 2016-09-19T10:24:20Z | 39,571,210 | <pre><code>def rowfilter(col1, col2):
try:
csv_read = csv.reader(open('items.csv'), delimiter=',', quotechar='|')
for row in csv_read:
print(row[int(cols[0]):int(cols[1])])
except FileNotFoundError:
print("File not found")
inputrows = input("Enter columns in the format: ... | 0 | 2016-09-19T10:42:59Z | [
"python",
"python-3.x",
"csv"
] |
How to read columns from CSV file in Python | 39,570,849 | <pre><code>def rowfilter():
field_data = {}
try:
csv_read = csv.reader(open('sample.csv', ), delimiter=',', quotechar='|')
for row in csv_read:
for field in row[7]:
print(field)
except FileNotFoundError:
print("File not found")
rowfilter()
</... | -2 | 2016-09-19T10:24:20Z | 39,571,533 | <p>This is almost certainly a job for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pandas</a></p>
<pre><code>import pandas as pd
df = pd.read_csv('sample.csv', delimiter=',', quotechar='|')
#you can get the 7th column like this
df_seven = df[df.columns[7]]
#The... | 0 | 2016-09-19T10:59:38Z | [
"python",
"python-3.x",
"csv"
] |
Python bitarray manipulation | 39,571,128 | <p>I want to remove the least significant 2 bits of every 16-bit integer from a bitarray. They're stored like this:</p>
<pre><code>010101**00**10010101101100**00**10101010.....
</code></pre>
<p>(The zeroes between the asterisks will be removed. There are two of them every 16 bits (ignoring the very first)).</p>
<p>I... | -1 | 2016-09-19T10:38:05Z | 39,571,450 | <p>You can clear bits quite easily with masking. If you want to clear bits 8 and 7 you can do it like this:</p>
<pre><code>a = int('10010101101100',2)
mask = ~((1 << 7) | (1 << 8))
bin(a&mask)
</code></pre>
<p>more information about masking from <a href="https://wiki.python.org/moin/BitManipulation" r... | 2 | 2016-09-19T10:55:25Z | [
"python",
"arrays",
"list",
"bit-manipulation",
"bitarray"
] |
How do you open specific text files on python? | 39,571,134 | <p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
| -1 | 2016-09-19T10:38:23Z | 39,571,218 | <p>presuming that you want the line <code>m</code> and the name file is <code>file.txt</code></p>
<pre><code>with open('file.txt') as f:
line = f.read().splitlines()[m]
print(line)
</code></pre>
<p><code>line</code> is the line that you want.</p>
| 2 | 2016-09-19T10:43:28Z | [
"python"
] |
How do you open specific text files on python? | 39,571,134 | <p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
| -1 | 2016-09-19T10:38:23Z | 39,571,267 | <p>If the lines are selected by line numbers which follow a consistent pattern, use
<a href="https://docs.python.org/3.6/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a>.</p>
<p>E.g. To select every second line from line 3 up to but not including line 10:</p>
<pre><code>import... | 1 | 2016-09-19T10:46:00Z | [
"python"
] |
How do you open specific text files on python? | 39,571,134 | <p>I want to open specific lines from an ordinary text file in python. is there anyway to do this? and how?</p>
| -1 | 2016-09-19T10:38:23Z | 39,574,220 | <p>First lets see how to open a file to write:</p>
<pre><code>f = open(âfilename.txtâ, âwâ)
</code></pre>
<p>Now we have opened a file named filename, in write mode. Write mode is indicated using âwâ. If a file of that particular name is not present then a new file would be created.</p>
<p>It has created... | 0 | 2016-09-19T13:18:17Z | [
"python"
] |
How can I manipulate an array declared as `self.tab[('_',0)]` without explicitly knowing what it contains? | 39,571,169 | <p>I am writing a code in python that will be reading each character from a file and save its number of occurrences. As it is a homework assignement, I am not allowed to change the way the array was declared.</p>
<p>The array was declared in this way:</p>
<pre><code> def __init__(self):
self.tab = [('_', 0)... | 2 | 2016-09-19T10:40:18Z | 39,572,005 | <p>To check if your character is already present in the tab, you can use something like:</p>
<pre><code>found_char = [arr_item for arr_item in self.tab if arr_item[0]==c]
</code></pre>
<p>and check the returned value:</p>
<pre><code>if found_char == []:
# add a new entry in your tab using the self.size attribute... | 0 | 2016-09-19T11:23:16Z | [
"python",
"arrays"
] |
How can I manipulate an array declared as `self.tab[('_',0)]` without explicitly knowing what it contains? | 39,571,169 | <p>I am writing a code in python that will be reading each character from a file and save its number of occurrences. As it is a homework assignement, I am not allowed to change the way the array was declared.</p>
<p>The array was declared in this way:</p>
<pre><code> def __init__(self):
self.tab = [('_', 0)... | 2 | 2016-09-19T10:40:18Z | 39,572,083 | <p>As I mentioned in the comment, this is <em>not</em> a great data structure to use for this problem. </p>
<p>Firstly, tuples are immutable, i.e., they can't be updated. To change a string or integer in one of those <code>self.tab</code> tuples you basically need to create a new tuple and replace the original one. So... | 4 | 2016-09-19T11:27:42Z | [
"python",
"arrays"
] |
Scraping data from interactive graph | 39,571,193 | <p>There is a <a href="https://opensignal.com/reports/2016/02/state-of-lte-q4-2015/" rel="nofollow">website</a> with a couple of interactive charts from which I would like to extract data. I've written a couple of web scrapers before in python using selenium webdriver, but this seems to be a different problem. I've loo... | 0 | 2016-09-19T10:41:51Z | 39,650,363 | <p>SVG charts like this tend to be a bit tough to scrape. The numbers you want aren't displayed until you actually hover the individual elements with your mouse.</p>
<p>To get the data you need to</p>
<ol>
<li>Find a list of all dots</li>
<li>For each dot in dots_list, click or hover (action chains) the dot</li>
<li>... | 0 | 2016-09-22T23:30:53Z | [
"python",
"json",
"selenium"
] |
Python multiprocess lists of images | 39,571,222 | <p>I want to use multi process to stack many images. Each stack consists of 5 images, which means I have a list of images with a sublist of the images which should be combined:</p>
<blockquote>
<p>img_lst = [[01_A, 01_B, 01_C, 01_D, 01_E], [02_A, 02_B, 02_C, 02_D, 02_E], [03_A, 03_B, 03_C, 03_D, 03_E]]</p>
</blockqu... | 0 | 2016-09-19T10:43:38Z | 39,571,704 | <p><code>Pool.map</code> works like the builtin <code>map</code> function.It fetch one element from the second argument each time and pass it to the function that represent by the first argument.</p>
<pre><code>if __name__ == '__main__':
from multiprocessing import Pool
# I store my lists in a file
f_in =... | 1 | 2016-09-19T11:07:28Z | [
"python",
"multiprocessing"
] |
HTML/CSS center for all resolutions without % (percentage) | 39,571,232 | <p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p>
<p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p>... | 0 | 2016-09-19T10:44:14Z | 39,571,417 | <p>You can position it using absolute positions in CSS and measurements in px. If you are using Jquery then you can get the document sizes using</p>
<pre><code>$(document).height();
$(document).width();
</code></pre>
<p>or
$(window).height(); // for the viewport.</p>
<p>Some quick JavaScript calculations should... | 0 | 2016-09-19T10:54:17Z | [
"python",
"html",
"css",
"center"
] |
HTML/CSS center for all resolutions without % (percentage) | 39,571,232 | <p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p>
<p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p>... | 0 | 2016-09-19T10:44:14Z | 39,573,142 | <p>If your page is served as a HTML webpage, you <em>should</em> be able to use JS, HTML, and CSS without your backend mucking it up. If you apply the following styles to <strong>any</strong> element, it will be centered:</p>
<pre><code> position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -5... | 1 | 2016-09-19T12:26:06Z | [
"python",
"html",
"css",
"center"
] |
HTML/CSS center for all resolutions without % (percentage) | 39,571,232 | <p>I was wondering, is it possible to make this central box be "in the very" center of the page without using %?</p>
<p>I'm using VPS and I have some Python going on there, so I don't know how to use % sizes in order to get it right. But this is how far I came up only to hear that this isn't centered on 1280x1024:</p>... | 0 | 2016-09-19T10:44:14Z | 39,577,817 | <p>thank you for your help, but I talked to a friend meanwhile and we came up to satisfying solution, so here's the final code and what we did</p>
<ol>
<li>I removed the table from the body and other non-necessary items (forgive me, as I'm a newbie)</li>
<li>Instead of max height and width we used height and width - w... | 0 | 2016-09-19T16:27:13Z | [
"python",
"html",
"css",
"center"
] |
Django forms: Error message display all the time, not only after errors | 39,571,245 | <p>I'm building my own site with Django's Framework.
I made a form for creating a new account. It works well but I have a problem with my errors messages.</p>
<p>All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages... | 0 | 2016-09-19T10:44:59Z | 39,571,297 | <p>In each field you have {% if form.errors %} - so when there is at least one error, you are going to display it everywhere.</p>
<p>change it to <code>{% if form.field_name.errors %}</code> and then html should render only the errors associated with that specific field</p>
| 0 | 2016-09-19T10:47:49Z | [
"python",
"django",
"forms"
] |
Django forms: Error message display all the time, not only after errors | 39,571,245 | <p>I'm building my own site with Django's Framework.
I made a form for creating a new account. It works well but I have a problem with my errors messages.</p>
<p>All my errors are already display when I first arrive on the page. After submit, if a field is wrong, the page newly updated display only the wanted messages... | 0 | 2016-09-19T10:44:59Z | 39,571,358 | <p>You should only pass request.POST into the field if it actually is a POST. So:</p>
<pre><code>def create_new_user(request):
if request.method=="POST":
form = UserCreateForm(request.POST)
if form.is_valid():
...
else:
form = UserCreateForm()
return render(request, 'lej... | 3 | 2016-09-19T10:51:14Z | [
"python",
"django",
"forms"
] |
BadRequestError: BLOB, ENITY_PROTO or TEXT property concise_topics must be in a raw_property field | 39,571,299 | <p>Here is the code for my model. </p>
<pre><code>from google.appengine.ext import ndb
from modules.admin.models.Author import Author
from modules.hod.models.Concept import Concept
class Post(ndb.Model):
author_key = ndb.KeyProperty(kind=Author)
content = ndb.StringProperty(indexed=False)
created = ndb.D... | 0 | 2016-09-19T10:47:52Z | 39,571,546 | <p>I would use <code>_pre_put_hook</code> instead of <code>ComputedProperty</code></p>
<pre><code>topics = ndb.StructuredProperty(Concept, repeated=True)
concise_topics = ndb.StructuredProperty(Concept, repeated=True)
def _pre_put_hook(self):
self.concise_topics = filter(lambda x: x.occurrences > 1, self.topic... | 0 | 2016-09-19T11:00:14Z | [
"python",
"python-2.7",
"google-app-engine"
] |
How can I use two keys with defaultdict? | 39,571,543 | <p>I am trying to create a defaultdict with nested keys. Here is the view that I wrote, but apparently multiple keys don't work in defaultdict.</p>
<pre><code>def routine_view(request, klass_id):
days = Routine.DAYS
periods = Routine.PERIODS
class_details = defaultdict(list)
classes = Routine.objects.... | 0 | 2016-09-19T11:00:04Z | 39,571,619 | <p>Your question isn't totally clear, but I think you want a defaultdict which itself contains a defaultdict of lists. So:</p>
<pre><code>class_details = defaultdict(lambda: defaultdict(list))
</code></pre>
<p>Alternatively, you may not need a nested dict at all; you could instead use the original defauldict with key... | 1 | 2016-09-19T11:03:07Z | [
"python",
"django",
"defaultdict"
] |
openpyxl: Gives error on load_workbook() | 39,571,560 | <p>The following code was executing fine, until I setup the development environment on a different computer. </p>
<pre><code>workbook_obj = load_workbook(filename=xl_file, data_only=True, use_iterators=True)
</code></pre>
<p>I get the following error: </p>
<pre><code>TypeError: load_workbook() got an unexpected keyw... | -1 | 2016-09-19T11:00:54Z | 39,572,032 | <p>The <code>use_iterators</code> keyword <a href="https://openpyxl.readthedocs.io/en/default/changes.html?highlight=use_iterators#id14" rel="nofollow">was removed</a> since 2.4.0. Use <code>read_only=True</code> instead.</p>
| 3 | 2016-09-19T11:24:37Z | [
"python",
"openpyxl"
] |
Post data from html to another html | 39,571,659 | <p>I want to post data from html to another html</p>
<p>I know how to post data html->python and python-> html</p>
<p>I have dictionary in the html (I get it from python - <code>return render_to_response('page.html', locals()</code>)</p>
<p>how can I use with the dictionary in the second html file?</p>
| 0 | 2016-09-19T11:05:05Z | 39,576,661 | <p>you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="nofollow">window.postMessage</a> and window.addEventListener as described in this <a href="http://stackoverflow.com/questions/13545883/can-i-communicate-between-two-local-html-files-using-javascript">example</a> .</p>
| 0 | 2016-09-19T15:18:07Z | [
"javascript",
"python",
"html"
] |
Python sorting by attributes that can be None | 39,571,738 | <p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>
<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>
<p>And that'd work just fine. However, <code>data</co... | 2 | 2016-09-19T11:09:01Z | 39,571,933 | <p>just filter for the None before sorting</p>
<pre><code>sorted(filter(None, items), key=attrgetter('data.value'))
</code></pre>
| 0 | 2016-09-19T11:19:06Z | [
"python",
"python-2.7",
"sorting"
] |
Python sorting by attributes that can be None | 39,571,738 | <p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>
<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>
<p>And that'd work just fine. However, <code>data</co... | 2 | 2016-09-19T11:09:01Z | 39,571,937 | <p>If you do not have a function handy that returns the key you want then just write your own.</p>
<pre><code>def item_key(item):
try:
return item.data.value
except AttributeError:
return None
sorted(items, key=item_key)
</code></pre>
| 0 | 2016-09-19T11:19:14Z | [
"python",
"python-2.7",
"sorting"
] |
Python sorting by attributes that can be None | 39,571,738 | <p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>
<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>
<p>And that'd work just fine. However, <code>data</co... | 2 | 2016-09-19T11:09:01Z | 39,571,950 | <p>Just filter the None values first before sending them to sorted.</p>
<pre><code>sorted(filter(None, items), key=attrgetter('data.value'))
</code></pre>
<p>And if you really want the None items too, you can do something like this:</p>
<pre><code># items already defined with values
new_items_list = sorted(filter(No... | 0 | 2016-09-19T11:20:24Z | [
"python",
"python-2.7",
"sorting"
] |
Python sorting by attributes that can be None | 39,571,738 | <p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>
<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>
<p>And that'd work just fine. However, <code>data</co... | 2 | 2016-09-19T11:09:01Z | 39,572,023 | <pre><code>sorted(items, key=lambda i: i.data.value if i.data else 0)
</code></pre>
| 0 | 2016-09-19T11:24:22Z | [
"python",
"python-2.7",
"sorting"
] |
Python sorting by attributes that can be None | 39,571,738 | <p>Let's say I have a list of items I want to sort: <code>items = [ item1, item2, item3 ]</code>. The attribute I want to use to sort them is <code>item.data.value</code>, so I'd normally go:</p>
<pre><code>sorted(items, key=attrgetter('data.value'))
</code></pre>
<p>And that'd work just fine. However, <code>data</co... | 2 | 2016-09-19T11:09:01Z | 39,572,117 | <p>Use as key a <em>tuple</em>, like <code>(False, value)</code>. If value is None, then the tuple should be <code>(True, None)</code>.</p>
<p>Tuples are compared by their first element first, then the second, et cetera. False sorts before True. So all None values will be sorted to the end.</p>
<pre><code>def none_to... | 2 | 2016-09-19T11:29:54Z | [
"python",
"python-2.7",
"sorting"
] |
Find longest path with BFS | 39,571,825 | <p>I have a list with 794 three-letter long words. My task is to find the word(s) with the longest path to a given word. </p>
<p><strong>Definition (children):</strong><br>
Children to a parent word are the parent word with one and only one letter replaced. </p>
<p><strong>Example:</strong><br>
'can', 'run', 'rap' e... | 2 | 2016-09-19T11:13:48Z | 39,572,240 | <p>IIUC, this is not guaranteed to work (in fact, you can build cases where it doesn't).</p>
<p>Suppose you start at node <em>a</em>; there is a direct path <em>a → b</em>; there are also a direct path <em>a → c</em> and an indirect path <em>c ⇒ b</em>. </p>
<p>Suppose that when you iterate over the c... | 1 | 2016-09-19T11:36:38Z | [
"python",
"python-3.x",
"python-3.5"
] |
How to row-wise concatenate several columns containing strings? | 39,571,832 | <p>I have a specific series of datasets which come in the following general form:</p>
<pre><code>import pandas as pd
import random
df = pd.DataFrame({'n': random.sample(xrange(1000), 3), 't0':['a', 'b', 'c'], 't1':['d','e','f'], 't2':['g','h','i'], 't3':['i','j', 'k']})
</code></pre>
<p>The number of <em>tn</em> colu... | 3 | 2016-09-19T11:14:07Z | 39,573,438 | <p>Here is a slightly alternative solution:</p>
<pre><code>In [57]: df['result'] = df.filter(regex=r'^t').apply(lambda x: x.add(' ')).sum(axis=1).str.strip()
In [58]: df
Out[58]:
n t0 t1 t2 t3 result
0 92 a d g i a d g i
1 916 b e h j b e h j
2 363 c f i k c f i k
</code></pre>
| 2 | 2016-09-19T12:39:40Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
"string-concatenation"
] |
Size issues with Python shelve module | 39,571,859 | <p>I want to store a few dictionaries using the shelve module, however, I am running into a problem with the size. I use Python 3.5.2 and the latest shelve module.</p>
<p>I have a list of words and I want to create a map from the bigrams (character level) to the words. The structure will look something like this:</p>
... | 0 | 2016-09-19T11:15:37Z | 39,574,975 | <p>The problem here is not so much the number of keys, but that each key references a list of words.</p>
<p>While in memory as one (huge) dictionary, this isn't that big a problem as the words are simply shared between the lists; each list is simply a sequence of references to other objects and here many of those obje... | 2 | 2016-09-19T13:55:23Z | [
"python",
"dictionary",
"shelve"
] |
Part II: Counting how many times in a row the result of a sum is positive (or negative) | 39,572,089 | <p><strong>Second part</strong> First part can be found here: <a href="http://stackoverflow.com/questions/39514202/counting-how-many-times-in-a-row-the-result-of-a-sum-is-positive-or-negative">Click me</a></p>
<p>Hi all, I have been practising with the gg function that you guys help me create -- see part one. Now, I ... | 0 | 2016-09-19T11:28:03Z | 39,573,123 | <p>What you are looking for are the <code>groupby</code> function <strong>from <code>itertools</code></strong> and <code>Counter</code> from <code>collections</code>. Here is how to achieve what you want :</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(15, 2), columns=["open", "... | 1 | 2016-09-19T12:24:56Z | [
"python",
"pandas",
"numpy"
] |
Run tests in celery workers | 39,572,178 | <p>I'm looking for a Python test-suite that takes tests, converts them into celery tasks which are run on workers, gathers the results and prints them as if the tests were running normally.</p>
<p>Searching only came up with ways of testing celery tasks. I don't want to test celery tasks, I want celery tasks to test o... | 0 | 2016-09-19T11:32:45Z | 39,572,311 | <p>I'm not aware of any library that uses celery to distribute tests, but there are libraries for both pytest and nose that do something similar.</p>
<ul>
<li><a href="https://pypi.python.org/pypi/pytest-xdist" rel="nofollow">https://pypi.python.org/pypi/pytest-xdist</a></li>
<li><a href="https://github.com/dlanger/no... | 0 | 2016-09-19T11:39:49Z | [
"python",
"testing",
"celery"
] |
How to replace code block in a source file using shell script or python or perl | 39,572,195 | <p>In my source file there are multiple if clause with same check . I want to make one of the conditional block executed all the time by commenting out conditional statement which is based on text defined after if statement. </p>
<pre><code>if [ "${SVR_GRP}" = "obi" ] ; then
EXTRA_JAVA_PROPERTIES="-Doracle.fusion.ap... | 1 | 2016-09-19T11:33:50Z | 39,574,395 | <blockquote>
<p>I want comment out condition based on second line text value</p>
</blockquote>
<p>I'm afraid this is a very unclear specification. Please try harder to explain what needs to happen to your text.</p>
<p>This Perl code transforms your sample input into your sample output, but given the vagueness of yo... | 0 | 2016-09-19T13:27:05Z | [
"python",
"perl",
"shell",
"python-2.4"
] |
Pyomo's parameter estimation in an ODE system with missing values in time series | 39,572,201 | <p>I have an ODE system of 7 equations for explaining a particular set of microorganisms dynamics of the form:</p>
<p><img src="http://latex.codecogs.com/gif.latex?%5Cbegin%7Balign*%7D&space;%5Cfrac%7BdX_1%7D%7Bdt%7D&=-Y_1%5C,.%5C,v_1-Y_2%5C,.%5C,v_3%5C%5C[4pt]&space;%5Cfrac%7BdX_2%7D%7Bdt%7D&=v_1-v_2%5C%5C[4p... | 0 | 2016-09-19T11:34:04Z | 39,575,258 | <p>I think all you need to do is slightly modify your objective function like this:</p>
<pre><code>def _obj(m):
sum1 = sum((m.x1[i]-m.x1_meas[i])**2 for i in m.MEAS_t if i in m.x1_meas.keys())
sum2 = sum((m.x2[i]-m.x2_meas[i])**2 for i in m.MEAS_t if i in m.x2_meas.keys())
sum3 = sum((m.x3[i]-m.x3_meas[i])... | 1 | 2016-09-19T14:09:23Z | [
"python",
"ode",
"pyomo"
] |
How to execute python scripts with a custom name without .py extension | 39,572,325 | <p>Lets say I have a python script that makes an http request and prints the response code to the screen and exits.</p>
<pre><code># check_app_status.py
import requests
r = requests.get("https://someapp.com")
print r.status_code
</code></pre>
<p>Now i can run it by </p>
<pre><code>$ python check_app_status.py
200... | 1 | 2016-09-19T11:40:54Z | 39,572,364 | <p>Assuming you're on a unixoid system, you just need to add a shebang line:</p>
<pre><code>#!/usr/local/bin/python
import requests
...
</code></pre>
<p>The exact location of the python executable may vary, so you can alternatively also use the shebang line <code>#!/usr/bin/env python</code>, which should always wor... | 3 | 2016-09-19T11:43:15Z | [
"python"
] |
Scrapy - How to keep track of start url | 39,572,599 | <p>Given a pool of start urls I would like to identify in the parse_item() function the origin url.</p>
<p>As far as I'm concerned the scrapy spiders start crawling from the initial pool of start urls, but when parsing there is no trace of which of those urls was the initial one. How it would be possible to keep track... | 0 | 2016-09-19T11:56:22Z | 39,575,584 | <p>If you need a parsing url inside the spider, just use response.url:</p>
<pre><code>def parse_item(self, response):
print response.url
</code></pre>
<p>but in case you need it outside spider I can think of following ways:</p>
<ol>
<li>Use <a href="http://doc.scrapy.org/en/latest/topics/api.html" rel="nofollow... | 0 | 2016-09-19T14:25:46Z | [
"python",
"scrapy",
"web-crawler"
] |
Using graphframes with PyCharm | 39,572,603 | <p>I have spent almost 2 days scrolling the internet and I was unable to sort out this problem. I am trying to install the <a href="https://spark-packages.org/package/graphframes/graphframes" rel="nofollow">graphframes package</a> (Version: 0.2.0-spark2.0-s_2.11) to run with spark through PyCharm, but, despite my best ... | 0 | 2016-09-19T11:56:31Z | 39,575,317 | <p>You can set <code>PYSPARK_SUBMIT_ARGS</code> either in your code</p>
<pre><code>os.environ["PYSPARK_SUBMIT_ARGS"] = (
"--packages graphframes:graphframes:0.2.0-spark2.0-s_2.11 pyspark-shell"
)
spark = SparkSession.builder.getOrCreate()
</code></pre>
<p>or in PyCharm edit run configuration (<kbd>Run</kbd> -> <... | 2 | 2016-09-19T14:12:24Z | [
"python",
"install",
"pycharm",
"pyspark",
"graphframes"
] |
Python XML parse issues | 39,572,648 | <p>Currently trying to parse some XML using python, so far I've managed to get the name of the tag however I can't figure out how to get the data from inside this.</p>
<pre><code> <Fragment name="Located At">Sector 121212</Fragment>
</code></pre>
<p>The above is an example of the XML file, I can get the ... | 0 | 2016-09-19T11:59:19Z | 39,572,756 | <p>According to the <a href="https://docs.python.org/2/library/xml.dom.minidom.html" rel="nofollow"><code>minidom</code> docs</a>, it looks like <code>.childNodes</code> might be the thing you're looking for.</p>
| 1 | 2016-09-19T12:05:37Z | [
"python",
"xml",
"python-2.7"
] |
How do I roll a dice and store the total number using Python3.4 | 39,572,664 | <pre><code>import tkinter
import random
def rollDice():
x=random.randint(1,6)
total=0
if x == 1:
total+=1
....
print(total)
</code></pre>
<p>I would like to add each number I roll in <code>.rollDice</code> and store into <code>total</code> , and maximum is 50. How can I do that?</p>
| -2 | 2016-09-19T12:00:34Z | 39,572,968 | <p>As @PaulRooney says, i am not sure what <code>tkinter</code> has to do with this. From what i understand, you want to roll a dice until your <code>total</code> reaches or exceeds 50.. So here is my take on this:</p>
<pre><code>from random import randint
def rollDice():
return randint(1,6)
total = 0
while tota... | 0 | 2016-09-19T12:16:05Z | [
"python",
"tkinter"
] |
Thread in python- | 39,572,769 | <p>I want to use threads to get better performance in python.</p>
<p>My program need to return value from each function the thread does.</p>
<p>And I need to know when the thread is finished.</p>
<p>There are 3 ways I tried to execute this little program.</p>
<pre><code>import thread
import datetime
from threading ... | 2 | 2016-09-19T12:05:59Z | 39,572,927 | <p>Threading is primarily of use when you have multiple tasks contending for CPU but spending most of their time waiting for some external event like a network read or a database write.</p>
<p>With multiple threads active, every (some number) of opcodes it spends time deciding to switch to another thread (assuming the... | 3 | 2016-09-19T12:14:04Z | [
"python",
"multithreading",
"python-2.7",
"threadpool"
] |
Thread in python- | 39,572,769 | <p>I want to use threads to get better performance in python.</p>
<p>My program need to return value from each function the thread does.</p>
<p>And I need to know when the thread is finished.</p>
<p>There are 3 ways I tried to execute this little program.</p>
<pre><code>import thread
import datetime
from threading ... | 2 | 2016-09-19T12:05:59Z | 39,573,328 | <p>To append the other answer:</p>
<p>The reason the threaded version can actually be slower in a CPU-bound operation is (as mentioned) GIL, the Global Interpreter Lock. GIL works as a mutex, allowing only a single thread to access it at a time. So threading is only useful when waiting for IO-operations.</p>
<p>Howev... | 1 | 2016-09-19T12:34:35Z | [
"python",
"multithreading",
"python-2.7",
"threadpool"
] |
Python - check if it's prime number | 39,572,815 | <p>I know that this question was asked way too many times, but I'm not searching for the fastest algorithm. I'd only like to know what I'm doing wrong with my code since it's faulty.</p>
<pre><code>import math
def is_prime(number):
for i in range (2, 1+ int(math.sqrt(number))):
if number % i == 0:
... | 0 | 2016-09-19T12:08:20Z | 39,572,861 | <p>You are returning immediately in the first iteration of the loop ... always.</p>
<p>Instead only return immediately when you know it is not a prime, else keep going:</p>
<pre><code>def is_prime(number):
for i in range (2, 1+ int(math.sqrt(number))):
if number % i == 0:
return 0
return 1... | 4 | 2016-09-19T12:11:04Z | [
"python"
] |
Python, using threading with multiprocessing | 39,572,941 | <p>Can someone explain why threading don't work in multiprocessing.Process.</p>
<p>I've attached some example to explain my problem.</p>
<p>I have a process that executed every second and write to file. When I run it from shell, it works as expected.</p>
<p><strong>stat_collect.py</strong></p>
<pre><code>#!/usr/bin... | 2 | 2016-09-19T12:14:53Z | 39,617,461 | <p>Here is what is going on:</p>
<ol>
<li>You start your process </li>
<li><code>collect_statistics</code> runs</li>
<li>Timer is started</li>
<li>now the function called in the process(<code>collect_statistics</code>) is finished, so the process
quit, killing the timer in the same time.</li>
</ol>
<p>Here is how to ... | 1 | 2016-09-21T13:07:36Z | [
"python",
"multithreading",
"python-multiprocessing"
] |
Tuples in python to 3D matrix | 39,573,129 | <p>I have a list of lists in python that contains the score of users in a game with different courses and levels. My tuple (users, courses, levels, scores). I ve got 20 users 4 courses and 10 levels. What I want is to create a 3D matrix which will have as dimensions users-courses-levels and as a value user score. My t... | 1 | 2016-09-19T12:25:15Z | 39,575,380 | <p>If you really need the data in that form, you could do something like:</p>
<pre><code>data = [(110, 'Math', 1, 5),
(110, 'Sports', 1, 5),
(110, 'Geography', 1, 10),
(112, 'History', 1, 9),
(112, 'History', 2, 10)] #I'm using Python 3 -- u'' is superfluous
dataDict = {(x,y,z):w for x,y,z,w in data}
users = [110... | 1 | 2016-09-19T14:15:43Z | [
"python"
] |
Django validate what user sends from admin panel | 39,573,167 | <p>I am kind of new to Django, and i am trying to make sort of a news website where users can submit articles(with an account) but the admin needs to check them before they can be posted. Is that possible?</p>
| 1 | 2016-09-19T12:27:08Z | 39,573,262 | <p>Yes, it is. </p>
<p>The simplest approach would be creating simple flag in model let's say a Boolean field named <code>verified</code>, which by default would be False. You could add permissions. So in the end you could overwrite a function in your admin form, and show the field for superuser only.</p>
<pre><code>... | 2 | 2016-09-19T12:31:23Z | [
"python",
"django",
"frameworks",
"website"
] |
Output Projection in Seq2Seq model Tensorflow | 39,573,188 | <p>I'm going through the translation code implemented by <code>tensorflow</code> using <code>seq2seq</code> model. I'm following <code>tensorflow</code> tutorial about <a href="https://www.tensorflow.org/versions/r0.10/tutorials/seq2seq/index.html" rel="nofollow"><code>seq2seq</code> model</a>.</p>
<p>In that tutorial... | 0 | 2016-09-19T12:27:58Z | 39,578,266 | <p>Internally, a neural network operates on dense vectors of some size, often 256, 512 or 1024 floats (let's say 512 for here). But at the end it needs to predict a word from the vocabulary which is often much larger, e.g., 40000 words. Output projection is the final linear layer that converts (projects) from the inter... | 1 | 2016-09-19T16:52:10Z | [
"python",
"tensorflow"
] |
why using matplotlib text alignent with string format functions works wrong? | 39,573,252 | <p>I am trying to align my texts to right in matplotlib bars. The following codes works just fine:</p>
<pre><code>colors = ['red', 'blue', 'green', 'yellow']
for color in colors:
print('{:>15}'.format(color))
</code></pre>
<p>output:</p>
<pre><code> red
blue
green
yellow
</code></pre>... | 0 | 2016-09-19T12:31:02Z | 39,573,344 | <p><a href="http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.text" rel="nofollow"><code>ax.text()</code></a> creates a matplotlib <code>Text</code> object, which have the option <a href="http://matplotlib.org/api/text_api.html#matplotlib.text.Text.set_horizontalalignment" rel="nofollow"><code>horizontalalig... | 0 | 2016-09-19T12:35:25Z | [
"python",
"string",
"matplotlib",
"plot",
"text-alignment"
] |
How to create field named «from» in WTForms? | 39,573,284 | <p>I want to make a form for selecting an interval with two fields: <code>from</code> and <code>to</code>. But since <code>from</code> is a keyword in Python, I can't just write:</p>
<pre class="lang-python prettyprint-override"><code>class MyForm(Form):
from = DateField()
to = DateField()
</code></pre>
<p>Th... | 1 | 2016-09-19T12:32:27Z | 39,673,889 | <p>You can use Python's built in function <code>setattr</code>:</p>
<pre><code>class MyForm(Form):
to = DateField()
setattr(MyForm, 'from', DateField())
myform = MyForm()
</code></pre>
<p>You can access the field again with <code>getattr</code>:</p>
<pre><code>from_ = getattr(myform, 'from')
</code></pre>
| 1 | 2016-09-24T07:46:10Z | [
"python",
"wtforms"
] |
Deploy Python executable to Azure Service Fabric | 39,573,315 | <p>I am looking for helpful solutions to deploy <code>Python</code> executable to <code>Azure Service Fabric</code></p>
<p>There is documentation for <code>node js</code> <a href="https://azure.microsoft.com/en-us/documentation/articles/service-fabric-deploy-multiple-apps/" rel="nofollow">here</a> but I could not find... | 1 | 2016-09-19T12:33:55Z | 39,599,956 | <p>This shouldn't be any different for Python, as long as you either install the Python requirements directly on the nodes through a script extension (for Azure). Or call the Python installer as the SetupEntryPoint.</p>
| 0 | 2016-09-20T17:04:41Z | [
"python",
"azure",
"web-deployment"
] |
find all words in list/file that begin/ends with a specific prefix/suffix | 39,573,394 | <p>The below code gives the words which begin/ends with a specific prefix/suffix.</p>
<pre><code>string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
if word[-1] == "a":
print word
string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
... | 1 | 2016-09-19T12:37:31Z | 39,573,479 | <p>If <code>word</code> is a string, then <code>word[0] == "fi"</code> does not do what you think it does. </p>
<p>You can instead use <code>startswith</code> and <code>endswith</code> to check for <em>multicharacter</em> suffixes and prefixes.</p>
<pre><code>string_list = open("file.txt", 'r')
for word in string_li... | 1 | 2016-09-19T12:41:40Z | [
"python",
"regex",
"prefix",
"suffix"
] |
find all words in list/file that begin/ends with a specific prefix/suffix | 39,573,394 | <p>The below code gives the words which begin/ends with a specific prefix/suffix.</p>
<pre><code>string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
if word[-1] == "a":
print word
string_list = [line.strip() for line in open("file.txt", 'r')]
for word in string_list:
... | 1 | 2016-09-19T12:37:31Z | 39,574,034 | <p>If you need speed, you could simply use <a href="https://en.wikipedia.org/wiki/Grep" rel="nofollow">GREP</a>, which is written in a lowlevel language and is bound to be faster than a python loop by leaps and bounds. </p>
<p>It is also portable and runs just fine on Linux/Windows/OSX/...</p>
| 0 | 2016-09-19T13:09:04Z | [
"python",
"regex",
"prefix",
"suffix"
] |
Update default value Entry Widget | 39,573,459 | <p>I have a toplevel window containing a simple entry widget and two buttons. (Class opc)</p>
<p>The entry widget has assigned a default value "test". What I´m trying to do is update this default value when the user input a new value, and show this as default in new instances of the window.</p>
<p>When I change the ... | 0 | 2016-09-19T12:40:34Z | 39,587,366 | <p>One option is to create a list owned by the class, i.e.:</p>
<pre><code>class classname(object):
defaultvalue=[100] #Default is 100
def dostuff(self):
self.defaultvalue[0]=self.entryname.get()
</code></pre>
<p>The basic idea is that each class has the same value for defaultvalue: a link to a spot... | 0 | 2016-09-20T06:44:09Z | [
"python",
"tkinter"
] |
How to ignore lower as well upper case of a word in python? | 39,573,486 | <p>I want to find <strong>Andy</strong> in the list. Either <strong>Andy</strong> comes in upper or lower case in string the program should return <code>True</code> </p>
<pre><code>String1 ='Andy is an awesome bowler'
String2 ='andy is an awesome bowler'
String3 ='ANDY is an awesome bowler'
</code></pre>
<p>I am doi... | -1 | 2016-09-19T12:42:09Z | 39,573,564 | <p>You can convert the string to uppercase or lowercase first:</p>
<pre><code>String1 ='Andy is an awesome bowler'
String2 ='andy is an awesome bowler'
String3 ='ANDY is an awesome bowler'
if 'andy' in String1.lower(): # or this could be if 'ANDY' in String1.upper():
print('success')
else:
print('Nothing')
<... | 3 | 2016-09-19T12:46:14Z | [
"python"
] |
How to ignore lower as well upper case of a word in python? | 39,573,486 | <p>I want to find <strong>Andy</strong> in the list. Either <strong>Andy</strong> comes in upper or lower case in string the program should return <code>True</code> </p>
<pre><code>String1 ='Andy is an awesome bowler'
String2 ='andy is an awesome bowler'
String3 ='ANDY is an awesome bowler'
</code></pre>
<p>I am doi... | -1 | 2016-09-19T12:42:09Z | 39,573,750 | <p>If you are sure that you string contains only ascii characters, use the following approach: </p>
<pre><code>if 'andy' in string1.lower():
do something
</code></pre>
<p>If your comparision strings involve unicodedata: </p>
<pre><code>import unicodedata
def normalize_caseless(text):
return unicodedata.norm... | 1 | 2016-09-19T12:54:35Z | [
"python"
] |
How to detect logic gates from scanned images of hand drawn circuits? | 39,573,527 | <p>we started with scanned images of proper drawn diagrams of logic circuit we were able to separate the logic gates from the scanned image of the circuit however we were not able detect and how to proceed further,we had use python open cv for this ,our code for the above is</p>
<pre><code>import cv2
import numpy as n... | 1 | 2016-09-19T12:44:42Z | 39,603,383 | <p>The logic doors all have the same size. I would do that:</p>
<ol>
<li>Connected component labeling of white areas.</li>
<li>Separate/isolate</li>
<li>Filter the labels by the size.</li>
<li>(optional) All the logic doors will touch a tiny white pattern/label on the right.</li>
</ol>
| 0 | 2016-09-20T20:42:11Z | [
"python",
"opencv",
"image-processing",
"image-recognition",
"morphological-analysis"
] |
Project Euler #13 Python. Incorrect carry over | 39,573,554 | <p>This problem asks to sum up 100 numbers, each 50 digits long. <a href="http://code.jasonbhill.com/python/project-euler-problem-13/" rel="nofollow">http://code.jasonbhill.com/python/project-euler-problem-13/</a></p>
<p>We can replace <code>\n</code> with "\n+" in Notepad++ yielding</p>
<pre><code>a=3710728753390210... | 0 | 2016-09-19T12:45:52Z | 39,573,694 | <p>Python source code lines are terminated by newline characters. The subsequent lines in the first example are separate expression statements consisting of a single integer with a unary plus operator in front, but they don't do anything. They evaluate the expression (resulting in the integer constant itself), and th... | 0 | 2016-09-19T12:52:06Z | [
"python"
] |
Project Euler #13 Python. Incorrect carry over | 39,573,554 | <p>This problem asks to sum up 100 numbers, each 50 digits long. <a href="http://code.jasonbhill.com/python/project-euler-problem-13/" rel="nofollow">http://code.jasonbhill.com/python/project-euler-problem-13/</a></p>
<p>We can replace <code>\n</code> with "\n+" in Notepad++ yielding</p>
<pre><code>a=3710728753390210... | 0 | 2016-09-19T12:45:52Z | 39,573,705 | <p>As you can see in the result, the first set of instruction is not computing the sum. It preserved the first assignment. Since <code>+N</code> is on its own a valid instruction, the next lines after the assignment do nothing. Thus</p>
<pre><code>a=42
+1
print a
</code></pre>
<p>prints <code>42</code></p>
<p>To wr... | 1 | 2016-09-19T12:52:38Z | [
"python"
] |
How to compare four columns of pandas dataframe at a time? | 39,573,574 | <p>I have one dataframe. </p>
<p><strong>Dataframe :</strong> </p>
<pre><code> Symbol1 BB Symbol2 CC
0 ABC 1 ABC 1
1 PQR 1 PQR 1
2 CPC 2 CPC 0
3 CPC 2 CPC 1
4 CPC 2 CPC 2
</code></pre>
<p>I want to compare <code>Symbol1</c... | 3 | 2016-09-19T12:46:48Z | 39,573,631 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing"><code>boolean indexing</code></a> and compare with <code>&</code> instead <a href="http://stackoverflow.com/a/21415990/2901002"><code>and</code></a>:</p>
<pre><code>print ((df.Symbol1 == df.Symbol2) & (df.BB == ... | 6 | 2016-09-19T12:49:19Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
How to compare four columns of pandas dataframe at a time? | 39,573,574 | <p>I have one dataframe. </p>
<p><strong>Dataframe :</strong> </p>
<pre><code> Symbol1 BB Symbol2 CC
0 ABC 1 ABC 1
1 PQR 1 PQR 1
2 CPC 2 CPC 0
3 CPC 2 CPC 1
4 CPC 2 CPC 2
</code></pre>
<p>I want to compare <code>Symbol1</c... | 3 | 2016-09-19T12:46:48Z | 39,574,920 | <p>Here is an alternative way, which is bit nicer, but it's also bit slower:</p>
<pre><code>In [65]: df.query('Symbol1 == Symbol2 and BB == CC')
Out[65]:
Symbol1 BB Symbol2 CC
0 ABC 1 ABC 1
1 PQR 1 PQR 1
4 CPC 2 CPC 2
</code></pre>
| 3 | 2016-09-19T13:52:56Z | [
"python",
"pandas",
"indexing",
"dataframe",
"condition"
] |
share variables by PHP, python, bash | 39,573,614 | <p>I have project that uses same initial variables on same server by different programming languages. they are PHP, python and bash. i need all languages to access those variable and I cannot exclude any language.</p>
<p>for now I keep 3 places to store variables:
for php I have Mysql storage, for python and bash 2 s... | 1 | 2016-09-19T12:48:37Z | 39,580,897 | <p>OK, I think the best approach for me here would be to limit variable storages from 3 to at least 2 and make python script deal with bash tasks over os.system. To use 2 storages is somehow manageable</p>
| 0 | 2016-09-19T19:43:45Z | [
"php",
"python",
"bash",
"variables",
"share"
] |
Python - Can't connect to MS SQL | 39,573,669 | <p>When I try to connect to MS SQL, I got this error:</p>
<pre><code>> pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC Driver 13 for SQL
> Server]SQL Server Network Interfaces: Error Locating Server/Instance
> Specified [xFFFFFFFF]. (-1) (SQLDriverConnect); [HYT00]
> [Microsoft][ODBC Driver 13 for SQL S... | 1 | 2016-09-19T12:51:10Z | 39,573,670 | <p>In my case, it was solved by activating <code>SQL Server (SQLEXPRESS)</code> in services. It turns out, it doesn't turn on automatically when the computer starts.</p>
<p><a href="http://i.stack.imgur.com/D6hsT.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/D6hsT.jpg" alt="enter image description here"></a><... | 1 | 2016-09-19T12:51:10Z | [
"python",
"sql-server",
"database",
"database-connection",
"pyodbc"
] |
How do I get the filepath of an uploaded file? | 39,573,710 | <p>I'm having difficulty passing the path of a file to a library called Textract.</p>
<pre><code>def file_to_string(filepath):
text = textract.process(filepath)
print text
return text
</code></pre>
<p>Here is my upload form in views.py</p>
<pre><code>if request.method == 'POST':
upload_form = UploadF... | 0 | 2016-09-19T12:52:55Z | 39,574,121 | <p>Try using <code>file_to_string(file.name)</code>.</p>
<p>Docs: <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.fields.files.FieldFile.name</a></p>
| 0 | 2016-09-19T13:13:41Z | [
"python",
"django",
"django-models",
"django-uploads"
] |
How do I get the filepath of an uploaded file? | 39,573,710 | <p>I'm having difficulty passing the path of a file to a library called Textract.</p>
<pre><code>def file_to_string(filepath):
text = textract.process(filepath)
print text
return text
</code></pre>
<p>Here is my upload form in views.py</p>
<pre><code>if request.method == 'POST':
upload_form = UploadF... | 0 | 2016-09-19T12:52:55Z | 39,574,169 | <p><code>request.session['text'] = file_to_string(filetosave.file.path)</code> should do the trick</p>
| 0 | 2016-09-19T13:16:13Z | [
"python",
"django",
"django-models",
"django-uploads"
] |
Django - dropdown form with multiple select | 39,573,772 | <p><strong>I need guidance building a django <em>dropdown</em> <code>forms.Form</code> field in which I can select <em>multiple</em> choices. I need to select multiple locations on the <code>office</code> field of the form.</strong></p>
<p>When submitted, the form needs to return a <code>list</code> of the chosen off... | 0 | 2016-09-19T12:55:54Z | 39,573,931 | <p>"Dropdown" boxes don't support multiple selection in HTML; browsers will always render it as a flat box as your image shows.</p>
<p>You probably want to use some kind of JS widget - <a href="https://select2.github.io/" rel="nofollow">Select2</a> is a popular one. There are a couple of Django projects - <a href="htt... | 1 | 2016-09-19T13:03:33Z | [
"python",
"django",
"forms"
] |
Django - dropdown form with multiple select | 39,573,772 | <p><strong>I need guidance building a django <em>dropdown</em> <code>forms.Form</code> field in which I can select <em>multiple</em> choices. I need to select multiple locations on the <code>office</code> field of the form.</strong></p>
<p>When submitted, the form needs to return a <code>list</code> of the chosen off... | 0 | 2016-09-19T12:55:54Z | 39,722,350 | <p>You can choose multiple choices by using Django select2. Include below code in your respective HTML file.</p>
<pre><code><link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min... | 0 | 2016-09-27T10:30:50Z | [
"python",
"django",
"forms"
] |
python - Convert list of dicts to hierarchy/multiple nested dicts - issue with orders | 39,573,845 | <p>Currently I have these input:</p>
<pre><code>query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None}
,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 10}
,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2}
,{'id': 4, 'desc': 'desc_child_5', 'parent_id': 5}
,{'id': 5, 'desc': '... | 1 | 2016-09-19T12:59:09Z | 39,573,941 | <p>This does not require recursion.</p>
<p>First create a dictionary of nodes, one for each item using <code>id</code> as the key, which includes an empty list of children. Then you can scan that dictionary, and add each node to the list of children for its parent (skipping those whose parent is <code>None</code>). ... | 2 | 2016-09-19T13:04:19Z | [
"python",
"dictionary",
"recursion",
"parent-child"
] |
python - Convert list of dicts to hierarchy/multiple nested dicts - issue with orders | 39,573,845 | <p>Currently I have these input:</p>
<pre><code>query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None}
,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 10}
,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2}
,{'id': 4, 'desc': 'desc_child_5', 'parent_id': 5}
,{'id': 5, 'desc': '... | 1 | 2016-09-19T12:59:09Z | 39,575,135 | <p>This would be my solution:</p>
<pre><code>#! /usr/bin/env python3
from pprint import pprint
query = [{'id': 1, 'desc': 'desc_father', 'parent_id': None}
,{'id': 2, 'desc': 'desc_child_1', 'parent_id': 1}
,{'id': 3, 'desc': 'desc_child_2', 'parent_id': 2}
,{'id': 4, 'desc': 'desc_child_5',... | 1 | 2016-09-19T14:03:42Z | [
"python",
"dictionary",
"recursion",
"parent-child"
] |
Building HTML table from list of dictionaries | 39,573,901 | <p>I have a list containing dictionaries that I would like to output into an HTML table.</p>
<p>My list looks like this:</p>
<pre><code>[{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'},
{'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}]
</code></pre>
<p>I am trying to make i... | 0 | 2016-09-19T13:02:07Z | 39,574,046 | <p>You could use an example supplied in the docs for <a href="https://docs.python.org/3/library/contextlib.html" rel="nofollow"><code>contextlib</code></a> and build it accordingly.</p>
<p>Essentially, create a context manager with <a href="https://docs.python.org/3/library/contextlib.html#contextlib.contextmanager" r... | 0 | 2016-09-19T13:09:23Z | [
"python",
"python-3.x"
] |
Building HTML table from list of dictionaries | 39,573,901 | <p>I have a list containing dictionaries that I would like to output into an HTML table.</p>
<p>My list looks like this:</p>
<pre><code>[{'description': 'KA8ts5', 'password': 'KA8ts5', 'username': 'test4'},
{'description': '5j6mEF', 'password': '5j6mEF', 'username': 'test5'}]
</code></pre>
<p>I am trying to make i... | 0 | 2016-09-19T13:02:07Z | 39,574,130 | <p>I would use a <em>template engine</em> like <a href="http://www.makotemplates.org/" rel="nofollow"><code>mako</code></a> or <a href="http://jinja.pocoo.org/docs/dev/" rel="nofollow"><code>jinja2</code></a>.</p>
<p>Example using <code>mako</code>:</p>
<pre><code>from mako.template import Template
template = """
&l... | 1 | 2016-09-19T13:14:16Z | [
"python",
"python-3.x"
] |
How does one create an generalise AttrDict Mixin for a python "dict-style" class? | 39,573,949 | <p>Basically I want to be able to take <code>class</code> that <em>quacks</em> like a <code>dict</code> (eg my example <code>DICT</code> below) and add a <code>MixIn</code> that allows me to access the <code>DICT</code>'s values as attributes... eg </p>
<pre><code>print purchase.price # instead of purchase["price"]
</... | 0 | 2016-09-19T13:04:37Z | 39,576,145 | <p>Implement it like so:</p>
<pre><code>class AttrDictMixin(object):
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
self[name] = value
def __delattr__(self, name):
del self[name]
</code></pre>
<p>Upon attribute access, setting, or deleting - <cod... | 0 | 2016-09-19T14:52:34Z | [
"python",
"class",
"dictionary",
"attributes",
"multiple-inheritance"
] |
Xgboost crossvalidated model access | 39,574,014 | <p>Is there any way I can access the trained <code>xgboost</code> model from <code>xgboost.cv</code> directly? Or do I manually have to loop over the folds and perform a fit in this case?</p>
<pre><code>xgb.cv(param, dtrain, num_round, nfold = 5, seed = 0,
obj = logregobj, feval=evalerror)
</code></pre>
| 0 | 2016-09-19T13:07:51Z | 39,664,355 | <p>First, you cross-validate xgboost as you indicate:</p>
<p><code>xgb.cv_m <- xgb.cv(param, dtrain, num_round, nfold = 5, seed = 0, obj = logregobj, feval=evalerror)</code></p>
<p>Then, the number of rounds needed corresponds to the best AUC (the AUC train and test means and std resulted from cross-validation are... | 1 | 2016-09-23T15:22:25Z | [
"python",
"data-science",
"xgboost"
] |
How to delete pages from pdf file using Python? | 39,574,096 | <p>I have some .pdf files with more than 500 pages, but I need only a few pages in each file. It is necessary to preserve document`s title pages. I know exactly the numbers of the pages that program should remove. How I can do it using Python 2.7 Environment, which is installed upon MS Visual Studio?</p>
| 0 | 2016-09-19T13:12:17Z | 39,574,216 | <p>Use pyPDF2:</p>
<p><a href="https://github.com/mstamy2/PyPDF2" rel="nofollow">https://github.com/mstamy2/PyPDF2</a></p>
<p>Documentation is at:</p>
<p><a href="https://pythonhosted.org/PyPDF2/" rel="nofollow">https://pythonhosted.org/PyPDF2/</a></p>
<p>It seems pretty intuitive.</p>
| 0 | 2016-09-19T13:18:00Z | [
"python",
"pdf"
] |
How to delete pages from pdf file using Python? | 39,574,096 | <p>I have some .pdf files with more than 500 pages, but I need only a few pages in each file. It is necessary to preserve document`s title pages. I know exactly the numbers of the pages that program should remove. How I can do it using Python 2.7 Environment, which is installed upon MS Visual Studio?</p>
| 0 | 2016-09-19T13:12:17Z | 39,574,231 | <p>Try using <a href="https://pypi.python.org/pypi/PyPDF2/1.26.0" rel="nofollow">PyPDF2</a>. Some sample code (adapted from <a href="https://www.binpress.com/tutorial/manipulating-pdfs-with-python/167" rel="nofollow">here</a>).</p>
<pre><code>pages_to_keep = [1,2,10]
from PyPDF2 import PdfFileWriter, PdfFileReader
inf... | 1 | 2016-09-19T13:18:45Z | [
"python",
"pdf"
] |
Missing menuBar in PyQt5 | 39,574,105 | <p>I've been developing a GUI using PyQt5 and wanted to include a menu bar. When I went to code this feature, however, my menu wouldn't appear. Figuring my understanding on how to implement menu bars in PyQt5 was off, I looked for a pre-existing example online. With some tweaking I developed the following test case:</p... | 2 | 2016-09-19T13:12:49Z | 39,574,279 | <p>try this:</p>
<pre><code>menubar = QMenuBar()
self.setMenuBar(menubar)
</code></pre>
<p>instead of <code>menubar = self.menuBar()</code></p>
| 0 | 2016-09-19T13:20:57Z | [
"python",
"osx",
"pyqt",
"pyqt5",
"menubar"
] |
Missing menuBar in PyQt5 | 39,574,105 | <p>I've been developing a GUI using PyQt5 and wanted to include a menu bar. When I went to code this feature, however, my menu wouldn't appear. Figuring my understanding on how to implement menu bars in PyQt5 was off, I looked for a pre-existing example online. With some tweaking I developed the following test case:</p... | 2 | 2016-09-19T13:12:49Z | 39,603,054 | <p>Have you tried the most simple example in the following link <a href="https://www.tutorialspoint.com/pyqt/qmenubar_qmenu_qaction_widgets.htm" rel="nofollow">tutorialspoint</a>.</p>
<p>Here is the most simple example.</p>
<pre><code>import sys
from PyQt5.QtWidgets import QHBoxLayout, QAction, QApplication, QMainWi... | 0 | 2016-09-20T20:16:35Z | [
"python",
"osx",
"pyqt",
"pyqt5",
"menubar"
] |
xpath cant select only one html tag | 39,574,222 | <p>I am trying to get some data from a website, but when i use the following code it's return all of the matched elements, i want to return only 1st match! I've tried extract_first but it returned none!</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
from gumtree.items import GumtreeItem
class FlatSpider(scrap... | 1 | 2016-09-19T13:18:20Z | 39,574,339 | <p>This is because the first element is actually empty - filter out the non-empty values only and use <code>extract_first()</code> - works for me:</p>
<pre><code>$ scrapy shell "https://www.gumtree.com/flats-for-sale" -s USER_AGENT="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko)... | 1 | 2016-09-19T13:24:01Z | [
"python",
"python-3.x",
"xpath",
"web-scraping",
"scrapy"
] |
xpath cant select only one html tag | 39,574,222 | <p>I am trying to get some data from a website, but when i use the following code it's return all of the matched elements, i want to return only 1st match! I've tried extract_first but it returned none!</p>
<pre><code># -*- coding: utf-8 -*-
import scrapy
from gumtree.items import GumtreeItem
class FlatSpider(scrap... | 1 | 2016-09-19T13:18:20Z | 39,646,519 | <p>Strictly speaking it should be <code>response.xpath('(//*[@class="listing-title"])[1]/text()')</code> but if what you want is to grab the title of each ad (to create an item for example) you should probably do this instead:</p>
<pre><code>for article in response.xpath('//article[@data-q]'):
item = GumtreeItem(... | 0 | 2016-09-22T18:36:35Z | [
"python",
"python-3.x",
"xpath",
"web-scraping",
"scrapy"
] |
Override builtin type __str__ method in python | 39,574,286 | <p>I need to port some code from Python2 to Python3 and the main problem seems to be in bytes type, because str(bytes) gives me "b'%s'" result, but '%s' is needed, so I decided to override __str__() method of bytes class to print exactly what I want.</p>
<p>I tried to patch builtins.bytes with class inherited from byt... | 2 | 2016-09-19T13:21:19Z | 39,574,509 | <p>The rule with text is "decode on input, encode on output." Although a lot of work has been done to make it easier to write code that is compatible between v2 and v3, there are always going to be some discrepancies and the fact that Python 3 no longer defines the <code>unicode</code> symbol is one of them.</p>
<p>It... | 2 | 2016-09-19T13:32:17Z | [
"python",
"decode",
"2to3",
"builtins"
] |
Match the last occurrence of delimiter in the expect function of pexpect | 39,574,329 | <p>I utilize pexpect for automation. The delimiter for the command prompt is '>'. However it so happens that sometimes the output itself contain a '>' sign causing the expect function to delimit at that precise location rather than taking all the output till the command prompt.
Is there any way to make expect function ... | 0 | 2016-09-19T13:23:27Z | 39,607,336 | <p>Pexpect cannot tell which <code>></code> is the last one because the spawned process may keep outputting something. To solve your problem you can customize the shell prompt and then you just expect your own shell prompt. For example:</p>
<pre class="lang-none prettyprint-override"><code>[STEP 101] # cat pexp.py
... | 0 | 2016-09-21T04:01:36Z | [
"python",
"shell",
"automation",
"command-line-interface",
"pexpect"
] |
Python urllib2 request exploiting Active Directory authentication | 39,574,388 | <p>I've got a Windows server (Navision) offering web access to its APIs through Active Directory authentication.<br/>
I'm trying to make a request to the web server through Active Directory authentication, by using an external Linux based host.</p>
<p>I successfully authenticated by using <code>python-ldap</code> libr... | 0 | 2016-09-19T13:26:48Z | 39,589,376 | <p>If it's a Dynamics NAV Webservice you want to trigger (didn't see that from code but from tag) you have to activcate ntlm on your NST.
Just change the Property 'ServicesUseNTLMAuthentication' from False to True in your CustomSettings.config or just use the Microsoft Dynamics NAV Administration MMC. Don't forget to r... | 0 | 2016-09-20T08:39:03Z | [
"python",
"active-directory",
"windows-authentication",
"ntlm",
"navision"
] |
Run Length Encoding in python | 39,574,474 | <p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one tim... | -2 | 2016-09-19T13:30:22Z | 39,575,637 | <p>Three remarks:</p>
<ol>
<li>You should use the existing method <code>str.count</code> for the <code>encode</code> function.</li>
<li>The <code>decode</code> function will print <code>count</code> times a character, not the character and its counter.</li>
<li>Actually the <code>decode(encode(string))</code> combinat... | 0 | 2016-09-19T14:28:10Z | [
"python"
] |
Run Length Encoding in python | 39,574,474 | <p>i got homework to do "Run Length Encoding" in python and i wrote a code but it is print somthing else that i dont want. it prints just the string(just like he was written) but i want that it prints the string and if threre are any characthers more than one time in this string it will print the character just one tim... | -2 | 2016-09-19T13:30:22Z | 39,575,748 | <p>Came up with this quickly, maybe there's room for optimization (for example, if the strings are too large and there's enough memory, it would be better to use a set of the letters of the original string for look ups rather than the list of characters itself). But, does the job fairly efficiently:</p>
<pre><code>tex... | 0 | 2016-09-19T14:33:33Z | [
"python"
] |
Python Pandas calculate time until output reaches 0 | 39,574,497 | <p>I have a pandas dataframe in python with several columns and a datetime stamp. One of the columns has a true/false variable. I'd like to calculate time until that column is false.</p>
<p>Ideally it would look something like this:</p>
<pre><code>datetime delivered secondsuntilfailure
2014-05-01 01:00... | 0 | 2016-09-19T13:31:48Z | 39,574,725 | <p>You can first change order by <code>[::-1]</code>, then find <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html" rel="nofollow"><code>diff</code></a> and count <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cumsum.html" rel="nofollow"><code>cumsum</co... | 0 | 2016-09-19T13:43:22Z | [
"python",
"datetime",
"pandas"
] |
Python Pandas calculate time until output reaches 0 | 39,574,497 | <p>I have a pandas dataframe in python with several columns and a datetime stamp. One of the columns has a true/false variable. I'd like to calculate time until that column is false.</p>
<p>Ideally it would look something like this:</p>
<pre><code>datetime delivered secondsuntilfailure
2014-05-01 01:00... | 0 | 2016-09-19T13:31:48Z | 39,575,552 | <p>Count the seconds:</p>
<pre><code>cumsecs = df.datetime.diff().astype('timedelta64[s]').cumsum().fillna(value=0.0)
</code></pre>
<p>Copy the cumulative value whenever delivered fails, and fill any preceeding values:</p>
<pre><code>undeliv_secs = cumsecs.where(~df['delivered']).fillna(method='bfill')
</code></pre>... | 0 | 2016-09-19T14:23:53Z | [
"python",
"datetime",
"pandas"
] |
Reset a python mock generator return value | 39,574,537 | <p>How can I "reset" a method that returns a generator. If I mock this method but use the parent class twice in a method under test, the first call consumes the generator and the second call has no data. Sample code below. The two calls to get_values should return the same (mocked) list.</p>
<pre><code>import mock
cl... | 1 | 2016-09-19T13:33:24Z | 39,575,889 | <p>How's this?</p>
<pre><code>mock_class.side_effect = lambda x: {'a': '10', 'b': '20'}.iteritems()
</code></pre>
<p>Side effect occurs every call thus recreates every time.</p>
<p>You can even set the dict before like so</p>
<pre><code>my_dict = {'a': '10', 'b': '20'}
mock_class.side_effect = lambda x: my_dict.ite... | 2 | 2016-09-19T14:40:15Z | [
"python",
"mocking"
] |
text document sorting to sides | 39,574,541 | <p>I'm currently learning python and I am supposed to write a program which asks a user for input of name and then input of age, It is supposed to look like this "<a href="http://i.imgur.com/hcMTJuK.png" rel="nofollow">http://i.imgur.com/hcMTJuK.png</a>" Sorry i cannot add pictures yet since I don't have 10 rep yet, bu... | 0 | 2016-09-19T13:33:46Z | 39,574,820 | <p>I am currently learning Python, too. I am excited because I think I can help you.</p>
<p>So what I would try and do is to put "Name" and "Age" on the same line and assign it to the variable "title". What I think will also help you is if you use a variable called "space" so that you'll be able to control the forma... | 0 | 2016-09-19T13:47:45Z | [
"python",
"project"
] |
Django redirect after logout | 39,574,559 | <p>I'm using Django and to authenticate my user, I have a custom OAuth2 provider. I had to write the login and logout view myself because they are doing some very specific things.</p>
<p>I would like to be redirected to the same url after logout. If you are on a page that require to be authenticated, I would like to r... | 0 | 2016-09-19T13:34:42Z | 39,574,655 | <p>The <a href="https://docs.djangoproject.com/en/1.10/topics/auth/default/#the-login-required-decorator" rel="nofollow"><code>login_required</code></a> decorator takes a parameter to redirect users. You could use this.</p>
<p>As of Django 1.9, you could also use the <a href="https://docs.djangoproject.com/en/1.10/top... | 0 | 2016-09-19T13:39:32Z | [
"python",
"django"
] |
Django redirect after logout | 39,574,559 | <p>I'm using Django and to authenticate my user, I have a custom OAuth2 provider. I had to write the login and logout view myself because they are doing some very specific things.</p>
<p>I would like to be redirected to the same url after logout. If you are on a page that require to be authenticated, I would like to r... | 0 | 2016-09-19T13:34:42Z | 39,574,865 | <p>Sure, just use query string parameter <code>next</code>, e.g.: </p>
<pre><code><a href="{% url 'users:user_logout' %}?next={% url 'some_url' %}">Log out</a>
</code></pre>
<p>The rest is only a matter of arranging template hierarchy, so you will use different urls in different templates without repetiti... | 0 | 2016-09-19T13:49:47Z | [
"python",
"django"
] |
Acessing a variable as a string in a module | 39,574,560 | <p>Following other posts here, I have a function that prints out information about a variable based on its name. I would like to move it into a module.</p>
<pre><code>#python 2.7
import numpy as np
def oshape(name):
#output the name, type and shape/length of the input variable(s)
#for array or list
x=glob... | 5 | 2016-09-19T13:34:43Z | 39,574,697 | <p>The actual problem you have here is a namespace problem.</p>
<p>You could write your method this way:</p>
<pre><code>def oshape(name, x):
# output the name, type and shape/length of the input variable(s)
# for array or list
if type(x) in (np.array, np.ndarray):
print('{:20} {:25} {}'.format(nam... | 2 | 2016-09-19T13:41:53Z | [
"python",
"python-2.7"
] |
Acessing a variable as a string in a module | 39,574,560 | <p>Following other posts here, I have a function that prints out information about a variable based on its name. I would like to move it into a module.</p>
<pre><code>#python 2.7
import numpy as np
def oshape(name):
#output the name, type and shape/length of the input variable(s)
#for array or list
x=glob... | 5 | 2016-09-19T13:34:43Z | 39,575,206 | <p>Your logic is way over complicated, you should just pass the arrays themselves as you are also already passing the variable name as a string so you are not looking up something you don't have access to. But if you wanted to make your code work exactly as is you could set an attibute on the module:</p>
<pre><code>im... | 1 | 2016-09-19T14:06:47Z | [
"python",
"python-2.7"
] |
merge() missing 1 required positional argument: 'right' | 39,574,571 | <p>I am doing a tutorial and I have a problem:
<strong>My code:</strong></p>
<pre><code>import html5lib
import quandl
import pandas as pd
import pickle
pd.read_html("https://simple.wikipedia.org/wiki/List_of_U.S._states")
main_df = pd.DataFrame()
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of... | 0 | 2016-09-19T13:35:26Z | 39,577,959 | <pre><code>main_df.merge(df, how = "right")
</code></pre>
| 0 | 2016-09-19T16:35:19Z | [
"python",
"pandas"
] |
How to create a custom field in python jira | 39,574,585 | <p>I'd like to store some extra information in a custom field. So I create a dictionary for my issue:</p>
<pre><code> issue_dict = {
'project': 'PROJECT-TITLE',
'summary': 'issue title',
'description': 'issue description',
'assignee': 'issue assignee',
... | 1 | 2016-09-19T13:36:14Z | 39,589,103 | <p>One workaround that I found was to store the information in a comment instead and parsing <code>comment body</code>instead. It ain't pretty though.</p>
| 0 | 2016-09-20T08:24:39Z | [
"python",
"python-jira"
] |
ImportError: cannot import name 'QtCore' | 39,574,639 | <p>I am getting the below error with the following imports.
It seems to be related to pandas import. I am unsure how to debug/solve this.</p>
<p>Imports:</p>
<pre><code>import pandas as pd
import numpy as np
import pdb, math, pickle
import matplotlib.pyplot as plt
</code></pre>
<p>Error:</p>
<pre><code>In [1]: %run... | 11 | 2016-09-19T13:38:41Z | 39,577,184 | <p>Downgrading pyqt version 5.6.0 to 4.11.4, and qt from version 5.6.0 to 4.8.7 fixes this:</p>
<pre><code>$ conda install pyqt=4.11.4
$ conda install qt=4.8.7
</code></pre>
<p>The issue itself is being resolved here: <a href="https://github.com/ContinuumIO/anaconda-issues/issues/1068">https://github.com/ContinuumIO/... | 11 | 2016-09-19T15:50:01Z | [
"python",
"anaconda",
"python-import",
"qtcore"
] |
ImportError: cannot import name 'QtCore' | 39,574,639 | <p>I am getting the below error with the following imports.
It seems to be related to pandas import. I am unsure how to debug/solve this.</p>
<p>Imports:</p>
<pre><code>import pandas as pd
import numpy as np
import pdb, math, pickle
import matplotlib.pyplot as plt
</code></pre>
<p>Error:</p>
<pre><code>In [1]: %run... | 11 | 2016-09-19T13:38:41Z | 39,756,863 | <p>To avoid downgrading you can also (as was suggested by tacaswell in the issue) set the backend to use <code>Qt5Agg</code> using one of the methods here: <a href="http://matplotlib.org/faq/usage_faq.html#what-is-a-backend" rel="nofollow">http://matplotlib.org/faq/usage_faq.html#what-is-a-backend</a></p>
<p>E.g., you... | 1 | 2016-09-28T20:15:42Z | [
"python",
"anaconda",
"python-import",
"qtcore"
] |
ImportError: cannot import name 'QtCore' | 39,574,639 | <p>I am getting the below error with the following imports.
It seems to be related to pandas import. I am unsure how to debug/solve this.</p>
<p>Imports:</p>
<pre><code>import pandas as pd
import numpy as np
import pdb, math, pickle
import matplotlib.pyplot as plt
</code></pre>
<p>Error:</p>
<pre><code>In [1]: %run... | 11 | 2016-09-19T13:38:41Z | 40,113,906 | <p>Updating matplotlib did the trick for me: </p>
<pre><code>conda install matplotlib
</code></pre>
| 1 | 2016-10-18T16:52:03Z | [
"python",
"anaconda",
"python-import",
"qtcore"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.