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 |
|---|---|---|---|---|---|---|
60,289,195 | 2020-2-18 | https://stackoverflow.com/questions/60289195/open-cv-trivial-circle-detection-how-to-get-least-squares-instead-of-a-contou | My goal is to accurately measure the diameter of a hole from a microscope. Workflow is: take an image, process for fitting, fit, convert radius in pixels to mm, write to a csv This is an output of my image processing script used to measure the diameter of a hole. I'm having an issue where it seems like my circle fitti... | Here is another way to fit a circle by getting the equivalent circle center and radius from the binary image using connected components and drawing a circle from that using Python/OpenCV/Skimage. Input: import cv2 import numpy as np from skimage import measure # load image and set the bounds img = cv2.imread("dark_cir... | 7 | 5 |
60,289,768 | 2020-2-18 | https://stackoverflow.com/questions/60289768/error-unhashable-type-dict-with-dataclass | I have a class Table: @dataclass(frozen=True, eq=True) class Table: name: str signature: Dict[str, Type[DBType]] prinmary_key: str foreign_keys: Dict[str, Type[ForeignKey]] indexed: List[str] And need to create such dictionary: table = Table(*args) {table: 'id'} TypeError: unhashable type: 'dict' Don't understand ... | The autogenerated hash method isn't safe, since it tries to hash the unhashable attributes signature, primary_key, and indexed. You need to define your own __hash__ method that ignores those attributes. One possibility is def __hash__(self): return hash((self.name, self.primary_key)) Both self.name and self.primary_ke... | 8 | 15 |
60,285,688 | 2020-2-18 | https://stackoverflow.com/questions/60285688/python-typehint-for-os-getenv-causes-downstream-incompatible-type-errors | When using os.getenv to retrieve environment variables, the default behavior returns a type of Optional[str]. This is problematic as any downstream methods/functions that utilize these variables will likely be defined to accept a str type explicitly. Is there an accepted usage to get around this issue or enforce the st... | tl;dr Use os.environ['SOME_VAR'] if you're sure it's always there os.getenv can and does return None -- mypy is being helpful in showing you have a bug there: >>> repr(os.getenv('DOES_NOT_EXIST')) 'None' >>> repr(os.getenv('USER')) "'asottile'" Alternatively, you can convince mypy that it is of the type you expect in... | 10 | 13 |
60,241,138 | 2020-2-15 | https://stackoverflow.com/questions/60241138/animation-of-tangent-line-of-a-3d-curve | I am writing a Python program to animate a tangent line along a 3D curve. However, my tangent line is not moving. I think the problem is line.set_data(np.array(Tangent[:,0]).T,np.array(Tangent[:,1]).T) in animate(i) but I can't figure out. Any help will be appreciated. The following is the code. from mpl_toolkits impo... | you've called the wrong function in animate: Replace line.set_data(...) with line.set_data_3d(Tangent[0], Tangent[1], Tangent[2]) and it will work. There are still some minor issues in the code (e.g., don't use len as a variable name). I'd recommend using the following: #!/usr/bin/env python3 from mpl_toolkits import m... | 7 | 4 |
60,281,354 | 2020-2-18 | https://stackoverflow.com/questions/60281354/apply-minmaxscaler-on-multiple-columns-in-pyspark | I want to apply MinMaxScalar of PySpark to multiple columns of PySpark data frame df. So far, I only know how to apply it to a single column, e.g. x. from pyspark.ml.feature import MinMaxScaler pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]}) df = spark.createDataFrame(pdf) scaler = MinMaxScaler(inpu... | Question 1: How to change your example to run properly. You need to prepare the data as a vector for the transformers to work. from pyspark.ml.feature import MinMaxScaler from pyspark.ml import Pipeline from pyspark.ml.linalg import VectorAssembler pdf = pd.DataFrame({'x':range(3), 'y':[1,2,5], 'z':[100,200,1000]}) df ... | 19 | 24 |
60,280,466 | 2020-2-18 | https://stackoverflow.com/questions/60280466/merging-two-dataframes-with-pd-na-in-merge-column-yields-typeerror-boolean-val | With Pandas 1.0.1, I'm unable to merge if the df = df.merge(df2, on=some_column) yields File /home/torstein/code/fintechdb/Sheets/sheets/gild.py, line 42, in gild df = df.merge(df2, on=some_column) File /home/torstein/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py, line 7297, in merge validate=validate, F... | This has to do with pd.NA being implemented in pandas 1.0.0 and how the pandas team decided it should work in a boolean context. Also, you take into account it is an experimental feature, hence it shouldn't be used for anything but experimenting: Warning Experimental: the behaviour of pd.NA can still change without wa... | 11 | 13 |
60,273,813 | 2020-2-18 | https://stackoverflow.com/questions/60273813/what-is-runtime-in-context-of-python-what-does-it-consist-of | In context to this question What is “runtime”? (https://stackoverflow.com/questions/3900549/what-is-runtime/3900561) I am trying to understand what would a python runtime be made of. My guess is: The python process that contains all runtime variables. The GIL The underlying interpreter code (CPython etc.). Now if th... | You are talking about two different (yet similar) concepts in computer science; multiprocess, and multithreading. Here is some compilation of questions/answers that might be useful: Multiprocessing -- Wikipedia Multiprocessing is the use of two or more central processing units (CPUs) within a single computer system.... | 7 | 18 |
60,270,639 | 2020-2-17 | https://stackoverflow.com/questions/60270639/python-mocking-sqlalchemy-connection | I have a simple function that connects to a DB and fetches some data. db.py from sqlalchemy import create_engine from sqlalchemy.pool import NullPool def _create_engine(app): impac_engine = create_engine( app['DB'], poolclass=NullPool # this setting enables NOT to use Pooling, preventing from timeout issues. ) return i... | Another option would be to mock your _create_engine function. Since this is a unit test and we want to test get_all_pos we shouldn't need to rely on the behavior of _create_engine, so we can just patch that like so. import unittest import db from unittest.mock import patch class TestPosition(unittest.TestCase): @patch.... | 9 | 5 |
60,266,554 | 2020-2-17 | https://stackoverflow.com/questions/60266554/type-object-datetime-datetime-has-no-attribute-fromisoformat | I have a script with the following import: from datetime import datetime and a piece of code where I call: datetime.fromisoformat(duedate) Sadly, when I run the script with an instance of Python 3.6, the console returns the following error: AttributeError: type object 'datetime.datetime' has no attribute 'fromisofor... | The issue here is actually that fromisoformat is not available in Python versions older than 3.7, you can see that clearly stated in the documenation here. Return a date corresponding to a date_string given in the format YYYY-MM-DD: >>> >>> from datetime import date >>> date.fromisoformat('2019-12-04') datetime.date(20... | 46 | 59 |
60,264,419 | 2020-2-17 | https://stackoverflow.com/questions/60264419/does-it-make-sense-to-use-sklearn-gridsearchcv-together-with-calibratedclassifie | What I want to do is to derive a classifier which is optimal in its parameters with respect to a given metric (for example the recall score) but also calibrated (in the sense that the output of the predict_proba method can be directly interpreted as a confidence level, see https://scikit-learn.org/stable/modules/calibr... | Yes you can do this and it would work. I don't know if it makes sense to do this, but the least I can do is explain what I believe would happen. We can compare doing this to the alternative which is getting the best estimator from the grid search and feeding that to the calibration. Simply getting the best estimator a... | 8 | 7 |
60,264,393 | 2020-2-17 | https://stackoverflow.com/questions/60264393/pandas-copy-value-from-one-column-to-another-if-condition-is-met | I have a dataframe: df = col1 col2 col3 1 2 3 1 4 6 3 7 2 I want to edit df, such that when the value of col1 is smaller than 2 , take the value from col3. So I will get: new_df = col1 col2 col3 3 2 3 6 4 6 3 7 2 I tried to use assign and df.loc but it didn't work. What is the best way to do so? | df['col1'] = df.apply(lambda x: x['col3'] if x['col1'] < x['col2'] else x['col1'], axis=1) | 17 | 16 |
60,257,856 | 2020-2-17 | https://stackoverflow.com/questions/60257856/is-data-safety-guaranteed-while-using-threadpoolexecutor-from-pythons-future | I'm looking for a conceptual answer on this question. I'm wondering whether using ThreadPool in python to perform concurrent tasks, guarantees that data is not corrupted; I mean multiple threads don't access the critical data at the same time. If so, how does this ThreadPoolExecutor internally works to ensure that crit... | Thread pools do not guarantee that shared data is not corrupted. Threads can swap at any byte code execution boundary and corruption is always a risk. Shared data should be protected by synchronization resources such as locks, condition variables and events. See the threading module docs concurrent.futures.ThreadPoolEx... | 7 | 8 |
60,248,740 | 2020-2-16 | https://stackoverflow.com/questions/60248740/how-to-set-navigator-webdriver-to-undefined-with-selenium-for-firefox-geckodriv | I am trying to set the navigator.webdriver variable in the Firefox browser to undefined using Selenium in Python. I have been able to successfully do this when using Chrome, but now I need to do the same thing using in Firefox. When using the Firefox webdriver, execute_cdp_cmd(...) does not exist. Does anyone know how ... | I have since found a solution to my problem. The code below will set "navigator.webdriver" to undefined in a Firefox browser being run by Selenium. profile.set_preference("dom.webdriver.enabled", False) | 8 | 5 |
60,220,751 | 2020-2-14 | https://stackoverflow.com/questions/60220751/is-there-a-way-to-take-screen-shots-of-desktop-that-not-current-active-one-using | I'm trying to record screen when playing a website by using mss and opencv, but I don't want the program to use the current screen. I want to put them to play on a second desktop, like Desktop 2 in the following picture macos have 4 desktop setup so I can work in the desktop 1 without any interruption. | Currently, MSS does not support capturing inactive workspaces. This Ask Ubuntu answer indicates (referencing a post on an "archived" (i.e. apparently deleted) forum) that this is not normally possible in the X Window System.1 The answer discusses using Xvfb as a workaround, but this does not appear to be useful for scr... | 7 | 6 |
60,246,570 | 2020-2-16 | https://stackoverflow.com/questions/60246570/gensim-lda-coherence-score-nan | I created a Gensim LDA Model as shown in this tutorial: https://www.machinelearningplus.com/nlp/topic-modeling-gensim-python/ lda_model = gensim.models.LdaMulticore(data_df['bow_corpus'], num_topics=10, id2word=dictionary, random_state=100, chunksize=100, passes=10, per_word_topics=True) And it generates 10 topics wit... | Solved! Coherence Model requires the original text, instead of the training corpus fed to LDA_Model - so when i ran this: coherence_model_lda = CoherenceModel(model=lda_model, texts=data_df['corpus'].tolist(), dictionary=dictionary, coherence='c_v') with np.errstate(invalid='ignore'): lda_score = coherence_model_lda.ge... | 8 | 12 |
60,243,099 | 2020-2-15 | https://stackoverflow.com/questions/60243099/what-is-the-meaning-of-the-second-output-of-huggingfaces-bert | Using the vanilla configuration of base BERT model in the huggingface implementation, I get a tuple of length 2. import torch import transformers from transformers import AutoModel,AutoTokenizer bert_name="bert-base-uncased" tokenizer = AutoTokenizer.from_pretrained(bert_name) BERT = AutoModel.from_pretrained(bert_name... | The output in this case is a tuple of (last_hidden_state, pooler_output). You can find documentation about what the returns could be here. | 7 | 8 |
60,238,433 | 2020-2-15 | https://stackoverflow.com/questions/60238433/what-is-the-meaning-of-pydantic-modelsschemas-in-python-while-building-an-api | I am new at python, and I am trying to build an API with FastAPI.It's working so far, I connected with postgres db, I made post/get/ request and everything is working, but I don't have good understanding why we define the schemas like this, why do we have to create an class UserBase(BaseModel) class UserCreate(UserBas... | Pydantic schemas define the properties and types to validate some payload. They act like a guard before you actually allow a service to fulfil a certain action (e.g. create a database object). I'm not sure if you're used to serializers, but it's pretty much the same thing except Pydantic and FastAPI integrate with new... | 13 | 11 |
60,226,848 | 2020-2-14 | https://stackoverflow.com/questions/60226848/array-does-not-have-indent-or-space-in-pyyaml | In the code below I created the net_plan_dict variable dictionary and converted it into a YAML format file. Inside the dictionary I have a field called addresses which is an array of three elements. After creating the YAML file, the three array elements were not placed under the addresses field : import yaml net_plan_d... | PyYAML's dump() doesn't have the fine control to have a different indent for the mappings (2 positions) and sequences (4 positions), nor can it offset the sequence indicator (-) within the space of the (sequence) indent). If you want that kind of control over your output you should use ruamel.yaml (disclaimer: I am the... | 8 | 4 |
60,226,557 | 2020-2-14 | https://stackoverflow.com/questions/60226557/how-to-forcefully-close-an-async-generator | Let's say I have an async generator like this: async def event_publisher(connection, queue): while True: if not await connection.is_disconnected(): event = await queue.get() yield event else: return I consume it like this: published_events = event_publisher(connection, queue) async for event in published_events: # do ... | It seems to be related to this issue. Noticable: As shown in https://gist.github.com/1st1/d9860cbf6fe2e5d243e695809aea674c, it's an error to close a synchronous generator while it is being iterated. ... In 3.8, calling "aclose()" can crash with a RuntimeError. It's no longer possible to reliably cancel a running async... | 13 | 7 |
60,227,582 | 2020-2-14 | https://stackoverflow.com/questions/60227582/making-a-python-test-think-an-installed-package-is-not-available | I have a test that makes sure a specific (helpful) error message is raised, when a required package is not available. def foo(caller): try: import pkg except ImportError: raise ImportError(f'Install "pkg" to use {caller}') pkg.bar() with pytest.raises(ImportError, match='Install "pkg" to use test_function'): foo('test_... | I ended up with the following pytest-only solution, which appears to be more robust in the setting of a larger project. import builtins import pytest @pytest.fixture def hide_available_pkg(monkeypatch): import_orig = builtins.__import__ def mocked_import(name, *args, **kwargs): if name == 'pkg': raise ImportError() ret... | 8 | 6 |
60,211,248 | 2020-2-13 | https://stackoverflow.com/questions/60211248/sort-a-list-by-presence-of-items-in-another-list | Suppose I have two lists: a = ['30', '10', '90', '1111', '17'] b = ['60', '1201', '30', '17', '900'] How would you sort this most efficiently, such that: list b is sorted with respect to a. Unique elements in b should be placed at the end of the sorted list. Unique elements in a can be ignored. example output: c = ['3... | There is no need to actually sort here. You want the elements in a which are in b, in the same order as they were in a; followed by the elements in b which are not in a, in the same order as they were in b. We can just do this with two filters, using the sets for fast membership tests: >>> a = ['30', '10', '90', '1111'... | 7 | 7 |
60,226,735 | 2020-2-14 | https://stackoverflow.com/questions/60226735/how-to-count-overlapping-datetime-intervals-in-pandas | I have a following DataFrame with two datetime columns: start end 0 01.01.2018 00:47 01.01.2018 00:54 1 01.01.2018 00:52 01.01.2018 01:03 2 01.01.2018 00:55 01.01.2018 00:59 3 01.01.2018 00:57 01.01.2018 01:16 4 01.01.2018 01:00 01.01.2018 01:12 5 01.01.2018 01:07 01.01.2018 01:24 6 01.01.2018 01:33 01.01.2018 01:38 7... | Use Series.cumsum with Series.map (or Series.replace): new_df = df.melt(var_name = 'status',value_name = 'time').sort_values('time') new_df['counter'] = new_df['status'].map({'start':1,'end':-1}).cumsum() print(new_df) status time counter 0 start 2018-01-01 00:47:00 1 1 start 2018-01-01 00:52:00 2 11 end 2018-01-01 00:... | 8 | 10 |
60,214,658 | 2020-2-13 | https://stackoverflow.com/questions/60214658/patching-an-object-by-reference-rather-than-by-name-string | The most common way to patch something in a module seems to be to use something like from unittest.mock import patch from mypackage.my_module.my_submodule import function_to_test @patch('mypackage.my_module.my_submodule.fits.open') def test_something(self, mock_fits_open) # ... mock_fits_open.return_value = some_return... | Patching works by replacing in the namespace where the name is looked up. The underlying logic of mock.patch is essentially working with a context-managed name shadowing. You could do the same thing manually with: save original value associated with name (if any) try overwriting the name execute the code under test fi... | 7 | 3 |
60,206,006 | 2020-2-13 | https://stackoverflow.com/questions/60206006/where-does-zappa-upload-environment-variables-to | tl;dr Environment variables set in a zappa_settings.json don't upload as environment variables to AWS Lambda. Where do they go? ts;wm I have a Lambda function configured, deployed and managed using the Zappa framework. In the zappa_settings.json I have set a number of environment variables. These variables are definite... | environment_variables are saved in zappa_settings.py when creating a package for deployment (run zappa package STAGE and explore the archive) and are then dynamically set as environment variables by modifying os.environ in handler.py. To set native AWS variables you need to use aws_environment_variables. | 9 | 10 |
60,202,691 | 2020-2-13 | https://stackoverflow.com/questions/60202691/python-typing-declare-return-value-type-based-on-function-argument | Suppose I have function that takes type as argument and returns instance of that type: def fun(t): return t(42) Then I can call it and get objects of provided types: fun(int) # 42 fun(float) # 42.0 fun(complex) # (42+0j) fun(str) # "42" fun(MyCustomType) # something That list is not exhaustive, I'd like to be able to... | TLDR: You need a TypeVar for the return type of calling t: def fun(t: Callable[[int], R]) -> R: ... Constraining on a type is too restrictive here. The function accepts any Callable that takes an integer, and the return type of the function is that of the Callable. This can be specified using a TypeVar for the return... | 23 | 16 |
60,197,665 | 2020-2-12 | https://stackoverflow.com/questions/60197665/opencv-how-to-use-floodfill-with-rgb-image | I am trying to use floodFill on an image like below to extract the sky: But even when I set the loDiff=Scalar(0,0,0) and upDiff=Scalar(255,255,255) the result is just showing the seed point and does not grow larger (the green dot): code: Mat flood; Point seed = Point(180, 80); flood = imread("D:/Project/data/1.jpeg")... | You need to set loDiff and upDiff arguments correctly. See floodFill documentation: loDiff – Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. upDiff – Maximal upper brightness/color differ... | 7 | 4 |
60,189,415 | 2020-2-12 | https://stackoverflow.com/questions/60189415/black-python-ignore-rule | I feel Black is doing something not compliant (with my Organisation), so I am trying to ignore certain rules. Example below and a related link PEP 8: whitespace before ':' My Organisation (Coding Standards) does not give priority to what Black feels is right, but wants a way to customise black configurations. I dont s... | You can't customize black. From the readme: Black reformats entire files in place. It is not configurable. | 15 | 12 |
60,180,101 | 2020-2-12 | https://stackoverflow.com/questions/60180101/validate-list-in-marshmallow | currently I am using marshmallow schema to validate the request, and I have this a list and I need to validate the content of it. class PostValidationSchema(Schema): checks = fields.List( fields.String(required=True) ) the checks field is a list it should only contain these specific values ["booking", "reservation", "... | If you mean to check the list only has those three elements in that order, then use Equal validator. from marshmallow import Schema, fields, validate class PostValidationSchema(Schema): checks = fields.List( fields.String(required=True), validate=validate.Equal(["booking", "reservation", "flight"]) ) schema = PostValid... | 7 | 12 |
60,182,065 | 2020-2-12 | https://stackoverflow.com/questions/60182065/django-structlog-is-not-printing-or-writing-log-message-to-console-or-file | I have installed django-structlog 1.4.1 for my Django project. I have followed all the steps which has been described in that link. In my settings.py file: import structlog MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.C... | I haven't used django-structlog (but written structlog 🤓) and this looks like django_structlog_demo_project is not the name of the logger of your application and hence the settings don't apply (default log level is INFO). You can either fix the name or since your configurations are identical, I would suggest to delete... | 8 | 19 |
60,179,799 | 2020-2-12 | https://stackoverflow.com/questions/60179799/python-dataclass-whats-a-pythonic-way-to-validate-initialization-arguments | What's a pythonic way to validate the init arguments before instantiation w/o overriding dataclasses built-in init? I thought perhaps leveraging the __new__ dunder-method would be appropriate? from dataclasses import dataclass @dataclass class MyClass: is_good: bool = False is_bad: bool = False def __new__(cls, *args... | Define a __post_init__ method on the class; the generated __init__ will call it if defined: from dataclasses import dataclass @dataclass class MyClass: is_good: bool = False is_bad: bool = False def __post_init__(self): if self.is_good: assert not self.is_bad This will even work when the replace function is used to ma... | 35 | 62 |
60,175,608 | 2020-2-11 | https://stackoverflow.com/questions/60175608/visual-studio-code-and-jinja-templates | I use VS code since a while with some Extensions. All is perfect expect when I use Flask. Prettier put all flask code glued together, and intellisence is not working with flask code: {% extends "layout.html" %} {% block style %} body {color: red; } {% endblock %} {% block body %} you must provide a name {% endblock %} ... | Batteries included solution Here is a solution that gives you code highlighting, tag-autocompletion and customizable auto-formatting: Install Better Jinja or Django (better syntax highlighting within double quotes) plugin Install djLint plugin Press CTRL + Shift + P and type open settings json + Enter This is my conf... | 39 | 21 |
60,131,839 | 2020-2-8 | https://stackoverflow.com/questions/60131839/violin-plot-troubles-in-python-on-log-scale | My violin plots are showing weird formats when using a log scale on my plots. I've tried using matplotlib and seaborn and I get very similar results. import matplotlib.pyplot as plt import seaborn as sns data = [[1e-05, 0.00102, 0.00498, 0.09154, 0.02009, 1e-05, 0.06649, 0.42253, 0.02062, 0.10812, 0.07128, 0.03903, 0.... | New way, seaborn 0.13, parameter log_scale Seaborn version 0.13 introduces a new parameter log_scale. This enables the kde curve can be calculated directly in log space. Here is how it looks with the given data: import matplotlib.pyplot as plt import seaborn as sns import numpy as np data = [[1e-05, 0.00102, 0.00498, 0... | 12 | 15 |
60,169,996 | 2020-2-11 | https://stackoverflow.com/questions/60169996/does-a-with-statement-support-type-hinting | Can you define the type hint for a variable defined with the with syntax? with example() as x: print(x) I would like to type hint the above to say that x is a str (as an example). The only work around that I've found is to use an intermediate variable, but this feels hacky. with example() as x: y: str = x print(y) I ... | PEP 526, which has been implemented in Python 3.6, allows you to annotate variables. The variable used in a with statement can be annotated like this: x: str with example() as x: [...] | 56 | 73 |
60,092,641 | 2020-2-6 | https://stackoverflow.com/questions/60092641/mad-results-differ-in-pandas-scipy-and-numpy | I want to compute the MAD (median absolute deviation) which is defined by MAD = median(|x_i - mean(x)|) for a list of numbers x x = list(range(0, 10)) + [1000] However, the results differ significantly using numpy, pandas, and an hand-made implementation: from scipy import stats import pandas as pd import numpy as n... | The median absolute deviation is defined as: median(|x_i - median(x)| The method mad in Pandas returns the mean absolute deviation instead. You can calculate MAD using following methods: x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1000] stats.median_absolute_deviation(x, scale=1) # 3.0 np.median(np.absolute(x - np.median(x))) ... | 10 | 23 |
60,137,572 | 2020-2-9 | https://stackoverflow.com/questions/60137572/issues-installing-pytorch-1-4-no-matching-distribution-found-for-torch-1-4 | Used the install guide on pytorch.org on how to install it and the command I'm using is pip install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html But it's coming up with this error; ERROR: Could not find a version that satisfies the requirement torch===1.4.0 (from versions: 0... | Looks like this issue is related to virtual environment. Did you try recommended installation line in another/new one virtual environment? If it doesn't help the possible solution might be installing package using direct link to PyTorch and TorchVision builds for your system: Windows: pip install https://download.pytor... | 46 | 31 |
60,127,234 | 2020-2-8 | https://stackoverflow.com/questions/60127234/how-to-use-a-pydantic-model-with-form-data-in-fastapi | I am trying to submit data from HTML forms and validate it with a Pydantic model. Using this code from fastapi import FastAPI, Form from pydantic import BaseModel from starlette.responses import HTMLResponse app = FastAPI() @app.get("/form", response_class=HTMLResponse) def form_get(): return '''<form method="post"> <i... | I found a solution that can help us to use Pydantic with FastAPI forms :) My code: class AnyForm(BaseModel): any_param: str any_other_param: int = 1 @classmethod def as_form( cls, any_param: str = Form(...), any_other_param: int = Form(1) ) -> AnyForm: return cls(any_param=any_param, any_other_param=any_other_param) @r... | 56 | 73 |
60,158,087 | 2020-2-10 | https://stackoverflow.com/questions/60158087/youtubedl-certificate-verify-failed | I ran this code in Python: from __future__ import unicode_literals import youtube_dl ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download(['YOUTUBE URL']) I was hopin... | Add the no-check-certificate parameter to the command: youtube-dl --no-check-certificate This option was renamed to --no-check-certificates starting with version 2021.10.09 (inclusive). | 30 | 99 |
60,154,404 | 2020-2-10 | https://stackoverflow.com/questions/60154404/is-there-the-equivalent-of-to-markdown-to-read-data | With pandas 1.0.0 the use of .to_markdown() to show the content of a dataframe in this forum in markdown is going to proliferate. Is there a convenient way to load the data back into a dataframe? Maybe an option to .from_clipboard(markdown=True)? | None of the answers so far read the data from the clipboard. They all require the data to be in a string. This led me to look into the source code of pandas.read_clipboard(), and lo and behold, the method internally uses pandas.read_csv(), and passes all arguments to it. This automatically leads to the following soluti... | 22 | 4 |
60,095,520 | 2020-2-6 | https://stackoverflow.com/questions/60095520/understanding-contour-hierarchies-how-to-distinguish-filled-circle-contour-and | I am unable to differentiate between the below two contours. cv2.contourArea() is giving the same value for both. Is there any function to distinguish them in Python? How do I use contour hierarchies to determine the difference? | To distinguish between a filled contour and unfilled contour, you can use contour hierarchy when finding contours with cv2.findContours(). Specifically, you can select the contour retrieval mode to optionally return an output vector containing information about the image topology. There are the four possible modes: cv... | 8 | 23 |
60,150,956 | 2020-2-10 | https://stackoverflow.com/questions/60150956/attaching-python-script-while-building-r-package | I have not found some R package ( there is no one, trust me) for my tasks, but there is one in python. So i wrote python script and used reticulaye::py_run_file('my_script.py') in some functions. But after building and installation, package can't find that script. Where should i put this script in order to use it after... | Typically non-R code goes in ./inst/python/your_script.py (likewise for JS, etc). Anything in the inst folder will be installed into your package's root directory unchanged. To call these files in your package functions, use something like: reticulate::py_run_file(system.file("python", "your_script.py", package = "your... | 12 | 18 |
60,145,306 | 2020-2-10 | https://stackoverflow.com/questions/60145306/remove-background-text-and-noise-from-an-image-using-image-processing-with-openc | I have these images For which I want to remove the text in the background. Only the captcha characters should remain(i.e K6PwKA, YabVzu). The task is to identify these characters later using tesseract. This is what I have tried, but it isn't giving much good accuracy. import cv2 import pytesseract pytesseract.pytesse... | Here are two potential approaches and a method to correct distorted text: Method #1: Morphological operations + contour filtering Obtain binary image. Load image, grayscale, then Otsu's threshold. Remove text contours. Create a rectangular kernel with cv2.getStructuringElement() and then perform morphological operati... | 13 | 22 |
60,100,344 | 2020-2-6 | https://stackoverflow.com/questions/60100344/vscode-not-picking-up-ipykernel | I'm trying to use vscode with jupyter via the python extension. My pipfile looks like this: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [packages] opencv-python = "*" [requires] python_version = "3.6" [dev-packages] ipykernel = "*" ipython = "*" jupyter = "*" To start the ipython interpr... | I had the same issue do the following 1- remove python and fresh install new python the latest version has pip in it 2- open terminal as administrator and run the following command: pip install ipykernel --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org | 9 | 13 |
60,168,579 | 2020-2-11 | https://stackoverflow.com/questions/60168579/how-to-make-conda-build-work-correctly-and-find-the-setup-py | I am trying to create an anaconda python package. My meta.yaml looks like this: package: name: liveprint-lib version: "0.1.0" build: number: 0 requirements: build: - pip - python=3.7 - setuptools run: - python=3.7 - numpy - opencv about: home: https://github.com/monomonedula/liveprint license: Apache License 2.0 licens... | Your meta.yaml file is missing a source section. Also, it's usually best to keep your recipe files in a directory of their own, rather than in the top repo. I recommend the following: mkdir conda-recipe mv meta.yaml build.sh bld.bat conda-recipe Then, edit meta.yaml to add a source section, which points to the top-lev... | 9 | 4 |
60,107,347 | 2020-2-7 | https://stackoverflow.com/questions/60107347/createprocessw-failed-error2-ssh-askpass-posix-spawn-no-such-file-or-director | So I was following a tutorial to connect to my jupyter notebook which is running on my remote server so that I can access it on my local windows machine. These were the steps that I followed. On my remote server : jupyter notebook --no-browser --port=8889 Then on my local machine ssh -N -f -L localhost:8888:localhost:... | If you need the DISPLAY variable set because you want to use VcXsrc or another X-Server in Windows 10 the workaround is to add the host you want to connect to your known_hosts file. This can be done by calling ssh-keyscan -t rsa host.example.com | Out-File ~/.ssh/known_hosts -Append -Encoding ASCII; | 11 | 6 |
60,089,947 | 2020-2-6 | https://stackoverflow.com/questions/60089947/creating-pydantic-model-schema-with-dynamic-key | I'm trying to implement Pydantic Schema Models for the following JSON. { "description": "Best Authors And Their Books", "authorInfo": { "KISHAN": { "numberOfBooks": 10, "bestBookIds": [0, 2, 3, 7] }, "BALARAM": { "numberOfBooks": 15, "bestBookIds": [10, 12, 14] }, "RAM": { "numberOfBooks": 6, "bestBookIds": [3,5] } } }... | Actually you should remove Type from type annotations. You need an instance of a class, not an actual class. Try the solution below: from typing import List,Dict from pydantic import BaseModel class AuthorBookDetails(BaseModel): numberOfBooks: int bestBookIds: List[int] class AuthorInfoCreate(BaseModel): __root__: Dict... | 16 | 9 |
60,068,313 | 2020-2-5 | https://stackoverflow.com/questions/60068313/include-minimum-pip-version-in-setup-py | I've created a setup.py for my application. Some of the dependencies i set in install_requires require pip version 19.3.1 or greater. Is there a way to check for pip version as part of setup.py? and to upgrade pip prior to build? | This is not your responsibility to build workarounds in your project for the issues in the packaging of other projects. This is kind of a bad practice. There is also not much point in doing this as part of a setup.py anyway since in many cases this file is not executed during install time. The best thing you can do is ... | 10 | 5 |
60,074,344 | 2020-2-5 | https://stackoverflow.com/questions/60074344/reserved-word-as-an-attribute-name-in-a-dataclass-when-parsing-a-json-object | I stumbled upon a problem, when I was working on my ETL pipeline. I am using dataclasses dataclass to parse JSON objects. One of the keywords of the JSON object is a reserved keyword. Is there a way around this: from dataclasses import dataclass import jsons out = {"yield": 0.21} @dataclass class PriceObj: asOfDate: st... | You can decode / encode using a different name with the dataclasses_json lib, from their docs: from dataclasses import dataclass, field from dataclasses_json import config, dataclass_json @dataclass_json @dataclass class Person: given_name: str = field(metadata=config(field_name="overriddenGivenName")) Person(given_nam... | 10 | 8 |
60,111,305 | 2020-2-7 | https://stackoverflow.com/questions/60111305/getting-error-while-installing-apache-airflow | I am getting above error when i try airflow -version and airflow initdb File "/home/ravi/sandbox/bin/airflow", line 26, in <module> from airflow.bin.cli import CLIFactory File "/home/ravi/sandbox/lib/python3.6/site-packages/airflow/bin/cli.py", line 70, in <module> from airflow.www.app import (cached_app, create_app) ... | With this, it worked, thanks: pip install werkzeug==0.16.0 DB: sqlite:////home/centos/airflow/airflow.db [2020-02-07 12:02:02,523] {db.py:368} INFO - Creating tables | 16 | 45 |
60,077,137 | 2020-2-5 | https://stackoverflow.com/questions/60077137/conda-how-to-ignore-if-a-conda-channel-is-not-reachable-ignore-unavailableinva | The situation At work we have a private conda channel in our network that is used for some internal packages. Since I do not want to type the channel location every time I install something via conda install, I added it to condas default channels in .condarc. The problem Obviously the channel is only available inside m... | Solution More or less by accident I found the answer to my own question recently and do not want to keep it by myself. To prevent conda to fail when a channel is not available during install/update of packages from other available channels you have to set the following parameter in your .condarc file: allow_non_channe... | 9 | 8 |
60,067,953 | 2020-2-5 | https://stackoverflow.com/questions/60067953/is-it-possible-to-specify-the-pickle-protocol-when-writing-pandas-to-hdf5 | Is there a way to tell Pandas to use a specific pickle protocol (e.g. 4) when writing an HDF5 file? Here is the situation (much simplified): Client A is using python=3.8.1 (as well as pandas=1.0.0 and pytables=3.6.1). A writes some DataFrame using df.to_hdf(file, key). Client B is using python=3.7.1 (and, as it happen... | Update: I was wrong to assume this was not possible. In fact, based on the excellent "monkey-patch" suggestion of @PiotrJurkiewicz, here is a simple context manager that lets us temporarily change the highest pickle protocol. It: Hides the monkey-patching, and Has no side-effect outside of the context; it can be used ... | 8 | 7 |
60,088,889 | 2020-2-6 | https://stackoverflow.com/questions/60088889/how-do-you-permanently-delete-an-experiment-in-mlflow | Permanent deletion of an experiment isn't documented anywhere. I'm using Mlflow w/ backend postgres db Here's what I've run: client = MlflowClient(tracking_uri=server) client.delete_experiment(1) This deletes the the experiment, but when I run a new experiment with the same name as the one I just deleted, it will ret... | Unfortunately it seems there is no way to do this via the UI or CLI at the moment :-/ The way to do it depends on the type of backend file store that you are using. Filestore: If you are using the filesystem as a storage mechanism (the default) then it is easy. The 'deleted' experiments are moved to a .trash folder. Yo... | 30 | 30 |
60,134,947 | 2020-2-9 | https://stackoverflow.com/questions/60134947/why-couldnt-i-download-images-from-google-with-python | The code helped me download bunch of images from google. It used to work a few days back and now all of the sudden the code breaks. Code : # importing google_images_download module from google_images_download import google_images_download # creating object response = google_images_download.googleimagesdownload() sear... | Indeed the issue has appeared not so long ago, there are already a bunch of similar Github issues: https://github.com/hardikvasa/google-images-download/pull/298 https://github.com/hardikvasa/google-images-download/issues/301 https://github.com/hardikvasa/google-images-download/issues/302 Unfortunately, there is no of... | 18 | 2 |
60,157,335 | 2020-2-10 | https://stackoverflow.com/questions/60157335/cant-pip-install-tensorflow-msvcp140-1-dll-missing | I am currently trying to pip install tensorflow, which works but after I install it, and then import it into my python module via import tensorflow as tf I get following error message: ImportError: Could not find the DLL(s) 'msvcp140_1.dll'. TensorFlow requires that these DLLs be installed in a directory that is named ... | You can find msvcp140.dll in your %windows%/System32 folder, once you installed VC++ DIST for VS 2015, for msvcp140_1.dll you need to goto this page https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads and in the section :Visual Studio 2015, 2017 and 2019, pick the correct package wi... | 14 | 9 |
60,119,934 | 2020-2-7 | https://stackoverflow.com/questions/60119934/how-to-read-from-a-high-io-dataset-in-pytorch-which-grows-from-epoch-to-epoch | I use Tensorflow, but I'm writing documentation for users that will typically vary across deep learning frameworks. When working with datasets that don't fit on the local filesystem (TB+) I sample data from a remote data store and write samples locally to a Tensorflow standardtfrecords format. During the first epoch o... | Actually, you can easily deserialize data in a subprocess by using torch.utils.data.DataLoader. By setting num_workers argument to 1 or a bigger value, you can spawn subprocesses with their own python interpreters and GILs. loader = torch.utils.data.DataLoader(your_dataset, num_workers=n, **kwargs) for epoch in range(e... | 9 | 10 |
60,145,006 | 2020-2-10 | https://stackoverflow.com/questions/60145006/cannot-import-name-easter-from-holidays | I am trying to import fbprophet on Python Anaconda, however, I get this error: ImportError: cannot import name 'easter' from 'holidays' Can anyone suggest what might have gone wrong? Code: from fbprophet import fbprophet | I'm using anaconda, and the only solution that worked for me was: Replace line 16 in fbprophet/hdays.py (\AppData\Local\Continuum\anaconda3\Lib\site-packages\fbprophet\hdays.py): from holidays import WEEKEND, HolidayBase, easter, rd to from holidays import WEEKEND, HolidayBase from dateutil.easter import easter from d... | 9 | 13 |
60,178,119 | 2020-2-11 | https://stackoverflow.com/questions/60178119/signaturedoesnotmatch-boto3-django-storages | I have the following config: Django/DRF Boto3 Django-storages I am using an IAM user credentials with one set of keys. I have removed all other sets of keys including root keys from my account, to eliminate keys mismatch. I created a new bucket my-prod-bucket. Updated the bucket name settings in my env file. I ran pyth... | Ok, so after spending nearly 2 days trying to make sense of this, this is what I came up with: The problem in my case was that the bucket created in zone ca-central-1. Once I changed the request to a bucket in us-east-1 everything was immediately working fine without that error. Everything on my end was set perfectly. ... | 9 | 14 |
60,111,361 | 2020-2-7 | https://stackoverflow.com/questions/60111361/how-to-download-a-file-from-google-drive-using-python-and-the-drive-api-v3 | I have tried downloading file from Google Drive to my local system using python script but facing a "forbidden" issue while running a Python script. The script is as follows: import requests url = "https://www.googleapis.com/drive/v3/files/1wPxpQwvEEOu9whmVVJA9PzGPM2XvZvhj?alt=media&export=download" querystring = {"alt... | To make requests to Google APIs the work flow is in essence the following: Go to developer console, log in if you haven't. Create a Cloud Platform project. Enable for your project, the APIs you are interested in using with you projects' apps (for example: Google Drive API). Create and download OAuth 2.0 Client IDs cre... | 9 | 26 |
60,172,458 | 2020-2-11 | https://stackoverflow.com/questions/60172458/sklearn-cross-val-score-returns-nan-values | i'm trying to predict next customer purchase to my job. I followed a guide, but when i tried to use cross_val_score() function, it returns NaN values.Google Colab notebook screenshot Variables: X_train is a dataframe X_test is a dataframe y_train is a list y_test is a list Code: X_train, X_test, y_train, y_test = tr... | Well thanks everyone for your answers. The answer of Anna helped me a lot!, but i don't used X_train.values, instead i assigned an unique ID to the Customers, then dropped Customers column and it works! Now the models has this output :) LR [0.73958333 0.74736842] NB [0.60416667 0.71578947] RF [0.80208333 0.82105263] SV... | 11 | 1 |
60,147,431 | 2020-2-10 | https://stackoverflow.com/questions/60147431/how-to-put-a-label-on-a-country-with-python-cartopy | Using python3 and cartopy, having this code: import matplotlib.pyplot as plt import cartopy import cartopy.io.shapereader as shpreader import cartopy.crs as ccrs ax = plt.axes(projection=ccrs.PlateCarree()) ax.add_feature(cartopy.feature.LAND) ax.add_feature(cartopy.feature.OCEAN) ax.add_feature(cartopy.feature.COASTLI... | You can retrieve the centroid of the geometry and plot the text at that location: import matplotlib.patheffects as PathEffects for country in countries: if country.attributes['SOVEREIGNT'] == "Bulgaria": g = ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(0, 1, 0), label="A") x = country.geometry.cen... | 10 | 13 |
60,149,801 | 2020-2-10 | https://stackoverflow.com/questions/60149801/import-error-importerror-cannot-import-name-abc-from-bson-py3compat | How can i solve this error. It will generate while running program. from bson import ObjectId class JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) return json.JSONEncoder.default(self, o) | That's most likely due to version mismatches. This worked for me: pip uninstall bson pip uninstall pymongo pip install pymongo | 21 | 77 |
60,073,711 | 2020-2-5 | https://stackoverflow.com/questions/60073711/how-to-build-c-extensions-via-poetry | To build a python project managed with poetry I need to build C extensions first (an equivalent to python setup.py build). poetry is able to do this according to this github issue. But to me it's not clear what to include into pyproject.toml that the C extension build is executed when building with poetry build? | Add build.py to the repo-root. E.g. if one has one header file directory and 2 source files: from distutils.command.build_ext import build_ext ext_modules = [ Extension("<module-path-imported-into-python>", include_dirs=["<header-file-directory>"], sources=["<source-file-0>", "<source-file-1>"], ), ] class BuildFailed(... | 13 | 8 |
60,158,357 | 2020-2-10 | https://stackoverflow.com/questions/60158357/why-do-i-get-attributeerror-fields-set-when-subclassing-a-pydantic-basemo | I have this project where my base class and my sub-classes implement pydantic.BaseModel: from pydantic import BaseModel from typing import List from dataclasses import dataclass @dataclass class User(BaseModel): id: int @dataclass class FavoriteCar(User): car_names: List[str] car = FavoriteCar(id=1, car_names=["Acura"]... | You need to decide whether to inherit from pydantic.BaseModel, or whether to use the @dataclass decorator (either from dataclasses, or from pydantic.dataclasses). Either is fine, but you cannot use both, according to the documentation (bold face added by myself): If you don't want to use pydantic's BaseModel you can i... | 43 | 39 |
60,158,618 | 2020-2-10 | https://stackoverflow.com/questions/60158618/plotly-how-to-add-elements-to-hover-data-using-plotly-express-piechart | I am playing with examples from plotly.express piechart help page and trying to add an extra element iso_num to the hover_data property (iso_num is an int64 column in the gapminder dataframe) import plotly.express as px df = px.data.gapminder().query("year == 2007").query("continent == 'Americas'") fig = px.pie(df, val... | This seems to be a relic from back when it was stated that Oh pie hover is a big mess Which since seems to be have been resolved. But perhaps not for px.pie()? I've tried numerous approaches, but I'm only able to get the customdata + hovertemplate approach to work for go.Pie and not for px.Pie. Here's a demonstration... | 9 | 6 |
60,069,977 | 2020-2-5 | https://stackoverflow.com/questions/60069977/sharing-gpu-memory-between-process-on-a-same-gpu-with-pytorch | I'm trying to implement an efficient way of doing concurrent inference in Pytorch. Right now, I start 2 processes on my GPU (I have only 1 GPU, both process are on the same device). Each process load my Pytorch model and do the inference step. My problem is that my model takes quite some space on the memory. I have 12G... | The GPU itself has many threads. When performing an array/tensor operation, it uses each thread on one or more cells of the array. This is why it seems that an op that can fully utilize the GPU should scale efficiently without multiple processes -- a single GPU kernel is already massively parallelized. In a comment you... | 11 | 2 |
60,150,031 | 2020-2-10 | https://stackoverflow.com/questions/60150031/how-to-display-latex-f-strings-in-matplotlib | In Python 3.6, there is the new f-string to include variables in strings which is great, but how do you correctly apply these strings to get super or subscripts printed for matplotlib? (to actually see the result with the subscript, you need to draw the variable foo on a matplotlib plot) In other words how do I get thi... | You need to escape the curly brackets by doubling them up, and then add in one more to use in the LaTeX formula. This gives: foo = f'text$_{{{var}}}$' Example: plt.figure() plt.plot([1,2,3], [3,4,5]) var = 123 plt.text(1, 4,f'text$_{{{var}}}$') Output: Incidentally, in this example, you don't actually need to use a ... | 28 | 46 |
60,156,202 | 2020-2-10 | https://stackoverflow.com/questions/60156202/flask-app-wont-launch-importerror-cannot-import-name-cached-property-from-w | I've been working on a Flask app for a few weeks. I finished it today and went to deploy it... and now it won't launch. I haven't added or removed any code so assume something has changed in the deployment process? Anyway, here is the full error displayed in the terminal: Traceback (most recent call last): File "C:\Use... | Try: from werkzeug.utils import cached_property https://werkzeug.palletsprojects.com/en/1.0.x/utils/ | 39 | 15 |
60,149,105 | 2020-2-10 | https://stackoverflow.com/questions/60149105/userwarning-warn-box-bound-precision-lowered-by-casting-to-float32 | I continuously get this error UserWarning: WARN: Box bound precision lowered by casting to float32 warnings.warn(colorize('%s: %s'%('WARN', msg % args), 'yellow')) when I start my training session. I guess it's coming from this line self.action_space = spaces.Box(low, high) The code is running but I want to stop th... | Explicitly specify the dtype as float32 in the call like so... self.action_space = spaces.Box(low, high, dtype=np.float32) If that doesn't work, set the logger level lower in gym like so... import gym gym.logger.set_level(40) | 14 | 8 |
60,153,981 | 2020-2-10 | https://stackoverflow.com/questions/60153981/scikit-learn-one-hot-encoding-certain-columns-of-a-pandas-dataframe | I have a dataframe X with integer, float and string columns. I'd like to one-hot encode every column that is of "Object" type, so I'm trying to do this: encoding_needed = X.select_dtypes(include='object').columns ohe = preprocessing.OneHotEncoder() X[encoding_needed] = ohe.fit_transform(X[encoding_needed].astype(str)) ... | # example data X = pd.DataFrame({'int':[0,1,2,3], 'float':[4.0, 5.0, 6.0, 7.0], 'string1':list('abcd'), 'string2':list('efgh')}) int float string1 string2 0 0 4.0 a e 1 1 5.0 b f 2 2 6.0 c g 3 3 7.0 d h Using pandas With pandas.get_dummies, it will automatically select your object columns and drop these columns while ... | 9 | 21 |
60,145,652 | 2020-2-10 | https://stackoverflow.com/questions/60145652/no-module-named-sklearn-neighbors-base | I have recently installed imblearn package in jupyter using !pip show imbalanced-learn But I am not able to import this package. from tensorflow.keras import backend from imblearn.over_sampling import SMOTE I get the following error --------------------------------------------------------------------------- ModuleN... | Previous sklearn.neighbors.base has been renamed to sklearn.neighbors._base in version 0.22.1. You have probably a version of scikit-learn older than that. Installing the latest release solves the problem: pip install -U scikit-learn or pip install scikit-learn==0.22.1 | 15 | 11 |
60,148,137 | 2020-2-10 | https://stackoverflow.com/questions/60148137/what-happens-if-i-dont-join-a-python-thread | I have a query. I have seen examples where developers write something like the code as follows: import threading def do_something(): return true t = threading.Thread(target=do_something) t.start() t.join() I know that join() signals the interpreter to wait till the thread is completely executed. But what if I do not w... | A Python thread is just a regular OS thread. If you don't join it, it still keeps running concurrently with the current thread. It will eventually die, when the target function completes or raises an exception. No such thing as "thread reuse" exists, once it's dead it rests in peace. Unless the thread is a "daemon thre... | 12 | 13 |
60,144,693 | 2020-2-10 | https://stackoverflow.com/questions/60144693/show-image-in-its-original-resolution-in-jupyter-notebook | I have a very high resolution(3311, 4681, 3) image, which I want to show in my jupyter notebook using opencv but as other answers stated its not possible to use cv2.imshow in the jupyter notebook, so i used plt.imshow to do the same but the problem is I have to define the fig_size parameter if I want to display my imag... | You can imshow the image in its original resolution by calculating the corresponding figure size, which depends on the dpi (dots per inch) value of matplotlib. The default value is 100 dpi and is stored in matplotlib.rcParams['figure.dpi']. So imshowing the image like this import cv2 from matplotlib import pyplot as pl... | 9 | 9 |
60,120,849 | 2020-2-7 | https://stackoverflow.com/questions/60120849/outputting-attention-for-bert-base-uncased-with-huggingface-transformers-torch | I was following a paper on BERT-based lexical substitution (specifically trying to implement equation (2) - if someone has already implemented the whole paper that would also be great). Thus, I wanted to obtain both the last hidden layers (only thing I am unsure is the ordering of the layers in the output: last first o... | The reason is that you are using AutoModelWithLMHead which is a wrapper for the actual model. It calls the BERT model (i.e., an instance of BERTModel) and then it uses the embedding matrix as a weight matrix for the word prediction. In between the underlying model indeed returns attentions, but the wrapper does not car... | 10 | 3 |
60,140,174 | 2020-2-9 | https://stackoverflow.com/questions/60140174/basic-flask-app-not-running-typeerror-required-field-type-ignores-missing-fr | I have a very basic flask app with dependencies installed from my requirements.txt. All of these dependencies are installed in my virtual environment. requirements.txt given below, aniso8601==6.0.0 Click==7.0 Flask==1.0.3 Flask-Cors==3.0.7 Flask-RESTful==0.3.7 Flask-SQLAlchemy==2.4.0 itsdangerous==1.1.0 Jinja2==2.10.1 ... | The bug was fixed in werkzeug 0.15.5. Upgrade from 0.15.4 to to a later version. | 21 | 48 |
60,137,570 | 2020-2-9 | https://stackoverflow.com/questions/60137570/explanation-of-generator-close-with-exception-handling | I am reading the python doc https://docs.python.org/3/reference/expressions.html about generator.close(). My translation of the documentation is: ##generator.close() Raises a GeneratorExit at the point where the generator function was paused. If the generator function then exits gracefully : 1.1 is already closed, 1.... | GeneratorExit does not inherit from Exception, but from the more fundamental BaseException. Thus, it is not caught by your except Exception block. So your assumption 2 is wrong. The generator exits gracefully via case 1.3, since GeneratorExit is not stopped. The GeneratorExit is thrown at (yield value). The try: excep... | 11 | 12 |
60,107,946 | 2020-2-7 | https://stackoverflow.com/questions/60107946/how-to-add-column-delimiter-to-pandas-dataframe-display | For example, define df=pd.DataFrame(np.random.randint(0,10,(6,6))) df Which gives below display in Jupyter notebook My question is that is it possible to add a column delimiter to the dataframe like Thank you for all the answers, currently I use below custom functions def css_border(x,pos): return ["border-left: 1... | This piece of code should add the desired lines to the table. from IPython.display import display, HTML CSS = """ .rendered_html td:nth-child(even) { border-left: 1px solid red; } """ HTML('<style>{}</style>'.format(CSS)) Note that you can change the style of those linse by simply changing the definition of border-le... | 10 | 10 |
60,113,143 | 2020-2-7 | https://stackoverflow.com/questions/60113143/how-to-properly-use-asyncio-run-coroutine-threadsafe-function | I am trying to understand asyncio module and spend about one hour with run_coroutine_threadsafe function, I even came to the working example, it works as expected, but works with several limitations. First of all I do not understand how should I properly call asyncio loop in main (any other) thread, in the example I ca... | First of all I do not understand how should I properly call asyncio loop in main (any other) thread, in the example I call it with run_until_complete and give it a coroutine to make it busy with something until another thread will not give it a coroutine. What are other options I have? This is a good use case for loo... | 24 | 29 |
60,132,045 | 2020-2-8 | https://stackoverflow.com/questions/60132045/fastapi-uvicorn-not-working-when-specifying-host | I'm running a FastAPI app in Python using uvicorn on a Windows machine without a frontend (e.g. Next.js, etc.) so there should NOT be any iteraction between a local frontend and backend like there is in this question. Plus the answer(s) to that question would not have solved my issue/question. That question was also as... | As I was writing the question above, I found the solution and thought I would share in case someone else runs into this. To get it to work put "http://localhost:8080" into the web browser instead of "http://0.0.0.0:8080" and it will work fine. This also works if you're hitting the endpoint via the python requests packa... | 29 | 28 |
60,130,622 | 2020-2-8 | https://stackoverflow.com/questions/60130622/warningtensorflow-with-constraint-is-deprecated-and-will-be-removed-in-a-future | I am following Tensorflow's tutorial on building a simple neural network, and after importing the necessary libraries (tensorflow, keras, numpy & matplotlib) and datasets (fashion_mnist) I ran this code as per the tutorial: model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, ... | This is internal TensorFlow message, you can safely ignore it. It will be gone in future versions of TensorFlow, no actions from your side is needed. | 8 | 11 |
60,123,611 | 2020-2-8 | https://stackoverflow.com/questions/60123611/how-to-position-legends-inside-a-plot-in-plotly | I have got this code from Plotly page. I need to make the background transparent and the axis highlighted. And also the legends positioned inside the plot. import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="Increasing" )) fig.add_trace(go.Scatter( x... | To change the background color you need specify it by plot_bgcolor='rgba(0,0,0,0)',, while to move the legend inside the plot, on the left, you need to explicitly define the position: import plotly.graph_objects as go trace0 = go.Scatter( x=[1, 2, 3, 4, 5], y=[1, 2, 3, 4, 5], name="Increasing" ) trace1 = go.Scatter( x=... | 10 | 8 |
60,127,165 | 2020-2-8 | https://stackoverflow.com/questions/60127165/pytest-test-function-that-creates-plots | I have several functions that create plots, which I use in Jupyter notebooks to visualise data. I want to create basic tests for these, checking that they still run without erroring on various inputs if I make changes. However, if I call these functions using pytest, creating the plots causes the program to hang until ... | This works. from unittest.mock import patch import pytest import matplotlib.pyplot as plt def plot_fn(): plt.plot([1,2,3]) plt.show() @patch("matplotlib.pyplot.show") def test_plot_fn(mock_show): plot_fn() Based on this answer (possible duplicate) Turn off graphs while running unittests | 10 | 4 |
60,082,546 | 2020-2-5 | https://stackoverflow.com/questions/60082546/airflow-proper-way-to-run-dag-for-each-file | I have the following task to solve: Files are being sent at irregular times through an endpoint and stored locally. I need to trigger a DAG run for each of these files. For each file the same tasks will be performed Overall the flows looks as follows: For each file, run tasks A->B->C->D Files are being processed in b... | I found this article: https://medium.com/@igorlubimov/dynamic-scheduling-in-airflow-52979b3e6b13 where a new operator, namely TriggerMultiDagRunOperator is used. I think this suits my needs. | 9 | 1 |
60,111,684 | 2020-2-7 | https://stackoverflow.com/questions/60111684/geometry-must-be-a-point-or-linestring-error-using-cartopy | I'm trying to run a simple Cartopy example: import cartopy.crs as ccrs import matplotlib.pyplot as plt ax = plt.axes(projection=ccrs.PlateCarree()) ax.coastlines() plt.show() But I'm getting this error: Geometry must be a Point or LineString python: geos_ts_c.cpp:4179: int GEOSCoordSeq_getSize_r(GEOSContextHandle_t,... | The problem is a wrong version of shapely, with Cartopy the binary package shoudn't be used, it should be built from source instead. This is explained here and here. So I did: pip uninstall shapely pip install shapely --no-binary shapely | 14 | 29 |
60,115,855 | 2020-2-7 | https://stackoverflow.com/questions/60115855/difference-between-viewset-modelviewset-and-apiview | What are the advantages of ViewSet, ModelViewSet and APIView. In the django-rest-framework documents it is not clear, it does not say when to use ViewSet, ModelViewSet and APIView. I want to implement an API that will have a business logic in there, a great business logic with data processing as well, what should be us... | Summarizing: on one hand you have the APIView, which is the most generic of the three, but also in which you must do almost all business logic 'manually'. You have the class methods mapping http methods (get, post, ...) plus some class attributes to configure things like authentication, rendering, etc. Often you'll be ... | 8 | 13 |
60,098,005 | 2020-2-6 | https://stackoverflow.com/questions/60098005/fastapi-starlette-get-client-real-ip | I have an API on FastAPI and i need to get the client real IP address when he request my page. I'm ty to use starlette Request. But it returns my server IP, not client remote IP. My code: @app.post('/my-endpoint') async def my_endpoint(stats: Stats, request: Request): ip = request.client.host print(ip) return {'status'... | request.client should work, unless you're running behind a proxy (e.g. nginx) in that case use uvicorn's --proxy-headers flag to accept these incoming headers and make sure the proxy forwards them. | 56 | 58 |
60,105,443 | 2020-2-7 | https://stackoverflow.com/questions/60105443/how-do-i-correctly-use-mock-call-args-with-pythons-unittest-mock | Consider the following files: holy_hand_grenade.py def count(one, two, five='three'): print('boom') test_holy_hand_grenade.py from unittest import mock import holy_hand_grenade def test_hand_grenade(): mock_count = mock.patch("holy_hand_grenade.count", autospec=True) with mock_count as fake_count: fake_count(1, 2, fiv... | This is a feature introduced in Python 3.8 in this issue. The 3.7 documentation does not mention it (while the newest docs do) - so you have to access the arguments by index in Python < 3.8. | 12 | 14 |
60,115,633 | 2020-2-7 | https://stackoverflow.com/questions/60115633/pytorch-flatten-doesnt-maintain-batch-size | In Keras, using the Flatten() layer retains the batch size. For eg, if the input shape to Flatten is (32, 100, 100), in Keras output of Flatten is (32, 10000), but in PyTorch it is 320000. Why is it so? | As OP already pointed out in their answer, the tensor operations do not default to considering a batch dimension. You can use torch.flatten() or Tensor.flatten() with start_dim=1 to start the flattening operation after the batch dimension. Alternatively since PyTorch 1.2.0 you can define an nn.Flatten() layer in your m... | 11 | 19 |
60,101,240 | 2020-2-6 | https://stackoverflow.com/questions/60101240/finding-mean-and-standard-deviation-across-image-channels-pytorch | Say I have a batch of images in the form of tensors with dimensions (B x C x W x H) where B is the batch size, C is the number of channels in the image, and W and H are the width and height of the image respectively. I'm looking to use the transforms.Normalize() function to normalize my images with respect to the mean ... | You just need to rearrange batch tensor in a right way: from [B, C, W, H] to [B, C, W * H] by: batch = batch.view(batch.size(0), batch.size(1), -1) Here is complete usage example on random data: Code: import torch from torch.utils.data import TensorDataset, DataLoader data = torch.randn(64, 3, 28, 28) labels = torch.z... | 11 | 10 |
60,107,982 | 2020-2-7 | https://stackoverflow.com/questions/60107982/attributeerror-function-object-has-no-attribute-func-name-and-python-3 | I downloaded the following code : from __future__ import print_function from time import sleep def callback_a(i, result): print("Items processed: {}. Running result: {}.".format(i, result)) def square(i): return i * i def processor(process, times, report_interval, callback): print("Entered processor(): times = {}, repo... | That behaviour in Python 3 is expected as it was changed from Python 2. Per the documentation here: https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods The function attributes named func_X have been renamed to use the __X__ form, freeing up these names in the function attribute namespace for user... | 14 | 15 |
60,104,564 | 2020-2-6 | https://stackoverflow.com/questions/60104564/when-and-why-to-use-self-dict-instead-of-self-variable | I'm trying to understand some code which is using this class below: class Base(object): def __init__(self, **kwargs): self.client = kwargs.get('client') self.request = kwargs.get('request') ... def to_dict(self): data = dict() for key in iter(self.__dict__): # <------------------------ this if key in ('client', 'reques... | Almost all of the time, you shouldn't use self.__dict__. If you're accessing an attribute like self.client, i.e. the attribute name is known and fixed, then the only difference between that and self.__dict__['client'] is that the latter won't look up the attribute on the class if it's missing on the instance. There is ... | 10 | 20 |
60,102,928 | 2020-2-6 | https://stackoverflow.com/questions/60102928/pandas-fillna-only-numeric-int-or-float-columns | I would like to apply fillna only in numeric columns. Is possible? Right now, I'm applying it in all columns: df = df.replace(r"^\s*$", np.nan, regex=True) | You can select numeric columns and then fillna E.g: import pandas as pd df = pd.DataFrame({'a': [1, None] * 3, 'b': [True, None] * 3, 'c': [1.0, None] * 3}) # select numeric columns numeric_columns = df.select_dtypes(include=['number']).columns # fill -1 to all NaN df[numeric_columns] = df[numeric_columns].fillna(-1) #... | 11 | 19 |
60,101,168 | 2020-2-6 | https://stackoverflow.com/questions/60101168/pytorch-runtimeerror-dataloader-worker-pids-15332-exited-unexpectedly | I am a beginner at PyTorch and I am just trying out some examples on this webpage. But I can't seem to get the 'super_resolution' program running due to this error: RuntimeError: DataLoader worker (pid(s) 15332) exited unexpectedly I searched the Internet and found that some people suggest setting num_workers to 0. But... | There is no "complete" solve for GPU out of memory errors, but there are quite a few things you can do to relieve the memory demand. Also, make sure that you are not passing the trainset and testset to the GPU at the same time! Decrease batch size to 1 Decrease the dimensionality of the fully-connected layers (they ar... | 35 | 17 |
60,079,644 | 2020-2-5 | https://stackoverflow.com/questions/60079644/how-do-you-edit-an-existing-tensorboard-training-loss-summary | I've trained my network and generated some training/validation losses which I saved via the following code example (example of training loss only, validation is perfectly equivalent): valid_summary_writer = tf.summary.create_file_writer("/path/to/logs/") with train_summary_writer.as_default(): tf.summary.scalar('Traini... | As mentioned in How to load selected range of samples in Tensorboard, TensorBoard events are actually stored record files, so you can read them and process them as such. Here is a script similar to the one posted there but for the purpose of renaming events, and updated to work in TF 2.x. #!/usr/bin/env python3 # -*- c... | 9 | 13 |
60,095,973 | 2020-2-6 | https://stackoverflow.com/questions/60095973/find-peaks-does-not-identify-a-peak-at-the-start-of-the-array | I am trying to find a vectorized approach of finding the first position in an array where the values did not get higher than the maximum of n previous numbers. I thought about using the find_peaks method of scipy.signal to find a local maximum. I think it does exactly that if you define the distance to let's say 10 n i... | def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) def get_peaks(arr, window): maxss = np.argmax(rolling_window(arr1, window), axis=1) return np.where(maxss == 0)[0] >>> ... | 9 | 2 |
60,086,741 | 2020-2-6 | https://stackoverflow.com/questions/60086741/docker-so-slow-while-installing-pip-requirements | I am trying to implement a docker for a dummy local Django project. I am using docker-compose as a tool for defining and running multiple containers. Here I tried to containerize the Django-web-app and PostgreSQL two services. Configuration used in Dockerfile and docker-compose.yml Dockerfile # Pull base image FROM p... | Probably this is because PyPI wheels don’t work on Alpine. Instead of using precompile files Alpine downloads the source code and compile it. Try to use python:3.7-slim image instead: # Pull base image FROM python:3.7-slim # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work direc... | 11 | 31 |
60,079,783 | 2020-2-5 | https://stackoverflow.com/questions/60079783/difference-between-keras-batchnormalization-and-pytorchs-batchnorm2d | I've a sample tiny CNN implemented in both Keras and PyTorch. When I print summary of both the networks, the total number of trainable parameters are same but total number of parameters and number of parameters for Batch Normalization don't match. Here is the CNN implementation in Keras: inputs = Input(shape = (64, 64... | Keras treats as parameters (weights) many things that will be "saved/loaded" in the layer. While both implementations naturally have the accumulated "mean" and "variance" of the batches, these values are not trainable with backpropagation. Nevertheless, these values are updated every batch, and Keras treats them as n... | 15 | 20 |
60,077,401 | 2020-2-5 | https://stackoverflow.com/questions/60077401/rotate-x-axis-labels-facetgrid-seaborn-not-working | I'm attempting to create a faceted plot using seaborn in python, but I'm having issues with a number of things, one thing being rotating the x-axis labels. I am currently attempting to use the following code: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt vin = pd.Series(["W1","W1","W2","W2",... | Try this, it seems you were over-writing the 'plot' variable.: import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline vin = pd.Series(["W1","W1","W2","W2","W1","W3","W4"]) word1 = pd.Series(['pdi','pdi','tread','adjust','fill','pdi','fill']) word2 = pd.Series(['perform','perform','... | 10 | 14 |
60,077,695 | 2020-2-5 | https://stackoverflow.com/questions/60077695/how-to-get-the-last-row-value-in-pandas-through-dataframe-get-value | I follow this instruction https://www.geeksforgeeks.org/python-pandas-dataframe-get_value/ and know how to get the value from a dateframe data in pandas: df.get_value(10, 'Salary') My question is how to get the value of 'Salary' in the last row? | First of all I would advise against using get_value since it is/will be deprecated. (see: https://pandas.pydata.org/pandas-docs/version/0.23.4/generated/pandas.DataFrame.get_value.html ) There are a couple of solutions: df['Salary'].iloc[-1] df.Salary.iloc[-1] are synonymous. Iloc is the way to retrieve items in a pan... | 8 | 22 |
60,071,680 | 2020-2-5 | https://stackoverflow.com/questions/60071680/django-shell-api-keyerror | I am importing models in django shell API but i get the below error. Here is how it occurs: python manage.py shell from .models import Device I get: File "<console>", line 1, in <module> KeyError: "'__name__' not in globals" | Try putting the app name before ".models". Here .models trying to import from models.py in the current directory but models.py is actually located in the app directory. >> from [app_name].models import Device | 8 | 24 |
60,067,548 | 2020-2-5 | https://stackoverflow.com/questions/60067548/clone-base-environment-in-anaconda | My conda version is 4.7.11. I am trying to clone the base env to a new one so I can install some specific packages and will not mess up the base environment. I tried as some other answers suggested: conda create --name <myenv> --clone base and conda create --name <myenv> --clone root But none of them works. The messa... | I would recommend that you try the method as shown on this official documentation. In summary, you can get all the list of modules installed in the virtual environment, save it as a .txt file, and create a new environment from that .txt file. For example, conda list --explicit > spec-file.txt Then, create a new enviro... | 33 | 30 |
59,981,914 | 2020-1-30 | https://stackoverflow.com/questions/59981914/missing-dependancies-of-rtree | I am currently using Spyder for Python, and I have this error message when I open the program: Error: You have missing dependencies! rtree>= 0.8.3: None (NOK) Please install them to avoid this message. Note: Spyder could work without some of these dependencies, however to have a smooth experience, we strongly recommend... | It looks like Rtree requires libspatialindex (https://libspatialindex.org) which is not automatically installed. It seems some devs are aware of the problem and working on a fix: https://github.com/Toblerity/rtree/issues/146 https://github.com/Toblerity/rtree/issues/147 | 9 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.