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 |
|---|---|---|---|---|---|---|---|---|---|
Fast incremental update of the mean and covariance in Python | 37,498,612 | <p>I have a Python script where I need to frequently update the mean and co-variance matrix. What I am currently doing is that each time I get a new data point $x$ (a vector), I recompute the mean and covariance as follows:</p>
<pre><code>data.append(x) # My `data` is just a list of lists of floats (i.e., x is a list ... | 2 | 2016-05-28T11:49:06Z | 37,498,797 | <p>For mean calculation, you could store the mean of N data before, suppose it's called "before_mean", and when new data x comes, new mean of these N+1 data will be simply calculated like before:</p>
<pre><code>new_mean = float(before_mean * N + x) / (N + 1)
</code></pre>
<p>so you don't need to recalculate before da... | -1 | 2016-05-28T12:07:42Z | [
"python",
"numpy",
"normal-distribution"
] |
Fast incremental update of the mean and covariance in Python | 37,498,612 | <p>I have a Python script where I need to frequently update the mean and co-variance matrix. What I am currently doing is that each time I get a new data point $x$ (a vector), I recompute the mean and covariance as follows:</p>
<pre><code>data.append(x) # My `data` is just a list of lists of floats (i.e., x is a list ... | 2 | 2016-05-28T11:49:06Z | 37,499,056 | <p>For a variance (only the diagonal of the covariance matrix) it is simple. You need to also keep the sum of squares for your data. Recall that the formula for variance is: Var(x)=E[x^2]-(E[x])^2). So each step you are calculating your regular mean, and the mean of the squares sum.</p>
<p>This can be generalized for ... | 0 | 2016-05-28T12:35:10Z | [
"python",
"numpy",
"normal-distribution"
] |
Fast incremental update of the mean and covariance in Python | 37,498,612 | <p>I have a Python script where I need to frequently update the mean and co-variance matrix. What I am currently doing is that each time I get a new data point $x$ (a vector), I recompute the mean and covariance as follows:</p>
<pre><code>data.append(x) # My `data` is just a list of lists of floats (i.e., x is a list ... | 2 | 2016-05-28T11:49:06Z | 37,499,920 | <p>I just figured out that we can easily do that using the mdp library
<a href="http://mdp-toolkit.sourceforge.net/api/mdp.utils.CovarianceMatrix-class.html" rel="nofollow">http://mdp-toolkit.sourceforge.net/api/mdp.utils.CovarianceMatrix-class.html</a></p>
| 0 | 2016-05-28T14:02:29Z | [
"python",
"numpy",
"normal-distribution"
] |
Fast incremental update of the mean and covariance in Python | 37,498,612 | <p>I have a Python script where I need to frequently update the mean and co-variance matrix. What I am currently doing is that each time I get a new data point $x$ (a vector), I recompute the mean and covariance as follows:</p>
<pre><code>data.append(x) # My `data` is just a list of lists of floats (i.e., x is a list ... | 2 | 2016-05-28T11:49:06Z | 37,501,938 | <p>I'd do it by keeping track of the sum and sum of squares.</p>
<p>In the <code>__init__</code>:</p>
<pre><code>self.sumx = 0
self.sumx2 = 0
</code></pre>
<p>And then in the append:</p>
<pre><code>data.append(x)
self.sumx += x
self.sumx2 += x * x[:,np,newaxis]
self.mean = sumx / len(data)
self.cov = (self.sumx2 -... | 1 | 2016-05-28T17:33:01Z | [
"python",
"numpy",
"normal-distribution"
] |
Windows 7 cmd, from Visual Studio, not displaying floats | 37,498,622 | <p>In Visual Studio 2015, I made a program to calculate pi. The variable for pi is <code>float</code> (I wasn't sure if this was really necessary but I thought I might as well just in case), anyway.. Here's the function:</p>
<pre><code>float pi(int accuracy) {
float pi = 3;
int nint = 2;
int next;
for ... | 0 | 2016-05-28T11:50:19Z | 37,498,664 | <p>"The variable for pi is long long" - that's likely your problem right there. <code>long long</code> is an integer type. It can't store a floating point number like pi. Use a <code>float</code>, <code>double</code> or <code>long double</code>.</p>
| 0 | 2016-05-28T11:54:37Z | [
"python",
"c++",
"cmd",
"visual-studio-2015",
"floating-point"
] |
Windows 7 cmd, from Visual Studio, not displaying floats | 37,498,622 | <p>In Visual Studio 2015, I made a program to calculate pi. The variable for pi is <code>float</code> (I wasn't sure if this was really necessary but I thought I might as well just in case), anyway.. Here's the function:</p>
<pre><code>float pi(int accuracy) {
float pi = 3;
int nint = 2;
int next;
for ... | 0 | 2016-05-28T11:50:19Z | 37,498,691 | <p><code>next = 4 / (nint * (nint + 1) * (nint + 2));</code></p>
<p><code>(nint * (nint + 1) * (nint + 2))</code> is an <code>int</code>. 4 is an <code>int</code>. Dividing two <code>int</code>s gives you another <code>int</code>, by removing the decimal part (because <code>int</code>s have no decimal parts).</p>
<p>... | 3 | 2016-05-28T11:57:12Z | [
"python",
"c++",
"cmd",
"visual-studio-2015",
"floating-point"
] |
Coverting list of Coordinates to list of tuples | 37,498,669 | <p>I'm trying to covert a list of coordinates to a list of tuples:</p>
<p>from:</p>
<pre><code>a_list = ['56,78','72,67','55,66']
</code></pre>
<p>to:</p>
<pre><code>list_of_tuples = [(56,78),(72,67),(55,66)]
</code></pre>
<p>I've tried doing a for, in loop to convert each element in a_list to a tuple however the ... | 1 | 2016-05-28T11:55:07Z | 37,498,720 | <p>Use a list comprehension, <code>split</code> the items and convert each subitem to <code>int</code> using <code>map</code>: </p>
<pre><code>>>> result = [map(int, item.split(',')) for item in a_list ]
>>> result
[(56, 78), (72, 67), (55,66)]
</code></pre>
<p>On python 3.x, you should convert th... | 0 | 2016-05-28T12:00:33Z | [
"python",
"list",
"for-loop",
"tuples",
"coordinates"
] |
Coverting list of Coordinates to list of tuples | 37,498,669 | <p>I'm trying to covert a list of coordinates to a list of tuples:</p>
<p>from:</p>
<pre><code>a_list = ['56,78','72,67','55,66']
</code></pre>
<p>to:</p>
<pre><code>list_of_tuples = [(56,78),(72,67),(55,66)]
</code></pre>
<p>I've tried doing a for, in loop to convert each element in a_list to a tuple however the ... | 1 | 2016-05-28T11:55:07Z | 37,498,725 | <pre><code>a_list = ['56,78','72,67','55,66']
coords = []
for x in a_list:
lat, lon = x.split(',')
coords.append((int(lat),int(lon)))
print coords
</code></pre>
<p>Output:</p>
<pre><code>[(56, 78), (72, 67), (55, 66)]
</code></pre>
| 0 | 2016-05-28T12:01:01Z | [
"python",
"list",
"for-loop",
"tuples",
"coordinates"
] |
Coverting list of Coordinates to list of tuples | 37,498,669 | <p>I'm trying to covert a list of coordinates to a list of tuples:</p>
<p>from:</p>
<pre><code>a_list = ['56,78','72,67','55,66']
</code></pre>
<p>to:</p>
<pre><code>list_of_tuples = [(56,78),(72,67),(55,66)]
</code></pre>
<p>I've tried doing a for, in loop to convert each element in a_list to a tuple however the ... | 1 | 2016-05-28T11:55:07Z | 37,498,741 | <p>You can use list comprehension:</p>
<pre><code>result = [tuple(map(int,element.split(','))) for element in a_list]
</code></pre>
<p>edit: shorter version by @Lol4t0</p>
<p>As mentioned the spaces between the elements come from printing the list. There are no actual "spaces" in the data structure. However, if you ... | 3 | 2016-05-28T12:02:15Z | [
"python",
"list",
"for-loop",
"tuples",
"coordinates"
] |
Coverting list of Coordinates to list of tuples | 37,498,669 | <p>I'm trying to covert a list of coordinates to a list of tuples:</p>
<p>from:</p>
<pre><code>a_list = ['56,78','72,67','55,66']
</code></pre>
<p>to:</p>
<pre><code>list_of_tuples = [(56,78),(72,67),(55,66)]
</code></pre>
<p>I've tried doing a for, in loop to convert each element in a_list to a tuple however the ... | 1 | 2016-05-28T11:55:07Z | 37,498,931 | <p>Nice and simple, here it is</p>
<pre><code> a_list = ['56,78','72,67','55,66']
result = []
for coord in a_list:
result.append(tuple([int(x) for x in coord.split(',')]))
print(str(result).replace(" ", ""))
# Output
[(56,78),(72,67),(55,66)]
</code></pre>
<p>The first way I thought... | 0 | 2016-05-28T12:22:31Z | [
"python",
"list",
"for-loop",
"tuples",
"coordinates"
] |
Print text before input() prompt in python | 37,498,704 | <p>In Python, is it possible to request user input with input() in the console while simultaneously printing out text in the line BEFORE the prompt?
It should look something like this:</p>
<pre><code>Text 1
Text 2
Text 3
Please enter something: abc
</code></pre>
<p>Whenever new text is printed, it should be printed a... | 1 | 2016-05-28T11:59:25Z | 37,499,080 | <p>On Linux you can do it this way:</p>
<pre><code>#!/usr/bin/python
CURSOR_UP_ONE = '\x1b[1A'
ERASE_LINE = '\x1b[2K'
print('Text 1\nText 2\nText 3')
inp = ''
while inp != 'END':
inp = raw_input('Please enter something:')
print(CURSOR_UP_ONE + ERASE_LINE + inp)
</code></pre>
<p>The point is in moving the c... | 1 | 2016-05-28T12:36:55Z | [
"python",
"cmd"
] |
Print text before input() prompt in python | 37,498,704 | <p>In Python, is it possible to request user input with input() in the console while simultaneously printing out text in the line BEFORE the prompt?
It should look something like this:</p>
<pre><code>Text 1
Text 2
Text 3
Please enter something: abc
</code></pre>
<p>Whenever new text is printed, it should be printed a... | 1 | 2016-05-28T11:59:25Z | 37,499,086 | <p>You could mimic what you want by doing something like this:</p>
<pre><code>import os
def clear(): os.system('cls')
screen = ""
prompt = ""
def printToScreen(s):
global screen, prompt
clear()
screen += (s + '\n')
print(screen)
print(prompt)
def promptToScreen(p):
global screen, prompt
... | 1 | 2016-05-28T12:37:14Z | [
"python",
"cmd"
] |
Print text before input() prompt in python | 37,498,704 | <p>In Python, is it possible to request user input with input() in the console while simultaneously printing out text in the line BEFORE the prompt?
It should look something like this:</p>
<pre><code>Text 1
Text 2
Text 3
Please enter something: abc
</code></pre>
<p>Whenever new text is printed, it should be printed a... | 1 | 2016-05-28T11:59:25Z | 37,501,797 | <p>Here's another approach using ANSI/VT100 terminal control escape sequences. </p>
<p>We tell the terminal to only scroll the upper region of the terminal, where the output data is printed, so that the lower region, where the input prompt is printed, stays fixed in place. When we exit the program (using <kbd>Ctrl</kb... | 1 | 2016-05-28T17:16:47Z | [
"python",
"cmd"
] |
print function does not get called in an async function before await in python | 37,498,791 | <p>I want to get some links with requests and asyncio.I have a sample program but I think there is a problem because the print function only gets called when I'm using await.</p>
<p>So why doesn't print gets called where I call the actual function? What I have understood if the await keyword is used, the function inte... | 1 | 2016-05-28T12:07:15Z | 37,499,194 | <p>coroutines don't get executed until they are awaited, that is why it's happening</p>
| 0 | 2016-05-28T12:48:59Z | [
"python",
"asynchronous",
"python-requests",
"python-3.5",
"python-asyncio"
] |
Dynamically creating module in sys.modules causes sys to become None | 37,498,894 | <p>I'm creating a module called <code>Qt</code> (<a href="https://github.com/mottosso/Qt/blob/master/Qt.py" rel="nofollow">Github link</a>) where I alias another module (for example <code>PyQt4</code>), so that when I import <code>Qt</code> I am in fact importing <code>PyQt4</code>:</p>
<pre><code>from Qt import QtWid... | 4 | 2016-05-28T12:18:22Z | 37,505,358 | <p>When there are no longer any reference to a module, it will drop all its globals by replacing them with <code>None</code>.</p>
<p>You need to remember the <em>old</em> verion of <code>sys.modules['Xyz']</code> (i.e. the current module) until you are done executing it.</p>
| 3 | 2016-05-29T01:38:40Z | [
"python"
] |
how to access custom exception handler from python module? | 37,498,929 | <p>These are my files:</p>
<pre><code>myModule/__init__.py
import sys
class MyModule:
handle_exceptions = handle_exceptions
def __init__(self):
sys.excepthook = handle_exceptions
#myModule/handle_exceptions.py
def handle_exceptions(ex_cls, ex, tb):
#not important here
pass
#my_script.py
import s... | -1 | 2016-05-28T12:22:24Z | 37,499,183 | <p>Try this</p>
<pre><code>myModule/__init__.py
import sys
class MyModule:
def __init__(self):
sys.excepthook = handle_exceptions
self.handle_exceptions = handle_exceptions
#myModule/handle_exceptions.py
def handle_exceptions(ex_cls, ex, tb):
#not important here
pass
import sys
from myModule impor... | 0 | 2016-05-28T12:48:28Z | [
"python",
"exception-handling"
] |
OpenCV: wait for different keys? | 37,499,096 | <p>I am working with OpenCV and I want OpenCV to <em>not</em> wait for <em>any</em> key being pressed (default behaviour of <code>cv2.waitKey()</code>), but to wait for specific keys that I define (and do subsequent actions).</p>
<p>My current solution for this problem is the following recursive one:</p>
<pre><code>d... | 2 | 2016-05-28T12:39:28Z | 37,522,271 | <p>If it is not neccessary you could try non-recursive approach:</p>
<pre><code>def is_pressed(key)
# if statement
def opencv_wait():
key = 0
while is_pressed(key) :
key = cv2.waitKey(0)
</code></pre>
| 0 | 2016-05-30T09:33:17Z | [
"python",
"python-2.7",
"opencv",
"wait",
"keypress"
] |
Geany not running Python | 37,499,130 | <p>I'm a new user of Python</p>
<p>I installed Python35 for Windows. Hello.py runs fine in a terminal.
When trying to run the same in Geany the path is not found.</p>
<p>These are the settings in Geany:</p>
<p>Compile: C:\Python35\python -m py_compile "%f"</p>
<p>Execute: C:\Python35\python ¨%f¨</p>
<p>What I'm... | 1 | 2016-05-28T12:42:40Z | 37,499,554 | <blockquote>
<p>Execute: C:\Python35\python ¨%f¨</p>
</blockquote>
<p>This string contains the diaeresis character (¨) (U+00A8) instead of the double quote (") (U+0022).</p>
| 1 | 2016-05-28T13:23:51Z | [
"python",
"geany"
] |
Mass insert with Redis fails with strange errors | 37,499,131 | <p>I am playing with Redis mass import using the pipe and have the following Python script:</p>
<pre><code>mydata = ""
mydata += "*4\r\n$4\r\nHSET\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n" % (len('myhash'), 'myhash', len('myfield'), 'myfield', len('myvalue'), 'myvalue')
print mydata.rstrip()
</code></pre>
<p>It pr... | 0 | 2016-05-28T12:42:42Z | 37,500,946 | <p>Answer to my own question: I didn't know it needed a final CRLF, hence this:</p>
<pre><code>print mydata.rstrip()
</code></pre>
<p>Became:</p>
<pre><code>print mydata
</code></pre>
<p>Result:</p>
<pre><code>$ python redis_test.py | redis-cli -h rnode -n 5 --pipe --pipe-timeout 10
All data transferred. Waiting f... | 0 | 2016-05-28T15:43:20Z | [
"python",
"redis"
] |
how to print previous string after selecting specific string python | 37,499,148 | <p>I want to find word that appear before a keyword (specified and searched by me) and print out the result. I tried below code but it gives me after words not before...</p>
<pre><code> str = "Phone has better display, good speaker. Phone has average display"
p1 = re.search(r"(display>=?)(.*)", str)
if p... | -1 | 2016-05-28T12:44:58Z | 37,499,245 | <p>You can use a positive lookahead, with <code>findall</code> instead of <code>search</code>:</p>
<pre><code>>>> p = re.compile(r'(\w+)\s+(?=display)')
>>> p.findall(str)
['better', 'average']
</code></pre>
| 2 | 2016-05-28T12:53:59Z | [
"python",
"regex",
"search",
"keyword",
"matching"
] |
how to print previous string after selecting specific string python | 37,499,148 | <p>I want to find word that appear before a keyword (specified and searched by me) and print out the result. I tried below code but it gives me after words not before...</p>
<pre><code> str = "Phone has better display, good speaker. Phone has average display"
p1 = re.search(r"(display>=?)(.*)", str)
if p... | -1 | 2016-05-28T12:44:58Z | 37,499,274 | <p>You can use a positive lookahead assertion <code>?=</code>:</p>
<pre><code>import re
str = "Phone has better display, good speaker. Phone has average display"
p1 = re.findall(r"(\w+)\s*(?=display)", str)
print(p1)
# ['better', 'average']
</code></pre>
<p><code>\w</code> means a word character.</p>
| 0 | 2016-05-28T12:56:46Z | [
"python",
"regex",
"search",
"keyword",
"matching"
] |
How do I make a stopwatch that continues to run even after closing the application? | 37,499,166 | <p>I'd like to create a stopwatch of-sorts that records the duration elapsed from a specific moment in time. I would then save it to a database. When I close the application and then reload the application I'd like to be able to see the time elapsed since the specific moment in time the timer was initiated. I'd also li... | 0 | 2016-05-28T12:46:54Z | 37,499,256 | <p>You can put your timer code in thread, which will work as deamon , and record the time:</p>
<pre><code>class TimeThread(threading.Thread):
stop = 0
def __init__(self):
threading.Thread.__init__(self)
def run(self):
# here your code for timer
#you can put some condition to ... | 0 | 2016-05-28T12:55:23Z | [
"python",
"datetime"
] |
How do I make a stopwatch that continues to run even after closing the application? | 37,499,166 | <p>I'd like to create a stopwatch of-sorts that records the duration elapsed from a specific moment in time. I would then save it to a database. When I close the application and then reload the application I'd like to be able to see the time elapsed since the specific moment in time the timer was initiated. I'd also li... | 0 | 2016-05-28T12:46:54Z | 37,499,289 | <p>Write the start time in a file.</p>
<p>Or, don't even bother writing the time in the file, just <code>touch</code> the file and use its modification time. For that, see: <a href="http://stackoverflow.com/questions/1158076/implement-touch-using-python">Implement touch using Python?</a></p>
| 0 | 2016-05-28T12:58:39Z | [
"python",
"datetime"
] |
Django CSRF Error PW Reset and Login | 37,499,392 | <p>I'm using django.contrib.auth.views for password reset.</p>
<p>I get the CSRF error when I try to submit the password change form.</p>
<p>It lets me enter my email, sends me a link with uidb64 and token, and then lets me enter a new password twice. When I submit this password_reset_confirm form I get the CSRF inv... | 0 | 2016-05-28T13:09:07Z | 37,499,645 | <p>Remove the <code><div class='form'></code> tag.
Place <code>{% csrf_token %}</code> right after <code><form class="login-form" action="" method="post"></code>.</p>
| 0 | 2016-05-28T13:32:12Z | [
"python",
"django"
] |
RxPy with_latest_from producing inconsistent results | 37,499,424 | <p>I'm using <code>group_by</code> on an <code>Observable</code> but for each newly created group, I want to snap the element (with the new key) that caused the group to be created using <code>with_latest_from</code>:</p>
<pre><code>>>> from __future__ import print_function
>>> from rx import Observa... | 0 | 2016-05-28T13:11:41Z | 37,499,433 | <p>From <a href="https://github.com/ReactiveX/RxPY/issues/96" rel="nofollow">Dag Brattli</a>:</p>
<blockquote>
<p>The problem seems to be that you are basically using with_latest_from() on a stream with itself. Thus there are no guaranties if source or latest will trigger first. If latest triggers before source for ... | 0 | 2016-05-28T13:12:24Z | [
"python",
"reactive-programming",
"rx-py"
] |
python-requests cookies export session to selenium | 37,499,452 | <p>I want to export cookies session from python-requests to selenium, im write this code :</p>
<pre><code>import requests
from selenium import webdriver
session=requests.Session()
MyHeaderss = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.32 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.32", "X-... | 0 | 2016-05-28T13:14:26Z | 37,531,556 | <p>Cookies are not floating around in the browser preferences. They are always tied to a specific domain or a wildcard domain, but they always have a domain.</p>
<p>Have a look at <a href="https://pypi.python.org/pypi/selenium-requests/" rel="nofollow">selenium-requests</a> package which seems to ease the creation of ... | 0 | 2016-05-30T18:13:19Z | [
"python",
"session",
"selenium",
"cookies",
"python-requests"
] |
Edit multiple objects with Get() function Django | 37,499,636 | <p>I want to edit two forms in Django. A form for 'Motel' and its 'Images'. In my app, users can upload multiple images to the 'Motel' model. And now, editing the images with 'get()' function is giving me,</p>
<pre><code>MultipleObjectsReturned get() returned more than one MotelImages -- it returned 4!
</code></pre>
... | 0 | 2016-05-28T13:31:17Z | 37,499,681 | <p><code>images = MotelImages.objects.get(motel=motel_id)</code></p>
<p>Since <code>get</code> can return only one object, you want to use <code>filter</code>:</p>
<p><code>images = MotelImages.objects.filter(motel__pk=motel_id)</code></p>
<p><code>images</code> will be a list of the relevant images.</p>
| 0 | 2016-05-28T13:35:12Z | [
"python",
"django",
"django-models",
"django-views"
] |
Create file from bytes stored as string | 37,499,637 | <p>I have a use case where I am getting a blob back from the database which I have to convert to a binary file. Python stores this as a string although it is actually bytes. When I try to write as binary I get a Type Error, str not accepted.</p>
<p>I wrote some sample code to reproduce what the variable looks like. I ... | 1 | 2016-05-28T13:31:18Z | 37,499,785 | <p>You can write:</p>
<pre><code>f.write(bytearray(output,"utf-8"))
</code></pre>
<p>instead of:</p>
<pre><code>f.write(output) #TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>to solve the problem. Although it seems not to be the most pythonic way to do it.</p>
| 0 | 2016-05-28T13:46:56Z | [
"python",
"python-3.x",
"byte"
] |
Listing all the variables in a Python class | 37,499,694 | <p>I've made a class, and after the program has finished running, I want to list all the variables I have kinda like so</p>
<pre><code>var1: val
var2: val
etc
</code></pre>
<p>my class looks like this</p>
<pre><code>class character:
name = 'Player1'
level = 1
str = 100
con = 80
sta = 150
critchanc... | 1 | 2016-05-28T13:36:11Z | 37,499,783 | <p>You can use dictionary comprehension (assuming Python 2.6+) to extract the variables from the class' <code>__dict__</code>:</p>
<pre><code>print({k: v for k, v in character.__dict__.items() if not k.startswith('__')})
>> {'con': 80, 'level': 1, 'critchance': 0.1, 'sta': 150,
'str': 100, 'name': 'Player1'... | 1 | 2016-05-28T13:46:41Z | [
"python"
] |
Listing all the variables in a Python class | 37,499,694 | <p>I've made a class, and after the program has finished running, I want to list all the variables I have kinda like so</p>
<pre><code>var1: val
var2: val
etc
</code></pre>
<p>my class looks like this</p>
<pre><code>class character:
name = 'Player1'
level = 1
str = 100
con = 80
sta = 150
critchanc... | 1 | 2016-05-28T13:36:11Z | 37,499,790 | <p>Is something like this what you are looking for?</p>
<pre><code>for var in dir(character):
if var[:2] != '__':
print '%s:' % var, getattr(character, var)
</code></pre>
| 0 | 2016-05-28T13:47:22Z | [
"python"
] |
String formatting argument reference with item lookup | 37,499,702 | <p>Is it possible to use the value of a format string argument as a key to other argument?</p>
<pre><code>mins = {'a': 2, 'b': 4, 'c': 3}
maxs = {'a': 12, 'b': 7, 'c': 21}
'{0} {1[{0}]} {2[{0}]}'.format('a', mins, maxs)
</code></pre>
<p>I'd expect <code>a 2 12</code> however a <code>KeyError: '{0}'</code> is thrown ... | 3 | 2016-05-28T13:37:13Z | 37,500,150 | <p>No, according to the <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow">PEP3101</a>, you <em>cannot nest the replacement fields</em>:</p>
<blockquote>
<p>Format specifiers can themselves contain replacement fields. For
example, a field whose field width is itself a parameter could be
specified... | 2 | 2016-05-28T14:25:34Z | [
"python"
] |
How can I send a image by using mosquitto? | 37,499,739 | <p>I'm a student who is studying MQTT and I'm trying to send a jpg image using MQTT mosquitto broker(pub and sub) in Raspberry Pi2.</p>
<p>I've solved many error, however, It doesn't work.</p>
<p>This is my python code pub.py(modified)</p>
<pre><code>import paho.mqtt.client as mqtt
def on_publish(mosq, userdata, mi... | 0 | 2016-05-28T13:41:54Z | 37,501,126 | <p>In <em>sub.py</em> you have 2 <code>on_public</code> functions which should be renamed <code>on_connect</code> and <code>on_publish</code> respectively.</p>
<p>In <em>pub.py</em> you need to actually set the <code>on_publish</code> method on the client so it will be called once the publish has been completed. </p>
... | 1 | 2016-05-28T16:01:11Z | [
"python",
"raspberry-pi",
"publish-subscribe",
"mqtt",
"mosquitto"
] |
How can I send a image by using mosquitto? | 37,499,739 | <p>I'm a student who is studying MQTT and I'm trying to send a jpg image using MQTT mosquitto broker(pub and sub) in Raspberry Pi2.</p>
<p>I've solved many error, however, It doesn't work.</p>
<p>This is my python code pub.py(modified)</p>
<pre><code>import paho.mqtt.client as mqtt
def on_publish(mosq, userdata, mi... | 0 | 2016-05-28T13:41:54Z | 37,752,494 | <p>In your sub.py you need a callback which handles incoming messages for your subscription. The standard callback for that is <code>on_message</code>.</p>
<p>Just rename in your sub.y <code>on_publish(client, userdata, msg)</code> to <code>on_message(client, userdata, msg)</code>and assign <code>client.on_message = o... | 1 | 2016-06-10T15:56:07Z | [
"python",
"raspberry-pi",
"publish-subscribe",
"mqtt",
"mosquitto"
] |
python split a unicode string by 3-bytes utf8 character | 37,499,815 | <p>suppose that we have a unicode string in python,</p>
<p><code>s = u"abcä½ å¥½defå"</code></p>
<p>Now I want to split that by no-ascii characters, with result like
<code>
result = ["abc", "ä½ å¥½", "def", "å"]
</code></p>
<p>So, how to implement that?</p>
| 3 | 2016-05-28T13:49:45Z | 37,499,954 | <p>With regex you could simply split between "has or has not" a-z chars.</p>
<pre><code>>>> import re
>>> re.findall('([a-zA-Z0-9]+|[^a-zA-Z0-9]+)', u"abcä½ å¥½defå")
["abc", "ä½ å¥½", "def", "å"]
</code></pre>
<p>Or, with all ASCIIs</p>
<pre><code>>>> ascii = ''.join(chr(x) for x in r... | 4 | 2016-05-28T14:06:02Z | [
"python",
"regex",
"unicode"
] |
python split a unicode string by 3-bytes utf8 character | 37,499,815 | <p>suppose that we have a unicode string in python,</p>
<p><code>s = u"abcä½ å¥½defå"</code></p>
<p>Now I want to split that by no-ascii characters, with result like
<code>
result = ["abc", "ä½ å¥½", "def", "å"]
</code></p>
<p>So, how to implement that?</p>
| 3 | 2016-05-28T13:49:45Z | 37,500,007 | <pre><code>s = "abcä½ å¥½defå"
filter(None, re.split('(\w+|\W+)', s))
</code></pre>
<p>works in python 2.x versions</p>
| 1 | 2016-05-28T14:11:49Z | [
"python",
"regex",
"unicode"
] |
python split a unicode string by 3-bytes utf8 character | 37,499,815 | <p>suppose that we have a unicode string in python,</p>
<p><code>s = u"abcä½ å¥½defå"</code></p>
<p>Now I want to split that by no-ascii characters, with result like
<code>
result = ["abc", "ä½ å¥½", "def", "å"]
</code></p>
<p>So, how to implement that?</p>
| 3 | 2016-05-28T13:49:45Z | 37,500,081 | <p>You can do something like this:</p>
<pre><code>s = u"abcä½ å¥½defå"
status = ord(s[0]) < 128
word = ""
res =[]
for b, letter in zip([ ord(c) < 128 for c in s ], s):
if b != status:
res.append(word)
status = b
word = ""
word += letter
res.append(word)
print res
&... | 2 | 2016-05-28T14:19:10Z | [
"python",
"regex",
"unicode"
] |
python split a unicode string by 3-bytes utf8 character | 37,499,815 | <p>suppose that we have a unicode string in python,</p>
<p><code>s = u"abcä½ å¥½defå"</code></p>
<p>Now I want to split that by no-ascii characters, with result like
<code>
result = ["abc", "ä½ å¥½", "def", "å"]
</code></p>
<p>So, how to implement that?</p>
| 3 | 2016-05-28T13:49:45Z | 37,500,647 | <p>Just ... split.</p>
<pre><code>[s[i:i+3] for i in xrange(0, len(s), 3)]
</code></pre>
<p><a href="http://ideone.com/PeoGaF" rel="nofollow">http://ideone.com/PeoGaF</a></p>
| 0 | 2016-05-28T15:12:22Z | [
"python",
"regex",
"unicode"
] |
Python 3.4: zlib, deflate and shared dict | 37,499,818 | <p>Any ideas how to fix following code (Python 3.4.3):</p>
<pre><code>import zlib
hello = b'hello'
co = zlib.compressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
data = co.compress(hello) + co.flush()
do = zlib.decompressobj(wbits=-zlib.MAX_WBITS, zdict=hello)
data = do.decompress(data)
print(data)
</code></pre>
<p>F... | 0 | 2016-05-28T13:50:01Z | 37,504,728 | <p>You can't use negative wbits with a dictionary. Negative wbits gets rid of the zlib header and trailer, but the zlib header is how decompress knows to use a dictionary.</p>
<p>Just get rid of the wbits options.</p>
| 0 | 2016-05-28T23:34:01Z | [
"python",
"zlib"
] |
Merge rows in dataframe | 37,499,819 | <p>Part of a csv-file ('data.csv') I have to process, looks like this:</p>
<pre><code>parent_id,parent_name,Type,Companyname,Custsupid,Streetaddress
3,Customer,,,C0010,
3,Customer,A,,,
3,Customer,,ACE SYSTEMS,,
3,Customer,,,,Straat 10
7,Customer,,,Q8484,
7,Customer,B,,,
7,Customer,,XYZ AUTOMAT,,
7,Customer,,,,Laan 99
... | 2 | 2016-05-28T13:50:03Z | 37,499,956 | <pre><code>In [37]: df.groupby(['parent_id', 'parent_name']).sum()
Out[37]:
Type Companyname Custsupid Streetaddress
parent_id parent_name
3 Customer A ACE SYSTEMS C0010 Straat 10
7 Customer B XYZ AUTOMAT Q8484 ... | 2 | 2016-05-28T14:06:22Z | [
"python",
"pandas",
"dataframe"
] |
<type 'exceptions.SyntaxError'> invalid table/column name "size" is a "ALL" reserved SQL/NOSQL keyword | 37,499,864 | <pre><code> db.define_table('bookspace',
Field('locaton','string'),
Field('size','string'),
Field('availablefrom', 'string'),
Field('availableto', 'string'),
Field('rooftype', 'string'),
Field('sitetype', 'string'),
Field('name', '... | 0 | 2016-05-28T13:55:14Z | 37,499,926 | <pre><code>db = DAL(..., entity_quoting=True)
</code></pre>
<p><a href="http://www.web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Database-quoting-and-case-settings-entity_quoting-ignore_field" rel="nofollow">http://www.web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Databa... | 0 | 2016-05-28T14:03:16Z | [
"python",
"sqlite",
"web2py",
"web2py-modules"
] |
<type 'exceptions.SyntaxError'> invalid table/column name "size" is a "ALL" reserved SQL/NOSQL keyword | 37,499,864 | <pre><code> db.define_table('bookspace',
Field('locaton','string'),
Field('size','string'),
Field('availablefrom', 'string'),
Field('availableto', 'string'),
Field('rooftype', 'string'),
Field('sitetype', 'string'),
Field('name', '... | 0 | 2016-05-28T13:55:14Z | 37,499,937 | <p>Size is a word that is reserved by the db. That is, they have a special meaning to the db and so cannot be redefined. For this reason, you cannot use them to name database objects such as columns, tables, or indexes. Try using a different name instead :)</p>
| 0 | 2016-05-28T14:04:35Z | [
"python",
"sqlite",
"web2py",
"web2py-modules"
] |
<type 'exceptions.SyntaxError'> invalid table/column name "size" is a "ALL" reserved SQL/NOSQL keyword | 37,499,864 | <pre><code> db.define_table('bookspace',
Field('locaton','string'),
Field('size','string'),
Field('availablefrom', 'string'),
Field('availableto', 'string'),
Field('rooftype', 'string'),
Field('sitetype', 'string'),
Field('name', '... | 0 | 2016-05-28T13:55:14Z | 37,506,311 | <p>You need to set appropriate value for <code>check_reserved</code> in DAL signature.</p>
<p>Read this - <a href="http://Read%20http://www.web2py.com/books/default/chapter/29/06/the-database-abstraction-layer#Reserved-keywords" rel="nofollow">Reserved keywords</a></p>
<p>Other solution can be, use <code>rname</code>... | 0 | 2016-05-29T04:53:42Z | [
"python",
"sqlite",
"web2py",
"web2py-modules"
] |
error while connecting kivy app with bluetooth. | 37,499,941 | <p>i'm using windows 7 and python 2.7, i'm trying to connect my kivy app with bluetooth but i'm getting this error message. please explain. </p>
<pre><code>*Traceback (most recent call last):
File "bluetooth.py", line 15, in <module>
BluetoothAdapter = autoclass('android.bluetooth.BluetoothAdapter')
File... | 0 | 2016-05-28T14:05:04Z | 37,500,174 | <p>The code you're showing is what you'd run on Android to access the BluetoothAdapter class. Windows doesn't have this (or any of the rest of the Android API), so it fails.</p>
<p>If you want to use bluetooth on windows, find a windows platform specific way of doing it (this is unlikely to involve pyjnius).</p>
| 1 | 2016-05-28T14:27:41Z | [
"android",
"python",
"bluetooth",
"kivy"
] |
Finding all repeated substrings in a string and how often they appear | 37,499,968 | <h2>Problem:</h2>
<p>I need all the sequences of characters that meet the following:</p>
<ol>
<li>Sequence of characters must be present more than once ((LE, 1) is thus invalid). </li>
<li>Sequence of characters must be longer than one character ((M, 2) is thus invalid).</li>
<li>Sequence of characters must not be pa... | 1 | 2016-05-28T14:07:37Z | 37,985,206 | <p>Your suffix tree approach is the right way.</p>
<h2>Getting the set of matches and their number of occurrences</h2>
<p>Basically what you need to do is traverse the tree in a BFS fashion. Starting from the root's children you would recursively count the number of leaves reachable by each node. This would lead to a... | 2 | 2016-06-23T07:43:34Z | [
"python",
"string",
"algorithm",
"suffix-tree"
] |
Odoo: test unique constraint? | 37,499,977 | <p>It looks like Odoo fails at testing unique constraint.</p>
<p>I have added this constraint:</p>
<pre><code>_sql_constraints = [(
'uniq_line',
'unique(routing_phase_id, project_id)',
'Phase have to be unique per Routing!')
]
</code></pre>
<p>Constraint itself works, but running unittest, I can't succes... | 1 | 2016-05-28T14:09:04Z | 39,466,498 | <p>Encountered this issue myself and found an existing test used by Odoo themselves. </p>
<p>They use a <code>openerp.tools.mute_logger('openerp.sql_db')</code> decorator on methods testing that an IntegrityError is raised.</p>
<p><a href="https://github.com/odoo/odoo/blob/7682760dcad232829fbb5d4221f66a1ebb9d6c91/ope... | 1 | 2016-09-13T09:24:26Z | [
"python",
"unit-testing",
"openerp",
"odoo-8",
"unique-constraint"
] |
Python nested loop speed issues | 37,500,035 | <p>I am currently working on a program to test for ideal angle-values to construct something. Now I'm stuck at a nested-for-loop which I'm going to attach below. While idealy it would count each 'a' to 9000, it already takes almost forever if values are set like below. Is there a way to speed up this nested loop? Or ca... | 0 | 2016-05-28T14:14:58Z | 37,500,064 | <p>The <a href="https://docs.python.org/2.7/library/itertools.html#itertools.product" rel="nofollow"><em>itertools.product()</em></a> function will greatly speed the nested for-loops.</p>
<p>That said, the running time will likely be dominated by the total number of calls to <em>mathmatvec()</em>.</p>
| 1 | 2016-05-28T14:17:40Z | [
"python",
"for-loop"
] |
Python nested loop speed issues | 37,500,035 | <p>I am currently working on a program to test for ideal angle-values to construct something. Now I'm stuck at a nested-for-loop which I'm going to attach below. While idealy it would count each 'a' to 9000, it already takes almost forever if values are set like below. Is there a way to speed up this nested loop? Or ca... | 0 | 2016-05-28T14:14:58Z | 37,500,092 | <p>You could try to convert <code>for</code> loops into <code>while</code> loops, should be faster as the latter does not create any iterators. So instead of:</p>
<pre><code>for a1 in xrange(15, 91):
</code></pre>
<p>write:</p>
<pre><code>a1 = 15
while a1 < 91:
...
a1 += 1
</code></pre>
<p>Or try to use ... | 0 | 2016-05-28T14:20:16Z | [
"python",
"for-loop"
] |
Python nested loop speed issues | 37,500,035 | <p>I am currently working on a program to test for ideal angle-values to construct something. Now I'm stuck at a nested-for-loop which I'm going to attach below. While idealy it would count each 'a' to 9000, it already takes almost forever if values are set like below. Is there a way to speed up this nested loop? Or ca... | 0 | 2016-05-28T14:14:58Z | 37,500,096 | <p>Solution: Use a different algorithm.</p>
<p>As it is now, you execute the innermost loop 999*(76**5) == 2,532,989,850,624 times. This is probably too many, unless the innermost loop calculations are trivial.</p>
<p>You say you want "to test for ideal angle-values to construct something." If you can formalize what ... | 0 | 2016-05-28T14:20:30Z | [
"python",
"for-loop"
] |
How to enable Windows console QuickEdit Mode from python? | 37,500,076 | <p>I'd like to force QuickEdit Mode in the console when running a python script and then disable it right before terminating. Is there a way to do that?</p>
| 0 | 2016-05-28T14:18:50Z | 37,505,496 | <p>You can use <a href="https://docs.python.org/3/library/ctypes.html" rel="nofollow">ctypes</a> to call <a href="https://msdn.microsoft.com/en-us/library/ms683167" rel="nofollow"><code>GetConsoleMode</code></a> and <a href="https://msdn.microsoft.com/en-us/library/ms686033" rel="nofollow"><code>SetConsoleMode</code></... | 0 | 2016-05-29T02:08:12Z | [
"python",
"windows",
"console",
"prompt"
] |
How to parse json text data with python | 37,500,363 | <p>I need to make a request to the api of my client, and the api returns this data:</p>
<pre><code>[6,0,'VT3zrYA',5,'USUeZWA',5,0,0,0,0,0,4,0,0,0,2,0,0,3,0,0,0,0,2,0,1,["portale.titolari.client.config.ShoulderDTO/4121330600","java.util.HashSet/3273092938","MATTEO SBRAGIA","java.util.ArrayList/4159755760","java.util.Da... | 0 | 2016-05-28T14:45:46Z | 37,500,730 | <p>This in fact is not a valid JSON string because it contains single quotes <code>'</code>. You can replace all single quotes with double quotes and then parse the string but it's a question whether this was intentional or a mistake:</p>
<pre><code>import json
s = '[6,0,\'VT3zrYA\',5,\'USUeZWA\',5,0,0,0,0,0,4,0,0,0,... | 2 | 2016-05-28T15:20:03Z | [
"python",
"json"
] |
peewee with bulk insert is very slow into sqlite db | 37,500,369 | <p>I'm trying to do a large scale bulk insert into a sqlite database with peewee. I'm using <code>atomic</code> but the performance is still terrible. I'm inserting the rows in blocks of ~ 2500 rows, and due to the <a href="http://stackoverflow.com/questions/35616602/peewee-operationalerror-too-many-sql-variables-on-up... | 1 | 2016-05-28T14:46:19Z | 37,501,775 | <p>In all of the documentation where code using <code>atomic</code> appears as a context manager, it's been used as a function. Since it sounds like you're never seeing your code <em>exit</em> the <code>with</code> block, you're probably not seeing an error about not having an <code>__exit__</code> method.</p>
<p>Can ... | -1 | 2016-05-28T17:14:30Z | [
"python",
"performance",
"sqlite",
"database-performance",
"peewee"
] |
peewee with bulk insert is very slow into sqlite db | 37,500,369 | <p>I'm trying to do a large scale bulk insert into a sqlite database with peewee. I'm using <code>atomic</code> but the performance is still terrible. I'm inserting the rows in blocks of ~ 2500 rows, and due to the <a href="http://stackoverflow.com/questions/35616602/peewee-operationalerror-too-many-sql-variables-on-up... | 1 | 2016-05-28T14:46:19Z | 37,803,830 | <p>Mobius was trying to be helpful in the comments but there's a lot of misinformation in there.</p>
<ul>
<li>Peewee creates indexes for foreign keys when you create the table. This happens for all database engines currently supported.</li>
<li>Turning on the foreign key PRAGMA is going to slow things down, why would ... | 2 | 2016-06-14T05:46:16Z | [
"python",
"performance",
"sqlite",
"database-performance",
"peewee"
] |
python - printing items inline in IPython | 37,500,383 | <p>I need to print everything inline dynamically in a for loop in an IPython notebook. I am using <strong>python 2.7</strong>. I used the code:</p>
<pre><code>for i in xrange(10):
print "." ,
#some computation and no print statement
</code></pre>
<p>and even used:</p>
<pre><code>for i in xrange(10):
print ... | 0 | 2016-05-28T14:48:09Z | 37,500,451 | <p>I may not understand your question but have you tried to use:</p>
<pre><code>print "."*10
</code></pre>
<p>You would get:</p>
<pre><code>..........
</code></pre>
| -2 | 2016-05-28T14:55:26Z | [
"python",
"ipython",
"jupyter-notebook"
] |
python - printing items inline in IPython | 37,500,383 | <p>I need to print everything inline dynamically in a for loop in an IPython notebook. I am using <strong>python 2.7</strong>. I used the code:</p>
<pre><code>for i in xrange(10):
print "." ,
#some computation and no print statement
</code></pre>
<p>and even used:</p>
<pre><code>for i in xrange(10):
print ... | 0 | 2016-05-28T14:48:09Z | 37,500,457 | <p>how about</p>
<pre><code>from __future__ import print_function
for i in xrange(10):
print(".", end=' ')
</code></pre>
| 0 | 2016-05-28T14:55:56Z | [
"python",
"ipython",
"jupyter-notebook"
] |
python - printing items inline in IPython | 37,500,383 | <p>I need to print everything inline dynamically in a for loop in an IPython notebook. I am using <strong>python 2.7</strong>. I used the code:</p>
<pre><code>for i in xrange(10):
print "." ,
#some computation and no print statement
</code></pre>
<p>and even used:</p>
<pre><code>for i in xrange(10):
print ... | 0 | 2016-05-28T14:48:09Z | 37,500,494 | <p>This will work on both Python 2 and Python 3:</p>
<pre class="lang-py prettyprint-override"><code>from __future__ import print_function
for i in range(10):
print('.', end='')
</code></pre>
<p>You can also pass <code>flush=True</code> keyword argument to force it to flush the buffer instantly.</p>
<p>You can ... | 4 | 2016-05-28T14:58:47Z | [
"python",
"ipython",
"jupyter-notebook"
] |
python - printing items inline in IPython | 37,500,383 | <p>I need to print everything inline dynamically in a for loop in an IPython notebook. I am using <strong>python 2.7</strong>. I used the code:</p>
<pre><code>for i in xrange(10):
print "." ,
#some computation and no print statement
</code></pre>
<p>and even used:</p>
<pre><code>for i in xrange(10):
print ... | 0 | 2016-05-28T14:48:09Z | 37,500,515 | <p>You can do exactly the same thing doing:</p>
<pre><code>print('.' * 10)
</code></pre>
<p>If you need a for loop you can assing the <em>end</em> variable to the print method like this:</p>
<pre><code>for i in range(10):
print('.', end="")
</code></pre>
| -1 | 2016-05-28T15:00:47Z | [
"python",
"ipython",
"jupyter-notebook"
] |
python - printing items inline in IPython | 37,500,383 | <p>I need to print everything inline dynamically in a for loop in an IPython notebook. I am using <strong>python 2.7</strong>. I used the code:</p>
<pre><code>for i in xrange(10):
print "." ,
#some computation and no print statement
</code></pre>
<p>and even used:</p>
<pre><code>for i in xrange(10):
print ... | 0 | 2016-05-28T14:48:09Z | 37,500,724 | <p>You can do it using <code>sys</code> module.</p>
<pre><code>import sys
for i in xrange(10):
sys.stdout.write(".")
</code></pre>
<p>The <code>print</code> function is a wrapper which converts the object to <code>string</code> and formats the output.</p>
| 0 | 2016-05-28T15:19:22Z | [
"python",
"ipython",
"jupyter-notebook"
] |
How to convert "01 January 2016" to UTC ISO format? | 37,500,384 | <p>So I have the following string : " 01 January 2016" to UTC ISO date format ?</p>
<p>I'm using arrow module and the following code, but it's full of errors, and I was thinking that may be, there was a smaller more elegent solution as python encourages elegant and easier ways to do things, anyways here's my code : </... | 2 | 2016-05-28T14:48:12Z | 37,500,445 | <p>You can use <a href="https://docs.python.org/2/library/datetime.html" rel="nofollow"><code>datetime</code></a>'s methods to parse this date string and then reformat it to UTC format:</p>
<pre><code>>>> from datetime import datetime
>>> updateStr = " 01 January 2016" #Note the space at the beginnin... | 0 | 2016-05-28T14:55:06Z | [
"python",
"datetime",
"utc"
] |
How to convert "01 January 2016" to UTC ISO format? | 37,500,384 | <p>So I have the following string : " 01 January 2016" to UTC ISO date format ?</p>
<p>I'm using arrow module and the following code, but it's full of errors, and I was thinking that may be, there was a smaller more elegent solution as python encourages elegant and easier ways to do things, anyways here's my code : </... | 2 | 2016-05-28T14:48:12Z | 37,500,490 | <p>You can use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime" rel="nofollow">datetime</a>:</p>
<pre><code>>>> updateStr = " 01 January 2016"
>>> import datetime as dt
>>> dt.datetime.strptime(updateStr, " %d %B %Y")
datetime.datetime(2016, 1, 1, 0, 0)
&g... | 2 | 2016-05-28T14:58:24Z | [
"python",
"datetime",
"utc"
] |
How to convert "01 January 2016" to UTC ISO format? | 37,500,384 | <p>So I have the following string : " 01 January 2016" to UTC ISO date format ?</p>
<p>I'm using arrow module and the following code, but it's full of errors, and I was thinking that may be, there was a smaller more elegent solution as python encourages elegant and easier ways to do things, anyways here's my code : </... | 2 | 2016-05-28T14:48:12Z | 37,500,717 | <p>Using <a href="https://arrow.readthedocs.io/en/latest/" rel="nofollow">arrow</a>:</p>
<pre><code>>>> import arrow
>>> updateStr = " 01 January 2016"
>>> arrow.get(updateStr, "DD MMMM YYYY").isoformat()
'2016-01-01T00:00:00+00:00'
>>>
</code></pre>
| 1 | 2016-05-28T15:18:29Z | [
"python",
"datetime",
"utc"
] |
Python 2 to 3 conversion: iterating over lines in subprocess stdout | 37,500,410 | <p>I have the following Python 2 example code that I want to make compatible with Python 3:</p>
<pre><code>call = 'for i in {1..5}; do sleep 1; echo "Hello $i"; done'
p = subprocess.Popen(call, stdout=subprocess.PIPE, shell=True)
for line in iter(p.stdout.readline, ''):
print(line, end='')
</code></pre>
<p>This w... | 2 | 2016-05-28T14:51:40Z | 37,501,096 | <p>You can use <code>p.communicate()</code> and then decode it if it is a <code>bytes</code> object:</p>
<pre><code>from __future__ import print_function
import subprocess
def b(t):
if isinstance(t, bytes):
return t.decode("utf8")
return t
call = 'for i in {1..5}; do sleep 1; echo "Hello $i"; done'
p... | 0 | 2016-05-28T15:57:09Z | [
"python",
"python-3.x",
"subprocess"
] |
Python 2 to 3 conversion: iterating over lines in subprocess stdout | 37,500,410 | <p>I have the following Python 2 example code that I want to make compatible with Python 3:</p>
<pre><code>call = 'for i in {1..5}; do sleep 1; echo "Hello $i"; done'
p = subprocess.Popen(call, stdout=subprocess.PIPE, shell=True)
for line in iter(p.stdout.readline, ''):
print(line, end='')
</code></pre>
<p>This w... | 2 | 2016-05-28T14:51:40Z | 37,501,756 | <p>You can add <code>unversal_newlines=True</code>.</p>
<pre><code>p = subprocess.Popen(call, stdout=subprocess.PIPE, shell=True, universal_newlines=True)
for line in iter(p.stdout.readline, ''):
print(line, end='')
</code></pre>
<p>Instead of <code>bytes</code>, <code>str</code> will be returned so <code>''</cod... | 2 | 2016-05-28T17:12:18Z | [
"python",
"python-3.x",
"subprocess"
] |
Python - Get Path of Selected File in Current Windows Explorer | 37,500,504 | <p>I am trying to do <a href="http://stackoverflow.com/questions/2701298/assigning-keyboard-shortcut-to-get-path-of-selected-item-in-windows-explorer">this</a> in Python 2.7. I have found an answer for it in C# <a href="http://stackoverflow.com/questions/14193388/how-to-get-windows-explorers-selected-files-from-within-... | 0 | 2016-05-28T14:59:38Z | 37,531,774 | <p>Sorry but what you are trying to achieve does not make much sense because you can have multiple Explorer Windows with files selected in them, multiple displays and even multiple terminal Sessions running on the same machine.</p>
| 0 | 2016-05-30T18:28:54Z | [
"python",
"python-2.7",
"operating-system",
"pywin32"
] |
Nested recursive function in python | 37,500,514 | <p>I tried to implement a nested recursive function in python it is giving an error "RuntimeError: maximum recursion depth exceeded" you can see the function in the following code. your help regarding the question is appreciated. </p>
<pre><code>n=10
def test(n):
if n<=0:
return 1
else:
ret... | 0 | 2016-05-28T15:00:35Z | 37,500,644 | <p>One very important part of recursion is that with every recursive call you have to get <strong>closer</strong> to your anchor case, which in this case is:</p>
<pre><code>if n<=0:
return 1
</code></pre>
<p>However, with your code you are not getting close to this case. The problem is this line:</p>
<pre><co... | 6 | 2016-05-28T15:11:56Z | [
"python",
"python-3.x",
"recursion"
] |
Accessing values of a dictionary in a list using lambda | 37,500,623 | <p>I'm a newbie to python. I've multiple dictionaries inside a list and I want to do some analysis based on values. The reason I'm using lambda is because the function is not always expected. I'm just showing 2 dictionaries for reference, but the output gives me multiple dictionaries at times.</p>
<pre><code>statistic... | 0 | 2016-05-28T15:08:59Z | 37,500,679 | <p>You don't need <code>[0]</code>. </p>
<p>When using <code>filter(lambda x: ...)</code>, <code>x</code> is the element in the iterable.
Since you have a list of dictionaries, <code>x</code> will be the dictionary itself.</p>
<p>Your code should be:</p>
<pre><code>statistics = [{"ip_dst": "10.0.0.1", "ip_proto": "... | 1 | 2016-05-28T15:15:49Z | [
"python",
"list",
"dictionary",
"lambda"
] |
Accessing values of a dictionary in a list using lambda | 37,500,623 | <p>I'm a newbie to python. I've multiple dictionaries inside a list and I want to do some analysis based on values. The reason I'm using lambda is because the function is not always expected. I'm just showing 2 dictionaries for reference, but the output gives me multiple dictionaries at times.</p>
<pre><code>statistic... | 0 | 2016-05-28T15:08:59Z | 37,500,702 | <p>If you are trying to extract the packets as a separate list of items then you wouldn't use filter. Filter will just reduce the number of dictionaries in a new list. You could use a list comprehension,</p>
<pre><code>packets = [x['packets'] for x in statistics]
print(packets)
# [30, 34]
</code></pre>
<p>This create... | 1 | 2016-05-28T15:17:17Z | [
"python",
"list",
"dictionary",
"lambda"
] |
Accessing values of a dictionary in a list using lambda | 37,500,623 | <p>I'm a newbie to python. I've multiple dictionaries inside a list and I want to do some analysis based on values. The reason I'm using lambda is because the function is not always expected. I'm just showing 2 dictionaries for reference, but the output gives me multiple dictionaries at times.</p>
<pre><code>statistic... | 0 | 2016-05-28T15:08:59Z | 37,500,733 | <p>The filter function returns the original list without the elements where the lambda evaluates to false. So, if you did that correctly, you'd get all the elements anyways because a non-empty string or value other than 0 is considered to be True in Python. </p>
<p>If you'd like to get just those values of the keys, y... | 0 | 2016-05-28T15:20:12Z | [
"python",
"list",
"dictionary",
"lambda"
] |
NQueens Slver in python | 37,500,792 | <p>I am making a nQueen Problem Solver but every time I run the program it launch this error: </p>
<p>"tuple" has no attribute "row"</p>
<p>I want to know if the function place is well structure because is the one that throw the error </p>
<pre><code>import sys #use of argv
#Create the object queen with the row and... | 0 | 2016-05-28T15:25:17Z | 37,502,111 | <pre><code>Queenaux = (row,i)
Board.append(Queenaux)
</code></pre>
<p>Because of these lines, <code>Board</code> contains tuples. You must fix it by making <code>Queenaux</code> a <code>Queen</code> instance, like so:</p>
<pre><code>Queenaux = Queen(row,i)
</code></pre>
<p>Also note that <code>NQueens</code> doesn't... | 0 | 2016-05-28T17:48:09Z | [
"python",
"backtracking"
] |
Convert 3d Numpy array to 2d | 37,500,804 | <p>I have a 3d numpy array of following form:</p>
<pre><code>array([[[ 1., 5., 4.],
[ 1., 5., 4.],
[ 1., 2., 4.]],
[[ 3., 6., 4.],
[ 6., 6., 4.],
[ 6., 6., 4.]]])
</code></pre>
<p>Is there a efficient way to convert it to a 2d array of form:</p>
<pre><code>array([[1, 1, 1, 5, 5, 2, 4,... | 1 | 2016-05-28T15:26:55Z | 37,500,847 | <pre><code>In [54]: arr = np.array([[[ 1., 5., 4.],
[ 1., 5., 4.],
[ 1., 2., 4.]],
[[ 3., 6., 4.],
[ 6., 6., 4.],
[ 6., 6., 4.]]])
In [61]: arr.reshape((arr.shape[0], -1), order='F')... | 7 | 2016-05-28T15:31:23Z | [
"python",
"numpy"
] |
Attribute system similar to HTTP Headers for local files | 37,500,810 | <p>I am in the process of writing a program and need some guidance. Essentially, I am trying to determine if a file has some marker or flag attached to it. Sort of like the attributes for a HTTP Header. </p>
<p>If such a marker exists, that file will be manipulated in some way (moved to another directory).</p>
<p>My ... | 0 | 2016-05-28T15:27:13Z | 37,501,333 | <p>If you are dealing with binary files like docx and pdf, you're best off storing the metadata in seperate files or in a sqlite file.</p>
<p>Metadata is usually stored seperate from files, in data structures called inodes (at least in Unix systems, Windows probably has something similar). But you probably don't want ... | 1 | 2016-05-28T16:24:20Z | [
"python",
"file-io",
"go",
"attributes",
"metadata"
] |
Attribute system similar to HTTP Headers for local files | 37,500,810 | <p>I am in the process of writing a program and need some guidance. Essentially, I am trying to determine if a file has some marker or flag attached to it. Sort of like the attributes for a HTTP Header. </p>
<p>If such a marker exists, that file will be manipulated in some way (moved to another directory).</p>
<p>My ... | 0 | 2016-05-28T15:27:13Z | 37,502,101 | <p>Metadata you wish to add is best kept in a separate file or database for all files.</p>
<p>Or in another file with same name and different extension or prefix, that you can make hidden.</p>
<p>Relying on a file system is very tricky and your data will be bound by the restrictions and capabilities of the file syste... | 2 | 2016-05-28T17:47:25Z | [
"python",
"file-io",
"go",
"attributes",
"metadata"
] |
Converting DOS text files to Unicode using Python | 37,500,872 | <p>I am trying to write a Python application for converting old DOS code page text files to their Unicode equivalent. Now, I have done this before using Turbo Pascal by creating a look-up table and I'm sure the same can be done using a Python dictionary. My question is: <em>How do I index into the dictionary to find th... | -1 | 2016-05-28T15:34:21Z | 37,502,334 | <p>You can use standard buildin <code>decode</code> method of <code>bytes</code> objects:</p>
<pre><code>with open('dos.txt', 'r', encoding='cp437') as infile, \
open('unicode.txt', 'w', encoding='utf8') as outfile:
for line in infile:
outfile.write(line)
</code></pre>
| 0 | 2016-05-28T18:11:55Z | [
"python",
"text",
"unicode",
"codepages"
] |
Converting DOS text files to Unicode using Python | 37,500,872 | <p>I am trying to write a Python application for converting old DOS code page text files to their Unicode equivalent. Now, I have done this before using Turbo Pascal by creating a look-up table and I'm sure the same can be done using a Python dictionary. My question is: <em>How do I index into the dictionary to find th... | -1 | 2016-05-28T15:34:21Z | 37,505,229 | <p>Python has the codecs to do the conversions:</p>
<pre><code>#!python3
# Test file with bytes 0-255.
with open('dos.txt','wb') as f:
f.write(bytes(range(256)))
# Read the file and decode using code page 437 (DOS OEM-US).
# Write the file as UTF-8 encoding ("Unicode" is not an encoding)
# UTF-8, UTF-16, UTF-32 ... | 1 | 2016-05-29T01:12:19Z | [
"python",
"text",
"unicode",
"codepages"
] |
NameError: name 'addTimeInterval' not defined | 37,500,913 | <p>I'm trying to run a code on Hull-White one factor model and at this point in time: </p>
<pre><code>today = datetime.date(2014,10,24)
spot_rate = 0.02
fardate = today + addTimeInterval(10.0, 'y')
</code></pre>
<p>I get this error message:</p>
<pre><code>NameError ... | -3 | 2016-05-28T15:40:48Z | 37,501,074 | <p>Remember to share a full-working example. In your code, you had at least to import the datetime function. </p>
<p>Your code tells you that there is a NameError: </p>
<pre><code>NameError: name 'addTimeInterval' is not defined
</code></pre>
<p>The object <code>addTimeInterval</code> which seems not to be a functio... | 0 | 2016-05-28T15:55:07Z | [
"python",
"ipython",
"jupyter"
] |
Controlling a relay with a momentary button in Python | 37,500,915 | <p>I was able to control the relay with a momentary button with the code below:</p>
<pre><code>#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(4, GPIO.OUT)
GPIO.output(4, GPIO.HIGH)
def callback_func(pin):
if GPIO.input(17):
... | 0 | 2016-05-28T15:40:56Z | 37,507,958 | <p>Removing the bouncetime completly fixed the issue. So:</p>
<pre><code>GPIO.add_event_detect(17, GPIO.BOTH, callback=callback_func, bouncetime=200)
</code></pre>
<p>to</p>
<pre><code>GPIO.add_event_detect(17, GPIO.BOTH, callback=callback_func)
</code></pre>
| 1 | 2016-05-29T08:52:24Z | [
"python",
"gpio"
] |
PyBluez pairing bluetooth device | 37,500,992 | <p>How do I initiate pairing of a bluetooth device with PyBluez in Python? I see ways to discover, but not pair.</p>
| 0 | 2016-05-28T15:46:54Z | 39,666,806 | <p>PyBluez does not support cross-platform pairing management. This is because some operating systems, like Windows, require super-user level permissions to programatically pair devices.</p>
<p>On most operating systems, when PyBluez attempts to connect to the socket using the connect method, the operating system will... | 0 | 2016-09-23T17:54:13Z | [
"python",
"bluetooth",
"pybluez"
] |
Stop retrying periodic celery task on error | 37,501,055 | <p>Imagine a task in <code>celery schedule</code>, that runs each minute and <strong>sends email</strong> on errors. If there is an error, it's more often persistent, like database unavailability, so mail box get's spammed with similar emails. </p>
<p>What's the possible workarounds?</p>
| 1 | 2016-05-28T15:53:21Z | 37,501,197 | <p>You could use a flag so the program knows whether it has already sent an alarm email, which gets set back to False once the database comes back online</p>
<p>The code is just an example of the concept.. it's unrelated to Celery, however I'm sure you can work it to fit your needs</p>
<pre><code>database_flag = Fals... | 1 | 2016-05-28T16:09:46Z | [
"python",
"django",
"celery",
"celerybeat"
] |
How to get parameter arguments from a frozen spicy.stats distribution? | 37,501,075 | <h1>Frozen Distribution</h1>
<p>In <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#statistics-scipy-stats" rel="nofollow"><code>scipy.stats</code></a> you can create a <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/stats.html#freezing-a-distribution" rel="nofollow"><em>frozen</em> d... | 4 | 2016-05-28T15:55:08Z | 37,501,076 | <h1>Accessing <code>rv</code> frozen parameters</h1>
<p>Yes, the parameters used to create a frozen distribution are available within the instance of the distribution. They are stored within the <a href="https://github.com/scipy/scipy/blob/v0.17.0/scipy/stats/_distn_infrastructure.py#L423-L428" rel="nofollow"><code>ar... | 2 | 2016-05-28T15:55:08Z | [
"python",
"random",
"parameters",
"scipy",
"distribution"
] |
How to read some contents of xml files and write them into a text file? | 37,501,150 | <p>I have a following xml file, I want to read the contents in <code><seg></code> and save them into a plain text file with Python. And I used the DOM module.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true">
<div class="snippet-code">
<pre class="snippet-code-html lang-html pre... | 1 | 2016-05-28T16:04:24Z | 37,501,268 | <p>You're only calling <code>file.write(sent)</code> once, open the file before the loop, and then add the following line to this code:</p>
<pre><code>file = open(r'file.txt','w')
for item in seg:
sent = item.firstChild.data
print(sent,sep='')
file.write(sent) // <---- this line
file.close()
</code></... | 2 | 2016-05-28T16:17:13Z | [
"python",
"xml",
"text"
] |
Execute a file in temp (tempfile) | 37,501,186 | <p>I'm trying to write a python script which creates a temporary file (another python script) in the Temp folder. Then it should proceed to execute this temp file.</p>
<p>I wrote something like this:</p>
<pre><code> with tempfile.TemporaryFile(mode='w+b', suffix='.py') as temp:
stuff stuff stuff
temp.write(my... | 0 | 2016-05-28T16:08:23Z | 37,501,286 | <p>The line <code>os.system(temp.name)</code> should be outside of <code>with</code> closure.</p>
<p>Doing that however doesn't work here since the file will be removed by then, therefore you need to have the parameter <code>delete=False</code> passed to <code>TemporaryFile()</code>.</p>
<p>Preferably consider using ... | 1 | 2016-05-28T16:19:20Z | [
"python"
] |
How to get Windows window names with ctypes in python | 37,501,191 | <p>I try to get Windows window title names and pids through handles with long objects. My code works but there is something wrong with it. I get only 4 window titles when I should get 10 or more. Can anyone help and tell me how to fix this code? I think the problem is with how I convert long objects (I don't understand... | 0 | 2016-05-28T16:08:59Z | 37,503,441 | <p>You're passing a process ID to functions that take a window handle. What you want to do is enumerate handles for the top-level windows and then map each window to a process ID.</p>
<p>First lets define the ctypes function prototypes to get proper type checking on function arguments. Also, use <code>use_last_error=T... | 1 | 2016-05-28T20:23:09Z | [
"python",
"windows",
"ctypes",
"long-integer",
"psapi"
] |
Scipy Sparse Matrix built with non-int64 (indptr, indices) for dot | 37,501,227 | <p>Is it ok to use uint32 type for indptr and indices when I manually construct a scipy.sparse.csr_matrix? Will the dot method of the matrix return the correct answer?</p>
<p>The following example seems to be ok... Not sure if that is officially ok.</p>
<pre><code>import numpy as np
import scipy.sparse as spsp
x = np... | 1 | 2016-05-28T16:14:21Z | 37,501,922 | <p>I'm not sure what you goal is. What you are doing works (sort of)</p>
<pre><code>In [237]: X=x_csr.dot(x_csr.T)
In [238]: np.allclose(X.A,x.dot(x.T))
Out[238]: True
</code></pre>
<p>That is, the multiplication with the modified <code>x_csr</code> works.</p>
<p>But note that any manipulation of <code>x_csr</code... | 2 | 2016-05-28T17:30:40Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] |
Indentation preserving formatting of multiline strings | 37,501,228 | <p>I generate bits of (C++) code using format strings such as</p>
<pre><code>memfn_declaration = '''\
{doc}
{static}auto {fun}({formals}){const}
-> {result};
'''
</code></pre>
<p>Format strings are nice for this, but is there a way to make them keep the indentation level for <code>{doc}</code> here? It's ... | 0 | 2016-05-28T16:14:28Z | 37,501,507 | <p>Now that you've posted your own answer and clarified at little more about what you want. I think it would be slightly better to implement it by defining your own <code>str</code> subclass that extends the way strings can be formatted by supporting a new conversion type, <code>'i'</code>, which must be followed by a ... | 1 | 2016-05-28T16:44:42Z | [
"python",
"format",
"string-formatting"
] |
Indentation preserving formatting of multiline strings | 37,501,228 | <p>I generate bits of (C++) code using format strings such as</p>
<pre><code>memfn_declaration = '''\
{doc}
{static}auto {fun}({formals}){const}
-> {result};
'''
</code></pre>
<p>Format strings are nice for this, but is there a way to make them keep the indentation level for <code>{doc}</code> here? It's ... | 0 | 2016-05-28T16:14:28Z | 37,505,584 | <p>The issue is this:</p>
<pre><code>'''\
</code></pre>
<p>The backslash will ignore all whitespaces up to the next character. Remove the backslash.</p>
| 0 | 2016-05-29T02:27:37Z | [
"python",
"format",
"string-formatting"
] |
Indentation preserving formatting of multiline strings | 37,501,228 | <p>I generate bits of (C++) code using format strings such as</p>
<pre><code>memfn_declaration = '''\
{doc}
{static}auto {fun}({formals}){const}
-> {result};
'''
</code></pre>
<p>Format strings are nice for this, but is there a way to make them keep the indentation level for <code>{doc}</code> here? It's ... | 0 | 2016-05-28T16:14:28Z | 37,523,118 | <p>I'm looking for something which is light-weight on the caller site. I can live with the following compromise: I use the fact that format strings are allowed to query for attributes (<code>0.foo</code>) or items (<code>0['foo']</code>) to pass the indentation level in the format string.</p>
<pre><code>import textwr... | 0 | 2016-05-30T10:15:04Z | [
"python",
"format",
"string-formatting"
] |
Why simple import of module in same directory is not allowed | 37,501,590 | <p>I've created two modules in the same directory:</p>
<pre><code>.
âââ mod1.py
âââ mod2.py
</code></pre>
<p>There is no <code>__init__.py</code>, I don't want to create this as a package, I'm just creating a simple script which I have modularized by breaking into different modules.</p>
<p>My intention i... | 0 | 2016-05-28T16:53:08Z | 37,501,814 | <p>You shouldn't use relative, but absolute import:</p>
<pre><code>import mod2
print(mod2.some_expr)
</code></pre>
<p>The <a href="https://docs.python.org/3/reference/import.html" rel="nofollow">documentation</a> is pretty good, and this <a href="http://stackoverflow.com/a/2349998/3077939">SO answers</a> gives an alt... | 1 | 2016-05-28T17:18:12Z | [
"python"
] |
trouble querying an SQL database held on a Flask app - returning "None" in Flask when it returns data when I interact with the database | 37,501,615 | <p>I'm working in a Flask app, and I'm trying to set it up to create dynamic webpages based on the data in the SQL database. For example, if we scrape data about a certain criminal, I want Flask to route my requests such that I can type:</p>
<p>myflaskapp.com/criminal/[criminal's name]/</p>
<p>and be taken to a page... | 0 | 2016-05-28T16:55:01Z | 37,501,956 | <p>Your routing seems to be wrong?</p>
<p>This is not the same </p>
<pre><code>myflaskapp.com/[criminal's name]/
</code></pre>
<p>as </p>
<pre><code>@app.route('/criminal/<first_name>')
</code></pre>
<p>Try </p>
<pre><code>myflaskapp.com/criminal/[criminal's name]/
</code></pre>
| 1 | 2016-05-28T17:34:35Z | [
"python",
"sql",
"flask",
"flask-sqlalchemy"
] |
Is it possible to make wrapper object for numbers, e.g. float, to make it mutable? | 37,501,632 | <p>In Python 3 everything is supposed to be an object, even numbers, but they're <strong>immutable</strong>.</p>
<p><strong>Is it possible to create wrapper object for numbers, e.g. float, such that it would behave exactly as ordinary numbers except it must be mutable?</strong></p>
<p>I've wondered whether it would b... | 3 | 2016-05-28T16:56:35Z | 37,501,960 | <p>Values are immutable. They're platonic forms. An expression like <code>5 := 3</code> is nonsensical. What are mutable are <code>locations</code>, usually referred to as addresses or pointers. Python doesn't have those, but we can fake it by using a container type like a <code>list</code>, which is really a location ... | 3 | 2016-05-28T17:34:58Z | [
"python",
"python-3.x",
"immutability",
"mutable",
"shallow-copy"
] |
Linux -OpenWrt- (Unwired One) python wlan interface scan error | 37,501,646 | <p>The thing I am trying to achive, I want my android app to get a list of all available wlan connections within the range of a device with a wlan (at that point the device is an access point). Then I want to tell that device to which network to connect. So far so good.</p>
<p>I am trying to access the wlan module on ... | 0 | 2016-05-28T16:58:13Z | 37,604,632 | <p>Just as an info, i solved my issue by changing the module I have been using. Now I am using [1]. When I execute this code </p>
<pre><code>from wifi import Cell, Scheme
print "%s" %(Cell.all('wlan0'))
</code></pre>
<p>I get a list with all surrounding networks. Then I have just to choose one of them (by the SSID) a... | 0 | 2016-06-03T01:38:25Z | [
"python",
"linux",
"wifi",
"openwrt",
"iwconfig"
] |
Python map a value to each i-th sublist's element | 37,501,651 | <p>I'm trying to do the following in python: given a list of lists and an integer i</p>
<pre><code>input = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]]
i = 1
</code></pre>
<p>I need to obtain another list which has all 1s for the elements of the i-th list, 0 otherwise</p>
<pre><code>output = [0, 0, 0, 0, 1, 1, 1, 1, 0... | 4 | 2016-05-28T16:58:46Z | 37,501,731 | <p>Creating extra variable to get index of current element in interation is quite unpythonic. Usual alternative is usage of <a href="https://docs.python.org/2/library/functions.html#enumerate" rel="nofollow"><code>enumerate</code></a> built-in function.</p>
<blockquote>
<p>Return an enumerate object. sequence must b... | 4 | 2016-05-28T17:09:40Z | [
"python"
] |
Python map a value to each i-th sublist's element | 37,501,651 | <p>I'm trying to do the following in python: given a list of lists and an integer i</p>
<pre><code>input = [[1, 2, 3, 4], [1, 2, 3, 4], [5, 6, 7, 8]]
i = 1
</code></pre>
<p>I need to obtain another list which has all 1s for the elements of the i-th list, 0 otherwise</p>
<pre><code>output = [0, 0, 0, 0, 1, 1, 1, 1, 0... | 4 | 2016-05-28T16:58:46Z | 37,501,738 | <p>Here's a 1-liner, but it's not really obvious:</p>
<pre><code>output = [int(j == i) for j, sublist in enumerate(input) for _ in sublist]
</code></pre>
<p>Somewhat more obvious:</p>
<pre><code>output = []
for j, sublist in enumerate(input):
output.extend([int(i == j)] * len(sublist))
</code></pre>
<p>Then "0 ... | 3 | 2016-05-28T17:10:21Z | [
"python"
] |
JSON dump breaks my dictionary when using certain characters | 37,501,683 | <p>Dumping data into a file with json.dump.
The data looks like this:</p>
<pre><code>{"hello": {"this": 1, "a": 1, "is": 1, "test": 1}}
</code></pre>
<p>The code I use to achieve this is as follows (worddict is a file, something like file.json):</p>
<pre><code>with open(words, 'w') as fp:
json.dump(worddict, fp)... | 0 | 2016-05-28T17:04:22Z | 37,501,749 | <p>Replace</p>
<pre><code> json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '))
</code></pre>
<p>with</p>
<pre><code> json.dump(worddict, fp, sort_keys=True, indent=4, separators=(',', ': '), ensure_ascii=False)
</code></pre>
| 0 | 2016-05-28T17:11:08Z | [
"python",
"json",
"character",
"dump"
] |
JSON dump breaks my dictionary when using certain characters | 37,501,683 | <p>Dumping data into a file with json.dump.
The data looks like this:</p>
<pre><code>{"hello": {"this": 1, "a": 1, "is": 1, "test": 1}}
</code></pre>
<p>The code I use to achieve this is as follows (worddict is a file, something like file.json):</p>
<pre><code>with open(words, 'w') as fp:
json.dump(worddict, fp)... | 0 | 2016-05-28T17:04:22Z | 37,502,187 | <p>I ran your code snippet in both python2 and python3.
In python3, it gave me no errors.</p>
<p>I ran the following code:</p>
<pre><code>import json
words = 'a.txt'
worddict = {"hello": {"this": 1, "a": 1, "is": 1, "test": "Ã"}}
with open(words, 'w') as fp:
json.dump(worddict, fp, sort_keys=True, indent=4, sep... | 0 | 2016-05-28T17:55:50Z | [
"python",
"json",
"character",
"dump"
] |
Edit a piece of data inside a csv | 37,501,752 | <p>I have a csv file looking like this</p>
<pre><code>34512340,1
12395675,30
56756777,30
90673412,45
12568673,25
22593672,25
</code></pre>
<p>I want to be able to edit the data after the comma from python and then save the csv.</p>
<p>Does anybody know how I would be able to do this?
This bit of code below will writ... | 0 | 2016-05-28T17:11:16Z | 37,501,811 | <p>You can use python <code>pandas</code> to edit the column you want for e.g increase the column number by <code>n</code>:</p>
<pre><code>import pandas
data_df = pandas.read_csv('input.csv')
data_df = data_df['column2'].apply(lambda x: x+n)
print data_df
</code></pre>
<p>for adding <code>1</code> replace <code>n</co... | 0 | 2016-05-28T17:17:46Z | [
"python",
"csv"
] |
Edit a piece of data inside a csv | 37,501,752 | <p>I have a csv file looking like this</p>
<pre><code>34512340,1
12395675,30
56756777,30
90673412,45
12568673,25
22593672,25
</code></pre>
<p>I want to be able to edit the data after the comma from python and then save the csv.</p>
<p>Does anybody know how I would be able to do this?
This bit of code below will writ... | 0 | 2016-05-28T17:11:16Z | 37,501,861 | <p>Here is a sample, which adds 1 to the second column:</p>
<pre><code>import csv
with open('data.csv') as infile, open('output.csv', 'wb') as outfile:
reader = csv.reader(infile)
writer = csv.writer(outfile)
for row in reader:
# Transform the second column, which is row[1]
row[1] = int(ro... | 1 | 2016-05-28T17:22:51Z | [
"python",
"csv"
] |
can't sum my list because of commas | 37,501,808 | <p>I have a list of numbers input by the user. The list is of random length depending on how many elements the user inputs.
python sees the list (e.g) like this:
the numbers you entered are: </p>
<pre><code>['6', '7', '8', '4', '5', '98', '34', '56']
</code></pre>
<p>They are on a list called <code>numlist</code>.</... | 0 | 2016-05-28T17:17:39Z | 37,501,833 | <p>I suspect you're trying to add together a list of strings, you have to convert those strings to integers first before calling <code>sum</code>; try doing this:</p>
<pre class="lang-py prettyprint-override"><code>print(sum(int(item) for item in numlist))
</code></pre>
| 2 | 2016-05-28T17:19:54Z | [
"python",
"list",
"sum"
] |
can't sum my list because of commas | 37,501,808 | <p>I have a list of numbers input by the user. The list is of random length depending on how many elements the user inputs.
python sees the list (e.g) like this:
the numbers you entered are: </p>
<pre><code>['6', '7', '8', '4', '5', '98', '34', '56']
</code></pre>
<p>They are on a list called <code>numlist</code>.</... | 0 | 2016-05-28T17:17:39Z | 37,501,848 | <pre><code>numlist =[1,2,3,4,5]
sum=0
for element in numlist:
sum+=element
print sum
</code></pre>
| 0 | 2016-05-28T17:21:47Z | [
"python",
"list",
"sum"
] |
can't sum my list because of commas | 37,501,808 | <p>I have a list of numbers input by the user. The list is of random length depending on how many elements the user inputs.
python sees the list (e.g) like this:
the numbers you entered are: </p>
<pre><code>['6', '7', '8', '4', '5', '98', '34', '56']
</code></pre>
<p>They are on a list called <code>numlist</code>.</... | 0 | 2016-05-28T17:17:39Z | 37,501,860 | <p>You are trying to add up string elements of list. If you want sum of list elements. For e.g. if you have a list</p>
<pre><code>a = ['1','2']
</code></pre>
<p>1) Convert list elements of <code>a</code> to <code>int</code> and assign to list <code>b</code></p>
<pre><code> b= [int(i) for i in a ]
</code></pre>
<p>... | 3 | 2016-05-28T17:22:49Z | [
"python",
"list",
"sum"
] |
can't sum my list because of commas | 37,501,808 | <p>I have a list of numbers input by the user. The list is of random length depending on how many elements the user inputs.
python sees the list (e.g) like this:
the numbers you entered are: </p>
<pre><code>['6', '7', '8', '4', '5', '98', '34', '56']
</code></pre>
<p>They are on a list called <code>numlist</code>.</... | 0 | 2016-05-28T17:17:39Z | 37,502,615 | <p>The single quotes indeed make your list a list of strings. You need to turn the strings into numbers. For completeness sake:</p>
<pre><code>sum(map(int, numlist))
sum(map(float, numlist))
</code></pre>
| 0 | 2016-05-28T18:41:15Z | [
"python",
"list",
"sum"
] |
can't sum my list because of commas | 37,501,808 | <p>I have a list of numbers input by the user. The list is of random length depending on how many elements the user inputs.
python sees the list (e.g) like this:
the numbers you entered are: </p>
<pre><code>['6', '7', '8', '4', '5', '98', '34', '56']
</code></pre>
<p>They are on a list called <code>numlist</code>.</... | 0 | 2016-05-28T17:17:39Z | 37,502,617 | <p>That's the easiest and most efficient:</p>
<pre><code>print(sum(map(int, numlist)))
</code></pre>
| 0 | 2016-05-28T18:41:18Z | [
"python",
"list",
"sum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.