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
Why is statistics.mean() so slow?
37,533,666
<p>I compared the performance of the <code>mean</code> function of the <code>statistics</code> module with the simple <code>sum(l)/len(l)</code> method and found the <code>mean</code> function to be very slow for some reason. I used <code>timeit</code> with the two code snippets below to compare them, does anyone know ...
42
2016-05-30T21:05:05Z
37,533,735
<p>I asked the same question a while back but once I noticed the <code>_sum</code> function called in mean on line <a href="https://github.com/python/cpython/blob/master/Lib/statistics.py#L317" rel="nofollow">317</a> in the source I understood why:</p> <pre><code>def _sum(data, start=0): """_sum(data [, start]) -&...
4
2016-05-30T21:14:20Z
[ "python", "performance", "mean" ]
Why is statistics.mean() so slow?
37,533,666
<p>I compared the performance of the <code>mean</code> function of the <code>statistics</code> module with the simple <code>sum(l)/len(l)</code> method and found the <code>mean</code> function to be very slow for some reason. I used <code>timeit</code> with the two code snippets below to compare them, does anyone know ...
42
2016-05-30T21:05:05Z
37,533,799
<p>Python's <code>statistics</code> module is not built for speed, but for precision</p> <p>In <a href="https://www.python.org/dev/peps/pep-0450/">the specs for this module</a>, it appears that</p> <blockquote> <p>The built-in sum can lose accuracy when dealing with floats of wildly differing magnitude. Conseque...
65
2016-05-30T21:22:30Z
[ "python", "performance", "mean" ]
Why is statistics.mean() so slow?
37,533,666
<p>I compared the performance of the <code>mean</code> function of the <code>statistics</code> module with the simple <code>sum(l)/len(l)</code> method and found the <code>mean</code> function to be very slow for some reason. I used <code>timeit</code> with the two code snippets below to compare them, does anyone know ...
42
2016-05-30T21:05:05Z
37,533,841
<p>if you do care of speed use numpy/scipy/pandas instead:</p> <pre><code>In [119]: from random import randint; from statistics import mean; import numpy as np; In [122]: l=[randint(0, 10000) for i in range(10**6)] In [123]: mean(l) Out[123]: 5001.992355 In [124]: %timeit mean(l) 1 loop, best of 3: 2.01 s per loop ...
6
2016-05-30T21:27:58Z
[ "python", "performance", "mean" ]
Why is statistics.mean() so slow?
37,533,666
<p>I compared the performance of the <code>mean</code> function of the <code>statistics</code> module with the simple <code>sum(l)/len(l)</code> method and found the <code>mean</code> function to be very slow for some reason. I used <code>timeit</code> with the two code snippets below to compare them, does anyone know ...
42
2016-05-30T21:05:05Z
37,533,991
<p>Both len() and sum() are Python builtin functions (with limited functionality), that are written in C and, more importantly, are optimized to work fast with certain types or objects (list).</p> <p>You can look at the implementation of builtin functions here:</p> <p><a href="https://hg.python.org/sandbox/python2.7/...
5
2016-05-30T21:48:05Z
[ "python", "performance", "mean" ]
Pandas dataframe sub-selection
37,533,828
<p>I am new to programming and have taken up learning python in an attempt to make some tasks I run in my research more efficient. I am running a PCA in the pandas module (I found a tutorial online) and have the script for this, but need to subselect part of a dataframe prior to the pca. </p> <p>so far I have (just fo...
2
2016-05-30T21:26:32Z
37,533,874
<p>Indexers like <code>loc</code>, <code>iloc</code>, and <code>ix</code> accept boolean arrays. For example if you have three columns, <code>df.loc[:, [True, False, True]]</code> will return all the rows and the columns 0 and 2 (when corresponding value is True). You can check whether any of the elements in a column i...
1
2016-05-30T21:32:58Z
[ "python", "pandas", "dataframe", "subset" ]
Google Appengine application written in Java with access to Python+Numpy+Scipy?
37,533,921
<p>I have a rather big appengine application completely written in Java. I would need to obtain results from functions completely written in python (if possible 3.x) with numpy and similar packages. </p> <p>What is the best way to do it?</p>
0
2016-05-30T21:38:31Z
37,547,311
<p>I'm thinking in two options.</p> <ol> <li>You can write an app-engine's python module (now called <a href="https://cloud.google.com/appengine/docs/java/an-overview-of-app-engine#services_the_building_blocks_of_app_engine" rel="nofollow">services</a>) using default or <a href="https://cloud.google.com/appengine/docs...
1
2016-05-31T13:35:29Z
[ "java", "python", "google-app-engine", "numpy", "scipy" ]
Getting the index of pandas dataframe for matching row values
37,533,956
<p>I have to dataframes in pandas , <code>A</code> and <code>B</code>: </p> <p>A:</p> <pre><code>A = pd.DataFrame({0:[1.24, 8.75, 4.32]}) 0 1.24 1 8.75 2 4.32 </code></pre> <p>where the <code>0 1 2 3 4 5</code> is the index of the dataframe</p> <p>and another dataframe with strings as index:</p> <pre><co...
1
2016-05-30T21:43:14Z
37,533,972
<p>I would approach this program by using a join operation. First, use <code>reset_index</code> on B to make the index a new column in the dataframe. Then use an inner join to combine the two dataframes together using the <code>merge</code> function. Make sure you disable sorting during the join operation. The index co...
0
2016-05-30T21:45:58Z
[ "python", "pandas" ]
Getting the index of pandas dataframe for matching row values
37,533,956
<p>I have to dataframes in pandas , <code>A</code> and <code>B</code>: </p> <p>A:</p> <pre><code>A = pd.DataFrame({0:[1.24, 8.75, 4.32]}) 0 1.24 1 8.75 2 4.32 </code></pre> <p>where the <code>0 1 2 3 4 5</code> is the index of the dataframe</p> <p>and another dataframe with strings as index:</p> <pre><co...
1
2016-05-30T21:43:14Z
37,534,055
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.isin.html" rel="nofollow">isin()</a> function for that:</p> <pre><code>In [141]: B[B[0].isin(A[0])].index Out[141]: Index(['p_21', 'p_05', 'p_76'], dtype='object') In [142]: B[B[0].isin(A[0])] Out[142]: 0 p_21 1.2...
2
2016-05-30T21:53:38Z
[ "python", "pandas" ]
Python edit xml file
37,533,974
<p>I am very new one here, I am searching here for more than our, but I can not find answer.</p> <p>I need to edit xml file using python. I have current structure:</p> <pre><code>&lt;?xml version="1.0" encoding="windows-1250"?&gt; &lt;MoneyData ICAgendy="46501401" KodAgendy="" HospRokOd="2016-01-01" HospRokDo="2016-1...
1
2016-05-30T21:46:27Z
37,534,064
<p>Just find the nodes and change <code>tag</code>:</p> <pre><code>from xml.etree import ElementTree as et x="""&lt;?xml version="1.0" encoding="windows-1250"?&gt; &lt;MoneyData ICAgendy="46501401" KodAgendy="" HospRokOd="2016-01-01" HospRokDo="2016-12-31" description="všetky skladové doklady" ExpZkratka="_S" ExpDa...
3
2016-05-30T21:54:01Z
[ "python", "xml" ]
Python 3.4, Windows 10 and Unable to find vcvarsall.bat
37,534,000
<p>When I try to build one package:</p> <pre><code>C:\Linter\intlib\PYTHON&gt;python setup.py build </code></pre> <p>I get this error message:</p> <blockquote> <p>running build</p> <p>running build_ext</p> <p>building 'LinPy' extension</p> <p>error: Unable to find vcvarsall.bat</p> </blockquote> <p...
2
2016-05-30T21:48:59Z
37,631,048
<p>The issue is caused because you don't have a compiler installed for the receptive build you are trying to run. </p> <hr> <p>The following is what you may require as per the MS Python Engineering community,</p> <pre><code>Python Version |You will need ------------------------------------ 3.5 and later |Visual C...
3
2016-06-04T13:54:30Z
[ "python", "windows", "visual-studio-2010" ]
Python 3.4, Windows 10 and Unable to find vcvarsall.bat
37,534,000
<p>When I try to build one package:</p> <pre><code>C:\Linter\intlib\PYTHON&gt;python setup.py build </code></pre> <p>I get this error message:</p> <blockquote> <p>running build</p> <p>running build_ext</p> <p>building 'LinPy' extension</p> <p>error: Unable to find vcvarsall.bat</p> </blockquote> <p...
2
2016-05-30T21:48:59Z
37,667,801
<p>You can ease your pains with Microsoft compilers for Python 3.4 by installing mingwpy or libpython (not both):</p> <p><code>pip install -i https://pypi.anaconda.org/carlkl/simple mingwpy</code></p> <p><code>conda install libpython</code></p>
2
2016-06-06T22:28:21Z
[ "python", "windows", "visual-studio-2010" ]
Python 3.4, Windows 10 and Unable to find vcvarsall.bat
37,534,000
<p>When I try to build one package:</p> <pre><code>C:\Linter\intlib\PYTHON&gt;python setup.py build </code></pre> <p>I get this error message:</p> <blockquote> <p>running build</p> <p>running build_ext</p> <p>building 'LinPy' extension</p> <p>error: Unable to find vcvarsall.bat</p> </blockquote> <p...
2
2016-05-30T21:48:59Z
37,688,367
<p>I did a search for a python wheel of <code>LinPy</code> unfortunately there happened to be none. </p> <p><code>Cython</code> has a very good workaround for setting up a windows C/C++ compiler for builds in python. You can find it <a href="https://github.com/cython/cython/wiki/CythonExtensionsOnWindows#using-windows...
2
2016-06-07T20:06:40Z
[ "python", "windows", "visual-studio-2010" ]
Python 3.4, Windows 10 and Unable to find vcvarsall.bat
37,534,000
<p>When I try to build one package:</p> <pre><code>C:\Linter\intlib\PYTHON&gt;python setup.py build </code></pre> <p>I get this error message:</p> <blockquote> <p>running build</p> <p>running build_ext</p> <p>building 'LinPy' extension</p> <p>error: Unable to find vcvarsall.bat</p> </blockquote> <p...
2
2016-05-30T21:48:59Z
37,922,446
<p>To use mingwpy instead of the MSVC compiler create a file named <strong>pydistutils.cfg</strong> in the folder <strong>%USERPROFILE%</strong> with the following content:</p> <pre><code>[config] compiler=mingw32 [build] compiler=mingw32 [build_ext] compiler=mingw32 </code></pre> <p>see also <a href="http://stackove...
0
2016-06-20T12:19:27Z
[ "python", "windows", "visual-studio-2010" ]
addCleanUp vs tearDown
37,534,021
<p>Recently, Ned Batchelder during <a href="http://nedbatchelder.com/text/machete.html">his talk at PyCon 2016</a> noted:</p> <blockquote> <p>If you are using <code>unittest</code> to write your tests, definitely use <code>addCleanup</code>, it's much better than <code>tearDown</code>.</p> </blockquote> <p>Up unt...
14
2016-05-30T21:50:18Z
37,534,051
<p>Per the <a href="https://docs.python.org/3.5/library/unittest.html#unittest.TestCase.addCleanup"><code>addCleanup</code> doc string</a>:</p> <blockquote> <p>Cleanup items are called even if setUp fails (unlike tearDown)</p> </blockquote> <p><code>addCleanup</code> can be used to register multiple functions, so y...
15
2016-05-30T21:53:21Z
[ "python", "unit-testing", "python-unittest" ]
addCleanUp vs tearDown
37,534,021
<p>Recently, Ned Batchelder during <a href="http://nedbatchelder.com/text/machete.html">his talk at PyCon 2016</a> noted:</p> <blockquote> <p>If you are using <code>unittest</code> to write your tests, definitely use <code>addCleanup</code>, it's much better than <code>tearDown</code>.</p> </blockquote> <p>Up unt...
14
2016-05-30T21:50:18Z
37,534,071
<p><code>addCleanup()</code> methods will run even if one of them fails, and will run even if <code>setUp()</code> fails. You should also consider using <a href="http://pytest.org/latest/" rel="nofollow">pytest</a>.</p>
3
2016-05-30T21:54:26Z
[ "python", "unit-testing", "python-unittest" ]
How to use a function containing eval in a file by variable defined at another file from that another file?
37,534,046
<p>Assume, I have created an python file (FirstFile.py) name which contains many functions and other things. One of the function is this (of course, it is simplified):</p> <pre><code>def func(string): assert eval(string) </code></pre> <p>Besides, I have created an python file which imports func() from the file me...
0
2016-05-30T21:53:00Z
37,534,722
<p>by default <code>eval</code> executes in the current local/global scope, if you want to specify a different environment you can do something like:</p> <pre><code>eval("x == 1", {"x":1}) </code></pre> <p>so your function could take an optional <code>environ</code> argument:</p> <pre><code>def func(string, environ=...
0
2016-05-30T23:21:03Z
[ "python", "python-3.x", "eval" ]
What is the difference between boto3 list_objects and list_objects_v2?
37,534,077
<p>I'm trying to list objects in an Amazon s3 bucket in python using <code>boto3</code>.</p> <p>It seems <code>boto3</code> has 2 functions for listing the objects in a bucket: <code>list_objects()</code> and <code>list_objects_v2()</code>. </p> <p>What is the difference between the 2 and what is the benefit of using...
1
2016-05-30T21:54:55Z
37,534,078
<p>According to boto3 documentation <a href="http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2" rel="nofollow">here</a>, it is recommended to use the "revised API". Why is this the case, they don't mention. </p> <p>The main difference is a leaner Response object. In the respons...
0
2016-05-30T21:54:55Z
[ "python", "amazon-s3", "boto3" ]
What is the difference between boto3 list_objects and list_objects_v2?
37,534,077
<p>I'm trying to list objects in an Amazon s3 bucket in python using <code>boto3</code>.</p> <p>It seems <code>boto3</code> has 2 functions for listing the objects in a bucket: <code>list_objects()</code> and <code>list_objects_v2()</code>. </p> <p>What is the difference between the 2 and what is the benefit of using...
1
2016-05-30T21:54:55Z
37,539,994
<p>Comparison side by side.</p> <p>list_objects() :</p> <pre><code>response = client.list_objects( Bucket='string', Delimiter='string', EncodingType='url', #Marker to list continuous page Marker='string', MaxKeys=123, Prefix='string' ) </code></pre> <p>list_objects_v2()</p> <pre><code>re...
3
2016-05-31T07:55:21Z
[ "python", "amazon-s3", "boto3" ]
How to react to a button click in pyqt5
37,534,093
<p>So, I am new to python programming. I have started to implement a UI in pyqt5 and there I have a button and I want to react when the user clicks it.</p> <p>According to <a href="http://zetcode.com/gui/pyqt5/eventssignals/" rel="nofollow">this Link</a> I should simply write <code>btn.clicked.connect(self.buton_press...
0
2016-05-30T21:57:20Z
37,590,946
<p>It's hard to understand your problem since you don't provide us with a <a href="http://stackoverflow.com/help/mcve">working example</a>, i.e. a peace of code one can run "as is". Something like this:</p> <pre><code>from PyQt4 import QtCore, QtGui class MyWindow(QtGui.QWidget): def __init__(self): super...
0
2016-06-02T11:45:39Z
[ "python", "connect", "pyqt5" ]
reading all the text files from directory
37,534,141
<p>I am new to python and I am using following code to pull output as sentiment analysis:</p> <pre><code>import json from watson_developer_cloud import ToneAnalyzerV3Beta import urllib.request import codecs import csv import os import re import sys import collections import glob ipath = 'C:/TEMP/' # input folder opath...
0
2016-05-30T22:04:43Z
37,534,164
<p><em>glob</em> returns a list of files, you need to iterate over the list, open each file and then call <em>.read</em> on the <em>file object</em>:</p> <pre><code>files = glob.glob(path) # iterate over the list getting each file for fle in files: # open the file and then call .read() to get the text with ope...
3
2016-05-30T22:06:58Z
[ "python", "csv" ]
How to connect to my remote SQL server
37,534,186
<p>I have a linux ubuntu server that I rent from DigitalOcean for storing streaming real time data in MySQL by coding with python.</p> <p>Problem is that I am coding not in the linux server environment but in my local computer python(personal Windows 10(not a server)). So in the coding, I need to connect to my linux s...
0
2016-05-30T22:09:21Z
37,534,326
<p>Similar question have already been asked <a href="http://stackoverflow.com/questions/12972867/connect-on-remote-mysql-database-through-python" title="here">here</a>. </p> <ul> <li>Can you connect from your local OS to your remote Database? <code>mysql -u XXXX -h {IP} -p</code></li> <li><p>Have you granted your cli...
-1
2016-05-30T22:24:33Z
[ "python", "linux", "server" ]
Python Read Fortran Binary File
37,534,220
<p>I'm trying to read a binary file output from Fortran code below, but the results are not the same from output file. Can anyone help me? Thanks in advance.</p> <p>Fortran 77 code:</p> <pre><code> program test implicit none integer i,j,k,l real*4 pcp(2,3,4) open(10, file='pcp.bin', form='unf...
2
2016-05-30T22:13:38Z
37,535,538
<p>Use nupy.fromfile (<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.fromfile.html</a>)</p> <p>I guess you have missed something in fortran code, to write to binary file apply this code:</p> <pre><code>program ...
1
2016-05-31T01:30:50Z
[ "python", "file", "binary", "fortran" ]
Python Read Fortran Binary File
37,534,220
<p>I'm trying to read a binary file output from Fortran code below, but the results are not the same from output file. Can anyone help me? Thanks in advance.</p> <p>Fortran 77 code:</p> <pre><code> program test implicit none integer i,j,k,l real*4 pcp(2,3,4) open(10, file='pcp.bin', form='unf...
2
2016-05-30T22:13:38Z
37,552,062
<p>Because you are writing <code>real*4</code> data on a sequential file, simply try replacing <code>dtype=float</code> to <code>dtype='float32'</code> (or <code>dtype=np.float32</code>) in read_reals(): </p> <pre><code>&gt;&gt;&gt; from scipy.io import FortranFile &gt;&gt;&gt; f = FortranFile( 'pcp.bin', 'r' ) &gt;&...
2
2016-05-31T17:25:54Z
[ "python", "file", "binary", "fortran" ]
Creating chains that loop on themselves
37,534,255
<p>I want to have a number that breaks into 2 other numbers and checks for end conditions, breaking off each number until the conditions are met. </p> <p>I came up with the following example to try to figure it out. Take a number, and break it into 2 more numbers: one is the original number multiplied by 2 and the oth...
1
2016-05-30T22:16:26Z
37,534,726
<p>This sort of problem typically lends itself to <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)" rel="nofollow">trees</a> and/or <a href="https://en.wikipedia.org/wiki/Recursion" rel="nofollow">recursion</a>. However, the rate at which you're spawning new work is quite high compared to the rate at which ...
1
2016-05-30T23:21:32Z
[ "python", "recursion", "while-loop" ]
Creating chains that loop on themselves
37,534,255
<p>I want to have a number that breaks into 2 other numbers and checks for end conditions, breaking off each number until the conditions are met. </p> <p>I came up with the following example to try to figure it out. Take a number, and break it into 2 more numbers: one is the original number multiplied by 2 and the oth...
1
2016-05-30T22:16:26Z
37,534,738
<p>Using a simple <code>Node</code> class, this can give you an idea of the tree structure. This traverses the tree in level-order (which guarantees to find the shortest chain):</p> <pre><code>from collections import deque import numpy as np def check_conditions(number): return number &gt; 100 or number == 6 or n...
1
2016-05-30T23:24:26Z
[ "python", "recursion", "while-loop" ]
How to read the config file as an input when running the python code from command line
37,534,315
<p>I have multiple test classes and a basetest class in python. test classes inherits from basetest class.</p> <p>I want to run the test class from command line and it needs some input parameters, these input parameters should be stored in a config file. This config file can be provided as an input from the command li...
0
2016-05-30T22:22:58Z
38,826,956
<p>Use a hierarchy as below.</p> <pre><code>` | |- TestModule | |- main.py (your entry point to the test) |- conf.ini |- parse_config.py </code></pre> <p>Now here, you in the <code>parse_config.py</code> you call your <code>SafeConfigParser</code> on the <code>conf.ini</code>. Pass its pat...
0
2016-08-08T10:33:17Z
[ "python", "selenium", "selenium-webdriver", "py.test", "python-unittest" ]
Work with intervals using pandas
37,534,316
<p>I have df</p> <pre><code>num city inc pop 1,0 Абан 29343,00 8683,00 2,0 Агинское 25896,00 17496,00 3,0 Александровский Шлюз 21785,00 15063,00 4,0 Анапа 20000,00 70453,00 5,0 Апатиты 44057,00 57398,00 6,0 Арзамас 24000,00 104...
0
2016-05-30T22:23:16Z
37,534,518
<p>If I understand correctly, you want to print the data frame only in the range: price_people ± 10000.</p> <pre><code>price_people = 30000 print( df[ ( df['inc'] &gt;= price_people - 10000 ) &amp; ( df['inc'] &lt;= price_people + 10000 ) ] ) </code></pre> <p>prints out:</p> <pre><code> num city inc po...
1
2016-05-30T22:49:44Z
[ "python", "pandas" ]
How to stop timer tick
37,534,325
<p>In my code, I have a timer called timer. I started it somewhere in the game by doing timer.tick(). I was wondering if there is any kind of command that can stop the timer from recording time anymore and just stop. Because if I just set it to zero it keeps going, which I have tried. Is there a command like timer.sto...
1
2016-05-30T22:24:27Z
37,541,021
<p>Because <code>timer.get_time()</code> returns the time from the last call to <code>timer.tick()</code>, all you have to do is set the <code>timer_count</code> back to 0 and <code>call timer.tick()</code> to reset everything.</p> <p>Here is an example:</p> <pre><code>import pygame clock = pygame.time.Clock() FPS =...
2
2016-05-31T08:49:43Z
[ "python", "pygame" ]
How can I extract data from a Python tuple?
37,534,327
<p>I'm a newbie to Python. For this data, I'm working with Jupytier iPython. I'm trying to extract numerical data from a csv file to then run Sklearn on. I have :</p> <p>Opened and read the CSV file with Pandas</p> <p>Set the data to a dictionary I set up to organza my data</p> <p>( set up a Pandas DataFrame to se...
-3
2016-05-30T22:24:34Z
37,534,564
<p>If you mean basic python syntax, you should go there first.</p> <p><a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences</a></p> <p>Here are some examples:</p> <pre><code>data = ('first', 'se...
0
2016-05-30T22:57:11Z
[ "python", "csv", "numpy", "scikit-learn" ]
Advice for using argparse
37,534,352
<p>I am writing a python command line client program to interface with an api. The user uses the client program to run following command and the client program makes following example calls to api</p> <blockquote> <p>python run.py --car --> calls method get_all(vehicle_type) which requests--> /car/all --&lt; whi...
1
2016-05-30T22:27:17Z
37,534,515
<p>I find when using mutually_exclusive_groups I frequently make use of the <a href="https://docs.python.org/3/library/argparse.html#dest" rel="nofollow"><code>dest</code> option</a> so you have one variable with a dynamic value:</p> <pre><code>import argparse parser = argparse.ArgumentParser() grp1 = parser.add_mutu...
1
2016-05-30T22:49:22Z
[ "python", "argparse" ]
Advice for using argparse
37,534,352
<p>I am writing a python command line client program to interface with an api. The user uses the client program to run following command and the client program makes following example calls to api</p> <blockquote> <p>python run.py --car --> calls method get_all(vehicle_type) which requests--> /car/all --&lt; whi...
1
2016-05-30T22:27:17Z
37,535,091
<p>A relatively straight forward way of doing what you want (I think) is:</p> <pre><code>import argparse def get_all(vehicle_type, *value): # optional value parameter print('all', vehicle_type) def get_by_id(vehicle_type, id): print('id', vehicle_type, id) def get_by_color(vehicle_type, color): print(...
2
2016-05-31T00:20:48Z
[ "python", "argparse" ]
Is there a way to reference the instance in decorators inside a class?
37,534,361
<p>I'm using <a href="https://bitbucket.org/pyglet/pyglet/wiki/Home" rel="nofollow">pyglet</a> and pyglet uses decorators in order to deal with events. I'm subclassing <code>pyglet.window.Window</code> in my own class:</p> <pre><code>class YApp(YData, pyglet.window.Window): def __init__(self, screen_width=1024, s...
3
2016-05-30T22:28:39Z
37,534,555
<p>That's unfortunately not possible. The decorator is executed when defining the class, but you can't (normally) create an instance of a class before it's defined.</p> <p>But you don't have to do this. As shown in the <a href="http://pyglet.readthedocs.io/en/latest/programming_guide/windowing.html#subclassing-windo...
3
2016-05-30T22:56:01Z
[ "python", "python-3.x" ]
empty paginate object sqlalchemy
37,534,383
<p>I am using sqlalchemy to retrieve a list of objects using the paginate function </p> <pre><code>results = models.Object.query.filter(models.Object.id.in_(list_of_ids)).paginate(page, 10, False) </code></pre> <p>Sometimes <code>list_of_ids</code> can be empty. I noticed that queries where this list is empty are ver...
0
2016-05-30T22:32:01Z
37,546,556
<p>You could probably mess around and instantiate your own instance of an empty <code>Pagination</code> object in order to avoid a query, but it might just be easier to perform a simple, fast, query that returns no rows:</p> <pre><code>&gt;&gt;&gt; empty_paginator = models.Object.query.filter_by(id=None).paginate() &g...
1
2016-05-31T13:03:07Z
[ "python", "pagination", "sqlalchemy", "flask-sqlalchemy" ]
How to flatten zipped object containing nested arrays to a list?
37,534,422
<p>I have a zipped object like this:</p> <pre><code>z = zip(a, b) lst = list(z) print(lst) </code></pre> <p>Output:</p> <pre><code>[(0, array([[72, 65], [70, 71]], dtype=uint8)), (1, array([[ 71, 99], [190, 163]], dtype=uint8)), (2, array([[52, 59], [69, 72]], dtype=uint8)), etc....
1
2016-05-30T22:37:47Z
37,534,488
<pre><code>from itertools import chain list(chain.from_iterable(chain([x], chain.from_iterable(y)) for x, y in z)) </code></pre> <p>I'm using just <code>chain</code> for consistency but there are plenty of ways to flatten things, as @Padriac has shown.</p>
0
2016-05-30T22:45:48Z
[ "python", "list", "python-3.x", "numpy" ]
How to flatten zipped object containing nested arrays to a list?
37,534,422
<p>I have a zipped object like this:</p> <pre><code>z = zip(a, b) lst = list(z) print(lst) </code></pre> <p>Output:</p> <pre><code>[(0, array([[72, 65], [70, 71]], dtype=uint8)), (1, array([[ 71, 99], [190, 163]], dtype=uint8)), (2, array([[52, 59], [69, 72]], dtype=uint8)), etc....
1
2016-05-30T22:37:47Z
37,534,489
<p>You data is nested so you would need chain to recursively flatten which chain does not do, what you can do is flatten the numpy arrays and add:</p> <pre><code>from itertools import chain print list(chain.from_iterable(([a] + arr.flatten().tolist()) for a, arr in lst)) </code></pre> <p>Or use <code>.flat</code> an...
2
2016-05-30T22:45:55Z
[ "python", "list", "python-3.x", "numpy" ]
How to flatten zipped object containing nested arrays to a list?
37,534,422
<p>I have a zipped object like this:</p> <pre><code>z = zip(a, b) lst = list(z) print(lst) </code></pre> <p>Output:</p> <pre><code>[(0, array([[72, 65], [70, 71]], dtype=uint8)), (1, array([[ 71, 99], [190, 163]], dtype=uint8)), (2, array([[52, 59], [69, 72]], dtype=uint8)), etc....
1
2016-05-30T22:37:47Z
37,534,526
<p>Use one of</p> <ul> <li><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ravel.html" rel="nofollow"><code>numpy.ravel</code></a> returns a contiguous flattened array.</li> <li><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flat" rel...
3
2016-05-30T22:51:25Z
[ "python", "list", "python-3.x", "numpy" ]
Python - matplotlib.pyplot ion() slow
37,534,431
<p>I am trying to update my maze as the search for the solution continuous (this is a simple uniform-cost-search for a maze). I am using pyplots <code>ion()</code> to update my figure after each node visit. My problem is that the figure updates very slowly at about 20 iterations. I tried to reduce the value for <code>p...
1
2016-05-30T22:38:52Z
37,535,009
<p>Here is a basic example showing how to animate a <code>Quadmesh</code> such as the one returned by <code>pcolormesh</code>. All you need to do (hah!) is modify <code>step</code> to yield the mazes that you wish to display. </p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.colors a...
2
2016-05-31T00:06:54Z
[ "python", "python-2.7", "matplotlib" ]
Passing command line arguments to argv in jupyter/ipython notebook
37,534,440
<p>I'm wondering if it's possible to populate <code>sys.argv</code> (or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script. </p> <p>For instance, if I were to run a python script as follows:</p> <p><code>python test.py False</code></p> <p...
2
2016-05-30T22:39:48Z
38,220,095
<p>I think this Gist may help you : <a href="https://gist.github.com/gbishop/acf40b86a9bca2d571fa" rel="nofollow">https://gist.github.com/gbishop/acf40b86a9bca2d571fa</a></p> <p>This is an attempt at a simple argument parser for mostly key=value pairs that can be used both on the command line and in IPython notebooks....
0
2016-07-06T09:04:18Z
[ "python", "command-line-arguments", "jupyter", "jupyter-notebook" ]
Check whether each row of a matrix is in another matrix [Python]
37,534,466
<p>I have two matrices (or, better, 2D numpy arrays), <code>A</code> and <code>B</code>, with same number of columns (well, to be fair they have a different number of rows, however I'm just slicing both matrices on two columns) but different number of rows. </p> <p>I would like to check whether every row in <code>A</...
1
2016-05-30T22:42:49Z
37,534,552
<p>You can use a vectorized approach using <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html" rel="nofollow"><code>NumPy broadcasting</code></a>, like so -</p> <pre><code>np.argwhere((B[:,None,[0,1]] == A[:,[1,2]]).all(-1)) </code></pre> <p>Alternatively, since you are dealing with rows of...
1
2016-05-30T22:55:45Z
[ "python", "numpy", "matrix" ]
The right way to perform a task asynchronously in Django, via Celery
37,534,469
<p>I have a Django app which mimics Instagram, in that users upload photos or memes, and then their fans get notified of the said photo.</p> <p>Currently, in order to send notifications, as soon as a user uploads a photo, I iterate through every fan the uploader has, append the notifications to a list, and then <code>...
4
2016-05-30T22:43:04Z
37,534,524
<p>You need to pass <code>fans</code> (you might have to cast it to <code>list</code> if it is actually a <code>ValuesListQuerySet</code>) and all other things the task needs (e.g. <code>photo.id</code>) as an argument to the task:</p> <pre><code>@task def bulk_create_notifications(fans, photo_id): fan_list = [] ...
3
2016-05-30T22:51:08Z
[ "python", "django", "celery", "django-celery", "celery-task" ]
Truncate a big integer to a uint8 type in Python
37,534,634
<p>I'm casting an array that is populated with signed 32-bit integers to an array with only uint8 values (from 0 to 255). Right now, my code looks like this:</p> <pre><code>newArray = Image.fromarray(oldArray.astype(numpy.uint8)) </code></pre> <p>The thing is: I want the numbers lower than zero to become zero, and th...
2
2016-05-30T23:05:36Z
37,534,671
<p>For in-place thresholding, I would use numpy.clip(myArray,0,255) before casting your array into the new data type.</p>
4
2016-05-30T23:12:14Z
[ "python", "arrays", "types", "casting" ]
How to remove values from a list that are less than a target value from the previous number
37,534,655
<p>Given a sorted list of increasing numbers, I'm trying to create a new list that only keeps values that are at least 3 greater than the previous number. I have tried some conditional statements, but fail to get the correct format. For example, from </p> <pre><code>a = [3,4,8,12,14,16] </code></pre> <p>we would obt...
1
2016-05-30T23:09:09Z
37,534,703
<pre><code>a = [3,4,8,12,14,16] b = a[:1] last_num = b[0] for num in a: if last_num is not None and last_num + 3 &lt;= num: b.append(num) last_num = num print(b) </code></pre>
0
2016-05-30T23:17:49Z
[ "python", "list" ]
How to remove values from a list that are less than a target value from the previous number
37,534,655
<p>Given a sorted list of increasing numbers, I'm trying to create a new list that only keeps values that are at least 3 greater than the previous number. I have tried some conditional statements, but fail to get the correct format. For example, from </p> <pre><code>a = [3,4,8,12,14,16] </code></pre> <p>we would obt...
1
2016-05-30T23:09:09Z
37,534,788
<p>This should do:</p> <pre><code>new_a = a[:1] for i in a[1:]: if i &gt;= new_a[-1] + 3: new_a.append(i) </code></pre>
5
2016-05-30T23:30:49Z
[ "python", "list" ]
How to remove values from a list that are less than a target value from the previous number
37,534,655
<p>Given a sorted list of increasing numbers, I'm trying to create a new list that only keeps values that are at least 3 greater than the previous number. I have tried some conditional statements, but fail to get the correct format. For example, from </p> <pre><code>a = [3,4,8,12,14,16] </code></pre> <p>we would obt...
1
2016-05-30T23:09:09Z
37,535,269
<p>Possibly overkill, but if you end up doing this computation a lot (as well as adding new numbers to the list) you can try subclassing <code>list</code>.</p> <pre><code>class Newlist(list): def __init__(self, *args): super(Newlist, self).__init__(*args) if len(self) &gt; 0: i = 1 ...
0
2016-05-31T00:49:31Z
[ "python", "list" ]
How to edit global variable in module?
37,534,826
<p>I am writing a Python module and I have a function that defines a new variable in the module. I want to set a variable that can be accessed in the file that is importing the file. If that is confusing, here is my code:</p> <pre><code># main.py import other_module other_module.set_variable("var1") print(other_mod...
0
2016-05-30T23:36:49Z
37,535,614
<p>What you are doing sounds like class method behavior to me. A class will be safer to use than the global namespace, try a class?</p> <p>This works:</p> <pre><code># other.py class Other(object): @classmethod def set_variable(cls, name): exec('Other.%s = 5' % name) # main.py from other import Othe...
1
2016-05-31T01:42:43Z
[ "python", "python-3.x", "global-variables" ]
Write series of strings (plus a number) to a line of csv
37,534,849
<p>It's not pretty code, but I have some code that grabs a series of strings out of an HTML file and gives me a series of strings: <code>author</code>, <code>title</code>, <code>date</code>, <code>length</code>, <code>text</code>. I have 2000+ html files and I want go through all of them and write this data to a single...
1
2016-05-30T23:42:53Z
37,541,879
<p>This will grab all the files and put the data into a csv, you just need to pass the path to the folder that contains the html files and the name of your output file:</p> <pre><code>import re import csv import os from bs4 import BeautifulSoup from glob import iglob def parse(soup): # both title and author are ...
1
2016-05-31T09:29:02Z
[ "python", "csv", "pandas" ]
How to store Entry as a variable that can be used in an equation to have the result printed in label with tkinter
37,534,885
<p>I am trying to take entry from an entry boxes and use them in an equation. Basically it is </p> <p>Entry_one - Entry_two * entry_three / 12. But I cant seem to figure out how to do this. To make it more clear here is the working python code: </p> <pre><code>a = int(input('Order Amount. ')) c = int(input('Beams Lef...
-2
2016-05-30T23:47:56Z
37,535,249
<p>you could create a variable and retrieve it with the get method in your function: as explained in the following <a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow">documentation</a>:</p> <pre><code>from tkinter import * root = Tk() var_01 = StringVar() enter_01 = Entry(root, textvariable=var_01) ent...
0
2016-05-31T00:44:54Z
[ "python", "tkinter", "entry" ]
How to store Entry as a variable that can be used in an equation to have the result printed in label with tkinter
37,534,885
<p>I am trying to take entry from an entry boxes and use them in an equation. Basically it is </p> <p>Entry_one - Entry_two * entry_three / 12. But I cant seem to figure out how to do this. To make it more clear here is the working python code: </p> <pre><code>a = int(input('Order Amount. ')) c = int(input('Beams Lef...
-2
2016-05-30T23:47:56Z
37,545,436
<p>Your code doesn't exhibit the error you say it does. Just about the only possible way to get that specific error is if you omit the first three lines of your program after the import, and set <code>root</code> to a string. Even when you do that, you get a slightly different error -- it will complain about the first...
1
2016-05-31T12:11:25Z
[ "python", "tkinter", "entry" ]
Formatting log axis labels with proper superscripts in Bokeh
37,534,927
<p>This is, admittedly, a minor annoyance. When using log scale axes, Bokeh formats the tick labels as "10^1" instead of "10<sup>1</sup>"</p> <p><a href="http://i.stack.imgur.com/A68Fq.png" rel="nofollow"><img src="http://i.stack.imgur.com/A68Fq.png" alt="enter image description here"></a></p> <p>Is there any way I c...
0
2016-05-30T23:55:06Z
37,553,712
<p>As of Bokeh <code>0.11.1</code> there is no way to have the actual superscript. Support for LaTeX labels is a long-standing feature request, but some recent other work may have helped pave the way for finally adding it in the near future. </p> <hr> <p>In the mean time, you could create your own custom <code>TickFo...
1
2016-05-31T19:05:33Z
[ "python", "bokeh" ]
Masking between Pandas dataframes where index doesn't match
37,534,932
<p><strong>The Goal</strong></p> <p>Perform a combination of 2-sample t-tests between 2 dataframes: a boolean matrix that sets the True/False context, and a matrix of values. The combination happens between rows that don't share an index, and I cannot think of how to apply a mask from one index in one df to a mismatc...
0
2016-05-30T23:55:22Z
37,535,159
<pre><code>import itertools for pr in itertools.product(rnadf_all.index, cnv_mask.index): print('&amp;'.join(pr), rnadf_all.loc[pr[0]][cnv_mask.loc[pr[1]]].tolist(), rnadf_all.loc[pr[0]][~cnv_mask.loc[pr[1]]].tolist()) x&amp;a [8, 1, 5] [1, 8] x&amp;b [1, 8] [8, 1, 5] x&amp;c [8, 8, 1] [1, 5] y&amp;a [6,...
1
2016-05-31T00:29:55Z
[ "python", "pandas", "scipy" ]
Creating CSV file with output of python code
37,534,942
<p>I am looking to write a python code that will take the text from multiple .txt files in a directory and run the text against 'Tone analyzer' to do the analysis of the tone. So if I have two files ABC.txt and XYZ.txt. I am looking to do the tone analysis on both the file and create two output files ABC.csv and XYZ.cs...
0
2016-05-30T23:57:44Z
37,536,129
<p>Simply save loop output to lists and then use <code>csv</code> module's <code>writerow()</code> to write lists to file. Below will save <code>tone['tone_name']</code> and <code>tone['tone_score']</code> data to csv files with <code>output</code> serving as the unique identifier in file name (extension .txt removed)....
0
2016-05-31T02:55:19Z
[ "python", "csv" ]
How to store a random number in several variables?
37,534,948
<p>How do I store a random number into several variables?</p> <p>So far I have this:</p> <pre><code>import random random_selection = random.random() random_number_1 = random_selection print(random_number_1) </code></pre> <p>Now when I run random_selection again, it stores a new number into random_number_1 </p> <p>I...
-1
2016-05-30T23:58:29Z
37,534,971
<p>You cannot "run <code>random_selection</code>". It is not a function or any other callable, but a <code>float</code>:</p> <pre><code>import random random_number_1 = random.random() random_number_2 = random.random() </code></pre> <p>You have to call the <code>random()</code> function again in order to get a new ran...
2
2016-05-31T00:01:11Z
[ "python" ]
Getting "RuntimeError: maximum recursion depth exceeded" when editing a TableView cell
37,535,029
<p>====Solution====</p> <p>You'll find that in the comments @TimHoffmann asked me if I had another instance of <code>dataChanged()</code> and it turns out I was using it inside <code>data()</code>, causing the recursion problem.</p> <p>===============</p> <p>I'm trying to track down an error I get when editing a QTa...
-1
2016-05-31T00:11:06Z
37,552,575
<p>====Solution====</p> <p>You'll find that in the comments @TimHoffmann asked me if I had another instance of dataChanged() and it turns out I was using it inside data(), causing the recursion problem.</p> <p>===============</p>
0
2016-05-31T17:56:49Z
[ "python", "qt", "pyside" ]
how to plot sub df with values from whole dataset as x axis ticks in python
37,535,037
<p>I have a big data frame which contains thousands of data point and there is one column called period with the format 2011q1 stands for quarter 1 in 2011 from 2009q2 to 2015q2. After group by person, I got several sub-data frame and each of it only contains certain time interval instead of the whole time interval fro...
1
2016-05-31T00:13:27Z
37,536,462
<blockquote> <p>@StanleyR Both of my x axis value and y value are something I got from the groupby and aggregate command, so how can I separate them for defining the x and y value in the plt.plot(x,y) function?</p> </blockquote> <pre><code>import matplotlib.pyplot as plt import numpy as np X = ['2009q1', '2009q...
0
2016-05-31T03:41:48Z
[ "python", "pandas", "matplotlib" ]
how to plot sub df with values from whole dataset as x axis ticks in python
37,535,037
<p>I have a big data frame which contains thousands of data point and there is one column called period with the format 2011q1 stands for quarter 1 in 2011 from 2009q2 to 2015q2. After group by person, I got several sub-data frame and each of it only contains certain time interval instead of the whole time interval fro...
1
2016-05-31T00:13:27Z
37,537,382
<p>You could certainly do it Stanley's way, and maybe use <code>full_df['Period'].unique()</code> to get your labels. But it sounds to me like what you actually want to do is go back to before doing the <code>groupby</code> and use a pivot table.</p> <pre><code>import pandas as pd D=pd.DataFrame({'Period':['Q1','Q1'...
0
2016-05-31T05:22:18Z
[ "python", "pandas", "matplotlib" ]
How to Obtain k Most/Least Frequent in a list?
37,535,052
<p>I have a list of items. My goal is to find the top k most frequent items <strong>without using collections.Counter</strong>.</p> <p>Idea #1: I walk through the list, put the item in a dictionary, along with a count. If I encounter the item again, I increment the count. Reverse keys. (item, count) -> (count, List of...
-1
2016-05-31T00:15:16Z
37,535,114
<p>If you don't want to use <code>collections.Counter</code>, you can use a simple dict:</p> <pre class="lang-py prettyprint-override"><code>data = ['a', 'b', 'c', 'a', 'b'] counts = {} for item in data: counts[item] = counts.get(item, 0) + 1 print(counts) </code></pre> <p>which outputs</p> <pre><code>{'a': 2, ...
0
2016-05-31T00:24:38Z
[ "python", "algorithm" ]
How to Obtain k Most/Least Frequent in a list?
37,535,052
<p>I have a list of items. My goal is to find the top k most frequent items <strong>without using collections.Counter</strong>.</p> <p>Idea #1: I walk through the list, put the item in a dictionary, along with a count. If I encounter the item again, I increment the count. Reverse keys. (item, count) -> (count, List of...
-1
2016-05-31T00:15:16Z
37,535,116
<p>You can use a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> or just a <code>dict</code> to do the job comfortably. This essentially resembles your first laid out path.</p> <pre><code>from collections import defaultdict import random ...
3
2016-05-31T00:24:50Z
[ "python", "algorithm" ]
How to Obtain k Most/Least Frequent in a list?
37,535,052
<p>I have a list of items. My goal is to find the top k most frequent items <strong>without using collections.Counter</strong>.</p> <p>Idea #1: I walk through the list, put the item in a dictionary, along with a count. If I encounter the item again, I increment the count. Reverse keys. (item, count) -> (count, List of...
-1
2016-05-31T00:15:16Z
37,538,233
<p>if you want things to work faster for this kind of problem use heapq. min heap for k most frequent word. check <a href="http://www.geeksforgeeks.org/find-the-k-most-frequent-words-from-a-file/" rel="nofollow">this url</a> if you are interested.</p>
0
2016-05-31T06:21:40Z
[ "python", "algorithm" ]
How to Obtain k Most/Least Frequent in a list?
37,535,052
<p>I have a list of items. My goal is to find the top k most frequent items <strong>without using collections.Counter</strong>.</p> <p>Idea #1: I walk through the list, put the item in a dictionary, along with a count. If I encounter the item again, I increment the count. Reverse keys. (item, count) -> (count, List of...
-1
2016-05-31T00:15:16Z
37,552,026
<p>If, as you suggest, you are looking for interesting or optimal <em>algorithms</em> to solve this problem, rather than the way to do it in Python (which is surely to use collections.Counter), a good first step is to google the name of the problem plus "Knuth".</p> <p>Searching "Knuth order values by frequency" led m...
2
2016-05-31T17:24:13Z
[ "python", "algorithm" ]
os.mkdir under if not working python
37,535,080
<p>I have the below code, the <code>os.mkdir</code> is not working on mine. Compiling does not return any error, but running the code does not create folder.</p> <pre><code>def folder(): timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S') folderpath = os.path.join(currentpath,"folder",str(timenow)) if os....
0
2016-05-31T00:18:37Z
37,535,171
<p>Try this:</p> <pre><code>def folder(): timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S') folderpath = os.path.join(currentpath, "folder", str(timenow)) if not os.path.exists(folderpath): os.makedirs(folderpath) print 'Created:', folderpath folder() </code></pre> <p><code>makedirs</c...
1
2016-05-31T00:30:31Z
[ "python", "python-os" ]
os.mkdir under if not working python
37,535,080
<p>I have the below code, the <code>os.mkdir</code> is not working on mine. Compiling does not return any error, but running the code does not create folder.</p> <pre><code>def folder(): timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S') folderpath = os.path.join(currentpath,"folder",str(timenow)) if os....
0
2016-05-31T00:18:37Z
37,535,300
<p>Here's my stab at it, with some minor error handling...</p> <pre><code>def folder(): timenow = datetime.now().strftime('%Y-%m-%d_%H%M%S') folderpath = os.path.join(os.getcwd(),"folder",str(timenow)) if not os.path.exists(folderpath): os.makedirs(folderpath) if os.path.exists(folderpath):...
0
2016-05-31T00:53:55Z
[ "python", "python-os" ]
How do I read part of a file into a DataFrame with Python
37,535,139
<p>I have text files which look like this:</p> <pre><code> 0.289 -------- A B C D E -------- EBA E-D EB- EED EBD EBE E-D E-D </code></pre> <p>Now I want to read the various bits into data structures. </p> <p>I want to learn how to use dataframes, so I want to open the file read the first value into a float, skip ...
1
2016-05-31T00:27:41Z
37,535,329
<p>You cannot be better than in your example for the first bits. However, you can read the remainder as fixed width file (pandas.read_fwf):</p> <pre><code>with open("test.txt", 'r') as f: theta = float(f.readline().strip()) f.readline() alphabet = f.readline().split() f.readline() alignmentDF = pan...
1
2016-05-31T00:59:22Z
[ "python", "pandas" ]
using dask multi threaded module
37,535,160
<p>I am trying to use dask's multi-threaded module. This code</p> <pre><code>def foo(arg): return arg*2 jobs = [] t = delayed(foo)(100) jobs.append(t) j = delayed(jobs, pure=True) #j = j.compute() j = j.compute(get=dask.multiprocessing.get) print("class:", type(j[0])) </code></pre> <p>prints <code>('class:', &lt;...
1
2016-05-31T00:29:56Z
37,535,378
<p>If your goal is to compute a list of delayed objects then I recommend using dask's compute function rather than the compute method.</p> <pre><code>from dask import delayed, compute import dask.multiprocessing def foo(arg): return arg*2 jobs = [delayed(foo)(100)] &gt;&gt;&gt; compute(*jobs, get=dask.multiproces...
0
2016-05-31T01:05:36Z
[ "python", "dask" ]
Capturing stdout of a Linux Process with Python using its PID
37,535,170
<p>I have a process in Linux running on the background that writes to stdout. I cannot to run it as a <code>subprocess</code> in a python script.</p> <p>Is there any way to capture its standard out from from a python script using its PID? Sort of using <code>strace -p&lt;pid&gt; -e write</code>in bash.</p> <p><strong...
1
2016-05-31T00:30:25Z
37,536,077
<p>How to deal with this depends on some details, like exactly who owns the background process, and what you can change about how it's started.</p> <h1>Case 1: Not your background process</h1> <p>If you don't own the background process, you don't get to read its output, unless that process makes its output available...
1
2016-05-31T02:47:15Z
[ "python", "linux", "process" ]
Homework: Generating A List of Possible Moves
37,535,241
<p>I am trying to generate a list of possible moves for a checkers-like game. For example, at the start of the game the board would look like [[1,1,1], [0,0,0], [2,2,2]]. My function would take the color (one for white, or two for black) and move the pieces either one space forward, or one space diagonal to capture ano...
-2
2016-05-31T00:43:14Z
37,535,444
<p>First, we must note that moving forward or backwards depends on the owner of the piece.</p> <p>We'll take as an argument the direction of the movement, with the code of the player, the code of the opponent and the board.</p> <p>Now I'll define a function which generates the possible moves. The format is (original ...
0
2016-05-31T01:15:58Z
[ "python" ]
Return Alternating Letters in Two Strings of Different Lengths
37,535,313
<p>I currently have a code written that recursively takes the letters within two strings and returns the new word with alternating letters. I would like to optimize this code so that if the first or second word was longer it will still return the remaining letters in the longer string.</p> <pre><code>def alt(s,t): ...
0
2016-05-31T00:55:59Z
37,535,355
<p>Just test for <code>s</code> and <code>t</code> are empty and return the <em>other</em> value if one of them is:</p> <pre><code>def alt(s, t): if not s: return t elif not t: return s else: return s[0] + t[0] + alt(s[1:], t[1:]) </code></pre> <p>Even if both <code>s</code> and <c...
3
2016-05-31T01:02:26Z
[ "python", "python-3.x", "recursion" ]
Return Alternating Letters in Two Strings of Different Lengths
37,535,313
<p>I currently have a code written that recursively takes the letters within two strings and returns the new word with alternating letters. I would like to optimize this code so that if the first or second word was longer it will still return the remaining letters in the longer string.</p> <pre><code>def alt(s,t): ...
0
2016-05-31T00:55:59Z
37,535,537
<pre><code>def alt(s,t): maxLen = max(len(s),len(t)) S = list(s.ljust(maxLen)) T = list(t.ljust(maxLen)) newWord = '' for x in range(maxLen): if S[x] != " ": newWord += S[x] if T[x] != " ": newWord += T[x] return newWord print alt('hello','bye') #hbeylelo </code></pre>
-1
2016-05-31T01:30:49Z
[ "python", "python-3.x", "recursion" ]
Return Alternating Letters in Two Strings of Different Lengths
37,535,313
<p>I currently have a code written that recursively takes the letters within two strings and returns the new word with alternating letters. I would like to optimize this code so that if the first or second word was longer it will still return the remaining letters in the longer string.</p> <pre><code>def alt(s,t): ...
0
2016-05-31T00:55:59Z
37,535,576
<p>The problem itself is not inherently recursive. An iterative solution may be simpler in this case.</p> <p>Python 2:</p> <pre><code>from itertools import izip_longest def alt(s, t): return ''.join(a + b for a, b in izip_longest(s, t, fillvalue='')) </code></pre> <p>Python 3:</p> <pre><code>from itertools impo...
0
2016-05-31T01:37:28Z
[ "python", "python-3.x", "recursion" ]
Return Alternating Letters in Two Strings of Different Lengths
37,535,313
<p>I currently have a code written that recursively takes the letters within two strings and returns the new word with alternating letters. I would like to optimize this code so that if the first or second word was longer it will still return the remaining letters in the longer string.</p> <pre><code>def alt(s,t): ...
0
2016-05-31T00:55:59Z
37,535,592
<p>If you like a one-liner using <a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> and <a href="https://docs.python.org/2/library/functions.html#zip" rel="nofollow"><code>zip</code></a> (or <a href="https://docs.python.org/3.0/library/itertools.ht...
0
2016-05-31T01:39:05Z
[ "python", "python-3.x", "recursion" ]
Python Raw SQL query is returning values enclosed inside [('...'),]
37,535,467
<p>I am facing an issue while using raw SQL queries in Django.</p> <p>In views.py, the following function is defined:</p> <pre><code>def functionSQL(): from django.db import connection cursor = connection.cursor() cursor.execute('select column_name from "table_name" where CONDITION') value = cursor.f...
0
2016-05-31T01:19:45Z
37,536,173
<p>They are not <em>prefixes</em> and <em>suffixes</em>. The return value of <code>.fetchall()</code> is always a <strong>list of tuples</strong>, whether it returns a single value or multiple rows and columns. From the <a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchall.htm...
1
2016-05-31T03:00:47Z
[ "python", "django", "views", "models", "rawsql" ]
condition parameter adjustment
37,535,624
<p>I try to use 'IF' in python in order to achieve the algorithm that can automatically ajust the value of a parameter in 'IF' according to some stock trasactions. </p> <pre><code>if self.sellcount==0 and int(time.time())-self.programstarttime&gt;600: if cur_sum/total_sum&gt;0.15: Other Code else: ...
0
2016-05-31T01:45:01Z
37,535,900
<p><strong>I'd like to start with a disclaimer to be careful, stock trading is not this easy and you can lose a lot of money with a simple algorithm (just as you can with a complex one)</strong></p> <p>However, this is also a nice example to understand how to deal with running a program over time in Python and underst...
0
2016-05-31T02:25:02Z
[ "python", "algorithm", "trading" ]
taking difference of array with specific spacing in numpy
37,535,627
<p>I'm approximating a first order derivative of an array in numpy using <code>np.ediff1d</code>:</p> <pre><code>x=array([ 1, 2, 5, 10]) np.ediff1d(x) # = array([1, 3, 5]) </code></pre> <p><code>np.ediff1d</code> uses consecutive elements of the array. Is there a way to control the spacing i.e. is there a numpy fun...
1
2016-05-31T01:45:29Z
37,535,759
<p>Simply take the difference of shifted slices:</p> <pre><code>n = 2 x[n:] - x[:-n] </code></pre>
2
2016-05-31T02:03:39Z
[ "python", "arrays", "numpy", "scipy" ]
taking difference of array with specific spacing in numpy
37,535,627
<p>I'm approximating a first order derivative of an array in numpy using <code>np.ediff1d</code>:</p> <pre><code>x=array([ 1, 2, 5, 10]) np.ediff1d(x) # = array([1, 3, 5]) </code></pre> <p><code>np.ediff1d</code> uses consecutive elements of the array. Is there a way to control the spacing i.e. is there a numpy fun...
1
2016-05-31T01:45:29Z
37,535,899
<pre><code>n=2 v = [x[i+n]-x[i] for i in range(len(x)-n)] </code></pre>
2
2016-05-31T02:25:02Z
[ "python", "arrays", "numpy", "scipy" ]
How to sequentially read all the files in a directory and export the contents in Python?
37,535,644
<p>I have a directory <code>/directory/some_directory/</code> and in that directory I have a set of files. Those files are named in the following format: <code>&lt;letter&gt;-&lt;number&gt;_&lt;date&gt;-&lt;time&gt;_&lt;dataidentifier&gt;.log</code>, for example:</p> <pre><code>ABC1-123_20162005-171738_somestring.log ...
1
2016-05-31T01:47:30Z
37,535,764
<p>just use <a href="https://docs.python.org/2/library/re.html" rel="nofollow">re</a> lib to match file name pattern, and use <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> lib to export.</p>
1
2016-05-31T02:05:24Z
[ "python", "export-to-csv" ]
How to sequentially read all the files in a directory and export the contents in Python?
37,535,644
<p>I have a directory <code>/directory/some_directory/</code> and in that directory I have a set of files. Those files are named in the following format: <code>&lt;letter&gt;-&lt;number&gt;_&lt;date&gt;-&lt;time&gt;_&lt;dataidentifier&gt;.log</code>, for example:</p> <pre><code>ABC1-123_20162005-171738_somestring.log ...
1
2016-05-31T01:47:30Z
37,535,792
<p>You need code something like that:</p> <pre><code>import glob from csv import writer files = glob.glob(path) # iterate over the list getting each file for fle in files: # open the file and then call .read() to get the text with open(fle) as f, open("{}.csv".format(fle.rsplit(".", 1)[1]),"w") as out: te...
0
2016-05-31T02:08:51Z
[ "python", "export-to-csv" ]
How to sequentially read all the files in a directory and export the contents in Python?
37,535,644
<p>I have a directory <code>/directory/some_directory/</code> and in that directory I have a set of files. Those files are named in the following format: <code>&lt;letter&gt;-&lt;number&gt;_&lt;date&gt;-&lt;time&gt;_&lt;dataidentifier&gt;.log</code>, for example:</p> <pre><code>ABC1-123_20162005-171738_somestring.log ...
1
2016-05-31T01:47:30Z
37,535,817
<p>Your question could be better stated, based on your current code snipet, I'll assume that you want to:</p> <ol> <li>Filter files in a directory based on glob pattern.</li> <li>Concatenate their contents to a file named <code>output.csv</code>.</li> </ol> <p>In python you can achieve (1.) by using <a href="https://...
1
2016-05-31T02:12:29Z
[ "python", "export-to-csv" ]
How to sequentially read all the files in a directory and export the contents in Python?
37,535,644
<p>I have a directory <code>/directory/some_directory/</code> and in that directory I have a set of files. Those files are named in the following format: <code>&lt;letter&gt;-&lt;number&gt;_&lt;date&gt;-&lt;time&gt;_&lt;dataidentifier&gt;.log</code>, for example:</p> <pre><code>ABC1-123_20162005-171738_somestring.log ...
1
2016-05-31T01:47:30Z
37,535,843
<p>You can use the <code>os</code> module to list the files.</p> <pre><code>import os files = os.listdir(os.getcwd()) m_class = "ABC1" m_id = "123" device = m_class + "-" + m_id file_extension = ".log" # filter the files by their extension and the starting name files = [x for x in files if x.startswith(device) and ...
1
2016-05-31T02:16:40Z
[ "python", "export-to-csv" ]
How to sequentially read all the files in a directory and export the contents in Python?
37,535,644
<p>I have a directory <code>/directory/some_directory/</code> and in that directory I have a set of files. Those files are named in the following format: <code>&lt;letter&gt;-&lt;number&gt;_&lt;date&gt;-&lt;time&gt;_&lt;dataidentifier&gt;.log</code>, for example:</p> <pre><code>ABC1-123_20162005-171738_somestring.log ...
1
2016-05-31T01:47:30Z
37,536,035
<p>Only a few adjustments, You were close </p> <pre><code>filesFromDir = os.listdir(os.getcwd()) fileList = [file for file in filesFromDir if file.startswith(device)] f = open("LogOutput.csv", "ab") for file in fileList: #print "Processing", file with open(file, "rb") as log_file: txt = log_fi...
1
2016-05-31T02:42:18Z
[ "python", "export-to-csv" ]
Python: ftfy causes app crash when compiled to exe using pyinstaller, cx_freeze or p2exe
37,535,673
<p>Whenever I import <code>ftfy</code> and use it in my python script apps I have no problems at all.</p> <p>But if I compile to binary exe using <code>pyinstaller</code>, <code>cx_freeze</code> or <code>p2exe</code>, my app will compile without problems but crashes every time time when I run the app. </p> <p>The rea...
0
2016-05-31T01:51:21Z
37,536,924
<p>According to your log, the file looked for is <code>C:\Users\BILLTH~1\AppData\Local\Temp\_MEI64282\ftfy\char_classes.dat</code>.</p> <p>As it is a temporary directory, I guess that it is where the archive was extracted. These compiler tools create an auto-extractable zip archive which extracts the sources and the e...
0
2016-05-31T04:38:11Z
[ "python", "python-3.x" ]
Segmentation fault (core dumped) error for cifar10 example tensorflow
37,535,765
<p>I am trying to adjust the example cifar10 code and I am not sure why I have Segmentation fault (core dumped) error when I run my adjust cifar10_eval.py. It seems like this code actually works in Mac and I am not sure why it doesn't work for linux.</p> <p>Thanks for your help.</p> <p>-----------------------Below C...
0
2016-05-31T02:05:31Z
37,550,626
<p>This looks like a <a href="https://github.com/tensorflow/tensorflow/issues/1924" rel="nofollow">recurring issue</a> where the TensorFlow Python module clashes with code in the OpenCV and/or PIL libraries. The root cause is usually incompatible versions of <code>libjpeg</code> or <code>libpng</code> included in those...
2
2016-05-31T16:05:32Z
[ "python", "image", "gpu", "tensorflow", "deep-learning" ]
python generator in class
37,535,857
<p>I am learning generator from this <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">thread</a>. This is really a good example for generator. But I am confused by one of the example code.</p> <pre><code>&gt;&gt;&gt; class Bank(): # let's create a bank, building ATMs ... ...
1
2016-05-31T02:18:38Z
37,536,019
<p>The problem is coming from the fact that when you say</p> <pre><code>corner_street_atm = hsbc.create_atm() </code></pre> <p>You are calling the function once, and that is all the times it will be called. Thus, let's keep a view of what is happening</p> <pre><code> def create_atm(self): # Called right aw...
1
2016-05-31T02:40:13Z
[ "python", "class", "generator" ]
python generator in class
37,535,857
<p>I am learning generator from this <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">thread</a>. This is really a good example for generator. But I am confused by one of the example code.</p> <pre><code>&gt;&gt;&gt; class Bank(): # let's create a bank, building ATMs ... ...
1
2016-05-31T02:18:38Z
37,536,042
<p>Generally it is due to that you called the <code>corner_street_atm.next()</code> after you set the <code>hsbc.crisis=True</code>. If you do it like this, you would have no problem:</p> <pre><code>hsbc.crisis=False corner_street_atm = hsbc.create_atm() hsbc.crisis=True hsbc.crisis=False corner_street_atm.next() ...
1
2016-05-31T02:43:09Z
[ "python", "class", "generator" ]
python generator in class
37,535,857
<p>I am learning generator from this <a href="http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python">thread</a>. This is really a good example for generator. But I am confused by one of the example code.</p> <pre><code>&gt;&gt;&gt; class Bank(): # let's create a bank, building ATMs ... ...
1
2016-05-31T02:18:38Z
37,536,100
<p>The problem here is that your generator (which is a type of iterator) has been exhausted. Once it has been exhausted, an iterator should not flip back and forth between yielding values and raising the <code>StopIteration</code> (in other words your example is behaving as it should even though it isn't what you want ...
1
2016-05-31T02:51:22Z
[ "python", "class", "generator" ]
Update model from web controller Odoo v8
37,535,903
<p>I have this controller:</p> <pre><code>@route('/contrato/crear/', type='http', auth='public',website=True) def create(self, **post_data): form = CuidumForm(request.httprequest.form) form.partner_id.choices = [ (partner.id, partner.name) for partner in request.env['res.partner'].search([]) ...
1
2016-05-31T02:25:32Z
37,537,807
<p>create a new url handler <strong>/contrato/update/</strong></p> <pre><code> @route('/contrato/update/', type='http', auth='public',website=True) </code></pre> <p>Here in case of <strong>GET</strong> also render the <strong>id</strong> of model in hidden fields </p> <p>And at the time of <strong>POST</strong>(up...
1
2016-05-31T05:56:07Z
[ "python", "forms", "openerp", "qweb" ]
Python reading Wiegand dropping Zeros
37,535,905
<p>Here's the code snippet from my RFID wiegand reader on my Raspberry Pi I use already.</p> <pre><code>def main(): set_procname("Wiegand Reader") global bits global timeout GPIO.add_event_detect(D0, GPIO.FALLING, callback=one) GPIO.add_event_detect(D1, GPIO.FALLING, callback=zero) GPIO.add_eve...
0
2016-05-31T02:25:53Z
37,536,112
<p>Python will remove the front few bits if they are zero, this also applies to integers. For example</p> <pre><code>&gt;&gt;&gt; a = 0003 &gt;&gt;&gt; a 3 &gt;&gt;&gt; b = 0b0011 &gt;&gt;&gt; bin(b) 0b11 </code></pre> <p>From what I see, all RFID's will have 10 numbers. You can make a simple program to add those num...
1
2016-05-31T02:53:33Z
[ "python", "raspberry-pi2", "rfid", "wiegand" ]
Python reading Wiegand dropping Zeros
37,535,905
<p>Here's the code snippet from my RFID wiegand reader on my Raspberry Pi I use already.</p> <pre><code>def main(): set_procname("Wiegand Reader") global bits global timeout GPIO.add_event_detect(D0, GPIO.FALLING, callback=one) GPIO.add_event_detect(D1, GPIO.FALLING, callback=zero) GPIO.add_eve...
0
2016-05-31T02:25:53Z
37,542,339
<p>As mentioned already, leading zeros are removed in binary sequences and also when you explicitly convert a string to decimal using <code>int()</code>.</p> <p>What hasn't been mentioned already is that, in Python 2.x, integers with leading zeros are treated as octal values. </p> <pre><code>&gt;&gt;&gt; a = 0003 &gt...
1
2016-05-31T09:48:35Z
[ "python", "raspberry-pi2", "rfid", "wiegand" ]
Python command line print on the same lines
37,535,978
<p>There are many questions relating to printing on the same line but there aren't any for printing multiple lines on the same line within the terminal.</p> <p>For example:</p> <pre><code>ogeno@OH-ogeno-MBP:~|⇒ python my_script.py Process 1: 5% Process 2: 14% Process 3: 55% </code></pre> <p>I want the progress of ...
2
2016-05-31T02:36:05Z
37,536,235
<p>One approach is to use the <a href="https://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">ANSI escape-code</a> <code>"\033[F"</code> for going to the beginning of the previous line. The following worked well in all my terminals, just writing to the next two lines from the current terminal position:</p> <pr...
1
2016-05-31T03:08:03Z
[ "python", "shell", "terminal" ]
Python command line print on the same lines
37,535,978
<p>There are many questions relating to printing on the same line but there aren't any for printing multiple lines on the same line within the terminal.</p> <p>For example:</p> <pre><code>ogeno@OH-ogeno-MBP:~|⇒ python my_script.py Process 1: 5% Process 2: 14% Process 3: 55% </code></pre> <p>I want the progress of ...
2
2016-05-31T02:36:05Z
37,536,340
<p>for python 2.7 you can use,</p> <pre><code>print 2%, 3% # Using comma will print it in same line </code></pre> <p>for python 3.x</p> <pre><code>print('2%', end=" ") </code></pre> <p>Or you can use sys.stdout.write for doing it with sys.stdout.flush() Please check my below code, I have created a demo progress bar...
0
2016-05-31T03:24:00Z
[ "python", "shell", "terminal" ]
Python command line print on the same lines
37,535,978
<p>There are many questions relating to printing on the same line but there aren't any for printing multiple lines on the same line within the terminal.</p> <p>For example:</p> <pre><code>ogeno@OH-ogeno-MBP:~|⇒ python my_script.py Process 1: 5% Process 2: 14% Process 3: 55% </code></pre> <p>I want the progress of ...
2
2016-05-31T02:36:05Z
37,536,424
<p>This can easily be done by using backspace. Following is the sample code that will print the percentage on the same line.</p> <pre><code>import time print "Work in progress(0%%)", # Python 2 print without newline for work_done in range(10): print "\b\b\b\b\b%2d%%)" % work_done, # Backspace then overwrite ti...
0
2016-05-31T03:37:54Z
[ "python", "shell", "terminal" ]
How would I read this data structure in Perl? Dictionary/Hash with keys containing lists containing lists. Python::Inline giving me errors
37,535,999
<p>I've been struggling for about 3 weeks on this simple issue. I can't understand why and I would give anything to solve it lol.</p> <p>I am trying to read values from the data structure below. The docs say it's a dictionary with keys containing lists of results of that type.</p> <p>Example: I get the master query r...
1
2016-05-31T02:38:21Z
37,536,737
<p>OK, this isn't really an answer, but out of the goodness of my heart I cleaned up your data for you. Here is a real Python dict. I don't know if some of the numerical string values should be ints or not, so I didn't mess with them. It'll be up to you to figure out what to do with the truncated URLs.</p> <p>Another ...
1
2016-05-31T04:16:34Z
[ "python", "list", "perl", "hash", "inline" ]
How would I read this data structure in Perl? Dictionary/Hash with keys containing lists containing lists. Python::Inline giving me errors
37,535,999
<p>I've been struggling for about 3 weeks on this simple issue. I can't understand why and I would give anything to solve it lol.</p> <p>I am trying to read values from the data structure below. The docs say it's a dictionary with keys containing lists of results of that type.</p> <p>Example: I get the master query r...
1
2016-05-31T02:38:21Z
37,537,992
<p><strong>Update</strong> &nbsp; Added a comment on invalid JSON at the end.<br> <strong>Update</strong> &nbsp; Added regex that fixes JSON in a ~100Kb document linked in comments.</p> <hr> <p>I take it that the data structure shown is in <code>$googleResult</code>. This is 'almost' <code>JSON</code> and you can pro...
3
2016-05-31T06:07:24Z
[ "python", "list", "perl", "hash", "inline" ]
How would I read this data structure in Perl? Dictionary/Hash with keys containing lists containing lists. Python::Inline giving me errors
37,535,999
<p>I've been struggling for about 3 weeks on this simple issue. I can't understand why and I would give anything to solve it lol.</p> <p>I am trying to read values from the data structure below. The docs say it's a dictionary with keys containing lists of results of that type.</p> <p>Example: I get the master query r...
1
2016-05-31T02:38:21Z
37,958,546
<p>I've worked out a solution using a list comprehension like so:</p> <pre><code>use Inline::Python qw(py_eval); my $song_hits = py_eval("[x for x in $googleResult-&gt;{song_hits}]", 0); for my $hit (@$song_hits) { push @{$result-&gt;{tracks}}, to_slim_track($hit-&gt;{track}); } </code></pre> <p>The commit is at...
0
2016-06-22T04:26:56Z
[ "python", "list", "perl", "hash", "inline" ]
Understanding Asynchronous IO: vs asynchronous programming
37,536,061
<p>I'm having a difficult time understanding asynchronous IO so I hope to clear up some of my misunderstanding because the word "asynchronous" seems to be thrown in a lot. If it matters, my goal is to get into twisted python but I want a general understanding of the underlying concepts.</p> <p>What exactly is asynchro...
0
2016-05-31T02:45:36Z
37,536,473
<p>Asynchronous IO means the application isn't blocked when your computer is waiting for something. The definition of <em>waiting</em> here is not processing. Waiting for a webserver? Waiting for a network connection? Waiting for a hard drive to respond with data on a platter? All of this is IO.</p> <p>Normally, you w...
3
2016-05-31T03:43:39Z
[ "python", "node.js", "asynchronous", "io", "twisted" ]
remove line breaks from list to create a single line - Python
37,536,062
<p>I have this code, what I want it to do is take a user input of something like:</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>And turn it into: 1, 2, 3, 4, 5</p> <p>My code doesn't seem to do it, it just returns the first word in the list, any help would be amazing.</p> <hr> <pre><code>i = raw_input("P...
-2
2016-05-31T02:45:50Z
37,536,098
<p><code>raw_input()</code> echos the text entered by an user, including the trailing newline. That means whatever the user has typed will be returned to standard output.</p> <p>Possible solution <a href="http://stackoverflow.com/a/36210179/2666859">http://stackoverflow.com/a/36210179/2666859</a></p>
0
2016-05-31T02:50:54Z
[ "python", "list", "shell", "replace", "terminal" ]
remove line breaks from list to create a single line - Python
37,536,062
<p>I have this code, what I want it to do is take a user input of something like:</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>And turn it into: 1, 2, 3, 4, 5</p> <p>My code doesn't seem to do it, it just returns the first word in the list, any help would be amazing.</p> <hr> <pre><code>i = raw_input("P...
-2
2016-05-31T02:45:50Z
37,536,135
<p>When the user press enter after the 1 raw_input stops reading.</p> <p>Take a look at this question to see how to read multiple lines</p> <p><a href="http://stackoverflow.com/questions/11664443/raw-input-across-multiple-lines-in-python">Raw input across multiple lines in Python</a></p>
0
2016-05-31T02:55:45Z
[ "python", "list", "shell", "replace", "terminal" ]
remove line breaks from list to create a single line - Python
37,536,062
<p>I have this code, what I want it to do is take a user input of something like:</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>And turn it into: 1, 2, 3, 4, 5</p> <p>My code doesn't seem to do it, it just returns the first word in the list, any help would be amazing.</p> <hr> <pre><code>i = raw_input("P...
-2
2016-05-31T02:45:50Z
37,536,187
<p>You can write a simple loop and break with some specified command. For example</p> <pre><code>break_command = 'q' values = [] while True: i = raw_input("Type a number (or q to exit): ") if (i==break_command): break values.append(i) </code></pre>
0
2016-05-31T03:03:33Z
[ "python", "list", "shell", "replace", "terminal" ]
remove line breaks from list to create a single line - Python
37,536,062
<p>I have this code, what I want it to do is take a user input of something like:</p> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>And turn it into: 1, 2, 3, 4, 5</p> <p>My code doesn't seem to do it, it just returns the first word in the list, any help would be amazing.</p> <hr> <pre><code>i = raw_input("P...
-2
2016-05-31T02:45:50Z
37,536,584
<p>If you want to take multiple user inputs, put all the inputs into a list, and then print out the list, try this:</p> <pre><code>listX = [] #An empty list for x in range(y): #Where y in the number of times you want the user to enter the input listX.append(raw_input("Your message here: "))...
0
2016-05-31T03:57:31Z
[ "python", "list", "shell", "replace", "terminal" ]
Directly use Intel mkl library on Scipy sparse matrix to calculate A dot A.T with less memory
37,536,106
<p>I want to call <a href="https://software.intel.com/en-us/node/468640" rel="nofollow">mkl.mkl_scsrmultcsr</a> from python. The goal is to calculate a sparse matrix C in <a href="http://docs.scipy.org/doc/scipy-0.17.0/reference/generated/scipy.sparse.csr_matrix.html" rel="nofollow">compressed sparse row</a> format. Sp...
0
2016-05-31T02:51:54Z
37,540,149
<p>Look at the Python code for the scipy sparse product. Notice that it calls the compiled code in 2 passes.</p> <p>It looks like the mkl code does the same thing</p> <p><a href="https://software.intel.com/en-us/node/468640" rel="nofollow">https://software.intel.com/en-us/node/468640</a></p> <blockquote> <p>If re...
1
2016-05-31T08:04:04Z
[ "python", "scipy", "ctypes", "sparse-matrix", "intel-mkl" ]
PyXero Library Validation Exception
37,536,369
<p>I'm trying to add a payment to xero using the pyxero python library for python3. I'm able to add invoices and contacts, but payments always returns a validation exception. Here is the data I'm submitting:</p> <pre><code>payments.put([{'Amount': '20.00', 'Date': datetime.date(2016, 5, 25), ...
0
2016-05-31T03:29:10Z
37,579,794
<p>Please note: this solution became a hack inside pyxero to get the result I needed. This may not be the best solution for you.</p> <p>The XML that pyxero generates for "payments.put" does not match the "<a href="https://developer.xero.com/documentation/api/payments/" rel="nofollow">PUT Payments</a>" XML structure fo...
0
2016-06-01T22:27:04Z
[ "python", "xero-api" ]
list(set) for nested lists?
37,536,419
<p>I am currently working on a module that will compute the angle between a vector and the normal of a plane.</p> <p>Anyhow to satisfy the conditions of computing the normal to the plane, I need 3 points in R3.</p> <p>I have found a way to do this by converting the list elements to strings, however this complicates t...
0
2016-05-31T03:37:07Z
37,536,459
<p>Cast your mutable, non-hashable lists to immutable, hashable tuples which can be used as elements for a <code>set</code>:</p> <pre><code>new_t1 = list(set(map(tuple, t1))) new_t1.sort(key=t1.index) # preserves order of first occurrence in original list new_t1 = [list(x) for x in new_t1] # back to list of lists </...
0
2016-05-31T03:41:38Z
[ "python", "math" ]