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
77,759,907
2024-1-4
https://stackoverflow.com/questions/77759907/how-to-remove-xa0-from-soup-in-beautifulsoup-python
I am currently using Beautifulsoup to parse the HTML code of a webpage. To get the text from an element, I use the ".text" attribute: soup.find('p', {'class': 'example'}).text But the problem is that sometimes I get "\xa0" in the result: "some text «\xa0text\xa0»" I tried using the "replace" function: soup = Beautifu...
The problem is that the HTML source probably contains  , not the literal \xa0. Try replacing that instead, or as well. soup = BeautifulSoup( driver.page_source.replace( ' ', ' ').replace('\xa0', ' '), "lxml")
2
2
77,759,260
2024-1-4
https://stackoverflow.com/questions/77759260/django-appregistrynotready-when-running-unittests-from-vscode
My UnitTest test cases in a Django project run fine when running them directly from the Django utility (python manage.py test). However, when trying to run them from VSCode's test explorer, I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. I found several similar questions that were already ans...
You can try to do the following steps: Create a __init__.py file in your tests directory (if it doesn't already exist), and add the following code: import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") django.setup() These codes manually set the Django settings module and ini...
2
3
77,761,161
2024-1-4
https://stackoverflow.com/questions/77761161/sqlalchemy-string-relationships-cause-undefined-name-complaints-by-flake8-and
# order.py class Order(Base): __tablename__ = "Order" id: Mapped[int] = mapped_column(primary_key=True) items: Mapped[List["Item"]] = relationship(back_populates="order") # item.py class Item(Base): __tablename__ = "Item" id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True) order_id: Mapped[int] = mapp...
mypy and flake8 are correct here, these warnings shouldn't be ignored. To resolve the circular import problem, you can use "typechecking-only import", i.e. an import statement wrapped in if TYPE_CHECKING block (TYPE_CHECKING constant is explained here) . Here's how it may look like: # order.py from typing import TYPE_C...
2
3
77,761,185
2024-1-4
https://stackoverflow.com/questions/77761185/deleteing-unwanted-characters-from-dat-file-then-performing-calculations-on-the
I need to read a .dat file in Python. The file has 3 columns in total and hundreds of rows. The second and third column contain two characters followed by a float that I would like to extract--the second column always starts with "SA" and the third column always starts with "SC". I am currently loading in the data and ...
You can use pandas to do that: #! pip install pandas import pandas as pd import numpy as np df = pd.read_csv('serial_2.dat', sep='\s+', header=None, names=['time', 's1', 's2']) df['s1'] = df['s1'].str.extract('^[\D]+(.*)').astype(float) df['s2'] = df['s2'].str.extract('^[\D]+(.*)').astype(float) Output: >>> df time s1...
2
3
77,758,047
2024-1-4
https://stackoverflow.com/questions/77758047/encountering-importerror-with-tesserocr-symbol-not-found-in-flat-namespace-z
I'm attempting to use tesserocr in my Python project, but when I try to import it, I'm getting [No module named 'tesserocr'], I run into an ImportError. The error message points to a missing symbol related to the Tesseract library. Here is the full error message: ImportError: dlopen(/Volumes/WorkSpace/Backend/Reverat...
I ran into a problem when trying to work with the tesserocr package, but I managed to find a fix and wanted to share it for anyone who might be experiencing the same issue. The error was resolved by first completely uninstalling the tesserocr package and then reinstalling it using the --no-binary option with pip. Here ...
4
8
77,753,885
2024-1-3
https://stackoverflow.com/questions/77753885/fastapi-supporting-either-basic-auth-or-jwt-auth-to-access-endpoint
Referencing this link: fastapi-supporting-multiple-authentication-dependencies I think this is the closest to what I need, but somehow I can’t get either of the dependency to work because fastapi is enforcing both dependencies before it grants access to endpoint. Snippet for custom depedency: def basic_logged_user(cred...
The idea is to make all of this security dependencies not to raise exceptions on user authentication error at the dependency resolving stage. For HTTPBasic pass auto_error=False: security = HTTPBasic(auto_error=False) And then in basic_logged_user you should check that def basic_logged_user(credentials: Annotated[Opti...
2
0
77,753,658
2024-1-3
https://stackoverflow.com/questions/77753658/langchain-local-llama-compatible-model
I'm trying to setup a local chatbot demo for testing purpose. I wanted to use LangChain as the framework and LLAMA as the model. Tutorials I found all involve some registration, API key, HuggingFace, etc, which seems unnecessary for my purpose. Is there a way to use a local LLAMA comaptible model file just for testing ...
No registration is required to utilize on-prem local models within ecosystems like Hugging Face (HF). Similarly, using Langchain does not involve any registration requirements. Various model formats, such as GGUF and GGML, are employed for storing models for inference and can be found on HF. It is crucial to consider t...
3
4
77,753,308
2024-1-3
https://stackoverflow.com/questions/77753308/is-this-tuple-syntax-inside-a-python-list-comprehension-if-not-what-is-it
I am having some trouble understanding parts of syntax. Particularly when parentheses () are required for tuples. For instance, this piece of code below: c = {'a':10,'b':1,'c':22,'d':10} tup = a,b = 4,5 print(a) print(b) print(tup) newlist = [(x,y) for y,x in c.items()] print(newlist) The output for this code is: 4 5 ...
Parentheses are needed to give priority to operators. Consider the two following lines of code, which differ only by the parentheses: tup_a = 3, 4 + 10, 20 tup_b = (3, 4) + (10, 20) The first line defines a tuple tup_a of 3 elements, (3, 14, 20). The second line defines two tuples (3, 4) and (10, 20), then concatenate...
3
9
77,753,412
2024-1-3
https://stackoverflow.com/questions/77753412/get-the-standard-deviation-of-a-row-ignoring-the-min-and-max-values
Given the following data frame: a b c d e sd -100 2 3 60 4 1 7 5 -50 9 130 2 How would I calculate the standard deviation sd column which excludes the minimum and maximum values from each row? The actual data frame is a few million rows long so something vectorised would be great! To replicate: df = pd.Da...
Excluding the first min/max An approach that should be fast would be to use numpy to sort the values per row, exclude the first and last and compute the std: df['sd'] = np.sort(df, axis=1)[:, 1:-1].std(axis=1, ddof=1) Handling duplicate min/max (excluding all) If you can have several times the same min/max and want to...
2
5
77,752,740
2024-1-3
https://stackoverflow.com/questions/77752740/pandas-use-assign-transform-in-pipe-after-a-merge
I have two dfs solar_part = pd.DataFrame( {'pool': 1, 'orig': 635.1}, index = [0] ) solar_aod = pd.DataFrame( {'pool': [1,1,1,1], 'MoP': [1,2,3,4], 'prin': [113.1, 115.3, 456.6, 234.1]} ) Which I then merge together via pipeline and try and transform/assign a new variable solar_p = ( solar_aod .merge(solar_part, on = ...
You can use eval to create an additional column as well as assign but the latter need to evaluate the new dataframe before use columns that why you have to use a lambda function here: solar_p = ( solar_aod .merge(solar_part, on='pool', how='left') .eval('remn = prin / orig') ) Output: >>> solar_p pool MoP prin orig re...
3
4
77,751,520
2024-1-3
https://stackoverflow.com/questions/77751520/performing-addition-and-subtraction-operations-within-the-columns-of-the-same-py
I have a data Dataframe like, data = { "A": [42, 38, 39,23], "B": [45, 30, 15,65], "C": [60, 50, 25,43], "D": [12, 70, 35,76,], "E": [87, 90, 45,43], "F": [40, 48, 55,76], "G": [58, 42, 85,10], } df = pd.DataFrame(data) print(df) A B C D E F G 0 42 45 60 12 87 40 58 1 38 30 50 70 90 48 42 2 39 15 25 35 45 55 85 3 23 65...
You can use a single eval with a multiline expression: df = df.eval('''C=C-B+A D=D-B+A E=E-B+A ''') Or, for this particular operation, since all are +A-B: df[['C', 'D', 'E']] = df[['C', 'D', 'E']].add(df['A'].sub(df['B']), axis=0) Output: A B C D E F G 0 42 45 57 9 84 40 58 1 38 30 58 78 98 48 42 2 39 15 49 59 69 55...
4
4
77,750,484
2024-1-3
https://stackoverflow.com/questions/77750484/why-is-pd-date-range-sometimes-stop-inclusive-and-sometimes-exclusive-based-on
import pandas as pd print(pd.date_range(start='1999-08-01', end='2000-07-01', freq='D')) print(pd.period_range(start='1999-08-01', end='2000-07-01', freq='D')) print(pd.date_range(start='1999-08', end='2000-07', freq='M')) #This doesn't include anything from 2000-07, ie is not stop-inclusive - length 11 print(pd.period...
This is because 2000-07 is understood as 2000-07-01 and M is the end of month (opposite to MS the start of month) so 2000-07-31 is after 2000-07-01. If you want to include "July" change the frequency from M to MS but it will change the day: >>> pd.date_range(start='1999-08', end='2000-07', freq='M')[[0, -1]] DatetimeIn...
2
1
77,750,066
2024-1-3
https://stackoverflow.com/questions/77750066/group-axis-labels-for-seaborn-box-plots
I want a grouped axis label for box-plots for example a bit like this bar chart where the x axis is hierarchical: I am struggling to work with groupby objects to extract the values for the box plot. I have found this heatmap example which references this stacked bar answer from @Stein but I can't get it to work for my...
You can use: import numpy as np import seaborn as sns import matplotlib.pyplot as plt from itertools import groupby def test_table(): data_table = pd.DataFrame({'Room':['Room A']*24 + ['Room B']*24, 'Shelf':(['Shelf 1']*12 + ['Shelf 2']*12)*2, 'Staple':['Milk','Water','Sugar','Honey','Wheat','Corn']*8, 'Quantity':np.ra...
2
1
77,749,311
2024-1-3
https://stackoverflow.com/questions/77749311/replace-multiple-matching-groups-with-modified-captured-gropus
I am reading text from a file that contains flags start and end. I want to replace everything between start and end with the same text except I want to remove any newlines in the matching group. I tried to do it as follows: import re start = '---' end = '===' text = '''\ Some text ---line 1 line 2 line 3=== More text ....
Use non-greedy modifier (?) in the capturing group. Also, change the replacement function for simple str.replace: import re start = "---" end = "===" text = """\ Some text ---line 1 line 2 line 3=== More text ... Some more text ---line 4 line 5=== and even more text\ """ modified = re.sub( pattern=rf"{start}(.+?){end}"...
2
1
77,732,090
2023-12-29
https://stackoverflow.com/questions/77732090/polars-multiply-2-lazyframes-together-by-column
I have 2 polars LazyFrames: df1 = pl.DataFrame(data={ 'foo': np.random.uniform(0,127, size= n).astype(np.float64), 'bar': np.random.uniform(1e3,32767, size= n).astype(np.float64), 'baz': np.random.uniform(1e6,2147483, size= n).astype(np.float64) }).lazy() df2 = pl.DataFrame(data={ 'foo': np.random.uniform(0,127, size= ...
you'll need to join ( df1.with_row_index() .join(df2.with_row_index(), on="index") .select(pl.col(col) * pl.col(f"{col}_right") for col in df1.columns) .collect() ) shape: (10, 3) ┌─────────────┬──────────┬───────────┐ │ foo ┆ bar ┆ baz │ │ --- ┆ --- ┆ --- │ │ f64 ┆ f64 ┆ f64 │ ╞═════════════╪══════════╪═══════════╡ │...
2
2
77,738,762
2023-12-31
https://stackoverflow.com/questions/77738762/django-multiselectfield-error-super-object-has-no-attribute-get-flatchoices
I tried to use Django Multiselectfield library but i got this error: I already installed it properly by command: pip install django-multiselectfield I also added in my settings.py INSTALLED_APPS = [ ..... 'multiselectfield', ] My models.py: from multiselectfield import MultiSelectField from django.db import models CA...
The current version of Multiselectfield is incompatible with Django 5.0. There is no _get_flatchoices in django's CharField anymore, instead Django provides flatchoices directly. Therefore, the following code in ../multiselectfield/db/fields.py should be removed. def _get_flatchoices(self): flat_choices = super(MultiSe...
1
6
77,737,323
2023-12-30
https://stackoverflow.com/questions/77737323/why-does-parallel-reading-of-an-hdf5-dataset-max-out-at-100-cpu-but-only-for-l
I'm using Cython to read a single Dataset from an HDF5 file using 64 threads. Each thread calculates a start index start and chunk size size, and reads from that chunk into a common buffer buf, which is a memoryview of a NumPy array. Crucially, each thread opens its own copy of the file and Dataset. Here's the code: de...
Something is happening that is either preventing cython's prange from launching multiple threads, or is preventing the threads from getting anywhere once launched. It may or may not have anything to do directly with hdf5. Here's some possible causes: Are you pre-allocating a buf large enough to hold the entire dataset...
3
1
77,747,229
2024-1-2
https://stackoverflow.com/questions/77747229/log-a-dataframe-using-logging-and-pandas
I am using pandas to operate on dataframes and logging to log intermediate results, as well as warnings and errors, into a separate log file. I need to also print into the same log file a few intermediate dataframes. Specifically, I want to: Print dataframes into the same log file as the rest of the logging messages (...
What you are looking for is a custom Formatter. Using it will be more Pythonic. It provides better flexibility and code readability, as it is part of Python logging system. class DataFrameFormatter(logging.Formatter): def __init__(self, fmt: str, n_rows: int = 4) -> None: self.n_rows = n_rows super().__init__(fmt) def ...
2
6
77,725,407
2023-12-28
https://stackoverflow.com/questions/77725407/how-to-forecast-out-of-sample-value-in-sktime-squaringresiduals
I am trying to forecast out-of-sample value using sktime SquaringResiduals. Here is the code which working well for in-sample prediction. from sktime.forecasting.arch import StatsForecastGARCH from sktime.forecasting.squaring_residuals import SquaringResiduals def hybridModel(p,q,model): out_sample_date = FH(np.arange(...
The documentation explains that the forecaster is trained on y(t_1),...y(t_i) where i = initial_window, ... N-steps_ahead, and that this is used to calculate the residual r(t_i+steps_ahead) := y(t_i+steps_ahead) - ŷ(t_i+steps_ahead) for each value of i. The initial_window must be less than or equal to N-steps_ahead to ...
3
1
77,740,462
2023-12-31
https://stackoverflow.com/questions/77740462/deconvolution-of-distributions-defined-by-histograms
I'm reading an excellent paper (here) in which the authors begin with a dataset of effect estimates from randomized control trials. In theory, these numbers are a convolution between an unknown distribution and a standard normal. That is to say, each number can be thought of as a draw from the unknown distribution plus...
Yes, when independent random variables X and E are added, the pdf of the sum (X + E) is the convolution of X's pdf and E's pdf. So, if we know the distribution of E and have a histogram estimating the pdf of (X + E), it is possible to obtain a non-parametric estimate of the distribution of X by deconvolution. An import...
2
2
77,733,446
2023-12-29
https://stackoverflow.com/questions/77733446/polars-api-registering-and-type-checkers
I'm consistently getting type errors from either mypy or pyright when using polars namespace registration functions. Is there a way I can avoid type-checker errors other than hinting # type: ignore[attr-defined] every time I'm using a function from my custom namespace? Example follows from the official documentation ht...
Polars API registration is non-compliant with Python's typing system. First and foremost, Polars can help by providing a dynamic attribute access typing hint. Without them doing this, only type-checkers with modding or plugin support can allow you to get around this. Polars classes with dynamically-registerable namespa...
5
3
77,738,266
2023-12-31
https://stackoverflow.com/questions/77738266/how-to-make-pydantic-class-fields-immutable
I am trying to create a pydantic class with Immutable class fields (not instance fields). Here is my base code: from pydantic import BaseModel class ImmutableModel(BaseModel): _name: str = "My Name" _age: int = 25 ImmutableModel._age = 26 print("Class variables:") print(f"Name: {ImmutableModel._name}") print(f"Age: {Im...
Initially, I tried to achieve creating immutable Class and Instance using pydantic module. Now I were able to manage it using native method itself. Since this was completely defined by me and immutable, its fine to have no validation. class ImmutableMetaclass(type): def __setattr__(cls, name, value): raise AttributeErr...
2
0
77,742,640
2024-1-1
https://stackoverflow.com/questions/77742640/moviepy-compositevideoclip-generates-blank-unplayable-video
I'm trying to generate a video: the image at the top, the text in the center and the video at the bottom. I don't want any gap between them. The image is resized to become the first half, so the height is set to 960 (the final video is 1080 x 1920). Similarly, the video is resized and cropped. The text should be on top...
The issue comes from these two lines bellow, resize asumes that only one of the arguments will be specified, meaning that the width argument is ignored (hitting this condition) and because you didn't specify a size when calling CompositeVideoClip, the final clip will be rendered with the size of the first clip in the a...
2
1
77,739,186
2023-12-31
https://stackoverflow.com/questions/77739186/initializing-an-earth-engine-project-in-colab
I can no longer initailize my own earth engine project on Google colab using Python. I tried initializing using the ee.Initialize() method on Colab with used to provide with a link that will generate a token to my project but instead i get this error: WARNING:googleapiclient.http:Encountered 403 Forbidden with reason "...
Their lack of documentation on this change is incredibly frustrating, but fortunately it's a very easy fix (or at least it was for me). If you go to your earth engine code editor and click on the 'Assets' tab, then copy the name of the Project that all of your EE assets are that you're trying to access.see linked image...
2
4
77,746,344
2024-1-2
https://stackoverflow.com/questions/77746344/how-to-hyperlink-nodes-in-d3js-networkx-digraph
I would like to create a NetworkX graph and visualize it using d3js similarly to the javascript example in the NetworkX docs. This graph is very similar to the interactive graph on the NetworkX homepage page. The example works for me, but I would like to add hyperlinks to the nodes. I think I have node attributes calle...
Here's a solution using gravis, which accepts graph objects from NetworkX, iGraph, graph-tool and some other Python libraries and can visualize them with either d3.js, vis.js or three.js with a single function call. Disclaimer: I'm the developer of gravis. Your use case appears to be 1) creating an interactive graph vi...
1
2
77,745,673
2024-1-2
https://stackoverflow.com/questions/77745673/poetry-add-command-removes-category-from-lock-file
My current poetry.lock file looks like this (part of it) # This file is automatically @generated by Poetry and should not be changed by hand. [[package]] name = "annotated-types" version = "0.6.0" description = "Reusable constraint types to use with typing.Annotated" category = "main" optional = false python-versions =...
category was removed since poetry 1.5, that is why it's removed in poetry.lock file after any changes
2
4
77,747,059
2024-1-2
https://stackoverflow.com/questions/77747059/why-does-hatch-not-save-the-virtual-environment-in-the-same-directory-i-am-worki
Why does hatch not save the virtual environment in the same directory I am working in? I went through the doc and couldn't find a way to achieve that. Maybe it makes sense that it's that way but I can't really think why. Is there a way to create it in the project directory? Or a good reason to not want to do that?
When you use a tool like hatch, you are basically giving up precise control over the virtual environment in favor of letting hatch manage it for you; this includes letting hatch decide where to keep all such managed environments. That said, hatch stores virtual environments in a specific data directory that you can spe...
3
2
77,746,742
2024-1-2
https://stackoverflow.com/questions/77746742/what-is-the-term-for-a-colon-before-a-suite-in-python-syntax
I want to know what the technical term for a colon in the context of introducing a suite after a statement is called. I do not mean colons in slices, key-value pairs or type hints, but this kind of usage: if True: pass else: pass try: raise except: pass def foo(): pass lambda: ... # I don't know if this is appertaining...
It's simply called a "colon" :, but I might say and the grammar spec suggests you'd say something like "the start of a block" https://docs.python.org/3/reference/grammar.html # COMPOUND STATEMENTS # =================== # Common elements # --------------- block: | NEWLINE INDENT statements DEDENT | simple_stmts
2
3
77,742,624
2024-1-1
https://stackoverflow.com/questions/77742624/how-to-group-items-of-a-list-based-on-their-type-transition
My input is a list: data = [ -1, 0, 'a','b', 1, 2, 3, 'c', 6, 'd', 'e', .4, .5, 'a', 'b', 4, 'f', 'g', ] I'm trying to form groups (dictionary) where the keys are the strings and the values are the numbers right after them. There are however three details I should consider: The list of data I receive can sometimes ha...
You can use itertools.groupby with a key function that tests if the current item is a string. To skip possible leading non-string items, fetch the first group, and fetch the next group again as a replacement if the first group items are not strings. For each group of items, if they are strings, join them as a key; othe...
1
1
77,743,877
2024-1-2
https://stackoverflow.com/questions/77743877/model-instance-doesnt-check-fields-integrity
Consider the model below class Faculty(models.Model): name = models.CharField(max_length=255) short_name = models.CharField(max_length=15) description = models.CharField(max_length=512) logo = models.ImageField(upload_to=faculty_upload_to, null=True) That I do Faculty.objects.create() or faculty = Faculty() faculty.sa...
CharFields default to an empty string (""), which is a valid value for a VARCHAR column. You may consider adding a CheckConstraint if you want to validate values at the database level: class Faculty(models.Model): name = models.CharField(max_length=255) short_name = models.CharField(max_length=15) description = models....
1
2
77,743,898
2024-1-2
https://stackoverflow.com/questions/77743898/keep-the-previous-maximum-value-after-the-streak-ends
This is my dataframe: import pandas as pd df = pd.DataFrame( { 'a': [110, 115, 112, 180, 150, 175, 160, 145, 200, 205, 208, 203, 206, 207, 208, 209, 210, 215], 'b': [1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1], } ) And this is the output that I want. I want to create column c. a b c 0 110 1 110 1 115 1 115 ...
You just want cummax: df['c'] = df['a'].cummax() Output: a b c 0 110 1 110 1 115 1 115 2 112 0 115 3 180 1 180 4 150 0 180 5 175 1 180 6 160 0 180 7 145 0 180 8 200 1 200 9 205 1 205 10 208 1 208 11 203 0 208 12 206 1 208 13 207 1 208 14 208 1 208 15 209 1 209 16 210 1 210 17 215 1 215
2
4
77,741,382
2024-1-1
https://stackoverflow.com/questions/77741382/how-to-make-a-column-with-data-type-bit-and-lenght-4-in-sqlalchemy-for-mariadb-o
I have not found a way to do this as the BIT data type in sqlalchemy inherits from Boolean datatype. flags = Column(BIT(4), nullable=False) # BIT column with length 4 sql: `flags` BIT(4) NOT NULL DEFAULT b'0', AttributeError: 'BIT' object has no attribute 'length'
BIT is not a standard data type (neither in SQL Standard nor in SQLAlchemy) but it is supported by e.g. PostgreSQL, SQL Server, MariaDB and MySQL. As @danblack already mentioned in his comment, BIT type is defined in types.py (but also in base.py as MSBit). That means you have to use types of your dialect, in this case...
2
1
77,742,615
2024-1-1
https://stackoverflow.com/questions/77742615/how-to-easily-get-these-values-from-a-2d-matrix-using-numpy
I have this 2d numpy matrix a = np.array( [[ 1 2 3 4 5] [ 6 7 8 9 10] [11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25] [26 27 28 29 30]]) and I want to extract these values from it just for the sake of learning :) [[11,12],[16,17],[29,30]] After so many tries I ended up in chatGPT which gave me a wrong answer :(. c...
You need to add commas to your array. You can use numpy indexing: https://numpy.org/doc/stable/user/basics.indexing.html import numpy as np a=np.array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30]]) print(a[2:4,0:2]) or print(a[[2,3],0:2]...
2
1
77,740,136
2023-12-31
https://stackoverflow.com/questions/77740136/read-from-multiple-rest-api-stream-endpoints-python
I have a multiple rest api endpoints (urls) which streams data. I wonder what would be the best approach to read from all of them in one / many processes. currently I'm reading the data only from one url, doing something like: s = requests.Session() resp = s.get(url, headers=headers, stream=True) for line in resp.iter...
Here is an example how you can read from multiple URLs using concurrent.futures.ThreadPoolExecutor. But this is just one approach, you can use multiprocessing, asyncio/aiohttp, etc. from concurrent.futures import ThreadPoolExecutor import requests def get_from_api(tpl): session, url = tpl resp = session.get(url, stream...
2
2
77,741,201
2024-1-1
https://stackoverflow.com/questions/77741201/check-if-a-child-element-is-present-and-non-empty-in-xml-file
I have the following xml file: <?xml version="1.0" encoding="utf-8"?> <components version="1.0.0"> <component type="foo"> <maintag> <subtag> <check>Foo</check> </subtag> <subtag> <check></check> </subtag> <subtag> </subtag> </maintag> </component> </components> I want to check that each subtag element has child elemen...
You can translate your two conditions to an XPath : root = etree.parse("test.xml") expr = "//subtag[not(check/text()) or not(check)]" not any(e is not None for e in root.xpath(expr)) # False Alternatively, if you need to verbose the checks, you can do something like : for idx, st in enumerate(root.xpath("//subtag"), 1...
2
2
77,741,143
2024-1-1
https://stackoverflow.com/questions/77741143/matplotlib-ticks-are-overlapped-when-hspace-0
When pushing two plots together, I'd like to have the the ticks set to 'inout' and have it properly displayed over both the charts, but the 2nd chart is overlapping it. import matplotlib.pyplot as plt import numpy as np t = np.arange(0.01, 5.0, 0.01) s1 = np.sin(2 * np.pi * t) s2 = np.exp(-t) ax1 = plt.subplot(211) pl...
IIUC, you can create ax2 before ax1: import matplotlib.pyplot as plt import numpy as np t = np.arange(0.01, 5.0, 0.01) s1 = np.sin(2 * np.pi * t) s2 = np.exp(-t) ax2 = plt.subplot(212) plt.plot(t, s2) ax1 = plt.subplot(211, sharex=ax2) plt.plot(t, s1) plt.tick_params('x', labelbottom=False, direction='inout', length=6)...
3
3
77,740,674
2024-1-1
https://stackoverflow.com/questions/77740674/pandas-groupby-run-self-function-then-transformapply
I need to run regression for each group, then pass the coefficients into the new column b. Here is my code: Self-defined function: def simplereg(g, y, x): try: xvar = sm.add_constant(g[x]) yvar = g[y] model = sm.OLS(yvar, xvar, missing='drop').fit() b = model.params[x] return pd.Series([b*100]*len(g)) except Exception ...
Is it a bad idea to catch all exceptions? Obviously yes. In addition you do not display any error message. If your function returns NaN values, it's probably because your code is throwing an exception. Your code works well for me if I import statsmodels.api as sm and make minor changes: import statsmodels.api as sm def...
3
0
77,741,075
2024-1-1
https://stackoverflow.com/questions/77741075/merge-dfs-but-avoid-duplication-of-columns-and-maintain-the-order-in-pandas
All the dfs have a key col "id". pd.merge is not a viable option even with the suffix option. There are over 40k cols in each of the dfs so column binding and deleting later (suffix_x) is not an option. Exactly 50k (common) rows in each of the dfs identified by "id" col. Minimal example with two common cols: df1 = pd.D...
If memory is limiting and the dataframes are already aligned, you could try to set up the output and update it: from functools import reduce dfs = [df1, df2, df3] cols = reduce(lambda a,b: a.union(b, sort=False), (x.columns for x in dfs)) out = pd.DataFrame(index=dfs[0].index, columns=cols) for x in dfs: out.update(x) ...
3
4
77,740,923
2024-1-1
https://stackoverflow.com/questions/77740923/replacing-a-value-with-its-previous-value-in-a-column-if-it-is-greater
This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [101, 90, 11, 120, 1] } ) And this is the output that I want. I want to create column y: a y 0 101 101.0 1 90 101.0 2 11 90.0 3 120 120.0 4 1 120.0 Basically, values in a are compared with their previous value, and the greater one is selected. For e...
You can use np.fmax to get the maxima without creating an additional column: df["y"] = np.fmax(df["a"], df["a"].shift(1)) This outputs: a y 0 101 101.0 1 90 101.0 2 11 90.0 3 120 120.0 4 1 120.0 We use np.fmax() to ignore the NaN created when shifting df["a"].
2
5
77,740,276
2023-12-31
https://stackoverflow.com/questions/77740276/pandas-dataframe-groupby-over-consecutive-duplicates-and-sum-the-values
In pandas dataframe, I'm totally confused of how to use the method of groupby() over consecutive duplicates by sum values in column Let's say I have the following DataFrame df : index type value 0 profit 11 1 profit 10 2 loss -5 3 profit 50 4 profit 15 5 loss -30 6 loss -25 7 loss -10 what I'm looking to is: index typ...
Instead of .cumcount() use sum: out = ( df.groupby(df["type"].ne(df["type"].shift()).cumsum(), as_index=False) .agg({"type": "first", "value": "sum"}) .rename(columns={"value": "grand"}) ) print(out) Prints: type grand 0 profit 21 1 loss -5 2 profit 65 3 loss -65
2
1
77,737,760
2023-12-30
https://stackoverflow.com/questions/77737760/pandas-join-with-multi-index-and-nan
I am using Pandas 2.1.3. I am trying to join two DataFrames on multiple index levels, and one of the index levels has NA's. The minimum reproducible example looks something like this: a = pd.DataFrame({ 'idx_a':['A', 'A', 'B'], 'idx_b':['alpha', 'beta', 'gamma'], 'idx_c': [1.0, 1.0, 1.0], 'x':[10, 20, 30] }).set_index(...
You can resolve your problem by removing the indexes and using merge instead of join: a = pd.DataFrame({ 'idx_a':['A', 'A', 'B'], 'idx_b':['alpha', 'beta', 'gamma'], 'idx_c': [1.0, 1.0, 1.0], 'x':[10, 20, 30] }) b = pd.DataFrame({ 'idx_b':['gamma', 'delta', 'epsilon', np.nan, np.nan], 'idx_c': [1.0, 1.0, 1.0, 1.0, 1.0]...
2
2
77,736,673
2023-12-30
https://stackoverflow.com/questions/77736673/how-to-show-progression-of-changing-subplot-labels-plt-text-along-with-color-c
running python 3.9: import matplotlib.pyplot as plot import numpy as np import matplotlib.animation as animation fig, plt = plot.subplots() myArray = np.array([[0, 1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12, 13], [14, 15, 16, 17, 18, 19, 20], [21, 22, 23, 24, 25, 26, 27], [28, 29, 30, 31, 32, 33, 34], [35, 36, 37, 38, 39,...
From the ArtistAnimation documentation on the artistlist parameter: Each list entry is a collection of Artist objects that are made visible on the corresponding frame. Note that every object you add to a Matplotlib figure is an artist, including the Text objects that are returned by plt.text. So, for each frame, we c...
2
2
77,736,263
2023-12-30
https://stackoverflow.com/questions/77736263/pandas-loc-method-using-not-and-in-operators
I have a data frame and I want to remove some rows if their value is not equal to some values that I have stored in a list. So I have a list variable stating the values of objects I want to keep: allowed_values = ["value1", "value2", "value3"] And I am attempting to remove rows from my dataframe if a certain column do...
Try this: import pandas as pd allowed_values = ['White', 'Green', 'Red'] df = pd.DataFrame({'color': ['White', 'Black', 'Green', 'White']}) df = df[df['color'].isin(allowed_values)] df color 0 White 2 Green 3 White If you must use .loc then you can use: df = df.loc[df['color'].isin(allowed_values)]
2
1
77,735,868
2023-12-30
https://stackoverflow.com/questions/77735868/stack-multiple-columns-in-a-pandas-dataframe
I have a pandas data frame and would like to stack 4 columns to 2. So I have this df = pd.DataFrame({'date':['2023-12-01', '2023-12-05', '2023-12-07'], 'other_col':['a', 'b', 'c'], 'right_count':[4,7,9], 'right_sum':[2,3,5], 'left_count':[1,8,5], 'left_sum':[0,8,4]}) date other_col right_count right_sum left_count le...
You can use a custom reshaping with a temporary MultiIndex: out = (df .set_index(['date', 'other_col']) .pipe(lambda x: x.set_axis(x.columns.str.split('_', expand=True), axis=1)) .rename_axis(columns=['side', None]) .stack('side').reset_index() ) Or a melt+pivot: tmp = df.melt(['date', 'other_col'], var_name='side') t...
2
3
77,734,544
2023-12-30
https://stackoverflow.com/questions/77734544/breaking-up-dataframe-into-chunks-for-a-loop
I am using a loop (that was answered in this question) to iteratively open several csv files, transpose them, and concatenate them into a large dataframe. Each csv file is 15 mb and over 10,000 rows. There are over 1000 files. I am finding that the first 50 loops happen within a few seconds but then each loop takes a m...
The reason the code is slow is because you are using concat in the loop. You should collect the data in a python dictionary then do a single concat at the end. With few improvements: import pathlib import pandas as pd root_path = pathlib.Path('root') # use pathlib instead of os.path data = {} # use enumerate rather tha...
3
1
77,732,026
2023-12-29
https://stackoverflow.com/questions/77732026/how-to-draw-images-visualizing-numpy-arrays-themselves
Are there tools for visualizing numpy arrays themselves like the image below?
You can do it from first principles: from matplotlib import pyplot as plt from matplotlib.patches import Rectangle from matplotlib.transforms import Bbox def square(i, j, k, origin=(0,0), zstep=0.2, **kwargs): xy = np.array(origin) + np.array((k, j)) + np.array([1, -1]) * i * zstep return Rectangle(xy, 1, 1, zorder=-i,...
4
3
77,734,349
2023-12-29
https://stackoverflow.com/questions/77734349/creating-a-new-column-by-a-condition-and-selecting-the-maximum-value-by-shift
This is my DataFrame: import pandas as pd df = pd.DataFrame( { 'a': [10, 20, 30, 400, 50, 60], 'b': [897, 9, 33, 4, 55, 65] } ) And this is the output that I want. I want to create column c. a b c 0 10 897 NaN 1 20 9 897.0 2 30 33 NaN 3 400 4 400.0 4 50 55 NaN 5 60 65 NaN These are the steps needed: a) Find rows tha...
Try: mask = df.a > df.b df.loc[mask, "c"] = np.where(df["a"] > df["b"].shift(), df["a"], df["b"].shift())[mask] print(df) Prints: a b c 0 10 897 NaN 1 20 9 897.0 2 30 33 NaN 3 400 4 400.0 4 50 55 NaN 5 60 65 NaN
2
1
77,732,940
2023-12-29
https://stackoverflow.com/questions/77732940/aggregate-dataframe-using-simpler-vectorized-operations-instead-of-loops
I have a piece of code that works correctly (gives the expected answer), but is both inefficient and unnecessarily complex. It uses loops that I want to simplify and make more efficient, possibly using vectorized operations. It also converts a dataframe to a series and then back into a dataframe again - another code ch...
IIUC, you can do: length_cutoffs = [10, 100, 1000] df["bins"] = pd.cut( df["length"], pd.IntervalIndex.from_breaks([-np.inf] + length_cutoffs + [np.inf], closed="left"), ) out = df.pivot_table(index=["regions", "bins"], values="length", aggfunc="sum") g = out.groupby(level=0) out["frc_tot_length"] = ( g["length"].trans...
2
2
77,723,957
2023-12-27
https://stackoverflow.com/questions/77723957/permutation-where-element-can-be-repeated-specific-times-and-do-it-fast
I have been looking for a function like this, sadly I was not able to found it. Here a code that do what I write: import itertools #Repeat every element specific times data = { 1: 3, 2: 1, 3: 2 } #Length n = 0 to_rep = [] for i in data: to_rep += [i]*data[i] n += data[i] #itertools will generate also duplicated ones re...
Here are several options. Simple recursive algorithm You can use the following recursive function that iterates over keys: def multiset_permutations(d: dict) -> list: if not d: return [tuple()] else: perms = [] for k in d.keys(): remainder = d.copy() if remainder[k] > 1: remainder[k] -= 1 else: del remainder[k] perms +...
3
3
77,728,680
2023-12-28
https://stackoverflow.com/questions/77728680/python-3-x-how-should-one-override-inherited-properties-from-parent-classes
A simple example probably shows more: class NaturalNumber(): def __init__(self, val): self._value = val def _get_value(self): return self._value def _set_value(self, val): if val < 0: raise ValueError( f"Cannot set value to {val}: Natural numbers are not negative." ) self._value = val value = property(_get_value, _set_...
So first off: super(type(self), type(self)) is straight up wrong; never do that (it seems like it works when there is one layer, it fails with infinite recursion if you make a child class and try to invoke the setter on it). Sadly, this is a case where there is no elegant solution. The closest you can get, in the gener...
2
1
77,730,831
2023-12-29
https://stackoverflow.com/questions/77730831/image-dimension-mismatch-while-trying-to-add-noise-to-image-using-keras-sequenti
To Recreate this question's ask on your system, please find the Source code and Dataset here What I am trying? I am trying to create a simple GAN (Generative Adversarial N/w) where I am trying to recolor Black and White images using a few ImageNet images. What Process am I following? I have take a few Dog images, whic...
generator outputs [32 28 28 3], whereas it is getting a target of shape [32 224 224]. The target has two differences: it is greyscale rather than colour, and has larger dimensions. I am assuming the target supplied to the generator should be colour rather than grayscale. You can load the colour images and resize them u...
2
2
77,728,334
2023-12-28
https://stackoverflow.com/questions/77728334/install-lightgbm-gpu-in-a-wsl-conda-env
-------------------- original question --------------------------------- How to install LightGBM?? I have checked multiple sources but staill failed to install. I tried pip and conda but both return the error: [LightGBM] [Warning] Using sparse features with CUDA is currently not supported. [LightGBM] [Fatal] CUDA Tree ...
Seeing logs about CUDA in the original posts suggests to me that you're trying to use CUDA-enabled LightGBM. It's important to clarify that, as LightGBM supports two different GPU-accelerated builds: -DUSE_GPU=1 ("device": "gpu") = OpenCL-based build targeting a wide range of GPUs -DUSE_CUDA=1 ("device": "cuda") = CUD...
3
4
77,723,202
2023-12-27
https://stackoverflow.com/questions/77723202/how-to-avoid-odoo-15-render-error-for-missing-values
In ODOO 15 I have made my own template that runs a method that returns some data to show in a dictionary. This is a piece of the template: <t t-set="PRI_par_DSP_par_stage" t-value="o.PRI_par_DSP_par_stage(o.date_start, o.date_end, o.source, o.domain)"/> <table border="1" style="text-align: left; width: auto; margin: 0 ...
<td t-if="'dsp_id' in row.keys()"><t t-esc="row['dsp_id']"/></td> <td t-if="'Brouillon' in row.keys()"><t t-esc="row['Brouillon']"/></td>
2
2
77,731,279
2023-12-29
https://stackoverflow.com/questions/77731279/python-how-to-add-a-filter-to-a-histogram
I use Python in Power BI and have currently the following code: import matplotlib.pyplot as plt plt.hist(dataset.age, bins=10, edgecolor="#6A9662", color="#DDFFDD", alpha=0.75) plt.show() In my table i have a column TYPE with "E" and "G". How can i add a Filter TYPE = "E" to the Python code? Many thanks in advance! I ...
I suggest you to filter the dataframe before plotting import matplotlib.pyplot as plt data = dataset[dataset["TYPE"]=="E"].age plt.hist(data, bins=10, edgecolor="#6A9662", color="#DDFFDD", alpha=0.75) plt.show()
2
1
77,731,198
2023-12-29
https://stackoverflow.com/questions/77731198/polars-product-of-all-columns-except-one-in-2-lazyframes
I am learning polars, having come from pandas. In pandas land, I frequently operate on 2 dataframes, each with a datetime index, and the same columns. Example: df1 = pd.DataFrame(data={ 'time': pd.date_range('2023-01-01', periods=n, freq='1 min'), 'foo': np.random.uniform(0,127, size=n).astype(np.float64), 'bar': np.ra...
You can create a .struct containing the "non-index" columns. df1.select("time", cols=pl.struct(pl.exclude("time"))) shape: (5, 2) ┌─────────────────────┬───────────────────────────────────┐ │ time ┆ cols │ │ --- ┆ --- │ │ datetime[ns] ┆ struct[3] │ ╞═════════════════════╪═══════════════════════════════════╡ │ 2023-01-...
2
1
77,729,423
2023-12-28
https://stackoverflow.com/questions/77729423/pandas-dataframe-to-json-transform-pythonic-way
I am bit rusty in pandas to json transforms. I have a pandas data frame like this for a fictional library: userId visitId readingTime Books BookType u1 1 300 book1,book2,book3 Fiction u2 1 400 book4,book5 Horror u2 2 250 book6 Romance Need to create a json that is like: { "visitSummary": { "u1": [ { "re...
With split, groupby & to_dict : out = { "visitSummary": (df.assign(Books=df["Books"].str.split(",")) .groupby("userId").apply(lambda g: g.drop( columns=["userId", "visitId"]).to_dict("records")).to_dict()) } Output : import json; print(json.dumps(out, indent=4)) { "visitSummary": { "u1": [ { "readingTime": 300, "Books...
2
1
77,728,931
2023-12-28
https://stackoverflow.com/questions/77728931/how-to-use-tqdm-and-processpoolexecutor
I'm creating a program that processes files sometimes very huge files in the order of GB. It takes a lot of time. At first I tried using ThreadPoolExecutor which relatively improved the speed. For example a ~200 Mb file would take about ~3 minutes running synchronously, with ThreadPoolExecutor, about ~130+ seconds. Tha...
Since you want to use a ProcessPoolExecutor instance (you code still shows you using a ThreadPoolExecutor instance), then the main process which has nothing else to except wait for submitted tasks to complete can easily be the updater of the progress bar. You now need to arrange for your worker function/method (in your...
2
2
77,728,651
2023-12-28
https://stackoverflow.com/questions/77728651/is-there-a-way-to-stream-multiple-videos-continuosly-with-the-same-address-and-r
I am participating in a project using RTSP and cameras footage. My objective is to create a continuous flow of videos streamed in the same address and route to update the videos according to the footage we need to display. So, the expected behavior I have to create is to change the video streamed in the address while u...
I realized that I was creating a new object instead of changing the current one. This made that ffplay was incapable of keeping track of the address and route because loses connection and then it is reconnected immediately, making the stream to crash. The final code for updating the videos is a modification of the func...
2
1
77,724,098
2023-12-27
https://stackoverflow.com/questions/77724098/getting-csrf-verification-failed-request-aborted-on-a-django-forms-on-live-ser
Hello I am learning Django i write a app and publish it in AWS EC2 instance with gunicorn and ngnix on local environments everything works fine but in production on every submit on forms i get this 403 Error : Forbidden (403) CSRF verification failed. Request aborted. More information is available with DEBUG=True. iam...
Everything works fine but in production on every submit on forms i get this 403 Error The reason you get this error is because you are requesting your website with https but you have not defined the 443 port on nginx. Here is a post to do this using AWS. Here is a simple example: server { server_name winni-furnace.ca...
2
1
77,724,742
2023-12-28
https://stackoverflow.com/questions/77724742/reset-index-acting-in-an-unexpected-way-unexpected-keyword-argument-names
I'm cleaning up a dataset for plotting. Pretty standard stuff, transposing, deleting unnecessary columns, etc. Here is the code so far: #File name fname = r'E:\Grad School\Research\BOEM\Data\Grain Size\ForScript\allmyCoresRunTD.csv' #Read csv file into a dataframe. skips the first row that just has the 'record number'....
Check that version of pandas you are running is >= 1.5.0. The parameter was introduced in 1.5.0 for reset_index() import pandas as pd pd.__version__
2
4
77,725,185
2023-12-28
https://stackoverflow.com/questions/77725185/can-i-run-just-pd-df-to-csv-in-a-different-thread
I have a pretty big pandas dataframe and I want to select some rows based on conditions. The problem is that the act of saving as CSV is separate from the overall flow of the program and consumes quite a bit of time. Is it possible to separate the threads so that the main thread progresses to the selected rows, while a...
Yes, Python's either threading or multiprocessing features are handy for concurrent tasks like saving a DataFrame to CSV while doing other tasks. There are things you need to consider while working with threads and multiprocessing in python: Global Interpreter Lock (GIL) in Python: This means threading may not always ...
2
5
77,723,077
2023-12-27
https://stackoverflow.com/questions/77723077/how-to-make-sure-all-combinations-for-each-number-are-given-in-an-integer-compos
I'm watching the MIT OCW 2008 Introduction to Computer Science and Programming, and trying to do the assignments. This is informal so there's no grading involved. There's this problem where you have to have to buy specific numbers of nuggets with packs containing 6, 9, and 20 nuggets. The aim is to learn to how to use ...
I took a quick go at this question, following the comment from gog. The reason that you are only getting one answer for each answer you input is that you are returning prematurely. Each time you find the first answer, you create a new child function and look for an answer in this number. Eventually, you reach 66 which ...
2
2
77,723,163
2023-12-27
https://stackoverflow.com/questions/77723163/can-a-decorator-name-classes-it-creates
I have a decorator which wraps functions and produces classes (for a better reason than in the following example). It all works, except that I'd like to be able to set the name of the class given by type(). For example, >>> class Animal: ... pass ... >>> def linnean_name(genus, species): ... def _linnean_name(fn): ... ...
You are looking for __new__. It allows you to specify a new class name and share a common base class for pre-defined behavior. You could also make MixIn classes by define more bases/base classes etc. class Animal: def talk(self): print(f"Hello, I am {self}") def __str__(self): return f'{self.family} {self. spec}' def _...
5
1
77,724,179
2023-12-27
https://stackoverflow.com/questions/77724179/how-numpy-arrays-are-overwritten-from-interpreter-point-of-view
I wrote two simple functions to learn CPython's behaviour regarding numpy arrays. Python 3.12.1 and numpy version 1.26.2, compiled by mkl (conda default) def foo(): for i in range(100): H = np.random.rand(1000, 1000) %timeit -r 100 foo() def baaz(): H = np.zeros((1000, 1000)) for i in range(100): H[:, :] = np.random....
In both cases you are creating a new array when you do np.random.rand(1000, 1000), and then de-allocating it. In the baaz case, you are also going through the work up updating the initial array. Hence it is slower. Numpy functions provide a way to avoid this, consider a simple case: arr[:] = arr + 1 This always create...
2
1
77,723,914
2023-12-27
https://stackoverflow.com/questions/77723914/how-to-share-a-common-argument-between-nested-function-calls-in-python
I have two Python functions f() and g() which share one argument: a. def f(a, b): return a + b def g(a, c): return a * c Sometimes, g() is called standalone, in which case both arguments are necessary: g(a = 1, c = 3) Sometimes, g() is called as an argument inside a f() call: f(a = 1, b = g(a = 1, c = 3)) Notice tha...
What you want is not possible, g cannot know how it is called and it is evaluated before f. If you can modify the functions, g could return a partial if a is missing, then f can evaluate it if b is a function: from functools import partial def f(a, b): if callable(b): b = b(a) return a + b def g(a=None, c=None): if a i...
2
3
77,719,569
2023-12-27
https://stackoverflow.com/questions/77719569/multivariable-gradient-descent-for-mles-nonlinear-model-in-python
I am trying to perform gradient descent to compute three MLEs (from scratch). I have data $x_i=s_i+w_i$ where $s_i=A(nu_i/nu_0)^{alpha}(nu_i/nu_0+1)^{-4alpha}$ where I have calculated the first derivatives analytically: import numpy as np import matplotlib.pyplot as plt #model function s_i def signal(A,nu_0,alpha,nu): ...
Observations Your MCVE seems to have hard time with some xi values when assessing derivatives: it experiences overflow or division by 0. As a consequence, your parameter vector contains NaN and the algorithm fails. For some setup, the problem is not present, for instance fixing the random seed to: np.random.seed(123456...
3
1
77,720,049
2023-12-27
https://stackoverflow.com/questions/77720049/optimizing-multiple-try-except-code-for-web-scraping
I have a web scraping script where, due to many reasons, some codes "break" if not finding the information as expected. I am handling it with multiple "try/except" blocks. asin = item.get('data-asin') title = item.find_all('span',{'class' : 'a-size-base-plus a-color-base a-text-normal'})[0].get_text() try: label = ite...
Yes, you can create a function to handle the repetitive try/except blocks, but you have to find a common way to get your fields, then it might be something like: def get_element(item, selector, attribute, failsafe_value=None): try: element = item.find(selector).get(attribute) return element if element else failsafe_val...
2
3
77,719,714
2023-12-27
https://stackoverflow.com/questions/77719714/detect-and-create-mask-for-color-highlighted-section-on-image
How can I create a highlight mask for an image? I have attempted various methods, however, I have not been able to attain the desired outcome. How to detect colored sections without any adverse effects on the pink colored section, or any other color such as yellow? Input Current output Desired output import cv2 impo...
You are almost there. You need a couple of Morphological filters and a little bit of tuning in your HSV thresholds. To obtain the final mask, you could also apply a Flood-fill at one corner using white color. Something like this: # Imports: import cv2 # Set image path directoryPath = "D://opencvImages//" # Set image pa...
2
1
77,697,302
2023-12-21
https://stackoverflow.com/questions/77697302/how-to-run-ollama-in-google-colab
I have a code like this. And I'm launching it. I get an ngrok link. !pip install aiohttp pyngrok import os import asyncio from aiohttp import ClientSession # Set LD_LIBRARY_PATH so the system NVIDIA library becomes preferred # over the built-in library. This is particularly important for # Google Colab which installs o...
1. Run ollama but don't stop it !curl https://ollama.ai/install.sh | sh # should produce, among other thigns: # The Ollama API is now available at 0.0.0.0:11434 This means Ollama is running (but do check to see if there are errors, especially around graphics capability/Cuda as these may interfere. However, Don't run !...
17
12
77,690,729
2023-12-20
https://stackoverflow.com/questions/77690729/django-built-in-logout-view-method-not-allowed-get-users-logout
Method Not Allowed (GET): /users/logout/ Method Not Allowed: /users/logout/ [10/Dec/2023 12:46:21] "GET /users/logout/ HTTP/1.1" 405 0 This is happening when I went to url http://127.0.0.1:8000/users/logout/ urls.py: from django.contrib.auth import views as auth_views urlpatterns = [ ...other urls... path('users/logou...
Since django-5, you need to do this through a POST request, since it has side-effects. The fact that it worked with a GET request was (likely) a violation of the HTTP protocol: it made it possible for certain scripts to log out users, without the user wanting to. So a POST request also protects against cross-site reque...
21
20
77,706,694
2023-12-23
https://stackoverflow.com/questions/77706694/how-to-modify-my-python-slack-bolt-socket-mode-code-to-reload-automatically-duri
I have the following Python code which works fine using the Web Socket mode. When I type a slash command (/hello-socket-mode) on my Slash application then it very well invokes my method, handle_some_command():- import os from slack_bolt import App from slack_bolt.adapter.socket_mode import SocketModeHandler # Install t...
Code like this will work; you may delete fastapi dependency if not needed when development finished import os from fastapi import FastAPI from slack_bolt.adapter.socket_mode import SocketModeHandler from slack_bolt.app import App # Set enviornment vars BOT_TOKEN = os.environ["SLACK_BOT_TOKEN"] APP_TOKEN = os.environ["S...
2
3
77,692,864
2023-12-20
https://stackoverflow.com/questions/77692864/django-request-from-requestfactory-on-windows-does-not-include-session-attribut
My drone pipeline suddenly started failing on Windows only (the Linux pipeline, executing the same tests, works fine). error: assert hasattr(request, 'session'), "The session-based temporary "\ AssertionError: The session-based temporary message storage requires session middleware to be installed, and come before the...
Why is the session attribute not present on the request? You're using RequestFactory to create your request and directly passing it to the view, this means the request doesn't go through any of the middleware and since SessionMiddleware is responsible for setting up the session it doesn't work. This is described more i...
2
2
77,692,807
2023-12-20
https://stackoverflow.com/questions/77692807/aws-glue-4-0-failing-when-calling-dynamicframe-fromdf
I'm trying to convert a Spark data frame in Python 3.10 into a dynamic frame using Glue's fromDF method from awsglue.dynamicframe import DynamicFrame DynamicFrame.fromDF(frame, glue_context, "node") But this throws an error on CloudWatch saying com.mongodb.spark.sql.connector.exceptions.MongoSparkException: Partitionin...
What worked for me is setting the partitioner in the batch read configuration for mongo-spark to be set to SinglePartitionPartitioner. Seems like the default was updated to use SamplePartitioner in Glue 4.0 and the newer mongo-spark connector versions which was causing the problem. Refer the documentation
2
1
77,704,979
2023-12-22
https://stackoverflow.com/questions/77704979/importerror-libsingular-singular-4-3-1-so-cannot-open-shared-object-file-no-s
I am trying to run sage in the Ubuntu 23.10 terminal and it throws this exact error: ImportError: libsingular-Singular-4.3.1.so: cannot open shared object file: No such file or directory I am not sure which package to install and (considering the new ubuntu 23 (https://askubuntu.com/questions/1465218/pip-error-on-ubunt...
This is a known bug: A quick workaround is downgrading singular-related packages. Here is a one-line-solution: curl -O https://mirror.enzu.com/ubuntu/pool/universe/s/singular/libsingular4-dev-common_4.3.1-p3+ds-1_all.deb -O https://mirror.enzu.com/ubuntu/pool/universe/s/singular/libsingular4-dev_4.3.1-p3+ds-1_amd64.deb...
3
4
77,707,877
2023-12-23
https://stackoverflow.com/questions/77707877/change-x-axis-labels
I have created a Python function (see below code) that when called, plots a grouped bar chart which is working ok. I have also attached an image of the created graph. Is there a way instead of printing 1,2,3,4,5,6,7,8,9,10 on the x-axis, 6 times for each indexed list inside data_list. And then separate each of the 10 g...
Some notes before I answer your questions: Make sure your indentation is correct; consider using numpy for your arrays (faster and easier if you know what you're doing); don't use list as a variable name as it has a specific use in Python. Also, please see answer number 3 if you want a more complete answer for number 1...
2
1
77,705,521
2023-12-22
https://stackoverflow.com/questions/77705521/why-is-pdb-showing-blank-line-or-comment-but-there-is-a-line
I'm trying to interactively run pdb on a remote system I don't own (I'm not sure if that's relevant), and it's behaving a bit differently than I expect. Listing the source shows there is clearly a line 22, but when I try to set the breakpoint, it tells me the line is blank. Fiddling a bit, I can get it to break on line...
Here it is, you've been hit by this issue - https://github.com/python/cpython/issues/103319 - that is whyit only affects a few Python versions. All it took for me to find was to open the Lib/pdb.py on cpython's source tree, look for "ll", and inspect visually the code from there - the issue itself is described as comme...
2
1
77,716,501
2023-12-26
https://stackoverflow.com/questions/77716501/odoo-remote-attach-vscode-not-hitting-breakpoints
I'm trying to debug Odoo with no success. Docker compose starts the environment for Odoo so it's already built. This is my launch file: { "version": "0.2.0", "env": { "GEVENT_SUPPORT": "True" }, "configurations": [ { "name": "Debug", "type": "python", "request": "attach", "connect": { "host": "127.0.0.1", "port": 5678 ...
I managed to make it "work". It's a bug already reported here: https://github.com/microsoft/debugpy/issues/1206 Breakpoints hit when I remove GEVENT_SUPPORT=True or set it to False, but as soon as I do that I get spammed: It seems that the gevent monkey-patching is being used. Please set an environment variable with: ...
2
1
77,691,002
2023-12-20
https://stackoverflow.com/questions/77691002/attributeerror-flask-object-has-no-attribute-before-first-request-in-flask
I'm trying to run init function when flask app run. Here's server.py: from .parser import Parser app = Flask(config().get("FLASK_APP")) parser = None @app.before_first_request def init(): parser = Parser() Here's wsgi.py: import logging from src.utils.config import config host = config().get("FLASK_HOST") port = conf...
Suddenly i found the solution. The problem as i see is in the flask's reloader, so i just disabled this feature in the app.run bootstrap function. Here's detailed info by Sean's answer https://stackoverflow.com/a/9476701/11988818 For now, my application runs once. And there's no needs in the before_first_request decor...
2
2
77,717,029
2023-12-26
https://stackoverflow.com/questions/77717029/redisearch-full-text-index-not-working-with-python-client
I am trying to follow this Redis documentation link to create a small DB of notable people searchable in real time (using Python client). I tried a similar code, but the final line, which queries by "s", should return two documents, instead, it returns a blank set. Can anybody help me find out the mistake I am making? ...
When executing a query from the redis-py client, it will transmit the FT.SEARCH command to the redis server. You can observe it by using the command MONITOR from a redis-client for example. According to the documentation, when providing a single word for the research, the matching is full. That's why the result of your...
6
2
77,712,157
2023-12-25
https://stackoverflow.com/questions/77712157/django-refresh-token-rotation-and-user-page-refresh
I'm using Django simple JWT to implement user authentication, I have done few adjustments so the access token and refresh token are sent as http-only cookies and everything works well On the frontend I have implemented Persistent Login that would keep the user logged in when they refresh the page or close the browser e...
Refreshing a page should not require a token refresh. Instead the backend should receive and use the existing access token (from the HTTP only cookie). When the access token expires, the backend should return a 401 unauthorized response to the frontend. The frontend can then perform a synchronized token refresh. This c...
2
1
77,708,266
2023-12-23
https://stackoverflow.com/questions/77708266/speed-up-for-finding-an-optimal-partition-line
This coding question derived from this question. Consider an n by n grid of integers. The task is to draw a straight line across the grid so that the part that includes the top left corner sums to the largest number possible. Here is a picture of an optimal solution with score 45: We include a square in the part that ...
TL;DR: This answer provides a much faster solution than the one of @AndrejKesely. Is also makes use of Numba, but the final code is more optimized despite being also more complex. First simple implementation The initial code is not efficient because it calls Numpy function in a loop. In such a case, Numpy functions ar...
8
6
77,704,108
2023-12-22
https://stackoverflow.com/questions/77704108/convolutional-neural-network-not-learning
I'm trying to train a Convolutional Neural Network for image recognition on a training set 1500 images with 15 categories. I've been told that, with this architecture and initial weights drawn from a Gaussian distribution with a mean of 0 and a standard deviation of 0.01 and the initial bias values to 0, with the prope...
The problem is given was given by the fact that I was importing the images, and then converting them to tensors with transforms.ToTensor(), which rescales the pixel values in the range [0,1]. While the CNN was actually meant to work with [0,255]. Having so small pixel values, a small standard deviation with the normal ...
2
0
77,696,374
2023-12-21
https://stackoverflow.com/questions/77696374/how-to-fix-importerror-dll-load-failed-while-importing-bcrypt-the-specified
I'm currently facing an issue with importing the _bcrypt module in Python, and I would greatly appreciate any help or insights you can provide. I am using Python 3.9 on a Windows 10 Pro machine. the code calls paramiko which calls bcrypt When I try to import paramiko, I encounter the following error: Traceback (most r...
I ran into the same issue for latest versions of paramiko(3.4.0) and bcrypt(4.1.2). I tried installing a lower version of bcrypt but should be >=3.2 as latest paramiko version(3.4.0) requires bcrypt>=3.2. This worked for me.
4
4
77,714,222
2023-12-25
https://stackoverflow.com/questions/77714222/http-error-when-calling-the-duckduckgo-api
I am currently following a course on machine learning : the course from the fast.ai web site. The course is a video, but it is linked to a a jupyter notebook on kaggle (https://www.kaggle.com/code/jhoward/is-it-a-bird-creating-a-model-from-your-own-data). However when i try to run cell number 11: the one that contains ...
On the right side of the webpage, under "Notebook options", find a drop down menu called "ENVIRONMENT". Change this to "Always use latest environment". Rerun ALL the cells (including the cell with the import statement) and see if the error persists.
3
5
77,716,028
2023-12-26
https://stackoverflow.com/questions/77716028/inserting-many-rows-in-psycopg3
I used to use execute_values in psycopg2 but it's gone in psycopg3. I tried following the advice in this answer or this github post, but it just doesn't seem to work for my use case. I'm trying to insert multiple values, my SQL is like so: sql = INSERT INTO activities (type_, key_, a, b, c, d, e) VALUES %s ON CONFLICT ...
The values clause should be consist of one %s placeholder for each column being inserted, separated by commas and all within parentheses, like this: INSERT INTO t (a, b, c) VALUES (%s, %s, %s) We can produce the desired string with string manipulation: # Create one placeholder per column inserted. placeholders = ', '....
3
3
77,715,680
2023-12-26
https://stackoverflow.com/questions/77715680/how-to-align-bar-labels-on-the-right-in-barh-plot
Example Code import pandas as pd import seaborn as sns sns.set_style('white') s = pd.Series({'John': 7, 'Amy': 4, 'Elizabeth': 4, 'James': 4, 'Roy': 2}) color1 = ['orange', 'grey', 'grey','grey','grey'] ax1 = s.plot(kind='barh', color=color1, figsize=(6, 3), width=.8) ax1.invert_yaxis() ax1.bar_label(ax1.containers[0],...
Edit: You can patch Text manually to change the horizontal alignment and get a better result: labels = ax1.bar_label(ax1.containers[0], labels=s.index, padding=-5, color='white', fontsize=12, fontweight='bold') for label in labels: label.set_ha('right') Output: Old answer: You can use annotate to more precisely cont...
3
4
77,715,516
2023-12-26
https://stackoverflow.com/questions/77715516/python-format-negative-time
I am writing a program that tracks running performance using Python. It calculates the runner's pace given the calculated elapsed_time and the distance. The issue I am facing is in the calculation of the difference between the runner's pace and their predicted pace. This difference can be positive or negative, as you c...
I think this arises from the way Python's time.strftime() function handles times. When you provide a negative number of seconds to time.strftime(), it doesn't format it as a negative time. Instead, it calculates a time that many seconds before the epoch, which is not what you want it seems. You need a custom solution t...
2
2
77,707,533
2023-12-23
https://stackoverflow.com/questions/77707533/busy-gpios-raspberry-pi5
I bought the new PI5, and I'm in a middle of a difficulty: This is a python/flask script - main.py - which call for a python script named shift_register.py and runs SRoutput(): from website import create_app from flask import send_from_directory, request import os, sys ctrl_hardware_path = os.path.abspath(os.path.join(...
Fix my problem: If anyone stumble upon this error this is how I fix it: import os os.environ['GPIOZERO_PIN_FACTORY'] = os.environ.get('GPIOZERO_PIN_FACTORY', 'mock') from gpiozero import OutputDevice Addendum By setting 'mock' as the default, the code is configuring gpiozero to use a pin simulation (a simulated enviro...
2
3
77,714,037
2023-12-25
https://stackoverflow.com/questions/77714037/python-sort-groupby-data-by-key-function
I would like to sort the data by the month however not alphabetically rather by the month order, i.e first the sales for January and then February etc, see the illustrated data I created month=['January','February','March','April','January','February','March','April'] sales=[10,100,130,145,13409,670,560,40] dict = {'mo...
Alternatively and probably slower, but just for posterity you can use lambda with map: month_order = {"January": 1, "February": 2, "March": 3, "April": 4} df = df.sort_values(by="month", key=lambda x: x.map(month_order), ignore_index=True)
2
1
77,712,635
2023-12-25
https://stackoverflow.com/questions/77712635/how-to-disable-border-in-subplot-for-a-3d-plot-in-matplotlib
I have the following code which produces two plots in matplotlib. However, each I'm unable to remove this border in the second subplot despite feeding all these arguments. How can I remove the black border around the second subplot (see attached image) import matplotlib.pyplot as plt import numpy as np from mpl_toolkit...
I think the issue here is that you are creating a subplot with two 2D axes and then adding a 3D axis over the right 2D one. You have removed the splines for the 3D plot, but the original 2D plot that you originally made is still there. I think a better way to do this would be to create the figure and then the subplots ...
2
1
77,710,854
2023-12-24
https://stackoverflow.com/questions/77710854/time-limit-exceed-in-the-code-that-sums-the-numbers
in the question there will be a number taken from user. Up to that number, I want to find the sum of all numbers if the sum of that number's digits is odd. For example if the input is 13 then ; 1+3+5+7+9+10+12 = 47 should be the result. In order to prevent time limit exceed, question says "Since the answer might be too...
Surely, brute force is not right way for given range. Instead think about the next: 1 3 5 7 9 10 12...18 21...29 30...98 100 102..108 111...199 201...999 1000 1002... We can see that ever decade *0..*9 contains exactly 5 numbers with odd digit sum, but these numbers can start from *0 or from *1. Aslo note that every h...
2
5
77,712,255
2023-12-25
https://stackoverflow.com/questions/77712255/how-the-parameter-vector-of-zeroes-works-in-tensorflow
I'm following book on Tensorflow by Chris Mattman. Here is the code: import tensorflow as tf tf.disable_v1_behavior() def model(X, w): terms = [] for i in range(num_coeffs): #num_coeffs = 6 term = tf.multiply(w[i], tf.pow(X, i)) terms.append(term) return tf.add_n(terms) w = tf.Variable([0.]*num_coeffs, name="parameters...
The parameter [0.]*num_coefs is the initial value of the tensorflow variable represented by w. Of course, when all coefficients are zero, the result of multiplying by those coefficients is zero. Th point of performing optimization with respect to some distance or loss metric (e.g. minimizing mean squared error) is that...
2
0
77,709,156
2023-12-23
https://stackoverflow.com/questions/77709156/check-if-float-result-is-close-to-one-of-the-expected-values
I have a function in Python makes a number of calculations and returns a float. I need to validate the float result is close (i.e. +/- 1) to one of 4 possible integers. For example the expected integers are 20, 50, 80, 100. If I have result = 19.808954 if would pass the validation test as it is with +/- 1 of 20 which i...
any(abs(actual - expected) < 1 for expected in [20, 50, 80, 100]) # ^^^^^^^^^^^^^^^^^^^^^^^^^^ This checks if the underlined boolean expression is true for any of the expected values. any will return as soon as it finds a true value and return True or False accordingly. If you want to know which expected value it matc...
3
3
77,711,479
2023-12-24
https://stackoverflow.com/questions/77711479/how-to-fix-cant-load-file-activate-ps1-because-script-execution-is-disable
I'm using VS Code and I have followed the steps in the docs to set it up for Python development: https://code.visualstudio.com/docs/python/python-tutorial. But when trying to run a program I get the error: can´t load the file C:\V\VSCode\Python.venv\Scripts\Activate.ps1 because script execution is disabled on this sys...
Run the command get-executionpolicy to verify your execution policy setting. If you get Restricted, it means No scripts can be run and you can only use Windows PowerShell in interactive mode. If you get AllSigned, it means you can run only scripts that have been digitally signed by a trusted publisher. If you get Remot...
2
4
77,711,457
2023-12-24
https://stackoverflow.com/questions/77711457/an-object-that-works-with-the-operator-for-both-strings-and-ints
Is there a way in Python to initialise a variable so that it will work with += "a string" or with += 100? For example: a = <what to put here> a += 100 # a = 100 b = <same what to put here from above> b += "a string" # b = "a string" If I use: a = "" a += "a string" # this will work fine b = "" b += 0 # -> TypeError O...
a = type('', (), {'__add__': lambda _, x: x})() a += 100 b = type('', (), {'__add__': lambda _, x: x})() b += "a string" print([a, b]) Output (Attempt This Online!): [100, 'a string']
6
1
77,711,068
2023-12-24
https://stackoverflow.com/questions/77711068/add-rows-without-duplicates-in-python
I want to add new items to the original csv file. The original file's ID increases by 1 each time an item is added, as shown below. Id Name 0 Alpha 1 Beta 2 Gamma 3 Delta I want to add the following array items = ["Epsilon", "Beta", "Zeta"] to the original csv file and eliminate duplicates, which woul...
Try: items = ["Epsilon", "Beta", "Zeta"] df = pd.concat([df, pd.DataFrame({"Name": items})]).drop_duplicates(subset="Name") df["Id"] = range(len(df)) print(df) # df.to_csv('out.csv') Prints: Id Name 0 0 Alpha 1 1 Beta 2 2 Gamma 3 3 Delta 0 4 Epsilon 2 5 Zeta
2
3
77,709,546
2023-12-24
https://stackoverflow.com/questions/77709546/pyspark-ram-leakage
My spark codes recently causes ram leakage. For instance, before running any script, when I run top, I can see 251 GB total memory and 230 GB free + used memory. When I run my spark job through spark-submit, regardless of whether the job is completed or not (ending with exception) the free + used memory is much lower t...
There is no "RAM leakage" here. You're mis-interpreting what top is displaying: total is the total amount of memory (no surprises) free is the amount of memory that is unused for any purpose used is what the kernel currently has allocated, e.g. due to requests from applications the sum of free+ used is not total, beca...
2
2
77,708,843
2023-12-23
https://stackoverflow.com/questions/77708843/reading-opencv-yaml-in-python-gives-error-input-file-is-invalid-in-function-op
I have following test.yaml: Camera.ColourOrder: "RGB" Camera.ColourDepth: "UCHAR_8" Camera.Spectrum: "Visible_NearIR" IMU.T_b_c1: !!opencv-matrix rows: 4 cols: 4 dt: f data: [0.999903, -0.0138036, -0.00208099, -0.0202141, 0.0137985, 0.999902, -0.00243498, 0.00505961, 0.0021144, 0.00240603, 0.999995, 0.0114047, 0.0, 0.0...
Judging by the error message and the implementation, OpenCV expects YAML data to be preceded by a YAML directive (%YAML). The directive is also shown in the documentation's sample. Try the following (notice first line) %YAML:1.0 Camera.ColourOrder: "RGB" Camera.ColourDepth: "UCHAR_8" Camera.Spectrum: "Visible_NearIR" I...
3
3
77,708,882
2023-12-23
https://stackoverflow.com/questions/77708882/change-first-and-last-elements-of-strings-or-lists-inside-a-dataframe
I have a dataframe like this: data = { 'name': ['101 blueberry 2023', '102 big cat 2023', '103 small white dog 2023'], 'number': [116, 118, 119]} df = pd.DataFrame(data) df output: name number 0 101 blueberry 2023 116 1 102 big cat 2023 118 2 103 small white dog 2023 119 I would like to change the first and last num...
Don't bother with the lists. You can just extract the part of the strings you want and join the other parts. df.assign(name= df['number'].astype(str) + df['name'].str.extract(r'( .* )', expand=False) + '2024' ) name number 0 116 blueberry 2024 116 1 118 big cat 2024 118 2 119 small white dog 2024 119 This regex gets...
2
4
77,707,308
2023-12-23
https://stackoverflow.com/questions/77707308/why-do-attributes-that-are-being-set-by-a-custom-type-initializer-need-to-be-pro
The CPython Tutorial defines a custom initializer for a custom type which has the following lines : if (first) { tmp = self->first; Py_INCREF(first); self->first = first; Py_XDECREF(tmp); } but the tutorial advises against this simpler but more nefarious version : if (first) { Py_XDECREF(self->first); Py_INCREF(first)...
Let's suppose we have: custom = Custom(...) # global variable class SomePyClass: def __del__(self): # access global variable custom.__init__(1, 2, 3) Let's suppose that custom.first is an instance of SomePyClass and that this instance gets destructed at the line Py_XDECREF(self->first);. The arbitrary code in the dest...
2
1