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
70,519,432
2021-12-29
https://stackoverflow.com/questions/70519432/python-virtual-env-succesfully-activated-via-wsl-but-not-working
on my windows system I've succesfully installed a virtual environment (python version is 3.9) using windows command prompt python -m venv C:\my_path\my_venv Always using windows command prompt, I'm able to activate the created venv via C:\my_path\my_venv\Scripts\activate.bat I am sure the venv is correctly activated s...
Short answer: It's highly recommended to use the Linux version of Python and tools when in WSL. You'll find a number of posts here on Stack Overflow related to this, but your question is different enough (regarding venv) that it deserves its own answer. More Detail: Also worth reading this question. In that case, the q...
5
2
70,521,500
2021-12-29
https://stackoverflow.com/questions/70521500/tablescraping-from-a-website-with-id-using-beautifulsoup
Im having a problem with scraping the table of this website, I should be getting the heading but instead am getting AttributeError: 'NoneType' object has no attribute 'tbody' Im a bit new to web-scraping so if you could help me out that would be great import requests from bs4 import BeautifulSoup URL = "https://www.co...
What happens? Note: Always look at your soup first - therein lies the truth. The content can always be slightly to extremely different from the view in the dev tools. Access Revoked Your IP address has been blocked. We detected irregular, bot-like usage of our Property Search originating from your IP address. This blo...
5
2
70,518,288
2021-12-29
https://stackoverflow.com/questions/70518288/pytorch-training-loop-within-a-sklearn-pipeline
What I am playing around with right now is to work with PyTorch within a pipeline, where all of the preprocessing will be handled. I am able to make it work. However, the results I am getting are a bit off. The loss function seems to be not decreasing and gets stuck (presumably in local optima?) as the training loop pr...
The problem in this implementation is in the fit method. We are comparing prediction and design matrix # Compute and print loss loss = self.loss_func(pred_y, X) Should be prediction and real value y: loss = self.loss_func(pred_y, y)
5
3
70,515,194
2021-12-29
https://stackoverflow.com/questions/70515194/syntaxerror-future-feature-annotations-is-not-defined
I am try to run code sh run.sh and it showed me the error File "/anaconda3/envs/_galaxy_/lib/python3.6/site-packages/filelock/__init__.py", line 8 from __future__ import annotations ^ SyntaxError: future feature annotations is not defined I saw some solutions indicated that I need to update my python version, but I a...
Based on the error, it looks like your code is using Python 3.6 and not Python 3.9. This import is available starting from Python 3.7. Check run.sh to make sure it is referencing the right python interpreter. I'd also recommend using a virtual env using the python version you require and running your script inside that...
11
21
70,514,336
2021-12-29
https://stackoverflow.com/questions/70514336/solidity-typeerror-object-of-type-set-is-not-json-serializable
I ran the code in VSCode and got a TypeError: Object of type set is not JSON serializable. I just start to learn to code, really don't get it, and googled it, also didn't know what does JSON serializable means. from solcx import compile_standard import json # get the contract content with open("./SimpleStorage.sol", "r...
Instead of this: {"abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"} you should use this: ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"] Sets in Python aren't JSON serializable.
4
6
70,447,335
2021-12-22
https://stackoverflow.com/questions/70447335/what-is-the-use-case-for-djangos-on-commit
Reading this documentation https://docs.djangoproject.com/en/4.0/topics/db/transactions/#django.db.transaction.on_commit This is the use case for on_commit with transaction.atomic(): # Outer atomic, start a new transaction transaction.on_commit(foo) # Do things... with transaction.atomic(): # Inner atomic block, create...
Django documentation: Django provides the on_commit() function to register callback functions that should be executed after a transaction is successfully committed It is the main purpose. A transaction is a unit of work that you want to treat atomically. It either happens completely or not at all. The same applies to...
13
9
70,506,366
2021-12-28
https://stackoverflow.com/questions/70506366/failed-to-start-the-kernel-jupyter-in-vs-code
I am trying to use a Jupyter notebook for some Pandas in VS Code. I set up a virtual environment venv where I installed Pandas and jupyter. I always did it like this and it worked fine. But suddenly it does not work anymore.
Could you try to reinstall the pyzmq module? pip uninstall pyzmq pip install pyzmq==19.0.2 The version number may be different depending on the jupyter-client version.
31
21
70,507,099
2021-12-28
https://stackoverflow.com/questions/70507099/how-to-check-if-xgboost-uses-the-gpu
I'm writing a pytest file to check if my machine learning libraries use the GPU. For Tensorflow I can check this with tf.config.list_physical_devices(). For XGBoost I've so far checked it by looking at GPU utilization (nvdidia-smi) while running my software. But how can I check this in a simple test? Something similar ...
Note that tree_method="gpu_hist" is deprecated and will stop / has stopped working since xgboost==2.0.0. Histogram type and device are currently split into two parameters: tree_method (an unfortunate overwriting of the existing parameter, but with a different set of permitted levels) and a new one called device: import...
6
9
70,477,787
2021-12-25
https://stackoverflow.com/questions/70477787/how-to-get-current-path-in-fastapi-with-domain
I have a simple route as below that written in FastAPI, from fastapi import FastAPI app = FastAPI() @app.get("/foo/bar/{rand_int}/foo-bar/") async def main(rand_int: int): return {"path": f"https://some-domain.com/foo/bar/{rand_int}/foo-bar/?somethig=foo"} How can I get the current path "programmatically" with, domai...
We can use the Request.url-(starlette doc) API to get the various URL properties. To get the absolute URL, we need to use the Request.url._url private API ( or str(Request.url)), as below from fastapi import FastAPI, Request app = FastAPI() @app.get("/foo/bar/{rand_int}/foo-bar/") async def main(rand_int: int, request:...
26
41
70,489,367
2021-12-26
https://stackoverflow.com/questions/70489367/how-to-generate-a-random-convex-piecewise-linear-function
I want to generate a toy example to illustrate a convex piecewise linear function in python, but I couldn't figure out the best way to do this. What I want to do is to indicate the number of lines and generate the function randomly. A convex piecewise-linear function is defined as: For instance, if I want to have four...
The slope increases monotonically by a random value from the range [0,1), starting from 0. The first y value is also zero, see the comments. import numpy as np np.random.seed(0) x_points = np.random.randint(low=1, high=20, size=4) x_points.sort() x_points = np.append(0, x_points) # the first 0 point is 0 slopes = np.ad...
6
2
70,468,354
2021-12-23
https://stackoverflow.com/questions/70468354/fastapi-sqlalchemy-connection-was-closed-in-the-middle-of-operation
I have an async FastApi application with async sqlalchemy, source code (will not provide schemas.py because it is not necessary): database.py from sqlalchemy import ( Column, String, ) from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlalchemy.ext.declarative import declarative_base from sqlal...
I solve that using pool_pre_ping setting like that: engine = create_async_engine(DB_URL, pool_pre_ping=True) https://docs.sqlalchemy.org/en/14/core/pooling.html
5
7
70,493,438
2021-12-27
https://stackoverflow.com/questions/70493438/why-does-this-python-code-with-threading-have-race-conditions
This code creates a race condition: import threading ITERS = 100000 x = [0] def worker(): for _ in range(ITERS): x[0] += 1 # this line creates a race condition # because it takes a value, increments and then writes # some inrcements can be done together, and lost def main(): x[0] = 0 # you may use `global x` instead of...
Reading the docs better, I think there's the answer: The mechanism used by the CPython interpreter to assure that only one thread executes Python bytecode at a time. This simplifies the CPython implementation by making the object model (including critical built-in types such as dict) implicitly safe against concurrent...
8
4
70,458,458
2021-12-23
https://stackoverflow.com/questions/70458458/how-do-i-simply-run-a-python-script-from-github-repo-with-actions
I assume it's possible to schedule a python script to run every day for example, from my github repository. After searching, I've come up with the following main.yml file that resides in the master branch of the repo: the .py file I want to run resides in another branch; I suppose it doesn't have to if it causes an iss...
Everything seems to be working now, the solution was to move my main.yml file into .github/workflows. I also moved my_file.py from alternate branch into the master branch. One helpful comment recommended specifying the ref branch where you run my_file.py if my_file.py is not located in the default branch.
8
8
70,491,428
2021-12-27
https://stackoverflow.com/questions/70491428/how-do-i-reset-the-underscore-in-an-interactive-session
I have overriden the underscore variable _ in the Python interactive interpreter. How can I make the underscore work again without restarting the interpreter?
del _ A global _ shadows the builtin _, so deleting the global reveals the builtin again. It's also worth noting that it doesn't actually stop working, it's just not accessible. You can import builtins to access it: >>> _ = 'foobar' >>> 22 22 >>> _ 'foobar' >>> import builtins >>> 23 23 >>> builtins._ 23
4
6
70,511,031
2021-12-28
https://stackoverflow.com/questions/70511031/rename-names-of-multiindex-pandas-dataframe
I'm in trouble with a dataframe created from a groupby function. df = base.groupby(['year', 'categ']).agg({'id_prod':'count', 'price':'sum'}).unstack(level=1) it returns this result : but I would like to rename id_prod and price to no_sales and revenue but I don't know how to do that because of the MultiIndex with th...
df = df.rename(columns={'id_prod': 'no_sales', 'price': 'revenue'}, level=0) The level=0 indicates where in the multi-index the keys to be renamed can be found.
5
4
70,467,781
2021-12-23
https://stackoverflow.com/questions/70467781/feature-importance-with-svr
I would like to plot Feature Importance with SVR, but I don't know if possible with support vector regression it's my code. from sklearn.svm import SVR C=1e3 svr_lin = SVR(kernel="linear", C=C) y_lin = svr_lin.fit(X,Y).predict(X) scores = cross_val_score(svr_lin, X, Y, cv = 5) print(scores) print(scores.mean()) print(s...
SVR does not support native feature importance scores, you might need to try Permutation feature importance which is a technique for calculating relative importance scores that is independent of the model used. First, a model is fit on the dataset, such as a model that does not support native feature importance scores....
5
2
70,448,419
2021-12-22
https://stackoverflow.com/questions/70448419/how-to-retry-async-requests-upon-clientoserror-errno-104-connection-reset-by
I have a function in Google Cloud that accepts a number of parameters. I generate ~2k asynchronous requests with different combinations of parameter values using aiohttp: # url = 'https://...' # headers = {'X-Header': 'value'} timeout = aiohttp.ClientTimeout(total=72000000) async def submit_bt(session, url, payload): a...
The solution suggested by @vaizki in the comment seems to be working well for me. After a closer look at the traceback it turned out that the exception was raised in the submit_bt co-routine, so I added the try-except clause: async def submit_bt(session, url, payload): try: async with session.post(url, json=payload) as...
4
5
70,466,886
2021-12-23
https://stackoverflow.com/questions/70466886/typeerror-init-got-an-unexpected-keyword-argument-providing-args
I am creating a Django website. I was recently adding permissions/search functionality using the allauth package. When I attempt to run the website through docker I receive the error message: File "/usr/local/lib/python3.9/site-packages/allauth/account/signals.py", line 5, in user_logged_in = Signal(providing_args=["re...
Based on the comments, you're running Django 4.0 with an old version of AllAuth. So you just need to update AllAuth and should be fine. However, other people who have upgraded AllAuth and are running Django 4.0 but still seeing this error may have custom AllAuth or other signals registered that include the providing_a...
16
20
70,508,775
2021-12-28
https://stackoverflow.com/questions/70508775/error-could-not-build-wheels-for-pycairo-which-is-required-to-install-pyprojec
Error while installing manimce, I have been trying to install manimce library on windows subsystem for linux and after running pip install manimce Collecting manimce Downloading manimce-0.1.1.post2-py3-none-any.whl (249 kB) |████████████████████████████████| 249 kB 257 kB/s Collecting Pillow Using cached Pillow-8.4.0-c...
apt-get install sox ffmpeg libcairo2 libcairo2-dev apt-get install texlive-full pip3 install manimlib # or pip install manimlib Then: pip3 install manimce # or pip install manimce And everything works.
52
23
70,474,854
2021-12-24
https://stackoverflow.com/questions/70474854/returning-result-set-from-redshift-stored-procedure
I have a procedure that returns a recordset using the cursor method: CREATE OR REPLACE PROCEDURE myschema.permissions_sp(rs_out INOUT refcursor) LANGUAGE plpgsql SECURITY DEFINER AS $$ BEGIN OPEN rs_out FOR select schema_name,schema_owner,grantee_type,grantee,p_usage,p_create,object_name,perms,p_select,p_update,p_inser...
The procedure receives a name as its argument and returns a server-side cursor with that name. On the client side, after calling the procedure you must declare a named cursor with the same name and use it to access the query results. You must do this before committing the connection, otherwise the server-side cursor wi...
6
4
70,489,306
2021-12-26
https://stackoverflow.com/questions/70489306/kill-a-python-subprocess-that-does-not-return
TLDR I want to kill a subprocess like top while it is still running I am using Fastapi to run a command on input. For example if I enter top my program runs the command but since it does not return, at the moment I have to use a time delay then kill/terminate it. However I want to be able to kill it while it is still r...
It's because subprocess.run is blocking itself - you need to run shell command in background e.g. if you have asnycio loop already on, you could use subprocesses import asyncio process = None @app.get("/command/{command}") async def run_command(command: str): global process process = await asyncio.create_subprocess_exe...
6
2
70,492,432
2021-12-27
https://stackoverflow.com/questions/70492432/gunicorn-async-and-threaded-workers-for-django
Async For input/output(IO) bound we need to use async code and django is not async by default, but we can achieve this running gunicorn with the gevent worker and monkey patching: gunicorn --worker-class=gevent --worker-connections=1000 --workers=3 main:app Gunicorn changelog from 2014 https://docs.gunicorn.org/en/sta...
Do i still need to monkey patch my app or it's done by default from a worker ? No need to patch anything in your code. No need to modify codes at all. How did gevent achieve async functionality for my django code ? gunicorn patches everything. If we use this configuration for i/o bound, does it work? When one thread...
6
7
70,452,647
2021-12-22
https://stackoverflow.com/questions/70452647/how-to-use-python-to-read-excel-files-that-contain-extended-fonts-openpyxl-err
As a learning project for Python, I am attempting to read all Excel files in a directory and extract the names of all the sheets. I have been trying several available Python modules to do this (pandas in this example), but am running into an issue with most of them depending on openpyxl. This is my current code: import...
The issue is that your file does not conform to the Open Office specification. Only certain font families are allowed. Once openpyxl encounters a font out of specification, it throws this error because OpenPyxl only allows spec-conforming excel files. Some Excel readers may not have an issue with this and are more flex...
4
5
70,506,629
2021-12-28
https://stackoverflow.com/questions/70506629/efficient-code-for-custom-color-formatting-in-tkinter-python
So , I was trying to create a Periodic Table and its almost done from the exterior efficiently . However , I couldn't understand if there's any way I could fill in colors in individual buttons in the same fashion . Can anyone please help me regarding this ? Below here is my code : from tkinter import * period_1 = ['H',...
I rewrote your code with some better ways to create table. My idea was to pick out the buttons that fell onto a range of type and then loop through those buttons and change its color to those type. from tkinter import * period_1 = ['H' ,'','','','','','','','','','','','','','','','','He'] period_2 = ['Li','Be','','','...
5
5
70,512,660
2021-12-28
https://stackoverflow.com/questions/70512660/how-to-show-text-on-a-heatmap-with-plotly
I am trying to show the z items as text on a Plotly heatmap. I am using the latest version (5.5.0) and following the exact example shown on the Plotly Heatmaps webpage (https://plotly.com/python/heatmaps/), see the section "Text on Heatmap Points" near the bottom. My code is their example code, which is: figHeatmap = g...
This is a new feature in 5.5.0 https://github.com/plotly/plotly.py/releases. After installing and restarting my jupyter kernel, this did not work. Required restart of complete jupyter environment the documented example using go https://plotly.com/python/heatmaps/#text-on-heatmap-points plus note in release notes auto_...
8
9
70,512,520
2021-12-28
https://stackoverflow.com/questions/70512520/python-unittest-mock-pyspark-chain
I'd like to write some unit tests for simple methods which have pyspark code. def do_stuff(self, df1: DataFrame, df2_path: str, df1_key: str, df2_key: str) -> DataFrame: df2 = self.spark.read.format('parquet').load(df2_path) return df1.join(df2, [f.col(df1_key) == f.col(df2_key)], 'left') How can I mock the spark read...
You can do it using PropertyMock. Here is an example: # test.py import unittest from unittest.mock import patch, PropertyMock, Mock from pyspark.sql import SparkSession, DataFrame, functions as f from pyspark_test import assert_pyspark_df_equal class ClassToTest: def __init__(self) -> None: self._spark = SparkSession.b...
7
7
70,508,568
2021-12-28
https://stackoverflow.com/questions/70508568/django-csrf-trusted-origins-not-working-as-expected
Im having trouble in understanding why a post from a third party site is being rejected even though the site is added to CSRF_TRUSTED_ORIGINS list in settings.py. Im receiving a 403 error after the post stating the the csrf check has failed. I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site ex...
This assumption is wrong: I thought that adding the site to CSRF_TRUSTED_ORIGINS should make the site exempt from csrf checks. Adding the URL to CSRF_TRUSTED_ORIGINS is only one thing you need to do to allow a POST request from a form on an external domain. You also need to: Make an AJAX-call from the external page ...
15
34
70,466,992
2021-12-23
https://stackoverflow.com/questions/70466992/partial-tucker-decomposition
I want to apply a partial tucker decomposition algorithm to minimize MNIST image tensor dataset of (60000,28,28), in order to conserve its features when applying another machine algorithm afterwards like SVM. I have this code that minimizes the second and third dimension of the tensor i = 16 j = 10 core, factors = part...
Just like principal component analysis the partial tucker decomposition will give better results as we increase the rank, in the sense that the optimal mean square residual of the reconstruction is smaller. In general, features (the core tensor) that enables accurate reconstructions of the original data, can be used to...
5
5
70,511,762
2021-12-28
https://stackoverflow.com/questions/70511762/modify-duplicated-rows-in-dataframe-python
I am working with a dataframe in Pandas and I need a solution to automatically modify one of the columns that has duplicate values. It is a column type 'object' and I would need to modify the name of the duplicate values. The dataframe is the following: City Year Restaurants 0 New York 2001 20 1 Paris 2000 40 2 New Yo...
Use np.where, to modify column City if duplicated df['City']=np.where(df['City'].duplicated(keep=False), df['City']+' '+df['Year'].astype(str),df['City'])
4
3
70,502,457
2021-12-28
https://stackoverflow.com/questions/70502457/do-i-need-to-do-any-text-cleaning-for-spacy-ner
I am new to NER and Spacy. Trying to figure out what, if any, text cleaning needs to be done. Seems like some examples I've found trim the leading and trailing whitespace and then muck with the start/stop indexes. I saw one example where the guy did a bunch of cleaning and his accuracy was really bad because all the in...
First, spaCy does no transformation of the input - it takes it literally as-is and preserves the format. So you don't lose any information when you provide text to spaCy. That said, input to spaCy with the pretrained pipelines will work best if it is in natural sentences with no weird punctuation, like a newspaper arti...
7
5
70,501,334
2021-12-27
https://stackoverflow.com/questions/70501334/cannot-install-openvino-with-pip
I'm trying to install Openvino to convert a Keras model into a representation for the inference engine. I'm running the command: python3 openvino/tools/mo/mo_tf.py —model_13.h5/ --input_shape=\[180,180\] This returns the error: from openvino.tools.mo.subprocess_main import subprocess_main ModuleNotFoundError: No modul...
The latest version of openvino is 2021.4.2. The list of packages to download by pip includes packages for Python 3.6-3.9 for Linux, MacOS on Intel, and Windows; only packages for 64-bit platforms are provided. No packages for Python 3.10 and no source code. The solution is either to compile from sources, or install wit...
11
13
70,501,065
2021-12-27
https://stackoverflow.com/questions/70501065/type-hint-pandas-dataframegroupby
How should I type hint in Python a pandas DataFrameGroupBy object? Should I just use pd.DataFrame as for normal pandas dataframes? I didn't find any other solution atm
DataFrameGroupBy is a proper type in of itself. So if you're writing a function which must specifically take a DataFrameGroupBy instance: from pandas.core.groupby import DataFrameGroupBy def my_function(dfgb: DataFrameGroupBy) -> None: """Do something with dfgb.""" If you're looking for a more general polymorphic type...
7
11
70,498,791
2021-12-27
https://stackoverflow.com/questions/70498791/how-to-sort-a-mixed-typed-list
I have a list that looks as follows (the 'None' in the list is a string, not a None): profit = [1 , 20 , 3 , 5 , 90 , 'None', 900, 67 , 'None'] name = ['a', 'b', 'c', 'e', 'd', 'f' , 'g', 'k', 'pp'] The profit list is a list of "profit" values, so I had to sort it in a reversed order so that the highest values will be...
You can use a "priority" key to the sort function which checks the types as well: >>> sorted(profit, key=lambda x: (isinstance(x, int), x), reverse=True) [900, 90, 67, 20, 5, 3, 1, 'None', 'None'] If you're doing that just to sort the names list, then it is not necessary to sort the indices, you should use zip: profi...
4
6
70,497,633
2021-12-27
https://stackoverflow.com/questions/70497633/how-to-correctly-read-csv-file-generated-by-groupby-results
I have calculated the mean value of DataFrame by two groups and saved the results to CSV file. Then, I tried to read it again by read_csv(), but the .loc() function doesn't work for the loaded DataFrame. Here's the code example: import pandas as pd import numpy as np np.random.seed(100) df = pd.DataFrame(np.random.rand...
You should read the index as a MultiIndex, but you need to convert the strings to interval. You can use to_interval (all credits to korakot): def to_interval(istr): c_left = istr[0]=='[' c_right = istr[-1]==']' closed = {(True, False): 'left', (False, True): 'right', (True, True): 'both', (False, False): 'neither' }[c_...
4
3
70,492,568
2021-12-27
https://stackoverflow.com/questions/70492568/how-to-use-queue-with-threading-properly
I am new to queue & threads kindly help with the below code , here I am trying to execute the function hd , I need to run the function multiple times but only after a single run has been completed import queue import threading import time fifo_queue = queue.Queue() def hd(): print("hi") time.sleep(1) print("done") for ...
You can use a Semaphore for your purposes A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release(). A default value o...
6
1
70,491,270
2021-12-27
https://stackoverflow.com/questions/70491270/how-to-make-a-single-image-using-several-images
I have these images and there is a shadow in all images. I target is making a single image of a car without shadow by using these three images: Finally, how can I get this kind of image as shown below: Any kind of help or suggestions are appreciated. EDITED According to the comments, I used np.maximum and achieved ea...
Here's a possible solution. The overall idea is to compute the location of the shadows, produce a binary mask identifying the location of the shadows and use this information to copy pixels from all the cropped sub-images. Let's see the code. The first problem is to locate the three images. I used the black box to segm...
5
1
70,490,381
2021-12-26
https://stackoverflow.com/questions/70490381/how-can-you-multiply-all-the-values-within-a-2d-df-with-all-the-values-within-a
I'm new to numpy and I'm currently working on a modeling project for which I have to perform some calculations based on two different data sources. However until now I haven't managed to figure out how I could multiply all the individual values to each other: I have two data frames One 2D-dataframe: df1 = np.array([[1,...
Try this: df1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) df2 = np.array([1, 2, 3, 4, 5]) df3 = df1 * df2[:, None, None] Output: >>> df3 array([[[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9]], [[ 2, 4, 6], [ 8, 10, 12], [14, 16, 18]], [[ 3, 6, 9], [12, 15, 18], [21, 24, 27]], [[ 4, 8, 12], [16, 20, 24], [28, 32, 36]], [[ 5, 10...
4
5
70,461,753
2021-12-23
https://stackoverflow.com/questions/70461753/shap-the-color-bar-is-not-displayed-in-the-summary-plot
When displaying summary_plot, the color bar does not show. shap.summary_plot(shap_values, X_train) I have tried changing plot_size. When the plot is higher the color bar appears, but it is very small - doesn't look like it should. shap.summary_plot(shap_values, X_train, plot_size=0.7) Here is an example of a proper...
I had the same problem as you did, and I found that the solution was to downgrade matplotlib to 3.4.3.. It appears SHAP isn't optimized for matplotlib 3.5.1 yet.
12
6
70,479,867
2021-12-25
https://stackoverflow.com/questions/70479867/install-uwsgi-on-m1-monterey-fails-with-python-3-10-0
I installed python via pyenv, and then created virtual environment with command python -m venv .venv which python Returns: /Users/my_name/Development/my_project/.venv/bin/python Then pip install uWSGI==2.0.20 fails with following error: *** uWSGI linking *** clang -o /Users/my_name/Development/my_project/.venv/bin/uwsg...
Found solution on github: https://github.com/unbit/uwsgi/issues/2361 LDFLAGS=-L/opt/homebrew/Cellar/gettext/0.21/lib pip install --no-cache-dir "uWSGI==2.0.20"
4
9
70,489,412
2021-12-26
https://stackoverflow.com/questions/70489412/path-to-each-leaf-of-a-binary-tree
The function above AllPaths() appends an array containing the path to each leaf of the binary tree to the global array res. The code works just fine, but I want to remove the global variable res and make the function return an array instead. How can I do that? class Node: def __init__(self, value, left=None, right=N...
A simple way that allow you to avoid the inner lists and global list altogether is to make a generator that yields the values as they come. Then you can just pass this to list to make the final outcome: class Node: def __init__(self, value, left=None, right=None) -> None: self.value = value self.left = left self.right ...
16
12
70,489,368
2021-12-26
https://stackoverflow.com/questions/70489368/how-to-register-an-exact-x-y-boundary-crossing-when-object-is-moving-more-than-1
I'm trying to learn Python/Pygame and I made a simple Pong game. However I cannot get the square to bounce off the sides at the perfect pixel as the drawing of the square is updating let's say 3 pixels every frame. I have a code to decide when the square is hitting the edges and bounce in a reverse direction like this:...
You also need to correct the position of the ball when changing the direction of the ball. The ball bounces on the boundaries and moves the excessive distance in the opposite direction like a billiard ball: e.g.: if y_ball < 100: y_ball = 100 + (100 - y_ball) y_ball_change = y_ball_change * -1 if y_ball > 675: y_ball =...
5
2
70,486,824
2021-12-26
https://stackoverflow.com/questions/70486824/share-media-between-multiple-djangovms-servers
We have deployed a django server (nginx/gunicorn/django) but to scale the server there are multiple instances of same django application running. Here is the diagram (architecture): Each blue rectangle is a Virtual Machine. HAProxy sends all request to example.com/admin to Server 3.other requests are divided between S...
You should use an object store to save and serve your user uploaded files. django-storages makes the implementation really simple. If you don’t want to use cloud based AWS S3 or equivalent, you can host your own on-prem S3 compatible object store with minio. On your current setup I don’t see any easy way to fix where t...
7
2
70,489,060
2021-12-26
https://stackoverflow.com/questions/70489060/efficient-pandas-grouby-nunique-rolling-calculation
I am trying to build a scalable method to calculate the number of unique members that have modified a certain file up to and including the latest modified_date. The unique_member_until_now column contains expected result for each file. import pandas as pd from pandas import Timestamp # Example Dataset df = pd.DataFrame...
An efficient method would be to compute the (non) duplicated on the File+Member columns, then groupby File and cumsum: (~df[['File', 'Member']].duplicated()).groupby(df['File']).cumsum() Saving as column: df['unique_member_until_now'] = (~df[['File', 'Member']].duplicated()).groupby(df['File']).cumsum() output: File...
6
2
70,477,631
2021-12-25
https://stackoverflow.com/questions/70477631/batchdataset-get-img-array-and-labels
Here is the batch data set i created before to fit in the model: train_ds = tf.keras.preprocessing.image_dataset_from_directory( train_path, label_mode = 'categorical', #it is used for multiclass classification. It is one hot encoded labels for each class validation_split = 0.2, #percentage of dataset to be considered ...
Just unbatch your dataset and convert the data to lists: import tensorflow as tf import pathlib dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz" data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True) data_dir = pathlib.Path(data_dir) ba...
6
7
70,486,284
2021-12-26
https://stackoverflow.com/questions/70486284/for-loop-is-only-storing-the-last-value-in-colum
I am trying to pull the week number given a date and then add that week number to the corresponding row in a pandas/python dataframe. When I run a for loop it is only storing the last calculated value instead of recording each value. I've tried .append but haven't been able to get anything to work. import datetime from...
You can simply use Pandas .apply method to make it a one-liner: df["week"] = df.apply(lambda x: date(x.year, x.month, x.day).isocalendar()[1], axis=1)
6
1
70,482,003
2021-12-25
https://stackoverflow.com/questions/70482003/updating-a-json-in-a-more-efficient-way
[ {"923390702359048212": 5}, {"462291477964259329": 1}, {"803390252265242634": 3}, {"824114065445486592": 2}, {"832041337968263178": 4} ] This is a list of user ids that I just randomly made and some sample number that each id has. In this case lets call it a number of goals scored in a season in a video game. As I tr...
Not sure why you couldn't get it work earlier, but storing it as dict would be much, much easier. # file.json { "923390702359048212": 5, "462291477964259329": 1, "803390252265242634": 3, "824114065445486592": 2, "832041337968263178": 4 } def goalscored(): with open("Goals.json", "r") as f: jsondata = json.load(f) # Mak...
5
1
70,481,851
2021-12-25
https://stackoverflow.com/questions/70481851/how-to-fix-exception-has-occurred-sslerror-httpsconnectionpool-in-vs-code-env
i try to use python requests library but i got this error i use psiphon VPN most of time in Windows 10 and got this below error after calling requests.get('[API URL]') Exception has occurred: SSLError HTTPSConnectionPool(host='api.github.com', port=443): Max retries exceeded with url: /user (Caused by SSLError(SSLError...
You should try to add verify=False to your request: import requests r = requests.get('https://api.github.com/user', verify=False) requests verifies SSL certificates for HTTPS requests, just like a web browser. By default, SSL verification is enabled, and requests will throw an SSLError if it’s unable to verify the cer...
7
11
70,479,605
2021-12-25
https://stackoverflow.com/questions/70479605/python-pandas-pandas-correlation-one-column-vs-all
I'm trying to get the correlation between a single column and the rest of the numerical columns of the dataframe, but I'm stuck. I'm trying with this: corr = IM['imdb_score'].corr(IM) But I get the error operands could not be broadcast together with shapes which I assume is because I'm trying to find a correlation b...
The most efficient method it to use corrwith. Example: df.corrwith(df['A']) Setup of example data: import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(10, size=(5, 5)), columns=list('ABCDE')) # A B C D E # 0 7 2 0 0 0 # 1 4 4 1 7 2 # 2 6 2 0 6 6 # 3 9 8 0 2 1 # 4 6 0 9 7 7 output: A 1.000000 B ...
8
9
70,472,945
2021-12-24
https://stackoverflow.com/questions/70472945/pandas-getting-the-mean-of-columns-in-multi-index-dataframe
I have a pandas multi index dataframe like shown below. M EM A ... EA M0 EM0 Component EN EZ NZ EN EZ NZ EN EZ ... EZ NZ EN EZ NZ EN EZ NZ Date ... 2020-07-15 0.001682 0.000963 0.001292 0.000737 0.000635 0.000907 -0.048716 0.022769 ... 0.013103 0.016042 0.003619 0.001009 0.001718 0.000829 0.000685 0.000880 2020-07-16 ...
Try: df_mean = pd.concat({'mean': df.groupby(level=0, axis=1).mean()}, axis=1).swaplevel(axis=1) df = df.join(df_mean).sort_index(level=0, axis=1) print(df) # Output: EM M Component EN EZ NZ mean EN EZ NZ mean Date 2020-07-15 4 5 6 5.0 1 2 3 2.0 2020-07-16 14 15 16 15.0 11 12 13 12.0 Setup to be reproducible: import i...
4
7
70,471,888
2021-12-24
https://stackoverflow.com/questions/70471888/text-as-tooltip-popup-or-labels-in-folium-choropleth-geojson-polygons
Folium allow to create Markers with tooltip or popup text. I would like to do the same with my GeoJSON polygons. My GeoJSON has a property called "name" (feature.properties.name -> let's assume it is the name of each US state). I would like to be able to display this as a label in my choropleth map, in addition to the ...
I've had to use folium's GeoJsonTooltip() and some other steps to get this done in the past. I'm curious to know if someone has a better way Capture the return value of the Choropleth function Add a value(eg unemployment) to the Chorpleth's underlying geojson obj Create GeoJsonTooltip with that value from step 2 Add t...
10
17
70,465,276
2021-12-23
https://stackoverflow.com/questions/70465276/multiprocessing-hanging-at-join
Before anyone marks it as a duplicate question. I have been looking at StackOverflow posts for days, I haven't really found a good or satisfying answer. I have a program that at some point will take individual strings (also many other arguments and objects), do some complicated processes on them, and spit 1 or more str...
Read carefully the documentation for `multiprocessing.Queue. Read the second warning, which says in part: Warning: As mentioned above, if a child process has put items on a queue (and it has not used JoinableQueue.cancel_join_thread), then that process will not terminate until all buffered items have been flushed to t...
4
7
70,473,310
2021-12-24
https://stackoverflow.com/questions/70473310/why-does-python-tell-me-to-sort-before-taking-a-random-sample
Python just gave me weird advice: >>> import random >>> random.sample({1: 2, 3: 4, 5: 6}, 2) Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> random.sample({1: 2, 3: 4, 5: 6}, 2) File "C:\Users\*****\AppData\Local\Programs\Python\Python310\lib\random.py", line 466, in sample raise TypeError("...
From the commit history of cpython - My emphasis: github In the future, the population must be a sequence. Instances of :class:set are no longer supported. The set must first be converted to a :class:list or :class:tuple, preferably in a deterministic order so that the sample is reproducible. If you don't care about ...
4
5
70,470,136
2021-12-24
https://stackoverflow.com/questions/70470136/how-to-generate-a-environments-yml-file-of-a-python-virtual-environment
I want to generate a environments.yml file of an existing Python environment. I tried the following command: python env export --from-history -f environment.yml This throws the following error: can't open file 'env': [Errno 2] No such file or directory Note: This is not a conda environment.
pip freeze > requirements.txt to save the venv pip install -r requirements.txt to create venv.
5
1
70,467,517
2021-12-23
https://stackoverflow.com/questions/70467517/how-can-i-know-what-python-versions-can-run-my-code
I've read in few places that generally, Python doesn't provide backward compatibility, which means that any newer version of Python may break code that worked fine for earlier versions. If so, what is my way as a developer to know what versions of Python can execute my code successfully? Is there any set of rules/guara...
99% of the time, if it works on Python 3.x, it'll work on 3.y where y >= x. Enabling warnings when running your code on the older version should pop DeprecationWarnings when you use a feature that's deprecated (and therefore likely to change/be removed in later Python versions). Aside from that, you can read the What's...
4
8
70,461,249
2021-12-23
https://stackoverflow.com/questions/70461249/how-to-flatten-a-multi-level-columns-in-pandas
Please see the data in excel above. When use df.columns this is the printout: Index(['Country of Citizenship', '2015', 'Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6', 'Unnamed: 7', 'Unnamed: 8', 'Unnamed: 9', ... 'Unnamed: 108', 'Unnamed: 109', 'Unnamed: 110', 'Unnamed: 111', 'Unnamed: 112', 'Unn...
You can read a excel file into a pandas dataframe with multi-indexes, like with the following example: import pandas as pd df = pd.read_excel('your_file.xlsx', header=[0,1,2], index_col=[0]) If you want to know how to navigate and use multi-indexes i recommend: this guide on indexes Alternatively there are also alot o...
4
4
70,455,957
2021-12-22
https://stackoverflow.com/questions/70455957/quart-framework-warningasyncioexecuting
We are using Quart (Flask+asyncio) Python web framework. Every time the request is processed and the response is sent to a client, this (or similar) message is logged: WARNING:asyncio:Executing <Task pending name='Task-11' coro=<ASGIHTTPConnection.handle_request() running at /usr/local/lib/python3.8/site-packages/quar...
asyncio and other event loops require the tasks to yield control back to the event loop periodically so that it can switch to another task and execute tasks concurrently. This warning is indicating that a task is taking a long time between yields, thereby 'blocking' the event loop. It is likely this is happening as you...
4
5
70,463,736
2021-12-23
https://stackoverflow.com/questions/70463736/templatedoesnotexist-graphene-graphiql-html
I'm trying to setup Graphene, but have a following exception raised when open http://localhost:8000/graphql/ in browser: TemplateDoesNotExist at /graphql/ graphene/graphiql.html Request Method: GET Request URL: http://localhost:8000/graphql/ Django Version: 3.2.10 Added did whole setup, added to urls, configured schem...
Looks like forgot to add following in settings.py, so it wasn't fully configured, at least for DEBUG mode: INSTALLED_APPS = [ # ... "graphene_django", # ... ]
4
9
70,462,865
2021-12-23
https://stackoverflow.com/questions/70462865/how-to-use-a-column-value-as-key-to-a-dictionary-in-pyspark
I have a small PySpark DataFrame df: index col1 0 1 1 3 2 4 And a dictionary: LOOKUP = {0: 2, 1: 5, 2: 5, 3: 4, 4: 6} I now want to add an extra column col2 to df, equal to the LOOKUP values of col1. My output should look like this: index col1 col2 0 1 5 1 3 4 2 4 6 I tried using: df = df.withColumn(col("col2"), LOO...
You can use a map column that you create from the lookup dictionary: from itertools import chain from pyspark.sql import functions as F lookup = {0: 2, 1: 5, 2: 5, 3: 4, 4: 6} lookup_map = F.create_map(*[F.lit(x) for x in chain(*lookup.items())]) df1 = df.withColumn("col2", lookup_map[F.col("col1")]) df1.show() #+-----...
5
6
70,450,880
2021-12-22
https://stackoverflow.com/questions/70450880/pandas-groupby-with-multiple-conditions
I'm trying to create a summary of call logs. There are 4 cases There is only one call log record for a phone and it has outcome, we choose its values for duration, status and outcome_record Multiple call logs of same phone has outcome, we choose the summary, duration and outcome_record of call log with max duration Th...
I think you can simplify the logic. If you sort your values mainly by 'outcome' and 'duration', you just have to drop duplicates and keep the last row of each sorted groups like this: cols = ['phone', 'outcome', 'duration'] new_df = df.sort_values(cols).drop_duplicates('phone', keep='last') print(new_df) # Output: id p...
5
1
70,458,086
2021-12-23
https://stackoverflow.com/questions/70458086/how-to-import-pyspark-sql-functions-all-at-once
from pyspark.sql.functions import isnan, when, count, sum , etc... It is very tiresome adding all of it. Is there a way to import all of it at once?
You can try to use from pyspark.sql.functions import *. This method may lead to namespace coverage, such as pyspark sum function covering python built-in sum function. Another insurance method: import pyspark.sql.functions as F, use method: F.sum.
5
20
70,452,146
2021-12-22
https://stackoverflow.com/questions/70452146/how-to-speed-up-the-agg-of-pandas-groupby-bins
I have created different bins for each column and grouped the DataFrame based on these. import pandas as pd import numpy as np np.random.seed(100) df = pd.DataFrame(np.random.randn(100, 4), columns=['a', 'b', 'c', 'value']) # for simplicity, I use the same bin here bins = np.arange(-3, 4, 0.05) df['a_bins'] = pd.cut(df...
For this data, I'd suggest you pivot the data, and pass the mean. Usually, this is faster since you are hitting the entire dataframe, instead of going through each group: (df .pivot(None, ['a_bins', 'b_bins', 'c_bins'], 'value') .mean() .sort_index() # ignore this if you are not fuzzy on order ) a_bins b_bins c_bins (-...
8
6
70,453,104
2021-12-22
https://stackoverflow.com/questions/70453104/brownie-not-working-cython-undefined-symbol-pygen-send
I set up my development environment on Fedora 35 and when I run any brownie command such as $ brownie console or even brownie --version I get the following error: Traceback (most recent call last): File "/home/philippbunke/.local/bin/brownie", line 5, in <module> from brownie._cli.__main__ import main File "/home/phili...
The problem here seems to be Python 3.10.1! I used anaconda to create a new virtual environment with Python 3.8.12, installed brownie using pipx install --python python3.8 eth-brownie and it worked! The trick here was, to also tell pipx to use another python version, otherwise it would create a dependency to the global...
9
7
70,452,465
2021-12-22
https://stackoverflow.com/questions/70452465/how-to-load-in-graph-from-networkx-into-pytorch-geometric-and-set-node-features
Goal: I am trying to import a graph FROM networkx into PyTorch geometric and set labels and node features. (This is in Python) Question(s): How do I do this [the conversion from networkx to PyTorch geometric]? (presumably by using the from_networkx function) How do I transfer over node features and labels? (more impor...
The easiest way is to add all information to the networkx graph and directly create it in the way you need it. I guess you want to use some Graph Neural Networks. Then you want to have something like below. Instead of text as labels, you probably want to have a categorial representation, e.g. 1 stands for Ford. If you...
12
14
70,447,276
2021-12-22
https://stackoverflow.com/questions/70447276/i-have-a-dataset-in-which-i-have-two-columns-with-time-in-it-but-the-dat
Unnamed: 0 Created Date Closed Date Agency Agency Name Complaint Type Descriptor Location Type Incident Zip Address Type City Landmark Status Borough 2869 2869 10/30/2013 09:14:47 AM 10/30/2013 10:48:51 AM NYPD New York City Police Department Illegal Parking Double Parked Blocking Traffic Street/Sidewalk 11217.0 PLACEN...
You can first start by converting your date columns to datetime type using pd.to_datetime(): for c in ['Created Date', 'Closed Date']: df[c] = pd.to_datetime(df[c]) #df[c+'_date'] = df[c].dt.date # to extract the date (for created + closed) #df[c+'_time'] = df[c].dt.time # to extract the time (for created + closed) Th...
5
1
70,449,114
2021-12-22
https://stackoverflow.com/questions/70449114/programming-a-probability-of-twins-reunion
I have a problem as below, I tried but I couldn't find the right result. I want to solve it in a simple way without using an extra library. I don't have any data to share because I can't establish a correct logic. 4 twins (8 children in total) play with their eyes closed. The children in the randomly distributed group ...
Creating all pairings and comparing to correct pairing First, define a function to generate all pairings, and a function to generate the correct pairing: def all_pairings(l): if len(l) == 0: return [[]] else: return [[(l[0],l[i])] + p for i in range(1,len(l)) for p in all_pairings(l[1:i]+l[i+1:])] def adjacent_pairing(...
6
3
70,449,405
2021-12-22
https://stackoverflow.com/questions/70449405/when-why-use-types-from-typing-module-for-type-hints
What is exactly the 'right' way for type hinting? My IDE (and resulting code) works fine for type hints using either of below options, but some types can be imported from the typing module. Is there a preference for using the import from the typing module over builtins (like list or dict)? Examples: from typing import ...
The "right" way is to use builtins when possible (e.g. dict over typing.Dict). typing.Dict is only needed if you use Python < 3.9. In older versions you couldn't use generic annotations like dict[str, Any] with builtins, you had to use Dict[str, Any]. See PEP 585
12
14
70,444,996
2021-12-22
https://stackoverflow.com/questions/70444996/obtaining-metadata-where-from-of-a-file-on-mac
I am trying to obtain the "Where from" extended file attribute which is located on the "get info" context-menu of a file in MacOS. Example When right-clicking on the file and displaying the info it shows the this metadata. The highlighted part in the image below shows the information I want to obtain (the link of the w...
TL;DR: Get the extended attribute like MacOS's "Where from" by e.g. pip-install pyxattr and use xattr.getxattr("file.pdf", "com.apple.metadata:kMDItemWhereFroms"). Extended Attributes on files These extended file attributes like your "Where From" in MacOS (since 10.4) store metadata not interpreted by the filesystem. T...
5
9
70,446,485
2021-12-22
https://stackoverflow.com/questions/70446485/check-whether-url-exists-or-not-without-downloading-the-content-using-python
I have to check whether url exists or not using python. I am trying to use requests.get(url) but it is taking alot of time as the file starts downloading as soon as get is hit. I don't want the file to be downloaded for checking the url validity. Can this be achieved using python ?
Something like the below. See HTTP head for more info. import requests urls = ['https://www.google.com','https://www.google.com/you_can_not_find_me'] for idx,url in enumerate(urls,1): r = requests.head(url) if r.status_code == 200: print(f'{idx}) {url} was found') else: print(f'{idx}) {url} was NOT found') output 1) h...
4
6
70,361,947
2021-12-15
https://stackoverflow.com/questions/70361947/how-to-install-python-package-from-github-that-doesnt-have-setup-py-in-it
I would like to use the following sdk in my python project -> https://github.com/LBank-exchange/lbank-api-sdk-v2. It has sdk's for 3 languages (I just want the python one). I tried to install it using the command: pip install git+https://github.com/LBank-exchange/lbank-api-sdk-v2.git#egg=lbank which gave the error does...
Looks like the developer didn't bother to package it properly. If it was me using it, I would fork it on GH, add the setup.py and use the fork. Maybe a good exercise for you? Meanwhile, to just get it to work, in your project "root": git clone https://github.com/LBank-exchange/lbank-api-sdk-v2.git ln -s lbank-api-sdk-v...
6
6
70,392,020
2021-12-17
https://stackoverflow.com/questions/70392020/f-string-formatting-display-number-sign
Basic question about python f-strings, but couldn't find out the answer: how to force sign display of a float or integer number? i.e. what f-string makes 3 displayed as +3?
From Docs: Format Specification Mini-Language(Emphasis mine): Option Meaning '+' indicates that a sign should be used for both positive as well as negative numbers. '-' indicates that a sign should be used only for negative numbers (this is the default behavior). Example from docs: >>> '{:+f}; {:+f}'.fo...
14
22
70,367,905
2021-12-15
https://stackoverflow.com/questions/70367905/how-to-create-a-new-branch-push-a-text-file-and-send-merge-request-to-a-gitlab
I found https://github.com/python-gitlab/python-gitlab, but I was unable to understand the examples in the doc.
That's right there are no tests we can find in the doc. Here's a basic answer for your question. If you would like a complete working script, I have attached it here: https://github.com/hubshashwat/common_scripts/blob/main/automation_to_create_push_merge_in_gitlab/usecase_gitlab_python.py Breaking down the steps below:...
6
2
70,404,485
2021-12-18
https://stackoverflow.com/questions/70404485/how-did-printa-a-pop0-change
This code: a = [1, 2, 3] print(*a, a.pop(0)) Python 3.8 prints 2 3 1 (does the pop before unpacking). Python 3.9 prints 1 2 3 1 (does the pop after unpacking). What caused the change? I didn't find it in the changelog. Edit: Not just in function calls but also for example in a list display: a = [1, 2, 3] b = [*a, a.po...
I suspect this may have been an accident, though I prefer the new behavior. The new behavior is a consequence of a change to how the bytecode for * arguments works. The change is in the changelog under Python 3.9.0 alpha 3: bpo-39320: Replace four complex bytecodes for building sequences with three simpler ones. The f...
65
53
70,363,269
2021-12-15
https://stackoverflow.com/questions/70363269/how-can-i-convert-a-markdown-string-to-a-docx-in-python
I am getting markdown text from my API like this: { name:'Onur', surname:'Gule', biography:'## Computers I like **computers** so much. I wanna *be* a computer.', membership:1 } biography column includes markdown string like above. ## Computers I like **computers** so much. I wanna *be* a computer. I want to take this...
I solved it without any shortcut. I turn the markdown to html with beautifulSoup and then process every paragraph by checking theirs tag names. In my word template: {% if markdownText != None %} {% for mt in markdownText|mark2html %} {{mt}} {% endfor %} {% endif %} My template tag: def mark2html(value): if value == No...
7
10
70,383,316
2021-12-16
https://stackoverflow.com/questions/70383316/pydantic-constr-vs-field-args
I wanted to know what is the difference between: from pydantic import BaseModel, Field class Person(BaseModel): name: str = Field(..., min_length=1) And: from pydantic import BaseModel, constr class Person(BaseModel): name: constr(min_length=1) Both seem to perform the same validation (even raise the exact same excep...
constr and Fields don't serve the same purpose. constr is a specific type that give validation rules regarding this specific type. You have equivalent for all classic python types. arguments of constr: strip_whitespace: bool = False: removes leading and trailing whitespace to_lower: bool = False: turns all characters ...
19
15
70,416,097
2021-12-19
https://stackoverflow.com/questions/70416097/adding-data-labels-ontop-of-my-histogram-python-matplotlib
i am trying to add data labels values on top of my histogram to try to show the frequency visibly. This is my code now but unsure how to code up to put the value ontop: plt.figure(figsize=(15,10)) plt.hist(df['Age'], edgecolor='white', label='d') plt.xlabel("Age") plt.ylabel("Number of Patients") plt.title = ('Age Dist...
You can use the new bar_label() function using the bars returned by plt.hist(). Here is an example: from matplotlib import pyplot as plt import pandas as pd import numpy as np df = pd.DataFrame({'Age': np.random.randint(20, 60, 200)}) plt.figure(figsize=(15, 10)) values, bins, bars = plt.hist(df['Age'], edgecolor='whit...
11
24
70,362,595
2021-12-15
https://stackoverflow.com/questions/70362595/visual-studio-code-not-recognizing-python-import-and-functions
What do the squiggly lines represent in the image? The actual error the flags up when I hover my mouse over the squiggly line is: Import "pyspark.sql.functions" could not be resolvedPylance I'm not sure what that means, but I'm getting the error for almost all functions in Visual Studio Code. How can I resolve it?
I was with the same error as yours. Visual Studio Code usually has a "recommended" interpreter, but sometimes it won't help you out with what you need. So, I changed the Interpreter (Ctrl + Shift + P in Visual Studio Code). Look for "Python: Select Interpreter. Choose the one who contains the name "Conda" And that's ...
8
8
70,426,576
2021-12-20
https://stackoverflow.com/questions/70426576/get-random-number-from-set-deprecation
I am trying to get a random n number of users from a set of unique users. Here is what I have so far users = set() random_users = random.sample((users), num_of_user) This works well but it is giving me a deprecated warning. What should I be using instead? random.choice doesn't work with sets UPDATE I am trying to get ...
Convert your set to a list. by using the list function: random_users = random.choices(list(users),k=num_of_user) by using * operator to unpack your set or dict: random_users = random.choices([*users],k=num_of_user) Solution 1. is 3 char longer than the 2., but solution 1. is more literal - to me. It is not guaran...
12
13
70,396,931
2021-12-17
https://stackoverflow.com/questions/70396931/catch-all-overload-for-in-python-type-annotations
The below code fails mypy with error: Overloaded function signatures 1 and 2 overlap with incompatible return types. @overload def test_overload(x: str) -> str: ... @overload def test_overload(x: object) -> int: ... def test_overload(x) -> Union[str, int]: if isinstance(x, str): return x else: return 1 What I'm trying...
At the moment (Python 3.10, mypy 0.961) there is no way to express any object except one. But you could use ignoring type: ignore[misc] for excepted types. And they must precede the more general variant, because for @overload order is matter: from typing import overload, Union @overload def test_overload(x: str) -> str...
10
7
70,376,255
2021-12-16
https://stackoverflow.com/questions/70376255/how-to-fetch-data-from-clickhouse-in-dicitionary-name-tuple-using-clickhouse-dri
When we fetch data using the DB API 2.0 cur.execute("select * from db.table") we get a cursor which seems like a generator object of list of tuples. Whereas in pymongo, when we fetch we get it as list of dictionaries. I wanted to achieve something like this. Instead of fetching list of tuples, I wanted list of dictiona...
You can alternatively create a Client and call its query_dataframe method. import clickhouse_driver as ch ch_client = ch.Client(host='localhost') df = ch_client.query_dataframe('select * from db.table') records = df.to_dict('records')
5
3
70,416,187
2021-12-19
https://stackoverflow.com/questions/70416187/check-if-values-in-a-column-exist-elsewhere-in-a-dataframe-row
Suppose I have a dataframe as below: df = pd.DataFrame({'a':[1,2,3,4],'b':[2,3,4,5],'c':[3,4,5,6],'d':[5,3,2,4]}) I want to check if elements in column d exist elsewhere in its corresponding row. So the outcome I want is [False, True, False, True] Towards that end, I used df.apply(lambda x: x['d'] in x[['a','b','c']]...
Try: out = (df[['a','b','c']].T==df['d']).any() Output: 0 False 1 True 2 False 3 True dtype: bool
5
3
70,437,840
2021-12-21
https://stackoverflow.com/questions/70437840/how-to-change-colors-for-decision-tree-plot-using-sklearn-plot-tree
How to change colors in decision tree plot using sklearn.tree.plot_tree without using graphviz as in this question: Changing colors for decision tree plot created using export graphviz? plt.figure(figsize=[21, 6]) ax1 = plt.subplot(121) ax2 = plt.subplot(122) ax1.plot(X[:, 0][y == 0], X[:, 1][y == 0], "bo") ax1.plot(X[...
Many matplotlib functions follow the color cycler to assign default colors, but that doesn't seem to apply here. The following approach loops through the generated annotation texts (artists) and the clf tree structure to assign colors depending on the majority class and the impurity (gini). Note that we can't use alpha...
11
8
70,375,349
2021-12-16
https://stackoverflow.com/questions/70375349/using-searchvectorfields-on-many-to-many-related-models
I have two models Author and Book which are related via m2m (one author can have many books, one book can have many authors) Often we need to query and match records for ingests using text strings, across both models ie: "JRR Tolkien - Return of the King" when unique identifiers are not available. I would like to test ...
Finally got it. I suppose you need to search by query containing the author and the book's name at the same time. And you wouldn't be able to separate them to look at Book table for "book" part of the query and the same for Author. Yep, making an index of fields from separate tables is impossible with PostgreSQL. I don...
5
4
70,422,166
2021-12-20
https://stackoverflow.com/questions/70422166/when-run-pip-compile-requirements-in-in-macos12-monterey-using-venv-python-3-9
OS: monterey macOSv12.0.1 python venv: 3.9.9 requirements.in # To update requirements.txt, run: # # pip-compile requirements.in # # To install in localhost, run: # # pip-sync requirements.txt # django==3.2.10 # https://www.djangoproject.com/ psycopg2-binary==2.9.2 # https://github.com/psycopg/psycopg2 After i turn on ...
I appreciate the other 2 answers from @Vishnudev and @cetver 🙏 But I tried to install postgresql using brew install and it took a very long time and I still cannot complete after 20 mins. I figured this out eventually after much googling Here are my tech specs of my situation: monterey 12.1.0 Apple silicon zsh Conce...
6
7
70,393,863
2021-12-17
https://stackoverflow.com/questions/70393863/polymorphism-and-type-hints-in-python
Consider the following case: class Base: ... class Sub(Base): ... def get_base_instance(*args) -> Base: ... def do_something_with_sub(instance: Sub): ... Let's say I'm calling get_base_instance in a context where I kow it will return a Sub instance - maybe based on what args I'm passing. Now I want to pass the returne...
I think you were on the right track when you thought about it in terms of casting. We could use cast from typing to stop the IDE complaining. For example: from typing import cast class Base: pass class Sub(Base): pass def get_base_instance(*args) -> Base: return Sub() def do_something_with_sub(instance: Sub): print(ins...
7
2
70,420,155
2021-12-20
https://stackoverflow.com/questions/70420155/how-to-predict-actual-future-values-after-testing-the-trained-lstm-model
I have trained my stock price prediction model by splitting the dataset into train & test. I have also tested the predictions by comparing the valid data with the predicted data, and the model works fine. But I want to predict actual future values. What do I need to change in my code below? How can I make predictions u...
Below is an example of how you could implement this approach for your model: import pandas as pd import numpy as np from datetime import date from nsepy import get_history from keras.models import Sequential from keras.layers import LSTM, Dense from sklearn.preprocessing import MinMaxScaler pd.options.mode.chained_assi...
5
3
70,442,764
2021-12-21
https://stackoverflow.com/questions/70442764/custom-conflict-handling-for-argumentparser
What I need I need an ArgumentParser, with a conflict handling scheme, that resolves some registered set of duplicate arguments, but raises on all other arguments. What I tried My initial approach (see also the code example at the bottom) was to subclass ArgumentParser, add a _handle_conflict_custom method, and then in...
For a various reasons -- notably the needs of testing -- I have adopted the habit of always defining argparse configuration in the form of a data structure, typically a sequence of dicts. The actual creation of the ArgumentParser is done in a reusable function that simply builds the parser from the dicts. This approach...
9
2
70,413,959
2021-12-19
https://stackoverflow.com/questions/70413959/combine-2-string-columns-in-pandas-with-different-conditions-in-both-columns
I have 2 columns in pandas, with data that looks like this. code fx category AXD AXDG.R cat1 AXF AXDG_e.FE cat1 333 333.R cat1 .... There are other categories but I am only interested in cat1. I want to combine everything from the code column, and everything after the . in the fx column and replace the code column wit...
There are other categories but I am only interested in cat1 You can use str.split with series.where to add the extention for cat1: df['code'] = (df['code'].astype(str).add("."+df['fx'].str.split(".").str[-1]) .where(df['category'].eq("cat1"),df['code'])) print(df) code fx category 0 AXD.R AXDG.R cat1 1 AXF.FE AXDG_...
6
3
70,433,788
2021-12-21
https://stackoverflow.com/questions/70433788/proper-c-type-for-nested-list-of-arbitrary-and-variable-depth
I'm trying to port some code from Python to C++. The Python code has a function foo that can take nested lists of ints, with variable list depth. For example, these are legitimate function calls to foo: foo([ [], [[]], [ [], [[]] ] ]) foo([1]) foo([ [1], [2, 3, [4, 5]], [ [6], [7, [8, 9], 10] ] ]) What should the meth...
Here's a way that's pretty simple to define and use: #include <variant> #include <vector> struct VariableDepthList : std::variant<std::vector<VariableDepthList>, int> { private: using base = std::variant<std::vector<VariableDepthList>, int>; public: using base::base; VariableDepthList(std::initializer_list<VariableDept...
6
4
70,416,616
2021-12-20
https://stackoverflow.com/questions/70416616/rolling-sum-based-on-all-previous-dates-not-previous-rows-sorted-by-date
Given the following dataframe: +------------+--------+ | Date | Amount | +------------+--------+ | 01/05/2019 | 15 | | 27/05/2019 | 20 | | 27/05/2019 | 15 | | 25/06/2019 | 10 | | 29/06/2019 | 25 | | 01/07/2019 | 50 | +------------+--------+ I need to get the rolling sum of all previous dates as follows: +------------+...
You can do df['new'] = df.Date.map(df.groupby('Date').Amount.sum().rolling("28d", closed="left").sum()) df Date Amount new 0 2019-05-01 15 NaN 1 2019-05-27 20 15.0 2 2019-05-27 15 15.0 3 2019-06-15 10 35.0 4 2019-06-29 25 10.0 5 2019-07-01 50 35.0
6
2
70,400,639
2021-12-18
https://stackoverflow.com/questions/70400639/how-do-i-get-python-dataclass-initvar-fields-to-work-with-typing-get-type-hints
When messing with Python dataclasses, I ran into this odd error that's pretty easy to reproduce. from __future__ import annotations import dataclasses as dc import typing @dc.dataclass class Test: foo: dc.InitVar[int] print(typing.get_type_hints(Test)) Running this gets you the following: Traceback (most recent call l...
So I was actually able to replicate this exact same behavior in my Python 3.10 environment, and frankly was sort of surprised that I was able to do so. The issue, at least from the surface, seems to be with InitVar and with how typing.get_type_hints resolves such non-generic types. Anyways, before we get too deep into ...
6
14
70,429,982
2021-12-21
https://stackoverflow.com/questions/70429982/how-to-disable-all-tensorflow-warnings
I have a for loop with several different deep learning models in it that generates this warning: WARNING:tensorflow:5 out of the last 5 calls to <function Model.make_predict_function.<locals>.predict_function at 0x000001B0A8CC90D0> triggered tf.function retracing. Tracing is expensive and the excessive number of tracin...
Use this: tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
5
7
70,425,481
2021-12-20
https://stackoverflow.com/questions/70425481/namedtuple-with-default-values
I'm trying to use a function with a parameter of namedTuple which has default values. I tried this. Is that somehow possible? from typing import Optional, NamedTuple Stats = NamedTuple("Stats", [("min", Optional[int]), ("max", Optional[int])]) def print(value1: Stats=None, value2: Stats=None): print("min: ", value1.min...
Rename your print() function, first you're using the built-in function name print which is bad style, secondly then you make a recursive call to print() inside print() (and I'm sure you meant to call the actual built-in print() inside function's body). Second, use collection.namedtuple class to implement actual type of...
9
5
70,428,172
2021-12-20
https://stackoverflow.com/questions/70428172/how-to-put-string-parameters-in-functions-inside-f-strings
I have the following f-string: f"Something{function(parameter)}" I want to hardcode that parameter, which is a string: f"Something{function("foobar")}" It gives me this error: SyntaxError: f-string: unmatched '(' How do I do this?
Because f-strings are recognized by the lexer, not the parser, you cannot nest quotes of the same type in a string. The lexer is just looking for the next ", regardless of its context. Use single quotes inside f"..." or double quotes inside f'...'. f"Something{function('foobar')}" f'Something{function("foobar")}' Esca...
5
7
70,420,566
2021-12-20
https://stackoverflow.com/questions/70420566/dataframe-pairs-of-columns-division
I have a DataFrame and want to get divisions of pairs of columns like below: df = pd.DataFrame({ 'a1': np.random.randint(1, 1000, 1000), 'a2': np.random.randint(1, 1000, 1000), 'b1': np.random.randint(1, 1000, 1000), 'b2': np.random.randint(1, 1000, 1000), 'c1': np.random.randint(1, 1000, 1000), 'c2': np.random.randint...
You can use: df[['a', 'b', 'c']] = df[['a2', 'b2', 'c2']].values / df[['a1', 'b1', 'c1']].values OUTPUT a1 a2 b1 b2 c1 c2 a b c 0 864 214 551 761 174 111 0.247685 1.381125 0.637931 1 820 971 379 79 190 587 1.184146 0.208443 3.089474 2 305 154 519 378 567 186 0.504918 0.728324 0.328042 3 51 505 303 417 959 326 9.90196...
6
3
70,419,372
2021-12-20
https://stackoverflow.com/questions/70419372/python-generic-type-that-implements-protocol
Objects A, B ... have attribute namespace and I have a function that filters a list of such objects by a certain set of values of namespace attribute: T = TypeVar('T') def filter(seq: list[T], namespace_values: set[str]) -> list[T]: # Returns a smaller list containing only the items from # `seq` whose `namespace` are i...
Use a bound type variable with the protocol as the bound. Consider the following module: (py39) Juans-MacBook-Pro:~ juan$ cat test.py Which has: from typing import TypeVar, Protocol from dataclasses import dataclass class Namespaced(Protocol): namespace: str T = TypeVar("T", bound="Namespaced") @dataclass class Foo: n...
9
9
70,418,120
2021-12-20
https://stackoverflow.com/questions/70418120/python-how-to-transpose-the-count-of-values-in-one-pandas-data-frame-to-multiple
I have 2 data frames df1 and df2. import pandas as pd df1 = pd.DataFrame({ 'id':['1','1','1','2','2','2', '3', '4','4', '5', '6', '7'], 'group':['A','A','B', 'A', 'A', 'C', 'A', 'A', 'B', 'B', 'A', 'C'] }) df2 = pd.DataFrame({ 'id':['1','2','3','4','5','6','7'] }) I want to add 3 columns to df2 named group_A, group_B,...
Use crosstab with DataFrame.join, type of both id has to by same, like here strings: print (pd.crosstab(df1['id'], df1['group']).add_prefix('group_')) group group_A group_B group_C id 1 2 1 0 2 2 0 1 3 1 0 0 4 1 1 0 5 0 1 0 6 1 0 0 7 0 0 1 df = df2.join(pd.crosstab(df1['id'], df1['group']).add_prefix('group_'), on='id'...
5
3
70,410,527
2021-12-19
https://stackoverflow.com/questions/70410527/tesseract-ocr-gives-really-bad-output-even-with-typed-text
I've been trying to get tesseract OCR to extract some digits from a pre-cropped image and it's not working well at all even though the images are fairly clear. I've tried looking around for solutions but all the other questions I've seen on here involve a problem with cropping or skewed text. Here's an example of my co...
I've found a decent workaround. First off I've made the image larger. More area for tesseract to work with helped it a lot. Second, to get rid of non-digit outputs, I've used the following config on the image to string function: config = "--psm 7 outputbase digits" That line now looks like this: speed = pytesseract.im...
5
1
70,381,558
2021-12-16
https://stackoverflow.com/questions/70381558/get-the-name-or-label-from-django-integerchoices-providing-a-valid-value
I have django 3.2 and an IntegerChoices class class Type(models.IntegerChoices): GENERAL = 2, _("general address") DELIVERY = 4, _("delivery address") BILLING = 6, _("billing address") I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label. But how can I get these v...
IntegerChoices.choices returns you a list of tuples with all content. In your case you'll have something like: [(2, 'general address'), (4, 'delivery address'), (6, 'billing address')] Thus it can be done this way: class Type(models.IntegerChoices): GENERAL = 2, _("general address") DELIVERY = 4, _("delivery address")...
5
4
70,409,343
2021-12-19
https://stackoverflow.com/questions/70409343/assert-to-check-if-a-element-present-in-a-list-or-not
I am trying to find if a particular element (int/string type), exists in my list or not. But I am using assert to evaluate my condition, meaning if the assert condition states True (element is present inside the list), False for element not being there in the list. Here is what I am trying- def test(x): try: for i in x...
Try using this: assert 210410 in x
8
18
70,401,561
2021-12-18
https://stackoverflow.com/questions/70401561/integrate-js-scripts-on-streamlit
I am trying to integrate my Medium profile on a streamlit app using the below code snippet (generate through https://medium-widget.pixelpoint.io/) import streamlit as st st.markdown(''' <div id="medium-widget"></div> <script src="https://medium-widget.pixelpoint.io/widget.js"></script> <script>MediumWidget.Init({render...
You can use Streamlit component html. Code: import streamlit as st import streamlit.components.v1 as components components.html(''' <div id="medium-widget"></div> <script src="https://medium-widget.pixelpoint.io/widget.js"></script> <script>MediumWidget.Init({renderTo: '#medium-widget', params: {"resource":"https://med...
6
3