title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
How do I optimise this Python code?
39,899,567
<p>I'm doing a coding challenge for fun and to work on my skills - some of you may remember the Advent of Code challenge from last December, I'm working through that. I've got this code as the solution to one of the problems, which works, but it's uselessly slow.</p> <pre><code>inp = "1113122113" def iterate(num): pos = 0 new = "" while pos &lt; len(num): counter = 0 d = num[pos] for i in range(pos, len(num)): if num[i] == d: counter += 1 else: break new+=str(counter) new+=str(d) pos += counter print len(new) return new for i in range (50): inp = iterate(inp) </code></pre> <p>Past iteration 35 or so, it gets to the point where it's taking several minutes for each iteration. The object is to generate a look-and-say sequence - so 1 goes to 11, then 21, 1211, 111221, 3112211 and so on. I need to find the length of the string after the 50th iteration, but it's 360154 characters long after 40 iterations and my code just isn't optimised enough to handle strings that long in a reasonable time. Can anyone give me some pointers?</p>
0
2016-10-06T15:07:13Z
39,900,068
<p>Using <code>itertools.groupby</code> will make this very fast.</p> <pre><code>from itertools import groupby def next_say(s): return ''.join(str(sum(1 for _ in g))+k for k, g in groupby(s)) def iterate(num): """Generator that yields the first num iterations""" val = '1' for i in range(num): val = next_say(val) yield val </code></pre> <p><a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow">https://docs.python.org/2/library/itertools.html#itertools.groupby</a></p>
1
2016-10-06T15:30:25Z
[ "python", "optimization" ]
Float value behaviour in Python 2.6 and Python 2.7
39,899,580
<p>I have to convert string to tuple of float. In Python 2.7, it gives correct conversion, but in Python it is not same case.</p> <p>I want same behaviour in Python 2.6 </p> <p>Can anyone help me why this is not same in Python 2.6 and how to do in Python 2.6.</p> <p><strong>Python 2.6</strong></p> <pre><code>&gt;&gt;&gt; a '60.000,494.100,361.600,553.494' &gt;&gt;&gt; eval(a) (60.0, 494.10000000000002, 361.60000000000002, 553.49400000000003) &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval(a) (60.0, 494.10000000000002, 361.60000000000002, 553.49400000000003) &gt;&gt;&gt; &gt;&gt;&gt; for i in a.split(","): ... float(i) ... 60.0 494.10000000000002 361.60000000000002 553.49400000000003 &gt;&gt;&gt; </code></pre> <p><strong>Python 2.7</strong></p> <pre><code>&gt;&gt;&gt; a '60.000,494.100,361.600,553.494' &gt;&gt;&gt; eval(a) (60.0, 494.1, 361.6, 553.494) &gt;&gt;&gt; import ast &gt;&gt;&gt; ast.literal_eval(a) (60.0, 494.1, 361.6, 553.494) &gt;&gt;&gt; &gt;&gt;&gt; for i in a.split(","): ... float(i) ... 60.0 494.1 361.6 553.494 </code></pre> <p>Its not look good</p> <p><strong>[Edit 2]</strong></p> <p><strong>I just print value and condition</strong></p> <pre><code>print fGalleyTopRightOddX, "&gt;=", tLinetextBbox[2], fGalleyTopRightOddX&gt;=tLinetextBbox[2] 361.6 &gt;= 361.6 False </code></pre> <p>I calculate <code>tLinetextBbox</code> value from string and which is <code>361.60000000000002</code> and <code>fGalleyTopRightOddX</code> value is <code>361.6</code></p> <p>I am working on <strong>Python Django</strong> project where <strong>apache</strong> is server.</p> <ol> <li><code>fGalleyTopRightOddX</code> i.e. <code>361.6</code> is calculated in apache environment</li> <li><code>tLinetextBbox</code> i.e. <code>361.60000000000002</code> is calculated on cmd means I pass <code>fGalleyTopRightOddX</code> to program which run by command <code>line os.system</code></li> </ol> <p><strong>[Edit 3]</strong> Just one more information,</p> <p>when I log diction in text file then i get <code>tLinetextBbox</code> vale as <code>361.59999999999997</code></p>
4
2016-10-06T15:07:54Z
39,899,817
<p>In order to get the same result in Python 2.6, you have to explicitly do:</p> <pre><code>'%.12g' % float_variable </code></pre> <p>Better to create a custom function to do this as:</p> <pre><code>def convert_to_my_float(float_value): return float('%.12g' % float_value) </code></pre> <hr> <p>As per <a href="https://docs.python.org/2/library/decimal.html#decimal-objects" rel="nofollow">Python's Decimal Objects</a> Document:</p> <blockquote> <p>Changed in version 2.6: leading and trailing whitespace characters are permitted when creating a Decimal instance from a string.</p> <p>Changed in version 2.7: The argument to the constructor is now permitted to be a float instance.</p> </blockquote> <p>The answer to <em>Why they are behaving differently?</em> is, because <code>float.__repr__()</code> and <code>float.__str__()</code> methods in Python 2.7 changed.</p>
4
2016-10-06T15:18:10Z
[ "python", "python-2.7" ]
Same xpath returns different values on Centos, Ubuntu
39,899,632
<p>We're trying to port our application from a Centos environment into other linuxes, in particular Ubuntu. The application is python-based so there should be no problems, however we noticed an odd behaviour when parsing XPATHs.</p> <p>Sample file:</p> <pre><code>&lt;root&gt; &lt;outer&gt; &lt;inner&gt; &lt;el/&gt; &lt;/inner&gt; &lt;inner&gt; &lt;el/&gt; &lt;/inner&gt; &lt;/outer&gt; &lt;/root&gt; </code></pre> <p>Code:</p> <pre><code>from lxml import etree r = etree.parse('foo.xml') print 'One: ', r.xpath('.//el[2]') print 'Two: ', r.xpath('(.//el)[2]') </code></pre> <p>On Centos (python 2.7.5):</p> <pre><code>One: [&lt;Element el at 0x25fdcf8&gt;] New version: [&lt;Element el at 0x25fdcf8&gt;] </code></pre> <p>On RedHat Enterprise 6.6 (python 2.7.11)</p> <pre><code>One: [] Two: [&lt;Element el at 0x7fa27198cd40&gt;] </code></pre> <p>On Debian and Ubuntu (python 2.7.9 and 2.7.12):</p> <pre><code>One: [] Two: [&lt;Element el at 0x7f94ed6cf200&gt;] </code></pre> <p>This is the <strong>same</strong> code trying to access the second element <code>el</code>.</p> <p>Debian, Ubuntu and Cents environment have lxml (installed from <code>pip</code>) version 3.6.4. When installing lxml it compiles it against libxml2 which is </p> <p>On debian: </p> <pre><code> $ dpkg -l | grep libxml2-dev ii libxml2-dev:amd64 2.9.1+dfsg1-5+deb8u2 amd64 </code></pre> <p>On centos:</p> <pre><code>$ rpm -q libxml2-devel libxml2-devel-2.9.1-6.el7_2.3.x86_64 </code></pre> <p>RedHat runs etree 3.6.0:</p> <pre><code>$ rpm -q libxml2-devel libxml2-devel-2.7.6-21.el6.x86_64 </code></pre> <p>What's going on here?</p>
2
2016-10-06T15:09:55Z
39,956,501
<p>The result on CentOS is incorrect.</p> <p><code>libxml2</code> 2.9.0 introduced a regression, see <a href="https://bugzilla.gnome.org/show_bug.cgi?id=695699" rel="nofollow">libxml 2.9.0 XPath evaluation issue</a>. It is fixed in 2.9.2 but not in 2.9.1.</p> <p>Debian has integrated the patch in version 2.9.1+dfsg1-3:</p> <blockquote> <p>libxml2 (2.9.1+dfsg1-3) unstable; urgency=low</p> <ul> <li>debian/patches/0007-Fix-XPath-optimization-with-predicates.patch: <ul> <li>Upstream patch to fix XPath evaluation issue. (Closes: #713146)</li> </ul></li> </ul> </blockquote>
1
2016-10-10T10:45:56Z
[ "python", "linux", "xpath", "centos", "lxml" ]
Django template doesn't show model items
39,899,687
<p>I'm very new to Django and I'm currently trying to create a movie database for a few of my favorite directors. I've been following tutorial videos, and I'm currently trying to get my detail view to display all the added movies for each director. However when I go into the director, it does not display their films.</p> <p>director/models.py</p> <pre><code>from django.db import models class Director(models.Model): photo = models.CharField(max_length=250, default='none') name = models.CharField(max_length=250) born = models.CharField(max_length=250) birth_date = models.CharField(max_length=20) married = models.CharField(max_length=1) def __str__(self): return self.name class Films(models.Model): director = models.ForeignKey(Director, on_delete=models.CASCADE) title = models.CharField(max_length=50) year = models.IntegerField(default=0) rating = models.DecimalField(max_digits=2, decimal_places=1, default=0) budget = models.CharField(max_length=20) def __str__(self): return self.title </code></pre> <p>director/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P&lt;name_id&gt;[0-9]+)/$', views.detail, name='detail'), ] </code></pre> <p>director/views.py</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from .models import Director, Films def index(request): all_directors = Director.objects.all() return render(request, 'director/index.html', {'all_directors': all_directors}) def detail(request, name_id): try: direct = Director.objects.get(pk=name_id) except Director.DoesNotExist: raise Http404("Director not found") return render(request, 'director/detail.html', {'direct': direct}) </code></pre> <p>director/detail.html</p> <pre><code>&lt;h3 align="center"&gt; {{ direct }} &lt;/h3&gt;&lt;br&gt; &lt;img src="{{ director.photo }}"&gt; &lt;h4&gt;Film List&lt;/h4&gt; &lt;ul&gt; {% for films in director.films_set.all %} &lt;li&gt;{{ direct.title }} - {{ direct.rating }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>When I run the server and go to the page, I click on a director and all it says is the directors name, and "Film List". Please advise on how to fix this, any help is greatly appreciated!</p>
1
2016-10-06T15:12:18Z
39,899,821
<p>This should solve it:</p> <pre><code>{% for film in director.films_set.all %} &lt;li&gt;{{ film.title }} - {{ film.rating }}&lt;/li&gt; {% endfor %} </code></pre> <p>You want each movie's title and rating, so I guess using <code>direct.title</code> and <code>direct.rating</code> was the problem. Also, the variable you define in the loop is each individual <code>film</code>, so I replaced <code>films</code> with <code>film</code>.</p>
0
2016-10-06T15:18:22Z
[ "python", "django" ]
Django template doesn't show model items
39,899,687
<p>I'm very new to Django and I'm currently trying to create a movie database for a few of my favorite directors. I've been following tutorial videos, and I'm currently trying to get my detail view to display all the added movies for each director. However when I go into the director, it does not display their films.</p> <p>director/models.py</p> <pre><code>from django.db import models class Director(models.Model): photo = models.CharField(max_length=250, default='none') name = models.CharField(max_length=250) born = models.CharField(max_length=250) birth_date = models.CharField(max_length=20) married = models.CharField(max_length=1) def __str__(self): return self.name class Films(models.Model): director = models.ForeignKey(Director, on_delete=models.CASCADE) title = models.CharField(max_length=50) year = models.IntegerField(default=0) rating = models.DecimalField(max_digits=2, decimal_places=1, default=0) budget = models.CharField(max_length=20) def __str__(self): return self.title </code></pre> <p>director/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P&lt;name_id&gt;[0-9]+)/$', views.detail, name='detail'), ] </code></pre> <p>director/views.py</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from .models import Director, Films def index(request): all_directors = Director.objects.all() return render(request, 'director/index.html', {'all_directors': all_directors}) def detail(request, name_id): try: direct = Director.objects.get(pk=name_id) except Director.DoesNotExist: raise Http404("Director not found") return render(request, 'director/detail.html', {'direct': direct}) </code></pre> <p>director/detail.html</p> <pre><code>&lt;h3 align="center"&gt; {{ direct }} &lt;/h3&gt;&lt;br&gt; &lt;img src="{{ director.photo }}"&gt; &lt;h4&gt;Film List&lt;/h4&gt; &lt;ul&gt; {% for films in director.films_set.all %} &lt;li&gt;{{ direct.title }} - {{ direct.rating }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>When I run the server and go to the page, I click on a director and all it says is the directors name, and "Film List". Please advise on how to fix this, any help is greatly appreciated!</p>
1
2016-10-06T15:12:18Z
39,899,868
<p>In your view, you only pass one context object to the template, <code>direct</code>. This <code>direct</code> is a member of your director model: it makes sense that <code>direct</code> in your template displays the name of the director, since that is how you define the <code>__str__</code> method for that model.</p> <p>Beyond that, though, none of your other variables will display. Why?</p> <ul> <li>You use <code>director.photo</code> instead of <code>direct.photo</code>. <code>director</code> is undefined in the template. (As a side note, <code>director</code> is IMO a better variable name.)</li> <li>You use <code>direct.rating</code> and <code>direct.title</code> even though these are attributes of the <code>Film</code> model. You will need to modify as follows:</li> </ul> <pre> &lt;ul> {% for film in direct.films_set.all %} &lt;li>{{ film.title }} - {{ film.rating }}&lt;/li> {% endfor %} &lt;/ul> </pre> <p>(I also changed <code>films</code> to <code>film</code> since that more accurately reflects the variable's content.)</p>
0
2016-10-06T15:20:11Z
[ "python", "django" ]
Pandas - Grouping rows in time buckets
39,899,737
<p>I have a data frame with thousands of line looking like this:</p> <pre><code> time type value 0 09:30:01.405735 EVENT_0 2.1 0 09:30:01.405761 EVENT_0 2.1 0 09:30:01.419743 EVENT_0 1.1 1 09:30:02.419769 EVENT_0 32.1 2 09:30:02.419775 EVENT_0 2.15 3 09:30:02.419775 EVENT_0 24.1 4 09:30:06.419775 EVENT_0 3.1 5 09:30:06.419793 EVENT_0 1.1 6 09:30:06.419793 EVENT_0 2.4 .... </code></pre> <p>We define a "window" as a continuous list of events that are not separated by more than 1 second (that is, a gap of 1 second or more between two consecutive events create a new window)</p> <p>Here we would have 3 windows:</p> <pre><code> time type value 0 09:30:01.405735 EVENT_0 2.1 0 09:30:01.405761 EVENT_0 2.1 0 09:30:01.419743 EVENT_0 1.1 </code></pre> <p>====================================</p> <pre><code>1 09:30:02.419769 EVENT_0 32.1 2 09:30:02.419775 EVENT_0 2.15 3 09:30:02.419775 EVENT_0 24.1 </code></pre> <p>====================================</p> <pre><code>4 09:30:06.419775 EVENT_0 3.1 5 09:30:06.419793 EVENT_0 1.1 6 09:30:06.419793 EVENT_0 2.4 .... </code></pre> <p>I have trying to find a way to compute the average of the "value" column for each window, but can't find a way to do it properly in pandas.</p>
0
2016-10-06T15:14:26Z
39,900,167
<p>Assuming you time column is of datetime format and the data frame is sorted according to the time column:</p> <pre><code># calculate the windows, gives a unique number per entry associating it to its respective window windows = (data.time.diff().apply(lambda x: x.total_seconds()) &gt;= 1).astype(int).cumsum() # group by these windows and compute the value mean data.groupby(windows).value.mean() </code></pre>
2
2016-10-06T15:34:57Z
[ "python", "pandas" ]
Will this image always load into the .py app if it's in the same directory?
39,899,809
<p>I'm writing an application that I would like to use this .gif file in. If I want to execute this app with this picture in the same folder as the .py file will it simply show with this code or do I have to embed them into the app using base64? Thanks for your help.</p> <pre><code>jlu_logo = tkinter.PhotoImage(file="jlu-logo.gif") jlulogo = tkinter.Label(main, image = jlu_logo) jlulogo.place(x=255, y=230, anchor="s") </code></pre>
0
2016-10-06T15:17:56Z
39,907,141
<p>you could try something like</p> <pre><code>import os jlu_logo = tkinter.PhotoImage(file=os.path.join(os.path.dirname(__file__), "jlu-logo.gif")) jlulogo = tkinter.Label(main, image = jlu_logo) jlulogo.place(x=255, y=230, anchor="s") </code></pre>
0
2016-10-06T23:27:07Z
[ "python", "python-3.x", "tkinter" ]
Python Pyramid url replacement variable restrictions
39,899,880
<p>I'm developing in Pyramid 1.7 and running into an interesting scenario where some URL dispatch replacement variables match the route, while others do not. These variables are numbers, which may not be best practice or even be allowed from what I can tell in the documentation:</p> <p><a href="http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html" rel="nofollow">http://docs.pylonsproject.org/projects/pyramid/en/latest/narr/urldispatch.html</a></p> <p>My route is essentially defined as:</p> <pre><code>config.add_route("my_route", "/path/more_path/{num_var1}-{num_var2}-even_more_path") </code></pre> <p>The funny thing I'm seeing is that if num_var1 = 1 and num_var2 = 1, the path resolves fine. If num_var1 = 100 and num_var_2 = 100, it also resolves fine. Yet, if num_var1 = 1 and num_var2 = 100, it fails to resolve. Is this a failure I should expect for some reason or should this properly resolve?</p> <p>Thanks!</p>
1
2016-10-06T15:20:53Z
40,113,324
<p>I made a test case which passes fine with your examples. Feel free to play with this until it reproduces your issues, but until then I'm not sure how to help.</p> <pre><code>from pyramid.config import Configurator from webtest import TestApp config = Configurator() config.add_route('my_route', '/path/more_path/{num_var1}-{num_var2}-even_more_path') config.add_view(lambda r: 'hello', route_name='my_route', renderer='string') app = config.make_wsgi_app() test = TestApp(app) test.get('/path/more_path/1-1-even_more_path') test.get('/path/more_path/100-100-even_more_path') test.get('/path/more_path/1-100-even_more_path') test.get('/path/more_path/1-100') # fails, missing extra path </code></pre>
0
2016-10-18T16:18:32Z
[ "python", "pyramid" ]
Running python in parallel
39,899,929
<p>I have this bash script:</p> <pre><code>#!/bin/bash for i in `seq 1 32`; do python run.py file$i.txt &amp; if (( $i % 10 == 0 )); then wait; fi done wait </code></pre> <p>I want to run it on a cluster with 64 cores. How will the 10 files be distributed among the cores? IF I have 10 free cores at the same time, each core will take one file, or there is a more complex way? Also, if all of the ore are free, should I run 64 files at a time, or it might encounters problems if I use all of them (like the program might be slowed down due to memory issues?</p>
0
2016-10-06T15:23:30Z
39,900,745
<p>When you run the scripts from the shell in paralel, you are delegating responsibility of process managment to the OS scheduler, which is not a bad idea, because the OS knows well how to handle process through the processor cores, but sometimes you need more control about the tasks execution (maybe because you will run a really large number of tasks) if so, in my opinion the best approach will be run your tasks using the python multiprocessing module and program the tasks execution logic.</p>
0
2016-10-06T16:03:01Z
[ "python", "bash", "parallel-processing" ]
directory listing to xml - cannot concatenate 'str' and 'NoneType' objects - How To Handle?
39,899,986
<p>Using part of a script I found on here to run through the directories on a Windows PC to produce an XML file. However I am running into the above error and I am not sure how to handle the error. I have added a try/except in however it still crashes out. This works perfectly if i set the directory to be my Current Working Directory by replacing the "DirTree3("C:/") " with "DirTree3((os.getcwd())" </p> <pre><code>def DirTree3(path): try: result = '&lt;dir&gt;%s\n' % xml_quoteattr(os.path.basename(path)) for item in os.listdir(path): itempath = os.path.join(path, item) if os.path.isdir(itempath): result += '\n'.join(' ' + line for line in DirTree3(os.path.join(path, item)).split('\n')) elif os.path.isfile(itempath): result += ' &lt;file&gt; %s &lt;/file&gt;\n' % xml_quoteattr(item) result += '&lt;/dir&gt; \n' return result except Exception: pass print '&lt;DirectoryListing&gt;\n' + DirTree3("C:/") + '\n&lt;/DirectoryListing&gt;' </code></pre> <p>As a side note, this script will be run on a system without admin privileges so running as admin is not an option</p>
0
2016-10-06T15:26:13Z
39,900,465
<p>Based on your comments below about getting and wanting to ignore any path access errors, I modified the code in my answer below to do that as best it can. Note that it will still terminate if some other type of exception occurs.</p> <pre><code>def DirTree3(path): try: result = '&lt;dir&gt;%s\n' % xml_quoteattr(os.path.basename(path)) try: items = os.listdir(path) except WindowsError as exc: return '&lt;error&gt; {} &lt;/error&gt;'.format(xml_quoteattr(str(exc))) for item in items: itempath = os.path.join(path, item) if os.path.isdir(itempath): result += '\n'.join(' ' + line for line in DirTree3(os.path.join(path, item)).split('\n')) elif os.path.isfile(itempath): result += ' &lt;file&gt; %s &lt;/file&gt;\n' % xml_quoteattr(item) result += '&lt;/dir&gt; \n' return result except Exception as exc: print('exception occurred: {}'.format(exc)) raise print '&lt;DirectoryListing&gt;\n' + DirTree3("C:/") + '\n&lt;/DirectoryListing&gt;' </code></pre>
1
2016-10-06T15:49:05Z
[ "python", "xml" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently:</p> <p>mainapp/urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>NetworkTopology/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^json/$', views.returnjson, name='returnjson'), ] </code></pre> <p>NetworkTopology/views.py</p> <pre><code>from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): return render_to_response('index.html') def returnjson(request): if request.is_ajax(): request_data = request.POST print("Raw Data: " + request_data.body) return HttpResponse("OK") </code></pre> <p>JavaScript function (return JSON button is pressed):</p> <pre><code>function returnJsonTop(){ $(document).ready(function() { $.ajax({ method: 'POST', url: '/NetworkTopology/json', dataType: 'json', data: JSON.stringify(nodes.get(),null,4), success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); }); } </code></pre> <p>In my index template, I have created a button which calls the returnJsonTop() function when it is pressed:</p> <pre><code>&lt;button id="submitJson" onclick="returnJsonTop();"&gt;Deploy&lt;/button&gt; </code></pre> <p>Currently, when I press the Deploy button, I just get the 'it didn't work' alert that has been setup to handle an errors. I'd really appreciate someone pointing me in the right direction here. I suspect the issue is in my urls.py files but I've tried various combinations of urls without any luck.</p>
1
2016-10-06T15:26:24Z
39,900,177
<p>You're trying to access <code>body</code> on <code>request.POST</code>. But body is an attribute directly of the request. Your code should be:</p> <pre><code> request_data = request.body print("Raw Data: " + request_data) </code></pre> <p>Also note, in your Javascript that <code>$(document).ready</code> line makes no sense there; you should remove it.</p>
0
2016-10-06T15:35:22Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently:</p> <p>mainapp/urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>NetworkTopology/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^json/$', views.returnjson, name='returnjson'), ] </code></pre> <p>NetworkTopology/views.py</p> <pre><code>from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): return render_to_response('index.html') def returnjson(request): if request.is_ajax(): request_data = request.POST print("Raw Data: " + request_data.body) return HttpResponse("OK") </code></pre> <p>JavaScript function (return JSON button is pressed):</p> <pre><code>function returnJsonTop(){ $(document).ready(function() { $.ajax({ method: 'POST', url: '/NetworkTopology/json', dataType: 'json', data: JSON.stringify(nodes.get(),null,4), success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); }); } </code></pre> <p>In my index template, I have created a button which calls the returnJsonTop() function when it is pressed:</p> <pre><code>&lt;button id="submitJson" onclick="returnJsonTop();"&gt;Deploy&lt;/button&gt; </code></pre> <p>Currently, when I press the Deploy button, I just get the 'it didn't work' alert that has been setup to handle an errors. I'd really appreciate someone pointing me in the right direction here. I suspect the issue is in my urls.py files but I've tried various combinations of urls without any luck.</p>
1
2016-10-06T15:26:24Z
39,900,221
<p>first of all you dont even need to use all this in your ajax call data: JSON.stringify(nodes.get(),null,4), replace by data: nodes.get(), should be enougth as long as this method returns a valid json object</p> <p>second one, I ´d strongly recommend you to use a framework to help you to parse JSON python have may, but to ilustrate this example, I ve used django rest framework, which is a very good one.</p> <pre><code>from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.renderers import JSONRenderer import json import controllers#this class belongs to my business logic layer, you can encapsulate yours and use instead of it #in this solution you must create a pre-parser to handle responses class JSONResponse(HttpResponse): """ An HttpResponse that renders its content into JSON. """ def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs['content_type'] = 'application/json' super(JSONResponse, self).__init__(content, **kwargs) @csrf_exempt # this is for prevent invasions def login(request): #this one here handle your jquery post data into a valid json object in python represented by a Dict envelopin = json.loads(request.body) # here we pass the dict inside my business controll logic routine which also responds with a valid Python Dict envelopout = controllers.login(envelopin) # and for last, we use our pre-parser Class to make your response be handled by jquery as valid json return JSONResponse(envelopout) </code></pre> <p>and that is it, you success jquey data variable, will hold the envelopout json object, in the same shape as it has inside yor django-python code.</p> <p>hope this help</p>
0
2016-10-06T15:37:32Z
[ "javascript", "jquery", "python", "ajax", "django" ]
Passing a JSON string to django using JQuery and Ajax
39,899,989
<p>I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object.</p> <p>I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently:</p> <p>mainapp/urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>NetworkTopology/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^json/$', views.returnjson, name='returnjson'), ] </code></pre> <p>NetworkTopology/views.py</p> <pre><code>from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): return render_to_response('index.html') def returnjson(request): if request.is_ajax(): request_data = request.POST print("Raw Data: " + request_data.body) return HttpResponse("OK") </code></pre> <p>JavaScript function (return JSON button is pressed):</p> <pre><code>function returnJsonTop(){ $(document).ready(function() { $.ajax({ method: 'POST', url: '/NetworkTopology/json', dataType: 'json', data: JSON.stringify(nodes.get(),null,4), success: function (data) { //this gets called when server returns an OK response alert("it worked!"); }, error: function (data) { alert("it didnt work"); } }); }); } </code></pre> <p>In my index template, I have created a button which calls the returnJsonTop() function when it is pressed:</p> <pre><code>&lt;button id="submitJson" onclick="returnJsonTop();"&gt;Deploy&lt;/button&gt; </code></pre> <p>Currently, when I press the Deploy button, I just get the 'it didn't work' alert that has been setup to handle an errors. I'd really appreciate someone pointing me in the right direction here. I suspect the issue is in my urls.py files but I've tried various combinations of urls without any luck.</p>
1
2016-10-06T15:26:24Z
39,902,705
<p>For those reading this later, this is what I did:</p> <p>mainapp/urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>NetworkTopology/urls.py</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^json/$', views.returnjson, name='returnjson'), ] </code></pre> <p>NetworkTopology/views.py</p> <pre><code>from django.http import HttpResponse from django.shortcuts import render_to_response from django.views.decorators.csrf import csrf_exempt def index(request): return render_to_response('index.html') @csrf_exempt def returnjson(request): if request.is_ajax(): request_data = request.POST print("Raw Data: " + str(request_data)) return HttpResponse("OK") </code></pre> <p>I was getting a 403 error so I added '@csrf_exempt'. I'll probably change this to handle it properly afterwards.</p> <p>Return JSON function:</p> <pre><code>function returnJsonTop(){ $.ajax({ method: 'POST', url: '/NetworkTopology/json/', dataType: 'json', data: JSON.stringify(nodes.get(),null,4) }); } </code></pre>
0
2016-10-06T17:57:10Z
[ "javascript", "jquery", "python", "ajax", "django" ]
"ValueError: chunksize cannot exceed dimension size" when trying to write xarray to netcdf
39,900,011
<p>I got the following error when trying to write a xarray object to netcdf file: </p> <pre><code>"ValueError: chunksize cannot exceed dimension size" </code></pre> <p>The data is too big for my memory and needs to be chunked.<br> The routine is basically as follows: </p> <pre><code>import xarray as xr ds=xr.open_dataset("somefile.nc",chunks={'lat':72,'lon':144} myds=ds.copy() #ds is 335 (time) on 720 on 1440 and has variable var def some_function(x): return x*2 myds['newvar']=xr.DataArray(np.apply_along_axis(some_function,0,ds['var'])) myds.drop('var') myds.to_netcdf("somenewfile.nc") </code></pre> <p>So basically, I just manipulate the content and rewrite. Nevertheless, chunks seem to be bad. Same with rechunking to one array. I neither can rewrite ds. Any idea how to track the error down or solve this?</p> <p>netCDF4 version is 1.2.4<br> xarray (former xray) version is 0.8.2<br> dask version is 0.10.1 </p>
0
2016-10-06T15:27:28Z
39,960,638
<p>It was an issue of the engine in the writing command. You need to change the engine from netcdf4 (default) to scipy if you are using chunks! </p> <pre><code>myds.to_netcdf("somenewfile.nc",engine='scipy') </code></pre> <p>The netcdf4 package is NOT capable of writing such files.</p>
0
2016-10-10T14:29:14Z
[ "python", "netcdf4" ]
Python subprocess not returning
39,900,020
<p>I want to call a Python script from Jenkins and have it build my app, FTP it to the target, and run it.</p> <p>I am trying to build and the <code>subprocess</code> command fails. I have tried this with both <code>subprocess.call()</code> and <code>subprocess.popen()</code>, with the same result.</p> <p>When I evaluate <code>shellCommand</code> and run it from the command line, the build succeeds.</p> <p>Note that I have 3 shell commands: 1) remove work directory, 2) create a fresh, empty, work directory, then 3) build. The first two commands return from <code>subprocess</code>, but the third hangs (although it completes when run from the command line).</p> <p>What am I doing wrongly? Or, what alternatives do I have for executing that command?</p> <pre><code># +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= def ExcecuteShellCommandAndGetReturnCode(arguments, shellCommand): try: process = subprocess.call(shellCommand, shell=True, stdout=subprocess.PIPE) #process.wait() return process #.returncode except KeyboardInterrupt, e: # Ctrl-C raise e except SystemExit, e: # sys.exit() raise e except Exception, e: print 'Exception while executing shell command : ' + shellCommand print str(e) traceback.print_exc() os._exit(1) # +=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= def BuildApplciation(arguments): # See http://gnuarmeclipse.github.io/advanced/headless-builds/ jenkinsWorkspaceDirectory = arguments.eclipseworkspace + '/jenkins' shellCommand = 'rm -r ' + jenkinsWorkspaceDirectory ExcecuteShellCommandAndGetReturnCode(arguments, shellCommand) shellCommand = 'mkdir ' + jenkinsWorkspaceDirectory if not ExcecuteShellCommandAndGetReturnCode(arguments, shellCommand) == 0: print "Error making Jenkins work directory in Eclipse workspace : " + jenkinsWorkspaceDirectory return False application = 'org.eclipse.cdt.managedbuilder.core.headlessbuild' shellCommand = 'eclipse -nosplash -application ' + application + ' -import ' + arguments.buildRoot + '/../Project/ -build myAppApp/TargetRelease -cleanBuild myAppApp/TargetRelease -data ' + jenkinsWorkspaceDirectory + ' -D DO_APPTEST' if not ExcecuteShellCommandAndGetReturnCode(arguments, shellCommand) == 0: print "Error in build" return False </code></pre>
1
2016-10-06T15:28:11Z
39,900,993
<p>Ok, I go it. No comments or answers so far, but, rather then delete the question, I will leave it here in case it helps anyone in future.</p> <p>I Googled further and found <a href="https://www.webcodegeeks.com/python/python-subprocess-example/" rel="nofollow">this page</a>, which, at 1.2 says </p> <blockquote> <p>One way of gaining access to the output of the executed command would be to use PIPE in the arguments stdout or stderr, but the child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from.</p> </blockquote> <p>Sure enough, when I deleted the <code>, stdout=subprocess.PIPE</code> from the code above, it worked as expected.</p> <p>As I only want the exit code from the subprocess, the above code is enough for me. Read the linked page if you want the output of the command.</p>
0
2016-10-06T16:16:35Z
[ "python", "python-2.7", "subprocess" ]
Sort lists in a Pandas Dataframe column
39,900,061
<p>I have a Dataframe column which is a collection of lists</p> <pre><code> a ['a', 'b'] ['b', 'a'] ['a', 'c'] ['c', 'a'] </code></pre> <p>I would like to use this list to group by its unique values (['a', 'b'] &amp; ['a', 'c']). However, this generates an error </p> <pre><code>TypeError: unhashable type: 'list' </code></pre> <p>Is there any way around this. Ideally I would like to sort the values in place and create an additional column of a concatenated string.</p>
3
2016-10-06T15:30:05Z
39,900,295
<p>list are unhashable. however, tuples are hashable</p> <p>use</p> <pre><code>df.groupby([df.a.apply(tuple)]) </code></pre> <p><strong><em>setup</em></strong><br> <code>df = pd.DataFrame(dict(a=[list('ab'), list('ba'), list('ac'), list('ca')]))</code><br> <strong><em>results</em></strong><br> <code>df.groupby([df.a.apply(tuple)]).size()</code></p> <pre><code>a (a, b) 1 (a, c) 1 (b, a) 1 (c, a) 1 dtype: int64 </code></pre>
3
2016-10-06T15:41:14Z
[ "python", "pandas" ]
Sort lists in a Pandas Dataframe column
39,900,061
<p>I have a Dataframe column which is a collection of lists</p> <pre><code> a ['a', 'b'] ['b', 'a'] ['a', 'c'] ['c', 'a'] </code></pre> <p>I would like to use this list to group by its unique values (['a', 'b'] &amp; ['a', 'c']). However, this generates an error </p> <pre><code>TypeError: unhashable type: 'list' </code></pre> <p>Is there any way around this. Ideally I would like to sort the values in place and create an additional column of a concatenated string.</p>
3
2016-10-06T15:30:05Z
39,901,889
<p>You can also sort values by column.</p> <p>Example:</p> <pre><code>x = [['a', 'b'], ['b', 'a'], ['a', 'c'], ['c', 'a']] df = pandas.DataFrame({'a': Series(x)}) df.a.sort_values() a 0 [a, b] 2 [a, c] 1 [b, a] 3 [c, a] </code></pre> <p>However, for what I understand, you want to sort <code>[b, a]</code> to <code>[a, b]</code>, and <code>[c, a]</code> to <code>[a, c]</code> and then <code>set</code> values in order to get only <code>[a, b][a, c]</code>.</p> <p>i'd recommend use <code>lambda</code></p> <p>Try:</p> <pre><code>result = df.a.sort_values().apply(lambda x: sorted(x)) result = DataFrame(result).reset_index(drop=True) </code></pre> <p>It returns:</p> <pre><code>0 [a, b] 1 [a, c] 2 [a, b] 3 [a, c] </code></pre> <p>Then get unique values:</p> <pre><code>newdf = pandas.DataFrame({'a': Series(list(set(result['a'].apply(tuple))))}) newdf.sort_values(by='a') a 0 (a, b) 1 (a, c) </code></pre>
2
2016-10-06T17:07:07Z
[ "python", "pandas" ]
Unable to install tweepy in Python on Windows 7
39,900,113
<p>I have Python 3.5.2 installed on Windows 7 (64bit). Pip module is installed as well by default. I am new to installing Python packages. I am trying to install tweepy module, but keep running into the problem described below:</p> <p>1) I tried to install tweepy navigating to C:...\Python35\Scripts in command line and running "pip install tweepy" from there, but it returns the error below:</p> <p><a href="http://i.stack.imgur.com/DDxu0.png" rel="nofollow">Command line error - pip installation</a></p> <p>2) Afterwards, I downloaded tweepy from GitHub, unzipped it and try to install it from command line by navigating to the tweepy folder and running "setup.py install" from there, but I received the error below:</p> <p><a href="http://i.stack.imgur.com/XPt8W.png" rel="nofollow">Command line error - setup.py installation</a></p> <p>The installation crashed when trying to download some "six" module. Does anyone know solution to this problem? I read through all the possible posts, but none addresses this issue.</p>
-1
2016-10-06T15:32:25Z
39,900,520
<p>Your first screenshot is clear.</p> <p>The sentence <em>Requirement already satisfied</em> makes me thinks that you have already installed <strong>tweepy</strong>.</p> <p>To check this I suggest you to go in <em>C:...\Python35\Scripts</em> and type </p> <pre><code>pip freeze </code></pre> <p>This command shows all packages that you have installed. So check if there is <strong>tweepy</strong>.</p> <p>After this try to open a terminal and launch python3 interpreter. Try to import in this way:</p> <pre><code>import tweepy </code></pre> <p>If this command doesn't raise any error, your package is ready to be used.</p> <p>If you are not able to use it yet, try to update tweety as MooingRawr suggests you in the comments.</p> <p>Lastly, i suggest you to read the <a href="http://tweepy.readthedocs.io/en/v3.5.0/index.html" rel="nofollow">documentation</a>, for each package not only for tweepy.</p>
0
2016-10-06T15:51:51Z
[ "python", "windows", "pip", "tweepy", "six" ]
Unable to install tweepy in Python on Windows 7
39,900,113
<p>I have Python 3.5.2 installed on Windows 7 (64bit). Pip module is installed as well by default. I am new to installing Python packages. I am trying to install tweepy module, but keep running into the problem described below:</p> <p>1) I tried to install tweepy navigating to C:...\Python35\Scripts in command line and running "pip install tweepy" from there, but it returns the error below:</p> <p><a href="http://i.stack.imgur.com/DDxu0.png" rel="nofollow">Command line error - pip installation</a></p> <p>2) Afterwards, I downloaded tweepy from GitHub, unzipped it and try to install it from command line by navigating to the tweepy folder and running "setup.py install" from there, but I received the error below:</p> <p><a href="http://i.stack.imgur.com/XPt8W.png" rel="nofollow">Command line error - setup.py installation</a></p> <p>The installation crashed when trying to download some "six" module. Does anyone know solution to this problem? I read through all the possible posts, but none addresses this issue.</p>
-1
2016-10-06T15:32:25Z
39,917,445
<p>After some testing I was finally able to successfully import tweety in Python interpreter as well as all its dependencies (that includes modules <em>six, requests, requests-oauthlib</em> and <em>oauthlib</em>).</p> <p>The solution was the following:</p> <p>I installed <em>six</em> using <code>pip install C:...\Python35\Scripts\file.whl</code>. The wheel file was downloaded from <a href="https://pypi.python.org/pypi/six/" rel="nofollow">https://pypi.python.org/pypi/six/</a>. The same solution worked for <em>requests</em> module, which was also not installed and required as a dependency by tweepy 3.5.0.</p> <p>I installed <em>requests-oauthlib</em> using <code>setup.py install</code> from the folder where the unzipped tar.gz file was stored. I donwloaded the zipped tar.gz file from <a href="https://pypi.python.org/pypi/requests-oauthlib/0.7.0" rel="nofollow">https://pypi.python.org/pypi/requests-oauthlib/0.7.0</a>. The same solution worked for <em>oauthlib</em> module.</p> <p>To conclude, it seems like the original tweepy installation did not installed some of its dependencies along with it. The solution was to download all the missing modules from <em>pypi</em> (<em>whl</em> or <em>tar.gz</em> file) and install them one by one. The methods are more closely described above.</p>
0
2016-10-07T12:34:05Z
[ "python", "windows", "pip", "tweepy", "six" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> <p>This has the unique column vectors <code>[1.,2.]</code>, <code>[0.,0.]</code>, <code>[0.,4.]</code> and <code>[0.,3.]</code>. There is one duplicate: <code>[0.,0.]</code> appears twice.</p> <p>Now I found a way to get the unique vectors and their indices <a href="http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">here</a> but it is not clear to me how I would get the occurences of duplicates as well. I have tried several naive ways (with <code>np.where</code> and list comps) but those are all very very slow. Surely there has to be a numpythonic way?</p> <p>In matlab it's just the <code>unique</code> function but <code>np.unique</code> flattens arrays.</p>
4
2016-10-06T15:36:49Z
39,901,297
<p>For small arrays:</p> <pre><code> from collections import defaultdict indices = defaultdict(list) for index, column in enumerate(a.transpose()): indices[tuple(column)].append(index) unique = [kk for kk, vv in indices.items() if len(vv) == 1] non_unique = {kk:vv for kk, vv in indices.items() if len(vv) != 1} </code></pre>
-1
2016-10-06T16:32:35Z
[ "python", "arrays", "numpy", "unique" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> <p>This has the unique column vectors <code>[1.,2.]</code>, <code>[0.,0.]</code>, <code>[0.,4.]</code> and <code>[0.,3.]</code>. There is one duplicate: <code>[0.,0.]</code> appears twice.</p> <p>Now I found a way to get the unique vectors and their indices <a href="http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">here</a> but it is not clear to me how I would get the occurences of duplicates as well. I have tried several naive ways (with <code>np.where</code> and list comps) but those are all very very slow. Surely there has to be a numpythonic way?</p> <p>In matlab it's just the <code>unique</code> function but <code>np.unique</code> flattens arrays.</p>
4
2016-10-06T15:36:49Z
39,901,407
<p>Here's a vectorized approach to give us a list of arrays as output -</p> <pre><code>ids = np.ravel_multi_index(a.astype(int),a.max(1).astype(int)+1) sidx = ids.argsort() sorted_ids = ids[sidx] out = np.split(sidx,np.nonzero(sorted_ids[1:] &gt; sorted_ids[:-1])[0]+1) </code></pre> <p>Sample run -</p> <pre><code>In [62]: a Out[62]: array([[ 1., 0., 0., 0., 0.], [ 2., 0., 4., 3., 0.]]) In [63]: out Out[63]: [array([1, 4]), array([3]), array([2]), array([0])] </code></pre>
0
2016-10-06T16:38:48Z
[ "python", "arrays", "numpy", "unique" ]
How to get unique rows and their occurrences for 2D array?
39,900,208
<p>I have a 2D array, and it has some duplicate columns. I would like to be able to see which unique columns there are, and where the duplicates are.</p> <p>My own array is too large to put here, but here is an example:</p> <pre><code>a = np.array([[ 1., 0., 0., 0., 0.],[ 2., 0., 4., 3., 0.],]) </code></pre> <p>This has the unique column vectors <code>[1.,2.]</code>, <code>[0.,0.]</code>, <code>[0.,4.]</code> and <code>[0.,3.]</code>. There is one duplicate: <code>[0.,0.]</code> appears twice.</p> <p>Now I found a way to get the unique vectors and their indices <a href="http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array">here</a> but it is not clear to me how I would get the occurences of duplicates as well. I have tried several naive ways (with <code>np.where</code> and list comps) but those are all very very slow. Surely there has to be a numpythonic way?</p> <p>In matlab it's just the <code>unique</code> function but <code>np.unique</code> flattens arrays.</p>
4
2016-10-06T15:36:49Z
39,903,835
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) contains efficient functionality for computing these kind of things:</p> <pre><code>import numpy_indexed as npi unique_columns = npi.unique(a, axis=1) non_unique_column_idx = npi.multiplicity(a, axis=1) &gt; 1 </code></pre> <p>Or alternatively:</p> <pre><code>unique_columns, column_count = npi.count(a, axis=1) duplicate_columns = unique_columns[:, column_count &gt; 1] </code></pre>
0
2016-10-06T19:05:50Z
[ "python", "arrays", "numpy", "unique" ]
How create the Decay function in ElasticSearch DSL python
39,900,211
<p>I am querying the Elastic Search with <a href="https://pypi.python.org/pypi/elasticsearch-dsl/2.0.0" rel="nofollow">elasticsearch-dsl/2.0.0</a></p> <pre><code> "linear": { "date": { "origin": "now", "scale": "10d", "offset": "5d", "decay" : 0.5 } } </code></pre> <p><a href="https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-function-score-query.html#function-decay" rel="nofollow">https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-function-score-query.html#function-decay</a></p> <p>How to construct the linear function query with elasticsearch-dsl</p>
2
2016-10-06T15:36:54Z
39,909,469
<p>Try the following query</p> <pre><code>from elasticsearch import Elasticsearch from elasticsearch_dsl import Search, query client = Elasticsearch() s = Search(using=client) function_score_query = query.Q( 'function_score', query=query.Q('match', your_field='your_query'), functions=[ query.SF('linear',date={"origin":"now","scale":"10d", "offset":"5d", "decay":0.5}) ] ) </code></pre> <p>If you print the <code>function_score_query.to_dict()</code> you will get</p> <pre><code>{ 'function_score': { 'query': { 'match': { 'your_field': 'your_query' } }, 'functions': [{ 'linear': { 'date': { 'origin': 'now', 'decay': 0.5, 'scale': '10d', 'offset': '5d' } } }] } } </code></pre> <p>You could check the <a href="https://github.com/elastic/elasticsearch-dsl-py/blob/3ebb486363b2c94172b81668e41fdb2411e5a022/test_elasticsearch_dsl/test_query.py#L284" rel="nofollow">test cases</a> on github to see how function score query can be used in DSL</p>
1
2016-10-07T04:36:07Z
[ "python", "elasticsearch" ]
Ansible prompt_vars error: GetPassWarning: Cannot control echo on the terminal
39,900,282
<p>I am using Ansible and Docker for automating the environment build process. I use prompt_vars to try to collect the username and password for the git repo but unfortunately i got this error: </p> <blockquote> <p>GetPassWarning: Cannot control echo on the terminal</p> </blockquote> <p>The docker ubuntu version is 14.04 and python version is 2.7</p>
0
2016-10-06T15:40:20Z
39,901,858
<p>The error</p> <blockquote> <p>GetPassWarning: Cannot control echo on the terminal</p> </blockquote> <p>is raised by Python and indicates that the terminal you are using does not provide <code>stdin</code>, <code>stdout</code> and <code>stderr</code>. In this case its <code>stderr</code>.</p> <p>As there is not much information provided in the question I guess it is tried to use interactive elements like <code>prompt_vars</code> inside a <code>Dockerfile</code> which is IMHO not possible.</p>
0
2016-10-06T17:04:55Z
[ "python", "docker", "ansible" ]
Installing python package on AWS lambda
39,900,449
<p>I have deployed my <code>zipped</code> project without <code>psycopg2</code> package. I want to install this package on my <code>lambda</code> without re-uploading my fixed project (i haven't access to my project right now). How can i install this <code>package</code> on my <code>lambda</code>? Is it possible to do it with <code>pip</code>?</p>
0
2016-10-06T15:48:06Z
39,900,507
<p>It's not possible to do with <code>pip</code>. You have to add the dependency to your zipped Lambda deployment file. You can't modify your Lambda deployment without uploading a new zipped deployment file.</p>
0
2016-10-06T15:51:13Z
[ "python", "amazon-web-services", "pip", "aws-lambda", "psycopg2" ]
Installing python package on AWS lambda
39,900,449
<p>I have deployed my <code>zipped</code> project without <code>psycopg2</code> package. I want to install this package on my <code>lambda</code> without re-uploading my fixed project (i haven't access to my project right now). How can i install this <code>package</code> on my <code>lambda</code>? Is it possible to do it with <code>pip</code>?</p>
0
2016-10-06T15:48:06Z
39,902,104
<p>It is not possible to use <strong>pip directly on the lambda</strong>. Rather I use a custom build script to create zip package [this can give you a brief idea - it can certainly be made much simpler]</p> <pre><code>rm -rf ~/devops/tempenv &gt; /dev/null virtualenv ~/devops/tempenv source ~/devops/tempenv/bin/activate pip install SlackClient pip install PyYaml deactivate rm -rf temp &gt; /dev/null mkdir temp rm aws-lambda.zip &gt; /dev/null cp -r ~/devops/tempenv/lib/python2.7/site-packages/* temp/ cp *.py temp cd temp zip -r aws-lambda.zip . mv aws-lambda.zip ../ cd .. rm -rf temp rm -rf ~/devops/tempenv </code></pre>
0
2016-10-06T17:20:23Z
[ "python", "amazon-web-services", "pip", "aws-lambda", "psycopg2" ]
Pandas pivot_table do not comply with values order
39,900,493
<p>I have an issue with pandas pivot_table.</p> <p>Sometimes, the order of the columns specified on "values" list does not match</p> <pre><code>In [11]: p = pivot_table(df, values=["x","y"], cols=["month"], rows="name", aggfunc=np.sum) </code></pre> <p>i get the wrong order (y,x) instead of (x,y)</p> <pre><code>Out[12]: y x month 1 2 3 1 2 3 name a 1 NaN 7 2 NaN 8 b 3 NaN 9 4 NaN 10 c NaN 5 NaN NaN 6 NaN </code></pre> <p>Is there something i don't do well ?</p>
3
2016-10-06T15:50:33Z
39,903,058
<p>According to the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pandas documentation</a>, <code>values</code> should take the name of a single column, not an iterable.</p> <blockquote> <p>values : column to aggregate, optional</p> </blockquote>
1
2016-10-06T18:19:13Z
[ "python", "pandas", "pivot-table" ]
How to apply a function can test whether an element in a list in data frame with python-pandas?
39,900,505
<p>For a data frame <code>df</code>, it has a column <code>col</code> contains <code>list</code> value:</p> <pre><code> id col 1 [1, 10, 23] 2 [2, 11, 19, 29] .. </code></pre> <p>I tried:</p> <pre><code>df[1 in df.col] </code></pre> <p>But got an error:</p> <pre><code>KeyError: True </code></pre> <p>Do you know how can I implement it appropriately? Thanks in advance!</p>
2
2016-10-06T15:51:08Z
39,900,621
<p>option using <code>apply</code><br> <code>df.col.apply(lambda x: 1 in x)</code></p> <p><strong><em>demo</em></strong><br> <code>df[df.col.apply(lambda x: 1 in x)]</code><br> <a href="http://i.stack.imgur.com/wRvd7.png" rel="nofollow"><img src="http://i.stack.imgur.com/wRvd7.png" alt="enter image description here"></a></p>
3
2016-10-06T15:57:12Z
[ "python", "pandas" ]
How to apply a function can test whether an element in a list in data frame with python-pandas?
39,900,505
<p>For a data frame <code>df</code>, it has a column <code>col</code> contains <code>list</code> value:</p> <pre><code> id col 1 [1, 10, 23] 2 [2, 11, 19, 29] .. </code></pre> <p>I tried:</p> <pre><code>df[1 in df.col] </code></pre> <p>But got an error:</p> <pre><code>KeyError: True </code></pre> <p>Do you know how can I implement it appropriately? Thanks in advance!</p>
2
2016-10-06T15:51:08Z
39,900,874
<p>try read the "apply" function in pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">document</a>.</p> <pre><code>df['has_element'] = df['col'].apply(lambda x: element in x) </code></pre>
1
2016-10-06T16:10:21Z
[ "python", "pandas" ]
How to make a python program that lists the positions and displays and error message if not found
39,900,510
<p>I did this code:</p> <pre><code>sentence = input("Type in your sentance ").lower().split() Word = input("What word would you like to find? ") Keyword = Word.lower().split().append(Word) positions = [] for (S, subword) in enumerate(sentence): if (subword == Word): positions.append print("The word" , Word , "is in position" , S+1) </code></pre> <p>But there are 2 problems with it; I dont know how to write a code when the users word is not found and to but the positions in "The word position is in [1,3,6,9]. Any help? Thanks</p>
1
2016-10-06T15:51:19Z
39,900,786
<p>Your code is having multiple errors. I am pasting here the sample code for your reference:</p> <pre><code>from collections import defaultdict sentence_string = raw_input('Enter Sentence: ') # Enter Sentence: Here is the content I need to check for index of all words as Yes Hello Yes Yes Hello Yes word_string = raw_input("Enter Words: ") # Enter Words: yes hello word_list = sentence_string.lower().split() words = word_string.lower().split() my_dict = defaultdict(list) for i, word in enumerate(word_list): my_dict[word].append(i) for word in words: print "The word" , word, "is in position " , my_dict[word] # The word yes is in position [21, 23, 24, 26] # The word hello is in position [22, 25] </code></pre> <p>The approach here is:</p> <ol> <li>Break your sentence i.e <code>sentence_string</code> here into list of words</li> <li>Break your word string into list of words.</li> <li>Create a dictionary <code>my_dict</code> to store all the indexes of the words in <code>word_list</code></li> <li>Iterate over the <code>words</code> to get your result with index, based on the value you store in <code>my_dict</code>.</li> </ol> <p><em>Note:</em> The commented part in above example is basically the output of the code.</p>
1
2016-10-06T16:05:37Z
[ "python" ]
How to make a python program that lists the positions and displays and error message if not found
39,900,510
<p>I did this code:</p> <pre><code>sentence = input("Type in your sentance ").lower().split() Word = input("What word would you like to find? ") Keyword = Word.lower().split().append(Word) positions = [] for (S, subword) in enumerate(sentence): if (subword == Word): positions.append print("The word" , Word , "is in position" , S+1) </code></pre> <p>But there are 2 problems with it; I dont know how to write a code when the users word is not found and to but the positions in "The word position is in [1,3,6,9]. Any help? Thanks</p>
1
2016-10-06T15:51:19Z
39,901,121
<blockquote> <p>Use index.</p> </blockquote> <pre><code>a = 'Some sentence of multiple words' b = 'a word' def list_matched_indices(list_of_words, word): pos = 0 indices = [] while True: try: pos = list_of_words.index(word, pos) indices.append(pos) pos+=1 except: break if len(indices): print(indices) return indices else: print ("Not found") list_matched_indices(a, b) </code></pre>
0
2016-10-06T16:23:36Z
[ "python" ]
Pulling elements from 2D array based on index array
39,900,543
<p>I have an array as:</p> <pre><code>import numpy as np A = np.arange(15).reshape(3, 5) </code></pre> <p>I also have an index array as:</p> <pre><code>ind = np.asarray([1,2,0,2,2]) </code></pre> <p>The elements of ind represent the row number of A for each column of A.</p> <p>i.e </p> <p>I want to pull <code>ind[0] = 1</code> element from column 0 of A I want to pull <code>ind[4] = 2</code> element from column 4 of A</p> <p>Desired output is:</p> <pre><code>5, 11, 2, 13, 14 </code></pre>
1
2016-10-06T15:53:12Z
39,900,638
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing" rel="nofollow">Numpy's <code>fancy-indexing</code></a> -</p> <pre><code>A[ind,np.arange(ind.size)] </code></pre>
2
2016-10-06T15:58:18Z
[ "python", "numpy" ]
With python how can I have the start of my weeks start on Wednesday instead of Sunday or Monday?
39,900,627
<p>I am using <code>gmtime, strftime and datetime.</code></p> <p>To give context I am setting up an on call schedule, and to allow people to easily switch people's on call schedules I wrote a script to change the xml file to accomplish that. To make it a bit easier on everyone on call I set the script up so that you can ask what the week number of a specific date is. Most of the built in functionality uses Sunday or Monday as the starting date, and that is not what I need. </p> <p>The Function in question:</p> <p>I know <code>%U</code> starts on Sunday, I just need a work around so that it will calculate for it to start on wednesday.</p> <pre><code>`#option 2 def getWeek(): print("\n\n") date = input("Enter the date you want the week number of (MM DD YYYY): ") if(len(date) != 10): print("You typed it in wrong. Try it again.") getWeek() else: d = time.strptime(date, "%m %d %Y") print(strftime("%U" + 2, d))` </code></pre>
0
2016-10-06T15:57:40Z
39,908,836
<p>Why don't you just manually calculate week # yourself.<br> Basic algorithm:</p> <ul> <li>Get current day of year</li> <li>Shift back to the nearest Wednesday (or whatever day you want)</li> <li>Divide by 7 + 1 = Week # (assuming the first partial week is 0)</li> </ul> <p>In code:</p> <pre><code>&gt;&gt;&gt; wednesday = 3 # sunday = 0, monday = 1, etc. &gt;&gt;&gt; week_no = lambda d: (d.tm_yday - (d.tm_wday-wednesday)%7) // 7 + 1 &gt;&gt;&gt; week_no(time.strptime("10 06 2016", "%m %d %Y")) # Thursday 41 &gt;&gt;&gt; week_no(time.strptime("10 04 2016", "%m %d %Y")) # Tuesday 40 </code></pre> <p>Sanity Check:</p> <pre><code>&gt;&gt;&gt; time.strftime("%U", time.strptime("10 06 2016", "%m %d %Y")) '40' &gt;&gt;&gt; time.strftime("%U", time.strptime("10 04 2016", "%m %d %Y")) '40' </code></pre>
1
2016-10-07T03:20:13Z
[ "python", "python-3.x" ]
PyObject_CallObject failing on bytearray method
39,900,630
<p>In the following code I create a pointer to a PyObject, representing a bytearray, using the Python C API. I then extract the method "endswith" from the bytearray and try to call it on the original bytearray itself, expecting it to return <code>Py_True.</code> However, it returns <code>NULL</code> and the program prints "very sad".</p> <pre><code>#include&lt;Python.h&gt; #include&lt;iostream&gt; int main() { Py_Initialize(); //make a one-byte byte array PyObject* oneByteArray = PyByteArray_FromStringAndSize("a", 1); //get the method "endswith" from the object at oneByteArray PyObject* arrayEndsWith = PyObject_GetAttrString(oneByteArray, "endswith"); //ask python if "a" ends with "a" PyObject* shouldbetrue = PyObject_CallObject(arrayEndsWith, oneByteArray); if (shouldbetrue == Py_True) std::cout &lt;&lt; "happy\n"; if(shouldbetrue == NULL)std::cout &lt;&lt; "very sad\n"; Py_Finalize(); return 0; } </code></pre> <p>I have checked in Python that for bytearrays, <code>foo</code> and <code>bar</code>, <code>foo.endswith(bar)</code> returns a Boolean. I also added <code>PyCallable_Check(arrayEndsWith)</code> to the code above and verified that the object is callable. What is my mistake?</p>
3
2016-10-06T15:57:51Z
39,913,456
<p>If you add the line <a href="https://docs.python.org/2/c-api/exceptions.html" rel="nofollow"><code>PyErr_PrintEx(1)</code></a> it helpfully tells you:</p> <blockquote> <p>TypeError: argument list must be a tuple</p> </blockquote> <p>This is confirmed by <a href="https://docs.python.org/2/c-api/object.html" rel="nofollow">the documentation for <code>PyObject_CallObject</code></a>:</p> <blockquote> <p>Call a callable Python object callable_object, with arguments given by the tuple args.</p> </blockquote> <p>There's a whole bunch of ways of calling functions from the C-api. I picked one that doesn't require a tuple and it works for me (but pick the one you like):</p> <pre><code>PyObject* shouldbetrue = PyObject_CallFunctionObjArgs(arrayEndsWith, oneByteArray,NULL); </code></pre>
1
2016-10-07T09:03:59Z
[ "python", "c++", "python-c-api" ]
Moving average by id/group with a defined interval in python
39,900,708
<p>Given is a csv dataset with the following columns and values (example). I want to <strong>add a new column</strong> in my csv data with a <strong>moving average</strong> of S1 according to each id. S1 are my measurements. The timeframe t should be 3.That's how my dataset currently looks.</p> <pre><code>id S1 1 3 1 4 1 2 1 6 1 9 2 3 2 1 2 2 2 3 2 8 2 6 3 1 3 4 3 2 3 8 3 5 </code></pre> <p>And that's what I wanna do:</p> <pre><code>id S1 movA 1 3 NaN 1 4 NaN 1 2 3.000 1 6 4.000 1 9 5.667 2 3 NaN 2 1 NaN 2 2 2.000 2 3 2.000 2 8 4.333 2 6 5.333 3 1 NaN 3 4 NaN 3 2 2.333 3 8 4.667 3 5 5.000 </code></pre>
2
2016-10-06T16:01:18Z
39,901,244
<p>use <code>groupby</code> and <code>rolling</code> with <code>mean</code></p> <pre><code>g = df.groupby('id').S1 rolls = [2, 3, 4, 5] pd.concat([g.rolling(i).mean() for i in rolls], axis=1, keys=rolls) </code></pre> <p><a href="http://i.stack.imgur.com/2veRn.png" rel="nofollow"><img src="http://i.stack.imgur.com/2veRn.png" alt="enter image description here"></a></p>
2
2016-10-06T16:29:58Z
[ "python", "csv", "pandas", "numpy", "moving-average" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 1 ", names) test1 = names os.chdir('Deployment/Work/test2/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 2 ", names) test2 = names print ("Lines ", test1 + test2) </code></pre> <p>Traceback:</p> <pre><code>FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src' </code></pre>
0
2016-10-06T16:02:37Z
39,900,790
<p>Your <code>os.chdir</code> is interpreted relative to the current working directory. Your first <code>os.chdir</code> changes the working directory. The system tries to find the second path relative to the first path.</p> <p>There are several ways to solve this. You can keep track of the current directory and change back to it. Else make the second <code>os.chdir</code> relative to the first directory. (E.g. <code>os.chdir(../../test2/src')</code>. This is slightly ugly. A third option is to make all paths absolute instead of relative.</p>
2
2016-10-06T16:06:04Z
[ "python" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 1 ", names) test1 = names os.chdir('Deployment/Work/test2/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 2 ", names) test2 = names print ("Lines ", test1 + test2) </code></pre> <p>Traceback:</p> <pre><code>FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src' </code></pre>
0
2016-10-06T16:02:37Z
39,900,802
<p>You'll either have to return to the root directory using as many <code>..</code> as required, store the root directory or specify a full directory from your home:</p> <pre><code>curr_path = os.getcwd() os.chdir('Deployment/Work/test2/src') os.chdir(curr_path) os.chdir('Deployment/Work/test2/src') </code></pre> <p>Or:</p> <pre><code>os.chdir('Deployment/Work/test2/src') os.chdir('../../../../Deployment/Work/test2/src') # Not advisable </code></pre> <hr> <p>Instead of the above, you may consider more <em>Pythonic</em> ways to change directories on the fly, like using a <em>context manager</em> for directories:</p> <pre><code>import contextlib import os @contextlib.contextmanager def working_directory(path): prev_cwd = os.getcwd() os.chdir(path) yield os.chdir(prev_cwd) with working_directory('Deployment/Work/test1/src'): names = {} for fn in glob.glob('*.c'): with working_directory('Deployment/Work/test2/src'): names = {} for fn in glob.glob('*.c'): ... </code></pre> <p>You simply specify the relative directory from the current directory, and then run your code in the context of that directory. </p>
2
2016-10-06T16:06:27Z
[ "python" ]
How to change directories within Python?
39,900,734
<p>I have the following code. It works for the first directory but not the second one... What I am trying to do is to count the lines on each of the files in different directory.</p> <pre><code>import csv import copy import os import sys import glob os.chdir('Deployment/Work/test1/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 1 ", names) test1 = names os.chdir('Deployment/Work/test2/src') names={} for fn in glob.glob('*.c'): with open(fn) as f: names[fn]=sum(1 for line in f if line.strip() and not line.startswith('/') and not line.startswith('#') and not line.startswith('/*')and not line.startswith(' *')) print ("Lines test 2 ", names) test2 = names print ("Lines ", test1 + test2) </code></pre> <p>Traceback:</p> <pre><code>FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Deployment/Work/test2/src' </code></pre>
0
2016-10-06T16:02:37Z
39,900,882
<p>I suppose the script is not working because you are trying to change the directory using a relative path. This means that when you execute the first <code>os.chdir</code> you change your working directory from the current one to <code>'Deployment/Work/test1/src'</code> and when you call <code>os.chdir</code> the second time the function tries to change working directory to <code>'Deployment/Work/test1/src/Deployment/Work/test2/src'</code> that I suppose is not what you want.</p> <p>To solve this you can either use an absolute path:</p> <p><code>os.chdir('/Deployment/Work/test1/src')</code></p> <p>or before the first <code>os.chdir</code> you could keep track of your current folder:</p> <p><code>current = os.getcwd() os.chdir('Deployment/Work/test1/src') ... os.chdir(current) os.chdir('Deployment/Work/test2/src')</code></p>
0
2016-10-06T16:10:43Z
[ "python" ]
Python - tkinter - dynamic checkboxes
39,900,839
<p>One of my courses made a passing reference to tkinter, and that it was out of the scope of what the introductory course offered. It piqued my curiosity though and I wanted to dig deeper into it.</p> <p>I have the basics down - I can get checkboxes to appear where I want them to, but I'd like to make it more dynamic/pythonic.</p> <p>Column 1 - all checkboxes should always display. This works as expected. Column 2 - only the first checkbox should display, and if it's clicked, then the additional 4 checkboxes should display. When any of those 4 checkboxes are clicked, it should display a message in the text box at the bottom of the UI.</p> <p>When I click the checkboxes for the focus courses in the 2nd column at the moment, they do nothing. Also, the ABC 702 checkbox that is normally hidden seems to randomly appear when the checkbox for a core course is selected. I can't figure out why.</p> <pre><code> from tkinter import * class Application(Frame): def __init__(self, master): Frame.__init__(self, master) self.grid() self.create_widgets() # self.grid() # self.create_widgets() def create_widgets(self): Label(self, text="How many of the core courses have you completed so far?" ).grid(row=1, column=0, sticky=W) self.checkBoxA = BooleanVar() Checkbutton(self, text="ABC 501", variable=self.checkBoxA, command=self.update_text ).grid(row=2, column=0, sticky=W) self.checkBoxB = BooleanVar() Checkbutton(self, text="ABC 502", variable=self.checkBoxB, command=self.update_text ).grid(row=3, column=0, sticky=W) self.checkBoxC = BooleanVar() Checkbutton(self, text="ABC 601", variable=self.checkBoxC, command=self.update_text ).grid(row=4, column=0, sticky=W) self.checkBoxD = BooleanVar() Checkbutton(self, text="ABC 602", variable=self.checkBoxD, command=self.update_text ).grid(row=5, column=0, sticky=W) self.checkBoxE = BooleanVar() Checkbutton(self, text="ABC 603", variable=self.checkBoxE, command=self.update_text ).grid(row=6, column=0, sticky=W) self.checkBoxF = BooleanVar() Checkbutton(self, text="ABC 701", variable=self.checkBoxF, command=self.update_text ).grid(row=7, column=0, sticky=W) self.results_txt = Text(self, width=80, height=10, wrap=WORD) self.results_txt.grid(row=8, column=0, columnspan=3) Label(self, text="Which focus are you enrolled in?" ).grid(row=1, column=1, sticky=W) self.checkBoxF1 = BooleanVar() Checkbutton(self, text="Focus #1", variable=self.checkBoxF1, command=self.update_text ).grid(row=2, column=1, sticky=W) # if self.checkBoxF1.get(): # self.checkBoxF1A = BooleanVar() # Checkbutton(self, # text="ABC 503", # variable=self.checkBoxF1A, # command=self.update_text # ).grid(row=3, column=1, sticky=W) def update_text(self): courses = "" counter = 0 focusCounter = 0 ##The checkboxes for the focus courses do not display text at the bottom ##The ABC 702 checkbox randomly appears when clicking core courses ##Is this related to reusing self vs creating another attribute? if self.checkBoxF1.get(): self.checkBoxF1A = BooleanVar() Checkbutton(self, text="ABC 503", variable=self.checkBoxF1A, command=self.update_text ).grid(row=3, column=1, sticky=W) self.checkBoxF1B = BooleanVar() Checkbutton(self, text="ABC 504", variable=self.checkBoxF1B, command=self.update_text ).grid(row=4, column=1, sticky=W) self.checkBoxF1C = BooleanVar() Checkbutton(self, text="ABC 505", variable=self.checkBoxF1C, command=self.update_text ).grid(row=5, column=1, sticky=W) self.checkBoxF1D = BooleanVar() Checkbutton(self, text="ABC 702", variable=self.checkBoxF1D, command=self.update_text ).grid(row=6, column=1, sticky=W) if self.checkBoxA.get(): courses += "Introductory class \n" counter += 1 if self.checkBoxB.get(): courses += "Next level class description \n" counter += 1 if self.checkBoxC.get(): courses += "Core class #3 \n" counter += 1 if self.checkBoxD.get(): courses += "Another core class \n" counter += 1 if self.checkBoxE.get(): courses += "A higher level class \n" counter += 1 if self.checkBoxF.get(): courses += "An advanced class \n" counter += 1 if self.checkBoxF1A.get(): specialty = "Focused class #1" focusCounter += 1 if self.checkBoxF1B.get(): specialty = "Focused class #2" focusCounter += 1 if self.checkBoxF1C.get(): specialty = "Focused class #3" focusCounter += 1 if self.checkBoxF1D.get(): specialty = "Focused class #4" focusCounter += 1 self.results_txt.delete(0.0, END) self.results_txt.insert(0.0, courses) if focusCounter &gt; 0: #this means the user selected at least 1 focus course self.results_txt.insert(0.0, specialty) if counter == 6: congrats = ("\n Congratulations on completing all of your core courses! \n \n") self.results_txt.insert(0.0, congrats) # print(focusCounter) root = Tk() root.title("This is where the title goes") app = Application(root) root.mainloop() </code></pre>
-1
2016-10-06T16:08:17Z
39,901,643
<p>If you first click checkbox <code>Focus #1</code> then it shows new checkboxes and they work as expected</p> <p>But if you click other checkbox as first then you get error message </p> <blockquote> <p>AttributeError: 'Application' object has no attribute 'checkBoxF1A'</p> </blockquote> <p>Problem is because in <code>update_text()</code> you use <code>checkBoxF1A</code>, <code>checkBoxF1B</code>, etc. even if they don't exist yet.</p> <pre><code>if self.checkBoxF1A.get(): specialty = "Focused class #1" focusCounter += 1 </code></pre> <p>Create <code>self.checkBoxF1A = BooleanVar()</code> in <code>create_widgets()</code> - not in <code>if self.checkBoxF1.get()</code> and you will not have problem. </p> <p>You can even create Checkbuttons without <code>grid()</code> in <code>create_widgets()</code></p> <pre><code> self.checkbutton_F1 = Checkbuttons(...) </code></pre> <p>and in <code>if self.checkBoxF1A.get():</code> use <code>self.checkbutton_F1.grid(...)</code> to show widget and (in <code>else:</code>) <code>self.checkbutton_F1.grid_forget()</code> to hide it.</p>
0
2016-10-06T16:53:55Z
[ "python", "user-interface", "checkbox", "tkinter", "python-3.5" ]
conda install fails even i found the package by conda info package
39,900,964
<p>I am on windows using Anaconda with python 3.5, I want to install opencv3.1, so I found a channel called conda-forge has the opencv3.2 for my python version, but when I try to install it by:</p> <blockquote> <p>conda install -c conda-forge opencv</p> </blockquote> <p>I got error message:</p> <pre><code>Fetching package metadata ............. Solving package specifications: .... UnsatisfiableError: The following specifications were found to be in conflict: - opencv -&gt; jpeg 9* - opencv -&gt; numpy 1.9* - opencv -&gt; python 2.7*|3.4* Use "conda info &lt;package&gt;" to see the dependencies for each package. </code></pre> <p>but when I do:</p> <blockquote> <p>conda info opencv</p> </blockquote> <p>there is an opencv for python3.5, why conda cannot find it?</p> <pre><code>opencv 3.1.0 np111py35_1 ------------------------ file name : conda-forge::opencv-3.1.0-np111py35_1.tar.bz2 name : opencv version : 3.1.0 build number: 1 build string: np111py35_1 channel : conda-forge size : 84.4 MB arch : x86_64 binstar : {'owner_id': '5528f42ce1dad12974506e8d', 'package_id': '56feac4e676dfa6a0572551e', 'channel': 'main'} fn : opencv-3.1.0-np111py35_1.tar.bz2 has_prefix : True license : BSD 3-clause machine : x86_64 md5 : 9ff21915905c36894059eaf8d6d554cc operatingsystem: win32 platform : win priority : 1 schannel : conda-forge subdir : win-64 target-triplet: x86_64-any-win32 url : https://conda.anaconda.org/conda-forge/win-64/opencv-3.1.0-np111py35_1.tar.bz2 dependencies: jpeg 9* libpng &gt;=1.6.21,&lt;1.7 libtiff 4.0.* numpy 1.11* python 3.5* zlib 1.2.* </code></pre> <p>so I checked the env by <code>conda list</code> and I have:</p> <pre><code>λ conda list # packages in environment at C:\Users\MPNV38\AppData\Local\Continuum\Anaconda3: # _license 1.1 py35_1 _nb_ext_conf 0.3.0 py35_0 alabaster 0.7.9 py35_0 anaconda 4.2.0 np111py35_0 anaconda-clean 1.0.0 py35_0 anaconda-client 1.5.1 py35_0 anaconda-navigator 1.3.1 py35_0 argcomplete 1.0.0 py35_1 astroid 1.4.7 py35_0 astropy 1.2.1 np111py35_0 babel 2.3.4 py35_0 backports 1.0 py35_0 beautifulsoup4 4.5.1 py35_0 bitarray 0.8.1 py35_1 blaze 0.10.1 py35_0 bokeh 0.12.2 py35_0 boto 2.42.0 py35_0 bottleneck 1.1.0 np111py35_0 bzip2 1.0.6 vc14_3 [vc14] cffi 1.7.0 py35_0 chest 0.2.3 py35_0 click 6.6 py35_0 cloudpickle 0.2.1 py35_0 clyent 1.2.2 py35_0 colorama 0.3.7 py35_0 comtypes 1.1.2 py35_0 conda 4.2.9 py35_0 conda-build 2.0.3 py35_0 conda-env 2.6.0 0 configobj 5.0.6 py35_0 console_shortcut 0.1.1 py35_1 contextlib2 0.5.3 py35_0 cryptography 1.5 py35_0 curl 7.49.0 vc14_0 [vc14] cycler 0.10.0 py35_0 cython 0.24.1 py35_0 cytoolz 0.8.0 py35_0 dask 0.11.0 py35_0 datashape 0.5.2 py35_0 decorator 4.0.10 py35_0 dill 0.2.5 py35_0 docutils 0.12 py35_2 dynd-python 0.7.2 py35_0 entrypoints 0.2.2 py35_0 et_xmlfile 1.0.1 py35_0 fastcache 1.0.2 py35_1 filelock 2.0.6 py35_0 flask 0.11.1 py35_0 flask-cors 2.1.2 py35_0 freetype 2.5.5 vc14_1 [vc14] get_terminal_size 1.0.0 py35_0 gevent 1.1.2 py35_0 greenlet 0.4.10 py35_0 h5py 2.6.0 np111py35_2 hdf5 1.8.15.1 vc14_4 [vc14] heapdict 1.0.0 py35_1 icu 57.1 vc14_0 [vc14] idna 2.1 py35_0 imagesize 0.7.1 py35_0 ipykernel 4.5.0 py35_0 ipython 5.1.0 py35_0 ipython_genutils 0.1.0 py35_0 ipywidgets 5.2.2 py35_0 itsdangerous 0.24 py35_0 jdcal 1.2 py35_1 jedi 0.9.0 py35_1 jinja2 2.8 py35_1 jpeg 8d vc14_2 [vc14] jsonschema 2.5.1 py35_0 jupyter 1.0.0 py35_3 jupyter_client 4.4.0 py35_0 jupyter_console 5.0.0 py35_0 jupyter_core 4.2.0 py35_0 lazy-object-proxy 1.2.1 py35_0 libdynd 0.7.2 0 libpng 1.6.22 vc14_0 [vc14] libtiff 4.0.6 vc14_2 [vc14] llvmlite 0.13.0 py35_0 locket 0.2.0 py35_1 lxml 3.6.4 py35_0 markupsafe 0.23 py35_2 matplotlib 1.5.3 np111py35_0 menuinst 1.4.1 py35_0 mistune 0.7.3 py35_0 mkl 11.3.3 1 mkl-service 1.1.2 py35_2 mpmath 0.19 py35_1 multipledispatch 0.4.8 py35_0 nb_anacondacloud 1.2.0 py35_0 nb_conda 2.0.0 py35_0 nb_conda_kernels 2.0.0 py35_0 nbconvert 4.2.0 py35_0 nbformat 4.1.0 py35_0 nbpresent 3.0.2 py35_0 networkx 1.11 py35_0 nltk 3.2.1 py35_0 nose 1.3.7 py35_1 notebook 4.2.3 py35_0 numba 0.28.1 np111py35_0 numexpr 2.6.1 np111py35_0 numpy 1.11.1 py35_1 odo 0.5.0 py35_1 openpyxl 2.3.2 py35_0 openssl 1.0.2j vc14_0 [vc14] pandas 0.18.1 np111py35_0 partd 0.3.6 py35_0 path.py 8.2.1 py35_0 pathlib2 2.1.0 py35_0 patsy 0.4.1 py35_0 pep8 1.7.0 py35_0 pickleshare 0.7.4 py35_0 pillow 3.3.1 py35_0 pip 8.1.2 py35_0 pkginfo 1.3.2 py35_0 ply 3.9 py35_0 prompt_toolkit 1.0.3 py35_0 psutil 4.3.1 py35_0 py 1.4.31 py35_0 pyasn1 0.1.9 py35_0 pycosat 0.6.1 py35_1 pycparser 2.14 py35_1 pycrypto 2.6.1 py35_4 pycurl 7.43.0 py35_0 pyflakes 1.3.0 py35_0 pygments 2.1.3 py35_0 pylint 1.5.4 py35_1 pyopenssl 16.0.0 py35_0 pyparsing 2.1.4 py35_0 pyqt 5.6.0 py35_0 pytables 3.2.2 np111py35_4 pytest 2.9.2 py35_0 python 3.5.2 0 python-dateutil 2.5.3 py35_0 pytz 2016.6.1 py35_0 pywin32 220 py35_1 pyyaml 3.12 py35_0 pyzmq 15.4.0 py35_0 qt 5.6.0 vc14_0 [vc14] qtawesome 0.3.3 py35_0 qtconsole 4.2.1 py35_2 qtpy 1.1.2 py35_0 requests 2.11.1 py35_0 rope 0.9.4 py35_1 ruamel_yaml 0.11.14 py35_0 scikit-image 0.12.3 np111py35_1 scikit-learn 0.17.1 np111py35_1 scipy 0.18.1 np111py35_0 setuptools 27.2.0 py35_1 simplegeneric 0.8.1 py35_1 singledispatch 3.4.0.3 py35_0 sip 4.18 py35_0 six 1.10.0 py35_0 snowballstemmer 1.2.1 py35_0 sockjs-tornado 1.0.3 py35_0 sphinx 1.4.6 py35_0 spyder 3.0.0 py35_0 sqlalchemy 1.0.13 py35_0 statsmodels 0.6.1 np111py35_1 sympy 1.0 py35_0 tk 8.5.18 vc14_0 [vc14] toolz 0.8.0 py35_0 tornado 4.4.1 py35_0 traitlets 4.3.0 py35_0 unicodecsv 0.14.1 py35_0 vs2015_runtime 14.0.25123 0 wcwidth 0.1.7 py35_0 werkzeug 0.11.11 py35_0 wheel 0.29.0 py35_0 widgetsnbextension 1.2.6 py35_0 win_unicode_console 0.5 py35_0 wrapt 1.10.6 py35_0 xlrd 1.0.0 py35_0 xlsxwriter 0.9.3 py35_0 xlwings 0.10.0 py35_0 xlwt 1.1.2 py35_0 zlib 1.2.8 vc14_3 [vc14] </code></pre>
0
2016-10-06T16:14:51Z
40,090,173
<p>Please check the link <a href="https://github.com/ContinuumIO/anaconda-issues/issues/1074" rel="nofollow">here</a>. As far as I understand, it is an issue related to the new version of anaconda. If you need to find a fast solution, you can simply create a virtual environment, activate the environment, and install opencv there.</p> <p>The other solution is to simply use this command:</p> <p><code>conda install -c menpo opencv3=3.1.0</code></p>
0
2016-10-17T15:22:32Z
[ "python", "opencv", "anaconda", "conda" ]
Python - Gathering File Information Recursively Leads to Memory Error
39,901,031
<p>I am writing a script to recurse over all directories and subdirectories of a starting folder but I'm running into memory errors (the error is <code>MemoryError</code>). My guess would be that maybe my <code>data_dicts</code> list is getting too big but I'm not sure. Any advice would be appreciated.</p> <pre><code>import os # example data dictionary data_dict = { 'filename': 'data.csv', 'folder': 'R:/', 'size': 300000 } def get_file_sizes_folder(data_dicts, starting_folder): # Given a list of file information dictionaries and a folder, iterate over the files # in the folder to get their information and append it to the list. # Also recurse through subdirectories for entry in os.scandir(starting_folder): if not entry.name.startswith('.'): if entry.is_file(): size = entry.stat().st_size filename = entry.name folder = os.path.dirname(entry.path) temp_dict = {'filename': filename, 'size': size, 'folder': folder} data_dicts.append(temp_dict.copy()) else: print(entry.path) data_dicts.extend(get_file_sizes_folder(data_dicts, entry.path)) return data_dicts d = get_file_sizes_folder([], 'R:/') </code></pre>
0
2016-10-06T16:18:26Z
39,901,647
<p>You shouldn't supply <code>data_dicts</code> as an argument to your function <code>get_file_sizes_folder()</code>. Doing so will produce many, many duplicates of your entries, at a rate that is probably nearly factorial. No wonder that your computer runs out of memory very quickly!</p> <p>Instead, use only <code>starting_folder</code> as an argument, and simply create a new list <code>data_dicts</code> in the first line of your function, like so: </p> <pre class="lang-py prettyprint-override"><code>def get_file_sizes_folder(starting_folder): # Given a list of file information dictionaries and a folder, iterate over the files # in the folder to get their information and append it to the list. # Also recurse through subdirectories data_dicts = [] for entry in os.scandir(starting_folder): if not entry.name.startswith('.'): if entry.is_file(): size = entry.stat().st_size filename = entry.name folder = os.path.dirname(entry.path) temp_dict = {'filename': filename, 'size': size, 'folder': folder} data_dicts.append(temp_dict) else: print(entry.path) data_dicts.extend(get_file_sizes_folder(entry.path)) return data_dicts </code></pre>
3
2016-10-06T16:54:08Z
[ "python", "recursion" ]
Python - Gathering File Information Recursively Leads to Memory Error
39,901,031
<p>I am writing a script to recurse over all directories and subdirectories of a starting folder but I'm running into memory errors (the error is <code>MemoryError</code>). My guess would be that maybe my <code>data_dicts</code> list is getting too big but I'm not sure. Any advice would be appreciated.</p> <pre><code>import os # example data dictionary data_dict = { 'filename': 'data.csv', 'folder': 'R:/', 'size': 300000 } def get_file_sizes_folder(data_dicts, starting_folder): # Given a list of file information dictionaries and a folder, iterate over the files # in the folder to get their information and append it to the list. # Also recurse through subdirectories for entry in os.scandir(starting_folder): if not entry.name.startswith('.'): if entry.is_file(): size = entry.stat().st_size filename = entry.name folder = os.path.dirname(entry.path) temp_dict = {'filename': filename, 'size': size, 'folder': folder} data_dicts.append(temp_dict.copy()) else: print(entry.path) data_dicts.extend(get_file_sizes_folder(data_dicts, entry.path)) return data_dicts d = get_file_sizes_folder([], 'R:/') </code></pre>
0
2016-10-06T16:18:26Z
39,912,697
<p>You shouldn't perform a recursion at all. Use <a href="https://docs.python.org/2.7/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a></p> <p>Example:</p> <pre><code>def get_file_sizes_folder(starting_folder): data_dicts = list() for root, _, files in os.walk(starting_folder): data_dicts.extend({ 'filename': f, 'size': os.path.getsize(os.path.join(root, f)), 'folder': root, } for f in files) return data_dicts d = get_file_sizes_folder('R:/') </code></pre>
1
2016-10-07T08:22:23Z
[ "python", "recursion" ]
A split image can't be merged after performing a .dot on any of the split bands using pillow/numpy
39,901,043
<p>I am trying to correct the color in images using pillow and numpy. Using im.split() in combination with np.array.</p> <p>I would like to multiply all colours in the red band, but can't find a way of doing it.</p> <p>I've tried all kinds of things and after a lot of googling had hoped that this would be the solution:</p> <pre><code>from PIL import Image import numpy as np im=Image.open('test.jpg') r,g,b=im.split() datar = np.array(r) datag = np.array(g) datab = np.array(b) rm=0.4 # the value I would like to multiply all red pixels by datar=datar.dot(rm) # this works, but turns the values in the array into floats datar=datar.astype(int) # I was hoping this would solve it im=Image.merge("RGB", (Image.fromarray(datar), Image.fromarray(datag), Image.fromarray(datab))) </code></pre> <p>I can do a lot of things with the arrays and the merge succeeds, but trying this gives me the following error:</p> <pre><code>im=Image.merge("RGB", (Image.fromarray(datar), Image.fromarray(datag), Image.fromarray(datab))) File "/usr/local/lib/python2.7/dist-packages/PIL/Image.py", line 2408, in merge im.putband(bands[i].im, i) ValueError: images do not match </code></pre> <p>The array looks the same before and after the .dot and the .astype(int) are applied, and the values are multiplied correctly.</p>
2
2016-10-06T16:19:06Z
39,901,729
<p><code>Image.merge</code> fails because rgb images are not of the same mode (see <a href="http://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#concept-modes" rel="nofollow">PIL Image modes</a>). You can check the mode this way:</p> <pre><code>&gt;&gt;&gt; Image.fromarray(datar).mode 'I' &gt;&gt;&gt; Image.fromarray(datag).mode 'L' </code></pre> <p>The reason for this is the type of the numpy array:</p> <pre><code>&gt;&gt;&gt; datar.dtype dtype('int32') &gt;&gt;&gt; datag.dtype dtype('uint8') </code></pre> <p>To fix that, replace this:</p> <pre><code>datar=datar.astype(int) </code></pre> <p>with this:</p> <pre><code>datar = datar.astype('uint8') </code></pre>
2
2016-10-06T16:58:28Z
[ "python", "arrays", "python-2.7", "numpy", "pillow" ]
Can I setup a PHP Twilio application server and grant push capabilities
39,901,053
<p>I currently use a Python Twilio application server and grant push capabilities to my tokens with the following lines of code:</p> <pre><code>@app.route('/accessToken') def token(): account_sid = os.environ.get("ACCOUNT_SID", ACCOUNT_SID) api_key = os.environ.get("API_KEY", API_KEY) api_key_secret = os.environ.get("API_KEY_SECRET", API_KEY_SECRET) push_credential_sid = os.environ.get("PUSH_CREDENTIAL_SID", PUSH_CREDENTIAL_SID) app_sid = os.environ.get("APP_SID", APP_SID) grant = VoiceGrant( push_credential_sid=push_credential_sid, outgoing_application_sid=app_sid ) token = AccessToken(account_sid, api_key, api_key_secret, IDENTITY) token.add_grant(grant) return str(token) </code></pre> <p>Is there a way for me to do that with PHP? I have loaded Twilio dependencies with composer and can get a token just fine. I just don't know how to add push capabilities to the token. These lines currently generate tokens (but not with push capabilities):</p> <pre><code>&lt;?php include('./vendor/autoload.php'); include('./config.php'); include('./randos.php'); use Twilio\Jwt\ClientToken; use Twilio\Jwt\Grants; // choose a random username for the connecting user $identity = $_GET['identity']; $capability = new ClientToken($TWILIO_ACCOUNT_SID, $TWILIO_AUTH_TOKEN); $capability-&gt;allowClientOutgoing($TWILIO_TWIML_APP_SID); $capability-&gt;allowClientIncoming($identity); $token = $capability-&gt;generateToken(); echo $token; ?&gt; </code></pre>
2
2016-10-06T16:19:32Z
39,910,755
<p>Thanks to a tip from Zack with Twilio, I finally got this working!</p> <pre><code>include('./vendor/autoload.php'); include('./config.php'); include('./randos.php'); use Twilio\Jwt\AccessToken; use Twilio\Jwt\Grants; use Twilio\Jwt\Grants\VoiceGrant; use Twilio\Rest\Client; // choose a random username for the connecting user $identity = randomUsername(); $token = new AccessToken($TWILIO_ACCOUNT_SID, $API_KEY, $API_KEY_SECRET, 3600, $identity); $grant = new VoiceGrant(); $grant-&gt;setPushCredentialSid($PUSH_CREDENTIAL_SID); $grant-&gt;setOutgoingApplicationSid($TWILIO_TWIML_APP_SID); $token-&gt;addGrant($grant); echo $token; </code></pre>
1
2016-10-07T06:26:30Z
[ "php", "python", "twilio" ]
Finding Range of active/selected cell in Excel using Python and xlwings
39,901,092
<p>I am trying to write a simple function in Python (with xlwings) that reads a current 'active' cell value in Excel and then writes that cell value to the cell in the next column along from the active cell.</p> <p>If I specify the cell using an absolute reference, for example range(3, 2), then I everything is ok. However, I can't seem to manage to find the row and column values of whichever cell is selected once the function is run.</p> <p>I have found a lot of examples where the reference is specified but not where the active cell range can vary depending on the user selection.</p> <p>I have tried a few ideas. The first option is trying to use the App.selection that I found in the v0.10.0 xlwings documentation but this doesn't seem to return a range reference that can be used - I get an error "Invalid parameter" when trying to retrieve the row from 'cellRange':</p> <pre><code>def refTest(): import xlwings as xw wb = xw.Book.caller() cellRange = xw.App.selection rowNum = wb.sheets[0].range(cellRange).row colNum = wb.sheets[0].range(cellRange).column url = wb.sheets[0].range(rowNum, colNum).value wb.sheets[0].range(rowNum, colNum + 1).value = url </code></pre> <p>The second idea was to try to read the row and column directly from the cell selection but this gives me the error "Property object has no attribute 'row'":</p> <pre><code>def refTest(): import xlwings as xw wb = xw.Book.caller() rowNum = xw.App.selection.row colNum = xw.App.selection.column url = wb.sheets[0].range(rowNum, colNum).value wb.sheets[0].range(rowNum, colNum + 1).value = url </code></pre> <p>Is it possible to pass the range of the active/selected cell from Excel to Python with xlwings? If anyone is able to shed some light on this then I would really appreciate it.</p> <p>Thanks!</p>
0
2016-10-06T16:22:06Z
39,905,568
<p>You have to get the app object from the workbook. You'd only use <code>xw.App</code> directly if you wanted to instantiate a new app. Also, <code>selection</code> returns a Range object, so do this: </p> <pre><code>cellRange = wb.app.selection rowNum = cellRange.row colNum = cellRange.column </code></pre>
0
2016-10-06T21:02:32Z
[ "python", "xlwings" ]
How to avoid encoding parameter when opening file in Python3
39,901,130
<p>When I am working on a .txt file on a Windows device I must save as either: ANSI, Unicode, Unicode big endian, or UTF-8. When I run Python3 on an OSX device and try to import and read the .txt file, I have to do something along the lines of:</p> <pre><code>with open('ships.txt', 'r', encoding='utf-8') as f: for line in f.readlines(): print(line) </code></pre> <p>Is there a particular format I should use to encode the .txt file on the Windows device to avoid adding the encoding parameter when opening the file in Python?</p>
0
2016-10-06T16:24:08Z
39,911,243
<p>Call <code>locale.getpreferredencoding(False)</code> on your OSX device. That's the default encoding used for reading a file on that device. Save in that encoding on Windows and you won't need to specify the encoding on your OSX device.</p> <p>But as the <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a> says, "Explicit is better than implicit." Since you know the encoding, why not specify it?</p>
0
2016-10-07T06:59:17Z
[ "python", "unicode", "encoding", "python-import" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not a word right?</p>
-1
2016-10-06T16:24:23Z
39,901,202
<p>Use <code>word in sentence</code>. For example:</p> <pre><code>&gt;&gt;&gt; 'el' in 'Hello' True &gt;&gt;&gt; 'xy' in 'Hello' False </code></pre> <p>For your reference, check: <a href="http://kracekumar.com/post/22512660850/python-in-operator-use-cases" rel="nofollow">python <code>in</code> operator use cases</a></p>
1
2016-10-06T16:27:29Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not a word right?</p>
-1
2016-10-06T16:24:23Z
39,901,218
<p>Simple:</p> <pre><code>&gt;&gt;&gt; var = "I eat breakfast." &gt;&gt;&gt; 'ea' in var True </code></pre> <p>I'm not clear what you mean by "put those values into a list." I assume you mean the words:</p> <pre><code>&gt;&gt;&gt; [w for w in var.split() if 'ea' in w] ['eat', 'breakfast.'] </code></pre>
1
2016-10-06T16:28:11Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not a word right?</p>
-1
2016-10-06T16:24:23Z
39,901,234
<p>You can use <code>in</code> to check if a string contains a substring. It also sounds like you want to add <code>var</code> to a list if it contains a substring. Observe the following interactive session:</p> <pre><code>In [1]: var = "I eat breakfast." In [2]: lst = [] In [3]: if "ea" in var: ...: lst.append(var) ...: In [4]: lst Out[4]: ['I eat breakfast.'] </code></pre>
0
2016-10-06T16:29:19Z
[ "python", "python-3.x" ]
Python check if string got a certain word (or combination of characters)
39,901,140
<p>Ok so I have this string (for example):</p> <pre><code>var = "I eat breakfast." </code></pre> <p>What i would like to do is to check if that string has the letters "ea", and I wanted to be able to put those values into a list.</p> <p>I tried using var[x] but I can only have one character at the same time and not a word right?</p>
-1
2016-10-06T16:24:23Z
39,901,395
<p>This is a duplicate of <a href="http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python#3873422">Finding multiple occurrences of a string within a string in Python</a></p> <p>You can use <code>find(str, startIndex)</code> like so:</p> <pre><code>var = "I eat breakfast." locations = [] index = 0 while index &lt; len(var): index = var.find('ea', index) if index == -1: break locations.append(index) index += 2 </code></pre> <p><code>locations</code> is a list of the indices where <code>'ea'</code> was found.</p>
1
2016-10-06T16:37:51Z
[ "python", "python-3.x" ]
Replace values of two columns in pandas
39,901,162
<p>What is the fastest way to replace values of two columns in pandas? Let's say given is:</p> <pre><code>A B 0 2 1 3 </code></pre> <p>and we want to get:</p> <pre><code>A B 2 0 3 1 </code></pre>
2
2016-10-06T16:25:13Z
39,901,255
<p>This code flips the values between the columns:</p> <pre><code>&gt;&gt;&gt; df_name[['A', 'B']] = df_name[['B', 'A']] &gt;&gt;&gt; print(df_name) A B 2 0 3 1 </code></pre>
4
2016-10-06T16:31:02Z
[ "python", "pandas" ]
Installing librdkafka on Windows to support Python development
39,901,163
<p>A little background: I am working on some python modules that other developers on our team will use. A common theme of each module is that one or more messages will be published to Kafka. We intend at this time to use the Confluent Kafka client. We are pretty new to python development in our organization -- we have traditionally been a .NET shop.</p> <p>The complication: while the code that we create will run on Linux (rhel 7), most of the developers will do their work on Windows.</p> <p>So we need the librdkafka C library compiled on each developer machine (which has dependencies of its own, one of which is OpenSSL). Then a pip install of confluent-kafka should just work, which means a pip install of our package will work. Theoretically.</p> <p>To start I did the install on my Linux laptop (Arch). I knew I already had OpenSSL and the other zip lib dependencies available, so this process was painless:</p> <ul> <li>git clone librdkafka repo</li> <li>configure, make and install per the README</li> <li>pip install confluent-kafka</li> <li>done</li> </ul> <p>The install of librdkafka went into <code>/usr/local</code>:</p> <pre><code>/usr/local/lib/librdkafka.a /usr/local/lib/librdkafka++.a /usr/local/lib/librdkafka.so -&gt; librdkafka.so.l /usr/local/lib/librdkafka++.so -&gt; librdkafka++.so.l /usr/local/lib/librdkafka.so.l /usr/local/lib/librdkafka++.so.l /usr/local/lib/pkgconfig/rdkafka.pc /usr/local/lib/pkgconfig/rdkafka++.pc /usr/local/include/librdkafka/rdkafkacpp.h /usr/local/include/librdkafka/rdkafka.h </code></pre> <p>Now the painful part, making it work on Windows:</p> <ul> <li>install <a href="https://slproweb.com/products/Win32OpenSSL.html" rel="nofollow">precompiled OpenSSL</a></li> <li>git clone librdkafka repo</li> <li>open in VS2015</li> <li>install libz via NuGet</li> <li>build solution</li> <li><strong>install to where???</strong></li> </ul> <p>This is where I'm stuck. <strong>What would a standard install on a Windows 7/8/10 machine look like?</strong></p> <p>I have the following from the build output, but no idea what should go where in order to make the <code>pip install confluent-kafka</code> "just work":</p> <pre><code>/librdkafka/win32/Release/librdkafka.dll /librdkafka/win32/Release/librdkafka.exp /librdkafka/win32/Release/librdkafka.lib /librdkafka/win32/Release/librdkafkacpp.dll /librdkafka/win32/Release/librdkafkacpp.exp /librdkafka/win32/Release/librdkafkacpp.lib /librdkafka/win32/Release/zlib.dll &lt;and the .h files back in the src&gt; </code></pre> <p>Any recommendations on an install location?</p>
2
2016-10-06T16:25:15Z
39,916,730
<p>I'm not sure where the ideal place to install on Windows would be, but I ran the following test with some success.</p> <p>I copied my output and headers to <code>C:\test\lib</code> and <code>C:\test\include</code>, then ran a pip install with the following options:</p> <pre><code> pip install --global-option=build_ext --global-option="-LC:\test\lib" --global-option="-IC:\test\include" confluent-kafka </code></pre> <p>Unfortunately, this doesn't quite work because the confluent-kafka setup does not support Windows at this time: <a href="https://github.com/confluentinc/confluent-kafka-python/issues/52#issuecomment-252098462" rel="nofollow">https://github.com/confluentinc/confluent-kafka-python/issues/52#issuecomment-252098462</a></p>
1
2016-10-07T11:59:03Z
[ "python", "windows", "apache-kafka" ]
Create directory of dynamically created html files. Flask
39,901,177
<p>I've got a simple flask app, with a templates folder with a bunch of html files that are created by a separate program. I want to (1) serve each of these html files by hitting <code>localhost:8888/&lt;html_filename&gt;</code> and (2) create a directory with hyperlinks to these endpoints on my main <code>/</code> endpoint. </p> <p>Thoughts on how I could get a jinja template to create links to those endpoints? Heres what I've been thinking.</p> <p>Flask App:</p> <pre><code>@app.route('/') def index(): reports = [f_name for f_name in os.listdir("templates") if f_name.endswith(".html")] return render_template("index.html", reports=reports) @app.route('/&lt;report&gt;') def render_report(report): return render_template(report+'.html') </code></pre> <p>index.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Report Directory&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;ul&gt; {% for r in reports %} &lt;li&gt; &lt;a href="{{ r }}"&gt;{{ r }}&lt;/a&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2016-10-06T16:26:11Z
39,922,137
<p>Off the top of my head and not tested in any way define a route along the lines of the following:</p> <pre><code>@route("/&lt;string:slug&gt;/", methods=['GET']) def page(self, slug): if slug_exists_as_a_html_file(slug): return render_template(slug) abort(404) </code></pre> <p>The function (or inline it) )<code>slug_exists_as_a_html_file</code> needs to return True if the slug matches a valid html template file, otherwise false.</p> <p>To generate your report listing use something like :</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;Report Directory&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;ul&gt; {% for r in reports %} &lt;li&gt; &lt;a href="{{ url_for('page', slug=r) }}"&gt;{{ r }}&lt;/a&gt; &lt;/li&gt; {% endfor %} &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2016-10-07T16:39:11Z
[ "python", "flask" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,246
<p>This will create list with <code>[0,51]</code> values</p> <pre><code>list_of_cards = [i for i in range(52)] </code></pre> <p>This will create list with <code>[1,52]</code> values (This is what you want to use):</p> <pre><code>list_of_cards = [i for i in range(1,53)] </code></pre>
0
2016-10-06T16:30:21Z
[ "python", "list", "python-3.x" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,369
<p>Use built-in <a href="https://docs.python.org/2/library/functions.html#range" rel="nofollow"><code>range()</code></a> function which returns the list of numbers. For example:</p> <p><strong>In Python 2.7</strong>:</p> <pre><code># To get numbers from 0 to n-1. Here, 'n' = 10 &gt;&gt;&gt; range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # To get numbers from m to n-1. Here, 'm' = 5, 'n' = 10 &gt;&gt;&gt; range(5, 10) [5, 6, 7, 8, 9] # To get numbers from m to n-1 with step of s. Here, 'm' = 5, 'n' = 10, 's' = 2 &gt;&gt;&gt; range(5, 10, 2) [5, 7, 9] </code></pre> <p><strong>In Python 3</strong>: </p> <p>You need to explicitly type-cast it to <code>list</code> as: </p> <pre><code>&gt;&gt;&gt; list(range(10)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] </code></pre>
0
2016-10-06T16:36:15Z
[ "python", "list", "python-3.x" ]
How do you make a list inclusive?
39,901,195
<p>I have homework that asks me to make a list from 1 to 52 inclusive. (for a deck of cards) I was just wondering how do you make a list inclusive?</p> <p>I know how to make a list, just am not sure how to make it inclusive. I searched on here for awhile and couldn't really find anything helpful.</p>
-3
2016-10-06T16:27:02Z
39,901,495
<p>Inclusive is a term that is often used when expressing bounds. It means that the range of this bound includes all values <strong>including</strong> the the inclusive value. An example of this would be:</p> <p><em>Print all integers 1-5 inclusive.</em> The expected output would be:</p> <p>1 2 3 4 5</p> <p>The antonym of this term would be exclusive which would include all values <strong>excluding</strong> the exclusive value. An example of this would be:</p> <p><em>Print all integers 1-5 exclusive.</em> The expected output would be:</p> <p>1 2 3 4</p> <p>It is important to note, that in programming generally the first value is inclusive unless otherwise noted. In mathematics this can differ. Inclusive and exclusive ranges are often notated with [] and ().</p> <p><a href="http://stackoverflow.com/questions/4396290/what-does-this-square-bracket-and-parenthesis-bracket-notation-mean-first1-last">What does this square bracket and parenthesis bracket notation mean [first1,last1)?</a></p>
1
2016-10-06T16:44:31Z
[ "python", "list", "python-3.x" ]
Merge two vectors with alternate locations
39,901,209
<p>I have:</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) </code></pre> <p>I want to create:</p> <pre><code>C = np.asarray([1,2,3, 4,5,6,7,8,9,10]) </code></pre> <p>Is there a better way to do than to run a for loop</p>
0
2016-10-06T16:27:46Z
39,901,289
<p>You can the <em>stack</em> arrays vertically using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html#numpy.vstack" rel="nofollow"><code>vstack</code></a>, <em>transpose</em> and then <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.ravel.html" rel="nofollow"><code>ravel</code></a>:</p> <pre><code>&gt;&gt;&gt; A = np.asarray([1,3,5,7,9]) &gt;&gt;&gt; B = np.asarray([2,4,6,8,10]) &gt;&gt;&gt; C = np.vstack((A, B)).T.ravel() &gt;&gt;&gt; C array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) </code></pre>
1
2016-10-06T16:32:16Z
[ "python", "numpy" ]
Merge two vectors with alternate locations
39,901,209
<p>I have:</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) </code></pre> <p>I want to create:</p> <pre><code>C = np.asarray([1,2,3, 4,5,6,7,8,9,10]) </code></pre> <p>Is there a better way to do than to run a for loop</p>
0
2016-10-06T16:27:46Z
39,901,293
<p>Try the following :</p> <pre><code>import numpy as np A = np.asarray([1,3,5,7,9]) B = np.asarray([2,4,6,8,10]) C = np.sort(np.hstack((A,B))) #array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) </code></pre>
0
2016-10-06T16:32:25Z
[ "python", "numpy" ]
pytest: xfail on given exception, pass otherwise
39,901,211
<p>I have a test that uses <code>requests</code> and needs an active connection.</p> <p>I would like it to <code>xfail</code> if the connection is down but pass normally otherwise.</p> <p>Here is what I tried:</p> <pre><code>from requests import ConnectionError @pytest.mark.xfail(raises=ConnectionError) class TestStuff(): def test_stuff(): do stuff </code></pre> <p>This will indeed <code>xfail</code> if connection is down but it <code>xpass</code>es in the general case.</p> <p>Is there any way to achieve what I want?</p> <p>I can use a try/except:</p> <pre><code>from requests import ConnectionError class TestStuff(): def test_stuff(): try: do stuff except ConnectionError: pass </code></pre> <p>but I get no xfail. The test always passes, but I'm not notified that it couldn't be performed properly.</p> <p>I guess xfail is meant for systematic errors that may be fixed someday (broken lib,...), not for transient errors like connection errors.</p>
1
2016-10-06T16:27:52Z
39,983,314
<p>pytest supports imperative xfail from within a test or setup function.</p> <p>Use the try/except code you have, and include <code>pytest.xfail('some message')</code> in the <code>except</code> body.</p> <p>See: <a href="http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-function" rel="nofollow">http://doc.pytest.org/en/latest/skipping.html#imperative-xfail-from-within-a-test-or-setup-function</a></p>
1
2016-10-11T17:39:13Z
[ "python", "py.test" ]
pytest: xfail on given exception, pass otherwise
39,901,211
<p>I have a test that uses <code>requests</code> and needs an active connection.</p> <p>I would like it to <code>xfail</code> if the connection is down but pass normally otherwise.</p> <p>Here is what I tried:</p> <pre><code>from requests import ConnectionError @pytest.mark.xfail(raises=ConnectionError) class TestStuff(): def test_stuff(): do stuff </code></pre> <p>This will indeed <code>xfail</code> if connection is down but it <code>xpass</code>es in the general case.</p> <p>Is there any way to achieve what I want?</p> <p>I can use a try/except:</p> <pre><code>from requests import ConnectionError class TestStuff(): def test_stuff(): try: do stuff except ConnectionError: pass </code></pre> <p>but I get no xfail. The test always passes, but I'm not notified that it couldn't be performed properly.</p> <p>I guess xfail is meant for systematic errors that may be fixed someday (broken lib,...), not for transient errors like connection errors.</p>
1
2016-10-06T16:27:52Z
39,992,948
<p>Calling <code>xfail</code> when <code>ConnectionError</code> was caught is a solution.</p> <p>It is even better to check connection in a fixture (the same way - try-except with <code>pytest.xfail</code>) and use that fixture in all tests that need a connection. </p> <p>That way such fixture will cause all dependent tests to xfail without even running them.</p>
1
2016-10-12T07:33:30Z
[ "python", "py.test" ]
How to implement quaternary search?
39,901,240
<p>I know this algorithm is no better than binary search, but it's an interesting thought experiment for understanding recursion. I haven't been able to get very far on this though(way too much recursion for my brain to handle.). Anyone know how to actually implement this?</p> <p>I have the following, which is nowhere close to correct. I really don't even know how to approach this, it's like the search version of inception.</p> <pre><code>def srb(list,key,q1,q2,q3,q4): mid1 = (q1+q2)//2 mid2 = (q3+q4)//2 if mid1 &lt; list[0] or mid1 &gt; list[-1] or key &lt; list[0] or key &gt; list[-1]: return False if mid2 &lt; list[0] or mid2 &gt; list[-1] or key &lt; list[0] or key &gt; list[-1]: return False elif key == mid1 or key == mid2: return True elif key &gt; mid1 and key &lt; q3: return srb(list,key,mid1+1,q2) elif key &lt; mid1: return srb(list,key,q1,mid1-1) elif key &gt; q3 and key &lt; mid2: return srb(list,key,q3+1,mid2) else: return srb(list,key,mid2+1,q4) </code></pre>
0
2016-10-06T16:29:32Z
39,901,503
<p>Start with a correct implementation of binary search. Then replace each recursive call with an inline version of the whole search (minus any initialization), i.e expand the binary search code in place as if it were a macro expansion [change variable names as necessary]. I believe if you do it right you will then have a quarternary search procedure.</p>
0
2016-10-06T16:45:06Z
[ "python", "algorithm", "search", "binary-search" ]
How to implement quaternary search?
39,901,240
<p>I know this algorithm is no better than binary search, but it's an interesting thought experiment for understanding recursion. I haven't been able to get very far on this though(way too much recursion for my brain to handle.). Anyone know how to actually implement this?</p> <p>I have the following, which is nowhere close to correct. I really don't even know how to approach this, it's like the search version of inception.</p> <pre><code>def srb(list,key,q1,q2,q3,q4): mid1 = (q1+q2)//2 mid2 = (q3+q4)//2 if mid1 &lt; list[0] or mid1 &gt; list[-1] or key &lt; list[0] or key &gt; list[-1]: return False if mid2 &lt; list[0] or mid2 &gt; list[-1] or key &lt; list[0] or key &gt; list[-1]: return False elif key == mid1 or key == mid2: return True elif key &gt; mid1 and key &lt; q3: return srb(list,key,mid1+1,q2) elif key &lt; mid1: return srb(list,key,q1,mid1-1) elif key &gt; q3 and key &lt; mid2: return srb(list,key,q3+1,mid2) else: return srb(list,key,mid2+1,q4) </code></pre>
0
2016-10-06T16:29:32Z
39,902,159
<p>How is this solution ? </p> <pre><code>#start = 0 #first_quarter = int(len(a_list)/4) - 1 #mid_point = int(len(a_list)/2) - 1 #third_quarter = int(len(a_list)*3/4) - 1 #end = len(a_list) - 1 def search(a_list, elem): return search_recur(a_list, elem, *generate_quartets(a_list, 0)) def generate_quartets(a_list, start): return [x + start for x in [0, int(len(a_list)/4) - 1 , int(len(a_list)/2) - 1, int(len(a_list)*3/4) - 1, len(a_list) - 1]] def search_recur(a_list, elem, start, first_quarter, mid_point, third_quarter, end): #print(a_list) if not a_list: return -1 list_of_quartets = [start, first_quarter, mid_point, third_quarter, end] try: ind = [a_list[x] for x in list_of_quartets].index(elem) return list_of_quartets[ind] except: pass if (a_list[start] &lt; elem &lt; a_list[first_quarter]): return search_recur(a_list, elem, *generate_quartets(a_list[start+1:first_quarter], start+1)) elif (a_list[first_quarter] &lt; elem &lt; a_list[mid_point]): return search_recur(a_list, elem, *generate_quartets(a_list[first_quarter+1:mid_point], first_quarter+1)) elif (a_list[mid_point] &lt; elem &lt; a_list[third_quarter]): return search_recur(a_list, elem, *generate_quartets(a_list[mid_point+1:third_quarter], mid_point+1)) elif (a_list[third_quarter] &lt; elem &lt; a_list[end]): return search_recur(a_list, elem, *generate_quartets(a_list[third_quarter+1:end], third_quarter+1)) else: return -1 print(search([1,2,3,4], 4)) print(search([10, 12, 14, 17, 19, 20], 4)) print(search([10, 12, 14, 17, 19, 20], 17)) print(search([9, 15, 22, 35, 102, 205, 315, 623], 22)) print(search([9, 15, 22, 35, 102, 205, 315, 623], 35)) print(search([9, 15, 22, 35, 102, 205, 315, 623], 102)) </code></pre> <p>Output - </p> <pre><code>3 -1 3 2 3 4 </code></pre>
1
2016-10-06T17:23:35Z
[ "python", "algorithm", "search", "binary-search" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.objects.filter(Q(title__contains=proTitle ) | Q(description__contains=ProDescription ) ) for res in result: list0.append(res.project_id) data ={'title result':list0} return HttpResponse(json.dumps(data)) return HttpResponse(json.dumps(data), content_type='application/json') </code></pre> <p>When pass all value that is <code>proTitle,ProDescription it working fine. If any value is going to none it encounter a error</code>Cannot use None as a query value` Why this error occured when i am using OR operator into my queryset</p> <p>I am also try this </p> <p><code>result = Project.objects.filter(title__contains=proTitle) | Project.objects.filter(description__contains=ProDescription )</code></p> <p>but same error occured I am unable to understand actually what is the problem</p>
1
2016-10-06T16:31:19Z
39,901,483
<p>You may set the defaults of the <code>get</code> method to something other than <code>None</code>, say empty string:</p> <pre><code>proTitle = request.GET.get('title', '') ProDescription = request.GET.get('description', '') funAria = request.GET.get('funAria', '') femaleReq = request.GET.get('femaleReq', '') </code></pre> <p>This is however likely to return all results in the DB when using <code>__contains</code>.</p> <p>Otherwise you may build the Q functions discarding all <code>None</code> values.</p> <p>Use this as a guideline: <a href="http://stackoverflow.com/questions/852414/how-to-dynamically-compose-an-or-query-filter-in-django">How to dynamically compose an OR query filter in Django?</a></p>
1
2016-10-06T16:43:44Z
[ "python", "django" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.objects.filter(Q(title__contains=proTitle ) | Q(description__contains=ProDescription ) ) for res in result: list0.append(res.project_id) data ={'title result':list0} return HttpResponse(json.dumps(data)) return HttpResponse(json.dumps(data), content_type='application/json') </code></pre> <p>When pass all value that is <code>proTitle,ProDescription it working fine. If any value is going to none it encounter a error</code>Cannot use None as a query value` Why this error occured when i am using OR operator into my queryset</p> <p>I am also try this </p> <p><code>result = Project.objects.filter(title__contains=proTitle) | Project.objects.filter(description__contains=ProDescription )</code></p> <p>but same error occured I am unable to understand actually what is the problem</p>
1
2016-10-06T16:31:19Z
39,901,487
<p>You can build the <code>Q</code> object in a loop, discarding all values that are none. Note that after consideration, it appears that your <code>except</code> will never be reached because <code>get</code> will simply return <code>None</code> if the Get parameter is not present. You can thus replace the <code>try</code> with an <code>if</code>. </p> <p>The following code assumes that you simply want the unset values to be ignored in the filter.</p> <p>(This is untested--let me know if you have any issues.)</p> <pre><code>attributes = (('title', 'title__contains'), ('description', 'description__contains'), ('funAria', 'functional_area__contains'), ('femaleReq', 'female_candidate')) query_filter = Q() # initialize for get_param, kw_arg in attributes: get_value = request.GET.get(get_param) if get_value: query_filter |= Q(**{ kw_arg: get_value }) result = Product.objects.filter(query_filter) </code></pre>
0
2016-10-06T16:44:10Z
[ "python", "django" ]
When using Q objects in django queryset for OR condition error occured
39,901,266
<p>I want to use filter with OR condition in django. For this i want to use Q objects. My code is this</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') except: pass list0 = [] result = Product.objects.filter(Q(title__contains=proTitle ) | Q(description__contains=ProDescription ) ) for res in result: list0.append(res.project_id) data ={'title result':list0} return HttpResponse(json.dumps(data)) return HttpResponse(json.dumps(data), content_type='application/json') </code></pre> <p>When pass all value that is <code>proTitle,ProDescription it working fine. If any value is going to none it encounter a error</code>Cannot use None as a query value` Why this error occured when i am using OR operator into my queryset</p> <p>I am also try this </p> <p><code>result = Project.objects.filter(title__contains=proTitle) | Project.objects.filter(description__contains=ProDescription )</code></p> <p>but same error occured I am unable to understand actually what is the problem</p>
1
2016-10-06T16:31:19Z
39,901,520
<p>Your error seems to mean that one of your values is <code>None</code>:</p> <pre><code>def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') funAria = request.GET.get('funAria') femaleReq = request.GET.get('femaleReq') someIntValue = request.GET.get('someIntValue') except: pass allQs = Q() if proTitle is not None: allQs |= Q(title__contains=proTitle ) if ProDescription is not None: allQs |= Q(description__contains=ProDescription ) if funAria is not None: allQs |= Q(functional_area__contains=funAria ) if someIntValue is not None: allQs |= Q(some_int_value__gte=someIntValue) # no need to convert someIntValue to an int here as long as you are guaranteed it is unique. allQs |= Q(female_candidate=femaleReq ) list0 = [] result = Product.objects.filter(allQs) for res in result: list0.append(res.project_id) data ={'title result':list0} return HttpResponse(json.dumps(data)) </code></pre>
0
2016-10-06T16:45:57Z
[ "python", "django" ]
Write a list into a file onto HDFS
39,901,442
<p>I am writing a python code to run on a Hadoop Cluster and need to store some intermediate data in a file. Since I want to run the code on the cluster, I want to write the intermediate data into the <code>/tmp</code> directory on HDFS. I will delete the file immediately after I use it for the next steps. How can I do that? </p> <p>I know I can use <code>subprocess.call()</code> but how do I write the data into the file? The data I want to write is inside a list.</p> <p>I tried the following syntax:</p> <pre><code>for item in mylist: subprocess.call(["echo '%s' | hadoop fs -put - /tmp/t"%item], shell=True) </code></pre> <p>It writes fine but there is a problem here: For the second record onwards, it throws an error <code>/tmp/t</code> already exists.</p> <p>Is there a way I can do this?</p>
0
2016-10-06T16:41:12Z
39,903,286
<p>You're facing that error because HDFS cannot append the files when written from shell. You need to create new files each time you want to dump files.</p> <p>A better way to do this would be to use a python HDFS client to do the dumping for you. I can recommend <a href="https://github.com/spotify/snakebite" rel="nofollow">snakebite</a>, <a href="http://crs4.github.io/pydoop/" rel="nofollow">pydoop</a> and <a href="https://pypi.python.org/pypi/hdfs/" rel="nofollow">hdfs</a> packages. I haven't tried the third one though so I cannot comment on them, but the other two work fine.</p>
0
2016-10-06T18:32:08Z
[ "python", "hadoop", "subprocess" ]
compare List of attributes against an object inside list
39,901,524
<p>This is how my Input looks like:</p> <pre><code>cust1Attributes = [{'Key': 'FirstName', 'Value': 'SomeFirstName'}, {'Key': 'LastName', 'Value': 'SomeLastName'}] </code></pre> <p>This is how my MandatoryData list looks like:</p> <pre><code>class MustHaveData(object): def __init__(self, name, defaultValue): self.name = name self.defaultValue = defaultValue customerMandatoryData=[] customerMandatoryData.append(MustHaveData(name="FirstName", defaultValue="Default First Name")) customerMandatoryData.append(MustHaveData(name="LastName", defaultValue="Default Last Name")) customerMandatoryData.append(MustHaveData(name="State", defaultValue="Default State")) </code></pre> <p>I need to compare <code>cust1Attributes's key</code> against <code>customerMandatoryData's name</code> and get the list of <code>customerMandatoryData</code> back which does not exist for <code>cust1Attributes</code></p> <p>How do i do this?</p>
0
2016-10-06T16:46:12Z
39,901,644
<p>Build a <em>set</em> from the dictionary containing the items at each <code>Key</code> and use a <em>list comprehension</em> to filter out objects with names in the set:</p> <pre><code>custset = {x['Key'] for x in cust1Attributes} result = [obj for obj in customerMandatoryData if obj.name not in custset] </code></pre>
2
2016-10-06T16:53:56Z
[ "python" ]
how to make if conditions work with specific string characters?
39,901,537
<p>I want to develop a program that takes input in the form of bits and outputs the decimal equivalent. </p> <p>I am restricted in the kind of functions I can use so this is what I came up with:</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) repeat=a c=0 total=0 while (c &lt; repeat): if digits[c]==1: total=total + (2**a) c=c+1 a=a-1 else: c=c+1 a=a-1 print total </code></pre> <p>The code returns <code>0</code> for all kinds of strings I enter. </p> <p>How can I fix my <code>if</code> statement to work correctly.</p>
0
2016-10-06T16:46:53Z
39,901,728
<p><code>if 1==1</code> means if number 1 is equal 1</p> <p><code>if "1"=="1"</code> means if string ("1") is equal "1"</p> <p>You need to learn difference between data types.</p> <pre><code>counter = 100 # An integer assignment miles = 1000.0 # A floating point name = "John" # A string </code></pre> <hr> <p>So, your code should look like this:</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) repeat=a c=0 total=0 while (c &lt; repeat): if digits[c]=="1": total=total + (2**a) c=c+1 a=a-1 else: c=c+1 a=a-1 print total </code></pre>
1
2016-10-06T16:58:25Z
[ "python" ]
how to make if conditions work with specific string characters?
39,901,537
<p>I want to develop a program that takes input in the form of bits and outputs the decimal equivalent. </p> <p>I am restricted in the kind of functions I can use so this is what I came up with:</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) repeat=a c=0 total=0 while (c &lt; repeat): if digits[c]==1: total=total + (2**a) c=c+1 a=a-1 else: c=c+1 a=a-1 print total </code></pre> <p>The code returns <code>0</code> for all kinds of strings I enter. </p> <p>How can I fix my <code>if</code> statement to work correctly.</p>
0
2016-10-06T16:46:53Z
39,901,770
<p>The reason its not working is that the variable digits is string and when you compare it with integer one it won't work you have to convert it to the below</p> <pre><code>if int(digits[c]) == 1: </code></pre> <p>or </p> <pre><code>if str(digits[c]) == "1": </code></pre> <p>Also your code has a lot of unwanted lines, so please find below the smaller and working code for the same</p> <pre><code>digits=raw_input("enter 1's and 0's") a=len(digits) c = 0 total = 0 while (c &lt; a): if int(digits[c])==1: total += pow(2,c) c += 1 print "converted value : ", total </code></pre> <p>There is better of way of writing it using for loop than while, please find below the code fior the saem using for loop </p> <pre><code>digits=raw_input("enter 1's and 0's") total = 0 for c in xrange(len(digits)): if int(digits[c])==1: total += pow(2,c) print total </code></pre> <p>Even better way of doing it in 2 lines below</p> <pre><code>binary_no = raw_input("Enter binary no : ") # It converts the string to base 2 decimal equivalent decimal_eqivalent = int(binary_no, 2) print "Decimal eq : ", decimal_eqivalent </code></pre>
0
2016-10-06T17:00:31Z
[ "python" ]
Python: UserWarning: This pattern has match groups. To actually get the groups, use str.extract
39,901,550
<p>I have a dataframe and I try to get string, where on of column contain some string Df looks like</p> <pre><code>member_id,event_path,event_time,event_duration 30595,"2016-03-30 12:27:33",yandex.ru/,1 30595,"2016-03-30 12:31:42",yandex.ru/,0 30595,"2016-03-30 12:31:43",yandex.ru/search/?lr=10738&amp;msid=22901.25826.1459330364.89548&amp;text=%D1%84%D0%B8%D0%BB%D1%8C%D0%BC%D1%8B+%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD&amp;suggest_reqid=168542624144922467267026838391360&amp;csg=3381%2C3938%2C2%2C3%2C1%2C0%2C0,0 30595,"2016-03-30 12:31:44",yandex.ru/search/?lr=10738&amp;msid=22901.25826.1459330364.89548&amp;text=%D1%84%D0%B8%D0%BB%D1%8C%D0%BC%D1%8B+%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD&amp;suggest_reqid=168542624144922467267026838391360&amp;csg=3381%2C3938%2C2%2C3%2C1%2C0%2C0,0 30595,"2016-03-30 12:31:45",yandex.ru/search/?lr=10738&amp;msid=22901.25826.1459330364.89548&amp;text=%D1%84%D0%B8%D0%BB%D1%8C%D0%BC%D1%8B+%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD&amp;suggest_reqid=168542624144922467267026838391360&amp;csg=3381%2C3938%2C2%2C3%2C1%2C0%2C0,0 30595,"2016-03-30 12:31:46",yandex.ru/search/?lr=10738&amp;msid=22901.25826.1459330364.89548&amp;text=%D1%84%D0%B8%D0%BB%D1%8C%D0%BC%D1%8B+%D0%BE%D0%BD%D0%BB%D0%B0%D0%B9%D0%BD&amp;suggest_reqid=168542624144922467267026838391360&amp;csg=3381%2C3938%2C2%2C3%2C1%2C0%2C0,0 30595,"2016-03-30 12:31:49",kinogo.co/,1 30595,"2016-03-30 12:32:11",kinogo.co/melodramy/,0 </code></pre> <p>And another df with urls</p> <pre><code>url 003\.ru\/[a-zA-Z0-9-_%$#?.:+=|()]+\/mobilnyj_telefon_bq_phoenix 003\.ru\/[a-zA-Z0-9-_%$#?.:+=|()]+\/mobilnyj_telefon_fly_ 003\.ru\/sonyxperia 003\.ru\/[a-zA-Z0-9-_%$#?.:+=|()]+\/mobilnye_telefony_smartfony 003\.ru\/[a-zA-Z0-9-_%$#?.:+=|()]+\/mobilnye_telefony_smartfony\/brands5D5Bbr_23 1click\.ru\/sonyxperia 1click\.ru\/[a-zA-Z0-9-_%$#?.:+=|()]+\/chasy-motorola </code></pre> <p>I use </p> <pre><code>urls = pd.read_csv('relevant_url1.csv', error_bad_lines=False) substr = urls.url.values.tolist() data = pd.read_csv('data_nts2.csv', error_bad_lines=False, chunksize=50000) result = pd.DataFrame() for i, df in enumerate(data): res = df[df['event_time'].str.contains('|'.join(substr), regex=True)] </code></pre> <p>but it return me</p> <pre><code>UserWarning: This pattern has match groups. To actually get the groups, use str.extract. </code></pre> <p>How can I fix that?</p>
2
2016-10-06T16:47:36Z
39,902,267
<p>At least one of the regex patterns in <code>urls</code> must use a capturing group. <code>str.contains</code> only returns True or False for each row in <code>df['event_time']</code> -- it does not make use of the capturing group. Thus, the <code>UserWarning</code> is alerting you that the regex uses a capturing group but the match is not used.</p> <p>If you wish to remove the <code>UserWarning</code> you could find and remove the capturing group from the regex pattern(s). They are not shown in the regex patterns you posted, but they must be there in your actual file. Look for parentheses outside of the character classes.</p> <p>Alternatively, you could suppress this particular UserWarning by putting </p> <pre><code>import warnings warnings.filterwarnings("ignore", 'This pattern has match groups') </code></pre> <p>before the call to <code>str.contains</code>.</p> <hr> <p>Here is a simple example which demonstrates the problem (and solution):</p> <pre><code># import warnings # warnings.filterwarnings("ignore", 'This pattern has match groups') # uncomment to suppress the UserWarning import pandas as pd df = pd.DataFrame({ 'event_time': ['gouda', 'stilton', 'gruyere']}) urls = pd.DataFrame({'url': ['g(.*)']}) # With a capturing group, there is a UserWarning # urls = pd.DataFrame({'url': ['g.*']}) # Without a capturing group, there is no UserWarning. Uncommenting this line avoids the UserWarning. substr = urls.url.values.tolist() df[df['event_time'].str.contains('|'.join(substr), regex=True)] </code></pre> <p>prints</p> <pre><code> script.py:10: UserWarning: This pattern has match groups. To actually get the groups, use str.extract. df[df['event_time'].str.contains('|'.join(substr), regex=True)] </code></pre> <p>Removing the capturing group from the regex pattern:</p> <pre><code>urls = pd.DataFrame({'url': ['g.*']}) </code></pre> <p>avoids the UserWarning.</p>
3
2016-10-06T17:30:23Z
[ "python", "regex", "pandas" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:SHIPNAME/direction:asc"&gt;Vessel Name&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:TIMESTAMP_UTC/direction:asc"&gt;Timestamp&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:PORT_NAME/direction:asc"&gt;Port&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:MOVE_TYPE_NAME/direction:asc"&gt;Port Call type&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:ELAPSED/direction:asc"&gt;Time Elapsed&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9" title="View details for: SIDER LUCK"&gt;SIDER LUCK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/163/port_name:MILAZZO/_:3525d580eade08cfdb72083b248185a9" title="View details for: MILAZZO"&gt;MILAZZO&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:288753/imo:9389693/mmsi:249474000/vessel:OOCL%20ISTANBUL/_:3525d580eade08cfdb72083b248185a9" title="View details for: OOCL ISTANBUL"&gt;OOCL ISTANBUL&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/17436/port_name:AMBARLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: AMBARLI"&gt;AMBARLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:754480/imo:9045613/mmsi:636014098/vessel:TK%20ROTTERDAM/_:3525d580eade08cfdb72083b248185a9" title="View details for: TK ROTTERDAM"&gt;TK ROTTERDAM&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/3504/port_name:DILISKELESI/_:3525d580eade08cfdb72083b248185a9" title="View details for: DILISKELESI"&gt;DILISKELESI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:412277/imo:9039585/mmsi:353430000/vessel:SEA%20AEOLIS/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEA AEOLIS"&gt;SEA AEOLIS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/1/port_name:PIRAEUS/_:3525d580eade08cfdb72083b248185a9" title="View details for: PIRAEUS"&gt;PIRAEUS&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:346713/imo:7614599/mmsi:273327300/vessel:SOLIDAT/_:3525d580eade08cfdb72083b248185a9" title="View details for: SOLIDAT"&gt;SOLIDAT&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/883/port_name:SEVASTOPOL/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEVASTOPOL"&gt;SEVASTOPOL&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:752974/imo:9195298/mmsi:636011072/vessel:OCEANPRINCESS/_:3525d580eade08cfdb72083b248185a9" title="View details for: OCEANPRINCESS"&gt;OCEANPRINCESS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/21780/port_name:EREGLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: EREGLI"&gt;EREGLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:201260/imo:9385075/mmsi:235102768/vessel:EMERALD%20BAY/_:3525d580eade08cfdb72083b248185a9" title="View details for: EMERALD BAY"&gt;EMERALD BAY&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:418956/imo:9102746/mmsi:356579000/vessel:MSC%20DON%20GIOVANNI/_:3525d580eade08cfdb72083b248185a9" title="View details for: MSC DON GIOVANNI"&gt;MSC DON GIOVANNI&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/67/port_name:CONSTANTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: CONSTANTA"&gt;CONSTANTA&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:748395/imo:9460734/mmsi:622121422/vessel:WADI%20SAFAGA/_:3525d580eade08cfdb72083b248185a9" title="View details for: WADI SAFAGA"&gt;WADI SAFAGA&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/997/port_name:DAMIETTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: DAMIETTA"&gt;DAMIETTA&lt;/a&gt; </code></pre> <p>I want to pull out the strings that start with <code>/en/ais/details/ships/shipid:</code> such as:</p> <pre><code>`&lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9"` </code></pre> <p>I was able to copy these examples (<a href="http://stackoverflow.com/questions/7732694/find-specific-link-w-beautifulsoup">Find specific link w/ beautifulsoup</a> or <a href="http://stackoverflow.com/questions/12611592/how-to-get-beautiful-soup-to-get-link-from-href-and-class">How to get Beautiful Soup to get link from href and class?</a>) but I would rather not use regex. </p> <p>So far I have: </p> <pre><code>for i in ase: #ase is where the html is sotred print(i.get('href')) #prints everysingle href. </code></pre> <p>In short, my question is how do I only keep the <code>href</code>'s that have the string I'm interested in without using regex?</p>
2
2016-10-06T16:47:52Z
39,901,685
<p>Try the following list comprehension:</p> <pre><code>[h.get('href') for h in ase if 'string' in h.get('href', '')] </code></pre> <p>This will give you a list containing only the links that contain the substring <code>'string'</code>.</p> <h1>Update:</h1> <p>As <strong>@PadraicCunningham</strong> pointed out in the comments, <code>'string' in h.get('href')</code> (which was part of my original answer) will raise a <code>TypeError</code> if <code>h</code> does not have a key <code>'href'</code> - not likely since <code>h</code> will be a representation of an <code>&lt;a&gt;</code> tag, but also certainly a non-trivial possibility. To allow for this possibility, you can simply pass to <code>.get()</code> a default argument of <code>''</code> to be returned instead of <code>None</code> when a key does not exist.</p> <p>Also, I have made no claims that my solution is the best; it is likely not particularly efficient or elegant. However, from my understanding of the OPs question, this solution will work, is minimal, and is easy to understand. </p>
2
2016-10-06T16:56:11Z
[ "python", "html", "beautifulsoup" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:SHIPNAME/direction:asc"&gt;Vessel Name&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:TIMESTAMP_UTC/direction:asc"&gt;Timestamp&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:PORT_NAME/direction:asc"&gt;Port&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:MOVE_TYPE_NAME/direction:asc"&gt;Port Call type&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:ELAPSED/direction:asc"&gt;Time Elapsed&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9" title="View details for: SIDER LUCK"&gt;SIDER LUCK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/163/port_name:MILAZZO/_:3525d580eade08cfdb72083b248185a9" title="View details for: MILAZZO"&gt;MILAZZO&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:288753/imo:9389693/mmsi:249474000/vessel:OOCL%20ISTANBUL/_:3525d580eade08cfdb72083b248185a9" title="View details for: OOCL ISTANBUL"&gt;OOCL ISTANBUL&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/17436/port_name:AMBARLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: AMBARLI"&gt;AMBARLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:754480/imo:9045613/mmsi:636014098/vessel:TK%20ROTTERDAM/_:3525d580eade08cfdb72083b248185a9" title="View details for: TK ROTTERDAM"&gt;TK ROTTERDAM&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/3504/port_name:DILISKELESI/_:3525d580eade08cfdb72083b248185a9" title="View details for: DILISKELESI"&gt;DILISKELESI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:412277/imo:9039585/mmsi:353430000/vessel:SEA%20AEOLIS/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEA AEOLIS"&gt;SEA AEOLIS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/1/port_name:PIRAEUS/_:3525d580eade08cfdb72083b248185a9" title="View details for: PIRAEUS"&gt;PIRAEUS&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:346713/imo:7614599/mmsi:273327300/vessel:SOLIDAT/_:3525d580eade08cfdb72083b248185a9" title="View details for: SOLIDAT"&gt;SOLIDAT&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/883/port_name:SEVASTOPOL/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEVASTOPOL"&gt;SEVASTOPOL&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:752974/imo:9195298/mmsi:636011072/vessel:OCEANPRINCESS/_:3525d580eade08cfdb72083b248185a9" title="View details for: OCEANPRINCESS"&gt;OCEANPRINCESS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/21780/port_name:EREGLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: EREGLI"&gt;EREGLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:201260/imo:9385075/mmsi:235102768/vessel:EMERALD%20BAY/_:3525d580eade08cfdb72083b248185a9" title="View details for: EMERALD BAY"&gt;EMERALD BAY&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:418956/imo:9102746/mmsi:356579000/vessel:MSC%20DON%20GIOVANNI/_:3525d580eade08cfdb72083b248185a9" title="View details for: MSC DON GIOVANNI"&gt;MSC DON GIOVANNI&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/67/port_name:CONSTANTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: CONSTANTA"&gt;CONSTANTA&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:748395/imo:9460734/mmsi:622121422/vessel:WADI%20SAFAGA/_:3525d580eade08cfdb72083b248185a9" title="View details for: WADI SAFAGA"&gt;WADI SAFAGA&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/997/port_name:DAMIETTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: DAMIETTA"&gt;DAMIETTA&lt;/a&gt; </code></pre> <p>I want to pull out the strings that start with <code>/en/ais/details/ships/shipid:</code> such as:</p> <pre><code>`&lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9"` </code></pre> <p>I was able to copy these examples (<a href="http://stackoverflow.com/questions/7732694/find-specific-link-w-beautifulsoup">Find specific link w/ beautifulsoup</a> or <a href="http://stackoverflow.com/questions/12611592/how-to-get-beautiful-soup-to-get-link-from-href-and-class">How to get Beautiful Soup to get link from href and class?</a>) but I would rather not use regex. </p> <p>So far I have: </p> <pre><code>for i in ase: #ase is where the html is sotred print(i.get('href')) #prints everysingle href. </code></pre> <p>In short, my question is how do I only keep the <code>href</code>'s that have the string I'm interested in without using regex?</p>
2
2016-10-06T16:47:52Z
39,901,769
<p>I would still advice you to use regex, as it is more concise and saves you another loop over the list. </p> <pre><code>import re find_all('a', href=re.compile("/en/ais/details/ships/shipid:")) </code></pre> <p>In the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow">documentation</a> you find a similar solution to this.</p>
0
2016-10-06T17:00:30Z
[ "python", "html", "beautifulsoup" ]
Parsing HTML with Beautiful Soup to get link after href
39,901,554
<p>This is a result of a <code>find_all('a')</code> (it's very long):</p> <pre><code>&lt;/a&gt;, &lt;a class="btn text-default text-dark clear_filters pull-right group-ib" href="#" id="export_dialog_close" title="Cancel"&gt;&lt;span class="glyphicon glyphicon-remove"&gt;&lt;/span&gt;&lt;span&gt;Cancel&lt;/span&gt;&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:SHIPNAME/direction:asc"&gt;Vessel Name&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:TIMESTAMP_UTC/direction:asc"&gt;Timestamp&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:PORT_NAME/direction:asc"&gt;Port&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:MOVE_TYPE_NAME/direction:asc"&gt;Port Call type&lt;/a&gt;, &lt;a href="/ais/index/port_moves/all/include_anchs:no/ship_type:7/_:3525d580eade08cfdb72083b248185a9/in_transit:no/time_interval:1474948800.0_1475035200.00/per_page:50/portname:NOVOROSSIYSK/cb:6651/move_type:1/sort:ELAPSED/direction:asc"&gt;Time Elapsed&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9" title="View details for: SIDER LUCK"&gt;SIDER LUCK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/163/port_name:MILAZZO/_:3525d580eade08cfdb72083b248185a9" title="View details for: MILAZZO"&gt;MILAZZO&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:288753/imo:9389693/mmsi:249474000/vessel:OOCL%20ISTANBUL/_:3525d580eade08cfdb72083b248185a9" title="View details for: OOCL ISTANBUL"&gt;OOCL ISTANBUL&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/17436/port_name:AMBARLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: AMBARLI"&gt;AMBARLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:754480/imo:9045613/mmsi:636014098/vessel:TK%20ROTTERDAM/_:3525d580eade08cfdb72083b248185a9" title="View details for: TK ROTTERDAM"&gt;TK ROTTERDAM&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/3504/port_name:DILISKELESI/_:3525d580eade08cfdb72083b248185a9" title="View details for: DILISKELESI"&gt;DILISKELESI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:412277/imo:9039585/mmsi:353430000/vessel:SEA%20AEOLIS/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEA AEOLIS"&gt;SEA AEOLIS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/1/port_name:PIRAEUS/_:3525d580eade08cfdb72083b248185a9" title="View details for: PIRAEUS"&gt;PIRAEUS&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:346713/imo:7614599/mmsi:273327300/vessel:SOLIDAT/_:3525d580eade08cfdb72083b248185a9" title="View details for: SOLIDAT"&gt;SOLIDAT&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/883/port_name:SEVASTOPOL/_:3525d580eade08cfdb72083b248185a9" title="View details for: SEVASTOPOL"&gt;SEVASTOPOL&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:752974/imo:9195298/mmsi:636011072/vessel:OCEANPRINCESS/_:3525d580eade08cfdb72083b248185a9" title="View details for: OCEANPRINCESS"&gt;OCEANPRINCESS&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/21780/port_name:EREGLI/_:3525d580eade08cfdb72083b248185a9" title="View details for: EREGLI"&gt;EREGLI&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:201260/imo:9385075/mmsi:235102768/vessel:EMERALD%20BAY/_:3525d580eade08cfdb72083b248185a9" title="View details for: EMERALD BAY"&gt;EMERALD BAY&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:418956/imo:9102746/mmsi:356579000/vessel:MSC%20DON%20GIOVANNI/_:3525d580eade08cfdb72083b248185a9" title="View details for: MSC DON GIOVANNI"&gt;MSC DON GIOVANNI&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/67/port_name:CONSTANTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: CONSTANTA"&gt;CONSTANTA&lt;/a&gt;, &lt;a href="/en/ais/details/ships/shipid:748395/imo:9460734/mmsi:622121422/vessel:WADI%20SAFAGA/_:3525d580eade08cfdb72083b248185a9" title="View details for: WADI SAFAGA"&gt;WADI SAFAGA&lt;/a&gt;, &lt;a href="/en/ais/details/ports/767/port_name:NOVOROSSIYSK/_:3525d580eade08cfdb72083b248185a9" title="View details for: NOVOROSSIYSK"&gt;NOVOROSSIYSK&lt;/a&gt;, &lt;a href="/en/ais/details/ports/997/port_name:DAMIETTA/_:3525d580eade08cfdb72083b248185a9" title="View details for: DAMIETTA"&gt;DAMIETTA&lt;/a&gt; </code></pre> <p>I want to pull out the strings that start with <code>/en/ais/details/ships/shipid:</code> such as:</p> <pre><code>`&lt;a href="/en/ais/details/ships/shipid:465271/imo:9495595/mmsi:373571000/vessel:SIDER%20LUCK/_:3525d580eade08cfdb72083b248185a9"` </code></pre> <p>I was able to copy these examples (<a href="http://stackoverflow.com/questions/7732694/find-specific-link-w-beautifulsoup">Find specific link w/ beautifulsoup</a> or <a href="http://stackoverflow.com/questions/12611592/how-to-get-beautiful-soup-to-get-link-from-href-and-class">How to get Beautiful Soup to get link from href and class?</a>) but I would rather not use regex. </p> <p>So far I have: </p> <pre><code>for i in ase: #ase is where the html is sotred print(i.get('href')) #prints everysingle href. </code></pre> <p>In short, my question is how do I only keep the <code>href</code>'s that have the string I'm interested in without using regex?</p>
2
2016-10-06T16:47:52Z
39,903,911
<p><a href="http://stackoverflow.com/a/39901685/771848">@elethan's answer</a> is not the best one. It would <strong>find you all the links and only then filter them out</strong>. Why don't we just <em>get the links we needed straight with no extra filtering</em> - <code>BeautifulSoup</code> is very capable of that:</p> <pre><code>prefix = "/en/ais/details/ships/shipid" [a["href"] for a in soup("a", href=lambda x: x and x.startswith(prefix))] </code></pre> <p>Or, instead of a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow">function</a>, you can pass a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">regular expression pattern</a> to check if a string "starts with" a desired sub-string:</p> <pre><code>pattern = re.compile(r"^/en/ais/details/ships/shipid") [a["href"] for a in soup("a", href=pattern)] </code></pre> <p><code>^</code> here denotes the beginning of a string.</p> <p>Or, we can even use a <a class='doc-link' href="http://stackoverflow.com/documentation/beautifulsoup/1940/locating-elements/6340/using-css-selectors-to-locate-elements-in-beautifulsoup#t=201610061913079501684">CSS selector</a>:</p> <pre><code>[a["href"] for a in soup.select('a[href^="/en/ais/details/ships/shipid"]')] </code></pre> <p><code>^=</code> is a "starts-with" selector.</p>
3
2016-10-06T19:09:48Z
[ "python", "html", "beautifulsoup" ]
Creating a dictionary in python by combining two .csv files
39,901,640
<p>I am trying to create a dictionary in python by combining data from two .csv files, by matching the first column of the two files. This is what I have so far </p> <pre><code>import csv with open('a.csv', 'r') as my_file1 : rows1 = list(csv.reader(my_file1)) with open('aa.csv', 'r') as my_file2 : rows2 = list(csv.reader(my_file2)) max_length = min(len(rows1), len(rows2)) for i in range(10): new_dict = {} if (rows1[i][0]== rows2[i][0]): temp = {(rows1[i][0], (rows1[i][5], rows1[i][6], rows2[i][5], rows2[i][6] )) } new_dict.update(temp) print(new_dict) </code></pre> <p>The output that I get is the last data entry in arrays. It does not seem to append all the values. This is what the output looks like </p> <pre><code>{'2016-09-12': ('1835400', '45.75', '21681500', '9.78')} </code></pre> <p>instead of the complete list with keys and values. How do I go about correcting this? Thanks! </p>
1
2016-10-06T16:53:46Z
39,901,719
<p>You're creating a new dictionary on every iteration of your <code>for</code>, so only the update from the last iteration is kept, others have been thrown away.</p> <p>You can solve this by moving the dictionary setup outside the <code>for</code>:</p> <pre><code>new_dict = {} for i in range(10): ... </code></pre>
1
2016-10-06T16:58:00Z
[ "python", "dictionary" ]
Python: printing result of multiple inputs
39,901,750
<p>I'm pretty new to python programming, but i'm trying to write a program that goes as follows:</p> <p>First: the program asks the user for a fixed number. Then: the user can input as many numbers as he wants, until he writes "stop". (this is not really where i'm having trouble)</p> <p>the output needs to be something like this: 'fixed number' 'input #1 = fixed number + first inputted number' 'input #2 = fixed number + first inputted number + second inputted number' 'an so on until all inputted numbers have been added'</p> <p>my code doesn't print this out correctly, it prints the correct #1, #2, #n but not the summation i listed above.</p> <p>Any help is appreciated</p> <p>Here is my code at this moment:</p> <pre><code>random_number = int(input("Enter random number:")) count_added = 0 while number != "stop": number = input("Enter number: ") if number == "stop": break else: number_int = int(number) count_added += 1 sum = number_int + random_number print(random_number) for x in range(1, count_added + 1): print("input #{} is sum {} ".format(x, sum)) </code></pre>
-3
2016-10-06T16:59:16Z
39,901,862
<pre><code>input_list = [] sum = 0 while True: user_input = int(input('Enter the number')) if user_input != 'stop' input_list.append(user_input) elif user_input == 'stop': break; for i in input_list: sum += i print(sum) </code></pre>
0
2016-10-06T17:05:26Z
[ "python", "loops", "sum" ]
Python: printing result of multiple inputs
39,901,750
<p>I'm pretty new to python programming, but i'm trying to write a program that goes as follows:</p> <p>First: the program asks the user for a fixed number. Then: the user can input as many numbers as he wants, until he writes "stop". (this is not really where i'm having trouble)</p> <p>the output needs to be something like this: 'fixed number' 'input #1 = fixed number + first inputted number' 'input #2 = fixed number + first inputted number + second inputted number' 'an so on until all inputted numbers have been added'</p> <p>my code doesn't print this out correctly, it prints the correct #1, #2, #n but not the summation i listed above.</p> <p>Any help is appreciated</p> <p>Here is my code at this moment:</p> <pre><code>random_number = int(input("Enter random number:")) count_added = 0 while number != "stop": number = input("Enter number: ") if number == "stop": break else: number_int = int(number) count_added += 1 sum = number_int + random_number print(random_number) for x in range(1, count_added + 1): print("input #{} is sum {} ".format(x, sum)) </code></pre>
-3
2016-10-06T16:59:16Z
39,902,077
<pre><code>random_number = int(input("Enter random number:")) number_list = [random_number] flag = True while flag: try: number = int(input("Enter number: ")) number_list.append(number) except: # if not a number, break the loop flag = False print random_number for i in range(1, len(number_list)): print "Input #%d is sum %d" \ %(number_list[i], sum(number_list[:i+1])) </code></pre>
0
2016-10-06T17:18:28Z
[ "python", "loops", "sum" ]
asyncio server and client to handle input from console
39,901,813
<p>I have an asyncio TCP server that take messages from client, do stuff() on server and sends texts back. Server works well in the sense that receives and sends data correctly. Problem is that I can't takes messages back from server in the client because I have the blocking routine on input from console (basically the data_received method is never executed). Only the exit command works fine (it closes the loop). How to solve this? This is the server and client code. It's basically the EchoClient asyncio version with some more plumbing code for an exercise.</p> <pre><code># client.py import abc import asyncio import sys MENU = ''' a) do x b) do y c) exit ''' loop_ = asyncio.get_event_loop() class XCommand: def run(self): self.client.send_data_to_tcp('X:') # to bytes class YCommand(Command): def run(self): s = input('Input for Y ### ') self.client.send_data_to_tcp('Y:' + s) class ExitCommand(Command): def run(self): self.client.send_data_to_tcp('EXIT:') print('Goodbye!') loop_.close() exit() class CommandFactory: _cmds = {'a': ACommand, 'b': BCommand, 'c': ExitCommand, } @classmethod def get_cmd(cls, cmd): cmd_cls = cls._cmds.get(cmd) return cmd_cls def show_menu(client): print(MENU) while True: command = input('Insert Command$: ') cmd_cls = CommandFactory.get_cmd(command) if not cmd_cls: print('Unknown: {}'.format(command)) continue cmd_cls(client).run() class Client(asyncio.Protocol): def __init__(self, loop): self.loop = loop self.transport = None def connection_made(self, transport): self.transport = transport def data_received(self, data): print('Data received from server: \n{!r}'.format(data.decode()), flush=True) def send_data_to_tcp(self, data): self.transport.write(data.encode()) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') self.loop.stop() def main(): client = Client(loop_) coro = loop_.create_connection(lambda: client, '127.0.0.1', 10888) loop_.run_until_complete(coro) loop_.run_in_executor(None, show_menu(client)) # I've tried this...not working loop_.run_forever() loop_.close() if __name__ == '__main__': main() # server.py import abc import asyncio import sys from asyncio_exercise.db import DB class ACommand: @classmethod def run(cls, db, param1=None, param2=None): res = db.a() if not res: return '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Empty &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' return '\n'.join('{}: {}'.format(col, val) for col, val in res.items()) class BCommand: @classmethod def run(cls, db, param1=None, param2=None): db.b(param1, param2) return 'B Ok!' class ExitCommand: @classmethod def run(cls, db, param1=None, param2=None): loop.close() server.close() loop.run_until_complete(server.wait_closed()) print('Buona giornata!!!') sys.exit(0) class CommandFactory: _cmds = {'X': ACommand, 'Y': BCommand, 'EXIT': ExitCommand} @classmethod def get_cmd(cls, cmd): tokens = cmd.split(':') cmd = tokens[0] if len(tokens) == 1: param1, param2 = None, None else: param1, param2 = (tokens[1], tokens[2]) if len(tokens) == 3 else (tokens[1], None) cmd_cls = cls._cmds.get(cmd) return cmd_cls, param1, param2 class Server(asyncio.Protocol): db_filename = '../data/db' db = DB(db_filename) def connection_made(self, transport): peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.transport = transport def data_received(self, data): message = data.decode() print('Data received: {!r}'.format(message)) cmd_cls, param1, param2 = CommandFactory.get_cmd(message) res = cmd_cls.run(self.db, param1, param2) print('Sending response: {!r}'.format(res)) self.transport.write(bytes(res, encoding='UTF-8')) if __name__ == '__main__': loop = asyncio.get_event_loop() # Each client connection will create a new protocol instance coro = loop.create_server(Server, '127.0.0.1', 10888) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass finally: # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close() </code></pre> <p><strong>UPDATE</strong>: The solution was to use aioconsole package and ainput function.Below code using aioconsole (working very good).</p> <pre><code># server.py import abc import asyncio from d_1_networking.esercizio_soluzione.SOversion.dummydb import DummyDB as DB class Command(metaclass=abc.ABCMeta): @abc.abstractclassmethod def run(self, a, b, c): raise NotImplementedError() class XCommand(Command): @classmethod def run(cls, db, param1=None, param2=None): res = db.x() if not res: return '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Empty response! &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' return '\n'.join('{}: {}'.format(col, val) for col, val in res.items()) class YCommand(Command): @classmethod def run(cls, db, param1=None, param2=None): db.y(param1) return 'Operation Y OK: {}'.format(param1) class QuitCommand(Command): @classmethod def run(cls, rubrica_db, param1=None, param2=None): return 'Disconnected...' class CommandFactory: _cmds = {'X': XCommand, 'Y': YCommand, 'DISCONNECT': QuitCommand} @classmethod def get_cmd(cls, cmd): tokens = cmd.split(':') cmd = tokens[0] if len(tokens) == 1: nome, numero = None, None else: nome, numero = (tokens[1], tokens[2]) if len(tokens) == 3 else (tokens[1], None) cmd_cls = cls._cmds.get(cmd) return cmd_cls, nome, numero class Server(asyncio.Protocol): db_filename = '../data/exercise.db' db = DB(db_filename) def connection_made(self, transport): peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.transport = transport def data_received(self, data): message = data.decode() print('Data received: {!r}'.format(message)) cmd_cls, param1, param2 = CommandFactory.get_cmd(message) res = cmd_cls.run(self.db, param1, param2) print('Sending response: {!r}'.format(res)) self.transport.write(bytes(res, encoding='UTF-8')) if __name__ == '__main__': loop = asyncio.get_event_loop() # Each client connection will create a new protocol instance coro = loop.create_server(RubricaServer, '127.0.0.1', 10888) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close() </code></pre> <hr> <pre><code>#dummydb.py class DummyDB: def __init__(self, fn): self.fn = fn def x(self): return {'field_a': '55 tt TTYY 3334 gghyyujh', 'field_b': 'FF hhhnneeekk', 'field_c': '00993342489048222 news'} def y(self, param): return param </code></pre> <hr> <pre><code># client.py import abc from asyncio import * from aioconsole import ainput MENU = ''' --------------------------- A) Command X B) Command Y (require additional input) C) Quit program --------------------------- ''' loop_ = get_event_loop() class Command(metaclass=abc.ABCMeta): asyn = False def __init__(self, tcp_client): self.client = tcp_client @abc.abstractmethod def run(self): raise NotImplementedError() class ACommand(Command): def run(self): # send X command to server self.client.send_data_to_tcp('X:') class BCommand(Command): asyn = True async def run(self): s = await ainput('Insert data for B operation (es. name:43d3HHte3) &gt; ') # send Y command to server self.client.send_data_to_tcp('Y:' + s) class QuitCommand(Command): def run(self): self.client.send_data_to_tcp('DISCONNECT:') print('Goodbye!!!') self.client.disconnect() exit() class CommandFactory: _cmds = {'A': ACommand, 'B': BCommand, 'C': QuitCommand} @classmethod def get_cmd(cls, cmd): cmd = cmd.strip() cmd_cls = cls._cmds.get(cmd) return cmd_cls class Client(Protocol): def __init__(self, loop): self.loop = loop self.transport = None def disconnect(self): self.loop.stop() def connection_made(self, transport): self.transport = transport def data_received(self, data): print('Data received from server: \n===========\n{}\n===========\n'.format(data.decode()), flush=True) def send_data_to_tcp(self, data): self.transport.write(data.encode()) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') self.loop.stop() def menu(): print(MENU) async def main(): menu() while True: cmd = await ainput('Insert Command &gt;') cmd_cls = CommandFactory.get_cmd(cmd) if not cmd_cls: print('Unknown: {}'.format(cmd)) elif cmd_cls.asyn: await cmd_cls(client).run() else: cmd_cls(client).run() if __name__ == '__main__': client = Client(loop_) coro = loop_.create_connection(lambda: client, '127.0.0.1', 10888) loop_.run_until_complete(coro) loop_.run_until_complete(main()) </code></pre>
0
2016-10-06T17:02:51Z
39,903,445
<p>I've found solution to implement an async_input for asyncio here: <a href="https://gist.github.com/nathan-hoad/8966377" rel="nofollow">https://gist.github.com/nathan-hoad/8966377</a></p> <p>Just need to fix imports for Stream classes for python 3.5</p>
0
2016-10-06T18:40:50Z
[ "python", "tcpclient", "python-asyncio" ]
asyncio server and client to handle input from console
39,901,813
<p>I have an asyncio TCP server that take messages from client, do stuff() on server and sends texts back. Server works well in the sense that receives and sends data correctly. Problem is that I can't takes messages back from server in the client because I have the blocking routine on input from console (basically the data_received method is never executed). Only the exit command works fine (it closes the loop). How to solve this? This is the server and client code. It's basically the EchoClient asyncio version with some more plumbing code for an exercise.</p> <pre><code># client.py import abc import asyncio import sys MENU = ''' a) do x b) do y c) exit ''' loop_ = asyncio.get_event_loop() class XCommand: def run(self): self.client.send_data_to_tcp('X:') # to bytes class YCommand(Command): def run(self): s = input('Input for Y ### ') self.client.send_data_to_tcp('Y:' + s) class ExitCommand(Command): def run(self): self.client.send_data_to_tcp('EXIT:') print('Goodbye!') loop_.close() exit() class CommandFactory: _cmds = {'a': ACommand, 'b': BCommand, 'c': ExitCommand, } @classmethod def get_cmd(cls, cmd): cmd_cls = cls._cmds.get(cmd) return cmd_cls def show_menu(client): print(MENU) while True: command = input('Insert Command$: ') cmd_cls = CommandFactory.get_cmd(command) if not cmd_cls: print('Unknown: {}'.format(command)) continue cmd_cls(client).run() class Client(asyncio.Protocol): def __init__(self, loop): self.loop = loop self.transport = None def connection_made(self, transport): self.transport = transport def data_received(self, data): print('Data received from server: \n{!r}'.format(data.decode()), flush=True) def send_data_to_tcp(self, data): self.transport.write(data.encode()) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') self.loop.stop() def main(): client = Client(loop_) coro = loop_.create_connection(lambda: client, '127.0.0.1', 10888) loop_.run_until_complete(coro) loop_.run_in_executor(None, show_menu(client)) # I've tried this...not working loop_.run_forever() loop_.close() if __name__ == '__main__': main() # server.py import abc import asyncio import sys from asyncio_exercise.db import DB class ACommand: @classmethod def run(cls, db, param1=None, param2=None): res = db.a() if not res: return '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Empty &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' return '\n'.join('{}: {}'.format(col, val) for col, val in res.items()) class BCommand: @classmethod def run(cls, db, param1=None, param2=None): db.b(param1, param2) return 'B Ok!' class ExitCommand: @classmethod def run(cls, db, param1=None, param2=None): loop.close() server.close() loop.run_until_complete(server.wait_closed()) print('Buona giornata!!!') sys.exit(0) class CommandFactory: _cmds = {'X': ACommand, 'Y': BCommand, 'EXIT': ExitCommand} @classmethod def get_cmd(cls, cmd): tokens = cmd.split(':') cmd = tokens[0] if len(tokens) == 1: param1, param2 = None, None else: param1, param2 = (tokens[1], tokens[2]) if len(tokens) == 3 else (tokens[1], None) cmd_cls = cls._cmds.get(cmd) return cmd_cls, param1, param2 class Server(asyncio.Protocol): db_filename = '../data/db' db = DB(db_filename) def connection_made(self, transport): peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.transport = transport def data_received(self, data): message = data.decode() print('Data received: {!r}'.format(message)) cmd_cls, param1, param2 = CommandFactory.get_cmd(message) res = cmd_cls.run(self.db, param1, param2) print('Sending response: {!r}'.format(res)) self.transport.write(bytes(res, encoding='UTF-8')) if __name__ == '__main__': loop = asyncio.get_event_loop() # Each client connection will create a new protocol instance coro = loop.create_server(Server, '127.0.0.1', 10888) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass finally: # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close() </code></pre> <p><strong>UPDATE</strong>: The solution was to use aioconsole package and ainput function.Below code using aioconsole (working very good).</p> <pre><code># server.py import abc import asyncio from d_1_networking.esercizio_soluzione.SOversion.dummydb import DummyDB as DB class Command(metaclass=abc.ABCMeta): @abc.abstractclassmethod def run(self, a, b, c): raise NotImplementedError() class XCommand(Command): @classmethod def run(cls, db, param1=None, param2=None): res = db.x() if not res: return '&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Empty response! &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;' return '\n'.join('{}: {}'.format(col, val) for col, val in res.items()) class YCommand(Command): @classmethod def run(cls, db, param1=None, param2=None): db.y(param1) return 'Operation Y OK: {}'.format(param1) class QuitCommand(Command): @classmethod def run(cls, rubrica_db, param1=None, param2=None): return 'Disconnected...' class CommandFactory: _cmds = {'X': XCommand, 'Y': YCommand, 'DISCONNECT': QuitCommand} @classmethod def get_cmd(cls, cmd): tokens = cmd.split(':') cmd = tokens[0] if len(tokens) == 1: nome, numero = None, None else: nome, numero = (tokens[1], tokens[2]) if len(tokens) == 3 else (tokens[1], None) cmd_cls = cls._cmds.get(cmd) return cmd_cls, nome, numero class Server(asyncio.Protocol): db_filename = '../data/exercise.db' db = DB(db_filename) def connection_made(self, transport): peername = transport.get_extra_info('peername') print('Connection from {}'.format(peername)) self.transport = transport def data_received(self, data): message = data.decode() print('Data received: {!r}'.format(message)) cmd_cls, param1, param2 = CommandFactory.get_cmd(message) res = cmd_cls.run(self.db, param1, param2) print('Sending response: {!r}'.format(res)) self.transport.write(bytes(res, encoding='UTF-8')) if __name__ == '__main__': loop = asyncio.get_event_loop() # Each client connection will create a new protocol instance coro = loop.create_server(RubricaServer, '127.0.0.1', 10888) server = loop.run_until_complete(coro) # Serve requests until Ctrl+C is pressed print('Serving on {}'.format(server.sockets[0].getsockname())) try: loop.run_forever() except KeyboardInterrupt: pass # Close the server server.close() loop.run_until_complete(server.wait_closed()) loop.close() </code></pre> <hr> <pre><code>#dummydb.py class DummyDB: def __init__(self, fn): self.fn = fn def x(self): return {'field_a': '55 tt TTYY 3334 gghyyujh', 'field_b': 'FF hhhnneeekk', 'field_c': '00993342489048222 news'} def y(self, param): return param </code></pre> <hr> <pre><code># client.py import abc from asyncio import * from aioconsole import ainput MENU = ''' --------------------------- A) Command X B) Command Y (require additional input) C) Quit program --------------------------- ''' loop_ = get_event_loop() class Command(metaclass=abc.ABCMeta): asyn = False def __init__(self, tcp_client): self.client = tcp_client @abc.abstractmethod def run(self): raise NotImplementedError() class ACommand(Command): def run(self): # send X command to server self.client.send_data_to_tcp('X:') class BCommand(Command): asyn = True async def run(self): s = await ainput('Insert data for B operation (es. name:43d3HHte3) &gt; ') # send Y command to server self.client.send_data_to_tcp('Y:' + s) class QuitCommand(Command): def run(self): self.client.send_data_to_tcp('DISCONNECT:') print('Goodbye!!!') self.client.disconnect() exit() class CommandFactory: _cmds = {'A': ACommand, 'B': BCommand, 'C': QuitCommand} @classmethod def get_cmd(cls, cmd): cmd = cmd.strip() cmd_cls = cls._cmds.get(cmd) return cmd_cls class Client(Protocol): def __init__(self, loop): self.loop = loop self.transport = None def disconnect(self): self.loop.stop() def connection_made(self, transport): self.transport = transport def data_received(self, data): print('Data received from server: \n===========\n{}\n===========\n'.format(data.decode()), flush=True) def send_data_to_tcp(self, data): self.transport.write(data.encode()) def connection_lost(self, exc): print('The server closed the connection') print('Stop the event loop') self.loop.stop() def menu(): print(MENU) async def main(): menu() while True: cmd = await ainput('Insert Command &gt;') cmd_cls = CommandFactory.get_cmd(cmd) if not cmd_cls: print('Unknown: {}'.format(cmd)) elif cmd_cls.asyn: await cmd_cls(client).run() else: cmd_cls(client).run() if __name__ == '__main__': client = Client(loop_) coro = loop_.create_connection(lambda: client, '127.0.0.1', 10888) loop_.run_until_complete(coro) loop_.run_until_complete(main()) </code></pre>
0
2016-10-06T17:02:51Z
39,914,294
<p>You could consider using <a href="https://github.com/vxgmichel/aioconsole" rel="nofollow">aioconsole.ainput</a>:</p> <pre><code>from aioconsole import ainput async def some_coroutine(): line = await ainput("&gt;&gt;&gt; ") [...] </code></pre> <p>The project is available on <a href="https://pypi.python.org/pypi/aioconsole" rel="nofollow">PyPI</a>.</p>
1
2016-10-07T09:48:22Z
[ "python", "tcpclient", "python-asyncio" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to assign the elements from this Series as keys in a dictionary, and indices as values, like this:</p> <pre><code>{ mySeries[i]: i for i in mySeries.index } </code></pre> <p>and I'm getting pretty much what I wanted, except that...</p> <pre><code>{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... } </code></pre> <p>Why has <code>3.1</code> suddenly changed into <code>3.1000000000000001</code>? I guess this has something to do with the way the floating point numbers are represented (?) but why does it happen <em>now</em> and how do I avoid/fix it?</p> <p><strong>EDIT:</strong> Please feel free to suggest a better title for this question if it's inaccurate.</p> <p><strong>EDIT2:</strong> Ok, so it seems that it's the exact same number, just <em>printed</em> differently. Still, if I assign <code>mySeries[26]</code> as a dictionary key and then I try to run:</p> <pre><code>myDict[mySeries[26]] </code></pre> <p>I get <code>KeyError</code>. What's the best way to avoid it?</p>
4
2016-10-06T17:03:38Z
39,901,950
<p>The value is already that way in the Series:</p> <pre><code>&gt;&gt;&gt; x = pd.Series([16,14,12,10,3.1]) &gt;&gt;&gt; x 0 16.0 1 14.0 2 12.0 3 10.0 4 3.1 dtype: float64 &gt;&gt;&gt; x.iloc[4] 3.1000000000000001 </code></pre> <p>This has to do with floating point precision:</p> <pre><code>&gt;&gt;&gt; np.float64(3.1) 3.1000000000000001 </code></pre> <p>See <a href="http://stackoverflow.com/questions/5160339/floating-point-precision-in-python-array">Floating point precision in Python array</a> for more information about this.</p> <p>Concerning the <code>KeyError</code> in your edit, I was not able to reproduce. See the below:</p> <pre><code>&gt;&gt;&gt; d = {x[i]:i for i in x.index} &gt;&gt;&gt; d {16.0: 0, 10.0: 3, 12.0: 2, 14.0: 1, 3.1000000000000001: 4} &gt;&gt;&gt; x[4] 3.1000000000000001 &gt;&gt;&gt; d[x[4]] 4 </code></pre> <p>My suspicion is that the <code>KeyError</code> is coming from the <code>Series</code>: what is <code>mySeries[26]</code> returning?</p>
3
2016-10-06T17:10:35Z
[ "python", "pandas", "dictionary", "floating-point" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to assign the elements from this Series as keys in a dictionary, and indices as values, like this:</p> <pre><code>{ mySeries[i]: i for i in mySeries.index } </code></pre> <p>and I'm getting pretty much what I wanted, except that...</p> <pre><code>{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... } </code></pre> <p>Why has <code>3.1</code> suddenly changed into <code>3.1000000000000001</code>? I guess this has something to do with the way the floating point numbers are represented (?) but why does it happen <em>now</em> and how do I avoid/fix it?</p> <p><strong>EDIT:</strong> Please feel free to suggest a better title for this question if it's inaccurate.</p> <p><strong>EDIT2:</strong> Ok, so it seems that it's the exact same number, just <em>printed</em> differently. Still, if I assign <code>mySeries[26]</code> as a dictionary key and then I try to run:</p> <pre><code>myDict[mySeries[26]] </code></pre> <p>I get <code>KeyError</code>. What's the best way to avoid it?</p>
4
2016-10-06T17:03:38Z
39,901,954
<p>The dictionary isn't changing the floating point representation of 3.1, but it is actually displaying the full precision. Your print of mySeries[26] is truncating the precision and showing an approximation.</p> <p>You can prove this:</p> <pre><code>pd.set_option('precision', 20) </code></pre> <p>Then view mySeries.</p> <pre><code>0 16.00000000000000000000 1 14.00000000000000000000 2 12.00000000000000000000 3 10.00000000000000000000 4 3.10000000000000008882 dtype: float64 </code></pre> <p><strong>EDIT</strong>:</p> <p><a href="https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html" rel="nofollow">What every computer programmer should know about floating point arithmetic</a> is always a good read.</p> <p><strong>EDIT</strong>:</p> <p>Regarding the KeyError, I was not able to replicate the problem.</p> <pre><code>&gt;&gt; x = pd.Series([16,14,12,10,3.1]) &gt;&gt; a = {x[i]: i for i in x.index} &gt;&gt; a[x[4]] 4 &gt;&gt; a.keys() [16.0, 10.0, 3.1000000000000001, 12.0, 14.0] &gt;&gt; hash(x[4]) 2093862195 &gt;&gt; hash(a.keys()[2]) 2093862195 </code></pre>
6
2016-10-06T17:10:56Z
[ "python", "pandas", "dictionary", "floating-point" ]
Assigning float as a dictionary key changes its precision (Python)
39,901,833
<p>I have a list of floats (actually it's a pandas Series object, if it changes anything) which looks like this:</p> <pre><code>mySeries: ... 22 16.0 23 14.0 24 12.0 25 10.0 26 3.1 ... </code></pre> <p>(So elements of this Series are on the right, indices on the left.) Then I'm trying to assign the elements from this Series as keys in a dictionary, and indices as values, like this:</p> <pre><code>{ mySeries[i]: i for i in mySeries.index } </code></pre> <p>and I'm getting pretty much what I wanted, except that...</p> <pre><code>{ 6400.0: 0, 66.0: 13, 3.1000000000000001: 23, 133.0: 10, ... } </code></pre> <p>Why has <code>3.1</code> suddenly changed into <code>3.1000000000000001</code>? I guess this has something to do with the way the floating point numbers are represented (?) but why does it happen <em>now</em> and how do I avoid/fix it?</p> <p><strong>EDIT:</strong> Please feel free to suggest a better title for this question if it's inaccurate.</p> <p><strong>EDIT2:</strong> Ok, so it seems that it's the exact same number, just <em>printed</em> differently. Still, if I assign <code>mySeries[26]</code> as a dictionary key and then I try to run:</p> <pre><code>myDict[mySeries[26]] </code></pre> <p>I get <code>KeyError</code>. What's the best way to avoid it?</p>
4
2016-10-06T17:03:38Z
39,901,991
<p>You can round it to the accuracy you can accept:</p> <pre><code>&gt;&gt;&gt; hash(round(3.1, 2)) 2093862195 &gt;&gt;&gt; hash(round(3.1000000000000001, 2)) 2093862195 </code></pre>
0
2016-10-06T17:13:11Z
[ "python", "pandas", "dictionary", "floating-point" ]
Webscraping using Python - Link is unchanged with form input
39,901,841
<p>I planned to retrieve the historical data from the open web available. From the link:</p> <p><a href="https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day" rel="nofollow">https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day</a></p> <p>Ideally, I am trying to change the country, day,month,year using the inputs from a Pandas Dataframe and retrieve the results (energy consumption here in this web page) and store back to excel. </p> <p>I am trying with different web scrappers and one information is doubtful to me about the possibilities. </p> <p>It is : when I manually change the Country, day, month,year and when retriving results, the web link remains unchanged. Is it possible to achieve my goal with this web link.</p> <p>Thank you for your time. </p>
0
2016-10-06T17:04:04Z
39,903,792
<p>First of all, you need to understand what happens when you click "Send" button. A POST request is sent to the same URL with parameters corresponding to values you've selected on the form. You can see this request in the browser developer tools - "Network" tab. Now, you need to simulate this request in your code (I'll use the awesome <a href="http://docs.python-requests.org/en/master/" rel="nofollow"><code>requests</code> package</a> below)</p> <p>The other problem is that if you inspect what you get in the response to that POST request, you would not find the same <code>table</code> element with the desired data as you would see in the browser. This is because the <code>table</code> is dynamically generated from the <code>myData</code> javascript variable "sitting" in on of the <code>script</code> elements. Since nor <code>BeautifiulSoup</code>, nor <code>requests</code> is a browser and cannot execute JavaScript, you need to extract the <code>myData</code> value from the script.</p> <p>Here is a working code that would get you the desired data in the "archived" scope for 01/01/2009:</p> <pre><code>import re from ast import literal_eval from pprint import pprint import requests from bs4 import BeautifulSoup url = "https://www.entsoe.eu/db-query/consumption/mhlv-a-specific-country-for-a-specific-day" data = { "opt_period": "2", "opt_Country": "3", "opt_Day": "1", "opt_Month": "1", "opt_Year": "2009", "opt_Response": "1", "send": "send" } with requests.Session() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'} # visit the page session.get(url) # make a POST request response = session.post(url, data=data) soup = BeautifulSoup(response.content, 'html.parser') # find the desired script pattern = re.compile(r"var myData = (.*?);", re.MULTILINE | re.DOTALL) script = soup.find("script", text=pattern) # extract the data from the script match = pattern.search(script.get_text()) data = match.group(1).strip() data = literal_eval(data) pprint(data) </code></pre> <p>Prints a Python list of lists:</p> <pre><code>[['AT', '2009-01-01', 6277, 6002, 5649, 5230, 5034, 5038, 4858, 5127, 5342, 5747, 6100, 6373, 6325, 6210, 6129, 6160, 6588, 7007, 7058, 6887, 6586, 6137, 6494, 5974]] </code></pre> <p>Also note how we are <a class='doc-link' href="http://stackoverflow.com/documentation/python/1792/web-scraping-with-python/8152/maintaining-web-scraping-session-with-requests#t=201610061906003569883">maintaining a web-scraping session</a> in this example.</p>
1
2016-10-06T19:03:23Z
[ "python", "web-scraping", "beautifulsoup", "scrapy", "mechanize" ]
What does defining a function with in the __init__ constructor in python mean?
39,901,860
<p>I have just seen the following code and would like to know what the function within the <code>__init__</code> function means</p> <pre><code>def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program self.alive = True </code></pre>
0
2016-10-06T17:05:20Z
39,902,110
<p>This code</p> <pre><code>class Foo: def __init__(self): def program(percept): return raw_input('Percept=%s; action? ' % percept) self.program = program </code></pre> <p>AFAIK, is actually the exact same as this since <code>self.program = program</code>. </p> <pre><code>class Foo: def __init__(self): pass def program(self, percept): return raw_input('Percept=%s; action? ' % percept) </code></pre> <p>The only reason I can see to nest a function there was if you just used the function to do some initializations within the constructor, but didn't want to expose it on the class. </p>
0
2016-10-06T17:20:29Z
[ "python", "constructor", "init" ]
adding tuples to a list in an if loop (python)
39,901,930
<p>I'm working in python with symbulate for a probability course and running some simulations. </p> <p>Setup: Two teams, A and B, are playing in a “best of n” game championship series, where n is an odd number. For this example, n=7, and the probability team A wins any individual game is 0.55. Approximate the probability that Team A wins the series, given that they win the first game.</p> <p>Here is what I've got so far, which I think is along the right lines:</p> <pre><code>model = BoxModel([1, 0], probs=[0.55, .45], size=7, replace=True) test = model.sim(10000) for x in range(0,10000): test1 = test[x] if test1[0] == 1: print (test1) test1 </code></pre> <p>The last two lines are where I'm having my difficulty. This 'for' and 'if' combination makes it so only the inputs that start with a '1' (i.e. Team A winning the first game) are displayed. I need to save these inputs into a table so that I can run some further testing on it.</p> <p>How do I input the value of test1 into a table while those loops are running? Currently, test1 only outputs the x=10,000th value.</p> <p>Edit: The "test" yields a list, 0-10000, of all the possible game outcomes. I need a list that only has the game outcomes that start with a "1".</p> <p>Edit2: Output of "test" (before I run a "for" or "if") look like: </p> <pre><code>Index Result 0 (1, 1, 1, 0, 0, 1, 1) 1 (0, 1, 0, 1, 1, 0, 0) 2 (1, 1, 1, 1, 0, 1, 0) 3 (0, 0, 1, 1, 1, 1, 1) 4 (0, 0, 0, 0, 0, 0, 0) 5 (1, 1, 0, 1, 0, 0, 1) 6 (0, 0, 1, 0, 1, 1, 1) 7 (0, 1, 0, 0, 0, 0, 1) 8 (1, 1, 0, 1, 0, 1, 0) ... ... 9999 (1, 1, 0, 1, 0, 0, 0) </code></pre> <p>I need a "test' (or another variable) to contain something that looks EXACTLY like that, but only contains lines that start with "1". </p>
-1
2016-10-06T17:09:28Z
39,901,955
<p>So you're looking to store the results of each test? Why not store them in a <code>list</code>?</p> <pre><code>test1_results = [] for x in range(0,10000): test1 = test[x] # check if first element in sequence of game outcomes is a win for team A if test1[0] == 1: # or '1' if you're expecting string test1_results.append(test1) </code></pre> <p>You can the run <code>print(test1_results)</code> to print the entire list of results, but if you want to print the first <code>n</code> results, do <code>print(test1_results[:n])</code>.</p> <p>If you want your <code>if</code> statement in there, you will have to slightly adjust the placement. What does your <code>test</code> object look like? Could you give us a small sample?</p> <p>edit: updated <code>if</code> statement to reflect comment below</p>
1
2016-10-06T17:11:02Z
[ "python" ]
adding tuples to a list in an if loop (python)
39,901,930
<p>I'm working in python with symbulate for a probability course and running some simulations. </p> <p>Setup: Two teams, A and B, are playing in a “best of n” game championship series, where n is an odd number. For this example, n=7, and the probability team A wins any individual game is 0.55. Approximate the probability that Team A wins the series, given that they win the first game.</p> <p>Here is what I've got so far, which I think is along the right lines:</p> <pre><code>model = BoxModel([1, 0], probs=[0.55, .45], size=7, replace=True) test = model.sim(10000) for x in range(0,10000): test1 = test[x] if test1[0] == 1: print (test1) test1 </code></pre> <p>The last two lines are where I'm having my difficulty. This 'for' and 'if' combination makes it so only the inputs that start with a '1' (i.e. Team A winning the first game) are displayed. I need to save these inputs into a table so that I can run some further testing on it.</p> <p>How do I input the value of test1 into a table while those loops are running? Currently, test1 only outputs the x=10,000th value.</p> <p>Edit: The "test" yields a list, 0-10000, of all the possible game outcomes. I need a list that only has the game outcomes that start with a "1".</p> <p>Edit2: Output of "test" (before I run a "for" or "if") look like: </p> <pre><code>Index Result 0 (1, 1, 1, 0, 0, 1, 1) 1 (0, 1, 0, 1, 1, 0, 0) 2 (1, 1, 1, 1, 0, 1, 0) 3 (0, 0, 1, 1, 1, 1, 1) 4 (0, 0, 0, 0, 0, 0, 0) 5 (1, 1, 0, 1, 0, 0, 1) 6 (0, 0, 1, 0, 1, 1, 1) 7 (0, 1, 0, 0, 0, 0, 1) 8 (1, 1, 0, 1, 0, 1, 0) ... ... 9999 (1, 1, 0, 1, 0, 0, 0) </code></pre> <p>I need a "test' (or another variable) to contain something that looks EXACTLY like that, but only contains lines that start with "1". </p>
-1
2016-10-06T17:09:28Z
39,901,996
<p>Based on your comment:</p> <pre><code>results_that_start_with_one = [] for result in test: result_string = str(result) if result_string[0] == "1": results_that_start_with_one.append(result_string) </code></pre> <p>This iterates through each of your results in the list "test". It convert each to a string (i'm assuming they are some numeric value). It then takes the first character in the string, and asks if its a 1.</p>
0
2016-10-06T17:13:20Z
[ "python" ]
Django: How do you associate an Object_PK in the URL to the Foreign_Key relation field when creating a new object?
39,902,029
<p>I am building an FAQ system. The models extend from Topic -> Section -> Article. When creating a new Article the User will select a Topic then a Section then the create Article button.</p> <p>The url will look something like //mysite.org/Topic_PK/Section_PK/Article_Create</p> <p>In Django it should look like this: </p> <pre><code>url(r'^ironfaq/(?P&lt;pk&gt;\d+)/(?P&lt;pk&gt;\d+)/article$', ArticleCreateView.as_view(), name=’article-create’) </code></pre> <p>What I am looking to do is to associate the Section_PK to the Article when the user submits the Article. I have the Section_PK in the URL I need help to figure out how to use it to do this.</p> <p>Alternatively with this set up I can have a form rendered with a choice selection from the Section_FK in the Articles Model. If when creating the Article upon rendering the template if I could limit the Section choices by the Topic in the form.py this will also work for my needs</p> <p>The url will look something like //mysite.org/Topic_PK/article/create</p> <p>In Django the url should look like this:</p> <pre><code>url(r'^ironfaq/(?P&lt;pk&gt;\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’) </code></pre> <p>Both these methods require the Passing of the Topic or Section PK to the view or form thru the URL. If there is a better way to do this I am open to other suggestions. </p> <p>In Django I have the following Models</p> <pre><code>class Topic(Audit): name = models.CharField(max_length=255) sort = models.SmallIntegerField() slug = models.SlugField() class Meta: verbose_name_plural = "topics" def __str__(self): return self.name def get_absolute_url(self): return ('faq-topic-detail',(), {'slug': self.slug}) class Section(Audit): name = models.CharField(max_length=255) sort = models.SmallIntegerField() slug = models.SlugField() topic = models.ForeignKey(Topic,on_delete=models.CASCADE) class Meta: verbose_name_plural = "sections" def __str__(self): return self.name def get_absolute_url(self): return ('faq-section-detail',(), {'topic__slug': self.topic.slug, 'slug': self.slug}) class Article(Audit): title = models.CharField(max_length=255) sort = models.SmallIntegerField() slug = models.SlugField() section = models.ForeignKey(Section,on_delete=models.CASCADE) answer = models.TextField() vote_up = models.IntegerField() vote_down = models.IntegerField() view_count = models.IntegerField(default=0) class Meta: verbose_name_plural = "articles" def __str__(self): return self.title def total_votes(self): return self.vote_up + self.vote_down def percent_yes(self): return (float(self.vote_up) / self.total_votes()) * 100 def get_absolute_url(self): return ('faq-article-detail',(), {'topic__slug': self.section.topic.slug, 'section__slug': self.section.slug, 'slug': self.slug}) </code></pre> <p>Mysite Forms</p> <pre><code>class CreateArticleForm(forms.ModelForm): class Meta: model = Article widgets = { 'answer': forms.Textarea(attrs={'data-provide': 'markdown', 'data-iconlibrary': 'fa'}), } fields = ('title','section','answer') </code></pre> <p>Mysite Views</p> <pre><code>class TopicCreateView(CreateView): model = Topic fields = ['name'] template_name = "faq/form_create.html" success_url = "/ironfaq" def form_valid(self, form): topic = form.save(commit=False) activity_user = self.request.user.username activity_date = datetime.datetime.now() topic.save() return super(TopicCreateView,self).form_valid(form) class SectionCreateView(CreateView): model = Section fields = ['name', 'topic'] template_name = "faq/form_create.html" def form_valid(self, form): section = form.save(commit=False) activity_user = self.request.user.username activity_date = datetime.datetime.now() section.save() self.success_url = "/ironfaq/%s/%s" % (section.topic.slug,section.slug) return super(SectionCreateView,self).form_valid(form) class ArticleCreateView(CreateView): model = Article form_class = CreateArticleForm template_name = "faq/form_create.html" def form_valid(self, form): article = form.save(commit=False) activity_user = self.request.user.username activity_date = datetime.datetime.now() article.save() self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug) return super(ArticleCreateView,self).form_valid(form) </code></pre>
0
2016-10-06T17:15:19Z
39,912,337
<p>Let's say that you have this url</p> <pre><code>url(r'^ironfaq/(?P&lt;topic_pk&gt;\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’) </code></pre> <p>Where <code>topic_pk</code> will be pk of topic you want to be associated with your Article. </p> <p>Then you just need to retrieve it in view. And this is done like this</p> <pre><code>class ArticleCreateView(CreateView): model = Article form_class = CreateArticleForm template_name = "faq/form_create.html" def form_valid(self, form): article = form.save(commit=False) # what are this variables for? activity_user = self.request.user.username activity_date = datetime.datetime.now() # here we are getting 'topic_pk' from self.kwargs article.topic_id = self.kwargs['topic_pk'] article.save() self.success_url = "/ironfaq/%s/%s/%s" % (article.section.topic.slug,article.section.slug,article.slug) return super(ArticleCreateView,self).form_valid(form) </code></pre> <p>All url params are stored in <code>self.args</code> and <code>self.kwargs</code>. Our <code>topic_pk</code> is named parameter and thats why we can get it by doing <code>self.kwargs['topic_pk']</code></p> <p>But be sure to validate existence of <code>Topic</code> with such pk before assigning it to your <code>Article</code></p>
0
2016-10-07T08:01:06Z
[ "python", "django" ]
Django - Template tags not working properly after form validation
39,902,092
<p>I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage. </p> <p>The following is my forms.py:</p> <pre><code>class CompForm(forms.ModelForm): class Meta: model = Comp fields = ('inp',) </code></pre> <p>The following is my views.py:</p> <pre><code>def index(request): form = CompForm(request.POST or None) context = { 'form': form, } print context if form.is_valid(): ... ... outData = "The values you gave is correct" errData = "The values you gave is incorrect" print context context['outData'] = outData context['errData'] = errData print context return render(request, 'comp/index.html', context) </code></pre> <p>The following is my index.html:</p> <pre><code>{% extends "comp/base.html" %} {% load crispy_forms_tags %} {% block content %} &lt;div class="row"&gt; &lt;div class="col-md-8 col-md-offset-2"&gt; &lt;form method="post" action=""&gt; {% csrf_token %} {{ form|crispy }} &lt;input class="btn btn-primary" type="submit" name="Submit" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; {% if outData %} {{ outData.as_p }} {% endif %} {% if errData %} {{ errData.as_p }} {% endif %} {% endblock %} </code></pre> <p>In the terminal I am able to get the <code>outData</code> and <code>errData</code> in the dictionary, but its not getting displayed in the webpage. What might be the mistake? Kindly help.</p>
0
2016-10-06T17:19:37Z
39,902,200
<p>You are trying to called the method <code>as_p</code> on strings which doesn't make sense. </p> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/#form-rendering-options" rel="nofollow"><code>as_p()</code></a> is a helper method on form instances to make it easier to render them in the template so you need:</p> <pre><code>{{ form.as_p }} </code></pre> <p>you can also use <code>as_table</code> and <code>as_ul</code></p> <p>You can read more in the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/api/#ref-forms-api-outputting-html" rel="nofollow">documentation</a></p>
1
2016-10-06T17:26:07Z
[ "python", "django" ]
passing radio buttons from javascript to django views as a paramater
39,902,125
<p>I have a html page where I am passing the selected checkboxes to django views as parameter which works completely fine.</p> <p>layout.html</p> <pre><code>&lt;form action="{% url 'URL Which calls view' %}" method="post"&gt; {% csrf_token %} &lt;label class="checkbox"&gt; &lt;input type="checkbox" name="checks" value="REG_AGREED_SUITE01"&gt;REG_AGREED_SUITE01 &lt;/label&gt; &lt;hr&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" name="checks" value="REG_AGREED_SUITE02"&gt;REG_AGREED_SUITE02 &lt;/label&gt; &lt;hr&gt; &lt;label class="checkbox"&gt; &lt;input type="checkbox" name="checks" value="REG_AGREED_SUITE03"&gt;REG_AGREED_SUITE03 &lt;/label&gt; &lt;hr&gt; </code></pre> <p>form.py</p> <pre><code>class NameForm(forms.Form): </code></pre> <p>views.py</p> <pre><code>def view(request): if request.method == 'POST': form = NameForm(request.POST) else: form = NameForm() print request.POST.getlist('checks') form = NameForm(request.POST) list1 = request.POST.getlist('checks') TestSuite = ', '.join(list1) </code></pre> <p>Now I have a situation, Where I would like to pass the radio buttons as parameters in django views. I have a json file from which using java script I am pulling the values and displaying on html. Is there any way, when ever I select a radio button, I can pass them as a parameter in django views as above case? or is it the best approach to create a form in Django?</p> <p>temp.json</p> <pre><code>[ {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#1", "STBSno": "M11435TDS144"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#2", "STBSno": "M11543TH4292"}, {"STBStatus": "0", "RouterSNo": "R1", "STBLabel": "STB#3", "STBSno": "SN005"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#4", "STBSno": "M11509TD9937"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#5", "STBSno": "M11543TH4258"}, {"STBStatus": "0", "RouterSNo": "R1", "STBLabel": "STB#6", "STBSno": "SN005"}, {"STBStatus": "0", "RouterSNo": "R1", "STBLabel": "STB#7", "STBSno": "SN006"}, {"STBStatus": "0", "RouterSNo": "R1", "STBLabel": "STB#8", "STBSno": "SN007"} ] </code></pre> <p>Javascript:</p> <pre><code>&lt;script&gt; function stbststus(){ show_alert() $.getJSON("Json", function(result){ $("#STBStatus").empty(); $.each(result, function(i, item){ if(item.STBStatus == "1"){ colorclass = "available" } if(item.STBStatus == "0"){ colorclass = "offline" } if(item.STBStatus == "2"){ colorclass = "In use" } $("#STBStatus").append("&lt;label class='radio'&gt;&lt;input type='radio' name='optradio' class='optradio'&gt;"+item.STBLabel +" &lt;i class='fa fa-circle pull-right "+colorclass+"' aria-hidden='true'&gt;&lt;/i&gt;&lt;/label&gt; &lt;hr&gt;"); }); }); } &lt;/script&gt; </code></pre> <p>layout.html</p> <pre><code> &lt;div class="quote-text scroller" id="STBStatus"&gt; &lt;/div&gt; &lt;div class="wrapper"&gt; &lt;div class="buttonHolder" onclick="pageload()"&gt; &lt;p&gt;&lt;a href="Set_Top_Box" class="btn btn-primary btn-large"&gt;Get Settopbox Status &amp;raquo;&lt;/a&gt;&lt;/p&gt; </code></pre>
1
2016-10-06T17:21:16Z
39,904,750
<p>Django will not handle onClick events or anything of sort, you are better off with javascript and or jquery for that.</p> <p><strong>Jquery</strong></p> <pre><code>$(function(){ $('input[type="radio"]').click(function(){ if ($(this).is(':checked')) { alert($(this).val()); } }); }); </code></pre> <p>or for vanilla JavaScript check this url <a href="http://www.dyn-web.com/tutorials/forms/radio/get-selected.php" rel="nofollow">Get Value of Selected Radio Button</a>.</p>
0
2016-10-06T20:04:18Z
[ "php", "python", "html", "django" ]
Generate features from "comments" column in dataframe
39,902,151
<p>I have a dataset with a column that has comments. This comments are words separated by commas.</p> <p>df_pat['reason'] = </p> <ol> <li>chest pain</li> <li>chest pain, dyspnea</li> <li>chest pain, hypertrophic obstructive cariomyop...</li> <li>chest pain </li> <li>chest pain</li> <li>cad, rca stents</li> <li>non-ischemic cardiomyopathy, chest pain, dyspnea</li> </ol> <p>I would like to generate separated columns in the dataframe so that a column represent each word from all the set of words, and then have 1 or 0 to the rows where I initially had that word in the comment.</p> <p>For example: df_pat['chest_pain'] = 1 1 1 1 1 1 0 1</p> <p>df_pat['dyspnea'] = 0 1 0 0 0 0 1</p> <p>And so on...</p> <p>Thank you!</p>
0
2016-10-06T17:22:52Z
39,902,292
<p><code>sklearn.feature_extraction.text</code> has something for you! It looks like you may be trying to predict something. If so - and if you're planning to use sci-kit learn at some point, then you can bypass making a dataframe with len(set(words)) number of columns and just use <code>CountVectorizer</code>. This method will return a matrix with dimensions (rows, columns) = (number of rows in dataframe, number of unique words in entire <code>'reason'</code> column). </p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer df = pd.DataFrame({'reason': ['chest pain', 'chest pain, dyspnea', 'chest pain, hypertrophic obstructive cariomyop', 'chest pain', 'chest pain', 'cad, rca stents', 'non-ischemic cardiomyopathy, chest pain, dyspnea']}) # turns body of text into a matrix of features # split string on commas instead of spaces vectorizer = CountVectorizer(tokenizer = lambda x: x.split(",")) # X is now a n_documents by n_distinct_words-dimensioned matrix of features X = vectorizer.fit_transform(df['reason']) </code></pre> <p><code>pandas</code> plays really nicely with <code>sklearn</code>.</p> <p>Or, a strict <code>pandas</code> solution that should probably be vectorized, but if you don't have that much data, should work:</p> <pre><code># split on the comma instead of spaces to get "chest pain" instead of "chest" and "pain" reasons = [reason for case in df['reason'] for reason in case.split(",")] for reason in reasons: for idx in df.index: if reason in df.loc[idx, 'reason']: df.loc[idx, reason] = 1 else: df.loc[idx, reason] = 0 </code></pre>
0
2016-10-06T17:31:55Z
[ "python", "text", "dataframe", "comments" ]
install theano with python centos-7
39,902,181
<p>I could successfully install theano with python2 by following the instructions here <a href="http://deeplearning.net/software/theano/install_centos6.html#install-centos6" rel="nofollow">http://deeplearning.net/software/theano/install_centos6.html#install-centos6</a>. Since I do not have root access, I asked my admin to install the additional packages required as mentioned. </p> <p>sudo yum install python-devel python-nose python-setuptools gcc gcc-gfortran gcc-c++ blas-devel lapack-devel atlas-devel.</p> <p>This works for python2 but not python3. Are their additional packages required for python3? Running with python3 gives an error </p> <p>.theano/compiledir_Linux-3.10-el7.x86_64-x86_64-with-centos-7.2.1511-Core-x86_64-3.4.3-64/lazylinker_ext/mod.cpp:1:20: fatal error: Python.h: No such file or directory. #include . ^. compilation terminated.. </p>
0
2016-10-06T17:25:08Z
39,916,218
<p>Seems like you didn't correctly install all the header files and static libraries for python dev. If you have administrative problems you can use Anaconda from <code>https://www.continuum.io/downloads</code> Else, the most preferred way is using your package manager to install them system-wide. </p> <p><code>sudo yum install python-devel</code></p> <p>Edit : You can install theano with anaconda without admin rights. You can download the anaconda's package for your system, set the appropriate path to the python compiler and then install theano using <code>conda install theano</code>. Also, you can install libgpuarray and pygpu, a dependency for using theano's new backend without admin rights, you can find the instructions <code>http://deeplearning.net/software/libgpuarray/installation.html#step-by-step-install</code>. </p>
1
2016-10-07T11:32:43Z
[ "python", "centos", "theano" ]
Setting up PyOpenGL with freeglut for Python 3.5.2
39,902,238
<p>I am trying to set up my machine to use PyOpenGL with freeglut. I have Python version 3.5.2 and a 64 bit copy of Windows 8.</p> <p>I have downloaded PyOpenGL using pip, then downloaded freeglut and placed the <code>include\</code> and <code>lib\</code> folders at <code>C:\Program Files\Common Files\MSVC\freeglut</code>. I have also placed a link to the 64 bit freeglut.dll file in the environment variables linking to C:\Work\freeglut.dll</p> <p>As I do not know any OpenGL yet I am simply trying to run the code from this page to see if my setup is functional <a href="http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLSierpinski" rel="nofollow">http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLSierpinski</a>. When run I receive the error message </p> <pre><code>Traceback (most recent call last): File "sier_tri.py", line 35, in &lt;module&gt; glutInit() File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\site-packag es\OpenGL\GLUT\special.py", line 333, in glutInit _base_glutInit( ctypes.byref(count), holder ) File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\site-packag es\OpenGL\platform\baseplatform.py", line 407, in __call__ self.__name__, self.__name__, OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling </code></pre> <p>Does anyone know what is causing this/how to fix it?</p>
0
2016-10-06T17:28:45Z
39,902,290
<p>place the <code>glut32.dll</code> next to the <code>py</code> file.</p> <p>Check this <a href="http://stackoverflow.com/questions/39181192/attempt-to-call-an-undefined-function-glutinit">link</a></p>
0
2016-10-06T17:31:55Z
[ "python", "freeglut", "pyopengl" ]
Setting up PyOpenGL with freeglut for Python 3.5.2
39,902,238
<p>I am trying to set up my machine to use PyOpenGL with freeglut. I have Python version 3.5.2 and a 64 bit copy of Windows 8.</p> <p>I have downloaded PyOpenGL using pip, then downloaded freeglut and placed the <code>include\</code> and <code>lib\</code> folders at <code>C:\Program Files\Common Files\MSVC\freeglut</code>. I have also placed a link to the 64 bit freeglut.dll file in the environment variables linking to C:\Work\freeglut.dll</p> <p>As I do not know any OpenGL yet I am simply trying to run the code from this page to see if my setup is functional <a href="http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLSierpinski" rel="nofollow">http://www.de-brauwer.be/wiki/wikka.php?wakka=PyOpenGLSierpinski</a>. When run I receive the error message </p> <pre><code>Traceback (most recent call last): File "sier_tri.py", line 35, in &lt;module&gt; glutInit() File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\site-packag es\OpenGL\GLUT\special.py", line 333, in glutInit _base_glutInit( ctypes.byref(count), holder ) File "C:\Users\Dylan\AppData\Local\Programs\Python\Python35-32\lib\site-packag es\OpenGL\platform\baseplatform.py", line 407, in __call__ self.__name__, self.__name__, OpenGL.error.NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling </code></pre> <p>Does anyone know what is causing this/how to fix it?</p>
0
2016-10-06T17:28:45Z
39,906,848
<p>I fixed this by switching to the 32 bit <code>freeglut.dll</code> file. I thought that the 32bit vs 64bit was dependent on your operating system but it's actually dependent on which kind of Python you have, as I have 32 bit Python I need the 32 bit dll.</p>
0
2016-10-06T22:55:09Z
[ "python", "freeglut", "pyopengl" ]
Multiple relative Imports in python 3.5
39,902,333
<p>This structure is just an example</p> <pre><code>pkg\ test\ __init__.py test.py __init__.py source.py another_source.py </code></pre> <p>another_source.py</p> <pre><code>class Bar(): def __init__(self): self.name = "bar" </code></pre> <p>source.py</p> <pre><code>from another_source import Bar class Foo(): def __init__(self): self.name = "foo" b = Bar() </code></pre> <p>test.py</p> <pre><code>from ..source import Foo if __name__== "__main__": f = Foo() print(f.name) </code></pre> <p>Now I want to run test.py. As it has been accepted as the <a href="http://stackoverflow.com/questions/11536764/how-to-fix-attempted-relative-import-in-non-package-even-with-init-py">answer</a> I have to go above my current package and run</p> <pre><code>python -m pkg.test.test </code></pre> <p>But this does not work and python gives me a traceback</p> <pre><code>Traceback (most recent call last): File "-\Python35\lib\runpy.py", line 170, in _run_module_as_main "__main__", mod_spec) File "-\Python35\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "~\test\test.py", line 1, in &lt;module&gt; from ..source import Foo File "~\source.py", line 1, in &lt;module&gt; from another_source import Bar ImportError: No module named 'another_source' </code></pre> <p>If I remove all the another_source-stuff it will work, but that is not a solution.</p> <p>Now is there a sane way to import classes from places that are one directory above me?</p>
2
2016-10-06T17:35:23Z
39,902,394
<p><code>pkg.source</code> is trying to import things from the <code>pkg.another_source</code> module as if it were top-level. That import needs to be corrected:</p> <pre><code>from .another_source import Bar # or from pkg.another_source import another_source </code></pre>
1
2016-10-06T17:38:31Z
[ "python" ]
How to set the current working directory in the Python sh module?
39,902,365
<p>Is there a way to set the current working directory within a call to the Python <a href="http://amoffat.github.io/sh/" rel="nofollow">sh</a> module?</p> <p>I'd like to be able to execute a command --- and only the command --- in a different directory than the one I'm currently in. Something along the lines of:</p> <pre><code>import sh foo = sh.ls(_current_directory="/tmp") </code></pre> <p>woudl be nice.</p>
0
2016-10-06T17:37:18Z
39,902,550
<p>Use the <a href="https://amoffat.github.io/sh/special_arguments.html#special-keyword-arguments" rel="nofollow"><code>_cwd</code> parameter</a> to set the current working directory on a per-command basis:</p> <pre><code>import sh print(sh.ls(_cwd='/tmp')) </code></pre> <p>This works for any command, not just <code>sh.ls</code>.</p>
1
2016-10-06T17:48:36Z
[ "python" ]
pyspark redueByKey modify single results
39,902,387
<p>I have a dataset that looks like this in pyspark:</p> <pre><code>samp = sc.parallelize([(1,'TAGA'), (1, 'TGGA'), (1, 'ATGA'), (1, 'GTGT'), (2, 'GTAT'), (2, 'ATGT'), (3, 'TAAT'), (4, 'TAGC')]) </code></pre> <p>I have a function that I'm using to combine the strings:</p> <pre><code> def combine_strings(x,y): if (isinstance(x,list) and isinstance(y, list)): z = x + y return z if (isinstance(x, list) and isinstance(y, str)): x.append(y) return x if (isinstance(x, str) and isinstance(y, list)): y.append(x) return y return [x,y] </code></pre> <p>The result I get is:</p> <pre><code>samp.reduceByKey(lambda x,y : combine_strings(x,y)).collect() [(1, ['TAGA', 'TGGA', 'ATGA', 'GTGT']), (2, ['GTAT', 'ATGT']), (3, 'TAAT'), (4, 'TAGC')] </code></pre> <p>What I want is:</p> <p>[(1, ['TAGA', 'TGGA', 'ATGA', 'GTGT']), (2, ['GTAT', 'ATGT']), (3, ['TAAT']), (4, ['TAGC'])]</p> <p>Where everything is an array. I can't tell if pyspark is calling combine_strings on a result where there's 1 entry or if I can tell reduceByKey to do something with singleton results? How do I modify the reduceByKey() or the combine_strings function to produce what I'd like? </p>
0
2016-10-06T17:38:14Z
39,902,956
<p>You could first map the values into lists and then only combine those lists:</p> <pre><code>samp.mapValues(lambda x : [x]).reduceByKey(lambda x,y : x + y).collect() </code></pre> <p>The problem here is that those singletons are not affected by <code>reduceByKey</code>. Here is another example:</p> <pre><code>samp = sc.parallelize([(1,1),(2,2),(2,2),(3,3)]) &gt;&gt;&gt; samp.reduceByKey(lambda x, y : x + y + 1).collect() [(3, 3), (1, 1), (2, 5)] </code></pre>
0
2016-10-06T18:13:41Z
[ "python", "mapreduce", "pyspark" ]
FullCalendar in Django
39,902,405
<p>So, I have an appointment models </p> <pre><code>class Appointment(models.Model): user = models.ForeignKey(User) date = models.DateField() time = models.TimeField() doctorName = models.CharField(max_length=50)` </code></pre> <p>And I want to implement this in the <code>FullCalendar</code> tool. I'm not sure how to even begin. Any help is appreciated. Thanks.</p>
1
2016-10-06T17:39:23Z
39,904,284
<p>Since your question shows you haven't tried anything , guessing you know javascript and tried some hands on full calendar js.</p> <p>Suppose you have model named Event for displaying different events in calendar.</p> <pre><code>class Events(models.Model): even_id = models.AutoField(primary_key=True) event_name = models.CharField(max_length=255,null=True,blank=True) start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) event_type = models.CharField(max_length=10,null=True,blank=True) def __str__(self): return self.event_name </code></pre> <p>In your views.py </p> <pre><code>def event(request): all_events = Events.objects.all() get_event_types = Events.objects.only('event_type') # if filters applied then get parameter and filter based on condition else return object if request.GET: event_arr = [] if request.GET.get('event_type') == "all": all_events = Events.objects.all() else: all_events = Events.objects.filter(event_type__icontains=request.GET.get('event_type')) for i in all_events: event_sub_arr = {} event_sub_arr['title'] = i.event_name start_date = datetime.datetime.strptime(str(i.start_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") end_date = datetime.datetime.strptime(str(i.end_date.date()), "%Y-%m-%d").strftime("%Y-%m-%d") event_sub_arr['start'] = start_date event_sub_arr['end'] = end_date event_arr.append(event_sub_arr) return HttpResponse(json.dumps(event_arr)) context = { "events":all_events, "get_event_types":get_event_types, } return render(request,'admin/poll/event_management.html',context) </code></pre> <p>And finally in your template setup full calendar with including necessary CSS,JS Files and HTML code.And then ,</p> <pre><code>&lt;script&gt; $(document).ready(function() { $('#calendar').fullCalendar({ defaultDate: '2016-07-19', editable: true, eventLimit: true, // allow "more" link when too many events events: [ {% for i in events %} { title: "{{ i.event_name}}", start: '{{ i.start_date|date:"Y-m-d" }}', end: '{{ i.end_date|date:"Y-m-d" }}', }, {% endfor %} ] }); }); &lt;/script&gt; </code></pre> <p>Dynamically on some event you need to change events for example by changing dropdown you need to filter events ,</p> <pre><code>$(document).ready(function(){ $('.event_types').on('change',function(){ var event_type = $.trim($(this).val()); $.ajax({ url: "{% url 'manage-event' %}", type: 'GET', data:{"event_type":event_type}, cache: false, success: function (response) { var event_arr = $.parseJSON(response); $('#calendar').fullCalendar('removeEvents'); $('#calendar').fullCalendar('addEventSource', event_arr); $('#calendar').fullCalendar('rerenderEvents' ); }, error: function () { alert("error"); } }) }) }) </code></pre>
3
2016-10-06T19:34:49Z
[ "python", "django", "fullcalendar" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game. This is the code I have come up with:</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre> <p>Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again? How can I modify my code to fix these errors?</p>
1
2016-10-06T17:39:52Z
39,902,488
<p>You need to make guess equal to <code>True</code> in your second <code>else</code> or else it will never satisfy stop condition for while loop. Do you understand?</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" elif tries+1 != 3: print "Wrong guess! Try again." print "Your remaining tries are",(3-(tries+1)) tries = tries + 1 if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" guess= True again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" guess = False tries = 0 </code></pre> <p>EDIT: I think this does the trick using your code.</p>
1
2016-10-06T17:44:28Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game. This is the code I have come up with:</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre> <p>Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again? How can I modify my code to fix these errors?</p>
1
2016-10-06T17:39:52Z
39,902,495
<p>You need to update tries. Additionally you need to break out of your loop even if guess != True</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" break tries += 1 again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre>
0
2016-10-06T17:44:55Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game. This is the code I have come up with:</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre> <p>Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again? How can I modify my code to fix these errors?</p>
1
2016-10-06T17:39:52Z
39,902,501
<p>You need to move where you set guess = True</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: guess = True if inp == x: print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre> <p>Before you were only ending on the condition where the last guess was correct. You should be ending whether the guess was correct or not.</p>
1
2016-10-06T17:45:19Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a correct guess, you tell the user they are out of tries and tell them they lost. When the program finishes after a correct or 3 wrong tries and the game is over, you ask if the user wants to play again. If they say "yes", you star the game again and if they say "no", you end the game. This is the code I have come up with:</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": print "Okay thanks for playing!" elif again =="yes": print "Great!" </code></pre> <p>Now when you guess the correct number before 3 tries, the program seems to be working fine, but even when the number of wrong tries exceeds 3, the program keeps asking for more guesses but I want it to stop the program right there. The second thing I don't get is how do I start the whole game again when the user wants to play again? How can I modify my code to fix these errors?</p>
1
2016-10-06T17:39:52Z
39,902,534
<p>I guess this is it. Tested this out. Working Perfect (Y)</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 while guess != True: if tries&lt;=3: inp = input("Guess the number: ") if tries&lt;3: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! Try again." tries = tries + 1 print "Your remaining tries are",(3-tries) if tries&gt;2: if inp == x: guess = True print "Correct! You won" else: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": guess = True print "Okay thanks for playing!" elif again =="yes": tries = 0 print "Great!" </code></pre> <p>Hope this helps.</p> <p>Here's more compact code you can try. Also it is solving your "Wrong Guess. Try Again." issue on last guess.</p> <pre><code>import random x =round(random.random()*5) guess = False tries = 0 print x while guess != True: while tries&lt;3: inp = input("Guess the number: ") if inp == x: guess = True print "Correct! You won" break else: tries = tries + 1 if tries == 3: break print "Wrong guess! Try again." print "Your remaining tries are", (3 - tries) if not guess: print "Wrong guess! You are out of tries" print "Game Over!" again = raw_input("Do you want to play again? ") if again == "no": guess = True print "Okay thanks for playing!" elif again == "yes": tries = 0 if guess: guess = False x = round(random.random() * 5) print "Great!" </code></pre>
3
2016-10-06T17:47:24Z
[ "python", "python-2.7" ]