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 |
|---|---|---|---|---|---|---|
75,761,216 | 2023-3-16 | https://stackoverflow.com/questions/75761216/how-can-i-create-an-avro-schema-from-a-python-class | How can I transform my simple python class like the following into a avro schema? class Testo(SQLModel): name: str mea: int This is the Testo.schema() output { "title": "Testo", "type": "object", "properties": { "name": { "title": "Name", "type": "string" }, "mea": { "title": "Mea", "type": "integer" } }, "required": ... | It looks like there are a few libraries that aim to provide this kind of functionality: py-avro-schema has support for generic Python classes dataclasses-avroschema has support for dataclasses, pydantic models, and faust records pydantic-avro requires your Python class to inherit from pydantic.BaseModel | 3 | 3 |
75,785,663 | 2023-3-19 | https://stackoverflow.com/questions/75785663/mkdocs-mkdocstrings-add-link-back-to-github-source-code | I am making docs for my Python code with mkdocs and mkdocstrings. I would like to have link from the docs to the source code (page and line number on github). Is there a way to automatic add that with function/class syntax (e.g., '::: identifier')? I am looking for something similar to 'SciPy' docs, where they have [so... | You can find inspiration in this archived repository: https://github.com/AI2Business/mkdocstrings-sourcelink. As of now (2023/07/06) there's no built-in way to achieve that. VCS support might happen in the future :) (source: am maintainer). | 5 | 1 |
75,793,794 | 2023-3-20 | https://stackoverflow.com/questions/75793794/adding-getitem-accessor-to-python-class-method | I'm attempting to add an item getter (__getitem__, to provide the [] syntax) to a class method so that I can use some unique-ish syntax to provide types to functions outside the normal parentheses, like the following. The syntax on the last line (of this first snippet) is really the goal for this whole endeavor. class ... | I never thought I would use a Python class this way, but if the pattern fits... I put a cleaned-up example of the below answer in this github gist that shows the same implementation and usage. The issue I was having was that the class instance reference (self) was being overridden due to the reassignment of the functi... | 3 | 0 |
75,804,182 | 2023-3-21 | https://stackoverflow.com/questions/75804182/valueerror-object-has-no-field-when-using-monkeypatch-setattr-on-a-pydantic-bas | I usually can patch methods of normal objects using pytest monkeypatch. However when I try with a pydantic.BaseModel it fails. from pydantic import BaseModel class Person(BaseModel): name: str age: int def intro(self) -> str: return f"I am {self.name}, {self.age} years old." def test_person_intro(monkeypatch): p = Pers... | You could patch the type: def test_person_intro(monkeypatch): p = Person(name='Joe', age=20) monkeypatch.setattr(Person, 'intro', lambda self: 'patched intro') assert p.intro() == 'patched intro' Or you could set item in the instance dict: def test_person_intro(monkeypatch): p = Person(name='Joe', age=20) monkeypatch.... | 4 | 4 |
75,773,786 | 2023-3-18 | https://stackoverflow.com/questions/75773786/why-cant-i-access-gpt-4-models-via-api-although-gpt-3-5-models-work | I'm able to use the gpt-3.5-turbo-0301 model to access the ChatGPT API, but not any of the gpt-4 models. Here is the code I am using to test this (it excludes my openai API key). The code runs as written, but when I replace "gpt-3.5-turbo-0301" with "gpt-4", "gpt-4-0314", or "gpt-4-32k-0314", it gives me an error opena... | Currently the GPT 4 API is restricted, Even to users with a Chat GPT + subscription. You may need to join the Waitlist for the API. | 20 | 18 |
75,804,781 | 2023-3-21 | https://stackoverflow.com/questions/75804781/how-to-create-pyspark-dataframes-from-pandas-dataframes-with-pandas-2-0-0 | I normally use spark.createDataFrame() which used to throw me deprecated warnings about iteritems() call in earlier version of Pandas. With pandas 2.0.0 it doesn't work at all, resulting in an error below: AttributeError Traceback (most recent call last) File <command-2209449931455530>:64 61 df_train_test_p.loc[df_trai... | This is currently a broken dependency. The issue was recently merged. It will be released in pyspark==3.4. Unfortunately, only pyspark==3.3.2 is available in pypi at the moment . But since pandas==2.0.0 was just released in pypi today (as of April 3, 2023), the current pyspark appears to be temporarily broken. The only... | 3 | 3 |
75,797,278 | 2023-3-21 | https://stackoverflow.com/questions/75797278/playing-a-video-with-captions-in-jupyter-notebook | How to play a video with captions in Jupyter notebook? With code snippets from these post, I've tried to play a video inside jupyter notebook: How can I play a local video in my IPython notebook? how play mp4 video in google colab from IPython.display import HTML # Show video compressed_path = 'team-rocket.video-comp... | Try this: from IPython.display import HTML from base64 import b64encode video_path = 'team-rocket.video-compressed.mp4' captions_path = 'team-rocket.vtt' with open(video_path, 'rb') as f: video_data = f.read() video_base64 = b64encode(video_data).decode() with open(captions_path, 'r') as f: captions_data = f.read() cap... | 4 | 5 |
75,804,180 | 2023-3-21 | https://stackoverflow.com/questions/75804180/how-to-do-a-qcut-by-group-in-polars | Consider the following example zz = pl.DataFrame({'group' : ['a','a','a','a','b','b','b'], 'col' : [1,2,3,4,1,3,2]}) zz Out[16]: shape: (7, 2) ┌───────┬─────┐ │ group ┆ col │ │ --- ┆ --- │ │ str ┆ i64 │ ╞═══════╪═════╡ │ a ┆ 1 │ │ a ┆ 2 │ │ a ┆ 3 │ │ a ┆ 4 │ │ b ┆ 1 │ │ b ┆ 3 │ │ b ┆ 2 │ └───────┴─────┘ I am trying to... | Update: Series.qcut was added in polars version 0.16.15 As it's not available on expressions as of yet, you could .partition_by pl.concat( frame.get_column("col") .qcut([.5], maintain_order=True) .select(pl.col("category").to_physical()) for frame in df.partition_by("group") ) shape: (7, 1) ┌──────────┐ │ category │ │... | 4 | 1 |
75,747,156 | 2023-3-15 | https://stackoverflow.com/questions/75747156/invalid-json-given-in-the-body-of-the-request-expected-a-map-when-using-rese | I am trying to change an existing job settings using the cli but when I invoke the reset_job method I am getting this error: Traceback (most recent call last): File "/home/vsts/work/1/s/S1.DataPlatform.DR/main.py", line 78, in <module> dr.experiment(host,token) File "/home/vsts/work/1/s/S1.DataPlatform.DR/main.py", lin... | The payload that you're using is only for the Job Get response - you can't use it as-is for resetting the job. If you look into the Job Reset API, you will see that the payload consists only of two fields: job_id - ID of the job to reset new_settings - settings to set for the job, while you use the settings. { "job_i... | 3 | 3 |
75,795,170 | 2023-3-20 | https://stackoverflow.com/questions/75795170/how-to-design-codeforces-interactive-grader | I came across one interactive problem in Codeforces. I want to know how the grader or interactor (as per Codeforces' terms) might be designed. Let's say I want to create a grader for this problem: 1. Guess the Number. My solution to the above problem is stored in 1_Guess_the_Number.py file. It is a correct solution and... | The comment from @user2357112 describes correctly why it is not working. While your pipe is sending the output of the first script to the grader, you're not sending 'grader.py''s responses to the first script. So what we need to do is to establish a two way communication. Here is one way to do it. In the grader, call t... | 7 | 3 |
75,749,584 | 2023-3-15 | https://stackoverflow.com/questions/75749584/how-can-i-convert-a-yolov8s-model-to-coreml-model-using-a-custom-dataset | I have trained a YOLOv8 object detection model using a custom dataset, and I want to convert it to a Core ML model so that I can use it on iOS. After exporting the model, I have a converted model to core ml, but I need the coordinates or boxes of the detected objects as output in order to draw rectangular boxes around ... | To get the cordinates as output use nms=True from ultralytics import YOLO model=YOLO('best.pt') model.export(format='coreml',nms=True) or yolo export model=path/to/best.pt format=onnx nms=True This will give a option to preview your model in Xcode , and the output will return coordinates | 8 | 6 |
75,747,955 | 2023-3-15 | https://stackoverflow.com/questions/75747955/transcription-via-openais-whisper-assertionerror-incorrect-audio-shape | I'm trying to use OpenAI's open source Whisper library to transcribe audio files. Here is my script's source code: import whisper model = whisper.load_model("large-v2") # load the entire audio file audio = whisper.load_audio("/content/file.mp3") #When i write that code snippet here ==> audio = whisper.pad_or_trim(audio... | I had the same problem and after some digging I found that whisper.decode is meant to extract metadata about the input, such as the language, and hence the limit to 30 seconds. (see source code for decode function here) In order to transcribe (even audio longer than 30 seconds) you can use whisper.transcribe as shown i... | 4 | 6 |
75,803,317 | 2023-3-21 | https://stackoverflow.com/questions/75803317/what-is-the-most-efficient-way-of-computing-abs2-of-a-complex-numpy-ndarray | I'm looking for the most time-efficient way of computing the absolute squared value of a complex ndarray in python. arr = np.empty((8, 4000), dtype="complex128") # typical size I have tried these options: # numpy implementation def abs2_numpy(x): return x.real**2 + x.imag**2 # numba implementation @numba.vectorize([n... | The execution time of the provided function is very challenging. In this case, the best solution to find if there is a better possible implementation is to look the generated assembly code since trying to write many alternative function blindly is a wast of time if the generated assembly code is close to be optimal. In... | 4 | 1 |
75,807,298 | 2023-3-21 | https://stackoverflow.com/questions/75807298/sympy-drop-terms-with-small-coefficients | Is it possible to drop terms with coefficients below a given, small number (say 1e-5) in a Sympy expression? I.e., such that 0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u) becomes 0.25 + 8.5*exp(-2.6*u) + 1.2*exp(-0.1*u) for instance. | You can use a combination of coeffs, subs and Poly: u = Symbol('u') poly = Poly(0.25 + 8.5*exp(-2.6*u) - 2.7e-17*exp(-2.4*u) + 1.2*exp(-0.1*u)) threshold = 1e-5 to_remove = [abs(i) for i in poly.coeffs() if abs(i) < threshold] for i in to_remove: poly = poly.subs(i, 0) poly no yields the following: 0.25 + 8.5*exp(-2.6... | 3 | 2 |
75,806,691 | 2023-3-21 | https://stackoverflow.com/questions/75806691/python-groupby-columns-and-apply-function | I have a dataframe that looks like this which contains all divisions and both conferences from 2000-2022. Tm Conference Division W-L%. Year Bills AFC East 0.813 2022 Dolphins AFC East 0.529 2022 Patriots AFC East 0.471 2022 Jets AFC East 0.412 2022 Cowboys NFC East 0.706 2022 Giants NFC East 0.559 2022 Eagles NFC East ... | You can use transform instead of apply. Compute the sum for the group and subtract the W-L%. of the current row then divide by the size of the group minus 1 (because you want to exclude the row itself): df['Division W-L%'] = (df.groupby(['Conference', 'Division', 'Year'])['W-L%.'] .transform(lambda x: (x.sum() - x) / (... | 3 | 3 |
75,804,936 | 2023-3-21 | https://stackoverflow.com/questions/75804936/pytest-caplog-for-testing-logging-formatter | I'm using a logging formatter to redact passwords. I want to write a test to confirm that the logging redactor is effective. In this example I simplified the code to redact "foo". With this redactor code in the my my_logger.py module (simplified redaction of a specific word): class RedactFoo: def __init__(self, base_fo... | The caplog fixture works by injecting its own LogCaptureHandler to the logging framework configuration. That's how it is able to intercept log records and provide the events at caplog.text, caplog.records, caplog.record_tuples etc which the user can make assertions against. Note that it is capturing stdlib LogRecord in... | 3 | 4 |
75,804,827 | 2023-3-21 | https://stackoverflow.com/questions/75804827/the-z-axis-label-is-not-showing-in-a-3d-plot | I have an issue with a 3d plot, at the moment of visualizing it. It appears without the z-axis label, but when I set a longer title, it appears: Is there any way to be able to "see" the z-axis label without modifying the title or another kind of solution to this issue? This is my code: mask1, mask2, mask3 shapes are ... | You can zoom out a bit to make the label visible. E.g.: import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(12, 4)) ax = fig.add_subplot(projection='3d') x, y = np.meshgrid(np.arange(100)*20, np.arange(100)*20) mask = np.ones(x.shape) s1 = ax.plot_surface(x, y, mask*400, linewidth=0, label='Ref... | 3 | 3 |
75,802,643 | 2023-3-21 | https://stackoverflow.com/questions/75802643/is-double-close-in-strace-necessarily-bad | I am training a neural network. Somewhere in my code base, I have a code snippet like the following: def foo(): d = {} with PIL.Image.open(img_path) as img: d["img"] = torchvision.transforms.functional.to_tensor(img) return d This code doesn't cause any problems. However, when I run my program under strace, I see that... | I would try to find out what causes this. In this particular example it seems OK, but there is room for very subtle errors. Imagine that you have a second thread, which open()s a file between the first and second close(4). It is likely, that this file descriptor get fd 4 assigned, and therefore will be closed immediate... | 3 | 3 |
75,801,560 | 2023-3-21 | https://stackoverflow.com/questions/75801560/use-bytesio-instead-of-namedtemporaryfile-with-openpyxl | I understand that with openpyxl>=3.1 function save_virtual_workbook is gone and preferred solution is using NamedTemporaryFile. I want it to be done without writing to filesystem, only in memory, just like BytesIO did. Before update I had: wb = Workbook() populate_workbook(wb) return BytesIO(save_virtual_workbook(wb)) ... | You're so close, dude. Just pass a io.BytesIO buffer to the wb.save method. import openpyxl, io # Create an in-memory bytes buffer, which is a file-like object buffer = io.BytesIO() # Create a workbook, do the shit you gotta do wb = openpyxl.Workbook() # Save the workbook to the buffer, as if it were a file on disk ope... | 3 | 2 |
75,799,722 | 2023-3-21 | https://stackoverflow.com/questions/75799722/how-to-deal-with-stack-expects-each-tensor-to-be-equal-size-eror-while-fine-tuni | I tried to fine tune a model with my personal information. So I can create a chat box where people can learn about me via chat gpt. However, I got the error of RuntimeError: stack expects each tensor to be equal size, but got [47] at entry 0 and [36] at entry 1 Because I have different length of input Here are 2 of m... | Yes seems like you didn't pad your inputs. The model expects the size to be the same for each text. So if it's too short, you pad it, and if it's too long, it should be truncated. See also https://huggingface.co/docs/transformers/pad_truncation How does max_length, padding and truncation arguments work in HuggingFace'... | 3 | 2 |
75,795,486 | 2023-3-20 | https://stackoverflow.com/questions/75795486/how-can-i-get-an-access-token-using-msal-in-python | I cannot seem to figure out how to acquire an access token using MSAL. I’ve spend time reading the source code and Microsoft documentation to no avail. I’d like to use the PublicClientApplication to acquire the token. Even when running proof of concepts with the QuickStarts using ConfidentialClientApplication I seem to... | To get your access use the acquire_token_silent or acquire_token_interactive methods of the PublicClientApplication class. Below is an example, replace the needed variables with your own. import msal app = msal.PublicClientApplication( "your_client_id", authority="https://yourtenant.b2clogin.com/yourtenant.onmicrosoft.... | 3 | 4 |
75,794,069 | 2023-3-20 | https://stackoverflow.com/questions/75794069/in-python-how-to-create-multiple-dataclasses-instances-with-different-objects-in | I'm trying to write a parser and I'm missing something in the dataclasses usage. I'm trying to be as generic as possible and to do the logic in the parent class but every child has the sames values in the end. I'm confused with what dataclasse decorator do with class variables and instances variables. I should probably... | This curious behavior is observed, since when you do: sender: VarSlice = VarSlice(3, 8) The default value here is a specific instance VarSlice(3, 8) - which is shared between all HeaderRecord instances. This can be confirmed, by printing the id of the VarSlice object - if they are the same when constructing an instanc... | 3 | 3 |
75,793,007 | 2023-3-20 | https://stackoverflow.com/questions/75793007/what-is-the-benefit-of-using-complex-numbers-to-store-graph-coordinates | I am looking at a solution to an Advent of Code puzzle that stores coordinates as complex numbers: heightmap = { complex(x, y): c for y, ln in enumerate(sys.stdin.read().strip().split("\n")) for x, c in enumerate(ln) } Then accesses them later as follows: for xy, c in heightmap.items(): for d in (1, -1, 1j, -1j): if ... | Yes, because it's easy/less to write and think about. Also means less opportunity for typos :-) I've been doing that for years, ever since I saw someone else do that. Usually not even typing the deltas explicitly but calculating them. I.e., instead of for d in (1, -1, 1j, -1j): use(z + d) do: for i in range(4): use(z ... | 4 | 5 |
75,786,523 | 2023-3-20 | https://stackoverflow.com/questions/75786523/how-to-limit-the-display-width-in-polars-so-that-wide-dataframes-are-printed-in | Consider the following example pd.set_option('display.width', 50) pl.DataFrame(data = np.random.randint(0,20, size = (10, 42)), columns = list('abcdefghijklmnopqrstuvwxyz123456789ABCDEFG')).to_pandas() You can see how nicely the columns are formatted, breaking a line after column k so that the full dataframe is print... | You can display all frame columns like so... with pl.Config() as cfg: cfg.set_tbl_cols(-1) print(df) ...which will give you a good result on the given frame if you have sufficient terminal/console/output width available. If this isn't enough, I recommend making a feature request for this on the polars GitHub repositor... | 5 | 4 |
75,785,959 | 2023-3-20 | https://stackoverflow.com/questions/75785959/assertion-failed-when-using-pyswip | I have just installed pyswip and I was testing if it is working correctly but I always get this error: Assertion failed: 0, file /home/swipl/src/swipl-devel/src/pl-fli.c, line 2637 I was using this example code: from pyswip import Prolog prolog = Prolog() prolog.assertz("father(michael,john)") I am using windows 10 py... | I faced a similar issue when getting a neurosymbolic model called DeepProbLog to run on my Windows. It'd be helpful to know which version of swipl and pyswip you have. I personally use swipl version 8.4.2 for Windows 64 bits (https://www.swi-prolog.org/download/stable?show=all) \ fork the pyswip provided by the repo ... | 3 | 3 |
75,789,383 | 2023-3-20 | https://stackoverflow.com/questions/75789383/pylint-func-max-is-not-callable | In my python code, I import func... from sqlalchemy.sql.expression import func Then, during my code I select data from a database table... select(func.max(MyTable.my_datetime)) ...where my_datetime is a DateTime data type... from sqlalchemy.types import DateTime my_datetime = Column('my_datetime', DateTime) The code... | The Pylint error you have (func.max is not callable Pylint(E1102:not-callable)) is a false positive and you can ignore it in your case. Pylint is flagging func.max not callable because it can't analyze the func object statically and determine that it has a max method. You can use func: Callable after importing . | 9 | 11 |
75,781,862 | 2023-3-19 | https://stackoverflow.com/questions/75781862/running-alembic-command-cause-importerror-cannot-import-name-bindparamclause | This happens whenever I ran any alembic command. I am using sqlalchemy version 2.0.3 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/ado/anaconda3/lib/python3.8/site-packages/alembic/__init__.py", line 8, in <module> from . import op # noqa File "/home/ado/anaconda3/lib/python3.8/site... | Solved after uninstalling alembic and reinstalling it afresh I ran: pip3 uninstall alembic pip3 install alembic | 4 | 10 |
75,787,164 | 2023-3-20 | https://stackoverflow.com/questions/75787164/expected-type-iterablesupportslessthan-any-matched-generic-type-iterable | The two following blocks of code should be equivalent: Block 1 array_1 = [[12, 15], [10, 1], [5, 13]] print(array_1) """ output: [[12, 15], [10, 1], [5, 13]] """ print(sorted(array_1)) """ output: [[5, 13], [10, 1], [12, 15]] """ Block 2 import numpy as np np_array_1 = np.array([[12, 15], [10, 1], [5, 13]]) print(np_... | This is a bug in PyCharm. Please see: https://youtrack.jetbrains.com/issue/PY-45958/Type-error-sorting-Iterable-of-dataclassorderTrue-instances | 3 | 3 |
75,785,079 | 2023-3-19 | https://stackoverflow.com/questions/75785079/python-parent-class-information-do-not-display | import sqlite3 sqlite3.Cursor.__base__ ## output: <class 'object'> however, clearly, it inherited from Iterator, can see from the source code class Cursor(Iterator[Any]): and issubclass(sqlite3.Cursor, Iterator) # previous edit was saying iterable, sorry ## output: True so, why does Python not properly display the ... | The cursor object is defined in C as far as I can tell, so it doesn't have a parent class. As to why issubclass returns that, issubclass does essentially a "duck typing check" in some cases, as hinted at in the ABC docs: Checking isinstance(obj, Iterable) detects classes that are registered as Iterable or that have an... | 3 | 2 |
75,784,875 | 2023-3-19 | https://stackoverflow.com/questions/75784875/can-another-thread-release-a-lock-held-by-another-thread-in-python | I am trying to understand threading in Python via this website. Here, it has the following code for a single producer/consumer-type problem: import random SENTINEL = object() def producer(pipeline): """Pretend we're getting a message from the network.""" for index in range(10): message = random.randint(1, 101) logging.... | The answer is in the documentation: The class implementing primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it. In fact this technique is frequently used to orchestrate the threads. If you look closely two Lock objects are... | 3 | 2 |
75,771,154 | 2023-3-17 | https://stackoverflow.com/questions/75771154/is-it-necessary-to-add-a-constant-to-a-logit-model-run-on-categorical-variables | I have a dataframe that looks like this: And am running a logit model on fluid as dependent variable, and excluding vp and perip: model = smf.logit('''fluid ~ C(examq3_n, Treatment(reference = 2.0)) + C(pmhq3_n) + C(fluidq3_n) + C(mapq3_n, Treatment(reference = 3.0)) + C(examq6_n, Treatment(reference = 2.0)) + C(pmhq6... | If you use formulas, then the formula handling by patsy adds automatically a constant/intercept. (when using e.g. smf.logit or sm.Logit.from_formula) If you create a model without formula using numpy arrays or pandas DataFrame, then the exog is not changed by statsmodels, i.e. users needs to add a constant themselves. ... | 3 | 2 |
75,780,600 | 2023-3-19 | https://stackoverflow.com/questions/75780600/how-to-raise-exceptions-in-python-asyncio-background-task | Problem I have a few tasks that run continuously, but one of them occasionally needs to restart so this one is run in the background. How can exceptions from this background task be raised immediately? In the following example, the exception is not raised until the next attempt to restart, which can be very infrequent ... | In python 3.11, using async with the asynchronous context manager and asyncio.TaskGroup() solves this problem simply. import asyncio i = 0 async def foo(): while True: print("foo") await asyncio.sleep(1) async def bar(): while True: global i i += 1 if i > 14: raise ValueError() print("bar", i) await asyncio.sleep(1) as... | 4 | 3 |
75,782,615 | 2023-3-19 | https://stackoverflow.com/questions/75782615/how-to-render-a-gym-env-in-test-but-not-in-learning | I want to render a gym env in test but not in learning. Here is my code: import gymnasium as gym import numpy as np env = gym.make('FrozenLake-v1') # initialize Q table Q = np.zeros([env.observation_space.n, env.action_space.n]) print(Q) # parameter lr = 0.8 gamma = 0.95 num_episodes = 2000 # learning for i in range(nu... | You can just recreate a new environment specifying the render mode. import gymnasium as gym import numpy as np env_train = gym.make('FrozenLake-v1') # initialize Q table Q = np.zeros([env_train.observation_space.n, env_train.action_space.n]) print(Q) # parameter lr = 0.8 gamma = 0.95 num_episodes = 2000 # learning for ... | 4 | 5 |
75,780,039 | 2023-3-19 | https://stackoverflow.com/questions/75780039/sum-up-rows-containing-exact-characters-in-dataframe | I have a dataframe like this. I want to sum up special rows containing exact characters that matched my targets. Ko_EC FPKM count 0 1.1.1.1 16.7 1 1 1.1.1.15 30.0 7 2 4.2.1.128 40.5 9 3 4.2.1.12 57.0 10 4 3.2.1.1 1.1.1.1 22.0 4 Here are my dataframe and my targets. # coding=utf-8 import pandas as pd import numpy as n... | Using a double explode, a merge then groupby.agg: # create a reference from target_list ref = (pd.Series(target_list, name='Ko_EC') .str.split(r';\s*') .explode() .reset_index() ) # merge the exploded "alls" then aggregate out = ( ref.merge(alls.assign(Ko_EC=alls['Ko_EC'].str.split()).explode('Ko_EC'), how='left') .gro... | 4 | 1 |
75,773,085 | 2023-3-18 | https://stackoverflow.com/questions/75773085/subprocess-runhuggingface-cli-login-token-token-works-on-mac-but | I am tring to run subprocess.run(["huggingface-cli", "login", "--token", TOKEN]) in a Jupyter notebook, which works on Mac but gets the following error on Ubuntu. I checked that pip install huggingface_hub has been executed. subprocess.run(["git", "lfs", "install"]) works. !huggingface-cli login in the jupyter cell get... | Your huggingface_hub is not in your path env variable for your Ubuntu system, it is not the same between your jupyter and your terminal session here what you can do, get the path of the executable pip show huggingface_hub | grep Location then update the path in your jupyter notebook, like for example: import os import ... | 4 | 1 |
75,778,543 | 2023-3-18 | https://stackoverflow.com/questions/75778543/python-telnetlib3-examples | I would like to understand how to use telnetlib3 for a simple scenario. The longstanding telnetlib (not 3) has a simple example at https://docs.python.org/3/library/telnetlib.html where the python program connects to a telnet server, then looks for prompts and provides responses. One can readily see how to extend this ... | I think it's a bit of a stretch to call telnetlib3 a "replacement" for telnetlib. I guess it's similar in that it allows you to write a telnet client (or server), but it's really an entirely different beast. For the sort of thing you're doing in the initial telnetlib example, I would generally reach for pexpect (or jus... | 4 | 5 |
75,774,350 | 2023-3-18 | https://stackoverflow.com/questions/75774350/special-case-when-for-string-concatenation-is-more-efficient-than | I have this code using python 3.11: import timeit code_1 = """ initial_string = '' for i in range(10000): initial_string = initial_string + 'x' + 'y' """ code_2 = """ initial_string = '' for i in range(10000): initial_string += 'x' + 'y' """ time_1 = timeit.timeit(code_1, number=100) time_2 = timeit.timeit(code_2, numb... | For a while now, CPython has had an optimization that tries to perform string concatenation in place where possible. The details vary between Python versions, sometimes a lot - for example, it doesn't work for globals on Python 3.11, and it used to be specific to bytestrings on Python 2, but it's specific to Unicode st... | 8 | 7 |
75,774,668 | 2023-3-18 | https://stackoverflow.com/questions/75774668/how-could-i-pair-up-x-and-y-generated-by-np-meshgrid-using-python | I'm trying to generate a 2-dim coordinates matrix using python. I'm using x=np.linespace(min, max, step) y=np.linespace(min, max, step) X, Y = np.meshgrid(x, y) to generate x and y coordinates, where X like: [[0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2. 3. 4.] [0. 1. 2... | You can implement something like this: #!/usr/bin/env ipython # --------------------------- import numpy as np x0,x1 = -2, 2 y0,y1 = 0,4 x=np.arange(x0,x1, 1) y=np.arange(y0,y1, 1) X, Y = np.meshgrid(x, y) ny,nx = np.shape(X) # ----------------------------------------------------------- ans = [[[X[jj,ii],Y[jj,ii]] for ... | 3 | 2 |
75,773,844 | 2023-3-18 | https://stackoverflow.com/questions/75773844/read-a-7z-file-in-memory-with-python-and-process-each-line-as-a-stream | I'm working with a huge .7z file that I need to process line by line. First I tried py7zr, but it only works by first decompressing the whole file into an object. This runs out of memory. Then libarchive is able to read block by block, but there's no straightforward way of splitting these binary blocks into lines. What... | This solution goes through all available get_blocks(). If the last line doesn't end in \n, we keep the remaining bytes to be yield on the next block. import libarchive def process(my_file): data = '' with libarchive.file_reader(my_file) as e: for entry in e: for block in entry.get_blocks(): data += block.decode('ISO-88... | 3 | 4 |
75,768,651 | 2023-3-17 | https://stackoverflow.com/questions/75768651/assign-and-re-use-quantile-based-buckets-by-group-in-pandas | What I am trying to achieve I have a pandas DataFrame in a long format, containing values for different groups. I want to compute and apply a quantile based-binning (e.g. quintiles in this example) to each group of the DataFrame. I also need to be able to keep the bins edges for each group and apply the same labelling ... | You can use groupby(...).quantile to get your bins. Getting the labels is the tricky part, if you want to have the same type of labels that cut and qcut returns you can convert this result to an pandas.arrays.IntervalArray and grab the left edges from there. bins = ( df.groupby('group')['val'] .quantile([0, .2, .4, .6,... | 3 | 1 |
75,767,309 | 2023-3-17 | https://stackoverflow.com/questions/75767309/python-speeding-up-a-loop-for-text-comparisons | I have a loop which is comparing street addresses. It then uses fuzzy matching to tokenise the addresses and compare the addresses. I have tried this both with fuzzywuzzy and rapidfuzz. It subsequently returns how close the match is. The aim is to try and take all my street addresses 30k or so and match a variation of ... | I would start by pre-calculating the sorted tokens once for each address so that you don't end up doing it n*n-1 times. This allows you to bypass the processor and avoid calling the sort method of the fuzzer. After that, I would take pandas out of the picture at least while doing these tests. This test runs through 1k ... | 3 | 1 |
75,765,213 | 2023-3-17 | https://stackoverflow.com/questions/75765213/pytube-attributeerror-nonetype-object-has-no-attribute-span-cipher-py | Yesterday this works fine, today i'm getting error on my local machine, colab notebook, even on my VPS. /usr/local/lib/python3.9/dist-packages/pytube/cipher.py in get_throttling_plan(js) 409 match = plan_regex.search(raw_code) 410 --> 411 transform_plan_raw = find_object_from_startpoint(raw_code, match.span()[1] - 1) 4... | Found a solution. cipher.py Line 411 transform_plan_raw = find_object_from_startpoint(raw_code, match.span()[1] - 1) to transform_plan_raw = js | 4 | 7 |
75,763,556 | 2023-3-17 | https://stackoverflow.com/questions/75763556/sys-getrefcount-returning-very-large-reference-counts | In CPython 3.11, the following code returns very large reference counts for some objects. It seems to follow pre-cached objects like integers -5 to 256, but CPython 3.10 does not: Python 3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "lice... | This is not related to PEP 683, but it will probably be superseded by PEP 683 once PEP 683 has been implemented. This refcount change was first introduced in a commit on December 13, 2021, which introduced a _PyObject_IMMORTAL_INIT macro: #define _PyObject_IMMORTAL_INIT(type) \ { \ .ob_refcnt = 999999999, \ .ob_type = ... | 8 | 8 |
75,756,665 | 2023-3-16 | https://stackoverflow.com/questions/75756665/how-to-make-pylance-understand-pydantics-allow-population-by-field-name-for-i | In my current project, we are using an OpenAPI-to-TypeScript-API generator, that generates automatically typed functions for calling API endpoints via Axios. In Python, we use snake_case for our class properties, while in TypeScript we use camelCase. Using this setup, we have found that the alias property (Field(..., a... | It seems like this is a known problem as you can see from issue #4936. It has to do with the way dataclass_transform (from PEP 681) handles the alias field attribute. There is currently no elegant solution for this, but there may be with Pydantic v2 at some point. I agree that you should not just passively ignore the w... | 4 | 5 |
75,739,583 | 2023-3-15 | https://stackoverflow.com/questions/75739583/is-there-a-way-to-detect-and-quantify-the-missing-area-of-objects-in-images | I am trying to calculate the percentage of leaf damage using R. I am able to do the image segmentation and area calculation using the pliman package, following the vignettes: https://cran.r-project.org/web/packages/pliman/vignettes/pliman_start.html I am using the following R code. I put a 1cm square as a reference sc... | Alright, here's a start for you: https://github.com/brockbrownwork/leaves I'll polish up this answer later, but here's the main results: Input: Output: Fraying: 3.947% Percentage of non-fray holes: 5.589% Edit: If you have a few examples of the images you're going to use, that would be helpful. Mainly I want to know... | 4 | 1 |
75,760,261 | 2023-3-16 | https://stackoverflow.com/questions/75760261/most-efficient-way-to-continuously-find-the-median-of-a-stream-of-numbers-in-py | I'm trying to solve a problem which reads as follows: A queue of eager single-digits (your input) are waiting to enter an empty room. I allow one digit (from the left) to enter the room each minute. Each time a new digit enters the room I chalk up the median of all the digits currently in the room on the chalkboard. [T... | You are repeatedly sorting, with key comparison, so total cost is O(N * N log N), that is, it is at least quadratic. single-digits (your input) are waiting to enter The key to this problem is the range limit on input. We know that each input x is in this range: 0 <= x < 10 Use counters. We can easily allocate ten of... | 5 | 4 |
75,759,568 | 2023-3-16 | https://stackoverflow.com/questions/75759568/python-convert-a-dataframe-of-events-into-a-square-wave-time-serie | How would you transform a pandas dataframe composed of successive events: start_time | end_time | value 1671221209 1671234984 2000 1671240425 1671241235 1000 1671289246 1671289600 133 ... ... ... into timeserie like this: time | value 1671221209 2000 1671234984 2000 1671234985 0 1671240424 0 1671240425 1000 167124123... | You can use melt function: result = ( df.melt(id_vars='value', var_name='time_type', value_name='time') .drop(columns=['time_type']) .sort_values(by='time') .reset_index(drop=True) ) result = result[['time', 'value']] | 3 | 2 |
75,745,438 | 2023-3-15 | https://stackoverflow.com/questions/75745438/how-to-print-polars-dataframe-without-the-leading-shape-information | When I print a Polars dataframe (e.g., from terminal or within Jupyter notebook), there is a leading string citing the shape of the resultant dataframe. I am looking for the method to not have this printed as part of the result. The simple example would be the following: >>> import polars as pl >>> df = pl.DataFrame() ... | I found a native way: you could use pl.Config.set_tbl_hide_dataframe_shape. This import polars as pl pl.Config.set_tbl_hide_dataframe_shape(True) df = pl.DataFrame({'col1': range(3), 'col2': ['a', 'b', 'c']}) print(df) results in ┌──────┬──────┐ │ col1 ┆ col2 │ │ --- ┆ --- │ │ i64 ┆ str │ ╞══════╪══════╡ │ 0 ┆ a │ │ 1... | 4 | 7 |
75,754,219 | 2023-3-16 | https://stackoverflow.com/questions/75754219/how-to-put-the-max-of-3-separate-columns-in-a-new-column-in-python-pandas | for example we have: a b c 1 1 3 2 4 1 3 2 1 And now using python I'm trying to create this: a b c max 1 1 3 3c 2 4 1 4b 3 2 1 3a | If need match first maximal column join max converted to strings with DataFrame.idxmax for columns names by max: cols = ['a','b','c'] df['max'] = df[cols].max(axis=1).astype(str).str.cat(df[cols].idxmax(axis=1)) print (df) a b c max 0 1 1 3 3c 1 2 4 1 4b 2 3 2 1 3a If possible multiple max values and need all matched ... | 3 | 3 |
75,747,252 | 2023-3-15 | https://stackoverflow.com/questions/75747252/using-sqlalchemy-orm-with-composite-primary-keys | Using sqlalchemy.orm I am trying to link two tables on a composite key, but keep getting an error. Unfortunately, the official docs provide an example that uses a single primary key (not composite), so I tried to come up with a basic example that reproduces the issue: from sqlalchemy import Column, ForeignKey, Integer,... | Unlike a composite primary key where you can add primary_key=True to columns you want, composite foreign keys do not work that way. What you have right now is two different foreign keys and not a single composite foreign key. You need to use ForeignKeyConstraint in the __table_args__ tuple like the following. __table_... | 4 | 5 |
75,744,991 | 2023-3-15 | https://stackoverflow.com/questions/75744991/is-there-any-pep-regarding-a-pipe-operator-in-python | It is often common to write this type of python code: def load_data(): df_ans = get_data() df_checked = check_data(df_ans) # returns df_ans or raises an error return_dict = format_data(df_ans) return return_dict One could write the above like this (but it's ugly in my opinion) def load_data(): return format_data(check... | I don't think a pipe operator in Python will be approved in the near future. To do that operation there is already the function pipe in the toolz library. It is not a Python built in library but is widely used. In case you are curious the implementation is just: def pipe(data, *funcs): for func in funcs: data = func(da... | 4 | 1 |
75,745,192 | 2023-3-15 | https://stackoverflow.com/questions/75745192/extract-digits-from-a-string-within-a-word | I want a regular expression, which returns only digits, which are within a word, but I can only find expressions, which returns all digits in a string. I've used this example: text = 'I need this number inside my wor5d, but also this word3 and this 4word, but not this 1 and not this 555.' The following code returns all... | You can use re.findall(r'(?<=[a-zA-Z])\d+|\d+(?=[a-zA-Z])', text) This regex will extract all one or more digit chunks that are immediately preceded or followed with an ASCII letter. A fully Unicode version for Python re would look like (?<=[^\W\d_])\d+|\d+(?=[^\W\d_]) where [^\W\d_] matches any Unicode letter. See t... | 4 | 1 |
75,683,009 | 2023-3-9 | https://stackoverflow.com/questions/75683009/how-to-catch-the-error-message-from-chem-molfromsmilesformula | I'm new to this rdkit, below is the code that I'm using to get the chemical image from the formula, from rdkit import Chem m = Chem.MolFromSmiles('OCC1OC(C(C(C1O)O)O)[C]1(C)(CO)CC(=O)C=C(C1CCC(=O)C)C') m if the code is correct, it displays the structre. The above code displays the error saying "[15:23:55] Explicit val... | It is not an Error, it is a Warning. Your code does not break doing that assignment. So there is no Error to catch. But your solution lays within the return of Chem.MolFromSmiles. If it fails to build a mol object of your SMILES it returns None, whereas it returns the mol object when it manages to "deal with the SMILES... | 4 | 1 |
75,726,959 | 2023-3-13 | https://stackoverflow.com/questions/75726959/how-to-reroute-requests-to-a-different-url-endpoint-in-fastapi | I am trying to write a middleware in my FastAPI application, so that requests coming to endpoints matching a particular format will be rerouted to a different URL, but I am unable to find a way to do that since request.url is read-only. I am also looking for a way to update request headers before rerouting. Are these t... | To change the request's URL path—in other words, reroute the request to a different endpoint—one can simply modify the request.scope['path'] value inside the middleware, before processing the request, as demonstrated in Option 3 of this answer. If your API endpoints include path parameters (e.g., '/users/{user_id}'), t... | 8 | 7 |
75,737,824 | 2023-3-14 | https://stackoverflow.com/questions/75737824/bases-must-be-type-error-when-running-from-google-cloud-import-bigquery-in-jup | I tried running the following: from google.cloud import bigquery But from some reason, I keep getting this "Bases must be types" error: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-3-1035661e8528> in <module> ----> 1 from google.... | Marking this as an answer for better visibility, as this resolved the question: pip installing protobuff v3.20.1 as @runner16 mentioned pip install protobuf==3.20.1 | 3 | 4 |
75,680,581 | 2023-3-9 | https://stackoverflow.com/questions/75680581/how-to-stream-from-a-generator-to-a-polars-dataframe-and-subsequent-lazy-plan | I have a very long generator function that I want to process as a column using Polars. Due to its size, I want to run it in lazy streaming mode using the generator as a source, but I have been unable to work out how to do it (if it is possible). Creating a normal dataframe and then converting to lazy obviously doesn't ... | Creating a normal dataframe and then converting to lazy obviously doesn't work since the generator is exhausted before the lazy plan is run with collect(). This is a mistaken assumption. If you do: df = pl.DataFrame({"a": generator}).lazy() then, yes, the generator is exhausted but all of its data is in df so it doe... | 4 | 2 |
75,711,757 | 2023-3-12 | https://stackoverflow.com/questions/75711757/fastapi-get-endpoint-returns-405-method-not-allowed-response | A GET endpoint in FastAPI is returning correct result, but returns 405 method not allowed when curl -I is used. This is happening with all the GET endpoints. As a result, the application is working, but health check on application from a load balancer is failing. Any suggestions what could be wrong? code @app.get('/hea... | The curl -I option (which is used in the example you provided) is the same as using curl --head and performrs an HTTP HEAD request, in order to fetch the headers only (not the body/content of the resource): The HTTP HEAD method requests the headers that would be returned if the HEAD request's URL was instead requested... | 6 | 4 |
75,715,657 | 2023-3-12 | https://stackoverflow.com/questions/75715657/getting-tox-to-use-the-python-version-set-by-pyenv | I can't seem to wrap my head around managing Python versions. When I run tox, I can immediately see that it's using Python 3.7.9: $ tox py39: commands[0]> coverage run -m pytest ================================================================================== test session starts =======================================... | Although this is an old question and it has already been marked as solved, I dare to give another answer since this post appears on the first page of Google search results of the "tox pyenv" query. As already noted, tox-pyenv is not compatible with tox version 4. Moreover, tox no longer discovers Python executables by ... | 3 | 4 |
75,701,437 | 2023-3-10 | https://stackoverflow.com/questions/75701437/why-do-we-multiply-learning-rate-by-gradient-accumulation-steps-in-pytorch | Loss functions in pytorch use "mean" reduction. So it means that the model gradient will have roughly the same magnitude given any batch size. It makes sense that you want to scale the learning rate up when you increase batch size because your gradient doesn't become bigger as you increase batch size. For gradient accu... | I found that they indeed divided the loss by N (number of gradient accumulation steps). You can see sample code from accelerate package here: https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation Notice the following line of code from the guide above: loss = loss / gradient_accumulation_steps This i... | 5 | 6 |
75,709,118 | 2023-3-11 | https://stackoverflow.com/questions/75709118/how-are-attribute-names-with-underscore-managed-in-pydantic-models | Can anyone explain how Pydantic manages attribute names with an underscore? In Pydantic models, there is a weird behavior related to attribute naming when using the underscore. That behavior does not occur in python classes. The test results show some allegedly "unexpected" errors. The following code is catching some e... | This different treatment of underscored variables is actually explicitly documented in the section "Automatically excluded attributes", although it is not worded clearly enough and could be better explained in my humble opinion. UPDATE (2023-08-16): In fairness, the Pydantic v2 docs do a better job by explicitly stati... | 5 | 13 |
75,671,499 | 2023-3-8 | https://stackoverflow.com/questions/75671499/duckdb-binder-error-referenced-column-not-found-in-from-clause | I am working in DuckDB in a database that I read from json. Here is the json: [{ "account": "abcde", "data": [ { "name": "hey", "amount":1, "flow":"INFLOW" }, { "name": "hello", "amount":-2, "flow": null } ] }, { "account": "hijkl", "data": [ { "name": "bonjour", "amount":1, "flow":"INFLOW" }, { "name": "hallo", "amoun... | I actually solved the issue. I had to use single quotes ' instead of double quotes " in the string comparison... Solution duckdb.sql(""" UPDATE mytable SET data = NULL WHERE account = 'abcde' """) correctly does ┌─────────┬────────────────────────────────────────────────────────────────────────────────────────────────... | 3 | 8 |
75,728,233 | 2023-3-14 | https://stackoverflow.com/questions/75728233/catch-overflow-error-in-numba-integer-multiplication | I am using numba and I would like to know if an overflow has occurred when I multiply two integers. Say the integers are positive for simplicity. I have written the following function to try and achieve this: from numba import njit import numpy as np @njit def safe_mul(a, b): c = a * b print('a: ', a) print('b: ', b) ... | On the Numba discourse site, the user sschaer was able to provide a very fast solution. See this: https://numba.discourse.group/t/catch-overflow-in-integer-multiplication/1827 for the original discussion. The solution is copied here with sschaer's permission. LLVM has integer operations that return an overflow bit and ... | 5 | 0 |
75,734,368 | 2023-3-14 | https://stackoverflow.com/questions/75734368/what-is-the-grid-size-parameter-in-shapely-operations-do | In a practical sense, what does the grid_size parameter do for you? When/why would you change it from the default? I understand from testing that it imposes a discretization on the coordinates of the resulting geometries, e.g. with grid_size=0.01 the fractional part of the coordinates will be multiples of 0.01. Does th... | A practical reason why I use it sometimes is to avoid having slivers after applying overlays (in non-topological data). The code sample below illustrates this: the intersection between the 2 polygons without grid_size results in a narrow polygon as intersection. the intersection between the 2 polygons with grid_size r... | 3 | 3 |
75,690,124 | 2023-3-9 | https://stackoverflow.com/questions/75690124/find-a-specific-concordance-index-using-nltk | I use this code below to get a concordance from nltk and then show the indices of each concordance. And I get these results show below. So far so good. How do I look up the index of just one specific concordance? It is easy enough to match the concordance to the index in this small example, but if I have 300 concordanc... | We can use concordance_list function (https://www.nltk.org/api/nltk.text.html) so that we can specify the width and number of lines, and then iterate over lines getting the 'offset' (i.e. line number) and adding surrounding brackets '[' ']' plus roi (i.e. 'monstrous') between the left and right words (of each line): so... | 5 | 2 |
75,671,456 | 2023-3-8 | https://stackoverflow.com/questions/75671456/error-installing-pyqt5-under-aarch64-architecture | I'm trying to install pyqt5 V5.15.2 on an emulate qemu aarch64 debian distro, but it fails with the following trace: root@debian-arm64:~# pip install pyqt5==5.15.2 --config-settings --confirm-license= --verbose Using pip 23.0.1 from /usr/local/lib/python3.9/dist-packages/pip (python 3.9) Collecting pyqt5==5.15.2 Using ... | I founded the following solution that worked for me: Instead of using pip for installing PyQt5, a PyQt5 package exists. Installing the package from apt worked for me. sudo apt-get install python3-PyQt5 | 3 | 1 |
75,719,072 | 2023-3-13 | https://stackoverflow.com/questions/75719072/dynamically-set-sql-default-value-with-table-name-in-sqlmodel | I'm trying to create a base-class in SQLModel which looks like this: class BaseModel(SQLModel): @declared_attr def __tablename__(cls) -> str: return cls.__name__ guid: Optional[UUID] = Field(default=None, primary_key=True) class SequencedBaseModel(BaseModel): sequence_id: str = Field(sa_column=Column(VARCHAR(50), serve... | Unfortunately, if you have an attribute that relies on a @declared_attr, it must also be a @declared_attr, since SqlAlchemy will wait until the whole mapping is completed and the classes get actual tables to be resolved (at least, that is my understanding). Now: declared_attr(s) are an SqlAlchemy concept, whereas the i... | 5 | 4 |
75,727,494 | 2023-3-13 | https://stackoverflow.com/questions/75727494/how-can-i-code-vuongs-statistical-test-in-python | I need to implement Vuong's test for non-nested models. Specifically, I have logistic-regression models that I would like to compare. I have found implementations in R and STATA online, but unfortunately I work in Python and am not familiar with those frameworks/languages. Also unfortunate is that I have not been unabl... | In order to move forward, I learned enough R to be able to make my own comparison between R and python for Vuong's Test as below. In the end, my original implementation was close except for the subtle point of difference between how numpy and R calculate standard deviations by default. After correcting to now calculate... | 3 | 3 |
75,700,322 | 2023-3-10 | https://stackoverflow.com/questions/75700322/when-is-d1-d2-not-equivalent-to-d1-eq-d2 | According to the docs (in Python 3.8): By default, object implements __eq__() by using is, returning NotImplemented in the case of a false comparison: True if x is y else NotImplemented. And also: The correspondence between operator symbols and method names is as follows: [...] x==y calls x.__eq__(y) So I expect =... | == calls the right operand's .__eq__() if the left operand's .__eq__() returns NotImplemented and if both sides return NotImplemented, == will return false. You can see this behavior by changing your class: class Dummy(): def __eq__(self, o): print(f'{id(self)} eq') return NotImplemented d1 = Dummy() d2 = Dummy() print... | 4 | 2 |
75,725,718 | 2023-3-13 | https://stackoverflow.com/questions/75725718/redirect-to-a-url-in-dash | I'm using dash to build a dashboard where I am creating a unique url whenever a particular data point is clicked, how can I redirect users to this created url? I'm using the below given code where whenever someone click on any data points, click event will trigger and callback function executes. app.layout = html.Div(c... | With a clienside callback, using window.location : app.clientside_callback( """ function(clickData) { if (clickData?.points?.length) { const point = clickData['points'][0]; const path = point.customdata ?? 'fallbackPath'; const url = `https://example.com/${path}`; window.location = url; } } """, Output('dummy-div', 'ch... | 3 | 4 |
75,719,802 | 2023-3-13 | https://stackoverflow.com/questions/75719802/test-code-and-branch-coverage-simultanously-with-pytest | I am using pytest to test my Python code. To test for code coverage (C0 coverage) I run pytest --cov and I can specify my desired coverage in my pyproject.toml file like this: [tool.coverage.report] fail_under = 95 I get this result with a coverage a 96.30%: ---------- coverage: platform linux, python 3.8.13-final-0 -... | My final solution uses pytest to execute the tests, coverage to generate coverage reports and coverage-threshold to interpret the results. From coverage-theshold's README: A command line tool for checking coverage reports against configurable coverage minimums. Currently built for use around python's coverage. Tools ... | 5 | 5 |
75,727,685 | 2023-3-13 | https://stackoverflow.com/questions/75727685/how-do-i-get-a-list-of-table-like-objects-visible-to-duckdb-in-a-python-session | I like how duckdb lets me query DataFrames as if they were sql tables: df = pandas.read_parquet("my_data.parquet") con.query("select * from df limit 10").fetch_df() I also like how duckdb has metadata commands like SHOW TABLES;, like a real database. However, SHOW TABLES; doesn't show pandas DataFrames or other table-... | You can use the different metadata table functions duckdb_% as referred here For an equivalent of SHOW TABLES and convert it as a pandas dataframe import duckdb df = duckdb.sql("SELECT * FROM duckdb_tables;").df() print(df.dtypes) database_name object database_oid int64 schema_name object schema_oid int64 table_name ob... | 3 | 8 |
75,695,118 | 2023-3-10 | https://stackoverflow.com/questions/75695118/how-to-avoid-reading-half-written-arrays-spanning-multiple-chunks-using-zarr | In a multiprocess situation, I want to avoid reading arrays from a zarr group that haven't fully finished writing by the other process yet. This functionality does not seem to come out of the box with zarr. While chunk writing is atomic in zarr, array writing seems not to be (i.e. while you can never have a half-writte... | You can't really get around using some form of synchronization. Your best bet is to communicate from the writer process to the reader processes that something is ready to be consumed. A simple multiprocessing.Queue would work if you are forking from the same process and each worker will operate on the array themselves.... | 4 | 3 |
75,738,343 | 2023-3-14 | https://stackoverflow.com/questions/75738343/how-can-i-use-pip-install-when-using-pyscript | I am trying to code an html file that is able to contact with chat gpt. this is the start of the code: <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/pyscript.js"></script> <py-script> import openai </py-script> but when I run it it says: Module... | According to the Getting Started documentation, you import external modules using a <py-config> tag: <py-config> packages = ["openai"] </py-config> However, even with that, this code: <html> <head> <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" /> <script defer src="https://pyscript.net/latest/... | 3 | 3 |
75,721,577 | 2023-3-13 | https://stackoverflow.com/questions/75721577/add-a-new-option-to-an-existing-selection-field | The following options are what I have available currently: I want to add another option called 'Solved', with blue colored circle. I did inherit the "project.task" model and added selection_add method and overridden the kanban_state selection field with the 'Solved' text: # Python File from odoo import models, fields,... | The selection state is designed to use red color for all new states. To use another color, you will need to override the selection state widget or create a custom selection widget Example: 1. Create a new selection state widget to set a custom color in solved state /** @odoo-module **/ import basicFields from "web.basi... | 3 | 2 |
75,736,939 | 2023-3-14 | https://stackoverflow.com/questions/75736939/error-could-not-build-wheels-for-python-ldap-which-is-required-to-install-pypr | I was installing Odoo 15 inside a Python virtual environment on Ubuntu 20.04. I've downloaded Odoo from the official GitHub repository and use Nginx as a reverse proxy. after following the documentation to install and set up odoo in ubuntu 22.04, I did followed this how-to-do doc in this link I get this error the momen... | You need to install on your system the GCC compiler package and the package that includes the development libraries and header files needed to compile applications that use LDAP | 11 | 5 |
75,724,033 | 2023-3-13 | https://stackoverflow.com/questions/75724033/set-the-media-type-of-a-custom-error-response-via-a-pydantic-model-in-fastapi | In my FastAPI application I want to return my errors as RFC Problem JSON: from pydantic import BaseModel class RFCProblemJSON(BaseModel): type: str title: str detail: str | None status: int | None I can set the response model in the OpenAPI docs with the responses argument of the FastAPI class: from fastapi import Fas... | As described in FastAPI's documentation about Additional Responses in OpenAPI: You can pass to your path operation decorators a parameter responses. It receives a dict, the keys are status codes for each response, like 200, and the values are other dicts with the information for each of them. Each of those response di... | 4 | 4 |
75,721,031 | 2023-3-13 | https://stackoverflow.com/questions/75721031/hide-legend-values-on-zoom-in-plotly-express | Is there a way to only show visible values in the legend in plotly express? So for example if this was my original scatter plot: and I zoom in on a few points like so: Is there a way to only show the legend values for the points that are currently visible, rather than showing all legend values? Code for reference: fi... | You can create a JupyterDash app, and use a callback to read in the layout data from zoom events, then update the figure accordingly. In order to reset the default (with all of the points and traces in the legend), you can click Zoom Out tooltip in the figure. import json import numpy as np import pandas as pd import p... | 3 | 2 |
75,733,809 | 2023-3-14 | https://stackoverflow.com/questions/75733809/how-to-crop-an-audio-file-based-on-the-timestamps-present-in-a-list | So, I have an audio file which is very long in duration. I have manual annotations (start and end duration in seconds) of the important parts which I need from the whole audio in a text file. I have converted this text file into a nested list where in each list has [start , end] The whole list looks like [[start1,end1]... | Try out Pydub! :) from pydub import AudioSegment def trim_audio(intervals, input_file_path, output_file_path): # load the audio file audio = AudioSegment.from_file(input_file_path) # iterate over the list of time intervals for i, (start_time, end_time) in enumerate(intervals): # extract the segment of the audio segment... | 4 | 4 |
75,734,763 | 2023-3-14 | https://stackoverflow.com/questions/75734763/ordering-multi-indexed-pandas-dataframe-on-two-levels-with-different-criteria-f | Consider the dataframe df_counts, constructed as follows: df2 = pd.DataFrame({ "word" : ["AA", "AC", "AC", "BA", "BB", "BB", "BB"], "letter1": ["A", "A", "A", "B", "B", "B", "B"], "letter2": ["A", "C", "C", "A", "B", "B", "B"] }) df_counts = df2[["word", "letter1", "letter2"]].groupby(["letter1", "letter2"]).count() O... | When you have a complex sorting order, it's always easy to use numpy.lexsort: # minor sorting order first, major one last # - to inverse the order order = np.lexsort([-df_counts['word'], -df_counts.groupby('letter1')['word'].transform('sum')]) out = df_counts.iloc[order] The pandas equivalent would be: (df_counts .ass... | 3 | 3 |
75,673,304 | 2023-3-8 | https://stackoverflow.com/questions/75673304/how-to-get-mastodon-direct-messages-using-mastodon-py | I am trying to get direct messages from my Mastodon account using Mastodon.py. I am able to get everything on the timeline, but can't seem to return direct messages. Since direct messages are separate from the timeline (on the web interface), I am assuming there is some function other than timeline() I should be using.... | Instead of mastodon.timeline() you want to call mastodon.conversations() To get the content of the conversations you can do conversations = mastodon.conversations() for c in conversations: print(c.last_status.content) https://mastodonpy.readthedocs.io/en/stable/07_timelines.html#mastodon.Mastodon.conversations | 4 | 2 |
75,729,285 | 2023-3-14 | https://stackoverflow.com/questions/75729285/pandas-find-the-left-most-value-in-a-pandas-dataframe-followed-by-all-1s | I have the following dataset data = {'ID': ['A', 'B', 'C', 'D'], '2012': [0, 1, 1, 1], '2013': [0, 0, 1, 1], '2014': [0, 0, 0, 1], '2015': [0, 0, 1, 1], '2016': [0, 0, 1, 0], '2017': [1, 0, 1,1]} df = pd.DataFrame(data) For each row I want to generate a new column - Baseline_Year - which assumes the name of the column... | I would use a boolean mask and idxmax: # get year columns, identify rightmost 1s m = (df.filter(regex=r'\d+') .loc[:, ::-1] .eq(1).cummin(axis=1) .loc[:, ::-1] ) df['Baseline_Year'] = m.idxmax(axis=1).where(m.any(axis=1)) Output: ID 2012 2013 2014 2015 2016 2017 Baseline_Year 0 A 0 0 0 0 0 1 2017 1 B 1 0 0 0 0 0 NaN ... | 3 | 5 |
75,714,883 | 2023-3-12 | https://stackoverflow.com/questions/75714883/how-to-test-a-fastapi-endpoint-that-uses-lifespan-function | Could someone tell me how I can test an endpoint that uses the new lifespan feature from FastAPI? I am trying to set up tests for my endpoints that use resources from the lifespan function, but the test failed since the dict I set up in the lifespan function is not passed to the TestClient as part of the FastAPI app. M... | Use the TestClient as a context manager. This triggers startup/shutdown events as well as lifespans. from fastapi.testclient import TestClient from app.main import app def test_read_prediction(): with TestClient(app) as client: model_input= "test" response = client.get(f"/prediction/?model_input={model_input}") assert ... | 18 | 45 |
75,690,059 | 2023-3-9 | https://stackoverflow.com/questions/75690059/pandas-interpolation-to-extend-data-is-giving-bad-results | I have a dataset with 'DEN' values as a function of 'Z', which goes to Z = ~425000, but I would like to extend it up to Z = 500000. I attempted to do this by adding a new data point to my pandas column at Z = 500000, and filling in the NaN values with spline and linear interpolation, but neither result gives a good fit... | The main issue is that your Z value makes a big jump from 434k to 500k. You should use Z as the index of df because the interpolate method is based on the index values. Method 1 - Linear extrapolation You can do it by adding a single new datapoint. df = pd.DataFrame.from_dict(dict) df_new = pd.DataFrame({'Z':[500000]})... | 3 | 4 |
75,726,452 | 2023-3-13 | https://stackoverflow.com/questions/75726452/can-i-force-the-install-of-a-package-that-requires-a-newer-python-version-than-t | I know it isn't a correct thing to do, but I would like to try to install package that requires Python 3.8, but my installed Python is 3.7. Is it possible using pip? Or I must clone the repository and change the setup.py? | You can use the --ignore-requires-python option. pip install --help --ignore-requires-python Ignore the Requires-Python information. You can try it with your package, or also with this minimal setup.py: from setuptools import setup, find_packages setup( name="foobar", version="1.0", packages=find_packages(), python_... | 8 | 15 |
75,726,719 | 2023-3-13 | https://stackoverflow.com/questions/75726719/confused-by-python-async-for-loop-executes-sequentially | I am new to asyncio and trying to understand basic for loop behavior. The code below executes sequentially, but my naive assumption was that while the sleeps are occurring, other items could be fetched via the for loop and start processing. But that doesn't seem to happen. For example, while the code is "doing somethin... | I think you have a common misunderstanding of how async works. You have written your program to be synchronous. await foo() says to call foo(), and feel free to go do something else while we're waiting for foo to return with its answer. Likewise, getting the next element from your custom iterator says "get the next ele... | 4 | 3 |
75,725,818 | 2023-3-13 | https://stackoverflow.com/questions/75725818/loading-hugging-face-model-is-taking-too-much-memory | I am trying to load a large Hugging face model with code like below: model_from_disc = AutoModelForCausalLM.from_pretrained(path_to_model) tokenizer_from_disc = AutoTokenizer.from_pretrained(path_to_model) generator = pipeline("text-generation", model=model_from_disc, tokenizer=tokenizer_from_disc) The program is quic... | You could try to load it with low_cpu_mem_usage: from transformers import AutoModelForSeq2SeqLM model_from_disc = AutoModelForCausalLM.from_pretrained(path_to_model, low_cpu_mem_usage=True) Please note that low_cpu_mem_usage requires: Accelerate >= 0.9.0 and PyTorch >= 1.9.0. | 7 | 9 |
75,707,701 | 2023-3-11 | https://stackoverflow.com/questions/75707701/why-i-can-not-install-pyside2 | I want to Install PySide 2 library But apparently this library is not found. I tried this to install PySide2: pip3 install PySide2 But after executing this command, I encountered the same problem: ERROR: Could not find a version that satisfies the requirement PySide2 (from versions: none) ERROR: No matching distribu... | According to the documentation for versions of python 3.7+ you need to do the following to install the module: pip install pyside6 | 5 | 9 |
75,723,227 | 2023-3-13 | https://stackoverflow.com/questions/75723227/pandas-select-rows-where-any-column-passes-condition | How can I return all rows where one of the columns passes a given condition, WITHOUT specifying any column? My situation is as follows: import pandas as pd print(pd.__version__) # 1.5.2 x = [ 1, 2, 3 ] y = [ 4, 5, 6 ] z = [ 7, 8, 9 ] df = pd.DataFrame({ "a": x, "b": y, "c": z }) I know you can apply a condition on a g... | Use vectorial code with any and boolean indexing: df[df.gt(1).any(axis=1)] | 3 | 7 |
75,719,665 | 2023-3-13 | https://stackoverflow.com/questions/75719665/in-python-issubclass-unexpectedly-complains-about-protocols-with-non-method-m | I have tried the obvious way to check my protocol: from typing import Any, Protocol, runtime_checkable @runtime_checkable class SupportsComparison(Protocol): def __eq__(self, other: Any) -> bool: ... issubclass(int, SupportsComparison) Unfortunately the issubclass() call ends with an exception (Python 3.10.6 in Ubuntu... | From the documentation: A class that overrides __eq__() and does not define __hash__() will have its __hash__() implicitly set to None. Therefore, in your case, you have the implicit non-method member SupportsComparison.__hash__ = None. You can fix it by declaring __hash__ explicitly: from typing import Any, Protocol... | 3 | 4 |
75,719,006 | 2023-3-13 | https://stackoverflow.com/questions/75719006/in-python-for-parameter-typing-do-you-use-the-capital-versions-of-dict-and-list | Apologies, am new to Python so a very basic question. Below is an example line of my method definition. Where would I be using capital Dict/List and lowercase Dict/List? Thanks in advance! Example scenarios below def execute_signals(self, parameter1: dict[list], parameter2: dict) -> list[dict]: def execute_signals(self... | On Python 3.8 and earlier, the name of the collection type is capitalized, and the type is imported from the typing module. Python 3.5 - 3.8 (also works in Python 3.9+): from typing import List, Set, Dict, Tuple x: List[int] = [1] x: Set[int] = {6, 7} x: Dict[str, float] = {"field": 2.0} x: Tuple[int, str, float] = (3,... | 10 | 6 |
75,674,773 | 2023-3-8 | https://stackoverflow.com/questions/75674773/creating-huggingface-dataset-to-train-an-bio-tagger | I have a list of dictionaries: sentences = [ {'text': ['I live in Madrid'], 'labels':[O, O, O, B-LOC]}, {'text': ['Peter lives in Spain'], 'labels':[B-PER, O, O, B-LOC]}, {'text': ['He likes pasta'], 'labels':[O, O, B-FOOD]}, ... ] I want to create a HuggingFace dataset object from this data so that I can later prepro... | First you'll need some extra libraries to use the metrics and datasets features. pip install -U transformers datasets evaluate seqeval To convert list of dict to Dataset object import pandas as pd from datasets import Dataset sentences = [ {'text': 'I live in Madrid', 'labels':['O', 'O', 'O', 'B-LOC']}, {'text': 'Pete... | 4 | 8 |
75,717,408 | 2023-3-13 | https://stackoverflow.com/questions/75717408/python-dataframe-isocalendar-boolean-condition-not-producing-desired-result-wh | I am surprised that my simple boolean condition was producing a complete year result when I wanted only the first week's data of that year only. My code: # Some sample data df1 = pd.DataFrame([1596., 1537., 1482., 1960., 1879., 1824.],index=['2007-01-01 00:00:00', '2007-01-01 01:00:00', '2007-01-01 02:00:00', '2007-12-... | This is normal behavior. >>> df1.index.isocalendar().week 2007-01-01 00:00:00 1 2007-01-01 01:00:00 1 2007-01-01 02:00:00 1 2007-12-31 21:00:00 1 2007-12-31 22:00:00 1 2007-12-31 23:00:00 1 Name: week, dtype: UInt32 >>> >>> df1.index.isocalendar().year 2007-01-01 00:00:00 2007 2007-01-01 01:00:00 2007 2007-01-01 02:00:... | 3 | 3 |
75,714,478 | 2023-3-12 | https://stackoverflow.com/questions/75714478/splitting-text-based-on-a-delimiter-in-python | I have just started learning python. I am working on netflix_tiles dataset downloaded from Kaggle. Some of the entries in the director column have multiple director names separated by column, i was trying to separate director names using the split function The following is one of the original values loaded from the fil... | Use str.strip(): df = pd.read_csv('/home/damien/Downloads/netflix_titles.csv.zip') directors = df['director'].str.split(',\s*') Output: >>> directors 0 [Kirsten Johnson] 1 NaN 2 [Julien Leclercq] 3 NaN 4 NaN ... 8802 [David Fincher] 8803 NaN 8804 [Ruben Fleischer] 8805 [Peter Hewitt] 8806 [Mozez Singh] Name: director,... | 3 | 3 |
75,714,660 | 2023-3-12 | https://stackoverflow.com/questions/75714660/how-to-view-the-value-of-a-metashape-application-attribute-that-displays-in-angl | How do I access the value of an object attribute that displays in angle brackets like: <attribute 'version' of 'Metashape.Metashape.Application' objects>? Specifically, I am using the Metashape Python module and run the following lines within an interactive Python session: import Metashape a = Metashape.Application a.v... | According to the docs: An instance of Application object can be accessed using Metashape.app attribute, so there is usually no need to create additional instances in the user code. so... import Metashape print(Metashape.app.version) If you want to do it your way, you need to instance Application. import Metashape ap... | 3 | 4 |
75,713,961 | 2023-3-12 | https://stackoverflow.com/questions/75713961/python-requests-returns-403-even-with-headers | I'm trying to get content of website but my requests return me an 403 ERROR. After searching, I found Network>Headers section to add headers before GET request and tried these headers. from bs4 import BeautifulSoup as bs import requests url = "https://clutch.co/us/agencies/digital-marketing" HEADERS = {"User-Agent": "M... | You can try to load the page from the Google cache instead directly: import requests from bs4 import BeautifulSoup url = "https://clutch.co/us/agencies/digital-marketing" cache_URL = "https://webcache.googleusercontent.com/search?q=cache:" def get_data(link): hdr = { "User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexu... | 3 | 3 |
75,714,112 | 2023-3-12 | https://stackoverflow.com/questions/75714112/how-do-i-configure-pdm-for-a-src-based-python-repository | I have previously arranged a Python repository without a src folder, and got it running with: pdm install --dev pdm run mymodule I am failing to replicate the process in a repository with a src folder. How do I do it? pyproject.toml [project] name = "mymodule" version = "0.1.0" description = "Minimal Python repository... | You need to modify your pyproject.toml as follows: [project.scripts] mymodule = "mymodule.cli:invoke" For good measure, you may want to delete the .venv folder and .pdm.toml file before running pdm install --dev again. | 7 | 3 |
75,712,458 | 2023-3-12 | https://stackoverflow.com/questions/75712458/disable-postgres-index-updation-temporarily-and-update-the-indexes-manually-late | i have about 1300 CSV files with almost 40k of rows in each file, i have written a python code to read the file and convert all the 40k entries into single insert statement to insert in Postgres database. The psudocode is following for file in tqdm(files, desc="Processing files"): rows = ReadFile(file) # read all 40k r... | No, you cannot disable indexes. If the table is empty or almost empty when you start loading, you can win by dropping the indexes before you start and creating them again afterwards. However, INSERT performance should stay constant over time. It is difficult to guess what might be the cause. You can try using auto_expl... | 3 | 1 |
75,692,370 | 2023-3-10 | https://stackoverflow.com/questions/75692370/fastapi-how-to-customise-422-exception-for-specific-route | How to replace 422 standard exception with custom exception only for one route in FastAPI? I don't want to replace for the application project, just for one route. I read many docs, and I don't understand how to do this. Example of route that I need to change the 422 exception: from fastapi import APIRouter from pydant... | You can register multiple error handlers with the router. You can re-declare the default handler, and then optionally call it depending on the path: class PayloadSchema(BaseModel): value_int: int value_str: str router = APIRouter() @router.post('/standard') async def standard_route(payload: PayloadSchema): return paylo... | 5 | 3 |
75,678,711 | 2023-3-8 | https://stackoverflow.com/questions/75678711/why-does-the-moon-spiral-towards-earth-in-simulation | I am trying to simulate a somewhat realistic program where Earth and the moon can interact gravitationally with each other. Now the problem is that the moon keeps on spiraling towards Earth and I don't understand why. This is my code: from math import sin,cos,sqrt,atan2,pi import pygame pygame.init() class Planet: dt =... | You need to compute the forces in one go, not body-move by body-move. Instead of computing the forces during the update loop, while shifting positions: def motion(): for i in range(0,len(bodies)): Fnx = 0 #net force Fny = 0 for j in range(0,len(bodies)): if bodies[i] != bodies[j]: Fnx += (bodies[i].move(bodies[j]))[0] ... | 5 | 4 |
75,701,208 | 2023-3-10 | https://stackoverflow.com/questions/75701208/how-to-apply-condition-on-grouped-records-in-a-pyspark-dataframe | I am looking to find a solution to check multiple conditions within a group. First I'm checking for overlaps between records (based on id) and second I should make an exception for the highest numbered record within the same contagious overlap. On top of that, there can be multiple overlaps for same id. The example: da... | Join with self, and group by for the dataframe, count how many of the records are overlapped and get the validation. df.alias('a').join( df.alias('b'), (f.col('a.id') == f.col('b.id')) & (f.col('a.start') != f.col('b.start')) & (f.col('b.start').between(f.col('a.start'), f.col('a.end'))), 'left' ) \ .groupBy('a.id', 'a... | 3 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.