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 |
|---|---|---|---|---|---|---|
64,406,942 | 2020-10-17 | https://stackoverflow.com/questions/64406942/in-a-pytest-coverage-report-what-does-mean-for-missing-lines | I'm running pytest with the coverage plugin (pytest --cov) and in the report I got the following line: Name Stmts Miss Branch BrPart Cover Missing --------------------------------------------------------- foo.py 5 1 2 1 71% 3->5, 5 I know that 3-5 would mean it missed lines 3 to 5, but I don't know what -> means. From... | Coverage collects pairs of transition in your code that goes from one line (the source) to another (the destination). In some cases, some transitions could be jumped, like in conditional statements or a break statememt, then it would be measured as a missing branch (or missing transition). For example, in your code the... | 8 | 7 |
64,406,954 | 2020-10-17 | https://stackoverflow.com/questions/64406954/how-can-i-drop-a-column-if-the-last-row-is-nan | I have found examples of how to remove a column based on all or a threshold but I have not been able to find a solution to my particular problem which is dropping the column if the last row is nan. The reason for this is im using time series data in which the collection of data doesnt all start at the same time which i... | You can also do something like this df.loc[:, ~df.iloc[-1].isna()] A C 0 NaN x 1 1 3 2 x z 3 4 6 | 9 | 5 |
64,401,916 | 2020-10-17 | https://stackoverflow.com/questions/64401916/python-cannot-import-token-from-token | I'm trying to make a lexer in python but when I try to import a class from file token.py I get this error ImportError: cannot import name 'Token' from 'token' the code for token.py is as follows from enum import Enum class Token(): def __init__(self, ttype, value=None): self.type = ttype self.value = value def __repr_... | There is a library in python called token, so your interpreter might be confusing it with the inbuilt python library. Try to rename the library. Name it token_2.py or something | 7 | 13 |
64,385,747 | 2020-10-16 | https://stackoverflow.com/questions/64385747/valueerror-you-are-trying-to-merge-on-object-and-int64-columns-when-use-pandas | The test.csv data likes this: device_id,upload_time,latitude,longitude,mileage,other_vals,speed,upload_time_1 11115304371,2020-08-05 05:10:05+00:00,23.140366,114.18685,0,,0,202008 1234,2020-08-05 05:10:33+00:00,22.994716,114.2998,0,,0,202008 11115304371,2020-08-05 05:20:55+00:00,22.994716,114.2998,0,,3.8,202008 1111530... | When I use this code df.astype(str): import pandas as pd df_device_data = pd.read_csv(r'E:/test.csv', encoding='utf-8', parse_dates=[1], low_memory=False) df_device_data['device_id'] = df_device_data['device_id'].astype(str) df_common_car_info = pd.read_csv(r'E:/info.csv', encoding='utf-8', low_memory=False) df_common_... | 12 | 7 |
64,395,136 | 2020-10-16 | https://stackoverflow.com/questions/64395136/typeerror-object-of-type-uuid-is-not-json-serializable | I'm building a fairly large JSON dictionary where I specify a few uuids like this: import uuid game['uuid'] = uuid.uuid1() I'm getting a type error with the following traceback. I'm not sure what the issue is because we can have UUIDs within json objects Traceback (most recent call last): File "/Users/claycrosby/Deskt... | The uuid.UUID class itself can't be JSON serialized, but the object can be expressed in several JSON compatible formats. From help(uuid.UUID) we can see these options (though bytes would need some more work because they aren't json either). | bytes the UUID as a 16-byte string (containing the six | integer fields in b... | 5 | 7 |
64,390,560 | 2020-10-16 | https://stackoverflow.com/questions/64390560/error-could-not-find-a-version-that-satisfies-the-requirement-csv-from-version | I'm trying to install the csv module in Python 3. I have pip install, and I'm using Pycharm. I've tried downloading it in the terminal using both pip install csv and pip3 install csv, but neither of those worked. I get the following error: ERROR: Could not find a version that satisfies the requirement csv (from version... | You can't install the csv module because it is already part of Python, so you can just start to use it by including in your file: import csv . | 6 | 10 |
64,382,010 | 2020-10-16 | https://stackoverflow.com/questions/64382010/how-to-create-a-seaborn-heatmap-by-hour-day-from-timestamp-with-multiple-data-po | I have a data frame with a date column which is a timestamp. There are multiple data points per hour of a day eg 2014-1-1 13:10, 2014-1-1 13:20 etc. I want to group the data points from the same hour of a specific day and then create a heatmap using seaborn and plot a different column. I have tried to use groupby but I... | You can use dt.strftime('%H') to get the hours, and dt.strftime('%Y-%m-%D') or dt.normalize() for the days sns.heatmap(df.groupby([df.date.dt.normalize(), df.date.dt.strftime('%H:00')]) ['data'].mean() .rename_axis(index=['day','hour']) .unstack(level=0) ) Output: Update: for the weeks, we can use a similar approach... | 6 | 5 |
64,374,482 | 2020-10-15 | https://stackoverflow.com/questions/64374482/how-to-calculate-distance-for-every-row-in-a-pandas-dataframe-from-a-single-poin | I have a point point = np.array([0.07852388, 0.60007135, 0.92925712, 0.62700219, 0.16943809, 0.34235233]) And a pandas dataframe a b c d e f 0 0.025641 0.554686 0.988809 0.176905 0.050028 0.333333 1 0.027151 0.520914 0.985590 0.409572 0.163980 0.424242 2 0.028788 0.478810 0.970480 0.288557 0.095053 0.939394 3 0.01869... | You can compute vectorized Euclidean distance (L2 norm) using the formula sqrt((a1 - b1)2 + (a2 - b2)2 + ...) df.sub(point, axis=1).pow(2).sum(axis=1).pow(.5) 0 0.474690 1 0.257080 2 0.703857 3 0.503596 4 0.461151 dtype: float64 Which gives the same output as your current code. Or, using linalg.norm: np.linalg.norm... | 18 | 11 |
64,370,230 | 2020-10-15 | https://stackoverflow.com/questions/64370230/deleting-rows-which-sum-to-zero-in-1-column-but-are-otherwise-duplicates-in-pand | I have a pandas dataframe of the following structure: df = pd.DataFrame({'ID':['A001', 'A001', 'A001', 'A002', 'A002', 'A003', 'A003', 'A004', 'A004', 'A004', 'A005', 'A005'], 'Val1':[2, 2, 2, 5, 6, 8, 8, 3, 3, 3, 7, 7], 'Val2':[100, -100, 50, -40, 40, 60, -50, 10, -10, 10, 15, 15]}) ID Val1 Val2 0 A001 2 100 1 A001 ... | I put some comments in the code, so hopefully, my line of thought should be clear : cond = df.assign(temp=df.Val2.abs()) # a way to get the same values (differentiated by their sign) # to follow each other cond = cond.sort_values(["ID", "Val1", "temp"]) # cumsum should yield a zero for numbers that are different # only... | 8 | 2 |
64,369,710 | 2020-10-15 | https://stackoverflow.com/questions/64369710/what-are-the-hex-codes-of-matplotlib-tab10-palette | Do you know what are the hex codes or RGB values of the "tab" palette (the default 10 colors: tab:blue, tab:orange, etc...) of matplotlib ? And possibly do you know how if there's a way to obtain the hex code for any named color in matplotlib ? | Turns out this piece of code from the matplotlib examples gave me the answer I was after. The hex codes of the "tableau" palette are as follows: tab:blue : #1f77b4 tab:orange : #ff7f0e tab:green : #2ca02c tab:red : #d62728 tab:purple : #9467bd tab:brown : #8c564b tab:pink : #e377c2 tab:gray : #7f7f7f tab:olive : #bcbd2... | 31 | 57 |
64,364,499 | 2020-10-15 | https://stackoverflow.com/questions/64364499/set-description-for-query-parameter-in-swagger-doc-using-pydantic-model-fastapi | This is continue to this question. I have added a model to get query params to pydantic model class QueryParams(BaseModel): x: str = Field(description="query x") y: str = Field(description="query y") z: str = Field(description="query z") @app.get("/test-query-url/{test_id}") async def get_by_query(test_id: int, query_p... | This is not possible with Pydantic models The workaround to get the desired result is to have a custom dependency class (or function) rather than the Pydantic model from fastapi import Depends, FastAPI, Query app = FastAPI() class CustomQueryParams: def __init__( self, foo: str = Query(..., description="Cool Descriptio... | 28 | 25 |
64,362,032 | 2020-10-14 | https://stackoverflow.com/questions/64362032/how-to-melt-a-dataframe-while-doing-some-operation | Let's say that I have the following dataframe: index K1 K2 D1 D2 D3 N1 0 1 12 4 6 N2 1 1 10 2 7 N3 0 0 3 5 8 Basically, I want to transform this dataframe into the following: index COL1 COL2 K1 D1 = 0*12+1*10+0*3 K1 D2 = 0*4+1*2+0*5 K1 D3 = 0*6+1*7+0*8 K2 D1 = 1*12+1*10+0*3 K2 D2 = 1*4+1*2+0*5 K2 D3 = 1*6+1*7+0*8 The... | This is matrix multiplication: (df[['D1','D2','D3']].T@df[['K1','K2']]).unstack().reset_index() Output: level_0 level_1 0 0 K1 D1 10 1 K1 D2 2 2 K1 D3 7 3 K2 D1 22 4 K2 D2 6 5 K2 D3 13 | 5 | 7 |
64,362,290 | 2020-10-14 | https://stackoverflow.com/questions/64362290/python-struct-pack-and-unpack | I want to reverse the packing of the following code: struct.pack("<"+"I"*elements, *self.buf[:elements]) I know "<" means little endian and "I" is unsigned int. How can I use struct.unpack to reverse the packing? | struct.pack takes non-byte values (e.g. integers, strings, etc.) and converts them to bytes. And conversely, struct.unpack takes bytes and converts them to their 'higher-order' equivalents. For example: >>> from struct import pack, unpack >>> packed = pack('hhl', 1, 2, 3) >>> packed b'\x00\x01\x00\x02\x00\x00\x00\x03' ... | 9 | 15 |
64,362,044 | 2020-10-14 | https://stackoverflow.com/questions/64362044/what-does-levels-mean-in-seaborn-kde-plot | I am trying to make a contour plot of my 2d data. However, I would like to input the contours manually. I found the "levels" option in seaborn.kde documentation, where I can define the levels for contours manually. However, I have no idea what these levels mean. The documentation gives this definition - Levels corresp... | Basically, the contour line for the level corresponding to 0.05 is drawn such that 5% of the distribution lies "below" it. Alternately, because the integral over the full density equals 1 (that's what makes it a PDF), the integral over the area outside of the contour line will be 0.05. | 10 | 3 |
64,359,016 | 2020-10-14 | https://stackoverflow.com/questions/64359016/how-can-i-remove-numbers-and-words-with-length-below-2-from-a-sentence | I am trying to remove words that have length below 2 and any word that is numbers. For example s = " This is a test 1212 test2" Output desired is " This is test test2" I tried \w{2,} this removes all the word whose length is below 2. When I added \D+ this removes all numbers when I didn't want to get rid of 2 from t... | You may use: s = re.sub(r'\b(?:\d+|\w)\b\s*', '', s) RegEx Demo Pattern Details: \b: Match word boundary (?:\d+|\w): Match a single word character or 1+ digits \b: Match word boundary \s*: Match 0 or more whitespaces | 6 | 3 |
64,345,790 | 2020-10-14 | https://stackoverflow.com/questions/64345790/sort-a-pandas-dataframe-by-multiple-columns-using-key-argument | I have a dataframe a pandas dataframe with the following columns: df = pd.DataFrame([ ['A2', 2], ['B1', 1], ['A1', 2], ['A2', 1], ['B1', 2], ['A1', 1]], columns=['one','two']) Which I am hoping to sort primarily by column 'two', then by column 'one'. For the secondary sort, I would like to use a custom sorting rule th... | You can split column one into its constituent parts, add them as columns to the dataframe and then sort on them with column two. Finally, remove the temporary columns. >>> (df.assign(lhs=df['one'].str[0], rhs=df['one'].str[1:].astype(int)) .sort_values(['two', 'rhs', 'lhs']) .drop(columns=['lhs', 'rhs'])) one two 5 A1 ... | 10 | 3 |
64,348,644 | 2020-10-14 | https://stackoverflow.com/questions/64348644/set-default-logging-extra-for-pythons-logger-object | In built-in python's logging module you create a logger and log messages: import logging log = logging.getLogger('mylogger') log.info('starting!') You can also pass extras to the log message that will be used later by the formatter: user = 'john doe' log.info('starting!', extra={'user': 'john doe'}) However it's quit... | The builtin way to do this is using a logging adapter. A filter would also work but for your described use-case adapters are perfect. import logging logging.basicConfig(level=logging.DEBUG, format='user: %(user)s - message: %(msg)s') logger = logging.getLogger() logger_with_user = logging.LoggerAdapter(logger, {'user':... | 10 | 20 |
64,347,217 | 2020-10-14 | https://stackoverflow.com/questions/64347217/error-pickle-picklingerror-cant-pickle-function-lambda-at-0x0000002f2175b | I am trying to run following code that reported running well with other users, but I found this error. -- coding: utf-8 -- Import the Stuff import torch import torch.nn as nn import torch.optim as optim from torch.utils import data from torch.utils.data import DataLoader import torchvision.transforms as transforms impo... | pickle doesn't pickle function objects. It expects to find the function object by importing its module and looking up its name. lambdas are anonymous functions (no name) so that doesn't work. The solution is to name the function at module level. The only lambda I found in your code is transformations = transforms.Compo... | 9 | 8 |
64,291,076 | 2020-10-10 | https://stackoverflow.com/questions/64291076/generating-all-permutations-efficiently | I need to generate as fast as possible all permutations of integers 0, 1, 2, ..., n - 1 and have result as a NumPy array of shape (factorial(n), n), or to iterate through large portions of such an array to conserve memory. Is there some built-in function in NumPy for doing this? Or some combination of functions. Using ... | Here's a NumPy solution that builds the permutations of size m by modifying the permutations of size m-1 (see more explanation further down): from math import factorial def permutations(n): a = np.zeros((factorial(n), n), np.uint8) f = 1 for m in range(2, n+1): b = a[:f, n-m+1:] # the block of permutations of range(m-1... | 13 | 12 |
64,314,141 | 2020-10-12 | https://stackoverflow.com/questions/64314141/psycopg2-importerror-dll-load-failed-while-importing-psycopg-the-operating | I installed psycopg2 using conda on Windows 10. https://anaconda.org/anaconda/psycopg2 I did it in a clean new conda environment (named wr). I then tried to run this sample app but I am getting this error (see below). I have no idea what I might be doing wrong because it was all straightforward and I did it in a clean ... | You can use psycopg2-binary library instead of psycopg2. After installation the usage is the same. psycopg2 requires some dll file to be installed on your operating system. You can either install it manually or you can install psycopg2-binary instead which packs both the library and dll files together. The documentatio... | 20 | 18 |
64,282,629 | 2020-10-9 | https://stackoverflow.com/questions/64282629/why-does-module-file-return-none | I've added a local directory to my system path. When I import it, it's fine but when I do import local_repo print(local_repo.__file__) it returns None. How do I get it to return the path... P.S. When I try this with other modules works fine - returns the path - for example import pathlib print(pathlib.__file__) >>>> "... | __file__ is None because there is no file for your package. You've made a namespace package, and those aren't even supposed to correspond to a specific directory, let alone a file - they're designed for a very specialized use case that doesn't match what you're doing. If you want a regular package, with a non-None __fi... | 7 | 7 |
64,255,154 | 2020-10-8 | https://stackoverflow.com/questions/64255154/change-tf-contrib-layers-xavier-initializer-to-2-0-0 | how can I change tf.contrib.layers.xavier_initializer() to tf version >= 2.0.0 ?? all codes: W1 = tf.get_variable("W1", shape=[self.input_size, h_size], initializer=tf.contrib.layers.xavier_initializer()) | the TF2 replacement for tf.contrib.layers.xavier_initializer() is tf.keras.initializers.glorot_normal(Xavier and Glorot are 2 names for the same initializer algorithm, referring to one researcher named Xavier Glorot) documentation link. if dtype is important for some compatibility reasons - use tf.compat.v1.keras.initi... | 9 | 9 |
64,252,764 | 2020-10-7 | https://stackoverflow.com/questions/64252764/sql-case-when-x-like-t-in-python-script-resulting-in-typeerror-dict-is-not | I am attempting to run a SQL query against a Redshift DB in a Python script. The following results in an error "TypeError: dict is not a sequence" and I cannot figure out why. test1 = """ WITH A AS ( SELECT *, CASE WHEN substring(text_value, 0, 4) LIKE ' ' THEN substring(substring(text_value, 0, 4), 3) ELSE substring(t... | you need to escape % character using %% in Python. % is used for string formatting in Python. Not a solution to this problem but it's worth mentioning here that in Python 3.6 and later, there is a more recommended way of string formatting using f-strings. For example: name = 'eshirvana' message = f"I am {name}" print(m... | 17 | 41 |
64,303,607 | 2020-10-11 | https://stackoverflow.com/questions/64303607/python-asyncio-how-to-read-stdin-and-write-to-stdout | I have a need to async read StdIn in order to get messages (json terminated by \r\n) and after processing async write updated message to StdOut. At the moment I am doing it synchronous like: class SyncIOStdInOut(): def write(self, payload: str): sys.stdout.write(payload) sys.stdout.write('\r\n') sys.stdout.flush() def ... | Here's an example of echo stdin to stdout using asyncio streams (for Unix). import asyncio import sys async def connect_stdin_stdout(): loop = asyncio.get_event_loop() reader = asyncio.StreamReader() protocol = asyncio.StreamReaderProtocol(reader) await loop.connect_read_pipe(lambda: protocol, sys.stdin) w_transport, w... | 20 | 29 |
64,280,161 | 2020-10-9 | https://stackoverflow.com/questions/64280161/importing-python-files-in-docker-container | When running my docker image, I get an import error: File "./app/main.py", line 8, in <module> import wekinator ModuleNotFoundError: No module named 'wekinator'` How do I import local python modules in Docker? Wouldn't the COPY command copy the entire "app" folder (including both files), hence preserving the correct i... | Setting the PYTHONPATH as such works but feels clumsy: ENV PYTHONPATH "${PYTHONPATH}:/app/" Using Docker's WORKDIR allows for a much cleaner solution: FROM python:3.7 WORKDIR /code RUN pip install fastapi uvicorn python-osc EXPOSE 80 COPY app ./app CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"] ... | 7 | 3 |
64,236,463 | 2020-10-7 | https://stackoverflow.com/questions/64236463/jupyter-notebook-installation-error-building-wheel-for-argon2-cffi-pep-517 | Building wheels for collected packages: argon2-cffi Building wheel for argon2-cffi (PEP 517) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\prasa\appdata\local\programs\python\python39\python.exe' 'c:\users\prasa\appdata\local\programs\python\python39\lib\site-packages\pip\_vendor\pep517\_i... | In case, you are a mac user on Intel CPUs, just check your pip version, if you are installing through the command : pip install notebook Upgrade your PIP, the command that worked for me: /Library/Developer/CommandLineTools/usr/bin/python3 -m pip install --upgrade pip Check if its the latest version of PIP , by using ... | 21 | 18 |
64,241,264 | 2020-10-7 | https://stackoverflow.com/questions/64241264/i-have-a-high-performant-function-written-in-julia-how-can-i-use-it-from-python | I have a found a Julia function that nicely does the job I need. How can I quickly integrate it to be able to call it from Python? Suppose the function is f(x,y) = 2x.+y What is the best and most elegent way to use it from Python? | Assuming your Python and Julia are installed you need to take the following steps. Run Julia and install PyCall using Pkg pkg"add PyCall" Put your code into a Julia package using Pkg Pkg.generate("MyPackage") In the folder src you will find MyPackage.jl, edit it to look like this: module MyPackage f(x,y) = 2x.+y ex... | 38 | 46 |
64,337,087 | 2020-10-13 | https://stackoverflow.com/questions/64337087/typeerror-init-got-an-unexpected-keyword-argument-name-when-loading-a-m | I made a custom layer in keras for reshaping the outputs of a CNN before feeding to ConvLSTM2D layer class TemporalReshape(Layer): def __init__(self,batch_size,num_patches): super(TemporalReshape,self).__init__() self.batch_size = batch_size self.num_patches = num_patches def call(self,inputs): nshape = (self.batch_siz... | Based on the error message only, I would suggest putting **kwargs in __init__. This object will then accept any other keyword argument that you haven't included. def __init__(self, batch_size, num_patches, **kwargs): super(TemporalReshape, self).__init__(**kwargs) # <--- must, thanks https://stackoverflow.com/users/349... | 14 | 21 |
64,306,147 | 2020-10-11 | https://stackoverflow.com/questions/64306147/using-playwright-for-python-how-do-i-select-an-option-from-a-drop-down-list | This is a followup to this question on the basic functionality of Playwright for Python. How do I select an option from a drop down list? This example remote controls a vuejs-webseite that has a drop down list of fruits like "Apple", "Banana", "Carrot", "Orange" Here I want to select the option "Banana" from playwright... | After trying many different variants, I guessed a working syntax handle.selectOption({"label": "Banana"}) | 9 | 6 |
64,268,575 | 2020-10-8 | https://stackoverflow.com/questions/64268575/how-can-i-import-the-first-and-only-dict-out-of-a-top-level-array-in-a-json-file | I'm working with a json file in Python and I wanted to convert it into a dict. This is what my file looks like: [ { "label": "Label", "path": "/label-path", "image": "icon.svg", "subcategories": [ { "title": "Main Title", "categories": { "column1": [ { "label": "Label Title", "path": "/Desktop/Folder" } ] } } ] } ] So... | Your data get's imported as list, because in your JSON file the main structure is an Array (squared brackets), which is comparable to a list in Python. If you want just inner dict you can do data = json.load(f)[0] | 18 | 18 |
64,324,688 | 2020-10-12 | https://stackoverflow.com/questions/64324688/how-can-i-get-the-tag-name-in-selenium-python | Is there a way to get the name of the tag of a Selenium web element? I found, there is .getTagName() in selenium for Java, in How do I get a parent HTML Tag with Selenium WebDriver using Java?. Example: In this HTML, if I iterate though class='some_class_name', how can I get the tag_name (h2, p, ul or li)? <div class='... | In Python, you have tag_name to get the tag name. content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*") for c in content: print(c.tag_name) | 9 | 18 |
64,268,081 | 2020-10-8 | https://stackoverflow.com/questions/64268081/creating-a-subplot-of-images-with-plotly | I wanted to display the first 10 images from the mnist dataset with plotly. This is turning out to be more complicated than I thought. This does not work: import numpy as np np.random.seed(123) import plotly.express as px from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() fig = su... | Using facets Please consider the following answer, which is much simpler: import plotly.express as px from keras.datasets import mnist (X_train, y_train), (X_test, y_test) = mnist.load_data() fig = px.imshow(X_train[:10, :, :], binary_string=True, facet_col=0, facet_col_wrap=5) It produces the following output: Using... | 9 | 8 |
64,334,033 | 2020-10-13 | https://stackoverflow.com/questions/64334033/how-to-solve-runtimeerror-cuda-error-invalid-device-ordinal | I'm trying to run this code. I don't know what is wrong with it, but this code is not running. and I don't know how to solve this problem. import cv2 from facial_emotion_recognition import EmotionRecognition emotion_detector = EmotionRecognition(device='gpu', gpu_id=1) camera = cv2.VideoCapture(0) while True: image = c... | Try changing: emotion_detector = EmotionRecognition(device='gpu', gpu_id=1) To: emotion_detector = EmotionRecognition(device='gpu', gpu_id=0) gpu_id is only effective when more than one GPU is detected, you only seem to have one GPU, so it throws an error since you tell the function to get GPU 2 (since we count from ... | 24 | 25 |
64,261,546 | 2020-10-8 | https://stackoverflow.com/questions/64261546/how-to-solve-error-microsoft-visual-c-14-0-or-greater-is-required-when-inst | I'm trying to install a package on Python, but Python is throwing an error on installing packages. I'm getting an error every time I tried to install pip install google-search-api. Here is the error how can I successfully install it? error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Bu... | Go to this link and download Microsoft C++ Build Tools: https://visualstudio.microsoft.com/visual-cpp-build-tools/ Open the installer, then follow the steps. You might have something like this, just download it or resume. If updating above doesn't work then you need to configure or make some updates here. You can mak... | 222 | 330 |
64,312,153 | 2020-10-12 | https://stackoverflow.com/questions/64312153/tf-newaxis-operation-in-tensorflow | x_train = x_train[..., tf.newaxis].astype("float32") x_test = x_test[..., tf.newaxis].astype("float32") Can someone please explain how tf.newaxis works ? I found a brief mention in the documentation https://www.tensorflow.org/api_docs/python/tf/strided_slice but I could not properly understand. | Check this example: a = tf.constant([100]) print(a.shape) ## (1) expanded_1 = tf.expand_dims(a,axis=1) print(expanded_1.shape) ## (1,1) expanded_2 = a[:, tf.newaxis] print(expanded_2.shape) ## (1,1) It is similar to expand_dims() which adds a new axis. If you want to add a new axis at the beginning of the tensor, use ... | 16 | 19 |
64,253,599 | 2020-10-7 | https://stackoverflow.com/questions/64253599/spacy-confusion-about-word-vectors-and-tok2vec | it would be really helpful for me if you would help me understand some underlying concepts about Spacy. I understand some spacy models have some predefined static vectors, for example, for the Spanish models these are the vectors generated by FastText. I also understand that there is a tok2vec layer that generates vect... | Does the NER component also use the static vectors? This is addressed in point 2 and 3 of my answer here. Is the tok2vec layer already trained for pretrained downloaded models, e.g. Spanish? Yes, the full model is trained, and the tok2vec layer is a part of it. If I replace the NER component of a pretrained model,... | 6 | 6 |
64,296,359 | 2020-10-10 | https://stackoverflow.com/questions/64296359/how-can-i-install-pip-for-python2-7-in-ubuntu-20-04 | Is there any way that I can install "pip" for "Python2.7" ? I could install python2.7 by sudo apt install python2-minimal I tried installing pip for this. sudo apt install python-pip / python2-pip / python2.7-pip but none worked. Can anybody have solution for this. | Pip for Python 2 is not included in the Ubuntu 20.04 repositories. Try this guide which suggests to fetch a Python 2.7 compatible get_pip.py and use that to bootstrap pip. curl https://bootstrap.pypa.io/pip/2.7/get-pip.py --output get-pip.py | 35 | 23 |
64,284,698 | 2020-10-9 | https://stackoverflow.com/questions/64284698/export-conda-environment-with-minimized-requirements | The typical command to export a Anaconda environment to a YAML file is: conda env export --name my_env > myenv.yml However, one huge issue is the readbility of this file as it includes hard specifications for all of the libraries and all of their dependencies. Is there a way for Anaconda to export a list of the optimal... | Options from the Conda CLI This is sort of what the --from-history flag is for, but not exactly. Instead of including exact build info for each package, it will include only what are called explicit specifications, i.e., the specifications that a user has explicitly requested via the CLI (e.g., conda install scipy=1.3.... | 32 | 43 |
64,297,272 | 2020-10-10 | https://stackoverflow.com/questions/64297272/best-way-to-convert-ipynb-to-py-in-vscode | I'm looking for a good way to convert .ipynb to .py files in VSCode. So far I've tried: the "Export As" Option built into vscode. Not ideal as it produces the following at the start of the script, as well as "Run Cell", "Run Below", etc. buttons/links: "To add a new cell, type '# %%' To add a new markdown cell, type... | We can add the following settings in "settings.json", the generated python file will not have "Run Cell", "Run Above", "Debug Cell": "jupyter.codeLenses": " ", | 23 | 5 |
64,281,002 | 2020-10-9 | https://stackoverflow.com/questions/64281002/pyinstaller-compiled-uvicorn-server-does-not-start-correctly | When I start the server.exe and it is trying to perform uvicorn.run(), the exception is being thrown: Traceback (most recent call last): File "logging\config.py", line 390, in resolve ModuleNotFoundError: No module named 'uvicorn.logging' The above exception was the direct cause of the following exception: Traceback (m... | I encountered the same problem. And I found it's a job of hiddenimports,It's useful to modify the following lines in xxx.spec: a = Analysis(['xxx.py'], hiddenimports=['uvicorn.logging'], <everything else>) however, there will still be other similar problems. So, I try to add all files of uvicorn,and it works with: hid... | 6 | 8 |
64,331,384 | 2020-10-13 | https://stackoverflow.com/questions/64331384/tuple-object-has-no-attribute-committed-error-while-updating-image-objects | Here I am trying to update each product image of a particular product. But it is not working properly. Here only the image of first object is updating. There is a template where we can update product and product images at once. ProductImage has a ManyToOne relation with Product Model so in the template there can be mul... | First, change input name to be able to identify which ProductImage was updated. <!-- <td><input type="file" name="image"></td> --> <td><input type="file" name="image-{{image.pk}}"></td> Next, iterate the input_name in request.FILES and get the ProductImage PK. Then, lookup the ProductImage p, update the image field an... | 6 | 3 |
64,324,685 | 2020-10-12 | https://stackoverflow.com/questions/64324685/why-my-pca-is-not-invariant-to-rotation-and-axis-swap | I have a voxel (np.array) with size 3x3x3, filled with some values, this setup is essential for me. I want to have rotation-invariant representation of it. For this case, I decided to try PCA representation which is believed to be invariant to orthogonal transformations. another For simplicity, I took some axes swap, b... | Firstly, your pca function is not correct, it should be def pca(x): x -= np.mean(x,axis=0) cov = np.cov(x.T) e_values, e_vectors = np.linalg.eig(cov) order = np.argsort(e_values)[::-1] v = e_vectors[:,order] return x @ v You shouldn't transpose the e_vectors[:,order] because we want each column of the v array is an ei... | 6 | 5 |
64,327,534 | 2020-10-13 | https://stackoverflow.com/questions/64327534/unable-to-connect-to-websocket-server-with-nginx-reverse-proxy | I want to set up a websocket server with a reverse proxy. To do so I create a docker-compose with a simple websocket server in python and a nginx reverse proxy. SETUP: docker-compose.yml: version: '2.4' services: wsserver: restart: always ports: - 8765:8765 build: context: ./server dockerfile: Dockerfile ngproxy: imag... | After some research I finally got what was wrong: I mapped my local nginx configuration to the wrong file on the container. So to fix it a changed the volume in my docker-compose.yml From: volumes: - ./nginx/nginx.conf:/etc/nginx/conf.conf To: volumes: - ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro And also r... | 7 | 5 |
64,344,515 | 2020-10-13 | https://stackoverflow.com/questions/64344515/python-consistent-hash-replacement | As noted by many, Python's hash is not consistent anymore (as of version 3.3), as a random PYTHONHASHSEED is now used by default (to address security concerns, as explained in this excellent answer). However, I have noticed that the hash of some objects are still consistent (as of Python 3.7 anyway): that includes int,... | Short answer to broad question: There are no explicit guarantees made about hashing stability aside from the overall guarantee that x == y requires that hash(x) == hash(y). There is an implication that x and y are both defined in the same run of the program (you can't perform x == y where one of them doesn't exist in t... | 8 | 3 |
64,337,550 | 2020-10-13 | https://stackoverflow.com/questions/64337550/neither-pytorch-nor-tensorflow-2-0-have-been-found-models-wont-be-available | I am trying to install transformers using pip pip install transformers after import transformers this error show Neither PyTorch nor TensorFlow >= 2.0 have been found.Models won't be available and only tokenizers, configuration, and file/data utilities can be used. although I install TensorFlow-GPU= 2.3.1 and using c... | I found the problem after investigate for 10 hours I installed tensorflow by using conda install tensorflow-gpu and transformers by using pip after remove tensorflow-gpu and install it by using pip it works fine | 27 | 8 |
64,297,237 | 2020-10-10 | https://stackoverflow.com/questions/64297237/how-can-i-prevent-or-trap-stopiteration-exception-in-the-yield-calling-function | A generator-returning function (i.e. one with a yield statement in it) in one of our libraries fails some tests due to an unhandled StopIteration exception. For convenience, in this post I'll refer to this function as buggy. I have not been able to find a way for buggy to prevent the exception (without affecting the fu... | You can trap the StopIteration exception in the lexical scope of the buggy function this way: import csv # essential! def buggy(csvfile): with open(csvfile) as stream: reader = csv.reader(stream) try: yield next(reader) except StopIteration: yield 'dummy value' for row in reader: yield row You basically manually reque... | 6 | 5 |
64,329,049 | 2020-10-13 | https://stackoverflow.com/questions/64329049/converting-smiles-to-chemical-name-or-iupac-name-using-rdkit-or-other-python-mod | Is there a way to convert SMILES to either chemical name or IUPAC name using RDKit or other python modules? I couldn't find something very helpful in other posts. Thank you very much! | As far as I am aware this is not possible using rdkit, and I do not know of any python modules with this ability. If you are ok with using a web service you could use the NCI resolver. Here is a naive implementation of a function to retrieve an IUPAC identifier from a SMILES string: import requests CACTUS = "https://ca... | 7 | 5 |
64,336,575 | 2020-10-13 | https://stackoverflow.com/questions/64336575/select-a-file-or-a-folder-in-qfiledialog-pyqt5 | My scrip ist currently using QtWidgets.QFileDialog.getOpenFileNames() to let the user select files within Windows explorer. Now I´m wondering if there is a way to let them select also folders, not just files. There are some similar posts, but none of them provides a working solution. I really dont want to use the QFile... | QFileDialog doesn't allow that natively. The only solution is to create your own instance, do some small "patching". Note that in order to achieve this, you cannot use the native dialogs of your OS, as Qt has almost no control over them; that's the reason of the dialog.DontUseNativeDialog flag, which is mandatory. The ... | 7 | 8 |
64,338,294 | 2020-10-13 | https://stackoverflow.com/questions/64338294/how-to-disable-scientific-notation-in-hvplot-plots | I have just started using hvPlot today, as part of Panel. I am having a difficult time figuring out how to disable scientific notation in my plots. For example here is a simple bar plot. The axis and the tootltip are in scientific notation. How can I change the format to a simple int? I am showing this to non numerica... | You can specify the formatter you would like to use in either x- or y-axis ticks, as such: df.hvplot.bar(height=500,width=1000, yformatter='%.0f') According to the Customization page you also referenced, the xformatter and yformatter arguments can accept "printf formatter, e.g. '%.3f', and bokeh TickFormatter". So, an... | 9 | 14 |
64,259,054 | 2020-10-8 | https://stackoverflow.com/questions/64259054/django-duplicated-logic-between-properties-and-queryset-annotations | When I want to define my business logic, I'm struggling finding the right way to do this, because I often both need a property AND a custom queryset to get the same info. In the end, the logic is duplicated. Let me explain... First, after defining my class, I naturally start writing a simple property for data I need: c... | Based on your different good answers, I decided to stick with annotations and properties. I created a cache mechanism to make it transparent about the naming. The main advantage is to keep the business logic in one place only. The only drawback I see is that an object could be called from database a second time to be a... | 19 | 1 |
64,319,173 | 2020-10-12 | https://stackoverflow.com/questions/64319173/pre-release-versions-are-not-matched-by-pip-when-using-the-pre-option | Imagine you have published two pre-releases: package 0.0.1.dev0 package 0.0.2.dev0 My install_requires section in setup.py states: [ 'package>=0.0.2,<1.0.0' ] Now, when i run pip install . --upgrade --pre I get an error: ERROR: Could not find a version that satisfies the requirement package<1.0.0,>=0.0.2 (from vers... | Summary The pip --pre option directs pip to include potential matching pre-release and development versions, but it does not change the semantics of version matching. Since pre-release 0.0.2.dev0 is older than stable release 0.0.2, pip correctly reports an error when searching for a package that is at least as new as s... | 9 | 7 |
64,323,261 | 2020-10-12 | https://stackoverflow.com/questions/64323261/how-does-fastapis-application-mounting-works | For certain reasons, we have chosen the FastAPI, in order to use it as back-end tier of our multi-module production. One of its attractive features is sub application, that helps us to separate different modules with intention of making it more modular. But we are concerned about some possible deficiencies which are mi... | I think documentation is pretty clear about it. "Mounting" means adding a completely "independent" application. Whatsoever, let's keep going from your example. This is what we got for our subapi's routes. [{"path":route.path} for route in subapi.routes] = [ {'path': '/openapi.json'}, {'path': '/docs'}, {'path': '/doc... | 8 | 13 |
64,323,745 | 2020-10-12 | https://stackoverflow.com/questions/64323745/how-to-find-the-version-of-jupyter-notebook-from-within-the-notebook | I wish to return the version of Jupyter Notebook from within a cell of a notebook. For example, to get the python version, I run: from platform import python_version python_version() or to get the pandas version: pd.__version__ I have tried: notebook.version() ipython.version() jupyter.version() and several other, r... | Paste the following command into your jupyter cell(exclamation symbol means that you need to run shell command, not python) !jupyter --version example output: jupyter core : 4.6.0 jupyter-notebook : 6.0.1 qtconsole : 4.7.5 ipython : 7.8.0 ipykernel : 5.1.3 jupyter client : 5.3.4 jupyter lab : not installed nbconvert :... | 12 | 22 |
64,241,837 | 2020-10-7 | https://stackoverflow.com/questions/64241837/use-python-open-cv-for-segmenting-newspaper-article | I'm using the code below for segmenting the articles from an image of newspaper. def segmenter(image_received): # Process 1: Lines Detection img = image_received gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # convert to binary gray image edges = cv2.Canny(gray, 75, 150) # determine contours lines = cv2.HoughLinesP(edge... | here my pipeline. I think can be optimized. Initialization %matplotlib inline import numpy as np import cv2 from matplotlib import pyplot as plt Load image image_file_name = 'paper.jpg' image = cv2.imread(image_file_name) # gray convertion gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) The first important thing is to... | 12 | 21 |
64,317,360 | 2020-10-12 | https://stackoverflow.com/questions/64317360/how-to-use-memcached-in-django | I've seen all over problems using Memcached in Django projects which is considered to be The fastest, most efficient type of cache supported natively by Django For instances, Why doesn't memcache work in my Django? How to configure Memcache for Django on Google cloud AppEngine? Django doesn't use memcached framework... | This answer explains how to install Memcached on Windows 10 and how to integrate it with Django through a specific client. It was validated using Memcached 1.4.4, Python 2.7 and Django 1.11. In your Django project, under settings.py, add the following code in the bottom of the file SESSIONS_ENGINE='django.contrib.sess... | 9 | 11 |
64,306,938 | 2020-10-11 | https://stackoverflow.com/questions/64306938/how-can-i-generate-three-random-integers-that-satisfy-some-condition | I'm a beginner in programming and I'm looking for a nice idea how to generate three integers that satisfy a condition. Example: We are given n = 30, and we've been asked to generate three integers a, b and c, so that 7*a + 5*b + 3*c = n. I tried to use for loops, but it takes too much time and I have a maximum testing ... | import numpy as np def generate_answer(n: int, low_limit:int, high_limit: int): while True: a = np.random.randint(low_limit, high_limit + 1, 1)[0] b = np.random.randint(low_limit, high_limit + 1, 1)[0] c = (n - 7 * a - 5 * b) / 3.0 if int(c) == c and low_limit <= c <= high_limit: break return a, b, int(c) if __name__ =... | 40 | 36 |
64,309,821 | 2020-10-11 | https://stackoverflow.com/questions/64309821/difference-between-the-lte-and-gte-in-django | I am trying to figure out the difference between the __lte and __gte in Django. The reason being that I am trying to create a function with dates that can work only with a time frame, so I've been researching between Field Lookups Comparison. I've looked up several documentations https://docs.djangoproject.com/en/3.0/r... | The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects.filter(field__gte=5) # field ≥ 5 MyModel.objects.filter(field_... | 10 | 7 |
64,298,298 | 2020-10-10 | https://stackoverflow.com/questions/64298298/type-hinting-callable-with-no-parameters | I want to use type hinting for a function with no parameters from typing import Callable def no_parameters_returns_int() -> int: return 7 def get_int_returns_int(a: int) -> int: return a def call_function(next_method: Callable[[], int]): print(next_method()) call_function(no_parameters_returns_int) # no indication of e... | Is it possible to hint that the passed function receives no arguments? The correct way to type hint a Callable without arguments is stated in: "Fundamental building blocks", PEP 483 Callable[[t1, t2, ..., tn], tr]. A function with positional argument types t1 etc., and return type tr. The argument list may be empty ... | 12 | 9 |
64,277,506 | 2020-10-9 | https://stackoverflow.com/questions/64277506/what-does-the-qq-mean-as-a-pip-install-option | I saw this on a jupyter notebook: !pip install -Uqq fastbook ! runs commands on shell. U stands for upgrade. What do the options qq mean? q stands for quiet. Why are there two q's? Looked up pip install --help. Looked up User guide to no avail. | The option -q of pip give less output. The Option is additive. In other words, you can use it up to 3 times (corresponding to WARNING, ERROR, and CRITICAL logging levels). So: -q means display only the messages with WARNING,ERROR,CRITICAL log levels -qq means display only the messages with ERROR,CRITICAL log levels ... | 15 | 24 |
64,303,839 | 2020-10-11 | https://stackoverflow.com/questions/64303839/how-to-calculate-ndcg-with-binary-relevances-using-sklearn | I'm trying to calculate the NDCG score for binary relevances: from sklearn.metrics import ndcg_score y_true = [0, 1, 0] y_pred = [0, 1, 0] ndcg_score(y_true, y_pred) And getting: ValueError: Only ('multilabel-indicator', 'continuous-multioutput', 'multiclass-multioutput') formats are supported. Got binary instead Is ... | Please try: from sklearn.metrics import ndcg_score y_true = [[0, 1, 0]] y_pred = [[0, 1, 0]] ndcg_score(y_true, y_pred) 1.0 Note the expected shapes in the docs: y_true: ndarray, shape (n_samples, n_labels) y_score: ndarray, shape (n_samples, n_labels) | 9 | 12 |
64,303,326 | 2020-10-11 | https://stackoverflow.com/questions/64303326/using-playwright-for-python-how-do-i-select-or-find-an-element | I'm trying to learn the Python version of Playwright. See here I would like to learn how to locate an element, so that I can do things with it. Like printing the inner HTML, clicking on it and such. The example below loads a page and prints the HTML from playwright import sync_playwright with sync_playwright() as p: br... | You can use the querySelector function, and then call the innerHTML function: handle = page.querySelector(".user-agent") print(handle.innerHTML()) | 10 | 7 |
64,295,425 | 2020-10-10 | https://stackoverflow.com/questions/64295425/how-to-set-different-colors-for-bars-in-a-plotly-waterfall-chart | I have a waterfall chart and I want to set each bar's color separately (blue for the first one, red for the 2nd, 3rd, and 4th one, green for 5th one, and blue for 6th one). All the relative bars in the chart are increasing, and the plotly only allows you to set three colors for increasing, decreasing, and total ones. I... | Problem Ploty waterfall chart bar color customization. As OP mentioned, currently plotly supports customizing bar colors for decreasing, increasing, and totals. Solution In OP's example, to make color of bars (blue, red, red, red, green, blue): set marker color red in increasing attribute set marker color blue in tota... | 6 | 10 |
64,246,437 | 2020-10-7 | https://stackoverflow.com/questions/64246437/how-to-increase-aws-sagemaker-invocation-time-out-while-waiting-for-a-response | I deployed a large 3D model to aws sagemaker. Inference will take 2 minutes or more. I get the following error while calling the predictor from Python: An error occurred (ModelError) when calling the InvokeEndpoint operation: Received server error (0) from model with message "Your invocation timed out while waiting for... | It’s currently not possible to increase timeout—this is an open issue in GitHub. Looking through the issue and similar questions on SO, it seems like you may be able to use batch transforms in conjunction with inference. References https://stackoverflow.com/a/55642675/806876 Sagemaker Python SDK timeout issue: https://... | 12 | 8 |
64,292,938 | 2020-10-10 | https://stackoverflow.com/questions/64292938/how-to-find-indices-of-first-two-elements-in-a-list-that-are-any-of-the-elements | How do I find the indices of the first two elements in a list that are any of the elements in another list? For example: story = ['a', 'b', 'c', 'd', 'b', 'c', 'c'] elementsToCheck = ['a', 'c', 'f', 'h'] In this case, the desired output is a list indices = [0,2] for strings 'a' and 'c'. | story = ['a', 'b', 'c', 'd', 'b', 'c', 'c'] elementsToCheck = ['a', 'c', 'f', 'h'] out = [] for i, v in enumerate(story): if v in elementsToCheck: out.append(i) if len(out) == 2: break print(out) Prints: [0, 2] | 9 | 7 |
64,237,904 | 2020-10-7 | https://stackoverflow.com/questions/64237904/numpy-installation-for-python-ver-3-9 | I'm trying to install NumPy but I'm facing an issue. The python ver I'm using is 3.9 and Windows version is 10. The error is as follows: C:\>pip3 install numpy Collecting numpy Using cached numpy-1.19.2.zip (7.3 MB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing wheel meta... | The numpy package does not yet include binaries for Python 3.9, so pip tries to compile from source. This (of course) requires you to have the appropriate C compiler, as the error message says. That is not straightforward. pip wants Visual C++ 14.2. The only version readily available from Microsoft is Visual C++ 2019, ... | 7 | 5 |
64,269,453 | 2020-10-8 | https://stackoverflow.com/questions/64269453/pandas-replace-duplicates-with-nan-and-keep-row | How do I replace duplicates for each group with NaNs while keeping the rows? I need to keep rows without removing and perhaps keeping the first original value where it shows up first. import pandas as pd from datetime import timedelta df = pd.DataFrame({ 'date': ['2019-01-01 00:00:00','2019-01-01 01:00:00','2019-01-01 ... | I assume you check duplicates on columns value and ID and further check on date of column date df.loc[df.assign(d=df.date.dt.date).duplicated(['value','ID', 'd']), 'value'] = np.nan Out[269]: date value ID 0 2019-01-01 00:00:00 10.0 Jackie 1 2019-01-01 01:00:00 NaN Jackie 2 2019-01-01 02:00:00 NaN Jackie 3 2019-01-01 0... | 7 | 10 |
64,266,229 | 2020-10-8 | https://stackoverflow.com/questions/64266229/fast-way-to-find-length-and-start-index-of-repeated-elements-in-array | I have an array A: import numpy as np A = np.array( [0, 0, 1, 1, 1, 0, 1, 1, 0 ,0, 1, 0] ) The length of consecutive '1s' would be: output: [3, 2, 1] with the corresponding starting indices: idx = [2, 6, 10] The original arrays are huge and I prefer a solution with less for-loop. Edit (Run time): import numpy as np ... | Here is a pedestrian try, solving the problem by programming the problem. We prepend and also append a zero to A, getting a vector ZA, then detect the 1 islands, and the 0 islands coming in alternating manner in the ZA by comparing the shifted versions ZA[1:] and ZA[-1]. (In the constructed arrays we take the even plac... | 11 | 3 |
64,239,799 | 2020-10-7 | https://stackoverflow.com/questions/64239799/werkzeug-disable-bash-colors-when-logging-to-file | In a Flask application, I use a RotatingFileLogger to log werkzeug access logs to a file like shown in this question: file_handler_access_log = RotatingFileHandler("access.log", backupCount=5, encoding='utf-8') formatter = logging.Formatter('%(asctime)s %(module)s %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S... | OK, so what you are hitting is if click: color = click.style if code[0] == "1": # 1xx - Informational msg = color(msg, bold=True) ... self.log("info", '"%s" %s %s', msg, code, size) Source: https://github.com/pallets/werkzeug/blob/ef545f0d0bf28cbad02066b4cb7471bea50a93ee/src/werkzeug/serving.py Not easy to prevent t... | 9 | 4 |
64,261,360 | 2020-10-8 | https://stackoverflow.com/questions/64261360/how-are-pythons-c-and-c-libraries-cross-platform | Many of Python's libraries, e.g. Pandas and Numpy, are actually C or C++ with Python wrappers round them. I have no experience with compiled languages and don't understand how these libraries are cross platform (i.e. run on Mac, Windows, Linux), since my understanding is that C and C++ need to be compiled for a specifi... | As has been pointed out in comments, Python package using C/C++ compiled code require compilation on the target architecture for them to be cross-platform. Under the hood, when you use pip install pandas for example, pip will look for the requested package on PyPI and, if available, it will install the wheel correspond... | 8 | 8 |
64,252,434 | 2020-10-7 | https://stackoverflow.com/questions/64252434/architecture-not-supported-error-when-installing-nltk-with-pip-on-mac | New MacBookPro running Catalina. I have a virtualenv with no additional libraries installed yet. When I try to install nltk with pip3 install nltk, I get the following long error. The gist of it being "Architecture Not Supported". I tried installing with pip3 install -U but got a similar failure. Below is the all of th... | I had the same problem with the default installed python. (pip3 install regex) When using python from brew it worked for me. Try this: brew install python3 /usr/local/bin/pip3 install nltk or with a virtualenv: brew install python3 /usr/local/bin/python3 -m venv venv . venv/bin/activate pip install ntlk | 18 | 13 |
64,258,570 | 2020-10-8 | https://stackoverflow.com/questions/64258570/seaborn-title-error-attributeerror-facetgrid-object-has-no-attribute-set-t | I created a lineplot graph to begin with using the following code: plot = sns.lineplot(data=tips, x="sex", y="tip", ci=50, hue="day", palette="Accent") plot.set_title("Value of Tips Given to Waiters, by Days of the Week and Sex", fontsize=24, pad=30, fontdict={"weight": "bold"}) plot.legend("") I have realised that it... | When you call catplot, it returns a FacetGrid object, so to change the the title and remove legend, you have to use the legend= option inside the function, and also use plot.fig.suptitle() : import seaborn as sns tips = sns.load_dataset("tips") plot = sns.catplot (data=tips, x="day", y="tip", kind='bar', ci=50, hue="se... | 12 | 11 |
64,255,834 | 2020-10-8 | https://stackoverflow.com/questions/64255834/no-definition-found-for-function-vscode-python | I am using VSCode for Python along with the Microsoft for Python extension enabled in VSCode. For Python v3.9.0 I am getting No definition found if I try to seek a function definition. However, I do not get the error if I use my Conda Virtual environment for Python 3.7.0 What might be the problem? | When I used the code you provided and disabled the Python extension, I encountered the same problem as you. Since "Go to Definition" is supported by the corresponding language service extension, it is recommended that you check that the current Python extension is available and confirm that the selected python interpre... | 35 | 18 |
64,248,955 | 2020-10-7 | https://stackoverflow.com/questions/64248955/how-to-register-typing-callable-with-python-singledispatch | Background Suppose I am to implement a simple decorator @notifyme that prints a message when the decorated function is invoked. I would like the decorator to accept one argument to print a customized message; the argument (along with the parentheses surrounding the argument) may be omitted, in which case the default me... | I was unable to use typing.Callable with functools.singledispatch, but I did find a workaround by using a function class reference instead: from functools import singledispatch from typing import Callable function = type(lambda: ()) @singledispatch def notifyme(arg): return NotImplemented @notifyme.register def notifym... | 9 | 3 |
64,247,450 | 2020-10-7 | https://stackoverflow.com/questions/64247450/runtime-marshalerror-in-python | I am Getting this error. I am executing code of aws lambda function using python 3.7 to know quicksight dashboard version. Thanks in advance! errorMessage: "Unable to marshal response: Object of type datetime is not JSON serializable", errorType : "Runtime.MarshalError" Code- import boto3 import time import sys cli... | I quick fix could be: import boto3 import time import sys import json client = boto3.client('quicksight') def lambda_handler(event, context): response = client.list_dashboard_versions(AwsAccountId='11111', DashboardId='2222',MaxResults=10) return json.dumps(response, default=str) | 10 | 15 |
64,250,017 | 2020-10-7 | https://stackoverflow.com/questions/64250017/how-to-aggregate-combining-dataframes-with-pandas-groupby | I have a dataframe df and a column df['table'] such that each item in df['table'] is another dataframe with the same headers/number of columns. I was wondering if there's a way to do a groupby like this: Original dataframe: name table Bob Pandas df1 Joe Pandas df2 Bob Pandas df3 Bob Pandas df4 Emily Pandas df5 After g... | Given 3 dataframes import pandas as pd dfa = pd.DataFrame({'a': [1, 2, 3]}) dfb = pd.DataFrame({'a': ['a', 'b', 'c']}) dfc = pd.DataFrame({'a': ['pie', 'steak', 'milk']}) Given another dataframe, with dataframes in the columns df = pd.DataFrame({'name': ['Bob', 'Joe', 'Bob', 'Bob', 'Emily'], 'table': [dfa, dfa, df... | 7 | 1 |
64,246,528 | 2020-10-7 | https://stackoverflow.com/questions/64246528/add-missing-rows-based-on-column | I have given the following df df = pd.DataFrame(data = {'day': [1, 1, 1, 2, 2, 3], 'pos': 2*[1, 14, 18], 'value': 2*[1, 2, 3]} df day pos value 0 1 1 1 1 1 14 2 2 1 18 3 3 2 1 1 4 2 14 2 5 3 18 3 and i want to fill in rows such that every day has every possible value of column 'pos' desired result: day pos value 0 ... | Let's try pivot then stack: df.pivot('day','pos','value').stack(dropna=False).reset_index(name='value') Output: day pos value 0 1 1 1.0 1 1 14 2.0 2 1 18 3.0 3 2 1 1.0 4 2 14 2.0 5 2 18 NaN 6 3 1 NaN 7 3 14 NaN 8 3 18 3.0 Option 2: merge with MultiIndex: df.merge(pd.DataFrame(index=pd.MultiIndex.from_product([df['d... | 6 | 4 |
64,246,026 | 2020-10-7 | https://stackoverflow.com/questions/64246026/switching-between-python-virtual-environments | I have some noob level virtual environment questions. I've been using virtual environments a little but still have a few questions. I have created and activated an env which is my main working environment as follows: virtualenv env source /path/to/environment/env/bin/activate Having activated this, I can now see I am ... | Yes you need to run activate command i.e. source each time you open a terminal session. Switching between two virtual environment is easy. You can run deactivate command and source the other virtual environment. | 9 | 10 |
64,246,136 | 2020-10-7 | https://stackoverflow.com/questions/64246136/how-to-access-the-top-element-in-heapq-without-deleting-popping-it-python | How to access the top element in heapq without deleting (popping) it python ? I need only to check the element at the top of my heapq without popping it. How can I do that. | From docs python, under heapq.heappop definition, it says: To access the smallest item without popping it, use heap[0]. It says smallest, because it is a min heap. So the item at the top will be the smallest one. Illustration: import heapq pq = [] heapq.heappush(pq,5) heapq.heappush(pq,3) heapq.heappush(pq,1) heapq.hea... | 10 | 23 |
64,138,325 | 2020-9-30 | https://stackoverflow.com/questions/64138325/python-asyncio-queue-join-finishes-only-when-exception-are-not-raised-why | I've been trying to write an async version of the map function in Python for doing IO. To do that, I'm using a queue with a producer/consumer. At first it seems to be working well, but only without exceptions. In particular, if I use queue.join(), it works well when no exceptions, but blocks in case of exception. If I ... | Problem is, your are NOT catching exceptions. From Python doc The count of unfinished tasks goes up whenever an item is added to the queue. The count goes down whenever a consumer coroutine calls task_done() to indicate that the item was retrieved and all work on it is complete. When the count of unfinished tasks drop... | 8 | 9 |
64,180,511 | 2020-10-3 | https://stackoverflow.com/questions/64180511/pip-change-directory-of-pip-cache-on-linux | I heard changing XDG_CACHE_DIR or XDG_DATA_HOME fixes that but I did export XDG_CACHE_DIR=<new path> export XDG_DATA_HOME=<new path> I've also tried pip cache dir --cache-dir <new path> and pip cache --cache-dir <new path> and --cache-dir <new path> and python --cache-dir <new path> from https://pip.pypa.io/en/sta... | TL;TR;: do not change XDG_CACHE_HOME globally unless you are sure you really want to do that. Changing XDG_CACHE_HOME globally, like some people suggested would not only affect pip but also other apps as well. You simply do not want to mess that deep, because it's simply not necessary in most of the cases. So what are... | 28 | 48 |
64,130,332 | 2020-9-30 | https://stackoverflow.com/questions/64130332/how-to-pass-seaborn-positional-and-keyword-arguments | I want to plot a seaborn regplot. my code: x=data['Healthy life expectancy'] y=data['max_dead'] sns.regplot(x,y) plt.show() However this gives me future warning error. How to fix this warning? FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will ... | Seaborn >= 0.12 With seaborn 0.12, the FutureWarning from seaborn 0.11 is now an TypeError. Only data may be specified as the first positional argument for seaborn plots. All other arguments must use keywords (e.g. x= and y=). This applies to all seaborn plotting functions. sns.*plot(data=penguins, x="bill_length_mm"... | 15 | 36 |
64,199,103 | 2020-10-4 | https://stackoverflow.com/questions/64199103/how-to-display-two-figures-side-by-side-in-a-jupyter-cell | import pandas as pd import seaborn as sns # load data df = sns.load_dataset('penguins', cache=False) sns.scatterplot(data=df, x='bill_length_mm', y='bill_depth_mm', hue='sex') plt.show() sns.scatterplot(data=df, x='flipper_length_mm', y='body_mass_g', hue='sex') plt.show() When I draw two plots with seaborn, in one ce... | Markdown seems to be the easiest option because it does not require loading any additional packages, nor does it require multiple lines of code. This question is about displaying two figures, side by side. Separate figures, side by side, executed from a code cell, does not work. You will need to create separate fig... | 13 | 10 |
64,193,171 | 2020-10-4 | https://stackoverflow.com/questions/64193171/how-to-generate-presigned-s3-urls-using-django-storages | I have a Django form which saves a file to s3 through the django-storages library and works fine. How can I generate and return a pre-signed url so the user can access the file temporarily after it is uploaded ? Is this abstracted by django-storages or do I have to use the boto3 api? I have spent hours going through th... | Turns out you do not need to use boto3 to generate a presigned url. Django-storages abstracts the entire process. You can simply access the url attribute on the FileField, like in this example: document_form = DocumentForm.objects.get(pk=1) url = document_form.docfile.url --- Edit ---- For reference, here is the S3 st... | 17 | 17 |
64,226,700 | 2020-10-6 | https://stackoverflow.com/questions/64226700/download-entire-content-of-a-subfolder-in-a-s3-bucket | I have a bucket in s3 called "sample-data". Inside the Bucket I have folders labelled "A" to "Z". Inside each alphabetical folder there are more files and folders. What is the fastest way to download the alphabetical folder and all it's content? For example --> sample-data/a/foo.txt,more_files/foo1.txt In the above exa... | I think your best bet would be the awscli aws s3 cp --recursive s3://mybucket/your_folder_named_a path/to/your/destination From the docs: --recursive (boolean) Command is performed on all files or objects under the specified directory or prefix. EDIT: However, to do this with boto3 try this: import os import errno i... | 8 | 19 |
64,156,202 | 2020-10-1 | https://stackoverflow.com/questions/64156202/add-dense-layer-on-top-of-huggingface-bert-model | I want to add a dense layer on top of the bare BERT Model transformer outputting raw hidden-states, and then fine tune the resulting model. Specifically, I am using this base model. This is what the model should do: Encode the sentence (a vector with 768 elements for each token of the sentence) Keep only the first vec... | There are two ways to do it: Since you are looking to fine-tune the model for a downstream task similar to classification, you can directly use: BertForSequenceClassification class. Performs fine-tuning of logistic regression layer on the output dimension of 768. Alternatively, you can define a custom module, that crea... | 25 | 38 |
64,229,894 | 2020-10-6 | https://stackoverflow.com/questions/64229894/how-to-fix-numpy-ndarray-object-has-no-attribute-get-figure-when-plotting-su | I have written the following code to plot 6 pie charts in different subplots, but I get an error. This code works correctly if I use it to plot only 2 charts, but produces an an error for anything more than that. I have 6 categorical variables in my dataset, the names of which are stored in the list cat_cols. The chart... | The issue is plt.subplots(2, 3, figsize=(24, 10)) creates two groups of 3 subplots, not one group of six subplots. array([[<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>], [<AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>, <AxesSubplot:xlabel='radians'>]],... | 9 | 20 |
64,234,182 | 2020-10-6 | https://stackoverflow.com/questions/64234182/error-when-creating-a-pipenv-virtual-environment-with-python-3-7 | My OS is ubuntu 20.04 and my default python is 3.8.2. I'm trying to create a virtual environment with pipenv and python 3.7. The following error occurs when I run pipenv install --python 3.7: Creating a virtualenv for this project… Using /usr/bin/python3.7m (3.7.0) to create virtualenv… ⠋RuntimeError: failed to query /... | Did you install the python3-distutils package ? If not you can install it with : sudo apt-get install python3-distutils If you need it for a python3 version that is not the system default, specify the python 3 version : sudo apt-get install python3.X-distutils example: python3.8-distutils | 14 | 9 |
64,208,678 | 2020-10-5 | https://stackoverflow.com/questions/64208678/hiding-secret-key-in-django-project-on-github-after-uploading-project | I uploaded my django project on github and I have a lot of commits on my project. I don't want to delete my project and reupload it again. what is the easiest way to hide secret key after uploading project to github and after a lot of commits? | In the same directory where manage.py is, create a file whose name is .env, and put inside it: SECRET_KEY = '....your secret key ....' # --- the one indicated in your settings.py, cut an paste it here where SECRET_KEY = '....your secret key ....' is the one indicated in your settings.py. So cut this line from your set... | 16 | 43 |
64,197,754 | 2020-10-4 | https://stackoverflow.com/questions/64197754/how-do-i-rotate-a-pytorch-image-tensor-around-its-center-in-a-way-that-supports | I'd like to randomly rotate an image tensor (B, C, H, W) around it's center (2d rotation I think?). I would like to avoid using NumPy and Kornia, so that I basically only need to import from the torch module. I'm also not using torchvision.transforms, because I need it to be autograd compatible. Essentially I'm trying ... | So the grid generator and the sampler are sub-modules of the Spatial Transformer (JADERBERG, Max, et al.). These sub-modules are not trainable, they let you apply a learnable, as well as non-learnable, spatial transformation. Here I take these two submodules and use them to rotate an image by theta using PyTorch's func... | 8 | 13 |
64,170,759 | 2020-10-2 | https://stackoverflow.com/questions/64170759/pyathena-is-super-slow-compared-to-querying-from-athena | I run a query from AWS Athena console and takes 10s. The same query run from Sagemaker using PyAthena takes 155s. Is PyAthena slowing it down or is the data transfer from Athena to sagemaker so time consuming? What could I do to speed this up? | Just figure out a way of boosting the queries: Before I was trying: import pandas as pd from pyathena import connect conn = connect(s3_staging_dir=STAGIN_DIR, region_name=REGION) pd.read_sql(QUERY, conn) # takes 160s Figured out that using a PandasCursor instead of a connection is way faster import pandas as pd pyathe... | 9 | 20 |
64,187,581 | 2020-10-3 | https://stackoverflow.com/questions/64187581/e-package-python-pip-has-no-installation-candidate | $ sudo apt-get install python-pip Reading package lists... Done Building dependency tree Reading state information... Done Package python-pip is not available, but is referred to by another package. This may mean that the package is missing, has been obsoleted, or is only available from another source However the follo... | If you have python(python2) installed you then you can use following command to install pip(for python2). curl https://bootstrap.pypa.io/pip/2.7/get-pip.py -o get-pip.py python get-pip.py Now you can check for pip2 pip2 --version I hope these will help you | 15 | 45 |
64,235,312 | 2020-10-6 | https://stackoverflow.com/questions/64235312/how-to-implodereverse-of-pandas-explode-based-on-a-column | I have a dataframe df like below NETWORK config_id APPLICABLE_DAYS Case Delivery 0 Grocery 5399 SUN 10 1 1 Grocery 5399 MON 20 2 2 Grocery 5399 TUE 30 3 3 Grocery 5399 WED 40 4 I want to implode( combine Applicable_days from multiple rows into single row like below) and get the average case and delivery per config_id... | If you want the "opposite" of explode, then that means bringing it into a list in Solution #1. You can also join as a string in Solution #2: Use lambda x: x.tolist() for the 'APPLICABLE_DAYS' column within your .agg groupby function: df = (df.groupby(['NETWORK','config_id']) .agg({'APPLICABLE_DAYS': lambda x: x.tolist(... | 46 | 54 |
64,218,755 | 2020-10-6 | https://stackoverflow.com/questions/64218755/getting-error-403-in-google-colab-with-tensorboard-with-firefox | I have a tfevent file already present on my Drive and I have successfully connected it to Google Colab. After searching within the issues of Tensorboard Github, I found that I had to set dom.serviceWorkers.enabled to True which I have done. But on Google Colab after performing the two steps: %load_ext tensorboard %ten... | It seems that Tensorboard needs you to enable third party cookies to run without returning a HTTP 403 (Forbidden) error. I had the same issue using Chrome and fixed it by just allowing everything: You can do the same on Firefox like so: You could also find out which exact cookie is needed and then just allow that one... | 27 | 28 |
64,189,006 | 2020-10-3 | https://stackoverflow.com/questions/64189006/why-is-pipenv-not-picking-up-my-pyenv-versions | My system Python version is 3.8.5, however I use pyenv to manage an additional version, 3.6.0, to mirror the server version my project is deployed to. I previously used virtualenv + virtualenvwrapper to manage my virtual environments, but I've heard great things on pipenv and thought I would give it a go. It's all grea... | pipenv doesn't respect pyenv local and pyenv global (reference) maybe it also doesn't respect pyenv shell I usually do what you did, specify the python like pipenv install --python 3.7 | 10 | 12 |
64,200,512 | 2020-10-4 | https://stackoverflow.com/questions/64200512/tensorflow-evalutaion-and-earlystopping-gives-infinity-overflow-error | I a model as seen in the code below, but when trying to evaluate it or using earlystopping on it it gives me the following error: numdigits = int(np.log10(self.target)) + 1 OverflowError: cannot convert float infinity to integer I must state that without using .EarlyStopping or model.evaluate everything works well. I... | Well it's hard to tell exactly as I can't run code without some_get_data_function() realization but recently I've got same error when mistakenly passed EMPTY array to model.evaluate. Taking into account that @meTchaikovsky comment solved your issue it's certainly due to messed up input arrays. | 8 | 9 |
64,132,842 | 2020-9-30 | https://stackoverflow.com/questions/64132842/resnet50-produces-different-prediction-when-image-loading-and-resizing-is-done-w | I want to use Keras Resnet50 model using OpenCV for reading and resizing the input image. I'm using the same preprocessing code from Keras (with OpenCV I need to convert to RGB since this is the format expected by preprocess_input()). I get slightly different predictions using OpenCV and Keras image loading. I don't un... | # Keras prediction img = image.load_img(img_path, target_size=(224, 224)) # OpenCV prediction imgcv = cv2.imread(img_path) dim = (224, 224) imgcv_resized = cv2.resize(imgcv, dim, interpolation=cv2.INTER_LINEAR) If you look attentively, the interpolation you specify in the case of cv2 is cv2.INTER_LINEAR (bilinear int... | 8 | 6 |
64,227,835 | 2020-10-6 | https://stackoverflow.com/questions/64227835/how-to-build-an-mac-os-app-from-a-python-script-having-a-pyside2-gui | Context: I am developping a simple Python application using a PySide2 GUI. It currently works fine in Windows, Linux and Mac. On Windows, I could use PyInstaller and InnoSetup to build a simple installer. Then I tried to do the same thing on Mac. It soon broke, because the system refused to start the command or the app... | Requirements works with Python 3.8.5 macOS 10.15.7 Catalina uses PySide2 and py2app Problems PySide2 must be added under OPTIONS to the packages list when running the app then still an error occurs: Library not loaded: @rpath/libshiboken2.abi3.5.15.dylib, Reason: image not found Solution The slightly modified setup... | 18 | 14 |
64,159,631 | 2020-10-1 | https://stackoverflow.com/questions/64159631/removing-collected-static-files | I ran collectstatic a few weeks back and I would like to remove most (99.5%) of the collected files so that I do not have to store them when deploying to production. I tried collectstatic --clear but this removed them and then placed the deleted files back afterwards (not sure what the practical point of the command is... | It took an interesting combination of commands and actions to get the job done. After replacing my static folder with a new folder with only my desired contents, the base command of collectstatic --noinput --clear --no-post-process got most of the files to be cleared and not re-copied. However, the js and css files we... | 8 | 9 |
64,158,887 | 2020-10-1 | https://stackoverflow.com/questions/64158887/how-to-see-python-print-statements-from-running-fargate-ecs-task | I have a Fargate ECS container that I use to run a Docker container through tasks in ECS. When the task starts, an sh script is called, runner.sh, #!/bin/sh echo "this line will get logged to ECS..." python3 src/my_python_script.py # however print statements from this Python script are not logged to ECS This in turn s... | Seems to me that there are a couple of things you could be dealing with here. The first is the default buffering behaviour of Python, which could stop the output from showing up. You will need to stop this. You can set the PYTHONUNBUFFERED env var correctly by inserting the following before CMD: ENV PYTHONUNBUFFERED=1 ... | 13 | 7 |
64,214,011 | 2020-10-5 | https://stackoverflow.com/questions/64214011/algorithm-what-set-of-tiles-of-length-n-can-be-used-to-generate-the-most-amount | I'm trying to create a function best_tiles which takes in the number of tiles in your hand and returns the set of tiles that allows you to produce the most number of unique English-valid words, assuming that you can only use each tile once. For example, with the set of tiles in your hand (A, B, C) you can produce the w... | I think this is good enough! Here is a log of my code running under PyPy: 0:00:00.000232 E 0:00:00.001251 ER 0:00:00.048733 EAT 0:00:00.208744 ESAT 0:00:00.087425 ESATL 0:00:00.132049 ESARTP 0:00:00.380296 ESARTOP 0:00:01.409129 ESIARTLP 0:00:03.433526 ESIARNTLP 0:00:10.391252 ESIARNTOLP 0:00:25.651012 ESIARNTOLDP 0:00... | 7 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.