title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How do you iteratre over a list performing some operation that turns a single element into multiple? | 39,599,807 | <p>I have a csv file of data from a LiDAR sensor that looks like this, but with a bagillion more lines:</p>
<pre><code>scan_0,scan_1,scan_2
timestamp_0,timestamp_1,timestamp_2
7900200,7900225,7900250
logTime_0,logTime_1,logTime_2
27:46.8,27:46.8,27:46.8
distance_0,distance_0,distance_0
132,141,139
136,141,155
139,141,... | 2 | 2016-09-20T16:56:00Z | 39,600,163 | <p>The problem that you have is that you are trying to assign new value to variable that does not reference to array.</p>
<p>So you have </p>
<pre><code>for x in my_r:
i=0
while i < row_count/360:
x = [x*math.cos(i), x*math.sin(i), i]
i = i + row_count/360
</code></pre>
<p>You cannot do th... | 1 | 2016-09-20T17:17:51Z | [
"python"
] |
Django password field input showing up as plaintext despite forms.PasswordInput declaration | 39,599,839 | <p>Django password field input showing up as plaintext despite <code>widget=forms.PasswordInput</code> declaration:</p>
<h1>forms.py</h1>
<pre><code>from django.contrib.auth.models import User
class LoginForm(forms.ModelForm):
# specify password type so that passwords show up as *******, not plaintext
# but t... | 0 | 2016-09-20T16:58:04Z | 39,599,912 | <p>You should not be using <code>forms.TextInput</code> for your password field. <a href="https://docs.djangoproject.com/en/1.10/ref/forms/widgets/#passwordinput" rel="nofollow">Django provides a PasswordInput widget</a> that is more appropriate. Try this:</p>
<pre><code>class Meta:
model = User
fields = ["use... | 3 | 2016-09-20T17:02:35Z | [
"python",
"django",
"forms"
] |
Raspberry send data via serial USB to Arduino Python | 39,599,857 | <p>Hi I have connected my raspberry to arduino via serial USB and on arduino there is a led that I want turn on if in the script in python I send a letter o a number</p>
<p>I have write this code in raspberry Python:</p>
<pre><code>import serial
ser=serial.Serial('/dev/ttyUSB0', 9600)
ser.write('3')
</code></pre>
<p... | 0 | 2016-09-20T16:59:18Z | 39,600,005 | <p>There is a typo in the if statement, you have put vale instead of val.</p>
<pre><code>ser.write('3')
</code></pre>
<p>takes 3 as a string.So try this in the if statement,</p>
<pre><code>if(val=='3')
</code></pre>
| 0 | 2016-09-20T17:07:54Z | [
"python",
"serialization",
"arduino"
] |
building simple terminal pyqt4 and pyserial how to update textbrowser | 39,600,006 | <p>I have followed a simple tutorial on creating a basic gui using qt designer and have incorporated that into python. I then made a simple python script that just continuously reads newlines from the serial port and prints them to the terminal. I want to combine them but I'm afraid my understanding of how pyqt4 works ... | 0 | 2016-09-20T17:07:57Z | 39,601,336 | <p>For anyone that has a similar issue. I found a solution by implementing a timer and creating a new function in the class:</p>
<pre><code>self.my_timer = QtCore.QTimer()
self.my_timer.timeout.connect(self.print_serial)
self.my_timer.start(10) # milliseconds
def print_serial(self):
if ser... | 0 | 2016-09-20T18:31:07Z | [
"python",
"pyqt",
"pyserial"
] |
Using a decorator to bring variables into decorated function namespace | 39,600,106 | <p>Say I have a function that looks like this:</p>
<pre><code>def func(arg1, arg2):
return arg1 + arg2 + arg3
</code></pre>
<p>And I want to bring in <code>arg3</code> using an argument passed to a decorator. Is this possible and if so how would this be done?</p>
<p>I've tried this which was suggested <a href="h... | -1 | 2016-09-20T17:13:41Z | 39,600,533 | <p>You can do it like that</p>
<pre><code>from functools import wraps
def addarg(arg):
def decorate(func):
@wraps(func)
def wrapped(*args):
return func(*args, arg)
return wrapped
return decorate
@addarg(3)
def func(arg1, arg2, *args):
return arg1 + arg2 + sum(args)
i... | 0 | 2016-09-20T17:43:24Z | [
"python",
"function",
"namespaces",
"python-decorators"
] |
Using a decorator to bring variables into decorated function namespace | 39,600,106 | <p>Say I have a function that looks like this:</p>
<pre><code>def func(arg1, arg2):
return arg1 + arg2 + arg3
</code></pre>
<p>And I want to bring in <code>arg3</code> using an argument passed to a decorator. Is this possible and if so how would this be done?</p>
<p>I've tried this which was suggested <a href="h... | -1 | 2016-09-20T17:13:41Z | 39,601,696 | <p>It's a little on the hacky side, but this implmentation of the decorator seems to do what you want. The <code>arg3</code> variable had to be made to appear as a global because it's referenced as one in the byte-code generated from the definition of <code>func()</code>, so it's not really considered a function argume... | 1 | 2016-09-20T18:50:58Z | [
"python",
"function",
"namespaces",
"python-decorators"
] |
Can't import tkinter (or Tkinter) | 39,600,159 | <p>I am trying to import Tkinter to my project using Python 2.7 and instead I get the error:</p>
<pre><code>ImportError: No module named tkinter
</code></pre>
<p>Before anyone says it, I have tried both "Tkinter" and "tkinter" but have gotten the exact same message.</p>
| -1 | 2016-09-20T17:17:33Z | 39,822,599 | <p>First try using this code for your imports.</p>
<pre><code>try:
import Tkinter as tk # this is for python2
except:
import tkinter as tk # this is for python3
</code></pre>
<p>If this doesn't work, try reinstalling tkinter. If you don't know how to reinstall tkinter look at the tkinter installation page,<a ... | 1 | 2016-10-02T22:59:10Z | [
"python",
"import",
"tkinter"
] |
Regular expression matching all but a string | 39,600,161 | <p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a'... | 4 | 2016-09-20T17:17:43Z | 39,600,219 | <p>You need to use a negative lookahead to restrict a more generic pattern, and a <code>re.findall</code> to find all matches.</p>
<p>Use</p>
<pre><code>res = re.findall(r'-(?!(?:aa|bb)-)(\w+)(?=-)', s)
</code></pre>
<p>or - if your values in between hyphens can be any but a hyphen, use a negated character class <c... | 2 | 2016-09-20T17:21:32Z | [
"python",
"regex"
] |
Regular expression matching all but a string | 39,600,161 | <p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a'... | 4 | 2016-09-20T17:17:43Z | 39,600,224 | <p>You can make use of negative look aheads.</p>
<p>For example,</p>
<pre><code>>>> re.findall(r'-(?!aa|bb)([^-]+)', string)
['a', 'bc', 'def', 'ghij']
</code></pre>
<hr>
<ul>
<li><p><code>-</code> Matches <code>-</code></p></li>
<li><p><code>(?!aa|bb)</code> Negative lookahead, checks if <code>-</code> is... | 6 | 2016-09-20T17:21:46Z | [
"python",
"regex"
] |
Regular expression matching all but a string | 39,600,161 | <p>I need to find all the strings matching a pattern with the exception of two given strings. </p>
<p>For example, find all groups of letters with the exception of <code>aa</code> and <code>bb</code>. Starting from this string:</p>
<pre><code>-a-bc-aa-def-bb-ghij-
</code></pre>
<p>Should return:</p>
<pre><code>('a'... | 4 | 2016-09-20T17:17:43Z | 39,600,980 | <p>Although a regex solution was asked for, I would argue that this problem can be solved easier with simpler python functions, namely string splitting and filtering:</p>
<pre><code>input_list = "-a-bc-aa-def-bb-ghij-"
exclude = set(["aa", "bb"])
result = [s for s in input_list.split('-')[1:-1] if s not in exclude]
</... | 0 | 2016-09-20T18:10:58Z | [
"python",
"regex"
] |
What is the fastest way to put the first axis behind the last one? [numpy] | 39,600,233 | <p>Let us look at this stupid example with a N0 x N1 x ... x Nm dimensional array, such as </p>
<pre><code>import numpy as np
x = np.random.random([N0,N1,...,Nm])
</code></pre>
<p>Now I want the N0 dimension to be behind the last one, i.e.</p>
<pre><code>np.swapaxis np.swapaxis(np.swapaxis(x, 0,1),1,2) ... # swappi... | 1 | 2016-09-20T17:22:28Z | 39,600,367 | <blockquote>
<p>I tried with np.rollaxis, but this seems to be the wrong function.</p>
</blockquote>
<p>No, it's the right function.</p>
<pre><code>x = numpy.rollaxis(x, 0, x.ndim)
</code></pre>
| 1 | 2016-09-20T17:31:16Z | [
"python",
"numpy"
] |
How to capture website screenshot in high resolution? | 39,600,245 | <p>I want to capture screenshot of a website in high resolution to recognize text or simply to save high quality images. I tried this code in Python 2.7. The website <a href="http://www.flaticon.com/" rel="nofollow">http://www.flaticon.com/</a> has been taken merely as example.</p>
<pre><code>from selenium import web... | 1 | 2016-09-20T17:23:23Z | 39,600,457 | <p>If it is about changing window size, you can set it by</p>
<pre><code>driver.set_window_size(480, 320)
</code></pre>
<p>Here is an example of doing this from <a href="https://gist.github.com/jsok/9502024" rel="nofollow">Github</a> of one of the developers. As you can see, you can adjust both Window size and qualit... | 1 | 2016-09-20T17:36:45Z | [
"python",
"selenium-webdriver"
] |
Django settings.py not updating | 39,600,309 | <p>I have enabled the setting:</p>
<p><code>USE_X_FORWARDED_HOST = True</code></p>
<p>in my settings.py. I am currently deploying the server, but when I try to render my index page it gives me a 404. The email says that it is a:</p>
<p><code>Invalid HTTP_HOST header: u'127.0.0.1:9001</code></p>
<p>And BEFORE ANYONE... | 0 | 2016-09-20T17:27:55Z | 39,617,323 | <p>Solved the problem. The redis server had to be restarted everytime the settings.py was updated for some reason.</p>
| 0 | 2016-09-21T13:01:43Z | [
"python",
"django",
"django-settings",
"django-deployment",
"django-channels"
] |
Dictionary Combinations - Unequal Number of Keys & Values | 39,600,405 | <p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><co... | 1 | 2016-09-20T17:33:21Z | 39,600,446 | <p>You were really close:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
# iterate on key/items couple
for k,vl in items.items():
# iterate on all values of the list
for v in vl:
# print with a simple format
print("{} {}".format(k,v))
</code></pre>
<p>output:</p>
<pre><... | 1 | 2016-09-20T17:35:57Z | [
"python",
"loops",
"dictionary"
] |
Dictionary Combinations - Unequal Number of Keys & Values | 39,600,405 | <p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><co... | 1 | 2016-09-20T17:33:21Z | 39,600,491 | <p>Using <a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain.from_iterables</code></a> and <a href="http://www.secnetix.de/olli/Python/list_comprehensions.hawk" rel="nofollow">list comprehension</a>, you can "flatten" this to a list of tuples:</p>
<pre><code>... | 1 | 2016-09-20T17:39:34Z | [
"python",
"loops",
"dictionary"
] |
Dictionary Combinations - Unequal Number of Keys & Values | 39,600,405 | <p>I want to print all unique combinations of keys and values for this dictionary:</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
</code></pre>
<p>Using the code,</p>
<pre><code>for key, value in items.items():
print(key,value)
</code></pre>
<p>I receive the following output:</p>
<pre><co... | 1 | 2016-09-20T17:33:21Z | 39,600,568 | <p>Or simply :</p>
<pre><code>items = {'a':[10,100,1000],'b':[11,110],'c':[12,120]}
for key, value in items.items():
for v in value :
print(key,v)
</code></pre>
| 2 | 2016-09-20T17:45:42Z | [
"python",
"loops",
"dictionary"
] |
Unicode issues when writing to CSV file | 39,600,483 | <p>I need some guidance, please. I'm using the following code: </p>
<pre><code>import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
reqSoup = bs4.BeautifulSoup(results.text, "html.parser... | 1 | 2016-09-20T17:38:58Z | 39,600,588 | <p>For removing the dashes try <code>y.replace("â","-").replace("â","-")</code> (first one is em-dash to minus, second one is en-dash to minus)</p>
<p>If you only want ASCII-codepoints you can remove everything else with</p>
<pre><code>import string
whitelist=string.printable+string.whitespace
def clean(s):
r... | 1 | 2016-09-20T17:46:51Z | [
"python",
"python-3.x",
"unicode"
] |
Unicode issues when writing to CSV file | 39,600,483 | <p>I need some guidance, please. I'm using the following code: </p>
<pre><code>import requests
import bs4
import csv
results = requests.get('http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/top-engineering-schools/eng-rankings?int=a74509')
reqSoup = bs4.BeautifulSoup(results.text, "html.parser... | 1 | 2016-09-20T17:38:58Z | 39,611,047 | <p>Learn to embrace Unicode...the world isn't ASCII anymore.</p>
<p>Assuming you are on Windows and viewing the .CSV with Excel or Notepad, use the following line on Python 3. With only this change (and fixing indentation of your post), You will even be able to view the non-ASCII characters correctly. Notepad and Ex... | 0 | 2016-09-21T08:16:25Z | [
"python",
"python-3.x",
"unicode"
] |
Appending lists according to a pair of lists (IndexError: list index out of range) | 39,600,504 | <p>I have these lists:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 4, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 6, 0, 0], [0, 0, 0, 0, 0, 5]]
crit = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3... | -3 | 2016-09-20T17:40:48Z | 39,600,672 | <p>At the time the exception is raised your Z value 4 but the n_crit is a list of 4 so index 4 (5th in the list) doesn't exist </p>
| 0 | 2016-09-20T17:51:45Z | [
"python",
"list",
"for-loop",
"append"
] |
Appending lists according to a pair of lists (IndexError: list index out of range) | 39,600,504 | <p>I have these lists:</p>
<pre><code>n_crit = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 4, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 6, 0, 0], [0, 0, 0, 0, 0, 5]]
crit = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3... | -3 | 2016-09-20T17:40:48Z | 39,601,183 | <p>Apparently it was caused by out-of-range when referring list element. </p>
<p>For the first example, consider the dimensions of the list (try to think the list as two dimensions of matrix, each element in list is a row in matrix)</p>
<pre><code>n_crit = 7x6 (6x5, if starts with 0)
crit = 6x6 (5x5, if starts with 0... | 1 | 2016-09-20T18:22:18Z | [
"python",
"list",
"for-loop",
"append"
] |
Flaw in hangman program | 39,600,549 | <p>I need to write a simple hangman function that takes in one string (the word that's being guessed) and a list of letters (the letters that are guessed).
Here is my code so far:</p>
<pre><code>def WordGuessed(Word, letters):
if letters == []:
return False
else:
for i in letters:
i... | 0 | 2016-09-20T17:44:16Z | 39,600,776 | <p>You are returning False as soon as you find a guessed letter that is not in the word. In your example, the very first letter is not in the word.</p>
<p>It would work if instead you loop through <code>Word</code> and check each letter if it is in the array <code>letters</code>:</p>
<pre><code>def WordGuessed(Word, ... | 0 | 2016-09-20T17:57:49Z | [
"python"
] |
Python 3.5.2 web-scraping - list index out of range | 39,600,662 | <p>I am new web scraping and trying to scrap all the contents of Restaurant's Details Form so that I can proceed my further scraping.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib
url = "https://www.foodpanda.in/restaurants"
r=requests.get(url)
soup=BeautifulSoup(r.content,"html.parser")
... | 0 | 2016-09-20T17:51:06Z | 39,601,782 | <p>The problem is with accessing element at index <code>0</code> for <code>soup.find_all("Section",class_="js-infscroll-load-more-here"ââ)</code>, because the result is an empty list.</p>
| 0 | 2016-09-20T18:55:23Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Python 3.5.2 web-scraping - list index out of range | 39,600,662 | <p>I am new web scraping and trying to scrap all the contents of Restaurant's Details Form so that I can proceed my further scraping.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import urllib
url = "https://www.foodpanda.in/restaurants"
r=requests.get(url)
soup=BeautifulSoup(r.content,"html.parser")
... | 0 | 2016-09-20T17:51:06Z | 39,605,554 | <p>html has no notion of uppercase tag and regardless even in the source itself it is <em>section</em> not <em>Section</em> with a lowercase s:</p>
<pre><code>section = soup.find_all("section",class_="js-infscroll-load-more-here")[0]
</code></pre>
<p>Since there is only one you can also use find:</p>
<pre><code> sec... | 0 | 2016-09-21T00:05:37Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Tkinter call function in another class | 39,600,676 | <p>Hi i got some code from an answer on <a href="http://stackoverflow.com/questions/7546050/switch-between-two-frames-in-tkinter">Switch between two frames in tkinter</a> which im trying to modify so a button in the StartPage class can call a function called msg in PageOne class. </p>
<p>But im getting this error:</p>... | -1 | 2016-09-20T17:52:09Z | 39,621,662 | <p>Since you're instantiating all your classes in a loop, the easiest way to add references between them is probably to do it after that loop. Remove those references from inside the class, as they won't be valid until after instantiation. Note how <code>button3</code> is no longer created or packed in <code>StartPage<... | 0 | 2016-09-21T16:15:16Z | [
"python",
"tkinter"
] |
How to paint on top of QListWidget in eventfilter in PyQt4/PySide? | 39,600,696 | <p>I tried this on QLable and it works, I do not want to subclass the widget, because they are defined in .ui files, and I just need to do simple modification so I want to avoid delegate. If I put my code in paintEvent it works, but why I can not put it in eventfilter? </p>
<p>It seems it painted the square but it's b... | 1 | 2016-09-20T17:53:23Z | 39,601,599 | <p>You need to install the event-filter on the viewport:</p>
<pre><code>class xxxx(QListWidget):
def __init__(self, parent=None):
super(xxxx, self).__init__(parent)
self.viewport().installEventFilter(self)
def eventFilter(self, widget, event):
if event.type() == QEvent.Paint:
... | 0 | 2016-09-20T18:46:14Z | [
"python",
"pyqt",
"pyside",
"qpainter",
"qlistwidget"
] |
How to print query result in python/django | 39,600,741 | <p>I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:</p>
<ul>
<li>A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpag... | 0 | 2016-09-20T17:55:24Z | 39,602,003 | <p>The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.</p>
<p>If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send <code>{'soc': s... | 0 | 2016-09-20T19:07:49Z | [
"php",
"python",
"django",
"cakephp",
"pprint"
] |
How to print query result in python/django | 39,600,741 | <p>I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:</p>
<ul>
<li>A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpag... | 0 | 2016-09-20T17:55:24Z | 39,602,469 | <p>I meant something like this in CakePHP</p>
<pre><code>/* First, create our posts table: */
CREATE TABLE posts (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(50),
body TEXT,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
/* Then insert some posts for testing: */
IN... | 0 | 2016-09-20T19:37:13Z | [
"php",
"python",
"django",
"cakephp",
"pprint"
] |
Webassets + Typescript, cannot resolve symbols/modules | 39,600,748 | <p>I have a flask project with the following structure:</p>
<pre><code>ââ app.py
ââ project
| ââ __init__.py
| ââ static
| ââ typescript
| ââ app.ts
ââ typings
ââ globals
| ââ ... # multiple imported ts libraries
ââ index.d.ts
</code></pre>
<p>I'm using a... | 0 | 2016-09-20T17:55:57Z | 39,604,440 | <p>I <em>kind of</em> solved it...</p>
<pre><code>glob_string = os.path.join(config.APP_ROOT, '..', 'typings', '*', '*', '*.d.ts')
assets.register('javascript', Bundle(
glob.glob(glob_string),
'typescript/app.ts',
filters = ('typescript', 'jsmin'),
output = 'js/app-%(version)s.js'
))
</code></pre>
<p... | 0 | 2016-09-20T22:04:37Z | [
"python",
"typescript",
"flask",
"webpack",
"webassets"
] |
Hacking tail-optimization | 39,600,764 | <p>I've recently discovered the <code>inspect</code> and thought if it's possible to manually remove "outer" frames of the current frame and thus implementing tail-recursion optimization. </p>
<p><strong>Is it possible? How?</strong></p>
| 0 | 2016-09-20T17:57:06Z | 39,600,829 | <p>It's not possible. <code>inspect</code> doesn't let you rewrite the stack that way, and in any case, it only gives Python stack frames. Even if you could change how the Python stack frames hook up to each other, the C call stack would be unaffected.</p>
| 1 | 2016-09-20T18:01:06Z | [
"python",
"optimization",
"tail-recursion"
] |
Django 1.9 check if email already exists | 39,600,784 | <p>My site is set up so there is no username (or rather user.username = user.email). Django has an error message if a user tries to input a username that is already in the database, however since I'm not using a username for registration I can't figure out how to do this. </p>
<p>Just like the default settings already... | 1 | 2016-09-20T17:58:08Z | 39,602,446 | <p>You can override the <code>clean_<INSERT_FIELD_HERE>()</code> method on the <code>UserForm</code> to check against this particular case. It'd look something like this:</p>
<p><em>forms.py:</em></p>
<pre><code>class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('email',)
... | 1 | 2016-09-20T19:35:38Z | [
"python",
"ajax",
"django",
"django-forms",
"django-templates"
] |
Why can you close() a file object more than once? | 39,600,786 | <p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error wh... | 1 | 2016-09-20T17:58:19Z | 39,600,863 | <p>Resource management is a big deal. It's part of the reason why we have context managers in the first place.</p>
<p>I'm <em>guessing</em> that the core development team thought that it is better to make it "safe" to call close more than once to encourage people to close their files. Otherwise, you could get yourse... | 3 | 2016-09-20T18:03:18Z | [
"python"
] |
Why can you close() a file object more than once? | 39,600,786 | <p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error wh... | 1 | 2016-09-20T17:58:19Z | 39,600,900 | <ol>
<li><p>Thinking about <code>with</code> is just wrong. This behaviour has been in Python <em>forever</em> and thus it's worth keeping it for backward compatibility.</p></li>
<li><p>Because it would serve no purpose to raise an exception. If you have an actual bug in your code where you might close the file before ... | 2 | 2016-09-20T18:06:11Z | [
"python"
] |
Why can you close() a file object more than once? | 39,600,786 | <p>This question is purely out of curiosity. Brought up in a recent discussion for a question <a href="http://stackoverflow.com/questions/39599926/what-does-with-open-do-in-this-situation/39600026?noredirect=1#39600026">here</a>, I've often wondered why the context manager (<code>with</code>) does not throw an error wh... | 1 | 2016-09-20T17:58:19Z | 39,600,961 | <p>Function call fulfilled its promise - after calling it file <strong>is closed</strong>. It's not like something <em>failed</em>, it's just you did not have to do anything at all to ensure condition you we're asking for.</p>
| 0 | 2016-09-20T18:10:08Z | [
"python"
] |
Scraping values from a webpage table | 39,600,800 | <p>I want to create a python dictionary of color names to background color from this <a href="http://people.csail.mit.edu/jaffer/Color/M.htm" rel="nofollow">color dictionary</a>.</p>
<p>What is the best way to access the color name strings and the background color hex values? I want to create a mapping for color name ... | 1 | 2016-09-20T17:58:56Z | 39,603,058 | <p>The webpage that you are trying to scrape is horribly-formed HTML. After <code>View Page Source</code>, it is apparent that most rows start with a <code><tr></code> and then have one or more <code><td></code> elements, all without their closing tags. With <code>BeautifulSoup</code> one should specify an ... | 0 | 2016-09-20T20:16:57Z | [
"python",
"html",
"beautifulsoup"
] |
Scraping values from a webpage table | 39,600,800 | <p>I want to create a python dictionary of color names to background color from this <a href="http://people.csail.mit.edu/jaffer/Color/M.htm" rel="nofollow">color dictionary</a>.</p>
<p>What is the best way to access the color name strings and the background color hex values? I want to create a mapping for color name ... | 1 | 2016-09-20T17:58:56Z | 39,603,387 | <p>Just look for the tds with nowrap, extract the text and get the following siblings td's <em>style</em> attribute:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
page = requests.get('http://people.csail.mit.edu/jaffer/Color/M.htm')
soup = BeautifulSoup(page.content)
for td in soup.select("td[nowrap]")... | 2 | 2016-09-20T20:42:20Z | [
"python",
"html",
"beautifulsoup"
] |
Setting pandas.DataFrame string dtype (not file based) | 39,600,816 | <p>I'm having trouble with using <code>pandas.DataFrame</code>'s constructor and using the <code>dtype</code> argument. I'd like to preserve string values, but the following snippets always convert to a numeric type and then yield <code>NaN</code>s.</p>
<pre><code>from __future__ import unicode_literals
from __future_... | 1 | 2016-09-20T18:00:36Z | 39,601,970 | <p>This is not a proper answer, but while you get one by someone else, I've noticed that using the <code>read_csv</code> function everything works.</p>
<p>So if you place your data in a <code>.csv</code> file called <code>myData.csv</code>, like this:</p>
<pre><code>great,good,average,bad,horrible
alice,,,,2016-05-24... | 0 | 2016-09-20T19:06:03Z | [
"python",
"pandas",
"numpy"
] |
Setting pandas.DataFrame string dtype (not file based) | 39,600,816 | <p>I'm having trouble with using <code>pandas.DataFrame</code>'s constructor and using the <code>dtype</code> argument. I'd like to preserve string values, but the following snippets always convert to a numeric type and then yield <code>NaN</code>s.</p>
<pre><code>from __future__ import unicode_literals
from __future_... | 1 | 2016-09-20T18:00:36Z | 39,602,426 | <p>For the particular case in the OP, you can use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_dict.html" rel="nofollow"><code>DataFrame.from_dict()</code> constructor</a> (see also the <a href="http://pandas.pydata.org/pandas-docs/stable/dsintro.html#alternate-constructors" ... | 1 | 2016-09-20T19:34:08Z | [
"python",
"pandas",
"numpy"
] |
Python 3.X Rock Paper Scissors Lizard Spock issue | 39,600,824 | <p>Hello i am new to coding but i have been stuck on a code for very long and can't seem to find the answer here on stackoverflow. </p>
<p>Whatever i do the answer ends up with the first print of Player 1 wins: Player One wins, Rock beats Scissors.</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, S... | 0 | 2016-09-20T18:00:49Z | 39,600,861 | <p>You are not properly constructing your conditions.</p>
<pre><code>elif (player1 == 1, player2 == 3)
</code></pre>
<p>This creates a <code>tuple</code> and then checks it for truthiness, which always succeeds, because that <code>tuple</code> is not empty. You need to use the logical operator <code>and</code>:</p>
... | 6 | 2016-09-20T18:03:07Z | [
"python"
] |
Python 3.X Rock Paper Scissors Lizard Spock issue | 39,600,824 | <p>Hello i am new to coding but i have been stuck on a code for very long and can't seem to find the answer here on stackoverflow. </p>
<p>Whatever i do the answer ends up with the first print of Player 1 wins: Player One wins, Rock beats Scissors.</p>
<pre><code>player1 = input("Player One do you want Rock, Paper, S... | 0 | 2016-09-20T18:00:49Z | 39,600,945 | <p>While TigerHawk covered your condiction, you also have to cast your inputs to ints.</p>
<pre><code>player1 = int(player1)
player2 = int(player2)
</code></pre>
<p>Right now you are comparing a str (your input) to an int (<code>player == 1</code>). Which won't yield what you want.</p>
<pre><code>player1 == 1 #... | 0 | 2016-09-20T18:09:08Z | [
"python"
] |
Understanding python slicings syntax as described in the python language reference | 39,600,833 | <p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= express... | 5 | 2016-09-20T18:01:14Z | 39,600,891 | <p>That's valid syntax, so you didn't get a SyntaxError. It's just not a meaningful or supported operation on Python lists. Similarly, <code>"5" + fish</code> isn't a SyntaxError, <code>1/0</code> isn't a SyntaxError, and <code>I.am.a.monkey</code> isn't a SyntaxError.</p>
<p>You can't just expect all syntactically va... | 2 | 2016-09-20T18:05:22Z | [
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference | 39,600,833 | <p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= express... | 5 | 2016-09-20T18:01:14Z | 39,600,904 | <p>A <code>slice_list</code> should contain as many "dimensions" as the object being indexed. The multi-dimensional capability is not used by any Python library object that I am aware of, but you can test it easily with <code>numpy</code>:</p>
<pre><code>import numpy as np
a = np.array([[1, 2], [3, 4]])
a[0:1, 0]
</co... | 2 | 2016-09-20T18:06:38Z | [
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference | 39,600,833 | <p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= express... | 5 | 2016-09-20T18:01:14Z | 39,601,204 | <p>This isn't a syntax issue hence no <code>SyntaxError</code>, <em>this syntax is totally supported</em>. <code>list</code>'s just don't know what to do with your slices. Take for example a dummy class that does <em>nothing</em> but define <code>__getitem__</code> that receives the contents of subscriptions <code>[]</... | 1 | 2016-09-20T18:23:43Z | [
"python",
"python-3.x",
"slice"
] |
Understanding python slicings syntax as described in the python language reference | 39,600,833 | <p>The following is the slicings syntax that I copied from <a href="https://docs.python.org/3/reference/expressions.html#slicings" rel="nofollow">The Python Language Reference</a>:</p>
<pre><code>slicing ::= primary "[" slice_list "]"
slice_list ::= slice_item ("," slice_item)* [","]
slice_item ::= express... | 5 | 2016-09-20T18:01:14Z | 39,601,454 | <p>Note that the grammar is structured this way to allow two things:</p>
<ol>
<li><p>A family of <code>slice</code> literals:</p>
<ol>
<li><code>x:y:z == slice(x, y, z)</code></li>
<li><code>x:y == slice(x, y, None)</code></li>
<li><code>x: == slice(x, None, None)</code></li>
<li><code>x::z == slice(x, None, z)</code... | 2 | 2016-09-20T18:38:42Z | [
"python",
"python-3.x",
"slice"
] |
XML generation Python reading from DB | 39,601,053 | <p>I have generate an xml, that take a param value from the model. </p>
<p>The result xml should be like this <code><read><test><value string/></test></read></code></p>
<pre><code>root = etree.Element('read')
node = etree.Element('test')
value = etree.SubElement(node, "value" )
for dict ... | 0 | 2016-09-20T18:15:10Z | 39,608,219 | <p>Firstly, as @parfait mentioned, the XML result you want (<code><read><test><value string/></test></read></code>) is not valid XML.</p>
<p>Using the code you provided, the node <code>test</code> doesn't get added to the root node <code>read</code>.</p>
<h1>1. Code to get your current r... | 0 | 2016-09-21T05:30:57Z | [
"python",
"xml"
] |
Python file.close() and with() behavior in high frequency loops | 39,601,070 | <p>I am working with a Raspberry PI and outputting a value from a sound sensor using a python script. In order to display this, I use an HTML page on my PI that calls a javascript include which is simply a single line that defines a value that will be used to change what the Google gauge displays. All of this is pretty... | 2 | 2016-09-20T18:15:56Z | 39,601,261 | <p>The <code>.close()</code> is definitely not needed. At issue is your browser reading the file <em>while it is still open anyway</em> and finding it in a truncated (so empty) state from time to time. And you can never close the file fast enough to prevent this.</p>
<p>What you should do instead is write the file to ... | 5 | 2016-09-20T18:26:33Z | [
"javascript",
"python"
] |
Python Tkinter Window not closing | 39,601,107 | <p>So I was writing a short code to test something when I noticed this interesting behaviour. </p>
<pre><code>import tkinter
from tkinter import *
master=tkinter.Tk()
master.geometry("800x850+0+0")
master.configure(background="lightblue")
def d():
master.destroy()
button=Button(master, text="asdf", command=d).p... | 0 | 2016-09-20T18:18:02Z | 39,678,316 | <p>I tried it out on some of my friends computers and they didn't have this issue, so it appears that it was just a hardware specific problem.</p>
| 0 | 2016-09-24T16:05:43Z | [
"python",
"tkinter",
"window"
] |
How to access prior rows within a multiindex Panda dataframe | 39,601,110 | <p>How to reach within a Datetime indexed multilevel Dataframe such as the following: This is downloaded Fin data.
The tough part is getting inside the frame and accessing non adjacent rows of a particular inner level, without specifying explicitly the outer level date, since I have thousands of such rows..</p>
<pre><... | 1 | 2016-09-20T18:18:09Z | 39,602,842 | <p>You can use:</p>
<pre><code>#add new datetime with data for better testing
print (df)
ABC DEF GHI
Date STATS
2012-07-19 NaN NaN NaN
investment 4.0 9.0 13.0
price 5.0 8.0 1.0
quantity 12.0 9.0 ... | 1 | 2016-09-20T20:01:53Z | [
"python",
"pandas",
"indexing",
"dataframe",
"multi-index"
] |
How to access prior rows within a multiindex Panda dataframe | 39,601,110 | <p>How to reach within a Datetime indexed multilevel Dataframe such as the following: This is downloaded Fin data.
The tough part is getting inside the frame and accessing non adjacent rows of a particular inner level, without specifying explicitly the outer level date, since I have thousands of such rows..</p>
<pre><... | 1 | 2016-09-20T18:18:09Z | 39,603,487 | <p>If need add output to original <code>DataFrame</code>, then it is more complicated:</p>
<pre><code>print (df)
ABC DEF GHI
Date STATS
2012-07-19 NaN NaN NaN
investment 4.0 9.0 13.0
price 5.0 8.0 1.0
... | 1 | 2016-09-20T20:49:42Z | [
"python",
"pandas",
"indexing",
"dataframe",
"multi-index"
] |
Extracting Fasta Moonlight Protein Sequences with Python | 39,601,114 | <p>I want to extract the FASTA files that have the aminoacid sequence from the Moonlighting Protein Database ( www.moonlightingproteins.org/results.php?search_text= ) via Python, since it's an iterative process, which I'd rather learn how to program than manually do it, b/c come on, we're in 2016. The problem is I donÂ... | 0 | 2016-09-20T18:18:27Z | 39,603,854 | <p>I would strongly suggest to ask the authors for the database. From the <a href="http://www.moonlightingproteins.org/faqs.php" rel="nofollow">FAQ</a>:</p>
<blockquote>
<p>I would like to use the MoonProt database in a project to analyze the
amino acid sequences or structures using bioinformatics. </p>
<p>Pl... | 0 | 2016-09-20T21:17:04Z | [
"python",
"database",
"data-mining",
"bioinformatics",
"protein-database"
] |
Tornado's reverse_url to a fully qualified URL | 39,601,123 | <p>Tornado's <code>reverse_url</code> is not a fully qualified URL. Is there a mechanism in Tornado to get back a fully qualified URL? For instance:</p>
<pre><code>>>> some_method('foo', 1234)
http://localhost:8080/foo/1234
</code></pre>
| 1 | 2016-09-20T18:19:17Z | 39,612,115 | <p>This is a small helper method which I add to all my handlers:</p>
<pre><code>from urllib.parse import urljoin # urlparse in Python 2
class BaseHandler(tornado.web.RequestHandler):
def reverse_full_url(self, name, *args, **kwargs):
host_url = "{protocol}://{host}".format(**vars(self.request))
... | 1 | 2016-09-21T09:07:14Z | [
"python",
"tornado"
] |
Transposing a subset of columns in a Pandas DataFrame while using others as grouping variable? | 39,601,126 | <p>Let's say I have a Pandas dataframe (that is already in the dataframe format):</p>
<pre><code>x = [[1,2,8,7,9],[1,3,5.6,4.5,4],[2,3,4.5,5,5]]
df = pd.DataFrame(x, columns=['id1','id2','val1','val2','val3'])
id1 id2 val1 val2 val3
1 2 8.0 7.0 9
1 3 5.6 4.5 4
2 3 4.5 5.0 5
</code></pre>
<p>I want ... | 2 | 2016-09-20T18:19:24Z | 39,601,213 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> column <code>variable</code>:</p>
<pre><code>print (p... | 2 | 2016-09-20T18:24:02Z | [
"python",
"performance",
"pandas",
"optimization",
"dataframe"
] |
Transposing a subset of columns in a Pandas DataFrame while using others as grouping variable? | 39,601,126 | <p>Let's say I have a Pandas dataframe (that is already in the dataframe format):</p>
<pre><code>x = [[1,2,8,7,9],[1,3,5.6,4.5,4],[2,3,4.5,5,5]]
df = pd.DataFrame(x, columns=['id1','id2','val1','val2','val3'])
id1 id2 val1 val2 val3
1 2 8.0 7.0 9
1 3 5.6 4.5 4
2 3 4.5 5.0 5
</code></pre>
<p>I want ... | 2 | 2016-09-20T18:19:24Z | 39,601,545 | <p>There's even a simpler one which can be done using <a href="https://github.com/pydata/pandas/blob/master/pandas/core/reshape.py#L804" rel="nofollow"><code>lreshape</code></a>(Not yet documented though):</p>
<pre><code>pd.lreshape(df, {'val': ['val1', 'val2', 'val3']}).sort_values(['id1', 'id2'])
</code></pre>
<p><... | 3 | 2016-09-20T18:43:11Z | [
"python",
"performance",
"pandas",
"optimization",
"dataframe"
] |
Why does PyCharm want to install itself in AppData\Roaming on Windows 7? Can I just put it in Program Files? | 39,601,151 | <p>Does anybody have any idea why PyCharm wants to install in the following directory:</p>
<pre><code>C:\Users\Lenovo\AppData\Roaming\JetBrains\PyCharm 2016.2.3
</code></pre>
<p><a href="http://i.stack.imgur.com/jy0sy.png" rel="nofollow"><img src="http://i.stack.imgur.com/jy0sy.png" alt="enter image description here"... | 0 | 2016-09-20T18:20:43Z | 39,601,368 | <p>I just restarted the installer and it automatically decided to install into the Program Files (x86) directory. Weird.</p>
| 0 | 2016-09-20T18:33:25Z | [
"python",
"windows",
"pycharm",
"windows-7-x64"
] |
Python get a value from numpy.ndarray by [index] | 39,601,165 | <pre><code>import numpy as np
ze=np.zeros(3)
print(ze[0]) # -> 0
</code></pre>
<p>I am pretty new to Python (3.5.2)</p>
<p>I learned 'list' in python and to show the i th element in list1</p>
<pre><code>print (list1[i])
</code></pre>
<p>but, even 'np.zeros(3)' is ndarray, a class in NumPy,
it can be used as t... | 0 | 2016-09-20T18:21:31Z | 39,601,403 | <p>If you want to implement a class that can return a value using the [] operator. Then implement the <code>__getitem__(self, key)</code> function in the class, see <a href="https://docs.python.org/2/reference/datamodel.html#emulating-container-types" rel="nofollow">https://docs.python.org/2/reference/datamodel.html#em... | 1 | 2016-09-20T18:35:59Z | [
"python",
"numpy"
] |
Why do I get ValueError in one piece of code but not the other although they are identical? | 39,601,169 | <p>I've been solving Project Euler problems and here is my code for <a href="https://projecteuler.net/problem=35" rel="nofollow">problem 35</a>:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**6
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = F... | -1 | 2016-09-20T18:21:41Z | 39,601,717 | <p>You don't mention the line on which you get the error. That would have helped. Also you know much of the code works. So just focus on the bit which is different: the truncations. </p>
<p>I suspect the error is in this <code>int(n[:i])</code></p>
<p>The range starts from 0, so the first term is a zero length string... | 1 | 2016-09-20T18:52:12Z | [
"python"
] |
Why do I get ValueError in one piece of code but not the other although they are identical? | 39,601,169 | <p>I've been solving Project Euler problems and here is my code for <a href="https://projecteuler.net/problem=35" rel="nofollow">problem 35</a>:</p>
<pre><code>def sieve_of_Erathosthenes():
sieve = [True] * 10**6
def mark(sieve, x):
for i in xrange(x+x, len(sieve), x):
sieve[i] = F... | -1 | 2016-09-20T18:21:41Z | 39,601,722 | <p>If I run your code, you'll notice the error happens when <code>i</code> is 11:</p>
<pre><code>>>> primes = sieve_of_Erathosthenes()
>>>
>>> trunctable_from_both_sides = 0
>>> for i in primes:
... if is_trunctable_from_the_left(str(i)) and is_trunctable_from_the_right(str(i))... | 1 | 2016-09-20T18:52:33Z | [
"python"
] |
string index out of range error in for loop | 39,601,218 | <p>I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears.
Here is the code:</p>
<pre><code>s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
u = s[i]
if u == 'o':
g = i
if g != 0 and g != len(s) :
if (s[g+1]) == 'b' and (s... | -1 | 2016-09-20T18:24:20Z | 39,601,335 | <p>Use </p>
<pre><code>for i in range(len(s)-1)
</code></pre>
<p>or</p>
<pre><code>g!=len(s)-1
</code></pre>
<p><code>len()</code> gives you the total number of characters, which will be the index of the character after the last one since indexing starts at 0.</p>
<p>You can get rid of the <code>if g!=0 and g!=le... | 1 | 2016-09-20T18:31:06Z | [
"python",
"python-3.x"
] |
string index out of range error in for loop | 39,601,218 | <p>I am trying to make a program that searches a string for 'bob' and prints the amount of times it appears.
Here is the code:</p>
<pre><code>s = 'mbobobboobooboo'
numbob = 0
for i in range(len(s) ) :
u = s[i]
if u == 'o':
g = i
if g != 0 and g != len(s) :
if (s[g+1]) == 'b' and (s... | -1 | 2016-09-20T18:24:20Z | 39,601,339 | <p>When you make your condition :</p>
<pre><code>if (s[g+1]) == 'b' and (s[g-1]) == 'b':
</code></pre>
<p>At the last element of your string, it is impossible to do <code>s[g+1]</code> because it is out of the string.</p>
<p>So you have to finish your loop just before the end. Like this for exemple :</p>
<pre><code... | 0 | 2016-09-20T18:31:24Z | [
"python",
"python-3.x"
] |
Python error when calling column data from Pandas DataFrame | 39,601,251 | <p>I was practicing to import stock market data from Google Finance into a Pandas DataFrame:</p>
<pre><code>import pandas as pd
from pandas import Series
path = 'http://www.google.com/finance/historical?cid=542029859096076&startdate=Sep+22%2C+2001&enddate=Sep+20%2C+2016&num=30&ei=3HvhV4n3D8XGmAGp4q74A... | 2 | 2016-09-20T18:26:14Z | 39,601,325 | <p>this CSV file contains <a href="http://stackoverflow.com/questions/17912307/u-ufeff-in-python-string">BOM (Byte Order Mark) signature</a>, so try it this way:</p>
<pre><code>df = pd.read_csv(path, encoding='utf-8-sig')
</code></pre>
<p>How one can easily identify this problem (thanks to <a href="http://stackoverfl... | 4 | 2016-09-20T18:30:20Z | [
"python",
"pandas",
"dataframe"
] |
Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) tried: [] | 39,601,272 | <p>I'm getting an error when trying to access edit link in django, i have looked here on stack overflow but i haven't found the solution that works in my case.</p>
<p>ERROR :
Exception Type : NoReverseMatch
Exception Value : Reverse for 'edit' with arguments '(9,)' and keyword arguments '{}' not found. 0 pattern(s) ... | 0 | 2016-09-20T18:27:05Z | 39,601,591 | <p>You need to use the namespace. Rather than <code>'edit'</code>, you should use <code>'posts:edit'</code>.</p>
<p>Or <code>'posts:update_post'</code> depending which name you're using in urls.py.</p>
| 1 | 2016-09-20T18:45:51Z | [
"python",
"django",
"django-models",
"django-templates",
"django-views"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,428 | <p>So you are just looking to find the biggest number in the first column of the file? This should help</p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
max = 0
for line in b.readlines():
num = int(line.split(",")[0])
if (max < num):
max = num
print(max)
# Close... | 0 | 2016-09-20T18:37:20Z | [
"python"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,515 | <ul>
<li>Read line </li>
<li>Split it on basis of comma</li>
<li>Append first element to temp list.</li>
</ul>
<p>Once complete reading of file is done,</p>
<ul>
<li>To get maximum number, just use <code>max</code> function on temp list.</li>
<li>Since file is read line by line sequentially and appending number from ... | 0 | 2016-09-20T18:42:02Z | [
"python"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,540 | <p>Iterate through the file and keep track of the highest number you've seen and the line you found it on. Just replace this with the new number and new line number when you see a bigger one.</p>
<pre><code>b = open('file.txt', 'r')
max = -1
lineNum = -1
line = b.readline()
index = 0
while(line):
index+=1
newN... | -1 | 2016-09-20T18:42:54Z | [
"python"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,556 | <p>This is how I'd go about doing it.</p>
<pre><code>max_num = 0
with open('file.txt', 'r') as data: # use the with context so that the file closes gracefully
for line in data.readlines(): # read the lines as a generator to be nice to my memory
try:
val = int(line.split(",")[0])
except ValueError: # ju... | 0 | 2016-09-20T18:43:55Z | [
"python"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,613 | <p>You need loop over each line in file, parse each line and find the largest number.</p>
<p>I do not quite understand how the numbers are stored in your file. Just assuming that in each line, the first field are numeric and separate with others (non-numeric) by <code>','</code>. And I assume all numbers are integer.<... | 0 | 2016-09-20T18:47:05Z | [
"python"
] |
How to find largest number in file and see on which line it is | 39,601,278 | <p>The file looks like this:</p>
<pre><code>1, a b
2, c d
3, e f
</code></pre>
<p>my current code </p>
<pre><code>b = open('file.txt', 'r')
c = b.readlines()
regels = len(c)
print(regels)
</code></pre>
<p>I got the numbers of lines but still need biggest number + on which line it is. </p>
| 1 | 2016-09-20T18:27:31Z | 39,601,708 | <p>None of the answers give you the line of the max number so I'll post some quick code and refine later</p>
<pre><code>max_num = 0
line_count = 0
with open('file.txt', 'r') as infile:
for line in infile:
number = int(line.split(',')[0])
if number > max_num:
max_num = number
... | 0 | 2016-09-20T18:51:41Z | [
"python"
] |
Scrapy. First response requires Selenium | 39,601,298 | <p>I'm scraping a website that strongly depends on Javascript. The main page from which I need to extract the urls that will be parsed depends on Javascript, so I have to modify start_requests.
I'm looking for a way to connect start_requests, with the linkextractor and with process_match</p>
<pre><code>class MatchSpid... | 0 | 2016-09-20T18:28:36Z | 39,602,405 | <p>There's two problems I see after looking into this. Forgive any ignorance on my part, because it's been a while since I was last in the Python/Scrapy world.</p>
<hr>
<p><strong>First:</strong> <strong><em>How do we get the HTML from Selenium?</em></strong></p>
<p>According to the <a href="http://selenium-python.r... | 1 | 2016-09-20T19:32:33Z | [
"python",
"selenium",
"scrapy"
] |
Scrapy SgmlLinkExtractor how to define XPath | 39,601,361 | <p>I want to retreive the cityname and citycode and store it in one string variable. The image shows the precise location:</p>
<p><a href="http://i.stack.imgur.com/PmMcq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PmMcq.png" alt="enter image description here"></a></p>
<p>Google Chrome gave me the following... | 0 | 2016-09-20T18:32:51Z | 39,601,633 | <p>Most of the time this occurs, this is because browsers correct invalid HTML. How do you fix this? Inspect the (raw) HTML source and write your own XPath that navigate the DOM with the shortest/simplest query.</p>
<p>I scrape a lot of data off of the web and I've never used an XPath as specific as the one you got fr... | 1 | 2016-09-20T18:47:47Z | [
"python",
"regex",
"xpath",
"scrapy"
] |
Scrapy SgmlLinkExtractor how to define XPath | 39,601,361 | <p>I want to retreive the cityname and citycode and store it in one string variable. The image shows the precise location:</p>
<p><a href="http://i.stack.imgur.com/PmMcq.png" rel="nofollow"><img src="http://i.stack.imgur.com/PmMcq.png" alt="enter image description here"></a></p>
<p>Google Chrome gave me the following... | 0 | 2016-09-20T18:32:51Z | 39,602,061 | <p>The DOM is manipulated by javascript, so what chrome shows is the xpath after
the all the stuff has happened.</p>
<p>If all you want is to get the cities, you can get it this way (using scrapy):</p>
<pre><code>city_text = response.css('.detail-address span::text').extract_first()
city_code, city_name = city_text.... | 1 | 2016-09-20T19:11:49Z | [
"python",
"regex",
"xpath",
"scrapy"
] |
Python openCV find image in folder of images(road sign recognition) | 39,601,465 | <p>I'm doing road sign recognition program. I've successfuly done with image preprocesing. I have extracted image of road sign. </p>
<p>Now I don't know what algorithem or template matching should I use to find matching image of my extracted image.</p>
<p>Solution must be simple and effective, because I'm still learn... | 0 | 2016-09-20T18:39:29Z | 39,602,564 | <p>Template matching doesn't work in your case. Template matching works only with nearly the same template in your source.
I propose to use <code>dlib</code>
<a href="http://dlib.net/ml.html" rel="nofollow">http://dlib.net/ml.html</a> for deep learning.
It's easy to learn and you don't need write a lot of code. If you... | 0 | 2016-09-20T19:44:13Z | [
"python",
"algorithm",
"opencv",
"template-matching"
] |
Error in scipy odeint use for system of ODE's | 39,601,483 | <p>I am trying to reproduce the two graphs shown below, which are temperature and concentration profiles as a function of time. I have checked my method and code a million times but cannot seem to find an error in it but I cannot reproduce those graphs. All values are constants except CA and T. Could it be an issue wit... | 0 | 2016-09-20T18:40:39Z | 39,602,463 | <p>Apparently there is a sign error in the formula <code>k = k0*np.exp(8750*1/T)</code>. If you change that to <code>k = k0*np.exp(-8750*1/T)</code>, you'll get plots like those you expect.</p>
| 1 | 2016-09-20T19:36:27Z | [
"python",
"scipy",
"ode",
"odeint"
] |
Twitter Search API query results don't match keyword | 39,601,524 | <p>I'm using Tweepy Cursor to find some tweets.</p>
<pre><code>for tweet in tweepy.Cursor(api.search, q='pg&e', count=100, lang='en', since=sinceDate, until=untilDate).items():
print str(tweet.created_at) + '\t' + str(tweet.text)
</code></pre>
<p>I have noticed that the tweet.text for many of the tweets retur... | 0 | 2016-09-20T18:42:26Z | 39,603,057 | <p><code>q="\"pg&e\""</code> will give you what you want. I guess the <code>&</code> is interpreted as an AND by the API, so you have to specify that you want to search for pure text by putting extra quotation marks.</p>
<p>If you want to search for more keywords, using OR in your query should work, provided t... | 1 | 2016-09-20T20:16:45Z | [
"python",
"api",
"search",
"twitter",
"tweepy"
] |
Retrieving tail text from html | 39,601,578 | <p>Python 2.7 using lxml</p>
<p>I have some annoyingly formed html that looks like this:</p>
<pre><code><td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
</code></pre>
<p>So bas... | 0 | 2016-09-20T18:45:01Z | 39,602,352 | <p>What not use getchildren function from view of each td. For example:</p>
<pre><code>from lxml import html
s = """
<td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
"""
record... | 0 | 2016-09-20T19:29:35Z | [
"python",
"xpath",
"lxml"
] |
Retrieving tail text from html | 39,601,578 | <p>Python 2.7 using lxml</p>
<p>I have some annoyingly formed html that looks like this:</p>
<pre><code><td>
<b>"John"
</b>
<br>
"123 Main st.
"
<br>
"New York
"
<b>
"Sally"
</b>
<br>
"101 California St.
"
<br>
"San Francisco
"
</td>
</code></pre>
<p>So bas... | 0 | 2016-09-20T18:45:01Z | 39,602,410 | <p>This should work:</p>
<pre><code>from lxml import etree
p = etree.HTMLParser()
html = open(r'./test.html','r')
data = html.read()
tree = etree.fromstring(data, p)
my_dict = {}
for b in tree.iter('b'):
br = b.getnext().tail.replace('\n', '')
my_dict[b.text.replace('\n', '')] = br
print my_dict
</code></p... | 1 | 2016-09-20T19:32:52Z | [
"python",
"xpath",
"lxml"
] |
Numpy - generating a sequence with a higher resolution within certain bounds | 39,601,601 | <p>Generating a sequence of a range with evenly spaced points using Numpy is accomplished easily using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="nofollow"><code>np.linspace(a, c, n)</code></a> where <code>a</code> is the start of the range, <code>c</code> is the endpoint of ... | 2 | 2016-09-20T18:46:17Z | 39,604,183 | <p>You could construct such a sequence by first making an array containing the spacings between each pair of points, then taking a cumsum over this.</p>
<p>For example, let's suppose I want to go from 0 to 50 everywhere in steps of 1, except between 20 and 30 where I want steps of 0.25:</p>
<pre><code>import numpy as... | 3 | 2016-09-20T21:41:43Z | [
"python",
"numpy"
] |
Print variable in Shell command | 39,601,614 | <p>I want to extract the text field from a json objcet of a tweet and run it through syntaxnet. I am doing it all in Python.</p>
<p>My code is:</p>
<pre><code>import os, sys
import subprocess
import json
def parse(text):
os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_anal... | 1 | 2016-09-20T18:47:07Z | 39,601,755 | <p>You can just use string formatter <code>%s</code> and substitute the text </p>
<pre><code>def parse(text):
os.chdir("/var/www/html/alenza/hdfs/user/alenza/sree_account/sree_project/src/core/data_analysis/syntaxnet/models/syntaxnet")
#synnet_output = subprocess.check_output()
subprocess.call(["echo '%s' ... | 0 | 2016-09-20T18:54:16Z | [
"python",
"shell",
"arguments",
"subprocess"
] |
math.acos math domain error within the range of acos | 39,601,642 | <p>I've got a script that runs through a set of coordinates for triangles and determines whether or not they're a right triangle. Part of this uses the cosine rule, and I've come across a problem when checking a certain set of points that happen to fall in a line. Here's the part that is causing problems:</p>
<pre><... | 0 | 2016-09-20T18:48:24Z | 39,601,925 | <p>When I run your code:</p>
<pre><code>import math
def foo(x, y):
x1, x2, x3 = x
y1, y2, y3 = y
s1 = math.sqrt(((x2-x1)**2)+((y2-y1)**2))
s2 = math.sqrt(((x3-x2)**2)+((y3-y2)**2))
s3 = math.sqrt(((x3-x1)**2)+((y3-y1)**2))
num1 = (s1**2)+(s2**2)-(s3**2)
den1 = (2)*(s1)*(s2)
theta1 = ma... | 1 | 2016-09-20T19:02:51Z | [
"python",
"math",
"cosine"
] |
Extract values between square brackets ignoring single quotes | 39,601,759 | <p>I am trying the following:</p>
<pre><code>s = "Text text text [123] ['text']"
</code></pre>
<p>This is my function:</p>
<pre><code>def getFromSquareBrackets(s):
m = re.findall(r"\[([A-Za-z0-9_']+)\]", s)
return m
</code></pre>
<p>But I am obtaining:</p>
<pre><code>['123', "'text'"]
</code></pre>
<p>I w... | 1 | 2016-09-20T18:54:26Z | 39,601,804 | <p>Make <code>'</code> optional and outside the capturing group</p>
<pre><code>m = re.findall(r"\['?([A-Za-z0-9_]+)'?\]", s)
</code></pre>
| 2 | 2016-09-20T18:56:45Z | [
"python",
"regex"
] |
Extract values between square brackets ignoring single quotes | 39,601,759 | <p>I am trying the following:</p>
<pre><code>s = "Text text text [123] ['text']"
</code></pre>
<p>This is my function:</p>
<pre><code>def getFromSquareBrackets(s):
m = re.findall(r"\[([A-Za-z0-9_']+)\]", s)
return m
</code></pre>
<p>But I am obtaining:</p>
<pre><code>['123', "'text'"]
</code></pre>
<p>I w... | 1 | 2016-09-20T18:54:26Z | 39,601,821 | <p>You can make <code>'</code> optional using <code>?</code> as</p>
<pre><code>>>> re.findall(r"\['?([^'\]]+)'?\]", s)
['123', 'text']
</code></pre>
<hr>
<ul>
<li><p><code>\['?</code> Matches <code>[</code> or <code>['</code>.</p></li>
<li><p><code>([^'\]]+)</code> Matches anything other than <code>'</code>... | 2 | 2016-09-20T18:57:25Z | [
"python",
"regex"
] |
How can I optimize the intersections between lists with two elements and generate a list of lists without duplicates in python? | 39,601,823 | <p>I need help with my loop. In my script I have two huge lists (~87.000 integers each) taken from an input file. </p>
<p>Check this example with a few numbers:</p>
<p>We have two lists:</p>
<p><code>nga = [1, 3, 5, 34, 12]</code></p>
<p><code>ngb = [3, 4, 6, 6, 5]</code></p>
<p>The order of these two lists matt... | 0 | 2016-09-20T18:57:36Z | 40,137,246 | <p>I solved my problem with this beautiful function:</p>
<pre><code>net = []
for a, b in zip(nga, ngb):
net.append([a, b])
def nets_super_gen(net):
not_con = list(net)
netn = list(not_con[0])
not_con.remove(not_con[0])
new_net = []
while len(netn) != len(new_net):
new_net = list(netn)
... | 0 | 2016-10-19T16:47:48Z | [
"python",
"list",
"optimization",
"intersection"
] |
pandas: slice dataframe based on NaN | 39,601,854 | <p>I have following dataframe <code>df</code></p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
NaN lkbljb
NaN jknnkn
30 kbknkn
</code></pre>
<p>I am trying the following:</p>
<pre><code>df[df['prod_id'] != np.nan]
</code></pre>
<p>but I get exactly the same dataframe.</p>
<p>I would like ... | 1 | 2016-09-20T18:58:58Z | 39,601,872 | <p>Use function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> or inverting <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isnull.html" rel="nofollow"><code>isnull</code></a>:</p>
<pre><code>print (df[df.p... | 3 | 2016-09-20T18:59:59Z | [
"python",
"python-2.7",
"pandas"
] |
pandas: slice dataframe based on NaN | 39,601,854 | <p>I have following dataframe <code>df</code></p>
<pre><code>prod_id prod_ref
10 ef3920
12 bovjhd
NaN lkbljb
NaN jknnkn
30 kbknkn
</code></pre>
<p>I am trying the following:</p>
<pre><code>df[df['prod_id'] != np.nan]
</code></pre>
<p>but I get exactly the same dataframe.</p>
<p>I would like ... | 1 | 2016-09-20T18:58:58Z | 39,601,897 | <p>The problem is that <code>np.nan != np.nan</code> is <code>True</code> (alternatively, <code>np.nan == np.nan</code> is <code>False</code>). Pandas provides the <code>.dropna()</code> method to do what you want:</p>
<pre><code>df.dropna()
</code></pre>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><c... | 3 | 2016-09-20T19:01:37Z | [
"python",
"python-2.7",
"pandas"
] |
How to use a for loop to iterate through an array | 39,601,863 | <p>So basically I am getting a list of ids and storing them in an array ids. I want to use these ids to do api calls. Here is my code:</p>
<pre><code>url = "https://swag.com"
headers = {'x-api-token': "cool"}
response = requests.get(url, headers=headers)
data = json.loads(response.text)
ids = [element['id'] for eleme... | -1 | 2016-09-20T18:59:30Z | 39,601,966 | <p>Your for loop is constructing a survey url based on <code>ids</code> instead of <code>id</code>.</p>
<p>Change it to</p>
<pre><code>for i in ids:
url2 = "https://swag.com/"
# your mistake was using str(ids) here.
survey_url = url_2 + str(i)
# proceed further with making the request for this survey ... | 3 | 2016-09-20T19:05:44Z | [
"python",
"arrays",
"api"
] |
Writing from a dictionary to a text file in a sorted way (python) | 39,601,875 | <p>I have a code where i need to write a dictionary to a .txt file in order.</p>
<pre><code>with open("Items.txt", "w+") as file:
for item in sorted(orders):
file.write(item + "," + ",".join(map(str,orders[item])) + "\n")
file.close
print("New stock level to file complete.")
</code><... | 0 | 2016-09-20T19:00:15Z | 39,601,953 | <p>Because <code>item</code> will be an <code>int</code>, you cannot use the <code>+</code> operator with it on a string (<code>,</code>). Python is a strongly typed language. Use:</p>
<pre><code>file.write(str(item) + "," + ",".join(map(str,orders[item])) + "\n")
</code></pre>
<p>instead.</p>
| 1 | 2016-09-20T19:04:37Z | [
"python"
] |
Can I use pandas.dataframe.isin() with a numeric tolerance parameter? | 39,602,004 | <p>I reviewed the following posts beforehand. Is there a way to use DataFrame.isin() with an approximation factor or a tolerance value? Or is there another method that could?</p>
<p><a href="http://stackoverflow.com/questions/12065885/how-to-filter-the-dataframe-rows-of-pandas-by-within-in">How to filter the DataFrame... | 6 | 2016-09-20T19:07:50Z | 39,602,108 | <p>You can do a similar thing with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.isclose.html" rel="nofollow">numpy's isclose</a>:</p>
<pre><code>df[np.isclose(df['A'].values[:, None], [3, 6], atol=.5).any(axis=1)]
Out:
A B
1 6.0 2.0
2 3.3 3.2
</code></pre>
<hr>
<p>np.isclose return... | 9 | 2016-09-20T19:14:33Z | [
"python",
"pandas",
"comparison",
"floating-accuracy",
"comparison-operators"
] |
Return Events from DispatchWithEvents using third party COM | 39,602,065 | <p>My code prints out what I need from the print statement in Events. But, I have no idea how to return the data because of the way the class is instantiated. Further, the print statement only works if pythoncom.PumpWaitingMessages() is included, but it doesn't return the data that's printed, or anything.</p>
<p>I'd... | 0 | 2016-09-20T19:12:03Z | 39,664,585 | <p>My solution is as follows. This may be ugly and wrong but it got me what I need. If anyone has a better way I'm happy to edit.</p>
<pre><code>class Events(object):
def get_barcode(self):
return self.pscanData
def OnBarcodeEvent(self, eventType=1, pscanData=pythoncom.Empty):
self.pscanDat... | 0 | 2016-09-23T15:33:43Z | [
"python",
"python-2.7",
"com",
"win32com",
"pythoncom"
] |
Map if it can be converted | 39,602,093 | <p>I have the following list:</p>
<pre><code>a = ['1', '2', 'hello']
</code></pre>
<p>And I want to obtain</p>
<pre><code>a = [1, 2, 'hello']
</code></pre>
<p>I mean, convert all integers I can.</p>
<p>This is my function:</p>
<pre><code>def listToInt(l):
casted = []
for e in l:
try:
c... | 0 | 2016-09-20T19:13:36Z | 39,602,178 | <p>Sure you can do this with <code>map</code></p>
<pre><code>def func(i):
try:
i = int(i)
except:
pass
return i
a = ['1', '2', 'hello']
print(list(map(func, a)))
</code></pre>
| 3 | 2016-09-20T19:19:04Z | [
"python",
"algorithm",
"list",
"casting"
] |
Map if it can be converted | 39,602,093 | <p>I have the following list:</p>
<pre><code>a = ['1', '2', 'hello']
</code></pre>
<p>And I want to obtain</p>
<pre><code>a = [1, 2, 'hello']
</code></pre>
<p>I mean, convert all integers I can.</p>
<p>This is my function:</p>
<pre><code>def listToInt(l):
casted = []
for e in l:
try:
c... | 0 | 2016-09-20T19:13:36Z | 39,602,239 | <pre><code>a = ['1', '2', 'hello']
y = [int(x) if x.isdigit() else x for x in a]
>> [1, 2, 'hello']
>> #tested in Python 3.5
</code></pre>
<p>Maybe something like this? </p>
| 2 | 2016-09-20T19:22:43Z | [
"python",
"algorithm",
"list",
"casting"
] |
Is there a way to read all files excluding a defined list of files in python apache beam? | 39,602,163 | <p>My use case is that I am batch processing files in a bucket that is constantly being updated with new files. I don't want to process csv files that have already been processed. </p>
<p>Is there a way to do that? </p>
<p>One potential solution I thought of, is to have a text file that maintains a list of processed ... | 1 | 2016-09-20T19:18:00Z | 39,604,762 | <p>There's not a good built-in way to do this, but you can have one stage of your pipeline that computes the list of files to read as you suggested, the using a DoFn that maps a filename to the contents of the file. See <a href="http://stackoverflow.com/questions/39578932/reading-multiple-gz-file-and-identifying-which... | 1 | 2016-09-20T22:34:17Z | [
"python",
"google-cloud-dataflow",
"dataflow",
"apache-beam"
] |
compare datetime.now() with utc timestamp with python 2.7 | 39,602,188 | <p>I have a timestamp such <code>1474398821633L</code> that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.</p>
<p>I am using python 2.7</p>
<pre><code>from datetime import datetime
timestamp = 1474398821633L
now = datetime.now()
if datetime.utcfromtimestamp(timestamp)... | 0 | 2016-09-20T19:19:30Z | 39,602,250 | <p>It <em>looks</em> like your timestamp is in milliseconds. Python uses timestamps in seconds:</p>
<pre><code>>>> datetime.datetime.utcfromtimestamp(1474398821.633)
datetime.datetime(2016, 9, 20, 19, 13, 41, 633000)
</code></pre>
<p>In other words, you might need to divide your timestamp by <code>1000.</co... | 3 | 2016-09-20T19:23:20Z | [
"python",
"python-2.7"
] |
compare datetime.now() with utc timestamp with python 2.7 | 39,602,188 | <p>I have a timestamp such <code>1474398821633L</code> that I think is in utc. I want to compare it to datetime.datetime.now() to verify if it is expired.</p>
<p>I am using python 2.7</p>
<pre><code>from datetime import datetime
timestamp = 1474398821633L
now = datetime.now()
if datetime.utcfromtimestamp(timestamp)... | 0 | 2016-09-20T19:19:30Z | 39,602,530 | <p>As <a href="http://stackoverflow.com/a/39602250/4279">@mgilson pointed out</a> your input is likely "milliseconds", not "seconds since epoch".</p>
<p>Use <code>time.time()</code> instead of <code>datetime.now()</code>:</p>
<pre><code>import time
if time.time() > (timestamp_in_millis * 1e-3):
print("expired... | 1 | 2016-09-20T19:42:03Z | [
"python",
"python-2.7"
] |
Image to Array: Plain English | 39,602,190 | <p>I'm starting to use numpy and PILlow to work with image files. And, generally loosing myself when it comes to converting images to arrays, and then working with arrays.
can someone explain what is happening when I convert an image to array. Such as this:</p>
<pre><code>ab = numpy.asarray(img.convert('L'))
</code><... | 0 | 2016-09-20T19:19:37Z | 39,669,750 | <p><strong>What is a digital image?</strong></p>
<p>A digital image is a set of pixel values. Consider this image: <a href="http://i.imgur.com/wlDQhpL.png" rel="nofollow"><img src="http://i.imgur.com/wlDQhpL.png" alt="small smiley face"></a>. It consists of 16x16 pixels. Because most displays have 8 bits (2^8 (256) p... | 2 | 2016-09-23T21:23:16Z | [
"python",
"arrays",
"python-2.7",
"numpy",
"pillow"
] |
BeautifulSoup webscraper issue: can't find certain divs/tables | 39,602,223 | <p>I'm having issues with scraping pro-football-reference.com. I'm trying to access the "Team Offense" table but can't seem to target the div/table.
The best I can do is:</p>
<pre><code>soup.find('div', {'id':'all_team_stats})
</code></pre>
<p>which doesn't return the table nor it's immediate div wrapper. The followi... | 2 | 2016-09-20T19:21:56Z | 39,602,574 | <p>A couple of thoughts here: first, as mentioned in the comments, the acutal table is commented out and is not <em>per se</em> part of the <code>DOM</code> (not accessible via a parser adhoc).<br>
In this situation, you can loop over the comments found and try to get the information via regular expressions (though thi... | 1 | 2016-09-20T19:44:35Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
BeautifulSoup webscraper issue: can't find certain divs/tables | 39,602,223 | <p>I'm having issues with scraping pro-football-reference.com. I'm trying to access the "Team Offense" table but can't seem to target the div/table.
The best I can do is:</p>
<pre><code>soup.find('div', {'id':'all_team_stats})
</code></pre>
<p>which doesn't return the table nor it's immediate div wrapper. The followi... | 2 | 2016-09-20T19:21:56Z | 39,603,191 | <p>Just remove the comments with <em>re.sub</em> before you pass to bs4:</p>
<pre><code>from bs4 import BeautifulSoup
import urllib2
import re
comm = re.compile("<!--|-->")
def make_soup(url):
page = urllib2.urlopen(url)
soupdata = BeautifulSoup(comm.sub("", page.read()), 'lxml')
return soupdata
def... | 1 | 2016-09-20T20:28:55Z | [
"python",
"web-scraping",
"beautifulsoup",
"bs4"
] |
Invalid syntax while using socket | 39,602,305 | <p>i've struggled with this code and I can't see why its saying there is a syntax error on line 15. Im trying to create a TCP connection with google for a diagnostic tool for my college coursework.</p>
<pre class="lang-python prettyprint-override"><code>import socket
import sys
#defining the port and host we wll be ... | 0 | 2016-09-20T19:27:01Z | 39,602,332 | <p>There is no <code>except</code> statement for </p>
<pre><code>try:
sockettest = socket.gethostbyname(remote_connection)
</code></pre>
| 5 | 2016-09-20T19:28:25Z | [
"python",
"sockets"
] |
Building JSON object that can hold contents of file | 39,602,353 | <p>I have to save contents of a python file to my database. I am writing fixtures so that I can load that to my database from Django project.</p>
<p>I have no idea where to begin with. The size is an issue that I need to address for my JSON object.</p>
<p>Edit: My app features an upload option where user can upload t... | 0 | 2016-09-20T19:29:36Z | 39,602,784 | <p>You should not be creating your fixtures manually. You should populate a test database with data then use <a href="https://docs.djangoproject.com/en/1.8/ref/django-admin/#django-admin-dumpdata" rel="nofollow"><code>manage.py dumpdata</code></a> to export it. </p>
<p>Django <a href="https://docs.djangoproject.com/en... | 1 | 2016-09-20T19:58:01Z | [
"python",
"json",
"django",
"database"
] |
python convert string time to sql datetime format | 39,602,376 | <p>I am importing a large csv file to ETL into a database, and the date format that was originally set in the csv file looks like <code>4/22/2016 1:00:00 PM</code>. Each date is part of a larger list that might have non-date type items in it. for example:</p>
<pre><code>v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 ... | 0 | 2016-09-20T19:30:46Z | 39,602,723 | <p>Please check this. <strong>Comments inline with code.</strong></p>
<pre><code>from datetime import datetime
v = ['4/29/2016 8:25:58 AM', '5/25/2016 2:22:22 PM', 'True', 'Foo', 1]
def fixdate(_params):
print "Before changing format ..."
print _params
#First date in list
tstamp = da... | 2 | 2016-09-20T19:53:52Z | [
"python",
"mysql",
"datetime"
] |
Numpy matrix exponentiation gives negative value | 39,602,404 | <p>I wanted to use <code>NumPy</code> in a Fibonacci question because of its efficiency in matrix multiplication. You know that there is a method for finding Fibonacci numbers with the matrix <code>[[1, 1], [1, 0]]</code>.</p>
<p><a href="http://i.stack.imgur.com/JuBny.gif" rel="nofollow"><img src="http://i.stack.imgu... | 2 | 2016-09-20T19:32:29Z | 39,602,984 | <p>The reason you see negative values appearing is because NumPy has defaulted to using the <code>np.int32</code> dtype for your matrix.</p>
<p>The maximum positive integer this dtype can represent is 2<sup>31</sup>-1 which is 2147483647. Unfortunately, this is less the 47th Fibonacci number, 2971215073. The resulting... | 6 | 2016-09-20T20:11:54Z | [
"python",
"numpy",
"matrix"
] |
Calling out a function, not defined error | 39,602,440 | <p>I'm new to making classes and I'm trying to complete exercise 9-1 in my 'Python Crash Course' book where the last part of the question asks me to call back my method but I end up getting</p>
<blockquote>
<p>'not defined error' for <code>describe_restaurant()</code>.</p>
</blockquote>
<p><strong>Here is my code:<... | 0 | 2016-09-20T19:35:28Z | 39,602,472 | <p>Try:</p>
<pre><code>class Restaurant():
def __init__(self, r_name, c_type):
self.r_name = r_name
self.c_type = c_type
def describe_restaurant(self):
print(self.r_name)
print(self.c_type)
def open_restaurant(self):
return "{} is now open!".format(self.r_name)
re... | 2 | 2016-09-20T19:37:18Z | [
"python",
"class"
] |
Replace Values in Dictionary | 39,602,476 | <p>I am trying to replace the <code>values</code> in the <code>lines dictionary</code> by the <code>values of the corresponding key</code> in the <code>points dictionary</code></p>
<pre><code>lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'... | 2 | 2016-09-20T19:37:41Z | 39,602,535 | <p>You are getting the wrong output because of
<code>lines[k] = v</code> . That is overwriting your previous assignment.</p>
<p>For your desired output - </p>
<pre><code>lines = {'24': ('2', '10'), '25': ('17', '18')} #k,v => Line ID(Points)
points = {'10': ('2.416067758476', '2.075872272548'), '17': ('2.45472513... | 2 | 2016-09-20T19:42:27Z | [
"python",
"python-2.7",
"dictionary"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.