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,705,698 | 2021-8-9 | https://stackoverflow.com/questions/68705698/how-to-write-tests-for-pydantic-models-in-fastapi | I just started using FastAPI but I do not know how do I write a unit test (using pytest) for a Pydantic model. Here is a sample Pydantic model: class PhoneNumber(BaseModel): id: int country: str country_code: str number: str extension: str I want to test this model by creating a sample PhoneNumber instance and ensure ... | The test you want to achieve is straightforward to do with pytest: import pytest def test_phonenumber(): pn = PhoneNumber(id=1, country="country", country_code="code", number="number", extension="extension") assert pn.id == 1 assert pn.country == 'country' assert pn.country_code == 'code' assert pn.number == 'number' a... | 17 | 36 |
68,669,767 | 2021-8-5 | https://stackoverflow.com/questions/68669767/pycharm-can%c2%b4t-find-reference-of-any-opencv-function-in-init-py | I'm using PyCharm 2021.2 Professional edition and I have installed opencv-python with: pip install opencv-python However, the IDE keeps giving me the following warning when I try to use cv2 package: Cannot find reference 'resize' in '__init__.py' Here I gave the example of the resize function, but it's happening for ... | This solution worked for me. In preferences, Select Python Interpreter Click the setting icon ( gear on right of box that display your Python Interpreter and select Show All A list of all your configured Interpreters is show with your current interpreter already hi-lighted. With your interpreter still highlighted, cli... | 9 | 21 |
68,649,314 | 2021-8-4 | https://stackoverflow.com/questions/68649314/how-to-display-current-virtual-environtment-in-python-in-oh-my-posh | First, I'm using hotstick.minimal theme in oh my posh. And it looks like this. As you can see, a current venv doesn't look good. And I made some changes in JSON file. Then it looks like this. I don't want to display the name of venv on the left. How can I do that? This is my JSON file: { "$schema": "https://raw.githu... | You have to include the following in your $PROFILE (profile.ps1): $env:VIRTUAL_ENV_DISABLE_PROMPT = 1 Two notes: Deactivate the venv first Close and re-open the terminal for it to work. See a fuller discussion here: https://github.com/JanDeDobbeleer/oh-my-posh/discussions/390 | 10 | 10 |
68,681,092 | 2021-8-6 | https://stackoverflow.com/questions/68681092/typing-namedtuple-and-mutable-default-arguments | Given I want to properly using type annotations for named tuples from the typing module: from typing import NamedTuple, List class Foo(NamedTuple): my_list: List[int] = [] foo1 = Foo() foo1.my_list.append(42) foo2 = Foo() print(foo2.my_list) # prints [42] What is the best or cleanest ways to avoid the mutable default ... | EDIT: Blending my approach with Sebastian Wagner's idea of using a decorator, we can achieve something like this: from typing import NamedTuple, List, Callable, TypeVar, Type, Any, cast from functools import wraps T = TypeVar('T') def default_factory(**factory_kw: Callable[[], Any]) -> Callable[[Type[T]], Type[T]]: def... | 9 | 2 |
68,704,002 | 2021-8-8 | https://stackoverflow.com/questions/68704002/importerror-cannot-import-name-abcindexclass-from-pandas-core-dtypes-generic | I have this output : [Pandas-profiling] ImportError: cannot import name 'ABCIndexClass' from 'pandas.core.dtypes.generic' when trying to import pandas-profiling in this fashion : from pandas_profiling import ProfileReport It seems to import pandas-profiling correctly but struggles when it comes to interfacing with p... | Thanks to the @aflyingtoaster's answer, the following workaround has worked fine for me: Edit the file "~/[your_conda_env_path]/lib/site-packages/visions/dtypes/boolean.py" Find the row "from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries" and just replace ABCIndexClass for ABCIndex. Save the boolean.py fi... | 19 | 23 |
68,721,086 | 2021-8-10 | https://stackoverflow.com/questions/68721086/plotly-how-to-define-marker-color-based-on-category-string-value-for-a-3d-scatt | I am using plotly.graph_object for 3D scatter plot. I'd like to define marker color based on category string value. The category values are A2, A3, A4. How to modify below code? Thanks Here is what I did: import plotly.graph_objects as go x=df_merged_pc['PC1'] y=df_merged_pc['PC2'] z=df_merged_pc['PC3'] color=df_merge... | I might be wrong here, but it sounds to me like you're actually asking for a widely used built-in feature of plotly.express where you can assign a color to subgroups of labeled data. Take the dataset px.data.iris as an example with: fig = px.scatter_3d(df, x='sepal_length', y='sepal_width', z='petal_width', color='spec... | 5 | 6 |
68,673,221 | 2021-8-5 | https://stackoverflow.com/questions/68673221/warning-running-pip-as-the-root-user | I am making simple image of my python Django app in Docker. But at the end of the building container it throws next warning (I am building it on Ubuntu 20.04): WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a v... | The way your container is built doesn't add a user, so everything is done as root. You could create a user and install to that users's home directory by doing something like this; FROM python:3.8.3-alpine RUN pip install --upgrade pip RUN adduser -D myuser USER myuser WORKDIR /home/myuser COPY --chown=myuser:myuser req... | 120 | 68 |
68,705,613 | 2021-8-9 | https://stackoverflow.com/questions/68705613/can-i-use-abstract-methods-to-import-file-specific-formatting-of-python-pandas | I have a class FileSet with a method _process_series, which contains a bunch of if-elif blocks doing filetag-specific formatting of different pandas.Series: elif filetag == "EntityA": ps[filetag+"_Id"] = str(ps[filetag+"_Id"]).strip() ps[filetag+"_DateOfBirth"] = str(pd.to_datetime(ps[filetag+"_DateOfBirth"]).strftime... | Why not use globals with asterisk: from my_formatters import * for tag in filetag: fmt = globals()[tag + '_formatter'] ps = self.format(pandas_series, fmt) return ps I converted your pseudocode to real code. globals documentation: Return a dictionary representing the current global symbol table. This is always the di... | 6 | 1 |
68,733,440 | 2021-8-10 | https://stackoverflow.com/questions/68733440/set-and-get-attributes-in-bunch-type-object | For simplicity to parse/create JSON, machine learning applications usually uses the Bunch object, e.g. https://github.com/dsc/bunch/blob/master/bunch/__init__.py When getting, there's a nested EAFP idiom that checks through the dict.get() function and then trying to access it with dictionary square bracket syntax, i.e.... | Lucky for you, all objects have an internal dict-like object that manages the attributes of the object (this is in the __dict__ attribute). To do what you're asking, you just need to make the class use itself as the __dict__ object: class Bunch(dict): def __init__(self, *args, **kwargs): self.__dict__ = self super().__... | 5 | 3 |
68,680,322 | 2021-8-6 | https://stackoverflow.com/questions/68680322/pytube-urllib-error-httperror-http-error-410-gone | I've been getting this error on several programs for now. I've tried upgrading pytube, reinstalling it, tried some fixes, changed URLs and code, but nothing seems to work. from pytube import YouTube #ask for the link from user link = input("Enter the link of YouTube video you want to download: ") yt = YouTube(link) #Sh... | Try to upgrade, there is a fix in version 11.0.0: python -m pip install --upgrade pytube | 21 | 31 |
68,720,486 | 2021-8-10 | https://stackoverflow.com/questions/68720486/how-to-fix-function-symbol-pango-context-set-round-glyph-positions-error | I have deployed a Django project using Apache2, everything is working fine except for weazyprint which creates PDF file for forms. The pdf was working fine in testing and local host. Now everytime I access the pdf it is showing this error: FileNotFoundError at /business_plan/businessplan/admin/info/2/pdf/ [Errno 2] No ... | I had also faced the same error 'pango_context_set_round_glyph_positions' not found in library i think you must be using weasyprint version 53.0 which requires pango version 1.44.0+ downgrading the weasyprint version to 52.5 solved my issue.because this does not require recent version of pango. you can also check thi... | 29 | 36 |
68,727,546 | 2021-8-10 | https://stackoverflow.com/questions/68727546/solving-optimal-control-problem-with-constraint-x0-x2-0-with-gekko | I am starting to learn Gekko and I am testing optimal control problems. I am trying to solve the following optimal control problem with Gekko The solution of this problem is (x_1(t) = (t-2)^2 - 2) How to build the constraint x(0) + x(2) = 0? My code gives me a wrong solution. m = GEKKO(remote=False) # initialize gekko... | Use m.integral or m.vsum() to create a time weighted summation or vertical summation along the time direction. Here is a solution that replicates the exact solution. from gekko import GEKKO import numpy as np import matplotlib.pyplot as plt m = GEKKO(remote=True) # initialize gekko nt = 501 m.time = np.linspace(0,2,nt... | 5 | 1 |
68,671,852 | 2021-8-5 | https://stackoverflow.com/questions/68671852/best-way-to-iterate-through-elements-of-pandas-series | All of the following seem to be working for iterating through the elements of a pandas Series. I'm sure there's more ways of doing it. What are the differences and which is the best way? import pandas arr = pandas.Series([1, 1, 1, 2, 2, 2, 3, 3]) # 1 for el in arr: print(el) # 2 for _, el in arr.iteritems(): print(el) ... | TL;DR Iterating in pandas is an antipattern and can usually be avoided by vectorizing, applying, aggregating, transforming, or cythonizing. However if Series iteration is absolutely necessary, performance will depend on the dtype and index: Index Fastest if numpy dtype Fastest if pandas dtype Idiomatic Unneeded... | 14 | 40 |
68,734,504 | 2021-8-10 | https://stackoverflow.com/questions/68734504/boxplot-by-two-groups-in-pandas | I have the following dataset: df_plots = pd.DataFrame({'Group':['A','A','A','A','A','A','B','B','B','B','B','B'], 'Type':['X','X','X','Y','Y','Y','X','X','X','Y','Y','Y'], 'Value':[1,1.2,1.4,1.3,1.8,1.5,15,19,18,17,12,13]}) df_plots Group Type Value 0 A X 1.0 1 A X 1.2 2 A X 1.4 3 A Y 1.3 4 A Y 1.8 5 A Y 1.5 6 B X 15.0... | As @Prune mentioned, the immediate issue is that your groupby() returns four groups (AX, AY, BX, BY), so first fix the indexing and then clean up a couple more issues: Change axs[i] to axs[i//2] to put groups 0 and 1 on axs[0] and groups 2 and 3 on axs[1]. Add positions=[i] to place the boxplots side by side rather th... | 5 | 3 |
68,719,486 | 2021-8-9 | https://stackoverflow.com/questions/68719486/checksummismatcherror-conda-detected-a-mismatch-between-the-expected-content-an | I have installed many many packages including torch, gpytorch, ... in the past in Windows, Ubuntu and Mac following this scenario: conda create -n env_name conda activate env_name conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia However, this time on Ubuntu, I interfered the following... | The PyTorch channel maintainers had an issue when uploading some new package builds, which has since been resolved (see GitHub Issue). The technical cause was uploading new builds with identical versions and build numbers as before, without replacing the previous build. This caused the expected MD5 checksum to correspo... | 5 | 1 |
68,732,114 | 2021-8-10 | https://stackoverflow.com/questions/68732114/how-can-i-select-rows-except-last-row-of-one-column | I'd like to select one column only but all the rows except last row. If I did it like below, the result is empty. a = data_vaf.loc[:-1, 'Area'] | loc:location iloc:index location. They just can't operate implicitly. Therefore we exclude last raw by iloc then select the column Area As shown by the comment from @ThePyGuy data_vaf.iloc[:-1]['Area'] Here's the structure of iloc[row, column] And iloc[row] do the same thing as iloc[row,:] df.iloc[:-1] do the same th... | 4 | 6 |
68,731,560 | 2021-8-10 | https://stackoverflow.com/questions/68731560/valueerror-axes-dont-match-array-cant-transpose-an-array | Traceback Error Traceback (most recent call last): File "C:\Users\trial2\trial.py", line 55, in <module> image_stack(image) File "C:\Users\trial2\trial.py", line 41, in image_stack transposed_axes = np.transpose(img, axes=concat) File "<__array_function__ internals>", line 5, in transpose File "C:\Users\trial2\venv\lib... | The type of the axes argument doesn't matter: In [96]: arr = np.ones( [720, 1280, 3 ] ) In [97]: np.transpose(arr,[0,1,2]).shape Out[97]: (720, 1280, 3) In [98]: np.transpose(arr,(0,1,2)).shape Out[98]: (720, 1280, 3) In [99]: np.transpose(arr,np.array([0,1,2])).shape Out[99]: (720, 1280, 3) but if I provide more valu... | 8 | 6 |
68,726,290 | 2021-8-10 | https://stackoverflow.com/questions/68726290/setting-learning-rate-for-stochastic-weight-averaging-in-pytorch | Following is a small working code for Stochastic Weight Averaging in Pytorch taken from here. loader, optimizer, model, loss_fn = ... swa_model = torch.optim.swa_utils.AveragedModel(model) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=300) swa_start = 160 swa_scheduler = SWALR(optimizer, swa_l... | does the above code imply that for the first 160 epochs the learning rate for training will be 1e-4 No it won't be equal to 1e-4, during the first 160 epochs the learning rate is managed by the first scheduler scheduler. This one is a initialize as a torch.optim.lr_scheduler.CosineAnnealingLR. The learning rate wil... | 5 | 8 |
68,722,516 | 2021-8-10 | https://stackoverflow.com/questions/68722516/exclude-some-attributes-from-str-representation-of-a-dataclass | We have this class: from dataclasses import dataclass, field from datetime import datetime from typing import List, Dict @dataclass class BoardStaff: date: str = datetime.now() fullname: str address: str ## attributes to be excluded in __str__: degree: str rank: int = 10 badges: bool = False cases_dict: Dict[str, str] ... | Obvious solution Simply define your attributes as fields with the argument repr=False: from dataclasses import dataclass, field from datetime import datetime from typing import List, Dict @dataclass class BoardStaff: date: str = datetime.now() fullname: str address: str ## attributes to be excluded in __str__: degree: ... | 21 | 32 |
68,647,962 | 2021-8-4 | https://stackoverflow.com/questions/68647962/identify-current-thread-in-concurrent-futures-threadpoolexecutor | the following code has 5 workers .... each opens its own worker_task() with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: future_to_url = {executor.submit(worker_task, command_, site_): site_ for site_ in URLS} for future in concurrent.futures.as_completed(future_to_url): url = future_to_url[future]... | You can get name of worker thread with the help of threading.current_thread() function. Please find some example below: from concurrent.futures import ThreadPoolExecutor, Future from threading import current_thread from time import sleep from random import randint # imagine these are urls URLS = [i for i in range(100)]... | 6 | 8 |
68,721,853 | 2021-8-10 | https://stackoverflow.com/questions/68721853/how-to-fix-google-sheets-api-has-not-been-used-in-project | I want to built a questionnaire line chatbot and transmit the answer to google sheet. Here is my code: ''' import os from flask import Flask, request, abort from linebot import ( LineBotApi, WebhookHandler ) from linebot.exceptions import ( InvalidSignatureError ) from linebot.models import ( MessageEvent, TextMessage,... | Google Sheets API has not been used in project 10137149515 before or it is disabled. Enable it by visiting This is a settings issue in your Google cloud console account if you follow the link to your project When you set up your project you need to tell google which APIs you intend to use you have forgotten to add th... | 10 | 12 |
68,718,381 | 2021-8-9 | https://stackoverflow.com/questions/68718381/why-does-the-key-kwargs-appear-when-using-kwargs | Why does {'kwargs':{'1':'a', '2':'b'}} appear when I run test_func()? I would have expected just this to print: {'1':'a', '2':'b'}. Code: class MyClass: def __init__(self, **kwargs): self.kwargs = kwargs def test_func(self): print(self.kwargs) test_kwargs = {'1':'a', '2':'b'} my_class = MyClass(kwargs=test_kwargs) my_c... | It's because you initialize the instance by passing 1 keyword argument named kwargs with the dictionary as value. If you want to see the dictionary as kwargs, you need to call in using my_class = MyClass(**test_kwargs) | 4 | 7 |
68,715,304 | 2021-8-9 | https://stackoverflow.com/questions/68715304/dual-x-axis-with-same-data-different-scale | I'd like to plot some data in Python using two different x-axes. For ease of explanation, I will say that I want to plot light absorption data, which means I plot absorbance vs. wavelength (nm) or energy (eV). I want to have a plot where the bottom axis denotes the wavelength in nm, and the top axis denotes energy in e... | In your code example, you plot the same data twice (albeit transformed using E=h*c/wl). I think it would be sufficient to only plot the data once, but create two x-axes: one displaying the wavelength in nm and one displaying the corresponding energy in eV. Consider the adjusted code below: import numpy as np import mat... | 5 | 2 |
68,716,239 | 2021-8-9 | https://stackoverflow.com/questions/68716239/passing-query-prameters-in-an-api-request | Why do I need to use a dictionary and set the parameters? Such as lat, lng in following: parameters = { "lat": MY_LAT, "lng": MY_LONG, "formatted": 0 } response = requests.get(url="https://api.sunrise-sunset.org/json", params=parameters) Why can't I do the below, for instance to put in latitude? response = requests.ge... | You can't pass the arguments by name because the Python requests library doesn't know what parameters a given URL accepts. The API at sunrise-sunset.org takes lat and lng parameters, but most other APIs would have no use for them. By passing a dictionary of key=value pairs, you tell requests both the names and values o... | 5 | 0 |
68,712,420 | 2021-8-9 | https://stackoverflow.com/questions/68712420/is-it-possible-to-run-isort-formatter-from-black-command-in-python | I like to get inspiration from well designed python projects. The last one that inspired me was the poetry repository. I copied a lot from that, but the subject of this post are black and isort. Both are well configured in pyproject.toml: [tool.isort] profile = "black" ... known_first_party = "poetry" [tool.black] line... | Question: does black run isort internally? No, it doesn't. isort has a profile = "black" option that makes it adhere to Black's standards though. The poetry repository itself has a pre-commit hook defined here in .pre-commit-config.yaml that makes sure isort is run (along with a couple of other tools). | 6 | 10 |
68,712,892 | 2021-8-9 | https://stackoverflow.com/questions/68712892/how-to-create-dev-requirements-txt-from-extras-require-section-of-setup-cfg | I use pip-tools to manage my dependencies and environments which perfectly generates a requirements.txt file for my package that consists of a setup.py that looks like this: #! /usr/bin/env python import os from setuptools import setup if "CI_COMMIT_TAG" in os.environ: VERSION = os.environ["CI_COMMIT_TAG"] else: VERSIO... | After digging for a while, I found my answer in another issue: $ pip-compile --extra testing --extra other | 4 | 10 |
68,708,788 | 2021-8-9 | https://stackoverflow.com/questions/68708788/running-azure-functions-with-vs-code-instanlty-fails-with-econnrefused | Yesterday I could run and debug my Azure Function project with VS Code. Today, when I'm hitting F5 ("Start Debugging"), a pop-up instantly appears with connect ECONNREFUSED 127.0.0.1:9091 I believe it's a network issue, since VS Code doesn't even open a terminal displaying "Executing task [...]". But within VS Code I... | This is so weird. I edited my launch.json back and forth, sometimes it was a valid one, sometimes it was not, and now when I'm saving my original launch.json, the configuration works. This configuration works fine: { "version": "0.2.0", "configurations": [ { "name": "Python: Current file", "type": "python", "request": ... | 5 | 3 |
68,667,893 | 2021-8-5 | https://stackoverflow.com/questions/68667893/implementing-python-decorators-in-a-toy-example | I have been trying to find a use case to learn decorators and I think I have found one which is relevant to me. I am using the following codes. In the file class1.py I have: import pandas as pd, os class myClass(): def __init__(self): fnDone = f'C:\user1\Desktop\loc1\fn.csv' if os.path.exists(fnDone): return self.Fn1()... | Because fnDone is a local variable rather than a parameter, it makes using a decorator a bit awkward. If you modify the code slightly to pass in fnDone as a parameter, it makes using a decorator more of a viable option. For example, you could make a decorator that wraps the constructor of an object, and checks if the f... | 5 | 4 |
68,703,741 | 2021-8-8 | https://stackoverflow.com/questions/68703741/using-new-in-inherited-dataclasses | Suppose I have the following code that is used to handle links between individuals and countries: from dataclasses import dataclass @dataclass class Country: iso2 : str iso3 : str name : str countries = [ Country('AW','ABW','Aruba'), Country('AF','AFG','Afghanistan'), Country('AO','AGO','Angola')] countries_by_iso2 = {... | Just because the dataclass does it behind the scenes, doesn't mean you classes don't have an __init__(). They do and it looks like: def __init__(self, person_id: int, country: Country): self.person_id = person_id self.country = country When you create the class with: CountryLinkFromISO2(123, 'AW') that "AW" string ge... | 7 | 8 |
68,700,008 | 2021-8-8 | https://stackoverflow.com/questions/68700008/difference-between-just-reshaping-and-reshaping-and-getting-transpose | I'm currently studying CS231 assignments and I've realized something confusing. When calculating gradients, when I first reshape x then get transpose I got the correct result. x_r=x.reshape(x.shape[0],-1) dw= x_r.T.dot(dout) However, when I reshape directly as the X.T shape it doesn't return the correct result. dw = ... | While both your approaches result in arrays of same shape, there will by a difference in the order of elements due to the way numpy reads / writes elements. By default, reshape uses a C-like index order, which means the elements are read / written with the last axis index changing fastest, back to the first axis index ... | 6 | 8 |
68,701,240 | 2021-8-8 | https://stackoverflow.com/questions/68701240/fastapi-post-request-with-bytes-object-got-422-error | I am writing a python post request with a bytes body: with open('srt_file.srt', 'rb') as f: data = f.read() res = requests.post(url='http://localhost:8000/api/parse/srt', data=data, headers={'Content-Type': 'application/octet-stream'}) And in the server part, I tried to parse the body: app = FastAPI() BaseConfig.arbit... | FastAPI by default will expect you to pass json which will parse into a dict. It can't do that if it's isn't json, which is why you get the error you see. You can use the Request object instead to receive arbitrary bytes from the POST body. from fastapi import FastAPI, Request app = FastAPI() @app.get("/foo") async def... | 6 | 11 |
68,697,824 | 2021-8-8 | https://stackoverflow.com/questions/68697824/numpy-error-when-importing-pandas-with-aws-lambda | I'm currently have an issue with importing the library pandas to my AWS Lambda Function. I have tried two scenarios. Installing pandas directly into one folder with my lambda_function and uploading the zipped file. Creating a layer with an uploaded zip file with the following structure: - python - lib - python3.8 -... | I have solved the issue, thanks to this article: https://korniichuk.medium.com/lambda-with-pandas-fd81aa2ff25e In my case, I cannot normally install the libraries through pip, I'm on a windows machine. You must install the linux versions of pandas and numpy. Since I'm on python 3.8 I installed these versions: numpy-1.... | 11 | 7 |
68,695,851 | 2021-8-7 | https://stackoverflow.com/questions/68695851/mypy-cannot-find-implementation-or-library-stub-for-module | I have: foo/ ├── __init__.py ├── bar.py └── baz ├── __init__.py └── alice.py In bar.py, I import Alice, which is an empty class with nothing in it but the name attribute set to "Alice". from baz.alice import Alice a = Alice() print(a.name) This runs properly: $ python foo/bar.py Alice But mypy complains: $ mypy --ve... | mypy has its own search path for imports and does not resolve imports exactly as Python does and it isn't able to find the baz.alice module. Check the documentation listed in the error message, specifically the section on How imports are found: The rules for searching for a module foo are as follows: The search looks ... | 50 | 44 |
68,688,309 | 2021-8-6 | https://stackoverflow.com/questions/68688309/why-does-dask-seem-to-store-parquet-inefficiently | When I save the same table using Pandas and Dask into Parquet, Pandas creates a 4k file, wheres Dask creates a 39M file. Create the dataframe import pandas as pd import pyarrow as pa import pyarrow.parquet as pq import dask.dataframe as dd n = int(1e7) df = pd.DataFrame({'col': ['a'*64]*n}) Save it in different ways #... | Dask appears to be saving an int64 index... >>> meta.row_group(0).column(1) <pyarrow._parquet.ColumnChunkMetaData object at 0x7fa41e1babd0> file_offset: 40308181 file_path: physical_type: INT64 num_values: 10000000 path_in_schema: __null_dask_index__ is_stats_set: True statistics: <pyarrow._parquet.Statistics object at... | 5 | 4 |
68,677,902 | 2021-8-6 | https://stackoverflow.com/questions/68677902/is-there-complete-documentation-for-setup-cfg | The Python Packaging Tutorial recommends that "Static metadata (setup.cfg) should be preferred. Dynamic metadata (setup.py) should be used only as an escape hatch when absolutely necessary. setup.py used to be required, but can be omitted with newer versions of setuptools and pip." The guide to packaging and distributi... | Yes, in the documentation of the setuptools. Here it is: https://setuptools.readthedocs.io/en/latest/userguide/declarative_config.html | 34 | 19 |
68,676,637 | 2021-8-6 | https://stackoverflow.com/questions/68676637/attributeerror-word2vec-object-has-no-attribute-most-similar-word2vec | I am using Word2Vec and using a wiki trained model that gives out the most similar words. I ran this before and it worked but now it gives me this error even after rerunning the whole program. I tried to take off return_path=True but im still getting the same error print(api.load('glove-wiki-gigaword-50', return_path=T... | You are probably looking for <MODEL>.wv.most_similar, so please try: model.wv.most_similar("glass") | 5 | 18 |
68,683,160 | 2021-8-6 | https://stackoverflow.com/questions/68683160/how-to-add-to-annotations-using-the-fmt-option-of-bar-label | I'm trying to use the new bar_label option in Matplotlib but am unable to find a way to append text e.g. '%' after the label values. Previously, using ax.text I could use f-strings, but I can't find a way to use f-strings with the bar-label approach. fig, ax = plt.subplots(1, 1, figsize=(12,8)) hbars = ax.barh(wash_nee... | I found a way to append '%' to the label figures - add an additional '%%' ax.bar_label(hbars, fmt='%.2f%%', padding=3) Working Example import pandas as pd import seaborn as sns # for tips data tips = sns.load_dataset('tips').loc[:15, ['total_bill', 'tip']] tips.insert(2, 'tip_percent', tips.tip.div(tips.total_bill).mu... | 6 | 14 |
68,682,091 | 2021-8-6 | https://stackoverflow.com/questions/68682091/docker-postgres-role-does-not-exist | I am using postgres with docker and having trouble with it. I successfully docker-compose up --build When I run below command it works fine. psql starts with my_username user as expected. I can see my database, \l, \dt commands works ok. docker-compose exec db psql --username=my_username --dbname=my_database But when... | You have changed the default username/database/password that the postgres database is initialized with by providing the POSTGRES_USER, POSTGRES_DB, and POSTGRES_PASSWORD environment variables. When you run createuser without a -U option, it tries to connect as the current user (postgres in this case) which doesn't exis... | 6 | 0 |
68,682,209 | 2021-8-6 | https://stackoverflow.com/questions/68682209/parse-json-without-quotes-in-python | I am trying to parse JSON input as string in Python, not able to parse as list or dict since the JSON input is not in a proper format (Due to limitations in the middleware can't do much here.) { "Records": "{Output=[{_fields=[{Entity=ABC , No=12345, LineNo= 1, EffDate=20200630}, {Entity=ABC , No=567, LineNo= 1, EffDate... | If the producer of the data is consistent, you can start with something like the following, that aims to bridge the JSON gap. import re import json source = { "Records": "{Output=[{_fields=[{Entity=ABC , No=12345, LineNo= 1, EffDate=20200630}, {Entity=ABC , No=567, LineNo= 1, EffDate=20200630}]}" } s = source["Records"... | 5 | 3 |
68,675,254 | 2021-8-6 | https://stackoverflow.com/questions/68675254/how-can-i-scroll-down-using-selenium | The code is as below. driver = webdriver.Chrome(chromedriver_path) #webdriver path driver.get('https://webtoon.kakao.com/content/%EB%B0%94%EB%8B%88%EC%99%80-%EC%98%A4%EB%B9%A0%EB%93%A4/1781') #website access time.sleep(2) driver.execute_script("window.scrollTo(0, 900)") #scroll down time.sleep(1) However, the page doe... | Tried with the below code, it did scroll. driver.get("https://webtoon.kakao.com/content/%EB%B0%94%EB%8B%88%EC%99%80-%EC%98%A4%EB%B9%A0%EB%93%A4/1781") time.sleep(2) options = driver.find_element_by_xpath("//div[@id='root']/main/div/div/div/div[1]/div[3]/div/div/div[1]/div/div[2]/div/div[1]/div/div/div/div") driver.exec... | 4 | 3 |
68,670,406 | 2021-8-5 | https://stackoverflow.com/questions/68670406/why-do-seaborn-countplots-and-histplots-display-the-same-hexadecimal-color-diffe | I'm trying to keep a singular color palette in my thesis, and I noticed that the blue of my histplots and the blue of my countplots are slightly different shades, even though I set them to the exact same hexadecimal value. Is there a setting that I'm missing or do these different plots not just show the hexadecimal as ... | The countplot has a saturation parameter (more saturation is more "real" color, less saturation is closer to grey). Seaborn uses saturation in bar plots to make the default colors look "smoother". The default saturation is 0.75; it can be set to 1 to get the "true" color. The histplot has an alpha parameter, making the... | 5 | 7 |
68,671,158 | 2021-8-5 | https://stackoverflow.com/questions/68671158/how-to-check-python-scripts-for-f-strings-which-are-missing-the-f-literal-for | I often forget to prefix formatted strings with "f". A buggy example: text = "results is {result}" Where it should be text = f"results is {result}" I make this error A LOT; my IDE don't report it, and the program runs without exceptions. I thought maybe to scan my source code for quoted strings, check for {,} character... | The problem is that text = "results is {result}" is a valid template string, so you can later use it in your program like: >>> text.format(result=1) 'results is 1' >>> text.format(result=3) 'results is 3' What you can achieve is just checking if an f-string does indeed use variables inside, like pylint and flake8 alre... | 5 | 4 |
68,671,051 | 2021-8-5 | https://stackoverflow.com/questions/68671051/special-text-to-latin-characters-in-python | I have the following pandas data frame: the_df = pd.DataFrame({'id':[1,2],'name':['Joe','𝒮𝒶𝓇𝒶𝒽']}) the_df id name 0 1 Joe 1 2 𝒮𝒶𝓇𝒶𝒽 As you can see, we can read the second name as "Sarah", but it's written with special characters. I want to create a new column with these characters converted to latin characte... | Try .str.normalize the_df['name'].str.normalize('NFKC').str.extract(r'(^[a-zA-Z\s]*)') Output: 0 0 Joe 1 Sarah | 5 | 5 |
68,669,841 | 2021-8-5 | https://stackoverflow.com/questions/68669841/how-can-i-use-this-complex-number-in-numpy-matrix | Here's the Python code I'm working on: def inver_hopf(x,y,z): return (1/np.sqrt(x**2+y**2+(1+z)**2))*np.matrix([[1+z],[x+y.j]],dtype=complex) The problem happens at [x+y.j], where j means complex unit. It returns me the error message AttributeError: 'int' object has no attribute 'j'. If I remove the dot, then it retur... | j alone is a variable, you can have the complex number by typing 1j | 4 | 5 |
68,668,895 | 2021-8-5 | https://stackoverflow.com/questions/68668895/when-i-run-the-code-it-says-typeerror-unlink-got-an-unexpected-keyword-argum | This is my code. It is everything I have in my programme: from pathlib import Path new_dir = Path.home() / "new_directory" file_path = new_dir / "program2.py" file_path.unlink(missing_ok=True) The file program2.py does not exist; that is why I wanted to set the missing_ok parameter to True so that it would not raise a... | The missing_ok parameter was added to Path.unlink only on python 3.8. You should upgrade python to newer version if you want to use this parameter. You can check your python version with the command python -V | 11 | 17 |
68,664,973 | 2021-8-5 | https://stackoverflow.com/questions/68664973/create-sqlalchemy-session-on-event | If I want to use database while processing a request, I make a Dependency Injection like this: @app.post("/sample_test") async def sample_test(db: Session = Depends(get_db)): return db.query(models.User.height).all() But I cannot do it with events like this: @app.on_event("startup") async def sample_test(db: Session =... | Instead of using a dependency you can import the SessionLocal you've created as shown in the FastAPI manual and use a contextmanager to open and close this session: @app.on_event("startup") async def sample_test(): with SessionLocal() as db: return db.query(models.User.height).all() | 5 | 4 |
68,664,644 | 2021-8-5 | https://stackoverflow.com/questions/68664644/how-can-i-convert-from-utc-time-to-local-time-in-python | So, I want to convert UTC date time 2021-08-05 10:03:24.585Z to Indian date time how to convert it? What I tried is from datetime import datetime from pytz import timezone st = "2021-08-05 10:03:24.585Z" datetime_object = datetime.strptime(st, '%Y-%m-%d %H:%M:%S.%fZ') local_tz = timezone('Asia/Kolkata') start_date = lo... | You can use sth like this: from datetime import datetime from dateutil import tz from_zone = tz.gettz('UTC') to_zone = tz.gettz('Asia/Kolkata') utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S') utc = utc.replace(tzinfo=from_zone) central = utc.astimezone(to_zone) | 4 | 7 |
68,663,853 | 2021-8-5 | https://stackoverflow.com/questions/68663853/filter-list-of-object-with-condition-in-python | I have a list structure like this: listpost = [ { "post_id":"01", "text":"abc", "time": datetime.datetime(2021, 8, 5, 15, 53, 19), "type":"normal", }, { "post_id":"02", "text":"nothing", "time":datetime.datetime(2021, 8, 5, 15, 53, 19), "type":"normal", } ] I want to filter the list by text in [text] key if only the [... | Since you specifically asked about filtering the list you have, you can use filter builtin with lambda to filter out the elements from the list. >>> list(filter(lambda x: x.get('text', '')=='abc', listpost)) [{'post_id': '01', 'text': 'abc', 'time': datetime.datetime(2021, 8, 5, 15, 53, 19), 'type': 'normal'}] But I'd... | 10 | 12 |
68,660,700 | 2021-8-5 | https://stackoverflow.com/questions/68660700/how-exactly-is-a-decimal-object-encoded-in-python | I'm currently writing code using decimal.Decimal in python (v3.8.5). I was wondering if anyone knows how the Decimal object is actually encoded. I can't understand why the memory size is the same even if I change getcontext().prec, which is equal to change coefficients and exponent in decimal floating-points, as follow... | For sys.getsizeof: Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. Since Decimal is a Python class with references to several other objects (EDIT: see below), you just get the total size of the references, which is constant — not incl... | 9 | 6 |
68,660,642 | 2021-8-5 | https://stackoverflow.com/questions/68660642/how-can-i-open-a-new-tab-with-selenium-python | I'm trying to make a program that opens multiple websites, but I can't get it to press control-t. I've tried multiple solutions, but I can't find one that works. When I do the keydown method, I get an error that says webdriver has no attribute key_down and when I try send_keys(Keys.CONTROL + 't') it doesn't raise any ... | You can do it as from selenium import webdriver driver.get("https://www.youtube.com") search = driver.find_element_by_id("search") driver.execute_script("window.open('https://www.google.com')") | 5 | 8 |
68,655,717 | 2021-8-4 | https://stackoverflow.com/questions/68655717/is-it-possible-to-freeze-a-dataclass-object-in-post-init-or-later | I'm wondering whether it's possible to "freeze" a dataclass object in post_init() or even after an object was defined. So instead of: @dataclass(frozen=True) class ClassName: var1: type = value Having something like: @dataclass class ClassName: var1: type = None def __post_init__(self): self.var1 = value FREEZE() Or ... | No, it isn't. But "frozen" can be subverted trivially, just use: @dataclass(frozen=True) class ClassName: var1: type = value def __post_init__(self): object.__setattr__(self, 'var1', value) | 5 | 5 |
68,654,842 | 2021-8-4 | https://stackoverflow.com/questions/68654842/pandas-to-sql-server-speed-python-bulk-insert | This is probably a highly discussed topic, but i have not found "the answer" yet. I am inserting big tables into Azure SQL Server monthly. I process the raw data in memory with python and Pandas. I really like the speed and versatility of Pandas. Sample DataFrame size = 5.2 million rows, 50 columns, 250 MB memory alloc... | I had a similar issue, and I resolved it using a BCP utility. The basic description of the bottleneck issue is that it seems to be using RBAR data entry, as in Row-By-Agonizing-Row inserts, i.e. one insert statement/record. Going the bulk insert route has saved me a lot of time. The real benefit seemed to come once I c... | 5 | 4 |
68,650,162 | 2021-8-4 | https://stackoverflow.com/questions/68650162/fastapi-receive-list-of-objects-in-body-request | I need to create an endpoint that can receive the following JSON and recognize the objects contained in it: { "data": [ { "start": "A", "end": "B", "distance": 6 }, { "start": "A", "end": "E", "distance": 4 } ] } I created a model to handle a single object: class GraphBase(BaseModel): start: str end: str distance... | This is a working example. from typing import List from pydantic import BaseModel from fastapi import FastAPI app = FastAPI() class GraphBase(BaseModel): start: str end: str distance: int class GraphList(BaseModel): data: List[GraphBase] @app.post("/dummypath") async def get_body(data: GraphList): return data I could ... | 9 | 12 |
68,644,548 | 2021-8-4 | https://stackoverflow.com/questions/68644548/simultaneous-assignment-indexing-different-list-elements-in-python | >>arr = [4, 2, 1, 3] >>arr[0], arr[arr[0]-1] = arr[arr[0]-1], arr[0] >>arr Result I expect >>[3, 2, 1, 4] Result I get >>[3, 2, 4, 3] Basically I'm trying to swap the #4 and #3 (In my actual problem, the index wont be 0, but rather an iterator "i" . So I cant just do arr[0], arr[3] = arr[3], arr[0]) I thought I unders... | Because the target list does not get evaluated simultaneously. Here is the relevant section of the docs: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets. Two things to keep in mind, the r... | 14 | 11 |
68,596,593 | 2021-7-30 | https://stackoverflow.com/questions/68596593/how-to-automatically-break-long-string-constants-in-python-code-using-black-form | Python formatting guidelines, the famous PEP8 recommends no line longer than 79 chars. I can easily auto-format my code to a max line length with the Black Formatter, but it does not break long strings. The linter will still complain about a long URL in your code and Black won't help. Is it possible to automatically br... | Edit 2024-05-27: updating for new black and VSCode configurations. First you must install VSCode Black Extension. Yes it is possible due to a new feature. First make sure that you have a very recent Black formatter installed. Now just run black with the option --preview. In VSCode you can configure it in your settings.... | 10 | 11 |
68,606,661 | 2021-8-1 | https://stackoverflow.com/questions/68606661/what-is-difference-between-nn-module-and-nn-sequential | I am just learning to use PyTorch as a beginner. If anyone is familiar with PyTorch, would you tell me the difference between nn.Module and nn.Sequential? My questions are What is the advantage to use nn.Module instead of nn.Sequential? Which is regularly utilised to build the model? How we should select nn.Module o... | TLDR; answering your questions What is the advantage to use nn.Module instead of nn.Sequential? While nn.Module is the base class to implement PyTorch models, nn.Sequential is a quick way to define a sequential neural network structures inside or outside an existing nn.Module. Which is regularly utilized to build... | 32 | 62 |
68,593,165 | 2021-7-30 | https://stackoverflow.com/questions/68593165/what-is-the-difference-between-cached-property-in-django-vs-pythons-functools | Django has a decorator called cached_property which can be imported from django.utils.functional. On the other hand, Python 3.8 added cached_property to the standard library which can be imported from functools. Are both equivalent, i.e., are they interchangeable? or what is the difference between both? Are there any b... | After some research both basically work the same way and the only difference you would see would be in the error handling and performance. There is a ticket #30949 on Django's issue tracker to use functools.cached_property instead of django.utils.functional.cached_property. You can see the source code [GitHub] for func... | 28 | 27 |
68,620,927 | 2021-8-2 | https://stackoverflow.com/questions/68620927/installing-scipy-and-scikit-learn-on-apple-m1 | The installation on the m1 chip for the following packages: Numpy 1.21.1, pandas 1.3.0, torch 1.9.0 and a few other ones works fine for me. They also seem to work properly while testing them. However when I try to install scipy or scikit-learn via pip this error appears: ERROR: Failed building wheel for numpy Failed to... | UPDATE: scikit-learn now works via pip ✅ Just first brew install openblas - it has instructions for different processors (wikipedia) brew install openblas export OPENBLAS=$(/opt/homebrew/bin/brew --prefix openblas) export CFLAGS="-falign-functions=8 ${CFLAGS}" # ^ no need to add to .zshrc, just doing this once. pip ins... | 31 | 47 |
68,640,984 | 2021-8-3 | https://stackoverflow.com/questions/68640984/how-to-stop-google-colab-runtime-without-it-automatically-restarting | I want to stop a Google Colab notebook programmatically when the thing I want to do has ended, I thought of putting a line at the end that would stop it from running. I have tried these, but none work. They all restart instead of shutting down or then just give an error. I got these from here: Is there a function in g... | Now (since September 12th, 2022) you can do this: from google.colab import runtime runtime.unassign() It was announced in this GitHub issue: https://github.com/googlecolab/colabtools/issues/2568. Thanks @HappyFace for commenting this link. | 6 | 4 |
68,596,302 | 2021-7-30 | https://stackoverflow.com/questions/68596302/f1-score-metric-per-class-in-tensorflow | I have implemented the following metric to look at Precision and Recall of the classes I deem relevant. metrics=[tf.keras.metrics.Recall(class_id=1, name='Bkwd_R'),tf.keras.metrics.Recall(class_id=2, name='Fwd_R'),tf.keras.metrics.Precision(class_id=1, name='Bkwd_P'),tf.keras.metrics.Precision(class_id=2, name='Fwd_P')... | As is mentioned in David Harris' comment, a neural network model is trained on loss functions, not on metric scores. Losses help drive the model towards a solution to provide accurate labels via backpropagation. Metrics help to provide a comparable evaluation of that model's performance that are a lot more human-legibl... | 5 | 5 |
68,611,397 | 2021-8-1 | https://stackoverflow.com/questions/68611397/pos-weight-in-binary-cross-entropy-calculation | When we deal with imbalanced training data (there are more negative samples and less positive samples), usually pos_weight parameter will be used. The expectation of pos_weight is that the model will get higher loss when the positive sample gets the wrong label than the negative sample. When I use the binary_cross_entr... | TLDR; both losses are identical because you are computing the same quantity: both inputs are identical, the two batch elements and labels are just switched. Why are you getting the same loss? I think you got confused in the usage of F.binary_cross_entropy_with_logits (you can find a more detailed documentation page wi... | 5 | 11 |
68,611,570 | 2021-8-1 | https://stackoverflow.com/questions/68611570/vsc-how-to-auto-close-curly-brackets-in-f-strings | Hi I want to ask if it's possible to enable auto closing curly brackets in f-strings in Visual Studio Code. In Python you use often f-strings and therefore you need curly brackets. print(f"Hello {name}!") I already found something but I don't know if that feature is already implemented and if not if I can implement it... | Use the "Always" Auto Closing Brackets setting, but limit it to Python in your settings.json: "[python]": { "editor.autoClosingBrackets": "always" } | 4 | 6 |
68,578,277 | 2021-7-29 | https://stackoverflow.com/questions/68578277/adding-a-nullable-column-in-spark-dataframe | In Spark, literal columns, when added, are not nullable: from pyspark.sql import SparkSession, functions as F spark = SparkSession.builder.getOrCreate() df = spark.createDataFrame([(1,)], ['c1']) df = df.withColumn('c2', F.lit('a')) df.printSchema() # root # |-- c1: long (nullable = true) # |-- c2: string (nullable = f... | The shortest method I've found - using when (the otherwise clause seems not needed): df = df.withColumn('c2', F.when(F.lit(True), F.lit('a'))) If in Scala: .withColumn("c2", when(lit(true), lit("a"))) Full test result: from pyspark.sql import SparkSession, functions as F spark = SparkSession.builder.getOrCreate() df ... | 7 | 11 |
68,571,543 | 2021-7-29 | https://stackoverflow.com/questions/68571543/using-a-pip-requirements-file-in-a-conda-yml-file-throws-attributeerror-fileno | I have a requirements.txt like numpy and an environment.yml containing # run via: conda env create --file environment.yml --- name: test dependencies: - python>=3 - pip - pip: - -r file:requirements.txt when I then run conda env create --file environment.yml I get Pip subprocess output: Pip subprocess error: ERROR: ... | Changes to Pip Behavior in 21.2.1 A recent change in the Pip code has changed its behavior to be more strict with respect to file: URI syntax. As pointed out by a PyPA member and Pip developer, the syntax file:requirements.txt is not a valid URI according to the RFC8089 specification. Instead, one must either drop the ... | 21 | 32 |
68,561,453 | 2021-7-28 | https://stackoverflow.com/questions/68561453/m1-mac-gdal-wrong-architecture-error-django | I'm trying to get a django project up and running, which depends on GDAL library. I'm working on a M1 based mac. Following the instructions on official Django docs, I've installed the necessary packages via brew $ brew install postgresql $ brew install postgis $ brew install gdal $ brew install libgeoip gdalinfo --ver... | GDAL and Python are likely compiled for different CPU architectures. On an M1 system the OS can run both native arm64 and emulated x86_64 binaries. To check: run file /opt/homebrew/Cellar/gdal/3.3.1_2/lib/libgdal.dylib and file $(which python3), which should show the supported CPU architectures for both. If the two don... | 12 | 7 |
68,625,748 | 2021-8-2 | https://stackoverflow.com/questions/68625748/attributeerror-cant-get-attribute-new-block-on-module-pandas-core-internal | I was using pyspark on AWS EMR (4 r5.xlarge as 4 workers, each has one executor and 4 cores), and I got AttributeError: Can't get attribute 'new_block' on <module 'pandas.core.internals.blocks'. Below is a snippet of the code that threw this error: search = SearchEngine(db_file_dir = "/tmp/db") conn = sqlite3.connect("... | Solutions Keeping the pickle file unchanged ,upgrade your pandas version to 1.3.x and then load the pickle file. Or Keeping your current pandas version unchanged, downgrade the pandas version to 1.2.x on the dumping side, and then dump a new pickle file with v1.2.x. Load it on your side with your pandas of version 1... | 54 | 78 |
68,558,129 | 2021-7-28 | https://stackoverflow.com/questions/68558129/opening-the-second-window-using-undetected-chromedriver-selenium-python | I'm trying to open two or more separate windows. I was able to open the first window by running from selenium import webdriver import undetected_chromedriver.v2 as uc options = webdriver.ChromeOptions() options.add_argument(r"--user-data-dir=C:\Users\username\AppData\Local\Google\Chrome\User Data") drivers = list() dri... | This worked for me , I couldn't use v2 but it works in v1. import undetected_chromedriver as uc uc.install(executable_path=PATH,) drivers_dict={} def scraping_function(link): try: thread_name= threading.current_thread().name #sometime we are going to have different thread name in each iteration so a little regex might... | 5 | 2 |
68,614,547 | 2021-8-1 | https://stackoverflow.com/questions/68614547/tensorflow-libdevice-not-found-why-is-it-not-found-in-the-searched-path | Win 10 64-bit 21H1; TF2.5, CUDA 11 installed in environment (Python 3.9.5 Xeus) I am not the only one seeing this error; see also (unanswered) here and here. The issue is obscure and the proposed resolutions are unclear/don't seem to work (see e.g. here) Issue Using the TF Linear_Mixed_Effects_Models.ipynb example (dow... | The diagnostic information is unclear and thus unhelpful; there is however a resolution The issue was resolved by providing the file (as a copy) at this path C:\Users\Julian\anaconda3\envs\TF250_PY395_xeus\Library\bin\nvvm\libdevice\ Note that C:\Users\Julian\anaconda3\envs\TF250_PY395_xeus\Library\bin was the path giv... | 33 | 6 |
68,582,382 | 2021-7-29 | https://stackoverflow.com/questions/68582382/how-to-pip-install-pickle-under-python-3-9-in-windows | I need the pickle package installed under my Python 3.9 under Windows 10. What I tried When trying with pip install pickle I was getting: ERROR: Could not find a version that satisfies the requirement pickle (from versions: none) ERROR: No matching distribution found for pickle Then I tried the solution suggested in ... | Cedric UPDATED answer is right. Pickle exists within Python 3.9. You don't need pip install pickle. Just use it. import pickle | 15 | 28 |
68,605,481 | 2021-7-31 | https://stackoverflow.com/questions/68605481/why-sqlalchemy-declarative-base-object-has-no-attribute-query | I created declarative table. from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String from sqlalchemy.dialects.postgresql import UUID import uuid Base = declarative_base() class User(Base): __tablename__ = 'users' id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4,... | The Model.query... idiom is not a default part of the SQLAlchemy ORM; it's a customisation provided by Flask-SQLAlchemy. It is not available in base SQLAlchemy, and that is why you get the error message. | 8 | 10 |
68,634,761 | 2021-8-3 | https://stackoverflow.com/questions/68634761/env-python3-9-no-such-file-or-directory | I have some python code formatters as git pre-commit hook and I have changed my python version as brew list | grep python python@3.7 python@3.9 brew unlink python@3.7 brew unlink python@3.9 brew link python@3.7 python -V Python 3.7.9 and know seems something get broken and on git commit I get env: python3.9: No such f... | In .git/hooks/pre-commit I have #!/usr/bin/env python3.9 and running pre-commit install fixed it to #!/usr/bin/env python3.7 | 7 | 5 |
68,624,314 | 2021-8-2 | https://stackoverflow.com/questions/68624314/do-asynchronous-context-managers-need-to-protect-their-cleanup-code-from-cancell | The problem (I think) The contextlib.asynccontextmanager documentation gives this example: @asynccontextmanager async def get_connection(): conn = await acquire_db_connection() try: yield conn finally: await release_db_connection(conn) It looks to me like this can leak resources. If this code's task is cancelled while... | Focusing on protecting the cleanup from cancellation is a red herring. There is a multitude of things that can go wrong and the context manager has no way to know which errors can occur, and which errors must be protected against. It is the responsibility of the resource handling utilities to properly handle errors. ... | 16 | 2 |
68,620,436 | 2021-8-2 | https://stackoverflow.com/questions/68620436/cannot-import-name-stop-words-from-sklearn-feature-extraction | I've been trying to follow an NLP notebook, and they use: from sklearn.feature_extraction import stop_words However, this is throwing the following error: ImportError: cannot import name 'stop_words' from 'sklearn.feature_extraction' My guess is that stop_words is not (or maybe no longer) part of the 'feature_extract... | I have sklearn version 0.24.1, and I found that the module is now private - it's called _stop_words. So: from sklearn.feature_extraction import _stop_words After a little digging, I found that this change was made in version 0.22, in response to this issue. It looks like they want people to use the "canonical" import ... | 10 | 17 |
68,617,654 | 2021-8-2 | https://stackoverflow.com/questions/68617654/error-problem-nothing-provides-usr-libexec-platform-python-needed-by-mongodb | I am using Fedora Linux and when i want to update MongoDB tools (mongodb-org-tools) or my packages via sudo dnf update i always get error like this: Error: Problem: problem with installed package mongodb-org-database-tools-extra-4.4.4-1.el8.x86_64 - cannot install the best update candidate for package mongodb-org-datab... | I also had problems installing Mongodb on Fedora 33. These problems occurred when I had the following code in /etc/yum.repos.d/mongodb-org.repo : [Mongodb] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/4.4/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-... | 10 | 7 |
68,616,000 | 2021-8-2 | https://stackoverflow.com/questions/68616000/pip-install-uwsgi-gives-error-attributeerror-module-os-has-no-attribute-un | System : Windows 10 Python : 3.9.5 I was learning to Deploying a Flask app on Google Cloud. I was trying to install uwsgi (on my windows system) as shown in this youtube video. pip install uwsgi This error is coming (flask) D:\projects\websites\googleHostFlaskApp>pip install uwsgi Collecting uwsgi Using cached uWSGI-... | Installing UWSGI wasn't an easy task. @Seraph answer did helped but he missed some points, that i did to finally install UWSGI. So here is Complete Steps so that you won't have to waste a day on this like me: Install Cygwin download (Cygwin is an open source collection of tools that allows Unix or Linux applications t... | 12 | 8 |
68,636,431 | 2021-8-3 | https://stackoverflow.com/questions/68636431/multiline-if-statement-with-a-single-conditional | Lets say I have two variables self.SuperLongSpecificCorperateVariableNameIcantChangeCommunication and self.SuperLongSpecificCorperateVariableNameIcantChangeControl And I need to compare them. The issue being that, when I put them both in an if statement, it blows past the style checker's line length. if (self.SuperLo... | Firstly, PEP 8 says you can split long lines under Maximum Line Length: Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation. In fact, the backslash in your example is not needed because of the parentheses. ... | 5 | 2 |
68,639,461 | 2021-8-3 | https://stackoverflow.com/questions/68639461/print-formatted-numpy-array | I want to print formatted numpy array along with a float with different significant figures. Consider the following code a = 3.14159 X = np.array([1.123, 4.456, 7.789]) print('a = %4.3f, X = %3.2f' % (a, X)) ------------------------ TypeError: only size-1 arrays can be converted to Python scalars I desire following ou... | Convert array to string first with array2string: print('a = %4.3f, X = %s' % (a, np.array2string(X, precision=2))) # a = 3.142, X = [1.12 4.46 7.79] | 5 | 3 |
68,637,971 | 2021-8-3 | https://stackoverflow.com/questions/68637971/how-to-detect-zstd-compression | I am currently working on a python application, that works with facebook api's. As we all know, facebook loves their own technology and is working with zstd for data compression. The problem: facebook is returning either a uncompressed response with normal json or if the response is longer, it is responding with a zstd... | What you're doing is fine. You could, I suppose, check to see if the stream starts with the four bytes 28 b5 2f fd. If it doesn't, it's not a zstd stream. If it does, it may be a zstd stream. In the latter case, you would try to decompress and if it fails, you would fall back to just copying the input. That turns out t... | 7 | 10 |
68,637,153 | 2021-8-3 | https://stackoverflow.com/questions/68637153/python-error-in-vscode-sorry-something-went-wrong-activating-intellicode-suppo | My code is not working in vscode when I click to run code I see this error: Sorry, something went wrong activating IntelliCode support for Python. Please check the "Python" and "VS IntelliCode" output windows for details. and when I tried to rerun the code I saw this message; Code is already running The code doesn'... | I would just like to add a few helpful links: Intellicode Issue 57 Intellicode Issue 266 Gitmemory issue 486082039 For a lot of people, it just began working after a few tries randomly. See this text (quoted from issue 57): There's a race condition in the activation of both the IntelliCode and Python language server e... | 13 | 8 |
68,603,585 | 2021-7-31 | https://stackoverflow.com/questions/68603585/mypy-why-does-typevar-not-work-without-bound-specified | I'm trying to understand type annotations and I have the following code: from typing import TypeVar T = TypeVar('T') class MyClass(): x: int = 10 def foo(obj: T) -> None: print(obj.x) foo(MyClass()) When I run mypy, I get the following error: main.py:9: error: "T" has no attribute "x" Found 1 error in 1 file (checked ... | This isn't what a TypeVar is usually used for. The following function is a good example of the kind of function that a TypeVar is typically used for: def baz(obj): return obj This function will work with an argument of any type, so one solution for annotating this function could be to use typing.Any, like so: from typ... | 4 | 13 |
68,631,257 | 2021-8-3 | https://stackoverflow.com/questions/68631257/how-is-str-joiniterable-method-implemented-in-python-linear-time-string-conca | I am trying to implement my own str.join method in Python, e.g: ''.join(['aa','bbb','cccc']) returns 'aabbbcccc'. I know that string concatenation using the join method would result in linear (in the number of characters of the result) complexity, and I want to know how to do it, as using the '+' operator in a for loop... | Joining str as actual str is a red herring and not what Python itself does: Python operates on mutable bytes, not the str, which also removes the need to know string internals. In specific, str.join converts its arguments to bytes, then pre-allocates and mutates its result. This directly corresponds to: a wrapper to e... | 7 | 6 |
68,631,476 | 2021-8-3 | https://stackoverflow.com/questions/68631476/how-to-find-the-index-of-the-max-value-in-a-list-for-python | I have a list, and I need to find the maximum element in the list and also record the index at which that max element is at. This is my code. list_c = [-14, 7, -9, 2] max_val = 0 idx_max = 0 for i in range(len(list_c)): if list_c[i] > max_val: max_val = list_c[i] idx_max = list_c.index(i) return list_c, max_val, idx_ma... | You are trying to find the index of i. It should be list_c[i]. Easy way/Better way is: idx_max = i. (Based on @Matthias comment above.) Use print to print the results and not return. You use return inside functions. Also your code doesn't work if list_c has all negative values because you are setting max_val to 0.... | 14 | 0 |
68,628,542 | 2021-8-2 | https://stackoverflow.com/questions/68628542/checking-if-file-exists-in-google-bucket-via-apache-airflow | I have a DAG that takes the results of a script in a Google cloud bucket, loads it into a table in Google BigQuery, then deletes the file in the bucket. I want the DAG to check every hour over the weekends. Right now, I'm using a GoogleCloudStoragetoBigQueryOperator. If the file is not there, the DAG fails. Is there a ... | You could use GCSObjectExistenceSensor from Google provider package in order to verify if the file is present before running downstream tasks. gcs_object_exists = GCSObjectExistenceSensor( bucket=BUCKET_1, object=PATH_TO_UPLOAD_FILE, mode='poke', task_id="gcs_object_exists_task", ) You can check the official example h... | 4 | 8 |
68,625,921 | 2021-8-2 | https://stackoverflow.com/questions/68625921/how-to-adjust-matplotlib-colorbar-range-in-xarray-plot | I have a plot that looks like this I cannot understand how to manually change or set the range of data values for the colorbar. I would like to experiment with ranges based on the data values shown in the plots and change the colorbar to (-4,4). I see that plt.clim, vmin and vmax are functions to possibly use. Here is... | I was able to reproduce your figure and found that I could add vmin and vmax as shown below. For some reason that meant I also had to specify the colormap, otherwise I ended up with viridis. But the code below works for me (with a bit of refactoring as I got it working — the only material change here is in the plotting... | 4 | 9 |
68,626,923 | 2021-8-2 | https://stackoverflow.com/questions/68626923/numpy-matrix-creation-timing-oddity | My application requires a starting matrix where each column is staggered-by-1 from the previous. It will contain millions of complex numbers representing a signal, but a small example is: array([[ 0, 1, 2, 3], [ 1, 2, 3, 4], [ 2, 3, 4, 5], [ 3, 4, 5, 6], [ 4, 5, 6, 7], [ 5, 6, 7, 8], [ 6, 7, 8, 9], [ 7, 8, 9, 10]]) I ... | user3483203's comment, above, provides answer to the issue. If I avoid the transpose by creating the matrix with: X = np.array([x[i:i+Np] for i in range(N)], dtype=complex) subsequent calcs() timing is as expected. Thank you, user3483203! | 5 | 3 |
68,625,894 | 2021-8-2 | https://stackoverflow.com/questions/68625894/pick-elements-from-list-of-sets-to-cover-all-sets-with-exactly-one-element | I am looking for the idiomatic and fast python solution for the following problem. Input is a list of sets. For example, 3 sets of strings. [ {a, b, c, d, e}, {a, c, e, f, g}, {e, f, a, d, l} ] I would like to find all choices of string combinations so that there is only one element in combination per set. For example... | I would use a SAT solver like z3 for this. import z3 sets = [ {"a", "b", "c", "d", "e"}, {"a", "c", "e", "f", "g"}, {"e", "f", "a", "d", "l"} ] alphabet = set.union(*sets) zvars = {w: z3.Bool(w) for w in alphabet} sol = z3.Solver() for s in sets: # Exactly one in each set. sol.add(z3.PbEq([(zvars[w], True) for w in s],... | 5 | 3 |
68,624,485 | 2021-8-2 | https://stackoverflow.com/questions/68624485/hide-play-and-stop-buttons-in-plotly-express-animation | How can I remove the play and stop buttons and just keep the slider? import plotly.express as px import pandas as pd df = pd.DataFrame(dict(x=[0, 1, 0, 1], y=[0, 1, 1, 0], z=[0, 0, 1, 1])) px.line(df, "x", "y", animation_frame="z") | fig = px.line(df, "x", "y", animation_frame="z") fig["layout"].pop("updatemenus") fig.show() | 4 | 7 |
68,616,781 | 2021-8-2 | https://stackoverflow.com/questions/68616781/customizing-the-hue-colors-used-in-seaborn-barplot | I'm using seaborn to create the following chart: I'd like to customize the colors that are generated by hue , preferably to set the order of the colors as Blue, Green, Yellow, Red. I have tried passing a color or a list of colors to the color argument in sns.barplot however it yields either gradients of the color or a... | The hue variable of seaborn.barplot() is mapped via palette: palette: palette name, list, or dict Colors to use for the different levels of the hue variable. Should be something that can be interpreted by seaborn.color_palette(), or a dictionary mapping hue levels to matplotlib colors. So to customize your hue colors... | 10 | 15 |
68,603,658 | 2021-7-31 | https://stackoverflow.com/questions/68603658/how-to-terminate-a-uvicorn-fastapi-application-cleanly-with-workers-2-when | I have an application written with Uvicorn + FastAPI. I am testing the response time using PyTest. Referring to How to start a Uvicorn + FastAPI in background when testing with PyTest, I wrote the test. However, I found the application process alive after completing the test when workers >= 2. I want to terminate the a... | I have found a solution myself. Thanks > https://stackoverflow.com/a/27034438/16567832 Solution After install psutil by pip install psutil, update test_main.py from multiprocessing import Process import psutil import pytest import requests import time import uvicorn HOST = "127.0.0.1" PORT = 8765 WORKERS = 3 def run_se... | 9 | 5 |
68,621,210 | 2021-8-2 | https://stackoverflow.com/questions/68621210/runtimeerror-expected-a-cuda-device-type-for-generator-but-found-cpu | I am trying to train PeleeNet pytorch and got the following error train.py line 80 pelee_voc train configuration | Turning the shuffle parameter off in the dataloader solved it. Got the answer form here. | 13 | 6 |
68,614,447 | 2021-8-1 | https://stackoverflow.com/questions/68614447/how-to-display-boxplot-in-front-of-violinplot-in-seaborn-seaborn-zorder | To customize the styles of the boxplot displayed inside a violinplot, on could try to plot a boxplot in front of a violinplot. However this does not seem to work as it is always displayed behind the violinplot when using seaborn. When using seaborn + matplotlib this works (but only for a single category): import matplo... | The zorder parameter of sns.boxplot only affects the lines of the boxplot, but not the rectangular box. One possibility is to access these boxes afterwards; they form the list of artists in ax.artists. Setting their zorder=2 will put them in front of the violins while still being behind the other boxplot lines. In the ... | 4 | 8 |
68,614,561 | 2021-8-1 | https://stackoverflow.com/questions/68614561/project-file-window-is-yellow-in-pycharm | I'm working with PyCharm 2019 and Django, in Windows 10 in a project that I haven't opened in a year. The Project files window is showing up as yellow, which seems new. What does this mean and how to I get the files to appear as white. | What the yellow background usually means is that the files are excluded form the project (it can also mean the files are "read-only"). This might happen for several reasons, the .idea folder might have broken and you need to delete it and recreate the project. If your project is installed in a venv sometimes the source... | 13 | 26 |
68,583,341 | 2021-7-29 | https://stackoverflow.com/questions/68583341/selenium-proxy-with-authentication | I have to use selenium and proxy with authentication. I have a few constraints I can't use selenium-wire (only pure selenium allowed) I have to use headless mode (e.g. chrome_options.add_argument("--headless")) I read this answer Python proxy authentication through Selenium chromedriver but it doesn't work for headle... | you can't because you need a GUI to handle it with selenium in your case so I would recommend using a virtual display like Xvfb display server You can use PyVirtualDisplay (a Python wrapper for Xvfb) to run headless. for Linux sudo apt-get install firefox xvfb install virtual display for python pip install pyvirtualdi... | 5 | 2 |
68,606,518 | 2021-7-31 | https://stackoverflow.com/questions/68606518/converting-pandas-dataframe-to-pyspark-dataframe-drops-index | I've got a pandas dataframe called data_clean. It looks like this: I want to convert it to a Spark dataframe, so I use the createDataFrame() method: sparkDF = spark.createDataFrame(data_clean) However, that seems to drop the index column (the one that has the names ali, anthony, bill, etc) from the original dataframe.... | Spark DataFrame has no concept of index, so if you want to preserve it, you have to assign it to a column first using reset_index in a pandas dataframe You can also use inplace to avoid additional memory overhead while resting the index df.reset_index(drop=False,inplace=True) sparkDF = sqlContext.createDataFrame(df) | 4 | 4 |
68,606,631 | 2021-8-1 | https://stackoverflow.com/questions/68606631/how-can-i-do-cross-validation-with-sample-weights | I'm trying to classify text data into multiple classes. I'd like to perform cross-validation to compare several models with sample weights. With each model, I can put a parameter like this. all_together = y_train.to_numpy() unique_classes = np.unique(all_together) c_w = class_weight.compute_class_weight('balanced', uni... | cross_val_score has a parameter called fit_params which accepts a dictionary of parameters (keys) and values to pass to the fit() method of the estimator. In your case, you can do cross_val_score(model, X_tfidf, y_train, scoring='f1_micro', cv=CV, fit_params={'sample_weight': [c_w[i] for i in all_together]}) | 5 | 10 |
68,602,274 | 2021-7-31 | https://stackoverflow.com/questions/68602274/readwritememory-reading-memory-as-an-int-instead-of-a-float | from ReadWriteMemory import ReadWriteMemory rwm = ReadWriteMemory() process = rwm.get_process_by_name("javaw.exe") process.open() module_base = 0x6FBB0000 static_address_offset = 0x007FD7C0 static_address = module_base + static_address_offset pitch_pointer = process.get_pointer(static_address, offsets=[0xB8, 0x1C8, 0x1... | You can use the struct module. Something like this: >>> import struct >>> i_value = 1108138163 >>> struct.unpack("@f", struct.pack("@I", i_value))[0] 35.21162033081055 That is, you convert your integer to a 4-byte array, and then you convert that to a float. struct.unpack always returns a tuple, in this case of a sing... | 5 | 4 |
68,591,271 | 2021-7-30 | https://stackoverflow.com/questions/68591271/how-can-i-combine-hue-and-style-groups-in-a-seaborn-legend | I'm doing a Seaborn lineplot for longitudinal data which is grouped by "Subscale" using hue and by "Item" using style. Here is my code (I hope this is understandable also without data): ax = sns.lineplot(data = df, x = 'Week', y = 'Value', style = 'Item', hue = 'Subscale', palette = 'colorblind', markers = True) plt.le... | If I understand correctly, all items of a certain type have the same subscale. So, you already have (or can create) a dictionary that maps an item type to the corresponding subscale. Seaborn creates following labels for the legend: 'Subscale' for a subtitle each of the subscales 'Item' for a second subtitle each of th... | 5 | 4 |
68,561,245 | 2021-7-28 | https://stackoverflow.com/questions/68561245/extract-or-set-input-output-tf-tensor-names-information-from-python-api-instea | I trained a simple model with Keras/TF2.5 and saved it as saved model. tf.saved_model.save(my_model,'/path/to/model') If I examine it via saved_model_cli show --dir /path/to/model --tag_set serve --signature_def serving_default I get these outputs/names: inputs['conv2d_input'] tensor_info: dtype: DT_FLOAT shape: (-1,... | The input/output tensor names displayed by saved_model_cli can be extracted as follows: from tensorflow.python.tools import saved_model_utils saved_model_dir = '/path/to/model' tag_set = 'serve' signature_def_key = 'serving_default' # 1. Load MetaGraphDef with saved_model_utils meta_graph_def = saved_model_utils.get_me... | 5 | 3 |
68,591,676 | 2021-7-30 | https://stackoverflow.com/questions/68591676/why-are-np-hypot-and-np-subtract-outer-very-fast-compared-to-vanilla-broadcast-a | I have two large sets of 2D points and need to calculate a distance matrix. I need it to be fast so I used NumPy broadcasting. Of two ways to calculate distance matrix I don't understand why one is better than the other. From here I have contradicting results. Cells [3, 4, 6] and [8, 9] both calculate the distance matr... | First of all, d0 and d1 takes each 50000 x 30000 x 8 = 12 GB which is pretty big. Make sure you have more than 100 GB of memory because this is what the whole script requires! This is a huge amount of memory. If you do not have enough memory, the operating system will use a storage device (eg. swap) to store excess dat... | 6 | 3 |
68,594,613 | 2021-7-30 | https://stackoverflow.com/questions/68594613/django-core-exceptions-fielddoesnotexist-user-has-no-field-named-username | I'm trying to customize django's AbstractUser. When I try to reset username to None, I get the following exception: "django.core.exceptions.FieldDoesNotExist: User has no field named 'username'". Here is my code: class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **ext... | You haven't set a value for USERNAME_FIELD in your code. This must be set to a field that uniquely identifies a user instance. AbstractUser sets this to 'username' and hence you are getting the error. You can set this to 'email' to solve your problem: class User(AbstractUser): username = None email = models.EmailField(... | 8 | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.