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
1,909,700
53,905,313
Sympy: Equation equals zero => How to remove denominator and get factors?
<p>After some calculations on the complex number z_re and its conjugate z(bar)_re, I get the following equations:</p> <p><img src="https://i.imgur.com/0fAvd3O.png" alt="equations"></p> <p>I simplify and expand and get the second or third of the three equations from the picture. This looks almost like what I want to a...
<p>Here's some code that will do what you ask. Basically I just expressed your equation, factored it such that it is in the form <code>&lt;some_fraction&gt; = 0</code> and got the numerator of that fraction, which is what you need.</p> <pre><code>from sympy import * z_re = Symbol('z_re',Complex=True) z_re_c = conjugat...
python|sympy|complex-numbers|simplify
2
1,909,701
65,288,046
Unable to change value of method variable inside if statement in python
<pre><code>def a(): no_user = False number_of_users = # gets number of users from db if number_of_users == 0: no_user = True if no_user: print(&quot;no users in db&quot;) else: print(number_of_users) </code></pre> <p>when above method is run, it never prints &quot;no user in db&quot;, even ...
<p>i guess, you should modify part as below:</p> <pre><code> if number_of_users &gt; 0: no_user = False </code></pre> <p>since if number_of_users &gt; 0, then there are users and no_user should be false</p>
python|python-2.7
1
1,909,702
45,651,080
When you run the script KeyError: 'EXIF DateTimeOriginal'
<p>I need to know the properties of an image data taken (day, time, hour, minute, second)</p> <pre><code>import exifread import os directoryInput=r"C:\tekstilshiki" for filename in os.listdir(directoryInput): if filename.endswith('.jpg'): with open(r"%s\%s" % (directoryInput, "11.jpg"), 'rb') as image: # d...
<p>Each instant of 'exif' can contain different keys, based on what is extracted from the image, so to avoid the "KeyError" message you need to check if 'exif' contains the key "EXIF DateTimeOriginal":</p> <pre><code>import exifread, os directoryInput=r"C:\tekstilshiki" for filename in os.listdir(directoryInput): ...
python|exif
0
1,909,703
14,359,288
Tokenize and label text
<p>Here's a simple scanner, that tokenizes text according to certain rules, and labels the tokens.</p> <ol> <li>What is the best way to handle unknown characters, and label them as unknown?</li> <li>Is there a recommended way/library to speed things up while accomplishing similar results and remaining relatively simpl...
<p>The <code>re.Scanner</code> matches patterns in the order provided. So you can provide a very general pattern at the end to catch "unknown" characters:</p> <pre><code>(r".", unknown) </code></pre> <hr> <pre><code>import re def alpha(scanner,token): return token, 'a' def numeric(scanner,token): return to...
python|nlp
3
1,909,704
57,001,600
Return average array for each element of list of arrays with columns and rows of fixed shape
<p>I have got multiple arrays with 1000 rows and 500 columns and I want to return an array which takes each element (row i and column j) of the arrays and calculates its average.</p> <p>I have tried the following:</p> <pre class="lang-py prettyprint-override"><code>listofarrays=[array1,array2,array3,array4,...,arrayx...
<p>you can review here : average of matrix</p> <p><a href="https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.matrix.mean.html" rel="nofollow noreferrer">https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.matrix.mean.html</a></p>
arrays|numpy|average
0
1,909,705
56,885,040
How do I select corresponding column field values in a dataframe?
<p>So I have created a data frame as follows -</p> <pre><code>|id | Image_name | result | classified | ------------------------------------------------- |01 | 1.bmp | 0 | 10 | |02 | 2.bmp | 1 | 11 | |03 | 3.bmp | 0 | 10 | |04 ...
<p>First get all the images names from the folder and store in a list</p> <pre><code>all_files_names=os.listdir("#path to the dir") df.loc[df['Image_name'].isin(all_files_names)] </code></pre> <p><strong>Output</strong> (assuming all four are there)</p> <pre><code> id Image_name result classified 0 1 1....
python|pandas|dataframe
1
1,909,706
44,572,490
Rendering multiple HTML pages in Python Flask (Heroku) App
<p>I am trying to serve multiple HTML Pages to a single page and then serve that final single page as a PDF. I have a total of 95 pages and I have already achieved this using the following stack;</p> <ol> <li>Python/ Flask</li> <li>WeasyPrint HTML to PDF Creator</li> <li><p>Jinja Templating using include </p> <pre><c...
<p>After trying out a few things, I think the best way to reduce the time is to simply use Reportlab and make PDF out of single pages. Then I will be using</p> <blockquote> <p>pyPDF2</p> </blockquote> <p>to merge all those single pages into one single PDF file to download. I will mark this as the answer, if I am ab...
python|heroku|flask|jinja2|weasyprint
0
1,909,707
73,063,606
Keras ValueError: Dimensions must be equal LSTM
<p>I'm creating a Bidirectional LSTM but I faced following error</p> <pre><code>ValueError: Dimensions must be equal, but are 5 and 250 for '{{node Equal}} = Equal[T=DT_INT64, incompatible_shape_error=true](ArgMax, ArgMax_1)' with input shapes: [?,5], [?,250] </code></pre> <p>I have no idea what is wrong and how to fix...
<p>the problem is because of the <strong>Loss function</strong> and y-label shape. we should not pad y_label and it should fit the model directly without any other process</p>
python|keras|error-handling|lstm|tf.keras
0
1,909,708
73,136,375
Mypy loses type of the TypedDict when unpacked
<p>I have the following code when trying to spread the dictionary from typing import TypedDict</p> <pre><code>class MyDict(TypedDict): foo: int def test(inp: MyDict): m: MyDict = inp # OK n: MyDict = {**inp} # &lt;-- ERROR </code></pre> <p>I receive an error <code>Expression of type &quot;dict[str, object]...
<p>Currently, neither <strong>mypy</strong> nor <strong>pyright</strong> is smart enough to infer the type of an unpacked <code>dict</code>. See <a href="https://github.com/python/mypy/issues/4122" rel="nofollow noreferrer">https://github.com/python/mypy/issues/4122</a>.</p> <p>As a workaround use <a href="https://docs...
python|python-3.x|mypy|python-typing
1
1,909,709
73,063,121
Encounter an issue while trying to remove unicode emojis from strings
<p>I am having a problem removing unicode emojis from my string. Here, I am providing some examples that I've seen in my data</p> <pre><code>['\\\\ud83d\\\\ude0e', '\\\\ud83e\\\\udd20', '\\\\ud83e\\\\udd23', '\\\\ud83d\\\\udc4d', '\\\\ud83d\\\\ude43', '\\\\ud83d\\\\ude31', '\\\\ud83d\\\\ude14', '\\\\ud83d\\\\udcaa', '\...
<p>Since your text does not contain emoji chars themselves, but their representations in hexadecimal notation (<em><code>\uXXXX</code></em>), you can use</p> <pre class="lang-py prettyprint-override"><code>data = re.sub(r'\s*(?:\\+u[a-fA-F0-9]{4})+', '', data) </code></pre> <p><em>Details</em>:</p> <ul> <li><code>\s*</...
python|regex
1
1,909,710
55,995,982
Alphvantage Intraday API has not been working for last few days, API is throwing back "Key Error: "Time Series (1min)'"
<p>Have been trying to query intraday series, but the call is failing with the below error.</p> <p>Can someone please help me resolve this error? </p> <p>Code is really simple, just querying USG equity symbol for 1 min interval from API</p> <p>data, meta_data = av_ts.get_intraday(symbol='USG',interval='1min', output...
<p>USG traded on April 18th, and on the 23rd, but not since then.</p> <p>The API is having trouble offering 1-minute updates of an issue that doesn't trade.</p>
python-3.x|alpha-vantage
0
1,909,711
73,335,987
discord.py: Adding role to user throws error
<p>I need help with a bot event. Whenever I add the code, it gives me this error:</p> <pre><code>Ignoring exception in on_member_join Traceback (most recent call last): File &quot;/home/runner/Tragic-Bot/venv/lib/python3.8/site-packages/discord/client.py&quot;, line 343, in _run_event await coro(*args, **kwargs) ...
<p>The error already tells you: <code>'Bot' object has no attribute 'add_roles'</code> -&gt; <code>Bot.add_roles()</code> doesn't exist. But what exists is <code>Member.add_roles()</code>.</p> <p>So, your code would look like that:</p> <pre class="lang-py prettyprint-override"><code>@client.event async def on_member_jo...
python|discord|discord.py
1
1,909,712
49,925,100
How to handle swapping variables in a pythonic way?
<p>I often have the case where I use two variables, one of them being the "current" value of something, another one a "newly retrieved" one.</p> <p>After checking for equality (and a relevant action taken), they are swapped. This is then repeated in a loop.</p> <pre><code>import time import random def get_new(): ...
<p>Really, all you have is a simple iteration over a sequence, and you want to detect changes from one item to the next. First, define an iterator that provides values from <code>get_new</code>:</p> <pre><code># Each element is a return value of get_new(), until it returns None. # You can choose a different sentinel v...
python|python-3.x|loops|infinite-loop
2
1,909,713
64,652,661
How to get response parameters in Django?
<p>I want to implement login with twitter without using any library for my django app. I am sending the user to login page using a request function in views by passing the tokens which is successfully going to the twitter login page. Twitter redirects user to a url which I have configured as</p> <p><code>login/twitter/...
<p>Please note that your case requires to extract parameters from a request. Twitter redirects the user to your application, and the redirect makes a request to your server</p> <p>You can get using the following approach:</p> <p>assuming your URL is called as GET <code>login/twitter/callback?token=abc123</code></p> <pr...
python|django|oauth
0
1,909,714
64,091,429
How do you add a CSS style to a HTML file with a python http.server?
<p>I have a simple http server running from python which returns an HTML file as a GET request. The HTMl file just has some input and it is sent correctly but is not styled even though it is linked to a CSS file. Here is the server.py:</p> <pre><code>from http.server import BaseHTTPRequestHandler, HTTPServer import tim...
<p>Its really complicated to do so, because you have to create new server that serve your css file. **Better you used Powerfull &amp; popular solutions likeFlask and Django **where you can configure these files easily. for more info about Flask <a href="https://pymbook.readthedocs.io/en/latest/flask.html" rel="nofollow...
python|html|css|server
0
1,909,715
53,267,965
Blank terminal screen unable to type anything in Platformio-ide-terminal in Atom
<p>I have installed platformio-ide-terminal in Atom for working on python project. But when I open the terminal it shows blank screen with no option to write anything.</p> <p><a href="https://i.stack.imgur.com/1H3Ar.png" rel="nofollow noreferrer">Blank terminal screen</a></p> <p>Can anyone please help me out with thi...
<p><strong>Below worked for me :</strong> Open 'Atom' -&gt; 'File' -&gt; 'Settings' -&gt; 'Packages' -&gt; 'Settings' for platformio-ide-terminal -&gt; Scroll down to 'Shell override' and pass correct path of command prompt.</p> <p>e.g., <a href="https://i.stack.imgur.com/HEgKF.png" rel="nofollow noreferrer"><img src="...
python|terminal|atom-editor|platformio
1
1,909,716
65,105,267
finding angles 0-360 in arctan
<p>I need help with a math issue:</p> <p>I need to get the angle from 0 until 360 degrees but this code gives the angle between -90 until 90 degrees:</p> <pre><code>N = math.cos(β * (math.pi / 180)) * math.tan((f + ω) * (math.pi / 180)) N2 = math.atan(N) * (180 / math.pi) </code></pre> <p>I want to N2 change between 0 ...
<p>Use <a href="https://docs.python.org/3/library/math.html#math.atan2" rel="nofollow noreferrer"><code>atan2</code></a> like so</p> <pre><code>import math math.atan2(-0.1, 0.1) + math.pi </code></pre> <p>The problem is <code>atan</code> does not know which quadrant you are in, while <code>atan2</code> does as it accep...
python|math
3
1,909,717
68,660,787
Django.db.models.deletion related_objects takes 3 positional arguments
<p>I'm upgrading my project from Django 2.2 to 3.2 and wracking my brain at what seems to be a bug in their code.</p> <p>I have a test that does a simple DELETE request to a resource (incidentally a DjangoRestFramework resource, DRF version is 3.12.4), and a crash happens inside django.db.models.deletion. here is the r...
<p>Alright, found my answer. Actually this is probably something no-one would have been able to guess, but I just want to share what I learned.</p> <p>So I was right, the error does not make sense, because it doesn't fit with the function signature. It should never be able to happen. So how to debug that?</p> <p>Well, ...
python|django
1
1,909,718
5,577,835
Handling assertion in python
<p>I can't understand why this code:</p> <pre><code>x='aaaa' try: self.assertTrue(x==y) except: print (x) </code></pre> <p>generates me this error</p> <pre><code>AssertionError: False is not True </code></pre> <p>It should be handle it by</p> <pre><code>print(x) </code></pre> <p><strong>EDIT</strong></p...
<p>You should include the code that defines the <code>assertTrue</code> method. From the output you get, I'd say that it actually does not throw an exception, but deals with it internally (thus the error message being printed, and not your value).</p> <p>You can use the built-in <a href="http://docs.python.org/referen...
python|exception-handling|assert
4
1,909,719
4,862,191
python processing a log file and stripping characters
<p>I am making a quick log parse tool:</p> <pre><code>findme = 'important ' logf = file('new.txt') newlines = [] for line in logf: if findme in line: line.partition("as follows: ")[2] newlines.append(line) outfile = file('out.txt', 'w') outfile.writelines(newlines) </code></pre>...
<p>Plus, I'm a little confused about the line</p> <pre><code>line.partition("as follows: ")[2] </code></pre> <p>. It simply does nothing. Maybe you wanted</p> <pre><code>line = line.partition("as follows")[2] </code></pre> <p>? By the way, it ist better to just write each line in the for loop instead of a giant <co...
python
3
1,909,720
62,710,093
How do I install sklearn module properly?
<p>I'm trying to install <code>sklearn</code> module using <code>pip command</code> but after the installation is completed , all I can see is this folder</p> <pre><code>C:\Users\Aditi\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\sklearn-0.0-p...
<p>Try to install using command <code>pip install scikit-learn</code> or you can use <code>pip install sklearn</code> but I prefer the first one.</p> <p>If it still not work for you, you can update the numpy or reinstall the numpy.</p> <p>You can check <a href="https://scikit-learn.org/stable/install.html" rel="nofollo...
python|scikit-learn|data-science|sklearn-pandas
3
1,909,721
62,566,558
Validation Accuracy stuck at .5073
<p>I am trying to create a regression model but my validation accuracy stays at <code>.5073</code>. I am trying to train on images and have the network find the position of an object and the rough area it covers. I increased the unfrozen layers and the plateau for accuracy dropped to <code>.4927</code>. I would appreci...
<ol> <li>The final activation function in your model should not be <code>sigmoid</code> since it will output numbers between <code>0</code> and <code>1</code> and I am assuming your labels (i.e., <code>positionx</code>, <code>positiony</code>, and <code>width</code> are not in this range). You could replace it with eit...
python|tensorflow|keras|linear-regression
1
1,909,722
61,664,330
Merging dataframes with time series data + checking if values already exist in the first df
<p>I'm new at Python so please bear with me. I have a dataframe that looks like this:</p> <pre><code>df1 Company 1/2020 2/2020 Apple 1 0 Google 0 2 </code></pre> <p>I want to be able to merge a new data frame that may look like:</p> <pre><code>df2 Company 2/2020 3/2020 ...
<p>I'm not sure if I fully understand the intent of the question. If the sum of <code>df1+df2</code> is required, the following code can be used.</p> <pre><code> import pandas as pd import io data = ''' Company 1/2020 2/2020 Apple 1 0 Google 0 2 ''' data2 = ''' Company 2/2020 3/2020 Apple 1 1 Google 2 0 '...
python|pandas
0
1,909,723
67,525,760
upload image to custom folder (fastapi)
<p>When I try to upload an image, images uploads in the main dir. how can I change the upload destination into the media folder?</p> <pre class="lang-py prettyprint-override"><code>@router.post('/icon', status_code=status.HTTP_201_CREATED,) async def create_file(single_file: UploadFile = File(...)): with open(sing...
<p>I'm not familiar with <code>shutil</code> module, but obviously, you should use</p> <pre><code>with open(f'my_dir/{single_file.filename}', &quot;wb&quot;) as buffer: </code></pre>
python|fastapi|shutil
1
1,909,724
67,309,730
How to overlay a scatterplot on top of boxplot with sns.catplot?
<p>It is possible to combine <a href="https://seaborn.pydata.org/tutorial/function_overview.html" rel="nofollow noreferrer">axes-level</a> plot functions by simply calling them successively:</p> <pre class="lang-py prettyprint-override"><code>import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset...
<p>The following works for me with seaborn v0.11:</p> <pre class="lang-py prettyprint-override"><code>import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset(&quot;tips&quot;) g = sns.catplot(x=&quot;sex&quot;, y=&quot;total_bill&quot;, hue=&quot;smoker&quot;, col=&quot;time&quot;, ...
python|seaborn
4
1,909,725
67,391,695
Convert date string to another date string format
<p>I am trying to convert a string datetime to another string time i.e... <code>May 4, 2021</code> but I am getting the following error</p> <pre><code>#convert '2021-05-04T05:55:43.013-0500' -&gt;&gt;&gt; May 4, 2021 timing = '2021-05-04T05:55:43.013-0500' ans = timing.strftime(f'%Y-%m-%d 'f'%H:%M:%S.%f') </code></pre...
<p>You want <code>datetime.strptime()</code> not <code>timing.strftime()</code>. <code>timing</code> is a string that doesn't have any functions called <code>strftime</code>. The <code>datetime</code> class of the <code>datetime</code> module<sup>I know, it's confusing</sup>, OTOH, does have a function to parse a strin...
python-3.x|datetime|python-datetime|strftime
4
1,909,726
60,525,201
Get coordinate(x,y) from xml file and put it into float list
<p>I want to put several coordinates (x, y) recovered from an xml file in a list that I can used with a drawcontour or polyline function the problem is that I don't know how to put them in a list I used liste.append but its not working :( please help me</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml v...
<ol> <li>Your XML is strange (<code>x</code> and <code>y</code> are not in <code>coordinateIndex</code>)</li> <li>Indentation matters in python</li> <li>You probably want to try ElementTree, which is considered a better alternative to minidom</li> <li>Working code for minidom and your input format</li> </ol> <pre><cod...
python|xml|list
1
1,909,727
60,666,698
How to find title and list where data-id is highest number
<p>I want to click the element with highest data-id. I'm generating title like this:</p> <pre><code>char_set = string.ascii_uppercase tagTitle = "AI TAG " + ''.join(random.sample(char_set * 4, 4)) driver.find_element_by_xpath("//*[@id='FolderName']").send_keys(tagTitle) </code></pre> <p>Currently I'm getting ...
<p>First you can get all the elements in a list and then you can click on the last element because that would be having the highest <code>data-id</code> and if you want to get the title which you are clicking then you can get it by using <code>get_attribute()</code> method.</p> <p>You can do it like:</p> <pre><code>#...
python|selenium|selenium-webdriver|automated-tests
1
1,909,728
71,288,217
Why does my Python bot not work? (PyAutoGUI)
<p>I coded a bot in Python that should automatically play Friday Night Funkin' (press the arrows when they are meant to be pressed) but for some reason it doesn't do anything. I took screenshots of the arrows when they are meant to be pressed and I made it so if python sees that the arrow is meant to be pressed (it see...
<p>maybe it is copy-paste lag, but there is no indention before &quot;if&quot;</p> <p>use &quot;not None&quot; instead of &quot;!= None&quot;</p> <p>use</p> <pre><code>if __name__ == &quot;__main__&quot;: </code></pre> <p>your script as it now can be run only as python file, through console command or import.</p>
python|pyautogui
0
1,909,729
64,284,668
Pygame - Mouse clicks not getting detected
<p>I'm learning Pygame to make games w/ Python. However, I'm encountering a problem. I'm trying to detect when the player is currently clicking the screen, but my code isn't working. Is my code actually screwed, or is it just the online Pygame compiler that I'm using?</p> <pre><code>import pygame pygame.init() screen ...
<p>The coordinates which are returned by <a href="https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.get_pressed" rel="nofollow noreferrer"><code>pygame.mouse.get_pressed()</code></a> are evaluated when the events are handled. You need to handle the events by either <a href="https://www.pygame.org/docs/ref/event.h...
python|python-3.x|pygame
1
1,909,730
70,293,606
Compute percentage changes with next row Pandas
<p>I want to compute the percentage change with the next n row. I've tried pct_change() but I don't get the expected results</p> <p>For example, with n=1</p> <pre><code> close return_n 0 100 1.00% 1 101 -0.99% 2 100 -1.00% 3 99 -4.04% 4 95 7.37% 5 102 NaN </code></pre> <p>With n=2</...
<p>You can do <code>shift</code> with <code>pct_change</code></p> <pre><code>n = 2 df['new'] = df.close.pct_change(periods=n).shift(-n) df Out[247]: close return_n new 0 100 1.00% 0.000000 1 101 -0.99% -0.019802 2 100 -1.00% -0.050000 3 99 -4.04% 0.030303 4 95 7.37% NaN 5 ...
python|pandas
2
1,909,731
63,400,473
Pandas passing arguments to apply
<p>I'm trying to apply a function to a dataframe, creating a new column as a result, like so:</p> <pre><code>def defensive_weights(DSp=None,SGp=None,FCp=None): if dfcrop['opp_goals'] == 0: DInd = (DSp*2 + SGp + FCp) else: DInd = (DSp + SGp + FCp) return DInd dfcrop['IED'] = dfcrop['opp_...
<p>It appears you're calling the entire dataframe series from within the function. I don't think you want to do this. You should allow the function to take a parameter, and pass it to the conditional:</p> <pre><code>def defensive_weights(item, DSp=None,SGp=None,FCp=None): if item == 0: DInd = (DSp*2 + SGp +...
python|pandas
1
1,909,732
56,572,787
Is it possible to run regular python code on Google TPU?
<p>So I'm pretty new with Google TPU. From what I've already researched, it is optimized specifically for training machine learning models written on TensorFlow. Currently, I am trying to see how the TPU performs with other types of functions. These functions are not related to machine learning. I have been trying to ...
<p>I am afraid the presence or absence of tensorflow has no effect on how <code>np</code> operations are executed.</p> <p>In your example above when you specify </p> <pre><code>tpuOperation = tf.contrib.tpu.batch_parallel(multiplicationComputation, [], num_shards=8) </code></pre> <p>where <code>multiplicationComputa...
python|tensorflow|google-colaboratory|tpu
1
1,909,733
56,697,766
How to create user in amazon-cognito using boto3 in python
<p>I'm trying to create user using python3.x and boto3 but end up with facing some issues</p> <p>I've tried using "admin_create_user" even id didn't worked for me</p> <pre><code>import boto3 aws_client = boto3.client('cognito-idp', region_name = CONFIG["cognito"]["region"] ) response = aws_client.admin_create_us...
<ul> <li>I think you didn't pass the configuration. First install the <a href="https://aws.amazon.com/cli/" rel="noreferrer">AWS CLI</a>.</li> </ul> <p><code>pip install awscli --upgrade --user</code></p> <ul> <li>Then type below command in your terminal,</li> </ul> <p><code>aws configure</code></p> <ul> <li>Provid...
python|python-3.x|boto3|amazon-cognito
7
1,909,734
56,559,885
sorting only what's in parentheses in a string
<pre><code>s = "Kadu (b, a), Dadu, Adu (y, i)" </code></pre> <p>I need this string to be sorted as follows:</p> <p><code>Adu (i, y), Dadu, Kadu (a, b)</code></p> <p>Extra explanation for those who have one more minute: As a translator, I sometimes have to translate alphabetically sorted, comma-delimited lists in whi...
<p>You can use <a href="https://docs.python.org/3/library/re.html#re.sub" rel="nofollow noreferrer"><code>re.sub</code></a> with a callback function to find the parts within <code>(...)</code> and replace it with a sorted version of itself.</p> <pre><code>&gt;&gt;&gt; ', '.join(sorted(re.sub("(?&lt;=\().+(?=\))", lamb...
regex|python-3.x
2
1,909,735
60,964,416
What am I missing when getting nouns from sentence and reversed sentence using nltk?
<p>I Have a <code>is_noun</code> definition using <code>nltk</code>:</p> <pre><code>is_noun = lambda pos: pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS' </code></pre> <p>then I have this in a function:</p> <pre><code>def test(text): tokenized = nltk.word_tokenize(text) nouns = [word for (word, ...
<h1>Summary: GIGO (Garbage In => Garbage Out).</h1> <p>As the comment suggests, word order matters. English is rife with words that can act as multiple parts of speech, depending on placement within a phrase. Consider:</p> <pre><code>You can cage a swallow. You cannot swallow a cage. </code></pre> <p>In the second...
python|nltk
1
1,909,736
60,775,609
Separate items in a list (or dictionary or counter *not sure XD)
<p>My code:</p> <pre><code>list1 = [] for line in open('live.txt'): name = line.strip() list1.append(name) import collections print("Original List : ",list1) ctr = collections.Counter(list1) print(ctr) </code></pre> <p>Output:</p> <pre><code>Original List : ['Heart', 'Thumbs up', 'Thumbs up', 'Smile', 'He...
<p>you should just iterate through a dictiory</p> <pre><code>for key in ctr: print(key, ': ', ctr[key]) </code></pre>
python|list|dictionary|counter
0
1,909,737
61,161,268
how to get all possible combinations of strings/words with each word multiple times
<p>I'm trying to create all possible stochiometries of chemical compounds, which essentially is combining strings/words: Let's say I have a list of elements: </p> <pre><code>els=['Ba','Ti','O'] </code></pre> <p>and I say the number of each element can be maximally 3 and I want all possible combinations,with always ea...
<p>You could use <code>itertools.permutations</code> for a shorter and maybe a bit more readable solution:</p> <pre class="lang-py prettyprint-override"><code>from itertools import permutations elements = {"Ba", "Ti", "O"} # Set of elements maxi = 3 # Maximum occurrence raw_output = permutation...
python-3.x|string|combinatorics|chemistry
1
1,909,738
66,038,506
Is there equivalent of bash's "set -x" in python?
<p>All I 've found is something like <code>python3 -m pdb myscript.py</code> but it does not do what <code>set -x</code> does which executes the script and shows on terminal each line that gets executed with the actual values of the variables.</p> <p>For example:</p> <pre><code>#!/bin/bash set -x echo &quot;This is a f...
<p>yes hi, perhaps using <code>python -m trace -t myscript.py</code> will show you the trace you're interested in.</p>
python|bash|debugging
1
1,909,739
66,040,824
subprocess call unable to find dot although it's installed
<p>I'm following this <a href="https://gist.github.com/WillKoehrsen/ff77f5f308362819805a3defd9495ffd" rel="nofollow noreferrer">this sample code</a> provided by <a href="https://towardsdatascience.com/how-to-visualize-a-decision-tree-from-a-random-forest-in-python-using-scikit-learn-38ad2d75f21c" rel="nofollow noreferr...
<p>As you can see, the error is at the line</p> <pre><code>call(['dot', '-Tpng', 'tree.dot', '-o', 'tree.png', '-Gdpi=600']) </code></pre> <p>and comes down to</p> <pre><code>hp, ht, pid, tid = _winapi.CreateProcess(executable, args, </code></pre> <p>in the <code>subprocess</code> module. So it seems that the <code>exe...
python|scikit-learn|anaconda|spyder
0
1,909,740
69,063,573
Replace abitrary HTML (subtree) within HTML document with other HTML (subtree) with BS4 or regex
<p>I am trying to build a function along the following lines:</p> <pre class="lang-py prettyprint-override"><code>import bs4 def replace(html: str, selector: str, old: str, new: str) -&gt; str: soup = bs4.BeautifulSoup(html) # likely complete HTML document old_soup = bs4.BeautifulSoup(old) # can contain H...
<p>The solution below works in three parts:</p> <ol> <li><p>All matches of <code>selector</code> from <code>html</code> are discovered.</p> </li> <li><p>Then, each match (as a <code>soup</code> object) is recursively traversed and every child is matched against <code>old</code>.</p> </li> <li><p>If the child object is ...
python|html|beautifulsoup
1
1,909,741
69,213,247
Why is my VSCode trying to use cuda even though I installed directml (I'm on amd)?
<p>I have a tensor flow object detection project I want to build and read that it would be slow on cpu. Thats when someone told me to use directml because I have an AMD gpu and not a NVIDIA one.</p> <p>I have created an anaconda environment which I called &quot;directml&quot; and installed tensorflow and directml on it...
<p>You shouldn't install tensorflow only tensorflow-directml. Because now python is importing tensorflow not tensorflow-directml. Uninstall tensorflow and it should fix imports.</p>
python|python-3.x|tensorflow
0
1,909,742
68,376,731
How to read picke files using pyarrow
<p>I have a bunch of code for reading multiple <code>pickle</code> files using <em><strong>Pandas</strong></em>:</p> <pre><code>dfs = [] for filename in glob.glob(os.path.join(path,&quot;../data/simulated-data-raw/&quot;, &quot;*.pkl&quot;)): with open(filename, 'rb') as f: temp = pd.read_pickle...
<p>FYI, <code>pyarrow.read_serialized</code> is deprecated and you should just use arrow <code>ipc</code> or python standard <code>pickle</code> module when willing to serialize data.</p> <p>Anyway I'm not sure what you are trying to achieve, saving objects with Pickle will try to deserialize them with the same exact t...
python|pandas|pickle|apache-arrow
2
1,909,743
59,216,555
Len function not returning the correct value for string
<p>So I am trying to call the length of a coded message, and then divide that length by 3 (every 3 chars represents one letter). Here is the message:</p> <pre><code>10311132-10710510810832-121111117114115101108102 </code></pre> <p>The dashs are set to be placed directly after spaces, or the letters a, b, or c (becaus...
<p>Because you've initiated <code>message</code> as an int. You can fix this by putting quotes around it:</p> <pre><code>message = ('10311132-10710510810832-121111117114115101108102') </code></pre> <p>At the moment, converting message to a string afterwards converts it <em>after</em> it has performed the minus operat...
python|string-length
3
1,909,744
59,405,888
Mismatch between janusgraph date value and gremlin query result
<p>I have some graph data with date type values. My gremlin query for the date type property is working, but output value is not the date value.</p> <p>Environment:</p> <ul> <li>Janusgraph 0.3.1 </li> <li>gremlinpython 3.4.3</li> </ul> <p>Below is my example:</p> <ul> <li>Data (JanusGraph): <code>{"ID": "doc_1", "M...
<p>There were some issue with Python and dates but I would have them fixed for 3.4.3, which is the version you stated you were using. The issue is described here at <a href="https://issues.apache.org/jira/browse/TINKERPOP-2264" rel="nofollow noreferrer">TINKERPOP-2264</a> along with the fix, but basically there were so...
gremlin|janusgraph|gremlinpython
1
1,909,745
35,766,034
Group list of objects based on close datetime attribute
<p>Say I have a list of objects. Each of these has a string representing a date (parseable by dateutil). How can I go about grouping these in a list of lists, in which each sublist contains consecutive (within 5 minutes) objects? For example:</p> <pre><code>o1.time = "2016-03-01 23:25:00-08:00" o2.time = "2016-03-01 2...
<p>Take a look at <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">groupby</a> function from itertools. It takes a list of objects and groups them according to a key function. Your code could look like this</p> <pre><code>from dateutil.parser import parse from iter...
python
3
1,909,746
35,768,633
Matplotlib bar plot remove internal lines
<p>I have a bar plot with high resolution. Is it possible to have only the border/frame/top line of the plot like in the following ROOT plot without, i.e. without internal lines?</p> <p><a href="https://i.stack.imgur.com/Lqmuk.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/Lqmuk.gif" alt="ROOT plot, empty i...
<p>Found out the answer: the simplest way to achieve the desired look is to use <code>plt.step</code> instead of <code>plt.bar</code>, that simple. Feel shame for asking.</p> <p><img src="https://i.stack.imgur.com/WioH8.png" alt="step plot"></p>
python|matplotlib|plot|histogram
13
1,909,747
31,485,636
Pygame, user input on a GUI?
<p>I need a user input for my <code>pygame program</code>, but I need it on my <code>GUI(pygame.display.set_mode etc.)</code>, not just like: <code>var = input("input something")</code>. Does anybody have suggestions how to do this?</p>
<p>There are some answers already here. Anyway, use PGU (Pygame GUI Utilities), it's available on pygame's site. It turns pygame into GUI toolkit. There is an explanation on how to combine it and your game. Otherwise, program it yourself using key events. It's not hard but time consuming and boring.</p>
python|pygame
0
1,909,748
15,528,228
replace letters in python string
<p>Im writing a program for french that turns present tense verbs into past tense. The problem is that I need to replace letters but they are user inputed so I have to have it replacing the letters from the end of the line. Here's what I have so far, but it doesn't change the letters it just gives an error:</p> <pre><...
<p>IMO there might be a problem with the way you are using replace. The syntax for replace is explained. <a href="http://docs.python.org/2/library/string.html#string.replace" rel="nofollow" title="Python string replace method">here</a></p> <pre><code>string.replace(s, old, new[, maxreplace]) </code></pre> <p>This ipy...
python
2
1,909,749
59,857,203
Remove border from matplotlib 3D pane
<p>I would like to remove the borders from my 3D scene as described below. Any idea how to do that?</p> <p><a href="https://i.stack.imgur.com/z1kyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z1kyA.png" alt="enter image description here"></a></p> <p>Here the code to generate the current scene:<...
<p>I usually set the alpha channel to 0 for spines and panes, and finally I remove the ticks: </p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Create figure plt.style.use('dark_background') # Dark theme fig = plt.figure() ax = fig.add_subplot(111, projection='3d') # Make pane...
python|matplotlib|mplot3d
2
1,909,750
59,699,781
How to fix broken up text with python docx to get free text for Ebooks?
<p>I'm trying to edit a free Ebook I found online into easily readable text for Kindle, with headers and full paragraphs. </p> <p>I'm very new to Python and coding in general so I don't really have any progress.</p> <p>Each line is separated by a break with Enter, so each line is considered a separate Paragraph by py...
<p>I used the docx library that is not installed by default, you can use pip or conda:</p> <pre><code>pip install python-docx conda install python-docx --channel conda-forge </code></pre> <p>After install:</p> <pre><code>from docx import Document doc = Document(r'path\to\file\pride_and_prejudice.docx') all_text=[] a...
python|ms-word|python-docx
0
1,909,751
59,705,670
astropy.table writing problems
<p>I'm having problems to write astropy.tables, since yesterday when I updated to astropy 4.0, I cannot write tables into files.</p> <p>I even tried to copy the examples in the <a href="https://docs.astropy.org/en/stable/io/ascii/index.html" rel="nofollow noreferrer">astropy web</a> like:</p> <pre><code>import numpy...
<p>After two downgrades and upgrades the problem resolved itself... I still don't know what happened but it's no longer displaying that odd behaviour. Thanks in any case! </p>
python|ascii|astropy
0
1,909,752
59,774,433
Python load .txt as array
<p>Just have a colors.txt file with data: </p> <pre><code>[(216, 172, 185), (222, 180, 190), (231, 191, 202), (237, 197, 206), (236, 194, 204), (227, 184, 194), (230, 188, 200), (232, 192, 203), (237, 199, 210), (245, 207, 218), (245, 207, 218)] </code></pre> <p>now just try to read this in python as an array</p> <p...
<p>The problem is that you are appending in string data from your file, when you really want a <code>list</code>. So use <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow noreferrer"><code>literal_eval</code></a> to safely evaluate the data type:</p> <pre class="lang-py prettyprint-ov...
python|arrays|numpy|file
2
1,909,753
49,011,681
I'm trying to create a sorting algorithm to find all combinations that would yield a certain result, but keep getting an error about the index
<p>the data is a numpy array (784,)</p> <p>here is the sorting function:</p> <pre><code>while flips &lt; max_flip: flipped_accuracy = 0 combination = [] while flipped_accuracy &lt;= original_accuracy: i_vals = [] for i in range(flips): i_vals.append(i) index = 1 ...
<p>The following code seems to be the likely culprit:</p> <pre><code>if i_vals[-index] &lt; 784: # ... i_vals[-index] += 1 </code></pre> <p>If <code>i_vals[-index]</code> is <code>783</code> it will be increased to <code>784</code>, so the next time that value is used as the index it will cause the error.</p>
python|sorting|numpy
0
1,909,754
25,264,958
An "Expecting property name:" error started coming - OAuth 2.0 Google APIs Client Library for Python
<p>I took this example from <a href="https://developers.google.com/youtube/v3/code_samples/python#retrieve_my_uploads" rel="nofollow">google code samples.</a> It was working earlier, but suddenly it stopped working. I tried reseting everything. Still not luck.</p> <p>What is that I'm doing wrong?</p> <p>Here is the e...
<p>I found the problem. I had added extra parameters in the <code>client_secrets.json</code> which is why <code>flow_from_clientsecrets()</code> wasn't able to parse it. It started working after I removed them.</p>
python|google-api-python-client
0
1,909,755
25,371,594
Is there a way to make this Python function to pull data from a ftp site better?
<p>I've created python function to extract data from an ftp site. It works well. However, there are a lot of try/except statements. I read about using a python "with" statement to make this better but I'm not clear how that will improve the function. Here is the code:</p> <pre><code>HOST = 'ftp.osuosl.org' DIRN = 'deb...
<p>In general this style works well. There's a try/except block per interesting section of code, so you can communicate specific details about the error to the caller.</p> <p>The code has <code>f.quit()</code> in several places. This is fine, but it's easy to lose track of which cases should have <code>quit</code> a...
python|ftp
0
1,909,756
25,138,524
List Append Conditionals
<p>In this specific situation, How do I make a proper if conditional that appends only a price value for example below 53 to a list?</p> <pre><code>offers_list = re.findall("&lt;div class=\"list\"(.*?)&lt;/div&gt;", http_response_body, re.DOTALL) # Find list of offers in HTTP Response Body price_list = [] offers_list2...
<p>Assuming your regex works properly, something like this would probably do:</p> <pre><code>for price in a: if int(price)&lt;=53: price_list.append(price) offers_list2.append(price) </code></pre> <p>Also, <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-sel...
python|list|conditional
2
1,909,757
70,765,082
“ warnings.warn('the tensorboard callback does not support '”
<p>“ warnings.warn('the tensorboard callback does not support '” when i wanted to use the Tensorboard ,i meet such promblem <a href="https://i.stack.imgur.com/fqOYh.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>You didn't list the callback in <code>model.fit</code> call.</p> <p>Try:</p> <pre><code>tb_callback = Tensorboard(...) model.fit(..., callbacks=[tb_callback]) </code></pre> <p>I didn't like naming the callback <code>Tensorboard</code>, so I changed it to <code>tb_callback</code>. Then I told <code>model.fit</code> t...
python|tensorflow|keras
0
1,909,758
70,978,135
Python - reorder pandas Dataframe rows based on column values
<p>I have a dataframe with 2 columns : id , antecedent_id I would like a code to reorder the dataframe in the right order using antecedent_id. The first id is the one with antecedent_id empty</p> <p>Dataframe example:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center...
<p>You basically want to sort the dataframe by values in a column:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd df = pd.DataFrame({ &quot;id&quot;: [&quot;id1&quot;, &quot;id4&quot;, &quot;id6&quot;, &quot;id7&quot;, &quot;id3&quot;, &quot;id2&quot;, &quot;id5&quot;], &quot;antecedent...
python|dataframe|sorting
0
1,909,759
70,830,748
convert list of lists to a list of smaller tuples
<p>I need some help with converting a list of equal sized lists <code>x</code> to a list of tuples such that each tuple should be the length of <code>x</code></p> <pre><code>x = [ ['4', '8', '16', '32', '64', '128', '256', '512', '1,024'], ['1,200', '2,400', '4,800', '4,800', '6,200', '6,200', '6,200', '6,200', '6,200...
<p>Use <code>zip</code> with unpacking operator <code>*</code>:</p> <pre><code>out = list(zip(*x)) </code></pre> <p>Output:</p> <pre><code>[('4', '1,200', '300'), ('8', '2,400', '600'), ('16', '4,800', '1,200'), ('32', '4,800', '2,400'), ('64', '6,200', '3,200'), ('128', '6,200', '3,200'), ('256', '6,200', '4,000...
python
4
1,909,760
60,041,813
Use IPython Widget Button to call Keras Training Function
<p>I would like to use an ipython button to run a function that trains a deep learning model using Keras's fit.generator() and ImageDataGenerator(). I tried to use <strong>lambda</strong> to pass the arguments to the function, but it returns <code>TypeError: expected str, bytes or os.PathLike object, not Button.</code>...
<p>Your <code>lambda</code> is bound to the <code>Button</code> class it was passed into, <a href="https://stackoverflow.com/questions/27627080/lambda-function-passing-not-desired-self">which implicitly made the first parameter the <code>Button</code> object itself.</a> The result was that the <code>trainpath</code> pa...
python|tensorflow|keras|jupyter-notebook
0
1,909,761
60,093,370
How is bitmap arrays more efficient than logical arrays?
<p>So, I am new to bitmaps. Please pardon the level of my question. I am trying to make a decision on the type of datastructure I should be using to make pairwise comparisons on vectors. </p> <p>I was told to use bitmaps instead of the representing each vector (40k in total),</p> <pre><code>v1 ={ 12,78,96,87,100,...}...
<p>Generally bitmaps are used to deal with a large number of related booleans in a memory-compact way. Such as, if you had 16 booleans, you could use a single bitmap to encode all of their states in a single 16-bit integer.</p> <p>It sounds like you want to compare more abstract vectors, in which case it doesn't sound...
python|arrays|data-structures|bitmap
0
1,909,762
60,201,221
PySpark execute plain Python function on each DataFrame row
<p>I have Spark DataFrame <strong>DF1</strong> with millions of rows. Each row have up to 100 columns. </p> <pre><code>col1 | col2 | col3 | ... | colN -------------------------------- v11 | v12 | v13 | ... | v1N v21 | v22 | v23 | ... | v2N ... | ... | ... | ... | ... </code></pre> <p>Also, I have another Dat...
<p>You can achieve that using SQL expressions which can be evaluated using <a href="https://stackoverflow.com/questions/60201221/pyspark-execute-plain-python-function-on-each-dataframe-row"><code>expr</code></a>. However, you'll not be able to join the 2 DataFrames as SQL expressions can't be evaluated as column values...
python|dataframe|apache-spark|pyspark|apache-spark-sql
1
1,909,763
60,105,540
Translate curl post to python requests post
<p>I am trying to upload an XML file to an <strong>IIS</strong> server using <strong>Python 3.8.1</strong> and <strong>requests</strong>. I have successfully done this many times using <strong>curl</strong>. This works:</p> <pre><code>curl -v -H "Content-Type: text/xml" --data-binary @MS1481_20200204_163918_4461289.xm...
<p>A 400 error indicates that something is wrong with your client side input.</p> <p>Is the file getting properly opened and read? You should use either the <code>with</code> condition to open it,</p> <pre><code>with open(path) as f: print(type(f)) </code></pre> <p>or make sure you read it with this <code>open(x...
post|python-requests
0
1,909,764
2,703,029
Why isn't the regular expression's "non-capturing" group working?
<p>In the snippet below, the <strong>non-capturing group <code>"(?:aaa)"</code></strong> should be ignored in the matching result,</p> <p>The result should be <code>"_bbb"</code> only.<br></p> <p>However, I get <code>"aaa_bbb"</code> in the matching result; only when I specify group(2) does it show <code>"_bbb"</code...
<p>I think you're misunderstanding the concept of a "non-capturing group". The text matched by a non-capturing group still becomes part of the overall regex match.</p> <p>Both the regex <code>(?:aaa)(_bbb)</code> and the regex <code>(aaa)(_bbb)</code> return <code>aaa_bbb</code> as the overall match. The difference i...
python|regex
126
1,909,765
5,735,841
TypeError: 'list' object is not callable while trying to access a list
<p>I am trying to run this code where I have a list of lists. I need to add to inner lists, but I get the error </p> <pre><code>TypeError: 'list' object is not callable. </code></pre> <p>Can anyone tell me what am I doing wrong here.</p> <pre><code>def createlists(): global maxchar global minchar global ...
<p>For accessing the elements of a list you need to use the square brackets (<code>[]</code>) and not the parenthesis (<code>()</code>).</p> <p>Instead of:</p> <pre><code>print wordlists(len(words)) </code></pre> <p>you need to use:</p> <pre><code>print worldlists[len(words)] </code></pre> <p>And instead of:</p> ...
python|callable
87
1,909,766
42,983,906
How to use `apply()` or other vectorized approach when previous value matters
<p>Assume I have a DataFrame of the following form where the first column is a random number, and the other columns will be based on the value in the previous column.</p> <p><a href="https://i.stack.imgur.com/sDcvN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sDcvN.png" alt="enter image descripti...
<p>What you're describing is a recurrence relation, and I don't think there is currently any non-loop way to do that. Things like <code>apply</code> and <code>rolling_apply</code> still rely on having all the needed data available before they begin, and outputting all the result data at once at the end. That is, they...
python|python-3.x|pandas
4
1,909,767
65,683,150
How to fix problem of "ModuleNotFoundError: No module named 'PIL'"?
<p>I tried with the solution given in 'stackoverflow', but not resolved.</p> <p>I am trying to extract text from images with the help of <strong>pytesseract</strong> module from python.</p> <p>The following are the steps I followed:</p> <p>code:</p> <pre><code>py -m pip install --user virtualenv py -m venv tessa #creat...
<p>It is saying that the module named <a href="https://pypi.org/project/Pillow/" rel="nofollow noreferrer">Pillow(PIL)</a> is missing. You can install it using pip. Enter the following in Command Line.</p> <pre><code>pip install Pillow </code></pre>
python|python-imaging-library|python-tesseract
2
1,909,768
60,507,576
pytesseract not idenfiying digits properly as well it is detecting dashed 0 as 8
<p>Pytesseract unable to identify proper characters as well it is predicting slashed zero wrong.</p> <p>Here is my Image: <img src="https://i.stack.imgur.com/HJI95.png" alt="enter image description here"></p> <pre><code>from PIL import Image import pytesseract import cv2 import numpy as np img = cv2.imread('dilation...
<p>For any image, you need to <strong>preprocess</strong> it make it detect more easily some methods are</p> <ul> <li>1.grayscale image</li> <li>2.erosion</li> <li>3.opening - erosion followed by dilation</li> <li>4.canny edge detection</li> <li>5.skew correction</li> <li>6.template matching</li> </ul> <p>Choose whic...
python-3.x|python-tesseract
0
1,909,769
58,093,439
Copying numpy array with '=' operator. Why is it working?
<p>According to <a href="https://stackoverflow.com/a/19676762/6740589">this</a> answer, <code>B=A</code> where <code>A</code> is a numpy array, <code>B</code> should be pointing to the same object <code>A</code>.</p> <pre><code>import cv2 import numpy as np img = cv2.imread('rose.jpeg') print("img.shape: ", np.shape(...
<p>The "problem" is that your not using numpy here but opencv and while numpy array.resize() is in-place opencv img.resize() is not.</p> <p>So your call to </p> <pre><code> img = cv2.resize(img, (250,100)) </code></pre> <p>creates a new object (image) with the given size. So here the img variable will point to a ...
python|numpy
1
1,909,770
57,750,843
BeautifulSoup Loop Thru Items
<p>I have a page that has the following structure </p> <pre><code>&lt;div class="cloud-grid margin-bottom-40"&gt; &lt;div class="cloud-grid__col is-6"&gt; &lt;a href="https://cloud.google.com/bigquery/" track-type="navigateTo" track-name="link" track-metadata-eventdetail="bigQuery" track-metadata-position="body" tra...
<p>A slightly different approach: There are equal numbers of these items, and a regular structure, so you could use join the three items as a list within a list comprehension. Title and link can both come from elements with class <code>cloud-product-card__headline</code>, and then the description is the <code>next_sibl...
python|beautifulsoup
0
1,909,771
57,759,840
How to count elements in an array withtin a given increasing interval?
<p>I have an array of time values. I want to know how many values are in each 0.05 seconds window. </p> <p>For example, some values of my array are: <code>-1.9493, -1.9433, -1.911 , -1.8977, -1.8671,..</code></p> <p>In the first interval of 0.050 seconds (from -1.9493 to -1.893) I´m expecting to have 3 elements</p> ...
<p>One of the variants:</p> <pre><code>import numpy as np # original array a = [-1.9493, -1.9433, -1.911 , -1.8977, -1.8671] step = 0.05 bounds = np.arange(min(a), max(a) + step, step) result = [ list(filter(lambda x: b[i] &lt;= x &lt;= b[i+1], a)) for i in range(len(b)-1) ] </code></pre>
python
1
1,909,772
18,619,300
python: checking for errors in the users input
<p>I would like to check if a string can be a float before I attempt to convert it to a float. This way, if the string is not float, we can print an error message and exit instead of crashing the program. so when the user inputs something, I wanna see if its a float so it will print "true" if its not then it will print"f...
<p>The only reliable way to figure out whether a string represents a float is to try to convert it. You could check first and convert then, but why should you? You'd do it twice, without need.</p> <p>Consider this code:</p> <pre><code>def read_float(): """ return a floating-point number, or None """ w...
python-2.7
0
1,909,773
18,254,854
How to enumerate possible reconstructions of a Hamiltonian cycle without DFS/BFS?
<p>I have a directed Hamiltonian cycle:</p> <pre><code>[..., a, b, ... , c, d, ..., e, f, ...] </code></pre> <p>Where <code>b = next(a)</code>, <code>d = next(c)</code>, and <code>f = next(e)</code>.</p> <p>Say I delete edges (a, b), (c, d), and (e, f). </p> <p><strong>Question</strong>: How do I generate all possi...
<p>Thanks to this helpful answer <a href="https://stackoverflow.com/a/18272004/290443">here</a>, here's the code that does it.</p> <pre><code>from itertools import chain, permutations, product def new_edge_sets(deleted_edges): def edges_to_pieces(l): new_list = [] n = len(l) for i in xran...
python|graph
2
1,909,774
55,209,211
Why can't I make a column with extracted months from the 'dates' column in my DataFrame?
<p>I have a dataframe with dates, and I want to make a column with only the month of the corresponding date in each row. First, I converted my dates to ts objects like this:</p> <pre><code>df['Date'] = pd.to_datetime(df['Date']) </code></pre> <p>After that, I tried to make my new column for the month like this:</p> ...
<p>You have to use property (or accessor object) <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html" rel="nofollow noreferrer">dt</a></p> <p><code>df["month"] = df.date.dt.month</code></p>
python|pandas|dataframe|timestamp
1
1,909,775
57,638,772
Creating a matrix from the data inside the csv
<p>I'm reading a CSV-file (data is comma separated), appending the two columns inside this file into two different arrays named 'x_train' and 'y_train'. The problem is that I can't manage to form the data the way I wanted to. So, to summarise; I want each entry for row[0] to be appended in x_train and row[1] for y_trai...
<p>If you need every number inside a list you can do it directly while appending in to <code>x_train</code> and <code>y_train</code>:</p> <pre><code>import numpy as np import csv x_train = [] y_train = [] with open("length_weight.csv", newline='') as csvfile: reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNU...
python|csv|linear-regression
0
1,909,776
42,395,318
Row wise extraction of common elements from 2 lists of list
<p>I have two lists of list with equal len in Python (let's say 3 for this example).</p> <pre><code>A = [['Horse','Duck','Goat'],['Rome','New York'],['Apple','Rome','Goat','Boat']] B = [['Carrot','Duck'],['Car','Boat','Plane'],['Goat','Apple','Boat']] </code></pre> <p>I would like to match elements in each row and c...
<p>Using <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehension</a> and <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow noreferrer"><code>zip</code></a>:</p> <pre><code>&gt;&gt;&gt; A = [['Horse','Duck','Goat'],['Ro...
python|list
3
1,909,777
42,499,656
Pass all arguments of a function to another function
<p>I want to have a class that I can create subclasses of that has a print function that only prints on a particular condition.</p> <p>Here's basically what I'm trying to do:</p> <pre><code>class ClassWithPrintFunctionAndReallyBadName: ... def print(self, *args): if self.condition: print(*...
<p>The standard way to pass on all arguments is as @JohnColeman suggested in a comment:</p> <pre><code>class ClassWithPrintFunctionAndReallyBadName: ... def print(self, *args, **kwargs): if self.condition: print(*args, **kwargs) </code></pre> <p>As parameters, <code>*args</code> receives a t...
python
30
1,909,778
54,052,307
Install a python package/module from github in local folder an use it
<h2>Issue</h2> <p>I would like to install with <code>pip3</code> a python module from github into a local folder named <code>local_lib/</code> and then use it in a script, <strong>without any virtualenv</strong>.</p> <h2>Context</h2> <p>Here is my folder structure :</p> <pre><code>. +-- local_lib/ // Folder where t...
<p>You have to tell Python that it has to look in <code>local_lib</code> for modules. E.g. by adding it to <a href="https://docs.python.org/3/library/sys.html?highlight=sys%20path#sys.path" rel="nofollow noreferrer"><code>sys.path</code></a> in your script (<em>before</em> importing from it) or by adding it to your <a ...
python|python-3.x|pip
2
1,909,779
53,976,574
How to safely truncate a quoted string?
<p>I have the following string:</p> <pre class="lang-none prettyprint-override"><code>Customer sale 88% in urm 50 </code></pre> <p>Quoted with <code>urllib.parse.quote</code>, it becomes:</p> <pre class="lang-none prettyprint-override"><code>Customer%20sale%2088%25%20in%20urm%2050%27 </code></pre> <p>Then I need to...
<p><code>urllib.quote</code> uses percent-encoding as defined in <a href="https://www.rfc-editor.org/rfc/rfc3986.html#section-2.1" rel="nofollow noreferrer">RFC 3986</a>. This means that encoded character will always be of the form <code>&quot;%&quot; HEXDIG HEXDIG</code>.</p> <p>So you simply can delete any trailing r...
python|urllib
4
1,909,780
70,672,820
How to extract one of the histogram plots resulting from using pd.Dataframe.hist()?
<p>when I use the hist() from Pandas it produces a series of histograms for all the features in the dataset. I want to know how to extract/select/reference only one of the histograms returned by hist()?</p> <p>For example, let'say I have the following code:</p> <pre><code>import pandas as pd import numpy as np import m...
<p>I believe you can pass in a column name to hist() in order to select one of the histograms.</p> <pre><code>df.hist(column = column_name) </code></pre>
python|pandas|matplotlib
0
1,909,781
55,739,779
How to display the correct date century in Pandas?
<p>I have following data in one of my columns:</p> <pre><code>df['DOB'] 0 01-01-84 1 31-07-85 2 24-08-85 3 30-12-93 4 09-12-77 5 08-09-90 6 01-06-88 7 04-10-89 8 15-11-91 9 01-06-68 Name: DOB, dtype: object </code></pre> <p>I want to convert this to a datatype column. I tried following:...
<p>You can first convert to datetimes and if years are above or equal <code>2020</code> then subtract <code>100</code> years created by <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#dateoffset-objects" rel="nofollow noreferrer"><code>DateOffset</code></a>:</p> <pre><code>df['DOB'] = p...
python|pandas|date
7
1,909,782
55,858,066
Radiobutton navigation and value storing
<p>I am trying to write a multiple choice quiz using Python Tkinter. I have a 2 part question. I have radio buttons that display the choices and collect the selected option. I also have a created a button to navigate to the next question or back to the previous question as well as another button to view the score.</p> ...
<p>Unfortunately, I think you need change the fundamental architecture of your program and make it much more object-oriented. Specifically, <em>instead</em> of having a bunch of separate <code>list</code>s like you have:</p> <pre><code># question list q = [ "question 1", "question 2", "question 3", "question 4" ] ...
python|python-3.x|list|tkinter|radio-button
1
1,909,783
55,942,223
Is there way to write hdf5 files row by row in Python?
<p>For CSV files we could use</p> <pre><code>writer = csv.writer(output) writer.writerow([a, b, c, d]) </code></pre> <p>Is there anything like that for writing Hdf5 files? </p>
<p>If you are not bound to a specific technology, check out <a href="http://www.hdfql.com" rel="nofollow noreferrer">HDFql</a> as this will alleviate you from low-level details when dealing with HDF5 files.</p> <p>To solve your question, you need to create a dataset with two dimensions: the first is extendible and the...
python|hdf5|pytables|hdfql
1
1,909,784
55,827,589
Skipping duplicated when generating combinations
<p>I have this code: </p> <pre><code>from collections import Counter def groups(d, l, c = []): if l == len(c): yield c else: for i in d: if i not in c: _c = Counter([j for k in [*c, i] for j in k]) if all(j &lt; 3 for j in _c.values()): yield from groups...
<p>You are reinventing the wheel. Simply use <code>itertools.combinations</code>:</p> <pre><code>from itertools import combinations data = [(1, 2), (2, 3), (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 4)] print(list(combinations(data, 3))) # [((1, 2), (2, 3), (2, 4)), ((1, 2), (2, 3), (2, 5)), ... </code></pre> <p>Yo...
python
1
1,909,785
73,328,031
Get timestamps with the same time_zone from all nodes in distributed system with Python
<p>I am building a mechanism to store information with the timestamp in a distributed system. Assuming that the information from all nodes in a distributed system will be merged together and sorted according to timestamp, how to make sure that all the timestamps from all systems refer to the same time_zone in Python?</...
<p>If you want synchronize data with time, System time is not good idea for distributed systems. In distributed systems, system time is unreliable. There are many different scenarios where a simple failure. Example scenarios:</p> <ul> <li>Someone can change local time on machine(or accidentally)</li> <li>Out-of-date ma...
python|python-datetime|distributed-system
0
1,909,786
73,353,124
Dedupe a list of dicts where the match criteria is multiple key value pairs being identical
<p>For the given sample input list, I want to dedupe the dicts based on the values of the keys <code>code</code>, <code>tc</code>, <code>signal</code>, and <code>in_force</code> all matching.</p> <h5>sample input:</h5> <pre><code>signals = [ None, None, {'code': 'sr', 'tc': 0, 'signal': '2U-2D', 'in_force':...
<p>I'd suggest something like this, with only Python's standard library:</p> <pre><code>result = [] seen = set() for s in signals: if not isinstance(s, dict): continue signature = (s['code'], s['tc'], s['signal'], s['in_force']) if signature in seen: continue seen.add(signature) result.append(s) </code></pre>
python|dictionary|filter|duplicates
4
1,909,787
49,985,574
create nested dictionary or collection counter with pandas and python
<p>I would like to create a nested dictionary or Collection in python by grouping</p> <pre><code>seriesA = ["groupA", "groupA", "groupB", "groupB", "groupC"] seriesB = ["item1", "item1," "item3", "item1", "item2"] </code></pre> <p>Desired output:</p> <pre><code>{ 'groupA': {'item1': 2}, 'groupB': {'item3': 1}, {'i...
<p>I'd use <code>collections.defaultdict</code> and <code>collections.Counter</code>:</p> <pre><code>from collections import defaultdict, Counter from pprint import pprint seriesA = ["groupA", "groupA", "groupB", "groupB", "groupC"] seriesB = ["item1", "item1", "item3", "item1", "item2"] nested_dict = defaultdict(Co...
python|pandas|dictionary|counter
4
1,909,788
66,449,526
concat 2 dataframes by multiindex
<p>Here I have two Nx1 dataframes(ds and code are indices, not columns). My purpose is, for each day, to concat open and close by code.</p> <pre><code>df1: ds code open 20160101 001 1.4 002 1.3 003 1.2 ``` ``` ``` 20201231 001 ...
<p>you can use <code>join</code> or <code>merge</code> to merge two dataframe.</p> <pre><code>df = df1.join(df2, how='outer') </code></pre> <p>if the index is not unique, <code>pd.concat</code> with <code>axis=1</code> will not work.</p>
python|pandas|concatenation
1
1,909,789
53,078,014
migrate error 'No migration to apply' also not add table in postgresql in django
<p>I'm trying to create a model for an eCommerce site but after makemigrations when I trying to migrate terminal show "No migration to apply" but when I checked database no new table was there. Please help me.</p> <p>`</p> <pre><code>from django.db import models from django.utils import timezone # Create your model...
<pre><code>python manage.py migrate product </code></pre> <p>After migrate with the specific model name it's worked for me.</p>
python|django|postgresql
0
1,909,790
53,324,596
Problems when implementing Keras model in Tensorflow
<p>I'm just starting off with <code>Tensorflow</code>.</p> <p>I tried implementing a model to classify digits in the MNSIT dataset.</p> <p>I am familiar with <code>Keras</code>, so I first used it to create the model.</p> <p>Keras code:</p> <pre><code>from keras.models import Sequential from keras.layers import Den...
<p>Turns out, the problem was that I initialized the weights as zeros!</p> <p>Simply changing</p> <pre><code>w = tf.Variable(tf.zeros([784, 700])) w2 = tf.Variable(tf.zeros([700, 500])) w3 = tf.Variable(tf.zeros([500, 500])) w4 = tf.Variable(tf.zeros([500, 500])) w5 = tf.Variable(tf.zeros([500, 10])) </code></pre> <...
python|python-3.x|tensorflow|keras|neural-network
1
1,909,791
71,535,403
When I run the code in vs code, the results seem to appear and then disappear quickly, how do I fix this?
<p>I downloaded Anaconda and VS Code and tried to link them. However, when I just test very simple code that just prints &quot;hello world&quot;, it did not show the result in the terminal. So I tried to change the default terminal setting to one of other options (Command Prompt, Powershell, Windows Powershell), but no...
<p>After starting your application (debug mode), click View &gt; Output (Ctrl + Alt + O) to show the output window. Stop your application and restart Visual Studio. Next time you run your application the output window should be visible automatically because Visual Studio remembers your opened windows in debug mode.</p>
python|visual-studio-code|printing|terminal|anaconda
1
1,909,792
62,805,349
using python read a column 'H' from csv and implement this function SUM(H16:H$280)/H$14*100
<p>Using python read a column <code>'H'</code> from a dataframe and implement this function:</p> <pre class="lang-py prettyprint-override"><code>CDF = {SUM(H1:H$266)/G$14}*100 </code></pre> <p>Where:</p> <ul> <li><code>H$266</code> is the last element of the column, and</li> <li><code>G$14</code> is the total sum of th...
<p>As an example, you could do this:</p> <pre class="lang-py prettyprint-override"><code>from pandas import Series s = Series([1, 2, 3]) # H1:H266 data sum_of_s = s.sum() # G14 def calculus(subset, total_sum): return subset.sum() / total_sum * 100 result = Series([calculus(s.iloc[i:], sum_of_s) for i in range(...
python|python-3.x|pandas|python-2.7|dataframe
0
1,909,793
62,610,277
python win32print can't set custom page size
<p>i am trying to print pdf file with custom page size in python with win32print i can change other setting like number of copies but setting custom page length and width is not working it always try to fit pdf content into page by covering whole page this is my code</p> <pre><code>printers=win32print.EnumPrinters(win...
<p>I am not sure if this also applies in this case. But from the class <a href="https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-printerconfiguration" rel="nofollow noreferrer">documentation</a>, I remember that the values for the mentioned attributes were assigned as <code>(Tenths of a millimeter)</co...
python|winapi|printing
0
1,909,794
70,264,794
Combine two lists while adding common values
<p>I have two lists of sets I'd like to combine, while adding the second set value when the first value matches.</p> <p>Example input:</p> <pre><code>listOne = [('a', 1), ('b', 3), ('c', 2), ('d', 5)] listTwo = [('a', 2), ('b', 1), ('c', 4)] </code></pre> <p>Desired output:</p> <pre><code>[('a', 3), ('b', 4), ('c', 6),...
<pre><code>from collections import Counter result = list((Counter(dict(listOne)) + Counter(dict(listTwo))).items()) </code></pre>
python
4
1,909,795
70,199,053
transpose the output of a sql output using pyspark
<p>I have a sparksql select query as below</p> <pre class="lang-sql prettyprint-override"><code>select max(age),min(age),avg(age),max(sal),min(sal),avg(sal) from Emp; </code></pre> <p>Output dataframe is getting created as below:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-a...
<p>The easiest way would be to run two queries (one for <code>sal</code> and one for <code>age</code> and <code>union</code> them.</p> <pre class="lang-sql prettyprint-override"><code>select 'age' as column, max(age) as max, min(age) as min, avg(age) as avg from Emp; select 'sal' as column, max(sal) as max, min(sal) as...
python|dataframe|pyspark|apache-spark-sql
1
1,909,796
10,916,960
Python Memory error solutions if permanent access is required
<p>first, I am aware of the amount of Python memory error questions on SO, but so far, none has matched my use case.</p> <p>I am currently trying to parse a bunch of textfiles (~6k files with ~30 GB) and store each unique word. Yes, I am building a wordlist, no I am not planning on doing evil things with it, it is for...
<p>You're probably going to need to store the keys on disk. A key-value store like <a href="http://redis.io/" rel="nofollow">Redis</a> might fit the bill.</p>
python|memory|python-2.7
3
1,909,797
56,450,107
Kivy label opacity not being consistent
<p>I am learning the basics of Kivy and going through tutorials. I noticed that when I start a Kivy app, the opacity of the labels are not consistent. Sometimes when I start the app, some labels are full opacity while others are half opacity. </p> <p><img src="https://i.imgur.com/HX5U7aP.png" alt="showing 3 half opaci...
<p>It's a bug that appeared during an sdl2 version update. It's fixed in Kivy 1.11, released a couple of days ago, make sure your Kivy is up to date.</p>
python|kivy
2
1,909,798
17,686,351
shell start / stop for python script
<p>I have a simple python script i need to start and stop and i need to use a start.sh and stop.sh script to do it. </p> <p>I have start.sh: </p> <pre><code>#!/bin/sh script='/path/to/my/script.py' echo 'starting $script with nohup' nohup /usr/bin/python $script &amp; </code></pre> <p>and stop.sh</p> <pre><code...
<p>It is because <code>ps aux |grep SOMETHING</code> also finds the <code>grep SOMETHING</code> process, because SOMETHING matches. After the execution the grep is finished, so it cannot find it. </p> <p>Add a line: <code>ps aux | grep -v grep | grep YOURSCRIPT</code></p> <p>Where -v means exclude. More in <code>man ...
python|linux|shell
4
1,909,799
69,069,336
Error in importing Sequential from Keras.Models
<p>I have installed Keras using <code>pip install keras</code> and tensorflow version 1.9.0 via <code>python -m pip install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.9.0-py2-none-any.whl</code>. I followed the directions at this <a href="https://stackoverflow.com/questions/38896424/tensor...
<p>@Jellyfish, you are using very old Tensorflow version. Install the latest Tensorflow version, 2.6.0. Latest Tensorflow version installs Keras library as well.</p> <p>Use imports as below.</p> <pre><code>import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense <...
python|windows|tensorflow|keras|python-2.x
0