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 |
|---|---|---|---|---|---|---|
73,475,379 | 2022-8-24 | https://stackoverflow.com/questions/73475379/image-too-big-for-processing-when-converting-large-1-3-gb-dng-file-to-png-usin | I need to convert a DNG file to PNG using python. I found a post here how to convert DNG: Opencv Python open dng format The code I tried: #open dng and convert import rawpy import imageio import os os.chdir(r'C:\Path\to\dir') path = r'path\to\file' with rawpy.imread(path) as raw: rgb = raw.postprocess() rgb_img.save('i... | There seems to be a limit of 2GB for the fully expanded in memory image. I don't mean the space your DNG requires on disk, I mean the following number: ImageHeight * ImageWidth * NumberOfChannels * BytesPerSample So it would be useful if you used exiftool to tell us those parameters, by clicking edit under your questi... | 3 | 4 |
73,492,285 | 2022-8-25 | https://stackoverflow.com/questions/73492285/subclass-enum-to-add-validation | The Python docs for the enum module contains the following example of subclassing Enum. The resulting class can be used to create enums that also validate that they have no two members with the same value. >>> class DuplicateFreeEnum(Enum): ... def __init__(self, *args): ... cls = self.__class__ ... if any(self.value =... | __init_subclass__ is what you are looking for1: class PreciselyTwoEnum(Enum): def __init_subclass__(cls): if len(cls.__members__) != 2: raise TypeError("only two members allowed") and in use: >>> class Allowed(PreciselyTwoEnum): ... FOO = 1 ... BAR = 2 ... >>> class Disallowed(PreciselyTwoEnum): # Should raise an erro... | 4 | 2 |
73,471,981 | 2022-8-24 | https://stackoverflow.com/questions/73471981/should-none-be-considered-a-data-type-python | I know this sounds stupid, but I'm reading a programming book and they talk about how print() can return nothing (None). They use this code to explain it. a = 10 b = 15 c = print('a =', a, 'b=', b) print(c) I get it, c isn't any data type that print() can take and, y'know, print it. c just has an empty value because i... | None is (like literally everything else in Python besides keywords) an object. Meaning it is an instance of a class (or type if you will). None is an instance of NoneType, which you can find out, if you do this: print(type(None)) # <class 'NoneType'> So yes, None has its own data type in Python. The class is special i... | 3 | 11 |
73,491,617 | 2022-8-25 | https://stackoverflow.com/questions/73491617/convert-enum-to-literal-type-alias-in-python-typing | Is there a way to type annotate a function or variable in Python in such a way it allows both an enum or Literal formed form the attributes of the enum? from enum import Enum from typing import Literal class State(str, Enum): ENABLED = "enabled" DISABLED = "disabled" def is_enabled(state: State | Literal["enabled", "di... | I'm afraid there's no such way. The first thing that comes to mind is iterating over enum's values to build a Literal type won't work, because Literal cannot contain arbitrary expressions. So, you cannot specify it explicitly: # THIS DOES NOT WORK def is_enabled(state: State | Literal[State.ENABLED.value, State.DISABLE... | 18 | 13 |
73,472,218 | 2022-8-24 | https://stackoverflow.com/questions/73472218/change-of-a-global-variable-gets-lost-when-importing-the-enclosing-namespace | I was playing with scopes and namespaces and I found a weird behaviour which I'm not sure how to explain. Say we have a file called new_script.py with inside a = 0 def func(): import new_script #import itself new_script.a += 1 print(new_script.a) func() print(a) when executing it prints 1 1 2 0 I didn't expect the la... | Well, this has lead down a very interesting rabit hole. So thanks you for that. Here are the key points: Imports will not recurse. If it's imported once, it will execute the module level code, but it will not execute again if it's imported again. Hence you only see 4 values. Imports are singletons. If you try this cod... | 3 | 2 |
73,482,110 | 2022-8-25 | https://stackoverflow.com/questions/73482110/what-is-fastest-way-to-convert-pdf-to-jpg-image | I am trying to convert multiple pdfs (10k +) to jpg images and extract text from them. I am currently using the pdf2image python library but it is rather slow, is there any faster/fastest library than this? from pdf2image import convert_from_bytes images = convert_from_bytes(open(path,"rb").read()) Note : I am using u... | pyvips is a bit quicker than pdf2image. I made a tiny benchmark: #!/usr/bin/python3 import sys from pdf2image import convert_from_bytes images = convert_from_bytes(open(sys.argv[1], "rb").read()) for i in range(len(images)): images[i].save(f"page-{i}.jpg") With this test document I see: $ /usr/bin/time -f %M:%e ./pdf.... | 5 | 7 |
73,538,040 | 2022-8-30 | https://stackoverflow.com/questions/73538040/cannot-add-conda-environment-to-pycharm-conda-executable-path-is-empty-even-wh | I am pretty proficient in pycharm but it is the first time I stumble into this problem. I created a conda environment Finding the conda executable which for me is in /home/my_username/.miniconda3/envs/py39/bin/python Adding it to pycharm results in: I tried to search for this issue and error but the results didnt he... | click the 'add interpreter'-'Add local interpreter'; click 'Conda Environment' on the left panel, browse and select 'yourAnacondaDir\Scripts\conda.exe'; click 'load Environment'; then two options: 'use existing environment' and 'create new environment' show up; click the first option; In the 'Use existing environment'... | 8 | 12 |
73,507,177 | 2022-8-26 | https://stackoverflow.com/questions/73507177/aws-sam-dockerbuildargs-it-does-not-add-them-when-creating-the-lambda-image | I am trying to test a lambda function locally, the function is created from the public docker image from aws, however I want to install my own python library from my github, according to the documentation AWS sam Build I have to add a variable to be taken in the Dockerfile like this: Dockerfile FROM public.ecr.aws/la... | I am having this issue too. What I have learned is that in the Metadata field there is DockerBuildArgs: that you can also add. Example: Metadata: DockerBuildArgs: MY_VAR: <some variable> When I add this it does make it to the DockerBuildArgs dict. | 4 | 6 |
73,521,495 | 2022-8-28 | https://stackoverflow.com/questions/73521495/how-to-stop-vs-code-from-removing-python-unused-imports-on-save | Looking for general advice, as I'm not completely sure what is causing this behavior which I did not encounter until recently. I'm finding it quite annoying because it can delete imports if I comment out a line during development. | Adding the following to your settings.json file (you can access it on Windows with ctrl+shift+p followed by a search for settings) "editor.codeActionsOnSave": { ... [other settings] ... "source.organizeImports": false } Note: ensure that "editor.codeActionsOnSave" is not defined elsewhere (aside from language specific... | 4 | 9 |
73,528,560 | 2022-8-29 | https://stackoverflow.com/questions/73528560/django-create-a-custom-model-field-for-currencies | Here I my custom model field I created it class CurrencyAmountField(models.DecimalField): INTEGER_PLACES = 5 DECIMAL_PLACES = 5 DECIMAL_PLACES_FOR_USER = 2 MAX_DIGITS = INTEGER_PLACES + DECIMAL_PLACES MAX_VALUE = Decimal('99999.99999') MIN_VALUE = Decimal('-99999.99999') def __init__(self, verbose_name=None, name=None,... | While I have yet to manage to get the comma to display on input, I have managed to get the comma to display when viewing the saved model This is what I have tried currently # forms.py class ValuesForm(forms.ModelForm): class Meta: model = Values fields = ['value'] value = forms.DecimalField(localize=True) #settings.py ... | 4 | 1 |
73,498,513 | 2022-8-26 | https://stackoverflow.com/questions/73498513/how-to-regrid-efficiently-a-multi-spectral-image | Given a multi-spectral image with the following shape: a = np.random.random([240, 320, 30]) where the tail axis represent values at the following fractional wavelengths: array([395.13, 408.62, 421.63, 434.71, 435.64, 453.39, 456.88, 471.48, 484.23, 488.89, 497.88, 513.35, 521.38, 528.19, 539.76, 548.39, 557.78, 568.06... | It depends on the interpolation method and Physics that you deem appropriate. From what you write, I would tend to assume that the error along the spatial dimensions is negligible compared to the error in the wavelength. If that is the case, an N-Dim interpolation is likely wrong as the pixel information should be inde... | 4 | 4 |
73,548,604 | 2022-8-30 | https://stackoverflow.com/questions/73548604/create-2d-matrix-of-ascending-integers-in-diagonal-triangle-like-order-with-nump | How do I create a matrix of ascending integers that are arrayed like this example of N=6? 1 3 6 2 5 0 4 0 0 Here another example for N=13: 1 3 6 10 0 2 5 9 13 0 4 8 12 0 0 7 11 0 0 0 10 0 0 0 0 Also, the solution should perform well for large N values. My code import numpy as np N = 13 array_dimension = 5 x = 0 y = 1... | The assignment can be completed in one step by simply transforming the index of the lower triangle: def fill_diagonal(n): assert n > 0 m = int((2 * n - 1.75) ** 0.5 + 0.5) '''n >= ((1 + (m - 1)) * (m - 1)) / 2 + 1 => 2n - 2 >= m ** 2 - m => 2n - 7 / 4 >= (m - 1 / 2) ** 2 => (2n - 7 / 4) ** (1 / 2) + 1 / 2 >= m for n > ... | 6 | 4 |
73,472,916 | 2022-8-24 | https://stackoverflow.com/questions/73472916/error-cannot-import-name-wrappers-from-tensorflow-python-keras-layers | The code is giving the following error message Cannot import name 'wrappers' from 'tensorflow.python.keras.layers' - and ImportError: graphviz or pydot are not available. Even after installing the graphviz and pydot using the !apt-get -qq install -y graphviz && pip install pydot still not able to genrate model.png. i... | It's the version issue. According to the latest tensorflow doc (at least from 2.8.1). there's no tensorflow.python package. plot_model module has been moved to tensorflow.keras.utils. so simply replacing from tensorflow.python.keras.utils.vis_utils import plot_model with from tensorflow.keras.utils import plot_model ... | 3 | 9 |
73,534,869 | 2022-8-29 | https://stackoverflow.com/questions/73534869/vs-code-deactivate-venv-not-inside-workspace | I am using VS code and have a venv folder for shared projects that lives outside of workspace/project folders. I want to change my workspace to use the interpreter within my AppData\local... folder (system installation of Python). I have been reading up on this but not found a solution to do this. How would I do this p... | You can use shortcuts "ctrl+shift+P" and type "Python: Clear Workspace Interpreter Settings" AND "Python: Select Interpreter" to change the environment. By default, the Python extension looks for and uses the first Python interpreter it finds in the system path. To select a specific environment, use the Python: Select... | 4 | 12 |
73,484,988 | 2022-8-25 | https://stackoverflow.com/questions/73484988/tqdm-notebook-bar-outputs-text-in-jupyter-lab | I am having a problem when using tqdm.notebook progress bar in Jupyter (version 3.4.4). When I launch a for loop, instead of the progress bar, I get the following text as output: Input: from tqdm.notebook import tqdm for i in tqdm(range(100)): a = 1 Output: root: n: 0 total: 100 elapsed: 0.01399087905883789 ncols: nul... | I ran across this in a dockerized jupyterlab service. This fixed it for me: (Done in the Dockerfile): pip install -U jupyterlab-widgets==1.1.1 pip install -U ipywidgets==7.7.2 | 17 | 16 |
73,534,425 | 2022-8-29 | https://stackoverflow.com/questions/73534425/remove-image-background-so-that-only-the-logo-usually-some-text-remains-as-png | I would like to extract logos from golf balls for further image processing. I have already tried different methods. I wanted to use the grayscale value of the images to locate their location and then cut it out. Due to many different logos and a black border around the images, this method unfortunately failed. as my ... | This is essentially "adaptive" thresholding, except this approach doesn't need to threshold. It adapts to the illumination, leaving you with a perfectly fine grayscale image (or color, if extended to do that). median blur (large kernel size) to estimate ball/illumination division to normalize illumination: normalize... | 4 | 1 |
73,545,390 | 2022-8-30 | https://stackoverflow.com/questions/73545390/monkey-patching-class-and-instance-in-python | I am confused with following difference. Say I have this class with some use case: class C: def f(self, a, b, c=None): print(f"Real f called with {a=}, {b=} and {c=}.") my_c = C() my_c.f(1, 2, c=3) # Output: Real f called with a=1, b=2 and c=3. I can monkey patch it for purpose of testing like this: class C: def f(sel... | Functions in Python are descriptors; when they're attached to a class, but looked up on an instance of the class, the descriptor protocol gets invoked, producing a bound method on your behalf (so my_c.f, where f is defined on the class, is distinct from the actual function f you originally defined, and implicitly passe... | 4 | 4 |
73,532,164 | 2022-8-29 | https://stackoverflow.com/questions/73532164/proper-data-encryption-with-a-user-set-password-in-python3 | I have been looking for a proper data encryption library in python for a long while, today I needed it once again, cannot find anything, so is there any way to encrypt data using a user-set password, if I find something it's usually insecure, if I find a good solution it has no support for user-set passwords, meaning I... | Building on the answer from Sam Hartzog, below is an example which follows the logic described for PBES2 (Password Based Encryption Scheme 2) defined in RFC8018, Section 6.2. However, it stops short of encoding algorithm choices and parameters. #!/usr/bin/python import base64 import secrets from cryptography.fernet imp... | 5 | 5 |
73,493,910 | 2022-8-25 | https://stackoverflow.com/questions/73493910/chunking-api-response-cuts-off-required-data | I am reading chunks of data that is an API response using the following code: d = zlib.decompressobj(zlib.MAX_WBITS|16) # for gzip for i in range(0, len(data), 4096): chunk = data[i:i+4096] # print(chunk) str_chunk = d.decompress(chunk) str_chunk = str_chunk.decode() # print(str_chunk) if '"@odata.nextLink"' in str_chu... | str_chunk is a contiguous sequence of bytes from the API response that can start anywhere in the response, and end anywhere in the response. Of course it will sometimes end in the middle of some semantic content. (New information from comment that OP neglected to put in question. In fact, still not in question. OP requ... | 4 | 2 |
73,545,218 | 2022-8-30 | https://stackoverflow.com/questions/73545218/utf-8-encoding-exception-with-subprocess-run | I'm having a hard time using the subprocess.run function with a command that contains accentuated characters (like "é" for example). Consider this simple example : # -*- coding: utf-8 -*- import subprocess cmd = "echo é" result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE) print("Output of subprocess.run : ... | As a fix try cp437 decoding: print("Output of subprocess.run : {}".format(result.stdout.decode('cp437'))) # or result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, text=True, encoding="cp437") print(f"Output of subprocess.run : {result.stdout}") From other stackoverlow answers it seems that Windows termin... | 4 | 3 |
73,531,279 | 2022-8-29 | https://stackoverflow.com/questions/73531279/caching-at-queryset-level-in-django | I'm trying to get a queryset from the cache, but am unsure if this even has a point. I have the following method (simplified) inside a custom queryset: def queryset_from_cache(self, key: str=None, timeout: int=60): # Generate a key based on the query. if key is None: key = self.__generate_key # () # If the cache has t... | This is a really cool idea, but I'm not sure if you can Cache full-on Objects.. I think it's only attributes Now this having a point. Grom what I'm seeing from the limited code I've seen idk if it does have a point, unless filtering for Jane and John (and only them) is very common. Very narrow. Maybe just try caching A... | 4 | 5 |
73,539,271 | 2022-8-30 | https://stackoverflow.com/questions/73539271/combining-several-sheets-into-one-excel | I am using this code to put all Excel files and sheets into one Excel file, and it works flawlessly. But on some occasions, I want to put them all into a single excel file, but to keep the sheets separate. I know there is "Copy sheet" in Excel, but I want to do it to multiple documents. I am sure pandas has such a func... | Here is the answer. I hope someone finds this useful. Combines all sheets from all excel files XLS od XLSX to a single excel file with all sheets. import pandas as pd import openpyxl print("Copying sheets from multiple files to one file") cwd = os.path.abspath('') files = os.listdir(cwd) df_total = pd.DataFrame() df_to... | 4 | 2 |
73,539,783 | 2022-8-30 | https://stackoverflow.com/questions/73539783/check-numerically-if-numbers-in-array-start-with-given-digits | I have a numpy array of integers a and an integer x. For each element in a I want to check whether it starts with x (so the elements of a usually have more digits than x, but that's not guaranteed for every element). I was thinking of converting the integers to strings and then checking it with pandas import pandas as ... | You can get the number of digits using the log10, then divide as integer: # number of digits of x n = int(np.ceil(np.log10(x+1))) # number of digits in array n2 = np.ceil(np.log10(a+1)).astype(int) # get first n digits of numbers in array out = a//10**np.clip((n2-n), 0, np.inf) == x output: array([False, True, True, F... | 3 | 4 |
73,496,946 | 2022-8-26 | https://stackoverflow.com/questions/73496946/vscode-autocomplete-and-suggestion-intellisense-doesnt-work-for-tensorflow-an | The VSCode autocomplete option doesn't work for tensorflow and keras libraries; However i've installed python and pylance extension on it; is there any solution to make it work or not, without install new extension or something like as AI autocomplete; Kite and tabinine? For instance, here i'm trying to use layers or p... | A potentially useful fix: try adding this to the bottom of your tensorflow/__init__.py # Explicitly import lazy-loaded modules to support autocompletion. # pylint: disable=g-import-not-at-top if _typing.TYPE_CHECKING: from tensorflow_estimator.python.estimator.api._v2 import estimator as estimator from keras.api._v2 i... | 3 | 5 |
73,507,463 | 2022-8-26 | https://stackoverflow.com/questions/73507463/how-do-i-specify-a-custom-lookup-field-for-a-drf-action-on-a-viewset | I would like to specify a custom lookup field on the action (different from the viewset default "pk"), i.e. @action( methods=["GET"], detail=True, url_name="something", url_path="something", lookup_field="uuid", # this does not work unfortunately ) def get_something(self, request, uuid=None): pass But the router does ... | I think it will create much confusion for your API consumers if you have 2 different resource identification on the same resource. You can name that action query_by_uuid or just allow them to use list_view to filter by uuid if you only want to represent the object tho. (so consumers can use /test/?uuid= to retrieve dat... | 3 | 1 |
73,534,908 | 2022-8-29 | https://stackoverflow.com/questions/73534908/how-to-groupby-and-resample-data-in-pandas | I have sales data for different customers on different dates. But the dates are not continuous and I would like to resample the data to daily frequency. How can I do this? MWE import numpy as np import pandas as pd df = pd.DataFrame({'id': list('aababcbc'), 'date': pd.date_range('2022-01-01',periods=8), 'value':range(8... | df["date"] = pd.to_datetime(df["date"]) df.set_index("date").groupby("id").resample("1d").sum() | 3 | 4 |
73,532,990 | 2022-8-29 | https://stackoverflow.com/questions/73532990/get-a-count-of-vaues-that-are-on-or-before-a-certain-date-from-a-pandas-datafram | I have a date 2020-05-31 and the following dataframe, where the column names are statuses: rejected revocation decision rfe interview premium received rfe_response biometrics withdrawal appeal 196 None None 2020-01-28 None None None 2020-01-16 None None None None 203 None None 2020-06-20 2020-04-01 None None 2020-01-0... | you can mask where the date is bigger than the chosen date, then use idxmax along the columns. dt_max = '2020-05-31' res = df.where(df.le(dt_max)).astype('datetime64[ns]')\ .dropna(how='all', axis=0).idxmax(axis=1) print(res) # 196 decision # 203 rfe # 209 received # 213 biometrics # 1449 decision # 1660 received # dty... | 3 | 4 |
73,530,034 | 2022-8-29 | https://stackoverflow.com/questions/73530034/allow-python-re-findall-to-find-overlapping-mathes-from-left-to-right | My requirement is very simple, but I just could not figure out how to reach it. This is the original string ACCCTNGGATGTGGGGGGATGTCCCCCATGTGCTCG, I want to find out all the sub-strings that only consist of [ACGT], end with ATGT, and have a length of at least 8. And what I expect is: GGATGTGGGGGGATGT GGATGTGGGGGGATGTCCC... | You can use PyPi's regex module, utilizing reversed and overlapped matching using only a small addition to your initial pattern: (?r)[ACGT]{4,}ATGT For example: import regex as re seq = 'ACCCTNGGATGTGGGGGGATGTCCCCCATGTGCTCG' matches = re.findall(r'(?r)[ACGT]{4,}ATGT', seq, overlapped=True) print(matches) Prints: ['GG... | 3 | 5 |
73,485,081 | 2022-8-25 | https://stackoverflow.com/questions/73485081/save-the-multiple-images-into-pdf-without-chainging-the-format-of-subplot | I've a df like this as shown below. What I'm doing is I'm trying to loop through the df column(s) with paths & printing the image as sub plots one column with image paths at axis0 and other column paths parallely on axis1 as follows. identity VGG-Face_cosine img comment 0 ./clip_v4/3.png 1.110223e-16 .\clip_v3\0.png .... | Use PdfPages from matplotlib.backends.backend_pdf to save figures one by one on separate pages of the same pdf-file: import pandas as pd import matplotlib.pyplot as plt import matplotlib.image as mpimg from matplotlib import rcParams from matplotlib.backends.backend_pdf import PdfPages df = df.iloc[1:] rcParams['figure... | 6 | 4 |
73,530,081 | 2022-8-29 | https://stackoverflow.com/questions/73530081/convert-nested-dictionary-to-multilevel-column-dataframe | I have a dictionary which I want to convert to multilevel column dataframe and the index will be the most outer keys of the dictionary. my_dict = {'key1': {'sub-key1': {'sub-sub-key1':'a','sub-sub-key2':'b'}, 'sub-key2': {'sub-sub-key1':'aa','sub-sub-key2':'bb'}}, 'key2': {'sub-key1': {'sub-sub-key1':'c','sub-sub-key2'... | You were pretty close with concat, need to unstack after so like res = pd.concat({k: pd.DataFrame.from_dict(v, orient='columns') for k, v in my_dict.items()} ).unstack() print(res) # sub-key1 sub-key2 # sub-sub-key1 sub-sub-key2 sub-sub-key1 sub-sub-key2 # key1 a b aa bb # key2 c d cc dd | 3 | 3 |
73,514,548 | 2022-8-27 | https://stackoverflow.com/questions/73514548/no-module-named-streamlit-cli | I am using MAC and downloaded the streamlit package using conda-forge. I am getting an error message as below. from streamlit.cli import main ModuleNotFoundError: No module named 'streamlit.cli' I have checked a stackoverflow post with the same issue, and it recommends installing networkx to fix this issue, but no he... | According to the response in github. Use streamlit.web.cli instead of streamlit.cli | 6 | 7 |
73,521,602 | 2022-8-28 | https://stackoverflow.com/questions/73521602/melt-function-duplicating-dataset | I have a table like this: id name doggo floofer puppo pupper 1 rowa NaN NaN NaN NaN 2 ray NaN NaN NaN NaN 3 emma NaN NaN NaN pupper 4 sophy doggo NaN NaN NaN 5 jack NaN NaN NaN NaN 6 jimmy NaN NaN puppo NaN 7 bingo NaN NaN NaN NaN 8 billy NaN NaN NaN pupper 9 tiger NaN floofer NaN NaN 10 lucy ... | df['dog_types'] = (df['doggo'].fillna(df['floofer']) .fillna(df['puppo']) .fillna(df['pupper'])) id name doggo floofer puppo pupper dog_types 0 1 rowa NaN NaN NaN NaN NaN 1 2 ray NaN NaN NaN NaN NaN 2 3 emma NaN NaN NaN pupper pupper 3 4 sophy doggo NaN NaN NaN doggo 4 5 jack NaN NaN NaN NaN NaN 5 6 jimmy NaN NaN pup... | 4 | 4 |
73,517,832 | 2022-8-28 | https://stackoverflow.com/questions/73517832/how-to-make-an-color-picker-in-pygame | I am making an illustrator n pygame and now i need to color my shapes. I need to make an color picker like this: The idea is that the user will scroll on the bar and select an color then it will return the program an rgb value or you can say the color that will tell which color is selected. How can i make this possibl... | The pygame.Color object can be used to convert between the RGB and [HSL/HSV](HSL and HSV) color schemes. The hsla property: The HSLA representation of the Color. The HSLA components are in the ranges H = [0, 360], S = [0, 100], V = [0, 100], A = [0, 100]. Create a pygame.Surface and use the function `hsla to create a... | 3 | 4 |
73,517,571 | 2022-8-28 | https://stackoverflow.com/questions/73517571/typevar-inference-broken-by-lru-cache-decorator | python's TypeVar inference broken when using lru_cache decorator. For example, after applying mypy the following example, only function with lru_cache causes error like: main.py:14: error: Incompatible types in assignment (expression has type "T", variable has type "int") Found 1 error in 1 file (checked 1 source file)... | Here's the relevant parts of the lru_cache type hints _T = TypeVar("_T") class _lru_cache_wrapper(Generic[_T]): __wrapped__: Callable[..., _T] def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T: ... def lru_cache( maxsize: int | None = ..., typed: bool = ... ) -> Callable[[Callable[..., _T]], _lru_cache_wrap... | 4 | 6 |
73,517,189 | 2022-8-28 | https://stackoverflow.com/questions/73517189/removing-n-from-columns-name-in-pandas-dataframe | I have a CSV file having column names with line breaks when I read the file with pd.read_csv() it returns the column names like this Violent\ncrime\nrate. how do I replace \n with "_" for all these columns? | Try: df.columns = [c.replace("\n", "_") for c in df.columns] print(df) | 3 | 4 |
73,514,339 | 2022-8-27 | https://stackoverflow.com/questions/73514339/django-admin-how-to-show-currency-numbers-in-comma-separated-format | In my models I have this: class Example(Basemodel): price = models.IntegerField(default=0) and in my admin I have this: @admin.register(Example) class ExampleAdmin(admin.ModelAdmin): list_display = ('price',) I want the price field to be shown in comma-separated format instead of the typical integer format and I want... | You can work with a property instead, for example: from django.contrib import admin class Example(Basemodel): price = models.IntegerField(default=0) @property @admin.display(description='price', ordering='price') def price_formatted(self): return f'{self.price:,}' and use that property: @admin.register(Example) class E... | 5 | 6 |
73,514,027 | 2022-8-27 | https://stackoverflow.com/questions/73514027/how-to-split-and-sort-content-of-a-list-in-python | I have the following list: list1 = ['# Heading', '200: Stop Engine', '', '20: Start Engine', '400: Do xy'] and I want to get: list2 = ['20: Start Engine', '200: Stop Engine', '400: Do xy'] So the empty list item and the ones starting with # should be deleted or ignored and the rest should be sorted by the number. I t... | Just do all the things you say: Ignore all the items which don't start with a number, then sort by the number before the colon delimiter: def FilterAndSort(items): items = [item for item in items if item and item[0].isdigit()] return sorted(items, key=lambda item:int(item.split(':')[0])) print(FilterAndSort(list1)) Ou... | 4 | 2 |
73,513,150 | 2022-8-27 | https://stackoverflow.com/questions/73513150/pairing-list-items-in-a-list | I am trying to pair elements of a list based on a condition. If two element have a common i will merge them and do this until no elements can be merged. Currently, my problem is looping through same elements and getting same merged result from different items. I have to check if group has been added before.But as my ar... | Use networkx's connected_components: import networkx as nx pairs = [[1, 3], [1, 8], [2, 1], [2, 3], [3, 1], [3, 8], [4, 11], [4, 15], [7, 13], [9, 12], [9, 13], [10, 1], [10, 18], [10, 20]] out = list(nx.connected_components(nx.from_edgelist(pairs))) output: [{1, 2, 3, 8, 10, 18, 20}, {4, 11, 15}, {7, 9, 12, 13}] | 4 | 7 |
73,507,532 | 2022-8-27 | https://stackoverflow.com/questions/73507532/why-is-the-return-value-for-clirunner-invoke-object-null | I'm using click v8.1.3 and I'm trying to create some pytests, but I'm not getting my expected return_value when using click.testing.CliRunner().invoke import click.testing import mycli def test_return_ctx(): @mycli.cli.command() def foo(): return "Potato" runner = click.testing.CliRunner() result = runner.invoke(mycli.... | Click command handlers do not return a value unless you use: standalone_mode=False. You can do that during testing like: result = CliRunner().invoke(foo, standalone_mode=False) Test code: import click from click.testing import CliRunner def test_return_value(): @click.command() def foo(): return "bar" result = CliRunn... | 5 | 7 |
73,480,501 | 2022-8-24 | https://stackoverflow.com/questions/73480501/error-tcgetpgrp-failed-not-a-tty-using-python3-to-open-web-browser | Here's the breakdown of my Windows WSL environment: Windows 11 WSL version 2 Ubuntu version 20.04.3 LTS Python 3.8.10 I have a super simple Python program I'm using to open a web page in my default browser. Here is my code: import webbrowser webbrowser.open('https://github.com') When I run this from my terminal the ... | Yes, I can also reproduce it from the Python (and IPython) REPL on Ubuntu under WSL. I don't get the "lockup" that requires Ctrl+C when running interactively, at least. I'll theorize on the "why". Most of this I can confirm myself, but the last bullet below is still a bit of a mystery to me: webbrowser-open uses whate... | 9 | 11 |
73,504,314 | 2022-8-26 | https://stackoverflow.com/questions/73504314/type-hint-for-can-be-compared-objects | I am writing several functions that handle ordered datasets. Sometime, there is an argument that can be a int or float or a timestamp or anything that supports comparison (larger than / smaller than) and that I can use for trimming data for instance. Is there a way to type-hint such a parameter? The typing module doesn... | There is no standard 'comparable' ABC, no, as the rich comparison methods are really very flexible and don't necessarily return booleans. The default built-in types return NotImplemented when applied to a type they can't be compared with, for example, while specialised libraries like SQLAlchemy and numpy use rich compa... | 4 | 4 |
73,498,143 | 2022-8-26 | https://stackoverflow.com/questions/73498143/checking-for-equality-if-either-input-can-be-str-or-bytes | I am trying to write a function that checks if two strings (with ASCII-only content) or bytes are equal. Right now I have: import typing as typ def is_equal_str_bytes( a: typ.Union[str, bytes], b: typ.Union[str, bytes], ) -> bool: if isinstance(a, str): a = a.encode() if isinstance(b, str): b = b.encode() return a == b... | Some benchmarks with random equal strings/bytes of a million characters (on TIO with Python 3.8 pre-release, but I got similar times with 3.10.2): 186.88 us s.encode() 187.39 us s.encode("utf-8") 183.85 us s.encode("ascii") 94.62 us b.decode() 94.27 us b.decode("utf-8") 137.91 us b.decode("ascii") 79.93 us s == s2 82.... | 3 | 4 |
73,496,372 | 2022-8-26 | https://stackoverflow.com/questions/73496372/is-there-any-way-to-capture-exact-line-number-where-exception-happened-in-python | Hi is there any way to get the exact line number where the exception happen? because i am using a wrapper method and in actual method there are many lines of code and i am getting a very generic exception and not sure where exactly it is happening . Eg code as below, import sys def test(**kwargs): print (kwargs) abc de... | Try this: the traceback library allows you to get a longer stack trace with more line numbers (this shows the real error is on line 5). import sys, traceback def test(**kwargs): print (kwargs) abc def wrapper_test(**kwargs): try: test(**kwargs) except Exception as e: exception_type, exception_object, exception_tracebac... | 3 | 4 |
73,496,251 | 2022-8-26 | https://stackoverflow.com/questions/73496251/find-all-combinations-of-tuples-inside-of-a-list | I am trying to find all permutations of the items inside of the tuples while in the list of length 2. The order of the tuples in relation to each other does not matter. perm = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3), (1, 9), (2, 5), (4, 8), (5, 1), (3, 7), (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)] An example of one p... | You can use product: from itertools import product lst = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3), (1, 9), (2, 5), (4, 8), (5, 1), (3, 7), (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)] output = product(*([(x, y), (y, x)] for x, y in lst)) output = list(output) # if you want a list, rather than a generator print(len(output)... | 3 | 4 |
73,493,393 | 2022-8-25 | https://stackoverflow.com/questions/73493393/devcontainer-json-postcreatecommand-warns-running-pip-as-the-root-user | Question: How should I refactor my postCreateCommand so that project dependencies are not installed as root? Problem (research and solution attempt follow below): I run pip install -r requirements.txt within the postCreateCommand in my devcontainer.json. However, pip still complains about being run as root: "postCreat... | Turns out that my dockerfile, in order to provide the correct environment for setup scripts, sets the user via ARG calls instead of the USER instruction. Therefore containerUser is implicitly set as root at the time that postCreateCommand is invoked. It was sufficient to explicitly set containerUser to the user created... | 5 | 5 |
73,493,678 | 2022-8-25 | https://stackoverflow.com/questions/73493678/ipython-deprecation-warning-when-importing-display | When I run: from IPython.core.display import display, HTML display(HTML("<style>.container { width:100% !important; }</style>")) I got /var/folders/6g/6gqq4lhx4jbcl4_tbrsxj3xr0000gq/T/ipykernel_5625/333572366.py:1: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, pleas... | replace from IPython.core.display import display, HTML with from IPython.display import display, HTML source here | 4 | 12 |
73,492,654 | 2022-8-25 | https://stackoverflow.com/questions/73492654/python-regex-find-all-caps-with-no-following-lowercase | How can I retain all capital characters, given that subsequent characters are not lower case? Consider this example: import re test1 = 'ThisIsATestTHISISATestTHISISATEST' re.findall(r'[A-Z]{2}[^a-z]+', test1) # ['THISISAT', 'THISISATEST'] Expectation: This: 'THISISAT', should read: 'THISISA' | Try (regex101): import re test1 = "ThisIsATestTHISISATestTHISISATEST" print(re.findall(r"[A-Z]{2}[A-Z]*(?![a-z])", test1)) Prints: ['THISISA', 'THISISATEST'] | 3 | 4 |
73,486,279 | 2022-8-25 | https://stackoverflow.com/questions/73486279/how-to-find-element-by-attribute-and-text-in-a-singe-locator | How can I find an element using Playwright using a single locator phrase? My element is: <div class="DClass">Hello</div> I wish to find the element by its class and text: myElement = self.page.locator('text="Hello",[class="DClass"]') Why it does not work? | If you separate the selectors with a , that's an or. You can chain selectors using >>. myElement = self.page.locator('text="Hello" >> [class="DClass"]') | 5 | 8 |
73,483,284 | 2022-8-25 | https://stackoverflow.com/questions/73483284/how-to-quickly-fillna-with-a-sequence | I have a question about how to quickly fillna with a sequence in Python(pandas).I have a dataset like following(the true dataset is longer), Time Number t0 NA t1 NA t2 NA t3 0 t4 NA t5 NA t6 NA t7 NA t8 0 t9 NA My requirement is to add numbers to N lines before and after non-blank lines, a... | There are still some unknowns in your question, like what happens if the intervals overlap. Here I will consider that a further interval overwrites the previous one (you can do the other way around with a change of code, see second part). Using rolling, groupby.cumcount, and a mask: s = df['Number'].notna().shift(-N, f... | 4 | 4 |
73,484,719 | 2022-8-25 | https://stackoverflow.com/questions/73484719/how-to-convert-list-to-list-of-list-for-adjacent-numbers | i have list [31, 32,33, 1,2,3,4, 11,12,13,14] I need to put into adjacent numbers into one list for i, i+1 Expected out [[1,2,3,4], [11,12,13,14], [31, 32,33]] l = [31, 32,33, 1,2,3,4, 11,12,13,14] l.sort() #sorted the items new_l = [] for i in l: temp_l = [] # temp list before appending to main list if i + 1 in l: #... | You can append an empty sub-list to the output list when the difference between the current number and the last number in the last sub-list in the output list is not 1, and keep appending the current number to the last sub-list of the output list: l = [31, 32,33, 1,2,3,4, 11,12,13,14] l.sort() output = [] for i in l: i... | 4 | 1 |
73,483,350 | 2022-8-25 | https://stackoverflow.com/questions/73483350/why-defining-only-lt-makes-operation-possible | class Node: def __init__(self,a,b): self._a=a self._b=b def __lt__(self,other): return self._a<other._a a=Node(1,2) b=Node(0,4) print(a>b) The code above shows True. class Node: def __init__(self,a,b): self._a=a self._b=b def __lt__(self,other): return self._a<other._a def __eq__(self,other): return self._a==other._a ... | The Python docs dictates: There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are t... | 3 | 5 |
73,481,220 | 2022-8-25 | https://stackoverflow.com/questions/73481220/removing-index-from-pandas-data-frame-on-print | I'm really struggling to get this to print the way I want to. I've read through the documentation on removing index, but it seems like it still shows up. Here is my code: quotes = pd.read_csv("quotes.txt",header = None, index_col = False) quote_to_send = quotes.sample(ignore_index = True) print(quote_to_send) The text... | The 0 on top is your column name, since you don't have one... The 0 on the left is your index, something that absolutely every dataframe needs. If you really want to see things without those essential pieces, you can use print(df.to_string(header=False, index=False)) When you arise in the morning think of what a privil... | 3 | 4 |
73,479,715 | 2022-8-24 | https://stackoverflow.com/questions/73479715/convert-local-file-url-to-file-path | I have a URL that points to a local file. 'file:///home/pi/Desktop/music/Radio%20Song.mp3' I need to somehow convert this into a traditional file path, like the os module employs. '/home/pi/Desktop/music/Radio Song.mp3' Right now I'm hacking it with the replace() method. path = file.replace('file://', '').replace('%2... | The following would work: from urllib.request import url2pathname from urllib.parse import urlparse p = urlparse('file:///home/pi/Desktop/music/Radio%20Song.mp3') file_path = url2pathname(p.path) print(file_path) (thanks to user @MillerTime correctly pointing out that the solution will not remove file:// without the u... | 5 | 5 |
73,477,369 | 2022-8-24 | https://stackoverflow.com/questions/73477369/s3-bucket-sensor-for-new-file | I am working on an ETL pipeline using docker airflow. I want to trigger my pipeline whenever any new file is uploaded to S3 bucket. Is there any S3sensor in airflow that checks any new file in bucket? The S3sensor should ignore the existing files in location and should only trigger when new file is added to S3. | You have several options to achieve this goal: The best solution is creating S3 Event Notifications on file creation to send a message to SQS. In Airflow you can create a sensor to check if there are new messages to process them. You can also create a sensor which list the files in S3 bucket, and add them to a state s... | 3 | 4 |
73,477,197 | 2022-8-24 | https://stackoverflow.com/questions/73477197/how-do-you-use-either-databricks-job-task-parameters-or-notebook-variables-to-se | The goal is to be able to use 1 script to create different reports based on a filter. I want my Databricks Job Task parameters and Notebook variables to share the same value for filtering purposes. This is how I declared these widgets and stored in a variable: dbutils.widgets.text(name='field', defaultValue='', label... | There are two methods to use with widgets [.text() + .get()]. One to create the widget the first time and one to grab the value from the widget. Here is some sample screen shots from a class I teach. The .text method creates the widget and sets the value. It only has to be executed once. It can be commented out afterw... | 3 | 4 |
73,476,388 | 2022-8-24 | https://stackoverflow.com/questions/73476388/creating-user-name-from-name-in-python | I have a spreadsheet with data. There I have a name like Roger Smith. I would like to have the user name rsmith. Therefore, the first letter of the first name followed by the family name. How can I do this in Python? | def make_username(full_name: str) -> str: first_names, last_name = full_name.lower().rsplit(maxsplit=1) return first_names[0] + last_name print(make_username("Roger M. Smith")) Output: rsmith The use of rsplit is to ensure that in case someone has more than one first name, the last name is still taken properly. I assu... | 3 | 7 |
73,442,335 | 2022-8-22 | https://stackoverflow.com/questions/73442335/how-to-upload-a-large-file-%e2%89%a53gb-to-fastapi-backend | I am trying to upload a large file (≥3GB) to my FastAPI server, without loading the entire file into memory, as my server has only 2GB of free memory. Server side: @app.post("/uploadfiles") async def uploadfiles(upload_file: UploadFile = File(...): pass Client side: file_name="afd.tgz" m = MultipartEncoder(fields = {"... | With requests-toolbelt, you have to pass the filename as well, when declaring the field for upload_file, as well as set the Content-Type header—which is the main reason for the error you get, as you are sending the request without setting the Content-Type header to multipart/form-data, followed by the necessary boundar... | 16 | 48 |
73,433,322 | 2022-8-21 | https://stackoverflow.com/questions/73433322/tqdm-progress-bar-with-docker-logs | I am using tqdm to display various progress bars for my Python console application. For the production deployment of the applications, I use Docker. The progress bars work fine when running a Python application in a terminal. However, when Dockerized and the terminal output is accessed through docker logs the progress ... | The package tqdm_loggable is a drop in replacement for tqdm that works well for this use case. To install: pip install tqdm-loggable Then just replace any imports of tqdm (from tqdm import tqdm) with: from tqdm_loggable.auto import tqdm Be sure to set logging level to INFO to see the results in the logs: import logging... | 5 | 1 |
73,393,235 | 2022-8-17 | https://stackoverflow.com/questions/73393235/polars-how-to-compute-rolling-ewm-grouped-by-column | What's the right way to perform a group_by + rolling aggregate operation in polars? For some reason performing an ewm_mean over a rolling groupby gives me the list of all the ewm's rolling by time. For example take the dataframe below: portfolios = pl.from_repr(""" ┌─────────────────────┬────────┬───────────┐ │ ts ┆ sy... | You were close. Since ewm_mean produces an estimate for each observation in each window, you simply need to specify that you want the last calculated value in each rolling window. ( portfolios .rolling("ts", group_by="symbol", period="1d") .agg( pl.col("signal_0").ewm_mean(half_life=10).last().alias(f"signal_0_mean") )... | 4 | 5 |
73,433,565 | 2022-8-21 | https://stackoverflow.com/questions/73433565/how-to-run-multiple-camera-in-threading-using-python | below is the code i used to play multiple videos in parallel using multi threading pool. but only one video is playing for each input. i want each video to open separately. not combined import concurrent.futures RTSP_URL = "rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4" RTSP_List = [RTSP_URL, RTSP_UR... | you just need each thread to use a different name for the window in cv2.imshow, so that each thread will generate a different window, and you should place them somewhere distinct so that they aren't appearing one over the other, i just added in index to them so that each distinct index will have a position on screen an... | 4 | 8 |
73,427,091 | 2022-8-20 | https://stackoverflow.com/questions/73427091/polars-replace-part-of-string-in-column-with-value-of-other-column | So I have a Polars dataframe looking as such df = pl.DataFrame( { "ItemId": [15148, 15148, 24957], "SuffixFactor": [19200, 200, 24], "ItemRand": [254, -1, -44], "Stat0": ['+5 Defense', '+$i Might', '+9 Vitality'], "Amount": ['', '7', ''] } ) I want to replace $i in the column "Stat0" with Amount whenever Stat0 contain... | As of Polars 0.14.4, the replace and replace_all expressions allow an Expression for the value parameter. Thus, we can solve this more simply as: df.with_columns( pl.col('Stat0').str.replace(r'\$i', pl.col('Amount')) ) shape: (3, 5) ┌────────┬──────────────┬──────────┬─────────────┬────────┐ │ ItemId ┆ SuffixFactor ┆ ... | 9 | 13 |
73,447,258 | 2022-8-22 | https://stackoverflow.com/questions/73447258/filtering-selected-columns-based-on-column-aggregate | I wish to select only columns with fewer than 3 unique values. I can generate a boolean mask via pl.all().n_unique() < 3, but I don't know if I can use that mask via the polars API for this. Currently, I am solving it via python. Is there a more idiomatic way? import polars as pl, pandas as pd df = pl.DataFrame({"col1"... | The selected answer, though syntactically clean, is inefficient. You can do about better Let us first include at least two filters rather than just one Problem: Select only those columns where the number of unique values is between 1 and 200 The thing to consider is that you would need a pass over the data no matter wh... | 3 | 2 |
73,444,180 | 2022-8-22 | https://stackoverflow.com/questions/73444180/what-does-runtimewarning-enable-tracemalloc-to-get-the-object-allocation-trace | When I call a coroutine without awaiting, in addition to a message warning me I have not awaited the coroutine, I also get the following warning message: RuntimeWarning: Enable tracemalloc to get the object allocation traceback I know how to fix this i.e. by awaiting the coroutine (and I do see a lot of questions abou... | What is tracemalloc? How do I enable it? tracemalloc is a module that is used to debug memory allocation in Python. You can enable it by setting PYTHONTRACEMALLOC environment variable to 1. Check the Tracemalloc docs for more info. What is the object allocation traceback? It's a way how Python manages memory and al... | 3 | 7 |
73,436,440 | 2022-8-21 | https://stackoverflow.com/questions/73436440/replace-and-aggregate-rows-in-pandas-according-to-condition | I have a dataframe: lft rel rgt num 0 t3 r3 z2 3 1 t1 r3 x1 9 2 x2 r3 t2 8 3 x4 r1 t2 4 4 t1 r1 z3 1 5 x1 r1 t2 2 6 x2 r2 t4 4 7 z3 r2 t4 5 8 t4 r3 x3 4 9 z1 r2 t3 4 And a reference dictionary: replacement_dict = { 'X1' : ['x1', 'x2', 'x3', 'x4'], 'Y1' : ['y1', 'y2'], 'Z1' : ['z1', 'z2', 'z3'] } My goal is to replac... | Reverse the replacement_dict mapping and map() this new mapping to each of lft and rgt columns to substitute certain values (e.g. x1->X1, y2->Y1 etc.). As some values in lft and rgt columns don't exist in the mapping (e.g. t1, t2 etc.), call fillna() to fill in these values.1 You may also stack() the columns whose valu... | 11 | 10 |
73,464,511 | 2022-8-23 | https://stackoverflow.com/questions/73464511/rich-prompt-confirm-not-working-in-rich-progress-context-python | I am working on an app that uses a rich.Progress for rendering progress bars. The problem is rich.prompt.Confirm just flashes instead of showing the message and asking for the confirmation while in the Progress context. Demo Code from rich.progress import Progress from rich.prompt import Confirm from time import sleep ... | So from the Github Issue (That might be the one you talked about), that is now a workaround, thanks to Leonardo Cencetti. The solution is simple. He pause the progress and clear the progress lines. When you are done, he starts the progress again. For Future people here is his code: from rich.progress import Progress cl... | 5 | 2 |
73,389,603 | 2022-8-17 | https://stackoverflow.com/questions/73389603/pytorch-tensor-sort-rows-based-on-column | In a 2D tensor like so tensor([[0.8771, 0.0976, 0.8186], [0.7044, 0.4783, 0.0350], [0.4239, 0.8341, 0.3693], [0.5568, 0.9175, 0.0763], [0.0876, 0.1651, 0.2776]]) How do you sort the rows based off the values in a column? For instance if we were to sort based off the last column, I would expect the rows to be such... t... | t = torch.rand(5, 3) COL_INDEX_TO_SORT = 2 # sort() returns a tuple where first element is the sorted tensor # and the second is the indices of the sorted tensor. # The [1] at the end is used to select the second element - the sorted indices. sorted_indices = t[:, COL_INDEX_TO_SORT].sort()[1] t = t[sorted_indices] | 3 | 3 |
73,463,001 | 2022-8-23 | https://stackoverflow.com/questions/73463001/how-to-skip-parametrized-tests-with-pytest | Is it possible to conditionally skip parametrized tests?Here's an example: @pytest.mark.parametrize("a_date", a_list_of_dates) @pytest.mark.skipif(a_date > date.today()) def test_something_using_a_date(self, a_date): assert <some assertion> Of course I can do this inside the test method, but I'm looking for a structur... | If you create your own method you check the values in test collection time and run the relevant tests only a_list_of_dates = [date.today(), date(2024, 1, 1), date(2022, 1, 1)] def get_dates(): for d in a_list_of_dates: if d <= date.today(): yield d class TestSomething: @pytest.mark.parametrize("a_date", get_dates()) de... | 3 | 3 |
73,391,230 | 2022-8-17 | https://stackoverflow.com/questions/73391230/how-to-run-an-end-to-end-example-of-distributed-data-parallel-with-hugging-face | I've extensively look over the internet, hugging face's (hf's) discuss forum & repo but found no end to end example of how to properly do ddp/distributed data parallel with HF (links at the end). This is what I need to be capable of running it end to end: do we wrap the hf model in DDP? (script needs to know how to sy... | You don't need to setup anything, just do: python -m torch.distributed.launch --nproc_per_node 2 ~/src/main_debug.py or torchrun --nproc_per_node=2 --nnodes=2 --use_env ~/src/main_debug.py then monitor the gpus with nvidia-smi see: Example from alpaca: torchrun --nproc_per_node=4 --master_port=<your_random_port> tra... | 7 | 2 |
73,445,422 | 2022-8-22 | https://stackoverflow.com/questions/73445422/does-f-string-formatting-cast-a-variable-into-a-string | I was working with f-strings, and I am fairly new to python. My question is does the f-string formatting cast a variable(an integer) into a string? number = 10 print(f"{number} is not a string") Is number cast into a string? | f"..." expressions format values to strings, integrate the result into a larger string and return that result. That's not quite the same as 'casting'*. number is an expression here, one that happens to produce an integer object. The integer is then formatted to a string, by calling the __format__ method on that object,... | 3 | 8 |
73,461,385 | 2022-8-23 | https://stackoverflow.com/questions/73461385/m1-mac-tensorflow-vs-code-rosetta2 | I'm struggling to install tensorflow with a M1 mac. I've got python 3.9.7 and Monterrey 12.3 and apple silicon visual studio code. There is an apple solution involving miniconda apple dependancies and tensorflow-macos and tensorflow-metal. However this solution is not good for me as I have to use Rosetta2 emulator for ... | Running TensorFlow on miniforge + conda-forge (arm64) TensorFlow can run natively on M1 (arm64) macs. A highly recommended, easy way to install TensorFlow on arm64 macs is to via conda-forge. You should install python via miniforge or miniconda, because there is an arm64 (Apple Sillicon) distribution. With this, as of ... | 3 | 5 |
73,449,968 | 2022-8-22 | https://stackoverflow.com/questions/73449968/pydantic-model-parse-pascal-case-fields-to-snake-case | I have a Pydantic class model that represents a foreign API that looks like this: class Position(BaseModel): AccountID: str AveragePrice: str AssetType: str Last: str Bid: str Ask: str ConversionRate: str DayTradeRequirement: str InitialRequirement: str PositionID: str LongShort: str Quantity: int Symbol: str Timestamp... | Yes, it's possible, use .dict(by_alias=True), see example: from pydantic import BaseModel, Field class Position(BaseModel): account_id: str = Field(alias='AccountID') pos2 = Position(AccountID='10') print(pos2.dict()) print(pos2.dict(by_alias=True)) Output: {'account_id': '10'} {'AccountID': '10'} | 3 | 5 |
73,406,581 | 2022-8-18 | https://stackoverflow.com/questions/73406581/python-manage-py-collectstatic-error-cannot-find-rest-framework-bootstrap-min-c | I am reading the book 'Django for APIs' from 'William S. Vincent' (current edition for Django 4.0) In chapter 4, I cannot run successfully the command python manage.py collectstatic. I get the following error: Traceback (most recent call last): File "/Users/my_name/Projects/django/django_for_apis/library/manage.py", li... | Update: DRF 3.14.0 now supports Django 4.1. If you've added stubs to static as per below, be sure to remove them. This appears to be related to Django 4.1: either downgrade to Django 4.0 or simply create the following empty files in one of your static directories: static/rest_framework/css/bootstrap-theme.min.css.map s... | 14 | 25 |
73,394,472 | 2022-8-17 | https://stackoverflow.com/questions/73394472/how-do-you-obtain-underlying-failed-request-data-when-catching-requests-exceptio | I am using a somewhat standard pattern for putting retry behavior around requests requests in Python, import requests from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry retry_strategy = Retry( total=HTTP_RETRY_LIMIT, status_forcelist=HTTP_RETRY_CODES, method_whitelist=HTTP_... | We can't get a response in every exception because a request may not have been sent yet or a request or response may not have reached its destination. For example these exceptions dont' get a response. urllib3.exceptions.ConnectTimeoutError urllib3.exceptions.SSLError urllib3.exceptions.NewConnectionError There's a pa... | 5 | 2 |
73,455,881 | 2022-8-23 | https://stackoverflow.com/questions/73455881/controlling-where-sphinx-generated-rst-files-are-saved | Suppose the following documentation structure for sphinx: doc |_ _static |_ _templates |_ api |_ index.rst |_ classes.rst |_ functions.rst |_ index.rst |_ more_functions.rst |_ conf.py And that classes.rst, functions.rst and more_functions.rst have classes and functions to auto-document with autodoc/autosummary. The b... | I don't think there is such native functionality in sphinx. The fastest way to achieve this without many headaches is to create a shell script to run the build and then move (with mv or rm if you're on gnu/linux) the files according to your needs. | 5 | 1 |
73,462,684 | 2022-8-23 | https://stackoverflow.com/questions/73462684/apply-function-to-dataframe-row-use-result-for-next-row-input | I am trying to create a rudimentary scheduling system. Here is what I have so far: I have a pandas dataframe job_data that looks like this: wc job start duration 1 J1 2022-08-16 07:30:00 17 1 J2 2022-08-16 07:30:00 5 2 J3 2022-08-16 07:30:00 21 2 J4 2022-08-16 07:30:00 12 It contains a wc (work center... | I show an alternative method where you only need the first start date and then bootstrap the lists according to the job durations. # import required modules import io import pandas as pd from datetime import datetime from datetime import timedelta # make a dataframe # note: only the first start date is required x = ''... | 4 | 1 |
73,458,847 | 2022-8-23 | https://stackoverflow.com/questions/73458847/discord-py-error-message-discord-ext-commands-bot-privileged-message-content-i | Can someone help me? I keep getting this error message when I try to start up my discord bot. [2022-08-23 14:32:12] [WARNING ] discord.ext.commands.bot: Privileged message content intent is missing, commands may not work as expected. This is the code for the bot and after this is just commands and events and client.ru... | You've got to change intents = discord.Intents.default() to intents = discord.Intents.all() It was an unmentioned change in the v2.0 discord.py update. https://discordpy.readthedocs.io/en/latest/migrating.html | 5 | 13 |
73,462,652 | 2022-8-23 | https://stackoverflow.com/questions/73462652/how-to-create-a-new-sheet-within-a-spreadsheet-using-google-sheets-api | The official documentation shows how to create a spreadsheet, but I can't find how to create a sheet. How do I do it in Python? | @PCDSandwichMan's answer uses gspread, which is a very useful third-party library to simplify the Sheets API in Python. Not all of Google's APIs have libraries like this, though, so you may want to learn the regular way as well. As an alternative in case that you want to use Google's API you can check out the documenta... | 3 | 8 |
73,421,164 | 2022-8-19 | https://stackoverflow.com/questions/73421164/pass-a-variable-between-multiple-custom-permission-classes-in-drf | I have a base permission class that two ViewSets are sharing and one other permission class each that is custom to each of the ViewSets, so 3 permissions all together, is there a way to pass a specific variable down from the base permission class to the other permission classes? My setup looks like this: class BasePerm... | i don't understand why you don't use mixin. For you ask: class BasePerm(permissions.BasePermission): def has_permission(self, request, view): self.some_var = # call an API using request variable return True class Perm1(BasePerm): def has_permission(self, request, view): # get the value of some_var from BasePerm return ... | 4 | 6 |
73,464,414 | 2022-8-23 | https://stackoverflow.com/questions/73464414/why-are-generics-in-python-implemented-using-class-getitem-instead-of-geti | I was reading python documentation and peps and couldn't find an answer for this. Generics in python are implemented by subscripting class objects. list[str] is a list where all elements are strings. This behaviour is achieved by implementing a special (dunder) classmethod called __class_getitem__ which as the document... | __class_getitem__ exists because using multiple inheritance where multiple metaclasses are involved is very tricky and sets limitations that can’t always be met when using 3rd-party libraries. Without __class_getitem__ generics requires a metaclass, as defining a __getitem__ method on a class would only handle attribut... | 9 | 13 |
73,394,537 | 2022-8-17 | https://stackoverflow.com/questions/73394537/pip-freeze-throws-the-directory-name-is-invalid | Running pip freeze in the terminal throws the following error (full traceback): PS C:\Users\lhott> pip freeze ERROR: Exception: Traceback (most recent call last): File "C:\Users\lhott\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\cli\base_command.py", line 167, in exc_logging_wrapper status = ... | I actualy found the answer. @Greg7000 saying Maybe one of your dependency is badly installed actually gave me a hint. I had a dependency installed (package of a friend) that I uninstalled manually by pressing delete on the corresponding folder instead of doing pip uninstall. This is likely to have created the error "di... | 3 | 2 |
73,449,754 | 2022-8-22 | https://stackoverflow.com/questions/73449754/assigning-vs-defining-python-magic-methods | Consider the following abhorrent class: class MapInt: __call__ = int def __sub__(self, other): return map(self, other) __add__ = map One can then call map(int, lst) via MapInt() - lst, i.e. assert list(MapInt() - ['1','2','3'])) == [1,2,3] # passes However, addition is not so cooperative: assert list(MapInt() + ['1',... | The transformation of instance methods is described in the Python Data Model (emphasis mine): Note that the transformation from function object to instance method object happens each time the attribute is retrieved from the instance [...] Also notice that this transformation only happens for user-defined functions; ot... | 24 | 19 |
73,395,718 | 2022-8-17 | https://stackoverflow.com/questions/73395718/join-dataframes-and-rename-resulting-columns-with-same-names | Shortened example: vals1 = [(1, "a"), (2, "b"), ] columns1 = ["id","name"] df1 = spark.createDataFrame(data=vals1, schema=columns1) vals2 = [(1, "k"), ] columns2 = ["id","name"] df2 = spark.createDataFrame(data=vals2, schema=columns2) df1 = df1.alias('df1').join(df2.alias('df2'), 'id', 'full') df1.show() The result ha... | Another method to rename only the intersecting columns from typing import List from pyspark.sql import DataFrame def join_intersect(df_left: DataFrame, df_right: DataFrame, join_cols: List[str], how: str = 'inner'): intersected_cols = set(df1.columns).intersection(set(df2.columns)) cols_to_rename = [c for c in intersec... | 6 | 3 |
73,457,345 | 2022-8-23 | https://stackoverflow.com/questions/73457345/how-to-test-dataclass-that-can-be-initialized-with-environment-variables | I have the following dataclass: import os import dataclasses @dataclasses.dataclass class Example: host: str = os.environ.get('SERVICE_HOST', 'localhost') port: str = os.environ.get('SERVICE_PORT', 30650) How do I write a test for this? I tried the following which looks like it should work: from stackoverflow import E... | Your tests fail because your code loads the environment variables when you import the module. Module-level code is very hard to test, as the os.environ.get() calls to set the default values have already run before your test runs. You'd have to effectively delete your module from the sys.modules module cache, and only i... | 4 | 11 |
73,457,379 | 2022-8-23 | https://stackoverflow.com/questions/73457379/python-regex-and-leading-0-in-capturing-group | I'm writing a script in python 3 to automatically rename files. But I have a problem with the captured group in a regex. I have these kinds of files : test tome 01 something.cbz test tome 2 something.cbz test tome 20 something.cbz And I would like to have : test 001 something.cbz test 002 something.cbz test 020 someth... | You can run the zfill(3) on the .group(1) value after stripping the zeroes from the left side: import re s = ("test tome 01 something.cbz\n" "test tome 2 something.cbz\n" "test tome 20 something.cbz") result = re.sub( r'tome (\d+)', lambda x: x.group(1).lstrip("0").zfill(3), s ) print(result) Output test 001 something... | 9 | 7 |
73,428,753 | 2022-8-20 | https://stackoverflow.com/questions/73428753/plotly-how-to-display-y-values-when-hovering-on-two-subplots-sharing-x-axis | I have two subplots sharing x-axis, but it only shows the y-value of one subplot not both. I want the hover-display to show y values from both subplots. Here is what is showing right now: But I want it to show y values from the bottom chart as well even if I am hovering my mouse on the top chart and vice versa. Here's... | Edit: At this time, I don't think a Unified hovermode across the subplots will be provided. I got the rationale for this from here. It does affect some features, but this can be applied to work around it. In your example, the horizontal line does not appear on both graphs. So, I have added two horizontal lines in line ... | 7 | 8 |
73,437,156 | 2022-8-21 | https://stackoverflow.com/questions/73437156/jupyter-notebook-multiprocessing-code-not-working | I am new in python i have Anaconda Pyton 3.9 I was studying about Multiprocessing. When i try this code from multiprocessing import Process # gerekli kütüphaneyi çağıracağız. import time def subfunc1(): time.sleep(2) print("subfunc1: Baslatildi") time.sleep(2) print("subfunc1: Sonlandi") time.sleep(2) def subfunc2(): t... | Am I correct in assuming you are running this on ms-windows or macOS? In that case, multiprocessing will not work in an interactive interpreter like IPython. This is covered in the documentation, see the "note": Functionality within this package requires that the __main__ module be importable by the children. This is ... | 4 | 5 |
73,422,130 | 2022-8-19 | https://stackoverflow.com/questions/73422130/what-are-all-the-valid-strings-i-can-use-with-keras-model-compile | What strings are valid metrics with keras.model.compile? The following works, model.compile(optimizer='sgd', loss='mse', metrics=['acc']) but this does not work, model.compile(optimizer='sgd', loss='mse', metrics=['recall', 'precision']) | Check method to check metrices. Check docstring for details | 4 | 2 |
73,413,556 | 2022-8-19 | https://stackoverflow.com/questions/73413556/how-to-make-a-dataclass-like-decorator-friendly-for-pylance | I'm using pylance and enabled the strict mode, and hoping for better developing experience. It works well until I define some class decorator def struct(cls : Type[Any]) -> Type[Any]: # ... do some magic here ... return dataclass(frozen=True)(cls) @struct class Vec: x: int y: int print(Vec(1, "abc")) # no error msg her... | If I understand your problem correctly, PEP 681 (Data Class Transforms) may be able to help you -- provided that you would be able to use Python 3.11 (at the time of writing, only pre-release versions of Python 3.11 are available) Data class transforms were added to allow library authors to annotate functions or classe... | 5 | 5 |
73,441,477 | 2022-8-22 | https://stackoverflow.com/questions/73441477/attributeerror-module-emoji-has-no-attribute-get-emoji-regexp | This is the code I'm using in Google Colab import re from textblob import TextBlob import emoji def clean_tweet(text): text = re.sub(r'@[A-Za-z0-9]+', '', str(text)) # remove @mentions text = re.sub(r'#', '', str(text)) # remove the '#' symbol text = re.sub(r'RT[\s]+', '', str(text)) # remove RT text = re.sub(r'https?\... | AttributeError: module 'emoji' has no attribute 'get_emoji_regexp' - get_emoji_regexp method was deprecated and subsequently removed in new versions of the package. | 4 | 2 |
73,433,750 | 2022-8-21 | https://stackoverflow.com/questions/73433750/how-do-i-develop-a-negative-film-image-using-python | I have tried inverting a negative film images color with the bitwise_not() function in python but it has this blue tint. I would like to know how I could develop a negative film image that looks somewhat good. Here's the outcome of what I did. (I just cropped the negative image for a new test I was doing so don't mind ... | If you don't use exact maximum and minimum, but 1st and 99th percentile, or something nearby (0.1%?), you'll get some nicer contrast. It'll cut away outliers due to noise, compression, etc. Additionally, you should want to mess with gamma, or scale the values linearly, to achieve white balance. I'll apply a "gray world... | 4 | 10 |
73,435,918 | 2022-8-21 | https://stackoverflow.com/questions/73435918/nicely-convert-a-txt-file-to-json-file | I have a data.txt file which I want to convert to a data.json file and print a nice first 2 entries (data.txt contains 3 unique IDs). The data.txt can oublicly found here (this is a sample - original file contains 10000 unique "linkedin_internal_id). I tried the following: with open("data.txt", "r") as f: content = f.r... | It is called new line delimited json where each line is a valid JSON value and the line separator is '\n', you can read it like this line by line and push it to a list, so later it will be easy for you to iterate/process it further. See: ldjson import json with open("data.txt", "r") as f: contents = f.read() data = [js... | 4 | 6 |
73,433,013 | 2022-8-21 | https://stackoverflow.com/questions/73433013/expand-pandas-dataframe-from-row-wise-to-column-wise | I want to expand the columns of the following (toy example) pandas DataFrame, df = pd.DataFrame({'col1': ["A", "A", "A", "B", "B", "B"], 'col2': [1, 7, 3, 2, 9, 4], 'col3': [3, -1, 0, 5, -2, -3],}) col1 col2 col3 0 A 1 3 1 A 7 -1 2 A 3 0 3 B 2 5 4 B 9 -2 5 B 4 -3 such that it will become row-wise, col1 col2_1 col2_2 ... | Update: the question has been updated to expand multiple columns row-wise. This requires some refactoring of the initial answers that were tailored to the initial question, which only required the operation to take place on one column (col2). Note that the current refactored answers also work perfectly fine on a single... | 3 | 3 |
73,430,919 | 2022-8-21 | https://stackoverflow.com/questions/73430919/how-does-python-handle-list-unpacking-redefinition-and-reference | I am new to python and am trying to understand how it handles copies vs references in respect to list unpacking. I have a simple code snippet and am looking for an explanation as to why it is behaving the way it does. arr = [1, 2, 3, 4] [one, two, three, four] = arr print(id(arr[0]), arr[0]) print(id(one), one) one = 5... | The id/address is not associated with the variable/name; it's associated with the data that the variable is referring to. The 1 object is, in this instance, at address 16274840, and the 5 object is at address 16274744. one = 5 causes one to now refer to the 5 object which is at location 16274744. Just to rephrase this... | 5 | 6 |
73,395,427 | 2022-8-17 | https://stackoverflow.com/questions/73395427/python-pandas-dataframe-how-to-use-stylesheet-in-to-xml-function | I have a dataframe like this: col1 col2 col3 col4 col5 col6 col7 col8 col9 col10 ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... and i want to create an xml like this: <?xml version='1.0' encoding='utf-8'?> <root xmlns:xsi="http://www.example.com" xmlns="http://www.example.... | Your setup for the to_xml function seems to be ok. In the code below I'm generating a DataFrame with 20 rows and 10 columns to emulate your example. You will find below an example of a xslt file that might work for the sample you have given and the XML output from that. import pandas as pd import numpy as np np.random.... | 6 | 4 |
73,423,759 | 2022-8-20 | https://stackoverflow.com/questions/73423759/how-to-update-a-list-of-dictionaries-from-a-user-input | I'm new to Python and working on a task where I need to update a list of dictionaries from a customer input. I have a list as follows: drinks_info = [{'Pepsi': 2.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}] If the user inputs: Pepsi: 3.0, Sprite: 2.50 Then the list should update to: [{'Pepsi': 3.0}, {'Coke': 2.... | We can use a function to update list based on user inputs. This function would ask user for each list item separately. def update_drinks_info(drinks_info): for drink in drinks_info: for key, value in drink.items(): print(key, value) new_price = input("Enter new price for " + key + ": ") if new_price != "": drink[key]... | 3 | 5 |
73,427,383 | 2022-8-20 | https://stackoverflow.com/questions/73427383/how-to-check-the-availability-of-environment-variables-correctly | I did a token check, if at least one token is missing, 'True' will not be. Now I need to deduce which variable is missing, how to do it? PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN') TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN') TELEGRAM_CHAT_ID = os.getenv('TELEGRAM_CHAT_ID') def check_tokens(): """Checks the availabi... | I might suggest putting these values inside a class. The check tokens method can be part of the class, and you can use __dict__ to dynamically get reference to all of the tokens you defined without having to duplicate code. class Environment: def __init__(self): self.PRACTICUM_TOKEN = os.getenv('PRACTICUM_TOKEN') self.... | 4 | 8 |
73,426,545 | 2022-8-20 | https://stackoverflow.com/questions/73426545/get-index-and-column-name-for-a-particular-value-in-pandas-dataframe | I have the following Pandas DataFrame: A B 0 Exporter Invoice No. & Date 1 ABC PVT LTD. ABC/1234/2022-23 DATED 20/08/2022 2 1234/B, XYZ, 3 ABCD, DELHI, INDIA Proforma Invoice No. Date. 4 AB/CDE/FGH/2022-23/1234 20.08.2022 5 Consignee Buyer (If other than consignee) 6 ABC Co. 8 P.O BOX NO. 54321 9 Berlin, Germany Now ... | Assuming you really want the index/column of the match, you can use a mask and stack: df.where(df.eq('Consignee')).stack() output: 5 A Consignee dtype: object As list: df.where(df.eq('Consignee')).stack().index.tolist() output: [(5, 'A')] | 3 | 5 |
73,426,426 | 2022-8-20 | https://stackoverflow.com/questions/73426426/understanding-the-logic-of-pandas-sort-values-in-python | here is the pandas code that i did to understand how it works for multiple columns. I thought, it sorts columns independently but it did not work like that. df = pd.DataFrame({ 'col1' : ['A', 'Z', 'E', np.nan, 'D', 'C','B'], 'col2' : [2, 1, 9, 8, 7, 4,10], 'col3': [0, 1, 9, 4, 2, 3,1], 'col4': [11,12,12,13,14,55,56], }... | df_sort2 will sort the dataframe only on col1 value but df_sort1 will do the sorting considering all three columns, if there is a tie break i.e if two rows have same col1 value then it will check for the value of col2 in case col2 value have same value in both the row then it will look after col3 value Lets take the ex... | 4 | 4 |
73,425,359 | 2022-8-20 | https://stackoverflow.com/questions/73425359/is-it-possible-to-compile-microbit-python-code-locally | I am running Ubuntu 22.04 with xorg. I need to find a way to compile microbit python code locally to a firmware hex file. Firstly, I followed the guide here https://microbit-micropython.readthedocs.io/en/latest/devguide/flashfirmware.html. After a lot of debugging, I got to this point: https://pastebin.com/MGShD31N How... | Okay, so elaborating on Peter Till's answer. Firstly, you can use uflash: uflash path/to/your/code . Or, you can use microfs: ufs put path/to/main.py | 4 | 1 |
73,424,696 | 2022-8-20 | https://stackoverflow.com/questions/73424696/how-to-get-the-consecutive-items-from-string | I need to get the substring which is continuous more than one char This is my code: l = [] p = 'abbdccc' for i in range(len(p)-1): m = '' if p[i] == p[i+1]: m +=p[i] l.append(m) print(l) My string is 'abbdccc' b and c are repeated more than 1 times expected out is ['bb', 'ccc'] if My string is '34456788' then my out... | Solution with groupby from itertools import groupby [v for _, g in groupby(s) if (v := ''.join(g)) and len(v) > 1] Sample run for input string s: # input: 'abbdccc' # output: ['bb', 'ccc'] # input: '34456788' # output: ['44', '88'] | 5 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.