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 |
|---|---|---|---|---|---|---|
74,826,321 | 2022-12-16 | https://stackoverflow.com/questions/74826321/how-to-type-hint-a-matplotlib-figure-object-in-python3 | I am trying to add type hints for data returned by plt.subplots. That works fine for plt.Axes, but I can't seem to find a solution for Figure. Any ideas what I could do? An abbreviated version of my code is: def draw_graph() -> Tuple[plt.Figure, plt.Axes]: fig, ax = plt.subplots(figsize=(14,10)) return (fig, ax) I get... | With the latest Matplotlib (v3.7.1) I was able to do the following: import matplotlib.pyplot as plt import matplotlib.figure def draw_graph() -> Tuple[matplotlib.figure.Figure, plt.Axes]: fig, ax = plt.subplots(figsize=(14,10)) return (fig, ax) I haven't tested using plt.Figure, but my IDE (i.e., VS Code) was not givi... | 6 | 6 |
74,867,332 | 2022-12-20 | https://stackoverflow.com/questions/74867332/websocket-django-channels-doesnt-work-with-postman | Django Channels Throw error with postman while working well with Html. I'm following Django Socket Tutorial "here's the error showing in Django". WebSocket HANDSHAKING /ws/chat/roomName/ [127.0.0.1:56504] WebSocket REJECT /ws/chat/roomName/ [127.0.0.1:56504] WebSocket DISCONNECT /ws/chat/roomName/ [127.0.0.1:56504] "E... | Stepping through the \channels\security\websocket.py module, Channels's OriginValidator is looking for an origin header, not a hosts header, which is what Postman defaults to. Assuming your ALLOWED_HOSTS looks like: ALLOWED_HOSTS = ["localhost", "127.0.0.1"] Then in Postman, in headers add: origin:http://127.0.0.1:800... | 3 | 5 |
74,837,978 | 2022-12-17 | https://stackoverflow.com/questions/74837978/syntaxerror-invalid-non-printable-character-u00a0-in-python | I'm getting the error: SyntaxError: invalid non-printable character U+00A0 When I'm running the code below: # coding=utf-8 from PIL import Image img = Image.open("img.png") I have tried to load different images with different formats (png, jpg, jpeg). I have tried using different versions of the Pillow library. I have... | The problem was related to a fake space found in the third line (the empty one). It is a character that looks like a space but is actually something else which is not detected by python. By removing this character the error disappeared. The character is this: | 8 | 20 |
74,844,262 | 2022-12-18 | https://stackoverflow.com/questions/74844262/how-can-i-solve-error-module-numpy-has-no-attribute-float-in-python | I am using NumPy 1.24.0. On running this sample code line, import numpy as np num = np.float(3) I am getting this error: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ubuntu/.local/lib/python3.8/site-packages/numpy/__init__.py", line 284, in __getattr__ raise AttributeError("module... | The answer is already provided in the comments by @mattdmo and @tdelaney: NumPy 1.20 (release notes) deprecated numpy.float, numpy.int, and similar aliases, causing them to issue a deprecation warning NumPy 1.24 (release notes) removed these aliases altogether, causing an error when they are used In many cases you ... | 75 | 64 |
74,857,405 | 2022-12-20 | https://stackoverflow.com/questions/74857405/how-to-use-diffusers-with-custom-ckpt-file | Currently I have the current code which runs a prompt on a model which it downloads from huggingface. from diffusers import StableDiffusionPipeline, EulerDiscreteScheduler model_id = "stabilityai/stable-diffusion-2" # Use the Euler scheduler here instead scheduler = EulerDiscreteScheduler.from_pretrained(model_id, subf... | You cannot use a ckpt file with diffusers out of the box. The ckpt file has to be converted to a diffusers friendly format. You can do that with a tool named StableTuner. Or this utility script on HuggingFace https://huggingface.co/spaces/anzorq/sd-to-diffusers | 4 | 3 |
74,866,909 | 2022-12-20 | https://stackoverflow.com/questions/74866909/inadequate-transform-produced-by-good-homographic-feature-match | I'm trying to determine a method to rotate and translate a scanned 2D image to match it's near-identical but lower-quality digital template. After running the code, I want the images to very closely align when overlaid, so that post-processing effects can be applied to the scan based on knowledge of the template layout... | To answer my own question in case someone mysteriously has a similar issue in future: it's important to make sure that when you're applying your homography matrix that your destination size corresponds with the template you're attempting to match if you're looking to get an "exact" match with said template. In my origi... | 3 | 4 |
74,827,982 | 2022-12-16 | https://stackoverflow.com/questions/74827982/using-a-buffer-to-write-a-psycopg3-copy-result-through-pandas | Using psycopg2, I could write large results as CSV using copy_expert and a BytesIO buffer like this with pandas: copy_sql = "COPY (SELECT * FROM big_table) TO STDOUT CSV" buffer = BytesIO() cursor.copy_expert(copy_sql, buffer, size=8192) buffer.seek(0) pd.read_csv(buffer, engine="c").to_excel(self.output_file) However... | The key to writing a large query to a file through psycopg3 in this fashion is to use a SpooledTemporaryFile, which will limit the amount of memory usage in Python (see max_size). Then after the CSV is written to disk, convert with pandas. from tempfile import SpooledTemporaryFile from pandas import read_csv from psyco... | 4 | 3 |
74,852,107 | 2022-12-19 | https://stackoverflow.com/questions/74852107/pytorch-linear-regression-1x1d-consistantly-wrong-slope | I am mastering pytorch here, and decided to implement very simple 1 to 1 linear regression, from height to weight. Got dataset: https://www.kaggle.com/datasets/mustafaali96/weight-height but any other would do nicely. Lets import libraries and information about females: import torch from torch.utils.data import Dataset... | I think your issue stems from the data not being centered around zero. See this thread for another example where "centering" the data prior to training has a huge effect on the convergence of SGD optimization. Update (Dec 29the, 2022): TL;DR It's all about normalization/initialization. In detail: Your data is not cent... | 5 | 6 |
74,832,296 | 2022-12-17 | https://stackoverflow.com/questions/74832296/typeerror-string-indices-must-be-integers-when-getting-data-of-a-stock-from-y | import pandas_datareader end = "2022-12-15" start = "2022-12-15" stock_list = ["TATAELXSI.NS"] data = pandas_datareader.get_data_yahoo(symbols=stock_list, start=start, end=end) print(data) When I run this code, I get error "TypeError: string indices must be integers". Edit : I have updated the code and passed list as ... | None of the solutions reported here so far worked for me. As per the discussion here Yahoo made changes to their API that broke compatibility with previous pandas datareader versions. In the same Github thread a fix is reported, implemented in a pull request from Github user raphi6. I confirmed the pull request works f... | 49 | 20 |
74,868,286 | 2022-12-20 | https://stackoverflow.com/questions/74868286/how-do-i-modify-this-function-to-return-a-4d-array-instead-of-3d | I created this function that takes in a dataframe to return an ndarrays of input and label. def transform_to_array(dataframe, chunk_size=100): grouped = dataframe.groupby('id') # initialize accumulators X, y = np.zeros([0, 1, chunk_size, 4]), np.zeros([0,]) # original inpt shape: [0, 1, chunk_size, 4] # loop over each ... | You can simply reshape the X just before returning it at the end of modified_transform_to_array(), e.g.: def modified_transform_to_array( ... ): ... # convert lists to numpy arrays X = np.array(X) y = np.array(y) X = X.reshape((X.shape[0], 1, *X.shape[1:])) # <-- THIS LINE return X, y or, equivalently: X = X.reshape((... | 5 | 4 |
74,844,094 | 2022-12-18 | https://stackoverflow.com/questions/74844094/projection-onto-unit-simplex-using-gradient-decent-in-pytorch | In Professor Boyd homework solution for projection onto the unit simplex, he winds up with the following equation: g_of_nu = (1/2)*torch.norm(-relu(-(x-nu)))**2 + nu*(torch.sum(x) -1) - x.size()[0]*nu**2 If one calculates nu*, then the projection to unit simplex would be y*=relu(x-nu*1). What he suggests is to find t... | The error comes from the derivation of the formula: from: If you develop the expression you will realize that it should be instead of In short, this error comes from forgetting the 1/2 factor while developing the norm. Once you make that change everything works as intended: import torch import torchvision import n... | 4 | 2 |
74,800,328 | 2022-12-14 | https://stackoverflow.com/questions/74800328/reshape-pandas-dataframe-from-wide-to-long-by-splitting | I am trying to reshape the following data from wide to long format df = pd.DataFrame( { "size_Ent": { pd.Timestamp("2021-01-01 00:00:00"): 600, pd.Timestamp("2021-01-02 00:00:00"): 930, }, "size_Baci": { pd.Timestamp("2021-01-01 00:00:00"): 700, pd.Timestamp("2021-01-02 00:00:00"): 460, }, "min_area_Ent": { pd.Timestam... | This can be solved in three simple steps: First, notice that your column names are actually encoding a 2x2 MultiIndex, so let's start by creating a MultiIndex from tuples. To do this, we need to first transform the existing column names into tuples. This is easy because we know they should be split at the last undersco... | 3 | 3 |
74,865,755 | 2022-12-20 | https://stackoverflow.com/questions/74865755/why-is-the-first-expression-interpreted-as-an-int-and-the-second-as-a-string | Using PyYaml import yaml yaml.full_load(StringIO('a: 16:00:00')) # {'a': 57600} yaml.full_load(StringIO('a: 09:31:00')) # {'a': '09:31:00'} Why is there a difference in those behaviors? | Older versions of YAML supported sexagesimal (base 60) numbers, intended for use for things like times. Instead of adding additional digits (like hexadecimal uses 0-9 and A-F), it simply uses decimal numbers 0-59 separated by :s. 16:00:00 is thus equivalent to 16*(60**2) + 0*60 + 0 == 57600. PyYAML apparently still us... | 4 | 4 |
74,866,750 | 2022-12-20 | https://stackoverflow.com/questions/74866750/error-floatobject-b0-000000000000-14210855-invalid-use-0-0-instead-while-u | I am using function to count occurrences of given word in pdf using PyPDF2. While the function is running I get message in terminal: FloatObject (b'0.000000000000-14210855') invalid; use 0.0 instead My code: def count_words(word): print() print('Counting words..') files = os.listdir('./pdfs') counted_words = [] for id... | See https://pypdf2.readthedocs.io/en/latest/user/suppress-warnings.html import logging logger = logging.getLogger("PyPDF2") logger.setLevel(logging.ERROR) | 4 | 1 |
74,866,168 | 2022-12-20 | https://stackoverflow.com/questions/74866168/how-to-get-individual-values-from-a-string-seperated-by-commas | I am reading a file using: def readFile(): file = open('Rules.txt', 'r') lines = file.readlines() for line in lines: rulesList.append(line) rulesList: ['\n', "Rule(F1, HTTPS TCP, ['ip', 'ip'], ['www.google.ca', '8.8.8.8'], 443)\n", '\n', "Rule(F2, HTTPS TCP, ['ip', 'ip'], ['75.2.18.233'], 443)\n", '\n'] My file looks... | If you have control over how the data in the file is stored and can replace the single quotes (') with double quotes (") to make the "list" structures valid JSON, you could use RegExp for this. A word of caution: unless you are absolutely sure that the format you'll be reading will largely remain the same and is rather... | 3 | 5 |
74,864,895 | 2022-12-20 | https://stackoverflow.com/questions/74864895/a-pythonic-way-to-init-inherited-dataclass-from-an-object-of-parent-type | Given a dataclass structure: @dataclass class RichParent: many_fields: int = 1 more_fields: bool = False class Child(RichParent): some_extra: bool = False def __init__(seed: RichParent): # how to init more_fields and more_fields fields here without referencing them directly? # self.more_fields = seed.more_fields # self... | I am unsure why you'd want to write an explicit __init__ *, although you may need to be on Python 3.10 to be able to pass in fields specific to Child to its init. ** from dataclasses import dataclass @dataclass(kw_only=True) class RichParent: many_fields: int = 1 more_fields: bool = False #for some reason not setting `... | 5 | 6 |
74,861,252 | 2022-12-20 | https://stackoverflow.com/questions/74861252/downgrade-poetry-version | I need to downgrade my version of poetry to version 1.2.1. Currently, it's 1.2.2. >>> poetry --version Poetry (version 1.2.2) I use the following command: >>> curl -sSL https://install.python-poetry.org | POETRY_VERSION=1.2.1 python3 - Retrieving Poetry metadata The latest version (1.2.1) is already installed. But I'... | if you want to install specific version in python hereit is , pip install poetry==1.2.1 In Future just simplpe pip install 'Your Library Name'== 'Specific version' | 13 | 5 |
74,859,403 | 2022-12-20 | https://stackoverflow.com/questions/74859403/using-exec-in-a-comprehension-list | I have a script that can be run independently but sometimes will be externally invoked with parameters meant to override the ones defined in the script. I got it working using exec() (the safety of this approach is not the point here) but I don't understand why it works in a for loop and not in a comprehension list. fo... | To update global variables, let exec() have access to them by passing globals() as the second parameter: [exec(ext,globals()) for ext in externally_given] # [None, None] foo # 10 bar # 20 (Subject to all the good comments to the original post.) | 3 | 5 |
74,831,594 | 2022-12-17 | https://stackoverflow.com/questions/74831594/cannot-import-name-wkbwriter-from-shapely-geos-when-import-google-cloud-ai-p | When I run this code on google colab. from google.cloud import aiplatform The following error occurred ImportError: cannot import name 'WKBWriter' from 'shapely.geos' (/usr/local/lib/python3.8/dist-packages/shapely/geos.py) Does anyone know how to solve this problem? I was working fine on 2022/12/16, but today it is no... | The bug is tracked in: https://github.com/googleapis/python-aiplatform/issues/1852 The workaround is to pin shapely < 2.0.0 pip install -U google-cloud-aiplatform "shapely<2" | 11 | 21 |
74,851,861 | 2022-12-19 | https://stackoverflow.com/questions/74851861/how-to-update-a-property-for-all-dataclass-objects-in-a-list | I have a list of objects of the following type: @dataclass class Feature: name: str active: bool and my list is: features = [Feature("name1",False), Feature("name2",False), Feature("name3",True)] I want to get back a list with all the features but switch their active property to True. I tried to use map() like this: ... | Reason why your logic is not working? It gives you error because the lambda function you're using is trying to modify the value of f.active, which is not allowed in a lambda function. lambda functions are allowed to only for expressions that return a value, rather than statements that perform some actions. So I think o... | 3 | 2 |
74,850,128 | 2022-12-19 | https://stackoverflow.com/questions/74850128/macros-are-not-recognised-in-dbt | {{ config ( pre_hook = before_begin("{{audit_tbl_insert(1,'stg_news_sentiment_analysis_incr') }}"), post_hook = after_commit("{{audit_tbl_update(1,'stg_news_sentiment_analysis_incr','dbt_development','news_sentiment_analysis') }}") ) }} select rd.news_id ,rd.title, rd.description, ns.sentiment from live_crawler_output_... | Your macro's definition has too much whitespace in the braces that define the jinja block: { % macro audit_tbl_insert (model_id_no, model_name_txt) % } Needs to be {% macro audit_tbl_insert (model_id_no, model_name_txt) %} And then this should work just fine. | 4 | 6 |
74,837,553 | 2022-12-17 | https://stackoverflow.com/questions/74837553/how-to-fix-a-mac-base-conda-environment-when-sqlite3-is-broken | I recently updated the Python version of my base conda environment from 3.8 to 3.9, using mamba update python=3.9, but I can no longer run IPython, because the sqlite3 package appears to be broken. python Python 3.9.15 | packaged by conda-forge | (main, Nov 22 2022, 08:55:37) [Clang 14.0.6 ] on darwin Type "help", "cop... | Following the suggestions by @merv, the solution to this problem was to force a reinstall of the libsqlite package. $ mamba install libsqlite --force-reinstall After updating Python, it seems that sqlite3 was linked to the Mac system library, /usr/lib/libsqlite3.dylib, rather than one installed by conda-forge. Accordi... | 10 | 13 |
74,853,515 | 2022-12-19 | https://stackoverflow.com/questions/74853515/how-to-make-scatter-plots-similar-to-the-one-in-the-paper-get-me-off-your-f | This is a serious question. Please do not take it as a joke. This is a scatter plot from an infamous paper with the same name, Get me off Your F****** Mailing List by Mazières and Kohle (2005), published in a predatory journal. Some people may know it. I am seriously interested in recreating the same scatter plot to t... | Now that the grid package supports clipping paths, we can do: library(grid) library(ggplot2) tg <- textGrob("Get me off\nYour Fuck\ning Mailing\nList", x = 0.2, hjust = 0, gp = gpar(cex = 6, col = "grey", font = 2)) cg <- pointsGrob(x= runif(15000), y = runif(15000), pch = 3, gp = gpar(cex = 0.5)) rg <- rectGrob(width ... | 4 | 5 |
74,852,879 | 2022-12-19 | https://stackoverflow.com/questions/74852879/finding-the-average-of-the-x-component-of-an-array-of-coordinates-based-on-the | I have the following example array of x-y coordinate pairs: A = np.array([[0.33703753, 3.], [0.90115394, 5.], [0.91172016, 5.], [0.93230994, 3.], [0.08084283, 3.], [0.71531777, 2.], [0.07880787, 3.], [0.03501083, 4.], [0.69253184, 4.], [0.62214452, 3.], [0.26953094, 1.], [0.4617873 , 3.], [0.6495549 , 0.], [0.84531478,... | Here's a completely vectorized solution that only uses numpy methods and no python iteration: sort_indices = np.argsort(A[:, 1]) unique_y, unique_indices, group_count = np.unique(A[sort_indices, 1], return_index=True, return_counts=True) Once we have the indices and counts of all the unique elements, we can use the np... | 4 | 4 |
74,849,203 | 2022-12-19 | https://stackoverflow.com/questions/74849203/extract-and-manipulate-dict-data-to-check-certificates | I struggle on a regular basis with data manipulation in Ansible. I'm not very familiar with Python and dict objects. I found an example that sums up a lot of my misunderstandings. I would like to verify a list of certificates. In found an example for a single domain in the documentation, I'm just trying to loop over se... | Given the simplified data for testing result_certs: changed: false msg: All items completed results: - expired: false item: domain.org public_key: <<PUBLIC KEY domain.org>> - expired: false item: domain.com public_key: <<PUBLIC KEY domain.com>> skipped: false result_privatekey: changed: false msg: All items completed... | 4 | 2 |
74,838,882 | 2022-12-18 | https://stackoverflow.com/questions/74838882/how-to-get-pixel-rgb-values-using-matplotlib | I need to find all red pixels in an image and create my own image with just the red pixels. So far I have been experimenting with matplotlib as I am very new to it. def find_red_pixels(map, upper_threshold=100, lower_threshold =50): """Finds all red pixels of the "map" image and outputs a binary image file "map-red-pix... | The first thing to understand is the way the image is represented in an array when it is read in. Here I read in a 320x160 image of a rainbow: >>> img = plt.imread('rainbow.png') >>> img.shape (160, 320, 4) This shows the dimensions of the array - note the last element of the tuple is 4. These values represent the re... | 4 | 4 |
74,848,349 | 2022-12-19 | https://stackoverflow.com/questions/74848349/pytorch-runtime-error-input-type-double-and-bias-type-float-should-be-the-s | The error came out when I try to train the CNN model using pytorch This is the model I create The model import torch class NNnet(torch.nn.Module): def __init__(self, channels = 19, samples = 1000.0, outputs = 4): super(NNnet, self).__init__() #Sequential 1 self.seq1 = torch.nn.Sequential( torch.nn.Conv2d(in_channels = ... | Default float in Numpy is float64, you must convert the Numpy tensor to np.float32 before converting it to Pytorch. train_dat = torch.utils.data.TensorDataset(torch.tensor(test_data_x).to(device), torch.tensor(test_data_y).to(device)) | 4 | 12 |
74,796,947 | 2022-12-14 | https://stackoverflow.com/questions/74796947/how-to-extract-rss-links-from-website-with-python | I am trying to extract all RSS feed links from some websites. Ofc if RSS exists. These are some website links that have RSS, and below is list of RSS links from those websites. website_links = ["https://www.diepresse.com/", "https://www.sueddeutsche.de/", "https://www.berliner-zeitung.de/", "https://www.aargauerzeitung... | Don't reinvent the wheel, there are many curated directories and collections that can serve you well and give you a nice introduction. However, to follow your approach, you should first collect all the links on the page that could point to an rss feed: soup.select('a[href*="rss"],a[href*="/feed"],a:-soup-contains-own("... | 5 | 8 |
74,847,117 | 2022-12-19 | https://stackoverflow.com/questions/74847117/unable-to-import-cartopy | After Installing cartopy on google-colab, I was not able to import it: !pip install cartopy import cartopy ImportError: cannot import name lgeos | The best way to install Cartopy in a Colab is by using the Conda environment. So we need to install the following: #1|Install Conda environment on Colab !pip install -q condacolab import condacolab condacolab.install() Then, #2|Install cartopy !mamba install -q -c conda-forge cartopy After that, #3|imoprt cartopy imp... | 4 | 3 |
74,846,232 | 2022-12-19 | https://stackoverflow.com/questions/74846232/search-part-of-tuple-list | I am trying to do a list comprehension of a tuples list based on another list of tuples with partial match. x = [((1,1),(1,1),(1,2)), ((2,1),(1,3),(2,9)), ((2,1),(2,3),(2,9))] y = [(2,1),(1,3)] [i for i in x for k in y if k in i] e.g. in this x is a list of tuples & y is the desired list of tuples. If y is found in an... | You can use: x = [ ((1, 1), (1, 1), (1, 2)), ((2, 1), (1, 3), (2, 9)), ((2, 1), (2, 3), (2, 9)), ] y = [(2, 1), (1, 3)] print([t for t in x if not set(y).difference(t)]) output: [((2, 1), (1, 3), (2, 9))] If you subtract tuples inside x from y with set operations, if all the sub tuples are present, you'll end up with... | 3 | 1 |
74,805,849 | 2022-12-15 | https://stackoverflow.com/questions/74805849/package-publishing-python-failing-through-poetry | I am new to this, trying to publish a package to pypi.org using Poetry package. on my local the build is working, I am able to import the package test run it, it's all good. but when I try to publish it to pypi.org, I get below error - as per the article I was following Link, it was supposed to prompt me for my pypi ac... | I was able to resolve the problem finally - Took help from poetry documentation here Issued the below command to setup my pypi.org account for auto authentication poetry config http-basic.pypi <username> <password> After that I ran the "poetry publish" command and was able to publish my package on pypi.org. It's reall... | 4 | 3 |
74,844,719 | 2022-12-18 | https://stackoverflow.com/questions/74844719/does-a-bitwise-and-operation-prepend-zeros-to-the-binary-representation | When I use bitwise and operator(&) with the number of 1 to find out if a number x is odd or even (x & 1), does the interpreter change the binary representation of 1 according to the binary representation of x? For example: 2 & 1 -> 10 & 01 -> then perform comparison bitwise 5 & 1 -> 101 & 001 -> then perform compariso... | Conceptually, adding zeros to the shorter number gives the same result as ignoring excess digits in the longer number. They both do the same thing. Padding, however, is inefficient, so in practice you wouldn't want to do it. The reason is because anything ANDed with 0 is 0. If you pad the short number to match the long... | 5 | 7 |
74,842,741 | 2022-12-18 | https://stackoverflow.com/questions/74842741/why-is-a-combination-of-numpy-functions-faster-than-np-mean | I am wondering what the fastest way for a mean computation is in numpy. I used the following code to experiment with it: import time n = 10000 p = np.array([1] * 1000000) t1 = time.time() for x in range(n): np.divide(np.sum(p), p.size) t2 = time.time() print(t2-t1) 3.9222593307495117 t3 = time.time() for x in range(n)... | For integer input, by default, numpy.mean computes the sum in float64 dtype. This prevents overflow errors, but it requires a conversion for every element. Your code with numpy.sum only converts once, after the sum has been computed. | 8 | 10 |
74,839,133 | 2022-12-18 | https://stackoverflow.com/questions/74839133/a-more-efficient-solution-for-balanced-split-of-an-array-with-additional-conditi | I appreciate your help in advance. This is a practice question from Meta's interview preparation website. I have solved it, but I wonder if any optimization can be done. Question: Is there a way to solve the following problem with a time complexity of O(n)? Problem Description: You have been given an array nums of typ... | For what it's worth, you can modify QuickSelect to get a with-high-probability and expected O(n)-time algorithm, though Python's sort is so fast that it hardly seems like a good idea. Deterministic O(n) is possible and left as an easy exercise to the reader familiar with selection algorithms (but the constant factor is... | 4 | 2 |
74,811,931 | 2022-12-15 | https://stackoverflow.com/questions/74811931/interpolate-time-series-data-from-one-df-to-time-axis-of-another-df-in-python-po | I have time series data on different time axes in different dataframes. I need to interpolate data from one df to onto the time axis of another df, df_ref. Ex: import polars as pl # DataFrame with the reference time axis: df_ref = pl.DataFrame({"dt": ["2022-12-14T14:00:01.000", "2022-12-14T14:00:02.000", "2022-12-14T14... | The scipy.interpolate.interpol1d example ends up calling this function. You could use the same approach and process each column with .map() def polars_ip(df_ref, df): old = df["dt"].dt.timestamp().to_numpy() new = df_ref["dt"].dt.timestamp().to_numpy() hi = np.searchsorted(old, new).clip(1, len(old) - 1) lo = hi - 1 de... | 5 | 4 |
74,840,187 | 2022-12-18 | https://stackoverflow.com/questions/74840187/how-to-remove-duplicated-buy-signal | I'm testing my stock trading logic and I made a position column to check the buying / selling signal df = pd.DataFrame({'position': [1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]}) I want to replace 1.0 value occurs between 1.0 and -1.0 with 0.0, and replac... | Here is a basic implementation based on the approach described by the previous answer: lastseen = 0 for n,el in enumerate(df["position"]): if lastseen == 0 and el == -1: raise Exception("Inconsistent data") if (el in [1, -1] and el != lastseen) or lastseen == 0: lastseen = el else: df["position"][n] = 0 I added the fi... | 4 | 1 |
74,838,633 | 2022-12-18 | https://stackoverflow.com/questions/74838633/can-i-delete-env-file-from-server | I have a Django application where all the secret information (secret key and keys for encryption) are in the .env file as environment variables - I'm using the python-dotenv library. After starting the application, I removed the .env file from the server files and the application continues to work as it should. Can del... | You shouldn't need .env file if you instead set up Environment variables while initialising the server machine. Many Cloud Service Providers let you do that. If you're setting up a docker container in Google App run, you should be able to setup environment variables or when setting up virtual machine with predetermined... | 4 | 1 |
74,827,320 | 2022-12-16 | https://stackoverflow.com/questions/74827320/atributeerror-cant-set-attribute-for-python-list-property | I'm working with the python-docx library from a forked version, and I'm having an issue with editing the elements list as it is defined as a property. # docx.document.Document @property def elements(self): return self._body.elements I tried to go with the solution mentioned here but the error AtributeError: can't set ... | The main "Attribute Error" issue, @Jasmijn already covered... the setter actually needs to set something. In regards to how to provide a setter for elements: First we need to figure out where elements comes from: Document.elements comes from [Document]._body.elements [Document]._body.elements comes from _Body, which i... | 4 | 2 |
74,836,347 | 2022-12-17 | https://stackoverflow.com/questions/74836347/sqlalchemy-session-with-autocommit-true-does-not-commit | I'm trying to use a session with autocommit=true to create a row in a table, and it does not seem to be working. The row is not saved to the table. import os import sqlalchemy from sqlalchemy import Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy imp... | If you enable the SQLALCHEMY_WARN_20=1 environment variable you will see RemovedIn20Warning: The Session.autocommit parameter is deprecated and will be removed in SQLAlchemy version 2.0. … The "2.0 way" to accomplish that "autocommit" behaviour is to do S2 = sessionmaker(engine) with S2() as session, session.begin():... | 5 | 9 |
74,823,596 | 2022-12-16 | https://stackoverflow.com/questions/74823596/type-a-function-that-takes-a-tuple-and-returns-a-tuple-of-the-same-length-with-e | I want to write a function that takes a tuple and returns a tuple of the same size but with each element wrapped in optional. Pseudo code: from typing import TypeVar T = TypeVar("T", bound=tuple[dict[str, str], ...]) def f(tup: T) -> Map[Optional, T]: # Dummy implementation return [None if ... else el for el in tup] H... | TLDR: Use @overload to define a practically sufficient number of items and a less strictly typed catch-all case. There is currently no way to unpack type variables from a tuple and transform each of them. However, for practical usage it is usually sufficient to explicitly type cases for a low number of items. This is ... | 3 | 2 |
74,823,526 | 2022-12-16 | https://stackoverflow.com/questions/74823526/pydantic-from-orm-to-load-django-model-with-related-list-field | I have the following Django models: from django.db import models class Foo(models.Model): id: int name = models.TextField(null=False) class Bar(models.Model): id: int foo = models.ForeignKey( Foo, on_delete=models.CASCADE, null=False, related_name="bars", ) And Pydantic models (with orm_mode set to True): from pydanti... | The bars attribute on your Foo model is a ReverseManyToOneDescriptor that just returns a RelatedManager for the Bar model. As with any manager in Django, to get a queryset of all the instances managed by it, you need to call the all method on it. Typically you would do something like foo.bars.all(). You can add your ow... | 4 | 1 |
74,825,382 | 2022-12-16 | https://stackoverflow.com/questions/74825382/should-i-type-something-as-optional-if-none-breaks-the-logic-of-the-function-bu | Sometimes at the beginning of my Python functions I check whether the correct variables types were used, or whether something was passed as None. For example: def fails_with_none(x: int): if x is None: raise TypeError('Function fails with None!') return x + 1 I am hesitating whether x should be typed as int or as Opti... | TL;DR: If x being None has meaning in your function, then annotate x accordingly. Otherwise don't and don't check it. Sometimes at the beginning of my python functions I check whether the correct variables types were used, or whether something was passed as None. I am not saying this is absolutely wrong, but there i... | 3 | 3 |
74,824,553 | 2022-12-16 | https://stackoverflow.com/questions/74824553/how-to-left-align-column-values-in-pandas-to-string | I want to save a pandas dataframe to a file with to_string(), but want to left align the column values. With to_string(justify=left), only column labels are left aligned. For example with pd.DataFrame({'col1': [' 123 ', ' 1234'], 'col2': ['1', '444441234']}).to_string(index=False) I get the following result: I want to... | The to_string methods provides support for per column formatters. It allows you to use specific formats for all of some columns. A rather simple way is to create a format and then apply it with a lambda. The only picky part is that to use left formatting, you will have to know the width of the column. For your provided... | 4 | 5 |
74,822,097 | 2022-12-16 | https://stackoverflow.com/questions/74822097/purpose-of-stop-gradient-in-jax-nn-softmax | jax.nn.softmax is defined as: def softmax(x: Array, axis: Optional[Union[int, Tuple[int, ...]]] = -1, where: Optional[Array] = None, initial: Optional[Array] = None) -> Array: x_max = jnp.max(x, axis, where=where, initial=initial, keepdims=True) unnormalized = jnp.exp(x - lax.stop_gradient(x_max)) return unnormalized /... | First off, the reason for subtracting x_max at all is because it prevents overflow for large inputs. For example: x = jnp.array([1, 2, 1000]) print(softmax_unstable(x)) # [ 0. 0. nan] print(softmax_stable(x)) # [0. 0. 1.] print(softmax_stop_gradient(x)) # [0. 0. 1.] As for why we use stop_gradient here, we can show an... | 3 | 3 |
74,818,864 | 2022-12-16 | https://stackoverflow.com/questions/74818864/does-mypy-require-init-to-have-none-annotation | Seeing kind of contradictory results: class A: def __init__(self, a: int): pass The snippet above passes a mypy test, but the one below doesn't. class A: def __init__(self): pass Any idea why? | This is documented here. When you have at least one (annotated) argument for a function, it is considered (at least partially) typed. When neither arguments nor return values are annotated, the function is considered untyped. This distinction is important because by default, mypy does not check the bodies of untyped fu... | 7 | 9 |
74,822,475 | 2022-12-16 | https://stackoverflow.com/questions/74822475/iterate-through-nested-dict-check-bool-values-to-get-indexes-of-array | I have a nested dict with boolean values, like: assignments_dict = {"first": {'0': True, '1': True}, "second": {'0': True, '1': False}, } and an array, with a number of elements equal to the number of True values in the assignments_dict: results_array = [10, 11, 12] and, finally, a dict for results structured this wa... | results_iter = iter(results_array) for key, value in assignments_dict.items(): for inner_key, inner_value in value.items(): if inner_value: results_dict[key][inner_key]['output'] = next(results_iter) print(results_dict) Output: {'first': {'0': {'output': 10}, '1': {'output': 11}}, 'second': {'0': {'output': 12}, '1': ... | 3 | 3 |
74,819,091 | 2022-12-16 | https://stackoverflow.com/questions/74819091/single-after-dependency-version-specifier-in-setup-py | I'm looking at a setup.py with this syntax: from setuptools import setup setup( ... tests_require=["h5py>=2.9=mpi*", "mpi4py"] ) I understand the idea of the ">=" where h5py should be at least version 2.9, but I cannot for the life of me understand the =mpi* afterwards. Is it saying the version should somehow match th... | Short answer The =mpi* qualifier says that you want to install h5py pre-compiled with MPI support. Details If you look at the documentation for h5py, you'll see references to having to build it with or without MPI explicitly (e.g., see https://docs.h5py.org/en/latest/build.html). When you look at the conda-forge downlo... | 6 | 2 |
74,804,358 | 2022-12-14 | https://stackoverflow.com/questions/74804358/combining-large-xml-files-efficiently-with-python | I have about 200 xml files ranging from 5MB to 50MB, with 80% being <10MB. These files contain multiple elements with both overlapping and unique data. My goal is to combine all this files, by performing a logical union over all the elements. The code seems to work but gets exponentially slower the more files it has to... | Caching all identifiers while proceeding seems to work well and doesn't significantly slow down as more data is added. The following code does this: def xml_union(files, loader): existing = {} path = [] def populatewalk(elem): pid = elem.get('id') ident = (elem.tag, pid) path.append(ident) if pid is not None: existing[... | 4 | 2 |
74,799,676 | 2022-12-14 | https://stackoverflow.com/questions/74799676/how-to-run-a-hello-world-python-script-with-google-cloud-run | Forgive my ignorance.. I'm trying to learn how to schedule python scripts with Google Cloud. After a bit of research, I've seen many people suggest Docker + Google Cloud Run + Cloud Scheduler. I've attempted to get a "hello world" example working, to no avail. Code hello.py print("hello world") Dockerfile # For more i... | UPDATE I've documented my problem and solution in much more detail here » I had been trying to deploy my script as a Cloud Run Service. I should've tried deploying it as a Cloud Run Job. The difference is that cloud run services require your script to listen for a port. jobs do not. Confusingly, you cannot deploy a c... | 4 | 6 |
74,811,255 | 2022-12-15 | https://stackoverflow.com/questions/74811255/pylint-ignore-rules-on-git-action | I've used the default pylint from git actions to check my project for any errors. There are some errors that I want to ignore though. If it was in vscode you could ignore them in settings.json. How do I ignore them in git actions? name: Pylint on: [push] jobs: build: runs-on: ubuntu-latest strategy: matrix: python-ver... | you could use noqa comments for ignore specific lines you can run probably pylint with option disable or something like that: pylint -d C0114,C0116 $(git ls-files '*.py') this would disable warnings with the codes C0114 and C0116 | 3 | 5 |
74,812,049 | 2022-12-15 | https://stackoverflow.com/questions/74812049/is-there-a-guarantee-that-code-after-yield-will-be-executed | Let's say we have a fixture that allocated some unmanaged resources and releases them like in the following example: @pytest.fixture def resource(): res = driver.Instance() yield res res.close() Is there a guarantee that the resource will be released even if something bad happens during the test that utilizes that fix... | It depends on what happens before yield: If a yield fixture raises an exception before yielding, pytest won’t try to run the teardown code after that yield fixture’s yield statement. But, for every fixture that has already run successfully for that test, pytest will still attempt to tear them down as it normally would... | 4 | 5 |
74,810,441 | 2022-12-15 | https://stackoverflow.com/questions/74810441/timezone-obtained-via-timezonefinder-america-ciudad-juarez-generates-error-u | I retrieve timezones from airports of the world, using TimezoneFinder().timezone_at applied on longitude and latitude of airports. And when I want to use these timezones (to compute times of departure ad arrival of flights) everything works except America/Ciudad_Juarez. This simple code: from timezonefinder import Time... | This timezone was only very recently added, as Ciudad Juárez decided to align it's time with the US for DST. See http://mm.icann.org/pipermail/tz-announce/2022-November/000076.html for the announcement. It looks like pytz has not been updated to include that change just yet. | 3 | 5 |
74,795,811 | 2022-12-14 | https://stackoverflow.com/questions/74795811/get-version-of-python-poetry-project-from-inside-the-project | I have a python library packaged using poetry. I have the following requirements Inside the poetry project # example_library.py def get_version() -> str: # return the project version dynamically. Only used within the library def get_some_dict() -> dict: # meant to be exported and used by others return { "version": get_... | Use importlib.metadata.version() from Python's own standard library: import importlib.metadata version = importlib.metadata.version('ProjectName') This is not specific to Poetry and will work for any project (library or application) whose metadata is readable. Make sure that ProjectName is installed. Where ProjectName... | 4 | 3 |
74,808,652 | 2022-12-15 | https://stackoverflow.com/questions/74808652/cant-get-the-changed-global-variable | t.py value = 0 def change_value(): global value value = 10 s.py import t from t import value t.change_value() print(f'test1: {t.value}') print (f'test2: {value}') Output test1: 10 test2: 0 Why isn't it not returning the changed value in the test2 ? | This is how import works in Python. You should read what the documentation says on the import statement carefully. Specifically, when you use the from import syntax on a module attribute, Python looks up the value of that attribute, and then "a reference to that value is stored in the local namespace". So, if value is ... | 4 | 5 |
74,802,561 | 2022-12-14 | https://stackoverflow.com/questions/74802561/how-to-create-regex-to-match-a-string-that-contains-only-hexadecimal-numbers-and | I am using a string that uses the following characters: 0-9 a-f A-F - > The mixture of the greater than and hyphen must be: -> --> Here is the regex that I have so far: [0-9a-fA-F\-\>]+ I tried these others using exclusion with ^ but they didn't work: [^g-zG-Z][0-9a-fA-F\-\>]+ ^g-zG-Z[0-9a-fA-F\-\>]+ [0-9a-fA-F\-\>]... | Firstly, you don't need to escape - and > Here's the regex that worked for me: ^([0-9a-fA-F]*(->)*(-->)*)*$ Here's an alternative regex: ^([0-9a-fA-F]*(-+>)*)*$ What does the regex do? ^ matches the beginning of the string and $ matches the ending. * matches 0 or more instances of the preceding token Created a big ()... | 4 | 2 |
74,803,526 | 2022-12-14 | https://stackoverflow.com/questions/74803526/why-dont-i-get-faster-run-times-with-threadpoolexecutor | In order to understand how threads work in Python, I wrote the following simple function: def sum_list(thelist:list, start:int, end:int): s = 0 for i in range(start,end): s += thelist[i]**3//10 return s Then I created a list and tested how much time it takes to compute its sum: LISTSIZE = 5000000 big_list = list(range... | The problem is that the function you are trying to make faster is CPU-bound and the Python Global Interpreter Lock (GIL) prevents any performance gain from parallelisation of such code. In Python, threads are wrapper around genuine OS thread. However, in order to avoid race conditions due to concurrent execution, only ... | 6 | 7 |
74,797,716 | 2022-12-14 | https://stackoverflow.com/questions/74797716/how-do-i-get-fastapi-to-do-ssr-for-vue-3 | According to this documentation for Vue's SSR, it is possible to use node.js to render an app and return it using an express server. Is is possible to do the same with FastAPI? Or is using Jinja2 templates or SPA the only solution? Problems: No SPA: To help with SEO No SSG: Too many pages will be generated. Some need ... | There are several options available, such as Nuxt.js, Quasar, and Gridsome, which provide support for SSR with FastAPI and Vue 3. | 4 | 1 |
74,795,315 | 2022-12-14 | https://stackoverflow.com/questions/74795315/processing-large-number-of-jsons-12tb-with-databricks | I am looking for guidance/best practice to approach a task. I want to use Azure-Databricks and PySpark. Task: Load and prepare data so that it can be efficiently/quickly analyzed in the future. The analysis will involve summary statistics, exploratory data analysis and maybe simple ML (regression). Analysis part is not... | Yes, it's sound reasonable, and in fact it's quite standard architecture (often referred as lakehouse). Usual implementation approach is following: JSON data loaded into blob storage are consumed using Databricks Auto Loader that provides efficient way of ingesting only new data (since previous run). You can trigger p... | 4 | 2 |
74,747,889 | 2022-12-9 | https://stackoverflow.com/questions/74747889/polars-map-elements-performance-for-custom-functions | I've enjoyed with Polars significant speed-ups over Pandas, except one case. I'm newbie to Polars, so it could be just my wrong usage. Anyway here is the toy-example: on single column I need to apply custom function in my case it is parse from probablepeople library (https://github.com/datamade/probablepeople) but prob... | It seems that pandarallel uses multiprocessing (Pool.map_async) to run tasks. It also has its own custom progress bar implementation. A "simple" way I've found to do this is: Pool.imap() (map_async cannot be used with track() as it consumes the iterable) rich.progress.track() (which is also bundled with pip) for a pro... | 4 | 8 |
74,720,194 | 2022-12-7 | https://stackoverflow.com/questions/74720194/polars-counting-elements-in-list-column | I've have dataframe with column b with list elements, I need to create column c that counts number elements in list for every row. Here is toy example in Pandas: import pandas as pd df = pd.DataFrame({'a': [1,2,3], 'b':[[1,2,3], [2], [5,0]]}) a b 0 1 [1, 2, 3] 1 2 [2] 2 3 [5, 0] df.assign(c=df['b'].str.len()) a b c 0 1... | You can use .list.len() df.with_columns(c = pl.col("b").list.len()) shape: (3, 3) ┌─────┬───────────┬─────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ list[i64] ┆ u32 │ ╞═════╪═══════════╪═════╡ │ 1 ┆ [1, 2, 3] ┆ 3 │ │ 2 ┆ [2] ┆ 1 │ │ 3 ┆ [5, 0] ┆ 2 │ └─────┴───────────┴─────┘ | 8 | 12 |
74,714,300 | 2022-12-7 | https://stackoverflow.com/questions/74714300/paramspec-for-a-pre-defined-function-without-using-generic-callablep | I want to write a wrapper function for a known function, like def wrapper(*args, **kwargs) foo() return known_function(*args, **kwargs) How can i add type-annotations to wrapper, such that it exactly follows the type annotations of known_function I have looked at ParamSpec, but it appears to only work when the wrapp... | PEP 612 as well as the documentation of ParamSpec.args and ParamSpec.kwargs are pretty clear on this: These “properties” can only be used as the annotated types for *args and **kwargs, accessed from a ParamSpec already in scope. - Source: PEP 612 ("The components of a ParamSpec" -> "Valid use locations") Both attr... | 9 | 3 |
74,716,259 | 2022-12-7 | https://stackoverflow.com/questions/74716259/the-seaborn-styles-shipped-by-matplotlib-are-deprecated-since-3-6 | The seaborn styles shipped by Matplotlib are deprecated since 3.6, as they no longer correspond to the styles shipped by seaborn. However, they will remain available as 'seaborn-v0_8-<style>'. Alternatively, directly use the seaborn API instead. I have tried this: # use seaborn style plt.style.use("seaborn") but it ... | This warning is telling you that seaborn styles in matplotlib do not match current seaborn styles, since the latest have been updated. This is why you should set the style as follow: plt.style.use("seaborn-v0_8") You can specify a theme by replacing <style> with one the following: bright colorblind dark dark-palette ... | 14 | 30 |
74,751,254 | 2022-12-10 | https://stackoverflow.com/questions/74751254/removing-all-duplicate-images-with-different-filenames-from-a-directory | I am trying to iterate through a folder and delete any file that is a duplicate image (but different name). After running this script all files get deleted except for one. There are at least a dozen unique ones out of about 5,000. Any help understanding why this is happening would be appreciated. import os import cv2 d... | There are a number of issues with your code, but I am going to suggest an alternate strategy. A more efficient way would be to collect md5 or sha1 hashes of the files, into a set or some other container, while iterating the directory. Then when you calculate the hashes you can check if that particular hash already exis... | 7 | 9 |
74,788,529 | 2022-12-13 | https://stackoverflow.com/questions/74788529/notimplementederror-you-should-not-call-an-overloaded-function | @overload def setSize(self,size:tuple[int|str])->None: ''' Set image size (width,height) ''' try:self.options.append(f"width=\"{str(size[0])}\" height=\"{str(size[1])}\"") except IndexError:print("Error reading the size, aborting") @overload def setSize(self,width:int|str,height:int|str)->None: ''' Set image Size ''' s... | When writing code with function overloading in Python, it is important to remember that [y]ou should not call an overloaded function. A series of @overload-decorated functions outside a stub module should always be followed by an implementation that is not @overload-ed. This is because @overload-ed functions are inte... | 3 | 4 |
74,724,128 | 2022-12-8 | https://stackoverflow.com/questions/74724128/is-there-a-way-to-get-p-d-q-p-d-q-params-from-statsforecast-autoarima | minimal example: from statsforecast import StatsForecast from statsforecast.models import AutoARIMA import pandas as pd df = pd.read_csv('https://datasets-nixtla.s3.amazonaws.com/air-passengers.csv') sf = StatsForecast( models = [AutoARIMA(season_length = 12)], freq = 'M', n_jobs=-1, verbose=True ) sf.fit(df) How to ... | From this answer, the solution would be: sf.fitted_[0][0].model_['arma'] which will output a tuple of 7 values. I don't know the exact mapping of parameters to tuple values, but from this line it appears to be: (p, d, q, P, D, Q, constant) | 4 | 5 |
74,740,640 | 2022-12-9 | https://stackoverflow.com/questions/74740640/install-postgresql-extension-before-pytest-set-up-database-for-django | I need to install citext extension to my postgresql database for django project. For the project itself it went smoothly and works great via migrations, but my pytest is configured with option --no-migrations, so pytest create database without running migrations. How can i make pytest to install citext postgres extensi... | Annoyingly, there are no appropriate hooks between setting up the database and loading the appropriate postgresql extensions. You can work around the issue by copying/modifying the pytest-django code that disables migrations and running your code instead of the upstream code. @pytest.fixture(scope="session") def django... | 3 | 4 |
74,711,405 | 2022-12-7 | https://stackoverflow.com/questions/74711405/importerror-cannot-import-name-getargspec-from-inspect-c-users-swapn-appd | File "f:\drug-traceability-blockchain-maddy\src\app.py", line 2, in <module> from web3 import Web3,HTTPProvider File "C:\Users\Swapn\AppData\Local\Programs\Python\Python311\Lib\site-packages\web3\__init__.py", line 6, in <module> from eth_account import ( File "C:\Users\Swapn\AppData\Local\Programs\Python\Python311\Li... | Try uninstalling web3 using pip uninstall web3.py and install the latest version from github using pip install git+https://github.com/ethereum/web3.py.git | 6 | 5 |
74,785,215 | 2022-12-13 | https://stackoverflow.com/questions/74785215/how-to-yield-a-db-connection-in-a-python-sqlalchemy-function-similar-to-how-it-i | In FastAPI I had the following function that I used to open and close a DB session: def get_db(): try: db = SessionLocal() yield db finally: db.close() And within the routes of my API I would do something like that: @router.get("/") async def read_all_events(user: dict = Depends(get_current_user), db: Session = Depend... | The usage of yield in this case is so that Depends(get_db) returns the db session instance, so that it can be used in the fastapi route, and as soon as the fastapi route returns response to user, the finally clause (db.close()) will be executed. This is good because every request will be using a separate db session, an... | 3 | 3 |
74,783,807 | 2022-12-13 | https://stackoverflow.com/questions/74783807/making-tqdm-write-to-log-files | tqdm is a nice python library to keep track of progress through an iterable. It's default mode of operation is to repeatedly clear a line and redraw with a carriage but this produced quite nasty output when combined with logging. Is there a way I can get this to write to log files periodically rather than using this pr... | You could redirect the outputs of the TQDM progress bar to a null device (e.g. /dev/null), and manually print/log the status bar whenever you want - either on every iteration, or at a certain interval. For example: import os import time import logging from tqdm import tqdm LOG_INTERVAL = 5 logging.basicConfig(level=log... | 4 | 9 |
74,748,826 | 2022-12-9 | https://stackoverflow.com/questions/74748826/how-to-visualize-cluster-boundaries | I generated several datasets, and using classifiers, I predicted the distribution of clusters. I need to draw boundaries between clusters on the chart. In the form of lines or in the form of filled areas - it does not matter. Please let me know if there is any way to do this. My code: import numpy as np import matplotl... | scikit-learn 1.1 introduced the DecisionBoundaryDisplay to assist with this sort of task. Following the use of make_moons and the KNeighborsClassifier in the question, we can fit the classifier on the dataset, invoke the DecisionBoundaryDisplay.from_estimator() method, then scatter the X data on the returned axis: impo... | 4 | 4 |
74,718,716 | 2022-12-7 | https://stackoverflow.com/questions/74718716/how-to-get-my-vim-and-macvim-to-find-python3 | When I use a plugin that requires python, it can't find it and barfs. The places that seem to being searched are: Using -version I see both: +python/dyn +python3/dyn However :echo has("python3") returns 0. I'm not sure if this is compile time config, or runtime-configurable via .vimrc. I'm not a python developer, and... | After some time, I found the following works, thought it was not a fun path of discovery. let &pythonthreedll = trim(system("pyenv which python")) | 4 | 2 |
74,744,899 | 2022-12-9 | https://stackoverflow.com/questions/74744899/how-does-tensorflows-decision-forests-handle-categorical-data | I'm evaluating two different unsupervised ML algorithms, Isolation Forest and LSTM Autoencoder model, to identify anomalies in a large time series data. This dataset includes mostly categorical data such as Ip Adresses, cloud subscription Ids,tenant Ids, userAgents, and client Application Ids. When reading a tutorial o... | Tl;dr: There is a natural way of using categorical features in decision trees/forests that requires no encoding. Tensorflow Decision Forests uses this and a number of standard transformations to handle categorical features. Tensorflow Decision Forest (TF-DF) constructs decision tree / decision forest models. A single d... | 3 | 3 |
74,736,220 | 2022-12-8 | https://stackoverflow.com/questions/74736220/importing-smote-raise-attributeerror-module-sklearn-metrics-dist-metrics-has | Running from imblearn.over_sampling import SMOTE will raise following error. --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) d:\A\OneDrive - UBC\ENGR\518 Machine Learning\Project\codes\model_training_laptop - Copy.ipynb Cell 2 in <cell line: 1... | This is probably a case where upgrading scikit-learn and imbalanced-learn will resolve the problem. pip install --upgrade scikit-learn pip install --upgrade imbalanced-learn Not all versions of scikit-learn and imbalanced-learn are compatible with one another. Version 0.10.0 should be compatible with scikit-learn>=1.0... | 3 | 3 |
74,783,071 | 2022-12-13 | https://stackoverflow.com/questions/74783071/reading-binary-file-to-find-a-sequences-of-ints-little-endian-permutations | Try to read a binary file (firmware) with a sequences like \x01\x00\x00\x00\x03\x00\x00\x00\x02\x00\x00\x00\x04\x00\x00\x00 Little endian integer 1,3,2,4 Attempt: with open("firm.bin", 'rb') as f: s = f.read() N = 16 allowed = set(range(4)) for val in allowed: val = bytes(val)+b'\x00\x00\x00' for index, b in enumerate... | You refer to the values in the firmware as 32-bit integers so I've assumed that the file can be converted to integers. I've used the Python struct lib to do this. I've also understood that you want to find a sequence of 16 unique integers in the range 0 to 15. My test below iterated over the integers in the firmware fi... | 4 | 2 |
74,786,867 | 2022-12-13 | https://stackoverflow.com/questions/74786867/subtract-vignetting-template-from-image-in-opencv-python | I have 750+ images, like this 'test.png', that I need to subtract the vignetting in 'vig-raw.png' from. I just started using opencv-python, so "I don't even know what I don't know". Using GIMP, I desaturated 'vig-raw.png' to create 'vig-desat.png', which I then converted with Color to Alpha to create 'vig-alpha.png'. T... | Vignette template is not supposed to be subtracted, it supposed to be scaled. The vignette correction process is known as Flat-field correction applies: G = m / (F - D) C = (R - D) * G When D is dark field or dark frame. We don't have dark frame sample - we may assume that the dark frame is all zeros. Assuming D=zeros,... | 3 | 4 |
74,771,032 | 2022-12-12 | https://stackoverflow.com/questions/74771032/how-to-test-an-element-from-a-generator-without-consuming-it | I have a generator gen, with the following properties: it's quite expensive to make it yield (more expensive than creating the generator) the elements take up a fair amount of memory sometimes all of the __next__ calls will throw an exception, but creating the generator doesn't tell you when that will happen I didn't... | I think I have what you are looking for using more_itertools library: import more_itertools if __name__ == "__main__": generator = range(100) peekable_generator = more_itertools.peekable(generator) print(f"peek {peekable_generator.peek()}") print(f"next {next(peekable_generator)}") print(f"next {next(peekable_generator... | 6 | 4 |
74,782,602 | 2022-12-13 | https://stackoverflow.com/questions/74782602/how-to-add-a-constant-to-negative-values-in-array | Given the xarray below, I would like to add 10 to all negative values (i.e, -5 becomes 5, -4 becomes 6 ... -1 becomes 9, all values remain unchanged). a = xr.DataArray(np.arange(25).reshape(5, 5)-5, dims=("x", "y")) I tried: a[a<0]=10+a[a<0], but it returns 2-dimensional boolean indexing is not supported. Several att... | xarray’s where method is the way to go here - you can provide any other argument which can be broadcast against the condition argument and the original array: a['variable'] = a['variable'].where( a['variable'] >= 0, (a['variable'] + 10), ) This will work fine with dask and will handle your coordinates seamlessly. Note... | 3 | 3 |
74,788,063 | 2022-12-13 | https://stackoverflow.com/questions/74788063/python-enum-equality-performance | Enum datatypes are good abstractions for enumerable datatype like days of week, months etc. Nevertheless the simplest tests show that we pay 2.5 slower performance for such datatypes. Do we have any explanation for such behavior? Consider two simple enums in Python import enum import timeit class IntDow(enum.Enum): MON... | The bulk of the extra time is not spent in the equality test, but in looking up the member from the enum (i.e. IntDow.MONDAY). In those cases where performance is critical, export the members from the enum first: MONDAY, TUESDAY, ... = IntDow Disclosure: I am the author of the Python stdlib Enum, the enum34 backport,... | 4 | 3 |
74,772,785 | 2022-12-12 | https://stackoverflow.com/questions/74772785/what-are-the-differences-among-mambaforge-mambaforge-pypy3-miniforge-miniforg | there have been explanations about the different between miniforge and miniconda miniforge is the community (conda-forge) driven minimalistic conda installer. Subsequent package installations come thus from conda-forge channel. miniconda is the Anaconda (company) driven minimalistic conda installer. Subsequent package... | mamba* use the c/c++ implementation of the conda protocol "mamba" instead of the python implementation which is called conda. The *pypy3 variants ship with PyPy as the python implementation in the base environment instead of CPython. | 7 | 5 |
74,785,680 | 2022-12-13 | https://stackoverflow.com/questions/74785680/how-to-format-a-dataframe-having-many-nan-values-join-all-rows-to-those-not-sta | I have the follwing df: df = pd.DataFrame({ 'col1': [1, np.nan, np.nan, np.nan, 1, np.nan, np.nan, np.nan], 'col2': [np.nan, 2, np.nan, np.nan, np.nan, 2, np.nan, np.nan], 'col3': [np.nan, np.nan, 3, np.nan, np.nan, np.nan, 3, np.nan], 'col4': [np.nan, np.nan, np.nan, 4, np.nan, np.nan, np.nan, 4] }) It has the follow... | If need join first values per groups defined by non missing values in df['col1'] use: df = (df.reset_index() .groupby(df['col1'].notna().cumsum()) .first() .set_index('index')) | 3 | 3 |
74,779,645 | 2022-12-13 | https://stackoverflow.com/questions/74779645/is-there-any-way-to-get-list-the-unconnected-inputs-of-an-openmdao-group | Considering the following problem import openmdao.api as om class Sys(om.Group): def setup(self): self.add_subsystem('sys1', om.ExecComp('v1 = a + b'), promotes=['*']) self.add_subsystem('sys2', om.ExecComp('v2 = v1 + c'), promotes=['*']) if __name__ == '__main__': prob = om.Problem() model = prob.model comp = model.ad... | Generally, I prefer to rely on the visual tools such as the N2. However, here is a scriptable solution that I use on occation. Fair warning, it requires the use of one non-public attribute of system... but this is how I do it: import openmdao.api as om class Sys(om.Group): def setup(self): self.add_subsystem('sub_sys1'... | 3 | 2 |
74,782,862 | 2022-12-13 | https://stackoverflow.com/questions/74782862/fancy-indexing-in-numpy | I am basically trying to do something like this but without the for-loop... I tried with np.put_along_axis but it requires times to be of dimension 10 (same as last index of src). import numpy as np src = np.zeros((5,5,10), dtype=np.float64) ix = np.array([4, 0, 0]) iy = np.array([1, 3, 4]) times = np.array([1 ,2, 4])... | One approach is to use np.add.at, preparing the indices first (as below): r = len(values) indices = (np.tile(ix, r), np.tile(iy, r), np.repeat(times, r)) np.add.at(src, indices, np.repeat(values, r)) print(src) Output [[[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] ... | 3 | 4 |
74,764,302 | 2022-12-11 | https://stackoverflow.com/questions/74764302/what-event-is-associated-with-zooming-an-interactive-matplotlib-plot | As I understand it, when a user interacts with an interactive matplotlib plot (i.e. by clicking, pressing a key, etc.), an Event is triggered, which can be linked to an arbitrary callback function, if desired. Interactive matplotlib plots often come with a navigation toolbar that includes certain features like zooming ... | Resolved on my own. In addition to the event types and the fig.canvas.mpl_connect() syntax shown on the "event handling" documentation page, you can also associate a callback function with an Axes instance directly, and this way has some different kinds of events that can be used as triggers. The API reference for the ... | 4 | 3 |
74,775,348 | 2022-12-12 | https://stackoverflow.com/questions/74775348/asyncio-as-completed-supposedly-accepting-iterable-but-crashes-if-input-is | So, essentially, in Python 3.7 (as far as I know) if you try to do this, import asyncio async def sleep(): asyncio.sleep(1) async def main(): tasks = (sleep() for _ in range(5)) for task in asyncio.as_completed(tasks): result = await task if __name__ == "__main__": asyncio.run(main()) It crashes with TypeError: expect... | You are right. The documentation here is not consistent with the actual behavior. The official documentation refers to the first argument as an "iterable". And typeshed as of today also annotates the first argument with Iterable[...]. However, in the CPython code for as_completed the first argument is passed to corouti... | 3 | 3 |
74,774,598 | 2022-12-12 | https://stackoverflow.com/questions/74774598/pandas-group-by-column-and-convert-to-keyvalue-pair | I want to convert DataFrame using pandas. I would like to convert it into dictionary format like {'Plant Delivering ID': [Ship-To ID]} there are multiple 'Ship-To ID' for single 'Plant Delivering ID' My Original Data Format: I would like to convert it to: How do I convert it? | Use pandas.DataFrame.groupby and then get the result of groupby with apply(list) at the end convert the result to dict with pandas.Series.to_dict. df.groupby('Plant Delivering ID')['Ship-To-ID'].apply(list).to_dict() | 3 | 2 |
74,762,158 | 2022-12-11 | https://stackoverflow.com/questions/74762158/how-can-staticmethods-be-called-as-regular-functions | A static method can be called either on the class (such as C.f()) or on an instance (such as C().f()). Moreover, they can be called as regular functions (such as f()). Could someone elaborate on the bold part of the extract from the documentation for Python static methods? Reading this description one would expect to... | The subsection 4.2.2. Resolution of names of the CPython documentation specifies the rules of visibility for variables defined in different type of nested code blocks. In particular it specifies the working of the visibility of the local class scope's variables inside its methods: The scope of names defined in a class... | 4 | 1 |
74,752,610 | 2022-12-10 | https://stackoverflow.com/questions/74752610/how-to-use-argparse-to-create-command-groups-like-git | I'm trying to figure out how to use properly builtin argparse module to get a similar output than tools such as git where I can display a nice help with all "root commands" nicely grouped, ie: $ git --help usage: git [--version] [--help] [-C <path>] [-c <name>=<value>] [--exec-path[=<path>]] [--html-path] [--man-path] ... | This isn't supported natively by argparse -- you can't nest subparsers, so if you want this sort of cli using argparse you're going to need to build a lot of logic on top of argparse. You can set nargs=argparse.REMAINDER to collect a subcommand and arguments without having them parsed by argparse, which means we can bu... | 6 | 8 |
74,741,268 | 2022-12-9 | https://stackoverflow.com/questions/74741268/installing-python-extension-module-understanding-skbuildsetuptools | I am one of the devs of a (fairly large) C++ simulation tool. Disclaimer : I'm more of a physicist than a dev. I wrote Python bindings for that project using pybind11. I managed to get the Python module to compile with cmake. I then managed to write a setup.py file using skbuild that does compile the Python module : py... | The command pip3 install dist tries (and fails) to install the dist package from the pypi repository. Maybe try pip3 install dist/cytosim-0.0.0.tar.gz instead. | 5 | 4 |
74,765,215 | 2022-12-11 | https://stackoverflow.com/questions/74765215/make-pip-install-option-install-less-packages-than-the-default-pip-install | First of all let's assume the following: I am building a python package mypackage and want to make it available broadly My package has the following python dependencies: "A","B","C" and "D" and we assume further that each dependency covers an independent use-case of the package (i.e. A is needed for users wanting to d... | has the situation changed…? No. or is it planned? Nobody knows. Most probably no. what would be a way to circumvent this issue…? Do not install dependencies with plain pip install mypackage. Declare separate extras A, B, C and D. Declare a combined extra all that includes all dependencies: extras_require={ 'A... | 3 | 3 |
74,767,068 | 2022-12-12 | https://stackoverflow.com/questions/74767068/python-double-underscore-prefixed-parameter-in-function | belows is in builtins.pyi def max(__arg1: _T, __arg2: _T, *_args: _T, key: Callable[[_T], SupportsLessThan]) -> _T: I do know what the name mangling means and know that the name mangling will influence every "__xxx" identifier as long as in class definition field. So I have three questions: why there paramters "__ar... | Name mangling applies only to names used in a class definition, not function parameters. In this case the leading underscores are only a naming convention to indicate that parameters with such names are not to be passed with keyword arguments, but rather only positional ones. This is to say that you should call max wit... | 4 | 5 |
74,763,554 | 2022-12-11 | https://stackoverflow.com/questions/74763554/how-to-use-subprocess-run-method-in-python | I wanted to run external programs using python but I receive an error saying I don't have the file the code I wrote: import subprocess subprocess.run(["ls", "-l"]) Output: Traceback (most recent call last): File "C:\Users\hahan\desktop\Pythonp\main.py", line 3, in <module> subprocess.run(["ls", "-l"]) File "C:\Users\h... | The stack trace suggests you're using Windows as the operating system. ls not something that you will typically find on a Windows machine unless using something like CygWin. Instead, try one of these options: # use python's standard library function instead of invoking a subprocess import os os.listdir() # invoke cmd ... | 8 | 5 |
74,740,448 | 2022-12-9 | https://stackoverflow.com/questions/74740448/how-to-wait-for-the-user-to-click-a-point-in-a-figure-in-ipython-notebook | I took the following steps to setup an IPython backend in Google Colab notebook: !pip install ipympl from google.colab import output output.enable_custom_widget_manager() Then I log the (x,y) location of the user's click on a figure: %matplotlib ipympl import matplotlib import matplotlib.pyplot as plt fig, ax = plt.su... | You could, instead of putting the code you want to run after a button_press_event, after the event listener, you could instead put it in the onclick function. Something like this: %matplotlib ipympl import matplotlib import matplotlib.pyplot as plt fig, ax = plt.subplots() def onclick(event): ix, iy = event.xdata, even... | 3 | 2 |
74,757,129 | 2022-12-10 | https://stackoverflow.com/questions/74757129/why-numpy-vectorization-is-slower-than-a-for-loop | The below code has two functions that does the same thing: checks to see if the line between two points intersects with a circle. from line_profiler import LineProfiler from math import sqrt import numpy as np class Point: x: float y: float def __init__(self, x: float, y: float): self.x = x self.y = y def __repr__(sel... | Is there a numpy function which doesn't iterate over the whole array but stops when the results are false? No. This is a long standing feature requested by Numpy users but it will certainly never be added to Numpy. For simple cases, like returning the first index of a boolean array, Numpy could implement that, but th... | 3 | 3 |
74,755,994 | 2022-12-10 | https://stackoverflow.com/questions/74755994/closest-true-value-to-zero-in-python | A long time ago I read about the closest true value to zero, like zero = 0.000000001, something like that. In the article they mentioned about this value in Python and how to achieve it. Does anyone knows about this? I have look up here in SO but all the answers are about the closest value to zero of an array and that'... | The minimum positive denormalized value in Python3.9 and up is given by math.ulp(0.0) which returns 5e-324, or 4.940656e-324 when printed with format(math.ulp(0.0), '.7'). | 4 | 2 |
74,747,965 | 2022-12-9 | https://stackoverflow.com/questions/74747965/loki-throws-unmarshalerdecoder-error-for-json-payload | I get this error loghttp.PushRequest.Streams: []*loghttp.Stream: unmarshalerDecoder: Value looks like Number/Boolean/None, but can't find its end: ',' or '}' symbol, error found in #10 byte of ...| ] } ] }|..., bigger context ...| } } ] } ] }|... when uploading the json { "streams":[ { "stream":{ "application":"fabric... | I missed the right format, as in the example in Loki documentation https://grafana.com/docs/loki/latest/api/#push-log-entries-to-loki { "streams": [ { "stream": { "label": "value" }, "values": [ [ "<unix epoch in nanoseconds>", "<log line>" ], [ "<unix epoch in nanoseconds>", "<log line>" ] ] } ] } changed the method ... | 5 | 3 |
74,748,563 | 2022-12-9 | https://stackoverflow.com/questions/74748563/how-do-i-download-pdf-files-using-pythons-reqests-httpx-module | I'm making a program that downloads PDFs from the internet. Here's a example of the code: import httpx # <-- This also happens with the requests module URL = "http://62.182.86.140/main/0/aee7239ffcf7871e1d6687ced1215e22/Markus%20Nix%20-%20Exploring%20Python-Entwickler%20%282005%29.djvu" r = httpx.get(URL, timeout=20.0)... | import httpx def main(url): r = httpx.get(url, timeout=20) with open('file.djvu', 'wb') as f: f.write(r.content) main('http://62.182.86.140/main/0/aee7239ffcf7871e1d6687ced1215e22/Markus%20Nix%20-%20Exploring%20Python-Entwickler%20%282005%29.djvu') | 5 | 7 |
74,742,335 | 2022-12-9 | https://stackoverflow.com/questions/74742335/how-to-get-multiprocessing-queues-queue-qsize-on-macos | This is an old issue which suggested workaround does not work. Below is a complete example showing how the suggested approach fails. Uncomment L31 for error. import multiprocessing import os import time from multiprocessing import get_context from multiprocessing.queues import Queue class SharedCounter(object): def __i... | well, you didn't to override __setstate__ and __getstate__ to include your variable, which are used by pickle to control the serialization Handling Stateful Objects ... so you should override them to add your variable to what's being serialized. import multiprocessing import os import time from multiprocessing import g... | 5 | 3 |
74,738,922 | 2022-12-9 | https://stackoverflow.com/questions/74738922/finding-permutation-matrix-with-numpy | I am looking for the correct permutation matrix that would take matrix a and turn it into matrix b given a = np.array([[1,4,7,-2],[3,0,-2,-1],[-4,2,1,0],[-8,-3,-1,2]]) b = np.array([[-4,2,1,0],[3,0,-2,-1],[-8,-3,-1,2],[1,4,7,-2]]) I tried x = np.linalg.solve(a,b) However, I know this is incorrect and it should be np.... | Generally, if you have some PA = B and you want P then you need to solve the equation for P. Matrix multiplication is not commutative, so you have to right multiply both sides by the inverse of A. With numpy, the function to get the inverse of a matrix is np.linalg.inv(). Using the matrix multiplication operator @, you... | 4 | 4 |
74,734,461 | 2022-12-8 | https://stackoverflow.com/questions/74734461/defer-method-returning-unknown-interaction-error | Issue My slash commands return 404 Not Found (error code: 10062): Unknown interaction when I run them. I do have them deferred as: @bot.tree.command(name="evaluate") async def evaluate(interaction: discord.Interaction): await interaction.response.defer(ephemeral=True) await asyncio.sleep(10) await interaction.followup.... | Posted this on the discord.py official Discord Server and got an answer. If a 404 Not Found error appears even after deferring, it means that it took too long for the defer() to execute. Or in other words, your await interaction.response.defer() is running after 3 seconds have passed and the API request has already bee... | 3 | 3 |
74,743,525 | 2022-12-9 | https://stackoverflow.com/questions/74743525/how-to-check-input-arguments-in-a-python-script-with-cli | I'm writing a small script to learn Python. The script prints a chess tournament table for N players. It has a simple CLI with a single argument N. Now I'm trying the following approach: import argparse def parse_args(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Tournament tables... | You could have main do all the checking aind raise ArgumentError if something is amiss. Then catch that exception and forward it to the parser for display. Something along these lines: import argparse def run_with_args(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Tournament table... | 4 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.