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 |
|---|---|---|---|---|---|---|
69,777,732 | 2021-10-30 | https://stackoverflow.com/questions/69777732/how-can-python-merges-a-list-of-sets-and-return-them-as-a-set | I have a list of sets like this: set_list = [{1, 2, 3}, {4, 5, 1, 6}, {2, 3, 6}, {1, 5, 8}] Now I want to merge all of the sets together and return a set of all sets like this: final_set = {1, 2, 3, 4, 5, 6, 8} I have used this code but it is not working correctly: tmp_list = [] final_set = set(tmp_list.append(elem) ... | You can use unpacking with set().union for a clean one-liner. >>> set().union(*set_list) {1, 2, 3, 4, 5, 6, 8} | 4 | 16 |
69,817,054 | 2021-11-2 | https://stackoverflow.com/questions/69817054/python-detection-of-delimiter-separator-in-a-csv-file | I have a function that reads and handles *.csv files in several dataframes. However, not all of the .csv files have the same separator. Is there a way to detect which type of separator the .csv file has, and then use it in the Pandas' read_csv() function? df = pd.read_csv(path, sep = 'xxx',header = None, index_col = 0)... | Update In fact, use engine='python' as parameter of read_csv. It will try to automatically detect the right delimiter. sepstr, default ‘,’ Delimiter to use. If sep is None, the C engine cannot automatically detect the separator, but the Python parsing engine can, meaning the latter will be used and automatically detec... | 8 | 15 |
69,778,351 | 2021-10-30 | https://stackoverflow.com/questions/69778351/how-to-fill-the-values-in-numpy-to-create-a-spectrum | I have done the following code but do not understand properly what is going on there. Can anyone explain how to fill colors in Numpy? Also I want to set in values in a way from 1 to 0 to give spectrum an intensity. E.g-: 0 means low intensity, 1 means high intensity import numpy as np import matplotlib.pyplot as plt a=... | res=256 op=np.zeros([res,res, 3]) # init the array #RGB op[:,:,0]= np.linspace(0,1,res) op[:,:,1]=np.linspace(0,1,res).reshape (256, 1) op[:,:,2]= np.linspace(1,0,res) plt.imshow(op) it will give the exact thing that you are looking for! let me know if it does not work | 6 | 7 |
69,796,358 | 2021-11-1 | https://stackoverflow.com/questions/69796358/repeating-triangle-pattern-in-python | I need to make a triangle of triangle pattern of * depending on the integer input. For example: n = 2 * *** * * * ********* n = 3 * *** ***** * * * *** *** *** *************** * * * * * *** *** *** *** *** ************************* I've already figured out the code for a single triangle, but I don't know how to dup... | Code I have simplified the following code so it should now look more clear easy to understand than it used to be. n = int(input("n = ")) rows = n ** 2 base = n * 2 - 1 for row in range(rows): triangle = row // n level = row % n a_space = " " * (n - triangle - 1) * base b_space = " " * (n - level - 1) line = (a_space + ... | 25 | 55 |
69,802,585 | 2021-11-1 | https://stackoverflow.com/questions/69802585/jupyter-notebook-in-vs-code-no-color-for-the-python-code-in-ipynb-file-what-a | Code of .ipynb file: Python is detected: The code has color in jupyter notebook: I tried setting up a jupyter notebook in vs code in an anaconda environment. I have tried - Python: Select interpreter and selected my anaconda environment. Made sure python is in the environment: python --version: Python 3.8.8. Tried c... | Jupyter extension detects your code as CVE instead of Python so Python syntax highlighting is not applied successfully. Refer to Jupyter in vscode can't execute syntax highlighting, the Dependency Analytics extension should be the reason. Remove or Disable it then reload window, the question should go away. | 5 | 11 |
69,797,728 | 2021-11-1 | https://stackoverflow.com/questions/69797728/extract-epsg-code-from-geodataframe-crs-result | Let's say I have a GeoDataFrame with a CRS set. gdf.crs gives me <Projected CRS: EPSG:25833> Name: ETRS89 / UTM zone 33N Axis Info [cartesian]: - [east]: Easting (metre) - [north]: Northing (metre) Area of Use: - undefined Coordinate Operation: - name: UTM zone 33N - method: Transverse Mercator Datum: European Terrest... | .crs returns a pyroj.CRS object. This should get you the EPSG code from the object: gdf.crs.to_epsg() pyproj docs | 6 | 13 |
69,778,356 | 2021-10-30 | https://stackoverflow.com/questions/69778356/iterable-pytorch-dataset-with-multiple-workers | So I have a text file bigger than my ram memory, I would like to create a dataset in PyTorch that reads line by line, so I don't have to load it all at once in memory. I found pytorch IterableDataset as potential solution for my problem. It only works as expected when using 1 worker, if using more than one worker it wi... | So I found an answer within the torch discuss forum https://discuss.pytorch.org/t/iterable-pytorch-dataset-with-multiple-workers/135475/3 where they pointed out I should be using the worker info to slice consecutively to the batch size. The new dataset would look like this: class CustomIterableDatasetv1(IterableDataset... | 7 | 10 |
69,794,239 | 2021-11-1 | https://stackoverflow.com/questions/69794239/how-can-i-handle-the-error-certificate-verify-failed-certificate-has-expired | I'm just starting to create an image classification program in Python with TensorFlow using the CIFAR10 dataset, following this tutorial. Here is my code so far: import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy as np datasets.cifar10.load_data() ... | Recently had a similar error using python 3.7 and just turned off the verification like this: import tensorflow as tf from tensorflow.keras import datasets, layers, models import matplotlib.pyplot as plt import numpy as np import ssl ssl._create_default_https_context = ssl._create_unverified_context datasets.cifar10.lo... | 4 | 8 |
69,735,307 | 2021-10-27 | https://stackoverflow.com/questions/69735307/how-to-display-a-heatmap-on-a-specific-parameter-with-geopandas | In my very simple case I would like to display the heatmap of the points in the points GeoJSON file but not on the geographic density (lat, long). In the points file each point has a confidence property (a value from 0 to 1), how to display the heatmap on this parameter? weight=points.confidence don't seem to work. for... | using your sample data for points these points are in Saudi Arabia, so assumed that polygons are regional boundaries in Saudi Arabia. Downloaded this from http://www.naturalearthdata.com/downloads/10m-cultural-vectors/ polygon data is a shape file loaded into geopandas to allow interface to GEOJSON __geo__interface d... | 5 | 5 |
69,792,774 | 2021-11-1 | https://stackoverflow.com/questions/69792774/how-to-draw-a-single-contour-line-in-matplotlib | Following code is borrowed from here: import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 fig, ax = plt.subpl... | Just add contour value: CS = ax.contour(X, Y, Z, [0.5]) import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt delta = 0.025 x = np.arange(-3.0, 3.0, delta) y = np.arange(-2.0, 2.0, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(-X**2 - Y**2) Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2) Z = (Z1 - Z2) * 2 f... | 5 | 6 |
69,784,120 | 2021-10-31 | https://stackoverflow.com/questions/69784120/pre-commit-x-vscode-env-python3-9-no-such-file-or-directory | I use pre-commit to run black flake8 and isort on my code. I ran pre-commit install and as expected it created .git/hooks/pre-commit which starts like: #!/usr/bin/env python3.9 # File generated by pre-commit: https://pre-commit.com # ID: 138fd403232d2ddd5efb44317e38bf03 import os import sys ... The hook works fine in ... | It seemed to be an issue with pyenv not being loaded by VSCode's source control panel when executing the git commands. I tried moving some stuff (like $(pyenv init -)) into an earlier zsh configuration file like .zshenv but that did not help. In the end, specifying the complete path fixed it #!/usr/bin/env /Users/victo... | 5 | 0 |
69,791,917 | 2021-11-1 | https://stackoverflow.com/questions/69791917/correct-way-to-initialize-an-optional-dict-with-type-hint-in-python3 | I want to initialize a dataclass dictionary with type hint(key should be string, the value should be another dataclass's instances) called usr_orders that does NOT require user init upon initializing instances. Based on my understanding Optional is the union(.., None), so I went with: @dataclass class User: usr_orders:... | You'll need to import a field and use a default_factory: from dataclasses import dataclass, field from typing import Optional, Dict @dataclass class BookOrder(): id: str @dataclass class User: usr_orders: Optional[Dict[str, BookOrder]] = field(default_factory=dict) def update_usr_orders(self, book_order:BookOrder): sel... | 4 | 3 |
69,778,194 | 2021-10-30 | https://stackoverflow.com/questions/69778194/how-can-i-check-whether-a-unicode-codepoint-is-assigned-or-not | I am using Python 3 and I know all about hex, int, chr, ord, '\uxxxx' escape and '\U00xxxxxx' escape and Unicode has 1114111 codepoints... How can I check if a Unicode codepoint is valid? That is, it is unambiguously mapped to a authoritatively defined character. For example, codepoint 720 is valid; it is 0x2d0 in hex,... | I believe the most straight-forward approach is to use unicodedata.category(). The examples from the OP are unassigned codepoints, which have a category of Cn ("Other, not assigned"). >>> import unicodedata as ud >>> ud.category('\u02d0') 'Lm' >>> ud.category('\u0378') # unassigned 'Cn' >>> ud.category(chr(127744)) 'So... | 5 | 4 |
69,789,910 | 2021-10-31 | https://stackoverflow.com/questions/69789910/find-the-value-of-a-masked-ci-cd-variable | I am currently trying to find the value of a CI/CD variable in a VM. I tried to output it but I find out the variable’s value is masked in job logs. This is the code I used in my .gitlab-ci.yml. image: python:3 stages: - deploy deploy: stage: deploy script: - echo "List all CI/CD variables" - export The line in questi... | You can reveal the values of CI/CD variables in the settings page for the project (or group, if it is a group variable) by clicking the "reveal values" button. You must have maintainer permission or higher to do this. Alternatively, you can expose secrets in the job log if you transform the value such that it won't be... | 5 | 10 |
69,788,338 | 2021-10-31 | https://stackoverflow.com/questions/69788338/what-is-the-fastest-way-to-calculate-create-powers-of-ten | If as the input you provide the (integer) power, what is the fastest way to create the corresponding power of ten? Here are four alternatives I could come up with, and the fastest way seems to be using an f-string: from functools import partial from time import time import numpy as np def fstring(power): return float(f... | You're comparing apples to oranges here. 10 ** n computes an integer (when n is non-negative), whereas float(f'1e{n}') computes a floating-point number. Those won't take the same amount of time, but they solve different problems so it doesn't matter which one is faster. But it's worse than that, because there is the ov... | 7 | 7 |
69,787,332 | 2021-10-31 | https://stackoverflow.com/questions/69787332/how-to-detect-if-init-subclass-has-been-overridden-in-a-subclass | Normally in Python, it is possible to detect whether a method has been overridden in a subclass using the following technique: >>> class Foo: ... def mymethod(self): pass ... >>> class Bar(Foo): pass ... >>> Bar.mymethod is Foo.mymethod True The expression Bar.mymethod is Foo.mymethod will evaluate to True if the meth... | __init_subclass__ is a special method, in that it is implicitly a classmethod even if you do not decorate it with @classmethod when defining it. However, the issue here does not arise from the fact that __init_subclass__ is a special method. Instead, there is a fundamental error in the technique you are using to detect... | 6 | 4 |
69,786,379 | 2021-10-31 | https://stackoverflow.com/questions/69786379/transforming-a-list-of-points-in-a-rank-of-indexes | Let's say that I have a list of points from a torunament points = [0, 12, 9] And I want to have a ranking of the players, so the expected outputs would be [1, 2, 0] Because the index 1 is first in the ranking, followed by index 2 and then index 0. My idea was to use a for to iterate through all the numbers, getting t... | Use sorted: points = [0, 12, 9] res = sorted(range(len(points)), key=lambda x: points[x], reverse=True) print(res) Output [1, 2, 0] The idea is to sort the indexes of the list (range(3)) according to their value on the list, hence the key=lambda x: points[x]. The reverse True is because you want a descending ranking. | 5 | 5 |
69,780,574 | 2021-10-30 | https://stackoverflow.com/questions/69780574/why-do-i-get-a-bad-handler-aws-lambda-not-enough-values-to-unpack-error | I'm trying to execute a Lambda function but I get the following error: { "errorMessage": "Bad handler 'AlertMetricSender': not enough values to unpack (expected 2, got 1)", "errorType": "Runtime.MalformedHandlerName", "stackTrace": [] } My Lambda handler is specified in AlertMetricSender.py: from modules.ZabbixSender ... | This is normally caused by an incorrect value specified for the "Handler" setting for the Lambda function. It is a reference to the method in your function code that processes events i.e. the entry point. The value of the handler argument is comprised of the below, separated by a dot: The name of the file in which th... | 21 | 33 |
69,773,539 | 2021-10-29 | https://stackoverflow.com/questions/69773539/how-do-i-convert-a-json-file-to-a-python-class | Consider this json file named h.json I want to convert this into a python dataclass. { "acc1":{ "email":"acc1@example.com", "password":"acc1", "name":"ACC1", "salary":1 }, "acc2":{ "email":"acc2@example.com", "password":"acc2", "name":"ACC2", "salary":2 } } I could use an alternative constructor for getting each accou... | This way you lose some dataclass features. Such as determining whether it is optional or not Such as auto-completion feature However, you are more familiar with your project and decide accordingly There must be many methods, but this is one of them: @dataclass class Account(object): email: str password: str name: str... | 9 | 7 |
69,774,045 | 2021-10-29 | https://stackoverflow.com/questions/69774045/selenium-chromedriver-issue-using-webdriver-manager-for-python | When running this code: from selenium import webdriver from selenium.webdriver.common.keys import Keys from webdrivermanager.chrome import ChromeDriverManager driver = webdriver.Chrome(ChromeDriverManager().download_and_install()) driver.get("http://www.python.org") This results in the following exception at the line ... | There are two issues in your code block as follows: You need to import ChromeDriverManager from webdriver_manager.chrome As per Webdriver Manager for Python download_and_install() isn't supported and you have to use install() So your effective code block will be: from selenium import webdriver from webdriver_manager.... | 7 | 6 |
69,758,301 | 2021-10-28 | https://stackoverflow.com/questions/69758301/efficient-algorithm-to-get-all-the-combinations-of-numbers-that-are-within-a-cer | Suppose I have two lists list_1 and list_2 list_1 = [1, 5, 10] list_2 = [3, 4, 15] I want to get a list of tuples containing elements from both list_1 and list_2 such that the difference between the numbers in a tuple is under a some constant c. E.g. suppose c is 2 then the tuples I would have would be: [(1, 3), (5, 3)... | Here is an implementation of the idea of Marat from the comments: import bisect def close_pairs(list1,list2,c): #assumes that list2 is sorted for x in list1: i = bisect.bisect_left(list2,x-c) j = bisect.bisect_right(list2,x+c) yield from ((x,y) for y in list2[i:j]) list_1 = [1, 5, 10] list_2 = [3, 4, 15] print(list(clo... | 8 | 4 |
69,748,145 | 2021-10-28 | https://stackoverflow.com/questions/69748145/continue-to-other-generators-once-a-generator-has-been-exhausted-in-a-list-of-ge | I have a list of generators in a function alternate_all(*args) that alternates between each generator in the list to print their first item, second item, ..., etc. until all generators are exhausted. My code works until a generator is exhausted and once the StopIteration occurs, it stops printing, when I want it to con... | This works. I tried to stay close to how your original code works (though I did replace your first loop with a list comprehension for simplicity). def alternate_all(*args): iter_list = [iter(arg) for arg in args] while iter_list: i = iter_list.pop(0) try: val = next(i) except StopIteration: pass else: yield val iter_li... | 5 | 4 |
69,767,707 | 2021-10-29 | https://stackoverflow.com/questions/69767707/jax-flax-very-slow-rnn-forward-pass-compared-to-pytorch | I recently implemented a two-layer GRU network in Jax and was disappointed by its performance (it was unusable). So, i tried a little speed comparison with Pytorch. Minimal working example This is my minimal working example and the output was created on Google Colab with GPU-runtime. notebook in colab import flax.linen... | The reason the JAX code compiles slowly is that during JIT compilation JAX unrolls loops. So in terms of XLA compilation, your function is actually very large: you call rnn_jax.apply() 1000 times, and compilation times tend to be roughly quadratic in the number of statements. By contrast, your pytorch function uses no ... | 5 | 1 |
69,765,183 | 2021-10-29 | https://stackoverflow.com/questions/69765183/why-does-starred-assignment-produce-lists-and-not-tuples | In python, I can write something like this: some_list = [(1, 2, 3), (3, 2, 1)] for i, *args in some_list: print(args) I will get the next output: [2, 3] [2, 1] When we use *args as function arguments, it is unpacked into a tuple. Why do we receive a list in this situation? | It is just a design decision. Making it a tuple was debated in the PEP 3132, but rejected on usability grounds: Make the starred target a tuple instead of a list. This would be consistent with a function's *args, but make further processing of the result harder. Simlarly, making it of the same type as the iterable on... | 11 | 11 |
69,763,127 | 2021-10-29 | https://stackoverflow.com/questions/69763127/django-rest-api-accept-list-instead-of-dictionary-in-post-request | I am trying to consume data from a callback API that sends the POST request in this format: [ { "key1": "asd", "key2": "123" } ] However my API currently only works when it is sent like this: { "key1": "asd", "key2": "123" } serializers.py: class RawIncomingDataSerializer(serializers.ModelSerializer): class Meta: mod... | In that case you can override create and explicitly specify many=True in the get_serializer call: class RawIncomingDataViewSet(viewsets.ModelViewSet): ... def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data, many=True) serializer.is_valid(raise_exception=True) self.perform_cre... | 6 | 6 |
69,741,177 | 2021-10-27 | https://stackoverflow.com/questions/69741177/run-multiple-async-loops-in-separate-processes-within-a-main-async-app | Ok so this is a bit convoluted but I have a async class with a lot of async code. I wish to parallelize a task inside that class and I want to spawn multiple processes to run a blocking task and also within each of this processes I want to create an asyncio loop to handle various subtasks. SO I short of managed to do t... | This is a very good question. Both the problem and the solution are quite interesting. The Problem One difference between multithreading and multiprocessing is how memory is handled. Threads share a memory space. Processes do not (in general, see below). Objects are passed to a ThreadPoolExecutor simply by reference. T... | 5 | 9 |
69,759,506 | 2021-10-28 | https://stackoverflow.com/questions/69759506/is-it-possible-to-construct-a-shebang-that-works-for-both-python-2-and-3 | I need to write a Python script that's compatible with both Python 2 and Python 3, can be called directly from a shell (meaning it has a shebang), and can run on systems that have either Python version installed, but possibly not both. Normally I can write a shebang for Python 2 like so: #!/usr/bin/env python and for ... | Realistically I would just specify python3 and make that a prerequisite. However, it's technically possible to trick a Python file into being its own shell script wrapper: #!/bin/sh ''':' for name in python3 python2 python do type "$name" > /dev/null 2>&1 && exec "$name" "$0" "$@" done echo >&2 "Please install python" ... | 8 | 10 |
69,751,853 | 2021-10-28 | https://stackoverflow.com/questions/69751853/attributeerror-api-object-has-no-attribute-followers-ids | I am trying to extract a list of followers from a particular user using Tweepy. However, I ran into an error saying that AttributeError: 'API' object has no attribute 'followers_ids'. This code, however, runs smoothly on another machine but not on mine. I tried to reinstall Tweepy but nothing changed. Please help T.T ... | Tweepy v4.0.0 renamed API.followers_ids to API.get_follower_ids. You're likely using an older version of Tweepy on the other machine. | 4 | 9 |
69,738,316 | 2021-10-27 | https://stackoverflow.com/questions/69738316/what-is-the-difference-between-poetry-run-black-myscript-py-and-black-myscrip | Based on the poetry docs: Likewise if you have command line tools such as pytest or black you can run them using poetry run pytest The suggested way to use black is: poetry run black myscript.py However, I do not notice any difference in behaviour if I just use black myscript.py What is the difference between these... | It allows you to run black (or whichever command comes after run) installed in your virtual environment without needing to activate your virtual environment first. The relevant note is in the poetry run docs (emphasis mine): The run command executes the given command inside the project’s virtualenv. Let's say you hav... | 8 | 12 |
69,747,328 | 2021-10-28 | https://stackoverflow.com/questions/69747328/pyqt6-qt-module-enums-raise-attributeerror | I need to translate the following code from PyQt5 (It works there) to PyQt6: self.setWindowFlags(Qt.FramelessWindowHint) This is the error: AttributeError: type object 'Qt' has no attribute 'FramelessWindowHint' I've already tried this: self.setWindowFlags(Qt.WindowFlags.FramelessWindowHint) It says: AttributeError:... | That flag now lives here: QtCore.Qt.WindowType.FramelessWindowHint | 7 | 12 |
69,746,102 | 2021-10-27 | https://stackoverflow.com/questions/69746102/python-socketio-keyerror-session-is-disconnected | On a small Flask webserver running on a RaspberryPi with about 10-20 clients, we periodically get this error: Error on request: Traceback (most recent call last): File "/home/pi/3D_printer_control/env/lib/python3.7/site-packages/werkzeug/serving.py", line 270, in run_wsgi execute(self.server.app) File "/home/pi/3D_prin... | As far as I can tell, this usually means the server can't keep up with supplying data to all of the clients. Some possible mitigation techniques include disconnecting inactive clients, reducing the amount of data sent where possible, sending live data in larger chunks, or upgrading the server. If you need a lot of data... | 8 | 7 |
69,733,618 | 2021-10-27 | https://stackoverflow.com/questions/69733618/sklearn-tree-plot-tree-show-returns-chunk-of-text-instead-of-visualised-tree | I'm trying to show a tree visualisation using plot_tree, but it shows a chunk of text instead: from sklearn.tree import plot_tree plot_tree(t) (where t is an instance of DecisionTreeClassifier) This is the output: [Text(464.99999999999994, 831.6, 'X[3] <= 0.8\nentropy = 1.581\nsamples = 120\nvalue = [39, 37, 44]'), Te... | In my case, it works with a simple "show": plot_tree(t) plt.show() | 7 | 7 |
69,680,566 | 2021-10-22 | https://stackoverflow.com/questions/69680566/environment-variable-error-when-running-python-pyspark-script | Is there an easy way to fix this error: Missing Python executable 'python3', defaulting to 'C:\Users\user1\Anaconda3\Lib\site-packages\pyspark\bin\..' for SPARK_HOME environment variable. Please install Python or specify the correct Python executable in PYSPARK_DRIVER_PYTHON or PYSPARK_PYTHON environment variable to de... | you need to add an environment variable called SPARK_HOME: this variable contain the path to the installed pyspark library . In my case , pyspark is installed under my home directory, so this is the content of the variable : SPARK_HOME=/home/zied/.local/lib/python3.8/site-packages/pyspark also you need another variabl... | 6 | 7 |
69,687,794 | 2021-10-23 | https://stackoverflow.com/questions/69687794/unable-to-manually-load-cifar10-dataset | First, I tried to load using: (X_train, y_train), (X_test, y_test) = datasets.cifar10.load_data() But it gave an error: Exception: URL fetch failure on https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz: None -- [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1125) So ... | I was having a similar CERTIFICATE_VERIFY_FAILED error downloading CIFAR-10. Putting this in my python file worked: import ssl ssl._create_default_https_context = ssl._create_unverified_context Reference: https://programmerah.com/python-error-certificate-verify-failed-certificate-has-expired-40374/ | 21 | 50 |
69,647,590 | 2021-10-20 | https://stackoverflow.com/questions/69647590/specifying-package-data-in-pyproject-toml | I use setuptools. In setup.cfg, I can define [options.package_data] myModule = '*.csv' to make sure that data will be installed for my users. Can I achive the same with pyproject.toml instead? | Starting in setuptools version 61.0.0 there is beta support for this feature. See the documentation https://setuptools.pypa.io/en/stable/userguide/datafiles.html The syntax is [tool.setuptools.package-data] myModule = ["*.csv"] Update 2024-01-12: This is no longer in beta. A handful of different mechanisms can enable ... | 52 | 51 |
69,728,330 | 2021-10-26 | https://stackoverflow.com/questions/69728330/type-hinting-pandas-dataframe-with-specific-columns | Suppose I have the following function: def foo(df: pd.DataFrame) -> pd.DataFrame: x = df["x"] y = df["y"] df["xy"] = x * y return df Is there a way I could hint that my function is accepting a data frame that must have the "x" and "y" column and that it will return a data frame with the "x", "y" and "xy" columns, inst... | Okay, so, I'm not sure if this is the correct way of implementing it, but seems to work for me. If you see any mistakes or alternatives let me know and I can edit the response but my solution was basically creating a new class and implementing the __class_getitem__ method as seen in the Pep 560, this was my final code:... | 10 | 6 |
69,710,333 | 2021-10-25 | https://stackoverflow.com/questions/69710333/is-there-a-way-to-match-inequalities-in-python-%e2%89%a5-3-10 | The new structural pattern matching feature in Python 3.10 is a very welcome feature. Is there a way to match inequalities using this statement? Prototype example: match a: case < 42: print('Less') case == 42: print('The answer') case > 42: print('Greater') | You can use guards: match a: case _ if a < 42: print('Less') case _ if a == 42: print('The answer') case _ if a > 42: print('Greater') Another option, without guards, using pure pattern matching: match [a < 42, a == 42]: case [True, False]: print('Less') case [_, True]: print('The answer') case [False, False]: print('... | 52 | 71 |
69,686,925 | 2021-10-23 | https://stackoverflow.com/questions/69686925/i-had-a-problem-with-python-library-pikepdf | When trying to install the python moduel pikepdf using pip, this error pops up: Building wheels for collected packages: pikepdf Building wheel for pikepdf (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for pikepdf (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [54 lines o... | Solution for Macbook, M1 brew install qpdf After it use pip install pikepdf Solution from https://github.com/pikepdf/pikepdf/issues/274 | 16 | 22 |
69,711,606 | 2021-10-25 | https://stackoverflow.com/questions/69711606/how-to-install-a-package-using-pip-in-editable-mode-with-pyproject-toml | When a project is specified only via pyproject.toml (i.e. no setup.{py,cfg} files), how can it be installed in editable mode via pip (i.e. python -m pip install -e .)? I tried both setuptools and poetry for the build system, but neither worked: [build-system] requires = ["setuptools", "wheel"] build-backend = "setuptoo... | PEP 660 – Editable installs for pyproject.toml based builds defines how to build projects that only use pyproject.toml. Build tools must implement PEP 660 for editable installs to work. You need a front-end (such as pip ≥ 21.3) and a backend. The statuses of some popular backends are: Setuptools implements PEP 660 as ... | 113 | 101 |
69,642,889 | 2021-10-20 | https://stackoverflow.com/questions/69642889/how-to-use-multiple-cases-in-match-switch-in-other-languages-cases-in-python-3 | I am trying to use multiple cases in a function similar to the one shown below so that I can be able to execute multiple cases using match cases in python 3.10 def sayHi(name): match name: case ['Egide', 'Eric']: return f"Hi Mr {name}" case 'Egidia': return f"Hi Ms {name}" print(sayHi('Egide')) This is just returning ... | According to What’s New In Python 3.10, PEP 636, and the docs, you use a | between patterns: case 'Egide' | 'Eric': | 108 | 206 |
69,711,886 | 2021-10-25 | https://stackoverflow.com/questions/69711886/python-dataclasses-inheritance-and-default-values | Given the following hierarchy of python dataclasses: @dataclass class A: a: str aa: str @dataclass class B(A): b: str @dataclass class C(A): c: str @dataclass class D(B, C): d: str Is there any general method that allows you to insert an attribute with a default value in this inheritance hierarchy? For instance, the f... | This is a well-known issue for data classes, there are several workarounds but this is solved very elegantly in Python 3.10, here is the PR that solved the issue 43532. It would work the following way: from dataclasses import dataclass @dataclass(kw_only=True) class Base: type: str counter: int = 0 @dataclass(kw_only=T... | 20 | 22 |
69,670,597 | 2021-10-22 | https://stackoverflow.com/questions/69670597/how-do-i-mock-a-file-open-for-a-specific-path-in-python | So I know that in my unit test I can mock a context manager open(), i.e.: with open('file_path', 'r') as stats: mocked with with mock.patch('builtins.open', mock.mock_open(read_data=mock_json)): but is there a way for me to only mock it for a specific file path? Or maybe some other way to ensure that the context mana... | To mock open only for a specific path, you have to provide your own mock object that handles open differently, depending on the path. Assuming we have some function: def do_open(path): with open(path, "r") as f: return f.read() where open shall be mocked to return a file with the content "bar" if path is "foo", but ot... | 5 | 11 |
69,702,485 | 2021-10-25 | https://stackoverflow.com/questions/69702485/numba-and-numpy-concatenate | I am trying to speed up some code using numba, but it is tough sledding. For example, the following function does not numba-fy, @jit(nopython=True) def returns(Ft, x, delta): T = len(x) rets = Ft[0:T - 1] * x[1:T] - delta * np.abs(Ft[1:T] - Ft[0:T - 1]) return np.concatenate([[0], rets]) because numba cannot find the ... | A bit late, but I hope still useful. Since you asked for the "canonical fix", I would like to explain why concatenate is a bad idea when working with arrays and especially if you indicate that you want to remove bottlenecks and therefore use the numba jit. An array is a continuous sequence of bytes in memory (numpy kno... | 7 | 5 |
69,664,189 | 2021-10-21 | https://stackoverflow.com/questions/69664189/pandas-rename-columns-with-method-chaining | I have a dataframe and did some feature engineering and now would like to change the column names. I know how to change them if I do a new assignment but I would like to do it with method chaining. I tried the below (the rename row) but it doesn't work. How could I write it so it works? df = pd.DataFrame({'ID':[1,2,2,3... | Renaming columns in a chain Use set_axis along axis=1: df.set_axis(['foo', 'bar', 'baz'], axis=1) Using groupby, pivot, melt, etc If the new columns depend on some earlier step in the chain, combine set_axis with pipe. For example, to capitalize pivoted columns in a chain: We cannot directly chain set_axis: # does N... | 9 | 16 |
69,697,724 | 2021-10-24 | https://stackoverflow.com/questions/69697724/auto-save-adds-two-empty-lines-between-comment-and-function-header-in-python-in | I write code in Python in VS code. If I add comment before function and hit save button, VS code adds two empty lines: # comment def MyMethod(): return 0 In settings I see that I use autopep8 formatter: I wasnt able to find what causes this annoying issue. Maybe I can configure settings somewhere? | Comment documenting function behavior should be placed inside function, just below signature. If it is not describing function (is placed outside function) it should have those blank lines. Don't mess with language's conventions, it's very bad idea. Edit, Further clarification: """Module-level comment """ def function(... | 5 | 3 |
69,687,604 | 2021-10-23 | https://stackoverflow.com/questions/69687604/running-into-an-error-when-trying-to-pip-install-python-docx | I just did a fresh install of windows to clean up my computer, moved everything over to my D drive and installed Python through Windows Store (somehow it defaulted to my C drive, so I left it there because Pycharm was getting confused about its location), now I'm trying to pip install the python-docx module for the fir... | One of the dependencies for python-docx is lxml. The latest stable version of lxml is 4.6.3, released on March 21, 2021. On PyPI there is no lxml wheel for 3.10, yet. So it try to compile from source and for that Microsoft Visual C++ 14.0 or greater is required, as stated in the error. However you can manually install ... | 5 | 6 |
69,673,807 | 2021-10-22 | https://stackoverflow.com/questions/69673807/python-coding-standard-for-safety-critical-applications | Coming from C/C++ background, I am aware of coding standards that apply for Safety Critical applications (like the classic trio Medical-Automotive-Aerospace) in the context of embedded systems , such as MISRA, SEI CERT, Barr etc. Skipping the question if it should or if it is applicable as a language, I want to create ... | Top layer safety standards for "functional safety" like IEC 61508 (industrial), ISO 26262 (automotive) or DO-178 (aerospace) etc come with a software part (for example IEC 61508-3), where they list a number of suitable programming languages. These are exclusively old languages proven in use for a long time, where all f... | 6 | 5 |
69,670,125 | 2021-10-22 | https://stackoverflow.com/questions/69670125/how-to-log-raw-http-request-response-in-python-fastapi | We are writing a web service using FastAPI that is going to be hosted in Kubernetes. For auditing purposes, we need to save the raw JSON body of the request/response for specific routes. The body size of both request and response JSON is about 1MB, and preferably, this should not impact the response time. How can we do... | You may try to customize APIRouter like in FastAPI official documentation: import time from typing import Callable from fastapi import APIRouter, FastAPI, Request, Response from fastapi.routing import APIRoute class TimedRoute(APIRoute): def get_route_handler(self) -> Callable: original_route_handler = super().get_rout... | 33 | 3 |
69,641,363 | 2021-10-20 | https://stackoverflow.com/questions/69641363/how-to-run-fastapi-app-on-multiple-ports | I have a FastAPI application that I am running on port 30000 using Uvicorn programmatically. Now I want to run the same application on port 8443 too. The same application needs to run on both these ports. How can I do this within the Python code? Minimum Reproducible code: from fastapi import FastAPI import uvicorn app... | The following solution worked for me. It runs one gunicorn process in the background and then another process to bind it to two ports. One of them will use HTTP and one can use HTTPS. Dockerfile: FROM python:3.7 WORKDIR /app COPY requirements.txt . RUN pip3 install -r requirements.txt COPY . . ENTRYPOINT ./docker-start... | 15 | 3 |
69,720,476 | 2021-10-26 | https://stackoverflow.com/questions/69720476/how-to-use-pytest-to-simulate-full-reboot | How do I test that my program is robust to unexpected shut-downs? My python code will run on a microcontroller that shuts off unexpectedly. I would like to test each part of the code rebooting unexpectedly and verify that it handles this correctly. Attempt: I tried putting code into its own process, then terminating it... | Your logic starts a process wrapped within the MyClass object which itself spawns a new process via the os.system call. When you terminate the MyClass process, you kill the parent process but you leave the 7zip process running as orphan. Moreover, the process.terminate method sends a SIGTERM signal to the child process... | 6 | 2 |
69,660,200 | 2021-10-21 | https://stackoverflow.com/questions/69660200/how-to-render-svg-image-to-png-file-in-python | So I want to render SVG from python code having target resolution WxH (having SVG text as str, like this that I generate dynamically): <svg width="200" height="200" viewBox="0 0 220 220" xmlns="http://www.w3.org/2000/svg"> <filter id="displacementFilter"> <feTurbulence type="turbulence" baseFrequency="0.05" numOctaves=... | there are multiple solutions available for converting svgs to pngs in python, but not all of them will work for your particular use case since you're working with svg filters. solution filter works? alpha channel? call directly from python? cairosvg some* yes yes svglib no no yes inkscape yes yes via subpro... | 16 | 34 |
69,725,429 | 2021-10-26 | https://stackoverflow.com/questions/69725429/filter-enum-in-list-of-enums-sqlalchemy | I have the following enum in python: class Status(enum.Enum): produced = 1 consumed = 2 success = 3 failed = 4 and the following SQLAlchemy model class Message(Base): __tablename__ = 'table' id = Column(Integer, primary_key=True) name = Column(String) status = Column(Enum(Status)) I want to filter on several statuses... | You should use in_ operator: session.query(Message).filter(Message.status.in_((Status.failed, Status.success))) | 8 | 8 |
69,686,581 | 2021-10-23 | https://stackoverflow.com/questions/69686581/the-term-pipx-is-not-recognized-as-the-name-of-a-cmdlet | I have followed the instructions to install Brownie on Visual studio code of their website. python3 -m pip install --user pipx python3 -m pipx ensurepath The 2 lines above poses no problem. I restarted the terminal to input line: pipx install eth-brownie pipx : The term 'pipx' is not recognized as the name of a cmdle... | Check your environment variables. python3 -m pipx ensurepath adds the directories to PATH, but they are added in all lowercase for some reason. Fix the directory paths to match the case. | 7 | 9 |
69,724,598 | 2021-10-26 | https://stackoverflow.com/questions/69724598/python-sqlmodel-truncate-table-or-delete-all-and-get-number-of-rows | Using Python SQLModel, I want to truncate a table, or remove all rows, and get the number of deleted rows, in the most SQLModel standar way. How can I do this? I am using this: with Session(engine) as session: count = session.exec(delete(MyModel)).fetchall() session.commit() But it raises an error: ResourceClosedErro... | with Session(engine) as session: statement = delete(MyModel) result = session.exec(statement) session.commit() print(result.rowcount) Matched Row Counts | 5 | 8 |
69,646,771 | 2021-10-20 | https://stackoverflow.com/questions/69646771/sql-alchemy-insert-statement-failing-to-insert-but-no-error | I am attempting to execute a raw sql insert statement in Sqlalchemy, SQL Alchemy throws no errors when the constructed insert statement is executed but the lines do not appear in the database. As far as I can tell, it isn't a syntax error (see no 2), it isn't an engine error as the ORM can execute an equivalent write p... | Just so this question is answered in case anyone else ends up here: The issue was a failure to call commit as a method, as @snakecharmerb pointed out. Gord Thompson also provided an alternate method using 'begin' which automatically commits rather than connection which is a 'commit as you go' style transaction. | 8 | 9 |
69,723,468 | 2021-10-26 | https://stackoverflow.com/questions/69723468/is-the-key-order-the-same-for-ordereddict-and-dict | dict keeps insertion order since Python 3.6 (see this). OrderedDict was developed just for this purpose (before Python 3.6). Since Python 3.6, is the key order always the same for dict or OrderedDict? I wonder whether I can do this in my code and have always the same behavior (except of equality, and some extended meth... | Both OrderedDict and dict are insertion-ordered¹ for iteration. There is practically no reason to use OrderedDict if iteration order is the only deciding point, especially if re-ordering is not needed. Obviously, if comparison order is desired OrderedDict and dict are not interchangeable. Or phrased differently, for P... | 13 | 9 |
69,710,875 | 2021-10-25 | https://stackoverflow.com/questions/69710875/how-can-i-have-a-synchronous-facade-over-asyncpg-apis-with-python-asyncio | Imagine an asynchronous aiohttp web application that is supported by a Postgresql database connected via asyncpg and does no other I/O. How can I have a middle-layer hosting the application logic, that is not async? (I know I can simply make everything async -- but imagine my app to have massive application logic, only... | You need to create a secondary thread where you run your async code. You initialize the secondary thread with its own event loop, which runs forever. Execute each async function by calling run_coroutine_threadsafe(), and calling result() on the returned object. That's an instance of concurrent.futures.Future, and its r... | 10 | 9 |
69,727,314 | 2021-10-26 | https://stackoverflow.com/questions/69727314/numpy-construct-squares-along-diagonal-of-matrix-expand-diagonal-matrix | Suppose you have either two arrays: index = [1, 2, 3] counts = [2, 3, 2] or a singular array arr = [1, 1, 2, 2, 2, 3, 3] How can I efficiently construct the matrix [ [1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 0, 0... | Try broadcasting: idx = np.repeat(np.arange(len(counts)), counts) np.where(idx==idx[:,None], arr, 0) # or # arr * (idx==idx[:,None]) Output; array([[1, 1, 0, 0, 0, 0, 0], [1, 1, 0, 0, 0, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 2, 2, 2, 0, 0], [0, 0, 0, 0, 0, 3, 3], [0, 0, 0, 0, 0, 3, 3]]) | 17 | 3 |
69,704,561 | 2021-10-25 | https://stackoverflow.com/questions/69704561/cannot-update-spyder-5-1-5-on-new-anaconda-install | I installed anaconda and spyder came with the installation. Spyder 4.2.5 came with the installation and I got a pop up notification that spyder=5.1.5 is available. I tried conda update anaconda conda install spyder=5.1.5 and gets an error: Solving environment: failed with initial frozen solve. Retrying with flexibl... | (Spyder maintainer here) Our regular instructions to update Spyder don't work in this case because there are some incompatible dependencies between Spyder 5.0.5 and 5.1.5. To workaround this problem, you need to close Spyder and run the following commands in the Anaconda Prompt (or your system terminal on Linux or macO... | 24 | 37 |
69,717,154 | 2021-10-26 | https://stackoverflow.com/questions/69717154/typeerror-cannot-concatenate-object-of-type-class-list-only-series-and-d | I have a list of 10 dataframes named d0, d1, d2,...d9. All have 3 columns and 100 rows. d0.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 100 entries, 0 to 99 Data columns (total 3 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 0 100 non-null float64 1 1 100 non-null float64 2 2 100... | s1 is already a list. Doing what you did called pd.concat with a list of a list with DataFrames, which pandas doesn't allow. You should do it like this instead: s2=pd.concat(s1) | 6 | 10 |
69,716,911 | 2021-10-26 | https://stackoverflow.com/questions/69716911/convert-subset-of-columns-to-rows-by-combining-columns | Pandas 1.1.4 MRE: df = pd.DataFrame({"Code":[1,2], "view_A":[3000, 2300], "click_A":[3, 23], "view_B":[1200, 300], "click_B":[5, 3]}) df.set_index("Code", inplace=True) >>> view_A click_A view_B click_B Code 1 3000 3 1200 5 2 2300 23 300 3 Want to make it into view click Code type 1 A 3000 3 2 A 2300 23 1 B 1200 5 2 ... | This is essentially a reshape operation using stack df.columns = df.columns.str.split('_', expand=True) df.stack().rename_axis(['code', 'type']) click view code type 1 A 3 3000 B 5 1200 2 A 23 2300 B 3 300 | 17 | 12 |
69,699,744 | 2021-10-24 | https://stackoverflow.com/questions/69699744/plotly-express-line-with-continuous-color-scale | I have the following piece of code import plotly.express as px import pandas as pd import numpy as np x = [1,2,3,4,5,6] df = pd.DataFrame( { 'x': x*3, 'y': list(np.array(x)) + list(np.array(x)**2) + list(np.array(x)**.5), 'color': list(np.array(x)*0) + list(np.array(x)*0+1) + list(np.array(x)*0+2), } ) for plotting_fun... | I am not sure this is possible using only plotly.express. If you use px.line, then you can pass the argument markers=True as described in this answer, but from the px.line documentation it doesn't look like continuous color scales are supported. UPDATED ANSWER: in order to have both a legend that groups both the lines ... | 7 | 4 |
69,709,227 | 2021-10-25 | https://stackoverflow.com/questions/69709227/how-to-reference-the-output-of-a-rule-in-snakemake | I was wondering if it is possible to use the output of a rule directly as the input of the next rule, without having to specify the path again. I thought maybe something like this would work, but it does not in my tests: rule A: input: in_file = "path/to/in_file" output: out_file = "path/to/out_file" shell: "...." rule... | Maybe this is the syntax you are looking for: rule B: input: in_file = rules.A.output.out_file, ... Although I prefer to hardcode the filenames since it makes the script more readable. | 5 | 6 |
69,710,194 | 2021-10-25 | https://stackoverflow.com/questions/69710194/get-all-objects-with-today-date-django | I have a model like this class Maca(models.Model): created_at = models.DateTimeField( auto_now_add=True ) Now I want in the views.py file to get all the entries that have created today, I'm trying this Maca.objects.filter(created_at=datetime.today().date()) But this looks for the clock that object is created too. P.S... | You have to just write a valid filter like this : from datetime import datetime today = datetime.today() year = today.year month = today.month day = today.day meca = Meca.objects.filter(created_at__year=year, created_at__month=month, created_at__day=day) | 5 | 8 |
69,708,821 | 2021-10-25 | https://stackoverflow.com/questions/69708821/can-i-have-multiple-subfolders-with-virtual-python-environments-in-vs-code | I have a monorepo structured like this: myRepo/ ├─ project_1/ │ ├─ .venv/ │ ├─ main.py ├─ project_2/ │ ├─ .venv/ │ ├─ main.py ├─ .gitignore ├─ README.md Can VS Code handle multiple python venvs in subfolders? After some googling I managed a find one solution, but its not very elegant. I created a workspace and added... | VS Code has a list of places, where it looks for virtual environments. Only environments located directly under the workspace are picked up automatically. You can also enter custom paths when running the Python: Select Interpreter command, though. Simply select "Enter interpreter path..." and navigate to your venv's /b... | 16 | 4 |
69,699,729 | 2021-10-24 | https://stackoverflow.com/questions/69699729/pydantic-is-confused-with-my-types-and-their-union | I have following Pydantic model type scheme specification: class RequestPayloadPositionsParams(BaseModel): """ Request payload positions parameters """ account: str = Field(default="COMBINED ACCOUNT") fields: List[str] = Field(default=["QUANTITY", "OPEN_PRICE", "OPEN_COST"]) class RequestPayloadPositions(BaseModel): ""... | This is one of the features of Pydantic matching Union, which is described as: However, as can be seen above, pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches.[...] As such, it is recommended that, when defining Union annotations, the most specific type is i... | 8 | 14 |
69,678,621 | 2021-10-22 | https://stackoverflow.com/questions/69678621/input-with-multiple-removable-values-in-dash | Is there a dash component like this: Basically a text input, but with a list of removable items, added by hitting enter. I know a dropdown can be made to work like this, but I don't have a specified list of options beforehand. | If you're open to dash components that are not standard, I would go for Tag input from Tauffer consulting. And if you would like to use approaches that ship with Dash, you can put together a few components to mimic a very similar functionality. Both approaches are described below. 1 - Tag input from Tauffer consulting ... | 6 | 3 |
69,692,703 | 2021-10-23 | https://stackoverflow.com/questions/69692703/compiling-python-3-10-at-amazon-linux-2 | I'm trying to compile and install Python 3.10 into a Amazon Linux 2 but I'm not being able to get it with https support. Here the commands that I'm using to compile it: sudo yum -y update sudo yum -y groupinstall "Development Tools" sudo yum -y install openssl-devel bzip2-devel libffi-devel wget https://www.python.org/... | From Python3.10, OpenSSL 1.1.1 or newer is required. (Ref: PEP 644, Python3.10 release) I have tried changing some of your code like below and worked. delete: openssl-devel add: openssl11 openssl11-devel. | 6 | 16 |
69,691,395 | 2021-10-23 | https://stackoverflow.com/questions/69691395/invalid-python-sdk-error-right-after-creating-a-new-project-in-pycharm | Background Some time ago I seriously crashed my Windows computer while using PyCharm - I remember some errors about memory and then a hard crash with no blue screen - just black with some thin vertical lines and reboot to Windows installation / fixing screen. Since then, I had this problem, with no way I found online t... | OK, that was a lucky one! I'm thus posting my comment as an answer: The problem is caused by the non-ASCII characters in the path, and the solution is to remove them. As indicated by @TheLazyScripter this is a known issue. | 6 | 4 |
69,682,403 | 2021-10-22 | https://stackoverflow.com/questions/69682403/rename-duplicate-column-name-by-order-in-pandas | I have a dataframe, df, where I would like to rename two duplicate columns in consecutive order: Data DD Nice Nice Hello 0 1 1 2 Desired DD Nice1 Nice2 Hello 0 1 1 2 Doing df.rename(columns={"Name": "Name1", "Name": "Name2"}) I am running the rename function, however, because both column names are identical, the res... | You could use an itertools.count() counter and a list expression to create new column headers, then assign them to the data frame. For example: >>> import itertools >>> df = pd.DataFrame([[1, 2, 3]], columns=["Nice", "Nice", "Hello"]) >>> df Nice Nice Hello 0 1 2 3 >>> count = itertools.count(1) >>> new_cols = [f"Nice{... | 7 | 1 |
69,681,378 | 2021-10-22 | https://stackoverflow.com/questions/69681378/why-does-this-python-snippet-regarding-dictionaries-work | Say we have this >>> x = {'a': 1, 'b': 2} >>> y = {} >>> for k, y[k] in x.items(): pass ... >>> y {'a': 1, 'b': 2} Why does this work? Note: I saw this first here | a, b = (c, d) unpacks the tuple from left to right and assigns a = c and b = d in that order. x.items() iterates over key-value pairs in x. E.g. doing list(x.items()) will give [('a', 1), ('b', 2)] for a, b in x.items() assigns the key to a, and the value to b for each key-value pair in x. for k, y[k] in x.items() assi... | 14 | 7 |
69,660,109 | 2021-10-21 | https://stackoverflow.com/questions/69660109/google-calendar-api-does-not-refresh-refresh-token | I use the google API for a personal project, so I don't have my app verified with google. I use exactly this code example myself and a token.json file gets generated when logging in. Everything works fine, the access token changes more or less every time I make a request (every 10 min). After a week, the request fails.... | You need to publish your app to production in order to remove the 7 days limitation. In APIs & Services / Oauth consent screen: From google documentation about refresh token expiration: A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of "Testin... | 5 | 3 |
69,673,518 | 2021-10-22 | https://stackoverflow.com/questions/69673518/return-pydantic-model-with-field-names-instead-of-alias-as-fastapi-response | I am trying to return my model with the defined field names instead of its aliases. class FooModel(BaseModel): foo: str = Field(..., alias="bar") @app.get("/") -> FooModel: return FooModel(**{"bar": "baz"}) The response will be {"bar": "baz"} while I want {"foo": "baz"}. I know it's somewhat possible when using the di... | You can add response_model_by_alias=False to path operation decorator. This key is mentioned here in the documentation. For example: @app.get("/model", response_model=Model, response_model_by_alias=False) def read_model(): return Model(alias="Foo") | 16 | 34 |
69,668,805 | 2021-10-21 | https://stackoverflow.com/questions/69668805/why-does-this-code-to-get-airflow-context-get-run-on-dag-import | I have an Airflow DAG where I need to get the parameters the DAG was triggered with from the Airflow context. Previously, I had the code to get those parameters within a DAG step (I'm using the Taskflow API from Airflow 2) -- similar to this: from typing import Dict, Any, List from airflow.decorators import dag, task f... | Unfortunately I am not able to reproduce your issue. The similar code below parses, renders a DAG, and completes successfully on Airflow 2.0, 2,1, and 2.2: from datetime import datetime from typing import Any, Dict from airflow.decorators import dag, task from airflow.operators.python import get_current_context def get... | 5 | 5 |
69,669,155 | 2021-10-21 | https://stackoverflow.com/questions/69669155/why-doesnt-mypy-pass-when-typeddict-calls-update-method | Example: from typing import TypedDict class MyType(TypedDict): a: int b: int t = MyType(a=1, b=2) t.update(b=3) mypy toy.py complains toy.py:9:1: error: Unexpected keyword argument "b" for "update" of "TypedDict" Found 1 error in 1 file (checked 1 source file) | It appears this is a known open issue for mypy: https://github.com/python/mypy/issues/6019 For now if you want mypy to not bother you with this error, you'll need to tell it to ignore it: t.update(b=3) # type: ignore[call-arg] | 10 | 6 |
69,660,175 | 2021-10-21 | https://stackoverflow.com/questions/69660175/why-does-redefining-a-variable-used-in-a-generator-give-strange-results | One of my friends asked me about this piece of code: array = [1, 8, 15] gen = (x for x in array if array.count(x) > 0) array = [2, 8, 22] print(list(gen)) The output: [8] Where did the other elements go? | The answer is in the PEP of the generator expressions, in particular the session Early Binding vs Late biding: After much discussion, it was decided that the first (outermost) for-expression should be evaluated immediately and that the remaining expressions be evaluated when the generator is executed. So basically th... | 31 | 32 |
69,665,304 | 2021-10-21 | https://stackoverflow.com/questions/69665304/return-reference-to-member-field-in-pyo3 | Suppose I have a Rust struct like this struct X{...} struct Y{ x:X } I'd like to be able to write python code that accesses X through Y y = Y() y.x.some_method() What would be the best way to implement it in PyO3? Currently I made two wrapper classes #[pyclass] struct XWrapper{ x:X } #[pyclass] struct YWrapper{ y:Y }... | I don't think what you say is possible without some rejigging of the interface: Your XWrapper owns the x and your Y owns its x as well. That means creating an XWrapper will always involve a clone (or a new). Could we change XWrapper so that it merely contains a reference to an x? Not really, because that would require ... | 6 | 2 |
69,665,765 | 2021-10-21 | https://stackoverflow.com/questions/69665765/featuretoolsentityset-object-has-no-attribute-entity-from-dataframe | I tried to learn featuretools following documentation from featuretools.com. A error came up: AttributeError: 'EntitySet' object has no attribute 'entity_from_dataframe' Could you help me? Thank you. Code: import featuretools as ft data = ft.demo.load_mock_customer() transactions_df = data["transactions"].merge(data["... | The documentation you are using is for an older version of Featuretools. You can find the updated Getting Started documentation that works with Featuretools version 1.0 here: https://featuretools.alteryx.com/en/stable/getting_started/getting_started_index.html | 6 | 3 |
69,659,712 | 2021-10-21 | https://stackoverflow.com/questions/69659712/poetry-run-worker-py-filenotfound-errno-2-no-such-file-or-directory-b-snap | I execute the below command, in the same working directory as file worker.py: poetry run worker.py Terminal: me@LAPTOP-G1DAPU88:~/.ssh/workers-python/workers/composite_key/compositekey$ poetry run worker.py FileNotFoundError [Errno 2] No such file or directory: b'/snap/bin/worker.py' at /usr/lib/python3.8/os.py:601 in... | poetry run means "run the following command in the venv managed by poetry". So the correct way of using it in your case is: poetry run python worker.py | 5 | 7 |
69,650,839 | 2021-10-20 | https://stackoverflow.com/questions/69650839/filter-by-partial-string-match-in-json-using-jmespath | Below is a sample JSON: { "School": [ {"@id": "ABC_1", "SchoolType": {"@tc": "10023204", "#text": "BLUE FOX"}}, {"@id": "ABC_2", "SchoolType": {"@tc": "143", "#text": "AN EAGLE"}}, {"@id": "ABC_3", "SchoolType": {"@tc": "21474836", "#text": "OTHER REASONS"}, "SchoolStatus": {"@tc": "21474836", "#text": "FINE"}, "Teache... | You have to warp the contains function around the array of your condition this way: [?contains(SchoolType."#text", 'OTHER')] So a way to get the full Teacher object would be: School[?contains(SchoolType."#text", 'OTHER')].Teacher Or, getting rid of the array of array with a flatten operator: School[?contains(SchoolTy... | 6 | 7 |
69,650,599 | 2021-10-20 | https://stackoverflow.com/questions/69650599/how-to-deactivate-virtualenv-in-powershell | So I am aware of virtualenv in PowerShell? question, specificly this answer, stating that all you need to activate is to execute venv/Scripts/activate.ps1 Of course it is required to set appropriate Execution Policy etc. But my question is: How to disable virtualenv activated inside Power Shell? I tried: venv/Scripts/... | Just a moment after creating this question I've realized that answer is much simpler that I expected. All I need is to type deactivate inside virtualenv. | 15 | 39 |
69,644,987 | 2021-10-20 | https://stackoverflow.com/questions/69644987/why-i-do-get-an-error-when-installing-the-psutil-package-for-python | I installed pyhton on a windows 64bit machine (Version 3.10). Afterwards I like to install psutil with: python -m pip install psutil but I get following error message: Collecting psutil Using cached psutil-5.8.0.tar.gz (470 kB) Preparing metadata (setup.py): started Preparing metadata (setup.py): finished with status ... | Install missing package pip install wheel Install this tools https://visualstudio.microsoft.com/visual-cpp-build-tools/ mark this option during the installation => Restart Your Machine. Run this command in cmd pip install --upgrade setuptools Now You Can Run this command in cmd pip install psutil Final... | 5 | 9 |
69,642,668 | 2021-10-20 | https://stackoverflow.com/questions/69642668/the-indices-of-the-two-geoseries-are-different-understanding-indices | I am working with GeoPandas and I have two GeoDataframes with the same CRS. One of them contains a geometry column with a polygon geometry, the other one a column with point geometry. I want to check which points are inside the polygon. Naively I tried shape.contains(points) This gave me > The indices of the two GeoSe... | What you are describing is effectively a spatial join. Below example constructs points from lon/lat of cities in UK and then finds which administrational area polygon the city is in. This is an NxM comparison import pandas as pd import numpy as np import geopandas as gpd import shapely.geometry import requests # source... | 8 | 4 |
69,591,233 | 2021-10-15 | https://stackoverflow.com/questions/69591233/how-to-select-rows-between-a-certain-date-range-in-python-polars | If a DataFrame is constructed like the following using polars-python: import polars as pl from polars import col from datetime import datetime df = pl.DataFrame({ "dates": ["2016-07-02", "2016-08-10", "2016-08-31", "2016-09-10"], "values": [1, 2, 3, 4] }) How to select the rows between a certain date range, i.e. betwe... | First you need transform the string values to date types then filter: # eager (df.with_columns(pl.col("dates").str.to_date()) .filter(col("dates").is_between(datetime(2016, 8, 9), datetime(2016, 9, 1))) ) # lazy (df.lazy() .with_columns(pl.col("dates").str.to_date()) .filter(col("dates").is_between(datetime(2016, 8, 9)... | 8 | 9 |
69,575,496 | 2021-10-14 | https://stackoverflow.com/questions/69575496/how-to-use-group-by-and-apply-a-custom-function-with-polars | I am breaking my head trying to figure out how to use group_by and apply a custom function using Polars. Coming from Pandas, I was using: import pandas as pd from scipy.stats import spearmanr def get_score(df): return spearmanr(df["prediction"], df["target"]).correlation df = pd.DataFrame({ "era": [1, 1, 1, 2, 2, 2, 5]... | Polars has the pl.corr() function which supports method="spearman" If you want to use a custom function you could do it like this: Custom function on multiple columns/expressions import polars as pl from typing import List from scipy import stats df = pl.DataFrame({ "g": [1, 1, 1, 2, 2, 2, 5], "a": [2, 4, 5, 190, 1, 4,... | 22 | 34 |
69,627,609 | 2021-10-19 | https://stackoverflow.com/questions/69627609/point-accepts-0-positional-sub-patterns-2-given | I'm trying to run an example from the docs, but get the error: Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: Point() accepts 0 positional sub-patterns (2 given) Can someone explain what I doing wrong here? class Point(): def __init__(self, x, y): self.x = x self.y = y x, y = 5 ,5 po... | You need to define __match_args__ in your class. As pointed at in this section of the "What's new in 3.10" page: You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting th... | 8 | 15 |
69,610,231 | 2021-10-18 | https://stackoverflow.com/questions/69610231/why-cant-pip-find-winrt | I just bought a new laptop and I'm trying to set it up with python. I am using python 3.10.0, windows 10, pip v21.3. For the most part, pip seems to be working correctly, I've already used it to install multiple packages such as pygame. When I try to install winrt, however, I get this error C:\Users\matth>pip install w... | Microsoft has not been maintaining the winrt package. There is no binary wheel for Python 3.10 as seen on PyPI. There is also a request for this on GitHub. I have started a community-maintained fork of the PyWinRT project. You can install and use winsdk instead. It supports Python 3.10. Just replace winrt with winsdk i... | 13 | 17 |
69,617,489 | 2021-10-18 | https://stackoverflow.com/questions/69617489/can-i-get-incoming-extra-fields-from-pydantic | I have defined a pydantic Schema with extra = Extra.allow in Pydantic Config. Is it possible to get a list or set of extra fields passed to the Schema separately. For ex: from pydantic import BaseModel as pydanticBaseModel class BaseModel(pydanticBaseModel): name: str class Config: allow_population_by_field_name = True... | NOTE: This answer applies to version Pydantic 1.x. See robcxyz's answer for a 2.x solution. From the pydantic docs: extra whether to ignore, allow, or forbid extra attributes during model initialization. Accepts the string values of 'ignore', 'allow', or 'forbid', or values of the Extra enum (default: Extra.ignore). ... | 35 | 37 |
69,549,954 | 2021-10-13 | https://stackoverflow.com/questions/69549954/python-plotly-radar-chart-with-style | I'm trying to the image shown below and I thought python would be a good idea to do this but I'm not sure. I want to randomize lots of football players' stats, make a radar chart for each and save the charts as images. But the plotly radar charts are not so stylish and I really want to make something stylish. How to t... | From the documentation for polar layout, it seems that Plotly does not offer much options when it comes the grid shape itself. However, Plotly allows you to create your own templates/themes or examine built-in themes. As a starting point, you should probably analyze the plotly_dark theme as it has some features similar... | 6 | 4 |
69,572,265 | 2021-10-14 | https://stackoverflow.com/questions/69572265/ingest-several-types-of-csvs-with-databricks-auto-loader | I'm trying to load several types of csv files using Autoloader, it currently merge all csv that I drop into a big parquet table, what I want is to create parquet tables for each type of schema/csv_file Current code does: #Streaming files/ waiting a file to be dropped spark.readStream.format("cloudFiles") \ .option("cl... | You can create different autoloader streams for each file from the same source directory and filter the filenames to consume by using the pathGlobFilter option on Autoloader (databricks documentation). By doing that you will end up having different checkpoints for each table and you can have the different schemas worki... | 5 | 2 |
69,598,542 | 2021-10-16 | https://stackoverflow.com/questions/69598542/failed-to-query-the-value-of-task-appcompiledebugjavawithjavac-property-opt | Can anyone help me to fix this error? FAILURE: Build failed with an exception. What went wrong: Execution failed for task ':app:compileDebugJavaWithJavac'. Failed to query the value of task ':app:compileDebugJavaWithJavac' property 'options.generatedSourceOutputDirectory'. Querying the mapped value of map(java.io.Fi... | It's an AGP related issue: https://youtrack.jetbrains.com/issue/KTIJ-19252 Updating AGP up to 4.2.2 or higher will probably solve this issue. | 8 | 5 |
69,629,495 | 2021-10-19 | https://stackoverflow.com/questions/69629495/export-pyvis-graph-as-vector-or-png-image-is-there-a-way | I'm looking for a way to export a huge Graph generated with pyvis in to a vector graphic .svg or at least .png format. Is there a way to do it? So far I've only found the option to save / export as .html file. Thanks in advance. | For me this worked: save the graph to HTML file open the HTML in a new tab right-click -> save image as ... | 8 | 2 |
69,570,717 | 2021-10-14 | https://stackoverflow.com/questions/69570717/dask-dataframe-can-set-index-put-a-single-index-into-multiple-partitions | Empirically it seems that whenever you set_index on a Dask dataframe, Dask will always put rows with equal indexes into a single partition, even if it results in wildly imbalanced partitions. Here is a demonstration: import pandas as pd import dask.dataframe as dd users = [1]*1000 + [2]*1000 + [3]*1000 df = pd.DataFram... | is it the case that a single index can never be in two different partitions? No, it's certainly allowed. Dask will even intend for this to happen. However, because of a bug in set_index, all the data will still end up in one partition. An extreme example (every row is the same value except one): In [1]: import dask.d... | 6 | 2 |
69,582,550 | 2021-10-15 | https://stackoverflow.com/questions/69582550/using-requests-module-for-post-i-want-to-pick-up-entire-json-body-from-whole | I've been trying to write a little python script to automate some API testing. I need it to pick up the whole JSON body from a CSV or other format file, but not just a single body per file, rather iterate over all the "bodies" in it. The way I concocted it is, each cell, or value, is an entire body. This comes from how... | csv.reader returns rows of strings, so the strings each need to be converted to a Python object for the json keyword argument in requests.request. We can use json.loads to deserialize a string. req_obj = json.loads(col) r = requests.request("POST", url, headers = headers, json = req_obj) | 5 | 1 |
69,581,672 | 2021-10-15 | https://stackoverflow.com/questions/69581672/how-to-pass-dictionary-elements-from-hydra-config-file | I am trying to instantiate objects with hydra, I have a class torchio.transforms.RemapLabels that I am using in my config file: _target_: torchio.transforms.RemapLabels The problem is that torchio.transforms.RemapLabels takes dictionary elements as input, how do I pass those from my hydra config file? (config.yaml)? I... | There are two options: you can pass the inputs as positional arguments or as named arguments. Using named arguments (a.k.a. keyword arguments) in your yaml file: _target_: torchio.transforms.RemapLabels remapping: 2: 1 4: 3 6: 5 8: 7 masking_method: "Anterior" or, using json-style maps: _target_: torchio.transforms.Re... | 5 | 5 |
69,593,336 | 2021-10-16 | https://stackoverflow.com/questions/69593336/why-does-pandas-allow-non-unique-index | Pandas allows both unique and non-unique indices. Some of the operations only allow unique indices. In what situation would it make sense to use non-unique indices? I think enforcing uniqueness of the indices can help discover data integrity problems upfront. | Disclaimer: a unique RangeIndex is always going to be the most performant option. This question seems to favour using a unique index and is specifically looking for cases where allowing non-unique indexes is desired. For this reason, from this point forward unique indexes are not going to be discussed, nor is performan... | 7 | 4 |
69,571,374 | 2021-10-14 | https://stackoverflow.com/questions/69571374/audio-recording-in-python-with-pyaudio-error-pamaccore-auhal-msg-audi | I am using pyaudio to record sounds on my Mac BigSur 11.6 (20G165). Specifically, I'm redirecting sound from an application to the input using BlackHole, which works fine. It usually works fine but, sometimes, I get this error in the Terminal: ||PaMacCore (AUHAL)|| Error on line 2500: err='-10863', msg=Audio Unit: can... | Apparently the problem were mismatched bitrates in BlackHole's aggregated output device. I was aggregating Blackhole's output (44,1kHz) and the Mac Speakers (48kHz). This did not cause any consistent bad behaviour but sometimes led to these errors. | 9 | 6 |
69,613,336 | 2021-10-18 | https://stackoverflow.com/questions/69613336/how-to-catch-python-warnings-with-sentry | With sentry_sdk, the sentry documentation explain how to automatically catch exceptions or logging messages. However, how can I catch a python warning, like a DeprecationWarning that would be raised with warnings.warn(DeprecationWarning, "warning message") | There's no certain API in sentry for sending warnings, However, you need to ensure you're logging these with the general logging infrastructure that you are using. For example, if you are using Django, you have to change the logging level to be Warning like below in the settings.py file LOGGING = { 'version': 1, 'disab... | 7 | 2 |
69,606,274 | 2021-10-17 | https://stackoverflow.com/questions/69606274/pytorch-equivalent-of-tensorflow-keras-stringlookup | I'm working with pytorch now, and I'm missing a layer: tf.keras.layers.StringLookup that helped with the processing of ids. Is there any workaround to do something similar with pytorch? An example of the functionality I'm looking for: vocab = ["a", "b", "c", "d"] data = tf.constant([["a", "c", "d"], ["d", "a", "b"]]) l... | Package torchnlp, pip install pytorch-nlp from torchnlp.encoders import LabelEncoder data = ["a", "c", "d", "e", "d"] encoder = LabelEncoder(data, reserved_labels=['unknown'], unknown_index=0) enl = encoder.batch_encode(data) print(enl) tensor([1, 2, 3, 4, 3]) | 4 | 7 |
69,609,618 | 2021-10-18 | https://stackoverflow.com/questions/69609618/github-action-i-wrote-doesnt-have-access-to-repos-files-that-is-calling-the-ac | A sample repo with the directory structure of what I'm working on is on GitHub here. To run the GitHub Action, you just need to go to the Action tab of the repo and run the Action manually. I have a custom GitHub Action I've written as well with python as the base image in the Docker container but want the python vers... | There's generally two ways to get files from your repository available to a docker container you build and run. You either (1) add the files to the image when you build it or (2) mount the files into the container when you run it. There are some other ways, like specifying volumes, but that's probably out of scope for ... | 9 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.