question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
73,137,036
2022-7-27
https://stackoverflow.com/questions/73137036/expected-type-warning-from-changing-dictionary-value-from-none-type-to-str-typ
I have a dictionary for which the key "name" is initialized to None (as this be easily used in if name: blocks) if a name is read in it is then assigned to name. All of this works fine but Pycharm throws a warning when "name" is changed due to the change in type. While this isn't the end of the world it's a pain for de...
Type hinting that dictionary with dict[str, None | str] (Python 3.10+, older versions need to use typing.Dict[str, typing.Optional[str]]) seems to fix this: from copy import deepcopy test: dict[str, None | str] = { "name": None, "other_variables": "Something" } def read_info(): test_2 = deepcopy(test) test_2["name"] = ...
7
4
73,135,253
2022-7-27
https://stackoverflow.com/questions/73135253/how-to-compare-two-dataframes-and-find-matches-from-columns-pandas
let's say we have the following code example where we create two basic dataframes: import pandas as pd # Creating Dataframes a = [{'Name': 'abc', 'Age': 8, 'Grade': 3}, {'Name': 'xyz', 'Age': 9, 'Grade': 3}] df1 = pd.DataFrame(a) b = [{'ID': 1,'Name': 'abc', 'Age': 8}, {'ID': 2,'Name': 'xyz', 'Age': 9}] df2 = pd.DataFr...
Use symmetric_difference res = df2.columns.symmetric_difference(df1.columns) print(res) Output Index(['Grade', 'ID'], dtype='object') Or as an alternative, use set.symmetric_difference res = set(df2.columns).symmetric_difference(df1.columns) print(res) Output {'Grade', 'ID'} A third alternative, suggested by @SashS...
4
6
73,134,521
2022-7-27
https://stackoverflow.com/questions/73134521/how-to-train-on-a-tensorflow-datasets-dataset
I'm playing around with tensorflow to become a bit more familiar with the overall workflow. To do this I thought I should start with creating a simple classifier for the well known Iris dataset. I load the dataset using: ds = tfds.load('iris', split='train', shuffle_files=True, as_supervised=True) I use the following ...
Set the batch size when loading your data: import tensorflow_datasets as tfds import tensorflow as tf ds = tfds.load('iris', split='train', shuffle_files=True, as_supervised=True, batch_size=10) model = tf.keras.Sequential([ tf.keras.layers.Dense(10,activation="relu"), tf.keras.layers.Dense(10,activation="relu"), tf.ke...
7
5
73,131,597
2022-7-27
https://stackoverflow.com/questions/73131597/pytorch-lightning-display-metrics-after-validation-epoch
I've implemented validation_epoch_end to produce and log metrics, and when I run trainer.validate, the metrics appear in my notebook. However, when I run trainer.fit, only the training metrics appear; not the validation ones. The validation step is still being run (because the validation code calls a print statement, w...
You could do the following. Let's say you have the following LightningModule: class MNISTModel(LightningModule): def __init__(self): super().__init__() self.l1 = torch.nn.Linear(28 * 28, 10) def forward(self, x): return torch.relu(self.l1(x.view(x.size(0), -1))) def training_step(self, batch, batch_nb): x, y = batch lo...
5
3
73,076,517
2022-7-22
https://stackoverflow.com/questions/73076517/how-to-send-redirectresponse-from-a-post-to-a-get-route-in-fastapi
I want to send data from app.post() to app.get() using RedirectResponse. @app.get('/', response_class=HTMLResponse, name='homepage') async def get_main_data(request: Request, msg: Optional[str] = None, result: Optional[str] = None): if msg: response = templates.TemplateResponse('home.html', {'request': request, 'msg': ...
In brief, as explained in this answer and this answer, as well as mentioned by @tiangolo here, when performing a RedirectResponse from a POST request route to a GET request route, the response status code has to change to 303 See Other. For instance (completet working example is given below): return RedirectResponse(re...
9
6
73,110,208
2022-7-25
https://stackoverflow.com/questions/73110208/how-to-load-a-different-file-than-index-html-in-fastapi-root-path-while-using-st
Here is a simple static FastAPI app. With this setup even though the root path is expected to return a FileResponse of custom.html, the app still returns index.html. How can I get the root path work and render custom.html? from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from fastapi.responses im...
As per Starlette documentation: StaticFiles Signature: StaticFiles(directory=None, packages=None, html=False, check_dir=True, follow_symlink=False) html - Run in HTML mode. Automatically loads index.html for directories if such file exists. In addtion, as shown from the code snippet you provided, you have mounted S...
4
9
73,065,760
2022-7-21
https://stackoverflow.com/questions/73065760/how-do-i-optimize-this-xor-sum-algorithm
I'm trying to solve this hackerrank problem https://www.hackerrank.com/challenges/xor-subsequence/problem from functools import reduce def xor_sum(arr): return reduce(lambda x,y: x^y, arr) def xorSubsequence(arr): freq = {} max_c = float("-inf") # init val min_n = float("inf") # init val for slice_size in range(1, len(...
Why Xor sum is Dyadic convolution Denote the input array as a. Construct an array b, such that b[i]=a[0]⊕a[1]⊕...⊕a[i]. One can then construct a list M, M[i] stands for the number of element in b which has a value i. Note that some zero-padding is added to make the length of M be a power of 2. Then consider the Dyadic ...
6
2
73,095,192
2022-7-24
https://stackoverflow.com/questions/73095192/poetry-show-command-what-do-the-red-listed-packages-mean
When I run poetry show - most of my packages are blue but a few are red? What do these two colors mean? I think red means the package is not @latest ?
Black: Not required package Red: Not installed / It needs an immediate semver-compliant upgrade Yellow: It needs an upgrade but has potentially breaking changes so is not urgent Green: Already latest
16
18
73,129,798
2022-7-26
https://stackoverflow.com/questions/73129798/how-to-model-an-empty-dictionary-in-pydantic
I'm working with a request of a remote webhook where the data I want to validate is either there, or an empty dictionary. I would like it to run through the model validator if it's there but also not choke if it's an empty dictionary. input 1: { "something": {} } input 2: { "something": { "name": "George", } } input ...
Use extra = "forbid" option to disallow extra fields and use an empty model to represent an empty dictionary. from pydantic import BaseModel, ConfigDict class Empty(BaseModel): ... model_config = ConfigDict(extra="forbid") class Person(BaseModel): name: str model_config = ConfigDict(extra="forbid") class WebhookRequest...
5
7
73,084,052
2022-7-22
https://stackoverflow.com/questions/73084052/writing-multiple-dataframes-to-multiple-sheets-in-an-excel-file
I have two data frames that I would like to each write to its own sheet in an Excel file. The following code accomplishes what I want: import pandas as pd df_x = pd.DataFrame({'a':[1, 2, 3]}) df_y = pd.DataFrame({'b':['a', 'b', 'c']}) writer = pd.ExcelWriter('df_comb.xlsx', engine='xlsxwriter') df_x.to_excel(writer, sh...
What you have is almost there, I think you'll run into problems trying to assign the sheet_name to be the DataFrame as well. I would suggest also having a list of names that you'd like the sheets to be. You could then do something like this: names = ["df_x", "df_y"] dataframes = [df_x, df_y] for i, frame in enumerate(d...
7
10
73,121,344
2022-7-26
https://stackoverflow.com/questions/73121344/i-cant-delete-an-poetry-managed-environment
I'd like to remove an environment (see this question) when I issue /progetti/project_blah$ poetry env remove ./.venv I get /bin/sh: 1: ./.venv: Permission denied EnvCommandError Command ./.venv -c "import sys; print('.'.join([str(s) for s in sys.version_info[:3]]))" errored with the following return code 126, and outp...
Besides the permission error, if you are here because you're unable to delete a locally created environment using poetry, you can refer to this github issue. Basically, at the moment, you can't delete the local environment with the poetry env remove <python> command since it will return the Environment does not exist e...
9
11
73,070,845
2022-7-21
https://stackoverflow.com/questions/73070845/how-to-import-julia-packages-into-python
One can use Julia's built-in modules and functions using the juliacall package. for example: >>> from juliacall import Main as jl >>> import numpy as np # Create a 2*2 random matrix >>> arr = jl.rand(2,2) >>> arr <jl [0.28133223988783074 0.22498491616860727; 0.008312971104033062 0.12927167014532326]> # Check whether Nu...
I found it by scrutinizing the pictures of the second example of the juliacall GitHub page. According to the example, I'm able to import Flux.jl by taking these steps: >>> from juliacall import Main as jl >>> jl.seval("using Flux") Also, one can install any registered Julia package using Pkg in Python: >>> from juliac...
6
5
73,077,163
2022-7-22
https://stackoverflow.com/questions/73077163/how-to-get-the-number-of-available-cores-in-python
The standard method that I know to get number of cores in python is to use multiprocess.cpu_count import multiprocessing print(multiprocessing.cpu_count()) Also, when creating a task we can specify some cores that the process can access using taskset. Apparently cpu_count is always getting the number of available core...
According to the docs, this may be of limited availability, but it seems the os library has what you want; Interface to the scheduler These functions control how a process is allocated CPU time by the operating system. They are only available on some Unix platforms. For more detailed information, consult your Unix man...
6
4
73,075,949
2022-7-22
https://stackoverflow.com/questions/73075949/using-pydantic-with-xml
I am working on a project that uses a lot of xml, and would like to use pydantic to model the objects. In this case I simplified the xml but included an example object. <ns:SomeType name="NameType" shortDescription="some data"> <ns:Bar thingOne="alpha" thingTwo="beta" thingThree="foobar"/> </ns:SomeType> Code from pyd...
xmltodict can help in your example if you combine it with field aliases: from typing import Optional import xmltodict from pydantic import BaseModel, Field class Bar(BaseModel): thing_one: str = Field(alias="@thingOne") thing_two: str = Field(alias="@thingTwo") thing_three: str = Field(alias="@thingThree") class SomeTy...
6
6
73,089,846
2022-7-23
https://stackoverflow.com/questions/73089846/python-3-simple-http-server-with-get-functional
I can't find any Python code for the equivalent of python -m http.server port --bind addr --directory dir So I need basically a working server class that process at least GET requests. Most of the things I found on Google were either an HTTP server with some special needs or something like that, where you need to code...
That's what I ended up with: # python -m http.server 8000 --directory ./my_dir from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler import os class HTTPHandler(SimpleHTTPRequestHandler): """This handler uses server.base_path instead of always using os.getcwd()""" def translate_path(self, path)...
5
3
73,104,543
2022-7-25
https://stackoverflow.com/questions/73104543/how-to-install-different-versions-of-r-e-g-r-4-1-2-in-a-conda-environment
I want to be able to install higher versions of R in my conda environment. In particular r 4.1.2. I have also installed Mamba fyi. Currently r-base has: conda activate main conda search r-base Name Version r-base 3.2.4 r-base 3.3.0 r-base 3.3.1 r-base 3.3.2 r-base 3.4.1 r-base 3.4.2 r-base 3.4.3 r-base 3.4.3 r-base 3.5...
You could specify the version directly: mamba install -c conda-forge r-base=4.1.2 or conda install -c conda-forge r-base=4.1.2 On Jul 25, 2022 the highest available in conda-forge was 4.1.3 while in pkgs/r 4.2.0 was the highest version available.
8
12
73,105,877
2022-7-25
https://stackoverflow.com/questions/73105877/importerror-cannot-import-name-parse-rule-from-werkzeug-routing
I got the following message after running my Flask project on another system. The application ran all the time without problems: Error: While importing 'app', an ImportError was raised: Traceback (most recent call last): File "c:\users\User\appdata\local\programs\python\python39\lib\site-packages\flask\cli.py", line 21...
The workaround I use for now is to pin werkzeug to 2.1.2 in requirements.txt. This should only be done until the other libraries are compatible with the latest version of Werkzeug, at which point the pin should be updated. werkzeug==2.1.2
40
38
73,060,080
2022-7-21
https://stackoverflow.com/questions/73060080/how-do-i-use-qt6-dark-theme-with-pyside6
Simple demo application I am trying to set the theme to dark. I would prefer a code version (non QtQuick preferred), but only way I see for Python is with a QtQuick config file, and even that does not work. from PySide6 import QtWidgets from PySide6 import QtQuick if __name__ == '__main__': app = QtWidgets.QApplication...
import sys sys.argv += ['-platform', 'windows:darkmode=2'] app = QApplication(sys.argv) above 3 lines can change your window to dark mode if you are using windows and Fusion style makes the app more beautiful, tested in windows 10, 11 example:- from PySide6.QtWidgets import ( QApplication, QCheckBox, QComboBox, QDateE...
8
11
73,080,088
2022-7-22
https://stackoverflow.com/questions/73080088/how-to-solve-jsondecodeerror-when-using-poetry-in-github-actions
Issue I've got a problem using poetry install in my CI/CD pipeline (Github Actions), on any GitHub runner, since I migrated from Python 3.8 to Python 3.10. Installing dependencies from lock file Package operations: 79 installs, 0 updates, 0 removals • Installing pyparsing (3.0.9) JSONDecodeError Expecting value: line 1...
After a few researches, I found this thread on the poetry GitHub repository from november 2021. There is this workaround from hoefling GitHub user: Disabling poetry's experimental new installer may be a workaround for now: Solution poetry config experimental.new-installer false Adding this line in the shell before r...
7
7
73,070,247
2022-7-21
https://stackoverflow.com/questions/73070247/how-to-change-image-format-when-uploading-image-in-django
When a user uploads an image from the Django admin panel, I want to change the image format to '.webp'. I have overridden the save method of the model. Webp file is generated in the media/banner folder but the generated file is not saved in the database. How can I achieve that? def save(self, *args, **kwargs): super(Ba...
from django.core.files import ContentFile If you already have the webp file, read the webp file, put it into the ContentFile() with a buffer (something like io.BytesIO). Then you can proceed to save the ContentFile() object to a model. Do not forget to update the model field, and save the model! https://docs.djangopro...
7
5
73,108,683
2022-7-25
https://stackoverflow.com/questions/73108683/getting-error-cannot-import-name-unicode-emoji-from-emoji-unicode-codes
I'm trying to create an Instagram bot using InstaPy. I'm following this tutorial. When I ran: from instapy import InstaPy session = InstaPy(username="your username", password="your password") session.login() I got this error: ImportError: cannot import name 'UNICODE_EMOJI' from 'emoji.unicode_codes' (C:\Users\roeegg22...
This happens because instapy (or some other library) doesn't reflect the latest update to the emoji library. You should be able to fix it by running pip uninstall emoji pip install emoji==1.7 in the terminal. That way you install the version of emoji library that instapy is made around and the import should work.
12
27
73,122,688
2022-7-26
https://stackoverflow.com/questions/73122688/numpy-efficiently-create-this-matrix-n-3-base-values-of-another-list-and-repe
How can I create the matrix [[a, 0, 0], [0, a, 0], [0, 0, a], [b, 0, 0], [0, b, 0], [0, 0, b], ...] from the vector [a, b, ...] efficiently? There must be a better solution than np.squeeze(np.reshape(np.tile(np.eye(3), (len(foo), 1, 1)) * np.expand_dims(foo, (1, 2)), (1, -1, 3))) right?
You can create a zero array in advance, and then quickly assign values by slicing: def concated_diagonal(ar, col): ar = np.asarray(ar).ravel() size = ar.size ret = np.zeros((col * size, col), ar.dtype) for i in range(col): ret[i::col, i] = ar return ret Test: >>> concated_diagonal([1, 2, 3], 3) array([[1, 0, 0], [0, 1...
4
3
73,125,231
2022-7-26
https://stackoverflow.com/questions/73125231/pytorch-dataloaders-bad-file-descriptor-and-eof-for-workers0
Description of the problem I am encountering a strange behavior during a neural network training with Pytorch dataloaders made from a custom dataset. The dataloaders are set with workers=4, pin_memory=False. Most of the time, the training finished with no problems. Sometimes, the training stopped at a random moment wit...
I have finally found a solution. Adding this configuration to the dataset script works: import torch.multiprocessing torch.multiprocessing.set_sharing_strategy('file_system') By default, the sharing strategy is set to 'file_descriptor'. I have tried some solutions explained in : this issue (increase shared memory, in...
5
7
73,075,669
2022-7-22
https://stackoverflow.com/questions/73075669/how-to-extract-doc-from-avro-data-and-add-it-to-dataframe
I'm trying to create hive/impala tables base on avro files in HDFS. The tool for doing the transformations is Spark. I can't use spark.read.format("avro") to load the data into a dataframe, as in that way the doc part (description of the column) will be lost. I can see the doc by doing: input = sc.textFile("/path/to/a...
If you would like to parse the schema yourself and manually add metadata to spark, I would suggest flatdict package: from flatdict import FlatterDict flat_schema = FlatterDict(schema) # schema as python dict names = {k.replace(':name', ''): flat_schema[k] for k in flat_schema if k.endswith(':name')} docs = {k.replace('...
6
1
73,093,143
2022-7-23
https://stackoverflow.com/questions/73093143/getting-ttm-income-statement-yahoo-finance-using-yahoo-fin
I try to get ttm values of the income statement for ticker symbol AAPL by using from yahoo_fin import stock_info as si import yfinance as yf import pandas as pd import matplotlib.pyplot as plt import pandas_datareader pd.set_option('display.max_columns', None) income_statement = si.get_income_statement("aapl") income_s...
The reason you don't get the exact same table you see on the website is because of the way yahoo_fin gets data from Yahoo. Rather than getting them from the table you see, they get them from json data that Yahoo provides. In this data, there are both quarterly and yearly income statements. When Yahoo renders the table ...
4
3
73,072,257
2022-7-21
https://stackoverflow.com/questions/73072257/resolve-warning-a-numpy-version-1-16-5-and-1-23-0-is-required-for-this-versi
When I import SciPy or a library dependent on it, I receive the following warning message: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.1 It's true that I am running NumPy version 1.23.1, however this message is a mystery to me since I am running SciPy ...
According to the setup.py file of the scipy 1.7.3, numpy is indeed <1.23.0. As @Libra said, the docs must be incorrect. You can: Ignore this warning Use scipy 1.8 Use numpy < 1.23.0 Edit: This is now fixed in the dev docs of scipy https://scipy.github.io/devdocs/dev/toolchain.html
27
12
73,125,077
2022-7-26
https://stackoverflow.com/questions/73125077/how-to-programatically-save-pdf-of-jupyter-notebook-with-a-custom-dynamic-file
On Windows 10, I am trying to save a Jupyter notebook as a pdf, under a name that will change for every run of the notebook. Here is what I have so far: name1 = 'July' name2 = 'August' jupyter_nb_filename = '{}_vs_{}'.format(name1,name2) !jupyter nbconvert --output-dir="C:\\mydir\\" --output=jupyter_nb_filename --to pd...
You have to prefix the variable name with $ for it to be interpreted as a variable in a console command. See this question. !jupyter nbconvert --output-dir="C:\\mydir\\" --output=$jupyter_nb_filename --to pdf --TemplateExporter.exclude_input=True mynotebook.ipynb
5
1
73,106,139
2022-7-25
https://stackoverflow.com/questions/73106139/fastest-way-to-repeatedly-find-indices-of-k-largest-values-in-an-iteratively-par
In a complex-valued array a with nsel = ~750000 elements, I repeatedly (>~10^6 iterations) update nchange < ~1000 elements. After each iteration, in the absolute-squared, real-valued array b, I need to find the indices of the K largest values (K can be assumed to be small, for sure K <= ~50, in practice likely K <= ~10...
I tried to implement a Cython solution based on C++ containers (for 64-bit float values). The good news is that it is faster than a naive np.argpartition. The bad news is that it is quite complex and not much faster: 3~4 times faster. One main issue is that Cython do not implement the std::multimap container which is t...
5
1
73,083,672
2022-7-22
https://stackoverflow.com/questions/73083672/aws-cdk-lambda-function-cannot-find-asset-at-path
I'm trying to make a Lambda function using the AWS CDK They make it seem simple enough, but when I use cdk synth, it's giving me an error that the asset doesn't exist (even though it does exist). Here's my code: cwd = os.getcwd() aws_lambda.Function(self, "lambda_function", runtime=aws_lambda.Runtime.PYTHON_3_9, handle...
From documentation The Code.from_asset(...) requires you to specify a directory or a .zip file. From your code you're referencing a directory which is not true. Change the path to add .zip extension. cwd = os.getcwd() aws_lambda.Function(self, "lambda_function", runtime=aws_lambda.Runtime.PYTHON_3_9, handler="index.han...
7
4
73,128,975
2022-7-26
https://stackoverflow.com/questions/73128975/pydantic-created-at-and-updated-at-fields
I'm new to using Pydantic and I'm using it to set up the models for FastAPI to integrate with my postgres database. I want to make a model that has an updated_at and created_at field which store the last datetime the model was updated and the datetime the model was created. I figured created_at could be something like ...
You can use a validator which will update the field updated_at each time when some other data in the model will change. The root_validator and the validate_assignment config attribute are what you are looking for. This is the sample code: from datetime import datetime from time import sleep from pydantic import BaseMod...
7
5
73,066,883
2022-7-21
https://stackoverflow.com/questions/73066883/display-html-table-from-xml-file-over-web-browser-without-using-any-software-or
I am a very new to HTML and javascript. Have come across many questions with regard to my problem and after struggling a lot to find a solution, I am posting this question. Problem statment: I have an xml which I am trying to convert it to HTML so that I can display it over web browser in a table format. <?xml version=...
This should solve your issue (as asked), using pandas: import pandas as pd xml_data = '''<?xml version="1.0" encoding="UTF-8"?> <chapter name="ndlkjfidm" date="dfhkryi"> <edge name="nnn" P="ffgnp" V="0.825" T="125c"> <seen name="seen1"> </seen> <seen name="ABB"> <mob name="adas_jk3" type="entry"> <nod name="VSS" voltag...
4
5
73,126,494
2022-7-26
https://stackoverflow.com/questions/73126494/how-to-keep-jupyter-kernel-alive-inside-vscode-remote-container
Question: How can I disconnect, then reconnect to a vscode dev container without killing the ipynb kernel within my workspace? Background: I access my jupyter notebook inside a vscode dev container in order to have reproducibility of my project-specific environment. I connect to the container host machine on my laptop....
Try to use jupyter server instead. You can refer to this issue aout using the 'remote' server to control your kernel lifetime for details.
4
4
73,124,895
2022-7-26
https://stackoverflow.com/questions/73124895/stacked-and-grouped-barchart
I have this data set import pandas as pd import plotly.express as px elements = pd.DataFrame(data={"Area": ["A", "A", "A", "B", "B", "C", "C", "C"], "Branch": ["a1", "f55", "j23", "j99", "ci2", "p21", "o2", "q35"], "Good": [68, 3, 31, 59, 99, 86, 47, 47], "Neutral": [48, 66, 84, 4, 83, 76, 6, 89],"Bad": [72, 66, 50, 83...
import plotly.graph_objects as go df = elements.melt(id_vars=['Area', 'Branch'], value_vars=['Good', 'Neutral', 'Bad'], var_name='Rating') df ### Area Branch Rating value 0 A a1 Good 68 1 A f55 Good 3 2 A j23 Good 31 3 B j99 Good 59 4 B ci2 Good 99 5 C p21 Good 86 6 C o2 Good 47 7 C q35 Good 47 8 A a1 Neutral 48 9 A f5...
4
2
73,129,698
2022-7-26
https://stackoverflow.com/questions/73129698/can-paramspec-be-used-to-type-individual-arguments
I'm trying to type the following wrapper function. It takes another function and the function's arguments and runs it with some side effect. from typing import Callable, ParamSpec, TypeVar P = ParamSpec("P") R = TypeVar("R") def wrapper(func: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R: # Run some side effe...
When you know the arguments that will be passed to func, you don't need ParamSpec; ordinary TypeVars will do. AType = TypeVar('AType') BType = TypeVar('BType') def wrapper(func: Callable[[AType, BType], R], a: AType, b: BType) -> R: return func(a, b) If there were additional arguments, then you would use Concatenate t...
5
5
73,129,334
2022-7-26
https://stackoverflow.com/questions/73129334/filter-pandas-dataframe-by-multiple-columns-using-tuple-from-list-of-tuples
So I have been referencing this previous question posted here Filter pandas dataframe from tuples. But the problem I am trying to solve is slightly different. I have a list of tuples. Each tuple represents a different set of filters I would like to apply to a dataframe accross multiple columns, so I can isolate the rec...
TL;DR: use df[df[["A","B"]].apply(tuple, 1) == AB_col[0]]. I think you might be overthinking the matter. Let's dissect the code a bit: df[["A","B"]].apply(tuple, 1) # or: df[["A","B"]].apply(tuple, axis=1) # meaning: create tuples for each row 0 (0, 230) 1 (20, 192) 2 (50, 90) dtype: object So this just gets us A and...
5
1
73,055,748
2022-7-20
https://stackoverflow.com/questions/73055748/how-to-draw-bubbles-and-turn-them-animated-into-circles
I am trying to make a python program to draw a line and turn it into a circle with an animation using pygame, yet I haven't even gotten through the drawing-the-line code. I have noticed that python is changing the wrong or both items in a list that contains the starting point when the user presses down the left click, ...
if not bubbles[-1][0] == 0: is False as long as the mouse is not released. Therefore add many line segments, each starting at bubline_start and ending at the current mouse position. You must redraw the scene in each frame. bubbles is a list of bubbles and each bubble has a list of points. Add a new point to the last bu...
6
18
73,063,362
2022-7-21
https://stackoverflow.com/questions/73063362/is-there-a-built-in-way-to-convert-datetimes-to-cftime-in-xarray
I would like to plot two time series, one of which is in cftime and the other in datetime. One possibility is to convert cftime to datetime, but this might give strange results for nonstandard cftime calendars (e.g. NoLeap). As such, I am trying to convert the datetime to cftime. I can brute-force it as follows, but is...
Indeed you might consider using DataArray.convert_calendar. For example if you would like to convert datetime64 values to cftime.DatetimeNoLeap objects, you could do something like this: >>> da.convert_calendar("noleap") <xarray.DataArray (time: 2)> array([1., 2.]) Coordinates: * time (time) object 2000-01-01 00:00:00 ...
5
3
73,112,948
2022-7-25
https://stackoverflow.com/questions/73112948/snakemake-run-directive-produces-no-error-message
When I use the run directive in snakemake (using python code) it doesn't produce any kind of error message for troubleshooting. Is this desired behavior? Am I missing something? Here a minimal example using snakemake 7.8.3 and python 3.9.13. I invoked snakemake with the -p option which in shell directive outputs the ex...
I suspect you are hitting this recent bug https://github.com/snakemake/snakemake/issues/1698. If that is the case, you can downgrade to v7.6.2 or work around it, i.e. bear with it or wrap the the code in run in a self-contained script that you execute via shell. This latter is not a bad solution anyway since it keeps t...
5
5
73,122,817
2022-7-26
https://stackoverflow.com/questions/73122817/initialize-dataframe-with-two-columns-which-have-one-of-the-them-all-zeros
I have a list and I would like to convert it to a pandas dataframe. In the second column, I want to give all zeros but I got "object of type 'int' has no len()" error. The thing I did is this: df = pd.DataFrame([all_equal_timestamps['A'], 0], columns=['data','label']) How can i add second column with all zeros to this...
Not sure what is in all_equal_timestamps, so I presume it's a list of elements. Do you mean to get this result? import pandas as pd all_equal_timestamps = {'A': ['1234', 'aaa', 'asdf']} df = pd.DataFrame(all_equal_timestamps['A'], columns=['data']).assign(label=0) # df['label'] = 0 print(df) Output: data label 0 1234...
4
1
73,121,956
2022-7-26
https://stackoverflow.com/questions/73121956/pandas-can-i-duplicate-rows-and-add-a-column-with-the-values-of-a-list
I have a dataframe like this: ID value repeat ratio 0 0 IDx10 6 0.5 1 1 IDx11 7 1.5 2 2 IDx12 8 2.5 and i have a list like this: l = [1,2] What i want to do is to duplicate every row the number of times of the length of the list and in every new row put each value of the list. And getting a dataframe like this: ID ...
Let us do a cross merge: out = df.merge(pd.Series(l, name='value2'), how='cross') output: ID value repeat ratio value2 0 0 IDx12 6 0.5 1 1 0 IDx12 6 0.5 2 2 0 IDx12 6 0.5 3 3 1 IDx12 7 1.5 1 4 1 IDx12 7 1.5 2 5 1 IDx12 7 1.5 3 6 2 IDx12 8 2.5 1 7 2 IDx12 8 2.5 2 8 2 IDx12 8 2.5 3
4
7
73,118,895
2022-7-26
https://stackoverflow.com/questions/73118895/how-would-you-type-hint-dict-in-python-with-constant-form-but-multiple-types
I want to type hint the return object of some_func function, which is always the same format. Is this correct? from typing import List, Dict def some_func() -> List[Dict[str, int, str, List[CustomObject]]]: my_list = [ {"ID": 1, "cargo": [CustomObject(), CustomObject()]}, {"ID": 2, "cargo": [CustomObject(), CustomObjec...
one way of correctly type hinting would look like this: from typing import List, Dict, Union def some_func() -> List[Dict[str, Union[int, List[CustomObject]]]]: my_list = [ {"ID": 1, "cargo": [CustomObject(), CustomObject()]}, {"ID": 2, "cargo": [CustomObject(), CustomObject()]}, {"ID": 2, "cargo": [CustomObject(), Cus...
4
4
73,116,647
2022-7-26
https://stackoverflow.com/questions/73116647/why-cant-i-install-a-python-package-with-the-python-requirement-3-8-3-11-i
I'm having an issue installing dependencies into my Poetry project. If I run poetry new (as described in https://python-poetry.org/docs/basic-usage/), I can create a new project: $ poetry new scipy-test Created package scipy_test in scipy-test My project structure looks like this after I delete a few files not needed ...
The caret requirement you specify... [tool.poetry.dependencies] python = "^3.9" ...means "This Python code has compatibility of 3.9 <= python_version < 4" (^ restricts differently based on how you specify the version, using semantic versioning). This is a wider constraint than what your dependency scipy specifies, bec...
23
40
73,112,516
2022-7-25
https://stackoverflow.com/questions/73112516/arimaresults-object-has-no-attribute-plot-predict-error
In stats models I have this code from statsmodels.tsa.arima.model import ARIMA from statsmodels.graphics.tsaplots import plot_predict df1.drop(df1.columns.difference(['PTS']), 1, inplace=True) model = ARIMA(df1.PTS, order=(0, 15,0)) res = model.fit() res.plot_predict(start='2021-10-19', end='2022-04-05') plt.show() Ho...
The .plot_predict() method no longer exists with the changes to the ARIMA classes in statsmodels version 13. So, just use the plot_predict() function that you already imported in your code. Here is an example with a different dataset: import matplotlib.pyplot as plt import pandas as pd import statsmodels.api as sm from...
4
6
73,114,693
2022-7-25
https://stackoverflow.com/questions/73114693/complex-list-comparisons-in-python
I want to do a complex list comparison with python. I want to see if listB contains all of the items from listA and if they are in the same order. But I do not care if listB has extra items or interleaved items. Examples: listA = ['A','B','C','D','E'] listB = [':','A','*','B','C','D','E','`'] A, B, C, D, and E all app...
Simple solution using a nested loop. Walk over listA and search the elements in listB in order. Should you fail at any point -> this is not a substring: def check(listA, listB): start = 0 for a in listA: for i in range(start, len(listB)): if a == listB[i]: start = i+1 break else: # triggered only if no break # print(f...
4
2
73,103,953
2022-7-25
https://stackoverflow.com/questions/73103953/how-to-print-the-body-of-gmail-in-python-using-gmail-api
Hello everyone I'm attempting to use the Gmail API to print out specific emails from a sender. I've managed to do some research and watched some videos on how to get the sender and the subject printed off but for some reason, I cant get the body of the message to print off. I've looked through the Gmail API and haven't...
In your script, how about the following modification? Modified script: service = build("gmail", "v1", credentials=creds) results = service.users().messages().list(userId="me", labelIds=["INBOX"], q="from:specific email, is:unread").execute() messages = results.get("messages", []) if not messages: print("You have no New...
4
9
73,097,290
2022-7-24
https://stackoverflow.com/questions/73097290/separate-lines-from-handwritten-text-using-opencv-in-python
I am using the below script to try and separate handwritten text from the lines which the text was written on. Currently I am trying to select the lines. This seems to work well when the line are solid but when the lines are a string of dots it becomes tricky. To try and get around this I have tried using dilate to mak...
By finding contours, we can eliminate smaller ones by their area using cv2.contourArea. This will work under the assumption that the image contains dotted lines. Code: # read image, convert to grayscale and apply Otsu threshold img = cv2.imread('text.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) th = cv2.threshold(...
4
4
73,097,741
2022-7-24
https://stackoverflow.com/questions/73097741/how-to-merge-two-rgba-images
I'm trying to merge two RGBA images (with a shape of (h,w,4)), taking into account their alpha channels. Example : What I've tried I tried to do this using opencv for that, but I getting some strange pixels on the output image. Images Used: and import cv2 import numpy as np import matplotlib.pyplot as plt image1 = ...
I was able to obtain the expected result in 2 stages. # Read both images preserving the alpha channel hh1 = cv2.imread(r'C:\Users\524316\Desktop\Stack\house.png', cv2.IMREAD_UNCHANGED) hh2 = cv2.imread(r'C:\Users\524316\Desktop\Stack\memo.png', cv2.IMREAD_UNCHANGED) # store the alpha channels only m1 = hh1[:,:,3] m2 = ...
4
3
73,095,952
2022-7-24
https://stackoverflow.com/questions/73095952/how-to-find-all-the-functions-that-has-been-used-in-a-python-script
Say I have a python script in this form import numpy as np x = [1, 2, 5, 3, 9, 6] x.sort() print(np.sum(x)) I want to extract all the functions that have been used in this script. For this example the outcome should be list.sort, np.sum, print. I can list all the builtin functions and then expand that list with dir(nu...
You can use ast module to do something like that: import ast code = """ import numpy as np x = [1, 2, 5, 3, 9, 6] x.sort() print(np.sum(x)) """ module = ast.parse(code) for node in ast.walk(module): if isinstance(node, ast.Call): try: parent_name = node.func.value.id + '.' except AttributeError: parent_name = '' if isi...
4
3
73,092,700
2022-7-23
https://stackoverflow.com/questions/73092700/segmentation-fault-while-running-python-in-docker-container
I am trying to run this Github project on docker on my machine. Here is my docker file that I am running after cloning the project on my local machine. FROM python:3 RUN mkdir -p /opt/cascade-server WORKDIR /opt/cascade-server COPY requirements.txt . RUN pip install -r requirements.txt COPY . . COPY docker_defaults.yml...
try to change the base image python:3 (which use Python 3.10) to python:3.7 base image like your local Python interpreter.
4
3
73,089,517
2022-7-23
https://stackoverflow.com/questions/73089517/how-to-insert-only-new-key-to-existing-keyvalue-pair-dictionary-python
I have a dict as below: dict1={ 'item1': {'result': [{'val': 228, 'no': 202}] }, 'item2': {'result': [{'value': 148, 'year': 201}] } } How can we insert a new key 'category' to each item so that the output looks like below: output={ 'item1': {'category': {'result': [{'val': 228, 'no': 202}] } }, 'item2': {'category': ...
Use to modify in-place the existing dictionary dict1: for key, value in dict1.items(): dict1[key] = { "category" : value } print(dict1) Output {'item1': {'category': {'result': [{'val': 228, 'no': 202}]}}, 'item2': {'category': {'result': [{'value': 148, 'year': 201}]}}} As an alternative use update: dict1.update((k,...
5
5
73,085,926
2022-7-22
https://stackoverflow.com/questions/73085926/make-python-subprocess-run-in-powershell
I'm trying to get the wireless debugging port of ADB in my Android, using the command here: & "D:\Tools\Nmap\nmap.exe" -T4 192.168.2.20 -p 37000-44000 | Where-Object {$_ -match "tcp open"} | ForEach-Object {$_.split("/")[0]} And I would like to make a Python script for further purposes: ip = '192.168.2.20' nmap_path = ...
The documentation says subprocess() uses COMSPEC to determine which shell to run if you set shell=True. I don't have, want, or use Windows, but imagine you'd need something like: import os import subprocess # Change COMSPEC to point to Powershell os.putenv('COMSPEC',r'C:\Windows\System32\WindowsPowerShell\v1.0\powershe...
4
0
73,085,720
2022-7-22
https://stackoverflow.com/questions/73085720/cuda-error-invalid-device-ordinal-when-using-python-3-9
I'm trying to excute a code, but I keep geting this error when compiling this piece of code: import tensorflow as tf from xba import XBA import torch torch.tensor([1, 2, 3, 4]).to(device="cuda:2") torch.tensor([1, 2, 3, 4]).to(device="cuda:2") generates this error: " RuntimeError: CUDA error: invalid device ordinal C...
"cuda:2" selects the third GPU in your system. If you don't have 3 GPUs (at least) in your system, you'll get this error. Assuming you have at least 1 properly installed and set up CUDA GPU available, try: "cuda:0"
4
7
73,072,159
2022-7-21
https://stackoverflow.com/questions/73072159/spyder-on-m1-chip
I am getting a new mac with m1 pro chip and want to install Python with Spyder IDE. I will be using conda to manage Python environments. I gather that as of now Spyder does not run natively on m1 chip while Python with different packages does, see for example: https://www.anaconda.com/blog/new-release-anaconda-distribu...
I personally have had no issue using Spyder through Anaconda, nonetheless it will be running on Rosetta (even if you download it directly). Python will be running using M1 inside the IDE. I haven't had any major issues. If you absolutely want to run python natively on M1 then python 3.9.1 is required and you should use...
4
2
73,083,535
2022-7-22
https://stackoverflow.com/questions/73083535/modify-dataframe-in-place-using-nan-values-from-passed-dataframe
So i have the following sample df df = pd.DataFrame({'Id':[1,1,2,3],'Origin':['int','int','pot','pot'],'Origin2':['pot','int','int','int']}) Id Origin Origin2 0 1 int pot 1 1 int int 2 2 pot int 3 3 pot int And i do the following replace command df.loc[df['Id'].eq(1)].apply(lambda x : x.replace('int':np.nan)) How cou...
Use mixed boolean/label indexing: m = df['Id'].eq(1) df.loc[m, ['Origin', 'Origin2']] = df.loc[m, ['Origin', 'Origin2']].replace('int', np.nan) Output: Id Origin Origin2 0 1 NaN pot 1 1 NaN NaN 2 2 pot int 3 3 pot int
4
3
73,074,874
2022-7-22
https://stackoverflow.com/questions/73074874/how-to-add-link-in-python-docstring
I have a function in python 3.x def foo(): """Lorem ipsum for more info, see here"" I want to add a hyperlink to 'here' to point to a web site. How can I do that without installing external plugin?
Just add the link as a string into the docstring, like so: def foo(): """Lorem ipsum for more info, see here: www.myfancydocu.com"" The doctring is just a string, so there is no Hyperlink. But anyone that wants to look at the website can just copy the link. There are automatic documentation-builders that build a docum...
5
5
73,081,130
2022-7-22
https://stackoverflow.com/questions/73081130/python-fastapi-shedule-task
I want to write a task that will only run once a day at 3:30 p.m. with Python FASTAPI. How can I do it? I tried this but it works all the time. schedule.every().day.at("15:30:00").do(job2) while True: schedule.run_all()
Swap the schedule.run_all() for schedule.run_pending(). It should work! import schedule import time def job(): print("I'm working...") schedule.every().day.at("15:30:00").do(job) while True: schedule.run_pending()
10
4
73,078,568
2022-7-22
https://stackoverflow.com/questions/73078568/filtering-long-format-pandas-df-based-on-conditions-from-the-dictionary
Imagine I have an order for specialists in some coding languages with multiple criterion in JSON format: request = {'languages_required': {'Python': 4, 'Java': 2}, 'other_requests': [] } languages_required means that the candidate must have a skill in the language and the number is the minimum level of this language. ...
You need call first condition in one step and then second in another step: df = df[df['language'].map(request['languages_required']).le(df['skill'])] df = df[df.groupby('candidate')['language'].transform(lambda x: set(request['languages_required']).issubset(x))] print (df) candidate language skill 0 a Python 5 1 a Java...
4
2
73,077,203
2022-7-22
https://stackoverflow.com/questions/73077203/how-to-create-a-dummy-variable-in-python-if-missing-values-are-included
How to create a dummy variable if missing values are included? I have the following data and I want to create a Dummy variable based on several conditions. My problem is that it automatically converts my missing values to 0, but I want to keep them as missing values. import pandas as pd mydata = {'x' : [10, 50, np.nan,...
When creating your boolean-mask, you are comparing integers with nans. In your case, when comparing df['x']=np.nan with 50, your mask df['x'] >= 50 will always be False and will equal 0 if you convert it to an integer. You can just create a boolean-mask that equals True for all rows that contain any np.nan in the colum...
5
5
73,069,550
2022-7-21
https://stackoverflow.com/questions/73069550/fastapi-best-practices-for-writing-rest-apis-with-multiple-conditions
Let's say I have two entities, Users and Councils, and a M2M association table UserCouncils. Users can be added/removed from Councils and only admins can do that (defined in a role attribute in the UserCouncil relation). Now, when creating endpoints for /councils/{council_id}/remove, I am faced with the issue of checki...
So, I will tell you how I would go about doing it with your example. Generally I like to keep my endpoints quite minimal. What you what to employ is a common pattern used in building APIs and that is to bundle your business logic into a service class. This service class allows you to reuse logic. Say you want to remove...
4
3
73,066,781
2022-7-21
https://stackoverflow.com/questions/73066781/how-to-find-circulation-in-dataframe
my goal is to find if the following df has a 'circulation' given: df = pd.DataFrame({'From':['USA','UK','France','Italy','Russia','china','Japan','Australia','Russia','Italy'], 'to':['UK','France','Italy','Russia','china','Australia','New Zealand','Japan','USA','France']}) df and if I graph it, it would look like thi...
The logic is not fully clear, however you can approach your problem with a graph. Your graph is the following: Let us consider circulating nodes, those that have more than one destination. You can obtain this with networkx: import networkx as nx G = nx.from_pandas_edgelist(df, source='From', target='to', create_using=...
5
5
73,070,369
2022-7-21
https://stackoverflow.com/questions/73070369/how-do-i-install-antlr4-for-python3-on-windows
I'm trying to install antlr4 for Python 3 on Windows. I run the following pip command successfully: pip install antlr4-python3-runtime Installs the packages, no problem. I'm using the Miniconda environment, and the files are where they are expected. When I try to run antlr4 from the command line, though, error is retur...
antlr4 is not a binary shipped with antlr4-python3-runtime. It is just an alias for the command: java -jar /usr/local/lib/antlr-4.10.1-complete.jar In other words, when you want to generate a parser from your .g4 grammar file, you need to download the antlr-4.10.1-complete.jar file and have a Java runtime installed. Y...
4
3
73,069,962
2022-7-21
https://stackoverflow.com/questions/73069962/correct-way-to-hint-that-a-class-is-implementing-a-protocol
On a path of improvement for my Python dev work. I have interest in testing interfaces defined with Protocol at CI/deb building time, so that if a interface isn't actually implemented by a class we will know immediately after the unit tests run. My approach was typing with Protocol and using implements runtime_checkabl...
When talking about static type checking, it helps to understand the notion of a subtype as distinct from a subclass. (In Python, type and class are synonymous; not so in the type system implemented by tools like mypy.) A type T is a nominal subtype of type S if we explicitly say it is. Subclassing is a form of nominal ...
13
18
73,062,386
2022-7-21
https://stackoverflow.com/questions/73062386/adding-single-integer-to-numpy-array-faster-if-single-integer-has-python-native
I add a single integer to an array of integers with 1000 elements. This is faster by 25% when I first cast the single integer from numpy.int64 to the python-native int. Why? Should I, as a general rule of thumb convert the single number to native python formats for single-number-to-array operations with arrays of about...
On my Windows PC with CPython 3.8.1, I get: [Old] Numpy 1.22.4: - First test: 1.65 µs VS 1.43 µs - Second: 2.03 µs VS 0.17 µs [New] Numpy 1.23.1: - First test: 1.38 µs VS 1.24 µs <---- A bit better than Numpy 1.22.4 - Second: 0.38 µs VS 0.17 µs <---- Much better than Numpy 1.22.4 While the new version of Numpy gives a...
7
1
73,067,671
2022-7-21
https://stackoverflow.com/questions/73067671/using-github-actions-how-do-you-store-flake8-exit-code-as-a-variable-instead-of
I have a GitHub Action workflow file that is doing multiple linting checks. flake8 is the first linting check and if it fails the entire workflow fails meaning the subsequent linting checks are name: lint on: push: pull_request: jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@main with: ref: ${{ git...
You could use the continue-on-error in conjunction with the outcome of the step. From the doc: steps.<step_id>.outcome string The result of a completed step before continue-on-error is applied. Possible values are success, failure, cancelled, or skipped. When a continue-on-error step fails, the outcome is failure, but...
4
4
73,067,450
2022-7-21
https://stackoverflow.com/questions/73067450/get-row-values-as-column-values
I have a single row data-frame like below Num TP1(USD) TP2(USD) TP3(USD) VReal1(USD) VReal2(USD) VReal3(USD) TiV1 (EUR) TiV2 (EUR) TiV3 (EUR) TR TR-Tag AA-24 0 700 2100 300 1159 2877 30 30 47 10 5 I want to get a dataframe like the one below ID Price Net Range 1 0 300 30 2 700 1159 30 3 2100 2877 47 The logic here is...
Assuming 'Num' is a unique identifier, you can use pandas.wide_to_long: pd.wide_to_long(df, stubnames=['TP', 'VR', 'TV'], i='Num', j='ID') or, for an output closer to yours: out = (pd .wide_to_long(df, stubnames=['TP', 'VR', 'TV'], i='Num', j='ID') .reset_index('ID') .drop(columns=['TR', 'TR-Tag']) .rename(columns={'T...
9
12
73,065,778
2022-7-21
https://stackoverflow.com/questions/73065778/compare-two-pandas-dataframes-in-the-most-efficient-way
Let's consider two pandas dataframes: import numpy as np import pandas as pd df = pd.DataFrame([1, 2, 3, 2, 5, 4, 3, 6, 7]) check_df = pd.DataFrame([3, 2, 5, 4, 3, 6, 4, 2, 1]) If want to do the following thing: If df[1] > check_df[1] or df[2] > check_df[1] or df[3] > check_df[1] then we assign to df 1, and 0 otherwi...
IIUC, this is easily done with a rolling.min: df['out'] = np.where(df[0].rolling(N, min_periods=1).max().shift(1-N).gt(check_df[0]), 1, -1) output: 0 out 0 1 -1 1 2 1 2 3 -1 3 2 1 4 5 1 5 4 -1 6 3 1 7 6 -1 8 7 -1 to keep the last items as is: m = df[0].rolling(N).max().shift(1-N) df['out'] = np.where(m.gt(check_df[0...
4
3
73,057,180
2022-7-20
https://stackoverflow.com/questions/73057180/split-a-string-if-character-is-present-else-dont-split
I have a string like below in python testing_abc I want to split string based on _ and extract the 2 element I have done like below split_string = string.split('_')[1] I am getting the correct output as expected abc Now I want this to work for below strings 1) xyz When I use split_string = string.split('_')[1] I g...
Set the maxsplit argument of split to 1 and then take the last element of the resulting list. >>> "testing_abc".split("_", 1)[-1] 'abc' >>> "xyz".split("_", 1)[-1] 'xyz' >>> "testing_abc_bbc".split("_", 1)[-1] 'abc_bbc'
4
9
73,056,691
2022-7-20
https://stackoverflow.com/questions/73056691/how-do-we-interpret-the-baseline-output-of-cv2-gettextsize
If I do this for example: cv2.getTextSize('blahblah', cv2.FONT_HERSHEY_SIMPLEX, 2, 2) it returns ((262, 43), 19) so the width and height of the text in pixels are 262 and 43, but what is the 19? Here it says it "corresponds to the y coordinate of the baseline relative to the bottom of the text" but this still doesn't m...
The baseline here is the yellow line in the figure on page 124. It is the line on which the letters sit. That is according to Pay attention to how the three little points (red,cyan, and green) are drawn and also to how the yellow baseline is shown.
5
7
73,056,540
2022-7-20
https://stackoverflow.com/questions/73056540/no-module-named-amazon-linux-extras-when-running-amazon-linux-extras-install-epe
Here is my (simplified) Dockerfile # https://docs.aws.amazon.com/lambda/latest/dg/images-create.html#images-create-from-base FROM public.ecr.aws/lambda/python:3.8 # get the amazon linux extras RUN yum install -y amazon-linux-extras RUN amazon-linux-extras install epel -y When it reaches the RUN amazon-linux-extras ins...
You're correct, it's because amazon-linux-extras only works with Python 2. You can modify the RUN instruction to RUN PYTHON=python2 amazon-linux-extras install epel -y
10
16
73,049,456
2022-7-20
https://stackoverflow.com/questions/73049456/apply-the-nested-shape-of-one-list-on-another-flat-list
I have two lists: A: [[0, 1], [2, [3]], 4] B: [5, 6, 7, 8, 9] I wish list B could have the same shape with list A: [5, 6, 7, 8, 9] => [[5, 6], [7, [8]], 9] So list A and list B have the same dimension/shape: A: [[0, 1], [2, [3]], 4] B: [[5, 6], [7, [8]], 9] Consider about time complexity, I hope there is a way of O(n) ...
Assuming the number of items is identical, you could use a recursive function and an iterator: A = [[0, 1], [2, [3]], 4] B = [5, 6, 7, 8, 9] def copy_shape(l, other): if isinstance(other, list): other = iter(other) if isinstance(l, list): return [copy_shape(x, other) for x in l] else: return next(other) out = copy_shap...
6
6
73,049,158
2022-7-20
https://stackoverflow.com/questions/73049158/extract-values-from-two-columns-of-a-dataframe-and-put-it-in-a-list
I have a dataframe as shown below: df = A col_1 col_45 col_3 1.0 4.0 45.0 [1, 9] 2.0 4.0 NaN [9, 10] 3.0 49.2 10.8 [1, 10] The values in col_1 are of type float and the values in col_3 are in a list. For every row, I want to extract the values in col_1 and col_3 and put it together in a list. I tried the following: df...
Convert one element in col_1 to list then use merge two list like list_1 + list_2, You can use pandas.apply with axis=1 for iterate over each row: >>> df.apply(lambda row: [row['col_1']] + row['col_3'], axis=1) 0 [4.0, 1, 9] 1 [4.0, 9, 10] 2 [49.2, 1, 10] dtype: object >>> df.apply(lambda row: [row['col_1']] + row['col...
5
3
73,044,698
2022-7-20
https://stackoverflow.com/questions/73044698/pandas-str-extract-giving-unexpected-nan
I have a data set which has a column that looks like this Badge Number 1 3 23 / gold 22 / silver 483 I need only the numbers. Here's my code: df = pd.read_excel('badges.xlsx') df['Badge Number'] = df['Badge Number'].str.extract('(\d+)') print(df) I was expecting an output like: Badge Number 1 3 23 22 483 but I got B...
Another option is while reading the XLS it self, specify your column to string. use dtype={'Badge Number': str} df = pd.read_excel('badges.xlsx',dtype={'Badge Number': str}) df['Badge Number'] = df['Badge Number'].str.extract('(\\d+)')
5
2
73,044,663
2022-7-20
https://stackoverflow.com/questions/73044663/why-are-f-strings-slower-than-string-concatenation-when-repeatedly-adding-to-a-s
I was benchmarking some code for a project with timeit (using a free replit, so 1024MB of memory): code = '{"type":"body","layers":[' for x, row in enumerate(pixels): for y, pixel in enumerate(row): if pixel != (0, 0, 0, 0): code += f'''{{"offsetX":{-start + x * gap},"offsetY":{start - y * gap},"rot":45,"size":{size},"...
So, first off, repeated concatenation in a language with immutable strings is, theoretically, O(n²), while efficiently implemented bulk concatenation is O(n), so both versions of your code are theoretically bad for repeated concatenation. The version that works everywhere with O(n) work is: code = ['{"type":"body","lay...
6
5
72,982,731
2022-7-14
https://stackoverflow.com/questions/72982731/how-to-transform-a-series-of-a-polars-dataframe
I am dealing with a large dataframe (198,619 rows x 19,110 columns) and so am using the polars package to read in the tsv file. Pandas just takes too long. However, I now face an issue as I want to transform each cell's value x raising it by base 2 as follows: 2^x. I run the following line as an example: df_copy = df d...
The secret to harnessing the speed and flexibility of Polars is to learn to use Expressions. As such, you'll want to avoid Pandas-style indexing methods. Let's start with this data: import polars as pl nbr_rows = 4 nbr_cols = 5 df = pl.DataFrame({ "col_" + str(col_nbr): pl.int_range(col_nbr, nbr_rows + col_nbr, eager=T...
4
2
73,000,068
2022-7-15
https://stackoverflow.com/questions/73000068/what-is-the-right-way-to-validate-a-storekit-2-transaction-jwsrepresentation-in
It's unclear from the docs what you actually do to verify the jwsRepresentation string from a StoreKit 2 transaction on the server side. Also "signedPayload" from the Apple App Store Notifications V2 seems to be the same, but there is also no documentation around actually validating that either outside of validating it...
Apple now provides an App Store Server Library available in a few different languages (including Python). You still need to manage loading the root certificates on your own, but here is an example: from functools import from appstoreserverlibrary.models.Environment import Environment from appstoreserverlibrary.signed_d...
4
2
72,976,543
2022-7-14
https://stackoverflow.com/questions/72976543/google-bigquery-query-in-python-works-when-using-result-but-permission-issue
I've run into a problem after upgrades of my pip packages and my bigquery connector that returns query results suddenly stopped working with following error message from google.cloud import bigquery from google.oauth2 import service_account credentials = service_account.Credentials.from_service_account_file('path/to/fi...
There are different ways of receiving data from bigquery. Using the BQ Storage API is considered more efficient for larger result sets compared to the other options: The BigQuery Storage Read API provides a third option that represents an improvement over prior options. When you use the Storage Read API, structured da...
5
5
73,026,698
2022-7-18
https://stackoverflow.com/questions/73026698/javas-spring-boot-vs-pythons-fastapi-threads
I'm a Java Spring boot developer and I develop 3-tier crud applications. I talked to a guy who seemed knowledgeable on the subject, but I didn't get his contact details. He was advocating for Python's FastAPI, because horizontally it scales better than Spring boot. One of the reasons he mentioned is that FastAPI is sin...
The issues with Java threads in the question are addressed by the project Loom, which is now included in Jdk21. It is very well explained here https://www.baeldung.com/openjdk-project-loom : Presently, Java relies on OS implementations for both the continuation [of threads] and the scheduler [for threads]. Now, in ord...
3
8
72,975,593
2022-7-14
https://stackoverflow.com/questions/72975593/where-to-store-tokens-secrets-with-fastapi
I'm working with FastAPI and Python on the backend to make external calls to a public API. After authentication, the public API gives an access token that grants access to a specific user's data. Where would be the best place to store/save this access token? I want to easily access it for all my future API calls with t...
Almost a year later, but I found a clean solution I was pleased with. I used Starlette's SessionMiddleware to store the access_token and user session data in the backend. Example: from fastapi import Request ... @router.get("/callback") async def callback(request: Request): ... request.session["access_token"] = access_...
3
4
72,995,109
2022-7-15
https://stackoverflow.com/questions/72995109/excluding-a-dependency-in-pip-audit
I have a pipenv project that is using the Trend Micro deepsecurity dependency. Up until recently, this was available on pypi, but Trend has since removed it. They require one to download the SDK and install it manually. Not a horrible issue, as I unzip the package and pip install it. pip freeze|grep deep  1 ✘  4s  p...
I never did find a real solution to the problem, but I did make this workaround; just delete deepsecurity! For reference, here is the script that I use in my CI pipeline set -e # Remove trend deep security, as it causes pip-audit to fail pipenv run pip uninstall -y deep-security-api pipenv run pip-audit
4
1
72,963,553
2022-7-13
https://stackoverflow.com/questions/72963553/opentelemetry-api-vs-sdk
I'm confused as why OpenTelemetry documentaion has OpenTelemetry Python API and OpenTelemetry Python SDK. Like when using the specification in python when we should consider pip install opentelemetry-api over pip install opentelemetry-sdk
There's no need to specify both the API and SDK dependencies in Python as the SDK has a dependency on the API: https://github.com/open-telemetry/opentelemetry-python/blob/main/opentelemetry-sdk/pyproject.toml#L29 The short answer for when to use each is that the API should be specified as a dependency for packages/libr...
9
5
72,980,095
2022-7-14
https://stackoverflow.com/questions/72980095/pyspark-cumulative-sum-with-limits
I have a dataframe as follows: +-------+----------+-----+ |user_id| date|valor| +-------+----------+-----+ | 1|2022-01-01| 0| | 1|2022-01-02| 0| | 1|2022-01-03| 1| | 1|2022-01-04| 1| | 1|2022-01-05| 1| | 1|2022-01-06| 0| | 1|2022-01-07| 0| | 1|2022-01-08| 0| | 1|2022-01-09| 1| | 1|2022-01-10| 1| | 1|2022-01-11| 1| | 1|...
In such cases, we usually think of window functions to do a calculation going from one row to next. But this case is different, because the window should kind of keep track of itself. So window cannot help. Main idea. Instead of operating with rows, one can do the work with grouped/aggregated arrays. In this case, it w...
5
6
73,021,768
2022-7-18
https://stackoverflow.com/questions/73021768/what-is-the-difference-between-the-mlrose-project-and-mlose-hiive
I can't find the difference between the mlrose (https://pypi.org/project/mlrose/) project and mlrose-hiive (https://pypi.org/project/mlrose-hiive/). I know hiive has some kind of extensions compared to the original mlrose but I can't find some documentation or anything that explains the new features.
Accordign private training forum info where I have access, it seems mlrose-hiive: mostly are improvements and fixes some dependency bugs, as in the six package: Python import error: cannot import name 'six' from 'sklearn.externals', is backwards-compatible, so, mlrose readthedocs should be OK, they even recommend that...
3
4
73,010,915
2022-7-17
https://stackoverflow.com/questions/73010915/multiple-array-agg-in-sqlalchemy
I am working with postgres. I want to fetch multiple fields using array_agg in sqlalchemy. But I couldn't find examples of such use anywhere. I made my request. But I can't process the result of array_agg. I'd like to get a list of strings, or better yet a list of tuples. It would also be nice to get rid of func.distin...
The problem here is that Postgresql's array_agg function is returning an array of unknown type; the default behaviour of the psycopg2 connector in this situation is to simply return the array literal as-is. This bug report exists from 2016. SQLAlchemy's maintainer, SO user zzzeek proposed creating a custom type to hand...
3
4
73,031,189
2022-7-19
https://stackoverflow.com/questions/73031189/backing-a-cisco-router-using-napalm-using-remote-login-using-ssh
this image is the diagram for GNS3 of routers want to configureTrying to Backup the configuration of a Cisco Router. but the connection is not opening. from napalm import * import napalm drivers = napalm.get_network_driver('ios') device_detail = {'hostname':'192.168.1.2','username':'wahid','password':'wahid'} router =...
Can you try as follows: from napalm import get_network_driver from getpass import getpass hostname = input("IP address of router: ") username = input(f"Username of {hostname}: ") password = getpass(f"Password of {hostname}") secret = getpass(f"Enable password of {hostname}: ") driver = get_network_driver("ios") device_...
3
3
72,964,480
2022-7-13
https://stackoverflow.com/questions/72964480/cannot-import-tensorflow-text
I have problem with importing tensorflow_text I tried importing like below two methods but none of them worked import tensorflow_text as text import tensorflow_text as tf_text My tensorflow version is 2.9.1 and python version is Python 3.7.13. I tried installing tensorflow_text using below two methods but none of them...
Update, Sometimes you need to reinstall and update tensorflow then install tensorflow_text. (Because you need your tensorflow.__version__ and tensorflow_text.__version__ to have the same version) !pip install -U tensorflow !pip install -U tensorflow-text import tensorflow as tf import tensorflow_text as text # Or insta...
5
4
73,026,671
2022-7-18
https://stackoverflow.com/questions/73026671/how-do-i-now-since-june-2022-send-an-email-via-gmail-using-a-python-script
I had a Python script which did this. I had to enable something in the Gmail account. For maybe 3 years the script then ran like this: import smtplib, ssl ... subject = 'some subject message' body = """text body of the email""" sender_email = 'my_gmail_account_name@gmail.com' receiver_email = 'some_recipient@something....
Google has recently made changes to access of less secure apps (read here: https://myaccount.google.com/lesssecureapps). In order to make your script work again, you'll need to make a new app password for it. Directions to do so are below: Go to My Account in Gmail and click on Security. After that, scroll down to cho...
10
26
73,013,333
2022-7-17
https://stackoverflow.com/questions/73013333/how-to-make-an-angled-arrow-style-border-in-pyqt5
How to make an Angled arrow-type border in PyQt QFrame? In My code, I Have two QLabels and respective frames. My aim is to make an arrow shape border on right side of every QFrame.For clear-cut idea, attach a sample picture. import sys from PyQt5.QtWidgets import * class Angle_Border(QWidget): def __init__(self): super...
Since the OP didn't ask for user interaction (mouse or keyboard), a possible solution could use the existing features of Qt, specifically QSS (Qt Style Sheets). While the currently previously accepted solution does follow that approach, it's not very effective, most importantly because it's basically "static", since it...
8
5
73,040,397
2022-7-19
https://stackoverflow.com/questions/73040397/vscode-python-debugger-stopped-launching
I'm using VSCode v1.69.0. My OS is MacOS v10.15.7 (Catalina). I have a Python code that I'm usually debugging with VSCode Python debugger (using the launch.json file). For no apparent reason the debugger recently stopped working, i.e. when I click on "Run Debug", the debug icons (stop, resume, step over etc.) show up f...
If you are using python3.6 version then latest version of debugger no longer supports it. You can use the historical version 2022.08.*. Or use a new python version.
4
7
73,022,745
2022-7-18
https://stackoverflow.com/questions/73022745/vscode-and-jupyter-notebook-changes-in-python-script-code-dont-update
When I write a code in the editor in VScode and then I try to import this code into jupyter notebook, the alterations I made in the code are do not update - the code that runs in jupyter notebook is the code that is open when I initialize VScode. To update the code I need to restart VScode, open jupyter notebook, and i...
You could download script file from jupyter as "py" file and run it on other editors most jupyter support that for example in anaconda jupyter and google colab support this too but a notebook run only with program support python notebook.
3
1
73,031,562
2022-7-19
https://stackoverflow.com/questions/73031562/how-to-disable-python-interactive-mode-in-vs-code
I prefer to use this extension so I find very annoying that every time I write a code-cell or hit shift-enter VS-Code opens its internal interactive python console. How to stop such a behavior?
You can view your keyboard shortcuts using: Click the gear icon in the lower left corner of the interface Select Keyboard Shortcuts (Ctrl + K + S) Select Record Keys (Alt + k) on the right side of the input box Press the SHIFT and ENTER keys View the functions bound to this shortcut key in the list Just delete...
3
9
73,028,924
2022-7-18
https://stackoverflow.com/questions/73028924/how-to-measure-time-spent-in-blocking-code-while-using-asyncio-in-python
I'm currently migrating some Python code that used to be blocking to use asyncio with async/await. It is a lot of code to migrate at once so I would prefer to do it gradually and have metrics. With that thing in mind I want to create a decorator to wrap some functions and know how long they are blocking the event loop....
TLDR; This decorator does the job: def measure_blocking_code(f): async def wrapper(*args, **kwargs): t = 0 coro = f() try: while True: t0 = time.perf_counter() future = coro.send(None) t1 = time.perf_counter() t += t1 - t0 while not future.done(): await asyncio.sleep(0) future.result() # raises exceptions if any except...
4
4
73,044,363
2022-7-19
https://stackoverflow.com/questions/73044363/python-convert-all-caps-into-title-case-without-messing-with-camel-case
I'm using python3 and would like to turn strings that contain all caps words (separately or inside a word) into title case (first letter capitalized). I do not want to disrupt one-off capital letters in the middle of a word (camel case), but if there are repeated capitalized letters, I want to keep only the first one c...
A regular expression substitution with a lambda is the way to go: import re a = "TITLE BY DeSoto theHUMUNGUSone" print(re.sub('[A-Z]+', lambda x: x.group(0).title(), a)) Output: Title By DeSoto theHumungusone
4
6
73,033,580
2022-7-19
https://stackoverflow.com/questions/73033580/why-polars-scan-csv-is-even-faster-than-disk-reading-speed
I am testing polars performance by LazyDataFrame API polars.scan_csv with filter. The performance is much better than I expect. Filtering a CSV file is even faster than the disk speed! WHY??? The CSV file is about 1.51 GB on my PC HDD. testing code: import polars as pl t0 = time.time() lazy_df = pl.scan_csv("kline.csv"...
What you're probably seeing is a common problem in benchmarking: the caching of files by your operating system. Most modern operating systems will attempt to cache files that are accessed, if the amount of RAM permits. The first time you accessed the file, your operating system likely cached the 1.51 GB file in RAM (po...
6
14
73,025,746
2022-7-18
https://stackoverflow.com/questions/73025746/what-does-python-do-inside-the-gdb-debugger
I was debugging a C++ program in the gdb debugger and tried to access the 5th element of vector which only contains 4 element. After trying it, this error was on the screen: (gdb) list main 1 #include <memory> 2 #include <vector> 3 4 int main(int argc, char *argv[]){ 5 6 7 std::vector<int> v_num = {1, 3, 5, 67}; 8 std:...
Does gdb uses python internally? Yes, it uses Python a lot to extend itself in many ways, see https://sourceware.org/gdb/onlinedocs/gdb/Python.html#Python. What you discovered is called Python Xmethods, see https://sourceware.org/gdb/onlinedocs/gdb/Xmethods-In-Python.html. Xmethods are used as a replacement of inline...
4
4
73,042,986
2022-7-19
https://stackoverflow.com/questions/73042986/csv-to-json-converter-grouping-by-same-keys-values
I'm trying to convert csv format to JSON, I googled I'm not getting the correct way to modify it to get the desired one. This is my code in python: import csv import json def csv_to_json(csvFilePath, jsonFilePath): jsonArray = [] #reading csv (encoding is important) with open(csvFilePath, encoding='utf-8') as csvf: #cs...
Something like this should work. def csv_to_json(csvFilePath, jsonFilePath): areas = {} with open(csvFilePath, encoding='utf-8') as csvf: csvReader = csv.DictReader(csvf) for column in csvReader: area, employee = column["Area"], column["Employee"] # split values if area in areas: # add all keys and values to one dictio...
4
3
73,042,044
2022-7-19
https://stackoverflow.com/questions/73042044/panda-multiply-dataframes-using-dictionary-to-map-columns
I am looking to multiply element-wise two dataframes with matching indices, using a dictionary to map which columns to multiply together. I can only come up with convoluted ways to do it and I am sure there is a better way, really appreciate the help! thx! df1: Index ABC DEF XYZ 01/01/2004 1 2 3 05/01/2004 4 ...
You can use: # only if not already the index df1 = df1.set_index('Index') df2 = df2.set_index('Index') df1.mul(df2[df1.columns.map(d)].set_axis(df1.columns, axis=1)) or: df1.mul(df2.loc[df1.index, df1.columns.map(d)].values) output: ABC DEF XYZ Index 01/01/2004 5 10 30 05/01/2004 -4 -7 -4
3
3
73,039,481
2022-7-19
https://stackoverflow.com/questions/73039481/check-if-values-in-all-n-previous-rows-are-greater-than-the-value-of-current-row
I have a pandas dataframe like this: col_name 0 2 1 3 2 1 3 0 4 5 5 4 6 3 7 3 that could be created with the code: import pandas as pd dataframe = pd.DataFrame( { 'col_name': [2, 3, 1, 0, 5, 4, 3, 3] } ) Now, I want to get the rows which have a value less than the values in all the n previous rows. So, for n=2 the o...
Let us use rolling to calculate the min value in n previous rows then compare the min value with current row to create a boolean mask df[df['col_name'] < df['col_name'].shift().rolling(2, min_periods=1).min()] col_name 2 1 3 0 6 3
4
3
72,970,941
2022-7-13
https://stackoverflow.com/questions/72970941/dash-leaflet-click-feature-event
I have been using dash leaflet for creating my own dashboard with maps, and it has been great to be able to visualize things with an interactive map. However, there is one thing that I have been stumped on a while for how to deal with a click happening on a polygon or marker. To explain this, I have created a simple ex...
In Dash, a callback is only invoked when a property changes. If you click the same feature twice, the click_feature property doesn't change, and the callback is thus not invoked. If you want to invoke the callback on every click, you can target the n_clicks property - it is incremented on (every) click, and the callbac...
4
1
73,038,799
2022-7-19
https://stackoverflow.com/questions/73038799/program-that-calculates-binary-gap-using-recursion-in-python-generates-recursion
I am new at programming (please be nice :)) and I am trying to write a function that calculates the binary gap of a number using recursion by using the modulus function to gather the bits of an integer and then counting the number of 0s between 1s and displaying the longest chain 0s in between two 1s. For example Input...
First, write a recursive function to convert decimal to binary (not necessary because there is already a bin function). Then, count the gap - there is no point using recursion in this because it is just way too complicated: def convert_to_binary(n): if n > 1: return convert_to_binary(n // 2) + str(n % 2) return str(n %...
4
0
73,034,438
2022-7-19
https://stackoverflow.com/questions/73034438/how-to-type-hint-function-with-a-callable-argument-and-default-value
I am trying to type hint the arguments of a function that takes a callable, and has a default argument (in the example below set) from typing import Callable, List T = TypeVar("T") def transform(data: List[int], ret_type: Callable[[List[int]], T] = set) -> T: return ret_type(data) a = [1, 2, 3] my_set: Set = transform(...
You could use the @overload for correctly type hinting of function with default argument for your case: from typing import Callable, List, TypeVar, overload, Set T = TypeVar("T") @overload def transform(data: List[int]) -> Set[int]: ... @overload def transform(data: List[int], ret_type: Callable[[List[int]], T]) -> T: ...
5
2