Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
4,200
37,112,149
How to read multiple specific lines from a txt file (python)
<h2>The question:</h2> <p>I am trying to have my program read multiple, specific lines from a text file. I have gotten to the stage where I am able to get the program to read multiple lines but I have to add them together and when printed they have '[],[]' around them.</p> <h2>Here is my current code:</h2> <pre><cod...
<p>If you want to read lines from a file you can use a for loop like so:</p> <pre><code>lines = [] for line in enumerate(open("solution.txt", "r")): lines.append(line) </code></pre> <p>This will create a tuple containing the line number (starting at zero) and the contents of that line, it will do this for every l...
python-3.x
0
4,201
36,896,660
Joining multiple dataframes and duplicate columns
<p>I'm sure i'm doing something wrong but it's not obvious to me.</p> <p>I have many dataframes which i want to join. I'm joining using pd.merge left joins i do this as</p> <pre><code>Database=pd.merge(df1, df2, left_on='key', Right_on='key',how='left') Database=pd.merge(df3, df4, left_on='key', Right_on='key',how='...
<p>I don't think you can avoid having the duplicates, at least not by means of using <code>pd.merge</code> with any arguments.</p> <p><code>pd.DataFrame.drop_duplicates()</code> seem to be working in dropping duplicate rows. That explains why you are transposing and the trying <code>drop_duplicates</code>. Might be an...
python|pandas
0
4,202
51,365,126
Combine 2 images with mask
<p>I am attempting to paint a logo over the top of a landscape image in OpenCV python. I have found answers that can 'blend'/watermark images but I don't want to make the logo transparent, I simply want to display the logo on top of the landscape image and keep the logo opacity (or lack thereof).</p> <p>I have tried b...
<p>I presume the following is what you had in mind.</p> <p><strong>Code:</strong></p> <pre><code>room = cv2.imread('room.JPG' ) logo = cv2.imread('logo.JPG' ) #--- Resizing the logo to the shape of room image --- logo = cv2.resize(logo, (room.shape[1], room.shape[0])) #--- Apply Otsu threshold to blue channel of th...
python|opencv
11
4,203
17,309,356
Getting twitter api to return search results instead of results summary
<p>I'm using requests to grab tweets from a geographically bounded area. When I try to print the results, I get what looks like the summary of the results rather than the results themselves. My code is:</p> <pre><code>from __future__ import unicode_literals import requests from requests_oauthlib import OAuth1 import p...
<p>Remove the spaces in your geocode parameter and it should return statuses:</p> <pre><code>query_params = { 'q': 'the', 'geocode': '33.520661,-86.80249,50mi' } </code></pre> <p>Also check out <a href="https://dev.twitter.com/console" rel="nofollow">the Twitter dev console</a> for te...
python|api|twitter
0
4,204
17,395,413
Python-unexpected behavior when I don't decode to utf-8
<p>I have the following function</p> <pre><code>import urllib.request def seek(): web = urllib.request.urlopen("http://wecloudforyou.com/") text = web.read().decode("utf8") return text texto = seek() print(texto) </code></pre> <p>When I decode to utf-8, I get the html code with indentation and carriage r...
<p>In Python 3, when you pass a byte value (raw bytes from the network without decoding) you get to see the <strong>representation</strong> of the byte value as a Python byte literal. This includes representing newlines as <code>\n</code> characters.</p> <p>By decoding, you now have a unicode string value instead, and...
python|utf-8|decode|urllib
2
4,205
17,670,985
Python: lambda function behavior with and without keyword arguments?
<p>I am using lambda functions for GUI programming with tkinter. Recently I got stuck when implementing buttons that open files:</p> <pre><code>self.file="" button = Button(conf_f, text="Tools opt.", command=lambda: tktb.helpers.openfile(self.file)) </code></pre> <p>As you see, I want to define a file path th...
<p>I'll try to explain it more in depth.</p> <p>If you do</p> <pre><code>i = 0 f = lambda: i </code></pre> <p>you create a function (lambda is essentially a function) which accesses its enclosing scope's <code>i</code> variable.</p> <p>Internally, it does so by having a so-called closure which contains the <code>i<...
python|lambda|tkinter
12
4,206
17,261,028
How do I make a pop up in Tkinter when a button is clicked?
<p>How do I make a pop-up in Tkinter when a button is clicked? When the 'About' button is clicked, I want a pop up with the disclaimer + about text. </p> <p>I have tried to set up a def method but it must be very wrong because it's not working as I would like. Any help would be very much appreciated.</p> <p>Thank you...
<p>If you want to display the text on a new window, then create a Toplevel widget and use it as the parent of the labels for the about text and the disclaimer.</p> <p>By the way, Tkinter variables are not necessary if you have static text, so in this case you can simply get rid of them and replace them with multiline ...
python|popup|tkinter
16
4,207
69,723,084
I wrote a line to display hello in pygamezero but instead its showing white blocks instead of texts
<p>i executed the following code</p> <pre class="lang-py prettyprint-override"><code>def draw(): screen.draw.text(&quot;hello&quot;, topleft=(10 , 10)) </code></pre> <p>but the output I get is just 5 white blocks instead of hello <a href="https://i.stack.imgur.com/cYB1J.png" rel="nofollow noreferrer">enter image de...
<p>The minimal <a href="https://pygame-zero.readthedocs.io/en/stable/" rel="nofollow noreferrer">Pygame Zero</a> script looks as follows:</p> <pre class="lang-py prettyprint-override"><code>import pgzrun def draw(): screen.clear() screen.draw.text(&quot;hello&quot;, topleft = (10, 10)) pgzrun.go() </code></pr...
python|pgzero
0
4,208
73,089,821
Property and method with the same name
<p>To simplify the problem, let's consider the following class</p> <pre><code>import numpy as np class MyClass: def __init__(self): self._time = np.ndarray([0, 1, 2, 3]) self._array = np.ndarray([0, 1, 2, 3]) @property def array(self): return self._array </code></pre> <p>so, wh...
<p>How about making vector optional:</p> <pre><code>class MyClass: def __init__(self): self._time = np.ndarray([0, 1, 2, 3]) self._array = np.ndarray([0, 1, 2, 3]) def array(self, vector=None): if not vector: return self._array return np.interp(vector, self._time, se...
python-3.x|methods|properties
0
4,209
55,645,161
How to change prediction threshold using Google AutoML?
<p>After creating Model in google AutoML we can use the provided python code to make a prediction. Here's the code : </p> <pre><code>import sys from google.cloud import automl_v1beta1 from google.cloud.automl_v1beta1.proto import service_pb2 def get_prediction(content, project_id, model_id): prediction_client = a...
<p>See the api documentation <a href="https://cloud.google.com/nodejs/docs/reference/automl/0.1.x/google.cloud.automl.v1beta1#.PredictRequest" rel="nofollow noreferrer">here</a> </p> <blockquote> <p>params</p> <p>Object with string properties</p> <p>Additional domain-specific parameters, any string must be...
python|automl|google-cloud-automl
4
4,210
73,324,659
How to save formsets in django
<p>I want to add multiple forms when a button is clicked and I am using formsets to accomplish that but when I try to save the forms it doesn't give an error bu does not save it either.</p> <p>my views.py:</p> <pre class="lang-py prettyprint-override"><code>def StepThreeView(request): formSet = modelformset_factory...
<p>You are missing the <code>action</code> attribute in your HTML. Also, I don't see the submit button anywhere.</p> <pre class="lang-html prettyprint-override"><code>&lt;form method=&quot;POST&quot; id=&quot;form&quot; action=&quot;{% url 'your-url-name-here' %}&quot;&gt; </code></pre>
python|django|django-views|django-forms|django-templates
0
4,211
73,291,760
Getting an incorrect output which is off by 1 - Min number of moves required to make all elements equal
<p>This is from <a href="https://leetcode.com/problems/minimum-moves-to-equal-array-elements/" rel="nofollow noreferrer">the leetcode question 453</a> which says :</p> <p>Given an integer array nums of size <code>n</code>, return the minimum number of moves required to make all array elements equal.</p> <p>In one move,...
<p>It looks like your algorithm doesn't handle duplicate maximums correctly. It fails for <code>[0,1,1]</code>, for example, which requires 2 moves to make all the elements the same.</p> <p>This problem doesn't require such a complicated algorithm. In terms of making all elements equal, <strong>incrementing n-1 eleme...
python|algorithm|math
2
4,212
73,221,615
Azure Batch OutputFiles upload from all compute nodes
<p>I have a mpi-based task, where each thread writes files on 'working-directory' for each compute node on Azure-Batch.</p> <p>The task is configured to upload result (files) to my storage account.</p> <p>But only the files on the master node are uploaded to storage.</p> <p>I want to know,</p> <p>how can I make all the...
<p>Currently, this is not possible. You have a few options:</p> <ol> <li>Use MPI primitives like gather/bcast/etc. to collect relevant data into a file that can be uploaded by the master task.</li> <li>Use <a href="https://docs.microsoft.com/rest/api/batchservice/file/get-from-compute-node" rel="nofollow noreferrer">Ge...
azure|azure-batch|azure-sdk-python
0
4,213
49,997,412
Fit of two different functions with boarder as fit parameter
<p>I have a question about a simple fit function in Python. I am trying to fit two different functions on a data set and the border between the two regimes should be also a fit parameter. Very naively I was trying something like this:</p> <pre><code>def FitFunc(x, a, b, c, d, e, border): if x &lt; border: ...
<p>The error message is saying that comparing the values of an array (<code>x</code>) with a scalar value (<code>border</code>) is ambiguous. Do you mean if <em>any</em> values of <code>x</code> are less than <code>border</code> or if <em>all</em> values of <code>x</code> are less than <code>border</code>? </p> <p>...
python|curve-fitting
2
4,214
49,968,025
Querying a database to pull up certain rows based on a variable
<p>I am trying to get the database to query and only show me one row which is determined by an if statement. I can't however get to that stage without first being able to get it to not take the first result it sees.</p> <pre><code>cursor.execute("SELECT password FROM testtable") rows = cursor.fetchone() for row in row...
<p>If it's just the second row you want, then call <code>fetchone</code> twice.</p> <pre><code>cursor.execute("SELECT password FROM testtable") row2 = cursor.fetchone() and curse.fetchone() </code></pre> <p>We're taking advantage of the fact that <code>cursor</code> is like a pointer that points to the <code>ResultSe...
python|mysql|python-3.x
1
4,215
53,008,222
python qrcode decode getting output?
<p>Hi there i have managed to create a qr code and then read it again. However on reading it i get lots of extra information that i do not want such as the width and hieght of the qr code image that was decoded. How do i just get the first part of the result?</p> <p>My code :</p> <pre><code>from PIL import Image from...
<p><code>decode()</code> returns a list of <code>Decoded</code> objects, so I would simply try this:</p> <pre><code>decoded_list = decode(Image.open('test1.png')) print(decoded_list[0].data) </code></pre> <p>I renamed your "<code>data</code>" variable to avoid confusion with the <code>data</code> attribute of a <code...
python|qr-code
0
4,216
68,538,520
I cannot use pyinstaller to pack , The Error is "RuntimeError: No metadata path found for distribution 'greenlet'."
<p>I don't know how to solve &quot;RuntimeError: No metadata path found for distribution 'greenlet'.&quot; I have searched my code for 'greenlet', but I didn't import the module. my pyinstaller version is 4.4, PyQt5 version is 5.15.4. The modules imported are pandas, PyQt5, os, sys, configparser, json, selenium, time</...
<p>I just started working on pyinstaller and immediately ran into this error. As a result of my efforts, I solved the problem with the following command.</p> <pre><code>pip install --ignore-installed greenlet </code></pre> <p>If you encounter a <em>check_exists</em> error, input the value <em>True</em> to the <em>sysc...
python-3.x|pyinstaller
2
4,217
71,630,170
How to change URL for beautifulsoup scraper every time the program runs (without doing it manually)?
<p>I have the following code to scrape Reddit usernames:</p> <pre><code> from bs4 import BeautifulSoup from requests import get from fake_useragent import UserAgent ua = UserAgent() def lovely_soup(u): r = get(u, headers={'User-Agent': ua.chrome}) return BeautifulSoup(r...
<p>I would recommend iterating over the urls, for example you could do the following:</p> <pre><code>for url in urls: soup = lovely_soup(url) titles = soup.findAll('a', {'class': 'author'}) for title in titles: print(title.text) </code></pre> <p>Where urls is your list of all the urls e.g. [&quot;w...
python|python-3.x|beautifulsoup|python-requests
1
4,218
61,773,160
Sorting and ranking subsets of complex data
<p>I have a large and complex GIS-datafile on road accidents in “cities" within “counties”. Rows represent roads. Columns provide “City”, “County” and "Sum of accidents in city”. A city thus contains several roads (repeated values of accident sums) and a county several cities. For each 'County', I now want to rank cit...
<p>I think the approach by @DarryIG is correct, but it doesn't consider that the environment is ArcGIS. </p> <p>Since you tagged your question with <code>Python</code> I came up with a workflow utilizing Pandas. There are other ways to do the same, using ArcGIS tools and or the Field Calculator.</p> <pre class="lang-...
python|subset|arcgis|ranking
0
4,219
67,488,244
Select a button with selenium with same XPATH but no tag or id
<p>I would like to select a button with selenium on the net, here's the HTML code of the button:</p> <pre><code>&lt;button type=&quot;button&quot; ng-if=&quot;grid.appScope.edit_column&quot; ng-click=&quot;grid.appScope.executeActionButtonEvent(row, grid.appScope.edit_column, grid['options'])&quot; class=&quot;btn btn-...
<p>In case the <code>ng-click</code> attribute inside those buttons value is unique for each element you can use something like this:<br /> <code>//button[contains(@ng-click.'grid.appScope.executeActionButtonEvent(row, grid.appScope.edit_column, grid['options'])')]</code> or any unique part of <code>grid.appScope.execu...
python|html|selenium|google-chrome|webdriver
2
4,220
70,192,640
Sorting a dictionary by values, using a class-provided sort key
<p>I'm using a class with multiple members. This class offers a method which returns a sort key: a tuple defining how instances should be sorted. I have a dictionary where the values are instances of this class, indexed by an integer identifier.</p> <pre><code>class Dog: def __init__(self, name: str, age: int): ...
<p>I discovered that <code>sorted()</code> was not returning the key but instead a <code>(key, value)</code> tuple (which, in hindsight, makes more sense).</p> <p>The following achieved my goal:</p> <pre><code>result = {i[0]: i[1] for i in sorted(unsorted.items(), key=lambda i: i[1].sort_key())} </code></pre>
python-3.x|dictionary|lambda
0
4,221
63,482,555
How to control audio playback in a Raspberry Pi?
<p>I am building a Telegram bot installed on my Raspberry Pi that will perform multiple functions. One of those is to play/pause/stop a 10-hours mp3 file in the Raspberry. So what I need is to control the audio playback with telegram messages.</p> <p>To simplify it, I can save some instructions into a .txt file, and an...
<p>I would suggest going with <a href="https://wiki.videolan.org/Python_bindings" rel="nofollow noreferrer">VLC</a></p> <pre><code>pip install python-vlc </code></pre> <p>And then simply:</p> <pre><code>import vlc from time import sleep p = vlc.MediaPlayer(audio_file_path) p.play() sleep(2) p.pause() sleep(2) p.play()...
python|python-3.x|audio|raspberry-pi|playback
2
4,222
68,927,809
I compare two identical sentences with RIBES NLTK and get an error. Why?
<p>I’m trying to use RIBES score from NLTK for quality evaluation of the machine translation. I wanted to check this code with two identical sentences. But when I’m running my code I get errors.</p> <p>My code:</p> <pre><code>from nltk.translate.ribes_score import sentence_ribes hyp1 = ['It', 'is', 'a', 'guide', 'to',...
<p>You're getting to a division by zero on this line:</p> <pre><code>tau = 2 * num_increasing_pairs / num_possible_pairs - 1 </code></pre> <p>This is because <code>num_possible_pairs</code> is 0 when <code>len(worder)</code> is 1. All of this is because you're calling <code>sentence_ribes</code> with two lists, when th...
python|nltk|metrics|machine-translation
1
4,223
58,652,106
Where to place supplementary files for a python package?
<p>I am working on developing a python package to simplify SOAP communications to Cisco Unified Communications Manager's AXL API. CUCM does not allow access of the WSDL directly via URL, instead, the WSDL must be downloaded locally. Instead of having to download the WSDL on each machine that I install my package on, I ...
<p>don't use <code>os.getcwd()</code></p> <p>determine the path of your module by looking at <code>__file__</code></p> <p>and in <code>test_axl_connection.py</code></p> <pre><code>import os MYPATH = os.path.realpath(os.path.dirname(__file__)) def wsdl(): os.startfile(os.path.join(MYPATH, 'axlsqltoolkit')) </co...
python|package|cucm
1
4,224
59,577,407
Uncaught (in promise) DOMException: Failed to execute 'texImage2D' on 'WebGL2RenderingContext': Tainted canvases may not be loaded
<pre><code>''' &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;!-- Load TensorFlow.js --&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"&gt;&lt;/script&gt; &lt;!-- Load Posenet --&gt; &lt;script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/posenet"&gt;&lt;/script&gt; &lt;/head&g...
<p><code>crossorigin='anonymous'</code> needs to be added to the image tag</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;meta charset="UT...
javascript|html|google-chrome|firefox|tensorflow.js
21
4,225
59,740,821
Pygame window is really laggy
<p>The pygame window gets really laggy when i try to run it. I have 132 lines of code so far and i have loads more stuff to add. While test-running i noticed that the game satrted lagging when i added the following bits of code in</p> <pre><code>class Game: def __init__(self): self.win = pygame.dis...
<p>I figured it out. Its because my <code>pygame.time.Clock().tick(60)</code> was in the game loop. Not sure why this was causing lag but for anyone who might be having the same issue, dont put it in the main loop.</p>
python|pygame|lag
1
4,226
59,971,848
Link in template for routers of rest_framework
<p>I set rest_framework and have the page named <code>api</code></p> <pre><code>from . import views from rest_framework import routers from django.conf.urls import url from django.conf.urls import include router = routers.DefaultRouter() router.register(r'genres', GenreViewSet) router.register(r'blogs',BlogViewSet) ...
<p>You can't set the <code>name</code> attribute on "included" paths.<br> But you can set the <code>namespace</code> attribute to access the included views with:<br> <code>{% url 'namespace:url_name' %}</code></p>
python|django|django-rest-framework
1
4,227
67,970,599
Zero out all x-values for specific time values: t > t0
<p>I use a data set called: <code>arr0</code> with dimensions: <code>(x, y, t) = (151, 151, 600)</code>. To create a 2D image I took a specific y-coordinate with slicing i.e. <code>arr0[:,0]</code>, now the dimensions are: <code>(x, t) = (151, 600)</code>. Within the dataset <code>arr0[:,0]</code> there are x-values f...
<p>If I understand you correctly, we can regard <code>x, y, t</code> as index variables along the axes of your 3-dimensional array, which contains the actual data values (represented by grayscale pixels in the plot). Here is a simplified example:</p> <pre class="lang-py prettyprint-override"><code>import numpy as np im...
python|physics
1
4,228
45,448,791
Appending zeroth element to a list, then iterating while appending the rest
<pre><code>a = [] a.append(0.99) for i in range(5): a[i+1] = a[i] * ((1+((d*c)/2))/(1-((d*c)/2))) a.append(a[i+1]) </code></pre> <p><code>IndexError: list index out of range</code> coming from the fourth line. </p> <p>I've tried a hand full of different methods, but can't seem to get it right. The output sho...
<p>When you create a list in python you can't access indices that don't have values yet (even if you want to assign them) unless you use <code>.append()</code>, and that is why you are getting index error. A work around for that is to have <code>None</code> values of the size you want or <code>0</code> values, for exam...
python
0
4,229
23,482,395
Ubuntu Varnish mobile detection results in to page not found?
<p>I am trying this example to do mobile device detection using varnish <a href="https://github.com/varnish/varnish-devicedetect/blob/master/INSTALL.rst" rel="nofollow">https://github.com/varnish/varnish-devicedetect/blob/master/INSTALL.rst</a></p> <p>I implemented Example 1 and now trying to test it via the testing t...
<p>for people coming on this page searching how to serve for different devices using varnish . other than varnish-devicedetect you can also try a different solution .</p> <p>try this tutorial from <a href="http://spin.atomicobject.com/2013/02/11/varnish-cache-mobile-devices/" rel="nofollow">atomic object</a></p> <p>t...
python|caching|ubuntu|amazon-web-services|varnish
0
4,230
46,200,015
Grammar Game (Python) not working, how do I fix it?
<p>I am working on a grammar game (Python), but it is not working. How do I fix it? Code:</p> <pre><code>print("Welcome! Type in 'Enter' (without apostrophes) to begin") start = input if start == "Enter": print "Fill in the blanks: I __ a boy" answer = input if answer != "am": print "Wrong answer! Try again: I __ a ...
<p>You aren't actually getting any input from the user, when you write <code>start = input</code> you are setting the variable start equal to the builtin function input. To actually get input you need to use <code>start = input(prompt)</code> like shown <a href="https://docs.python.org/2/library/functions.html#input" r...
python|python-2.7
2
4,231
31,182,311
add defaults configuration in odoo
<p>I wanna set default configuration Say in purchases I wanna ( Use 'Real Price' or 'Average' costing methods.) checked by default and in sales configuration i want ( Generate invoices after and based on delivery orders) to be check Using custom modules.</p>
<p>You can do it creating a new module using a <code>osv.osv_memory</code> model. Take a look at my <a href="https://stackoverflow.com/questions/31162964/how-to-change-settings-on-module-installation/31199994">question</a> and the <a href="https://www.odoo.com/es_ES/forum/help-1/question/how-to-change-settings-on-modul...
python|odoo-8
0
4,232
29,022,307
generator that does not necessarily yield anything
<p>I want to have a generator that may or may not have anything to yield, and if <code>.next()</code> or similar is used it will not have a <code>StopIteration</code> error if none of the conditions to yield are met.</p> <p>An example:</p> <pre><code>def A(iterable): for x in iterable: if x == 1: ...
<p>generally, in these circumstances you'd use the builtin <code>next</code> function:</p> <pre><code>my_iterator = A([2]) value = next(my_iterator, None) </code></pre> <p>In addition to being able to pass an optional "default" value when the iterator is empty, <code>next</code> has the advantage of working on python...
python
2
4,233
52,420,615
Extract data from web page using CSS selector - Selenium Python
<p>I want to extract some dates from Dell's website in my interest for my devices. I tried to download the webpages using <code>urllib</code> but it's protected by captcha and I can't bypass that for now. Now I am using Selenium to open a browser, solve manually the capthca and then automatically opening the pages and ...
<p>Looking at the API documentation, the <code>find_element_by_css_selector</code> function returns a <code>WebElement</code> object. See <a href="https://selenium-python.readthedocs.io/api.html" rel="nofollow noreferrer">https://selenium-python.readthedocs.io/api.html</a>.</p> <p>The web elements content needs to be ...
python|selenium|selenium-chromedriver
1
4,234
19,559,708
Groupby the list according to category
<p>my code gives me output as a list</p> <pre><code>def extractKeywords(): &lt;code&gt; return list list = [] data = extractKeywords() for x in range(0,5): get = data[0][x] list.append(get) print list12 </code></pre> <p>Output list is </p> <pre><code>['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer',...
<p>This solution uses itertools.groupby to avoid traversing the list twice.</p> <pre><code>&gt;&gt;&gt; from itertools import groupby &gt;&gt;&gt; data = ['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer','ELEPHANT'] &gt;&gt;&gt; # upper case letters have lower `ord` values than lower case letters &gt;&gt;&gt; sort_by_ca...
python|list|split|group-by|categories
2
4,235
54,365,784
No text is returned when pypdf2 is used to scrape a one paged pdf
<p>I have downloaded a bunch of pdfs from this source: '<a href="http://ec.europa.eu/growth/tools-databases/cosing/index.cfm?fuseaction=search.detailsPDF_v2&amp;id=28157" rel="nofollow noreferrer">http://ec.europa.eu/growth/tools-databases/cosing/index.cfm?fuseaction=search.detailsPDF_v2&amp;id=28157</a></p> <p>Now I ...
<p><a href="https://github.com/mstamy2/PyPDF2/issues/437" rel="nofollow noreferrer">This is because PyPDF2 is a inconsistent <strong>scraper</strong> </a>. You have to remember that not all pdfs are built the same, so based on the structure that the pdf was built PyPDF2 may or may not be able to <strong>scrape</strong>...
python|pdf-scraping
0
4,236
33,974,951
How to make sets of iterators
<p>I want to iterate over a certain range and create several sets that contain only the current i. (In the code I don't want to do this for every i, but it's about the general principle).</p> <pre><code>for i in range(5): s=set(i) print(s) </code></pre> <p>It says int object is not iterable. Why doesn't this ...
<p>Set constructor <code>set(x)</code> requires <code>x</code> to be some container, like a list, or other set. You pass an integer, python tries to iterate over it, and fails. </p> <p>In order to do so you need to pass a singleton of x, like that:</p> <pre><code>for i in range(5): s = set([i]) # or s = set((i,)) ...
python|python-3.x
1
4,237
43,975,314
get index column error from dataframe from
<p>I simply want to get index column.</p> <pre><code>import pandas as pd df1=pd.read_csv(path1, index_col='ID') df1.head() VAR1 VAR2 VAR3 OUTCOME ID 28677 28 1 0.0 0 27170 59 1 0.0 1 39245 65 1 0.0 1 31880 19 1 0.0 0 41441 24 1 0.0 ...
<p>First column is <code>index</code> so for select use:</p> <pre><code>print (df1.index) Int64Index([28677, 27170, 39245, 31880, 41441], dtype='int64', name='ID') </code></pre> <p>But if possible <code>MultiIndex</code> in <code>index</code> use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.I...
python|pandas|dataframe
1
4,238
47,234,640
How to convert this loops to python 3 from c language?
<p>This is in c language</p> <p>What is the condition should I put in python 3 </p> <pre><code>for (row=0; row&lt;4; row++) { for (col = 4; col &gt; row; col--) { printf(" "); } for (col =0; col&lt;=row; row++) { printf("*"); } } printf("\n"); </code></pre>
<pre><code>for row in range(4): for col in range(4,1,1): print(" ",end="") for col in range(row+1): print("*",end="") print("\n") </code></pre> <p>You should read the python manual.</p> <p>I am exactly translating the code with two knowledge: <code>range()</code>,<code>print()</code> and f...
c|python-3.x
3
4,239
46,686,946
Using keys to toggle functions in OpenCV- Python
<p>I am running into thread error : QObject::moveToThread: Current thread (0x7c2d90) is not the object's thread (0xcc44d0). Cannot move to target thread (0x7c2d90)</p> <p>while trying to run the below program. when i take off the last two lines, it doesn't give me this error. Can anybody tell why this is happening?</p...
<p>I was using Anaconda package , now i switched to python 2.7 distribution and the error is gone. </p>
python|opencv|opencv-python
0
4,240
55,721,913
How to write a list in one excel cell using python
<p>this is my list</p> <pre><code>list=['a','b','c'] </code></pre> <p>when using this code </p> <pre><code>with open('commentafterlink.csv', 'w') as f: f.write("%s\n" % list) </code></pre> <p>it stores each token of list in a one cell but i need to store whole list in one cell.where is the problem?</p>
<p>Can you try the following:</p> <pre><code>import xlwt from xlwt import Workbook # Workbook is created wb = Workbook() # add_sheet is used to create sheet. sheet1 = wb.add_sheet('Sheet 1') # sheet1.write(1, 0, ' '.join(list)) # if you want the output to be ['a','b','c'] sheet1.write(1, 0, str(list)) wb.save...
python|excel|python-3.x
1
4,241
55,713,445
Pandas Find Date Frequency
<p>I have a dataset: </p> <pre><code> login id 0 2015-06-22 04:55:00 1 1 2015-06-23 05:55:00 1 2 2015-06-25 04:55:00 2 3 2015-06-26 02:55:00 2 4 2015-07-02 04:55:00 2 5 2015-07-12 04:55:00 3 6 2015-07-13 04:55:00 3 7 2015-07-15 04:55:00 5 8 2015-07-21 04:55:00 5 9...
<p>Here's a multiple-step approach:</p> <pre><code>df['last_log'] = df.groupby('id').login.shift().fillna(pd.to_datetime(0)) df['duration'] = df.login - df.last_log # good ids df.id[(df['duration'] &lt;= pd.Timedelta(1, 'd'))].unique() # output: array([2, 3, 5], dtype=int64) </code></pre>
python|pandas
2
4,242
66,643,615
Python Numpy Linspace function for bidimensional array
<p>I know it is possible to create numpy arrays using the Linspace function. For example, given a range [x,y] I can make a vector of z elements equally distanced in [x,y]</p> <p>v = np.linspace(x, y, z, retstep=True)</p> <p>What if one needs more dimensions? Is it possible to use the same function to generate a 3x4 arr...
<p>You can use arrays for start and stop point of linspace:</p> <pre><code>x=np.linspace((0,0,0), (3,5,14), 4, axis=1) print(x) </code></pre> <p>This will give the output:</p> <pre><code>[[ 0. 1. 2. 3. ] [ 0. 1.66666667 3.33333333 5. ] [ 0. 4.66666667 9.33...
python|arrays|numpy|anaconda3
0
4,243
66,668,026
not able to import selenium, even though I have python and pip installed in vscode
<p>Even though I have Python installed and can confirm it in the command prompt. <a href="https://i.stack.imgur.com/4YUHZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4YUHZ.png" alt="enter image description here" /></a></p> <p>VSCode also shows the python installed</p> <p><a href="https://i.stack....
<p>Please refer to the following to check the installation of the module &quot;selenium&quot;:</p> <ol> <li><p>Please use the command &quot;<code>pip --version</code>&quot; to check whether the source of the module installation tool &quot;pip&quot; is the same as the python displayed in the lower left corner of VS Code...
python|selenium|selenium-webdriver|visual-studio-code
0
4,244
66,508,089
How can I group the numbers by 5?
<pre><code>def num (): num = int (input(&quot;Enter a number: &quot;) ) while num in range (num &gt;= 0,100) : num += 1 print (num, end = &quot; &quot;) num () </code></pre> <p>My problem is I don't know how to group it into 5 (for e.g. 1 2 3 4 5 and the next line is 6 7 8 9 10). 5 numbers each...
<p>Here is a variation:</p> <pre><code>num = int (input(&quot;Enter a number: &quot;) ) l = list(range(num,100)) for i in range(0, len(l),5): print(&quot; &quot;.join(map(str, l[i:i+5]))) </code></pre> <p>We take sublists of size 5 (or less for the last one if necesarry) and use <code>join</code> to create a string...
python
3
4,245
64,970,861
Error try to install azure-cognitiveservices-speech==1.13.0 in python environment
<p>I have a problem when I try to install azure-cognitiveservices-speech on my Python environment</p> <p>When I run the command:</p> <pre><code>pip install azure-cognitiveservices-speech==1.13.0 </code></pre> <p>The next message is shown:</p> <pre><code>ERROR: Could not find a version that satisfies the requirement azu...
<p>Ah !</p> <p>Currently the SPEECH SDK is supported in Python 3.5 to 3.8, hence the error. ( &amp; 64 bit)</p> <p><a href="https://i.stack.imgur.com/QnHxr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QnHxr.png" alt="enter image description here" /></a></p> <p>Reference :</p> <p><a href="https:/...
python|azure-cognitive-services
1
4,246
63,762,450
scrapy xpath : get all the inner text inside an element
<p>I am trying to get all the text inside the span tag. But instead of getting 2 elements, I am getting 4.</p> <pre><code>&lt;div class=&quot;col-sm-6 col-md-7&quot;&gt; &lt;ul&gt; &lt;li&gt; &lt;span style=&quot;font-family: Verdana, sans-serif; font-size: 10pt;&quot; class=&quot;text-black&quot;&gt; ...
<p>It happened because text data separated by <code>&lt;b&gt;</code> tags.</p> <p>In your case following steps needed:</p> <pre><code>data = [] # separately select span tags: for span_tag in response.xpath(&quot;.//div[@class='col-sm-6 col-md-7']//ul/li//span&quot;): # for each span tag add it's text as single string: ...
python|html|web-scraping|scrapy
1
4,247
68,669,247
read all files in sub folder with pandas
<p>My notebook is in the home folder where I also have another folder &quot;<strong>test</strong>&quot;. In the <strong>test</strong> folder, I have 5 sub folders. Each of the folder contains a .shp file. I want to iterate in all sub folders within test and open all .shp files. It doesn't matter if they get overwritten...
<p>you can use the os.walk method in the os library.</p> <pre><code>import os import pandas as pd for root, dirs, files in os.walk(&quot;./test&quot;): for name in files: fpath = os.path.join(root, name) data = pd.read_file(fpath) </code></pre>
python|python-3.x|dataframe|data-analysis|python-os
3
4,248
5,148,589
Python urllib over TOR?
<p>Sample code:</p> <pre><code>#!/usr/bin/python import socks import socket import urllib2 socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4, "127.0.0.1", 9050, True) socket.socket = socks.socksocket print urllib2.urlopen("http://almien.co.uk/m/tools/net/ip/").read() </code></pre> <p>TOR is running a SOCKS proxy on por...
<p>The problem is that <code>httplib.HTTPConnection</code> uses the <code>socket</code> module's <a href="http://docs.python.org/2/library/socket.html#socket.create_connection"><code>create_connection</code></a> helper function which does the DNS request via the usual <code>getaddrinfo</code> method before connecting t...
python|urllib2|socks|tor
21
4,249
61,943,614
How to fit text inside bounding box?
<p>I have extracted some text using Google vision api. Now the idea is to plot the text on a file using the coordinate and dimensional information from the bounding box. </p> <p>I have the position and the height and width of the bounding box. Now I need to fit the text inside the box. I am not able to obtain the corr...
<p>You could increase the font size as long as its height is less or equal to the bounding box height:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>fitTextInsideBox(documen...
javascript|python|html|css|computer-vision
0
4,250
61,635,384
Convert "0" and "1" strings in a multi-level list to integers
<p>I have a 3 level list of strings and need to convert the "0" and "1" strings into integers. I tried it like this but I am not getting the wanted result</p> <pre><code>for list in a: for sublist in list: for item in sublist: if item == "0" or item == "1": item == int(item)...
<p>You have to assign the converted item back to the original sub-sub list. All you have done so far is assign it to a temporary variable that gets overwritten on the next iteration. </p> <p>Also, try to avoid using <code>list</code> as a variable.</p> <p>Try this:</p> <pre><code>for sublist in a: for subsublist...
python
3
4,251
67,575,423
Problems with requests Python 3 retrieving an excel file from a WP site
<p>Here's my problem, I am trying to download excel xlsx files from a WP site, if I type</p> <p>the url I assigned to a variable in my code, called stock, directly in browser, Firefox downloads it perfectly.</p> <p>I'm trying to do this with Python so I've made a script using requests and then Pandas for processing and...
<p>You can't pass <code>output</code> to <code>pd.read_excel()</code>, because when the <code>with</code> context manager exits, the reference to the file (<code>output</code>) is destroyed. One option here, if you don't <em>really</em> need to save the Excel file for anything else, is to pass <code>resp.content</code>...
python|pandas|python-requests
1
4,252
60,559,429
Unable to read e-mails from Outlook for last 1 hour with Python
<p>I am trying to read emails from my outlook for last 1 hour. I have used the below code. here i am not getting any error but it is not giving me any output.</p> <pre class="lang-py prettyprint-override"><code>import win32com.client import datetime as dt import pandas as pd date_time = dt.datetime.now() lastHourDat...
<p>Change <code>%y</code> to <code>%Y</code> at line below.</p> <pre class="lang-py prettyprint-override"><code>lastHourMessages = messages.Restrict("[ReceivedTime] &gt;= '" + lastHourDateTime.strftime('%m/%d/%y %H:%M %p') + "'") </code></pre> <hr> <p>Just to be sure, correct is</p> <pre class="lang-py prettyprint-...
python|outlook|win32com
1
4,253
71,234,651
Keep part of string based on certain characters in a DataFrame column
<p>I know there have been a lot of questions around this topic but I didn't find any that described my problem. I have a <code>df</code>, with a specific column that looks like this:</p> <pre><code>colA ['drinks/coke/diet', 'food/spaghetti'] ['drinks/water', 'drinks/tea', 'drinks/coke', 'food/pizza'] ['drinks/coke/d...
<p>You could split on comma and <code>explode</code> to create a Series. Then use <code>str.contains</code> to create a boolean mask that you could use to filter the items that contain the word &quot;coke&quot;. Finally <code>join</code> the strings back across indices:</p> <pre><code>s = df['colA'].str.split(',').expl...
python|pandas|string|dataframe|lambda
1
4,254
71,116,760
What does `mode='c'` do in numpy.ndarray[..., mode='c'] do?
<p>I am modifying <a href="https://github.com/sagemath/sage/blob/develop/src/sage/plot/complex_plot.pyx" rel="nofollow noreferrer">cython code</a> that makes plots of complex-valued functions. This code includes something equivalent to the following:</p> <pre class="lang-py prettyprint-override"><code>cimport numpy as ...
<p>Argument <code>mode</code> maps to Python's <a href="https://docs.python.org/3/c-api/buffer.html#shape-strides-suboffsets" rel="nofollow noreferrer">buffer protocol's flags</a>:</p> <ul> <li><code>&quot;c&quot;</code> means <code>PyBUF_C_CONTIGUOUS</code></li> <li><code>&quot;fortran&quot;</code> means <code>PyBUF_F...
python|cython|numpy-ndarray
2
4,255
71,441,522
Global variable not being referenced for inner scope declaration in Python
<p>Python is declaring a variable that is already in the global scope. The code below creates an exception: &quot;local variable 'OLDTOTALNUMPASSED' referenced before assignment&quot;</p> <pre><code>#THIS CREATES AN EXCEPTION class Main(): global OLDTOTALNUMPASSED global OLDTOTALNUMFAILED global OLDRUNNINGC...
<p>Turns out, the variable Needs to be global in both the foo_bar() as well as the class. If it is not global in either the class or the function it does not work.</p> <pre><code>#THIS PASSES class Main(): global OLDTOTALNUMPASSED global OLDTOTALNUMFAILED global OLDRUNNINGCONSECUTIVEFAILURES OLDTOTALNUMPASSED = 0 OLDTO...
python|global|declaration|scoping
0
4,256
64,528,842
Python Discord, connect as an user
<p>So i try to make a selfbot (on my own server) who connect with a real account</p> <pre><code>import discord import asyncio client = discord.Client() @client.event async def on_ready(): print(client.servers) if __name__ == '__main__': email = input(&quot;Enter email: &quot;) password = input(&quot;Ente...
<p>Now i have my token i've an error <code>discord.errors.LoginFailure: Improper token has been passed.</code></p> <p>And i'm pretty sure that my token is correct</p>
python|discord|bots
0
4,257
11,377,888
Lifetime of a variable in python
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">&ldquo;Least Astonishment&rdquo; in Python: The Mutable Default Argument</a> </p> </blockquote> <p>Consider the following two functions</p> <p...
<p>Those defaults are, just as you said, evaluated only once, when the function is declared. That's why it's never a good idea to assign a list or hash literal as a default value, because you'll only get one instance for all function calls.</p> <p>That problem is described <a href="http://www.deadlybloodyserious.com/2...
python|variables|lifetime
2
4,258
63,321,409
Scrapy: Can't Crawling App store Reviews Page
<p>Hi guys I'm having some issues to get data from this page from app store: <a href="https://apps.apple.com/us/app/mathy-cool-math-learner-games/id1476596747#see-all/reviews" rel="nofollow noreferrer">app store reviews</a><a href="https://apps.apple.com/us/app/mathy-cool-math-learner-games/id1476596747#see-all/reviews...
<h2> The Problem </h2> <p>The top three reviews are loaded as part of the HTML but the rest are loaded by javascript. Which is why you're only getting the first three results.</p> <p>I'm not entirely sure whether this is the whole code you have for using scrapy. I'd be interested in why you choose that part of scrapy.<...
python|ios|web-scraping|scrapy|app-store
8
4,259
63,334,726
Remove square brackets and parenthesis from values?
<p>I have this code:</p> <pre><code>val_list = [] val_list_y = [] val_list_df = pd.DataFrame([]) for img in os.listdir(exa_test_dir): val_list.append(exa_test_dir +img) img_name = img.split('.')[0] val_list_y.append(val_df[val_df['filename_seconds']==img_name]['birds'].values) val_list_df['image'] = val_l...
<p>Try joining the values before each append to remove the square (list) brackets:</p> <pre><code>val_list_y.append(' '.join(val_df[val_df['filename_seconds']==img_name]['birds'].astype(str).values)) </code></pre>
python|pandas
1
4,260
63,572,878
To calculate maths operation in a column using pandas
<p>I would like to use python to get final values for maths operation in a column of a CSV file, may I know is it possible to get the value as below?</p> <p>Original CSV:</p> <pre><code>Type Total A 2+2 B (10/2)*5 C 5-2*3 </code></pre> <p>Expected Output:</p> <pre><code>Type Total A 4 B 25 C -1 </code...
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.eval.html" rel="nofollow noreferrer"><code>pandas.eval</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.apply.html" rel="nofollow noreferrer"><code>Series.apply</code></a>:</p> <pre><code>df[...
python|pandas|math|calculation|operation
2
4,261
56,715,786
Problem while solving question in infytq app
<p>The problem is even the calculator should the answer write but it is wrong in the website.</p> <h1>The problem Statement</h1> <p>ARS Gems Store sells different varieties of gems to its customers.</p> <p>Write a Python program to calculate the bill amount to be paid by a customer based on the list of gems and quantit...
<p>I think the best way to "match" the amount to the price of the same gem, is to create two dictionaries based on the corresponding lists.</p> <p>try this:</p> <pre class="lang-py prettyprint-override"><code>def calculate_bill_amount(gems_list, price_list, reqd_gems, reqd_quantity): price_dict = {gems_list[i]: p...
python|list
0
4,262
17,812,786
How can I include additional tests if a test passes?
<p>I'm using <code>nose</code> to run some system tests, one of which is to test whether a (config) file exists. If this file exists, I'd like to run some additional tests on it. If not, I'd like to skip a bunch of tests.</p> <p>What's the best approach to take to make <code>nose</code> include the additional tests if...
<p>You could use skipTest from the setUp method in your specific TestCase, like:</p> <pre><code>import os from unittest import TestCase class MyTest(TestCase): def setUp(self): if not os.path.exists('configfile'): return self.skipTest('config file not found') def test01(self): # D...
python|unit-testing|nose|system-testing
5
4,263
17,691,009
OpenCV Perspective Transform giving unexpected result
<p>I am trying to transform from a trapezoid (in the first image) to a rectangle (in the second image), but getting a strange result (in the third image).</p> <p><img src="https://i.stack.imgur.com/h3Id7.png" alt="enter image description here"></p> <p>My plan was to use a perspective transform, defined by the four co...
<p>Your methodology is correct. The problem arises when you specify the coordinates of your corner points. I don't know how you calculated them, but you have swapped your X and Y axes. This is reflected in the transformation applied to your final image. I find the corner points to be:</p> <pre><code>ptsTrap = [[[ 99....
python|opencv|transformation
8
4,264
66,141,589
Hiding facet row or column headers
<p>How can I hide the row (or column) header labels in a facet chart?</p> <p>I rotated the labels by 45 degrees in the following example (<a href="https://stackoverflow.com/questions/52360965/change-facet-title-position-in-altair:">copied from this post</a>) to highlight which ones I mean, the year numbers:</p> <pre><c...
<p>Another way to do this is to turn off the labels by setting <code>labels=False</code>:</p> <pre><code>header=alt.Header(labels=False) </code></pre>
python|charts|altair
3
4,265
69,230,706
Recovery by MQTT client for MQTT server failure/restart
<p>I have a long-running paho-MQTT (Python 3) client. The client is listen-only - it subscribes to topics and acts on those inputs but it does not publish. Everything runs fine until the server becomes unresponsive (server restart or network transport failure); at that point it becomes unresponsive since the connecti...
<p>As described in the Paho Python <a href="https://www.eclipse.org/paho/index.php?page=clients/python/docs/index.php#on-disconnect" rel="nofollow noreferrer">docs</a></p> <blockquote> <p><strong>on_disconnect()</strong></p> <p><code>on_disconnect(client, userdata, rc)</code></p> <p>Called when the client disconnects f...
python-3.x|mqtt|paho
0
4,266
68,935,034
django mongodb connections by using djongo and pymongo
<p>Can I use djongo to connect with Mongodb database and for complex queries i want to use Pymongo in my django project. please let me now if it is possible.</p> <p>As I wanted to do fulltext search in my project which is possible by pymongo.</p> <p>''' details = collection_name.find({&quot;$text&quot;: {&quot;$search&...
<p>Yes, it's possible. In my project I do it using <code>mongoengine</code> as below code in <code>settings.py</code></p> <pre><code>from mongoengine import connect MONGO_DATABASE_NAME = '&lt;database_name&gt;' MONGO_HOST = 'mongodb://&lt;host_name&gt;' MONGO_PORT = &lt;port_no.&gt; connect(MONGO_DATABASE_NAME, host=MO...
python|django|mongodb|pymongo|djongo
1
4,267
72,813,077
Can I insert a table name by using a query parameter?
<p>I have an SQL Alchemy engine where I try to insert parameters via sqlalchemy.sql.text to protect against SQL injection.</p> <p>The following code works, where I code variables for the condition and conditions values.</p> <pre><code>from sqlalchemy import create_engine from sqlalchemy.sql import text db_engine = cre...
<blockquote> <p>Any ideas why this does not work?</p> </blockquote> <p>Query parameters are used to supply the <em>values</em> of things (usually column values), not the <em>names</em> of things (tables, columns, etc.). Every database I've seen works that way.</p> <p>So, despite the ubiquitous advice that dynamic SQL i...
python|sqlalchemy
2
4,268
59,368,812
How can I use round() while forcing the digits to be as much as I firstly entered
<pre><code>import random userask = float(input("enter number: ")) userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100)) print("new value is " + str(userask)) </code></pre> <p>Let's say my input is 123.0123<br> I want the program to force the new value after such operation to have the same number ...
<p>You can try this:</p> <pre><code>import random userask = input("enter number: ") lst = userask.split('.') digits = 0 if len(lst)==1 else len(lst[1]) userask = float(userask) userask = userask + ((random.randrange(20)*userask)/random.randint(3, 100)) print("new value is " + '{:.{}f}'.format(digits).format(userask)) ...
python|python-3.x|numbers|rounding
1
4,269
63,201,427
Renaming dataframe columns with regex and dictionary
<p>I have a dataframe like this:</p> <pre><code>code_0101 code_0102 code_0103 code_0104 ... 0 1 2 3 ... ... ... ... ... </code></pre> <p>I also have a dictionary:</p> <pre><code>{'0101': 'cirurgical_procedures', '0102': 'medical_care', '...
<p>Use <code>series.replace</code> to replace and assign back to columns</p> <pre><code>d = {'0101': 'cirurgical_procedures', '0102': 'medical_care', '0103': 'remedy'} df.columns = df.columns.to_series().replace(d, regex=True) Out[12]: code_cirurgical_procedures code_medical_care code_remedy code_0104 0 ...
python|regex|pandas|dataframe
3
4,270
63,201,201
Uploading pictures python tkinter
<p>So I am completely new to Python and I'm trying to learn how to build GUI's for my business to help automate some of my work. I'm trying to upload a jpeg to the app I'm making, but I keep getting the same error code. Here it is along with my code beneath it:</p> <pre><code> self.tk.call(('image', 'create', imgtyp...
<p>You used Python built-in <code>PhotoImage()</code> which does not support JPEG image.</p> <p>Change</p> <pre><code>my_Image = PhotoImage(image, file=...) </code></pre> <p>to</p> <pre><code>my_Image = ImageTk.PhotoImage(file=...)` </code></pre> <p>Also the following line</p> <pre><code>Canvas.create_image(0, 0, ancho...
python|tkinter
2
4,271
63,172,763
Class variables and instance variables - which one to use and why, common patterns
<p>There is one thing that I have in back of my head when using some common libraries (like scrapy/django etc...). I know some top level difference between:</p> <ol> <li>Class variables - shared among all classes, <code>my_class_var</code> not in class.__dict__, defined like:</li> </ol> <pre class="lang-py prettyprint-...
<p>Class variables in such cases, e.g. ORM, are not used to store data but as a description or template. Variables with these names are also created in each instance of the class (in the hidden <code>__init__</code> method), in this case they are used to store data. This is a little magic that ORM hides from the user.<...
python|oop|variables
1
4,272
58,861,209
CRC - Python - How to calculate JAMCRC decimal number from string
<p>I need to calculate CRC-32/JAMCRC decimal number from a string in Python 3. How can I do it? For example, this webpage does it: <a href="https://www.crccalc.com/" rel="nofollow noreferrer">https://www.crccalc.com/</a> - for 'hello-world' it prints 1311505828. I would like to have script which does exactly the same c...
<p>To compute the CRC-32/JAMCRC you can simply perform the bitwise-not of the standard CRC-32 (in your case, the CRC-32 of 'hello-world' is 2983461467). But you can't simply use the <code>~</code> operator, because it works with signed integers (see <a href="https://stackoverflow.com/a/31151236">this answer</a>). Inste...
python|decimal|crc|crc32
0
4,273
58,882,323
Sorting the string lines in a txt file and then overwriting it with the sorted lines
<p>So basically I have a file that is something like this:</p> <pre><code>hi my name is </code></pre> <p>and I want it to be (get sorted alphabetically):</p> <pre><code>hi is my name </code></pre> <p>My code below stores the lines from the txt file into a list and then sorts it. It does what I want, but...:</p> <p...
<p>Define the <code>new</code> list out of the with the statement. And also correct the <code>file.write</code> argument. Here is the corrected code</p> <pre class="lang-py prettyprint-override"><code>new = [] with open ("3ex.txt","r") as f: for line in f: stripped = line.strip("\n") new.append(str...
python|list|file|overwrite
1
4,274
59,025,819
permission denied error while reading an excel file
<p>i got a permission denied error while i tried to open an excel file.</p> <p>I dont have the ms excel complete version. I mean, im just using the trial version. Could it be because of that?</p> <p>my code has just 4 lines</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt data...
<p>It's something about how file open function works. I successfully reproduced your problem and find the way.</p> <p>It's believed that you have a directory named <code>ML</code> in <code>E</code> disk, and maybe there are some excels files (such as <code>*.xls</code> or <code>*.xlsx</code>) in <code>ML</code>(I bet ...
python|error-handling
-1
4,275
15,727,885
Java equivalent of Python 'in' - for set membership test?
<p>I want to check if an <code>item</code> exists in an <code>item set</code>.</p> <p>I want to do this in <strong>java</strong>:</p> <pre><code>def is_item_in_set(item, item_set): return item in item_set </code></pre> <p>I've managed writing this:</p> <pre class="lang-java prettyprint-override"><code>boolean i...
<p>You can't do it with a straight array, but you can with a <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Set.html" rel="noreferrer"><code>Set&lt;T&gt;</code></a> by calling <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html#contains%28java.lang.Object%29" rel="noreferrer"><code>.contai...
java|python|set|membership
15
4,276
59,758,133
How to change the color of the background in a Networkx plot?
<p>I'm trying to change the background color of a networkx generated graph using matplotlib. But it seems my code only changes the external background, not the background of the graph itself. Example code:</p> <pre><code>import psutil import networkx as nx import matplotlib.pyplot as plt mlist = psutil.net_connection...
<p>You can change the background color with <code>ax.set_facecolor</code>. If you don't created an <code>ax</code>, you could use <code>plt.gca().set_facecolor</code>. If you also want to remove the black border, use <code>ax.axis('off')</code>. Note that the <code>bg_color=</code> is ignored in <code>nx.draw_network...
python|matplotlib|networkx
2
4,277
49,277,519
How to animate png with Matplotlib?
<p>I am trying to animate an png by moving it with changing its x position but the the loop doesn't overwrite the previous step but instead it just leave it and show a new version beside it:</p> <p><a href="https://i.stack.imgur.com/UuTST.png" rel="nofollow noreferrer">first step</a></p> <p><a href="https://i.stack.i...
<p>You should create the image once, outside the animating function. Then for the animation you only need to change the image's position, i.e. </p> <pre><code>image.set_extent(...) </code></pre> <p>Complete code:</p> <pre><code>import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotli...
python-3.x|matplotlib
1
4,278
60,129,419
How to generate independent(X) variable using Word2vec?
<p>I have a movie review data set which has two columns Review(Sentences) and Sentiment(1 or 0).</p> <p>I want to create a classification model using word2vec for the embedding and a CNN for the classification.</p> <p>I've looked for tutorials on youtube but all they do is create vectors for every words and show me t...
<p><code>Word2Vec</code> doesn't inherently create vectors for a text (set of words) – just individual words. </p> <p>But, sometimes a not-so-bad vector for a multi-word text is the average of all its word-vectors. </p> <p>If <code>list_of_words</code> is a list of the words in your text, and all the words are in the...
python|word2vec|sentiment-analysis
1
4,279
2,752,433
Why would one build supervisord inside of a buildout?
<p>I've seen buildout recipes that build <a href="http://supervisord.org" rel="nofollow noreferrer">supervisor</a> into the buildout, I suppose to control the daemons inside. However, it seems to me that one would still need something in /etc/init.d ( for example ) to run said supervisor instance on boot. </p> <p>So...
<p>When we create a buildout for a customer, we want that buildout to run on arbitrary hosting environments with minimal dependencies, all satisfiable with system packages. By including supervisord in the buildout, we eliminate the need for it to be installed system-wide and can tweak it's parameters finely, without ha...
python|buildout|supervisord
9
4,280
67,810,781
Algorithm to count unit triangles in large composite shape
<p>I need to write a brute-force algorithm to count the number of unit triangles in a complex shape. The shape is created each iteration by adding triangles to surround all outer edges.</p> <p><a href="https://i.stack.imgur.com/MgBGI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MgBGI.png" alt="Exa...
<p>Nevermind solution was simpler than I ever imagined as triangles added increase by 3 every time a simple for loop to add from n=1 worked easily enough.</p>
python|algorithm|shapes|pseudocode|brute-force
-1
4,281
30,507,524
Show small numbers as zero
<p>I'm very often fooled by very small float values in pandas which are "effectively zero".</p> <p>For example, it's hard to see at first glance what's going on with the following <code>Series</code>:</p> <pre><code>are_they_zero a -5.960464e-08 # This number is small b -2.384186e+07 # This one isn't c 2.38418...
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html#pandas.set_option" rel="noreferrer"><code>set_option</code></a> with <code>'display.chop_threshold'</code> to handle this:</p> <pre><code>In [20]: pd.set_option('display.chop_threshold', 0.001) df Out[20]: are_they...
python|pandas
6
4,282
66,965,685
How to reduce time complexity of this program
<p>The entry Y [i][j] stores the sum of the subarray X[i..j], but can I get a better time complexity?</p> <pre><code>def func(X, n): Y = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(i, n): for k in range(i, j+1): Y[i][j] += X[k] return Y if...
<p>You could use a <a href="https://www.geeksforgeeks.org/prefix-sum-array-implementation-applications-competitive-programming/" rel="nofollow noreferrer">prefix sum</a> array.</p> <p>The idea is that you have an array where the entry <code>ps[i]</code> denotes the sum of all elements <code>arr[0..i]</code>. You can ca...
python|algorithm
2
4,283
67,029,758
Brute-Force password cracker with no extra modules not working properly
<pre><code># Gets Input Values import sys sys.setrecursionlimit(1500) length = 0 intCorrent = &quot;&quot; looping = True # Sets Loop To Restart If Input Isn't An Int while looping: try: # Gets User Input For Length And Stops Loop If it's An Int print('Enter The Maximum Length:') length = in...
<p>The problem is that you call the recursion from the same variables sometimes.</p> <p>Look at this part of the code:</p> <pre><code> for i in letters: a += i main(max, num+1, a) </code></pre> <p>When you write <code>a += i</code> you are not actually creating a new list but extending th...
python
0
4,284
67,123,867
Drop down menu using button with image in tkinter
<p>I'm trying to create a dropdown menu using the button with images and I will put some functions on each button, but on the drop-down menu that I use the only button that is available to use is a check button. this is the program that I'm currently using.</p> <pre><code>from tkinter import * root = Tk() mbtn = Menubu...
<p>Does this solve Your issue?</p> <pre class="lang-py prettyprint-override"><code>from tkinter import * root = Tk() mbtn = Menubutton(root, text=&quot;Options&quot;, relief=RAISED) mbtn.pack() mbtn.menu = Menu(mbtn, tearoff = 0) mbtn[&quot;menu&quot;] = mbtn.menu mbtn.menu.add_checkbutton(label=&quot;Outing&quot;) mb...
python|tkinter|drop-down-menu
0
4,285
67,072,672
unable to add multiple users in Jmeter - tried with CSV still failing
<p>I have CSV file with added in the CSV Data Set Config,</p> <p><a href="https://i.stack.imgur.com/8S8zd.jpg" rel="nofollow noreferrer">please click the url to see the image </a></p> <p>CSV file content</p> <pre><code>EMAIL,USERNAME,FIRSTNAME,LASTNAME,PASSWORD pfuser2@pfuser.com,pfuser2,PF,User,test1234 pfuser3@pfuse...
<ul> <li><p>Either set <code>Ignore first line</code> to <code>True</code></p> <p><a href="https://i.stack.imgur.com/sLpJQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sLpJQ.png" alt="enter image description here" /></a></p> </li> <li><p>or set it to <code>False</code> and remove everything from t...
python|jmeter|jmeter-plugins|jmeter-5.0
0
4,286
67,102,641
Showing custom cooldown messages for a command usind discord.py
<p>I'm trying to add a cooldown for my discord.py bot such that the user is not able to spam a command, it works fine in my case. I use the following decorator and this <code>bot.event</code> and I'm able to get the bot to send a message saying that cooldown is in place.</p> <pre class="lang-py prettyprint-override"><c...
<p>So the problem is checking what command was invoked, we can do that with the provided context:</p> <pre class="lang-py prettyprint-override"><code>if isinstance(error, commands.CommandOnCooldown): if ctx.command.name == 'mine': await ctx.send(&quot;Coins dont rain from the sky&quot;) elif ctx.comman...
python|discord.py
0
4,287
63,989,709
Counter for a data from HTML file
<p>I have a task which we list 10 things from an HTML with using regex.</p> <p>I managed to list 10 things from a website, but I need numbers next to them while displaying on tkinter.</p> <p>For example 1 to 10 and/or 10 to 1 like this: example:<br /> <a href="https://i.stack.imgur.com/SRagv.png" rel="nofollow noreferr...
<p>You can use <code>enumerate()</code> function in the <code>for</code> loop:</p> <pre><code>font = ('Malgun', 10) for i, hidden_gems in enumerate(disney_plus[::-1], 1): # in reverse order Label(hidden_gems_on_disney, text='{})'.format(i), bg='pink', font=font).place(x=x_coord, y=y_coord) Label(hidden_gems_on...
python|tkinter
1
4,288
42,653,563
Why correlation of two matrix return nan?
<p>Consider the following code</p> <pre><code>import numpy as np from scipy.stats.stats import pearsonr A = np.ones([5,5]) B = np.ones([5,5]) pearsonr(A.flatten(), B.flatten()) </code></pre> <p>now my question is why last line of code returns: </p> <pre><code>(nan, 1.0) </code></pre>
<p>When I run your code it's giving me following error. Are you not getting this error?</p> <pre><code> In [6]:runfile('C:/Users/a*/.spyder-py3/temp.py', wdir='C:/Users/a*/.spyder-py3') (nan, 1.0) C:\Anaconda3\lib\site-packages\scipy\stats\stats.py:3029: RuntimeWarning: invalid value encountered in doub...
python|arrays|numpy|statistics
1
4,289
66,512,491
Use Python script to create new table from current dataset in PowerBI
<p>I'm having a csv file as a source dataset. Currently in the table there is a column that I would like to use Python to loop and extract data from string in each cell. For example, in a cell:</p> <p>&quot;Quantity changed by 10, Price changed by 90.&quot;</p> <p>I would like to use Python and extract &quot;Quantity, ...
<p>Extracting the data from the column is fairly easy if the data follows the same format:</p> <pre><code>s = &quot;Quantity changed by 10, Price changed by 90.&quot; l, sep, r = s.partition(',') if sep: quantity = int(l.split()[-1]) price = int(r.split()[-1][:-1]) print(quantity, price) #10 90 </code></pr...
python|powerbi|powerbi-datasource
0
4,290
50,730,073
SettingWithCopyWarning in pandas
<p>I have a dataframe as shown below:</p> <pre><code>df = index P01 unten oben RV R2_simu 2014-05-23 03:00:00 0.0 0.0 0.9 0.8 0 2014-05-23 06:00:00 0.5 0.7 1.4 0.1 0 2014-05-23 07:00:00 1.0 2.4 2.4 0.6 0 2014-05-23 08:00:00 0.55 15.7 28...
<p><code>SettingWithCopyWarning</code> is a common side effect of using syntax like yours:</p> <pre><code>df.R2_simu[i] = df.RV[i] </code></pre> <p>The developers recommended using <code>df.loc[]</code> instead of using the index to access elements. Also note that using <code>for i in range(0, len(df)):</code> is les...
python|pandas|dataframe
2
4,291
3,577,064
Sending multiple POST data items with the same name, using AppEngine
<p>I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values.</p> <pre><code>form_fields = { "data": "foo", "data": "bar" } form_data = urllib.urlencode(form_fields) result = urlfetch.fetch(url="http://www.foo.com/", payload=form_...
<p>Modify your <code>form_fields</code> dictionary so that fields with the same name are turned into lists, and use the <code>doseq</code> argument to <code>urllib.urlencode</code>:</p> <pre><code>form_fields = { "data": ["foo","bar"] } form_data = urllib.urlencode(form_fields, doseq=True) </code></pre> <p>At thi...
python|google-app-engine|urlfetch
14
4,292
50,411,747
Value from iterative function in pandas
<p>I have a dataframe and would like to have the values in one column being set through an iterative function as below.</p> <pre><code>import pandas as pd import numpy as np d = {'col1': [0.4444, 25.4615], 'col2': [0.5, 0.7], 'col3': [7, 7]} df = pd.DataFrame(data=d) df['col4'] = df['col1'] * df['col3']/4 ...
<p>For what it is worth, here is an inefficient solution: after each iteration, keep track of which coefficient starts satisfying the condition.</p> <pre><code>import pandas as pd import numpy as np d = {'col1': [0.4444, 25.4615], 'col2': [0.5, 0.7], 'col3': [7, 7]} df = pd.DataFrame(data=d) df['col4'] = d...
pandas|function|numpy|dataframe|iteration
0
4,293
34,956,749
call script from django unittest
<p>I'm trying to run a script from a django unit test but failing to do so. </p> <p>The script I want to call can be run from the command line with <code>python -m webapp.lib.cron.my_cron</code></p> <p>I've tried:</p> <pre><code>from subprocess import call call("python -m webapp.lib.cron.my_cron") </code></pre> <p>...
<p>You should pass the arguments as a list, not a string.</p> <pre><code>import subprocess subprocess.call(["python", "-m", "webapp.lib.cron.my_cron"]) </code></pre>
python|django|django-unittest
0
4,294
56,855,558
How to return a string if a re.findall finds no match
<p>I am writing a script to take scanned pdf files and convert them into lines of text to enter into a database. I use re.findall to get matches from a list of regular expressions to get certain values from the tesseract extracted strings. I am having trouble when a regular expression can't find a match I want it to ...
<p>You could do this in a single line:</p> <pre><code>results += re.findall(pattern, extracted_string) or ["Error"] </code></pre> <p>BTW, you get no benefit from compiling the pattern inside the vendor loop because you're only using it once. </p> <p>Your function could also return the whole search result using a si...
python|regex|string-search
3
4,295
45,150,773
Tensorflow Object Detection Training Killed, Resource starvation?
<p>This question has partially been asked <a href="https://stackoverflow.com/questions/45126872/tensorflow-object-detection-training-was-quickly-terminated-by-system">here</a> and <a href="https://stackoverflow.com/questions/44833085/tensorflow-object-detection-killed-before-starting">here</a> with no follow-ups, so ma...
<p>Alright, so after looking into it, and trying a few things, the problem ended up being in the Dmesg info I posted.</p> <p>Training was taking up more than the 8 GB of memory that I had, so the solution ended up being <a href="https://unix.stackexchange.com/questions/295833/increase-swap-space-in-linux-through-termi...
tensorflow|linux-kernel|protocol-buffers|object-detection|training-data
1
4,296
45,219,778
The best way to search a file and return required fields from rows
<p>I have the following code that works perfectly. It searches a txt file for an ID number, and if it exists, returns the first and last name.</p> <p>full listing: <a href="https://repl.it/Jau3/0" rel="nofollow noreferrer">https://repl.it/Jau3/0</a></p> <pre><code>import csv #==========Search by ID number. Return Ju...
<p>You should probably consider using <code>csv.DictReader</code> for this usage, since you have tabular data with consistent columns.</p> <p>If you only want to retrieve data once then you can simply iterate through the file until the first occurrence of the desired id, as follows;</p> <pre><code>import csv def sea...
python|file|csv|search
1
4,297
64,766,611
How to run multiple python files simultaneously?
<p>I have python files (named in same way) in different folders. I want to run all python files at the same time with one script, any of the terminals (of the executed files) should not to be closed when the new terminal is opened. Which means, I want them to run simultaneously, each in a <strong>new/different terminal...
<p><strong>SOLVED</strong></p> <p>I just had to use:</p> <blockquote> <p>subprocess.Popen(&quot;python pathtoeachfile//file.py&quot;, creationflags=subprocess.CREATE_NEW_CONSOLE)</p> </blockquote> <p>and loop over my files.</p>
python|terminal
0
4,298
61,420,058
i am getting HTTPError('502 Server Error: Bad Gateway for 'https://myurl") using locust with python
<p>while executing locust load test i have faced the mentioned issue and I have checked in my application insights there is no errors. so please help me how to resolve find the exact cause of this issue </p> <pre><code> @task(1) def test(self): r = self.client.post("url",data=json.dumps(payload)...
<p>There is not a lot more Locust can tell you: the server/URL you requested returned a 502 error. You can check exactly what URL locust ran against using <code>print(r.url)</code> (if it is literally <code>https://myurl</code> like you say in the title then that is your problem :)</p>
python|testing|load-testing|locust
0
4,299
61,582,593
Blas GEMM launch failed: Tensorflow / Jupyter / Anaconda on Windows:
<p>Thanks for looking at this. I'm trying to rerun a script I had running prior to a reformat. I am certain the script works because I had run it previously but I think my configuration is not quite right. Is there something straightforward I'm missing? </p> <p>I installed Anaconda / Tensorflow with this guide: <a hre...
<p>Solved this problem. This error apparently occurs when another instance is running. I tried closing Anaconda and restarting but this didn't help. However, a restart did, and I am now running this correctly.</p>
tensorflow|anaconda|jupyter
0