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
counting number of elements in a list
38,106,368
<p>I have a list</p> <pre><code>my_list = ['TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC', 'TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC', 'AGCTCCCCGTTTTC,AGCTCCCCGTTTTC...
0
2016-06-29T17:26:15Z
38,106,428
<p><strong>Instead of using for loop this solution has better time-complexity</strong> </p> <pre><code>from collections import Counter my_list = ['TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC', 'TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTAT...
1
2016-06-29T17:29:36Z
[ "python" ]
counting number of elements in a list
38,106,368
<p>I have a list</p> <pre><code>my_list = ['TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC', 'TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC,TTATGCTAAGTATC', 'AGCTCCCCGTTTTC,AGCTCCCCGTTTTC...
0
2016-06-29T17:26:15Z
38,106,577
<p>For me it comes down to what the OP means by <em>word</em>. My interpretation is as follows:</p> <pre><code>for string in my_list: print(Counter(string.split(',')).most_common()) </code></pre> <p>producing:</p> <pre><code>[('TTATGCTAAGTATC', 8)] [('TTATGCTAAGTATC', 8)] [('AGCTCCCCGTTTTC', 2)] </code></pre>
3
2016-06-29T17:38:18Z
[ "python" ]
Converting to Emoji
38,106,422
<p>so I am trying to take this data that uses unicode indicators and make it print with emojis. It is currently in a txt. file but I will write to an excel file later. So anyways I am getting an error I am not sure what to do with. This is the text I am reading:</p> <pre><code>"Thanks @UglyGod \ud83d\ude4f https:\\/\\...
2
2016-06-29T17:29:14Z
38,107,222
<p>Your emoji 🙏 is represented as a <a href="https://en.wikipedia.org/wiki/Universal_Character_Set_characters#Surrogates" rel="nofollow">surrogate pair</a>, see also <a href="http://apps.timwhitlock.info/unicode/inspect?s=%F0%9F%99%8F" rel="nofollow">here</a> for info about this particular glyph. Python cannot dec...
2
2016-06-29T18:14:56Z
[ "python", "unicode", "python-3.5", "emoji" ]
Converting to Emoji
38,106,422
<p>so I am trying to take this data that uses unicode indicators and make it print with emojis. It is currently in a txt. file but I will write to an excel file later. So anyways I am getting an error I am not sure what to do with. This is the text I am reading:</p> <pre><code>"Thanks @UglyGod \ud83d\ude4f https:\\/\\...
2
2016-06-29T17:29:14Z
38,145,581
<blockquote> <p>This is how the data was originally generated... <code>saveFile.write(json.dumps(data) + "\n")</code></p> </blockquote> <p>You should use <code>json.loads()</code> instead of <code>.decode('unicode-escape')</code> to read JSON text:</p> <pre><code>#!/usr/bin/env python3 import json with open('tweet...
1
2016-07-01T12:34:19Z
[ "python", "unicode", "python-3.5", "emoji" ]
Creating graph using dictionaries and nodes only
38,106,529
<p>I have this data.</p> <pre><code>CITY1 CITY2 A B A C A D B C B D C D </code></pre> <p>How i can create dictionary looking like this from the above data</p> <pre><code>x={A:[B,C,D], B:[A,C,D], C:[A,B,D], D:[A,B,C] } </code></pre> <p>Thanks </p>
-1
2016-06-29T17:35:17Z
38,106,715
<p>Is it in a csv? It looks like, from the data you provide, you are doing an undirected graph. Assuming that the data is in some kind of "row" type format that you can loop through, (i.e. row[0] is the city1 value, and row[1] is the city2 value):</p> <pre><code>from collections import defaultdict def make_graph(da...
1
2016-06-29T17:46:21Z
[ "python", "dictionary", "graph", "nodes" ]
Creating graph using dictionaries and nodes only
38,106,529
<p>I have this data.</p> <pre><code>CITY1 CITY2 A B A C A D B C B D C D </code></pre> <p>How i can create dictionary looking like this from the above data</p> <pre><code>x={A:[B,C,D], B:[A,C,D], C:[A,B,D], D:[A,B,C] } </code></pre> <p>Thanks </p>
-1
2016-06-29T17:35:17Z
38,107,746
<p>I was trying to do it without any library import. I made a simple dictionary first .</p> <pre><code>x={'A':['B','C','D'],'B':['C','D'],'C':['D']} for i,j in x.items(): for p in j: if p not in x.keys(): x[p]=[] if p in x[i] and i not in x[p]: x[p].append(i) print x...
0
2016-06-29T18:43:57Z
[ "python", "dictionary", "graph", "nodes" ]
How do I get a periodic curve fit from discrete data in python?
38,106,569
<p>I wand to do integration on a dynamic system like to the ODE</p> <pre><code>x_ddot + d*x_dot + k*x = a*sin(omega*t) </code></pre> <p>with one modification: The external force a * sin(omega * t) must be replaced by another periodic signal which is based on some measurement data. That means: I need do curve fitting ...
2
2016-06-29T17:38:00Z
38,107,727
<p>If you are content with a numerical function, a simple approach based on interpolation is the following:</p> <p>Step 1: Define an interpolation function based on the data set, which determines one period of the function. (I used the simple <code>interp1d</code> from Scipy, more elaborate alternatives are also avail...
3
2016-06-29T18:42:55Z
[ "python", "numpy" ]
How can I ignore the exception in Selenium?
38,106,678
<p>I use <strong>Python Selenium</strong> for scraping a website, but my crawler stopped because of a exception:</p> <blockquote> <p><code>StaleElementReferenceException</code>: Message: stale element reference: element is not attached to the page document</p> </blockquote> <p>How can i continue to crawl even if t...
1
2016-06-29T17:43:26Z
38,106,727
<p>Put a try-except block around the piece of code that produced that error.</p>
3
2016-06-29T17:47:14Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "web-crawler" ]
How can I ignore the exception in Selenium?
38,106,678
<p>I use <strong>Python Selenium</strong> for scraping a website, but my crawler stopped because of a exception:</p> <blockquote> <p><code>StaleElementReferenceException</code>: Message: stale element reference: element is not attached to the page document</p> </blockquote> <p>How can i continue to crawl even if t...
1
2016-06-29T17:43:26Z
38,107,150
<p>To be more specific about what John Gordon is talking about. Handle the <a href="http://selenium-python.readthedocs.io/api.html#selenium.common.exceptions.StaleElementReferenceException" rel="nofollow"><code>StaleElementReferenceException</code></a> common selenium exception and ignore it:</p> <pre><code>from selen...
3
2016-06-29T18:11:07Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "web-crawler" ]
How can I ignore the exception in Selenium?
38,106,678
<p>I use <strong>Python Selenium</strong> for scraping a website, but my crawler stopped because of a exception:</p> <blockquote> <p><code>StaleElementReferenceException</code>: Message: stale element reference: element is not attached to the page document</p> </blockquote> <p>How can i continue to crawl even if t...
1
2016-06-29T17:43:26Z
38,155,908
<p>It looks like the browser rendering engine or Javascript engine is using the element and it is blocking other external operations on this element. You can attempt to access it after some time. If it is not accessible for longer duration, an exception can be thrown. Some good examples are given <a href="http://darrel...
0
2016-07-02T02:20:16Z
[ "python", "selenium", "selenium-webdriver", "web-scraping", "web-crawler" ]
Django-RQ: How to call function?
38,106,696
<p>I am migrating a project to <code>Django</code> and like to use the <a href="https://github.com/ui/django-rq" rel="nofollow"><strong><code>django-rq</code></strong></a> module.<br> However, I am stuck at what to put here:</p> <pre><code>import django_rq queue = django_rq.get_queue('high') queue.enqueue(func, foo, b...
2
2016-06-29T17:44:58Z
38,106,908
<p>Create tasks.py file to include</p> <pre><code>from django_rq import job @job("high", timeout=600) # timeout is optional def your_func(): pass # do some logic </code></pre> <p>and then in your code</p> <pre><code>import django_rq from tasks import your_func queue = django_rq.get_queue('high') queue.en...
2
2016-06-29T17:57:15Z
[ "python", "django", "redis", "django-rq" ]
matplotlib - How to save an array as image with overlayed text?
38,106,701
<p>I have a 2D array that I need to save as a <code>png</code>. I also need to add a text label to the image. So far, I have tried two approaches, none of which is optimal: </p> <ul> <li><p>I use the <code>matplotlib.image</code> module to save the array directly as an image: </p> <pre><code>matplotlib.image.imsave...
1
2016-06-29T17:45:24Z
38,428,018
<p>I was able to solve my problem by using an object oriented approach from the start: </p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure(dpi=100, tight_layout=True, frameon=False, figsize=(resolution/100.,resolution/100.)) # dpi &amp; figsize of my choosing fig.figimage(ARRAY, cmap=plt.cm.binary) fig.t...
0
2016-07-18T03:02:54Z
[ "python", "image", "matplotlib" ]
Plotting Multiple Histograms in Matplotlib - Colors or side-by-side bars
38,106,730
<p><strong>Problem : When Plotting Multiple Histograms in Matplotlib, i cannot differentiate a plot from another</strong></p> <p><strong>Problem as Image : ** <a href="http://i.stack.imgur.com/xe2Zr.png" rel="nofollow"><img src="http://i.stack.imgur.com/xe2Zr.png" alt="Problem"></a> **Minor Problem : The left label 'C...
3
2016-06-29T17:47:25Z
38,107,296
<p>I tried and came up with this. You can change the xticks position in the code. Simply what you have to do is pass on a tuple to the <code>plt.hist</code>, can't be more simple right !? So lets suppose you have two lists of 0s and 1s, so what you gotta do is -</p> <pre><code>a = np.random.randint(2, size=1000) b = n...
3
2016-06-29T18:19:17Z
[ "python", "matplotlib", "histogram", "matplotlib-basemap" ]
Plotting Multiple Histograms in Matplotlib - Colors or side-by-side bars
38,106,730
<p><strong>Problem : When Plotting Multiple Histograms in Matplotlib, i cannot differentiate a plot from another</strong></p> <p><strong>Problem as Image : ** <a href="http://i.stack.imgur.com/xe2Zr.png" rel="nofollow"><img src="http://i.stack.imgur.com/xe2Zr.png" alt="Problem"></a> **Minor Problem : The left label 'C...
3
2016-06-29T17:47:25Z
38,171,574
<p>If your datasets are of equal length, you might be able to do this easily with pandas. So assuming you have</p> <pre><code>import numpy N = 1000 train, validation, test = [numpy.random.randint(2, size=N) for _ in range(3)] Y = [train, validation, test] </code></pre> <p>You can simply do</p> <pre><code>import pan...
1
2016-07-03T15:41:28Z
[ "python", "matplotlib", "histogram", "matplotlib-basemap" ]
Python equivalent of Matlab addpath
38,106,749
<p>Does python have an equivalent to Matlab's addpath? I know about sys.path.append, but that only seems to work for python files/modules, not for general files.</p> <p>Suppose I have a file config.txt in C:\Data and the current working directory is something else, say D:\my_project.</p> <p>I would like to have code...
0
2016-06-29T17:48:19Z
38,106,797
<pre><code>def foo(prefix): path = prefix + 'config.txt' with open(path) as f: print(f.read()) def main(): foo(r'C:\Data\') </code></pre> <p>---update----</p> <pre><code>import os class changeFileDir: def __init__(self, path): self.path= os.path.expanduser(path) def __enter__(se...
0
2016-06-29T17:51:03Z
[ "python", "matlab", "directory" ]
Python equivalent of Matlab addpath
38,106,749
<p>Does python have an equivalent to Matlab's addpath? I know about sys.path.append, but that only seems to work for python files/modules, not for general files.</p> <p>Suppose I have a file config.txt in C:\Data and the current working directory is something else, say D:\my_project.</p> <p>I would like to have code...
0
2016-06-29T17:48:19Z
38,106,831
<p>You can't add multiple paths like you would in matlab.</p> <p>You can use <code>os.chdir</code> to change directories, and access files and sub-directories from that directory:</p> <pre><code>import os def foo(): with open('config.txt') as f: print(f.read()) def main(): os.chdir(r'C:\Data') f...
4
2016-06-29T17:53:22Z
[ "python", "matlab", "directory" ]
Python equivalent of Matlab addpath
38,106,749
<p>Does python have an equivalent to Matlab's addpath? I know about sys.path.append, but that only seems to work for python files/modules, not for general files.</p> <p>Suppose I have a file config.txt in C:\Data and the current working directory is something else, say D:\my_project.</p> <p>I would like to have code...
0
2016-06-29T17:48:19Z
38,107,264
<p>You can use the <code>os.chdir</code> functionality along with your own <code>open</code> function to check all the paths you want to.</p> <pre><code>class FileOpener(object): def __init__(self): self.paths = [] def add_path(self, path): self.paths.append(path) def __open_path(self, path...
0
2016-06-29T18:17:09Z
[ "python", "matlab", "directory" ]
Python equivalent of Matlab addpath
38,106,749
<p>Does python have an equivalent to Matlab's addpath? I know about sys.path.append, but that only seems to work for python files/modules, not for general files.</p> <p>Suppose I have a file config.txt in C:\Data and the current working directory is something else, say D:\my_project.</p> <p>I would like to have code...
0
2016-06-29T17:48:19Z
38,113,209
<p>No, it doesn't. Python doesn't work this way. Files are loaded from the current working directory or a specific, resolved path. There is no such thing as a set of pre-defined paths for loading arbitrary files. </p> <p>Keeping data and program logic separate is an important concept in Python (and most other prog...
1
2016-06-30T02:54:12Z
[ "python", "matlab", "directory" ]
NameError: name 'n' is not defined in python script
38,106,769
<p>I'm trying to run a python script that is optimized to work with python 2.7:</p> <pre><code> #!/usr/bin/env python import sys,getopt,os SplitInput_string = """#!/bin/bash #BSUB -J SplitInput[1-%numSamples%] #BSUB -o Logs/SplitInput-Out-%I.out #BSUB -e Logs/SplitInput-Err-%I.err #BSUB -q week #BSUB -W 23:58 echo D...
0
2016-06-29T17:49:41Z
38,106,799
<p><code>n</code> is not defined in all code paths. It is only defined if you follow the path:</p> <pre><code>elif opt in ('-n'): </code></pre> <p>Define <code>m</code> at a higher scope (i.e. before the for loop) with a default value if you want to use it afterwards.</p> <pre><code>n = #default value for opt, arg i...
1
2016-06-29T17:51:16Z
[ "python" ]
NameError: name 'n' is not defined in python script
38,106,769
<p>I'm trying to run a python script that is optimized to work with python 2.7:</p> <pre><code> #!/usr/bin/env python import sys,getopt,os SplitInput_string = """#!/bin/bash #BSUB -J SplitInput[1-%numSamples%] #BSUB -o Logs/SplitInput-Out-%I.out #BSUB -e Logs/SplitInput-Err-%I.err #BSUB -q week #BSUB -W 23:58 echo D...
0
2016-06-29T17:49:41Z
38,106,809
<p>You must assign a value to <code>n</code> before entering the loop.</p> <pre><code>if __name__ == "__main__": try: opts, args = getopt.getopt(sys.argv[1:],'hi:n:',["inputdir="]) except: print help_message sys.exit(2) n = "" for opt, arg in opts: etc... </code></pre>
1
2016-06-29T17:52:01Z
[ "python" ]
Reading unicode characters from file/sqlite database and using it in Python
38,106,808
<p>I have a list of variables with unicode characters, some of them for chemicals like Ozone gas: like 'O\u2083'. All of them are stored in a sqlite database which is read in a Python code to produce O<sub>3</sub>. However, when I read I get 'O\\u2083'. The sqlite database is created using an csv file that contains the...
0
2016-06-29T17:51:50Z
38,107,307
<p>It's important to remember everything is bytes. To pull bytes into something useful to you, you kind of have to know what encoding is used when you pull in data. There are too many ambiguous cases to determine encoding by analyzing the data. When you send data out of your program, it's all back out to bytes again. D...
1
2016-06-29T18:19:40Z
[ "python", "sqlite", "unicode" ]
Reading unicode characters from file/sqlite database and using it in Python
38,106,808
<p>I have a list of variables with unicode characters, some of them for chemicals like Ozone gas: like 'O\u2083'. All of them are stored in a sqlite database which is read in a Python code to produce O<sub>3</sub>. However, when I read I get 'O\\u2083'. The sqlite database is created using an csv file that contains the...
0
2016-06-29T17:51:50Z
38,112,183
<p>If you have a byte string (length 7), decode the Unicode escape.</p> <pre><code>&gt;&gt;&gt; s = 'O\u2083' &gt;&gt;&gt; len(s) 7 &gt;&gt;&gt; s 'O\\u2083' &gt;&gt;&gt; print(s) O\u2083 &gt;&gt;&gt; u = s.decode('unicode-escape') &gt;&gt;&gt; len(u) 2 &gt;&gt;&gt; u u'O\u2083' &gt;&gt;&gt; print(u) O₃ </code></pre...
1
2016-06-30T00:34:07Z
[ "python", "sqlite", "unicode" ]
Reading unicode characters from file/sqlite database and using it in Python
38,106,808
<p>I have a list of variables with unicode characters, some of them for chemicals like Ozone gas: like 'O\u2083'. All of them are stored in a sqlite database which is read in a Python code to produce O<sub>3</sub>. However, when I read I get 'O\\u2083'. The sqlite database is created using an csv file that contains the...
0
2016-06-29T17:51:50Z
38,146,103
<p>SQLite allows you to read/write Unicode text directly. <code>u'O\u2083'</code> is <em>two</em> characters <code>u'O'</code> and <code>u'\u2083'</code> (your question has a typo: <code>'u\2083' != '\u2083'</code>).</p> <blockquote> <p>I understand that u\2083 is not being stored in sqlite database as unicode chara...
1
2016-07-01T12:59:54Z
[ "python", "sqlite", "unicode" ]
Reading large file in Spark issue - python
38,106,820
<p>I have spark installed in local, with python, and when running the following code:</p> <pre><code>data=sc.textFile('C:\\Users\\xxxx\\Desktop\\train.csv') data.first() </code></pre> <p>I get the following error:</p> <pre><code>--------------------------------------------------------------------------- Py4JJavaErro...
5
2016-06-29T17:52:50Z
38,260,668
<p>Whether you are using Spark in the standalone mode or the cluster mode, the <code>spark.driver.memory</code> and <code>spark.executor.memory</code> defaults to 1GB of memory. You can add more memory to both the <code>driver</code> and <code>executors</code> by changing this configuration while starting your Jupyter ...
3
2016-07-08T06:58:41Z
[ "python", "apache-spark" ]
Reading large file in Spark issue - python
38,106,820
<p>I have spark installed in local, with python, and when running the following code:</p> <pre><code>data=sc.textFile('C:\\Users\\xxxx\\Desktop\\train.csv') data.first() </code></pre> <p>I get the following error:</p> <pre><code>--------------------------------------------------------------------------- Py4JJavaErro...
5
2016-06-29T17:52:50Z
38,278,036
<p>As seen in the <a href="http://spark.apache.org/docs/latest/configuration.html" rel="nofollow">spark documentation</a> the default maximum values for the memory usage are set to 1GB.</p> <p>You can see the defaults in spark configuration file, if in linux might be located in:</p> <pre><code>/etc/spark/conf/spark-d...
2
2016-07-09T03:37:58Z
[ "python", "apache-spark" ]
'while read line' assume enter key is pressed and only executes one iteration, but 'for line in blah' works approropriately
38,106,911
<p>I have a python script that I'm executing in the terminal. The python script does some things in the background, and then waits (using a raw_input) for an "enter" key to be pressed before continuing. </p> <p>For simplicity sake, let's say the python script is the following:</p> <pre><code>import sys print 'PRESS E...
0
2016-06-29T17:57:22Z
38,107,467
<p><code>raw_input</code> reads from standard input. In your test, that input is inherited from the loop from which the script is run, so it <em>also</em> reads from the <code>echo</code> statement, not the keyboard. Also, Python uses buffered input by default; even though <code>raw_input</code> only <em>returns</em> a...
1
2016-06-29T18:28:41Z
[ "python", "bash", "python-2.7" ]
Why can't std::ref be used to pass objects into Boost.Python modules?
38,106,936
<p>Environment: Boost 1.61.0 compiled with Python 3.5</p> <p>The following C++ code outputs <code>12</code>:</p> <pre class="lang-cpp prettyprint-override"><code>class A { public: int func() { return 12; } }; BOOST_PYTHON_MODULE(bridge) { using namespace boost::python; class_&lt;A&gt;("A", no_init) ...
3
2016-06-29T17:59:22Z
38,107,504
<p>Nice article about <a href="https://misspent.wordpress.com/2009/10/11/boost-python-and-handling-python-exceptions/" rel="nofollow">handling python exceptions in C++</a>. Any way I guess python through exception <code>AttributeError</code> because of difference in <code>reference_wrapper</code> implementations in <a ...
0
2016-06-29T18:30:29Z
[ "python", "c++", "boost", "boost-python", "boost-ref" ]
Why Does This Python Function Print Twice?
38,106,947
<p>I'm not able to walk through as to why this code prints 'spam' twice.</p> <pre><code>def do_twice(f): f() f() def print_spam(): print('spam') do_twice(print_spam) </code></pre>
-16
2016-06-29T17:59:56Z
38,106,968
<p><code>do_twice(print_spam)</code> calls <code>print_spam</code> twice, and <code>print_spam</code> prints out <code>'spam'</code>, so that's why the code prints it out twice</p>
0
2016-06-29T18:01:13Z
[ "python" ]
Why Does This Python Function Print Twice?
38,106,947
<p>I'm not able to walk through as to why this code prints 'spam' twice.</p> <pre><code>def do_twice(f): f() f() def print_spam(): print('spam') do_twice(print_spam) </code></pre>
-16
2016-06-29T17:59:56Z
38,107,008
<p><code>print_spam</code> is a function object being passed in do_twice function. You are calling the function object with <code>function_object()</code></p>
1
2016-06-29T18:03:13Z
[ "python" ]
Why Does This Python Function Print Twice?
38,106,947
<p>I'm not able to walk through as to why this code prints 'spam' twice.</p> <pre><code>def do_twice(f): f() f() def print_spam(): print('spam') do_twice(print_spam) </code></pre>
-16
2016-06-29T17:59:56Z
38,107,101
<p>Let's split your code...</p> <p><strong>Part1</strong>: create function <code>do_twice(f)</code>, that will run <code>f()</code> two times.</p> <pre><code>def do_twice(f): f() f() </code></pre> <p><strong>Part2</strong>: create a function called <code>print_spam()</code> that will <code>print()</code> the...
7
2016-06-29T18:07:47Z
[ "python" ]
Pygame make a circle rotate around another
38,106,957
<p>I would like to make some kind of solar system in pygame. I've managed to do a fixed one but I thought it would be more interesting to do one with planets moving around the sun and moons around planets etc. Is there a way I could do that (using pygame if possible)?</p> <p>What I would like is : </p> <pre><code>Sun...
1
2016-06-29T18:00:25Z
38,107,556
<p>Coordinates of a planet rotated about the Sun through some angle with respect to the X-axis are <a href="http://i.stack.imgur.com/kjNh5.gif" rel="nofollow"><img src="http://i.stack.imgur.com/kjNh5.gif" alt="enter image description here"></a>, where <code>r</code> is the distance to the Sun, <code>theta</code> is tha...
0
2016-06-29T18:33:14Z
[ "python", "rotation", "position", "geometry", "pygame" ]
Pygame make a circle rotate around another
38,106,957
<p>I would like to make some kind of solar system in pygame. I've managed to do a fixed one but I thought it would be more interesting to do one with planets moving around the sun and moons around planets etc. Is there a way I could do that (using pygame if possible)?</p> <p>What I would like is : </p> <pre><code>Sun...
1
2016-06-29T18:00:25Z
38,107,871
<p>You can implement gravity with Newton's Law of Universal Gravitation and Newton's Second Law to get the accelerations of the planets. Give each planet an initial position, velocity and mass. Acceleration is change in velocity <code>a = v * dt</code>, velocity is change in position <code>v = r * dt</code>, so we can ...
0
2016-06-29T18:51:20Z
[ "python", "rotation", "position", "geometry", "pygame" ]
selenium wait until html is reloaded
38,107,184
<p>I have a script with python and selenium to scrape google results.. It works, but I'm looking for a better solution to wait until all <code>100</code> search results are fetched</p> <p>I use this solution to wait until the search is done</p> <pre><code>driver.wait.until(EC.presence_of_element_located( (By.ID, ...
1
2016-06-29T18:12:48Z
38,107,288
<p>You are absolutely right that <em><code>time.sleep(5)</code> is not a reliable and good way to wait for something on the page</em>. You would need to use <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow"><code>WebDriverWait</code> class</a> and a specific condition to wait for....
2
2016-06-29T18:18:55Z
[ "python", "selenium" ]
Pandas: Changing a specific row to percentages
38,107,304
<p>I have a row in a Pandas Data frame that contains the sales rate of my items.</p> <p>A look at my data:</p> <pre><code>block_combine Out[78]: END_MONTH 1 2 3 4 5 Total Listings 168 219 185 89 112 Total Sales 85 85 84 41 46 </code></pre> <p>I can easily calculate the sales % by...
3
2016-06-29T18:19:33Z
38,107,465
<p>You could use <code>.apply('{:.0%}'.format)</code>:</p> <pre><code>import pandas as pd df = pd.DataFrame([(168,219,185,89,112), (85,85,84,41,46)], index=['Total Listings', 'Total Sales'], columns=list(range(1,6))) df.loc['Total Sales Rate'] = ((df.loc['Total Sales']/df.loc['Total Listings']) ...
6
2016-06-29T18:28:30Z
[ "python", "pandas", "dataframe" ]
Pandas: Changing a specific row to percentages
38,107,304
<p>I have a row in a Pandas Data frame that contains the sales rate of my items.</p> <p>A look at my data:</p> <pre><code>block_combine Out[78]: END_MONTH 1 2 3 4 5 Total Listings 168 219 185 89 112 Total Sales 85 85 84 41 46 </code></pre> <p>I can easily calculate the sales % by...
3
2016-06-29T18:19:33Z
38,107,514
<pre><code>df = pd.DataFrame({ 1: [168,85], 2: [219,85], 3: [185,84], 4: [89,41], 5: [112,46] }, index=['Total Listings', 'Total Sales']) total_sales_rate = pd.Series(df.loc['Total Sales'] / df.loc['Total Listings'] * 100, name='Total Sales Rate').round() df = df.appen...
0
2016-06-29T18:31:03Z
[ "python", "pandas", "dataframe" ]
Merge 2 Pandas DataFrame, Take One Record Over Another if Index Matches
38,107,344
<p>I want to merge two Pandas DataFrames, but anywhere an index matches I only want to merge in the row from a specific <code>df</code>.</p> <p>So if I have</p> <pre><code>df1 A B type model apple v1 10 xyz orange v2 11 pqs df2 A B type model apple v3 11 xyz grape v4 12...
3
2016-06-29T18:21:42Z
38,107,446
<p>you can try this if you want to preserve NaN's in the <code>df1</code>'s cells or if you have a multiindex, for which you would receive: <code>NotImplementedError: merging with both multi-indexes is not implemented</code> when using <code>combine_first()</code>:</p> <pre><code>In [53]: df1 Out[53]: A ...
1
2016-06-29T18:27:02Z
[ "python", "pandas" ]
Merge 2 Pandas DataFrame, Take One Record Over Another if Index Matches
38,107,344
<p>I want to merge two Pandas DataFrames, but anywhere an index matches I only want to merge in the row from a specific <code>df</code>.</p> <p>So if I have</p> <pre><code>df1 A B type model apple v1 10 xyz orange v2 11 pqs df2 A B type model apple v3 11 xyz grape v4 12...
3
2016-06-29T18:21:42Z
38,107,589
<p>That's what <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>DataFrame.combine_first()</code></a> is for:</p> <pre><code>import pandas as pd df1 = pd.DataFrame({'A': [10, 11], 'B': ['xyz', 'pqs']}, index=['apple', 'orange']) df2 = pd.DataFrame...
3
2016-06-29T18:35:09Z
[ "python", "pandas" ]
Python-Pandas url request not returning all data
38,107,381
<p>I'm trying to get all the weather data from a website, but for some reason, I am not getting all the data. In the middle of the returned data, there are four missing lines. I'm missing lines 30-33.</p> <pre><code>import pandas as pd url2 = 'http://www.intellicast.com/Local/Observation.aspx?unit=F&amp;location=USMS0...
0
2016-06-29T18:23:58Z
38,108,255
<p>The rows are not missing. They are hidden by pandas because of the display settings. You can change the display settings with:</p> <pre><code>import pandas as pd pd.set_option('max_rows',100) #To display 100 rows </code></pre> <p>Also, the output of the call returns 2 dataframes and you want the second one. So, do...
0
2016-06-29T19:14:37Z
[ "python" ]
Python, Matplotlib: Suptitle with arbitrary number of vertical figures
38,107,451
<p>I have a website that produces (depending on available data stations running) an arbitrary number of plots (as an image), that are vertically stacked over one another. An example is the following:</p> <p><a href="http://i.stack.imgur.com/05tpMm.png" rel="nofollow"><img src="http://i.stack.imgur.com/05tpMm.png" alt=...
2
2016-06-29T18:27:26Z
38,109,732
<p>I suggest trying something manual: adding text annotation with position in units of the figure relative coordinates.</p> <p>Consider these two dummy examples:</p> <pre><code>hf,ax = plt.subplots(nrows=3) hf.text(0.5,0.92, "Hi there, this is the first line\nAnd this is the second!!!", horizontalalig...
1
2016-06-29T20:45:57Z
[ "python", "matplotlib", "plot", "spacing", "suptitle" ]
Handling multiple clients with twisted and spyne
38,107,473
<p>I'm trying to create a simple python server that can handle multiple RCP calls at the same time. I would like to use twisted for the networking and spyne to handle the RPCs. I found a good example in the spyne github repo <a href="https://github.com/arskom/spyne/blob/master/examples/twisted/resource.py" rel="nofollo...
0
2016-06-29T18:28:55Z
38,124,296
<p>This is fixed and will be released as part of Spyne 2.13.</p> <p>You can use code from the master branch of <a href="http://github.com/arskom/spyne" rel="nofollow">http://github.com/arskom/spyne</a> if you can't wait an indefinite amount of time until the release. Code only gets merged there if it passes all tests....
0
2016-06-30T13:15:37Z
[ "python", "twisted", "spyne" ]
How do I maintain the order when splitting a string?
38,107,483
<p>I am trying to create an ordered dictionary from a split string. How do I maintain the order of the split string? Sorry, my original example was confusing and contradicted the idea of an ordered dictionary. This is a different problem but I am not sure how to split the string as such.</p> <p>My sample file "practic...
0
2016-06-29T18:29:32Z
38,107,674
<p>The problem isn't with the OrderedDict, it's with your <code>for</code> loop. Your loop does the following:</p> <p>points ' text for chapter 1 ' to '\xc2\xa7' # in the dict as is</p> <p>points '\xc2\xa7' to ' text for chapter 2 ' # this gets overwritten</p> <p>points ' text for chapter 2 ' to '\xc2\xa7' # in the...
1
2016-06-29T18:39:28Z
[ "python", "list", "ordereddictionary" ]
How do I maintain the order when splitting a string?
38,107,483
<p>I am trying to create an ordered dictionary from a split string. How do I maintain the order of the split string? Sorry, my original example was confusing and contradicted the idea of an ordered dictionary. This is a different problem but I am not sure how to split the string as such.</p> <p>My sample file "practic...
0
2016-06-29T18:29:32Z
38,107,685
<p>From my understanding of your code your loop is incorrect. You want the first <code>§</code> with the first text entry. You also want to skip the <code>§</code> elements as a key to your dictionary, therefore you need a step of 2 for the loop. Finally, you may want to strip spaces off the start/end of the text.</...
2
2016-06-29T18:40:17Z
[ "python", "list", "ordereddictionary" ]
Memory order behavior issue when converting numpy array to QImage
38,107,493
<p>I have a simple viewer in PyQt4, and I'm having some strange behavior when converting from a numpy array (8-bit grayscale) to a QImage to display. It seems to me like something is going haywire when I try to construct a QImage from a transposed array, even though the memory order should have been updated (i.e. it's...
3
2016-06-29T18:29:58Z
38,111,459
<p>The issue stems from the creation of the <code>QImage</code>.</p> <pre><code>img = QtGui.QImage(bdata, wid, hgt, QtGui.QImage.Format_Indexed8) </code></pre> <p>The <a href="http://doc.qt.io/qt-4.8/qimage.html#QImage-4" rel="nofollow">documentation</a> for the signature of the constructor you are using says</p> <b...
1
2016-06-29T23:04:42Z
[ "python", "numpy", "pyqt4" ]
python xml - why find("..") doesn't return root
38,107,515
<p>Why doesn't <code>element.find("..")</code> return <code>root</code> when <code>root.findall("*")</code> returns <code>element</code>?</p> <pre><code>def XML_Extract_Node_Tags(Tree, Node_Tags): """ :param Tree: xml.etree.ElementTree :param Node_Tags: list :return: ReturnVal: """ for el in T...
1
2016-06-29T18:31:04Z
38,108,187
<p>Python's <code>xml.etree.ElementTree</code> implementation doesn't record the parent of an <code>Element</code>. Consequently, <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#supported-xpath-syntax" rel="nofollow">the documentation for XPath</a> includes this:</p> <blockquote> <p><code>..</c...
2
2016-06-29T19:10:13Z
[ "python", "xml" ]
NumPy: Select and sum data into array
38,107,571
<p>I have a (large) data array and a (large) list of lists of (a few) indices, e.g.,</p> <pre><code>data = [1.0, 10.0, 100.0] contribs = [[1, 2], [0], [0, 1]] </code></pre> <p>For each entry in <code>contribs</code>, I'd like to sum up the corresponding values of <code>data</code> and put those into an array. For t...
4
2016-06-29T18:34:06Z
38,107,667
<p>One possibility would be</p> <pre><code>data = np.array(data) out = [np.sum(data[c]) for c in contribs] </code></pre> <p>Should be faster than the double loop, at least.</p>
5
2016-06-29T18:39:14Z
[ "python", "numpy" ]
NumPy: Select and sum data into array
38,107,571
<p>I have a (large) data array and a (large) list of lists of (a few) indices, e.g.,</p> <pre><code>data = [1.0, 10.0, 100.0] contribs = [[1, 2], [0], [0, 1]] </code></pre> <p>For each entry in <code>contribs</code>, I'd like to sum up the corresponding values of <code>data</code> and put those into an array. For t...
4
2016-06-29T18:34:06Z
38,108,181
<p>Here's an <em>almost vectorized</em> * approach -</p> <pre><code># Get lengths of list element in contribs and the cumulative lengths # to be used for creating an ID array later on. clens = np.cumsum([len(item) for item in contribs]) # Setup ID array that corresponds to same ID for same list element in contribs. #...
2
2016-06-29T19:09:17Z
[ "python", "numpy" ]
NumPy: Select and sum data into array
38,107,571
<p>I have a (large) data array and a (large) list of lists of (a few) indices, e.g.,</p> <pre><code>data = [1.0, 10.0, 100.0] contribs = [[1, 2], [0], [0, 1]] </code></pre> <p>For each entry in <code>contribs</code>, I'd like to sum up the corresponding values of <code>data</code> and put those into an array. For t...
4
2016-06-29T18:34:06Z
38,109,111
<p>I'm not certain that all cases work, but for your example, with <code>data</code> as a <code>numpy.array</code>:</p> <pre><code># Flatten "contribs" f = [j for i in contribs for j in i] # Get the "ranges" of data[f] that will be summed in the next step i = [0] + numpy.cumsum([len(i) for i in contribs]).tolist()[:-...
0
2016-06-29T20:05:28Z
[ "python", "numpy" ]
How to do Conditional formatting in Python referring another cell
38,107,606
<p>Hi I want to perform conditional value on a cell, that refers to another cell. Below is the code I am using to color the cells from A2:J20, based on the cells BE2:KE20 with values as FALSE</p> <p>I tried this code it works fine, but when I open the excel file it is throwing an error, stating the formula is wrong</...
-1
2016-06-29T18:35:45Z
39,088,228
<pre><code>format1 = book.add_format({'bg_color': '#FFC7CE', 'font_color': '#9C0006'}) worksheet1.conditional_format('A2:J20', {'type': 'formula', 'criteria': '=RIGHT($BE2,10)= "FALSE"', 'format': format1}) </code></pre> <p>...
1
2016-08-22T20:31:28Z
[ "python", "conditional-formatting" ]
Schedule Gaps in Python datetime
38,107,635
<p>I'm trying to get available times from a given schedule: </p> <pre><code>167.0 01:50:48 02:09:56 167.0 03:48:08 04:07:16 167.0 05:45:25 06:04:32 167.0 07:42:39 08:01:45 167.0 08:49:05 22:16:43 167.0 23:17:18 23:59:59 168.0 03:11:24 03:32:05 168.0 00:00:00 03:32:05 168.0 05:08:25 05:...
-1
2016-06-29T18:37:41Z
38,108,231
<p>Well, think about a simple calendar application. You block out times that are invalid, and your calendar shows you those and the times that <em>are</em> valid. Thankfully, you're using military time, which makes the problem less complicated.</p> <p>Ultimately, you'll be left with a list of times.</p> <p>Here's rou...
0
2016-06-29T19:12:55Z
[ "python", "python-2.7", "date", "datetime", "schedule" ]
Column to Transacction ID for association rules on dataframes from Pandas Python.
38,107,681
<p>I imported a CSV into Python with Pandas and I would like to be able to use one as the columns as a transaction ID in order for me to make association rules. </p> <p>(link: <a href="https://github.com/antonio1695/Python/blob/master/nearBPO/facturas.csv" rel="nofollow">https://github.com/antonio1695/Python/blob/mast...
2
2016-06-29T18:39:43Z
38,108,218
<p>You can aggregate values into a list by doing the following:</p> <pre><code>df.groupby('UUID')['Desc'].apply(list) </code></pre> <p>This will give you what you want, if you want the UUID back as a column you can call <code>reset_index</code> on the above:</p> <pre><code>df.groupby('UUID')['Desc'].apply(list).rese...
2
2016-06-29T19:12:23Z
[ "python", "csv", "pandas", "dataframe", "arules" ]
Pythonic way to have a function return value in proper units
38,107,712
<p><strong>Objective:</strong> return a value from a function in the units (or any trivial modification) requested by the caller.</p> <p><strong>Background:</strong></p> <p>I am running Python 2.7 on a Raspberry Pi 3, and use the function <code>distance()</code> to get the distance a rotary encoder has turned. I need...
9
2016-06-29T18:41:42Z
38,107,826
<p>The dictionary lookup is good, but don't return a sentinel value to signal an error; just raise an appropriate exception. It could be as simple (though opaque) as letting the <code>KeyError</code> in your lookup propagate. A better solution, though, is to raise a custom exception:</p> <pre><code>class UnknownUnitEr...
5
2016-06-29T18:49:02Z
[ "python", "python-2.7", "design-patterns", "units-of-measurement" ]
Pythonic way to have a function return value in proper units
38,107,712
<p><strong>Objective:</strong> return a value from a function in the units (or any trivial modification) requested by the caller.</p> <p><strong>Background:</strong></p> <p>I am running Python 2.7 on a Raspberry Pi 3, and use the function <code>distance()</code> to get the distance a rotary encoder has turned. I need...
9
2016-06-29T18:41:42Z
38,108,081
<p>For your example it could be:</p> <pre><code>class DistanceUnits(): """ Enum class for indicating measurement units and conversions between them. Holds all related logic. """ M = 'm' KM = 'km' CM = 'cm' def distance(units=DistanceUnits.M): multiplier = { DistanceUnits.M: 1....
3
2016-06-29T19:03:05Z
[ "python", "python-2.7", "design-patterns", "units-of-measurement" ]
Pythonic way to have a function return value in proper units
38,107,712
<p><strong>Objective:</strong> return a value from a function in the units (or any trivial modification) requested by the caller.</p> <p><strong>Background:</strong></p> <p>I am running Python 2.7 on a Raspberry Pi 3, and use the function <code>distance()</code> to get the distance a rotary encoder has turned. I need...
9
2016-06-29T18:41:42Z
38,111,218
<p>How about, using a decorator:</p> <pre><code>def read_encoder(): return 10 multiplier = { 'm': 1.000, 'km': 0.001, 'cm': 10.00, 'yd': 1.094, } def multiply(fn): def deco(units): return multiplier.get(units, -1) * fn(units) return deco @multiply def distance(units='m'): m...
5
2016-06-29T22:42:59Z
[ "python", "python-2.7", "design-patterns", "units-of-measurement" ]
Python - TypeError: unbound method twitch_connect() must be called with Twitch instance
38,107,728
<p>For a couple of hours now, I have been messing with code to make a Twitch Plays stream on Twitch. I just got to the end, and tried to run it in Liclipse, but it says...</p> <blockquote> <p>TypeError: unbound method twitch_connect() must be called with Twitch instance as first argument (got str instance instead)</...
-1
2016-06-29T18:42:56Z
38,107,763
<p>You're calling <code>twitch_connect</code> from the class object not an instance, but the <code>twitch_connect</code> method takes <code>self</code> (or an instance of the class) as first argument:</p> <pre><code>t = twitch.Twitch </code></pre> <p>You should instantiate you class using <code>()</code>:</p> <pre><...
2
2016-06-29T18:45:09Z
[ "python" ]
Split string based off multiple possible deminiters but keep delimiters
38,107,752
<p>I am cleaning addresses. I am looking to strip everything after specific words (avenue, ave, road, place, etc etc etc).</p> <p>I was looking at doing something like this but I believe this will return everything before the word. That means "1 first avenue" would return "1 first".</p> <p>How can I append this (or d...
2
2016-06-29T18:44:27Z
38,108,110
<p>I think this is what you want.</p> <pre><code>pattern = ['ave', 'street', 'road'] address = 'Imaginary ave, Fantasy Island' for i in pattern: if i in address: print address[:address.find(i) + len(i)] </code></pre> <p>or if there are a list of addresses</p> <pre><code>print [address[:address.find(i) +...
2
2016-06-29T19:04:21Z
[ "python" ]
Split string based off multiple possible deminiters but keep delimiters
38,107,752
<p>I am cleaning addresses. I am looking to strip everything after specific words (avenue, ave, road, place, etc etc etc).</p> <p>I was looking at doing something like this but I believe this will return everything before the word. That means "1 first avenue" would return "1 first".</p> <p>How can I append this (or d...
2
2016-06-29T18:44:27Z
38,108,219
<p>This would work for searching for a specific <em>sub-string</em> in a string, I used the string <code>index()</code> method (however, as other users have pointed out there are multiple ways to solve this problem), which is why there is a try/except block. The <code>index()</code> method returns an error if the sub-...
1
2016-06-29T19:12:28Z
[ "python" ]
Split string based off multiple possible deminiters but keep delimiters
38,107,752
<p>I am cleaning addresses. I am looking to strip everything after specific words (avenue, ave, road, place, etc etc etc).</p> <p>I was looking at doing something like this but I believe this will return everything before the word. That means "1 first avenue" would return "1 first".</p> <p>How can I append this (or d...
2
2016-06-29T18:44:27Z
38,108,295
<p>There a few ways to achieve this. If the <code>reduce</code> here has a significene, this is one way to keep the answer within the <code>lambda</code>:</p> <pre><code>patterns = ["ave", "avenue", "road", "street"] string = 'queen ave west' reduce(lambda s, pat: s[:s.find(pat)+len(pat)] if s.find(pat) &gt; 0 else s,...
1
2016-06-29T19:16:52Z
[ "python" ]
Split string based off multiple possible deminiters but keep delimiters
38,107,752
<p>I am cleaning addresses. I am looking to strip everything after specific words (avenue, ave, road, place, etc etc etc).</p> <p>I was looking at doing something like this but I believe this will return everything before the word. That means "1 first avenue" would return "1 first".</p> <p>How can I append this (or d...
2
2016-06-29T18:44:27Z
38,108,327
<p>you can use this compact way</p> <pre><code>print reduce (lambda s,x : str(s.split(x)[0]) if (str(s.split(x)[0]) == s) else str(s.split(x)[0]) + x,patterns) </code></pre> <p>full example</p> <pre><code>patterns = ["ave", "ave", "road" ] string = "1 first avenue" patterns.insert(0,string) print reduce (lambda s,x ...
0
2016-06-29T19:18:31Z
[ "python" ]
Beautifulsoup4 - Trying to get the data using a while loop
38,107,874
<p>I have written a very basic crawler to check if a link is dead or not using bs4. I want to check if the anchor tag has an href or not (This way I can check if the link is active or not). There is only one anchor element in the page. </p> <p>This is the code:</p> <pre><code>import requests from bs4 import Beautiful...
-1
2016-06-29T18:51:24Z
38,108,133
<p>It's hard to say without knowing what website you're trying to check tags on, but at least from a code standpoint, you should probably be doing <code>not a.has_attr('href')</code> rather than <code>a.get('href') != ''</code> if your objective is to see if the anchor has any <code>href</code> attribute at all.</p> <...
1
2016-06-29T19:05:51Z
[ "python", "beautifulsoup", "bs4" ]
Beautifulsoup4 - Trying to get the data using a while loop
38,107,874
<p>I have written a very basic crawler to check if a link is dead or not using bs4. I want to check if the anchor tag has an href or not (This way I can check if the link is active or not). There is only one anchor element in the page. </p> <p>This is the code:</p> <pre><code>import requests from bs4 import Beautiful...
-1
2016-06-29T18:51:24Z
38,108,870
<p><code>a.get('href')</code> will never be equal to an empty string, it will be <em>None</em> if the anchor has no href so you if would never evaluate to True. </p> <p>If there is only one anchor then just <code>return soup.find("a", href=True)</code>, if there is an anchor with a href you will get the anchor, if not...
0
2016-06-29T19:50:22Z
[ "python", "beautifulsoup", "bs4" ]
How would I use values from two different functions where their keys match?
38,107,912
<p>I am having troubles trying to use the values from each function and combine them together. I have local variables from each function that I would like to use to in a different function where I would divided each value as long as their primary (categories) match each other. I currently have:</p> <pre><code>counters...
2
2016-06-29T18:53:42Z
38,108,338
<p>Make the <code>counter</code> dict local to each function, and <code>return</code> each <code>counter</code> in your functions:</p> <pre><code>def participated(): counters = {} for line in reader: if int(line[6]) &gt; 0: primary = line[7].strip('[]') counters.setdefault(prima...
2
2016-06-29T19:19:33Z
[ "python", "python-2.7" ]
From tuples to linear equations with numpy
38,107,979
<p>i need help in the following topic. Lets say i have three points, each with x, y coordinates and a corresponding z value, e.g.:</p> <pre><code>p_0 = (x_0, y_0, z_0) : coordinates of first point p_1 = (x_1, y_1, z_1) : coordinates of second point p_2 = (x_2, y_2, z_2) : coordinates of third point </code></pre> <p>L...
2
2016-06-29T18:56:42Z
38,108,070
<p>You could use</p> <pre><code>p = np.row_stack([p_0, p_1, p_2]) B = np.ones_like(p) # copy the first two columns of p into the last 2 columns of B B[:, 1:] = p[:, :2] z = p[:, 2] </code></pre> <hr> <p>For example,</p> <pre><code>import numpy as np p_0 = (1,2,3) p_1 = (4,-5,6) p_2 = (7,8,9) p = np.row_stack([p_0...
1
2016-06-29T19:02:29Z
[ "python", "numpy", "matrix", "interpolation", "linear-algebra" ]
From tuples to linear equations with numpy
38,107,979
<p>i need help in the following topic. Lets say i have three points, each with x, y coordinates and a corresponding z value, e.g.:</p> <pre><code>p_0 = (x_0, y_0, z_0) : coordinates of first point p_1 = (x_1, y_1, z_1) : coordinates of second point p_2 = (x_2, y_2, z_2) : coordinates of third point </code></pre> <p>L...
2
2016-06-29T18:56:42Z
38,108,073
<pre><code>&gt;&gt;&gt; p_0 = (-1,2,3) &gt;&gt;&gt; p_1 = (4,5,6) &gt;&gt;&gt; p_2 = (7,8,9) &gt;&gt;&gt; B = np.c[np.ones((3,1)),np.c_[p_0,p_1,p_2]] &gt;&gt;&gt; np.linalg.solve(B[:,:-1],B[:,-1]) </code></pre>
1
2016-06-29T19:02:38Z
[ "python", "numpy", "matrix", "interpolation", "linear-algebra" ]
From tuples to linear equations with numpy
38,107,979
<p>i need help in the following topic. Lets say i have three points, each with x, y coordinates and a corresponding z value, e.g.:</p> <pre><code>p_0 = (x_0, y_0, z_0) : coordinates of first point p_1 = (x_1, y_1, z_1) : coordinates of second point p_2 = (x_2, y_2, z_2) : coordinates of third point </code></pre> <p>L...
2
2016-06-29T18:56:42Z
38,108,433
<p>I would use a list concatenation like so</p> <pre><code>&gt;&gt;&gt; B = [[1, x[0], x[1]] for x in [p_0, p_1, p_2]] &gt;&gt;&gt; z = [[x[2]] for x in [p_0, p_1, p_2]] </code></pre> <p>An example</p> <pre><code>&gt;&gt;&gt; p_0, p_1, p_2 = (1, 2, 3), (4, 5, 6), (7, 8, 9) &gt;&gt;&gt; B = [[1, x[0], x[1]] for x in ...
1
2016-06-29T19:25:07Z
[ "python", "numpy", "matrix", "interpolation", "linear-algebra" ]
update all files
38,107,980
<p>I have a <code>models.manager</code> where I can filter files from:</p> <pre><code>class FileManager(models.Manager): def get_new_files(self, json_output=None, update=None): files = (self.filter(status=File.PENDING_STATUS)) \ .values('name', 'link', 'size', 'token__userid', 'token__...
0
2016-06-29T18:56:42Z
38,108,294
<p>If you just want to update the <code>status</code> field:</p> <pre class="lang-py prettyprint-override"><code>class FileManager(models.Manager): def get_new_files(self, json_output=None, update=None): files = (self.filter(status=File.PENDING_STATUS)) \ .values('name', 'link', 'size', 't...
1
2016-06-29T19:16:50Z
[ "python", "django", "django-models" ]
Arranging numpy arrays in a block matrix
38,108,335
<p>I have 3 numpy arrays <code>A</code>, <code>B</code> and <code>C</code>. For simplicity, let's assume that they are all of shape <code>[n, n]</code>. I want to arrange them as a block matrix</p> <pre><code>A B B^t C </code></pre> <p>where <code>B^t</code> shall denote the transpose of <code>B</code>. Of course...
3
2016-06-29T19:19:25Z
38,108,383
<p>You can use the NumPy built-in <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bmat.html" rel="nofollow"><code>np.bmat</code></a> that's perfectly suited for such a task, like so -</p> <pre><code>np.bmat([[A, B], [B.T, C]]) </code></pre> <p>As mentioned in the <a href="http://stackoverflow.com/q...
5
2016-06-29T19:22:24Z
[ "python", "numpy" ]
Arranging numpy arrays in a block matrix
38,108,335
<p>I have 3 numpy arrays <code>A</code>, <code>B</code> and <code>C</code>. For simplicity, let's assume that they are all of shape <code>[n, n]</code>. I want to arrange them as a block matrix</p> <pre><code>A B B^t C </code></pre> <p>where <code>B^t</code> shall denote the transpose of <code>B</code>. Of course...
3
2016-06-29T19:19:25Z
38,110,489
<p>Stripped of some bells and whisles, <code>np.bmat</code> does this:</p> <pre><code>def foo(alist): rowlist=[] for row in alist: rowlist.append(np.concatenate(row,axis=1)) return np.concatenate(rowlist, axis=0) </code></pre> <p>So for example:</p> <pre><code>In [1026]: A=np.arange(4).reshape(2,...
0
2016-06-29T21:39:19Z
[ "python", "numpy" ]
How to add up specific parts of a list?
38,108,345
<p>I have a list with a bunch of data in the format of: <code>date, month, data</code></p> <p>I would like all of the entries with the same date to sum up all of their data and the output be simply date, data. In other words, the data looks something like this</p> <pre><code>[(1/1/2011, August, 5), (1/1/2011, July, ...
2
2016-06-29T19:19:51Z
38,108,413
<p>Use a dictionary to keep the unique dates:</p> <pre><code>dates = {} for (date, month, day) in your_list: if date not in dates: dates[date] = day else dates[date] += day </code></pre> <p>You'd then have to go back to a list if you wanted the output as you've specified:</p> <pre><code>outli...
2
2016-06-29T19:24:09Z
[ "python", "list" ]
How to add up specific parts of a list?
38,108,345
<p>I have a list with a bunch of data in the format of: <code>date, month, data</code></p> <p>I would like all of the entries with the same date to sum up all of their data and the output be simply date, data. In other words, the data looks something like this</p> <pre><code>[(1/1/2011, August, 5), (1/1/2011, July, ...
2
2016-06-29T19:19:51Z
38,108,551
<p>Find all the dates in the list and then you can count each one:</p> <pre><code>dates = [('1/1/2011', 'August', 5), ('1/1/2011', 'July', 4), ('1/1/2011', 'June', 1), ('1/6/2011', 'December', 5)] each_date = set(d[0] for d in dates) count_dates = [(d, sum(i[2] for i in dates if i[0] == d)) for d in each_da...
1
2016-06-29T19:32:01Z
[ "python", "list" ]
How to add up specific parts of a list?
38,108,345
<p>I have a list with a bunch of data in the format of: <code>date, month, data</code></p> <p>I would like all of the entries with the same date to sum up all of their data and the output be simply date, data. In other words, the data looks something like this</p> <pre><code>[(1/1/2011, August, 5), (1/1/2011, July, ...
2
2016-06-29T19:19:51Z
38,109,627
<p>Here is a one-liner based on <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby()</code></a>:</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; dates = [('1/1/2011', 'August', 5), ('1/1...
1
2016-06-29T20:38:35Z
[ "python", "list" ]
GAE Python webapp2 image upload error
38,108,388
<p>I am working on a project in which i am trying to upload a image on blob store. But i am getting this error</p> <blockquote> <p>File "C:\Users\shaizi\PycharmProjects\simpletestapp\Update.py", line 51, in post</p> <p>blob_info = upload_files[0]<br> IndexError: list index out of range</p> </blockquote> <...
0
2016-06-29T19:22:39Z
38,108,830
<p>Actually i have to set the action to Upload url.</p> <pre><code>&lt;form id="signup" method="post" action="/post/signup" enctype="multipart/form-data"&gt; &lt;label&gt;Change image:&lt;/label&gt; &lt;input type="file" name="pict" &gt;&lt;br&gt; &lt;/form&gt; </code></pre>
0
2016-06-29T19:47:42Z
[ "python", "google-app-engine", "blobstore", "webapp2" ]
GAE Python webapp2 image upload error
38,108,388
<p>I am working on a project in which i am trying to upload a image on blob store. But i am getting this error</p> <blockquote> <p>File "C:\Users\shaizi\PycharmProjects\simpletestapp\Update.py", line 51, in post</p> <p>blob_info = upload_files[0]<br> IndexError: list index out of range</p> </blockquote> <...
0
2016-06-29T19:22:39Z
38,121,988
<p>I think you have to use a <code>form_url</code> variable:</p> <pre><code>` &lt;form method="post" action="{{ form_url }}" accept-charset="UTF-8" enctype="multipart/form-data"&gt;` </code></pre> <p>You get this variable from the appengine with your backend code:</p> <pre><code>class UploadPage(...
0
2016-06-30T11:37:22Z
[ "python", "google-app-engine", "blobstore", "webapp2" ]
GAE Python webapp2 image upload error
38,108,388
<p>I am working on a project in which i am trying to upload a image on blob store. But i am getting this error</p> <blockquote> <p>File "C:\Users\shaizi\PycharmProjects\simpletestapp\Update.py", line 51, in post</p> <p>blob_info = upload_files[0]<br> IndexError: list index out of range</p> </blockquote> <...
0
2016-06-29T19:22:39Z
38,132,680
<p>In my case, with multi-part forms, I am getting file data as follows:</p> <pre><code>self.request.get('&lt;name_in_form&gt;') </code></pre> <p>For your case, it should be:</p> <pre><code>self.request.get('pict') </code></pre> <p>In any case, if possible, try to avoid using blobstore, as Google recommends using C...
0
2016-06-30T20:28:28Z
[ "python", "google-app-engine", "blobstore", "webapp2" ]
How to store sensor data into Apache Hadoop HDFS, Hive, HBase or other
38,108,432
<p>Imagine you are reading millions of data rows from a CSV file. Each line shows the sensor-name, the current sensor-value and the timestamp when that value was observed. </p> <pre><code>key, value, timestamp temp_x, 8°C, 10:52am temp_x, 25°C, 11:02am temp_x, 30°C, 11:12am </code></pre> <p>This relates to a signa...
1
2016-06-29T19:25:03Z
38,114,740
<p>I would consider to use.</p> <ul> <li>Load data from CSV file with <a href="https://github.com/databricks/spark-csv" rel="nofollow">databricks csv</a></li> <li>Cleaning the data</li> <li><p>Write to qarquet file (to save space and time)</p></li> <li><p>Load data from parquet file</p></li> <li>Analyse it</li> <li>Pe...
1
2016-06-30T05:38:38Z
[ "python", "hadoop", "hdfs", "signal-processing", "sensor" ]
Django order by multiple filtered foreign key values
38,108,446
<p>I am attempting to sort by multiple values on related fields, filtered by a key, but running the second <code>order_by</code> is ordering by the <em>first</em> filter, not the most recent.</p> <pre><code>class Product(Model): name = CharField() class ProductAttribute(Model): product = ForeignKey(Product) ...
-1
2016-06-29T19:26:02Z
38,109,534
<p>I'm not sure if this is the kind of answer you're looking for, but I would suggest adding rating and score into your Product table as foreign keys to the product attribute as opposed to the other way around. To me, this makes more sense as a model.</p> <pre><code>class Product(Model): name = CharField() sco...
1
2016-06-29T20:32:43Z
[ "python", "django" ]
Is the 'is' keyword in Python the same as the === keyword in JS?
38,108,484
<p>I saw this question <a href="http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons?rq=1">here</a> and now I'm curious. How does the <code>is</code> operator behave in python in comparison to the === sign in JS?</p>
2
2016-06-29T19:28:18Z
38,108,540
<p>No, they are not the same. <code>is</code> in Python checks if two objects have the same <code>id</code> in Python, ie. they are the same, even in memory. Something you can do to check is this:</p> <pre><code>&gt;&gt;&gt; a='foo' &gt;&gt;&gt; a is 'foo' True &gt;&gt;&gt; id(a) 44434088 &gt;&gt;&gt; id('foo') 444340...
6
2016-06-29T19:31:34Z
[ "javascript", "python", "comparison" ]
Is the 'is' keyword in Python the same as the === keyword in JS?
38,108,484
<p>I saw this question <a href="http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons?rq=1">here</a> and now I'm curious. How does the <code>is</code> operator behave in python in comparison to the === sign in JS?</p>
2
2016-06-29T19:28:18Z
38,108,641
<p>In Javascript, the <code>==</code> operator will do implicit type conversion when comparing for equality so, for instance, <code>[] == ""</code> will return <code>true</code>. The <code>===</code> operator is used to check equality without type conversion (<code>[] === ""</code> returns false.)</p> <p>In Python, t...
2
2016-06-29T19:37:07Z
[ "javascript", "python", "comparison" ]
Is the 'is' keyword in Python the same as the === keyword in JS?
38,108,484
<p>I saw this question <a href="http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons?rq=1">here</a> and now I'm curious. How does the <code>is</code> operator behave in python in comparison to the === sign in JS?</p>
2
2016-06-29T19:28:18Z
38,108,691
<p>No. <code>is</code> in Python is seemingly much <em>stricter</em> than <code>===</code> in JS.</p> <p>In JS:</p> <blockquote> <p>For value types (numbers): <code>a === b</code> returns true if a and b have the same value and are of the same type</p> <p>For reference types: <code>a === b</code> returns tru...
1
2016-06-29T19:40:23Z
[ "javascript", "python", "comparison" ]
Classifier predictions are unreliable, is that because my GMM classifier is not trained correctly?
38,108,504
<p>I'm training two GMM classifiers, each for one label, with MFCC values. I concatenated all the MFCC values of a class and fitted into a classifier. And for each classifier I sum the probability of its label's probability.</p> <pre><code>def createGMMClassifiers(): label_samples = {} for label, sample in tra...
0
2016-06-29T19:29:13Z
38,116,726
<p>For classification tasks it's important to tune parameter given to the classifier, also a large number of classification algorithm follow chose theory, witch means if you change some parameter of the model briefly, you may get some huge different results. Also it's important to use different algorithms and not just ...
0
2016-06-30T07:36:32Z
[ "python", "machine-learning", "speech-recognition", "mfcc" ]
Classifier predictions are unreliable, is that because my GMM classifier is not trained correctly?
38,108,504
<p>I'm training two GMM classifiers, each for one label, with MFCC values. I concatenated all the MFCC values of a class and fitted into a classifier. And for each classifier I sum the probability of its label's probability.</p> <pre><code>def createGMMClassifiers(): label_samples = {} for label, sample in tra...
0
2016-06-29T19:29:13Z
38,125,160
<p>Your code has not much sense, you recreate classifier for every new training sample.</p> <p>Correct code scheme for training should look about this:</p> <pre><code>label_samples = {} classifiers = {} # First we collect all samples per label into array of samples for label, sample in samples: label_samples[la...
0
2016-06-30T13:51:35Z
[ "python", "machine-learning", "speech-recognition", "mfcc" ]
count numbers of tag_name in a webpage (python, selenium)
38,108,520
<p>Hi have the following code:</p> <pre><code>for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") cell = each.find_elements_by_tag_name('td')[0] cell2 = each.find_elements_by_tag_name('td')[1] cell3 = each.find_elements_by_tag_name('td')[2] </code></pre> <p>My prob...
-1
2016-06-29T19:30:19Z
38,108,545
<p>Just don't get them by index, use:</p> <pre><code>cells = each.find_elements_by_tag_name('td') </code></pre> <p>then <code>cells</code> would be a <em>list of elements</em> which you can call <code>len()</code> on:</p> <pre><code>print(len(cells)) </code></pre> <p>Or slice: </p> <pre><code>cells[:3] # gives fi...
0
2016-06-29T19:31:40Z
[ "python", "html", "selenium", "xpath", "webpage" ]
count numbers of tag_name in a webpage (python, selenium)
38,108,520
<p>Hi have the following code:</p> <pre><code>for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") cell = each.find_elements_by_tag_name('td')[0] cell2 = each.find_elements_by_tag_name('td')[1] cell3 = each.find_elements_by_tag_name('td')[2] </code></pre> <p>My prob...
-1
2016-06-29T19:30:19Z
38,108,658
<p><code>find_elements_by_tag_name</code> returns a list. Use <code>len()</code> on that list to get the number of elements by that tag name. Also, rather than saying <code>for each</code> I'd gently suggest using more descriptive assignments. </p> <pre><code>table = driver.find_element_by_xpath(".//*[@id='ip_market" ...
0
2016-06-29T19:37:50Z
[ "python", "html", "selenium", "xpath", "webpage" ]
count numbers of tag_name in a webpage (python, selenium)
38,108,520
<p>Hi have the following code:</p> <pre><code>for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") cell = each.find_elements_by_tag_name('td')[0] cell2 = each.find_elements_by_tag_name('td')[1] cell3 = each.find_elements_by_tag_name('td')[2] </code></pre> <p>My prob...
-1
2016-06-29T19:30:19Z
38,112,697
<p>From reading your comments, it looks like this is what you are trying to do...</p> <pre><code>for each in driver.find_elements_by_xpath(".//*[@id='ip_market" + market + "']/table/tbody") for i in range(0,len(each.find_elements_by_tag_name('td')) // you can now use i as an index into the loop through the...
0
2016-06-30T01:47:13Z
[ "python", "html", "selenium", "xpath", "webpage" ]
Write not working Odoo 8
38,108,568
<p>I have a problem when I try to modify informations for a res.partner but only in this file, in my other modules .write is working...</p> <p>I know it's going into the write and that it brings the informations but it just doesn't save.</p> <p>Also it was working before but for no obvious reason it's no more working...
0
2016-06-29T19:33:12Z
38,111,115
<p>Obviously it would not work. In a nutshell reason is that you're raising error from the function and this makes Odoo think that things go wrong in your function and the actual write to database does not happen (what happens instead is a rollback). To make sure that data gets written to the database, you should call ...
0
2016-06-29T22:31:06Z
[ "python", "openerp", "odoo-8" ]
Optionally retrieve related items in Django REST framework
38,108,688
<p>Suppose I have these models:</p> <pre><code>class House(models.Model): name = models.CharField(max_length=50) # Other attributes class Booking(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE) arrival_date = models.DateField() departure_date = models.DateField() </code><...
2
2016-06-29T19:40:13Z
38,108,911
<p>Maybe you can do two serializers, one to the List of houses without showing the books, and another for the individual house, showing the books.</p> <p>In the views you define the list serializer for the list uri, and the individual serializer for the individual uri.</p>
0
2016-06-29T19:53:14Z
[ "python", "django", "django-rest-framework" ]
Optionally retrieve related items in Django REST framework
38,108,688
<p>Suppose I have these models:</p> <pre><code>class House(models.Model): name = models.CharField(max_length=50) # Other attributes class Booking(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE) arrival_date = models.DateField() departure_date = models.DateField() </code><...
2
2016-06-29T19:40:13Z
38,109,613
<p>First, it makes more sense (to me at least) to have your endpoint for bookings for a given house exist at <code>/house/:houseId/bookings/</code> since the namespace at <code>/house/bookings/</code> will already be looking for an ID.</p> <p>You can also serialize the relationship between a House and Booking to displ...
2
2016-06-29T20:37:23Z
[ "python", "django", "django-rest-framework" ]
Optionally retrieve related items in Django REST framework
38,108,688
<p>Suppose I have these models:</p> <pre><code>class House(models.Model): name = models.CharField(max_length=50) # Other attributes class Booking(models.Model): house = models.ForeignKey(House, on_delete=models.CASCADE) arrival_date = models.DateField() departure_date = models.DateField() </code><...
2
2016-06-29T19:40:13Z
38,126,250
<p>Turns out, I was trying with too high-level parts of the API that restricted me more than they were helping me, I needed to do some things manually.</p> <p>This answer <a href="http://stackoverflow.com/a/17763864/1582024">http://stackoverflow.com/a/17763864/1582024</a> shows how to implement a hierarchy of resource...
0
2016-06-30T14:32:58Z
[ "python", "django", "django-rest-framework" ]
on click pause the real time plot of data
38,108,726
<p>I simply want to put a pause clause to my plot where I can pause the real time stream voluntarily. This is what I am trying. This is an edited code. It s making two subplots: scatter and pie chart. I am able to pause the scatter plot but when I pause pie chart disappears.</p> <pre><code>def onClick(event): glo...
0
2016-06-29T19:42:28Z
38,120,515
<p>There are more elegant methods of achieving this (using <code>matplotlib.animation</code>, see e.g. this: <a href="http://stackoverflow.com/a/16733373/3581217">http://stackoverflow.com/a/16733373/3581217</a> answer), but within the spirit of the example that you provided, this functionally works: </p> <pre><code>im...
0
2016-06-30T10:30:10Z
[ "python", "matplotlib", "graph", "pause" ]
Passing categorical data to Sklearn Decision Tree
38,108,832
<p>There are several posts about how to encode categorical data to Sklearn Decission trees, but from Sklearn documentation, we got these </p> <blockquote> <p>Some advantages of decision trees are:</p> <p>(...)</p> <p>Able to handle both numerical and categorical data. Other techniques are usually specialis...
2
2016-06-29T19:47:46Z
38,108,946
<p>Sklearn Decision Trees do not handle conversion of categorical strings to numbers. I suggest you find a function in Sklearn (maybe <a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.FeatureHasher.html" rel="nofollow">this</a>) that does so or manually write some code like:</p> <pr...
0
2016-06-29T19:55:25Z
[ "python", "scikit-learn", "decision-tree" ]
Passing categorical data to Sklearn Decision Tree
38,108,832
<p>There are several posts about how to encode categorical data to Sklearn Decission trees, but from Sklearn documentation, we got these </p> <blockquote> <p>Some advantages of decision trees are:</p> <p>(...)</p> <p>Able to handle both numerical and categorical data. Other techniques are usually specialis...
2
2016-06-29T19:47:46Z
38,109,663
<p>Contrary to the accepted answer, I would prefer to use tools provided by Scikit-Learn for this purpose. The main reason for doing so is that they can be easily integrated in a <a href="http://scikit-learn.org/stable/modules/pipeline.html#pipeline" rel="nofollow">Pipeline</a>.</p> <p>Scikit-Learn itself provides ver...
0
2016-06-29T20:41:11Z
[ "python", "scikit-learn", "decision-tree" ]
Why does an unassigned string not cause a compilation error in Python?
38,109,009
<p>In my workings with python, I have sometimes found that I deleted a variable and just left the string inline in my code. I have noticed you can do this and there is no notification at all from the compiler or any runtime error when this occurs. Can someone tell me why this does not error out?</p> <pre><code>c = 1 "...
0
2016-06-29T19:58:57Z
38,109,061
<p>Because Pyhthon defines and allows that, aka known as <a href="https://docs.python.org/2/reference/simple_stmts.html#expression-statements" rel="nofollow">expression-statements</a></p> <p>I quote:</p> <blockquote> <p>Expression statements are used (mostly interactively) to compute and write a value, or (usuall...
1
2016-06-29T20:02:03Z
[ "python", "documentation" ]
Why does an unassigned string not cause a compilation error in Python?
38,109,009
<p>In my workings with python, I have sometimes found that I deleted a variable and just left the string inline in my code. I have noticed you can do this and there is no notification at all from the compiler or any runtime error when this occurs. Can someone tell me why this does not error out?</p> <pre><code>c = 1 "...
0
2016-06-29T19:58:57Z
38,109,148
<p>As in many languages, it is perfectly valid to have an expression that is not assigned to a variable.</p> <pre><code>3.14 "Boo!" False 2 + 2 callable(func) and func() </code></pre> <p>Python will print the results of such expressions when they are executed on the command line, but in a script these values are disc...
0
2016-06-29T20:08:16Z
[ "python", "documentation" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,109,251
<p>You could handle large numbers by converting them to a string first and then parsing the string one character at a time. For example:</p> <pre><code>if n &gt;= 1000: place = {1:'', 2:'', 3:'hundred', 4:'thousand'} return_val = '' n = str(n) while n != '': c = n[0] return_val += numb...
0
2016-06-29T20:14:25Z
[ "python", "string", "printing", "numbers", "int" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,109,262
<p>You are close! I would start with a top down approach (e.g. start on the 100000 level and work your way down) and use recursive calls. I would also use the <code>%</code> operator which represents <code>mod</code> (basically gives you remainder <code>5%2 = 1</code>). </p> <p>Here is an idea that will handle for exa...
0
2016-06-29T20:15:01Z
[ "python", "string", "printing", "numbers", "int" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,109,326
<p>This may seem tedious, but convert each place into an individual number then add the strings of the words. I have done up to 999 in a few minutes. Continue the same pattern and it should be easy and very basic!</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ 6: 'Six', 7: 'Seve...
-2
2016-06-29T20:19:42Z
[ "python", "string", "printing", "numbers", "int" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,109,385
<p>I'll not give you a straight answer, but hints.</p> <p>First of all you need to parse numbers in groups of three digits as it is exactly the same wording for each group of 3, the only difference is suffix that describe "level", eg:</p> <p>505 and 505,000 will be basically the same: "five hundreds and five" where o...
0
2016-06-29T20:22:58Z
[ "python", "string", "printing", "numbers", "int" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,109,397
<p>You'll need to process each named group separately (Ex. <code>Twenty-Four Thousand Four Hundred Fifty-One</code>). Recursion will be your friend here so you won't have a long chain of <code>if</code>'s</p> <p>First off, you can short-circuit if the number provided is defined directly in your numbers dictionary, th...
1
2016-06-29T20:23:40Z
[ "python", "string", "printing", "numbers", "int" ]
Printing number names from 0-999999
38,109,086
<p>So I was given a little task, I had to write a program in Python that prints a number's name from 0-999999.</p> <p>But I ran into some problems, and I'd love to get your ideas and help.</p> <p>This is what I have written so far:</p> <pre><code>numbers = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \ ...
3
2016-06-29T20:03:47Z
38,110,499
<p>Brenden Abel's answer above is pretty good, but here's a nice and tight, more self-contained version. As others have pointed out, recursion is your friend here:</p> <pre><code>def beta1(n, returnZero=True): if n == 0 and not returnZero: return [] # Prevent superfluous final "zero", e.g. 2900: "two t...
0
2016-06-29T21:39:40Z
[ "python", "string", "printing", "numbers", "int" ]
Scraping a simple html table returns u'\n (Python with BeautifulSoup)
38,109,106
<p>I'm trying to scrape a table using <a href="http://www.analyticsvidhya.com/blog/2015/10/beginner-guide-web-scraping-beautiful-soup-python/" rel="nofollow">this</a> tutorial. I'm fairly sure I am getting the right table, but my output is just lists full of <code>u'\n'</code>. </p> <p>The line <code>if len(cells) == ...
1
2016-06-29T20:05:11Z
38,109,362
<p>I am not sure why this is the behavior you get, but you sure do not need to call <code>find()</code> in each cell. You can get the content of the cell from its <code>text</code> attribute. If you replace</p> <pre><code> NAM.append(cells[0].find(text=True)) </code></pre> <p>with</p> <pre><code> NAM.append(ce...
-1
2016-06-29T20:21:32Z
[ "python", "web-scraping", "beautifulsoup" ]
Kivy kv file is not working
38,109,126
<p>I have the same issue like described in this theme <a href="http://stackoverflow.com/questions/34748579/kivy-using-a-screenmanager-from-kv-file/38109098#38109098">kv incorrect</a>. When I use Builder and load the kv file I have normal working app. But when I try to use autoload kv file I have only black screen. Coul...
3
2016-06-29T20:06:27Z
38,110,500
<p>In your <code>kv</code> file, you define <code>ScreenManagement</code> to be the root element with its associated screens. But in <code>build</code>, you return a newly created <code>ScreenManagement</code> object, which will not have any children defined.</p> <p>Solution: Define <code>build</code> as </p> <pre><c...
2
2016-06-29T21:39:44Z
[ "python", "kivy", "kivy-language" ]