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
62,326,155
2020-6-11
https://stackoverflow.com/questions/62326155/how-to-efficiently-get-count-for-item-in-list-of-lists-in-python
I have three lists as follows. mylist = [[5274919, ["my cat", "little dog", "fish", "rat"]], [5274920, ["my cat", "parrot", "little dog"]], [5274991, ["little dog", "fish", "duck"]]] myconcepts = ["my cat", "little dog"] hatedconcepts = ["rat", "parrot"] For each concept in myconcepts, I want to get the count every ot...
I have tried to make it fast, avoided some repeated loops. Please check if this speeds things up. from itertools import chain from collections import Counter, defaultdict database = defaultdict(set) output = {} # created a map for different concepts, so we only search the indices where a certain concept is for index, (...
17
2
62,325,417
2020-6-11
https://stackoverflow.com/questions/62325417/inconsistent-behavior-when-inserting-a-set-into-cells-using-loc-in-pandas
It's a pretty simple example import pandas df = pandas.DataFrame() value_to_be_set = {'1'} df.loc[0, 'col1'] = value_to_be_set df['col2'] = None df.loc[0, 'col2'] = value_to_be_set print(df.head()) output col1 col2 0 1 {1} Why is the datatype different for both columns? Python 3.7.3 pandas version: 0.23.4
In first assignment, you create a num_column from a set, said differently from an iterable. You ask for 1 single element and provide an iterable of size one, so you affect the content of the set to the single cell. You can try to use a set of 2 values to see that it would raise an error. In second assignment, you updat...
8
7
62,304,176
2020-6-10
https://stackoverflow.com/questions/62304176/how-to-find-out-dataframe-to-numpy-did-not-create-a-copy
The pandas.DataFrame.to_numpy method has a copy argument with the following documentation: copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that copy=False does not ensure that to_numpy() is no-copy. Rather, copy=True ensure that a copy is made, even if not st...
There is numpy.shares_memory you can use: # Your first example print(np.shares_memory(array, frame)) # True, they are sharing memory # Your second example print(np.shares_memory(array2, frame2)) # False, they are not sharing memory There is also numpy.may_share_memory, which is faster but can only be used for making s...
10
6
62,319,228
2020-6-11
https://stackoverflow.com/questions/62319228/number-of-instances-per-class-in-pytorch-dataset
I'm trying to make a simple image classifier using PyTorch. This is how I load the data into a dataset and dataLoader: batch_size = 64 validation_split = 0.2 data_dir = PROJECT_PATH+"/categorized_products" transform = transforms.Compose([transforms.Grayscale(), CustomToTensor()]) dataset = ImageFolder(data_dir, transfo...
You need to use .targets to access the labels of data i.e. print(dict(Counter(dataset.targets))) It'll print something like this (e.g. in MNIST dataset): {5: 5421, 0: 5923, 4: 5842, 1: 6742, 9: 5949, 2: 5958, 3: 6131, 6: 5918, 7: 6265, 8: 5851} Also, you can use .classes or .class_to_idx to get mapping of label id to...
13
18
62,315,295
2020-6-11
https://stackoverflow.com/questions/62315295/convert-datetime-to-protobuf-timestamp-in-python
So I'm trying to prepare a message with Python that takes a Timestamp, but I'm having trouble converting a datetime to a protobuf Timestamp. Here's what I've tried so far: from google.protobuf.timestamp_pb2 import Timestamp import datetime now = datetime.datetime.now() timestamp = Timestamp() timestamp.FromDatetime(now...
This code is working fine on my machine from google.protobuf.timestamp_pb2 import Timestamp import datetime now = datetime.datetime.now() timestamp = Timestamp() timestamp.FromDatetime(now) Output: seconds: 1591859232 nanos: 803377000
8
16
62,309,487
2020-6-10
https://stackoverflow.com/questions/62309487/pybind11-init-with-lambda
I use pybind11 as a wrapper of my C++ code into a python library. It happens that there are arguments that I can't provide or sometimes I want to do a conversion/initialization that I know in the C++ side. It could be because the class is not known in python, for instance. How could that be done? The only "solution" I ...
pybind11 lets you bind factory functions as init methods. So you would have to provide a function in c++ that took a B and return an A and then you could bind that as an init method for A. An example from the pybind11 docs class Example { private: Example(int); // private constructor public: // Factory function: static...
9
10
62,299,740
2020-6-10
https://stackoverflow.com/questions/62299740/how-do-i-detect-and-invoke-a-function-when-a-python-enum-member-is-accessed
I have an enum for which some of the members are deprecated: from enum import Enum class Foo(Enum): BAR = "bar" BAZ = "baz" # deprecated How do it get the following behavior: When somebody writes Foo.BAR, everything behaves normally When somebody writes Foo.BAZ, a DeprecationWarning is issued using warnings.warn("BAZ...
This appears to be one of those times when subclassing EnumMeta is the right thing to do. The new metaclass will run an _on_access method, if it exists, whenever a member is accessed: class OnAccess(EnumMeta): """ runs a user-specified function whenever member is accessed """ # def __getattribute__(cls, name): obj = su...
8
13
62,301,268
2020-6-10
https://stackoverflow.com/questions/62301268/whenever-i-try-to-install-torch-it-displays-killed
I just want to install pytorch, I ran this in the terminal: pip install torch And it displays: Collecting torch Killed What is the problem?
It says your your free ram is not enough to install the package, but there is a method that you can still use it. pip install torch --no-cache-dir
36
112
62,267,544
2020-6-8
https://stackoverflow.com/questions/62267544/generate-pydantic-model-from-a-dict
Is there a straight-forward approach to generate a Pydantic model from a dictionary? Here is a sample of the data I have. { 'id': '424c015f-7170-4ac5-8f59-096b83fe5f5806082020', 'contacts': [{ 'displayName': 'Norma Fisher', 'id': '544aa395-0e63-4f9a-8cd4-767b3040146d' }], 'startTime': '2020-06-08T09:38:00+00:00' } Exp...
In Pydantic 2, you can use MyModel.model_validate(my_dict) to generate a model from a dictionary. According to the documentation – this is very similar to the __init__ method of the model, except it takes a dict rather than keyword arguments. If you're Pydantic 1, the method is parse_obj instead.
78
124
62,261,355
2020-6-8
https://stackoverflow.com/questions/62261355/how-to-add-watermark-in-all-pages-of-pdf-files-with-python
I'm try to adding watermark to every pages of my PDF file.My PDF files have 58 pages but my output file has get only last page in my PDF file. This's my code: from PyPDF2 import PdfFileReader, PdfFileWriter watermark_pdf = PdfFileReader("watermark.pdf") watermark_page = watermark_pdf.getPage(0) reader = PdfFileReader...
You're rewriting your "merged" file for each page. Try something like from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter pdf_file = "C:/Users/11359023/Desktop/deepfake_vee.pdf" watermark = "C:/Users/11359023/Desktop/simple.pdf" merged = "C:/Users/11359023/Desktop/merged.pdf" with open(pdf_file, "rb") as inp...
7
10
62,163,460
2020-6-3
https://stackoverflow.com/questions/62163460/remove-a-legend-section-from-a-seaborn-plot
Using the 'tips' dataset as a toy model, I generate the following plot: import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset("tips") cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True) g = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size = 'tip',sizes=(320, 600), data=tips...
I was able to find a fix by indexing the labels in the legend. import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset("tips") cmap = sns.cubehelix_palette(dark=.3, light=.8, as_cmap=True) ax = sns.scatterplot(x="total_bill", y="sex", hue="smoker", size='tip', sizes=(320, 600), data=tips) # extrac...
12
13
62,240,559
2020-6-7
https://stackoverflow.com/questions/62240559/closing-open-positions-on-binance
I am using the Binance Python API (Python 3.x) When one uses the “create_order” functionality, it creates an order on the SPOT exchange with a STATUS of NEW. When it gets filled, the STATUS goes to FILLED. Also, when it is FILLED, my understanding is that a POSITION is being created (Long or Short) My question is as fo...
Also, when it is FILLED, my understanding is that a POSITION is being created (Long or Short) As far as I know, Binance does not provide semantics for position (in terms of trading). Such abstractions are usually implemented for derivatives (e.g. futures) when it comes to currency markets, since currencies buying-and...
7
2
62,288,835
2020-6-9
https://stackoverflow.com/questions/62288835/how-to-interpret-conda-package-conflicts
I am attempting to create a conda environment with 3 packages and a specific python version and get the following output: $ conda create -n testing_junk -y instrain awscli samtools python=3.8 Collecting package metadata (current_repodata.json): done Solving environment: failed with repodata from current_repodata.json, ...
Some Practical Advice @Quantum7's answer gives a fine literal interpretation of Conda's conflict reporting. However, I wanted to offer a more practical take, which is that this "feature" from Conda is too non-specific to be useful in most non-trivial environments. And sometimes it won't even include the underlying conf...
39
34
62,178,888
2020-6-3
https://stackoverflow.com/questions/62178888/can-someone-explain-to-me-how-minmaxscaler-works
Why we are using the MinMaxScaler() and what does it do? scaler = MinMaxScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) model = LogisticRegression() model.fit(X_train, y_train) y_pred = model.predict(X_test)
Core of the method A way to normalize the input features/variables is the Min-Max scaler. By doing so, all features will be transformed into the range [0,1] meaning that the minimum and maximum value of a feature/variable is going to be 0 and 1, respectively. Why to normalize prior to model fitting? The main idea behi...
13
34
62,267,292
2020-6-8
https://stackoverflow.com/questions/62267292/fastapi-pydantic-accept-arbitrary-post-request-body
I want to create a FastAPI endpoint that just accepts an arbitrary post request body and returns it. If I send {"foo" : "bar"} , I want to get {"foo" : "bar"} back. But I also want to be able to send {"foo1" : "bar1", "foo2" : "bar2"} and get that back. I tried: from fastapi import FastAPI app = FastAPI() app.post("/"...
The accepted answer works as long as the input is wrapped in a dictionary. That is: started with a { and ends with a }. However, that does not cover all valid JSON inputs. For example, the following valid JSON inputs would fail: true / false 1.2 null "text" [1,2,3] In order to have a truly generic JSON input accepted...
17
10
62,279,710
2020-6-9
https://stackoverflow.com/questions/62279710/fastapi-variable-query-parameters
I am writing a Fast API server that accepts requests, checks if users are authorized and then redirects them to another URL if successful. I need to carry over URL parameters, e.g. http://localhost:80/data/?param1=val1&param2=val2 should redirect to http://some.other.api/?param1=val1&param2=val2, thus keeping previousl...
In the docs they talk about using the Request directly, which then lead me to this: from fastapi import FastAPI, Request from starlette.responses import RedirectResponse app = FastAPI() @app.get("/data/") async def api_data(request: Request): params = request.query_params url = f'http://some.other.api/?{params}' respon...
30
39
62,164,400
2020-6-3
https://stackoverflow.com/questions/62164400/how-to-access-private-github-repo-file-csv-in-python-using-pandas-or-requests
I had to switch my public Github repository to private and cannot access files, not with access tokens that I was able to with the public Github repo. I can access my private repo's CSV with curl: ''' curl -s https://{token}@raw.githubusercontent.com/username/repo/master/file.csv ''' However, I want to access this inf...
This is what ended up working for me - leaving it here if anyone runs into the same issue. Thanks for the help! import json, requests, urllib, io user='my_github_username' pao='my_pao' github_session = requests.Session() github_session.auth = (user, pao) # providing raw url to download csv from github csv_url = 'https...
13
3
62,290,209
2020-6-9
https://stackoverflow.com/questions/62290209/pandas-resample-with-start-date
I'd like to resample a pandas object using a specific date (or month) as the edge of the first bin. For instance, in the following snippet I'd like my first index value to be 2020-02-29 and I'd be happy specifying start=2 or start="2020-02-29". >>> dates = pd.date_range("2020-01-29", "2021-07-04") >>> s = pd.Series(ran...
My answer feels a little hacky, but uses resample and gives the desired output. Find the date one bin length (e.g. 4 months, or month ends specifically) before the specified date, append it to s, and then resample: rule = '4M' date = '02-29-2020' base_date = pd.to_datetime(date) - pd.tseries.frequencies.to_offset(rule)...
21
10
62,230,582
2020-6-6
https://stackoverflow.com/questions/62230582/http-method-not-allowed-when-trying-to-capture-console
I am trying to capture the console log of Firefox using Selenium but I am getting "HTTP method not allowed" error This is how I am doing it currently: from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities # enable browser logging d = DesiredCapabilities.FIREFOX d[...
get_log is not implemented by Firefox driver. See https://github.com/mozilla/geckodriver/issues/330
7
8
62,175,978
2020-6-3
https://stackoverflow.com/questions/62175978/is-0-is-0-always-true-in-python
Python 3.8 (or CPython 3.8?) added the warning SyntaxWarning: "is" with a literal. Did you mean "=="? for the code 0 is 0. I understand the warning, and I know the difference between is and ==. However, I also know that CPython caches the object for small integers and shares it in other cases as well. (Out of curiosit...
No, it isn't. Case in point the Rust implementation for Python returns False: >>>>> 0 is 0 False and this is not wrong, though I expect this to change in future versions (it has!). is calls id who's only stipulation is that the id returned is unique and constant for a given object. Whether the source code representati...
9
9
62,198,351
2020-6-4
https://stackoverflow.com/questions/62198351/why-doesnt-pytorch-allow-inplace-operations-on-leaf-variables
So if I run this code in Pytorch: x = torch.ones(2,2, requires_grad=True) x.add_(1) I will get the error: RuntimeError: a leaf Variable that requires grad is being used in an in-place operation. I understand that Pytorch does not allow inplace operations on leaf variables and I also know that there are ways to get a...
As I understand it, any time you do a non-traditional operation on a tensor that was initialized with requires_grad=True, Pytorch throws an error to make sure it was intentional. For example, you normally would only update a weight tensor using optimizer.step(). For another example, I ran into this issue when trying to...
12
15
62,264,787
2020-6-8
https://stackoverflow.com/questions/62264787/mypy-fastapi-response-model
I've been tasked with handling the update from Mypy 0.770 to 0.870 in our FastAPI project, and this has produced an error that I can't quite wrap my head around. My endpoint can return two different models based on some condition, and this was denoted as follows the endpont decorator: @router.get("/", response_model=Un...
This is a compatibility issue introduced in newer versions of mypy. There is an open issue on Github about this topic: https://github.com/tiangolo/fastapi/issues/2279 In the discussion they provide the following workarounds: Using a different approach to create a type alias: NewModel = TypeVar('NewModel',Model1,Model2...
7
5
62,254,125
2020-6-8
https://stackoverflow.com/questions/62254125/plot-multiple-distplot-in-seaborn-facetgrid
I have a dataframe which looks like below: df: RY MAJ_CAT Value 2016 Cause Unknown 0.00227 2016 Vegetation 0.04217 2016 Vegetation 0.04393 2016 Vegetation 0.07878 2016 Defective Equip 0.00137 2018 Cause Unknown 0.00484 2018 Defective Equip 0.01546 2020 Defective Equip 0.05169 2020 Defective Equip 0.00515 2020 Cause Unk...
setup the dataframe import pandas as pd import numpy as np import seaborn as sns # setup dataframe of synthetic data np.random.seed(365) data = {'RY': np.random.choice([2016, 2018, 2020], size=400), 'MAJ_CAT': np.random.choice(['Cause Unknown', 'Vegetation', 'Defective Equip'], size=400), 'Value': np.random.random(size...
8
9
62,281,476
2020-6-9
https://stackoverflow.com/questions/62281476/attributeerror-timedeltaproperties-object-has-no-attribute-minute
I have a dataframe that looks like this df [output]: date time 2020-02-28 00:30:45 2020-02-28 00:30:45 2020-03-09 00:21:06 2020-03-09 00:21:06 2020-03-09 00:21:06 with df.time.dtype [output]: dtype('<m8[ns]') I want to extract the minutes in the time variable with the following command df.time.dt.minute but instead,...
your column 'time' is of dtype timedelta as the error tells you; you could use the total_seconds() method to convert to seconds and divide by 60 to get the minutes. If you want a full-featured datetime column, combine 'date' and 'time'. Then you can use .dt.minute. Ex: import pandas as pd df = pd.DataFrame({'time': pd....
14
21
62,287,150
2020-6-9
https://stackoverflow.com/questions/62287150/django-geodjango-read-coordinates-in-the-wrong-order
first of all thanks for your help. I'm making a form with Django which uses the OSMWidget to save coordinates (Polygons, Lines and Points) to a Geometry field in a PostgreSQL database. It works well, I can save the information in the database without any problem. And when I make a query with PgAdmin I can see the geome...
I had the same problem. In my case, it was due to incompatibility between Django and GDAL, as has been also mentionned here : if you are using GDAL 3, then be sure to use Django 3.1. Upgrading Django did correct both OSMWidget and OSMGeoAdmin for PointField. I'm note sure you have exactly the same configuration problem...
9
6
62,212,263
2020-6-5
https://stackoverflow.com/questions/62212263/alembic-doesnt-recognize-false-default-value
While maintaining a SQLAlchemy data model and utilizing alembic for version control, the following code change I made resulted in an empty revision: some_column = Column(Boolean, nullable=False, default=False) While previously it was: some_column = Column(Boolean, nullable=False) So adding a default value produces no...
To do this automatically you have to turn on a setting to detect server default changes. In your env.py, for the context.configure calls (online and offline migrations, so in 2 places), add a compare_server_default=True kwarg. It is probably safer to just put in the alter_column yourself as well as definitely use serve...
14
13
62,178,926
2020-6-3
https://stackoverflow.com/questions/62178926/setting-up-coc-nvim-for-python
I have installed coc.nvim and extension coc-python(:CocInstall coc-python) When I opened file I refused of linting and then get error: [coc.nvim] Jedi error: Traceback (most recent call last): File "completion.py", line 694, in <module> [coc.nvim] Jedi error: Traceback (most recent call last): [coc.nvim] Jedi error: i...
It's recommended to use https://github.com/fannheyward/coc-pyright if you're using Python 3, or use https://github.com/pappasam/coc-jedi if you're using Jedi.
8
8
62,293,200
2020-6-9
https://stackoverflow.com/questions/62293200/upload-images-to-instagram-using-python
I'm trying to do a simple Instagram python bot in order to upload images in my Instagram profile. I've already tried the most common libraries (InstagramAPI, instapy, insta-cly). While I was searching I found out that Instagram has changed something making those libraries useless. Is there any library I can use? I know...
try this library: instabot https://pypi.org/project/instabot/ example of code for uploading an image: from instabot import Bot bot = Bot() bot.login(username="instagram_username", password="your_password") file = open('path_to_your_image', 'r') bot.upload_photo(file, caption="your post caption")
8
6
62,288,531
2020-6-9
https://stackoverflow.com/questions/62288531/how-to-capture-inputs-and-outputs-of-a-child-process
I'm trying to make a program which takes an executable name as an argument, runs the executable and reports the inputs and outputs for that run. For example consider a child program named "circle". The following would be desired run for my program: $ python3 capture_io.py ./circle Enter radius of circle: 10 Area: 314....
Is it possible to change this behaviour so that my input_filter will run only when Enter is pressed? Yes, you can do it by inheriting from pexpect.spawn and overwriting the interact method. I will come to that soon. As VPfB pointed out in their answer, you can't use a pipe and I think it's worth to mentioning that th...
9
0
62,238,064
2020-6-6
https://stackoverflow.com/questions/62238064/how-to-use-scipy-optimize-linear-sum-assignment-in-tensorflow-or-keras
first time posting here ! If my question is lacking anything please tell me and I'll fix it ! Facebook recently released DETR, an object detection model using transformers ! The model is implemented with Pytorch and I'm trying to implement the loss function where Hungarian algorithm is involved but with Keras and Tenso...
Does this work for you? See: https://www.tensorflow.org/api_docs/python/tf/numpy_function @tf.function def tf_linear_sum_assignment(cost_matrix): return tf.numpy_function(func=linear_sum_assignment,inp=[cost_matrix],Tout=[tf.int64,tf.int64])
10
7
62,182,687
2020-6-3
https://stackoverflow.com/questions/62182687/custom-help-in-python-click
By default, click adds a --help option that outputs a standardised usage text based on the structure of the click commands: Usage: ... Options: ... Commands: ... ... How to override this behaviour to have a custom help output ? What I am trying to do is to output a custom message using rich library.
The trick is to create a click.Group class and override format_help method class RichGroup(click.Group): def format_help(self, ctx, formatter): sio = io.StringIO() console = rich.Console(file=sio, force_terminal=True) console.print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:") formatter.write(sio.getvalue(...
7
15
62,269,892
2020-6-8
https://stackoverflow.com/questions/62269892/get-rid-of-white-border-around-option-menu
I'm trying to get rid of the white border around the OptionMenu. What I tried I changed the colour to red, but there is still a white border around it. Can anyone help? Here's the code: from tkinter import * import tkinter as tk from tkinter import ttk root = tk.Tk() root.geometry('500x500') var = StringVar() option =...
As stated in the comments by @Mike-SMT, Have you considered writing your own option menu? This, to me, seems to be the only way to get an OptionMenu without having that irritating grey border. Here is my attempt at it: import tkinter as tk root = tk.Tk() root.geometry('500x500') class custom_option_menu(tk.Tk): de...
11
6
62,167,179
2020-6-3
https://stackoverflow.com/questions/62167179/how-do-i-annotate-the-type-of-a-parameter-of-an-abstractmethod-when-the-paramet
How do I annotate the type of a function parameter of a abstractmethod, when the parameter can have any type derived from a specific base type? Example: import abc import attr @attr.s(auto_attribs=True) class BaseConfig(abc.ABC): option_base: str @attr.s(auto_attribs=True) class ConfigA(BaseConfig): option_a: str @attr...
TLDR: Make the baseclass Generic and parameterise the type of configuration: C = TypeVar('C', bound=BaseConfig) class Base(abc.ABC, Generic[C]): @abc.abstractmethod def do_something(self, config: C): pass The original class hierarchy declares that ClassA can be used anywhere Base is valid. When we assume some variabl...
7
11
62,220,904
2020-6-5
https://stackoverflow.com/questions/62220904/vs-code-python-installation-and-python-interpreter-not-recognized
I am getting this message on the VS Code that "Python is not installed. Please download and install python before using the extension." There is also no *"Python Interpreter"* to select. When I click on it it shows it empty. I do have Python and Python extension installed and I do have virtual environments set up in t...
I tried many methods but none worked. So then I removed this extension "Anaconda Extension Pack by Microsoft" and it solved the issue. So anyone facing the same issue might try uninstalling this extension.
10
2
62,193,187
2020-6-4
https://stackoverflow.com/questions/62193187/django-shell-plus-how-to-access-jupyter-notebook-in-docker-container
I am trying to access a Jupyter Notebook created with the shell_plus command from django-extensions in a Docker container. docker-compose -f local.yml run --rm django python manage.py shell_plus --notebook My configuration is based on the answers of @RobM and @Mark Chackerian to this Stack Overflow question. I.e. I in...
For the sake of records as of 2020, I managed to have a working django setup with Postgresql in docker-compose: development.py (settings.py) INSTALLED_APPS += [ "django_extensions", ] SHELL_PLUS = "ipython" SHELL_PLUS_PRINT_SQL = True NOTEBOOK_ARGUMENTS = [ "--ip", "0.0.0.0", "--port", "8888", "--allow-root", "--no-bro...
8
23
62,271,614
2020-6-8
https://stackoverflow.com/questions/62271614/what-does-typeerror-init-missing-1-required-positional-argument-get-res
I'm following the graphql python tutorial at https://www.howtographql.com/graphql-python/4-authentication/. It worked fine for the first 3 sections, but in the Authentication section I've run into this problem. I am learning python, don't know Django or graphql, so it's a lot to digest all at once, but it was going ok ...
Ok, I just found it. GRAPHENE = { 'SCHEMA': 'hackernews.schema.schema', 'MIDDLEWARES': ['graphql_jwt.middleware.JSONWebTokenMiddleware'], } Notice the S. It needs to be 'MIDDLEWARES', not 'MIDDLEWARE'. Found the solution on this GitHub issue Also, according to this comment on the same issue, you should add 'graphql_...
11
17
62,188,851
2020-6-4
https://stackoverflow.com/questions/62188851/social-auth-app-django-refresh-access-token
I use social-auth-app-django for my django website. Login all works, but after the token expires. I cant access the google's user data anymore. I found how to refresh the token, but it gives File "/mnt/s/github/nascentapp/app/booking/management/commands/sendmail.py", line 17, in handle new_token = self.get_token(user=...
Fixed it by adding this: SOCIAL_AUTH_GOOGLE_OAUTH2_AUTH_EXTRA_ARGUMENTS = { 'access_type': 'offline', 'approval_prompt': 'auto' } If the user already registered, you need to force the prompt first time (otherwhise you dont get the refresh token) /login/google-oauth2?approval_prompt=force
8
5
62,280,161
2020-6-9
https://stackoverflow.com/questions/62280161/saving-keras-models-with-custom-layers
I am trying to save a Keras model in a H5 file. The Keras model has a custom layer. When I try to restore the model, I get the following error: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-0fbff9b56a9d> in <module>() 1 model.sa...
Correction number 1 is to use Custom_Objects while loading the Saved Model i.e., replace the code, new_model = tf.keras.models.load_model('model.h5') with new_model = tf.keras.models.load_model('model.h5', custom_objects={'CustomLayer': CustomLayer}) Since we are using Custom Layers to build the Model and before Sav...
24
24
62,288,567
2020-6-9
https://stackoverflow.com/questions/62288567/time-travel-debugging-in-python-what-tools-are-suggested-to-use
I was recently wondering about Time Travel Debugging in relation to Python. I found information about tools like: RevPDB - unfortunately the last recorded activity is from 2016 timetravelpdb - unfortunately the last recorded activity is in 2015 Since the projects were updated so long ago, I was wondering if the tool...
General Overview of TTD Research At this very moment, available solutions are those listed in the description of the question and additionally PyTrace. As far as RevPDB and timetravelpdb are concerned, I haven't tested these solutions in any way as the activity in these projects is registered a few years ago so I assu...
10
11
62,268,459
2020-6-8
https://stackoverflow.com/questions/62268459/accuracy-with-tf-idf-and-non-tf-idf-features
I run a Random Forest algorithm with TF-IDF and non-TF-IDF features. In total the features are around 130k in number (after a feature selection conducted on the TF-IDF features) and the observations of the training set are around 120k in number. Around 500 of them are the non-TF-IDF features. The issue is that the accu...
Your view that 130K of features is way too much for the Random forest sounds right. You didn't mention how many examples you have in your dataset and that would be cruccial to the choice of the possible next steps. Here are a few ideas on top of my head. If number of datapoints is large enough you myabe want to train s...
9
2
62,210,221
2020-6-5
https://stackoverflow.com/questions/62210221/walk-forward-with-validation-window-for-time-series-data-cross-validation
I'm looking to perform walk forward validation on my time-series data. Extensive document exists on how to perform rolling window: or expanding window But this validation does not correspond to what will be in my production system: I want to daily retrain a model that will make prediction 14 days in the future. So ...
Here is my solution that allows the user to specify the testing horizon and the minimum sample of data for training: from sklearn.model_selection import TimeSeriesSplit from sklearn.utils import indexable from sklearn.utils.validation import _num_samples class TimeSeriesSplitCustom(TimeSeriesSplit): def __init__(self, ...
11
2
62,229,579
2020-6-6
https://stackoverflow.com/questions/62229579/google-colab-how-to-show-value-of-assignments
I am working on this python notebook in Google Colab: https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb I had to change the configuration line because the one stated in the original was erroring out: # Configure Jupyter to display the assigned value after an assignment # Line commented below be...
Google Colab has not yet been upgraded to the latest IPython version- if you explicitly upgrade with !pip install -U ipython then last_expr_or_assign will work.
8
2
62,293,077
2020-6-9
https://stackoverflow.com/questions/62293077/why-is-pils-image-fromarray-distorting-my-image-color
I am generating thumbnails for mp4 videos using the following code: import cv2 as cv from PIL import Image vidcap = cv.VideoCapture(videoPath) vidcap.set(cv.CAP_PROP_POS_MSEC, millisecond) #Turn video frame into numpy ndarray success, image = vidcap.read() cv.imwrite('fromImage.jpg', image) #line to be replaced The th...
https://note.nkmk.me/en/python-opencv-bgr-rgb-cvtcolor/ imageRGB = cv.cvtColor(image, cv.COLOR_BGR2RGB) img = Image.fromarray(imageRGB) img.save('fromArray.jpg')
11
22
62,288,898
2020-6-9
https://stackoverflow.com/questions/62288898/matplotlib-values-for-the-xx-small-x-small-small-medium-large-x-large-xx
The matplotlibrc sample file states that: ## The font.size property is the default font size for text, given in pts. ## 10 pt is the standard value. ## ## Note that font.size controls default text sizes. To configure ## special text sizes tick labels, axes, labels, title, etc, see the rc ## settings for axes and ticks....
You can also compute the absolute font sizes yourself very easily import matplotlib as mpl import matplotlib.pyplot as plt fig, ax = plt.subplots() t = ax.text(0.5, 0.5, 'Text') fonts = ['xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', 'larger', 'smaller'] for font in fonts: t.set_fontsize(font...
13
19
62,246,742
2020-6-7
https://stackoverflow.com/questions/62246742/how-to-add-a-different-model-form-to-modelformset-factory
With respect to these models: class Projects(models.Model): projectDescription = models.CharField(max_length=50,blank=True,null = True,) status = models.IntegerField(choices = Status_CHOICES, default = 4) projectOwner = models.ForeignKey(staff, on_delete=models.CASCADE, blank=True,null = True,) class Updates(models.Mod...
Solution I What you have done is almost correct. You have initiated an UpdateForm but you treated it as if it was a formset. However it's a Form instance. If you alter your code as below you may achieve your goal. models.py class Project(models.Model): description = models.CharField(max_length=50, blank=True, null=Tr...
8
7
62,287,001
2020-6-9
https://stackoverflow.com/questions/62287001/how-to-overlay-two-plots-in-same-figure-in-plotly-create-pareto-chart-in-plotl
I was trying to plot barplot and scatterplot in the same plot in plotly, but it shows only scatterplot. How to show both the plots? data import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter import plotly import plotly.offline as py i...
Try this: import plotly.graph_objects as go from plotly.subplots import make_subplots trace1 = go.Bar( x=df[cat], y=df[num], name=num, marker=dict( color='rgb(34,163,192)' ) ) trace2 = go.Scatter( x=df[cat], y=df['cumulative_perc'], name='Cumulative Percentage', yaxis='y2' ) fig = make_subplots(specs=[[{"secondary_y": ...
22
35
62,286,965
2020-6-9
https://stackoverflow.com/questions/62286965/is-there-a-difference-between-f-and-f-in-python-string-formatting
To format strings in Python 3.6+, I usually use the lowercase "f" option to include variables. For example: response = requests.get(f'{base_url}/{endpoint}?fields={field_list}') I've recently seen one of my coworkers who always uses capital "F", instead. Like this: response = requests.get(F'{base_url}/{endpoint}?fields...
As explained in the PEP 498, chapter Specification, both are accepted, and should not differ. In source code, f-strings are string literals that are prefixed by the letter 'f' or 'F'. Everywhere this PEP uses 'f', 'F' may also be used.
13
13
62,281,179
2020-6-9
https://stackoverflow.com/questions/62281179/how-to-adjust-scale-ranges-in-altair
I'm having trouble getting all of the axes onto the same scale when using altair to make a group of plots like so: class_list = ['c-CS-m','c-CS-s','c-SC-m','c-SC-s','t-CS-m','t-CS-s','t-SC-m','t-SC-s'] list_of_plots = [] for class_name in class_list: list_of_plots.append(alt.Chart(data[data['class'] == class_name]).mar...
First of all, it looks like you're trying to create a wrapped facet chart. Rather than doing that manually with concatenation, it's better to use a wrapped facet encoding. Second, when you specify resolve_scale(y='independent'), you're specifying that the y-scales should not match between subcharts. If instead you want...
16
32
62,274,412
2020-6-9
https://stackoverflow.com/questions/62274412/cv2-approxpolydp-cv2-arclength-how-these-works
How do these function works? I am using Python3.7 and OpenCv 4.2.0. Thanks in Advance. approx = cv2.approxPolyDP(cnt, 0.01*cv2.arcLength(cnt, True), True)
If you are looking for a example snippet, below is one: import cv2 import imutils # edged is the edge detected image cnts = cv2.findContours(edged, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) cnts = imutils.grab_contours(cnts) cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5] # loop over the contours for c in ...
15
16
62,265,366
2020-6-8
https://stackoverflow.com/questions/62265366/does-mypy-only-type-check-a-function-if-it-declares-a-return-type
The following file: from typing import List class A: def __init__(self, myStr): self.chars: List[int] = list(myStr) def toString(self): return "".join(self.chars) typechecks (note: chars should be List[str] not List[int]): ➜ Python python3 -m mypy temp.py => Success: no issues found in 1 source file, but the following...
This behavior of mypy is by design. Mypy assumes that if a function signature is missing type hints, the user did not want that function to be type checked yet and so skips analyzing that function body. This behavior is intended to make progressively adding type hints when working on large codebases easier: you end up ...
12
20
62,269,086
2020-6-8
https://stackoverflow.com/questions/62269086/preserve-column-order-when-using-pivot
I am trying to do a simple pivot on my dataframe, with one column as the index, one column as the columns, and one column as the values. Here is a screenshot of the code and the result: As you can see, it is just one simple line of code. You can also notice that once the table is pivoted, the columns get placed into a...
You can reorder the columns after the pivoting by selecting a column list in the original order. This column list is obtained from the original dataframe in generic way by selecting the column names for the first line. Example: df = pd.DataFrame({'equipment name':['r1', 'r1', 'r2', 'r2'], 'name': ['col2', 'col1', 'col...
7
8
62,264,277
2020-6-8
https://stackoverflow.com/questions/62264277/get-infinity-when-dividing-by-zero
Is it possible to assign say infinity to something divided by 0 instead of it throwing ZeroDivisionError? Like a function that assigns infinity to something/0.
If you just want a float that represents infinity, you can issue float('inf') or float('-inf'). Standard Python floats and ints will give you a ZeroDivisionError, but you can use numpy datatypes. >>> import numpy as np >>> np.float64(15)/0 inf Without numpy, write a function: def my_div(dividend, divisor): try: retu...
9
6
62,253,289
2020-6-8
https://stackoverflow.com/questions/62253289/valueerror-data-cardinality-is-ambiguous
I'm trying to train LSTM network on data taken from a DataFrame. Here's the code: x_lstm=x.to_numpy().reshape(1,x.shape[0],x.shape[1]) model = keras.models.Sequential([ keras.layers.LSTM(x.shape[1], return_sequences=True, input_shape=(x_lstm.shape[1],x_lstm.shape[2])), keras.layers.LSTM(NORMAL_LAYER_SIZE, return_sequen...
As the Error suggests, the First Dimension of X and y is different. First Dimension indicates the Batch Size and it should be same. Please ensure that Y also has the shape, (1, something). I could reproduce your error with the Code shown below: from tensorflow.keras.preprocessing.sequence import pad_sequences from tens...
18
15
62,253,718
2020-6-8
https://stackoverflow.com/questions/62253718/how-can-i-receive-file-in-python-telegram-bot
I have a problem about file messages in python telegram bot. How can I receive file and read that file ? Or save it.
You can: Register a handler that listens to Document get File object from the update (inside the listener using get_file) then simply call .download() to download the document Here a sample code to get you started: from telegram.ext import Updater, MessageHandler, Filters BOT_TOKEN = ' ... ' def downloader(update, co...
10
11
62,256,014
2020-6-8
https://stackoverflow.com/questions/62256014/does-python-forbid-two-similarly-looking-unicode-identifiers
I was playing around with Unicode identifiers and stumbled upon this: >>> 𝑓, x = 1, 2 >>> 𝑓, x (1, 2) >>> 𝑓, f = 1, 2 >>> 𝑓, f (2, 2) What's going on here? Why does Python replace the object referenced by 𝑓, but only sometimes? Where is that behavior described?
PEP 3131 -- Supporting Non-ASCII Identifiers says All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC. You can use unicodedata to test the conversions: import unicodedata unicodedata.normalize('NFKC', '𝑓') # f which would indicate that '𝑓' gets converte...
87
88
62,245,218
2020-6-7
https://stackoverflow.com/questions/62245218/python-pandas-reshape-dataframe
Given the following data frame: pd.DataFrame({"A":[1,2,3],"B":[4,5,6],"C":[6,7,8]}) A B C 0 1 4 6 1 2 5 7 2 3 6 8 3 11 14 16 4 12 15 17 5 13 16 18 I would like to reshape it so it would look like so: A B C A_1 B_1 C_1 A_2 B_2 C_2 0 1 4 6 2 5 7 3 6 8 1 11 14 16 12 15 17 13 16 18 So every 3 rows are grouped into 1 row...
One idea is create MultiIndex with integer and modulo division and reshape by DataFrame.unstack: a = np.arange(len(df)) df.index = [a // 3, a % 3] df = df.unstack().sort_index(axis=1, level=1) df.columns = [f'{a}_{b}' for a, b in df.columns] print (df) A_0 B_0 C_0 A_1 B_1 C_1 A_2 B_2 C_2 0 1 4 6 2 5 7 3 6 8 1 11 14 16 ...
10
12
62,250,799
2020-6-7
https://stackoverflow.com/questions/62250799/mean-of-non-diagonal-elements-of-each-row-numpy
I essentially have a confusion matrix of size n x n with all my diagonal elements being 1. For every row, I wish to calculate its mean, excluding the 1, i.e. excluding the diagonal value. Is there a simple way to do it in numpy? This is my current solution: mask = np.zeros(cs.shape, dtype=bool) np.fill_diagonal(mask, ...
A concise one using summation - (cs.sum(1)-1)/(cs.shape[1]-1) For a general case of ignoring diagonal elements, use np.diag in place of 1 offset - (cs.sum(1)-np.diag(cs))/(cs.shape[1]-1) Another with mean - n = cs.shape[1] (cs.mean(1)-1./n)*(n/(n-1))
8
6
62,248,185
2020-6-7
https://stackoverflow.com/questions/62248185/pandas-combining-sparse-columns-in-dataframe
I am using Python, Pandas for data analysis. I have sparsely distributed data in different columns like following | id | col1a | col1b | col2a | col2b | col3a | col3b | |----|-------|-------|-------|-------|-------|-------| | 1 | 11 | 12 | NaN | NaN | NaN | NaN | | 2 | NaN | NaN | 21 | 86 | NaN | NaN | | 3 | 22 | 87 | ...
You can use df.stack() assuming 'id' is your index else set 'id' as index. Then use pd.pivot_table. df = df.stack().reset_index(name='val',level=1) df['group'] = 'g'+ df['level_1'].str.extract('col(\d+)') df['level_1'] = df['level_1'].str.replace('col(\d+)','') df.pivot_table(index=['id','group'],columns='level_1',valu...
7
8
62,241,367
2020-6-7
https://stackoverflow.com/questions/62241367/have-permissionerror-when-i-run-poetry-run-command
Environment Ubuntu 20.04 Python 3.7.3 Poetry 1.0.8 My Problem I installed poetry to manage packages, and I tried it with following simple project, . └── myproject ├── README.rst ├── myproject │ ├── __init__.py │ ├── main.py ├── myproject.egg-info │ ├── PKG-INFO │ ├── SOURCES.txt │ ├── dependency_links.txt │ ├── requi...
My guess is that myproject/main.py isn't an executable (doesn't have the 'x') permission. That's why you can run it with python myproject/main.py, but can't run it as the main exe. To fix it, run chmod +x myproject/main.py, and then try poetry run again. Of course, you'll have to have a proper Shebang at the very top ...
22
6
62,239,593
2020-6-7
https://stackoverflow.com/questions/62239593/how-to-calculate-a-cumulative-product-of-a-list-using-list-comprehension
I'm trying my hand at converting the following loop to a comprehension. Problem is given an input_list = [1, 2, 3, 4, 5] return a list with each element as multiple of all elements till that index starting from left to right. Hence return list would be [1, 2, 6, 24, 120]. The normal loop I have (and it's working): l2r ...
Python 3.8+ solution: := Assignment Expressions lst = [1, 2, 3, 4, 5] curr = 1 out = [(curr:=curr*v) for v in lst] print(out) Prints: [1, 2, 6, 24, 120] Other solution (with itertools.accumulate): from itertools import accumulate out = [*accumulate(lst, lambda a, b: a*b)] print(out)
11
17
62,234,909
2020-6-6
https://stackoverflow.com/questions/62234909/layout-management-in-plotly-dash-app-how-to-position-html-div
I am creating a dash app, this is my code: # import required packages import dash import dash_table import dash_core_components as dcc import dash_html_components as html import dash_bootstrap_components as dbc import plotly.graph_objs as go import numpy as np import pandas as pd # define figure creation function def c...
To stack multiple html.Div() horizontally, use style={'display': 'inline-block'}. To align the dcc.RadioItems() vertically, use labelStyle={'display': 'block'}. I included an updated version of your code below. # import required packages import dash import dash_table import dash_core_components as dcc import dash_ht...
11
18
62,220,294
2020-6-5
https://stackoverflow.com/questions/62220294/hoverinformation-for-shapes-in-plotly
I know there is the hovertemplate/hover_text/ option for traces (marker/line) but I cannot find such a thing for shapes. Is there a way to have a hover text pop up when moving over a shape? Maybe a workaround? Example: import plotly.graph_objects as go fig = go.Figure() fig.add_trace(go.Scatter( x=[1.5, 3], y=[2.5, 2.5...
I thought of a solution I am happy with. Simply draw a shape. You won't be able to see a hover text. However, if you add a trace with a fill on top of the shape, then set the trace to opacity=0 you will see the hover text from the trace pop up when moving over the shape. Again, thanks for your responses! import plotly....
10
3
62,230,507
2020-6-6
https://stackoverflow.com/questions/62230507/multiple-columns-for-hue-parameter-in-seaborn-violinplot
I am working with tips data set, and here is the head of data set. total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 My code is sns.violinplot(x='day',y='...
You could use a seaborn.catplot in order to use 'sex' as hue and 'smoker' as column for generating two side by side violinplot. Check this code: import seaborn as sns import matplotlib.pyplot as plt sns.set() tips = sns.load_dataset("tips") sns.catplot(x = "day", y = "total_bill", hue = "sex", col = "smoker", data = ti...
20
7
62,230,148
2020-6-6
https://stackoverflow.com/questions/62230148/python-telegram-bot-markdown
I am working on a Telegram Bot in Python but I struggle to use markdown correctly and I can not find any proper resources about the telegram markdown implementation. It gets even more complicated because of two different markdown "versions" (Markdown and Markdown_V2). And none of them is matching the behavior of the no...
Bots need a different markdown syntax. To send bold and italic text use: update.message.reply_text('*_bold and italic_*', parse_mode='MarkdownV2') from the official telegram website https://core.telegram.org/bots/api#markdownv2-style *bold \*text* _italic \*text_ __underline__ ~strikethrough~ *bold _italic bold ~itali...
11
18
62,220,246
2020-6-5
https://stackoverflow.com/questions/62220246/how-to-create-a-facetgrid-stacked-barplot-using-seaborn
I am trying to plot a facet_grid with stacked bar charts inside. I would like to use Seaborn. Its barplot function does not include a stacked argument. I tried to use FacetGrid.map with a custom callable function. import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt def custom_st...
The simplest code to achive that result is this: import seaborn as sns import matplotlib.pyplot as plt sns.set() tips=sns.load_dataset("tips") g = sns.FacetGrid(tips, col = 'size', row = 'smoker', hue = 'day') g = (g.map(sns.barplot, 'time', 'total_bill', ci = None).add_legend()) plt.show() which gives this result:
8
8
62,221,654
2020-6-5
https://stackoverflow.com/questions/62221654/how-to-get-coverage-reporting-when-testing-a-pytest-plugin
Context I am updating an inherited repository which has poor test coverage. The repo itself is a pytest plugin. I've changed the repo to use tox along with pytest-cov, and converted the "raw" tests to use pytester as suggested in the pytest documentation when testing plugins. The testing and tox build, etc. works great...
Instead of using the pytest-cov plugin, use coverage to run pytest: coverage run -m pytest .... That way, coverage will be started before pytest.
63
94
62,222,436
2020-6-5
https://stackoverflow.com/questions/62222436/importerror-cannot-import-name-feature-from-setuptools
I want to install the requirements of this https://github.com/sraashis/deepdyn project, but when I run: pip install -r deepdyn/assets/requirements.txt I receive the following error in the terminal: ERROR: Command errored out with exit status 1: command: /home/masoud/anaconda3/envs/tfgpu/bin/python -c 'import sys, setu...
The bug was fixed in version 1.1 but deepdyn requires version 1.0. This is probably a bug in deepdyn and should be reported. Or may be deepdyn requires some older version of setuptools. Again, ask the authors about it.
14
5
62,223,424
2020-6-5
https://stackoverflow.com/questions/62223424/simplequeue-vs-queue-in-python-what-is-the-advantage-of-using-simplequeue
The queue — A synchronized queue class simply states that there are fewer functions allowed with SimpleQueue. I need very basic queue functionality for a multithreading application, would it help in any way to use SimpleQueue?
queue.SimpleQueue handles more than threadsafe concurrency. It handles reentrancy - it is safe to call queue.SimpleQueue.put in precarious situations where it might be interrupting other work in the same thread. For example, you can safely call it from __del__ methods, weakref callbacks, or signal module signal handler...
33
19
62,220,855
2020-6-5
https://stackoverflow.com/questions/62220855/tensorflow-removing-jfif
I am quite new to tensorflow, I would like to clearly know, what does the below command do? import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers import os num_skipped = 0 for folder_name in ("Cat", "Dog"): print("folder_name:",folder_name) #folder_name: Cat folder_path = os.path.join...
Wikipedia explains that JPG files contain the string "JFIF" at the beginning of the file, encoded as bytes: So: tf.compat.as_bytes("JFIF") converts the string "JFIF" to bytes. You could also just use b"JFIF", though maybe the TensorFlow implementation has some optimization I don't know about. fobj.peek(10) theoretica...
7
10
62,220,197
2020-6-5
https://stackoverflow.com/questions/62220197/how-to-catch-an-exception-message-in-python
I want something of the form try: # code except *, error_message: print(error_message) i.e I want to have a generic except block that catches all types of exceptions and prints an error message. Eg. "ZeroDivisionError: division by zero". Is it possible in python? If I do the following I can catch all exceptions, but I...
Try this: except Exception as e: print(str(e))
8
14
62,215,910
2020-6-5
https://stackoverflow.com/questions/62215910/how-to-get-the-centroids-in-dbscan-sklearn
I am using DBSCAN for clustering. However, now I want to pick a point from each cluster that represents it, but I realized that DBSCAN does not have centroids as in kmeans. However, I observed that DBSCAN has something called core points. I am thinking if it is possible to use these core points or any other alternative...
Why don't you estimate the centroids of the resulted estimated clusters? points_of_cluster_0 = dist[labels==0,:] centroid_of_cluster_0 = np.mean(points_of_cluster_0, axis=0) print(centroid_of_cluster_0) points_of_cluster_1 = dist[labels==1,:] centroid_of_cluster_1 = np.mean(points_of_cluster_1, axis=0) print(centroid_o...
11
7
62,213,171
2020-6-5
https://stackoverflow.com/questions/62213171/why-can-i-not-assign-cls-hash-id
I would have hoped this works (in Python 3.6), class A: __hash__ = id A().__hash__() but I get TypeError: id() takes exactly one argument (0 given) Surprisingly, def my_id(self): return id(self) class A: __hash__ = my_id A().__hash__() works as hoped.
id is of type builtin_function_or_method (it's a function that's built into the runtime - ), which for practical reasons (optimisation mainly) doesn't implement the descriptor protocol as a python function would, so A().__hash__ resolves to the id function itself, not to a method object wrapping the function. You'll ob...
7
9
62,212,417
2020-6-5
https://stackoverflow.com/questions/62212417/python-string-format-with-negative-sign-for-negative-number-but-space-for-posit
Is there a format code to format -2.34 as '-2.3', but +2.34 as ' 2.3' (notice the leading space)? Basically show the negative sign but leave a space for positive sign.
Use " " (a space) to insert a space before positive numbers and a minus sign before negative numbers: txt = "The temperature is between {: } and {: } degrees celsius." print(txt.format(-3, 7)) answer : The temperature is between -3 and 7 degrees celsius.
11
8
62,183,202
2020-6-3
https://stackoverflow.com/questions/62183202/cannot-read-properly-data-of-null-dash
When I run the below code it loads the web, but then it leaves an error message, it is because in some section there is no data, can a conditional help? I uploaded the code but I do not know where to act, i am new on Dash and my knowledge in javascript is limited. My main file import dash from dash.dependencies import...
Sometimes Dash can struggle if the prop being updated by a callback hasn't been initialized. In this case, the figure prop of the dcc.Graph was never declared. Setting an explicit empty value, such as figure={} is often enough to resolve this sort of error.
7
13
62,201,325
2020-6-4
https://stackoverflow.com/questions/62201325/how-to-count-the-occurrence-of-values-in-one-pandas-dataframe-if-the-values-to-c
I have a (really big) pandas Dataframe df: country age gender Brazil 10 F USA 20 F Brazil 10 F USA 20 M Brazil 10 M USA 20 M I have another pandas Dataframe freq: age gender counting 10 F 0 10 M 0 20 F 0 I wanna count the pair of values in freq when they occur in df: age gender counting 10 F 2 10 M 1 20 F 1 I'm us...
you can do it with inner merge to filter the combinations in df you don't want, then groupby age and gender and count the column counting. just reset_index to fit your expected output. freq = (df.merge(freq, on=['age', 'gender'], how='inner') .groupby(['age','gender'])['counting'].size() .reset_index()) print (freq) ag...
9
10
62,188,158
2020-6-4
https://stackoverflow.com/questions/62188158/clarification-for-it-should-be-possible-to-change-the-value-of-1-from-the-cpyt
See this link: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong The current implementation keeps an array of integer objects for all integers between -5 and 256; when you create an int in that range, you actually just get back a reference to the existing object. So, it should be possible to change the value...
It means that integers in Python are actual objects with a "value"-field to hold the integer's value. In Java, you could express Python's integers like so (leaving out a lot of details, of course): class PyInteger { private int value; public PyInteger(int val) { this.value = val; } public PyInteger __add__(PyInteger ot...
29
43
62,195,181
2020-6-4
https://stackoverflow.com/questions/62195181/how-to-pass-variable-to-json-for-python
I am new in work with JSON, so sorry in advance for the stupid question. I want to write JSON with the variable in the value field. It looks like this: def print_json(user_name): opened_json = open('way/to/json/file') tmp = json.load(opened_json) res = tmp(['path_to_folder'](user_name)) print(res) def main(user_name): ...
What you want isn't directly possible in JSON, because it doesn't support "templating". One solution would be to use a templating language such as Jinja to write a JSON template, then load this file without the json library and fill in the values using Jinja, and finally use json.loads to load a dictionary from your re...
7
6
62,186,218
2020-6-4
https://stackoverflow.com/questions/62186218/python-multiprocessing-attributeerror-cant-pickle-local-object
I have a method inside a class to return a func which parameters may change. The Interface function accept two parameters, f and its args.I want to use mp.pool to accelerate it.However, it returns an error. from multiprocessing import Pool # from multiprocess import Pool # from pathos.multiprocessing import ProcessingP...
Python can't pickle the closure, but all you really need is something that you can call that retains state. The __call__ method makes a class instance callable, so use that from multiprocessing import Pool class TempTest1: def __init__(self, a): self.a = a def __call__(self, x): return self.a + x class Temp: def __init...
8
10
62,183,821
2020-6-3
https://stackoverflow.com/questions/62183821/what-is-the-unit-in-python-lru-cache
According to the documentation the default value for lru_cache from functools is 128. But no unit is defined. Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive or I/O bound function is periodically called with the same arguments. ...
Short answer: It is the number of elements that are stored in the cache. We can look up the source code of the lru_cache [GitHub]. The code is rather complicated, but in a nutshell, line 619 already gives a clue: full = (cache_len() >= maxsize) This specifies that the cache is full given that the cache_len() is greate...
16
15
62,169,315
2020-6-3
https://stackoverflow.com/questions/62169315/runtimeerror-unable-to-create-link-name-already-exists-keras
When I save my model I get the following error: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-40-853303da8647> in <module>() 7 8 ----> 9 model.save(outdir+'model.h5') 10 11 5 frames /usr/local/lib/python3.6/dist-packages/h5py/_h...
I think the problem is that both of your weight variables have internally the same name, which should not happen, you can give them names with the name parameter to add_weight: self.alpha = self.add_weight(shape=(self.nout,), initializer='zeros', trainable=True, name="alpha") self.beta = self.add_weight(shape=(self.nou...
8
12
62,172,931
2020-6-3
https://stackoverflow.com/questions/62172931/cannot-unpack-non-iterable-int-object-when-using-python-dicitonary
I have the following command below: import pandas as pd import numpy as np from scipy import stats np.random.seed(12345) standarderrors1992 = stats.sem(np.random.normal(32000,200000,3650)) standarderrors1993 = stats.sem(np.random.normal(43000,100000,3650)) standarderrors1994 = stats.sem(np.random.normal(43500,140000,36...
You need to iterate over dict.items() for this to work. for key,value in dict.items(): # do stuff here I would advice against naming your variables dict which shadows the build in dict function though :)
7
18
62,170,394
2020-6-3
https://stackoverflow.com/questions/62170394/how-to-get-maximum-and-minimum-of-a-list-in-column
Given that, I have a dataframe as below: import pandas as pd import numpy as np dict = { "A": [[1,2,3,4],[3],[2,8,4],[5,8]] } dt = pd.DataFrame(dict) I wish to have the Maximum and minimum of each row in column B. My favorite output is: A B 0 [1, 2, 3, 4] [1,4] 1 [3] [3,3] 2 [2, 8, 4] [2,8] 3 [5, 8] [5,8] What I alr...
Like this: In [1592]: dt['B'] = dt.A.apply(lambda x: [min(x), max(x)]) In [1593]: dt Out[1593]: A B 0 [1, 2, 3, 4] [1, 4] 1 [3] [3, 3] 2 [2, 8, 4] [2, 8] 3 [5, 8] [5, 8] As suggested by @Ch3steR, using map since it's faster: dt['B'] = dt.A.map(lambda x: [min(x), max(x)])
10
12
62,166,719
2020-6-3
https://stackoverflow.com/questions/62166719/padding-same-conversion-to-pytorch-padding
I'm trying to convert the following Keras model code to pytorch, but am having problems dealing with padding='same'. model = Sequential() model.add(Conv2D(64, (3, 3), input_shape=img_size)) model.add(BatchNormalization(axis=1)) model.add(Activation('relu')) model.add(Dropout(0.3)) model.add(Conv2D(64, (3, 3), padding...
W:input volume size F:kernel size S:stride P:amount of padding size of output volume = (W-F+2P)/S+1 e.g. input:7x7, kernel:3x3, stride:1, pad:0 output size = (7-3+2*0)/1+1 = 5 =>5x5
8
6
62,040,724
2020-5-27
https://stackoverflow.com/questions/62040724/warning-the-lock-file-is-not-up-to-date-with-the-latest-changes-in-pyproject-to
When I am using a poetry command with Python 3.7, in my case: poetry export -f requirements.txt I am getting the following error: Warning: The lock file is not up to date with the latest changes in pyproject.toml. You may be getting outdated dependencies. Run update to update them. So far clear, but if I run poetry u...
UPDATE V2.0.0 (released date : 4 jan 2025) : The --no-update option does no longer exist (see V2 docs). The same documentation says: By default, packages that have already been added to the lock file before will not be updated. So now just use: poetry lock or downgrade you poetry version to use the solution below: Fo...
28
49
62,044,541
2020-5-27
https://stackoverflow.com/questions/62044541/change-pytest-working-directory-to-test-case-directory
I have the following pytest directory structure: system_tests/ ├── conftest ├── pytest.ini │ ├── suite_1/ │ └── test_A.py │ └── suite_2/ └── sub_suite_2a/ └── test_B.py When each test method runs, a number of third-party libraries/processes generate artifacts in the current working directory. When pytest is executed ...
EDIT: Improved Solution Using monkeypatch as suggested by @Kound removes the boilerplate code to restore the cwd. You can also enable autouse to automatically apply this fixture to all test functions. Add the following fixture to conftest.py to change the cwd for all tests: @pytest.fixture(autouse=True) def change_test...
25
35
62,069,596
2020-5-28
https://stackoverflow.com/questions/62069596/configuring-isort-and-autoflake-with-project-toml
I have a series of tools running locally and on Jenkins to check and format my Python code: autoflake isort black I use pyproject.toml file to configure black, isort with .isort.cfg and autoflake with command line parameters because I haven't found any support to configure it with a configuration file. Is there way...
isort configuration can be found at https://pycqa.github.io/isort/docs/configuration/options.html In general, config params are separated by underscores. The example below will provide configuration that makes black and isort compatible, as discussed here https://copdips.com/2020/04/making-isort-compatible-with-black.h...
9
15
62,099,939
2020-5-30
https://stackoverflow.com/questions/62099939/solving-linear-equations-on-the-gpu-with-numpy-and-pytorch
I am trying to solve a lot of linear equations as fast as possible. To find out the fastest way I benchmarked NumPy and PyTorch, each on the CPU and on my GeForce 1080 GPU (using Numba for NumPy). The results really confused me. This is the code I used with Python 3.8: import timeit import torch import numpy from numba...
Your analysis is correct on several fronts, but there are a couple of nuances that might help clarify your results and improve GPU performance: 1. CPU vs GPU Performance In general, GPU operations have an overhead cost associated with transferring data between the CPU and GPU memory. Therefore, the benefits of GPU acce...
12
3
62,117,400
2020-5-31
https://stackoverflow.com/questions/62117400/hashing-plaid-request-body-webhook
I am trying to verify a webhook sent from Plaid's API. Every webhook request is sent with a 'plaid-verification' header which is a JSON Web Token. The steps required to validate are: Extract JWT from request header signed_jwt = eyJhbGciOiJFUzI1NiIsImtpZCI6IjZjNTUxNmUxLTkyZGMtNDc5ZS1hOGZmLTVhNTE5OTJlMDAwMSIsInR5cCI6Ik...
It seems to be a problem with whitespace. If you modify body.json to have 2 spaces per ‘tab’ on each new line, it will generate the right hash.
7
10
62,162,970
2020-6-2
https://stackoverflow.com/questions/62162970/programmatically-determine-pip-user-install-location-scripts-directory
As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>. How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be inv...
I believe the following should give the expected result import os import sysconfig user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user') print(user_scripts_path) Command-line: python -c 'import os,sysconfig;print(sysconfig.get_path("scripts",f"{os.name}_user"))' Since pip 21.3 released on 2021-10-11, p...
11
14
62,134,556
2020-6-1
https://stackoverflow.com/questions/62134556/how-to-detect-android-os-from-a-python-script
I am running a python script in a termux environment on an Android device and I would like to be able to detect that the OS is Android. The traditional approaches don't work: >>> import platform >>> import sys >>> print(platform.system()) 'Linux' >>> print(sys.platform) 'linux' >>> print(platform.release()) '4.14.117-p...
There is more simple way that doesn't depend using external utilities and just uses sys module. Here is code: import sys is_android: bool = hasattr(sys, 'getandroidapilevel') Here are it's pros and cons: @@Pros@@ + Does not depend on environment values + Does not depend on third-party modules + Simple one-liner (2 tec...
7
1
62,160,411
2020-6-2
https://stackoverflow.com/questions/62160411/pythons-new-functools-cached-property-bug-or-limitation
Since Python 3.8, functools has a cached_property. I've been using a similar lazyprop decorator based on Beazley's cookbook (code below), but when I replace by the builtin, I get problems. Here's one of them. When I use the decorator within the class definition, using the @ operator, it doesn't complain. But if I use ...
TL;DR The cache is the instance dict itself, and the name of the property is needed as the key. The chosen design imposes the limitation, but (IMO) it's a good compromise. lazyprop is not thread-safe, or at least may call self.func more than is strictly necessary in a multi-threaded environment. To start, it is docume...
7
6
62,086,013
2020-5-29
https://stackoverflow.com/questions/62086013/download-file-folder-from-public-aws-s3-with-python-no-credentials
I have opened a public access to S3 bucket and I need to download files / folders with files from the bucket using python. The trick is that I do not want to supply credentials (which boto3 apparently requires). Is it even possible?
You can use GetObject from the S3 REST API, together with the Requests library in Python. If you grant READ access to the anonymous user, you can return the object without using an authorization header. Example of such an S3 REST call:: > GET /example-object HTTP/1.1 > Host: example-bucket.s3.<Region>.amazonaws.com Py...
8
3
62,045,387
2020-5-27
https://stackoverflow.com/questions/62045387/how-to-suppress-coroutine-was-never-awaited-warning
All search results on "coroutine was never awaited" are for people who were either trying to fire-and-forget or actually did forget to await. This is not my case. I want to use a coroutine the same way I often use generators: I'm creating it here while I have all the variables handy, but I'm not sure yet whether I'll e...
deceze's comment that you should not create the coroutine object until you are ready to await it is probably the most ideal solution. But if that isn't practical, you can use weakref.finalize() to call the coroutine object's close() method just before it is garbage-collected. >python -m asyncio asyncio REPL 3.9.5 (defa...
13
6
62,067,400
2020-5-28
https://stackoverflow.com/questions/62067400/understanding-accumulated-gradients-in-pytorch
I am trying to comprehend inner workings of the gradient accumulation in PyTorch. My question is somewhat related to these two: Why do we need to call zero_grad() in PyTorch? Why do we need to explicitly call zero_grad()? Comments to the accepted answer to the second question suggest that accumulated gradients can be u...
You are not actually accumulating gradients. Just leaving off optimizer.zero_grad() has no effect if you have a single .backward() call, as the gradients are already zero to begin with (technically None but they will be automatically initialised to zero). The only difference between your two versions, is how you calcul...
33
64
62,058,120
2020-5-28
https://stackoverflow.com/questions/62058120/how-to-use-python-black-formatter-under-a-project-for-python-3-5-managed-by-poe
I created a python project "foo" with Poetry. This is the content of pyproject.toml: [tool.poetry] name = "bar" version = "0.1.0" description = "" [tool.poetry.dependencies] python = ">=3.5" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry>=0.12"] build-backend = "poetry.masonry.api" This package is c...
Seems a bit late but actually you can do what you want even if black supports only Python >=3.6.2 In your pyproject.toml you can define a restricted dependcy as documented in https://python-poetry.org/docs/dependency-specification/#python-restricted-dependencies [tool.poetry.dependencies] python = ">=3.5" [tool.poetry....
9
7
62,114,945
2020-5-31
https://stackoverflow.com/questions/62114945/attributeerror-parsedrequirement-object-has-no-attribute-req
I have docker file with one layer as RUN python setup.py develop I am using a mutli-stage build with three stages and this is the stage one all the stages have the same base image, though I don't think this is a problem with dockerfile but seems to be a problem with python and the way it is executed working on the bas...
Update: * Please note that updating pip and pip-tools is not supported in my case. Then the workaround in my answer will help. * If updating pip and pip-tools to compatible version is supported then refer to Gnnr's answer or Heapify's answer I got the fix finally \o/ install_reqs = parse_requirements(requirements_path,...
14
23
62,150,659
2020-6-2
https://stackoverflow.com/questions/62150659/how-to-convert-a-tensor-of-booleans-to-ints-in-pytorch
Suppose, we have a tensor t = torch.tensor([True, False, True, False]) How do we convert it to an integer tensor with values [1, 0, 1, 0]?
The solution is just a single line of code. To convert a tensor t with values [True, False, True, False] to an integer tensor, just do the following. t = torch.tensor([True, False, True, False]) t_integer = t.long() print(t_integer) [1, 0, 1, 0]
18
29
62,137,479
2020-6-1
https://stackoverflow.com/questions/62137479/plotly-dash-dcc-radioitems-vertical-alignment
I would like to align vertically all options of a dash_core_components.RadioItems. According to the dash documentation, the default behavior should include a vertical alignment of the RadioItems options. If you wanted to align the options horizontally, you would have to specify: labelStyle={'display': 'inline-block'} ...
You can pass the labelStyle={'display': 'block'} property to dcc.RadioItems() in order to vertically align the different options, but I suggest that you follow the recommendation in the Dash Community Forum, which is to always link the Dash CSS file bWLwgP.css.
9
10
62,161,001
2020-6-2
https://stackoverflow.com/questions/62161001/python-newline-n-not-working-in-jupyter-notebooks
I'm trying to display the tuples of a postgreSQL table neatly in my Jupyter Notebook, but the newline \n escape character doesn't seem to work here (it works for my python scripts w/ same code outside of jupyter). I'm trying to run: cur.execute('SELECT * FROM Cars') '\n '.join(str(x) for x in cur.fetchall()) But my o...
When you don't put the output in print statement. "\n" would be printed as "\n" instead of newline in jupyter notebook and python shell. in: 'A\nB' out: 'A\nB' in: print('A\nB') out: A B The solution you need is: print('\n '.join(str(x) for x in cur.fetchall()))
9
18
62,151,238
2020-6-2
https://stackoverflow.com/questions/62151238/how-to-set-the-jinja-environment-variable-in-flask
I have a page with the following Code Structure: Python Code: from flask import Flask,render_template app=Flask(__name__) @app.route('/') def home(): return render_template("first.html") @app.route('/second') def next(): return render_template("second.html") if __name__=="__main__": app.run(debug=True) HTML Code for s...
It's not publically documented, but a Flask() object has a .jinja_options dict that will be used to build the Jinja Environment. Just make sure to set it ASAP. Source: https://github.com/pallets/flask/blob/bbb273bb761461ab329f03ff2d9002f6cb81e2a4/src/flask/app.py#L272 https://github.com/pallets/flask/blob/bbb273bb76146...
8
9