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 |
|---|---|---|---|---|---|---|
68,584,962 | 2021-7-30 | https://stackoverflow.com/questions/68584962/separate-panels-in-mplfinance | I would like to separate my panels because the titles superposed. ADX title is in RSI panel. I tried with tight_layout=True but still the same. My code: ap0 = [ mpf.make_addplot(df['sma_200'],color='#FF0000', panel=2), mpf.make_addplot(df['sma_50'],color='#ffa500', panel=2), mpf.make_addplot(df['sma_20'],color='#00FF0... | Mplfinance subplots do not have a function to adjust the graph spacing, so there is a way to fit them into matplotlib subplots and make them spaced. We recommend using the y-axis label instead of the title, which is a feature only available in Mplfinance. import yfinance as yf import mplfinance as mpf import matplotlib... | 8 | 10 |
68,586,561 | 2021-7-30 | https://stackoverflow.com/questions/68586561/sklearn-multi-class-problem-and-reporting-sensitivity-and-specificity | I have a three-class problem and I'm able to report precision and recall for each class with the below code: from sklearn.metrics import classification_report print(classification_report(y_test, y_pred)) which gives me the precision and recall nicely for each of the 3 classes in a table format. My question is how can ... | If we check the help page for classification report: Note that in binary classification, recall of the positive class is also known as “sensitivity”; recall of the negative class is “specificity”. So we can convert the pred into a binary for every class, and then use the recall results from precision_recall_fscore_su... | 4 | 8 |
68,587,852 | 2021-7-30 | https://stackoverflow.com/questions/68587852/how-to-iterate-over-items-in-dictionary-using-while-loop | i know how to iterate over items in dictionary using for loop. but i need know is how to iterate over items in dictionary using while loop. is that possible? This how i tried it with for loop. user_info = { "username" : "Hansana123", "password" : "1234", "user_id" : 3456, "reg_date" : "Nov 19" } for values,keys in user... | You can iterate the items of a dictionary using iter and next with a while loop. This is almost the same process as how a for loop would perform the iteration in the background on any iterable. https://docs.python.org/3/library/functions.html https://docs.python.org/3/library/stdtypes.html#iterator-types Code: user_i... | 4 | 10 |
68,584,302 | 2021-7-30 | https://stackoverflow.com/questions/68584302/modulenotfounderror-no-module-named-when-trying-to-make-unit-tests-in-pyt | Problem I am trying to make unit tests for my project, but I am having issues figuring out where my error is in regards to absolute importing the module to test. I am using Visual Studio Code as my IDE. My directories look like this: project_folder + code_files - reader.py - __init__.py + tests - test_reader.p... | Reason: This is because the folder of project_folder was not in the sys.path. A list of strings that specifies the search path for modules. Initialized from the environment variable PYTHONPATH, plus an installation-dependent default. As initialized upon program startup, the first item of this list, path[0], is the dir... | 10 | 8 |
68,576,519 | 2021-7-29 | https://stackoverflow.com/questions/68576519/what-is-the-type-hint-for-pytests-caplog-fixture | I am using the caplog fixture that comes with pytest. I am using mypy for my type checking, and would like to know what the correct type hint for caplog is. For example: def test_validate_regs(caplog: Any) -> None: validate_regs(df, logger) assert caplog.text == "", "No logs should have been made." In this example, I ... | as of pytest 6.2.0 you should use pytest.LogCaptureFixture prior to that you needed to import a private name which is not recommended (we frequently change the internals inside the _pytest namespace without notice and with no promises of forward or backward compatibility) disclaimer: I'm a pytest core dev | 24 | 32 |
68,583,870 | 2021-7-29 | https://stackoverflow.com/questions/68583870/checking-whether-a-function-is-decorated | I am trying to build a control structure in a class method that takes a function as input and has different behaviors if a function is decorated or not. Any ideas on how you would go about building a function is_decorated that behaves as follows: def dec(fun): # do decoration def func(data): # do stuff @dec def func2(d... | Yes, it's relatively easy because functions can have arbitrary attributes added to them, so the decorator function can add one when it does its thing: def dec(fun): def wrapped(*args, **kwargs): pass wrapped.i_am_wrapped = True return wrapped def func(data): ... # do stuff @dec def func2(data): ... # do other stuff def... | 7 | 7 |
68,581,187 | 2021-7-29 | https://stackoverflow.com/questions/68581187/playing-sound-in-google-colab | Hi so i have code which gives the answer in form of speech. I am using this code: audio.save("audio.wav") sound_file = '/content/audio.wav' Audio(sound_file, autoplay=True) Now the code plays file all well but if I play in a separate cell. But if I put this code in between my code, it doesn't work. Any ideas? | Wrap it in display(): from IPython.display import Audio, display display(Audio(sound_file, autoplay=True)) | 9 | 17 |
68,577,198 | 2021-7-29 | https://stackoverflow.com/questions/68577198/pytorch-summary-fails-with-huggingface-model | I want a summary of a PyTorch model downloaded from huggingface. Am I doing something wrong here? from torchinfo import summary from transformers import AutoModelForSequenceClassification model = AutoModelForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2) summary(model, input_size=(16, 512)) ... | There's a bug [also reported] in torchinfo library [torchinfo.py] in the last line shown. When dtypes is None, it is by default creating torch.float tensors whereas forward method of bert model uses torch.nn.embedding which expects only int/long tensors. def process_input( input_data: Optional[INPUT_DATA_TYPE], input_s... | 7 | 8 |
68,578,226 | 2021-7-29 | https://stackoverflow.com/questions/68578226/how-to-map-two-dataframe-with-output-of-overlapping-items-in-new-columns | I have two dataframes: data = { 'values': ['Cricket', 'Soccer', 'Football', 'Tennis', 'Badminton', 'Chess'], 'gems': ['A1K, A2M, JA3, AN4', 'B1, A1, Bn2, B3', 'CD1, A1', 'KWS, KQM', 'JP, CVK', 'KF, GF'] } df1 = pd.DataFrame(data) df1 values gems 0 Cricket A1K, A2M, JA3, AN4 1 Soccer B1, A1, Bn2, B3 2 Football CD1, A1... | first str.split and explode the column gems and reset_index to keep the original index. Then for each column of df2, merge with the exploded gems, groupby the original index and do both the count and the aggregation as you want with join. pd.concat the merges for each column and join to your original df1. fillna the co... | 5 | 6 |
68,575,716 | 2021-7-29 | https://stackoverflow.com/questions/68575716/docker-error-response-from-daemon-failed-to-create-shim | On a fresh ubunto i installed docker and when i run the image, i got following error docker: Error response from daemon: failed to create shim: OCI runtime create failed: container_linux.go:380: starting container process caused: exec: "--gpus": executable file not found in $PATH: unknown. ERRO[0000] error waiting for ... | This command is incorrectly ordered: sudo docker run test --gpus all The docker run command takes the syntax: docker ${args_to_docker} run ${args_to_run} image_name ${cmd_override} The --gpus is a flag to the run command, and not a command you want to run inside your container. So you'd reorder as: sudo docker run --... | 23 | 15 |
68,571,553 | 2021-7-29 | https://stackoverflow.com/questions/68571553/how-to-use-a-faker-value-as-part-of-another-field-with-factoryboy | I'm using FactoryBoy and Faker to generate some models for unit tests. Generating data for fields is easy enough, but how to I generate a string that incorporates a value produced from a Faker provider? import factory import MyModel class MyFactory(factory.django.DjangoModelFactory): class Meta: model = MyModel # my_ip... | With some trial and error I figured out this did require using LazyAttribute so the my_string attribute is calculated after the rest of the object is generated. However, I then discovered this is essentially a duplicate of: In Factory Boy, how to join strings created with Faker? If anyone is wondering, the way to do th... | 5 | 6 |
68,561,708 | 2021-7-28 | https://stackoverflow.com/questions/68561708/how-to-remove-noise-around-numbers-using-opencv | I'm trying to use Tesseract-OCR to get the readings on below images but having issues getting consistent results with the spotted background. I have below configuration on my pytesseract CONFIG = f"—psm 6 -c tessedit_char_whitelist=01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZÅÄabcdefghijklmnopqrstuvwxyzåäö.,-" I have also tri... | That was a challenge but i think i have an interesting approach: Pattern-matching If you zoom in, you realize that the pattern in the back only has 4 possible dots, a single full pixle, a double full pixel and a double pixel with a medium left or right. So what i did was grab these 4 patterns from the image with 17.160... | 4 | 5 |
68,569,239 | 2021-7-29 | https://stackoverflow.com/questions/68569239/what-is-the-difference-between-abstractclassmetaclass-abcmeta-and-class-abstra | I have seen two ways for defining Abstract Classes in Python. This one: from abc import ABCMeta, abstractmethod class AbstactClass(metaclass = ABCMeta): And this one: from abc import ABC, abstractmethod class AbstractClass2(ABC): What are there differences between them and what are the respective usage scenarios? | There is no actual functional difference. The ABC class is simply a convenience class to help make the code look less confusing to those who don't know the idea of a metaclass well, as the documentation states: A helper class that has ABCMeta as its metaclass. With this class, an abstract base class can be created by ... | 30 | 29 |
68,566,490 | 2021-7-28 | https://stackoverflow.com/questions/68566490/should-i-use-utf8-or-utf-8-sig-when-opening-a-file-to-read-in-python | I have alway used 'utf8' to read in a file: with open(filename, 'r', encoding='utf8') as f, open(filename2, 'r', encoding='utf8') as f2: for line in f: line = line.strip() columns = line.split(' ') for line in f2: line = line.strip() columns = line.split(' ') However, the code above introduced an additional '\ufeff' ... | UTF-8-encoded files can be written with a signature indicating it is UTF-8. This signature code is called the "byte order mark" (or BOM) and has the Unicode code point value U+FEFF. If the file containing a BOM is viewed in a hex editor the file will start with the hexadecimal bytes EF BB BF. When viewed in a text edit... | 4 | 8 |
68,561,211 | 2021-7-28 | https://stackoverflow.com/questions/68561211/python-set-timeout-on-popen-stdout-readline | I'd like to be able to set timeout on subprocess stdout and return an empty string if exceeded timeout. Here's my attempt to do so using asyncio. However, it failed on using file.stdout.readline() in asyncio.wait_for. Any idea how to fix this ? import threading import select import subprocess import queue import time i... | The subprocess library only provides synchronous functions. These cannot be directly used by asyncio, and manually wrapping them is inefficient. asyncio already ships with its own subprocess backend. Its process representation works similar to subprocess.Popen but allows to cooperatively wait for operations. import asy... | 5 | 5 |
68,555,085 | 2021-7-28 | https://stackoverflow.com/questions/68555085/how-can-i-chunk-through-a-csv-using-arrow | What I am trying to do I am using PyArrow to read some CSVs and convert them to Parquet. Some of the files I read have plenty of columns and have a high memory footprint (enough to crash the machine running the job). I am trying to chunk through the file while reading the CSV in a similar way to how Pandas read_csv wit... | The function you are looking for is pyarrow.csv.open_csv which returns a pyarrow.csv.CSVStreamingReader. The size of the batches will be controlled by the block_size option you noticed. For a complete example: import pyarrow as pa import pyarrow.parquet as pq import pyarrow.csv in_path = '/home/pace/dev/benchmarks-proj... | 9 | 16 |
68,561,198 | 2021-7-28 | https://stackoverflow.com/questions/68561198/how-to-make-a-matplotlib-screen-fullscreen-without-hiding-the-taskbar | Let's say I have the following chunk of code: import matplotlib.pyplot as plt manager = plt.get_current_fig_manager() manager.full_screen_toggle() plt.show() The screen is set to be in fullscreen mode. My issue is that the taskbar is being hidden. How do I adjust the fullscreen mode so that it doesn't hide my taskbar? | I usually use mng = plt.get_current_fig_manager() mng.frame.Maximize(True) before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only. Or try this, wm = plt.get_current_fig_manager() wm.window.state('zoomed') | 6 | 6 |
68,559,870 | 2021-7-28 | https://stackoverflow.com/questions/68559870/why-is-the-class-attribute-being-modified | In my book it says Use class attributes to define properties that should have the same value for every class instance. Use instance attributes for properties that vary from one instance to another. But then, in an example, the species class attribute is modified for miles as shown below: class Dog: species = "Canis f... | Why is the class attribute being modified? It isn't. miles is an instance of the Dog class, so assigning to miles.species creates an instance attribute. That means that the species class attribute is not for the entire Dog class. In the code you have shown, there are two things called species. An attribute of the ... | 4 | 3 |
68,554,782 | 2021-7-28 | https://stackoverflow.com/questions/68554782/modulenotfounderror-no-module-named-tkinter-on-macos | Tkinter doesn't work, it throws an error. Installation: % pip3 install tk My code: #!/usr/bin/env python3 import tkinter as tk The error: Traceback (most recent call last): File "/Users/arghadip/Library/Application Support/CodeRunner/Unsaved/Untitled.py", line 4, in <module> import tkinter as tk File "/usr/local/Cell... | For Python3 tkinter can be simply installed by, brew install python-tk pip sometimes wont work successfully on my Mac, especially with the High Sierra OS version. Brew can be used to install all kinds of software packages in mac. | 18 | 55 |
68,554,094 | 2021-7-28 | https://stackoverflow.com/questions/68554094/remove-the-trailing-comma-when-format-string-with-tuples | I'm doing string formatting with tuples: a = (1,2,3) s = f"something in {a}" print(s) 'something in (1, 2, 3)' Everything is fine until I encounter a single-element tuple, which gives: a = (1,) s = f"something in {a}" 'something in (1,)' what I actually want is: 'something in (1)' How do I make tuple string format... | You could use your own formatting logic, e.g. a = (1,2,3) s = ','.join([str(x) for x in a]) print(s) # 1,2,3 a = (1,) s = ','.join([str(x) for x in a]) print(s) # 1 | 5 | 5 |
68,549,918 | 2021-7-27 | https://stackoverflow.com/questions/68549918/how-to-send-messages-on-threads | I currently have code for a command that takes in a channel ID followed by some text message as input. The code then finds the channel and sends the message on it. However, Discord has just released a new thread feature, and currently, no update has been made to the official Discord API docs regarding how bots can inte... | Since discord.py 2.0, threads are supported with discord.Thread. get_thread method 1. Using the guild @bot.command() async def test(ctx): thread = ctx.guild.get_thread(thread_id) There is also the method get_channel_or_thread which returns either a channel or a thread. channel_or_thread = ctx.guild.get_channel_or_thr... | 4 | 4 |
68,500,166 | 2021-7-23 | https://stackoverflow.com/questions/68500166/does-select-for-update-work-with-the-update-method-in-django | The documentation for Django 2.2, which I'm using, gives the following example usage for select_for_update: from django.db import transaction entries = Entry.objects.select_for_update().filter(author=request.user) with transaction.atomic(): for entry in entries: ... Using this approach, one would presumably mutate the... | As far as I'm aware update just performs an UPDATE ... WHERE query, with no SELECT before it Yes, that's correct. You could confirm this by looking at the actual queries made. Using the canonical django tutorial "polls" app as an example: with transaction.atomic(): qs = polls.models.Question.objects.select_for_update... | 14 | 16 |
68,487,529 | 2021-7-22 | https://stackoverflow.com/questions/68487529/how-to-ensure-python-prints-utf-8-and-not-utf-16-le-when-piped-in-powershell | I want to print text as UTF-8 when piped (to, for example, a file), so on Python 3.7.3 on Windows 10 via PowerShell, I'm doing this: import sys if not sys.stdout.isatty(): sys.stdout.reconfigure(encoding='utf-8') print("Mamma mia.") When run as encodingtest.py > test.txt, test.txt then turns out to be this: 00000000 F... | Update: PowerShell (Core) v7.4+ now does support raw byte handling with external programs - see this answer. The following therefore applies only to Windows PowerShell and PowerShell (Core) 7.3- PowerShell fundamentally doesn't support processing raw output (a stream of bytes) from external programs: It invariabl... | 9 | 13 |
68,476,576 | 2021-7-21 | https://stackoverflow.com/questions/68476576/python-match-case-switch-performance | I was expecting the Python match/case to have equal time access to each case, but seems like I was wrong. Any good explanation why? Lets use the following example: def match_case(decimal): match decimal: case '0': return "000" case '1': return "001" case '2': return "010" case '3': return "011" case '4': return "100" c... | The match/case statement introduced in PEP 622 offers a more elegant and readable approach to pattern matching compared to traditional if-elif-else chains. Its primary advantage lies in its ability to streamline complex conditional logic. Traditional approach def is_tuple(node): if isinstance(node, Node) and node.child... | 15 | 9 |
68,533,094 | 2021-7-26 | https://stackoverflow.com/questions/68533094/how-do-i-access-mounted-secrets-when-using-google-cloud-run | I have two questions: Why can't I mount two cloud secrets in the same directory? I have attempted to mount two secrets, FIREBASE_AUTH_SERVICE_ACCOUNT and PURCHASE_VALIDATION_SERVICE_ACCOUNT in the directory: flask_app/src/services/firebase/service_accounts/ However I get this error, when attempting to do this: spec.te... | With Cloud Run and Secret manager you can load a secret in 2 manners: Load a secret in a environment variable, use --set-secrets=ENV_VAR_NAME=secretName:version Load a secret in a file, use --set-secrets=/path/to/file=secretName:version Therefore, you can read a secret as you read An environment variable (something ... | 6 | 12 |
68,545,064 | 2021-7-27 | https://stackoverflow.com/questions/68545064/python-commands-to-build-distribution-setup-py-build-vs-python-m-build | I'm learning about Python packaging, and according to this guide, the command to build a python distribution package seems to be python3 -m build. But I aslo found that there is a command line interface for setup.py file from setuptools: $ python setup.py --help-commands Standard commands: build build everything needed... | Citing Why you shouldn't invoke setup.py directly by Paul Ganssle. The setuptools project has stopped maintaining all direct invocations of setup.py years ago, and distutils is deprecated. There are undoubtedly many ways that your setup.py-based system is broken today, even if it's not failing loudly or obviously. Dir... | 25 | 20 |
68,517,139 | 2021-7-25 | https://stackoverflow.com/questions/68517139/matplotlib-appears-to-not-use-rcparams-when-plotting-particularly-for-text-e-g | I have an issue that matplotlib appears to not be following the rcparams. This occurs particularly for text: annotations, axis labels, titles, etc. I will note that I am not running Seaborn at the same time (Seaborn is known to interfere with some matplotlib settings). I am using Python 3.7.10, matplotlib 3.3.4, and se... | This is a known issue documented in font-manager.py. KNOWN ISSUES documentation font variant is untested font stretch is incomplete font size is incomplete default font algorithm needs improvement and testing setWeights function needs improvement 'light' is an invalid weight value, remove it. There seems to be an i... | 6 | 1 |
68,523,339 | 2021-7-26 | https://stackoverflow.com/questions/68523339/is-bisect-bisect-different-from-bisect-bisect-right-in-python | Based on everything that I have seen bisect.bisect and bisect.bisect_right in Python seem to do the same thing. Is there any difference that accounts for the difference in name, or do they have identical behavior and merely a different name? Obviously bisect.bisect_left is different from both of them, but both bisect a... | They are identical: >>> import bisect >>> bisect.bisect is bisect.bisect_right True In case you were curious, bisect_right is the original function and bisect is the alias: >>> bisect.bisect.__name__ 'bisect_right' | 4 | 14 |
68,532,627 | 2021-7-26 | https://stackoverflow.com/questions/68532627/fastapi-returns-404-when-accessing-url-in-the-browser | I am learning fastapi and created the sample following application: from fastapi import FastAPI import uvicorn app = FastAPI() @app.get("/hello") async def hello_world(): return {"message": "hello_world"} if __name__== "__main__": uvicorn.run(app, host="127.0.0.1", port=8080) The server starts fine but when I test the... | always add the trailing slash after the path, had the same issue, took me hours to debug | 4 | 7 |
68,490,691 | 2021-7-22 | https://stackoverflow.com/questions/68490691/faster-way-to-look-for-a-value-in-pandas-dataframe | I'm trying to "translate" some of my R scripts to Python, but I notice, that working with data frames in Python is tremendously slower than doing it in R, e.g. exctracting cells according to some conditions. I've done a little investigation, this is how much time it takes to look for a specific value in Python: import ... | Since you are looking to select a single value from a DataFrame there are a few things you can do to improve performance. Use .item() instead of [0], which has a small, but decent improvement especially for smaller DataFrames. It's wasteful to mask the entire DataFrame just to then select a known Series. Instead mask ... | 9 | 18 |
68,507,277 | 2021-7-24 | https://stackoverflow.com/questions/68507277/connection-error-between-two-devices-importerror-libmariadb-so-3-cannot-open | I have two devices that I use as MySql server and Django server. My system, which works on my development device, becomes inoperable when it switches to other devices. Settings on 192.168.3.60: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'bildirdi_hurmalar', 'USER': 'gungelir_tirmalar', 'PA... | Try to install libmariadbclient-dev: sudo apt install libmariadbclient-dev | 5 | 2 |
68,469,643 | 2021-7-21 | https://stackoverflow.com/questions/68469643/docker-build-time-secrets-with-layer-caching | I have a Dockerfile that does a pip install of a package from an AWS code artifact. The install requires an auth token, so my current approach is to generate the dynamic/secret repo url in a build script and pass it into Docker as a build arg, which leads to lines like this in my Dockerfile: ARG CORE_REPO_URL ARG CORE_... | Figured out for my use case of : Package in CA Multi account setup where you assume a role to get where you need. Hopefully this will help someone else who finds this. Docker Build using an Assumed Role Profile Remember to build with the buildkit # syntax = docker/dockerfile:experimental # This needs to go at the top... | 5 | 1 |
68,490,194 | 2021-7-22 | https://stackoverflow.com/questions/68490194/defining-a-python-enum-in-a-c-extension-am-i-doing-this-right | I'm working on a Python C extension and I would like to expose a custom enum (as in: a class inheriting from enum.Enum) that would be entirely defined in C. It turned out to not be a trivial task and the regular mechanism for inheritance using .tp_base doesn't work - most likely due to the Enum's meta class not being p... | The metaclass in Enum is tricky yes. But you can see here that you can create an enum (in Python) like: FooBar = enum.Enum('FooBar', dict(FOO=1, BAR=2)) So you can use this technique to easily create an enum class in Python C-API by doing something like: PyObject *key, *val, *name, *attrs, *args, *modname, *kwargs, *e... | 14 | 15 |
68,523,752 | 2021-7-26 | https://stackoverflow.com/questions/68523752/python-module-asyncio-has-no-attribute-to-thread | From python's asyncio examples: import asyncio import time def blocking_io(): print(f"start blocking_io at {time.strftime('%X')}") # Note that time.sleep() can be replaced with any blocking # IO-bound operation, such as file operations. time.sleep(1) print(f"blocking_io complete at {time.strftime('%X')}") async def mai... | to_thread is only available in python 3.9+, if you are working with python 3.8 or an older version, you can copy the source code of it: async def to_thread(func, /, *args, **kwargs): loop = asyncio.get_running_loop() ctx = contextvars.copy_context() func_call = functools.partial(ctx.run, func, *args, **kwargs) return a... | 9 | 19 |
68,486,056 | 2021-7-22 | https://stackoverflow.com/questions/68486056/different-behavior-while-reading-dataframe-from-parquet-using-cli-versus-executa | Please consider following program as Minimal Reproducible Example -MRE: import pandas as pd import pyarrow from pyarrow import parquet def foo(): print(pyarrow.__file__) print('version:',pyarrow.cpp_version) print('-----------------------------------------------------') df = pd.DataFrame({'A': [1,2,3], 'B':['dummy']*3}... | Credit to @U12-Forward for assisting me in debugging the issue. After a bit of research and debugging, and exploring the library program files, I found that pyarrow uses _ParquetDatasetV2 and ParquetDataset functions which are essentially two different functions that reads the data from parquet file, _ParquetDatasetV2 ... | 10 | 3 |
68,507,862 | 2021-7-24 | https://stackoverflow.com/questions/68507862/how-to-solve-condahttperror-http-000-connection-failed-error-in-wsl | I have enabled WSL in my Windows 10 and installed Ubuntu 20.04 LTS from Microsoft store. To use meep software, I am following the installation process on my Windows 10. Unfortunately, when I am running below command, conda create -n mp -c conda-forge pymeep I am getting an error like, Collecting package metadata (curr... | Maybe this discussion here helps: https://github.com/conda/conda/issues/9948 In summary three fixes are suggested there: Install an older version (4.7.12) of conda / miniconda see here Change file- & directory-permissions of your miniconda-installation (chmod -R 777 ~/.miniconda3) see here Restart wsl (wsl --shutdown)... | 7 | 12 |
68,463,220 | 2021-7-21 | https://stackoverflow.com/questions/68463220/pandas-importing-error-importerror-cannot-import-name-dtypearg-from-pandas | When I try to import pandas, it throws an error. I cannot import pandas. I re-install pandas but it keeps ont throwing the same error. I tried running it in a local prompt and in a jupyter notebook. I think it may conflict with the pip version so I removed the package from pip. Currently I just have the conda version b... | I confirm, it is a reproducible bug in pandas==1.3.1. A workaround is to downgrade it to some earlier version, e.g. pip install pandas==1.3.0. The woarkaround can be tested in build 20210717 of our python (3.8) CUDA-enabled containers: docker run -d --rm --name ml-gpu-py38-cuda112-cust -p 8888:8888 -v /home/mir:/home/j... | 29 | 22 |
68,495,481 | 2021-7-23 | https://stackoverflow.com/questions/68495481/how-to-map-function-directly-over-list-of-lists | I have built a pixel classifier for images, and for each pixel in the image, I want to define to which pre-defined color cluster it belongs. It works, but at some 5 minutes per image, I think I am doing something unpythonic that can for sure be optimized. How can we map the function directly over the list of lists? #Fi... | You can use the Numba's JIT to speed up the code by a large margin. The idea is to build classified_pixels on the fly by iterating over the colours for each pixel. The colours are stored in a Numpy array where the index is the colour key. The whole computation can run in parallel. This avoid many temporary arrays to be... | 8 | 10 |
68,529,610 | 2021-7-26 | https://stackoverflow.com/questions/68529610/how-to-set-the-size-of-pic-video-rendered-by-manim | The default size of picture or video rendered by manim is 1920*1080. But I want to resize it to for example 2000 * 2000, and I don't know how to modify it. I browsed the doc of manim, but I haven't find any useful ways. Can you help me with it? I tried to modify frame_height,frame_width,frame_size,but nothing happend... | you can use the -r, and set e.g. -r 2000,2000. Here I wrote a whole tutorial how to change the pixel size: https://flyingframes.readthedocs.io/en/latest/ch5.html | 6 | 12 |
68,549,442 | 2021-7-27 | https://stackoverflow.com/questions/68549442/how-to-run-mediapipes-pose-landmark-detection-on-a-gpu | I am able to run MediaPipe's Pose Landmark detection on my Windows 10 computer by following this tutorial here: https://google.github.io/mediapipe/solutions/pose.html#python-solution-api, but I'm not sure how I can run this example using a GPU. I know that it is quite fast to run on CPU, but I want to use the model wit... | TensorFlow Lite GPU delegate is majorly designed for mobile phone accelerations. See also https://www.tensorflow.org/lite/performance/gpu. Experimentally, the OpenCL backend in TFLite GPU delegate can be supported through Linux platforms. However, we have not verified it on Windows yet. See also https://github.com/tens... | 7 | 2 |
68,477,792 | 2021-7-22 | https://stackoverflow.com/questions/68477792/pandas-boxplot-contains-content-of-plot-saved-before | I'm plotting some columns of a datafame into a boxplot. Sofar, no problem. As seen below I wrote some stuff and it works. BUT: the second plot contains the plot of the first plot, too. So as you can see I tried it with "= None" or "del value", but it does not work. Putting the plot function outside also don't solves th... | I can see from your code that boxplots: boxplot1 & boxplot2 are in the same graph. What you need to do is instruct that there is going to be two plots. This can be achieved either by Create two sub plots using pyplot in matplotlib, this code does the trick fig1, ax1 = plt.subplots() with ax1 specifying boxplot to put ... | 4 | 4 |
68,542,054 | 2021-7-27 | https://stackoverflow.com/questions/68542054/fastapi-add-long-tasks-to-buffer-and-process-them-one-by-one-while-maintaining | I am trying to set up a FastAPI server that will take as input some biological data, and run some processing on them. Since the processing takes up all the server's resources, queries should be processed sequentially. However, the server should stay responsive and add further requests in a buffer. I've been trying to u... | EDIT: The original answer was influenced by testing with httpx.AsyncClient (as flagged might be the case in the original caveat). The test client causes background tasks to block that do not block without the test client. As such, there's a simpler solution provided you don't want to test it with httpx.AsyncClient. The... | 10 | 6 |
68,491,834 | 2021-7-22 | https://stackoverflow.com/questions/68491834/handle-client-side-cancellation-in-grpc-python-asyncio | Question first, context below. How can I perform some server-side action (eg, cleanup) based on a cancellation of an RPC from the client with an async gRPC python server? In my microservice, I have an asyncio gRPC server whose main RPCs are bidirectional streams. On the client side (which is also using asyncio), when I... | thanks for the post. We are aware of this issue, and adding support for those two methods is on our roadmap. For a short term solution, you can use try-catch and decorators. The client-side-cancellation is observed as an asyncio.CancelledError in method handler. Here is a modified helloworld example: Server code: class... | 4 | 6 |
68,543,704 | 2021-7-27 | https://stackoverflow.com/questions/68543704/why-do-i-get-method-describe-failed-401-unauthorized | Let me explain my problem, I am trying to access different channels in a DVR system. I have successfully gotten access to a single camera (channel 1) by using opencv as such: public_link = 'rtsp://test:test@192.168.1.48/cam/realmonitor' cap = cv2.VideoCapture(public_link, cv2.CAP_FFMPEG) The problem is I can't access ... | Well, after a lot of research of the DVR model that I am using. It turns out that I am using a Longse DVR type model. I don't really know what model number exactly but at least I knew that it was a Longse DVR. It turns out that I was using a wrong URL. The DVR/cameras URL should be in this format: rtsp://[username]:[pa... | 4 | 5 |
68,530,363 | 2021-7-26 | https://stackoverflow.com/questions/68530363/opentelemetry-python-how-to-instanciate-a-new-span-as-a-child-span-for-a-given | My goal is to perform tracing of the whole process of my application through several component. I am using GCP and Pub/Sub message queue to communicate information between components (developped in Python). I am currently trying to keep the same root trace between component A and component B by creating a new span as a... | It's called trace context propagation and there are multiple formats such w3c trace context, jaeger, b3 etc... https://github.com/open-telemetry/opentelemetry-specification/blob/b46bcab5fb709381f1fd52096a19541370c7d1b3/specification/context/api-propagators.md#propagators-distribution. You will have to use one of the pr... | 5 | 11 |
68,551,032 | 2021-7-27 | https://stackoverflow.com/questions/68551032/is-there-a-way-to-use-torch-nn-dataparallel-with-cpu | I'm trying to change some PyTorch code so that it can run on the CPU. The model was trained with torch.nn.DataParallel() so when I load the pre-trained model and try using it I must use nn.DataParallel() which I am currently doing like this: device = torch.device("cuda:0") net = nn.DataParallel(net, device_ids=[0]) net... | When you use torch.nn.DataParallel() it implements data parallelism at the module level. According to the doc: The parallelized module must have its parameters and buffers on device_ids[0] before running this DataParallel module. So even though you are doing .to(torch.device('cpu')) it is still expecting to pass the ... | 5 | 10 |
68,552,109 | 2021-7-27 | https://stackoverflow.com/questions/68552109/can-mark-rule-be-extended-outside-the-chart-with-altair | Is there a way to make a rule mark longer without disrupting the axes of a chart? If I have this: random.seed(0) df = pd.DataFrame({'x':[i for i in range(1,21)],'y':random.sample(range(1,50), 20)}) chart = alt.Chart(df).mark_area().encode(x='x',y='y') ruler = alt.Chart(pd.DataFrame({'x':[5]})).mark_rule().encode(x='x')... | You can set an explicit y-domain and then set clip=False inside mark_rule, but you also need to define the y-range of the rule since the default is to stretch over the entire plot: import altair as alt import pandas as pd import random random.seed(0) df = pd.DataFrame({'x':[i for i in range(1,21)],'y':random.sample(ran... | 4 | 2 |
68,551,327 | 2021-7-27 | https://stackoverflow.com/questions/68551327/split-column-of-pandas-dataframe-based-on-multiple-characters | I have a pandas dataframe which looks like this : Un_ID P_ID segment 0 Q8TDU6 7bw0 1( 16- 41), 2( 51- 73), 3( 86- 108) 1 P63092 7bw0 1( 16- 41), 2( 51- 73), 3( 86- 108) 2 Q8TDU6 7cfm 1( 22- 41), 2( 51- 72), 3( 86- 108) I want to split the third column'segment' into three columns i.e TM,starting,ending Un_ID P_ID seg... | Try: import re r = re.compile(r"(\d+)\(\s*(\d+)-\s*(\d+)\)") df["segment"] = df["segment"].apply(lambda x: r.findall(x)) df = df.explode("segment") df[["TM", "starting", "ending"]] = df.pop("segment").apply(pd.Series) df = df.sort_values(by="TM") df["TM"] = "TM" + df["TM"].astype(str) print(df) Prints: Un_ID P_ID TM ... | 4 | 4 |
68,536,546 | 2021-7-26 | https://stackoverflow.com/questions/68536546/using-pipelines-with-a-local-model | I am trying to use a simple pipeline offline. I am only allowed to download files directly from the web. I went to https://huggingface.co/distilbert-base-uncased-finetuned-sst-2-english/tree/main and downloaded all the files in a local folder C:\\Users\\me\\mymodel However, when I tried to load the model I get a strang... | the solution was slightly indirect: load the model on a computer with internet access save the model with save_pretrained() transfer the folder obtained above to the offline machine and point its path in the pipeline call The folder will contain all the expected files. | 5 | 2 |
68,520,738 | 2021-7-25 | https://stackoverflow.com/questions/68520738/identify-index-of-all-elements-in-a-list-comparing-with-another-list | For instance I have a list A: A = [100, 200, 300, 200, 400, 500, 600, 400, 700, 200, 500, 800] And I have list B: B = [100, 200, 200, 500, 600, 200, 500] I need to identify the index of elements in B with comparison to A I have tried: list_index = [A.index(i) for i in B] It returns: [0, 1, 1, 5, 6, 1, 5] But what I... | You can iterate through the enumeration of A to keep track of the indices and yield the values where they match: A = [100,200,300,200,400,500,600,400,700,200,500,800] B = [100,200,200,500,600,200,500] def get_indices(A, B): a_it = enumerate(A) for n in B: for i, an in a_it: if n == an: yield i break list(get_indices(A,... | 16 | 15 |
68,501,158 | 2021-7-23 | https://stackoverflow.com/questions/68501158/python-fetching-urllib3-request-headers | We are injecting tracing information into request headers of all the http request calls in our API client library which is implemented based on urllib3 def _init_jaeger_tracer(): '''Jaeger tracer initialization''' config = Config( config={ 'sampler': { 'type': 'const', 'param': 1, }, }, service_name="session" ) return ... | The documentation of urllib3.response.HTTPResponse says it's: Backwards-compatible with http.client.HTTPResponse [...] That's stdlib class which has getheader method described as: Return the value of the header name, or default if there is no header matching name. If there is more than one header with the name name,... | 6 | 1 |
68,532,800 | 2021-7-26 | https://stackoverflow.com/questions/68532800/pandas-read-excel-parsing-excel-datetime-field-correctly | I have the following sample data stored in Excel file CLAIM CODE1 AGE DATE 7538 359 71 28/11/2019 7538 359 71 28/11/2019 540 428 73 16/10/2019 540 428 73 16/10/2019 605 1670 40 04/12/2019 740 134 55 24/12/2019 When importing to my Jupyter Notebook using the pandas.read_excel API, the date field do... | To convert this Excel Date into datetime64[ns] use to_datetime to get unit in days with offset from origin '1899-12-30': excel = pd.read_excel('Libro.xlsx') excel['DATE'] = pd.to_datetime(excel['DATE'], unit='d', origin='1899-12-30') excel: CLAIM CODE1 AGE DATE 0 7538 359 71 2019-11-28 1 7538 359 71 2019-11-28 2 540 ... | 5 | 14 |
68,521,944 | 2021-7-25 | https://stackoverflow.com/questions/68521944/split-a-multifasta-file-to-files-with-the-same-number-of-accesion-numbers | I have a file that has thousands of accession numbers: and looks like this.. >NC_033829.1 Kallithea virus isolate DrosEU46_Kharkiv_2014, complete genome AGTCAGCAACGTCGATGTGGCGTACAATTTCTTGATTACATTTTTGTTCCTAACAAAATGTTGATATACT >NC_020414.2 Escherichia phage UAB_Phi78, complete genome TAGGCGTGTGTCAGGTCTCTCGGCCTCGGCCTCGCCGG... | It wasn't clear from your question that an "accession number" is unique per input block (don't assume the people reading your question know anything about your domain - it's all just lines of text to us). It would have been clearer if you had phrased your question to just say you want 5000 new-line-separated blocks per... | 5 | 3 |
68,536,339 | 2021-7-26 | https://stackoverflow.com/questions/68536339/numpy-returns-unexpected-results-of-analytical-function | When I try to compute d_j(x), defined below, the algorithm based on Numpy results in unexpected values. I believe it has something to do with numerical precision, but I'm not sure how to solve this. The function is: where and The code fails when j>10. For example, when j=16, the function d_j(x) returns wrong values ... | TL;DR: The problem comes from numerical instabilities. First of all, here is a simplified code on which the exact same problem appear (with different values): x = np.arange(0, 50, 0.1) plt.plot(np.sin(x) - np.sinh(x) - np.cos(x) + np.cosh(x)) plt.show() Here is another example where the problem does not appear: x = np... | 4 | 7 |
68,536,392 | 2021-7-26 | https://stackoverflow.com/questions/68536392/why-does-pytorch-autograd-need-a-scalar | I am working through "Deep Learning for Coders with fastai & Pytorch". Chapter 4 introduces the autograd function from the PyTorch library on a trivial example. x = tensor([3.,4.,10.]).requires_grad_() def f(q): return sum(q**2) y = f(x) y.backward() My question boils down to this: the result of y = f(x) is tensor(125... | TLDR; the derivative of a sum of functions is the sum of their derivatives Let x be your input vector made of x_i (where i in [0,n]), y = x**2 and L = sum(y_i). You are looking to compute dL/dx, a vector of the same size as x whose components are the dL/dx_j (where j in [0,n]). For j in [0,n], dL/dx_j is simply dy_j/dx... | 5 | 4 |
68,533,000 | 2021-7-26 | https://stackoverflow.com/questions/68533000/how-to-attach-a-managed-policy-to-a-an-iam-role-using-the-cdk | I'm try to create a service role for AWS CodeBuild. I can create a role like this: from aws_cdk import aws_iam as iam role = iam.Role( self, 'CodebuildServiceRole', assumed_by=iam.ServicePrincipal('codebuild.amazonaws.com'), max_session_duration=cdk.Duration.hours(1), ) Now I need to attach the Amazon-provided AWSCode... | You can get access to the policy like this: AWSCodeBuildAdminAccess = iam.ManagedPolicy.from_aws_managed_policy_name('AWSCodeBuildAdminAccess') And attach it to your role like this: role.add_managed_policy(AWSCodeBuildAdminAccess) | 4 | 1 |
68,531,077 | 2021-7-26 | https://stackoverflow.com/questions/68531077/python-pandas-how-to-combine-or-merge-two-difrent-size-dataframes-based-on-date | I like to merge or combine two dataframes of different size df1 and df2, based on a range of dates, for example: df1: Date Open High Low 2021-07-01 8.43 8.44 8.22 2021-07-02 8.36 8.4 8.28 2021-07-06 8.22 8.23 8.06 2021-07-07 8.1 8.19 7.98 2021-07-08 8.07 8.1 7.91 2021-07-09 7.97 8.11 7.92 2021-07-12 8 8.2 8 2021-07-13 ... | Try merge_asof #df1.date=pd.to_datetime(df1.date) df1['Day of month'] = df1.Date.dt.day out = pd.merge_asof(df1, df2, on ='Day of month', direction = 'backward') out Out[213]: Date Open High Low Day of month Revenue Earnings 0 2021-07-01 8.43 8.44 8.22 1 45000 4000 1 2021-07-02 8.36 8.40 8.28 2 45000 4000 2 2021-07-06 ... | 5 | 2 |
68,530,492 | 2021-7-26 | https://stackoverflow.com/questions/68530492/create-hierarchy-column-in-pandas | I have got a dataframe like this: part part_parent 0 part1 NaN 1 part2 part1 2 part3 part2 3 part4 part3 4 part5 part2 I need to add an additional column hierarchy like this: part part_parent hierarchy 0 part1 NaN part1 1 part2 part1 part1/part2/ 2 part3 part2 part1/part2/part3/ 3 part4 part3 part1/part2/part3/part4... | Here is a solution using networkx. It treats nan as the root node, and finds the shortest path to each node based on that. import networkx as nx def find_path(net, source, target): # Adjust this as needed (in case multiple paths are present) # or error handling in case a path doesn't exist path = nx.shortest_path(net, ... | 5 | 4 |
68,522,656 | 2021-7-25 | https://stackoverflow.com/questions/68522656/convert-pandas-dataframe-to-a-dictionary-with-first-column-as-key | I have a Pandas Dataframe : A || B || C x1 x [x,y] x2 a [b,c,d] and I am trying to make a dictionary to that looks like: {x1: {B : x, c : [x,y]}, x2: {B: a, C:[b,c,d}} I have tried the to_dict function but that changes the entire dataframe into a dictionary. I am kind of lost on how to iterate onto the first column a... | Try: x = df.set_index("A").to_dict("index") print(x) Prints: {'x1': {'B': 'x', 'C': ['x', 'y']}, 'x2': {'B': 'a', 'C': ['b', 'c', 'd']}} | 6 | 8 |
68,521,514 | 2021-7-25 | https://stackoverflow.com/questions/68521514/how-to-select-another-type-of-font-with-qfont | I am trying to assign different types of text fonts to my application with PyQt5, but I don't know how to assign a different one to the standard one, for example in my application I could only assign it 'Roboto', but if I want to change to Roboto-MediumItalic, I don't know how to specify that font type to it, i'm newbi... | You have to use the styles and QFontDatabase to use Roboto-MediumItalic. You can also set the italic weight style through QFont. import os import sys from pathlib import Path from PyQt5.QtCore import Qt, QDir from PyQt5.QtGui import QFont, QFontDatabase from PyQt5.QtWidgets import QApplication, QLabel CURRENT_DIRECTORY... | 5 | 5 |
68,481,660 | 2021-7-22 | https://stackoverflow.com/questions/68481660/django-admin-page-not-found-in-custom-view | I encountered very annoying problem. I have created my own AdminSite like this: from django.contrib import admin from django.template.response import TemplateResponse from django.urls import path class MyAdminSite(admin.AdminSite): def get_urls(self): urls = super().get_urls() my_urls = [ path('statistics/', self.admin... | Well. I'm going to answer to my own question, in order to help other people. The solution of this problem was to switch returning url addition like this: return my_urls + urls my_urls comes first and the other urls. Why this is happening? Because urls' last path contains some kind of big wildcard url that just overwr... | 7 | 7 |
68,500,704 | 2021-7-23 | https://stackoverflow.com/questions/68500704/why-should-i-use-normalised-units-in-numerical-integration | I was simulating the solar system (Sun, Earth and Moon). When I first started working on the project, I used the base units: meters for distance, seconds for time, and metres per second for velocity. Because I was dealing with the solar system, the numbers were pretty big, for example the distance between the Earth and... | Most, if not all integration modules work best out of the box if: your dynamical variables have the same order of magnitude; that order of magnitude is 1; the smallest time scale of your dynamics also has the order of magnitude 1. This typically fails for astronomical simulations where the orders of magnitude vary an... | 4 | 8 |
68,513,540 | 2021-7-24 | https://stackoverflow.com/questions/68513540/how-to-install-and-run-virtualenv-on-macos-correctly | Hi I'm a beginner of python, I don't remember when and how I installed python3.8 on my Macbook air, only knew the installed path: % which python /usr/bin/python % which python3 /usr/local/bin/python3 The pip command cannot not be found but pip3 is ok. Today I want to install virtaulenv: % sudo -H pip3 install virtuale... | try being explicit in the version of python you are using and install using -m pip instead python3 -m pip install virtualenv python3 -m virtualenv venv # create a new venv in ./venv source ./venv/bin/activate # activate your new venv often times the pip/pip3 just isnt pointing at the same python version you think you ... | 11 | 20 |
68,506,950 | 2021-7-24 | https://stackoverflow.com/questions/68506950/can-you-combine-the-addition-assignment-operator-with-the-walrus-operator | This is the code I write right now: a = 1 if (a := a + 1) == 2: print(a) I am wondering if something like this exists: a = 1 if (a +:= 1) == 2: print(a) | PEP-527 defined the new walrus operator. The section discussing differences between assignment statements and expressions explicitly states: Augmented assignment is not supported: total += tax # Equivalent: (total := total + tax) In the section explaining why = is still necessary with :=, we find: The two forms ... | 10 | 12 |
68,512,089 | 2021-7-24 | https://stackoverflow.com/questions/68512089/statements-must-be-separated-by-newlines-or-semicolons | I'm literally using the same code as the official Betfair Developer example, the only difference is that I'm putting the APP_KEY_HERE and SESSION_TOKEN data. But unlike the site, Visual Studio Code is giving me an error and a crash in the terminal. Terminal response: line 11 print json.dumps(json.loads(response.text),... | In python 3.x, you have to enclose the arguments in (). print(json.dumps(json.loads(response.text), indent=3)) | 15 | 32 |
68,500,213 | 2021-7-23 | https://stackoverflow.com/questions/68500213/some-numbers-are-automatically-formatted-using-rich-console-how-to-prevent-this | The following code from rich.console import Console console = Console() console.print("ciao-16S-123") will print the number 123 highlighted (in blue, in my terminal). This happens on many strings with numbers, what could be the problem that causes this unwanted formatting, and how to prevent it? | As per Rich documentation, "Rich can apply styles to patterns in text which you print() or log(). With the default settings, Rich will highlight things such as numbers, strings, collections, booleans, None, and a few more exotic patterns such as file paths, URLs and UUIDs." You can disable it like this: console.print("... | 11 | 13 |
68,507,229 | 2021-7-24 | https://stackoverflow.com/questions/68507229/how-can-i-remove-www-from-original-url-through-urllib-parse-in-python | Original URL ▶ https://www.exeam.org/index.html I want to extract exeam.org/ or exeam.org from original URL. To do this, I used urllib the most powerful parser in Python that I know, but unfortunately urllib (url.scheme, url.netloc ...) couldn't give me the type of format I wanted. | to extract the domain name from a url using `urllib): from urllib.parse import urlparse surl = "https://www.exam.org/index.html" urlparsed = urlparse(surl) # network location from parsed url print(urlparsed.netloc) # ParseResult Object print(urlparsed) this will give you www.exam.org, but you want to further decompose... | 5 | 7 |
68,506,555 | 2021-7-24 | https://stackoverflow.com/questions/68506555/pandas-if-else-condition-on-multiple-columns | I have a df as: df: col1 col2 col3 col4 col5 0 1.36 4.31 7.66 2 2 1 2.62 3.30 2.48 2 1 2 5.19 3.58 1.62 0 2 3 2.06 3.16 3.50 1 1 4 2.19 2.98 3.38 1 1 I want col6 to return 1 when (col4 > 1 and col5 > 1) else 0 and col7 to return 1 when (col4 > 1 and col5 > 1 and col 4 + col5 > 2) else 0 I am trying df.loc[df['col4'] >... | You can simple use bitwise operators: df['col6'] = ((df["col4"]>1) & (df["col5"]>1))*1 df['col7'] = ((df["col4"]>1) & (df["col5"]>1) & (df['col4']+df['col5']>2))*1 >>> df col1 col2 col3 col4 col5 col6 col7 0 1.36 4.31 7.66 2 2 1 1 1 2.62 3.30 2.48 2 1 0 0 2 5.19 3.58 1.62 0 2 0 0 3 2.06 3.16 3.50 1 1 0 0 4 2.19 2.98 3.... | 4 | 1 |
68,505,320 | 2021-7-23 | https://stackoverflow.com/questions/68505320/what-do-empty-curly-braces-mean-in-a-string | So I have been browsing through online sites to read a file line by line and I come to this part of this code: print("Line {}: {}".format(linecount, line)) I am quite confused as to what is happening here. I know that it is printing something, but it shows: "Line{}" I do not understand what this means. I know that yo... | Empty braces are equivalent to numeric braces numbered from 0: >>> '{}: {}'.format(1,2) '1: 2' >>> '{0}: {1}'.format(1,2) '1: 2' Just a shortcut. But if you use numerals you can control the order: >>> '{1}: {0}'.format(1,2) '2: 1' Or the number of times something is used: >>> '{0}: {0}, {1}: {1}'.format(1,2) '1: 1, 2... | 4 | 4 |
68,505,216 | 2021-7-23 | https://stackoverflow.com/questions/68505216/modulenotfounderror-no-module-named-app-routes | So I'm learning fastapi right now and I was trying to separate my project into multiple files but when I do I get this error. ModuleNotFoundError: No module named 'app.routes' I have read This multiple times and I'm pretty sure I did everything right can anyone tell me what I did wrong? app │ main.py │ __init__.py │ └─... | Your uvicorn command is slightly off. From whatever directory is above app run -- uvicorn app.main:app --reload | 9 | 9 |
68,504,268 | 2021-7-23 | https://stackoverflow.com/questions/68504268/how-to-type-hint-a-tuple-of-callables-when-the-default-is-empty | I'm type hinting like this: some_kwarg: Tuple[Callable] = () but mypy raises error: Incompatible default for argument "some_kwarg" (default has type "Tuple[]", argument has type "Tuple[Callable[..., Any]]") I wouldn't want to put a dummy callable in the default kwarg so what's the right thing to do? | You are type annotating it to accept a tuple of size exactly 1. Use: Tuple[Callable, ...] To indicate a homogeneous tuple of any size. | 4 | 8 |
68,503,708 | 2021-7-23 | https://stackoverflow.com/questions/68503708/convert-a-list-into-a-dict-where-each-key-is-nested-under-the-next-one | I want to convert this list: [1,2,3,4,5] Into this dict: { 1 : { 2 : { 3 : { 4 : 5 }}}} This doesn't sound too complicated but I'm stumped when it's time to assign a value to a key deeper than the surface. I have a recursive function for finding how deep my dictionary goes but I don't know how to tell my algorithm to... | You are looking for a recursive function that builds a dictionary with the first list element as a key and the transformed rest of the list as the value: l = [1, 2, 3, 4, 5] def l2d(l): if len(l) < 2: # Not good raise Exception("The list is too short") if len(l) == 2: # Base case return {l[0]: l[1]} # Recursive case re... | 4 | 6 |
68,498,945 | 2021-7-23 | https://stackoverflow.com/questions/68498945/parsing-yaml-file-with-in-python | How can we parse a file which contains multiple configs and which are separated by --- in python. I've config file which looks like File name temp.yaml %YAML 1.2 --- name: first cmp: - Some: first top: top_rate: 16000 audio_device: "pulse" --- name: second components: - name: second parameters: always_on: true timeout... | Your input is composed of multiple YAML documents. For that you will need yaml.load_all() or better yet yaml.safe_load_all(). (The latter will not construct arbitrary Python objects outside of data-like structures such as list/dict.) import yaml with open('temp.yaml') as f: temp = yaml.safe_load_all(f) As hinted at by... | 5 | 4 |
68,497,930 | 2021-7-23 | https://stackoverflow.com/questions/68497930/attributeerror-dlsymrtld-default-attachdebuggertracing-symbol-not-found | I'm trying to use the debugger in vs code (mac os big sur) with no success. I'm on the m1 macbook air. vs code insiders version. I've tried with all these python interpreters: 3.9.6 - /opt/homebrew/bin/python3 3.9.1 - /usr/local/bin/python3 3.8.2 - /usr/bin/python3 2.7.16 - /usr/bin/python I've tried with this launch.j... | I fixed the same issue I was having by rolling back to the prior version of ms-python.python extension. The problem seems to be in the extension and has yet to be resolved. | 5 | 5 |
68,499,904 | 2021-7-23 | https://stackoverflow.com/questions/68499904/how-to-define-a-python-protocol-that-is-callable-with-any-number-of-keyword-argu | How do I define a Python protocol for a type that is: Callable with any number of keyword arguments of any type that returns a value of a specified type This is my attempt: from typing import Any, Protocol, TypeVar T = TypeVar("T", covariant=True) class Operation(Protocol[T]): def __call__(self, **kwargs: Any) -> T: ... | I can't answer your question about exactly why MyPy isn't happy — but here's a different approach that MyPy does seem to be happy with: from typing import Any, Callable, TypeVar T = TypeVar("T", covariant=True) Operation = Callable[..., T] # some example functions that should be a structural sub-type of "Operation[str]... | 5 | 3 |
68,492,454 | 2021-7-22 | https://stackoverflow.com/questions/68492454/add-new-column-to-numpy-array-as-a-function-of-the-rows | I have a 2D Numpy Array, and I want to apply a function to each of the rows and form a new column (the new first column) with the results. For example, let M = np.array([[1,0,1], [0,0,1]]) and I want to apply the sum function on each row and get array([[2,1,0,1], [1,0,0,1]]) So the first column is [2,1], the sum of t... | You can generally append arrays to each other using np.concatenate when they have similar dimensionality. You can guarantee that sum will retain dimensionality regardless of axis using the keepdims argument: np.concatenate((M.sum(axis=1, keepdims=True), M), axis=1) This is equivalent to np.concatenate((M.sum(1)[:, Non... | 4 | 5 |
68,490,745 | 2021-7-22 | https://stackoverflow.com/questions/68490745/how-to-display-the-full-text-of-a-column-in-pandas | I have a data frame that contains a column with long texts. To demonstrate how it looks (note the ellipses "..." where text should continue): id text group 123 My name is Benji and I ... 2 The above text is actually longer than that phrase. For example it could be: My name is Benji and I am living in Kansas. The act... | You can convert to a list an join with newlines ("\n"): import pandas as pd text = """The bullet pierced the window shattering it before missing Danny's head by mere millimeters. Being unacquainted with the chief raccoon was harming his prospects for promotion. There were white out conditions in the town; subsequently,... | 7 | 2 |
68,489,765 | 2021-7-22 | https://stackoverflow.com/questions/68489765/what-is-the-correct-way-to-calculate-the-norm-1-norm-and-2-norm-of-vectors-in | I have a matrix: t = torch.rand(2,3) print(t) >>>tensor([[0.5164, 0.3651, 0.0882], [0.4488, 0.9824, 0.4067]]) I'm following this introduction to norms and want to try it in PyTorch. It seems like the: norm of a vector is "the size or length of a vector is a nonnegative number that describes the extent of the vector i... | To compute the 0-, 1-, and 2-norm you can either use torch.linalg.norm, providing the ord argument (0, 1, and 2 respectively). Or directly on the tensor: Tensor.norm, with the p argument. Here are the three variants: manually computed, with torch.linalg.norm, and with Tensor.norm. 0-norm >>> x.norm(dim=1, p=0) >>> tor... | 5 | 17 |
68,487,888 | 2021-7-22 | https://stackoverflow.com/questions/68487888/groupby-two-columns-sum-count-and-display-output-values-in-separate-column-pa | I have a dataset, df, where I would like to groupby two columns, take the sum and count of another column as well as list the strings in a separate column Data id date pwr type aa q321 10 hey aa q321 1 hello aa q425 20 hi aa q425 20 no bb q122 2 ok bb q122 1 cool bb q422 5 sure bb q422 5 sure bb q422 5 ok Desired id d... | You can use .GroupBy.transform() to set the values for columns pwr and count. Then .set_index() on the 4 columns except type to get a layout similar to the desired output: df['pwr'] = df.groupby(['id', 'date'])['pwr'].transform('sum') df['count'] = df.groupby(['id', 'date'])['pwr'].transform('count') df.set_index(['id'... | 5 | 3 |
68,476,886 | 2021-7-21 | https://stackoverflow.com/questions/68476886/what-is-the-correct-folder-structure-to-use-for-a-python-project-using-pytest | I try to organized my Python projects using a folder structure. When I need to make tests I use something like the following. . |-- src | |-- b.py | `-- main.py `-- tests `-- test_main.py There is just one big problem with this approach. Pytest won't run if main.py is importing b.py. So far I've tried placing empty __... | Python uses the 'environment variable' PYTHONPATH to look for sources to import code from. By default, the directory you execute a python program is automatically included, but you want to include something like this when you test: PYTHONPATH=$PYTHONPATH,../src python test_main.py This is if you're executing a test fr... | 18 | 4 |
68,483,090 | 2021-7-22 | https://stackoverflow.com/questions/68483090/adding-level-2-index-as-a-sum-of-other-indexes-with-a-condition | I have a df: df = pd.DataFrame.from_dict({('group', ''): {0: 'A', 1: 'A', 2: 'A', 3: 'A', 4: 'A', 5: 'A', 6: 'A', 7: 'A', 8: 'A', 9: 'B', 10: 'B', 11: 'B', 12: 'B', 13: 'B', 14: 'B', 15: 'B', 16: 'B', 17: 'B', 18: 'all', 19: 'all'}, ('category', ''): {0: 'Amazon', 1: 'Apple', 2: 'Facebook', 3: 'Google', 4: 'Netflix', 5... | Solution Drop all in level=0, similarly drop the other unwanted level values in level=1 Calculate the sum on level=0 to aggregate the frame Create Multindex to add the additional level combined in aggregated frame Append and sort the index to maintain the order s = df.drop('all').drop(['Facebook', 'total', 'Total'], ... | 5 | 4 |
68,478,097 | 2021-7-22 | https://stackoverflow.com/questions/68478097/excel-file-format-cannot-be-determined-you-must-specify-an-engine-manually | I am not sure why I am getting this error although sometimes my code works fine! Excel file format cannot be determined, you must specify an engine manually. Here below is my code with steps: 1- list of columns of customers Id: customer_id = ["ID","customer_id","consumer_number","cus_id","client_ID"] 2- The code to fi... | Found it. When an excel file is opened for example by MS excel a hidden temporary file is created in the same directory: ~$datasheet.xlsx So, when I run the code to read all the files from the folder it gives me the error: Excel file format cannot be determined, you must specify an engine manually. When all files are... | 50 | 47 |
68,477,345 | 2021-7-21 | https://stackoverflow.com/questions/68477345/cpu-only-pytorch-is-crashing-with-error-assertionerror-torch-not-compiled-with | I'm trying to run the code from this repository and I need to use Pytorch 1.4.0. I've installed the CPU only version of pytorch with pip install torch==1.4.0+cpu torchvision==0.5.0+cpu -f https://download.pytorch.org/whl/torch_stable.html. I ran the program by doing py -m train_Kfold_CV --device 0 --fold_id 10 --np_dat... | You are using CPU only pytorch, but your code has statement like cr = nn.CrossEntropyLoss(weight=torch.tensor(classes_weights).cuda()) which is trying to move the tensor to GPU. To fix it, remove all the .cuda() operations. | 4 | 5 |
68,473,604 | 2021-7-21 | https://stackoverflow.com/questions/68473604/does-pytorch-support-complex-numbers | Minimum (not) working example kernel = Conv2d(in_channels=1, out_channels=1, kernel_size=(3, 2)) data = torch.rand(1, 1, 100, 100).type(torch.complex64) kernel(data) yields RuntimeError: "unfolded2d_copy" not implemented for 'ComplexDouble' for 64 and 128 bit complex numbers, while for 32 bit, i get RuntimeError: "co... | Currently (@ latest stable version - 1.9.0) Pytorch is missing support for such operations on complex tensors (which are a beta feature). See this feature request at Native implementation of convolution for complex numbers Splitting into convolution on real & image separately, though not ideal, is the way to go for now... | 4 | 2 |
68,471,886 | 2021-7-21 | https://stackoverflow.com/questions/68471886/how-to-add-permissions-to-a-lambda-function-using-the-cdk | I have a Lambda function that utilizes the AWS Python SDK to manage AWS CodeCommit repositories. I create the Lambda function using the CDK like so: from aws_cdk import aws_lambda as _lambda from aws_cdk.aws_lambda_python import PythonFunction service = PythonFunction( self, 'Svc', entry='./path/to', index='file.py', r... | Create an IAM Policy Statement and add it to your Function's role policy: from aws_cdk import aws_iam as iam service.add_to_role_policy(iam.PolicyStatement( effect=iam.Effect.ALLOW, actions=[ 'codecommit:*', ], resources=[ 'arn:aws:codecommit:us-east-1:XXXXXXXXXXXX:*', ], )) | 5 | 10 |
68,472,236 | 2021-7-21 | https://stackoverflow.com/questions/68472236/type-hint-for-callable-that-takes-kwargs | I want to do something like from typing import Callable def a(foo: Callable[[int], None]): foo(b=5) This code works, but gives a warning Unexpected argument. Defining as def a(foo: Callable[[int], None]): foo(5) works with no warnings as expected. How can I pass in an expected argument as a kwarg into a function wit... | The Callable docs say There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types. However they also say Callable[..., ReturnType] (literal ellipsis) can be used to type hint a callable taking any number of arguments and returning ReturnType Applying here, tha... | 21 | 15 |
68,471,392 | 2021-7-21 | https://stackoverflow.com/questions/68471392/can-i-inform-mypy-that-an-expression-will-not-return-an-optional | I have the following code: def extract_table_date(bucket_path: str) -> str: event_date = re.search(r"date=([^/]+)", bucket_path) return event_date.group(1)[0:10].replace("-", "") mypy throws error on the last line: Item "None" of "Optional[Match[str]]" has no attribute "group" I think I can solve that by assigning a... | The thing that's Optional is event_date, because re.search is not guaranteed to return a match. mypy is warning you that this will raise an AttributeError if that's the case. You can tell it "no, I'm very confident that will not be the case" by doing an assert to that effect: def extract_table_date(bucket_path: str) ->... | 12 | 20 |
68,467,015 | 2021-7-21 | https://stackoverflow.com/questions/68467015/how-to-remove-rows-that-contain-nan-in-both-1st-and-3rd-columns | When dataframe is like this, a b c d 0 1.0 NaN 3.0 NaN 1 NaN 6.0 NaN 8.0 2 9.0 NaN NaN NaN 3 13.0 NaN 15.0 16.0 I want to remove rows that contain NaN in both b and d columns. So I want the result to be like this. a b c d 1 NaN 6.0 NaN 8.0 3 13.0 NaN 15.0 16.0 In this situation I can't use df.dropna(thresh=2) becau... | dropna has an additional parameter, how: how{‘any’, ‘all’}, default ‘any’ Determine if row or column is removed from DataFrame, when we have at least one NA or all NA. ‘any’ : If any NA values are present, drop that row or column. ‘all’ : If all values are NA, drop that row or column. If you set it to all, it will onl... | 4 | 6 |
68,464,926 | 2021-7-21 | https://stackoverflow.com/questions/68464926/how-to-test-django-querysets-are-equal-using-pytest-django | What's the best / most readable way to assert two querysets are equal? I've come up with a few solutions: # option 1 assert sorted(qs1.values_list("pk", flat=True)) == sorted(qs2.values_list("pk", flat=True)) # option 2 (need to assert length first because set might remove duplicates) assert len(qs1) == len(qs2) assert... | It's there in the starting lines of the link that you suggested: Assertions All of Django’s TestCase Assertions are available in pytest_django.asserts, e.g. from pytest_django.asserts import assertTemplateUsed Similarly you can use, from pytest_django.asserts import assertQuerysetEqual | 4 | 7 |
68,462,920 | 2021-7-21 | https://stackoverflow.com/questions/68462920/oserror-python-library-not-found-libpython3-9mu-so-1-0-libpython3-9m-so-etc | I am trying to create an executable from a python script, using pyinstaller, and am getting the error seen in the subject line. The particulars: python - version 3.9.2 pyinstaller - version 4 I am running on Debian Linux I evoke pyinstaller as: pyinstaller --onefile pythonfile.py When I looked to see what libpytho... | You need to generate the shared lib using: env PYTHON_CONFIGURE_OPTS="--enable-shared" pyenv install 3.9.2 I'm not sure whether 3.9.2 is working if not try 3.9.0 Official Document Here. | 4 | 12 |
68,436,658 | 2021-7-19 | https://stackoverflow.com/questions/68436658/mypy-says-request-json-returns-optionalany-how-do-i-solve | I am trying to understand mypy a little better. For the following line of code: request_body: dict = {} request_body = request.get_json() mypy returns an error: error: Incompatible types in assignment (expression has type "Optional[Any]", variable has type "Dict[Any, Any]") What is the correct fix for this? | As you can see in the following code, taken from /wekzeug/wrappers/request.py, the function get_json doesn't always return a dictionary. I would suggest removing the type hinting from the variable, as it can be None or a dictionary. def get_json( self, force: bool = False, silent: bool = False, cache: bool = True ) -> ... | 6 | 3 |
68,415,049 | 2021-7-16 | https://stackoverflow.com/questions/68415049/annotate-a-tuple-with-variable-number-of-items-and-first-item-is-of-different-ty | A few valid values for a tuple that I'm trying to annotate: ("foo", 1, 2) ("bar", 11) ("baz", 42, 31, 20, 0, -700, 44444, 12345, 1, 2, 3, 4, 5, 6, 7, 8, 9) I was expecting this to work: my_tuple: Tuple[str, int, ...] # doesn't work! ... but that throws error: Unexpected '...' Any way to annotate this structure? | In Python 3.11 I can now do the following: my_tuple: tuple[str, *tuple[int, ...]] = ("foo", 1, 2) This was added in PEP 646 For Python pre-3.11 (courtesy of @FMeinicke) typing_extensions.Unpack can be used instead [1,2,3]. from typing_extensions import Unpack my_tuple: tuple[str, Unpack[tuple[int, ...]]] = ("foo", 1,... | 7 | 3 |
68,381,971 | 2021-7-14 | https://stackoverflow.com/questions/68381971/how-to-use-postgresqls-stored-procedures-or-functions-in-django-project | I am working on one Django project. And I decided to write logic code in PostgreSQL instead of writing in Python. So, I created a stored procedure in PostgreSQL. For example, a stored procedure looks like this: create or replace procedure close_credit(id_loan int) language plpgsql as $$ begin update public.loan_loan se... | I'd recommend storing the procedure definition in a migration file. For example, in the directory myapp/migrations/sql.py: from django.db import migrations SQL = """ CREATE PROCEDURE close_credit(id_loan int) language plpgsql AS $$ BEGIN UPDATE public.loan_loan SET sum = 0 WHERE id = id_loan; COMMIT; END; $$ """ class ... | 10 | 16 |
68,461,626 | 2021-7-20 | https://stackoverflow.com/questions/68461626/how-to-fix-unterminated-expression-in-f-string-missing-close-brace-in-python | I want to use f string formatting instead of print. However, I get these errors: Unterminated expression in f-string; missing close brace Expected ')' var="ab-c" f"{var.replace("-","")}text123" I tried to use single quote f'' and also double brackets but neither of them worked. Any idea about how to fix this? | Before Python 3.12: For f"{var.replace("-","")}text123", Python parses f"{var.replace(" as a complete string, which you can see has an opening { and opening (, but then the string is terminated. It first expected a ) and eventually a }, hence the error you see. To fix it, Python allows ' or " to enclose a string, so us... | 15 | 36 |
68,396,962 | 2021-7-15 | https://stackoverflow.com/questions/68396962/how-to-split-strings-in-c-like-in-python | so in python you can split strings like this: string = "Hello world!" str1 , str2 = string.split(" ") print(str1);print(str2) and it prints: Hello world! How can i do the same in C++? This wasn't useful Parse (split) a string in C++ using string delimiter (standard C++) , i need them splited so i can acces them separ... | If your tokenizer is always a white space (" ") and you might not tokenize the string with other characters (e.g. s.split(',')), you can use string stream: #include <iostream> #include <string> #include <sstream> int main() { std::string my_string = " Hello world! "; std::string str1, str2; std::stringstream s(my_strin... | 9 | 9 |
68,375,767 | 2021-7-14 | https://stackoverflow.com/questions/68375767/how-can-i-use-databricks-utils-functions-in-pycharm-i-cant-find-appropriate-pi | PyCharm IDE. I want to use dbutils.widgets.get() in a module and than to import this module to databricks. I already tried with pip install databricks-client pip install databricks-utils and pip install DBUtils | The dbutils is available only as a part of the databricks-connect package. Its documentation contains detailed description on how to setup PyCharm to work with it. It also covers on how to use the dbutils. You may need to define following wrapper to be able to use dbutils locally and on Databricks: def get_dbutils(spar... | 8 | 7 |
68,417,319 | 2021-7-17 | https://stackoverflow.com/questions/68417319/initialize-python-dataclass-from-dictionary | Let's say I want to initialize the below dataclass from dataclasses import dataclass @dataclass class Req: id: int description: str I can of course do it in the following way: data = make_request() # gives me a dict with id and description as well as some other keys. # {"id": 123, "description": "hello", "data_a": "",... | Here's a solution that can be used generically for any class. It simply filters the input dictionary to exclude keys that aren't field names of the class with init==True: from dataclasses import dataclass, fields @dataclass class Req: id: int description: str def classFromArgs(className, argDict): fieldSet = {f.name fo... | 27 | 17 |
68,434,953 | 2021-7-19 | https://stackoverflow.com/questions/68434953/how-to-force-translate-i18n-in-some-specific-text-variable-in-vuejs | In normal context, we just attach translation property to a variable like : this.name = this.$t('language.name'); But I want to specific it in a specific language sometime( ex: in French). Can we do something like this in vue.js ? this.name = this.$t('language.name', locale: fr); | Using the old package kazupon/vue-i18n, the following should be possible: $t(key, locale) When using the successor-package intlify/vue-i18n-next, the answer depends on if you are using Vue I18n's Legacy API or the newer Composition API: Using Legacy API as described in the normal setup guide the usages of the t() fu... | 7 | 7 |
68,417,682 | 2021-7-17 | https://stackoverflow.com/questions/68417682/qt-and-opencv-app-not-working-in-virtual-environment | I created a GUI app using pyqt5 and opencv. The app works fine without activating the virtual env but when I activate the virtual env and run the app it shows this error: QObject::moveToThread: Current thread (0x125b2f0) is not the object's thread (0x189e780). Cannot move to target thread (0x125b2f0) qt.qpa.plugin: Cou... | The problem is that the version of Qt with which opencv was compiled is not similar to the one used by PyQt5 causing a conflict. A possible solution is to indicate to use the Qt plugins used by PyQt5. import os from pathlib import Path import PyQt5 from PyQt5.QtWidgets import QWidget # others imports import cv2 os.envi... | 6 | 18 |
68,446,642 | 2021-7-19 | https://stackoverflow.com/questions/68446642/how-do-i-get-pylance-to-ignore-the-possibility-of-none | I love Pylance type checking. However, If I have a variable var: Union[None, T], where T implements foo, pylance will throw an error at: var.foo() since type None doesn't implement foo. Is there any way to resolve this? A way to tell Pylance "This variable is None sometimes but in this case I'm 100% sure it will be ass... | There are many ways of forcing a type-checker to accept this. Use assert: from typing import Union def do_something(var: Union[T, None]): assert var is not None var.foo() Raise some other exception: from typing import Union def do_something(var: Union[T, None]): if var is None: raise RuntimeError("NO") var.foo() ... | 53 | 83 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.