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
Setting a return on a function to be different depending on button clicked in tkinter
38,159,555
<p>I have a text based adventure which uses tkinter as its GUI, and am trying to create a function which will label buttons with different options, then return which button was pressed. I want to do this so it can be used as a general function for any decision in the game. I can create the buttons, but cannot get the f...
0
2016-07-02T11:19:24Z
38,159,962
<p>There are a couple of things you can do. </p> <p>I would go with the dynamic approach. If you don't need to reference you buttons after creating them ( eg. don't need to change text or delete etc ) then you can do</p> <pre><code>def press(self, val): self.choice = val def create_buttons(self): btn_text = ...
1
2016-07-02T12:06:19Z
[ "python", "python-3.x", "tkinter" ]
How to remove the following error?
38,159,601
<p><strong><em>The question was to find the symmetric difference between two sets without using the the corresponding method !</em></strong></p> <p>from <strong>future</strong> import print_function</p> <pre><code>M=int(raw_input()) X=map(int,raw_input().split()) N=int(raw_input()) Y=map(int,raw_input().split()) ...
0
2016-07-02T11:25:29Z
38,159,649
<p><a href="https://docs.python.org/2/library/stdtypes.html#list.sort" rel="nofollow"><code>list.sort</code></a> does not return a new sorted function. It just sort the list (return <code>None</code>).</p> <p>If you want to get a new list sorted, use <a href="https://docs.python.org/2/library/functions.html#sorted" re...
1
2016-07-02T11:30:29Z
[ "python", "list", "python-2.7" ]
How to remove the following error?
38,159,601
<p><strong><em>The question was to find the symmetric difference between two sets without using the the corresponding method !</em></strong></p> <p>from <strong>future</strong> import print_function</p> <pre><code>M=int(raw_input()) X=map(int,raw_input().split()) N=int(raw_input()) Y=map(int,raw_input().split()) ...
0
2016-07-02T11:25:29Z
38,159,685
<p>Your error is here:</p> <pre><code>w=w.sort() </code></pre> <p>The return type for w.sort() is 'None'. The sort() method is in-place. Change it to just:</p> <pre><code>w.sort() </code></pre>
1
2016-07-02T11:34:43Z
[ "python", "list", "python-2.7" ]
OpenCv pytesseract for OCR
38,159,622
<p>How to use opencv and pytesseract to extract text from image?</p> <pre><code>import cv2 </code></pre> <p>import pytesseract from PIL import Image import numpy as np from matplotlib import pyplot as plt</p> <pre><code>img = Image.open('test.jpg').convert('L') img.show() img.save('test','png') img = cv2.imread('tes...
0
2016-07-02T11:26:57Z
39,058,306
<p>You cannot use directly Opencv objects with tesseract methods.</p> <p>Try:</p> <pre><code>from PIL import Image from pytesseract import * image_file = 'test.png' print(pytesseract.image_to_string(Image.open(image_file))) </code></pre>
1
2016-08-20T20:12:25Z
[ "python", "opencv" ]
opencv remove noise / detect net with canny
38,159,625
<p>What would be your approach to detecting the volleyball net on this images.<br> Unfortunately, <code>bilateralFilter</code> or <code>gaussianBlur</code> all result in a lot of noise (especially the trees and sand) for the <code>canny</code> line detector. </p> <p>Can you suggest a better course of action ?</p> <p>...
4
2016-07-02T11:27:24Z
38,222,607
<p>I am not confident that you will be able to write a completely all-fit generic code for detecting rectangles in all images. Meaning, whatever algorithm you write/use would have some issues, as it will have to deal with the noises related to the environment.</p> <p>However, one neat trick is enhance the contrast in ...
0
2016-07-06T11:10:39Z
[ "python", "opencv" ]
How to multicolour text with ScrolledText widget?
38,159,653
<pre><code>from tkinter import * from tkinter.scrolledtext import ScrolledText window= Tk() window.geometry('970x45') box = ScrolledText(window, width=70, height=7).pack() box.insert(END, "Ehila") #this insert "Ehila" into the box box.congif(foreground='green') #this change the colour of "Ehila" into green colour box....
0
2016-07-02T11:31:06Z
38,159,683
<p>Insert text with tags (<code>insert</code> method accept optional tag parameter(s)). Later use <a href="http://effbot.org/tkinterbook/text.htm#Tkinter.Text.tag_config-method" rel="nofollow"><code>Text.tag_config</code></a> to change the color of texts which tagged.</p> <pre><code>from tkinter import * from tkinter....
2
2016-07-02T11:34:16Z
[ "python", "python-3.x", "tkinter" ]
Indentation affecting program in Sage
38,159,745
<pre><code>k=10 l=1 o=2 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)-(x^k)-l m=poly.list() if(m!=0): print k </code></pre> <p>This gives output 10 as it should</p> <pre><code>k=10 o=2 l=1 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)...
0
2016-07-02T11:42:00Z
38,159,811
<p>Yes, that's your problem. Sage is basically Python when it comes to syntax (some extra goodies). In Python, the syntax <em>is</em> space and indentation. You only indent after colons (for things like loops, conditionals, definitions). Some good places to start learning basic Python are </p> <ul> <li><a href="ht...
0
2016-07-02T11:49:56Z
[ "python", "sage" ]
Indentation affecting program in Sage
38,159,745
<pre><code>k=10 l=1 o=2 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)-(x^k)-l m=poly.list() if(m!=0): print k </code></pre> <p>This gives output 10 as it should</p> <pre><code>k=10 o=2 l=1 F=IntegerModRing(k) R.&lt;t&gt;=F[] K.&lt;x&gt;=R.quotient(t^o-1) poly=((x+l)^k)...
0
2016-07-02T11:42:00Z
38,159,813
<p>The 'if' statement should not be indented. It won't run in the second example. In Python, there are strict rules in indentation. You can only indent if a new code block is started. The statement before the 'if' statement needs to be a loop statement, a conditional statement, or a function/class definition.</p>
1
2016-07-02T11:50:00Z
[ "python", "sage" ]
Mocking a Python Standard Library function with and without pytest-mock
38,159,765
<p>For testing purposes I would like to mock shutil.which (Python 3.5.1), which is called inside a simplified method find_foo()</p> <pre><code>def _find_foo(self) -&gt; Path: foo_exe = which('foo', path=None) if foo_exe: return Path(foo_exe) else: return None </code></pre> <p>I'm using pytest for implementing...
0
2016-07-02T11:44:45Z
38,159,836
<p>Try using <a href="http://pytest.org/latest/monkeypatch.html" rel="nofollow">monkeypatch</a>. You can see in the examples how they "monkeypatch" <code>os.getcwd</code> to return the wanted path. In your case I think that this should work:</p> <pre><code> monkeypatch.setattr("shutil.which", lambda: "/path/foo.exe") ...
1
2016-07-02T11:53:16Z
[ "python", "unit-testing", "mocking", "py.test" ]
Mocking a Python Standard Library function with and without pytest-mock
38,159,765
<p>For testing purposes I would like to mock shutil.which (Python 3.5.1), which is called inside a simplified method find_foo()</p> <pre><code>def _find_foo(self) -&gt; Path: foo_exe = which('foo', path=None) if foo_exe: return Path(foo_exe) else: return None </code></pre> <p>I'm using pytest for implementing...
0
2016-07-02T11:44:45Z
38,162,206
<p>Injecting the <code>which</code> method into your method or object would allow you to mock the dependency without <code>pytest-mock</code>.</p> <pre><code>def _find_foo(self, which_fn=shutil.which) -&gt; Path: foo_exe = which_fn('foo', path=None) if foo_exe: return Path(foo_exe) else: return None ...
1
2016-07-02T16:26:29Z
[ "python", "unit-testing", "mocking", "py.test" ]
Mocking a Python Standard Library function with and without pytest-mock
38,159,765
<p>For testing purposes I would like to mock shutil.which (Python 3.5.1), which is called inside a simplified method find_foo()</p> <pre><code>def _find_foo(self) -&gt; Path: foo_exe = which('foo', path=None) if foo_exe: return Path(foo_exe) else: return None </code></pre> <p>I'm using pytest for implementing...
0
2016-07-02T11:44:45Z
38,171,657
<p>I investigated more time studying unittest.mock and pytest-mock. I found a simple solution without modifying the production code using the patch decorator. In the following I pasted a code snippet demonstrating a third approach with pytest-mock:</p> <pre><code>def test_find_foo(mocker): mocker.patch('__main__.w...
0
2016-07-03T15:51:58Z
[ "python", "unit-testing", "mocking", "py.test" ]
itertools product should not contain combination having duplicate values
38,159,859
<p>I am trying to create combinations. Sample code is as follow:</p> <pre><code>a = [1, 2, 3], [1, 4, 5] combinations = list(itertools.product(*a)) </code></pre> <p>Output:</p> <pre><code>[(1, 1), (1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (3, 1), (3, 4), (3, 5)] </code></pre> <p>I don't need combination <code>(1,1)</...
2
2016-07-02T11:55:14Z
38,159,960
<p>For two iterables a simple list comprehension would do:</p> <pre><code>&gt;&gt;&gt; from itertools import product &gt;&gt;&gt; a = [1, 2, 3], [1, 4, 5] &gt;&gt;&gt; [(x, y) for x, y in product(*a) if x != y] [(1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (3, 1), (3, 4), (3, 5)] </code></pre> <p>If you need to filter a p...
3
2016-07-02T12:06:14Z
[ "python", "list", "combinations" ]
itertools product should not contain combination having duplicate values
38,159,859
<p>I am trying to create combinations. Sample code is as follow:</p> <pre><code>a = [1, 2, 3], [1, 4, 5] combinations = list(itertools.product(*a)) </code></pre> <p>Output:</p> <pre><code>[(1, 1), (1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (3, 1), (3, 4), (3, 5)] </code></pre> <p>I don't need combination <code>(1,1)</...
2
2016-07-02T11:55:14Z
38,159,985
<p>Edit the second part of your code like such:</p> <pre><code>for comb in combinations: if comb[0] == comb[1]: combinations.remove(comb) </code></pre>
0
2016-07-02T12:08:08Z
[ "python", "list", "combinations" ]
itertools product should not contain combination having duplicate values
38,159,859
<p>I am trying to create combinations. Sample code is as follow:</p> <pre><code>a = [1, 2, 3], [1, 4, 5] combinations = list(itertools.product(*a)) </code></pre> <p>Output:</p> <pre><code>[(1, 1), (1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (3, 1), (3, 4), (3, 5)] </code></pre> <p>I don't need combination <code>(1,1)</...
2
2016-07-02T11:55:14Z
38,160,106
<p>Here are 3 ways to do this</p> <pre><code>a = [1,2,3],[1,4,5] </code></pre> <ol> <li><pre><code>filter(lambda x: x[0] != x[1], [(x,y) for x in a[0] for y in a[1]]) </code></pre></li> <li><pre><code>combinations = list(itertools.product(*a)) [value for value in combinations if value[0] != value[1]] </code></pre></l...
0
2016-07-02T12:22:46Z
[ "python", "list", "combinations" ]
itertools product should not contain combination having duplicate values
38,159,859
<p>I am trying to create combinations. Sample code is as follow:</p> <pre><code>a = [1, 2, 3], [1, 4, 5] combinations = list(itertools.product(*a)) </code></pre> <p>Output:</p> <pre><code>[(1, 1), (1, 4), (1, 5), (2, 1), (2, 4), (2, 5), (3, 1), (3, 4), (3, 5)] </code></pre> <p>I don't need combination <code>(1,1)</...
2
2016-07-02T11:55:14Z
38,160,161
<p>In case your list of lists can have more than two sublists, you could compare the size of the tuple to the size of the tuple after converting it to a <code>set</code>, thus filtering duplicate elements.</p> <pre><code>&gt;&gt;&gt; import itertools &gt;&gt;&gt; b = [1,2,3],[1,4,5],[1,2,6] &gt;&gt;&gt; [x for x in it...
2
2016-07-02T12:29:23Z
[ "python", "list", "combinations" ]
Parallelizing different functions at the same time in python
38,159,931
<p>I want to execute f1 and f2 at the same time. but the following code doesn't work!</p> <pre><code>from multiprocessing import Pool def f1(x): return x*x def f2(x): return x^2 if __name__ == '__main__': x1=10 x2=20 p= Pool(2) out=(p.map([f1, f2], [x1, x2])) y1=out[0] y2=out[1] </code></pre>
2
2016-07-02T12:02:47Z
38,163,536
<p>I believe you'd like to use <code>threading.Thread</code> and <a href="https://docs.python.org/2/library/queue.html" rel="nofollow">shared queue</a> in your code.</p> <pre><code>from queue import Queue from threading import Thread import time def f1(q, x): # Sleep function added to compare execution times. ...
2
2016-07-02T19:02:48Z
[ "python", "multithreading", "parallel-processing", "subprocess" ]
Parallelizing different functions at the same time in python
38,159,931
<p>I want to execute f1 and f2 at the same time. but the following code doesn't work!</p> <pre><code>from multiprocessing import Pool def f1(x): return x*x def f2(x): return x^2 if __name__ == '__main__': x1=10 x2=20 p= Pool(2) out=(p.map([f1, f2], [x1, x2])) y1=out[0] y2=out[1] </code></pre>
2
2016-07-02T12:02:47Z
38,182,007
<blockquote> <p>I want to execute f1 and f2 at the same time. but the following code doesn't work! ...</p> <pre><code>out=(p.map([f1, f2], [x1, x2])) </code></pre> </blockquote> <p>The minimal change to your code is to replace the <code>p.map()</code> call with: </p> <pre><code>r1 = p.apply_async(f1, [x1]) out2 = ...
1
2016-07-04T10:07:05Z
[ "python", "multithreading", "parallel-processing", "subprocess" ]
Web Scrapping using python
38,159,942
<p>I have to write a program that scrapes the website “LivingSocial” for all the details of their deals and promo and store it in MySQLdatabase.<br> URL : "<a href="http://www.livingsocial.com/cities/15-san-francisco" rel="nofollow">http://www.livingsocial.com/cities/15-san-francisco</a>"<br> So far I have been abl...
-2
2016-07-02T12:04:10Z
38,160,839
<p>The first problem is that you are extracting descriptions and locations <em>independently</em> which would cause problems since not every deal has a location. Instead, you need to iterate over all "deals" and for each deal get the description and location:</p> <pre><code>deals = [ {'description': deal.findtext(...
0
2016-07-02T13:42:42Z
[ "python", "mysql", "web-scraping" ]
How to allow user to declare variable (Python)
38,159,955
<p>How do I allow my program to let a user declare their own variables, on Python, like this:</p> <pre><code>var x = 20 </code></pre> <p>Then possibly allow the user to make an if statement like this:</p> <pre><code>if x == 20: print("x is equal to 20") </code></pre>
-5
2016-07-02T12:05:23Z
38,160,031
<p>In Python the <code>var</code> declaration is not necessary, just type</p> <pre><code>x = 20 </code></pre> <p>Your conditional <code>print</code> statement should work just fine. This is a really basic question; I recommend you take a look at one of many free Python references, like <a href="http://greenteapress.c...
0
2016-07-02T12:12:31Z
[ "python" ]
filter by row_number in sqlalchemy
38,160,213
<p>how can I filter the row_number ==1 in the following query:</p> <pre><code>query = session.query(Foo, func.row_number().over( partition_by=Foo.foo_field, order_by=desc(Foo.foo_date_time)).label("row_number")) query = query.filter(Foo.time_key &lt;= time_key) # query = query.filter(row_number == 1) ...
0
2016-07-02T12:35:35Z
38,160,409
<p>I found it:</p> <pre><code> row_number_column = func.row_number().over(partition_by=Foo.foo_field, order_by=desc(Foo.foo_date_time)).label('row_number') query = self.session.query(Foo) query = query.filter(Foo.time_key &lt;= time_key) query = query.add_column(row_number_column) query = query.from...
1
2016-07-02T12:58:02Z
[ "python", "sqlalchemy", "row-number" ]
Count if another column contains a value
38,160,249
<p>I have a CSV file with two columns:</p> <pre><code>fruits values bananas 2 apples 5 oranges 4 pineapples 2 </code></pre> <p>I would like to sum the <code>values</code> if <code>fruits</code> has "apples" in it. It should return 5 + 2 = 7.</p> <p>I tried this:</p> <pre><code>sum= 0 if folh...
1
2016-07-02T12:39:48Z
38,160,554
<p>This is pretty straightforward:</p> <pre><code>In [10]: df Out[10]: fruits values 0 bananas 2 1 apples 5 2 oranges 4 3 pineapples 2 In [11]: df[df.fruits.str.contains('apples')]['values'].sum() Out[11]: 7 </code></pre>
2
2016-07-02T13:13:05Z
[ "python", "pandas", "sumifs" ]
Upload photo on AWS w/ Python script
38,160,252
<p>I am writing a Python script that uploads photos from my computer to AWS.</p> <p>I can get <code>policy, key, signature credentials</code> but cannot find information on AWS website the method to upload photo from my computer to AWS repository:</p> <pre><code>Location : https://myrepo.s3.amazonaws.com/folder1/1234...
1
2016-07-02T12:40:20Z
38,160,317
<p>In the getting started article i found the example</p> <pre><code>import boto s3 = boto.connect_s3() bucket = s3.create_bucket('media.yourdomain.com') # bucket names must be unique key = bucket.new_key('examples/first_file.csv') key.set_contents_from_filename('/home/patrick/first_file.csv') key.set_acl('public-rea...
0
2016-07-02T12:47:13Z
[ "python", "amazon-web-services", "amazon-s3" ]
How to protect custom endpoints using BasicAuth?
38,160,290
<p>Say I have enabled authentication to the resources using BasicAuth: </p> <pre><code>class MyBasicAuth(BasicAuth): def check_auth(self,username,password,allowed_roles,resource,method): return username == 'secretusername' and password == 'secretpass' </code></pre> <p>I also have custom routes which are u...
2
2016-07-02T12:44:24Z
38,161,090
<p>If you are using flask blueprints for your custom routes, you can add a before request function for your blueprint to do that.</p> <p>First, create a function to check authentication from blueprints. You need to get the <code>Authorization</code> header from the flask request by yourself, like this:</p> <pre><code...
0
2016-07-02T14:13:11Z
[ "python", "eve" ]
How to protect custom endpoints using BasicAuth?
38,160,290
<p>Say I have enabled authentication to the resources using BasicAuth: </p> <pre><code>class MyBasicAuth(BasicAuth): def check_auth(self,username,password,allowed_roles,resource,method): return username == 'secretusername' and password == 'secretpass' </code></pre> <p>I also have custom routes which are u...
2
2016-07-02T12:44:24Z
38,167,727
<p>You can leverage the <code>requires_auth</code> decorator which is used internally by Eve itself. That way, your auth class will also be used to protect your custom routes:</p> <pre><code>from eve import Eve from eve.auth import requires_auth app = Eve() @app.route('/hello') @requires_auth('resource') def hello_w...
1
2016-07-03T07:35:45Z
[ "python", "eve" ]
How to copy a file in a zipfile into a certain directory?
38,160,310
<p>I need only one subfile in each of 500 zipfiles, the paths are the same, like:</p> <pre><code>120132.zip/A/B/C/target_file 212332.zip/A/B/C/target_file .... </code></pre> <p>How can I copy all these target files into one directory? Keeping the entire paths in the new directory will be the best, which I mean is:</p...
1
2016-07-02T12:46:48Z
38,160,497
<p><a href="https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.extract" rel="nofollow"><code>ZipFile.extract</code></a> accepts optional <code>path</code> specifying into which directory it will extract file:</p> <pre><code>import os import zipfile zip_filepath = ['120132.zip', '212332.zip', ...] # or gl...
1
2016-07-02T13:07:06Z
[ "python", "zip" ]
Python: Communicate between two files
38,160,390
<p>I have a defined function in one program:</p> <pre><code>def start(): QuadraticButton = Button(left_frame, text = "Quadratic Equation Solver", command = calculateQuad) QuadraticButton.pack() </code></pre> <p>and then in a separate script I have the "calculate quad" function defined. How can I link these two togeth...
-3
2016-07-02T12:55:04Z
38,160,492
<p>include my_utils</p> <pre><code>def start(): from .utils import calculateQuad QuadraticButton = Button(left_frame, text = "Quadratic Equation Solver", command = calculateQuad) QuadraticButton.pack() </code></pre>
2
2016-07-02T13:06:31Z
[ "python", "tkinter" ]
Keep-alive within python-requests module
38,160,418
<p>I've got a question about python-requests module. According to the docs </p> <blockquote> <p>thanks to urllib3, keep-alive is 100% automatic within a session! Any requests that you make within a session will automatically reuse the appropriate connection!</p> </blockquote> <p>My sample code looks like this:</p> ...
0
2016-07-02T12:58:42Z
38,160,444
<p>Use a <a href="http://docs.python-requests.org/en/latest/user/advanced/#session-objects" rel="nofollow"><code>Session()</code> instance</a>:</p> <pre><code>def make_double_get_request(): session = requests.Session() response = session.get(url=API_URL, headers=headers, timeout=10) print response.text ...
2
2016-07-02T13:00:39Z
[ "python", "http", "python-requests", "keep-alive" ]
Python, Find the drive letter with windows installed
38,160,446
<p>I started making a program for fun when I encountered a problem. The problem was that I wanted to find the drive letter with windows installed on it (root drive). I assumed there was a function already made for that but I searched for a while and could not find one. </p> <p>I wrote this code to do what I just descr...
1
2016-07-02T13:00:47Z
38,160,636
<p>There is an environment variable <code>windir</code>. On my computer in contains "C:\Windows". You can read this variable by <code>os.getenv('WINDIR')</code> (refer to <a href="https://docs.python.org/2/library/os.html#os.getenv" rel="nofollow">python 2:os.getenv()</a> or <a href="https://docs.python.org/3/library/o...
2
2016-07-02T13:21:45Z
[ "python", "winapi" ]
Stripping string in python between quotes
38,160,518
<p>I have a string </p> <pre><code>text:u'tsod' </code></pre> <p>The "text:U" is part of the string.</p> <p>I want to strip only the characters between the single quotes. I know how to strip based on location but i do not know how to strip based on a value in my case the " ' " , I simply want to extract "tsod"</p> ...
1
2016-07-02T13:09:02Z
38,160,543
<p>You can split on the inverted comma <code>"'"</code>:</p> <pre><code>&gt;&gt;&gt; s = "text:u'tsod'".split("'") &gt;&gt;&gt; s ['text:u', 'tsod', ''] &gt;&gt;&gt; s[1] 'tsod' </code></pre>
1
2016-07-02T13:12:10Z
[ "python", "string", "python-2.7" ]
Stripping string in python between quotes
38,160,518
<p>I have a string </p> <pre><code>text:u'tsod' </code></pre> <p>The "text:U" is part of the string.</p> <p>I want to strip only the characters between the single quotes. I know how to strip based on location but i do not know how to strip based on a value in my case the " ' " , I simply want to extract "tsod"</p> ...
1
2016-07-02T13:09:02Z
38,161,072
<p>If you have multiple pairs of quotes, then this solution may help:</p> <pre><code>import re strng = "text:u'tsod';text2:u'tsod2';text3:u'tsod3'" qlist = re.findall("\'(.*?)\'",strng) </code></pre> <p>Then <code>qlist</code> will have : <code>['tsod', 'tsod2', 'tsod3'] </code></p>
2
2016-07-02T14:10:50Z
[ "python", "string", "python-2.7" ]
Longest Increasing Subsequence optimization
38,160,542
<p>The <em>Longest Increasing Subsequence</em> problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order and in which the subsequence is as long as possible.</p> <p>Here is my O(n^2) approach which is running very slow for long input:</p> <pre><code>N = int(input()) ...
-1
2016-07-02T13:12:07Z
38,161,668
<p>Great resources have been mentioned in the comments; if you still want a piece of python code, I've written and explained it here.</p> <p>In this algorithm, for all <code>L &lt; N</code>, we keep a track of the values in the input which represent the endpoint of the current longest increasing subsequence of length ...
2
2016-07-02T15:25:37Z
[ "python", "dynamic-programming", "subsequence" ]
Merge sort, where are the sublists saved?
38,160,564
<p>I have included the code I am using.</p> <p>I understand that the start of the code continues splitting the sublists until you have single values. The single values are saved in the variables lefthalf and righthalf and are then merged in sorted order.</p> <p>How does the code merge two lists of two elements? As I ...
4
2016-07-02T13:14:10Z
38,160,689
<p>The first <code>while</code> loop pick a smaller smaller item from <code>lefthalf</code>, <code>righthalf</code> until one of two lists run out. (<code>lefthalf</code>, <code>righthalf</code> each contains sorted items)</p> <pre><code>while i &lt; len(lefthalf) and j &lt; len(righthalf): if lefthalf[i] &lt; rig...
3
2016-07-02T13:28:31Z
[ "python", "algorithm", "sorting" ]
Merge sort, where are the sublists saved?
38,160,564
<p>I have included the code I am using.</p> <p>I understand that the start of the code continues splitting the sublists until you have single values. The single values are saved in the variables lefthalf and righthalf and are then merged in sorted order.</p> <p>How does the code merge two lists of two elements? As I ...
4
2016-07-02T13:14:10Z
38,160,726
<p>So this is a inplace version of <code>mergeSort</code>, in that it takes in a list and modifies it to be a sorted version. (Though it involves creating a copy of each half, so it isn't constant space). Here it is commented as to what the code is doing:</p> <pre><code>def mergeSort(alist): if len(alist)&gt;1: ...
3
2016-07-02T13:31:32Z
[ "python", "algorithm", "sorting" ]
Graceful exit server when using Django's autoreloader
38,160,577
<p>I am using a custom Django <code>runserver</code> command that is supposed to run a bunch of cleanup functions upon termination. This works fine as long as I don't use the autoreloader: by server catches the KeyboardInterrupt exception properly and exits gracefully.</p> <p>However, if I use Django's autoreloader, t...
0
2016-07-02T13:15:31Z
38,171,865
<p>Try using the <code>atexit</code> module to catch the termination. It should work for everything which acts like SIGINT or SIGTERM, SIGKILL cannot be interrupted (but should not be sent by any auto-restart script without sending SIGTERM before).</p>
1
2016-07-03T16:17:33Z
[ "python", "django" ]
How to efficiently multiply a list of NumPy views with corresponding weights?
38,160,585
<p>I am facing a memory and speed problem using NumPy but my issue is quite simple.</p> <ul> <li><code>A</code> is a large NumPy array of <code>H * W</code> integers.</li> <li><code>V</code> is a list containing <code>N</code> views of the large array <code>A</code>, each view as the same <code>(Hv, Wv)</code> shape.<...
2
2016-07-02T13:16:50Z
38,160,735
<p>I am assuming <code>V</code> is given as a list and we have don't have access to optimize creating it or just don't need to. So, <code>A</code> is out of the equation and we are left with <code>V</code> and <code>K</code> to get to final output <code>B</code> and thus, left with optimizing the last step.</p> <p>To ...
1
2016-07-02T13:32:28Z
[ "python", "arrays", "numpy", "optimization", "memory-management" ]
Python: single colon vs double colon
38,160,637
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
4
2016-07-02T13:21:45Z
38,160,686
<p>There is no difference. You're indexing by an identical <code>slice</code> object.</p>
0
2016-07-02T13:28:23Z
[ "python", "numpy", "slice", "colon" ]
Python: single colon vs double colon
38,160,637
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
4
2016-07-02T13:21:45Z
38,160,722
<p><strong>No</strong>, there is no difference.</p> <p>See the Python documentation for <a href="https://docs.python.org/2/library/functions.html#slice" rel="nofollow">slice</a>:</p> <p>From the docs: <code>a[start:stop:step]</code></p> <blockquote> <p>The start and step arguments default to None. Slice objects ha...
3
2016-07-02T13:31:06Z
[ "python", "numpy", "slice", "colon" ]
Python: single colon vs double colon
38,160,637
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
4
2016-07-02T13:21:45Z
38,160,723
<p>Both syntaxes result in the same indexes.</p> <pre><code>class Foo(object): def __getitem__(self, idx): print(idx) Foo()[1::,6] # prints (slice(1, None, None), 6) Foo()[1:,6] # prints (slice(1, None, None), 6) </code></pre> <p>Basically, <code>1::,6</code> is a tuple of a slice (<code>1::</code>) and a numb...
3
2016-07-02T13:31:11Z
[ "python", "numpy", "slice", "colon" ]
Python: single colon vs double colon
38,160,637
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
4
2016-07-02T13:21:45Z
38,160,733
<p>It's like this: <code>s[start:end:step]</code>. Slice s from start to end with step <em>step</em>.</p>
0
2016-07-02T13:32:11Z
[ "python", "numpy", "slice", "colon" ]
Python: single colon vs double colon
38,160,637
<p>What is the difference between single and double colon in this situation? <code>data[0:,4]</code> vs <code>data[0::,4]</code></p> <pre><code>women_only_stats = data[0::,4] == "female" men_only_stats = data[0::,4] != "female" </code></pre> <p>I tried to replace <code>data[0::,4]</code> with <code>data[0:,4]</...
4
2016-07-02T13:21:45Z
38,160,773
<p>In your case data is </p> <pre><code>data = ['1' '0' '3' 'Braund, Mr. Owen Harris' 'male' '22' '1' '0' 'A/5 21171' '7.25' '' 'S'] </code></pre> <p>So it is equal to </p> <pre><code>data = ['103Br.............7.25S'] </code></pre> <p>In this sitation there is only single item in list so data[0::4] or data[0:4] do...
0
2016-07-02T13:36:48Z
[ "python", "numpy", "slice", "colon" ]
Python if statement no cap check
38,160,724
<p>I have a input that the user types in something Example</p> <pre><code>Test = input( 'Type in something' ) if Test == 'SOMETHING' : print( 'You idiot!' ) </code></pre> <p>How do I ignore the if the word something is in all caps or non caps example: Something SOMETHING SoMeThinG</p> <p>Sorry My Grammar is so b...
0
2016-07-02T13:31:12Z
38,160,761
<p>Just make everything lowercase and strip whitespace </p> <pre><code>Test.lower().strip() </code></pre> <p>Provided <code>SOMETHING</code> is in lowercase.</p>
1
2016-07-02T13:35:19Z
[ "python", "python-3.x" ]
Python if statement no cap check
38,160,724
<p>I have a input that the user types in something Example</p> <pre><code>Test = input( 'Type in something' ) if Test == 'SOMETHING' : print( 'You idiot!' ) </code></pre> <p>How do I ignore the if the word something is in all caps or non caps example: Something SOMETHING SoMeThinG</p> <p>Sorry My Grammar is so b...
0
2016-07-02T13:31:12Z
38,160,767
<pre><code>if Test.upper() == "something".upper(): print("You idiot") </code></pre> <p>What about making the two parts of the equatation upper/lower?</p> <pre><code>Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more ...
1
2016-07-02T13:35:52Z
[ "python", "python-3.x" ]
Appending only unique items to python list?
38,160,752
<p>I am running a python scraping script and am getting a list like this - </p> <pre><code>[u'UI/UX Designer\xa0\u2013 Creative Head ', u'UX Designer ', u'UI/UX Designer\xa0\u2013 Creative Head', u'UX Designer'] </code></pre> <p>I wanted to add unique items only from the list so i used this - </p> <pre><code>profile...
1
2016-07-02T13:34:15Z
38,160,825
<p>The first two strings in the list contains trailing spaces.</p> <p>A string with a space and the other string without a space are different even though other characters are same:</p> <pre><code>&gt;&gt;&gt; 'a' == 'a ' False </code></pre> <p>You need to strip them:</p> <pre><code>for i in k: i = i.strip() #...
2
2016-07-02T13:41:42Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Appending only unique items to python list?
38,160,752
<p>I am running a python scraping script and am getting a list like this - </p> <pre><code>[u'UI/UX Designer\xa0\u2013 Creative Head ', u'UX Designer ', u'UI/UX Designer\xa0\u2013 Creative Head', u'UX Designer'] </code></pre> <p>I wanted to add unique items only from the list so i used this - </p> <pre><code>profile...
1
2016-07-02T13:34:15Z
38,160,864
<p>Looking at the output, the code you are using is actually working. The problem is, there is an extra space in the text:</p> <pre><code>[u'UI/UX Designer\xa0\u2013 Creative Head ', # Note the space here u'UX Designer ', # and here u'UI/UX Designer\xa0\u2013 Creative Head', u'UX Designer' ] </code></pre> <p>All you ...
2
2016-07-02T13:45:44Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Appending only unique items to python list?
38,160,752
<p>I am running a python scraping script and am getting a list like this - </p> <pre><code>[u'UI/UX Designer\xa0\u2013 Creative Head ', u'UX Designer ', u'UI/UX Designer\xa0\u2013 Creative Head', u'UX Designer'] </code></pre> <p>I wanted to add unique items only from the list so i used this - </p> <pre><code>profile...
1
2016-07-02T13:34:15Z
38,160,870
<p>There is a trailing space at the end of your strings, you should strip the excess whitespace. Use set or list comprehensions to make your code Pythonic. If you want the elements to be unique I also suggest using a set:</p> <pre><code>&gt;&gt;&gt; st = [u'UI/UX Designer\xa0\u2013 Creative Head ', u'UX Designer ', u'...
3
2016-07-02T13:46:19Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Sorting list by alphabetical order, with special case for certain starting letter
38,160,828
<p>Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first. </p> <p>For example:</p> <pre><code>['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] </code></pre> <p>Should yield:</p> <pre><code>['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ...
2
2016-07-02T13:42:00Z
38,160,887
<p>Just make a particular case in your key method: if starts with x, return a truncated string starting with "0" so it will appear first, but will be still sorted after "x".</p> <pre><code>z=['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] z.sort(key=lambda x : "0"+x if x.startswith("x") else x) print(z) </code></pre> ...
1
2016-07-02T13:49:01Z
[ "python", "list", "sorting" ]
Sorting list by alphabetical order, with special case for certain starting letter
38,160,828
<p>Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first. </p> <p>For example:</p> <pre><code>['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] </code></pre> <p>Should yield:</p> <pre><code>['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ...
2
2016-07-02T13:42:00Z
38,160,889
<pre><code>&gt;&gt;&gt; sorted(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'], key=lambda x: (not x.startswith('x'), x)) ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] </code></pre> <p>The <a href="https://docs.python.org/2/library/functions.html#sorted" rel="nofollow"><code>sorted()</code></a> builtin return...
1
2016-07-02T13:49:28Z
[ "python", "list", "sorting" ]
Sorting list by alphabetical order, with special case for certain starting letter
38,160,828
<p>Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first. </p> <p>For example:</p> <pre><code>['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] </code></pre> <p>Should yield:</p> <pre><code>['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ...
2
2016-07-02T13:42:00Z
38,160,894
<p><a href="https://docs.python.org/3/library/functions.html#sorted"><code>sorted</code></a> or <a href="https://docs.python.org/3/library/stdtypes.html#list.sort"><code>list.sort</code></a> accepts optional <code>key</code> keyword argument. That is the function used to get sort key, and the return value of the functi...
5
2016-07-02T13:50:18Z
[ "python", "list", "sorting" ]
Sorting list by alphabetical order, with special case for certain starting letter
38,160,828
<p>Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first. </p> <p>For example:</p> <pre><code>['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] </code></pre> <p>Should yield:</p> <pre><code>['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ...
2
2016-07-02T13:42:00Z
38,160,901
<p>You can sort it using the built-in <code>list.sort()</code> and then use list comprehension to get the output you desire as follows:</p> <pre><code>sl = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] sl.sort() sl = [el for el in sl if el.startswith("x")]+[el for el in sl if not el.startswith("x")] </code></pre>
0
2016-07-02T13:50:36Z
[ "python", "list", "sorting" ]
Sorting list by alphabetical order, with special case for certain starting letter
38,160,828
<p>Given a list of strings, I want to return a list with the strings in sorted order, except group all the strings that begin with 'x' first. </p> <p>For example:</p> <pre><code>['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] </code></pre> <p>Should yield:</p> <pre><code>['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] ...
2
2016-07-02T13:42:00Z
38,161,186
<pre><code>words = ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] result = [i for _, i in sorted((word[0]!='x', word) for word in words)] </code></pre>
1
2016-07-02T14:25:06Z
[ "python", "list", "sorting" ]
Cannot load css in Django template
38,161,032
<p>Here is my reduced html code:</p> <pre><code>{% load staticfiles %} &lt;html lang="en"&gt; &lt;head&gt; &lt;link href="{% static '/css/buttonform.css' %}" rel="stylesheet"&gt; &lt;/head&gt; &lt;/html&gt; </code></pre> <p>And here is my <em>settings.py</em><strong>:</strong></p> <pre><code>INSTALL...
0
2016-07-02T14:06:05Z
38,161,068
<p>Change</p> <pre><code>&lt;link href="{% static '/css/buttonform.css' %}" rel="stylesheet"&gt; </code></pre> <p>to</p> <pre><code>&lt;link href="{% static 'css/buttonform.css' %}" rel="stylesheet"&gt; </code></pre>
3
2016-07-02T14:10:15Z
[ "python", "html", "css", "django" ]
Newbie Debugging a Python Code
38,161,065
<p>I want local variable of a class to be changed by other class. My script is similar to the following :</p> <pre><code>import datetime b = [] class P: def __init__(self): self.count = 1 self.create() def create(self): global b a = C(self.count) for i in range(10): ...
-4
2016-07-02T14:09:41Z
38,161,105
<p>Make <code>C</code> constructor to accept <code>P</code> instance. And call the method of <code>P</code> to append item to instance attribute of <code>P</code> object.</p> <pre><code>class P: def __init__(self): self.count = 1 self.items = [] self.create() def append(self, item): ...
0
2016-07-02T14:15:14Z
[ "python", "python-2.7", "super" ]
Newbie Debugging a Python Code
38,161,065
<p>I want local variable of a class to be changed by other class. My script is similar to the following :</p> <pre><code>import datetime b = [] class P: def __init__(self): self.count = 1 self.create() def create(self): global b a = C(self.count) for i in range(10): ...
-4
2016-07-02T14:09:41Z
38,161,808
<p>You are probably looking for a class attribute. If you add <code>b</code> as an attribute to the <code>C</code> class, it can be accessed as <code>C.b</code> and <code>C().b</code>, i.e. from a reference to the class or any instance.</p> <pre><code>class C(object): # classes in py2 should inherit from object! b ...
0
2016-07-02T15:42:48Z
[ "python", "python-2.7", "super" ]
How do I efficiently map only those points that fall within the bounding box of a map?
38,161,133
<p>I have the following code, where <code>mp</code> is a <code>Shapely</code> <code>Multipolygon</code> off of a <code>Fiona</code> box:</p> <pre><code>ax = fig.add_subplot(111) minx, miny, maxx, maxy = mp.bounds w, h = maxx - minx, maxy - miny ax.set_xlim(minx, maxx) ax.set_ylim(miny, maxy) ax.set_aspect(1) patches =...
1
2016-07-02T14:18:31Z
38,189,112
<p>I guess it would be most efficient to filter the points on a pandas level. For that get the bounds of the Multipolygon using its <code>bounds</code> property and then filter the dataframe using</p> <pre><code>df[(df.lat &gt; latmin) &amp; (df.lat &lt; latmax) &amp; (df.long &gt; longmin) &amp; (df.long &lt; lon...
1
2016-07-04T16:33:11Z
[ "python", "pandas", "matplotlib" ]
Time duration by timedelta in python
38,161,152
<p>`hi I am trying to find time duration between start time and end time, but I have only one output! is there any solution to select all rows!? my code is following like this</p> <pre><code>import csv import datetime import time from datetime import datetime from datetime import timedelta,date f1=open("starttime.csv"...
0
2016-07-02T14:21:31Z
38,161,236
<p>You have only one output because all items in <code>time_arry_temp</code> poinst to same object, so to fix problem replace line:</p> <pre><code>time_arry_temp = [[]]*5 </code></pre> <p>to</p> <pre><code>time_arry_temp = [[] for _ in range(5)] </code></pre> <p>Take a look on <a href="http://docs.python-guide.org/...
0
2016-07-02T14:31:20Z
[ "python" ]
Time duration by timedelta in python
38,161,152
<p>`hi I am trying to find time duration between start time and end time, but I have only one output! is there any solution to select all rows!? my code is following like this</p> <pre><code>import csv import datetime import time from datetime import datetime from datetime import timedelta,date f1=open("starttime.csv"...
0
2016-07-02T14:21:31Z
38,161,710
<p>Well I've edited your code a little and written this. Check if it does your job.</p> <pre><code>import csv from datetime import datetime,timedelta get_time=lambda x: datetime.strptime(x, '%d/%m/%Y %H:%M') with open("starttime.csv") as f , open("endtime.csv") as g: d1=[get_time(row[0]) for row in csv.reader(f)] ...
0
2016-07-02T15:30:54Z
[ "python" ]
matplotlib: How to combine multiple bars with lines
38,161,161
<p>I have a very simple grouped-bar chart with 5 groups of 4 bars each. I used the example from the <a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">matplotlib documentation</a>, which goes like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt ind = np.arange(5) av...
1
2016-07-02T14:22:40Z
38,162,841
<p>I have started to learn <strong>Matplotlib</strong> and <strong>Numpy</strong> recently and found your question quite interesting. </p> <p>So, I spend time to create a combined graph of grouped-bar chart and line chart relevant to that grouped-bar chart. </p> <p><strong>Result</strong>: <a href="http://i.stack.img...
1
2016-07-02T17:37:29Z
[ "python", "matplotlib", "bar-chart", "linechart" ]
matplotlib: How to combine multiple bars with lines
38,161,161
<p>I have a very simple grouped-bar chart with 5 groups of 4 bars each. I used the example from the <a href="http://matplotlib.org/examples/api/barchart_demo.html" rel="nofollow">matplotlib documentation</a>, which goes like this:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt ind = np.arange(5) av...
1
2016-07-02T14:22:40Z
38,184,630
<p>Thank you @arsho for your input. I have made it a little more compact. It fixed also the error on the last group of bars in your code. See comments in code. Hope this helps.</p> <p>For those like me who are new to matplotlib: we can simple plot a line to the subplot, no matter if it already contains bars.</p> <pre...
0
2016-07-04T12:19:50Z
[ "python", "matplotlib", "bar-chart", "linechart" ]
Python code to automatically assign parsed json objects to their original names
38,161,259
<p>I have dumped a couple of variables I need to store in a json object as shown here-</p> <pre><code>def write_json(): variable = {} variable['p_id'] = p_id variable['s_id'] = s_id variable['t_id'] = t_id variable['b_start'] = b_start variable['b_end'] = b_end variable['wsp_after'] = wsp_a...
-1
2016-07-02T14:33:47Z
38,174,715
<p>Your current code doesn't work because the following lines just bind (and rebind, for the later values in the loop) a global variable named <code>'key'</code>:</p> <pre><code>global key key = variable[key] </code></pre> <p>While I'm not sure your design is really a good one, if you're sure you want all the values ...
0
2016-07-03T22:01:32Z
[ "python", "json" ]
Python code to automatically assign parsed json objects to their original names
38,161,259
<p>I have dumped a couple of variables I need to store in a json object as shown here-</p> <pre><code>def write_json(): variable = {} variable['p_id'] = p_id variable['s_id'] = s_id variable['t_id'] = t_id variable['b_start'] = b_start variable['b_end'] = b_end variable['wsp_after'] = wsp_a...
-1
2016-07-02T14:33:47Z
38,178,100
<p>Here's the solution -</p> <pre><code>with open('variable.json', 'r') as fp: variable = json.load(fp) for key in variable.keys(): exec(key + " = variable['" + key + "']") </code></pre> <p>The problem before was that each 'key' was a string, not an object. Using the exec function successfully parses each s...
0
2016-07-04T06:27:08Z
[ "python", "json" ]
Python using futures with loop_forever
38,161,271
<p>Just started experimenting with asynch which looks really cool. I'm trying to use futures with an asynch coroutine that runs forever but I get this error:</p> <pre><code>Task exception was never retrieved future: &lt;Task finished coro=&lt;slow_operation() done, defined at ./asynchio-test3.py:5&gt; exception=Inval...
1
2016-07-02T14:35:53Z
38,161,328
<p><code>slow_operator</code> is called indefinitely, calling <a href="https://docs.python.org/3/library/asyncio-task.html#asyncio.Future.set_result" rel="nofollow"><code>set_result</code></a> for the same future object multiple times; which is not possbile.</p> <pre><code>&gt;&gt;&gt; import asyncio &gt;&gt;&gt; futu...
2
2016-07-02T14:44:51Z
[ "python", "python-3.x", "python-asyncio" ]
Python using futures with loop_forever
38,161,271
<p>Just started experimenting with asynch which looks really cool. I'm trying to use futures with an asynch coroutine that runs forever but I get this error:</p> <pre><code>Task exception was never retrieved future: &lt;Task finished coro=&lt;slow_operation() done, defined at ./asynchio-test3.py:5&gt; exception=Inval...
1
2016-07-02T14:35:53Z
38,162,493
<p>Following @falsetru answer this is a complete program that has 3 asynch coroutines each with their own got_result function. I'm using v3.4 so thats why I don't use the new syntax. As an interesting side effect the output clearly demonstrates the single threaded nature of coroutines. I hope its useful as a templat...
1
2016-07-02T16:58:45Z
[ "python", "python-3.x", "python-asyncio" ]
How to match a string against multiple regex?
38,161,309
<p>At the moment I am using the below filter to increment elements in arr, given a list of strings as an argument, is there an efficient way to do this in python.I got millions of such lists to validate upon.</p> <pre><code> def countbycat(tempfilter): arr=[0,0,0,0,0] apattern,dpattern,mpattern,upatte...
2
2016-07-02T14:42:15Z
38,161,411
<p>For the regular expressions given in the question, you can use following regular expression using character class:</p> <pre><code>[admut]- </code></pre> <ul> <li><code>[admut]</code> will match any of <code>a</code>, <code>d</code>, <code>m</code>, <code>u</code>, <code>t</code></li> <li><code>^</code> can be omit...
4
2016-07-02T14:54:42Z
[ "python", "regex", "string" ]
How to match a string against multiple regex?
38,161,309
<p>At the moment I am using the below filter to increment elements in arr, given a list of strings as an argument, is there an efficient way to do this in python.I got millions of such lists to validate upon.</p> <pre><code> def countbycat(tempfilter): arr=[0,0,0,0,0] apattern,dpattern,mpattern,upatte...
2
2016-07-02T14:42:15Z
38,161,475
<p>In your simple case, go for <a href="http://stackoverflow.com/a/38161411/3821804">falsetru's answer</a></p> <p>In general case, you can combine your patterns into one regex (provided that your regexes doesn't contain capturing groups), and check which wart of regex matched:</p> <pre><code>patterns = ["^[a]-+", "^[...
0
2016-07-02T15:01:51Z
[ "python", "regex", "string" ]
How to match a string against multiple regex?
38,161,309
<p>At the moment I am using the below filter to increment elements in arr, given a list of strings as an argument, is there an efficient way to do this in python.I got millions of such lists to validate upon.</p> <pre><code> def countbycat(tempfilter): arr=[0,0,0,0,0] apattern,dpattern,mpattern,upatte...
2
2016-07-02T14:42:15Z
38,161,624
<p>Don't use regex for this. You are checking for a very specific, fixed condition. Namely, <code>each[1] == '-'</code> and <code>each[0] in 'admut'</code>. Both of these are <em>much</em> faster than regex. The later can also be used as a mapping.</p> <pre><code>def countbycat(tempfilter): arr = [0, 0, 0, 0, 0] ...
2
2016-07-02T15:20:06Z
[ "python", "regex", "string" ]
How to make columns in dataframe to be unique?
38,161,398
<p>I wanted to apply one-hot encoding (it isn't important to understand the question) to my dataframe this way:</p> <pre><code>train = pd.concat([train, pd.get_dummies(train['Canal_ID'])], axis=1, join_axes=[train.index]) train.drop([11,'Canal_ID'],axis=1, inplace = True) train = pd.concat([train, pd.get_dummies(trai...
2
2016-07-02T14:53:13Z
38,161,490
<p>I would append a random number to the original id of the columns.</p> <pre><code>new_cols = train.columns new_cols = new_cols.map(lambda x: "{}-{}".format(x, randint(0,100)) train.columns = new_cols </code></pre>
1
2016-07-02T15:04:27Z
[ "python", "python-2.7", "pandas", "unique" ]
How to make columns in dataframe to be unique?
38,161,398
<p>I wanted to apply one-hot encoding (it isn't important to understand the question) to my dataframe this way:</p> <pre><code>train = pd.concat([train, pd.get_dummies(train['Canal_ID'])], axis=1, join_axes=[train.index]) train.drop([11,'Canal_ID'],axis=1, inplace = True) train = pd.concat([train, pd.get_dummies(trai...
2
2016-07-02T14:53:13Z
38,161,503
<p>You can set new column names by <code>range</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shape.html" rel="nofollow"><code>shape</code></a>:</p> <pre><code>df.columns = range(df.shape[1]) </code></pre> <p>Sample:</p> <pre><code>df = pd.DataFrame({'A':[1,2,3], ...
1
2016-07-02T15:06:50Z
[ "python", "python-2.7", "pandas", "unique" ]
How to make columns in dataframe to be unique?
38,161,398
<p>I wanted to apply one-hot encoding (it isn't important to understand the question) to my dataframe this way:</p> <pre><code>train = pd.concat([train, pd.get_dummies(train['Canal_ID'])], axis=1, join_axes=[train.index]) train.drop([11,'Canal_ID'],axis=1, inplace = True) train = pd.concat([train, pd.get_dummies(trai...
2
2016-07-02T14:53:13Z
38,162,259
<p>Try this: get_dummies has a "prefix" method</p> <pre><code>df = pd.DataFrame({'A': ['a', 'b', 'a'], 'B': ['b', 'a', 'c'], 'C': [1, 2, 3]}) pd.get_dummies(df, prefix=['col1', 'col2']) C col1_a col1_b col2_a col2_b col2_c 0 1 1 0 0 1 0 1 2 0 1...
2
2016-07-02T16:32:26Z
[ "python", "python-2.7", "pandas", "unique" ]
Python: Removing a last element from list of list?
38,161,447
<p>Given a List <code>A</code>. I want to remove the last element (<code>b,'zz')</code>of each list with list <code>A</code>.</p> <pre><code>A = [ [(a,'rr'),(c,'rr'),(d,'rr'),(b,'zz')], [(g,'rr'),(h,'rr'),(e,'rr'),(b,'zz')], [(c,'rr'),(r,'rr'),(s,'rr'),(b,'zz')] ] </code></pre> <p>What I tried.</p> <pre>...
1
2016-07-02T14:58:51Z
38,161,457
<p>You could simply <em>slice</em> up till the last item in a list comprehension:</p> <pre><code>A = [l[:-1] for l in A] </code></pre>
3
2016-07-02T15:00:08Z
[ "python", "list", "python-3.x", "text" ]
Python: Removing a last element from list of list?
38,161,447
<p>Given a List <code>A</code>. I want to remove the last element (<code>b,'zz')</code>of each list with list <code>A</code>.</p> <pre><code>A = [ [(a,'rr'),(c,'rr'),(d,'rr'),(b,'zz')], [(g,'rr'),(h,'rr'),(e,'rr'),(b,'zz')], [(c,'rr'),(r,'rr'),(s,'rr'),(b,'zz')] ] </code></pre> <p>What I tried.</p> <pre>...
1
2016-07-02T14:58:51Z
38,161,471
<p>You can use the <code>list.pop()</code> method:</p> <pre><code>for i in A: i.pop() </code></pre> <p>Reference: <a href="https://docs.python.org/2/tutorial/datastructures.html" rel="nofollow">https://docs.python.org/2/tutorial/datastructures.html</a></p>
4
2016-07-02T15:01:32Z
[ "python", "list", "python-3.x", "text" ]
Python: Removing a last element from list of list?
38,161,447
<p>Given a List <code>A</code>. I want to remove the last element (<code>b,'zz')</code>of each list with list <code>A</code>.</p> <pre><code>A = [ [(a,'rr'),(c,'rr'),(d,'rr'),(b,'zz')], [(g,'rr'),(h,'rr'),(e,'rr'),(b,'zz')], [(c,'rr'),(r,'rr'),(s,'rr'),(b,'zz')] ] </code></pre> <p>What I tried.</p> <pre>...
1
2016-07-02T14:58:51Z
38,161,521
<p><code>del</code> is a statement and must be used accordingly. Most importantly, it cannot be used in an assignment.</p> <p>Simply remove the assignment:</p> <pre><code>for i in A: del i[-1] </code></pre>
2
2016-07-02T15:09:06Z
[ "python", "list", "python-3.x", "text" ]
Cannot execute python script on Rasberry Pi startup
38,161,476
<p>I'm having problems with starting a python script on Raspberry Pi boot. I have read many threads and tried some tricks, however, none of them worked for me.</p> <p>The file I am trying to execute is named <em>test.py</em>, it just logs a time to another file, when was Pi's startup:</p> <pre><code>#!/usr/bin/python...
4
2016-07-02T15:01:58Z
38,161,506
<p>If you don't specify absolute path, <code>open</code> assume relative path to current working directory.</p> <p>You'd better to try use absolute path first, before you know where the working directory is.</p> <pre><code>f = open('/home/pi/logger.txt', 'w') </code></pre>
5
2016-07-02T15:07:23Z
[ "python", "linux", "raspberry-pi", "rc" ]
MyHDL VHDL conversion: no index value can belong to null index range
38,161,494
<p>For an algorithm I implemented and successfully converted to VHDL, I get this error during the "Static elaboration of top level VHDL design":</p> <blockquote> <p>no index value can belong to null index range</p> </blockquote> <p>I boiled the code down to the essential part (you might recognize a cordic processor...
1
2016-07-02T15:05:11Z
38,163,288
<p>For variables declarations, MyHDL does not seem to support having an expression in the call to <code>range</code> in the list comprehension (although it does for signal declarations).</p> <p>If you change this:</p> <pre><code>dx = [intbv(0, min=-R2P_LIMIT, max=R2P_LIMIT) for _ in range(R2P_N+1)] dy = [intbv(0, min...
1
2016-07-02T18:31:46Z
[ "python", "vhdl", "myhdl" ]
Python Pandas: How do I return members of groupby
38,161,531
<p>I´m doing some resarch on a dataframe for people that are relative. But I can´t manage when I find brothers, I can´t find a way to write them down all on a specific column. Here follow an example:</p> <pre><code>cols = ['Name','Father','Brother'] df = pd.DataFrame({'Brother':'', 'Father':['Eri...
1
2016-07-02T15:10:31Z
38,161,814
<p>Here is an idea you can try, firstly create a <code>Brother</code> column with all brothers as a list including itself and then remove itself separately. The code could probably be optimized but where you can start from:</p> <pre><code>import numpy as np import pandas as pd df['Brother'] = df.groupby('Father')['Nam...
1
2016-07-02T15:43:56Z
[ "python", "pandas", "group-by" ]
Python Pandas: How do I return members of groupby
38,161,531
<p>I´m doing some resarch on a dataframe for people that are relative. But I can´t manage when I find brothers, I can´t find a way to write them down all on a specific column. Here follow an example:</p> <pre><code>cols = ['Name','Father','Brother'] df = pd.DataFrame({'Brother':'', 'Father':['Eri...
1
2016-07-02T15:10:31Z
38,162,041
<pre><code>def same_father(me, data): hasdad = data.Father == data.at[me, 'Father'] notme = data.index != me isbro = hasdad &amp; notme return data.loc[isbro].index.tolist() df2 = df.set_index('Name') getbro = lambda x: same_father(x.name, df2) df2['Brother'] = df2.apply(getbro, axis=1) </code></pre> ...
0
2016-07-02T16:10:21Z
[ "python", "pandas", "group-by" ]
Python's hash function gives large difference between similar data
38,161,535
<p>Consider the following hashes:</p> <pre><code>&gt;&gt;&gt; hash('ant') &gt;&gt;&gt; 6440141934328138723 &gt;&gt;&gt; hash('ants') &gt;&gt;&gt; 1001406009354992019 </code></pre> <p>I know the reason why such large difference between two so similar objects is occurring due to implementation of <code>hash</code> func...
1
2016-07-02T15:10:43Z
38,164,139
<p>Python's <code>hash()</code> isn't designer for that, however based on your other question about the text features for the SVM, I think you're looking for <a href="http://nlp.stanford.edu/IR-book/html/htmledition/stemming-and-lemmatization-1.html" rel="nofollow">stemming and/or lemmatization</a></p> <p>This is goin...
0
2016-07-02T20:18:51Z
[ "python", "hash" ]
Python bitwise operation on large binary strings
38,161,565
<p>I want to perform bitwise operation on binary strings with length more than 100 zeros and ones. I know i can convert them using something like <code>int('1'*100, 2)</code> which prints <code>1267650600228229401496703205375L</code> with <code>L</code> character at the end. Then use python bitwise operators but I thin...
2
2016-07-02T15:14:10Z
38,161,812
<p>Do not do bitwise operations on strings of <code>0</code>s and <code>1</code>s that is plain bad and slow. You shall convert the strings to actual numbers as then the processing of several bits is done at once. <strong>There is nothing wrong with</strong>:</p> <pre><code>int('1'*128,2) &amp; int('1'*128,2) </code...
0
2016-07-02T15:43:40Z
[ "python", "python-2.7", "binary", "bit-manipulation", "bitwise-operators" ]
Python bitwise operation on large binary strings
38,161,565
<p>I want to perform bitwise operation on binary strings with length more than 100 zeros and ones. I know i can convert them using something like <code>int('1'*100, 2)</code> which prints <code>1267650600228229401496703205375L</code> with <code>L</code> character at the end. Then use python bitwise operators but I thin...
2
2016-07-02T15:14:10Z
38,162,393
<p>I'm guessing that you do not like the idea of using integers because it obfuscates your underlying data. Plus it makes it difficult to work with strings that start with '0' (because they trimmed off when converting to an integer), not to mention the subtleties of signed integers and endianness.</p> <p>Try using the...
1
2016-07-02T16:47:04Z
[ "python", "python-2.7", "binary", "bit-manipulation", "bitwise-operators" ]
find the start position of the longest sequence of 1's
38,161,606
<p>I want to find the start position of the longest sequence of 1's in my array:</p> <pre><code>a1=[0,0,1,1,1,1,0,0,1,1] #2 </code></pre> <p>I am following this <a href="http://stackoverflow.com/a/16733324/4127806">answer</a> to find the length of the longest sequence. However, I was not able to determine the positio...
5
2016-07-02T15:18:20Z
38,161,734
<p>You could use a for loop and check if the next few items (of length <code>m</code> where <code>m</code> is the max length) are the same as the maximum length:</p> <pre><code># Using your list and the answer from the post you referred from itertools import groupby L = [0,0,1,1,1,1,0,0,1,1] m = max(sum(1 for i in g) ...
1
2016-07-02T15:33:47Z
[ "python", "numpy", "scipy" ]
find the start position of the longest sequence of 1's
38,161,606
<p>I want to find the start position of the longest sequence of 1's in my array:</p> <pre><code>a1=[0,0,1,1,1,1,0,0,1,1] #2 </code></pre> <p>I am following this <a href="http://stackoverflow.com/a/16733324/4127806">answer</a> to find the length of the longest sequence. However, I was not able to determine the positio...
5
2016-07-02T15:18:20Z
38,161,867
<p>Inspired by <a href="http://stackoverflow.com/a/38132942/3293881"><code>this solution</code></a>, here's a vectorized approach to solve it -</p> <pre><code># Get start, stop index pairs for islands/seq. of 1s idx_pairs = np.where(np.diff(np.hstack(([False],a1==1,[False]))))[0].reshape(-1,2) # Get the island length...
2
2016-07-02T15:50:51Z
[ "python", "numpy", "scipy" ]
find the start position of the longest sequence of 1's
38,161,606
<p>I want to find the start position of the longest sequence of 1's in my array:</p> <pre><code>a1=[0,0,1,1,1,1,0,0,1,1] #2 </code></pre> <p>I am following this <a href="http://stackoverflow.com/a/16733324/4127806">answer</a> to find the length of the longest sequence. However, I was not able to determine the positio...
5
2016-07-02T15:18:20Z
38,162,096
<p>This seems to work, using <code>groupby</code> from <code>itertools</code>, this only goes through the list once:</p> <pre><code>from itertools import groupby pos, max_len, cum_pos = 0, 0, 0 for k, g in groupby(a1): if k == 1: pat_size = len(list(g)) pos, max_len = (pos, max_len) if pat_size &...
2
2016-07-02T16:16:49Z
[ "python", "numpy", "scipy" ]
find the start position of the longest sequence of 1's
38,161,606
<p>I want to find the start position of the longest sequence of 1's in my array:</p> <pre><code>a1=[0,0,1,1,1,1,0,0,1,1] #2 </code></pre> <p>I am following this <a href="http://stackoverflow.com/a/16733324/4127806">answer</a> to find the length of the longest sequence. However, I was not able to determine the positio...
5
2016-07-02T15:18:20Z
38,162,383
<p>Another way of doing in a single loop, but without resorting to <code>itertool</code>'s <code>groupby</code>.</p> <pre><code>max_start = 0 max_reps = 0 start = 0 reps = 0 for (pos, val) in enumerate(a1): start = pos if reps == 0 else start reps = reps + 1 if val == 1 else 0 max_reps = max(reps, max_reps...
1
2016-07-02T16:45:47Z
[ "python", "numpy", "scipy" ]
find the start position of the longest sequence of 1's
38,161,606
<p>I want to find the start position of the longest sequence of 1's in my array:</p> <pre><code>a1=[0,0,1,1,1,1,0,0,1,1] #2 </code></pre> <p>I am following this <a href="http://stackoverflow.com/a/16733324/4127806">answer</a> to find the length of the longest sequence. However, I was not able to determine the positio...
5
2016-07-02T15:18:20Z
38,162,455
<p>A more compact one-liner using <code>groupby()</code>. Uses <code>enumerate()</code> on the raw data to keep the starting positions through the analysis pipeline, evenutally ending up with the list of tuples [(2, 4), (8, 2)] each tuple containing the starting position and length of non-zero runs:</p> <pre><code>fr...
2
2016-07-02T16:54:26Z
[ "python", "numpy", "scipy" ]
Python-Rounding the value of PI according to the number specified by user
38,161,620
<p>My Code :</p> <pre><code>import math def CalPI(precision): answer = round((math.pi),precision) return answer precision=raw_input('Enter number of digits you want after decimal:') try: roundTo=int(precision) print CalPI(roundTo) except: print 'Error' </code></pre> <p>When I run this code I ge...
0
2016-07-02T15:19:51Z
38,161,768
<p>If you use <code>repr</code> in your print you'll have 15 digits: 3.141592653589793.</p> <p>If you want more digits (until 50) use</p> <pre><code>nb_digits = 40 print(format(math.pi, '.%dg' % nb_digits)) </code></pre> <p>(thanks Stefan for the precision :) but as he stated again: don't trust digits after digit 15...
1
2016-07-02T15:37:25Z
[ "python" ]
Sending the length of jSON array though sockets (java to python)
38,161,631
<p>I am trying to connect with a python server (from my collegue), with java. The aim (for now) is to send a json array. We start by sending the length first. It works with an equivalent python client, which I am trying to translate into pyton. </p> <p>This is an excerpt from my java code</p> <pre><code> PrintWriter...
0
2016-07-02T15:21:00Z
38,162,531
<p>Your receiver is assuming the length is expressed in 8 bytes (N_BYTES_MSG_LEN). But you send the long as string. PrintWriter.write(long) is the same as PrintWriter.write(Long.valueof(long).toString). For example if the length is 356 it sends "356". You should lef pad your length first: "00000356".</p>
0
2016-07-02T17:02:25Z
[ "java", "python", "json", "sockets" ]
Sending the length of jSON array though sockets (java to python)
38,161,631
<p>I am trying to connect with a python server (from my collegue), with java. The aim (for now) is to send a json array. We start by sending the length first. It works with an equivalent python client, which I am trying to translate into pyton. </p> <p>This is an excerpt from my java code</p> <pre><code> PrintWriter...
0
2016-07-02T15:21:00Z
38,210,155
<p>I found the solution, you have to take into account that java uses. You can do this by changing the server (python) code to: </p> <pre><code> raw_len = struct.pack('!Q', len(raw_data)) </code></pre> <p>And you can then send it with: </p> <pre><code> JSONObject request = new JSONObject(); request.append("...
0
2016-07-05T18:23:20Z
[ "java", "python", "json", "sockets" ]
How to generate random points outside a rectangle?
38,161,719
<p>Let's say my window's dimensions are 400 width by 600 height.</p> <p>It's relatively easy to generate a random point on a single side, let's say the top of it:</p> <pre><code>random.randint(0, width) </code></pre> <p>But what would be the smartest way to get this to work for all 4 sides so that a random point is ...
0
2016-07-02T15:31:56Z
38,167,615
<p>Sorry; completely misinterpreted the question the first time.</p> <p>If you just want to pick a point randomly on the <em>edge</em> of a rectangle, try something like this:</p> <pre><code>p = random.randint(0, width + width + height + height) if p &lt; (width + height): if p &lt; width: obj.pos.x = p obj...
1
2016-07-03T07:17:49Z
[ "python", "random", "position" ]
How to install PyQt4-phonon (python3 version) on Ubuntu
38,161,805
<p>I have installed pyqt4 on ubuntu. Now my project requires pyqt4-phonon module. I have tried this way below which I got from the Internet:</p> <pre><code>sudo apt-get install Python-qt4-phonon </code></pre> <p>but I still cannot use phonon module in python3. While the module is available in python2. It seems to sho...
0
2016-07-02T15:42:26Z
38,161,877
<p>To install the Python 3 bindings for Qt4 Phonon, run:</p> <pre><code>sudo apt-get install python3-pyqt4.phonon </code></pre>
0
2016-07-02T15:51:44Z
[ "python", "ubuntu", "pyqt4" ]
Plotting Distributions(Histogram) on map
38,161,835
<p>I have data in the format (latitude, longitude, value). I want to plot (lat, long) -> value on a map of city. Something like this : <a href="http://i.stack.imgur.com/f3pPc.png" rel="nofollow">Histogram on map</a> <a href="http://i.stack.imgur.com/FTYb1.jpg" rel="nofollow">Distribution on map</a></p> <p>I've alrea...
0
2016-07-02T15:46:03Z
38,190,197
<p>I posted above question and then, found interesting plotting libraries. </p> <p><a href="https://cesiumjs.org/" rel="nofollow">Cesium</a> : An open-source JavaScript library for 3D globes and maps. </p> <p><a href="https://www.arcgis.com/features/index.html" rel="nofollow">ArcGIS</a>: This one is paid (60 days fre...
0
2016-07-04T18:05:16Z
[ "python", "google-maps", "gis", "visualization" ]
Why does using an integer value as a 'while' loop condition work in Python?
38,161,838
<p>The following code will output infinite lines of "test". </p> <pre><code>foo = 5 while foo: print("bar") </code></pre> <p>The other day I came across an answer here about digit sums. This was the code shown in the answer:</p> <pre><code>def digit_sum(t): s = 0 while t: s += t % 10 t //...
-4
2016-07-02T15:46:19Z
38,161,855
<p>The <code>while</code> condition tests for <em>truth</em>. Any non-zero numeric value is considered true. See the <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow"><em>Truth Value Testing</em> section</a> in the Python documentation:</p> <blockquote> <p>Any object can be...
4
2016-07-02T15:49:29Z
[ "python", "while-loop", "integer", "condition" ]
Why does using an integer value as a 'while' loop condition work in Python?
38,161,838
<p>The following code will output infinite lines of "test". </p> <pre><code>foo = 5 while foo: print("bar") </code></pre> <p>The other day I came across an answer here about digit sums. This was the code shown in the answer:</p> <pre><code>def digit_sum(t): s = 0 while t: s += t % 10 t //...
-4
2016-07-02T15:46:19Z
38,163,079
<p>You already got useful answers, but I just wanted to answer your question in a way that can be easily understood by someone who is a beginner in Python. You could rewrite your code as:</p> <pre><code>def digit_sum(t): s = 0 while t!=0: s += t % 10 t = t//10 return s </code></pre> <p>'wh...
0
2016-07-02T18:06:28Z
[ "python", "while-loop", "integer", "condition" ]
Use 'disable' attribute in modelformset
38,161,865
<p>I am using a modelformset to change multiple records at once. </p> <p>I started with a simple formset and a form:</p> <p><strong>forms.py</strong></p> <pre><code>class SetupForm(forms.Form): student_id = forms.IntegerField(disabled=True) student_firstname = forms.CharField(label = _("First Name")) stu...
0
2016-07-02T15:50:16Z
38,163,625
<p>Declare your formset like this:</p> <pre><code>StudentFormSet = modelformset_factory(Student, form=SetupForm, extra=0) </code></pre>
1
2016-07-02T19:13:23Z
[ "python", "django", "django-forms", "django-templates" ]
Points that follow a 1/R density distribution in an XY grid?
38,161,872
<p>I have a XY grid with some gridpoints having certain values assigned to them, in this case, each value means a certain mass, so basically point masses in a grid. I now want to obtain a set of points which follow a density distribution of 1/R, where R is the distance from the center, so R = sqrt(x^2 + y^2). By densit...
0
2016-07-02T15:51:19Z
38,172,416
<p>Assuming I understood your question (if not comments are welcomed):</p> <p>The way to create any given distribution is by interpolating over the inverse of the distribution CDF. This is my function to do it:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt def randdist(PDF, x, n): """Create a...
1
2016-07-03T17:16:42Z
[ "python", "numpy", "grid", "distribution" ]
PySpark (Python 2.7): loading multiline records via SparkContext.newAPIHadoopFile
38,161,907
<p>I'm loading a text file that comes in TSV (tabular separated value) notation but without the key in each line. So one line indicates a specific variable and all following lines are the values for that variable until a new variable occurs. </p> <p>Therefore I'm loading the file with a custom delimiter (in Jupyter No...
0
2016-07-02T15:55:09Z
38,171,145
<p>Each (key, value) pair returned by <code>o.a.h.mapreduce.lib.input.TextInputFormat</code> is a single local data structure containing an offset (<code>long</code>) and string. There is no mechanism which can split value between multiple records without creating custom Hadoop <a href="https://hadoop.apache.org/docs/r...
1
2016-07-03T14:53:11Z
[ "python", "python-2.7", "hadoop", "hdfs", "pyspark" ]
Using \n is placing the previous character on a new line
38,161,917
<p>Im trying to take some values for a list and use them for a game config, however when i'm writing to the config it is not using the layout it should.</p> <p>I have the text file called item_index.txt and the contents:</p> <pre><code> &lt;number&gt;: &lt;name&gt; </code></pre> <p>My code is this:</p> <pre><code>f...
-2
2016-07-02T15:56:11Z
38,161,997
<p>As for your question, your problem is that you have a <code>"\n"</code> at the end of each line of the read from the source file - just strip it before using its value - <code>new_skin[1].strip()</code> instead of <code>new_skin[1]</code></p> <p>But please, for your sake, checkout the tens of ways of handlign and ...
0
2016-07-02T16:04:24Z
[ "python" ]
Using \n is placing the previous character on a new line
38,161,917
<p>Im trying to take some values for a list and use them for a game config, however when i'm writing to the config it is not using the layout it should.</p> <p>I have the text file called item_index.txt and the contents:</p> <pre><code> &lt;number&gt;: &lt;name&gt; </code></pre> <p>My code is this:</p> <pre><code>f...
-2
2016-07-02T15:56:11Z
38,162,037
<p>You need to strip the newline from the end of new_skin:</p> <pre><code>new_skin = skin.strip('\n').split(":") </code></pre>
1
2016-07-02T16:09:38Z
[ "python" ]
python shell 3.5.2 confusion over type conversion
38,162,013
<p>Hi I am new to programming in general and am going through a tutorial and came to the section on type conversion and was experimenting with different scenarios. So the problem is when I use the input function such as </p> <pre><code>int (input("Enter a number")) </code></pre> <p>when I enter an integer it is fine...
1
2016-07-02T16:06:18Z
38,162,061
<p>You can not convert a string showing a floating-point number to <code>int</code> directly. This makes sense, since when the user enters a floating point number it should not "silently" be converted to the closest integer. The converse -- converting a string showing an integer to <code>float</code> -- is not as probl...
0
2016-07-02T16:12:46Z
[ "python", "shell", "type-conversion", "data-type-conversion" ]
AttributeError: object has no attribute 'tk'
38,162,028
<p>I have searched quite a bit,but I couldn't find a solution to this. I'm trying to create a registration form using tkinter which later on i shall connect to a database. Here is the code :</p> <pre><code>from Tkinter import * class MWindow(object): def __init__(self,master): self.frame=Frame(master) ...
0
2016-07-02T16:08:20Z
38,162,053
<p>You're passing <code>self</code> in as the master / parent to your widgets.</p> <p>e.g - <code>Entry(self, ...)</code> But, your class <code>MWindow</code> doesn't inherit from a Tkinter widget. </p> <p>Perhaps you meant to use <code>self.frame</code>?</p> <p>If you really want to use <strong><code>self</code></s...
1
2016-07-02T16:12:00Z
[ "python", "python-2.7", "tkinter", "registration", "mysql-connector" ]
django extend installed app model save method
38,162,034
<p>Let's say i need to call my own function <code>def do_stuff()</code> after i save model. If that model would be in app which i have created, that would be no problem. I could do: </p> <pre><code>def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) do_stuff() </code></pre> <p>But...
0
2016-07-02T16:09:07Z
38,162,055
<p>You can use <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#post-save" rel="nofollow">post_save</a> signal. It will be invoked after model is saved.</p>
0
2016-07-02T16:12:01Z
[ "python", "django" ]
django extend installed app model save method
38,162,034
<p>Let's say i need to call my own function <code>def do_stuff()</code> after i save model. If that model would be in app which i have created, that would be no problem. I could do: </p> <pre><code>def save(self, *args, **kwargs): super(Post, self).save(*args, **kwargs) do_stuff() </code></pre> <p>But...
0
2016-07-02T16:09:07Z
38,162,148
<p>There are signals that are dispatched after some certain events. One of them, <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#django.db.models.signals.post_save" rel="nofollow">post_save</a> (or <a href="https://docs.djangoproject.com/en/1.9/ref/signals/#django.db.models.signals.pre_save" rel="nofollow">...
2
2016-07-02T16:21:46Z
[ "python", "django" ]