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 |
|---|---|---|---|---|---|---|
63,786,661 | 2020-9-8 | https://stackoverflow.com/questions/63786661/python-argparse-select-a-list-from-choices | How do you use argparse to provide a list of arguments from a group of choices. For example, lets say I want something like: python sample.py --p1 ['a','b'] --p2 ['x','y'] Where p1 can only be any or all from list of 'a', 'b', 'c' and p2 can only be any or all from list of 'x', 'y', 'z' | I found a way to get the behavior you want, but with a different syntax than what you present. You have to specify each choice with a unique parameter name/value pair. If that's ok, then the following works: parser = argparse.ArgumentParser(prog='game.py') parser.add_argument('--p1', choices=['a', 'b', 'c'], action='ap... | 10 | 10 |
63,785,462 | 2020-9-7 | https://stackoverflow.com/questions/63785462/problems-instaling-libpq-dev-in-ubuntu-20-04 | I am currently trying to install libpq-dev to install psycopg2. The problem is, when I try to install it, an error occurs saying I don't have the latest libpq5 version. However when I try to download the newer version of libpq5 the system says that I already have the latest version. An example of the error. lhmendes@lh... | I would say you have installed the latest libpq (12.4-1) but libpq-dev needs older version (12.4-0) and this makes problem. You may try to install older libpq apt-get install libpq==12.4-0ubuntu0.20.04.1 but if other program uses the latest version then older version can make problem with this program. pgdg20 in 12.4... | 43 | 15 |
63,782,494 | 2020-9-7 | https://stackoverflow.com/questions/63782494/django-rest-framework-how-to-ignore-unique-primary-key-constraint-when-valida | I am attempting to store large amounts of transit data in a PostgreSQL database, where a client uploads multiple records at a time (in the tens of thousands). I only want one arrival time per stop, per route, per trip and the unique identifier for that stop, route, and trip is the primary key for my table (and a foreig... | So, turns out the unique constraint is a field-level validator which is why trying to remove it at the class level wasn't working. I explicitly declared the field in the serializer class without any validators real_id = serializers.CharField(validators=[]), which fixed the problem. This page ultimately helped me if any... | 8 | 9 |
63,779,927 | 2020-9-7 | https://stackoverflow.com/questions/63779927/typeerror-categorical-crossentropy-missing-2-required-positional-arguments | Import libraries and models, from __future__ import print_function import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten from keras.layers import Conv2D, MaxPooling2D import keras.backend as k batch_size = 128 num_classes = 10 epochs = 12 Bel... | This is the correct implementation for getting a Categorical Crossentropy class object. loss = keras.losses.CategoricalCrossentropy() keras.losses.categorical_crossentropy this is a function which requires 2 parameters. | 6 | 13 |
63,779,711 | 2020-9-7 | https://stackoverflow.com/questions/63779711/find-paired-records-after-groupby-python | I have a dataframe like this: df = pd.DataFrame( [['101', 'a', 'in', '10'], ['101', 'a', 'out', '10'], ['102', 'b', 'in', '20'], ['103', 'c', 'in', '30'], ['103', 'c', 'out', '40']], columns=['col1', 'col2', 'col3', 'col4'] ) I want to group by col1 and find paired records that have the same value in col2 and col4, bu... | Let us try transform with nunique out = df[df.groupby(['col1','col2','col4'])['col3'].transform('nunique')==2] Out[187]: col1 col2 col3 col4 0 101 a in 10 1 101 a out 10 | 6 | 3 |
63,758,186 | 2020-9-5 | https://stackoverflow.com/questions/63758186/how-to-catch-exceptions-thrown-by-functions-executed-using-multiprocessing-proce | How can I catch exceptions from a process that was executed using multiprocessing.Process()? Consider the following python script that executes a simple failFunction() (which immediately throws a runtime error) inside of a child process using mulitprocessing.Process() #!/usr/bin/env python3 import multiprocessing, time... | This can be achieved by overloading the run() method in the multiprocessing.Proccess() class with a try..except statement and setting up a Pipe() to get and store any raised exceptions from the child process into an instance field for named exception: #!/usr/bin/env python3 import multiprocessing, traceback, time class... | 8 | 5 |
63,721,614 | 2020-9-3 | https://stackoverflow.com/questions/63721614/unhashable-type-in-fastapi-request | I am writing a post-api using fastapi. The required request-format is: { "leadid":LD123, "parties":[ { "uid":123123, "cust_name":"JOhn Doe", }, ...]} The fastapi code in python is: class Customer(BaseModel): UID: str CustName: str class PackageIn(BaseModel): lead_id: str parties: Set[Customer] # threshold: Optional[in... | Pytdantic BaseClass is not hashable. There is a discussion about this feature, i guess it will not be implemented. There is workaround in the discussion, for your case you can try this: from pydantic import BaseModel from typing import Set class MyBaseModel(BaseModel): def __hash__(self): # make hashable BaseModel subc... | 16 | 19 |
63,729,195 | 2020-9-3 | https://stackoverflow.com/questions/63729195/how-to-terminate-loop-run-in-executor-with-processpoolexecutor-gracefully | How to terminate loop.run_in_executor with ProcessPoolExecutor gracefully? Shortly after starting the program, SIGINT (ctrl + c) is sent. def blocking_task(): sleep(3) async def main(): exe = concurrent.futures.ProcessPoolExecutor(max_workers=4) loop = asyncio.get_event_loop() tasks = [loop.run_in_executor(exe, blockin... | You can use the initializer parameter of ProcessPoolExecutor to install a handler for SIGINT in each process. Update: On Unix, when the process is created, it becomes a member of the process group of its parent. If you are generating the SIGINT with Ctrl+C, then the signal is being sent to the entire process group. imp... | 9 | 6 |
63,762,387 | 2020-9-6 | https://stackoverflow.com/questions/63762387/how-to-group-fastapi-endpoints-in-swagger-ui | I started programming using FastAPI framework and it comes with a builtin Swagger interface to handle requests and responses. I have completed nearly 20 APIs and its hard to manage and recognise APIs on Swagger interface. Someone told me to add sections in Swagger interface to distinguish APIs, but I couldn't find any ... | You can add tags to your path parameter, for example. If you have something like this, using tags is extremely helpful. @app.delete("/items", tags=["Delete Methods"]) @app.put("/items", tags=["Put Methods"]) @app.post("/items", tags=["Post Methods"]) @app.get("/items", tags=["Get Methods"]) async def handle_items(): re... | 18 | 46 |
63,761,991 | 2020-9-6 | https://stackoverflow.com/questions/63761991/how-to-scrape-a-javascript-website-in-python | I am trying to scrape a website. I have tried using two methods but both do not provide me with the full website source code that I am looking for. I am trying to scrape the news titles from the website URL provided below. URL: "https://www.todayonline.com/" These are the two methods I have tried but failed. Method 1: ... | You can access data via API (check out the Network tab): For example, import requests url = "https://www.todayonline.com/api/v3/news_feed/7" data = requests.get(url).json() | 6 | 3 |
63,757,476 | 2020-9-5 | https://stackoverflow.com/questions/63757476/error-while-using-confluent-kafka-python-library-with-aws-lambda | I am trying to use the confluent-kafka python library to administer my cluster via a lambda function but the function fails with the error: "Unable to import module 'Test': No module named 'confluent_kafka.cimpl'" My requirements.txt requests confluent-kafka To create the zip file I moved my code to the site-packages... | I created the required layer and can verity that it works. The technique used includes docker tool described in the recent AWS blog: How do I create a Lambda layer using a simulated Lambda environment with Docker? Thus for this question, I verified it as follows: Create empty folder, e.g. mylayer. Go to the folder ... | 8 | 8 |
63,755,912 | 2020-9-5 | https://stackoverflow.com/questions/63755912/why-does-pylint-complain-about-unnecessary-elif-after-return-no-else-return | why does pylint complain about this code block? R1705: Unnecessary "elif" after "return" (no-else-return) def f(a): if a == 1: return 1 elif a == 2: return 2 return 3 To prevent the error, I had to create a temporary variable, which feels less pleasant. def f(a): if a == 1: b = 1 elif a == 2: b = 2 else: b = 3 return ... | The purpose of an else block is to define code that will not be executed if the condition is true, so execution wouldn't continue on to the next block. However, in your code, the main conditional block has a return statement, meaning execution will leave the function, so there's no need for an else block: all subsequen... | 19 | 17 |
63,754,895 | 2020-9-5 | https://stackoverflow.com/questions/63754895/how-to-create-windows-service-using-python | I have written a python script which will be installed in as windows service. Below is the code: import datetime import logging from logging.handlers import RotatingFileHandler import os import time from random import randint import win32serviceutil import win32service import win32event import servicemanager import soc... | Anyone facing this issue, just copy pywintypes36.dll from Python36\Lib\site-packages\pywin32_system32 to Python36\Lib\site-packages\win32 Helpful commands: Install a service: python app.py install Uninstall a service: python app.py remove Start a service: python app.py start Update service: python app.py update | 6 | 6 |
63,754,311 | 2020-9-5 | https://stackoverflow.com/questions/63754311/unidentifiedimageerror-cannot-identify-image-file | Hello I am training a model with TensorFlow and Keras, and the dataset was downloaded from https://www.microsoft.com/en-us/download/confirmation.aspx?id=54765 This is a zip folder that I split in the following directories: . ├── test │ ├── Cat │ └── Dog └── train ├── Cat └── Dog Test.cat and test.dog have each folder ... | Try this function to check if the image are all in correct format. import os from PIL import Image folder_path = 'data\img' extensions = [] for fldr in os.listdir(folder_path): sub_folder_path = os.path.join(folder_path, fldr) for filee in os.listdir(sub_folder_path): file_path = os.path.join(sub_folder_path, filee) pr... | 7 | 15 |
63,732,353 | 2020-9-3 | https://stackoverflow.com/questions/63732353/error-could-not-build-wheels-for-opencv-python-which-use-pep-517-and-cannot-be | I was trying to install OpenCV4 in a docker on jetson nano. It has jetpack 4.4 s os. The docker was successfully created and Tensorflow is running but while installing OpenCV using pip it is showing CMake error. root@5abf405fb92d:~# pip3 install opencv-python Collecting opencv-python Downloading opencv-python-4.4.0.42.... | I had the same problem and i did this, pip install --upgrade pip setuptools wheel then install opencv again, pip install opencv-python this worked for me | 46 | 97 |
63,733,994 | 2020-9-4 | https://stackoverflow.com/questions/63733994/recursive-operation-in-pandas | I have a DataFrame like this: vals = {"operator": [1, 1, 1, 2, 3, 5], "nextval": [2, 3, 6, 4, 5, 6]} df = pd.DataFrame(vals) operator nextval 0 1 2 1 1 3 2 1 6 3 2 4 4 3 5 5 5 6 What I'm trying to do is get a list of all the possible paths from a starting point, like 1, and an ending point, like 6, using the operators... | Check with networkx , you need a direction graph with 'root' to 'leaf' path import networkx as nx G=nx.from_pandas_edgelist(df,source='operator',target='nextval', edge_attr=None, create_using=nx.DiGraph()) road=[] for n in G: if G.out_degree(n)==0: #leaf road.append(nx.shortest_path(G, 1, n)) road Out[82]: [[1, 2, 4], ... | 8 | 4 |
63,741,028 | 2020-9-4 | https://stackoverflow.com/questions/63741028/type-hint-for-a-tuple-whose-length-is-a-known-big-number | I currently type hint a function returning tuple as follows: FuncOutput = Tuple[nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image, nib.Nifti1Image] Is there a way to do this in a concise manner where I can specify the length without typing it so many times? | No. typing.Tuple only supports typing each element or a variable number of elements. | 8 | 5 |
63,733,644 | 2020-9-4 | https://stackoverflow.com/questions/63733644/set-log-level-with-structlog | I am trying to setup structlog and set log level. My code looks like this: import structlog import logging filepath=open("out.log",'a') logging.basicConfig( level=logging.INFO ) structlog.configure( processors=[structlog.stdlib.filter_by_level], wrapper_class=structlog.BoundLogger, context_class=dict, logger_factory=st... | Well, the reason my filter didn't work is this: https://www.structlog.org/en/stable/processors.html#adapting Last filter in chain is special and can't just return a dictionary. And the following filter did the trick: def my_filter_by_level(logger, name, event_dict): this_level = structlog.stdlib._NAME_TO_LEVEL[name] se... | 15 | 0 |
63,729,692 | 2020-9-3 | https://stackoverflow.com/questions/63729692/check-if-numpy-array-is-stored-in-shared-memory | In Python 3.8+, is it possible to check whether a numpy array is being stored in shared memory? In the following example, a numpy array sharedArr was created using the buffer of a multiprocessing.shared_memory.SharedMemory object. Will like to know if we can write a function that can detect whether SharedMemory is used... | In this particular case, you can use the base attribute of the shared array. The attribute is a reference to the underlying object from which this array derives its memory. This is None for most arrays, to indicate that such an array owns its data. Running this code on my machine indicates that this array's base is a m... | 6 | 6 |
63,728,242 | 2020-9-3 | https://stackoverflow.com/questions/63728242/importerror-cannot-import-name-unknown-location | The project structure my_package ├── my_package │ ├── __init__.py │ └── my_module.py └── setup.py The module my_module.py has a single func function I am attempting to import. The setup.py file has the following content. from setuptools import setup, find_packages setup( name='my_package', packages=find_packages(where... | You're running your test.py script in the parent directory of your my_package directory. As a result, test.py will try and import the my_package subdirectory as a package/module, not your installed package. You will need to move to a directory that doesn't contain your source code and then run test. This could be as si... | 7 | 9 |
63,723,763 | 2020-9-3 | https://stackoverflow.com/questions/63723763/error-using-drive-mount-with-google-colab | I had been working on Colab using: from google.colab import drive .mount('/content/gdrive') with no problems, until today. I don't know why this error was raised: Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&re... | It turns out that if you manually copy the auth code from the auth button instead of clicking the copy button, it works | 21 | 37 |
63,727,290 | 2020-9-3 | https://stackoverflow.com/questions/63727290/why-doesnt-python-give-any-error-when-quotes-around-a-string-do-not-match | I've started learning Python recently and I don't understand why Python behaves like this: >>> "OK" 'OK' >>> """OK""" 'OK' >>> "not Ok' File "<stdin>", line 1 "not Ok' ^ SyntaxError: EOL while scanning string literal >>> "not OK""" 'not OK' Why doesn't it give an error for the last statement as the number of quotes d... | The final """ is not recognized as a triple-quotation, but a single " (to close the current string literal) followed by an empty string ""; the two juxtaposed string literals are concatenated. The same behavior can be more readily recognized by putting a space between the closing and opening ". >>> "not OK" "" 'not OK'... | 69 | 112 |
63,719,618 | 2020-9-3 | https://stackoverflow.com/questions/63719618/how-to-reduce-the-space-between-the-axes-and-the-first-and-last-bar | There is a big space between the border/x-axe of the graph and the first and last bar in a bar plot in pyplot (red arrows in the first picture). In the image below, it looks fine in the graph on the left, but it's wasting a lot of space in the graph on the right. The larger the graph, the larger the space. See how muc... | You can use plt.margins(x=0, tight=True). The default margins are 0.05 which means that 5% of the distance between the first and last x-values is used as a margin. Choosing a small value such as plt.margins(x=0-01, tight=True) would leave a bit of margin, so the bars don't look glued to the axes. In some situations wid... | 9 | 11 |
63,718,559 | 2020-9-3 | https://stackoverflow.com/questions/63718559/finding-most-similar-sentences-among-all-in-python | Suggestions / refer links /codes are appreciated. I have a data which is having more than 1500 rows. Each row has a sentence. I am trying to find out the best method to find the most similar sentences among all. What I have tried I have tried K-mean algorithm which groups similar sentences in a cluster. But I found a ... | Why did it not work for you with cosine similarity and the TFIDF-vectorizer? I tried it and it works with this code: import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity df = pd.DataFrame(columns=["ID","DESCRIPTION"], d... | 6 | 12 |
63,718,582 | 2020-9-3 | https://stackoverflow.com/questions/63718582/split-time-range-into-multiple-time-periods-based-on-interval-in-python | I have a time-range and an interval, I need to split the time range into multiple time periods based on interval value. For example, time range is 9:30 to 11:30 and the interval is 30, the output time periods should be in a list as datetime objects Output: [ 2020-08-24 9:30 - 2020-08-24 10:00, 2020-08-24 10:00 - 2020-0... | You can do arithmetic on datetime objects by adding timedelta objects. You probably need to decide exactly what behaviour is required if the interval per period is not an exact divisor of the total, but this example would give a final short period in that case. import datetime tstart = datetime.datetime(2020,8,24,9,30)... | 6 | 5 |
63,718,246 | 2020-9-3 | https://stackoverflow.com/questions/63718246/how-to-generate-2d-mesh-from-two-1d-arrays-and-convert-it-into-a-dataframe | For example, I have two arrays: import numpy as np x = np.array([1,2,3]) y = np.array([10, 11]) How can I generate a pandas dataframe with every combination of x and y, like below? x y 1 10 1 11 2 10 2 11 3 10 3 11 | import pandas as pd import numpy as np x = np.array([1,2,3]) y = np.array([10, 11]) pd.DataFrame({'x':np.repeat(x,y.shape[0]), 'y':np.tile(y,x.shape[0])}) yields: x y 0 1 10 1 1 11 2 2 10 3 2 11 4 3 10 5 3 11 | 6 | 3 |
63,713,241 | 2020-9-2 | https://stackoverflow.com/questions/63713241/segmentation-fault-using-python-shared-memory | The function store_in_shm writes a numpy array to the shared memory while the second function read_from_shm creates a numpy array using data in the same shared memory space and returns the numpy array. However, running the code in Python 3.8 gives the following segmentation error: zsh: segmentation fault python foo.py... | Basically the problem seems to be that the underlying mmap'ed file (owned by shm within read_from_shm) is being closed when shm is garbage collected when the function returns. Then shmData refers back to it, which is where you get the segfault (for referring to a closed mmap) This seems to be a known bug, but it can be... | 6 | 7 |
63,712,706 | 2020-9-2 | https://stackoverflow.com/questions/63712706/sql-server-pivot-one-column-and-keep-other-columns | I am trying to pivot a table in SQL Server (52M+ observations) however I am not getting the results I need. There are 15 descriptions each with a value that I need to pivot. Original Dataframe: ID | Date | Description| Value ------------------------------------------------- P1 | 2016-12-31 | ABC | 900 P2 | 2016-11-30 |... | Use conditional aggregation: select id, date, max(case when description = 'ABC' then value end) as abc, max(case when description = 'DEF' then value end) as def, max(case when description = 'MNO' then value end) as mno from mytable group by id, date | 6 | 7 |
63,706,985 | 2020-9-2 | https://stackoverflow.com/questions/63706985/convert-sha256-digest-to-uuid-in-python | Given a sha256 hash of a str in python: import hashlib hash = hashlib.sha256('foobar'.encode('utf-8')) How can the hash be converted to a UUID? Note: there will obviously be a many-to-one mapping of hexdigest to UUID given that a hexdigest has 2^256 possible values and a UUID has 2^128. Thank you in advance for your c... | Given that UUID takes a 32 hex character input string and hexdigest produces 64 characters, a simple approach would be to sub-index the resulting hash digest to achieve the appropriate string length: import hashlib import uuid hash = hashlib.sha256('foobar'.encode('utf-8')) uuid.UUID(hash.hexdigest()[::2]) | 6 | 9 |
63,702,163 | 2020-9-2 | https://stackoverflow.com/questions/63702163/vs-code-does-not-change-python-environment | I am using VS-Code and anaconda environment for python interpreter. I select the exact anaconda base environment by ctrl + shift + ` and it also reflects in the downside panel of vscode. But, when I checked the python version it shows my system's default python environment 3.7.9. If you see the below screenshot than, t... | To check & change vs code interpreter: In top left menu bar Click view In the dropdown menu, Click Command Palette Click Python: Select Interpreter Choose & Click on your desired Interpreter Another way to be sure to use anconda interpreter, open anaconda navigator and launch vs code from there. original vs code How-... | 6 | -3 |
63,597,239 | 2020-8-26 | https://stackoverflow.com/questions/63597239/is-there-any-post-load-in-pydantic | Previously I used the marshmallow library with the Flask. Some time ago I have tried FastAPI with Pydantic. At first glance pydantic seems similar to masrhmallow but on closer inspection they differ. And for me the main difference between them is post_load methods which are from marshmallow. I can't find any analogs fo... | It is not obvious but pydantic's validator returns value of the field. Pydantic v1 There are two ways to handle post_load conversions: validator and root_validator. validator gets the field value as argument and returns its value. root_validator is the same but manipulates with the whole object. from pydantic import va... | 12 | 18 |
63,623,930 | 2020-8-27 | https://stackoverflow.com/questions/63623930/how-to-create-unit-test-for-a-python-telegram-bot | I've built this Telegram Bot in Python, with python-telegram-bot. It's not so complex, but I want to do some regression tests to check if everything works fine after a new feature or a change, and more generally to test specific features to find bugs/edge cases. How can I achieve this? For now, I'm doing this manually,... | Have you looked to unit tests that are present in python-telegram-bot library? I think it is a good place to start. For example, in this file (historical version) you can see how to test a dialog with bot that uses ConversationHandler. | 9 | 5 |
63,609,570 | 2020-8-27 | https://stackoverflow.com/questions/63609570/mysql-values-function-is-deprecated | This is my python code which prints the sql query. def generate_insert_statement(column_names, values_format, table_name, items, insert_template=INSERT_TEMPLATE, ): return insert_template.format( column_names=",".join(column_names), values=",".join( map( lambda x: generate_raw_values(values_format, x), items ) ), table... | Basically, mysql is looking toward removing a longstanding non-standard use of the values function to clear the way for some future work where the SQL standard allows using a VALUES keyword for something very different, and because how the VALUES function works in subqueries or not in a ON DUPLICATE KEY UPDATE clause c... | 17 | 42 |
63,696,833 | 2020-9-1 | https://stackoverflow.com/questions/63696833/how-to-clear-the-conda-environment-variables | While I was setting an environment variable on a conda base env, I made an error in the path that was supposed to be assigned to the variable. I was trying to set the $PYSPARK_PYTHON env variable on the conda env. The set command conda env config vars set $PYSPARK_PYTHON=errorpath executed successfully even though the ... | Try looking for a JSON file called state that resides in the conda-meta directory of your environment. Depending on your OS and install directory the conda-meta will be installed in different locations. The default install path for each OS is Windows: C:\Users\<your-username>\Anaconda3\conda-meta\state Mac:/Users/<you... | 9 | 13 |
63,693,550 | 2020-9-1 | https://stackoverflow.com/questions/63693550/system-libraries-in-conda-environment-not-seen-by-reticulate | I'm trying to get the R package reticulate working on a CentOS 7.8 system using RStudio Server v1.2.5042 with a custom environment created with conda. When I initiate a Python job with reticulate, I get an error that some system libraries are not the correct versions, specifically, libstdc++.so.6 and libz.so.1. First o... | After struggling with a similar issue for several days, and trying many of the suggested solutions on the web (mostly based on symlinks, LD_LIBRARY_PATH variable, or installing/upgrading/downgrading packages like libgcc), I finally found something that is only mentioned once here : https://github.com/rstudio/reticulate... | 7 | 2 |
63,648,752 | 2020-8-29 | https://stackoverflow.com/questions/63648752/requests-exceptions-connectionerror-connection-aborted-remotedisconnected | I'm trying to connect to https://apis.digital.gob.cl/fl/feriados/2020, but I get an requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected('Remote end closed connection without response',)) error on a script that works perfectly with other URLs. The code: import requests response = requests.get... | The issue is that the website filters out requests without a proper User-Agent, so just use a random one from MDN: requests.get("https://apis.digital.gob.cl/fl/feriados/2020", headers={ "User-Agent" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" }) | 15 | 20 |
63,624,633 | 2020-8-27 | https://stackoverflow.com/questions/63624633/pandas-info-not-showing-all-columns-and-datatypes | I am have imported a csv file onto my Jupyter notebook and trying to obtain all the columns names and datatypes using the info() function. However, I get the following image. Any idea how to resolve it? I can't view all the columns and datatypes, only this vague information Thanks! | use verbose as argument to info, it gives option to print the full summary. see full documentation here You can also use show_counts (or null_counts for older pandas version since it was deprecated since pandas 1.2.0) argument to see null count information For pandas >= 1.2.0: df.info(verbose=True, show_counts=True) Fo... | 13 | 38 |
63,654,232 | 2020-8-30 | https://stackoverflow.com/questions/63654232/pytorch-dataloader-extremely-slow-first-epoch | When I create a PyTorch DataLoader and start iterating -- I get an extremely slow first epoch (x10--x30 slower then all next epochs). Moreover, this problem occurs only with the train dataset from the Google landmark recognition 2020 from Kaggle. I can't reproduce this on synthetic images, also, I tried to create a fol... | Slavka, TLDR: This is a caching effect. I did not download the whole GLR2020 dataset but I was able to observe this effect on the image dataset that I had locally (80000 jpg images of approx 400x400 size). To find the reasons for the difference in performance I tried the following: reducing the augmentation to just re... | 16 | 17 |
63,682,956 | 2020-9-1 | https://stackoverflow.com/questions/63682956/fastapi-retrieve-url-from-view-name-route-name | Suppose I have following views, from fastapi import FastAPI app = FastAPI() @app.get('/hello/') def hello_world(): return {"msg": "Hello World"} @app.get('/hello/{number}/') def hello_world_number(number: int): return {"msg": "Hello World Number", "number": number} I have been using these functions in Flask and Django... | We have got Router.url_path_for(...) method which is located inside the starlette package Method-1: Using FastAPI instance This method is useful when you are able to access the FastAPI instance in your current context. (Thanks to @Yagizcan Degirmenci) from fastapi import FastAPI app = FastAPI() @app.get('/hello/') def ... | 39 | 63 |
63,678,723 | 2020-8-31 | https://stackoverflow.com/questions/63678723/is-there-a-python-equivalent-to-template-literals-in-javascript | To provide a basic example, say I wanted to write: name = str(input()) age = int(input()) print('Hi, {name}, you are {age}.') In javascript, this would look like: console.log(`Hi, ${name}, you are ${age}.`) I assume there is no direct implementation of template literals in Python, as I haven't found any mention on Go... | You can go with formatted string literals ("f-strings") since Python 3.6 f"Hi {name}, you are {age}" Or string formatting "Hi {}, you are {}".format(name, age) "Hi {name}, you are {age}".format(name=name, age=age) Or format specifiers "Hi %s, you are %d" % (name, age) | 43 | 81 |
63,643,687 | 2020-8-29 | https://stackoverflow.com/questions/63643687/import-tkinter-if-this-fails-your-python-may-not-be-configured-for-tk-error-i | Currently using Ubuntu 20.04 LTS with python3.8.5. Its my first time using ubuntu with absolutely no previous knowledge of terminal.SO,would love to have a detailed answer if possible. Below is terminal output when i try importing tkinter in python3. >>> import tkinter Traceback (most recent call last): File "<stdin>",... | Resolved the issue it occurred because the Tkinter was installed for version 3.5 and not for the 3.8 version. For that, I installed the 3.5 version and kept only one version i.e. 3.8, and installed Tkinter again, and it worked! This is just a workaround to make things work, but the more preferred way is to create a ven... | 11 | 1 |
63,656,333 | 2020-8-30 | https://stackoverflow.com/questions/63656333/reduction-parameter-in-tf-keras-losses | According to the docs, the Reduction parameter takes on 3 values - SUM_OVER_BATCH_SIZE, SUM and NONE. y_true = [[0., 2.], [0., 0.]] y_pred = [[3., 1.], [2., 5.]] mae = tf.keras.losses.MeanAbsoluteError(reduction=tf.keras.losses.Reduction.SUM) mae(y_true, y_pred).numpy() > 5.5 mae = tf.keras.losses.MeanAbsoluteError() m... | Your assumption is correct as far as I understand. If you check the github [keras/losses_utils.py][1] lines 260-269 you will see that it does performs as expected. SUM will sum up the losses in the batch dimension, and SUM_OVER_BATCH_SIZE would divide SUM by the number of total losses (batch size). def reduce_weighted_... | 7 | 5 |
63,630,179 | 2020-8-28 | https://stackoverflow.com/questions/63630179/avoid-division-by-zero-in-numpy-where | I have two numpy arrays a, b of the same shape, b has a few zeros. I would like to set an output array to a / b where b is not zero, and a otherwise. The following works, but yields a warning because a / b is computed everywhere first. import numpy a = numpy.random.rand(4, 5) b = numpy.random.rand(4, 5) b[b < 0.3] = 0.... | Simply initialize output array with the fallback values (condition-not-satisfying values) or array and then mask to select the condition-satisfying values to assign - out = a.copy() out[mask] /= b[mask] If you are looking for performance, we can use a modified b for the division - out = a / np.where(mask, b, 1) Going... | 7 | 7 |
63,687,314 | 2020-9-1 | https://stackoverflow.com/questions/63687314/why-does-keras-model-fit-use-so-much-memory-despite-using-allow-growth-true | I have, thanks to this question mostly been able to solve the problem of tensorflow allocating memory which I didn't want allocated. However, I have recently found that despite my using set_session with allow_growth=True, using model.fit will still mean that all the memory is allocated and I can no longer use it for th... | I used to face this problem. And I found a solution from someone who I can't find anymore. His solution I paste below. In fact, I found that if you set allow_growth=True, tensorflow seems to use all your memory. So you should just set your max limit. try this: gpus = tf.config.experimental.list_physical_devices("GPU") ... | 8 | 6 |
63,676,411 | 2020-8-31 | https://stackoverflow.com/questions/63676411/pydantic-how-to-use-one-fields-value-to-set-values-for-other-fields | What I Have Dictionary: user_dict = {'user': {'field1': 'value1', 'field2': 'value2'}, 'admin':{'field1': 'value3', 'field2': 'value4'}} Pydantic Model: class User(BaseModel): account_type: Optional[str] = 'user' field1: Optional[str] = '' field1: Optional[str] = '' class Config: validate_assignment = True @validator(... | I solved it by using the root_validator decorator as follows: Solution: @root_validator(pre=False) def _set_fields(cls, values: dict) -> dict: """This is a validator that sets the field values based on the the user's account type. Args: values (dict): Stores the attributes of the User object. Returns: dict: The attribu... | 13 | 13 |
63,687,113 | 2020-9-1 | https://stackoverflow.com/questions/63687113/no-such-option-use-feature-while-installing-tensorflow-object-detection-api | I'm trying to install Tensorflow Object Detection API, following the steps at this link, which is the official installation's documentation for Tensorflow 2. git clone https://github.com/tensorflow/models.git > everything is ok cd models/research/ > everything is ok protoc object_detection/protos/*.proto --python_out=.... | I had the same problem, I upgraded pip version from 20.0.2 to 20.2.2, then it worked. An issue was opened on github on this matter, check here. Use python -m pip install --upgrade pip to upgrade pip. | 6 | 15 |
63,624,533 | 2020-8-27 | https://stackoverflow.com/questions/63624533/coinbase-apierrorid-in-python | I want to transfer money between my coinbase accounts. I'm storing all of my accounts' IDs from client.get_accounts()['data']['id'] and transferring with the code, tx = client.transfer_money('2bbf394c-193b-5b2a-9155-3b4732659ede', to='58542935-67b5-56e1-a3f9-42686e07fa40', amount='1', currency= 'BTC) But, I get this e... | I struggled with the same problem. It seems to be on their side and not limited to the python client. The only way I managed to transfer from wallet to wallet is by using the undocumented and unimplemented API "trades" that is used by the website. First your have to find the base_id of both your currencies, then your c... | 6 | 0 |
63,645,357 | 2020-8-29 | https://stackoverflow.com/questions/63645357/using-pytorch-with-celery | I'm trying to run a PyTorch model in a Django app. As it is not recommended to execute the models (or any long-running task) in the views, I decided to run it in a Celery task. My model is quite big and it takes about 12 seconds to load and about 3 seconds to infer. That's why I decided that I couldn't afford to load i... | Setting this method works as long as you're also using Process from the same library. from torch.multiprocessing import Pool, Process Celery uses "regular" multiprocessing library, thus this error. If I were you I'd try either: run it single threaded to see if that helps run it with eventlet to see if that helps read... | 8 | 10 |
63,602,222 | 2020-8-26 | https://stackoverflow.com/questions/63602222/what-loss-or-reward-is-backpropagated-in-policy-gradients-for-reinforcement-lear | I have made a small script in Python to solve various Gym environments with policy gradients. import gym, os import numpy as np #create environment env = gym.make('Cartpole-v0') env.reset() s_size = len(env.reset()) a_size = 2 #import my neural network code os.chdir(r'C:\---\---\---\Python Code') import RLPolicy policy... | mprouveur's answer was half correct but I felt that I needed to explain the right thing to backpropagate. The answer to my question on ai.stackexchange.com was how I came to understand this. The correct error to backpropagate is the log probability of taking the action multiplied by the goal reward. This can also be ca... | 11 | 0 |
63,620,981 | 2020-8-27 | https://stackoverflow.com/questions/63620981/dropbox-cant-generate-access-token-missing-scope | I just got started with using the DropBox API for Python - i want to use it to store files that my Discord Bot previously downloaded, but even following the official tutorial 1:1 i cant get it to just read and write files. I registered the app and generated an access token, and it always tells me dropbox.exceptions.Aut... | Regarding the 'missing_scope' error: You're correct, the app and access token need the particular scope required by the route in order to access the route. Note that just enabling a particular scope for an app, via the App Console, does not retroactively add authorization for that scope to existing access tokens though... | 9 | 30 |
63,650,010 | 2020-8-29 | https://stackoverflow.com/questions/63650010/could-not-find-a-version-that-satisfies-the-requirement-pyyaml-5-3-but-pyyaml | I am using SetupTools to build a package of my own. In INSTALL_REQUIRES in setup.py I have the following dependencies: ... INSTALL_REQUIRES = [ 'ray>=0.8.7', 'pyyaml>=5.3', ] setup(name=PACKAGE_NAME, version=VERSION, description=DESCRIPTION, long_description=LONG_DESCRIPTION, long_description_content_type=LONG_DESC_TYP... | Anthony Sottile's suggestion to use --extra-index-url worked for me. | 6 | 6 |
63,686,877 | 2020-9-1 | https://stackoverflow.com/questions/63686877/how-to-install-python-on-windows-without-an-msi-installer | Take python 3.6.x for example. The last windows installer for python 3.6.x is 3.6.8: no more installers for 3.6x version that comes later (see https://www.python.org/downloads/windows/) 3.6.8 happens to be the last maintenance release of python3.6, I don't know if it is somehow related to not propose a package installe... | It is possible to create your own MSI installer from the source distributions at https://www.python.org/downloads/source/. This is what I did to install Python 3.6.12 on my Windows machine. In each source distribution, the files at PCBuild/readme.txt and Tools/msi/README.txt provide guidance for how to build your own P... | 8 | 19 |
63,646,854 | 2020-8-29 | https://stackoverflow.com/questions/63646854/how-to-get-list-of-channels-that-i-joined-in-telethon | I want to make a script that shows the channels that i joined and then leave all of it with this example: from telethon.tl.functions.channels import LeaveChannelRequest await client(LeaveChannelRequest(input_channel)) | In order to leave all the channels you're in, you have to fetch all the channels from the dialogs list and then just delete them. Here is a snippet. async for dialog in client.iter_dialogs(): if not dialog.is_group and dialog.is_channel: await dialog.delete() | 11 | 17 |
63,660,037 | 2020-8-30 | https://stackoverflow.com/questions/63660037/django-contrib-auth-login-function-not-returning-any-user-as-logged-in | I have created a basic app using Django's built in authentication system. I successfully created a User object in the shell using >>python manage.py createsuperuser. I then created a basic view, 'UserLogin' along with corresponding serializers/urls, to log an existing user in using the django.contrib.auth authenticate(... | You have to set the default auth class as session authenticate class in DRF settings. Read more about it here [1]. Session auth uses session id to identify the user. So you have to send the cookie based session id in the request. Read about session auth here [2]. for example: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_... | 6 | 5 |
63,652,016 | 2020-8-29 | https://stackoverflow.com/questions/63652016/python-serverless-function-vercel-next-js | I found out that I could use Python to create a serverless function inside a Next.js project. Once deployed to Vercel, it will get converted into a serverless function. I went through the docs and found a simple example that outputs the date: from http.server import BaseHTTPRequestHandler from datetime import datetime ... | After going over the FAQs. I found an entry named Unmatched Function Pattern, it states: the functions property uses a glob pattern for each key. This pattern must match Serverless Function source files within the api directory. It also mentions: if you'd like to use a Serverless Function that isn't written with Nod... | 10 | 15 |
63,589,249 | 2020-8-26 | https://stackoverflow.com/questions/63589249/plotly-dash-display-real-time-data-in-smooth-animation | We are trying to produce a real-time dashboard in plotly-dash that displays live data as it is produced. We are generally following the guidance here (https://dash.plotly.com/live-updates). We have a callback that gathers a chunk of new data points from the source approximately every second and then appends the data to... | Updating traces of a Graph component without generating a new graph object can be achieved via the extendData property. Here is a small example that appends data each second, import dash import dash_html_components as html import dash_core_components as dcc import numpy as np from dash.dependencies import Input, Output... | 45 | 68 |
63,679,315 | 2020-8-31 | https://stackoverflow.com/questions/63679315/how-to-use-cython-with-poetry | I have a file in my project which I would like to compile for performance reasons: mylibrary/myfile.py How to achieve this with Poetry? | There is an undocumented feature in Poetry. Add this to your pyproject.toml: [tool.poetry] ... build = 'build.py' [build-system] requires = ["poetry>=0.12", "cython"] build-backend = "poetry.masonry.api" What this does is runs the build.py:build() function inside the implicitly generated setup.py. This is where we bui... | 19 | 26 |
63,690,068 | 2020-9-1 | https://stackoverflow.com/questions/63690068/how-to-find-cosine-similarity-of-one-vector-vs-matrix | I have a TF-IDF matrix of shape (149,1001). What is want is to compute the cosine similarity of last columns, with all columns Here is what I did from numpy import dot from numpy.linalg import norm for i in range(mat.shape[1]-1): cos_sim = dot(mat[:,i], mat[:,-1])/(norm(mat[:,i])*norm(mat[:,-1])) cos_sim But this loop... | Leverage 2D vectorized matrix-multiplication Here's one with NumPy using matrix-multiplication on 2D data - p1 = mat[:,-1].dot(mat[:,:-1]) p2 = norm(mat[:,:-1],axis=0)*norm(mat[:,-1]) out1 = p1/p2 Explanation : p1 is the vectorized equivalent of looping of dot(mat[:,i], mat[:,-1]). p2 is of (norm(mat[:,i])*norm(mat[:,... | 6 | 6 |
63,672,218 | 2020-8-31 | https://stackoverflow.com/questions/63672218/efficiently-finding-consecutive-streaks-in-a-pandas-dataframe-column | I have a DataFrame similar to the below:, and I want to add a Streak column to it (see example below): Date Home_Team Away_Team Winner Streak 2005-08-06 A G A 0 2005-08-06 B H H 0 2005-08-06 C I C 0 2005-08-06 D J J 0 2005-08-06 E K K 0 2005-08-06 F L F 0 2005-08-13 A B A 1 2005-08-13 C D D 1 2005-08-13 E F F 0 2005-08... | I will present a numpy-based solution here. Firstly because I am not very familiar with pandas and don't feel like doing the research, and secondly because a numpy solution should work just fine regardless. Let's take a look at what happens to one given team first. Your goal is to find the number of consecutive wins fo... | 9 | 4 |
63,687,789 | 2020-9-1 | https://stackoverflow.com/questions/63687789/how-do-i-create-a-pie-chart-using-categorical-data-in-matplotlib | I have data as follows: ID Gender Country ... 1 Male UK 2 Female US 3 Male NZ 4 Female UK ... There are only 2 options for gender and 3 for country. I would like to create a seperate pie chart for both "Gender" and "Country" to show how many times each option shows up in the data but I'm quite confused about how to do... | Here is an approach using pandas: import pandas as pd import numpy as np from matplotlib import pyplot as plt def label_function(val): return f'{val / 100 * len(df):.0f}\n{val:.0f}%' N = 50 df = pd.DataFrame({'country': np.random.choice(['UK', 'US', 'NZ'], N), 'gender': np.random.choice(['Male', 'Female'], N)}) fig, (a... | 9 | 13 |
63,687,319 | 2020-9-1 | https://stackoverflow.com/questions/63687319/how-to-convert-a-sklearn-pipeline-into-a-pyspark-pipeline | We have a machine learning classifier model that we have trained with a pandas dataframe and a standard sklearn pipeline (StandardScaler, RandomForestClassifier, GridSearchCV etc). We are working on Databricks and would like to scale up this pipeline to a large dataset using the parallel computation spark offers. What ... | According to the Databricks instructions (here and here), the necessary requirements are: Python 3.6+ pyspark>=2.4 scikit-learn>=0.21 joblib>=0.14 I cannot reproduce your issue in a community Databricks cluster running Python 3.7.5, Spark 3.0.0, scikit-learn 0.22.1, and joblib 0.14.1: import sys import sklearn import... | 8 | 5 |
63,673,724 | 2020-8-31 | https://stackoverflow.com/questions/63673724/python-subtest-parameters | When using python's unittest subtest, I am confused regarding how parameters are named and scoped within the sub-test. The canonical example given in the link above seems to imply that the parameters used within the with self.subtest() clause can be passed as keyword arguments to subTest(). For reference, the example s... | It seems to me that it would be nice if this was expounded on a little bit more in the docs, but the API for subTest(msg=None, **params) states: ...msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly. So it seems that the keyword arguments ... | 7 | 11 |
63,668,501 | 2020-8-31 | https://stackoverflow.com/questions/63668501/windows-notification-with-button-using-python | I need to make a program that alerts me with a windows notification, and I found out that this can be simply done with the following code. I don't care what library I use from win10toast import ToastNotifier toast = ToastNotifier() toast.show_toast("alert","text") This code gives that following alert However, I want ... | This type of behavior is not supported in the currently released version of Windows-10-Toast-Notifications. However, a contributor created a pull request that adds functionality for a callback_on_click parameter that will call a function when the notification is clicked. This has yet to be merged into the master branch... | 7 | 10 |
63,663,362 | 2020-8-31 | https://stackoverflow.com/questions/63663362/django-python3-on-install-i-get-parent-module-setuptools-not-loaded | I see lots of errors and suggestions about Parent module '' not loaded, ... I don't see any about specifically "out of the box" django 3.5. $ mkvirtualenv foobar -p /usr/bin/python3 Already using interpreter /usr/bin/python3 Using base prefix '/usr' New python executable in /home/isaac/.virtualenvs/foobar/bin/python3 A... | Something happened in version 50 of setuptools. We could "solve" this problem by downgrading setuptools to 49.3.0 (and maybe pip to 20.2.1) pip install setuptools==49.3.0 and pip install pip==20.2.1 Be aware though that this should only be a temporary solution! | 15 | 18 |
63,668,103 | 2020-8-31 | https://stackoverflow.com/questions/63668103/how-can-i-get-or-print-current-datetime-of-gmt-time-zone-in-python | Here I print UTC time zone's current datetime. I want current GMT time zone's datetime by this method. How can I? import datetime dt_utcnow = datetime.datetime.utcnow() print(dt_utcnow) Output 2020-08-31 09:06:26.661323 | You can use the gmtime() of time module to achieve this: from datetime import datetime from time import gmtime, strftime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time) print("Your Time Zone is GMT", strftime("%z", gmtime())) | 6 | 8 |
63,651,619 | 2020-8-29 | https://stackoverflow.com/questions/63651619/why-is-fast-orb-bad-at-finding-keypoints-near-the-edge-of-an-image | ORB doesn't find keypoints near the edge of an image and I don't understand why. It seems worse that SIFT and SURF and I would expect the opposite. If I understand correctly then SIFT/SURF use a 16x16 and 20x20 square block respectedly around the test-point so I would expect them not to find keypoints 8 and 10 pixels f... | Usually, keypoints at the edge of the image are not useful for most applications. Consider e.g. a moving car or a plane for aerial images. Points at the image border are often not visible in the following frame. When calculating 3D reconstructions of objects most of the time the object of interest lies in the center of... | 6 | 6 |
63,667,255 | 2020-8-31 | https://stackoverflow.com/questions/63667255/plotting-graphs-in-c | I have made the following graph using matplotlib in python.I have also attached the code I used to make this. The code for the arena import matplotlib.pyplot as plt import matplotlib.patches as patches obs_boundary = [ [0, 0, 10, 600], [0, 600, 900, 10], [10, 0, 900, 10], [900, 10, 10, 600] ] obs_cir_own = [ [50,500,10... | You could try https://github.com/lava/matplotlib-cpp, which looks like it is just a wrapper around matplotlib anyway, so you are still calling/using Python and matplotlib in the end. With this you probably can copy your code nearly verbatim to "C++". | 7 | 13 |
63,665,702 | 2020-8-31 | https://stackoverflow.com/questions/63665702/why-is-binding-a-class-instance-method-different-from-binding-a-class-method | I was reading the python docs and stumbled upon the following lines: It is also important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this only happens when the function is an attribute of the class. Please, someone explain what does that mean in pl... | Setting a User Defined Method to be an Attribute of Class, The Wrong Way Consider the following example class A and function f: class A: pass def f(self): print("I\'m in user-defined function") a = A() The function f is defined separately and not inside the class. Let's say you want to add function f to be an instanc... | 14 | 13 |
63,614,899 | 2020-8-27 | https://stackoverflow.com/questions/63614899/stay-solid-and-dry-with-coroutines-and-functions-as-methods-in-python | I have that Code example: from time import sleep import asyncio class bird: def __init__(self, sleeptime=1): self.var = sleeptime def wait_meep(self): sleep(self.var) print("Meep") def do_sth(self): print("Dop Dop Do do ...") class bird_async: def __init__(self, sleeptime=1): self.var = sleeptime async def wait_meep(se... | The DRY solution is some kind of subclassing as you already did. I think a "SOLID" solution is very hard to achieve under your condition. Fact is, you have two functions wait_meep, which have actually different signature and semantics. Namely, the first one blocks for the sleep interval, which can be arbitrary long. Th... | 8 | 6 |
63,661,711 | 2020-8-30 | https://stackoverflow.com/questions/63661711/when-where-does-pypy-produce-machine-code | I have skimmed through the PyPy implementation details and went through the source code as well, but PyPy's execution path is still not totally clear to me. Sometimes Bytecode is produced, sometimes it is skipped for immediate machine-code compiling (interpreter level/app level code), But I can't figure out when and w... | Your best guide is the pypy architecture documentation, and the actual JIT documentation. What jumped out the most for me is this: we have a tracing JIT that traces the interpreter written in RPython, rather than the user program that it interprets. This is covered in more detail in the JIT overview. It seems to be t... | 8 | 3 |
63,661,866 | 2020-8-30 | https://stackoverflow.com/questions/63661866/ordinal-encoder-issues-with-nan-values | I have a dataframe with blank spaces as missing values, so I have replaced them with NaN values by using a regex. The problem that I have is when I want to use ordinal encoding for replacing categorical values. My code so far is the following: x=pd.DataFrame(np.array([30,"lawyer","France", 25,"clerk","Italy", 22," ","... | You can try with factorize, notice here is category start with 0 x.job.mask(x.job==' ').factorize()[0] Out[210]: array([ 0, 1, -1, 2, 0, 2], dtype=int32) | 6 | 4 |
63,658,086 | 2020-8-30 | https://stackoverflow.com/questions/63658086/tensorflow-2-0-valueerror-while-loading-weights-from-h5-file | I have a VAE architecture script as follows: import numpy as np import tensorflow as tf from tensorflow.keras.layers import Input, Conv2D, Flatten, Dense, Conv2DTranspose, Lambda, Reshape, Layer from tensorflow.keras.models import Model from tensorflow.keras.optimizers import Adam from tensorflow.keras import backend a... | What version of TF are you running? For a while the default saving format was hdf5, but this format cannot support subclassed models as easily, so you get this error. It may be solvable by first training it on a single batch and then loading the weights (to determine how the parts are connected, which is not saved in h... | 10 | 3 |
63,656,891 | 2020-8-30 | https://stackoverflow.com/questions/63656891/importerror-plotly-express-requires-pandas-to-be-installed | When I try to import plotly.express I get the error: ImportError: Plotly express requires pandas to be installed. The installation notes did not mention having to install anything additional. I can import plotly on its own, I only get the error when importing plotly.express. Any ideas on how to fix this? | Pandas is a dependency that is only used in plotly.express not in plotly. For more you can visit this issue.So you need to install pandas using pip install pandas or conda install -c anaconda pandas | 11 | 5 |
63,655,115 | 2020-8-30 | https://stackoverflow.com/questions/63655115/indexerror-replacement-index-1-out-of-range-for-positional-args-tuple | I am following a tutorial and I don't know why I got this error: <ipython-input-61-d59f7a5a07ab> in extract_featuresets(ticker) 2 tickers, df = process_data_for_labels(ticker) 3 df['{}_target'.format(ticker)] = list(map(buy_sell_hold, ----> 4 df['{}_{}1d'.format(ticker)], 5 df['{}_{}2d'.format(ticker)], 6 df['{}_{}3d'... | Your format string need two arguments in format while you are only passing in one ticker as argument. If ticker is a two element list or tuple, you can do this: df['{}_{}1d'.format(*ticker)] Otherwise remove one curly brackets: df['{}_1d'.format(ticker)] | 18 | 31 |
63,650,646 | 2020-8-29 | https://stackoverflow.com/questions/63650646/add-labels-and-title-to-a-plot-made-using-pandas | I made a simple histogram using the following code: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] pd.Series(a).value_counts().plot('bar') Although this is a concise way to plot frequency histogram, I am not sure how to customize the plot i.e. : Add Title Add Axis Labels Sort values ... | Series.plot (or DataFrame.plot) returns a matplotlib axis object which exposes several methods. For example: a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e'] ax = pd.Series(a).value_counts().sort_index().plot('bar') ax.set_title("my title") ax.set_xlabel("my x-label") ax.set_ylabel("my y-... | 7 | 7 |
63,648,184 | 2020-8-29 | https://stackoverflow.com/questions/63648184/error-installing-packages-using-pip-you-must-use-visual-studio-to-build-a-pyth | I am using VS Code on Windows 10. When I try to install the face_recognition package using pip I get the following error: ERROR: Command errored out with exit status 1: command: 'c:\users\admin\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Adm... | The answer is really simple. You have to do what it says. Go to the VS installer and install VS for C++ and C#. The reason is that these modules use C code and while using Visual Studio, you have to make it so that it can compile the C++ code | 8 | 8 |
63,647,103 | 2020-8-29 | https://stackoverflow.com/questions/63647103/merging-pandas-dataframes-with-respect-to-a-function-output | Is there a convenient way to merge two dataframes with respect to the distance between rows? For the following example, I want to get the color for df1 rows from the closest df2 rows. The distance should be computed as ((x1-x2)**0.5+(y1-y2)**0.5)**0.5. import pandas as pd df1 = pd.DataFrame({'x': [50,16,72,61,95,47],'y... | Something from numpy broadcast df1['color']=df2.color.iloc[np.argmin(np.sum(np.abs(df1[['x','y']].values-df2[['x','y']].values[:,None])**0.5,2),0)].values df1 Out[79]: x y size color 0 50 14 1 black 1 16 22 4 white 2 72 11 3 black 3 61 45 7 blue 4 95 58 6 blue 5 47 56 5 red | 8 | 6 |
63,642,961 | 2020-8-29 | https://stackoverflow.com/questions/63642961/split-list-recursively-until-flat | I'm writing a passion program that will determine the best poker hand given hole cards and community cards. As an ace can go both ways in a straight, I've coded this as [1, 14] for a given 5 card combination. I understand recursion but implementing it is a different story for me. I'm looking for a function that will sp... | Well, there is an easier way to do this: from itertools import product product(*[i if isinstance(i, list) else [i] for i in hand]) I challenge everybody to come up with a simpler solution | 20 | 20 |
63,635,104 | 2020-8-28 | https://stackoverflow.com/questions/63635104/plotly-how-to-set-choropleth-map-color-for-a-discrete-categorical-variable | I am trying to plot a world map with all the countries having different risk levels (low, moderate and high). I would like to make each risk level a different color but am not sure how to change the color scheme so that each risk category has a color of my choice. The df.risk variable currently has low as 1, moderate a... | In this case I would rather use plotly.express with color=df['risk'] and then set color_discrete_map={'High':'red', 'Moderate':'Yellow','Low':'Green'}: Plot: Complete code: import plotly.express as px import pandas as pd fig = px.choropleth(locations=df['Country'], locationmode="country names", color=df['risk'], color... | 13 | 10 |
63,639,543 | 2020-8-28 | https://stackoverflow.com/questions/63639543/how-to-get-top-n-rows-with-a-max-limit-by-group-in-pandas | I have a dataframe which looks like this pd.DataFrame({'A': ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10'], ...: 'B': ['A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'C'], ...: 'R': [9, 1, 7, 4, 3, 5, 2, 6, 8, 10]}) Out[3]: A B R 0 C1 A 9 1 C2 A 1 2 C3 A 7 3 C4 B 4 4 C5 B 3 5 C6 B 5 6 C7 B 2 7 C8 C 6 8 C9 ... | We can try with GroupBy.head new_df = df.sort_values('R').groupby('B', sort=False).head(3).head(5) print(new_df) A B R 1 C2 A 1 6 C7 B 2 4 C5 B 3 3 C4 B 4 7 C8 C 6 | 6 | 8 |
63,626,723 | 2020-8-28 | https://stackoverflow.com/questions/63626723/find-missing-elements-in-a-list-created-from-a-sequence-of-consecutive-integers | This is a Find All Numbers Disappeared in an Array problem from LeetCode: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once. Find all the elements of [1, n] inclusive that do not appear in this array. Could you do it without extra space and in O(n) run... | You can implement an algorithm where you loop through each element of the list and set each element at index i to a negative integer if the list contains the element i as one of the values,. You can then add each index i which is positive to your list of missing items. It doesn't take any additional space and uses at t... | 7 | 4 |
63,637,395 | 2020-8-28 | https://stackoverflow.com/questions/63637395/addition-between-int-and-custom-class | I was experimenting around with dunders in python when I found something: Say I created a class: class MyInt: def __init__(self, val): self.val = val def __add__(self, other): return self.val + other a = MyInt(3) The __add__ works perfectly fine when this is run: >>> print(a + 4) 7 However, when I ran this: >>> print... | This is what the __radd__ method is for - if your custom object is on the right side of the operator, and the left side of the operator can't handle it. Note that the left side of the operator will take precedence, if possible. >>> class MyInt: ... def __init__(self, val): ... self.val = val ... def __add__(self, other... | 8 | 12 |
63,628,218 | 2020-8-28 | https://stackoverflow.com/questions/63628218/how-to-get-current-time-in-india-in-python | How would I get the current timestamp in python of India? I tried time.ctime() and datetime.utcnow() also datetime.now() but they all return a different time than here it is in india. The codes above return the time that not match the current time on my computer. and the time in my computer is definitely correct. | from pytz import timezone from datetime import datetime ind_time = datetime.now(timezone("Asia/Kolkata")).strftime('%Y-%m-%d %H:%M:%S.%f') print(ind_time) >>> "2020-08-28 11:56:37.010822" | 6 | 19 |
63,603,325 | 2020-8-26 | https://stackoverflow.com/questions/63603325/error-no-matching-distribution-found-for-ipython-7-17-0 | I uploaded a Python app to Heroku. In my requirements.txt file I have a line for ipython==7.17.0 but Heroku seems unable to retrieve it, I don't understand why this might happen because I'm able to download that ipython version on my machine. The complete error thrown is: ERROR: Could not find a version that satisfies ... | The last allowed version is 7.16.1, that means you use Python 3.6. 7.17 requires Python 3.7+. | 6 | 12 |
63,623,113 | 2020-8-27 | https://stackoverflow.com/questions/63623113/i-am-trying-to-use-cv2-solvepnp-but-i-am-getting-an-error | This is the error: cv2.solvePnP(obj_points, image_points, mtx, dist) cv2.error: OpenCV(4.2.0) C:\projects\opencv-python\opencv\modules\calib3d\src\solvepnp.cpp:754: error: (-215:Assertion failed) ( (npoints >= 4) || (npoints == 3 && flags == SOLVEPNP_ITERATIVE && useExtrinsicGuess) ) && npoints == std::max(ipoints.chec... | I had this error very recently, and I resolved it by making the argument ndarrays floats instead of ints. You can do that in 2 ways: obj_points = np.array([[0.0, 0.0, 0.0], [297.0, 0.0, 0.0], [297.0, 210.0, 0.0], [0.0, 210.0, 0.0]]) image_points = np.array([[416.0, 268.0], [422.0, 535.0], [826.0, 543.0], [829.0, 264.0]... | 6 | 5 |
63,616,798 | 2020-8-27 | https://stackoverflow.com/questions/63616798/how-to-pass-the-default-value-to-a-variable-if-none-was-passed | Can I make a default value in Pydantic if None is passed in the field? I have the following code, but it seems to me that the validator here only works on initialization of the model and not otherwise. My Code: class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' email: EmailStr @validator('name... | You need to enable validate_assignment option in model config: from typing import Optional from pydantic import BaseModel, validator class User(BaseModel): name: Optional[str] = '' password: Optional[str] = '' class Config: validate_assignment = True @validator('name') def set_name(cls, name): return name or 'foo' user... | 61 | 56 |
63,615,560 | 2020-8-27 | https://stackoverflow.com/questions/63615560/boto3-dynamodb-put-item-error-only-accepts-keyword-arguments | I'm using boto3 in a lambda function to write information into a dynamodb table. I get the error put_item() only accepts keyword arguments. Searching on the web, i found that this error may mean that I am not matching dynamodb partition key, but it seems to me that I am doing everything correctly. Can anyone help me fi... | put_item requires keyword only arguments. This means, that in your case instead of: response = table.put_item(Item) there should be response = table.put_item(Item=Item) | 7 | 11 |
63,614,660 | 2020-8-27 | https://stackoverflow.com/questions/63614660/testing-fastapi-formdata-upload | I'm trying to test the upload of a file and its metadata using Python and FastAPI. Here is how I defined the route for the upload: @app.post("/upload_files") async def creste_upload_files(uploaded_files: List[UploadFile], selectedModel: str = Form(...), patientId: str = Form(...), patientSex: str = Form(...), actualMed... | The answer is just to replace json=self.metadata which can be used for body parameters by data=self.metadata for a formData | 8 | 13 |
63,604,630 | 2020-8-26 | https://stackoverflow.com/questions/63604630/dataclass-how-do-i-create-a-field-that-does-not-need-initializing-which-is-auto | I used field(init= False) to disable initializing self.ref. It is then a value in post. The following code raises AttributeError: 'Data' object has no attribute 'ref' from dataclasses import dataclass, field def make_list(): return [[0] for k in range(9)] @dataclass class Data: rows: list cols: list blocks: list ref: d... | Thanks to @wim and @juanpa.arrivillaga Deleting the __init__ would fix the problem and let the __post_init__ run again. (As pointed out by wim and juanpa.arrivillaga) If I write my own __init__ , why even bother writing __post_init__ , I can write all post processing all I want in there. (line order) from dataclasses i... | 20 | 17 |
63,601,580 | 2020-8-26 | https://stackoverflow.com/questions/63601580/use-gpu-with-opencv-python | I'm trying to use opencv-python with GPU on windows 10. I installed opencv-contrib-python using pip and it's v4.4.0.42, I also have Cuda on my computer and in path. Anyway, here is a (simple) code that I'm trying to compile: import cvlib as cv from cvlib.object_detection import draw_bbox bbox, label, conf = cv.detect_c... | The problem here is that version of opencv distributed with your system (Windows in this case) was not compiled with Cuda support. Therefore, you cannot use any cuda related function with this build. If you want to have an opencv with cuda support, you will have to either compile it yourself (which may be tedious on wi... | 22 | 10 |
63,599,687 | 2020-8-26 | https://stackoverflow.com/questions/63599687/is-it-better-to-pre-allocate-array-in-python-or-use-arr-append | In terms of readability and performance, should I pre-allocate memory for an array using [None]*n? Is allocating an empty one [] and using .append() over and over considered wasteful? | In this simple timing test, the use of [None] * n does indeed appear to be slightly quicker, but arguably not by enough to justify adopting this approach over the more usual idioms. import time def func1(size): a = [None] * size for i in range(size): a[i] = i def func2(size): a = [] for i in range(size): a.append(i) de... | 8 | 8 |
63,599,290 | 2020-8-26 | https://stackoverflow.com/questions/63599290/how-to-save-json-responses-with-asynchronous-requests | I have a question regarding asynchronous requests: How do I save response.json() to a file, on the fly? I want to make a request and save response to a .json file, without keeping it in memory. import asyncio import aiohttp async def fetch(sem, session, url): async with sem: async with session.get(url) as response: re... | How do I save response.json() to a file, on the fly? Don't use response.json() in the first place, use the streaming API instead: async def fetch(sem, session, url): async with sem, session.get(url) as response: with open("some_file_name.json", "wb") as out: async for chunk in response.content.iter_chunked(4096) out.... | 6 | 3 |
63,597,476 | 2020-8-26 | https://stackoverflow.com/questions/63597476/pandas-dataframe-multiline-query | Say I have a dataframe import numpy as np import pandas as pd df = pd.DataFrame(np.random.randint(10, size=(10,3)), columns=['a', 'b', 'c']) if I now try to query it using the query method: this works: df.query('''a > 3 and b < 9''') this throws an error: df.query( ''' a > 3 and b < 9 ''' ) I tried many variations of... | Use multi-line char backslash ( \ ) Ex: df = pd.DataFrame(np.random.randint(10, size=(10,3)), columns=['a', 'b', 'c']) print(df.query( ''' a > 3 and \ b < 9 ''' )) | 21 | 21 |
63,591,449 | 2020-8-26 | https://stackoverflow.com/questions/63591449/celery-task-hangs-after-calling-delay-in-django | While calling the .delay() method of an imported task from a django application, the process gets stuck and the request is never completed. We also don't get any error on the console. Setting up a set_trace() with pdb results in the same thing. The following questions were reviewed which didn't help resolve the issue: ... | The issue was with the setup of the celery application with Django. We need to make sure that the celery app is imported and initialized in the following file: backend\__init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that share... | 7 | 14 |
63,589,351 | 2020-8-26 | https://stackoverflow.com/questions/63589351/environment-variables-not-updating | I am using the dotenv package. I had a key that I had saved in my .env file but I updated it to a new key, but my script still outputs the old key. I have the ".env" file in the root directory. I thought that by using load_dotenv() that it's taking in the new keys whatever they may be at the current state in time and s... | I had to set override=True load_dotenv(override=True) load_dotenv does not override existing System environment variables. To override, pass override=True to load_dotenv(). | 25 | 63 |
63,583,880 | 2020-8-25 | https://stackoverflow.com/questions/63583880/make-isort-recognize-imports-from-django-apps-as-first-party-imports | I'm working on a project with many different Django apps. I want to use isort on this project but the imports from Django apps (from myapp1.mymodule import myfunction) are seen by isort as third-party imports. How can I make isort recognize them as first-party imports? I could add in the isort configuration (in the .cf... | You can use the src_paths option to specify the project folder. You do not need to maintain a known_first_party list. See the related source code: if ( _is_module(module_path) or _is_package(module_path) or _src_path_is_module(src_path, root_module_name) ): return (sections.FIRSTPARTY, f"Found in one of the configured ... | 8 | 7 |
63,488,416 | 2020-8-19 | https://stackoverflow.com/questions/63488416/how-to-move-files-from-current-path-to-a-specific-folder-named-like-or-similar-t | My Folder Structure looks like this: - 95000 - 95002 - 95009 - AR_95000.pdf - AR_95002.pdf - AR_95009.pdf - BS_95000.pdf - BS_95002.pdf - BS_95009.pdf [Note 95000, 95002, 95009 are folders] My goal is to move files AR_95000.pdf and BS_95000.pdf to the folder named 95000, then AR_95002.pdf and BS_95002.pdf to the fold... | Using pathlib this task becomes super easy: from pathlib import Path root = Path("/path/to/your/root/dir") for file in root.glob("*.pdf"): folder_name = file.stem.rpartition("_")[-1] file.rename(root / folder_name / file.name) As you can see, one main advantage of pathlib over os/shutil (in this case) is the interface... | 22 | 50 |
63,587,660 | 2020-8-25 | https://stackoverflow.com/questions/63587660/yielding-asyncio-generator-data-back-from-event-loop-possible | I would like to read from multiple simultanous HTTP streaming requests inside coroutines using httpx, and yield the data back to my non-async function running the event loop, rather than just returning the final data. But if I make my async functions yield instead of return, I get complaints that asyncio.as_completed()... | Normally you should just make collect_data async, and use async code throughout - that's how asyncio was designed to be used. But if that's for some reason not feasible, you can iterate an async iterator manually by applying some glue code: def iter_over_async(ait, loop): ait = ait.__aiter__() # helper async fn that ju... | 7 | 13 |
63,493,530 | 2020-8-19 | https://stackoverflow.com/questions/63493530/how-to-plot-and-annotate-a-grouped-bar-chart | I came across a tricky issue about the matplotlib in Python. I want to create a grouped bar chart with several codes, but the chart goes wrong. Could you please offer me some advice? The code is as follows. import numpy as np import pandas as pd file="https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/Co... | Imports and DataFrame import pandas as pd import matplotlib.pyplot as plt # given the following code to create the dataframe file = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv" df = pd.read_csv(file, index_col=0) df.sort_values(by=... | 7 | 12 |
63,512,788 | 2020-8-20 | https://stackoverflow.com/questions/63512788/how-to-fix-the-google-auth-exceptions-refresherror-no-access-token-in-respon | I followed the video from TechWithTim step by step (https://www.youtube.com/watch?v=cnPlKLEGR7E) but I am still getting an error when I try to open the sheet. The code works fine until sheet = client.open("GuildTaxes").sheet1 line. Here is my code. import gspread from oauth2client.service_account import ServiceAccountC... | I found the answer! After 2 hours, the scope in TechWithTim's video doesn't work for me, so if you stumble upon the same issue try using this one scope = [ 'https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive' ] It is the default scope. | 7 | 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.