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 |
|---|---|---|---|---|---|---|
78,402,155 | 2024-4-29 | https://stackoverflow.com/questions/78402155/inconsistencies-in-time-arithmetic-with-timezone-aware-datetime-objects-in-pytho | Surprisingly, time arithmetic is not handled as expected with pythons timezone aware objects. For example consider this snippet that creates a timezone aware object at 2022-10-30 02:00. from datetime import datetime, timezone, timedelta from zoneinfo import ZoneInfo zone = ZoneInfo("Europe/Madrid") HOUR = timedelta(hou... | In addition to my comment, here's an example using fold to maybe help clarify things (note the slightly modified time): from datetime import datetime, timezone, timedelta from zoneinfo import ZoneInfo zone = ZoneInfo("Europe/Madrid") HOUR = timedelta(hours=1) u0 = datetime(2022, 10, 30, 1, 59, 59, tzinfo=zone) print(u0... | 5 | 1 |
78,404,120 | 2024-4-29 | https://stackoverflow.com/questions/78404120/having-trouble-with-negative-lookahead-regex-in-python | So, I have to match everything before the last open-close parenthesis and get that in group. And after the last open-close parenthesis try to get the value with some pattern, again in group. This is my sample example: ID pqr () name:123. And this is my regex: ^(?P<JUNK>.*?)(?!\(.\))(\(.*\))?\sname\:(?P<name>\d+)\.$ A... | Try: ^(?P<JUNK>.*?)(\([^)]*\)\s)?name:(?P<name>\d+)\.$ See: regex101 Explanation ^: Start of string... (?P<JUNK>.*?): followed by JUNK... (\([^)]*\)\s)?: then, if applicable the last pair of brackets... name:: before literal "name:"... (?P<name>\d+): and collecting the number before... \.$: final "." at the end of t... | 2 | 3 |
78,396,578 | 2024-4-27 | https://stackoverflow.com/questions/78396578/how-to-make-my-tkinter-app-fit-the-whole-window-no-matter-the-size | I made a Tkinter app using Python. I want it to auto-resize and fill the whole window no matter how I resize it. The problem is that when I expand the window size (using my cursor), grey space appears on the borders to fill the gaps (see the image below). Grey space filling Here is the code minus the unnecessary detail... | You could use expand = True, fill = BOTH as an attribute for the required widgets to expand them to full size. | 2 | 1 |
78,406,021 | 2024-4-30 | https://stackoverflow.com/questions/78406021/pandas-series-get-value-by-index-with-fill-value-if-the-index-does-not-exist | ts = pd.Series({'a' : 1, 'b' : 2}) ids = ['a','c'] # 'c' is not in the index # the result I want np.array([ts.get(k, np.nan) for k in ids]) Is there a pandas native way to achieve this? | reindex and access the underlying numpy array: out = ts.reindex(ids).values # or # out = ts.reindex(ids).to_numpy() Output: array([ 1., nan]) Note that the fill_value in reindex is NaN by default, you can change it if desired: ts.reindex(ids, fill_value=0).values # array([1, 0]) | 2 | 2 |
78,405,251 | 2024-4-29 | https://stackoverflow.com/questions/78405251/create-dummy-for-missing-values-for-variable-in-python | I have the following dataframe in: a 1 3 2 2 3 Nan 4 3 5 Nan I need to recode this column so it looks like this: df_miss_a 1 0 2 0 3 1 4 0 5 1 I've tried: df_miss_a = np.where(df['a'] == 'Nan', 1, 0) and df_miss_a = np.where(df['a'] == Nan, 1, 0) The above outputs only 0s. The format of the output is unimportant. | If you have NaNs in your column you can use pd.Series.isna(): df_miss_a = df["a"].isna().astype(int) print(df_miss_a) Prints: 1 0 2 0 3 1 4 0 5 1 Name: a, dtype: int64 | 2 | 4 |
78,404,121 | 2024-4-29 | https://stackoverflow.com/questions/78404121/how-to-get-the-epoch-value-for-any-given-local-time-with-time-zone-daylight-sa | I'm new to Python and I have a use case which deals with datetime. Unfortunately, the data is not in UTC, so I have to rely on Local Time, Time Zones & Daylight Savings. I tried with datetime & pytz to get the epoch value from datetime, but its not working out. Approach 1 : If I try creating datetime object, localize i... | Use the built-in zoneinfo (available since Python 3.9) and .timestamp() instead of the non-standard .strftime('%s') (not supported on Windows). This produces correct results: # `zoneinfo` requires "pip install -U tzdata" for the latest time zone info # on some OSes, e.g. Windows. import datetime as dt import zoneinfo a... | 2 | 2 |
78,403,517 | 2024-4-29 | https://stackoverflow.com/questions/78403517/iterators-in-jit-jax-functions | I'm new to JAX and reading the docs i found that jitted functions should not contain iterators (section on pure functions) and they bring this example: import jax.numpy as jnp import jax.lax as lax from jax import jit # lax.fori_loop array = jnp.arange(10) print(lax.fori_loop(0, 10, lambda i,x: x+array[i], 0)) # expect... | Your code works because of the way that JAX's tracing model works. When JAX's tracing encounters Python control flow, like for loops, the loop is fully evaluated at trace-time (There's some exploration of this in JAX Sharp Bits: Control Flow). Because of this, your use of an iterator in this context is fine, because ev... | 4 | 2 |
78,398,120 | 2024-4-28 | https://stackoverflow.com/questions/78398120/show-image-in-python-and-matlab-showing-different-colors | I'm working on matlab, but I noticed that the image I was loading becomes black-an-white, when the original image has grays in it. I decided to check the image using a imshow on a new file, but it really makes it black and white. My code is simply: image_path = 'no.png'; img = imread(image_path); imshow(img); axis off;... | Actually, the problem comes from the fact that your image is not grayscale, but is indexed. image_path = 'no.png'; [img,map] = imread(image_path); % Returns a non-empty map --> indexed image Now, you can get the expected output by using the map: imshow(img,map); axis off; You can look at this answer for how to check... | 2 | 2 |
78,400,673 | 2024-4-29 | https://stackoverflow.com/questions/78400673/how-can-i-wait-for-the-actual-reply-of-an-openai-assistant-python-openai-api | I am interacting with the openai assistant API (python). so far, it works well. but sometimes the api returns the message i sent to the assistant instead of the assistants reply. from openai import OpenAI from os import environ OPEN_API_KEY = environ.get('OPEN_API_KEY') assistant_id = "xxxxxxx" client = OpenAI(api_key=... | This should work: run = openai.beta.threads.runs.create( thread_id=thread.id, assistant_id=assistant.id ) print(run) while run.status !="completed": run = openai.beta.threads.runs.retrieve( thread_id=thread.id, run_id=run.id ) print(run.status) messages = openai.beta.threads.messages.list( thread_id=thread.id ) print(m... | 2 | 2 |
78,400,329 | 2024-4-29 | https://stackoverflow.com/questions/78400329/multiplot-in-for-loop-by-importing-only-pandas | Sometime, DataFrame.plot() inside a for loop produces multiple charts. import pandas as pd data = {'Str': ['A', 'A', 'B', 'B'], 'Num': [i for i in range(4)]} df = pd.DataFrame(data) for n in ['A', 'B']: df[df.Str == n].plot(kind='bar') But sometimes, it produces a single chart. import pandas as pd data = {'C1': ['A',... | I'm not sure why matplotlib behave this way, but your code in the second loop products a Series while the first produces a DataFrame. This might force reusing the same axes. You could add as_index=False in the groupby to have an object that is comparable to the one in the first loop: for n in [1,2]: df[df.C3 == n].grou... | 2 | 1 |
78,399,639 | 2024-4-28 | https://stackoverflow.com/questions/78399639/how-to-use-io-bytesio-in-python-to-write-to-an-existing-buffer | According to How the write(), read() and getvalue() methods of Python io.BytesIO work? , it seems io.BytesIO will copy initial bytes provided. I have a buffer, and I want pickle to directly dump object in that buffer, without any copy. So I tried to use f = io.BytesIO(buffer). However, after f.write, my buffer is not m... | IIUC you can try to make your own IO class: import io import pickle class MyIO(io.IOBase): def __init__(self, buf): self.buf = memoryview(buf) self.position = 0 def write(self, b): start = self.position n = len(b) end = start + n self.buf[start: end] = b self.position = end a = bytearray(1024) with MyIO(a) as f: obj = ... | 3 | 2 |
78,399,629 | 2024-4-28 | https://stackoverflow.com/questions/78399629/slicing-using-polars-filter-is-slower-than-pandas-loc | I am trying to switch some of my pandas code to polars to leverage it's performance. I have found that the .filter operation is much slower than a similar slicing using .loc. import pandas as pd import polars as pl import datetime as dt import numpy as np date_index = pd.date_range(dt.date(2001,1,1), dt.date(2020,1,1),... | Polars doesn't use indexes, so random access of one specific element (if not by row number) will always have to loop over all the data. But you can efficiently get all the dates you are interested in in one go using a left join: test_dates_df = pl.DataFrame({"index": test_dates}) out = test_dates_df.join(test_pl, on="i... | 2 | 4 |
78,399,002 | 2024-4-28 | https://stackoverflow.com/questions/78399002/group-data-and-remove-duplicate | I have the data in the form of table below Name Mas Sce M ( (87) 83 (91) (97) ) T (77) 76 R (60) 32 G (95) 20 M ( (50) 89 (50) (99) ) Some of my data runs through multiple row such as M case. The data is enclosed within the bracket I have tried drop duplicates. It works when its single row. But, now i have a few rows ... | A pure pandas one-liner with duplicated, a mask and ffill: out = df[~df['Name'].duplicated() .mask(df['Name'].replace('', None).isna()) .ffill().infer_objects(copy=False)] Output: Name Mas Sce 0 M ( (87) 83 1 None (91) 2 None (97) ) 3 T (77) 76 4 R (60) 32 5 G (95) 20 | 2 | 0 |
78,398,988 | 2024-4-28 | https://stackoverflow.com/questions/78398988/multi-processing-code-not-working-in-while-loop | Happy Sunday. I have this code that I want to run using the multi-processing module. But it doesn't just work for some reason. with ProcessPoolExecutor() as executor: while True: if LOCAL_RUN: print("ALERT: Doing a local run of the automation with limited capabilities.") list_of_clients = db_manager.get_clients() rando... | ProcessPoolExecutor.map creates an iterator, you must consume the iterator to get the exception, otherwise the exception will be discarded. from concurrent.futures import ProcessPoolExecutor def raising_func(val): raise ValueError(val) with ProcessPoolExecutor(4) as pool: pool.map(raising_func, [1,2,3,4,5]) with Proces... | 2 | 2 |
78,398,642 | 2024-4-28 | https://stackoverflow.com/questions/78398642/maximum-number-of-elements-on-list-whose-value-sum-up-to-at-most-k-in-olog-n | I have this exercise to do: Let M be a positive integer, and V = ⟨v1, . . . , vn⟩ an ordered vector where the value of item vi is 5×i. Present an O(log(n)) algorithm that returns the maximum number of items from V that can be selected given that the sum of the selected items is less than or equal to M (repeated selecti... | The sum 1 + 2 + ... + n = n * (n+1) / 2. The sum 5 + 10 + ... + 5n = 5 * (1 + 2 + ... + n) = 5 * n * (n+1) / 2. So given an M, we want to solve for n so that 5 * n * (n+1) / 2 <= M. Then, add 1 to this to account for zero. You can use the quadratic formula for an O(1) (which is also O(log n)) solution, or binary search... | 4 | 5 |
78,388,116 | 2024-4-26 | https://stackoverflow.com/questions/78388116/how-can-i-locate-this-chemical-test-strip-in-the-picture-opencv-canny-edge-dete | I have an image that i would like to do an edge detection and draw a bounding box to it, my problem is my python code does not draw the bounding box and im not sure if its because it was not able to detect any objects in it or im just drawing the rectangle wrong. Here is my attempt import cv2 import numpy as np img = ... | My approach: optional: correct white balance so that the background loses its tint convert to color space with saturation channel, threshold that contours, minAreaRect This approach detects all four colored squares. # you can skip this step by defining `balanced = im * np.float32(1/255)` # gray = im.mean(axis=(0,1), ... | 3 | 4 |
78,390,439 | 2024-4-26 | https://stackoverflow.com/questions/78390439/how-to-pass-in-variables-during-redirect-in-html-using-jinja-syntax | I have the following code: @app.route("/", methods=["GET", "POST"]) def login(): if request.method == "GET": return render_template("login.html") elif request.method == "POST": username, password = request.form.get("username"), request.form.get("password") if validate_login(username, password): return redirect("/home.h... | I'm assuming you're using flask as your routing engine. If so, instead of redirecting to a bare html url, you can redirect to a new route. Something like: if validate_login(username, password): return redirect(f"/home/{username}") Then have that route render the home.html template using the variable as normal: @app.ro... | 2 | 1 |
78,386,255 | 2024-4-25 | https://stackoverflow.com/questions/78386255/odoo-cant-compare-dates-for-setting-a-computed-field-using-api-depends | Using Odoo 16, using Odoo.sh I am trying to set a date in a model that should be the furthest in the future of the dates among the related objects from a one2many field. So I have a computed field with a @api.depends computation to iterate through the one2many and find + assign this data to a field. Everything in my be... | As per comment from @CZoellner the issue was because I had not put handling into the code for when order_line.delivery was empty. Correct code below: @api.depends('order_line_ids') def _compute_full_delivery_date(self): for record in self: if record.order_line_ids: for order_line in record.order_line_ids: if order_line... | 2 | 1 |
78,390,521 | 2024-4-26 | https://stackoverflow.com/questions/78390521/consistent-initialisation-in-simple-dae-system-using-gekko | I'm messing around with GEKKO for dynamic simulations to see how it compares to commercial simulation software e.g. gPROMS. As a simple test I'm attempting to model the blowdown of a pressurised vessel. However I cannot seem to get the solver to consistently initialise the simulation. I have modelled the system using t... | The first node of a dynamic simulation is deactivated in Gekko because initial conditions are typically fixed. Gekko doesn't require consistent initial condition and can solve higher-index DAEs without Pantelides algorithm (differentiate higher-order algebraic equations to return to ODE or index-1 DAE form). There is n... | 2 | 1 |
78,390,452 | 2024-4-26 | https://stackoverflow.com/questions/78390452/how-to-adjust-spacy-tokenizer-so-that-it-splits-number-followed-by-dot-at-line-e | i have a use case in spacy where i want to find phone numbers in German sentences. Unfortunately the tokenizer is not doing the tokenization as expected. When the number is at the end of a sentence the number and the dot is not split into two tokens. English and German Version differ here, see the following code: impor... | You may use 'suffixes' to fix issues with punctuation. Here is an example: import spacy nlp_en = spacy.blank("en") nlp_de = spacy.blank("de") text = "Die Nummer lautet 1234 123448." suffixes = nlp_de.Defaults.suffixes + [r'\.',] suffix_regex = spacy.util.compile_suffix_regex(suffixes) nlp_de.tokenizer.suffix_search = s... | 2 | 1 |
78,386,497 | 2024-4-25 | https://stackoverflow.com/questions/78386497/how-to-regress-multiple-gaussian-peaks-from-a-spectrogram-using-scipy | I have this code that aims to fit the data in here DriveFilelink The function read_file is utilized to extract information in a structured manner. However, I'm encountering challenges with the Gaussian fit, evident from the discrepancies observed in the Gaussian fit image. This issue appears to stem from the constraint... | Here is a MCVE showing how to regress a variable number of peaks from the significant part of your signal. import itertools import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import signal, stats, optimize We load you data and post-process it to get physical series: data = pd.read_csv("2... | 2 | 3 |
78,389,992 | 2024-4-26 | https://stackoverflow.com/questions/78389992/does-python-throw-away-unused-expressions | In pyhon3.10, I can run this code snippet without raising any errors: {}[0]:1 which creates an empty dictionary, and then accesses the 0 key. However, the :1 that follows is what I would consider an invalid syntax. And indeed, if I try to determine the type of the result: type({}[0]:1) a syntax error gets raised. A s... | {}[0]:1 as a statement is not a syntax error. It's an annotation where {}[0] is the thing being annotated and 1 is the annotation. Normally, you would write something like x: int. {}[0] is not an error because it is executed as if on the left-hand side of an assignment. We can see this by using dis.dis (this is Python ... | 2 | 6 |
78,389,427 | 2024-4-26 | https://stackoverflow.com/questions/78389427/how-to-generate-multiple-responses-for-single-prompt-with-google-gemini-api | Context I am using google gemini-api. Using their Python SDK Goal I am trying to generate multiple possible responses for a single prompt according to the docs and API-reference Expected result - multiple response for a single prompt Actual result - single response Code I have tried # ... more code above model = gena... | When I saw the official document GenerationConfig of Method: models.generateContent, it says as follows. candidateCount: integer Optional. Number of generated responses to return. Currently, this value can only be set to 1. If unset, this will default to 1. It seems that in the current stage, candidateCount is only 1... | 2 | 1 |
78,389,964 | 2024-4-26 | https://stackoverflow.com/questions/78389964/return-diag-elements-of-nxn-matrix-without-using-a-for-loop | Imagine having an array of matrices (nxkxk), how would I return the diagonal entries while keeping the original shape without using a for-loop. For example, without keeping the original shape we could do np.diagonal(array_of_matrices, axis1=1, axis2=2) Obviously I could just do this and then reconstruct the original sh... | You can use broadcasting to multiply an eye matrix by your k x n x n shaped array to return only the diagonal elements. import numpy as np n = 4 k = 3 arr = np.arange(k * n * n).reshape(k, n, n) diags = arr * np.eye(n) Here are the elements: arr # returns: array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13... | 2 | 4 |
78,387,204 | 2024-4-25 | https://stackoverflow.com/questions/78387204/pybind11-cant-figure-out-how-to-access-tuple-elements | I'm an experienced Python programmer trying to learn C++ to speed up some projects. Passing a py::tuple to a function, how do I access the elements? Here's the constructor for a class I'm making to hold images from a video. Buffer::Buffer(int size, py::tuple hw_args_) { unsigned int frame_height = get<0>(hw_args_); uns... | py::tuple has an operator[] that returns a detail::tuple_accessor which has a .cast as any py::object uint32_t frame_height = hw_args_[0].cast<uint32_t>(); you could check its use from pybind11 tests [](const py::tuple &tup) { if (py::len(tup) != 4) { throw py::cast_error("Invalid size"); } return SimpleStruct{tup[0].... | 3 | 3 |
78,387,084 | 2024-4-25 | https://stackoverflow.com/questions/78387084/understanding-pythons-bisect-library-clarifying-usage-of-bisect-left | During my recent work on a mathematical problem in Python, I encountered some confusion regarding the behavior of the bisect.bisect_left function from the bisect library. This confusion arose due to its similarity with another function in the library, namely bisect.insort_left. In my specific use case, I was utilizing ... | Let's say the list items contain a lot of data. Each item can be e. g. a dict { 'id': 12, 'firstname': 'foo', 'lastname': 'bar', 'address': ..., 'phone': ... ... } These items are sorted in the list by id with an appropriate key function like lambda item: item['id']. If you want to find an item with bisect_left it sho... | 3 | 4 |
78,381,155 | 2024-4-24 | https://stackoverflow.com/questions/78381155/python-setuptools-multiple-extension-modules-with-shared-c-source-code-building | I'm working on a Python project with a setup.py that has something like this1: setup( cmdclass={"build_ext": my_build_ext}, ext_modules=[ Extension("A", ["a.c", "common.c"]), Extension("B", ["b.c", "common.c"]) ] ) I'm running into a problem when building the modules in parallel where it seems like one module tries to... | I found a potential solution by overriding build_extension() in a custom build_ext class: import copy, os from setuptools import Extension, setup from setuptools.command.build_ext import build_ext class my_build_ext(build_ext): def build_extension(self, ext): # Append the extension name to the temp build directory # so... | 3 | 3 |
78,384,202 | 2024-4-25 | https://stackoverflow.com/questions/78384202/filter-a-polars-dataframe-based-on-json-in-string-column | I have a Polars dataframe like df = pl.DataFrame({ "tags": ['{"ref":"@1", "area": "livingroom", "type": "elec"}', '{"ref":"@2", "area": "kitchen"}', '{"ref":"@3", "type": "elec"}'], "name": ["a", "b", "c"], }) ┌────────────────────────────────────────────────────┬──────┐ │ tags ┆ name │ │ --- ┆ --- │ │ str ┆ str │ ╞══... | pl.Expr.str.json_path_match can be used to extract the first match of the JSON string with the a suitable path expression. ( df .filter( pl.col("tags").str.json_path_match("$.area").is_not_null(), pl.col("tags").str.json_path_match("$.type") == "elec", ) ) shape: (1, 2) ┌───────────────────────────────────────────────... | 2 | 3 |
78,383,764 | 2024-4-25 | https://stackoverflow.com/questions/78383764/rolling-windows-over-internal-lists | I have a frame like this: import polars as pl from polars import Boolean, List, col src = pl.DataFrame( { "c1": ["a", "b", "c", "d"], "c2": [ [0, 0], [0, 1, 0, 0], [1, 0, 1, 1, 1], [1, 1, 0], ], }, schema_overrides={"c2": List(Boolean)}, ) For each of the inner lists in "c2", I am trying to calculate the maximum sum i... | You can access .rolling_sum() via the .list.eval() API. df.with_columns( pl.col("c2").list.eval( pl.element().rolling_sum(3) ) ) shape: (4, 2) ┌─────┬───────────────────────┐ │ c1 ┆ c2 │ │ --- ┆ --- │ │ str ┆ list[i64] │ ╞═════╪═══════════════════════╡ │ a ┆ [null, null] │ │ b ┆ [null, null, 1, 1] │ │ c ┆ [null, null,... | 3 | 3 |
78,381,346 | 2024-4-24 | https://stackoverflow.com/questions/78381346/building-plots-with-plotnine-and-python | I am looking for a way that I can modify plots by adding to an existing plot object. For example, I want to add annotations at particular dates in a work plot, but want a standard way of building the base chart, and then "adding" annotations if I decide to later. Example of what I want to do (using Altair) It might be ... | Similar to R's ggplot2 (see here) you can use a list to decompose the creation of a plot in multiple parts where each part consists of multiple components or layers: import plotnine as p9 import pandas as pd data = pd.DataFrame([ {'x': 0, 'y': 0}, {'x': 2, 'y': 1}, {'x': 3, 'y': 4} ]) events = pd.DataFrame([ {'x': 1, '... | 3 | 2 |
78,379,854 | 2024-4-24 | https://stackoverflow.com/questions/78379854/count-matches-with-multiple-options | I have a frame like this: src = pl.DataFrame( { "c1": ["a", "b", "c", "d"], "c2": [[0], [2, 3, 4], [3, 4, 7, 9], [3, 9]], } ) ... and a list of targets: targets = pl.Series([3, 7, 9]) ... and I want to count the number of targets in "c2": dst = pl.DataFrame( { "c1": ["a", "b", "c", "d"], "c2": [[0], [2, 3, 4], [3, 4,... | You could use pl.Expr.list.eval to evaluate for each element in the list column, whether it is contained in target. Then, the sum of the boolean list gives the number of matches. dst.with_columns( pl.col("c2").list.eval(pl.element().is_in(targets)).list.sum().alias("res") ) shape: (4, 4) ┌─────┬─────────────┬─────────... | 2 | 2 |
78,378,343 | 2024-4-24 | https://stackoverflow.com/questions/78378343/selecting-checkboxes-that-are-wrapped-with-a-and-i-tags | I'm trying to check if the checkbox is selected using is_selected() method. I understand that since the element I am trying to validate is not a legit checkbox, it's not right to validate it this way. It's pretty obvious because it's wrapped in an anchor(<a>) and italic tag(<i>). I've tried different variants of XPaths... | The problem is that the non-stop INPUT isn't actually storing checked state. It's being stored in the I tag right above it but inside the A tag. <a for="BE_flight_non_stop" title="Non Stop Flights" class="custom-check"> -> <i class="ico ico-checkbox"></i> <input data-trackcategory="Home Page" data-trackaction="Booking ... | 2 | 1 |
78,378,769 | 2024-4-24 | https://stackoverflow.com/questions/78378769/how-to-authenticate-on-msgraph-graphserviceclient | There is no documentation for do this, I found it unacceptable. from msal import ConfidentialClientApplication from msgraph import GraphServiceClient client_id = '' client_secret = '' tenant_id = '' authority = f'https://login.microsoftonline.com/{tenant_id}' scopes = ['https://graph.microsoft.com/.default'] app = Conf... | I registered one Entra ID application and granted User.Read.All permission of Application type as below: Initially, I too got same error when I ran your code to fetch list of users like this: from msal import ConfidentialClientApplication from msgraph import GraphServiceClient client_id = '' client_secret = '' tenant_... | 2 | 2 |
78,378,241 | 2024-4-24 | https://stackoverflow.com/questions/78378241/how-can-i-know-the-coincidences-in-2-list-in-python-order-matters-but-when-1-fa | I have 2 python lists to compare. list1 = ['13.3. Risk', '13.3.1. Process', 'Change'] list2 = ['Change', '13.3. Risk', '13.3.1. Process'] I want to know how exact the order of elements is. If I go item by item, the coincidence it´s 0 since the first one fails. But if you look carefully, just fails the first element. A... | May calculate Levenshtein distance between lists itself, not their concatenations: lev_dist = distance(list1, list2) percentage = 100 * (1 - lev_dist / (len(list1) + len(list2))) shows 66.66666666666666 | 2 | 2 |
78,377,954 | 2024-4-24 | https://stackoverflow.com/questions/78377954/groupby-mean-if-condition-is-true | I got the following dataframe: index user default_shipping_cost category shipping_cost shipping_coalesce estimated_shipping_cost 0 0 1 1 clothes NaN 1.0 6.0 1 1 1 1 electronics 2.0 2.0 6.0 2 2 1 15 furniture NaN 15.0 6.0 3 3 2 15 furniture NaN 15.0 15.0 4 4 2 15 furniture NaN 15.0 15.0 Per user, combine shipping_cost... | Add an extra condition with transform('any') and where: df['estimated_shipping_cost'] = (dfg_user['shipping_coalesce'].transform('mean') .where(dfg_user['shipping_cost'].transform('any')) ) Output: index user default_shipping_cost category shipping_cost shipping_coalesce estimated_shipping_cost 0 0 1 1 clothes NaN 1.... | 2 | 1 |
78,377,078 | 2024-4-24 | https://stackoverflow.com/questions/78377078/generating-combinations-in-pandas-dataframe | I have a dataset with ["Uni", 'Region', "Profession", "Level_Edu", 'Financial_Base', 'Learning_Time', 'GENDER'] columns. All values in ["Uni", 'Region', "Profession"] are filled while ["Level_Edu", 'Financial_Base', 'Learning_Time', 'GENDER'] always contain NAs. For each column with NAs there are several possible value... | You can combine itertools.product and a cross-merge: from itertools import product data = {'Level_Edu': ['undergrad', 'grad', 'PhD'], 'Financial_Base': ['personal', 'grant'], 'Learning_Time': ['morning', 'day', 'evening'], 'GENDER': ['Male', 'Female']} out = (sample_data_as_is[['Uni', 'Region', 'Profession']] .merge(pd... | 5 | 3 |
78,347,434 | 2024-4-18 | https://stackoverflow.com/questions/78347434/problem-setting-up-llama-2-in-google-colab-cell-run-fails-when-loading-checkpo | I'm trying to use Llama 2 chat (via hugging face) with 7B parameters in Google Colab (Python 3.10.12). I've already obtain my access token via Meta. I simply use the code in hugging face on how to implement the model along with my access token. Here is my code: !pip install transformers from transformers import AutoMod... | The issue is with Colab instance running out of RAM. Based on your comments you are using basic Colab instance with 12.7 Gb CPU RAM. For LLama model you'll need: for the float32 model about 25 Gb (but you'll need both cpu RAM and same 25 gb GPU ram); for the bfloat16 model around 13 Gb (and still not enough to fit bas... | 3 | 5 |
78,364,357 | 2024-4-22 | https://stackoverflow.com/questions/78364357/how-count-occurrences-across-all-columns-in-a-polars-dataframe | I have an imported .csv of number values- I want to sort the dataframe so I end up a list showing how many times each value occurs across the whole dataframe. E.g. 1: 5 2: 0 3: 23 4: 8 I have found how to count the values of a specified column, but I can't find a way to do the same thing for the entire dataframe- I co... | TLDR. You can use value_counts after unpivoting the dataframe into a long format. df.unpivot().get_column("value").value_counts() Explanation Let us consider the following example dataframe. import polars as pl df = pl.DataFrame({ "col_1": [1, 2, 3], "col_2": [2, 3, 7], "col_3": [1, 1, 9], }) shape: (3, 3) ┌───────┬─... | 2 | 2 |
78,357,791 | 2024-4-20 | https://stackoverflow.com/questions/78357791/how-to-apply-break-system-packages-conditionally-only-when-the-system-pip-py | I am adapting my pip commands to newer versions of Ubuntu (that support PEP 668). Out of the options, the only one worked so far (in my specific use case) is to Use --break-system-packages at the end of pip as indicated in this answer. That is, change sudo pip install xyz to sudo pip install xyz --break-system-packa... | You can set an environment variable instead of using --break-system-packages. PIP_BREAK_SYSTEM_PACKAGES=1 pip install xyz should work in both new and older versions of pip | 8 | 16 |
78,370,120 | 2024-4-23 | https://stackoverflow.com/questions/78370120/how-to-drag-qlineedit-form-one-cell-of-qgridlayout-to-other-cell-in-pyqt | I have gridlayout with four cells (0,0),(0,1),(1,0),(1,1). Every cell is vertical layout with scrollbar. Initially only (0,0) cell contains QLineEdit in it. I want to drag and drop them in any one of the cells. How can I do it? I want to layout the cells like the image contained in the following link. I have tried thi... | OK kind of solved the layout problem thanks to an old post I used some time ago that went nearly forgotten answer to How to make QScrollArea working properly Alternatively, you can also do the same from Designer with a small workaround: add any widget (a button, a label, it doesn't matter) to the scrollAreaWidgetCon... | 2 | 1 |
78,374,548 | 2024-4-23 | https://stackoverflow.com/questions/78374548/no-authentication-box-appears-when-authenticating-google-earth-engine-gee-pyth | I try to authenticate the GEE, the kernel keeps running, but authenticating box does not show to paste the authentication code in (picture below, but no authentication box showed). Anyone has similar experience? | You should add the authentication code to the box appearing on top of VSCode. This is the same box displayed under "the authorization workflow will generate a code which you should paste in the box below" in Jupyter. | 2 | 2 |
78,364,978 | 2024-4-22 | https://stackoverflow.com/questions/78364978/move-specific-column-information-to-a-new-row-under-the-current-row | Consider this df: data = { 'Name Type': ["Primary", "Primary", "Primary"], 'Full Name': ["John Snow", "Daenerys Targaryen", "Brienne Tarth"], 'AKA': ["Aegon Targaryen", None, None], 'LQAKA': ["The Bastard of Winterfell", "Mother of Dragons", None], 'Other': ["Info", "Info", "Info"]} df = pd.DataFrame(data) I need to m... | You can melt+dropna+sort_index and post-process: # reshape, remove None, and reorder out = (df.melt(['Name Type', 'Other'], ignore_index=False) .dropna(subset='value') .sort_index(kind='stable', ignore_index=True) .rename(columns={'value': 'Full Name'}) ) # identify rows with "Full Name" m = out['variable'].ne('Full Na... | 2 | 3 |
78,368,881 | 2024-4-22 | https://stackoverflow.com/questions/78368881/curve-fitting-with-scipy-failing-to-give-a-correct-fit | I have two NumPy arrays x_data and y_data. When I try to fit my data using a second order step response model and scipy.optimize.curve_fit with this code: import numpy as np from scipy.optimize import curve_fit import matplotlib.pyplot as plt x_data = np.array([51.5056, 51.5058, 51.5061, 51.5064, 51.5067, 51.5069, 51.5... | COMMENT : The model equation appears not well compatible with the data. The fitting is far to be correct. A different model equation is considered below. The variable t is repaced by a variable x=ln(t-t0). Of course this isn't significant on physical viewpoint. This is purely mathematical. | 5 | 2 |
78,373,626 | 2024-4-23 | https://stackoverflow.com/questions/78373626/two-dimensions-array-9x9-of-integers-without-using-numpy-array-subclassing-muta | Few days ago I found the next example of howto implement customs list classes via subclassing the MutableSequence from collections.abc. class TypedList(MutableSequence): def __init__(self, oktypes, *args): self.oktypes = oktypes self.list = list() self.extend(list(args)) def check(self, v): if not isinstance(v, self.ok... | There are these issues in your attempt: The if statement in check lacks an opening parenthesis. __len__ should return a number, not a tuple. __getitem__ and similar methods should not take two index arguments, but one. However, this argument can be a tuple (of 2 coordinates) In __setitem__ the call to self.check has a... | 2 | 2 |
78,363,215 | 2024-4-21 | https://stackoverflow.com/questions/78363215/python-multiprocessing-when-i-launch-many-processes-on-a-huge-pandas-data-frame | I am trying to gain execution time with python's multiprocessing library (pool_starmap) on a code that executes the same task in parallel, on the same Pandas DataFrame, but with different call arguments. When I execute this code on a small portion of the data frame and with 10 jobs, everything works just fine. However ... | Ok, so thanks to @SIGHUP and @Frank Yellin, I was able to find the issue, so I will share it here if anyone encounters a similar issue. Python seems unable to print anything when there are too many concurrent processes running. The solution, to check if your program is alive, is to make it write into a .txt file, for e... | 2 | 0 |
78,369,755 | 2024-4-23 | https://stackoverflow.com/questions/78369755/polars-compare-two-dataframes-is-there-a-way-to-fail-immediately-on-first-mism | I'm using polars.testing assert_frame_equal method to compare two sorted dataframes containing same columns and below is my code: assert_frame_equal(src_df, tgt_df, check_dtype=False, check_row_order=False) For a dataframe containing 5 million records, it takes long time to report a failure as it compares all the rows... | The polars.testing.* methods call .to_list() when reporting differences. https://github.com/pola-rs/polars/blob/main/py-polars/polars/testing/asserts/frame.py#L128-L130 I've found this to be a source of significant slowdown when larger data is involved. If you also want error reporting, it seems you need to resort to... | 2 | 1 |
78,366,661 | 2024-4-22 | https://stackoverflow.com/questions/78366661/i-get-an-empty-array-from-vector-serch-in-mongodb-with-langchain | I have the code: loader = PyPDFLoader(“https://arxiv.org/pdf/2303.08774.pdf”) data = loader.load() docs = text_splitter1.split_documents(data) vector_search_index = “vector_index” vector_search = MongoDBAtlasVectorSearch.from_documents( documents=docs, embedding=OpenAIEmbeddings(disallowed_special=()), collection=atlas... | So I was able to get this to work in MongoDB with the following code: text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150) loader = PyPDFLoader("https://arxiv.org/pdf/2303.08774.pdf") data = loader.load() docs = text_splitter.split_documents(data) DB_NAME = "langchain_db" COLLECTION_NAME =... | 3 | 2 |
78,353,162 | 2024-4-19 | https://stackoverflow.com/questions/78353162/odoo-14-binary-field-inside-hr-employee-public | I have a problem with the hr.employee.public model. If I try to add a new field Char, Integer, Many2one, etc. I have no issues. However, if I try to insert a Binary field like this employee_signature = fields.Binary(string='Employee signature', attachment=True, store=True) I always get the following error: psycopg2.err... | If you inherit hr.employee.public to add a stored field (not x2many fields), you should see the same error message because of the init function which tries to get fields from hr.employee You don't need to set the store attribute to True because it's the default value (if you set store to False, you will not be able to ... | 3 | 1 |
78,371,754 | 2024-4-23 | https://stackoverflow.com/questions/78371754/storing-numpy-array-in-raw-binary-file | How to store a 2D numpy ndarray in raw binary format? It should become a raw array of float32 values, in row-major order, no padding, without any headers. According to the documentations, ndarray.tofile() can store it as binary or textual, but the format argument is a string to textual formatting. And np.save() saves i... | with open('out', 'wb') as f: f.write(arr.tobytes()) should do. You may have to add a astype(np.float32) if arr is not already a float32 array. Likewise, if the array is not already in "row major order", you may have to add a .T somewhere. And of course (but I take you know that very well, if you want to dump binary re... | 2 | 2 |
78,369,655 | 2024-4-23 | https://stackoverflow.com/questions/78369655/scipys-solve-ivp-having-trouble-solving-simple-ivp | I'm attempting to solve a very simple IVP in Python in order to do error analysis: import numpy as np from scipy.integrate import solve_ivp def dh_dt_zerodriver(t, h): return -2 / h t = 50 steps = 10 dt = t / steps t_span = [0, t] t_eval = np.arange(0, t + dt, dt) h0 = 5 sol = solve_ivp(dh_dt_zerodriver, t_span=t_span,... | The problem is the domain you want your solution. Your ODE is h'(t) = -2/h(t) where h(0) = 5. The analytical solution is h(t) = sqrt(25 - 4t). For t < 6.25, the solution is real, but for t >= 6.25, the solution becomes complex. If you were to instead integrate over t = [0, 6], you would quickly get the correct result. | 2 | 4 |
78,368,454 | 2024-4-22 | https://stackoverflow.com/questions/78368454/group-streaks-ending-in-false-and-apply-forward-backward-filling | I have a dataframe, where I want to forward / backward fill, based on a boolean series, df['condition']. A single group consists of a streak of True values including the breaking False entry that separates a streak from the next one. What I mean is very clear when looking at my dataframes. My input looks like this: con... | You were quite close indeed! You can try as follows: Option 1: ffill().bfill() df['value'] = ( df.groupby( df['condition'].shift().eq(0).cumsum() .where(df['condition']).ffill() )['value'] .apply(lambda x: x.ffill().bfill()) .droplevel(0) ) Option 2: transform(first) If you only have one value per group (as in your ex... | 2 | 3 |
78,367,794 | 2024-4-22 | https://stackoverflow.com/questions/78367794/ansible-join-flatten-a-dict-of-lists | I have a dict of lists such as here, though the inner data could be any level of complexity (perhaps strings, perhaps dicts, perhaps multi layer nested complex object). my_dict: my_list_a: - a - b - c my_list_b: - a - d - e list_c: - f How do I flatten this structure / join the inner items into a list in the followin... | Q: Flatten the inner items into a list. A: The simplest option is my_combined_list: "{{ my_dict.values() | flatten }}" gives my_combined_list: [a, b, c, a, d, e, f] Q: Select or reject based on a test (start string: my_ , e.g. list_c is omitted). A: For example, use the test match allow_match: [my_] my_combined_list:... | 2 | 4 |
78,368,186 | 2024-4-22 | https://stackoverflow.com/questions/78368186/move-data-in-dataframe-based-on-a-value-of-a-different-column | I have a dataframe that looks like this: Put/Call StrikePrice fixedprice floatprice fixedspread floatspread Put 10 0 20 0 0 Put 10 0 20 0 0 nan 0 0 0 13 15 nan 0 0 0 14 16 If the put/call column has the value 'Put', I need to take the value from the strike price column and place it in the fixedspread column, and I nee... | You can directly combine the columns with mask using the underlying numpy array for the right-hand side: out = (df[['fixedspread', 'floatspread']] .mask(df['Put/Call'].eq('Put'), df[['StrikePrice', 'floatprice']].values) ) Output: fixedspread floatspread 0 10 20 1 10 20 2 13 15 3 14 16 | 2 | 2 |
78,367,100 | 2024-4-22 | https://stackoverflow.com/questions/78367100/does-this-code-adding-256-to-a-uint8-fail-in-numpy-2-due-to-nep-50 | The following code works in numpy 1.26.4, but not in numpy 2.0.0rc1, giving OverflowError: Python integer -256 out of bounds for int8 import numpy as np np.array([1], dtype=np.int8) + (-256) Is that expected? Is it due to NEP 50 adoption? If so, which part of NEP 50 mandates this new behavior? | Yeah, that's NEP 50 behavior. Quoting NEP 50: This proposal uses a “weak scalar” logic. This means that Python int, float, and complex are not assigned one of the typical dtypes, such as float64 or int64. Rather, they are assigned a special abstract DType, similar to the “scalar” hierarchy names: Integral, Floating, C... | 3 | 4 |
78,361,389 | 2024-4-21 | https://stackoverflow.com/questions/78361389/pystata-run-stata-instances-in-parallel-from-python | I'm using the pystata package that allows me to run stata code from python, and send data from python to stata and back. The way I understand this, is that there is a single stata instance that is running in the background. I want to bootstrap some code that wraps around the stata code, and I would like to run this in ... | Using backend="multiprocessing" as an argument to joblib.Parallel will launch Stata instances in separate processes. | 2 | 1 |
78,362,581 | 2024-4-21 | https://stackoverflow.com/questions/78362581/error-when-trying-to-do-multiturn-chat-with-gemini-pro | This is the code I took from the API docs in order to start multiturn chat model = genai.GenerativeModel("gemini-pro") messages = [{'role':'user', 'parts': ['hello']}] response = model.generate_content(messages) # "Hello, how can I help" messages.append(response.candidates[0].content) messages.append({'role':'user', 'p... | As a simple modification, how about the following modification? Modified script 1: genai.configure(api_key=apiKey) model = genai.GenerativeModel("gemini-pro") messages = [{"role": "user", "parts": ["hello"]}] response = model.generate_content(messages) messages.append({"role": "model", "parts": [response.text]}) print(... | 2 | 0 |
78,363,045 | 2024-4-21 | https://stackoverflow.com/questions/78363045/return-null-when-multiple-values-has-same-mode | Sharing one sample code . For column b as u can see both values{1,2} has same frequency{2} so mode is returning both values but I want null . Which logically means that it is unable to find one unique value which is most occuring. import polars as pl if __name__ == '__main__': df = pl.DataFrame( { "a": [1, 1, 2, 3], "b... | You could try using a pl.when().then() construct. df.select( pl.when( pl.col("b").mode().len() == 1 ).then( pl.col("b").mode() ) ) shape: (2, 1) ┌──────┐ │ b │ │ --- │ │ i64 │ ╞══════╡ │ null │ │ null │ └──────┘ If you prefer a single null, you can append .unique() to the closing parenthesis of .then(). | 2 | 1 |
78,362,424 | 2024-4-21 | https://stackoverflow.com/questions/78362424/how-do-i-print-an-equation-using-sympy | How do I show an equation like this: I can show the left side using display(binomial(n,k)) and the right side using y= factorial(n)/(factorial(n-k) * factorial(k)) display(y) but how do I show the equation? Also, how do I make it show (n-k) instead of (-k+n)? | Make it into an Equality. from sympy import init_session init_session(quiet=True) import sympy as smp n, k = smp.symbols("n k") eq = smp.Eq(smp.binomial(n, k), smp.factorial(n)/(smp.factorial(n-k) * smp.factorial(k))) eq The variable ordering in displayed result is determined internally by sympy (I believe it is alph... | 2 | 3 |
78,361,571 | 2024-4-21 | https://stackoverflow.com/questions/78361571/annotate-decorator-with-paramspec-correctly-using-new-typing-syntax-3-12 | I'm trying to use new type hints from Python 3.12, and suddenly PyCharm highlights some obscure problem about new usage of ParamSpec. import functools from dataclasses import dataclass from typing import Callable from typing import Concatenate @dataclass class Message: text: str type CheckFunc[**P] = Callable[Concatena... | Your code has no problem. The problem is with PyCharm. Its support for Concatenate et al. is incomplete, as discussed in PY-51766. I'm unable to find a good existing issue for this bug, however. Put a type: ignore or noqa comment there and move on. | 3 | 1 |
78,360,352 | 2024-4-21 | https://stackoverflow.com/questions/78360352/polars-lazyframe-not-returning-specified-schema-order-after-collecting | I have a function which runs in a loop performing calculations on a list of arrays. At a point during the first iteration of the function, a polars lazyframe is initialised. On the following iterations, a new dataframe is specified using the same schema, and the two dataframes are joined row-wise using pl.vstack, and t... | The problem is you're using a set which is an unordered collection in Python. >>> schema = {'MDL', 'MVL', 'MWVL', 'RR', 'DET'} >>> type(schema) set >>> schema {'DET', 'MDL', 'MVL', 'MWVL', 'RR'} # "random" order You want to use a list/tuple instead. There is a LazyFrame constructor, and you can use concat to combine f... | 2 | 2 |
78,360,123 | 2024-4-21 | https://stackoverflow.com/questions/78360123/rolling-sum-with-periods-given-from-pandas-column | Trying to calculate in pandas the rolling sum of Values in Column A, with lookback periods given in Column B and results of rolling sums stored in Column C. Index | Column A | Column B || Column C | | -------- | -------- || -------- | 0 | 1 | 1 || 1 | 1 | 2 | 2 || 3 | 2 | 1 | 3 || 4 | 3 | 3 | 2 || 4 | 4 | 2 | 4 || 8 | ... | Since your rolling sums depend on all values, you will have to compute one per window. This can be done using numpy and indexing lookup: import numpy as np idx, vals = pd.factorize(df['B']) df['C'] = np.vstack([ df['A'].rolling(v, min_periods=1).sum() for v in vals ])[idx, np.arange(len(df))] Output: A B C 0 1 1 1.0 ... | 2 | 3 |
78,359,610 | 2024-4-20 | https://stackoverflow.com/questions/78359610/split-array-of-integers-into-subarrays-with-the-biggest-sum-of-difference-betwee | I'm trying to find the algorithm efficiently solving this problem: Given an unsorted array of numbers, you need to divide it into several subarrays of length from a to b, so that the sum of differences between the minimum and maximum numbers in each of the subarrays is the greatest. The order of the numbers must be pr... | First let's solve a simpler problem. Let's run through an array, and give mins and maxes for all windows of fixed size. def window_mins_maxes (size, array): min_values = deque() min_positions = deque() max_values = deque() max_positions = deque() for i, value in enumerate(array): if size <= i: yield (i, min_values[0], ... | 8 | 9 |
78,359,009 | 2024-4-20 | https://stackoverflow.com/questions/78359009/calculating-min-value-with-condition | A column is added to the dataframe with min value for every item just from columns corresponding from dictionary. How can I add a condition when calculating min value - if the values in the selected columns are greater than the values in the column 'Col7'? import pandas as pd my_dict={'Item1':['Col1','Col3','Col6'], 'I... | You can get the minimum value and column name by adapting the answer given to your earlier question, passing a default value to min for the case where the condition causes there to be no matching columns: df[['min', 'name']] = df.apply( lambda r:min(((r[col], col) for col in my_dict.get(r['Col0'], []) if col in r and r... | 3 | 1 |
78,355,086 | 2024-4-19 | https://stackoverflow.com/questions/78355086/pandas-rolling-closest-value | Suppose we have the following dataframe: timestamp open high low close delta atr last_index bearish bullish_turning_point 2 04-10-2024 01:54:44 18370.00 18377.75 18367.50 18376.00 32 0 1949 False True 5 04-10-2024 03:21:14 18376.50 18383.00 18375.25 18381.25 28 0 3899 False True 7 04-10-2024 04:38:54 18378.50 18386.25... | If you want to include the current row's open in the closest open values, you can do this: df['nearest'] = [(abs(df.loc[:i, 'open'] - close)).idxmin() for i, close in df['close'].items()] Output: [2, 5, 7, 9, 7, 5, 7, 22, 25, 25, 30, 30, 43, 46, 49, 14, 5, 14, 9, 28] If you don't want to include the current row's ope... | 2 | 2 |
78,358,646 | 2024-4-20 | https://stackoverflow.com/questions/78358646/how-to-compare-hierarchy-in-2-pandas-dataframes-new-sample-data-updated | I have 2 dataframes that captured the hierarchy of the same dataset. Df1 is more complete compared to Df2, so I want to use Df1 as the standard to analyze if the hierarchy in Df2 is correct. However, both dataframes show the hierarchy in a bad way so it's hard to know the complete structure row by row. Eg. Company A ma... | Basically, you'll need to build a network graph of df1 to get a comprejhension map of the hierarchies. Once this is done, you need to compare the hierarchies of df2 with those of df1 and finally validate. To do so, you can define function. You'll create a new column hierarchies to df1 and Right/Wrong, Reason to df2. . ... | 2 | 1 |
78,359,422 | 2024-4-20 | https://stackoverflow.com/questions/78359422/trying-to-find-pythonic-way-to-partially-fill-numpy-array | I have a numpy array psi of shape (3,1000) psi.__class__ Out[115]: numpy.ndarray psi.shape Out[116]: (3, 1000) I want to partially fill psi with another array b b.__class__ Out[113]: numpy.ndarray b.shape Out[114]: (3, 500) I can do this with a loop: for n in range(3): psi[n][:500] = b[n] But it seems to me that the... | You can use: psi[:, :500] = b Or, if n (=3) in your loop does not match the first dimension of b: idx = np.arange(3) psi[idx, :500] = b[idx] Comparing the two approaches (psi1 with the loop, psi2 as vectorial assignment): np.allclose(psi1, psi2) # True | 2 | 2 |
78,358,193 | 2024-4-20 | https://stackoverflow.com/questions/78358193/struggling-to-position-objects-correctly-in-manim | My end goal with this program is to simulate constrained pendulums with springs but that is a goal for later, currently I have been trying to learn how object creation, positioning and interactions would work and will eventually build the way up. Currently I have been trying to make my code produce N number of independ... | This is a classical example of a good question. You were almost complete in your code. I made a few change to it, and as I was doing this in google.colab, there might be some things that you'll need to add, import numpy as np import manim as mn class Pendulum: g = -9.81 def __init__(self, mass, length, theta): self.mas... | 2 | 1 |
78,358,268 | 2024-4-20 | https://stackoverflow.com/questions/78358268/how-to-remove-indexing-past-lexsort-depth-may-impact-performance | I've a dataframe with a non-unique MultiIndex: A B L1 L2 7.0 7.0 -0.4 -0.1 8.0 5.0 -2.1 1.6 5.0 8.0 -1.8 -0.8 7.0 7.0 0.5 -1.2 NaN -1.1 -0.9 5.0 8.0 0.6 2.3 I want to select some rows using a tuple of values: data = df.loc[(7, 7), :] With no surprise a warning is triggered: PerformanceWarning: indexing past lexsort ... | I got rid of the warning by sorting the index and putting the NaN values first: df.sort_index(inplace=True, na_position="first") data = df.loc[(7, 7), :] print(data) Prints: A B L1 L2 7.0 7.0 -0.4 -0.1 7.0 0.5 -1.2 I think the issue is with the NaN value you have in index. Pandas has special index.codes for each un... | 4 | 6 |
78,354,782 | 2024-4-19 | https://stackoverflow.com/questions/78354782/how-to-use-returns-context-requirescontext-with-async-functions-in-python | I am very fond of the returns library in python, and I would like to use it more. I have a little issue right now. Currently, I have a function that uses a redis client and gets the value corresponding to a key, like so: from redis import Redis from returns.context import RequiresContext def get_value(key: str) -> Requ... | If you call a function (get_value) defined with async def you get an awaitable which you must use with await to get its return value. That's why you get the error. But get_value shouldn't be async def. It just defines and returns a function (wrapped by RequiresContextFutureResultE), it doesn't perform any IO itself. | 2 | 2 |
78,357,085 | 2024-4-20 | https://stackoverflow.com/questions/78357085/welford-variance-differs-from-numpy-variance | I want to use Welford's method to compute a running variance and mean. I came across this implementation of Welford's method in Python. However, when testing to double-check that it results in the same output as the standard Numpy implementation of calculating variance, I do find that there is a difference in output. R... | By default, np.var computes the so-called "population variance", in which the number of degrees of freedom is equal to the number of elements in the array. wellford.var_s is the sample variance, in which the number of degrees of freedom is the number of elements in the array minus one. To eliminate the discrepancy, pas... | 2 | 6 |
78,356,546 | 2024-4-19 | https://stackoverflow.com/questions/78356546/how-to-highly-optimize-correlation-calculations-using-pandas-dataframes-and-s | I want to calculate pearson correlations of the columns of a pandas DataFrame. I don't just want to use DataFrame.corr() because I also need the pvalue of the correlation; therefore, I am using scipy.stats.pearsonr(x, y). My problem right now is that my dataframe is huge (shape: (1166, 49262)), so I'm looking at (49262... | You can obtain about a 200x speedup by using pd.corr() plus converting the R values into a probability with a beta distribution. I would suggest implementing this by looking at how SciPy did it and seeing if there are any improvements which are applicable to your case. The source code can be found here. This tells you ... | 2 | 5 |
78,344,470 | 2024-4-18 | https://stackoverflow.com/questions/78344470/how-to-have-a-programmatical-conversation-with-an-agent-created-by-agent-builder | I created an agent with No Code tools offered by the Agent Builder GUI: https://vertexaiconversation.cloud.google.com/ I created a playbook and added a few Data store Tools for the agent to use for RAG. I'd like to call this agent programmatically to integrate it into mobile apps or web pages. There's a lot of code rel... | Looks like the "traditional" Dialogflow CX API calls can invoke an Agent Builder agent: import uuid from google.cloud.dialogflowcx_v3beta1.services.agents import AgentsClient from google.cloud.dialogflowcx_v3beta1.services.sessions import SessionsClient from google.cloud.dialogflowcx_v3beta1.types import session PROJEC... | 2 | 4 |
78,337,963 | 2024-4-17 | https://stackoverflow.com/questions/78337963/pytest-two-async-functions-both-with-endless-loops-and-await-commands | I am unit testing a python code. It has an asyncio loop. The main two functions in this loop have endless while loops. I have tested the non-async parts of the code. I am wondering what is the best strategy to unit test these two functions: import asyncio def main(): loop = asyncio.get_event_loop() loop.run_until_compl... | Both functions are not "endless" - the first will end when the generator returned by sync_receive_data_packets is exhausted, and the other whenever termination_signal_received() returns True. Just use mock.patch to point these two functions to callables under the control of your tests. Your tests should further verify ... | 2 | 2 |
78,354,608 | 2024-4-19 | https://stackoverflow.com/questions/78354608/instagram-api-on-python-missing-client-id-parameter | I am trying to get a long-lived access token from the Instagram graph API through a python script. No matter what I do, I keep receiving the following error: {"error":{"message":"Missing client_id parameter.","type":"OAuthException","code":101,"fbtrace_id":"AogeGpzZGW9AwqCYKHlmKM"}} My script is the following: import ... | The Postman called by GET parameters. In modified version, the params argument is used instead of data. This change will append the parameters in payload to the URL as a query string, So your code needs to change it import requests refresh_token_url = 'https://graph.facebook.com/v19.0/oauth/access_token' payload = { 'g... | 2 | 1 |
78,350,869 | 2024-4-19 | https://stackoverflow.com/questions/78350869/is-there-a-pythons-f-string-equivalent-in-matlab | I am wondering if there is a way to type and format strings in Matlab like how you have f-strings in Python: Python input: username = lemslems text = f"Hello {username}!" Output: Hello lemslems! I am asking this because I hate writing in the % format and it is just super convenient to write it like how I always do in... | Matlab doesn't have a direct equivalent to Python's f-strings, but you can achieve similar functionality using string formatting or concatenation. One way to do this is by using the sprintf function, which formats data into strings: name = 'John'; age = 30; formatted_string = sprintf('My name is %s and I am %d years ol... | 2 | 4 |
78,351,871 | 2024-4-19 | https://stackoverflow.com/questions/78351871/incompatible-dtype-in-dataframe | I am developing a python app and I'm working with pandas dataframe. Unfortunately, I have this warning: "Setting an item of incompatible dtype is deprecated and will raise an error in a future version of pandas. Value '[149.7 149.7 149.7 149.7]' has dtype incompatible with float64, please explicitly cast to a compatib... | You assigning data types that are not strictly floats to AuM that is set as a float when initialized with 0. Assign the correct data type to AuM: import numpy as np import pandas as pd df1['Date'] = pd.to_datetime(pd.date_range(simulationDate, end=fees:TQDeferred['Valuation date'].iloc[-1], freq='MS', inclusive='both')... | 2 | 1 |
78,349,268 | 2024-4-18 | https://stackoverflow.com/questions/78349268/changing-command-order-in-pythons-typer | I want Typer to display my commands in the order I have initialized them and it displays those commands in alphabetic order. I have tried different approaches including this one: https://github.com/tiangolo/typer/issues/246 In this I get AssertionError. Others like subclassing some Typer and click classes does actually... | All right I have found solution elsewhere, while trying to post the ticket to Typer (they have a really comprehensive troubleshooting!) https://github.com/tiangolo/typer/issues/428 The app that displays commands in the order I want them displayed looks like this: import typer from click import Context from typer.core i... | 2 | 3 |
78,349,687 | 2024-4-18 | https://stackoverflow.com/questions/78349687/how-do-you-turn-pairs-from-a-dataframe-column-into-two-new-columns | I've been trying to take a DataFrame like df below, and turning some of the columns (say B_m and B_n) into two columns (call them B_m1, B_m2, B_n1 and B_n2), for each pair of values in that column (akin to itertools.combinations(col, r=2)), where they share the same group number. So for B_m, the rows where Group is 0, ... | Here is an approach with groupby.apply and concat: from itertools import combinations cols = ['B_m', 'B_n'] group = list(df.columns.difference(cols, sort=False)) g = df.groupby(group, sort=False) out = pd.concat((g[c].apply(lambda x: pd.DataFrame(list(combinations(x, r=2)))) .rename(columns=lambda x: f'{c}{x+1}') for c... | 2 | 1 |
78,350,242 | 2024-4-18 | https://stackoverflow.com/questions/78350242/uninstall-last-pip-installed-packages | I have just installed a package in my virtual environment which I shouldn't have installed. It also installed many dependency packages. Is there a way to roll back and uninstall the package and its dependencies just installed? Something like "uninstall packages installed in the last 1 hour" or a similar functionality. | Below snippet can help you identify the recently installed pacakage. Once you have the list of packages, you can manually uninstall that pacakge. import pkg_resources import os import time for package in pkg_resources.working_set: print("%s: %s" % (package, time.ctime(os.path.getctime(package.location)))) | 2 | 3 |
78,350,133 | 2024-4-18 | https://stackoverflow.com/questions/78350133/what-is-the-correct-type-annotation-for-bytes-or-bytearray | In Python 3.11 or newer, is there a more convenient type annotation to use than bytes | bytearray for a function argument that means "An ordered collection of bytes"? It seems wasteful to require constructing a bytes from a bytearray (or the other way around) just to satisfy the type-checker. Note that the function doe... | The typing module used to have a type to represent this: ByteString. However, it was deprecated in 3.9. From the same section: Prefer collections.abc.Buffer, or a union like bytes | bytearray | memoryview. | 2 | 4 |
78,343,764 | 2024-4-17 | https://stackoverflow.com/questions/78343764/json-text-as-command-line-argument-when-running-python-script | I have read similar questions relating to passing JSON text as a command line argument with python, but none of the solutions have worked with my case. I am automating a python script, and the automation runs a powershell script that takes a JSON object generated from a power automate flow. Everything works great until... | Depending on the PowerShell version you're using, you will need to handle it differently, if using pwsh 7.3+ the solution is as simple as wrapping your Json string with single-quotes. Otherwise, if using below that, you would need to escape the double-quotes with \, otherwise those get eaten when passed thru your Pytho... | 2 | 2 |
78,344,344 | 2024-4-18 | https://stackoverflow.com/questions/78344344/pywinauto-throwing-an-memoryerror-on-windows-11-but-not-on-windows-10 | I have this code that works properly on windows 10 that I use to send text and enter keys to a specific window using pywinauto, but once i tried to use it in another system using win 11 it does not work. Here is the code: import pywinauto import time boolBisCheckbox = False def parar(eachFfox): global boolBisCheckbox i... | I just identified the culprit, thank you so much for your insights Vasily Ryabov ! It was SteelSeriesGG.exe app for the keyboard (bloatware **** ...), even in the tray it was somehow messing with it. | 2 | 1 |
78,341,348 | 2024-4-17 | https://stackoverflow.com/questions/78341348/find-the-minimum-and-maximum-possible-sum-for-a-given-number-from-an-integer-ar | There is an ordered array of integer elements and a limit. It is necessary to find the minimum possible and maximum possible sum that can greater or equal the limit, for the given elements. The minimum sum is the minimum sum of the sequence greater or equal than limit The maximum sum, is the sum of the sequence that sa... | I assume that you need to always start at the beginning of your sequence. Your examples were still not clear on that. If that is true then this should work: import heapq def min_max_limit_sum (arr, limit): # A path will be (idx_k, ...(idx_1, (idx_0, None))...) # By (value, index): path known = {} # heap of (value, coun... | 2 | 2 |
78,340,305 | 2024-4-17 | https://stackoverflow.com/questions/78340305/gekko-parameter-identification-on-a-spring-mass-system | I want to do parameter estimation on a Spring-Mass system with direct collocation method. The parameter k should be determined from response. I simulated this system by from scipy.integrate import odeint import numpy as np def dy(y, t): x, xdot = y return [xdot, -50*x] t = np.linspace(0, 1, 40) sol = odeint(dy, [2.0, ... | The -0.39 is a local minimum to the optimization problem. As the initial guess is further from the solution, it finds a different local solution. To prevent non-physical solutions, add a constraint for the solver to search only within bounds. This can be done during initialization with: k = m.FV(value=ki,lb=10,ub=100) ... | 3 | 1 |
78,342,121 | 2024-4-17 | https://stackoverflow.com/questions/78342121/how-can-i-make-playwright-waits-until-a-specific-cookie-appears-and-then-return | I'm making a python script that requests the user for their cookie through playwright webdriver This is my dummy code import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=False) context = await... | You could use wait_for_function: await page.wait_for_function("document.cookie.includes('account_cookie')") | 2 | 2 |
78,341,579 | 2024-4-17 | https://stackoverflow.com/questions/78341579/using-list-of-lists-of-indices-to-slice-columns-and-obtain-the-row-wise-vector-l | I have an NxM array, as well as an arbitrary list of sets of column indices I'd like to use to slice the array. For example, the 3x3 array my_arr = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) and index sets my_idxs = [[0, 1], [2]] I would like to use the pairs of indices to select the corresponding columns from the a... | You can try: my_arr = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) my_idxs = [[0, 1], [2]] out = np.c_[*[np.linalg.norm(my_arr[:, i], axis=1) for i in my_idxs]] print(out) Prints: [[2.23606798 3. ] [2.23606798 3. ] [2.23606798 3. ]] | 2 | 3 |
78,340,572 | 2024-4-17 | https://stackoverflow.com/questions/78340572/why-does-groupby-with-dropna-false-prevent-a-subsequent-multiindex-dropna-to-w | My understanding is MultiIndex.dropna() removes index entries for which at least one level is NaN, there are no conditions. However it seems if a previous groupby was used with dropna=False, it's no longer possible to use MultiIndex.dropna(). What are the reasons for the different behavior? How to drop the NaN entries... | Looking at the sources of pd.MultiIndex.dropna() reveals that there are codes for each value of index. Pandas expects code value -1 for NaN, which apparently is not the case when doing .groupby() (a bug?). You can avoid this issue by reconstructing the index and then drop NaN values, e.g.: df = df.groupby(["L1", "L2"],... | 4 | 4 |
78,339,449 | 2024-4-17 | https://stackoverflow.com/questions/78339449/what-is-the-best-approach-to-compute-bruns-constant-with-python-witch-include | Brun's constant : https://en.wikipedia.org/wiki/Brun%27s_theorem http://numbers.computation.free.fr/Constants/Primes/twin.html How to compute Brun's constant up to 10^20 with python knowing that primality check has a heavy cost and summing result up to 10^20 is a long task here is my 2 cents attempt : IsPrime : fastest... | Now, if you remember your classes in number theory there is something called sieve of Eratosthenes which is an algorithm to find all prime numbers up to any given limit: algorithm Sieve of Eratosthenes is input: an integer n > 1. output: all prime numbers from 2 through n. let A be an array of Boolean values, indexed b... | 2 | 3 |
78,339,087 | 2024-4-17 | https://stackoverflow.com/questions/78339087/is-it-possible-to-have-a-default-value-that-depends-on-a-previous-parameter | Suppose I want to write a recursive binary search function in Python. The recursive function needs to get the start and end of the current search interval as parameters: def binary_search(myarray, start, end): ... But, when I call the actual function from outside, I always start at 0 and finish at the end of the array... | The common idiom* is: def binary_search(myarray, start=0, end=None): if end is None: end = len(myarray) *(usually used to avoid a mutable default argument value, like here: https://stackoverflow.com/a/41686973/5052365) | 2 | 4 |
78,322,897 | 2024-4-14 | https://stackoverflow.com/questions/78322897/why-does-this-code-use-more-and-more-memory-over-time | Python: 3.11 Saxonche: 12.4.2 My website keeps consuming more and more memory until the server runs out of memory and crashes. I isolated the problematic code to the following script: import gc from time import sleep from saxonche import PySaxonProcessor xml_str = """ <root> <stuff>Lorem ipsum dolor sit amet, consectet... | It looks like a memory leak. I created a bug to track it: https://saxonica.plan.io/issues/6391 And the issue is now fixed in the released SaxonC 12.5. | 4 | 3 |
78,316,570 | 2024-4-12 | https://stackoverflow.com/questions/78316570/docker-docker-compose-and-pycharm-debug-port-conflict | I Am trying to set up the debug environment for Pycharm and Python(Fastapi) in Docker (with docker-compose). But I stuck into the problem that I cannot launch both: the debug server and the docker image. My setup of the entry point of the app: # import debugpy # debugpy.listen(('0.0.0.0', 5678)) # debugpy.wait_for_clie... | Replace 'localhost' with 'host.docker.internal' (at least on a Mac) Remove any port forward for port 5678 (so Docker won't try to allocate it) Use this in the code: import pydevd_pycharm pydevd_pycharm.settrace('host.docker.internal', port=5678, stdoutToServer=True, stderrToServer=True) You might also want to take a... | 2 | 1 |
78,311,513 | 2024-4-11 | https://stackoverflow.com/questions/78311513/train-neural-network-for-absolute-function-with-minimum-layers | I'm trying to train neural network to learn y = |x| function. As we know the absolute function has 2 different lines connecting with each other at point zero. So I'm trying to have following Sequential model: Hidden Layer: 2 Dense Layer (activation relu) Output Layer: 1 Dense Layer after training the model,it only fits... | It depends on the weight initialization. If both weights of are initilized with positive numbers, the network can only predict positive numbers. For negative numbers, it will always output zero. This will also result no gradients - there is no small step to the weights that would make the output match a bit better. So ... | 5 | 1 |
78,336,104 | 2024-4-16 | https://stackoverflow.com/questions/78336104/ckeditor-is-not-good-for-django-anymore | before ckeditor worked for django but now it is not working and expired. django by itself suggest non-free ckeditor 4 LTS or ckeditor 5 but I don't know how to use it please if there is give me another editor for django or guide me for this ckeditor. it is the warning message: WARNINGS: ?: (ckeditor.W001) django-ckedit... | You can use github.com/hvlads/django-ckeditor You can install it with pip install django-ckeditor-5 further instructions can be found on the github page. | 2 | 3 |
78,313,930 | 2024-4-12 | https://stackoverflow.com/questions/78313930/generic-type-hinting-for-kwargs | I'm trying to wrap the signal class of blinker with one that enforces typing so that the arguments to send and connect get type-checked for each specific signal. eg if I have a signal user_update which expects sender to be an instance of User and have exactly two kwargs: time: int, audit: str, I can sub-class Signal to... | After a lot of trial an error, I've found a relatively simple solution, although it depends on mypy_extensions which is deprecated so this may not be entirely future-proof, although it still works on the latest mypy version. Essentially, using mypy's NamedArg allows defining kwargs in a Callable, enabling us to simply ... | 2 | 0 |
78,329,987 | 2024-4-15 | https://stackoverflow.com/questions/78329987/numba-dispatch-on-type | I would like to dispatch on the type of the second argument in a function in numba and fail in doing so. If it is an integer then a vector should be returned, if it is itself an array of integers, then a matrix should be returned. The first code does not work @njit def test_dispatch(X, indices): if isinstance(indices, ... | You should not use isinstance in a JIT function like this, but instead use @overload (@generated_jit was the old obsolete way to do that) which is specifically made for this purpose. This enables Numba to generate the code faster since only a part of the function is compiled for each case rather than all the case for e... | 2 | 1 |
78,305,720 | 2024-4-10 | https://stackoverflow.com/questions/78305720/how-to-overlap-a-geopandas-dataframe-with-basemap | I have a shapefile that I read as a geopandas dataframe import geopandas as gpd gdf = gpd.read_file('myfile.shp') gdf.plot() where gdf.crs <Projected CRS: ESRI:54009> Name: World_Mollweide Axis Info [cartesian]: - E[east]: Easting (metre) - N[north]: Northing (metre) Area of Use: - name: World. - bounds: (-180.0, -90... | That's because the Mollweide projection's parameters (i.e, the proj-string) used by the Basemap are different from the ones of your GeoDataFrame (that is ESRI:54009) : >>> gdf.crs.srs 'esri:54009' >>> map.srs '+proj=moll +R=6370997.0 +units=m +lat_0=0.0 +lon_0=0.0 +x_0=18019900...' A simple fix would be to call to_crs... | 4 | 6 |
78,332,981 | 2024-4-16 | https://stackoverflow.com/questions/78332981/memory-leak-when-integrityerror-occurs | I am developing an API which accesses a MariaDB. I use SQLAlchemy for DB-access and encountered a strange memory leak while inserting data. When I insert data and there is no error, everything is normal. RAM consumption goes up but when the transaction is finished it goes down again as expected. That is not the case wh... | Ok, after hours and hours of research and many different tries I finally found a solution for this problem. It was no problem with SQLAlchemy, this was Pythons behaviour in exception handling. When the exception occurs, it builds up a stack traceback and since the exception traceback is so large due to the large number... | 2 | 2 |
78,313,566 | 2024-4-12 | https://stackoverflow.com/questions/78313566/including-a-select-all-feature-in-dash-plotly-callback-python | I've got a plotly bar chart that's connected to a callback to allow filtering. Using below, filtering is done on the Type column. Issue: The real data I actually filter on contains thousands of items. I want to show all data initially but don't want to visualise all individual items in the dropdown bar (because there a... | Your selection processing is OK, but you are missing an update of the Dropdown component. Also, in the case of adding something else to Select all option, you probably want to only purge the selection only, but keep the graph unchanged. It can be noted, that there are opposite cases, that end up with the similar select... | 3 | 1 |
78,318,223 | 2024-4-12 | https://stackoverflow.com/questions/78318223/change-keyboardinterrupt-to-enter | I have the following code: import time def run_indefinitely(): while True: # code to run indefinitely goes here print("Running indefinitely...") time.sleep(1) try: # Run the code indefinitely until Enter key is pressed run_indefinitely() except KeyboardInterrupt: print("Loop interrupted by user") Is there a way to bre... | This is surprisingly tricky to do in Python. The technique involves spawning a worker thread to interrupt us later. Using python-readchar: import os import signal import sys import time from threading import Timer from readchar import readkey # pip install readchar def wait_for(key, timeout): """wait `timeout` seconds ... | 2 | 4 |
78,335,363 | 2024-4-16 | https://stackoverflow.com/questions/78335363/converting-a-binary-to-a-string-variable-in-polars-python-library-with-non-utf | I'm having trouble manipulating a dataset in Python which has non-UTF-8 characters. The strings are imported as a binary. But I am having issues converting the binary columns to strings where a cell has non UTF-8 characters. A minimal working example of my issue is import polars as pl import pandas as pd pd_df = pd.Dat... | This solution also relies on applying python's native bytes.decode to all elements in the columns of type pl.Binary. Unfortunately, we cannot yet use polars' native expression API for this, but need to call pl.Expr.map_elements instead. df.with_columns( pl.col(pl.Binary).map_elements( lambda bytes: bytes.decode(errors=... | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.