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
76,140,839
2023-4-30
https://stackoverflow.com/questions/76140839/regex-to-find-sequences-of-two-given-characters-that-alternate
I have written a small program to convert IPv6 addresses to ints and back, and I have managed to beat built-in ipaddress.IPv6Address in terms of performance. import re MAX_IPV6 = 2**128-1 DIGITS = set("0123456789abcdef") def parse_ipv6(ip: str) -> int: assert isinstance(ip, str) and len(ip) <= 39 segments = ip.lower()....
See the Python manual -> re.findall If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result. To match the desired sequences and prevent matching such as :00: a0: 0a: here an idea. res = re.findall(r":?\b(?:0\b:?)+", ip) See thi...
3
3
76,139,355
2023-4-30
https://stackoverflow.com/questions/76139355/flask-object-has-no-attribute-session-cookie-name
I keep getting the error 'Flask' object has no attribute 'session_cookie_name' right at initialization on an app that used to work. I built a smaller test app to test it and noticed that if I remove the line app.config["SESSION_TYPE"] = "filesystem" the error goes away. Problem is I need to use sessions in my Flask app...
This error happens when the currently used version of Flask does not have the session_cookie_name attribute. This attribute was added in Flask 2.0, so if you are using an older version of Flask, you will need to upgrade to a newer version. Just upgrade Flask by executing the command pip install --upgrade Flask Note: If...
5
1
76,139,696
2023-4-30
https://stackoverflow.com/questions/76139696/how-to-get-list-of-possible-replacements-in-string-using-regex-in-python
I have the following strings: 4563_1_some_data The general pattern is r'\d{1,5}_[1-4]_some_data Note, that numbers before first underscore may be the same for different some_data So the question is: how to get all possible variants of replacement using regex? Desired output: [4563_1_some_data, 4563_2_some_data, 456...
You need to iterate over a range object to create your list. Create that range object: To do that you need a pattern to get the [1-4] part from your pattern. You'll need another pattern to replace the number in the actual data with the variable from range object. import re text = "4563_1_some_data" original_pattern =...
3
2
76,136,469
2023-4-29
https://stackoverflow.com/questions/76136469/how-to-allow-hyphen-in-query-parameter-name-using-fastapi
I have a simple application below: from typing import Annotated import uvicorn from fastapi import FastAPI, Query, Depends from pydantic import BaseModel app = FastAPI() class Input(BaseModel): a: Annotated[str, Query(..., alias="your_name")] @app.get("/") def test(inp: Annotated[Input, Depends()]): return f"Hello {inp...
Problem Overview As explained here by @JarroVGIT, this is a behaviour coming from Pydantic, not FastAPI. If you looked closely at the error you posted: {"detail":[{"loc":["query","extra_data"],"msg":"field required","type":"value_error.missing"}]} it talks about a missing value for a query parameter named extra_data—h...
3
6
76,139,101
2023-4-30
https://stackoverflow.com/questions/76139101/wordle-copy-having-trouble-with-duplicate-letters-python
I’m trying to make a copy of the game Wordle but I’m having trouble dealing with duplicate letters. Here’s my code and I explain my logic a bit below. # a portion of the code, the logical bit # def minigame(): # wordle global wordGuess delay_print([f'You have 6 chances to guess the 5 letter word. Heres the coloring gui...
You dont handle the duplicate letters properly, the same letter can be counted multiple times as a correct letter in the wrong position. we can create a separate function to compare the guess and correct word and return the colored output for each letter. def userGuess(guess: str, correct: str): if guess == correct: fo...
3
1
76,138,438
2023-4-29
https://stackoverflow.com/questions/76138438/incompatible-types-in-assignment-expression-has-type-liststr-variable-has
If I run this code through mypy: if __name__ == '__main__': list1: list[str] = [] list2: list[str | int] = [] list2 = list1 It gives me following error: error: Incompatible types in assignment (expression has type "List[str]", variable has type "List[Union[str, int]]") Why? Isn't a list[str] a subset of list[str | in...
Generic types can be classified as covariant, contravariant, or invariant. When u is a subtype of v, a generic type g is covariant when g[u] is a subtype of g[v], contravariant when g[v] is a subtype of g[u], or invariant when neither g[u] nor g[v] is a subtype of the other. list is invariant because lists are mutabl...
3
4
76,138,324
2023-4-29
https://stackoverflow.com/questions/76138324/create-a-new-dataframe-by-breaking-down-the-columns-data-of-an-old-dataframe
I have the below dataframe salesman north_access south_access east_access west_access A 1 0 0 1 B 0 1 1 1 C 1 0 1 1 I want to convert the above into the below format salesman direction access A north 1 A south 0 A east 0 A west 1 B north 0 B south 1 B east 1 B west 1 I tried ex...
Another solution (using pd.wide_to_long): df.columns = [f'access_{c.split("_")[0]}' if "_access" in c else c for c in df.columns] x = pd.wide_to_long( df, stubnames="access", suffix=r".*", i=["salesman"], j="direction", sep="_" ).reset_index() print(x) Prints: salesman direction access 0 A north 1 1 B north 0 2 C nor...
3
5
76,113,195
2023-4-26
https://stackoverflow.com/questions/76113195/custom-optimizer-in-pytorch-or-tensorflow-2-12-0
I am trying to implement my custom optimizer in PyTorch or TensorFlow 2.12.0. With help of ChatGPT I always get code that have errors, what's more I can't find any useful examples. I would like to implement custom optimizer as: d1 contains sign of current derivatives d2 contains sign of previous derivatives step_size i...
I did it. class MyOptimizer(optim.Optimizer): def __init__(self, params, lr=1.0): defaults = dict(lr=lr) super(MyOptimizer, self).__init__(params, defaults) self.lr = {} self.d2 = {} for group in self.param_groups: for param in group['params']: self.lr[param] = torch.ones_like(param.data) * lr self.d2[param] = torch.on...
4
2
76,136,591
2023-4-29
https://stackoverflow.com/questions/76136591/parse-a-remote-xml-gz-file-of-a-database-without-downloading
I need to parse a Pubchem database to search for certain clues on the pages of compounds (Toxicity codes, to be exact, they look like 'H300'), and then add their CIDs to the correspondent lists The Database is here https://ftp.ncbi.nih.gov/pubchem/Compound/CURRENT-Full/XML/ But the xml.gz files there are so big that th...
One way I would approach this is to use curl and gunzip and maybe grep: Example: curl -ks https://ftp.ncbi.nih.gov/pubchem/Compound/CURRENT-Full/XML/Compound_000000001_000500000.xml.gz -o - | gunzip | grep someString This will stream down the file, and in realtime decompress it, which will allow you in realtime to gre...
3
2
76,135,606
2023-4-29
https://stackoverflow.com/questions/76135606/what-is-the-benefit-of-using-curried-currying-function-in-functional-programming
If you consider inner_multiply as an initializer of multiply, shouldn't you make them loosely coupled and DI the initializer (or any other way) especially if you require multiple initializers? Or am I misunderstanding the basic concept of curried function in FP? def inner_multiply(x): def multiply(y): return x * y retu...
You can define an entirely generic curry function like this: def curry(f): return lambda x: lambda y: f(x, y) Assume, in order to reproduce the example in the OP, that you also define a multiply function like this: def multiply(x, y): return x * y You can now partially apply multiply using curry: >>> multiply_by_3 = ...
3
5
76,129,498
2023-4-28
https://stackoverflow.com/questions/76129498/wordcloud-only-supported-for-truetype-fonts
I am trying to generate a word cloud using the WordCloud module in Python, however I see the following error whenever I call .generate Traceback (most recent call last): File "/mnt/6db3226b-5f96-4257-980d-bb8ec1dad8e7/test.py", line 4, in <module> wc.generate("foo bar foo bar hello world") File "/home/mjc/.local/lib/py...
I could not reproduce your error with Python 3.10 even after downloading the same font - though I am on macOS. The only thing I can imagine is that your PIL doesn't support TrueType fonts, so you can check with: python3 -m PIL Sample Output -------------------------------------------------------------------- Pillow 9....
10
3
76,124,622
2023-4-27
https://stackoverflow.com/questions/76124622/override-new-of-a-class-which-extends-enum
A class Message extends Enum to add some logic. The two important parameters are verbose level and message string, with other optional messages (*args). Another class MessageError is a special form of the Message class in which verbose level is always zero, everything else is the same. The following code screams TypeEr...
Enums are unusual (aka weird) in several regards, with creation being the biggest area. During enum class creation, after the members themselves have been created but before the class is returned, any existing __new__ is renamed to __new_member__1 and the __new__ from Enum itself is inserted into the class -- this is s...
4
8
76,130,356
2023-4-28
https://stackoverflow.com/questions/76130356/which-http-method-to-use-when-no-data-is-transfered-just-to-execute-code-in-an
I build an Flask API endpoint which when called will execute an action to process some data (the data are not send but come from the database). The result of the method(action) called is to update some fields in some database objects based on calculations performed on the objects themselves. Initially from what I found...
PATCH seems to be the correct method for your use case since you're updating some fields of a resource, although POST should also be fine. You can use 204 status code (which means api was successfully executed but there's no content to send) if you're updating the fields before api return. Refer this: https://developer...
3
1
76,126,686
2023-4-28
https://stackoverflow.com/questions/76126686/appending-a-single-row-to-a-dataframe-in-pandas-2-0
I have a DF as below. I have added a new column which has Total of all the rows and a new row which has total of all columns: A B C D Total ------------------- 1 2 3 4 10 5 6 7 8 26 6 8 10 12 36 Now I need to add one more row for which the first element will be NaN and rest will be a column subtracted from the previou...
This would be one of the rare use cases for df.append, but in lieu of that you can extract the last row with iloc[-1] and diff the individual values, then combine this back with the original. Option 1 One method of doing this concatenation would be using pd.concat df2 = pd.concat([df, df.iloc[-1].diff().to_frame().T]) ...
5
5
76,124,814
2023-4-27
https://stackoverflow.com/questions/76124814/how-to-take-the-cumulative-maximum-of-a-column-based-on-another-column
I have a DataFrame like this: import pandas as pd import numpy as np df = pd.DataFrame({ "realization_id": np.repeat([0, 1], 6), "sample_size": np.tile([0, 1, 2], 4), "num_obs": np.tile(np.repeat([25, 100], 3), 2), "accuracy": [0.8, 0.7, 0.8, 0.6, 0.7, 0.5, 0.6, 0.7, 0.8, 0.7, 0.9, 0.7], "prob": [0.94, 0.96, 0.95, 0.98...
It looks like: df['desired_accuracy'] = df['accuracy'].mask(df['prob'].lt(df['accum_max_prob'])).ffill() Output: realization_id sample_size num_obs accuracy prob accum_max_prob desired_accuracy 0 0 0 25 0.8 0.94 0.94 0.8 1 0 1 25 0.7 0.96 0.96 0.7 2 0 2 25 0.8 0.95 0.96 0.7 3 0 0 100 0.6 0.98 0.98 0.6 4 0 1 100 0.7 0...
2
4
76,124,270
2023-4-27
https://stackoverflow.com/questions/76124270/classes-as-dictionary-keys-in-python
So, I've done a lot of research on this and saw various other links and conferred with the Python documentation, however, I'm still a bit unclear on this. Maybe the way I see classes in Python is a bit wrong. As I understand, keys in a dictionary must be immutable. However, classes can be keys in a dictionary because o...
Instances of your C class are actually hashable, it comes with a default implementation of __hash__ which pertains to the identity of that object: >>> hash(c) # calls c.__hash__() 306169194 This __hash__ implementation allows your instance to be used as a key in a dictionary. This explains "Why doesn't changing things...
3
5
76,123,245
2023-4-27
https://stackoverflow.com/questions/76123245/why-is-set-remove-so-slow-here
(Extracted from another question.) Removing this set's 200,000 elements one by one like this takes 30 seconds (Attempt This Online!): s = set(range(200000)) while s: for x in s: s.remove(x) break Why is that so slow? Removing a set element is supposed to be fast.
I think this is happening because you are removing the first element in the set every time. This creates a set which is increasingly empty one each iteration, so each time you create a new iterator and call __next__, it has to search further and further away. So, here is the source code for the iterator __next__ It has...
4
7
76,119,007
2023-4-27
https://stackoverflow.com/questions/76119007/efficient-way-to-handle-group-of-ids-in-pandas
df = pd.DataFrame({ 'caseid': [1, 1, 1, 2, 2, 2, 3, 3, 3], 'timestamp': [10, 20, 30, 10, 20, 30, 10, 20, 30] 'var1': [np.nan, np.nan, np.nan, 10, np.nan, 11, 12, 13, 14], 'var2': [2., 3., 4., np.nan, 5., 6., np.nan, np.nan, np.nan] }) I need to find the first (and last) valid timestamp for each variable per caseid. I....
You can select the desired columns with filter (or manually), then replace the non-NA values with the timestamp (using mul and where), finally use a groupby.agg with first/last: m = df.filter(like='var').notna() out = (m.mul(df['timestamp'], axis=0).where(m) .groupby(df['caseid']).agg(['first', 'last']) ) Output: var...
2
6
76,113,063
2023-4-26
https://stackoverflow.com/questions/76113063/how-do-i-get-a-list-faster-with-an-index-relationship-between-two-large-size-lis
The question is given the following two lists. import numpy as np import random as rnd num = 100000 a = list(range(num)) b = [rnd.randint(0, num) for r in range(num)] Between two lists with a huge size(assuming that the reference list is a), a list indicating where the same element is located in the relative array(b) ...
I can give a specific answer that is very fast based on the fact that your first list is simply an index. If you combine them in a 2D array, you can then sort by the second list, which will put the first list (indices of the second list) in the order of the result you want: import numpy as np import random as rnd num =...
5
3
76,110,009
2023-4-26
https://stackoverflow.com/questions/76110009/getitem-only-gets-called-if-iter-is-defined
I am subclassing a dict and would love some help understanding the behavior below (please) [Python version: 3.11.3]: class Xdict(dict): def __init__(self, d): super().__init__(d) self._x = {k: f"x{v}" for k, v in d.items()} def __getitem__(self, key): print("in __getitem__") return self._x[key] def __str__(self): retur...
Python's internals often directly invoke the C-level implementations of built-in class functionality, even in cases where a subclass may have overridden that functionality, leading to a lot of weird bugs where method overrides aren't invoked where you'd expect them to be. This is the case for a lot of the dict implemen...
2
6
76,109,578
2023-4-26
https://stackoverflow.com/questions/76109578/searching-a-large-dataframe-with-a-multiindex-slow
I have a large Pandas DataFrame (~800M rows), which I have indexed on a MultiIndex with two indices, an int and a date. I want to retrieve a subset of the DataFrame's rows based on a list of ints (about 10k) that I have. The ints match the first index of the multi-index. The multi-index is unique. The first thing I tri...
It can be difficult to retrieve a subset of a DataFrame containing 800M rows. Here are some ideas to help your search go more quickly: Use .loc() with boolean indexing instead of pd.IndexSlice: Use boolean indexing with.loc() instead of pd.IndexSlice to slice your multi-index instead. This can assist Pandas in avoidi...
3
3
76,108,171
2023-4-26
https://stackoverflow.com/questions/76108171/why-does-sqlalchemy-recommend-using-built-in-id-as-column-name
Using reserved keywords or built-in functions as variable/attribute names is commonly seen as bad practice. However, the SQLALchemy tutorial is full of exampled with attributes named id. Straight from the tutorial >>> class User(Base): ... __tablename__ = "user_account" ... ... id: Mapped[int] = mapped_column(primary_k...
Firstly, id is not a keyword; if it was one, you would get a syntax error (try replacing id there with e.g. pass). It is a global identifier for a built-in function. And while it is a bad practice to clobber over the default identifiers defined by Python, note that id: Mapped[int] = mapped_column(primary_key=True) insi...
4
6
76,105,218
2023-4-25
https://stackoverflow.com/questions/76105218/why-does-tkinter-or-turtle-seem-to-be-missing-or-broken-shouldnt-it-be-part
I have seen many different things go wrong when trying to use the Tkinter standard library package, or its related functionality (turtle graphics using turtle and the built-in IDLE IDE), or with third-party libraries that have this as a dependency (e.g. displaying graphical windows with Matplotlib). It seems that even ...
WARNING: Do not use pip to try to solve the problem The Pip package manager cannot help to solve the problem. No part of the Python standard library - including tkinter, turtle etc. - can be installed from PyPI. For security reasons, PyPI now blocks packages using names that match the standard library. There are many p...
34
45
76,066,812
2023-4-20
https://stackoverflow.com/questions/76066812/how-to-combine-columns-in-polars-horizontally
I'm trying to combine multiple columns into 1 column with python Polars. However I don't seem to find an (elegant) way to combine columns into a list. I only need to combine column b - e into 1 column. Column a needs to stay exactly as it is now. I've tried using map_elements to achieve this. Despite the fact that this...
Use concat_list. pl.Config(fmt_table_cell_list_len=10, fmt_str_lengths=80) # increase repr defaults df.select('a', value=pl.concat_list(pl.exclude('a'))) shape: (3, 2) ┌─────┬──────────────────────┐ │ a ┆ value │ │ --- ┆ --- │ │ f64 ┆ list[f64] │ ╞═════╪══════════════════════╡ │ 0.1 ┆ [1.1, 2.1, 3.1, 4.1] │ │ 0.2 ┆ [...
3
8
76,052,153
2023-4-19
https://stackoverflow.com/questions/76052153/how-to-fill-a-column-with-random-values-in-polars
I would like to know how to fill a column of a polars dataframe with random values. The idea is that I have a dataframe with a given number of columns, and I want to add a column to this dataframe which is filled with different random values (obtained from a random.random() function for example). This is what I tried f...
You need a "column" of random numbers the same height as your dataframe? np.random.rand could be useful for this: df = pl.DataFrame({"foo": [1, 2, 3]}) df.with_columns(pl.lit(np.random.rand(df.height)).alias("prob")) shape: (3, 2) ┌─────┬──────────┐ │ foo ┆ prob │ │ --- ┆ --- │ │ i64 ┆ f64 │ ╞═════╪══════════╡ │ 1 ┆ 0...
7
8
76,083,485
2023-4-23
https://stackoverflow.com/questions/76083485/shap-instances-that-have-more-than-one-dimension
I am very new to SHAP and I would like to give it a try, but I am having some difficulty. The model is already trained and seems to perform well. I then use the training data to test SHAP with. It looks like so: var_Braeburn var_Cripps Pink var_Dazzle var_Fuji var_Granny Smith \ 0 1 0 0 0 0 1 0 1 0 0 0 2 0 1 0 0 0 3 0...
Try this: from shap import Explainer from shap.plots import beeswarm from sklearn.ensemble import RandomForestClassifier from sklearn.datasets import load_breast_cancer X, y = load_breast_cancer(return_X_y=True, as_frame = True) model = RandomForestClassifier().fit(X, y) explainer = Explainer(model) sv = explainer(X) ...
4
13
76,106,117
2023-4-25
https://stackoverflow.com/questions/76106117/python-resolve-forwardref
I have a typing.ForwardRef object as a remnant from earlier generic programming shenanigans. At this point I know the class represented by the ForwardRef exists, but how can I retrieve this type? A fairly minimal example of what I am doing. Convoluted solution for this example, but for the actual use case it makes sens...
You can evaluate a ForwardRef by calling ForwardRef._evaluate(globals(), locals(), frozenset()) on it. This assumes that the type behind the forward ref is known in these namespaces, i.e. you have imported the type into the local or global scope of the module. if isinstance(myref, ForwardRef): myref_type = myref._evalu...
5
4
76,074,394
2023-4-21
https://stackoverflow.com/questions/76074394/typeerror-multipolygon-object-is-not-iterable
I am trying to run the below script from plotly: https://plotly.com/python/county-choropleth/ I'm receiving the error code right out the gate: TypeError: 'MultiPolygon' object is not iterable I've looked up several posts where this is a similar issue, but I'm skeptical these are solutions for this particular issue. OPT...
I had the same error message recently and came across this post. I think the key is the migration of shapely to 2.x. You need to use the ".geoms" attribute now to make multi-part geometries iterable: https://shapely.readthedocs.io/en/stable/migration.html This resolved my issue.
6
1
76,100,975
2023-4-25
https://stackoverflow.com/questions/76100975/yolov8-custom-save-directory-path
I'm currently working in a project in which I'm using Flask and Yolov8 together. When I run this code from ultralytics import YOLO model = YOLO("./yolov8n.pt") results = model.predict(source="../TEST/doggy.jpg", save=True, save_txt=True) the output will be saved in this default directory /run/detect/ like Ultralytics ...
You can change the directory where the results are saved (save_dir) by modifying two arguments in predict: project and name results = model.predict(source=xxx, save_txt = True, project="xxx", name="yyy") such that: save_dir=project/name
3
7
76,070,711
2023-4-21
https://stackoverflow.com/questions/76070711/how-to-make-a-window-scroll-when-the-turtle-hits-the-edge
I made this Python program that uses psutil and turtle to graph a computer's CPU usage, real time. My problem is, when the turtle hits the edge of the window it keeps going, out of view - but I want to make the window scroll right, so the turtle continues graphing the CPU usage while staying at the edge of the window. ...
You can apply a Flappy Bird design to this problem. In that game, it looks like the bird is flying forward, but the implementation is actually such that the pipes are moving from the right side of the screen to the left and the bird doesn't move at all on the x-axis. Applying this to your case, you can slowly move the ...
3
2
76,092,263
2023-4-24
https://stackoverflow.com/questions/76092263/column-and-row-wise-logical-operations-on-polars-dataframe
In Pandas, one can perform boolean operations on boolean DataFrames with the all and any methods, providing an axis argument. For example: import pandas as pd data = dict(A=["a","b","?"], B=["d","?","f"]) pd_df = pd.DataFrame(data) For example, to get a boolean mask on columns containing the element "?": (pd_df == "?"...
I think one thing that might be making this more confusing is that you're not doing everything in the select context. In other words, don't do this: (pl_df == "?") The first thing we can do is pl_df.select(pl.all()=="?") shape: (3, 2) ┌───────┬───────┐ │ A ┆ B │ │ --- ┆ --- │ │ bool ┆ bool │ ╞═══════╪═══════╡ │ false ┆...
4
3
76,083,428
2023-4-23
https://stackoverflow.com/questions/76083428/importerror-cannot-import-name-json-normalize-from-pandas-io-json
python 3.9.2-3 pandas 2.0.0 pandas-io 0.0.1 Error: from pandas.io.json import json_normalize ImportError: cannot import name 'json_normalize' from 'pandas.io.json' (/home/casaos/.local/lib/python3.9/site-packages/pandas/io/json/__init__.py) Apparently this was a problem early on in the pre 1x days of pandas, but seem...
This was indeed the solution simply removing the import line. I'd have liked an attribute to check to determine the pandas version installed easily, but have to settle for a try:except: to determine if the import is needed. pandas.io.json.json_normalize was deprecated and removed in the newest version. Use pandas.json_...
10
10
76,065,035
2023-4-20
https://stackoverflow.com/questions/76065035/yahoo-finance-v7-api-now-requiring-cookies-python
url = 'https://query2.finance.yahoo.com/v7/finance/quote?symbols=TSLA&fields=regularMarketPreviousClose&region=US&lang=en-US' headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' } data = requests.get(url,headers=headers) prepost_data = data.j...
This worked for me. Make HTTP GET call to URL https://fc.yahoo.com. Although this call result in a 404 error, we just need it to extract set-cookie from response headers which is then used in the subsequent calls Now make an HTTP GET call to the URL https://query2.finance.yahoo.com/v1/test/getcrumb, by including the o...
9
21
76,073,605
2023-4-21
https://stackoverflow.com/questions/76073605/add-py-typed-as-package-data-with-setuptools-in-pyproject-toml
From what I read, to make sure that the typing information of your code is distributed alongside your code for linters to read, the py.typed file should be part of your distribution. I find answers for how to add these to setup.py but it is not clear to me 1. whether it should be included in pyproject.toml (using setup...
Yes, you should add py.typed to your package's source folder (same level as __init__.py). This informs type checkers, like mypy, that your package supports typing. See PEP 561. Here is an example of what is needed in pyproject.toml. Replace pkgname with the name of your package. [tool.setuptools.package-data] "pkgname"...
15
18
76,072,664
2023-4-21
https://stackoverflow.com/questions/76072664/convert-pyspark-dataframe-to-pandas-dataframe-fails-on-timestamp-column
I create my pyspark dataframe: from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StructField, BinaryType, ArrayType, StringType, TimestampType input_schema = StructType([ StructField("key", StringType()), StructField("headers", ArrayType( StructType([ StructField("key", StringType()), Struc...
I found the solution: from pyspark.sql.functions import date_format df = df.withColumn("timestamp", date_format("timestamp", "yyyy-MM-dd HH:mm:ss")).toPandas() Now I was able to use assert_frame_equal(df, test_df) successfully. It did not lose precision.
12
12
76,087,301
2023-4-23
https://stackoverflow.com/questions/76087301/how-to-change-a-text-color-of-a-code-cell-in-markdown
I need to change a text color of a code cell (namely code cell, not just a text block) that is defined using "`" symbols in Markdown. All my attempts have failed and the color stays the same, which is by default black I have tried to use <font color="...">...<\font> attribute and also <span style="color:...;">...<\span...
If you want to add syntax highlighting to a programming language, it can be written like this: # For example, you want to use Python ```python print("the syntax is highlighted") ``` The result would be like this: print("the syntax is highlighted") EDIT: As far as I know, Markdown doesn't support color. So what you'll...
3
3
76,079,699
2023-4-22
https://stackoverflow.com/questions/76079699/computing-a-norm-in-a-loop-slows-down-the-computation-with-dask
I was trying to implement a conjugate gradient algorithm using Dask (for didactic purposes) when I realized that the performance were way worst that a simple numpy implementation. After a few experiments, I have been able to reduce the problem to the following snippet: import numpy as np import dask.array as da from ti...
I think the code snippet is missusing lazy evaluation in dask, specifically the addition operation. Without optimization, the addition lambda x: x+x is complicating the execution graph, with the depth growing with counter, hence overheads. More precisely, for the counter value i we handle the graph of O(i) when computi...
6
2
76,099,140
2023-4-25
https://stackoverflow.com/questions/76099140/hugging-face-transformers-bart-cuda-error-cublas-status-not-initialize
I'm trying to finetune the Facebook BART model, I'm following this article in order to classify text using my own dataset. And I'm using the Trainer object in order to train: training_args = TrainingArguments( output_dir=model_directory, # output directory num_train_epochs=1, # total number of training epochs - 3 per_d...
I was able to reproduce your problem, here is how I solved it (on both of the clusters you provided). In order to solve it I used (at the from_pretrained call): ignore_mismatched_sizes=True: because the model you use has fewer labels than what you have num_labels={}: Insert the number of your labels, I used 16 just to...
3
3
76,058,279
2023-4-19
https://stackoverflow.com/questions/76058279/the-travelling-salesman-problem-using-genetic-algorithm
I was looking to learn about AI and found the traveling salesman problem very interesting. I also wanted to learn about genetic algorithms, so it was a fantastic combo. The task is to find the shortest distance traveling from id 1 to each location from the list once and returning to the starting location id 1 Restricti...
Turns out everything is fine tweaking the distance function and the fit_proportionate_selection ensures a faster run time which makes testing the parameters faster. The other change is to have a fixed seed for the random() this way the results can be compared without much variant. def fit_proportionate_selection(top_po...
4
0
76,068,150
2023-4-20
https://stackoverflow.com/questions/76068150/how-to-use-inspect-signature-to-check-that-a-function-needs-one-and-only-one-par
I want to validate (at runtime, this is not a typing question), that a function passed as an argument takes only 1 positional variable (basically that function will be called with a string as input and returns a truthy). Naively, this is what I had: def check(v_in : Callable): """check that the function can be called w...
I don't think your problem is trivial, at all. And I am not aware of any given implementation, so I followed your train of thoughts and came to the conclusion that in the end, the problem boils down to answering the following questions: Does the callable have any arguments, at all? If so, is the first argument positio...
3
2
76,103,041
2023-4-25
https://stackoverflow.com/questions/76103041/how-to-change-background-color-of-the-title-of-legend
In the example below, how can I change the background color of "Title" to be red (with alpha=.5), not the font color of "Title"? import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1,2,3,], [1,2,3], label='Series') legend = ax.legend(title='Title') # Access to the legend title box adapted from # https://s...
You can change the color of the bounding box of the title text: import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3, ], [1, 2, 3], label='Series') legend = ax.legend(title='Title') legend._legend_title_box._text.set_bbox(dict(facecolor='red', alpha=0.3, lw=0)) plt.show() PS: For the red backgrou...
3
4
76,105,881
2023-4-25
https://stackoverflow.com/questions/76105881/why-does-python-defaultdict-use-factory-method-pattern
Python has a defaultdict class which behaves like a dictionary, except that it outputs a default value when encountering a new key. This default value is created using the default_factory attribute, which is a function that takes no arguments. For example, d = defaultdict(int) creates a dictionary d whose default value...
Think about how this would work for mutable types. For example, d = defaultdict(list) creates a new list object for each unassigned key that is requested. If you used a single instance, then each key would be returning the same instance of that list. Appending to an instance returned by one key, e.g. d[1].append(2) wou...
3
6
76,082,216
2023-4-22
https://stackoverflow.com/questions/76082216/python-pip-error-externally-managed-environment-after-upgrading-to-ubuntu-23-0
I'm running Ubuntu Server and upgraded it from 22.10 to 23.04. After the installation finished, I tried running one of my python scripts and one of my modules went missing. I tried to reinstall it with pip3 install playsound but I get this error: error: externally-managed-environment × This environment is externally ma...
Figured it out, just needed to activate the virtual environment I made.
7
2
76,099,798
2023-4-25
https://stackoverflow.com/questions/76099798/print-all-python-logs-within-github-action
I have a GitHub Action that calls a python script: - name: Test Python Script run: | python python_script.py This runs fine and prints me the logs from within here: if __name__ == "__ main __": print('Calling function') func_call() print('End of script') However, I don't get the print statements from func_call itself...
The solution was relatively simple, just adding the -u flag: - name: Test Python Script run: | python -u python_script.py From man python: -u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode.
5
4
76,101,455
2023-4-25
https://stackoverflow.com/questions/76101455/reformat-bidirectional-bar-chart-to-match-example
I have generated this bar-chart Using this code: s = """level,margins_fluid,margins_vp Volume,0,0 1L*,0.718,0.690 2L,0.501,0.808 5L,0.181,0.920 MAP,0,0 64*,0.434,0.647 58,0.477,0.854 52,0.489,0.904 Exam,0,0 dry,0.668,0.713 euvolemic*,0.475,0.798 wet,0.262,0.893 History,0,0 COPD*,0.506,0.804 Kidney,0.441,0.778 HF,0.450...
There is a some simplification/factorization you can deal with to make styling your plots easier. But you are basically almost there. Just set the tick labels and remove spaces between plots with fig.subplots_adjust(wspace=0) (you have to remove fig.tight_layout()): from io import StringIO import matplotlib.pyplot as p...
3
2
76,071,127
2023-4-21
https://stackoverflow.com/questions/76071127/find-spline-knots-by-variable-in-python
When fitting a linear GAM model in python imposing n_splines=5, a piecewise-linear function is fitted: import statsmodels.api as sm from pygam import LinearGAM data = sm.datasets.get_rdataset('mtcars').data Y = data['mpg'] X = data.drop("mpg",axis=1) model = LinearGAM(spline_order=1,n_splines=5).fit(X, Y) By using .co...
Finally I have come up with a solution, in this one I use partial dependence to calculate the function with its slope changes. In this one I take double differences and with it the change of slope. XX = model_gam.generate_X_grid(term=i) pdep, confi = model_gam.partial_dependence(term=i, X=XX, width=0.95) first_diff...
5
2
76,089,319
2023-4-24
https://stackoverflow.com/questions/76089319/express-relation-between-enum-and-its-member-in-python-typing
How to type (in Python, e.g. for MyPy) a function that expects two parameters - an enum and one of its values/members? from enum import Enum from typing import TypeVar, Type class MyEnumA(Enum): A = 1 B = 2 class MyEnumB(Enum): A = 1 B = 2 TE = TypeVar('TE', bound=Enum) def myfunction(member: TE, e: Type[TE]) -> None: ...
The key observation is what MyPy actually considers a class MyEnumA to be: reveal_type(MyEnumA) # mypy: Revealed type is "def (value: builtins.object) -> e.MyEnumA" It gives a clue to annotate myfunction in the following way, no matter how unobvious it is: P = ParamSpec('P') def myfunction(member: TE, e: Callable[P, T...
8
1
76,087,617
2023-4-23
https://stackoverflow.com/questions/76087617/how-to-search-with-regexp-within-blocks
I have a long file that is composed of many blocks like this: x=0 abc 20 def 76 ghi 11 x=1 def 45 ghi 32 x=2 jkl 56 mno 76 abc 134 . . . x=393 xyz 21 abc 9 x=394 ghi 43 def 166 xyz 25 I need the regular expression (for python) to get this output: return_list = [20,'x',134,...,9,'x'] (so matches for abc and x should b...
You can achieve the result you want with a single regex, by changing your regex to terminate at either abc = \d+ or \n\n or \Z (to allow a match of the last group at the end of the string - this is required for your sample data as it doesn't finish with \n\n). (?ms)(?=x=\d).*?(?:abc (\d+)|\n\n|\Z) If abc = \d+ is pres...
3
4
76,086,714
2023-4-23
https://stackoverflow.com/questions/76086714/can-i-set-a-variable-with-the-result-of-match
Setting a variable with a match can be done simply like this: Mode = 'fast' puts = '' match Mode: case "slow": puts = 'v2 k5' case "balanced": puts = 'v3 k5' case "fast": puts = 'v3 k7' But can you do something like this? Mode = 'fast' puts = match Mode: case "slow": 'v2 k5' case "balanced": 'v3 k5' case "fast": 'v3 k...
Not as far as I know in python. In this case I wouldn't use pattern matching at all: puts = { "slow": "v2 k5", "balanced": "v3 k5", "fast": "v3 k7" }.get(Mode, default) Clearer, more declarative, and no repeating yourself. But of course you can't use clever pattern destructuring.
8
13
76,077,950
2023-4-22
https://stackoverflow.com/questions/76077950/how-do-you-copy-a-dataframe-in-polars
In polars, what is the way to make a copy of a dataframe? In pandas it would be: df_copy = df.copy() But what is the syntax for polars?
That would be clone : df = pl.DataFrame( { "a": [1, 2, 3, 4], "b": [0.5, 4, 10, 13], "c": [True, True, False, True], } ) df_copy = df.clone() #cheap deepcopy/clone Output : ​ print(df_copy) ​ shape: (4, 3) ┌─────┬──────┬───────┐ │ a ┆ b ┆ c │ │ --- ┆ --- ┆ --- │ │ i64 ┆ f64 ┆ bool │ ╞═════╪══════╪═══════╡ │ 1 ┆ 0.5 ┆ ...
7
11
76,067,104
2023-4-20
https://stackoverflow.com/questions/76067104/using-vicuna-langchain-llama-index-for-creating-a-self-hosted-llm-model
I want to create a self hosted LLM model that will be able to have a context of my own custom data (Slack conversations for that matter). I've heard Vicuna is a great alternative to ChatGPT and so I made the below code: from llama_index import SimpleDirectoryReader, LangchainEmbedding, GPTListIndex, \ GPTSimpleVectorIn...
length is too long, 9999 will consume huge amount of GPU RAM, especially using 13b model. try 7b model. And try using something like peft/bitsandbytes to reduce GPU RAM usage. set load_in_8bit=True is a good start.
6
2
76,073,794
2023-4-21
https://stackoverflow.com/questions/76073794/difference-between-creating-indexes-in-django-using-db-index-true-and-class-meta
I was looking into how to create an index in Django. I came across two ways: Class Student(models.Model): name= models.CharField(........, db_index=True) age= models.CharField(........, db_index=True) Class Student(models.Model): name= models.CharField(........) age= models.CharField(........) Class Meta: indexes = [m...
The latter will make a combined index, so an index that takes the two fields, and makes a retrieval if both fields are specified efficient. This means that if only name is given to filter on, the index will (likely) not be useful, if you only specify the age, this will be the same, only if you specify both name and age...
5
0
76,064,194
2023-4-20
https://stackoverflow.com/questions/76064194/store-users-credentials-in-python-package
I'm working on a Python package where I need to get credentials (email and password) from the user via CLI and they can enter their credentials just as follows. $ my_package auth --email abc@efg.com --password testpass123 My package is responsible for storing and using the provided credentials in the next calls (even ...
In memory: These days most operating systems have memory protection which prevents other processes to access the memory used by some other process(you may specifically ask for sharing the memory though). So even a Python variable could do the job(just get it from sys.argv and store it in a variable) or an environment v...
3
2
76,072,637
2023-4-21
https://stackoverflow.com/questions/76072637/how-to-check-the-frequency-of-a-word-in-the-english-language
My problem: I want to check if the provided word is a common English word. I'm using pyenchant currently to see if a word is an actual word but I can't find a function in it that returns the frequency of a word/if it's a common word. Example code: import enchant eng_dict = enchant.Dict("en_US") words = ['hello', 'world...
You could use the Google Ngram API for this: url = "https://books.google.com/ngrams/json" query_params = { "content": <my_noun_phrase/string of noun phrases>, "year_start": 2017, "year_end": 2019, "corpus": 26, "smoothing": 1, "case_insensitive": True } response = requests.get(url=url, params=query_params) This API le...
3
4
76,071,934
2023-4-21
https://stackoverflow.com/questions/76071934/how-to-correctly-subtype-dict-so-that-mypy-recognizes-it-as-generic
I have a subclass of dict: class MyDict(dict): pass Later I use the definition: my_var: MyDict[str, int] = {'a': 1, 'b': 2} MyPy complains: error: "MyDict" expects no type arguments, but 2 given [type-arg] How can I define MyDict so that MyPy recognizes it as generic with two type arguments? I have tried deriving fr...
As a general rule you can remember to always provide type arguments to generic types, regardless of context. (Remember: explicit is better than implicit.) This means in annotations (e.g. d: dict[str, int]) and when subclassing (e.g. class MyDict(dict[str, int]): ...). If you want to retain genericity in terms of some o...
7
5
76,065,984
2023-4-20
https://stackoverflow.com/questions/76065984/how-to-provide-type-hint-for-a-function-that-returns-an-protocol-subclass-in-pyt
If a function returns a subclass of a Protocol, what is the recommended type-hint for the return type of that function? The following is a simplified piece of code for representation from typing import Protocol, Type from abc import abstractmethod class Template(Protocol): @abstractmethod def display(self) -> None: ......
Protocols are not ABCs Let me start of by emphasizing that protocols were introduced specifically so you do not have to define a nominal subclass to create a subtype relation. That is why it is called structural subtyping. To quote PEP 544, the goal was allowing users to write [...] code without explicit base classes ...
3
3
76,070,545
2023-4-21
https://stackoverflow.com/questions/76070545/fastapi-difference-between-json-dumps-and-jsonresponse
I am exploring FastAPI, and got it working on my Docker Desktop on Windows. Here's my main.py which is deployed successfully in Docker: #main.py import fastapi import json from fastapi.responses import JSONResponse app = fastapi.FastAPI() @app.get('/api/get_weights1') async def get_weights1(): weights = {'aa': 10, 'bb'...
In FastAPI you can create response 3 different ways (from most concise to most flexible): 1 return dict # Or model or ... In docs you linked we can see that FastAPI will automatically stringify this dict and wrap it in JSONResponse. This way is most concise and covers majority of use cases. 2 However sometimes you hav...
3
3
76,069,958
2023-4-21
https://stackoverflow.com/questions/76069958/how-to-change-the-format-of-a-date-in-python-to-the-spanish-format
I have a small problem with my date code. I would like the date to appear in Spanish add the date in Spanish. The date is currently formatted like this: 2004/03/30 But I want the formatting to be like this: 04/21/2023 What I'm trying to do is display any date in Spanish, as follows: Viernes, 02 De Junio De 2023 Is ther...
You can use the babel library to localize the date to Spanish. pip install babel The code would look like this: from datetime import datetime from babel.dates import format_date s = '2004/03/30' date = datetime.strptime(s, "%Y/%m/%d") # Spanish locale spanish_date = format_date(date, "EEEE, dd 'de' MMMM 'de' yyyy", lo...
3
3
76,069,849
2023-4-21
https://stackoverflow.com/questions/76069849/matplotlib-and-axes3d-give-a-blank-picture
I want to draw a 3D picture with these data using matplotlib and Axes3D import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D data = np.array([[4244.95, 4151.69, 2157.41, 829.769, 426.253, 215.655], [8263.14, 4282.98, 2024.68, 1014.6, 504.515, 250.906], [8658.01, 4339.53, 2173.56, 1...
replace this line ax = Axes3D(fig) with ax = fig.add_subplot(projection='3d') you do this in order to alert Matplotlib that we're using 3d data.
3
10
76,069,337
2023-4-21
https://stackoverflow.com/questions/76069337/how-to-create-a-function-which-applies-lag-to-a-numpy-array-in-python
Here are 3 numpy arrays with some numbers: import numpy as np arr_a = np.array([[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.3, 0.4, 0.5, 0.6], [0.4, 0.5, 0.6, 0.7], [0.5, 0.6, 0.7, 0.8], [0.6, 0.7, 0.8, 0.9]]) arr_b = np.array([[0.15, 0.25, 0.35, 0.45], [0.35, 0.45, 0.55, 0.65], [0.55, 0.65, 0.75, 0.85], [0.75, 0.85...
Slice your input array based on the given lag and then subtract the sliced arrays. import numpy as np def calc_acc_change(array, lag=2): acc_change = np.zeros_like(array) acc_change[:, lag:] = array[:, lag:] - array[:, :-lag] return acc_change arr_a = np.array([[0.1, 0.2, 0.3, 0.4], [0.2, 0.3, 0.4, 0.5], [0.3, 0.4, 0.5...
3
3
76,059,511
2023-4-19
https://stackoverflow.com/questions/76059511/how-would-you-properly-use-the-python-c-api-in-a-c-shared-library
Apologies in advance for the extremely long question--it has been a journey... so thanks in advance for your patience. TL;DR: python throws a segfault when using this set up: [numpy code] <-- [python/C api] <-- [C-implemented .so library] <-- [py driver using ctypes' cdll] Note the py driver is just for testing the .so...
When using functions exported by cdll.LoadLibrary, you're releasing the Global Interpreter Lock (GIL) as you enter the method. If you want to call python code, you need to re-acquire the lock. e.g. void someFunctionWithPython() { ... PyGILState_STATE state = PyGILState_Ensure(); printf("importing numpy...\n"); PyObject...
3
3
76,068,163
2023-4-20
https://stackoverflow.com/questions/76068163/is-it-possible-to-get-list-of-parameters-passed-into-a-constructor
Let's say I have this code snippet: class A: def __init__(self, p1=1, p2=None, p3="test"): self.p1 = p1 self.p2 = p2 self.p3 = p3 a1 = A() a2 = A(p1=2, p3="blah") What I want to do is to somehow retrieve ONLY the named parameters that are passed into the constructor, not including the optional parameters with default ...
You can intercept the arguments in __new__ like this: class A: def __init__(self, p1=1, p2=None, p3="test"): self.p1 = p1 self.p2 = p2 self.p3 = p3 def __new__(cls, *args, **kwargs): print(f"{kwargs = }") return super().__new__(cls) >>> a1 = A() kwargs = {} >>> a2 = A(p1=2, p3="blah") kwargs = {'p1': 2, 'p3': 'blah'}
5
4
76,059,875
2023-4-20
https://stackoverflow.com/questions/76059875/add-annotation-between-line-gap-in-plotly
I have a graph like this: Instead of the days being on top of the symbol, I was wondering if there is a way I can add this annotation between the lines? From one dot to another. I apologize if in case, this is a possible duplicate. This is my expected output: This is my current code for the annotation: fig.add_annot...
What you can do is create a new dataframe for your annotations by ordering your original df by the order_date, then take the average datetime and average sales between consecutive rows to determine where to place the annotations. To obtain the text, you can take the difference in time between consecutive orders. Your d...
3
3
76,057,261
2023-4-19
https://stackoverflow.com/questions/76057261/why-does-react-to-flask-call-fail-with-cors-despite-flask-cors-being-included
I need to read data from flask into react. React: const data = { name: 'John', email: 'john@example.com' }; axios.post('http://127.0.0.1:5000/api/data', data) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); Flask: from flask import Flask, request, jsonify from flask_cors import ...
The problem is that you are limiting the path /api/data to the http method POST @app.route('/api/data', methods=['POST']) CORS requires the client to make an OPTIONS 'pre-flight' call on that path to find out which origins are allowed (and other stuff like headers). Because your code only permits POST the OPTIONS call ...
4
5
76,062,184
2023-4-20
https://stackoverflow.com/questions/76062184/remove-last-character-if-it-is-number-from-data-frames-that-are-stored-as-a-valu
I wrote the code as follows to remove last character of Data Frames columns if it is number. Data Frames are stored as a values of dictionary in python and their name as a key of dictionary. my code doesn't produce the right result, how should I develop it? for key,val in df.items(): if key != "name1": for col in val.c...
You can simplify your code by just replacing a single digit at the end of a column name with an empty string. This will not affect any values that don't end with a digit: for key, val in df.items(): if key != "name1": val.columns = val.columns.str.replace(r'\d$', '', regex=True)
3
3
76,060,546
2023-4-20
https://stackoverflow.com/questions/76060546/what-allows-nan-to-work-with-the-python-list-inclusion-operator
Pretty much anyone who works with IEEE floating-point values has run into NaN, or "not a number", at some point. Famously, NaN is not equal to itself. >>> x = float('nan') >>> x == x False Now, I had come to terms with this, but there's a strange behavior I'm struggling to wrap my head around. Namely, >>> x in [x] Tru...
According to the docs it first uses the is operator to check for equality, and since x is x is True, x in [x] is also True: For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y). Note that identity (is) is different...
5
5
76,059,187
2023-4-19
https://stackoverflow.com/questions/76059187/how-do-i-indicate-that-the-value-of-an-enum-is-an-unstable-implementation-detai
The official Enum HOWTO has this example: class Planet(Enum): MERCURY = (3.303e+23, 2.4397e6) VENUS = (4.869e+24, 6.0518e6) EARTH = (5.976e+24, 6.37814e6) MARS = (6.421e+23, 3.3972e6) JUPITER = (1.9e+27, 7.1492e7) SATURN = (5.688e+26, 6.0268e7) URANUS = (8.686e+25, 2.5559e7) NEPTUNE = (1.024e+26, 2.4746e7) def __init__...
The exact value of any enum is nearly always an implementation detail; the reason it's exposed at all is that sometimes it's useful to be able to access it. There are several ways to de-emphasize it's presence: change the repr() of that enum class def __repr__(self): return '<%s.%s>' % (self.__class__.__name__, self...
3
2
76,056,906
2023-4-19
https://stackoverflow.com/questions/76056906/secure-route-in-fastapi
I have a Flask-based backend REST API and I want to migrate to FastAPI. However, I am not sure how to implement secure routes and create access tokens in FastAPI. In Flask, we have methods from the flask_jwt_extended library such as: @jwt_required() decorator for secure routes create_access_token() function for creati...
You can use libs like python-jose for JWT functionalities, but you have to implement jwt_required and create_access_token by yourself, for example create_access_token from jose import JWTError, jwt from datetime import datetime, timedelta def create_access_token(data: dict): to_encode = data.copy() expire = datetime.ut...
4
1
76,055,891
2023-4-19
https://stackoverflow.com/questions/76055891/fastapi-background-task-takes-up-to-100-times-longer-to-execute-than-calling-fun
I have simple fastAPI endpoint deployed on Google Cloud Run. I wrote the Workflow class myself. When the Workflow instance is executed, some steps happen, e.g., the files are processed and the result are put in a vectorstore database. Usually, this takes a few seconds per file like this: from .workflow import Workflow ...
With Cloud Function, like Cloud Run, the CPU is allocated (and billed) only when a request is processed. A request is considered being processed between the reception of the request and the sending of the response. The rest of the time, the CPU is throttled (below 5%). That's being said, look back to your functions. ...
5
4
76,056,936
2023-4-19
https://stackoverflow.com/questions/76056936/mysql-data-folder-keeps-growing-even-after-drop-table
I'm using MySQL (8.0.33-winx64, for Windows) with Python 3 and mysql.connector package. Initially my mysql-8.0.33-winx64\data folder was rather small: < 100 MB. Then after a few tests of CREATE TABLE..., INSERT... and DROP TABLE..., I notice that even after I totally drop the tables, the data folder keeps growing: #in...
You can disable the binary log, but only by setting disable_log_bin in your my.cnf file and restarting the MySQL Server. (See Disable MySQL binary logging with log_bin variable ) You can't change binary logging dynamically. See https://dev.mysql.com/doc/refman/8.0/en/replication-options-binary-log.html#sysvar_log_bin Y...
3
5
76,056,289
2023-4-19
https://stackoverflow.com/questions/76056289/using-pydantic-parent-attribute-to-validate-child
Is it possible to use a containing object's attribute during the validation of a child object in a pydantic model? Given the json data: # example.json { "multiplier": 5, "field_1": { "value": 1 }, "field_2": { "value": 2 } } and the corresponding Pydantic model: # example.py from pydantic import BaseModel, validator c...
Simplest approach is to perform validation on the parent instead of the child: from pydantic import BaseModel, validator class Item(BaseModel): value: int class Container(BaseModel): multiplier: int field_1: Item field_2: Item @validator("field_1", "field_2") def validate_value(cls, v, values): """Validate each item"""...
5
3
76,057,225
2023-4-19
https://stackoverflow.com/questions/76057225/replace-a-part-of-string-in-pandas-data-column-replace-doesnt-work
I have been trying to clean my data column by taking a part of the text out. Unfortunately cannot get my head around it. I tried using the .replace method in pandas series, but that did not seem to have worked df['Salary Estimate'].str.replace(' (Glassdoor est.)', '',regex=True) 0 $53K-$91K (Glassdoor est.) 1 $63K-$112...
If you enable regex, you have to escape regex symbol like (, ) or .: import re >>> df['Salary Estimate'].str.replace(re.escape(r' (Glassdoor est.)'), '',regex=True) 0 $53K-$91K 1 $63K-$112K 2 $80K-$90K 3 $56K-$97K 4 $86K-$143K Name: Salary Estimate, dtype: object # Or without import re module >>> df['Salary Estimate']....
3
3
76,054,155
2023-4-19
https://stackoverflow.com/questions/76054155/django-count-in-annotate-and-subquery-are-much-slower-than-simply-iterating-over
I'm trying to count how many documents per project (among other things) have been registered, Registered also holds other values like DateTime and User (just a disclosure they are unrelated to my issue). Iterating through a list and querying ~54 times ends up being much faster than Annotate or Subquery (13 vs 27 second...
I think you can use GROUP BY functionality here like this: Document.objects.filter(batch__project__completion_date__isnull=True).values('batch__project').annotate(doc_count= Count('pk')).values('batch__project','doc_count') More information on documentation Regarding the performance issue, there is no straight answer...
3
3
76,054,181
2023-4-19
https://stackoverflow.com/questions/76054181/cleaning-a-large-csv-file-efficiently
Problem: I have a CSV file with a large amount of data, and I need to perform some data cleaning and filtering operations on it using Python. For instance, the CSV file contains a column with dates in the format "YYYY-MM-DD", but some of the entries have incorrect formatting or missing values. I need to clean up these ...
I would recommend to use the pandas module which enables to handle csv data efficiently in Python. For instance, the following code solves your problem: import pandas as pd # Read the CSV file into a pandas dataframe df = pd.read_csv('data.csv') # Clean up the date column df['date'] = pd.to_datetime(df['date'], errors=...
4
2
76,050,901
2023-4-19
https://stackoverflow.com/questions/76050901/haystack-save-inmemorydocumentstore-and-load-it-in-retriever-later-to-save-embe
I am using InMemory Document Store and an Embedding retriever for the Q/A pipeline. from haystack.document_stores import InMemoryDocumentStore document_store = InMemoryDocumentStore(embedding_dim =768,use_bm25=True) document_store.write_documents(docs_processed) from haystack.nodes import EmbeddingRetriever retriever_m...
InMemoryDocumentStore: features and limitations From Haystack docs: Use the InMemoryDocumentStore, if you are just giving Haystack a quick try on a small sample and are working in a restricted environment that complicates running Elasticsearch or other databases. Slow retrieval on larger datasets. No Approximate Nea...
4
3
76,051,250
2023-4-19
https://stackoverflow.com/questions/76051250/how-to-remove-unused-packages-installed-with-pip-in-python
I have Python project and have installed hundreds of packages using pip over time. However, I have since improved my code and suspect that some of these packages are no longer in use. I want to remove all of the unused packages. I am already familiar with the pip uninstall package-name command and have seen suggestions...
Dependency management in Python is a painful topic. Check out this excellent overview: https://chriswarrick.com/blog/2023/01/15/how-to-improve-python-packaging/ I highly recommend you check out Poetry or Hatch for dependency and packaging management. In general you should at least always use virtual environment. This a...
3
2
76,050,130
2023-4-19
https://stackoverflow.com/questions/76050130/copy-the-schema-from-one-dataframe-to-another
I have a Spark data frame (df1) with a particular schema, and I have another dataframe with the same columns, but different schema. I know how to do it column by column, but since I have a large set of columns, it would be quite lengthy. To keep the schema consistent across dataframes, I was wondering if I could be abl...
Yes, its possible dynamically with dataframe.schema.fields df2.select(*[(col(x.name).cast(x.dataType)) for x in df1.schema.fields]) Example: from pyspark.sql.functions import * df1 = spark.createDataFrame([('2022-02-02',2,'a')],['A','B','C']).withColumn("A",to_date(col("A"))) print("df1 Schema") df1.printSchema() #df1 ...
6
5
76,046,269
2023-4-18
https://stackoverflow.com/questions/76046269/how-to-align-annotation-to-the-edge-of-whole-figure-in-plotly
I know how to align annotation respective to the plotting area (using xref="paper"). I want to place the annotation to right bottom corner of the whole figure. Absolute or relative offset does not work, since the width of the margin outside the plotting area is changing among several figures, depending on their content...
So the thing is that you technically can't automatically calculate and position annotations at a perfect spot in the corner of the figure for every plot (outside of the plot, but inside the figure). The problem is that to do so, you would need to be able to get the dimensions of every plot, which could be undefined whe...
4
2
75,998,227
2023-4-12
https://stackoverflow.com/questions/75998227/how-to-define-query-parameters-using-pydantic-model-in-fastapi
I am trying to have an endpoint like /services?status=New status is going to be either New or Old Here is my code: from fastapi import APIRouter, Depends from pydantic import BaseModel from enum import Enum router = APIRouter() class ServiceStatusEnum(str, Enum): new = "New" old = "Old" class ServiceStatusQueryParam(Ba...
To create a Pydantic model and use it to define query parameters, you would need to use Depends() along with the parameter in your endpoint. To add description, title, etc., to query parameters, you could wrap the Query() in a Field(). It should also be noted that one could use the Literal type instead of Enum, as desc...
9
23
76,035,847
2023-4-17
https://stackoverflow.com/questions/76035847/polars-python-limits-number-of-printed-table-output-rows
Does anyone know why polars (or maybe my pycharm setup or python debugger) limits the number of rows in the output? This drives me nuts. Here is the polars code i am running but I do suspect its not polars specific as there isnt much out there on google (and chatgpt said its info is too old haha). import polars as pl d...
Looks like the following will work. Thanks to @wayoshi for sharing this. I will say that the defaults are way too conservative! with pl.Config(tbl_rows=1000): print(result_df) or throw this at the top of your script if you prefer to not manage contexts. import polars as pl # Configure Polars cfg = pl.Config() cfg.set_...
6
9
76,000,750
2023-4-13
https://stackoverflow.com/questions/76000750/pandas-problem-when-assigning-value-using-loc
So what is happening is the values in column B are becoming NaN. How would I fix this so that it does not override other values? import pandas as pd import numpy as np # %% # df=pd.read_csv('testing/example.csv') data = { 'Name' : ['Abby', 'Bob', 'Chris'], 'Active' : ['Y', 'Y', 'N'], 'A' : [89, 92, np.nan], 'B' : ['eye...
You can implement this by creating a boolean mask using the condition: Where the 'Active' column is 'N' and the 'A' column has missing values (np.nan). We can then use this mask to filter rows in the DataFrame. First, we will replace the values in column 'A' with 99 for rows where the mask condition is True. Then, repl...
3
3
76,005,401
2023-4-13
https://stackoverflow.com/questions/76005401/cant-install-xmlsec-via-pip
I'm getting the following when running pip install xmlsec in macOS Big Sur 11.3.1: Building wheels for collected packages: xmlsec Building wheel for xmlsec (PEP 517) ... error ERROR: Command errored out with exit status 1: command: /Users/davidmasip/.pyenv/versions/3.9.9/bin/python3.9 /Users/davidmasip/.pyenv/versions/...
EDIT This GitHub comment is the simplest fix. https://github.com/xmlsec/python-xmlsec/issues/254#issuecomment-1612005910 When libxmlsec1 was bumped to v1.3 it broke pip install xmlsec. https://github.com/xmlsec/python-xmlsec/issues/254 I am using a Macbook with Apple Silicon (M1 / M2) and struggled for a while to ...
15
34
76,038,966
2023-4-17
https://stackoverflow.com/questions/76038966/type-hinting-pandas-dataframe-content-and-columns
I am writing a function that returns a Pandas DataFrame object. I would like to have a type hint that specifies which columns this DataFrame contains, besides just specifying in the docstring, to make it easier for the end user to read the data. Is there a way to type hint DataFrame content like this? Ideally, this wou...
The most powerful project for strong typing of pandas DataFrame as of now (Apr 2023) is pandera. Unfortunately, what it offers is quite limited and far from what we might have wanted. Here is an example of how you can use pandera in your case†: import pandas as pd import pandera as pa from pandera.typing import DataFra...
14
18
76,028,283
2023-4-16
https://stackoverflow.com/questions/76028283/missing-the-lzma-lib
The following message means that Python has not been installed completely. If Yes! Do I have to install the 'lzma' extension? ModuleNotFoundError: No module name '_lzma' Warning: The Python lzma extension was not compiled. Missing the lzma lib? Installed Python-3.11.3 to /Users/admin/.pyenv/versions/3.11.3 Thank you!
Per Chris' comment, the solution is to install OS-specific dependencies then use pyenv to install a python version.
25
12
76,038,513
2023-4-17
https://stackoverflow.com/questions/76038513/isort-black-strange-behavior
When applying isort 5.12.0 in pre-commit within a python file, it re-orders the imports in bad. In bitbucket pipelines, the same code orders correctly. This correct code: from dagster import build_init_resource_context from module1 import setting from module1.resources.apple import AppleConnector as apple_connector fro...
In .pre-commit-config.yaml isort configuration, I had to add module1 as a first-party package. That avoided different interpretations in different repositories. Then pre-commit worked consistently in all the pipelines. - repo: https://github.com/PyCQA/isort rev: 5.12.0 hooks: - id: isort args: ["--profile", "black", "-...
3
0
76,043,689
2023-4-18
https://stackoverflow.com/questions/76043689/pkg-resources-is-deprecated-as-an-api
When I try to install from a .tar.gz package, while making warnings into errors: python -W error -m pip install /some/path/nspace.pkga-0.1.0.tar.gz I get this error: ERROR: Exception: Traceback (most recent call last): File "/opt/util/nspace1/lib/python3.11/site-packages/pip/_internal/cli/base_command.py", line 169, i...
There is a related discussion on pip's ticket tracker. It seems like this issue has been solved in pip 23.1.1: "Revert pkg_resources (via setuptools) back to 65.6.3". And pip 23.1.2 seems to vendor the new setuptools (and pkg_resources) as expected but without the deprecation warnings (see also this message).
27
19
76,018,799
2023-4-14
https://stackoverflow.com/questions/76018799/how-to-clear-user-input-before-python-exits
If a program exits before all of its input has been consumed, then the remaining input will be sent to the shell. Here's an example: import sys for line in sys.stdin: sys.exit() Try running the example and copy-paste this multi-line input: foo bar baz The result will look like this: ❯ python example.py foo bar baz% ❯...
On Unix systems you can use os.set_blocking before reading the input. If the user pastes a large amount of text, then the terminal may be holding on to additional input that hasn't been sent to stdin yet. It may not be possible for the program to see this, so the following code includes a sleep to allow for the termina...
4
2
76,019,272
2023-4-14
https://stackoverflow.com/questions/76019272/error-when-i-open-spyder-pylsp-1-7-2-1-8-0-1-7-1-nok
I tried to upgrade conda and spyder, but I encountered an issue. I tried: conda update anaconda conda install spyder=5.4.3 pip install pylsp-mypy I used option 1 in the spyder terminal first and then I used it in the conda prompt, I don't know if that caused the error. How can I solve this issue? Edit (temporal solu...
Please use this instead: conda install -c conda-forge python-lsp-server
12
14
76,031,802
2023-4-17
https://stackoverflow.com/questions/76031802/python-kubernetes-client-equivalent-of-kubectl-api-resources-namespaced-false
Via the CLI, I can use kubectl api-resources --namespaced=false to list all available cluster-scoped resources in a cluster. I am writing a custom operator with the Python Kubernetes Client API, however I can't seem to find anything in the API that allows me to do this. The closest I have found is the following code, w...
I managed to solve the issue. For anyone wondering, the Python client API unfortunately does not have an equivalent function to kubectl api-resources, or kubectl api-resources --namespaced=false. I was able to create my own solution to this using the API, which you can see below. To get similar output to kubectl api-re...
3
4
76,040,523
2023-4-18
https://stackoverflow.com/questions/76040523/auto-gpt-command-evaluate-code-returned-error-the-model-gpt-4-does-not-exis
I'm working with auto-gpt and I got this error: Command evaluate_code returned: Error: The model: `gpt-4` does not exist and it's like it can't go furthermore. what should I do?
Update your .env file in your repo so that both are = to gpt-3.5-turbo SMART_LLM_MODEL=gpt-3.5-turbo FAST_LLM_MODEL=gpt-3.5-turbo this issue is happening because you do not have API access to GPT4.
5
11
76,046,538
2023-4-18
https://stackoverflow.com/questions/76046538/is-there-a-way-to-check-if-a-dataframe-is-contained-within-another
I am using pandas to check wether two dataframes are contained within each others. the method .isin() is only helpful (e.g., returns True) only when labels match (ref: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.isin.html) but I want to check further that this to include cases where the labels don't m...
You can use numpy's sliding_window_view: from numpy.lib.stride_tricks import sliding_window_view as swv (swv(df1, df2.shape)==df2.to_numpy()).all((-2, -1)).any() Output: True Intermediate: (swv(df1, df2.shape)==df2.to_numpy()).all((-2, -1)) array([[False, False, False, False], [False, True, False, False], # df2 is fou...
4
4
76,034,389
2023-4-17
https://stackoverflow.com/questions/76034389/google-analytics-is-not-working-on-streamlit-application
I have built a web application using streamlit and hosted it on the Google Cloud Platform (App Engine). The URL is something like https://xxx-11111.uc.r.appspot.com/ which is given for the Stream URL. I enabled Google Analytics 2 days back but apparently, it is not set up correctly. It was given that I need to add in t...
One way to implement Google Analytics into your GAE Streamlit app would be to add the GA global site tag JS code to the default /site-packages/streamlit/static/index.html file NOTE: This script should be run prior to running the streamlit server from bs4 import BeautifulSoup import shutil import pathlib import logging ...
6
4
76,012,502
2023-4-14
https://stackoverflow.com/questions/76012502/cant-reach-restapi-fastapi-from-my-flutter-web-cross-origin-request-blocked
I have a Linux Server. On that I have two Docker Containers.In the first one I am deploying my Flutter Web and in the other one I am running my RestAPI with FastAPI(). I set both the Docker containers in the same Network, so the communication should work. I also set origins with origins = ['*'] (Wildcard). I reverse pr...
I solved my problem. If anyone face the same problem in the future, here is the answer. My mistake was to call the server with http/https, while in the same (Docker) Network. So I changed: final Uri tokenUri = Uri.https(urlList[index]['url']!, ''); to final Uri tokenUri = Uri.parse('${urlList[index]['url']!}/'); One ...
3
4
76,045,605
2023-4-18
https://stackoverflow.com/questions/76045605/using-a-custom-trained-huggingface-tokenizer
I’ve trained a custom tokenizer using a custom dataset using this code that’s on the documentation. Is there a method for me to add this tokenizer to the hub and to use it as the other tokenizers by calling the AutoTokenizer.from_pretrained() function? If I can’t do that how can I use the tokenizer to train a custom mo...
The AutoTokenizer expects a few files in the directory: awesometokenizer/ tokenizer_config.json special_tokens_map.json tokenizer.json But the default tokenizer.Tokenizer.save() function only saves the vocab file in awesometokenizer/tokenizer.json, open up the json file and compare the ['model']['vocab'] keys to your ...
4
4
76,039,364
2023-4-17
https://stackoverflow.com/questions/76039364/extract-raw-sql-from-sqlalchemy-with-replaced-parameters
Given a sql query such as query = """ select some_col from tbl where some_col > :value """ I'm executing this with sqlalchemy using connection.execute(sa.text(query), {'value' : 5}) Though this does what's expected, I would like to be able to get the raw sql, with replaced parameters. Meaning I would like a way to be...
The SQLAlchemy documentation for Rendering Bound Parameters Inline explains how we can use literal_binds: query = "select some_col from tbl where some_col > :value" print( sa.text(query) .bindparams(value=5) .compile(compile_kwargs={"literal_binds": True}) ) # select some_col from tbl where some_col > 5
3
5
76,047,250
2023-4-18
https://stackoverflow.com/questions/76047250/what-else-goes-in-a-python-src-folder-according-to-actual-or-de-facto-standards
When using src layout rather than flat layout in a Python project, is anything other than the project module expected to live in the src folder? My understanding is that if I added mypkg2 under src in the layout below, and published the result to PyPI, anyone who did a pip install would be able to import mypkg and impo...
In a correct src-layout project, the only things that should be present in the src directory are the top-level import packages and top-level import modules (sub-packages are in the sub-directories of the top-level packages, obviously). By convention each distribution package contains one and only one top-level import p...
7
7
75,992,698
2023-4-12
https://stackoverflow.com/questions/75992698/how-do-i-click-on-clickable-element-with-selenium-in-shadow-root-closed
An "Agree with the terms" button appears on https://www.sreality.cz/hledani/prodej/domy I am trying to go through that with a .click() using Selenium and Python. The button element is: <button data-testid="button-agree" type="button" class="scmp-btn scmp-btn--default w-button--footer sm:scmp-ml-sm md:scmp-ml-md lg:scmp...
Check the below working workaround solution: driver = webdriver.Chrome() driver.implicitly_wait(10) driver.get("https://www.sreality.cz/hledani/prodej/domy") driver.maximize_window() # Below line creates instance of ActionChains class action = ActionChains(driver) # Below line locates and stores an element which is out...
3
3
76,043,784
2023-4-18
https://stackoverflow.com/questions/76043784/how-to-add-pydantic-serialization-deserialization-support-for-a-foreign-third-p
Consider a third-party class that doesn't support pydantic serialization, and you're not under control of the source code of that class, i.e., you cannot make it inherit from BaseModel. Let's assume the entire state of that class can be constructed and obtained via its public interface (but the class may have private f...
In general, the process of defining custom field types is described in this section of the documentation. The bare minimum is a method called __get_validators__ returning an iterator of validation methods, the last of which should return an instance of that custom type. That means with third-party classes you will almo...
4
4
76,044,951
2023-4-18
https://stackoverflow.com/questions/76044951/how-to-handle-errors-correctly-in-django
I have a question, I know that it is possible to do global exception handling in python, but how to do it for all views, namely, I am interested in DetailView, but others will also come in handy.I understand that you need to give your own examples of solutions, but could you give an example of how this can be done, bec...
The methodology here involves a couple things. First, within those views, you want to make sure you are getting those errors within an except block as your code does. Then you should return an HttpResponseRedirect object redirecting the user to the error page or another page where you would like for the user to return....
3
2
76,045,518
2023-4-18
https://stackoverflow.com/questions/76045518/finding-the-average-of-differences-between-each-row
Good morning, everyone. I'm trying to try to find the differences between two rows. I'm trying to put a formula together, but I feel like I'm making things too complicated when an easier answer may be available, and my code's not perfect. Here's my example dataset. cols = ['Name', 'Math', 'Science', 'English', "History...
# student to find difference student = 'Tom' # create your mask where the name is the student name mask = df['Name'].eq(student) # concat you masks together and set the index data = pd.concat([df[mask], df[~mask]]).set_index('Name') # get the mean from the differnce abs(data.iloc[0, :] - data.iloc[1:, :]).mean(axis=1) ...
3
4