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,812,405
2023-8-1
https://stackoverflow.com/questions/76812405/typeerror-stringmethods-rsplit-takes-from-1-to-2-positional-arguments-but-3-w
I'm trying to use Series.str.rsplit to return everything up to the delimiter, but can't seem to get past this TypeError I'm receiving: TypeError: StringMethods.rsplit() takes from 1 to 2 positional arguments but 3 were given I am using pandas 2.0.3. Here is my code: import pandas as pd df1 = pd.DataFrame({'name': ['to...
In Pandas 1.4 and before, the .rsplit method used ordinary parameters, so a call like this would mean that ' ' is the delimiter and 1 is the maximum number of times to split - just like the built-in method of the str class. However, starting in 1.5, n and expand are keyword-only parameters. To use them, the name needs ...
6
11
76,806,185
2023-7-31
https://stackoverflow.com/questions/76806185/what-is-the-meaning-of-valueerror-shapes-200-200-and-199-not-aligned-200
I am trying to simulate an option pricing scheme by defining functions (Black-Scholes and Crank-Nicolson) and comparing them. The implementation of the Crank-Nicolson scheme with boundary conditions is as follows (I include the full code for replication): import numpy as np from scipy.stats import norm from scipy.integ...
The error is caused since B.shape[1] is M, whereas V[1:-1, n-1].shape[0] is M-1, which do not match, thus I'd guess the error is due to the function definition. Changing A = np.diag(alpha[2:], -1) + np.diag(1+beta[1:]) + np.diag(gamma[:-2], 1) B = np.diag(-alpha[2:], -1) + np.diag(1-beta[1:]) + np.diag(-gamma[:-2], 1) ...
3
1
76,793,045
2023-7-29
https://stackoverflow.com/questions/76793045/python-error-showing-pygame-and-gymnasium-classic-control-not-installed-howev
I have just started learning OpenAI gymnasium and started with CartPole-v1. Being new I was following a YouTube tutorial; video:https://www.youtube.com/watch?v=Mut_u40Sqz4&t=2076s (I am up to 1:08:22) and I also wanted to see a window of the game. However when running the code, Python threw this error: Traceback (mos...
You have not installed pygame. The error message already shows that you have to do: pip install gymnasium[classic-control]. Considering the video provided in OG was from 6th of June 2021, the Gym version (not Gymnasium) must have been 0.18.3 or lower. The syntax has changed a lot throughout the newer Gym versions, whic...
2
1
76,806,529
2023-7-31
https://stackoverflow.com/questions/76806529/find-ranges-of-a-larger-range-not-covered-by-a-list-of-subranges
Apologies for the perhaps confusing title. Suppose you have a range (0,10000) and a list of smaller sub-ranges that may overlap [(20,3460),(200,3000),(2800,8704)] and you want to return the ranges of the original range NOT covered by the sub-ranges, in this case [(0, 19), (8705, 10000)] I am trying to figure out how to...
intspan can be used to get the complement of the sub ranges. from intspan import intspan start, end = (0,10000) subs = [(20,3460),(200,3000),(2800,8704)] span = intspan.from_ranges(subs) comp = span.complement(low=start, high=end).ranges() print(comp) Prints: [(0, 19), (8705, 10000)]
2
3
76,805,028
2023-7-31
https://stackoverflow.com/questions/76805028/scipy-genextreme-fit-returns-different-parameters-from-matlab-gev-fit-function-o
I'm trying to port some code from MATLAB to PYTHON and I realized gevfit function in MATLAB seems to behave differently from scipy genextreme, so I realized this minimal example: MATLAB % Create the MATLAB array x = [0.5700, 0.8621, 0.9124, 0.6730, 0.5524, 0.7608, 0.2150, 0.5787, ... 0.7210, 0.7826, 0.8181, 0.5449, 0.7...
The method genextreme.fit is failing to compute the correct result. You can help it generate the correct value by providing initial values for the numerical solver that are better than the default used by genextreme.fit. The initial values are set by providing values for the shape, location and scale parameters: In [29...
3
1
76,806,273
2023-7-31
https://stackoverflow.com/questions/76806273/pandas-add-increment-index
I have the following Pandas DataFrame Key Value A 10 A 20 B 30 B 40 C 50 A 60 A 70 A 70 B 80 A 90 And I need to create an index that auto increment only when the key repeats after sequence of different keys. So, I need this output: Key Value Index A 10 1 A 20 1 B 30 1 B 40 1 C 50 1 A 60 2 A 70 2 A 70 2 B 80 2 A 90 3 ...
Using an ordered Categorical and numpy.cumsum: import numpy as np s = pd.Categorical(df['Key'], ordered=True) df['Index'] = np.cumsum(s<s.shift())+1 If you want a custom order pass categories=['X', 'Z', 'Y']. Or, like @SimonT commented, if your categories are lexicographically sorted: df['Index'] = np.cumsum(df['Key']...
3
1
76,805,676
2023-7-31
https://stackoverflow.com/questions/76805676/how-to-replace-loop-with-if-and-elif-but-without-else-by-list-comprehensio
I am trying to use list comprehension for below code # Input values = [1, 2, 3, 4] # Using for loop ans = [] for value in values: if value == 1: ans.append(value + value) elif value == 4: ans.append(value * value) print(f"Ans: {ans}") # Using list comprehension ans = [ (value + value) if value == 1 else (value * valu...
I'm guessing that this is a small example of something more complicated, but as it is it is fairly easy to create a comprehension like: values = [1, 2, 3, 4] ans = [ value + value if value == 1 else value * value for value in values if value in [1,4] ] print(ans)
2
6
76,802,047
2023-7-31
https://stackoverflow.com/questions/76802047/remove-a-string-from-the-column-when-it-meets-the-condition
I would like to remove the string from a string column when it contains a lower letter (the string column may be NaN or include multiple string in one row) Column1 Column2 Column3 NaN NaN NaN BCDE8ENGUGUETNJN NaN NaN vk4JGFIEh5 NaN NaN t7chJGWYEj BCSTACK BCTENSORFLOW 5hNIE7EEP OVERFLOW NaN The origi...
One option, check for [a-z] with str.contains and mask: out = df.mask(df.apply(lambda s: s.str.contains('[a-z]').fillna(True))) Or, with replace: out = df.replace('.*[a-z].*', float('nan'), regex=True) Output: Column1 Column2 Column3 0 NaN NaN NaN 1 BCDE8ENGUGUETNJN NaN NaN 2 NaN NaN NaN 3 NaN BCSTACK BCTENSORFLOW 4...
3
1
76,801,382
2023-7-31
https://stackoverflow.com/questions/76801382/parsing-data-from-bash-table-with-empty-fields
I am currently trying to parse some data from bash tables, and I found strange behavior in parsing data if some columns is empty for example i have data like this containerName ipAddress memoryMB name numberOfCpus status --------------- --------------- ---------- ------- -------------- ---------- TEST_VM 192.168.150.11...
Don't parse the file manually, take advantage of pandas.read_fwf: df_info = pd.read_fwf(StringIO(table), skiprows=[1], delim_whitespace=True) df_info.columns = df_info.columns.str.strip() Output: containerName ipAddre memoryMB name numberOfCpu tatu 0 TEST_VM_second 3072 TEST_VM_second_renamed 1 POWERED_OFF Or, to ge...
4
1
76,786,670
2023-7-28
https://stackoverflow.com/questions/76786670/what-is-the-difference-between-threshold-and-prominence-in-scipy-signal-find-pe
I'm trying to find the peaks of a noisy signal using scipy.signal.find_peaks and I realised that I don't fully understand the difference between the threshold and prominence arguments. I understand that prominence is equivalent to topographical prominence, i.e. the height of a peak relative to the surrounding terrain. ...
Threshold is about vertical distance to the samples right before and after. Prominence is about vertical distance to the deepest valley. Here's a visual explanation of the difference: In this graph of cos(x), the peak has a threshold of 0.191, and a prominence of 2. What implications does this have? Threshold is good...
6
6
76,777,140
2023-7-27
https://stackoverflow.com/questions/76777140/manage-supabase-as-an-infrastructure-as-a-code-for-version-control
I want to be able to manage my Supabase project as a code, with regards to the SQL tables, the functions, auth, et cetera. The purpose is to allow myself to version control the project. I have gone through the official documentation and have not found anything pertaining to this. The closest approach I can find is simp...
Everything (except for some auth related features) you mentioned can be done with the Supabase CLI and it's migration capabilities. There is a guide on thw website explaining how to manage environments for this sort of setup https://supabase.com/docs/guides/cli/managing-environments.
4
3
76,798,411
2023-7-30
https://stackoverflow.com/questions/76798411/solving-assignment-problem-with-or-tools-with-number-of-tasks
I am trying to understand how OR-TOOLS works and wanted to solve the assignment problem but with number of tasks (2 out of 4) as constraints. But my code does not work as expectected. I have tried: from ortools.sat.python import cp_model costs = [ [90, 80, 75, 70], [35, 85, 55, 65], [125, 95, 90, 95], [45, 110, 95, 115...
This can be achieved using channeling constraint Expressing @AirSquid's idea in CP-SAT syntax: task_assigned = [model.NewBoolVar(f"task_assigned{i}") for i in range(num_tasks)] for task_id in range(num_tasks): sum_expr = sum([x[worker][task_id] for worker in range(num_workers)]) model.Add(sum_expr >= 1).OnlyEnforceIf(t...
2
1
76,797,647
2023-7-30
https://stackoverflow.com/questions/76797647/how-to-filter-part-of-a-multi-index-level-dataframe-with-different-conditions
Here is an original dataframe, country2 year 2017 2018 2019 country1 1 2 1 2 3 6 data_provider indicator prov_1 ind_a 45 30 22 30 30 30 prov_2 ind_a 30 30 30 30 25 30 ind_b 30 32 30 30 30 30 prov_3 ind_b 30 30 30 35 30 28 and I wish to filter the column and finally get a new dataframe, # item country2 # year 2017 201...
import pandas as pd df = pd.DataFrame( data={ "data_provider": ["prov_1", "prov_1", "prov_2", "prov_2", "prov_3", "prov_3"], "indicator": ["ind_a", "ind_a", "ind_a", "ind_b", "ind_b", "ind_b"], "unit": ["EUR", "EUR", "EUR", "EUR", "EUR", "EUR"], "year": ["2017", "2018","2019", "2017","2018","2019"], "country1": [1, 1, ...
2
5
76,793,693
2023-7-29
https://stackoverflow.com/questions/76793693/how-to-simplify-huge-arithmatic-expression
I've a huge expression like: x49 + t49 + FUNC1(y49 + z49 + FUNC1(w49 + h49 + FUNC1(v49) + RET(v49, t49, z49) + movr[50] + m1[50]) + RET(w49 + h49 + FUNC1(v49) + RET(v49, t49, z49) + movr[50] + m1[50], v49, t49) + movr[51] + m1[51]) + RET(y49 + z49 + FUNC1(w49 + h49 + FUNC1(v49) + RET(v49, t49, z49) + movr[50] + m1[50])...
The following function extracts all function calls and puts them into variables. def simplify(progstr, variable_prefix='x'): progstr = f' {progstr} ' prog = [] while progstr.count('(') > 0: for i, c in enumerate(progstr): if c == ')': c2, i2 = None, i while c2 != '(': i2 -= 1 c2 = progstr[i2] i2 -= 1 c2 = progstr[i2] w...
4
3
76,793,660
2023-7-29
https://stackoverflow.com/questions/76793660/remove-first-letter-prefix-of-the-command-message
so i am currently making the error handles for my discord bot, and when it returns that it has not all arguments, this is my code: @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send(f'❓ it seems like your entry `{ctx.message.content}` **does not con...
You can simply use the ctx.command.name attribute: @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): command = ctx.command.name await ctx.send(f'❓ it seems like your entry `{ctx.message.content}` **does not contain all needed arguments!** try `+help {command}` fo...
3
2
76,794,391
2023-7-29
https://stackoverflow.com/questions/76794391/difference-between-all-and-all-for-checking-if-an-iterable-is-true-everywhe
I believe there are two ways of checking if a torch.Tensor has values all greater than 0. Either with .all() or all(), a Minimal Reproducible Example will illustrate my idea: import torch walls = torch.tensor([-1, 0, 1, 2]) result1 = (walls >= 0.0).all() # DIFFERENCE WITH BELOW??? result2 = all(walls >= 0.0) # DIFFEREN...
all is Python builtin, meaning that it only works using extremely generic interfaces. In this case, all treats the tensor as an opaque iterable. It proceeds by iterating the elements of the tensor one-by-one, constructing a Python object for each one and then checking the truthiness of that Python object. That is slow,...
2
3
76,790,233
2023-7-28
https://stackoverflow.com/questions/76790233/how-to-make-pylance-and-pydantic-understand-each-other-when-instantiating-basemo
I am trying to instantiate user = User(**external_data), where User is Pydantic BaseModel, but I am getting error from Pylance, which don't like my external_data dictionary and unable to figure out that data in the dict is actually correct (see first screenshot). I found a workaround by creating TypedDict with the sam...
Why the errors? These warnings are to be expected because the type of your external_data object (without using a TypedDict) will be inferred by Pylance as dict[str, U], where U is the union of all the types it sees in the dictionary values. In your example U = int | str | datetime | list[int]. Normal dictionaries are h...
3
2
76,788,887
2023-7-28
https://stackoverflow.com/questions/76788887/polars-apply-function-dosent-pass-column-name-to-function
I am migrating my old code from pandas to polars. But i am not able to have a workaround for apply function. I have a function where i do some calculation from the data received from apply function where i have to use some column. My code In pandas for example: import pandas as pd data = {'A': [1, 2, 3], 'B': [4, 5, 6]...
The solution is to stop thinking in terms of apply. You can do something like ( pl.from_pandas(df) .with_columns( calc_data= pl.concat_list( pl.col(var1)+pl.col(var2), pl.col(var1)*pl.col(var2) ) ) ) shape: (3, 3) ┌─────┬─────┬───────────┐ │ A ┆ B ┆ calc_data │ │ --- ┆ --- ┆ --- │ │ i64 ┆ i64 ┆ list[i64] │ ╞═════╪═════...
3
1
76,787,417
2023-7-28
https://stackoverflow.com/questions/76787417/in-python-combine-two-iterator-based-on-time
I'd like to combine two iterators and yield the value(s) of the iterator that has the highest timestamp. Minimal example and expectations: # Outputs of these generators are "timestamps" def gen_even(): for x in range(0, 11, 2): yield x def gen_odd(): for x in sorted(list(range(1, 15, 2)) + [6]): yield x Combining thes...
You could avoid the stop iterator by handling it as follows: def gen_both(gen1, gen2): first = next(gen1, None) second = next(gen2, None) while True: if first is None and second is None: break elif first is None: yield second second = next(gen2, None) elif second is None: yield first first = next(gen1, None) else: if f...
4
2
76,781,391
2023-7-27
https://stackoverflow.com/questions/76781391/speed-up-loading-of-multiple-csv-files
I am trying to write a parser/API for the France's public drug database (https://base-donnees-publique.medicaments.gouv.fr/). It consists of eight CSV files (in fact TSV as they use tabs), each from a few kB to 4MB, the biggest having ~20000 lines (each line representing a drug with its name, codes, prices, etc). As th...
As usual: run a profiler on your code to see where it's spending its time. (This is PyCharm's, it wraps the stdlib cProfile.) Sequential: 7.865187874995172 Huh, okay. strptime, I can tell that'd get called by datetime.datetime.strptime. Also, weird, getlocale... why do we need locales there? Clicking through to the ...
2
3
76,780,968
2023-7-27
https://stackoverflow.com/questions/76780968/pytables-install-with-python-3-11-fails-on-macos-m1
$ python -m pip install tables stops with Error: compiling Cython file Environment (I am within a virtual environment, created with pyenv. ) Only few packages installed atm Package Version ---------- ------- Cython 3.0.0 numpy 1.25.1 pip 23.2.1 setuptools 65.5.0 wheel 0.41.0 My exports export HDF5_DIR="$(brew --pre...
I managed to reproduce your issue, the problem seems to be installing the package from PyPi. From the error message it seems the Cython cannot find lzo libraries. The solution of the mentioned GitHub thread seems to be installing c-blosc, which also did not fix the problem for me. There are two options that worked for ...
6
6
76,785,441
2023-7-28
https://stackoverflow.com/questions/76785441/python-pandas-filter-columns-for-true-false-and-both
I am currently trying to filter a pandas df with certain boolean columns for true, false and both types within a loop. For better explanation let's say we have the following df: df = pd.DataFrame({ 'a': [1, 2, 3, 5, 6, 7, 8, 9, 10], 'b': [True, True, True, False, False, True, False, True, False], 'c': [True, False, Fal...
Using any doesn't make sense here, this is a function not a generic term that pandas would understand. Why not using a set for your conditions? T = {True} F = {False} ANY = {True, False} NONE = {} loops = [[T, T], [T, ANY], [ANY, T], [ANY, ANY]] for loop in loops: x = df[df['b'].isin(loop[0]) & df['c'].isin(loop[1])]['...
2
4
76,778,911
2023-7-27
https://stackoverflow.com/questions/76778911/faster-way-to-split-a-large-csv-file-evenly-by-groups-into-smaller-csv-files
I'm sure there is a better way for this but I am drawing a blank. I have a CSV file in this format. The ID column is sorted so everything is grouped together at least: Text ID this is sample text, AAAA this is sample text, AAAA this is sample text, AAAA this is sample text, AAAA this is sample text, AAAA this is sample...
Using any awk in any shell on every Unix box: $ cat tst.awk NR==1 { hdr = $0 next } $NF != prev { out = (((blockCnt++) % X) + 1) ".csv" if ( blockCnt <= X ) { print hdr > out } prev = $NF } { print > out } $ awk -v X=3 -f tst.awk input.csv $ head [0-9]*.csv ==> 1.csv <== Text ID this is sample text, AAAA this is sa...
5
4
76,784,012
2023-7-27
https://stackoverflow.com/questions/76784012/pip-install-e-fails-with-expected-end-or-semicolon-for-githttps-in-require
I have a requirements.txt that uses git+https URLs like git+https://github.com/myorg/myrepo@v1.0.0#egg=mypackage This installs fine with pip install -r requirements.txt . But if I reference it in my setup.cfg: [options] install_requires = file: requirements.txt and pip install -e . my package as an editable install f...
It looks like setuptools requires the package name to be supplied as a prefix, then the fetch URL after an @, e.g. # requirements.txt mypackage @ git+https://github.com/myorg/myrepo@v1.0.0#egg=mypackage This form is accepted by pip install -e . with a setup.cfg that indirectly references the requirements.txt, and by p...
5
9
76,771,761
2023-7-26
https://stackoverflow.com/questions/76771761/why-does-llama-index-still-require-an-openai-key-when-using-hugging-face-local-e
I am creating a very simple question and answer app based on documents using llama-index. Previously, I had it working with OpenAI. Now I want to try using no external APIs so I'm trying the Hugging Face example in this link. It says in the example in the link: "Note that for a completely private experience, also setup...
Turns out I had to set the embed_model to "local" on the ServiceContext. ServiceContext.from_defaults(chunk_size=1024, llm=llm, embed_model="local") Also, when I was loading the vector index from disk I wasn't setting the llm predictor again which cause a secondary issue. So I decided to make the vector index a global...
20
25
76,780,741
2023-7-27
https://stackoverflow.com/questions/76780741/how-to-read-zipfile-from-stdin
I'm trying to solve reading a zipfile from stdin in python, but I keep getting issues. What I want is to be able to run cat test.xlsx | python3 test.py and create a valid zipfile.ZipFile object without first writing a temporary file if possible. My initial approach was this, but ZipFile complained the file is not seeka...
Zip files are binary data, not UTF-8 encoded text. You won't be able to read the file into a str with sys.stdin.read() without immediately hitting a UnicodeDecodeError: 'utf-8' codec can't decode byte ... error. Instead, you can access the underlying binary buffer object to read stdin as raw bytes. Pair that with Bytes...
2
3
76,780,929
2023-7-27
https://stackoverflow.com/questions/76780929/how-do-reverse-the-indexing-order-of-a-sub-loop-every-other-pass
I have a 2 dimensional array (10x10) that represents x & y positions. I'm writing a script that goes to each position, does some stuff, then moves to the next position. The most efficient way would be to start in one corner, scan at a constant x value (moving through y values), then at the end of all of the y values, m...
This should solve your problem for x in x_values: for y in y_values: do_something() y_values.reverse() After each iteration over y_values ​​, y_values ​​is reversed.
2
3
76,779,874
2023-7-27
https://stackoverflow.com/questions/76779874/python-django-typeerror-cannot-unpack-non-iterable-matchall-object
I am facing below error when try to query using 'Q' in a viewset. It will work without any issues if I use this in a management command file. My view. @permission_classes((AllowAny,)) class ClipartViewSet(viewsets.GenericViewSet): serializer_class = ClipartSerializer queryset = Clipart.objects.filter(is_active=True).al...
Likely you implement the wrong Q, you import this with: from django.db.models import Q @permission_classes((AllowAny,)) class ClipartViewSet(viewsets.GenericViewSet): serializer_class = ClipartSerializer queryset = Clipart.objects.filter(is_active=True).all() def list(self, request, **kwargs): qs = Clipart.objects.filt...
2
3
76,779,580
2023-7-27
https://stackoverflow.com/questions/76779580/dataframe-max-matching-two-columns
I have a Dataframe and I am looking for a way to find the maximum number on uniquly matched pairs on two columns. If for example I limit my Dataframe to only these two columns: X Y 1 a 1 b 2 c 2 d 3 b 3 a 4 c 4 d 4 e 5 e 5 c The result shoud be: X Y 1 a 2 c 3 b 4 d 5 e ...
I would use a linear_sum_assignment on the crosstab: from scipy.optimize import linear_sum_assignment tmp = pd.crosstab(df['X'], df['Y']) idx, col = linear_sum_assignment(tmp, maximize=True) out = pd.DataFrame({'X': tmp.index[idx], 'Y': tmp.columns[col]}) Output: X Y 0 1 a 1 2 c 2 3 b 3 4 d 4 5 e Intermediate crosst...
3
2
76,778,624
2023-7-27
https://stackoverflow.com/questions/76778624/attributeerror-module-plotly-tools-has-no-attribute-set-credentials-file
I am following an introduction tutorial for plotly and I am facing a problem, using Jupyter. This is the code below: import numpy as np import pandas as pd import cufflinks as cf import chart_studio.plotly as py import plotly.tools as tls import plotly.graph_objs as go tls.set_credentials_file(username = "xxx", api_key...
As it was mentioned by @Sotos in the comment, the set_credentials_file file is no longer available in plotly.tools. You should use the chart_studio instead: https://pypi.org/project/chart-studio/ and it should work for you: import chart_studio.tools as tls tls.set_credentials_file(username='xxx', api_key='yyyy') Also ...
2
3
76,776,186
2023-7-27
https://stackoverflow.com/questions/76776186/even-with-return-dtype-in-map-rows-i-get-could-not-determine-output-type-i
This works: f = lambda t: {'x': 1, 'y': "abc"} df = pl.DataFrame( {'c': [f(0)] } ) shape: (1, 1) ┌───────────┐ │ c │ │ --- │ │ struct[2] │ ╞═══════════╡ │ {1,"abc"} │ └───────────┘ >>> df.schema # Schema([('c', Struct({'x': Int64, 'y': String}))]) While using map_rows with same f and schema dies with: RuntimeError: ...
There are really two different apply methods that are relevant here. There's DataFrame.apply and there's Expr.apply. When you do: df.with_columns('c') The output of that is a DataFrame that includes c. The with_columns isn't doing anything except making sure c exists and throwing an error if it doesn't. Therefore when...
3
0
76,777,484
2023-7-27
https://stackoverflow.com/questions/76777484/find-the-sum-of-values-in-rows-of-one-column-for-where-the-other-column-has-nan
I have a dataframe with columns A and B. Column A has non continuous data where some of the rows are NAN and B has continuous data. I would like to create a third column where for each set of A rows with NAN it will have the sum of values in those same rows in B + the next valid value in B. All other values in C should...
A simple version using groupby.transform: # identify the non-NA and reverse m = df.loc[::-1, 'A'].notna() # group the preceding NA, sum, mask where NA df['C'] = df.groupby(m.cumsum())['B'].transform('sum').where(m) Output: A B C 0 1.0 10 10.0 1 1.0 20 20.0 2 NaN 30 NaN 3 NaN 40 NaN 4 2.0 50 120.0 5 5.0 60 60.0 6 NaN ...
2
4
76,775,248
2023-7-26
https://stackoverflow.com/questions/76775248/argumentparser-add-argument-raises-attributeerror-str-object-has-no-attribute
When I run my program, I immediately get an AttributeError when it's setting up the argument parser: Traceback (most recent call last): File "blah.py", line 55, in <module> parser.add_argument('--select-equal', '--equal', nargs=2, metavar=[ 'COLUMN', 'VALUE' ], action='append', dest='filter_equality_keys_and_values', d...
It is, in fact, something I was doing wrong. The clue is that the method is trying to access an attribute of an object that doesn't have such an attribute—and it's trying to do so on self. The first argument to my call to add_argument is indeed a string ('--select-equal'). The only way that string could end up being se...
3
6
76,772,127
2023-7-26
https://stackoverflow.com/questions/76772127/problem-with-using-python-via-rs-reticulate-in-docker-container
I create a Docker image based on rocker/shinyversewith the Dockerfile: # File: Dockerfile FROM rocker/shiny-verse:4.2.2 RUN echo "apt-get start" RUN apt-get update && apt-get install -y \ python3 \ python3-pip # install R packages RUN R -e "install.packages('remotes')" RUN R -e "install.packages('reticulate')" RUN R -e...
Folowing this issue, it seems pyenv installs Python without the Python shared library. You should try to add: reticulate::install_python() which wraps pyenv and set --enable-shared option or set the --enable-shared variable as suggested here
3
1
76,769,872
2023-7-26
https://stackoverflow.com/questions/76769872/how-to-provide-embedding-function-to-a-langchain-vector-store
I am trying to get a simple vector store (chromadb) to embed texts using the add_texts method with langchain, however I get the following error despite successfully using the OpenAI package with a different simple langchain scenario: ValueError: You must provide embeddings or a function to compute them Code: from lang...
embedding_function need to be passed when you construct the object of Chroma. source : Chroma class Class Code so your code would be: from langchain.embeddings.openai import OpenAIEmbeddings from langchain.vectorstores import Chroma db = Chroma(embedding_function=OpenAIEmbeddings()) texts = [ """ One of the most common...
4
3
76,771,208
2023-7-26
https://stackoverflow.com/questions/76771208/warningrootcan-not-find-chromedriver-for-currently-installed-chrome-version
I use selenium in my python project. Few days ago program worked correctly but today I ran my script and it caused this warning. Script: from selenium import webdriver import chromedriver_autoinstaller chromedriver_autoinstaller.install() options = webdriver.ChromeOptions() prefs = {"profile.default_content_setting_val...
Selenium Manager is now fully included with selenium 4.10.0, so this is all you need: from selenium import webdriver from selenium.webdriver.chrome.service import Service service = Service() options = webdriver.ChromeOptions() driver = webdriver.Chrome(service=service, options=options) # ... driver.quit() If the drive...
4
6
76,770,505
2023-7-26
https://stackoverflow.com/questions/76770505/numpy-finding-multiple-occurrence-in-an-array-by-index
Given the following array: array = [-1, -1, -1, -1, -1, -1, 3, 3, -1, 3, -1, -1, 2, 2, -1, -1, 1, -1] indexes 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 I need to find the indexes where the same number appears. In this example this would return a list of lists like this: list(list(), list(16), list(12, 13), list(6, 7...
For a solution in O(n) time*, use a dictionary to collect the indices: # collect positions per value for each item d = {} for i, x in enumerate(array): d.setdefault(x, []).append(i) # sort the output (optional) out = {k: d[k] for k in sorted(d)} Output: {-1: [0, 1, 2, 3, 4, 5, 8, 10, 11, 14, 15, 17], 1: [16], 2: [12, ...
4
4
76,769,098
2023-7-26
https://stackoverflow.com/questions/76769098/how-to-sort-and-group-on-column-using-pandas-loop
from a data frame df1 = Area Sequence X Y A 2 604582.25 320710 A 1 604590.25 320704.75 A 3 604579.25 320710 B 2 536584.47 176977.83 B 1 536570 176996.43 C 1 509202.13 307995.99 C 2 509205.3 307951.24 Need to generate into df1 = Area XY_by_sequence A 604590.25 320704.75 , 604582.25 320710...
Try: x = ( df.set_index(["Area", "Sequence"]) .stack() .groupby(level=[0, 1]) .agg(lambda x: " ".join(map(str, x))) .groupby(level=0) .agg(", ".join) .reset_index(name="XY_by_sequence") ) print(x) Prints: Area XY_by_sequence 0 A 604590.25 320704.75, 604582.25 320710.0, 604579.25 320710.0 1 B 536570.0 176996.43, 53658...
2
7
76,767,219
2023-7-26
https://stackoverflow.com/questions/76767219/error-ignored-the-following-versions-that-require-a-different-python-version
I need to migrate a python project from a Ubuntu machine to my local Windows laptop. In Ubuntu I am working in a virtual environment with python version 3.10.6. I created a requirements.txt using pip freeze > requirements.txt and pushed it together with my code to remote repository. Then I pulled the repository on my l...
Your error is not Ignored the following versions But Could not find a version that satisfies the requirement tensorflow-io-gcs-filesystem==0.32.0 (from versions: 0.23.1, 0.24.0, 0.25.0, 0.26.0, 0.27.0, 0.28.0, 0.29.0, 0.30.0, 0.31.0) The first line is simply the output of pip trying to figure out the list of versions...
3
3
76,744,193
2023-7-22
https://stackoverflow.com/questions/76744193/type-hint-for-attribute-that-might-not-exist
How do I do a type hint for attribute that might not exist on the object in Python? For example: class X: __slots__ = ('attr',) attr: int # either int or doesn't exist - what do I put here? So, concretely: >>> x = X() >>> x.attr Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'X'...
The answer currently appears to be "You can't". I've started a discussion thread for this in the Python Typing repo, which may get more visibility.
3
1
76,758,415
2023-7-24
https://stackoverflow.com/questions/76758415/pydantic-issue-for-tuple-length
I have the following model in pydantic (Version 2.0.3) from typing import Tuple from pydantic import BaseModel class Model(BaseModel): test_field: Tuple[int] But when I enter model = Model(test_field=(1,2)) I get as error: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib...
Following @Tim Robert's Answer, the linked PR suggests using the Ellipsis ... is the syntax you're after! https://github.com/pydantic/pydantic/pull/512/files class Model(BaseModel): test_field: Tuple[int, ...] >>> Model(test_field=(1,2)) Model(test_field=(1, 2)) Additionally, and though I don't think it's really adv...
6
9
76,750,445
2023-7-23
https://stackoverflow.com/questions/76750445/filling-date-gaps-with-polars
I have a problem I'm trying to solve but can't figure it out. I have something similar to this table: df = pl.from_repr(""" ┌─────┬────────────┬───────┐ │ id ┆ date ┆ sales │ │ --- ┆ --- ┆ --- │ │ i64 ┆ str ┆ f64 │ ╞═════╪════════════╪═══════╡ │ 1 ┆ 2023-01-01 ┆ 10.0 │ │ 1 ┆ 2023-02-01 ┆ 20.0 │ │ 1 ┆ 2023-03-01 ┆ 30.0 ...
Try: def fn(x, r): print(pl.DataFrame({"id": x["id"][0], "date": r})) print(x) return ( pl.DataFrame({"id": x["id"][0], "date": r}) .join(x, on="date", how="left")[["id", "date", "sales"]] .with_columns(pl.col("sales").fill_null(strategy="zero")) ) # convert to date df = df.with_columns(pl.col("date").str.to_date("%Y-%...
3
1
76,762,540
2023-7-25
https://stackoverflow.com/questions/76762540/pandas-eval-replacement-in-polars
Suppose I have an expression like "col3 = col2 + col1" so pandas we can directly call pandas.dataframe.eval() but in polars I cannot find such method. I have series.eval in polars but no luck as I want evaluate user given expression on a dataframe.
Acception strings You can pass SQL to pl.sql_expr. df = pl.DataFrame({ "col1": [1, 2], "col2": [1, 2], }) df.select( pl.sql_expr("col2 + col1 as col3") ) Or you can run a complete SQL query with pl.sql pl.sql("SELECT col2 + col1 as col3 FROM df").collect() shape: (2, 1) ┌──────┐ │ col3 │ │ --- │ │ i64 │ ╞══════╡ │ 2 ...
4
4
76,737,940
2023-7-21
https://stackoverflow.com/questions/76737940/i-was-trying-to-build-an-django-project-it-shows-got-an-unexpected-keyword-a
The project when I previously build on my laptop it works but when I was trying to build this project on my pc it shows docker.errors.DockerException: Error while fetching server API version: HTTPConnection.request() got an unexpected keyword argument 'chunked'. My docker-compose.yml file looks like version: "3.3" serv...
My Operating system is ubuntu 22 and running sudo apt install docker-compose-v2 did not work for me. The following command works for me. *Uninstall old docker-compose package sudo apt remove docker-compose Install docker-compose-plugin package sudo apt install docker-compose-plugin After installing this you are unabl...
5
0
76,736,361
2023-7-21
https://stackoverflow.com/questions/76736361/llama-qlora-error-target-modules-query-key-value-dense-dense-h-to-4h
I tried to load Llama-2-7b-hf LLM with QLora with the following code: model_id = "meta-llama/Llama-2-7b-hf" tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=True) # I have permissions. model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, quantization_config=bnb_config, device...
the strings in target_modules are different from models to models, you can debug the model = AutoModelForCausalLM.from_pretrained(model_id) and look into the model then you can find what are the linear layers names and input them into the target_modules
2
2
76,734,333
2023-7-20
https://stackoverflow.com/questions/76734333/pydantic-v2-field-validator-values-argument-equivalent
I'm migrating from v1 to v2 of Pydantic and I'm attempting to replace all uses of the deprecated @validator with @field_validator. Previously, I was using the values argument to my validator function to reference the values of other previously validated fields. As the v1 docs say: You can also add any subset of the fo...
The current version of the Pydantic v2 documentation is actually up to date for the field validators section in terms of what the signature of your validation method must/can look like. the second argument is the field value to validate; it can be named as you please the third argument is an instance of pydantic.Vali...
22
27
76,727,774
2023-7-20
https://stackoverflow.com/questions/76727774/selenium-webdriver-chrome-115-stopped-working
I have Chrome 115.0.5790.99 installed on Windows, and I use Selenium 4.10.0. In my Python code, I call service = Service(ChromeDriverManager().install()) and it returns the error: ValueError: There is no such driver by url [sic] https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790. I use ChromeDriver...
Until the stable webdriver version 115 is released, the solution is to use the test webdriver and test Chrome accordingly. The steps are: uninstall the current installed webdriver and Chrome from the system; find the stable version of webdriver and Chrome at Chrome for Testing availability search for the binary Chro...
30
3
76,760,906
2023-7-25
https://stackoverflow.com/questions/76760906/installing-mamba-on-a-machine-with-conda
I dont know if I have missed it, but this is not clear to me. I already have miniconda on my machine and I want now to install mamba. How this should be done please, I am supposed to download/run the correct mambaforge installer? Does this co-exist happily side by side with conda or you are supposed to have just one of...
Mamba is a replacement conda package manager. They do not co-exist happily as they both rely on a base environment for their dependencies. The recommended way is to install mambaforge or micromamba separately as a replacement. documentation for Mamba: https://mamba.readthedocs.io/en/latest/installation/mamba-installati...
15
5
76,728,876
2023-7-20
https://stackoverflow.com/questions/76728876/sqlalchemy-flask-and-cross-contamination
I have taken over a flask app, but it does not use the flask-sqlalchemy plugin. I am having a hard time wrapping my head around how it's set up. It has a database.py file. from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, scoped_session...
To explain what is happening in your code, let's first dive into how sqlalchemy connects to your database: 1. Creating an Engine: Connection to your database is stored in an engine. At minimum, you must supply a connection URI / database URL Connection engine is quite powerful, see connection parameters for more. A...
3
5
76,726,419
2023-7-20
https://stackoverflow.com/questions/76726419/langchain-modulenotfounderror-no-module-named-langchain
When I write code in VS Code, beginning with: import os from langchain.chains import RetrievalQA from langchain.llms import OpenAI from langchain.document_loaders import TextLoader I am met with the error: ModuleNotFoundError: No module named 'langchain' I have updated my Python to version 3.11.4, have updated pip, an...
I had installed packages with python 3.9.7 but this version was causing issues so I switched to Python 3.10. When I installed the langhcain it was in python 3.9.7 directory. If yo run pip show langchain, you get this Name: langchain Version: 0.0.220 Summary: Building applications with LLMs through composability Home-pa...
12
11
76,748,279
2023-7-23
https://stackoverflow.com/questions/76748279/changing-the-default-cache-path-for-all-huggingface-data
The default cache path of huggingface is in ~/.cache/huggingface, and in that folder, there are multiple cache files like models, and hub. The huggingface documents indicates that the default dataset cache location can be modified by setting the shell environment variable, HF_DATASETS_CACHE to a different directory as...
It seems that the variable is HF_HOME as this document indicates. So probably this terminal code should be the solution: export HF_HOME="/path/.cache/huggingface" export HF_DATASETS_CACHE="/path/.cache/huggingface/datasets" export TRANSFORMERS_CACHE="/path/.cache/huggingface/models" p.s. If you want to make your chang...
3
8
76,756,132
2023-7-24
https://stackoverflow.com/questions/76756132/python-client-library-for-language-server-protocol-lsp
I need to interact with a language server (Eclipse JDT LS) implementing the Language Server Protocol (LSP), and I need it for a Python project that will be used to analyze different programming languages, starting from Java. I've been looking around for a client library in Python that would fit my purpose, any suggesti...
I've discovered that, as of July 2023, there is a library named pygls (https://github.com/openlawlibrary/pygls) that is currently developing a usable client for the Language Server Protocol (LSP). While we wait for the first official release, I've included it in my setup.py file under "install_requires". This ensures i...
5
2
76,759,128
2023-7-25
https://stackoverflow.com/questions/76759128/typeerror-when-running-compute-that-includes-map-blocks-and-reduce
I am having difficulty diagnosing the cause of the error. My code involves running a convolution (with map_blocks) over some arrays if they belong to the same group of variables, otherwise just record the 2-dim array. I then do an argmax operation and add the result to a list, that we then concatenate. I tried running ...
As answered in https://dask.discourse.group/t/typeerror-on-da-argmax-when-executing-compute/2053: You need to work with Numpy arrays in simple_convolve, because this method is applied on Dask Array chunks, which are Numpy arrays. It should at least return a Numpy Array.
3
0
76,749,878
2023-7-23
https://stackoverflow.com/questions/76749878/i-cant-install-chromedrivermanager-with-chromedrivermanager-install
I've been learning Python for 2 month, and this error has never occurred to me once but all of a sudden I can't download CHROMEDRIVERMANAGER and whenever I get to its website to download it manually it says This XML file does not appear to have any style information. The document tree is shown below. The error: ` Acces...
Change the below line from: driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) TO: driver = webdriver.Chrome(service=Service(ChromeDriverManager(version="114.0.5735.90").install()),options=options) Above should solve your issue. Having said that, with latest selenium(v4.6.0 o...
5
11
76,763,668
2023-7-25
https://stackoverflow.com/questions/76763668/pybind11-bound-class-method-returns-new-class-instance-rather-than-editing-in
I am unable to return the input of a class method (input: specific instances of a seperate class) to Python. The binding compiles and I can use the resulting module in Python. The class method should however return the same instances as it admits (after some processing). The Obstacle class is used as the input. The Obs...
Thanks to comments from @DanMašek and @n.m.willseey'allonReddit it was unveiled that making these changes to operator_py() fixes the issue in the question: template <class Params> std::vector<std::shared_ptr<Obstacle>>& operator_py( std::vector<std::shared_ptr<Obstacle>> &obstacles, const Params &params ) { for (auto& ...
4
3
76,730,773
2023-7-20
https://stackoverflow.com/questions/76730773/how-to-edit-and-confirm-form-slots-in-rasa-framework
I'm building a booking bot using Python and Rasa. I want to add a confirmation step when user fills in all slots in my form. The requirements are: User may confirm the values. User may change the values. Bot must be expandable to handling other inputs and intents from the user. I drew a flow-diagram which demonstrate...
The only way I could do this is to implement everything in a single action, and set this action as an active loop. async def run( self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: DomainDict ) -> List[EventType]: latest_confirmation_status = tracker.get_slot('confirmation_status') latest_intent = track...
3
1
76,760,107
2023-7-25
https://stackoverflow.com/questions/76760107/extracting-crs-codes-from-pyproj-library
I need help with a python program. I am looking to obtain crs codes/definitions from Pyrpoj library, add them to a list, allow the user to select a crs from the list and print it out, but it does not seem to work. I have made sure to update the library to the latest version. I will be grateful if you guys can help me o...
As mentioned by @acw1668 in the comments, your error message looks different from the code you tried. However, if I run the same code you posted, I get the following error - TypeError: get_codes() takes at least 2 positional arguments (1 given) Following the official documentation, the function "pyproj.database.get_co...
3
1
76,764,911
2023-7-25
https://stackoverflow.com/questions/76764911/doctest-of-function-with-random-output
I have a function that prints a somewhat random string to the console, for example: from random import choice def hello(): print(f"Hello {choice(('Guido', 'Raymond'))}!") Please note that my actual function is more complicated than this. The random part is a request to a database that can either succeed or fail. This ...
You could use regex: Hello followed by either Guido or Raymond followed by an exclamation point and newline: Hello (Guido|Raymond)!\n However, capturing the stdout and running the regex is a lot of noise for a doctest. So instead, it'd be better to give an example in the docstring but skip testing it, and use a differ...
5
3
76,765,523
2023-7-25
https://stackoverflow.com/questions/76765523/python-listt-not-assignable-to-listt-none
I have a type T, a namedtuple actually: from collections import namedtuple T = namedtuple('T', ('a', 'b')) I have a function that accepts a list[T | None] and a list: def func(arg: list[T | None]): ... l = [T(1, 2), T(2, 3)] func(l) # Pylance error l is of type list[T]. When I pass a l to the function I get an error ...
The built-in mutable generic collection types such as list are all invariant in their type parameter. (see PEP 484) This means that given a type S that is a subtype of T, list[S] is not a subtype (nor a supertype) of list[T]. You can simplify your error even further: def f(a: list[int | None]) -> None: ... b = [1, 2] f...
4
8
76,763,873
2023-7-25
https://stackoverflow.com/questions/76763873/trio-seems-to-start-tasks-in-the-nursery-in-exactly-the-opposite-order-that-task
I don't expect trio to run in any particular order. It is async, after all. But I noticed something strange and wanted to ask if anyone else could explain what might have happened: I wanted to test the rate of data ingestion from Google's Pub Sub if I send a small message one at a time. In order to focus on the I/O of...
Heh, nicely spotted. So what's going on here is that Trio intentionally randomizes the order that tasks get scheduled, to help you catch places where you're accidentally relying on scheduler details to coordinate between tasks (since this is fragile, hard to reason about, and constrains trio's ability to improve the sc...
2
3
76,764,592
2023-7-25
https://stackoverflow.com/questions/76764592/legend-obscures-plot-using-seaborn-objects-api
I have a recurring problem with legends on many of my plots with legends. The legend often obscures part of the data. Reproducible example: import seaborn.objects as so import numpy as np import pandas as pd res_df = pd.DataFrame( {'value': np.random.rand(20), 'cfg__status_during_transmit': ['OK']*5 + ['ERR']*5 + ['WA...
Control over the legend using seaborn.objects might still be a work in progress according to this post. However, if I used plot() instead of show() I got a figure where the legend was placed outside the graph: import seaborn.objects as so import numpy as np import pandas as pd res_df = pd.DataFrame( {'value': np.random...
5
4
76,760,682
2023-7-25
https://stackoverflow.com/questions/76760682/tensorflow-2-13-1-no-matching-distribution-found-for-tensorflow-text-2-13-0
I am trying to install the latest Tensorflow models 2.13.1 (pip install tf-models-official==2.13.1), with Python 3.11. There seems to be an issue with Cython and PyYAML not playing nice together since last week in Tensorflow models 2.13.0, so it won't install. But 2.13.1 is giving me an error that the corresponding ten...
I resolved the issue, by installing Python 3.10 Tensorflow 2.13.0 tensorflow-text 2.13.0 tensorflow-models-official 2.13.1 Everything works with these versions, but I did not find a way to make it work with Python 3.11 atm. The issue is best described here (https://github.com/yaml/pyyaml/issues/724) and has to do with...
8
3
76,760,704
2023-7-25
https://stackoverflow.com/questions/76760704/python-docstring-inconsistent-leading-whitespace-error-without-new-line
my docstring: def some_f(): """ 1. First story >>> str(5) if you want to see the value: >>> print(str(5)) 2. Another story bla bla """ When using doctest, I'm getting: ValueError: line 6 of the docstring for File.Class.some_f has inconsistent leading whitespace: '2. Another story' I've read (here and here) that this...
The question and title should include the clarification that this error occurs because you are running doctest.testmod(); otherwise Python doesn't care about your formatting. The problem is that doctest expects each line that appears to be an interactive prompt to be followed by the expected output for the doctest, and...
2
4
76,760,381
2023-7-25
https://stackoverflow.com/questions/76760381/modulenotfounderror-no-module-named-exceptions
I need to transform 140 .docx files into txt. I am using the following Python code that I found here in StackOverflow. I tried this: import os from docx import Document # Path to the folder containing .docx files input_folder = "C:/Users/XXXXX/Desktop/word" # Path to the folder where .txt files will be saved output_fol...
The error can occur for multiple reasons: Not having the python-docx package installed by running pip install python-docx. Installing the package in a different Python version than the one you're using. Installing the package globally and not in your virtual environment. Your IDE running an incorrect version of ...
3
2
76,729,393
2023-7-20
https://stackoverflow.com/questions/76729393/how-to-properly-capture-library-package-version-in-my-package-when-using-pypro
I have moved away from a setup.py file to build my packages / libraries to fully using pyproject.toml. I prefer it overall, but it seems that the version placed in the pyproject.toml does not propagate through the build in any way. So I cannot figure out how to inject the package version -- or any other metadata provid...
As you've seen, the pyproject.toml file from the original source tree is generally not available to read from within an installed package. This isn't new, it's also the case that the setup.py file from a legacy source tree would be missing from an actual installation. The package metadata, however, is available in a .d...
2
4
76,755,607
2023-7-24
https://stackoverflow.com/questions/76755607/how-to-optimize-the-ulam-spiral-infinite-iterator
I have created an infinite iterator which maps natural numbers to all lattice points in a spiral like manner, akin to the Ulam Spiral: The code is below, I have made it as fast as possible, and I didn't use a single if condition: from itertools import islice, repeat def ulamish_spiral_gen(): xc = yc = length = 0 yield...
You already covered "memoize"/"skip". Here are faster infinite iterators. Times for the first 16384 coordinates (as in your benchmark): 1.01 ± 0.00 ms gen_Kelly_4 1.01 ± 0.00 ms gen_Kelly_5 1.03 ± 0.00 ms gen_Kelly_3 1.06 ± 0.00 ms gen_Kelly_2 1.21 ± 0.00 ms gen_Kelly_1 1.57 ± 0.00 ms gen_original Python: 3.11.4 (main...
2
4
76,757,194
2023-7-24
https://stackoverflow.com/questions/76757194/why-do-i-get-the-error-unrecognized-request-argument-supplied-functions-when
I'm trying to use functions when calling Azure OpenAI GPT, as documented in https://platform.openai.com/docs/api-reference/chat/create#chat/create-functions I use: import openai openai.api_type = "azure" openai.api_base = "https://XXXXXXXX.openai.azure.com/" openai.api_version = "2023-06-01-preview" openai.api_key = os...
Function support with the Azure API was added in 2023-07-01-preview. The API version needs to be updated in your example: openai.api_version = "2023-07-01-preview"
9
15
76,752,059
2023-7-24
https://stackoverflow.com/questions/76752059/how-can-i-stop-a-worker-thread-in-tkinter-when-window-is-closed
When I close the tkinter window while the worker thread is running I get this error after 10 seconds: RuntimeError: main thread is not in main loop probably because ROOT is destroyed. import tkinter as tk from tkinter import ttk import threading import time def worker(event_ready): event_ready.wait() progress_bar = ttk...
You simply only need to start the Thread as a daemon, at least in Windows. worker_thread = threading.Thread(target=worker, args=(event_ready,), daemon=True) Now when you close the Window, the program will terminate immediately.
3
1
76,748,693
2023-7-23
https://stackoverflow.com/questions/76748693/how-can-i-resolve-this-bubble-sort-problem
I'm trying to make a Python bubble sort with a 5 variable list. The user will input the 5 values and the bubble_sort is going to arrange them in ascending order, but when I try to run it it gives the error: lista = list(n1, n2, n3, n4, n5) ^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: list expected at most 1 argument, got 5 Thi...
you are trying to create the list lista using the list() function but it expects an iterable as its argument, not multiple individual elements! create a list containing all the elements like this: lista = [n1, n2, n3, n4, n5]
2
5
76,747,462
2023-7-23
https://stackoverflow.com/questions/76747462/how-to-optimize-printing-pascals-triangle-in-python
I have implemented the Pascal's triangle in Python, it is pretty efficient, but it isn't efficient enough and there are a few things I don't like. The Pascal's triangle is like the following: I have read this useless tutorial and this question, and the solutions are extremely inefficient, involving factorials and don'...
You can improve the pretty_print by getting the length (as string) of the longest number and using that as the basis for all the numbers' width; also using str.center might be easier. def pretty_print(self): longest = max(len(str(n)) for row in self.data for n in row) line_length = (longest + 1) * self.length for row...
2
2
76,747,279
2023-7-23
https://stackoverflow.com/questions/76747279/pyqt-how-to-use-qmessagebox-open-and-connect-callback
How can I connect a callback when using QMessageBox.open() ? In the documentation it says: QMessageBox.open(receiver, member) Opens the dialog and connects its finished() or buttonClicked() signal to the slot specified by receiver and member . If the slot in member has a pointer for its first parameter the connection ...
After some trial and error I found that I could simply use mbox.open(button_clicked) but I am still not sure how I can determine from within the callback which of the two buttons was clicked. Also one should not call QMessageBox.done() from within the callback since that would lead to infinite recursion. Here is how I ...
3
0
76,724,939
2023-7-19
https://stackoverflow.com/questions/76724939/there-is-no-such-driver-by-url-https-chromedriver-storage-googleapis-com-lates
I recently updated my Google Chrome browser to version 115.0.5790.99 and I'm using Python webdrivermanager library (version 3.8.6) for Chrome driver management. However, since this update, when I call the ChromeDriverManager().install() function, I encounter the following error: There is no such driver by URL https://...
Selenium Manager With the availability of Selenium v4.6 and above you don't need to explicitly download ChromeDriver, GeckoDriver or any browser drivers as such using webdriver_manager. You just need to ensure that the desired browser client i.e. google-chrome, firefox or microsoft-edge is installed. Selenium Manager i...
21
4
76,744,865
2023-7-22
https://stackoverflow.com/questions/76744865/python-encoding-all-possible-5-combinations-into-an-integer
I've got a set of 25 integers, ranging from 0 to 24 and my application involves selecting 5 of them (there are no repeated values, no value can be selected more than once) obtaining a combination like this one [15, 7, 12, 3, 22]. It's important to consider the the previous combination is considered equal to [7, 22, 12,...
Use more_itertools.nth_combination that can compute the nth combination without computing all previous ones: # pip install more-itertools from more_itertools import nth_combination nth_combination(range(25), 5, 0) # (0, 1, 2, 3, 4) nth_combination(range(25), 5, 42) # (0, 1, 2, 5, 7) nth_combination(range(25), 5, 53129)...
2
5
76,744,939
2023-7-22
https://stackoverflow.com/questions/76744939/importerror-using-the-trainer-with-pytorch-requires-accelerate-0-20-1
Please help me when I tried to use it in my Google Colab for transformers error: ImportError: Using the Trainer with PyTorch requires accelerate=0.20.1: Please run pip install transformers[torch] or pip install accelerate -U` NOTE: If your import is failing due to a missing package, you can manually install dependenc...
Steps: pip install accelerate -U then Restart the notebook run all and you'll see it'll solve
3
1
76,742,725
2023-7-22
https://stackoverflow.com/questions/76742725/python-flask-application-in-azure-web-app-only-showing-default-page
I have been struggling for days to deploy a Python web app with flask on Azure. But all I ever get is the default page. This is the address: https://el-priser.azurewebsites.net/ This is my Github repo: https://github.com/Michaelgimm/energinet-elpris I also tried with the azure guide for a test app, but it does the same...
I have tried to deploy your application to Azure web app through VScode. I could deploy the application, but I was able to see only default page and few times it also led me to Application Error. After many trials, I could figure out the resolution for this issue. To run the deployed Flask application, we have to ad...
3
3
76,741,158
2023-7-21
https://stackoverflow.com/questions/76741158/python-regex-findall-not-finding-all-matches-of-shorter-length
How can I find all matches that don't necessarily consume all characters with * and + modifiers? import regex as re matches = re.findall("^\d+", "123") print(matches) # actual output: ['123'] # desired output: ['1', '12', '123'] I need the matches to be anchored to the start of the string (hence the ^), but the + does...
You could use overlapped=True with the PyPi regex module and reverse searching (?r) Then reverse the resulting list from re.findall import regex as re res = re.findall(r"(?r)^\d+", "123", overlapped=True) res.reverse() print(res) Output ['1', '12', '123'] See a Python demo.
6
5
76,741,476
2023-7-21
https://stackoverflow.com/questions/76741476/how-can-i-create-a-table-with-a-uuid-column-in-a-postgres-db-using-sqlalchemy
I have created some tables using SQLALchemy 2.0's MappedAsDataclass and DeclarativeBase models, creating my tables like this: class Base(MappedAsDataclass, DeclarativeBase): """subclasses will be converted to dataclasses""" class Post(Base): __tablename__ = 'allposts' post_id: Mapped[int] = mapped_column(init=False, p...
Here is an example of how you can do it on a PostgreSQL server: import uuid from sqlalchemy import create_engine, select, text, types from sqlalchemy.orm import (DeclarativeBase, Mapped, MappedAsDataclass, mapped_column, sessionmaker) DATABASE_URL = "postgresql+psycopg2://test_username:test_password@localhost:5432/test...
4
6
76,736,925
2023-7-21
https://stackoverflow.com/questions/76736925/df-to-sql-missing-optional-dependency-pandas
SOLVED: I'm having an issue using sqlalchemy and snowflake.connector to push my df to a new table in Snowflake but I am prompted with this error: raise errors.MissingDependencyError(self._dep_name) snowflake.connector.errors.MissingDependencyError: Missing optional dependency: pandas Edit: Accidentally posted without a...
Moving the answer from the question to the answer section, so it doesn't look as unanswered: pip install snowflake-connector-python[pandas]
2
8
76,731,084
2023-7-20
https://stackoverflow.com/questions/76731084/calculate-the-rolling-mean-by-group-with-conditions-for-each-rows-in-a-pandas-da
I'm trying to create a rolling_median column as follow: For each row: Filter the DataFrame to only keep rows of the same Category, having Date_B < my_current_row.Date_A Sort this filtered DataFrame by Date_B Calculate the median of Value using the N last entries with my filters : for example, if N=2, I will use the la...
Probably not the most efficient way, but seems a little faster than the double for-loop: import pandas as pd import numpy as np # Sample DataFrame (replace this with your actual DataFrame) data = { 'Category': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'], 'Date_A': ['2023-07-08', '2023-07-09', '2023-07-11', '2023...
3
1
76,734,236
2023-7-20
https://stackoverflow.com/questions/76734236/pydantic-v2-field-validator-got-an-unexpected-keyword-argument-pre
I'm migrating from v1 to v2 of Pydantic and I'm attempting to replace all uses of the deprecated @validator with @field_validator. However, I was previously using the pre validator argument and after moving to @field_validator, I'm receiving the following error: TypeError: field_validator() got an unexpected keyword ar...
It seems it's still referenced in the V2 validator documentation [...] Not really. At least nowhere in the field validators section. (There is just an outdated mention of it in the "model validators" section as of today.) However, there is also a link to the detailed API reference for the field_validator decorator sh...
7
10
76,729,345
2023-7-20
https://stackoverflow.com/questions/76729345/is-it-possible-to-chain-several-discord-modals-discord-py
My goal is to chain or link several different discord modals after one-another in order to create a continuous form since Discord does not allow to add more than 5 items or "questions" per modal. The goal is to have modal_1 and modal_2 with 5 questions in each. Every time a command is ran by a user, modal_1 would be di...
No, you can't. Looking in this section of Discord's Developers' Portal, you can read that MODAL can't be the callback of a MODAL_SUBMIT interaction. Depending on what the data is, I would either use a form webpage or try to do something with the View Widgets, especially TextInputs, since you can send as many messages w...
3
1
76,734,284
2023-7-20
https://stackoverflow.com/questions/76734284/copying-bytes-object-to-shared-memory-list-truncates-trailing-zeros
I'm trying to copy large bytes objects into a shareable list that's been initialized with bytes objects of large enough size. When the bytes object I'm copying over has trailing zeros (i.e. final values are 0x00), the new entry in the shared memory list is missing these zeros. Zeros in the middle of the data do not cau...
CPython seems to explicitly .rstrip(b'\x00'), but there doesn't seem to be any mention of this in the documentation. There is nothing documented at all about the storage neither in terms of semantics nor implementation (except that it should use (or be compatible with) the struct module). Personally, I'd say the way it...
4
5
76,733,270
2023-7-20
https://stackoverflow.com/questions/76733270/avoid-inner-loop-while-iterating-through-nested-data-performance-improvement
I am working with a large dataset (1 million + rows) and am tasked with counting up each truthy value for each ID and generating a new dict. The solution I came up with works, but does very poor in regards to performance. I have a dictionary as follow: "data": { "employees": [ { "id": 274, "report": true }, { "id": 27...
There is no need to make multiple passes, just accumulate as you go so it is linear time not quadratic result = {} for employee in input_dict["data"]["employees"]: _id = employee["id"] if _id not in result: # note id is being added redundantly maybe rethink this result[_id] = dict(id=_id, count=0) result[_id]["count"] ...
4
2
76,733,588
2023-7-20
https://stackoverflow.com/questions/76733588/calculate-mean-of-consecutive-repititions-of-values-in-pandas-dataframe-numpy
I have the following dataframe / numpy array: a = np.array([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103]) df = pd.DataFrame([ 55, 55, 69, 151, 151, 151, 103, 151, 151, 103], columns = ["AOI"]) The values in this array can range from 1 to 151. I need to calculate the average consecutive repetition of the values. Th...
Here is one possible solution using pandas: df['group'] = (df.AOI != df.AOI.shift()).cumsum() x = df.groupby('group').agg({'AOI':('first', 'count')}).droplevel(0, axis=1) x = x.groupby('first')['count'].mean() x = x.reindex(range(0, x.index[-1] + 1), fill_value=0) # print(x) <- if you want pd.Series print(x.values) # p...
2
2
76,729,145
2023-7-20
https://stackoverflow.com/questions/76729145/explicit-matrix-multiplication-much-faster-than-numpy-matmul
In a Python code, I need at some point to multiply two large lists of 2x2 matrices, individually. In the code, both these lists are numpy arrays with shape (n,2,2). The expected result in another (n,2,2) array, where the matrix 1 is the result of the multiplication between matrix 1 of the first list and matrix 1 of the...
TL;DR: all the methods provided in the question are very inefficient. In fact, Numpy is clearly sub-optimal and there is no way to compute this efficiently only with Numpy. Still, there are faster solutions than the ones provided in the question. Explanation and faster implementation The Numpy code make use of powerfu...
4
6
76,730,133
2023-7-20
https://stackoverflow.com/questions/76730133/summing-large-matrices-of-image-data-efficiently
How do I sum large (100, 1024, 1024) .npz files most efficiently? Is there a better file format to store python data of the given dimensions? I currently use this to sum the matrices: summed_matrix = np.sum([np.load(file) for file in files_list]) This exceeds my available memory.
Currently, you're loading all files at once and only then begin summing. If memory is a concern, a better approach would be to read and add one at a time: summed_matrix = np.zeros((100, 1024, 1024)) for file in files_list: summed_matrix += np.load(file)
3
7
76,722,536
2023-7-19
https://stackoverflow.com/questions/76722536/with-python-textual-package-how-do-i-linearly-switch-between-different-screen
With textual I'd like to build a simple program which presents me with different options I can choose from using OptionList, but one by one, e.g. First "screen": what do you want to buy (Car/Bike)? +---------+ | Car | | > Bike | +---------+ bike And after I pressed/clicked on "Bike" I'd like to see the second 'scree...
Depending on the scope and purpose of the application you're wanting to build, there's a few different approaches you could take here. Some options are: If it's a limited number of main choices with a handful of widgets making up the sub-questions, perhaps TabbedContent would be what you're looking for. If you want a ...
5
5
76,728,740
2023-7-20
https://stackoverflow.com/questions/76728740/two-fields-with-same-name-causing-problem-in-pydantic-model-classes
I have two Pydantic model classes where two fields have the same name as can be seen below: class SnowflakeTable(BaseModel): database: str schema: str table: str table_schema: List[SnowflakeColumn] class DataContract(BaseModel): schema: List[OpenmetadataColumn] These model classes have been integrated with other modul...
You have to change the variable names because those names are already in use by pydantic. Try: class SnowflakeTable(BaseModel): database: str my_var_schema: str = Field(..., alias='schema') table: str table_schema: List[SnowflakeColumn] class DataContract(BaseModel): my_var_schema: List[OpenmetadataColumn] = Field(...,...
3
2
76,726,671
2023-7-20
https://stackoverflow.com/questions/76726671/im-populating-some-cards-using-for-loop-in-nicegui-each-has-a-label-and-a-butto
When I click on the button it should print the id of the label inside that card only. But it always prints the id of last label no matter which button I click on. In the code below my_grid is the name of the grid in which I'm trying to populate the cards and listcards is the list of cards labels that I'm trying to put ...
This is a very frequently asked question. We're actually thinking about introducing a FAQ section because of this question. But it is indeed a tricky Python behavior that keeps confusing developers. In the following code example, a button click will call the lambda function, which in turn prints the value of label_card...
2
4
76,726,572
2023-7-20
https://stackoverflow.com/questions/76726572/what-is-the-difference-between-excel-and-csv
I am learning about Python. I am trying to store project data to a .CSV file using Pandas library. I know csv is comma separated values, the data is separated by comma(,). I am wondering why I would use a .CSV instead of the other Excel file types?
The major differences between Excel XLSX and CSV file format are the file size and the formatting. In a *.CSV file, the file size is smaller, and the data looks like this: (there is no formatting, just raw data) And if you open using a text editor, you'd get this: idx,col1,col2 123,aaa,xxx 456,bbb,yyy 789,ccc,zzz And...
2
4
76,719,175
2023-7-19
https://stackoverflow.com/questions/76719175/np-sqrt-with-integers-and-where-condition-returns-wrong-results
I am getting weird results from numpy sqrt method when applying it on an array of integers with a where condition. See below. With integers: a = np.array([1, 4, 9]) np.sqrt(a, where=(a>5)) Out[3]: array([0. , 0.5, 3. ]) With floats: a = np.array([1., 4., 9.]) np.sqrt(a, where=(a>5)) Out[25]: array([1., 4., 3.]) Is it...
I think there might be a bug inconsistency*, when repeating the command several times I don't get consistent results. *this is actually due to the probable use of numpy.empty to initialize the output. This function reuses memory without setting the default values and thus will have non-predictable values in the cells t...
3
2
76,717,805
2023-7-19
https://stackoverflow.com/questions/76717805/how-can-i-show-a-python-package-installed-packages
If I install some python pacakges, like opencv-python, it will install the cv2 pacakge. But before I look at opencv's document, how can I inspector the opencv-python pacakge, and find out what it installed. Like pip info opencv-python, but it will not print the installed packages. Update: I find the pip installed place...
The answers demonstrating pip show usage are fine if you just wanted to discover this information from the command-line interactively. If you want access to the top-level package names programmatically, however, pip is not much help because it has no API. Since Python 3.10 the information is easily available using stdl...
2
2
76,668,373
2023-7-12
https://stackoverflow.com/questions/76668373/declare-intermediate-variables-in-select-statements-in-polars
When writing select or with_columns statements in Polars I often wish to declare intermediate variables to make the code more readable. I'd also like to be able to query a column in a context and reuse it in another column's expression. I am currently forced to chain multiple select/with_columns calls which lacks elega...
We can actually use walrus assignment to get very close to what you're after Say you have this: df = pl.DataFrame({'a':[1,2,3], 'b':[2,3,4], 'c':[3,4,5]}) You can do: df.with_columns( (stp_1 := (pl.col("a") * 2)).alias("step_1"), stp_1.pow(tempvar := (pl.col("b") + 1.5)).alias("step_2"), (pl.col("c") + tempvar).alias(...
5
2
76,701,351
2023-7-17
https://stackoverflow.com/questions/76701351/html-xml-understanding-how-scroll-bars-work
I am working with the R programming language and trying to learn about how to use Selenium to interact with webpages. For example, using Google Maps - I am trying to find the name, address and longitude/latitude of all Pizza shops around a certain area. As I understand, this would involve entering the location you are ...
I see that you updated your question to include a Python answer, so here's how it's done in Python. you can use the same method for R. The page is lazy loaded which means, as you scroll the data is paginated and loaded. So, what you need to do, is to keep finding the last HTML tag of the data which will therefore load ...
7
7
76,674,272
2023-7-12
https://stackoverflow.com/questions/76674272/pydantic-basesettings-cant-find-env-when-running-commands-from-different-places
So, Im trying to setup Alembic with FastAPI and Im having a problem with Pydantic's BaseSettings, I get a validation error (variables not found) because it doesnt find the .env file (?) It can be solved by changing env_file = ".env" to env_file = "../.env" in the BaseSettings class Config but that makes the error happe...
For me it was the fact that .env was not in the same directory as the running script. I had to manually anchor the .env file to an absolute path. Here is my settings.py file with .env residing alongside in the same directory: import os from pydantic_settings import BaseSettings, SettingsConfigDict DOTENV = os.path.join...
9
11
76,710,868
2023-7-18
https://stackoverflow.com/questions/76710868/why-i-take-an-exception-with-my-endpoint-fastapi
I have got an db like: class NewsBase(BaseModel): title: str topic: str class NewsCreate(NewsBase): datetime: datetime class News(NewsBase): id: int datetime: datetime class Config: orm_mode = True When i try to make this request, it returns with 500: @app.get("/news/find_by_topic/{topic}", response_model=schemas.News...
It seems like you need to set response_model properly. Read more here. If you are using Python 3.9: response_model=list[schemas.News] If you are using older Python: from typing import List response_model=List[schemas.News]
2
4
76,707,715
2023-7-17
https://stackoverflow.com/questions/76707715/stucking-at-downloading-shards-for-loading-llm-model-from-huggingface
I am just using huggingface example to use their LLM model, but it stuck at the: downloading shards: 0%| | 0/5 [00:00<?, ?it/s] (I am using Jupiter notebook, python 3.11, and all requirements were installed) from transformers import AutoTokenizer, AutoModelForCausalLM import transformers import torch model = "tiiuae/f...
I think it's not stuck. These are just very large models that take a while to download. tqdm only estimates after the first iteration, so it just looks like nothing is happening. I'm currently downloading the smallest version of LLama2 (7B parameters) and it's downloading two shards. The first took over 17 minutes to c...
19
25
76,691,401
2023-7-14
https://stackoverflow.com/questions/76691401/selenium-common-exceptions-nosuchdriverexception-message-unable-to-obtain-chro
I can't figure out why my code it's always getting an error This is my code: from selenium import webdriver url = "https://google.com/" path = "C:/Users/thefo/OneDrive/Desktop/summer 2023/chromedriver_win32" driver = webdriver.Chrome(path) driver.get(url) Path of chromedriver: and this is the error that always appear...
This error message... Traceback (most recent call last): File "C:\Users\thefo\AppData\Local\Programs\Python\Python311\Lib\site-packages\selenium\webdriver\common\driver_finder.py", line 42, in get_path path = SeleniumManager().driver_location(options) if path is None else path ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^...
5
10
76,682,341
2023-7-13
https://stackoverflow.com/questions/76682341/not-filled-white-voids-near-boundaries-of-polar-plot
I have tried to create a polar plot using matplotlib's contourf, but it produces some not-filled areas near the circle boundary, in just some sides of the plot. It seems, this problem is a common problem that we can see in many examples e.g. 1. At first, I thought it may needs some interpolations and tried interpolati...
After a related discussion in matplotlib repo, it seems there is not any simple and conventional solution for that (perhaps cartopy have prepared something helpful); The contouring algorithm doesn't know that it is acting on a polar plot, so when the contours are drawn in polar space the polygons are approximated. Thi...
3
1
76,709,695
2023-7-18
https://stackoverflow.com/questions/76709695/how-to-stop-multiprocessing-pool-with-ctrlc-python-3-10
I've spent several hours on research and no solution seems to work anymore. My function will take an estimated 30-50 minutes per process. If I spot flaws during the first few minutes, I don't want to wait for the processes to finish completely or have to close the terminal without killing the processes cleanly. For sim...
Problem Solved In another forum this problem was discussed and solved in a simple and clean way. Here is the link for everyone else: https://www.reddit.com/r/learnpython/comments/152sfp8/how_to_stop_multiprocessingpool_with_ctrlc_python/ Solution 1 In multiprocessing module there is an AsyncResult object. This includes...
2
4