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 |
|---|---|---|---|---|---|---|
61,670,081 | 2020-5-8 | https://stackoverflow.com/questions/61670081/django-secret-key-setting-must-not-be-empty-with-github-workflow | I have a GitHub workflow for Django and when it gets to migrating the database it gives the error django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. the secret key is stored in a .env file and loaded with from dotenv import load_dotenv load_dotenv() from pathlib import Path env_pat... | If you have stored the SECRET_KEY in your system's environment variable, then for GitHub workflow, you can add a dummy environment variable in the YAML file. The settings.py should look like this import os ... SECRET_KEY = os.environ.get('SECRET_KEY') # Or the name by which you stored environment variable ... The step... | 9 | 13 |
61,706,535 | 2020-5-10 | https://stackoverflow.com/questions/61706535/keras-validation-loss-and-accuracy-stuck-at-0 | I am trying to train a simple 2 layer Fully Connected neural net for Binary Classification in Tensorflow keras. I have split my data into Training and Validation sets with a 80-20 split using sklearn's train_test_split(). When I call model.fit(X_train, y_train, validation_data=[X_val, y_val]), it shows 0 validation los... | If you use keras instead of tf.keras everything works fine. With tf.keras, I even tried validation_data = [X_train, y_train], this also gives zero accuracy. Here is a demonstration: model.fit(X_train, y_train, validation_data=[X_train.to_numpy(), y_train.to_numpy()], epochs=10, batch_size=64) Epoch 1/10 8/8 [======... | 26 | 39 |
61,705,858 | 2020-5-10 | https://stackoverflow.com/questions/61705858/keras-unboundlocalerror-local-variable-logs-referenced-before-assignment | I am relatively new to python, and while attempting to train a chatbot I received the error: ‘UnboundLocalError: local variable 'logs' referenced before assignment‘. I used model.fit to train: model.fit(x_train, y_train, epochs=7) And I received the error: UnboundLocalError Traceback (most recent call last) <ipython-i... | This issue looks similar to the problem I had while working with small datasets and it is covered in this thread: #38064. I solved my particular issue setting a smaller batch_size, in my case: batch_size = 2 | 15 | 21 |
61,740,748 | 2020-5-11 | https://stackoverflow.com/questions/61740748/python-dataclass-generate-hash-and-exclude-unsafe-fields | I have this dataclass: from dataclasses import dataclass, field from typing import List @dataclass class Person: name: str dob: str friends: List['Person'] = field(default_factory=list, init=False) name and dob are immutable and friends is mutable. I want to generate a hash of each person object. Can I somehow specify... | Just indicate that the friends field should not be taken in account when comparing instances with __eq__, and pass hash=True to field instances on the desired fields. Then, pass the unsafe_hash=True argument to the dataclass decorator itself - it will work as you intend (mostly): In case of hash, the language restricti... | 8 | 13 |
61,675,812 | 2020-5-8 | https://stackoverflow.com/questions/61675812/from-excel-to-list-of-tuples | I have an Excel (.xlsx) file that has two columns of phrases. For example: John I have a dog Mike I need a cat Nick I go to school I want to import it in Python and to get a list of tuples like: [('John', 'I have a dog'), ('Mike', 'I need a cat'), ('Nick', 'I go to school'), ...] What could I do? | You can read the excel file using pd.read_excel. You need to care about the header is there are some or not. As you said, it returns a dataframe. In my case, I have the following. df = pd.read_excel("data.xlsx") print(df) # name message # 0 John I have a dog # 1 Mike I need a cat # 2 Nick I go to school Then, it's pos... | 10 | 5 |
61,718,126 | 2020-5-10 | https://stackoverflow.com/questions/61718126/how-to-multiply-two-2d-rfft-arrays-fftpack-to-be-compatible-with-numpys-fft | I'm trying to multiply two 2D arrays that were transformed with fftpack_rfft2d() (SciPy's FFTPACK RFFT) and the result is not compatible with what I get from scipy_rfft2d() (SciPy's FFT RFFT). The image below shares the output of the script, which displays: The initialization values of both input arrays; Both arrays a... | Correct functions: import numpy as np from scipy import fftpack as scipy_fftpack from scipy import fft as scipy # FFTPACK RFFT 2D def fftpack_rfft2d(matrix): fftRows = scipy_fftpack.fft(matrix, axis=1) fftCols = scipy_fftpack.fft(fftRows, axis=0) return fftCols # FFTPACK IRFFT 2D def fftpack_irfft2d(matrix): ifftRows =... | 10 | 4 |
61,723,421 | 2020-5-11 | https://stackoverflow.com/questions/61723421/how-python-interpreter-treats-the-position-of-the-function-definition-having-def | Why the first code outputs 51 and the second code outputs 21. I understand the second code should output 21, but the way I understood, the first code should also output 21 (The value of b changed to 20 and then is calling the function f). What am I missing? b = 50 def f(a, b=b): return a + b b = 20 print(f(1)) Output... | Tip for python beginners : If you use IDEs like pycharm - you can put a debugger and see what is happening with the variables. We can get a better understanding of what is going on using the id(b) which gets us the address of the particular object in memory: Return the “identity” of an object. This is an integer which... | 11 | 10 |
61,692,952 | 2020-5-9 | https://stackoverflow.com/questions/61692952/how-to-pass-debug-to-build-ext-when-invoking-setup-py-install | When I execute a command python setup.py install or python setup.py develop it would execute build_ext command as one of the steps. How can I pass --debug option to it as if it was invoked as python setup.py build_ext --debug? UPDATE Here is a setup.py very similar to mine: https://github.com/pybind/cmake_example/blob/... | A. If I am not mistaken, one could achieve that by adding the following to a setup.cfg file alongside the setup.py file: [build_ext] debug = 1 B.1. For more flexibility, I believe it should be possible to be explicit on the command line: $ path/to/pythonX.Y setup.py build_ext --debug install B.2. Also if I understood... | 8 | 13 |
61,754,736 | 2020-5-12 | https://stackoverflow.com/questions/61754736/django-3-model-save-when-providing-a-default-for-the-primary-key | I'm working on upgrading my project from Django 2 to Django 3, I have read their release notes of Django 3 and there is a point that I don't really understand what it will impact to my current project. Here they say: As I understand, if we try to call Model.save(), it would always create a new record instead of updati... | Consider this example. Suppose we have a simple model as CONSTANT = 10 def foo_pk_default(): return CONSTANT class Foo(models.Model): id = models.IntegerField(primary_key=True, default=foo_pk_default) name = models.CharField(max_length=10) The main thing I have done in this example is, I did set a default callable func... | 13 | 15 |
61,756,716 | 2020-5-12 | https://stackoverflow.com/questions/61756716/dataclass-argument-choices-with-a-default-option | I'm making a dataclass with a field for which I'd like there to only be a few possible values. I was thinking something like this: @dataclass class Person: name: str = field(default='Eric', choices=['Eric', 'John', 'Graham', 'Terry']) I know that one solution is to validate arguments in the __post_init__ method but is... | python 3.8 introduced a new type called Literal that can be used here: from dataclasses import dataclass from typing import Literal @dataclass class Person: name: Literal['Eric', 'John', 'Graham', 'Terry'] = 'Eric' Type checkers like mypy have no problems interpreting it correctly, Person('John') gets a pass, and Pers... | 7 | 13 |
61,669,873 | 2020-5-8 | https://stackoverflow.com/questions/61669873/python-venv-env-fails-winerror-2-the-system-cannot-find-the-file-specified | I installed the latest version of Python 3.8.2 on a Windows 10 machine. I previously had Python 3.7, which I uninstalled and confirmed in the System PATH it was no longer referenced. After installing the latest version, I run through CMD as Admin: py -m venv env and I get this error: Error: [WinError 2] The system ca... | I found out that Windows Defender now has a feature that blocks access/changes to system files. It added my documents folder by default, somehow preventing me from creating any folders in CMD despite having Admin Access. I hope this helps someone else!! In short -- you may have to revise or disable your Windows 10 "Ran... | 34 | 26 |
61,693,769 | 2020-5-9 | https://stackoverflow.com/questions/61693769/vs-code-run-debug-configuration-for-a-console-script-in-module-mode | My setup.py has the following console_scripts as entry points: entry_points={ 'console_scripts': ['script=myapp.app:do_something', 'script2=myapp.app:do_something2'], }, with the following structure . ├── myapp │ ├── __init__.py │ ├── app.py │ ├── mod.py │ ├── mod2.py │ └── submodules │ ├── __init__.py │ └── mod3.py ├... | There currently isn't a way to make this work. At minimum you need a separate module per entry point or have a single module that took a command-line argument that then chose which function to call. | 12 | 9 |
61,688,882 | 2020-5-8 | https://stackoverflow.com/questions/61688882/how-is-numpy-stack-different-from-numpy-v-stack-and-h-stack | I understand that numpy hstack stacks column wise and vstack stacks row wise. Then what is the function of numpy stack? | The key difference is in the documentation for np.stack (emphasis mine): Join a sequence of arrays along a new axis. Consider the following arrays: arr1=np.array([[1,2,3],[7,8,9]]) arr2=np.array([[4,5,6],[10,11,12]]) arr3=np.array([['a','b','c'],['d','e','f']]) [[1 2 3] [7 8 9]] [[ 4 5 6] [10 11 12]] [['a' 'b' 'c'] ... | 13 | 14 |
61,758,398 | 2020-5-12 | https://stackoverflow.com/questions/61758398/aws-lambda-unable-to-marshal-response-error | I am trying to setup an AWS lambda that will start an SSM session in my EC2 instance and run a command. For simplicity right now I am just trying to run ls. Here is my lambda function: import json import boto3 def lambda_handler(commands, context): """Runs commands on remote linux instances :param client: a boto/boto3 ... | The error has pretty clear wording, you're just fixating on wrong part. I assume you use the resp object somewhere down the line and that part tries to do something like json.load() or related. datetime.datetime(2020, 5, 12, 19, 34, 36, 349000, tzinfo=tzlocal()) is not JSON serializable This is a common error for peop... | 22 | 6 |
61,754,710 | 2020-5-12 | https://stackoverflow.com/questions/61754710/create-pandas-column-with-the-max-of-two-calculated-values-from-other-columns | I want to create a column with the maximum value between 2 values calculated from other columns of the data frame. import pandas as pd df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]}) df['Max Col'] = max(df['A']*3, df['B']+df['A']) ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item()... | Use np.maximum: df['max'] =np.maximum(df['A']*3, df['B']+df['A']) Output: A B max 0 1 -2 3 1 2 8 10 2 3 1 9 | 8 | 11 |
61,750,811 | 2020-5-12 | https://stackoverflow.com/questions/61750811/dropdown-menu-for-plotly-choropleth-map-plots | I am trying to create choropleth maps. Below is an example that works: df = px.data.gapminder().query("year==2007") fig = go.Figure(data=go.Choropleth( locations=happy['iso'], # Spatial coordinates z = happy['Happiness'].astype(float), # Data to be color-coded colorbar_title = "Happiness Score", )) fig.update_layout( t... | There are two ways to solve this Dash # save this as app.py import pandas as pd import plotly.graph_objs as go import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html # Data df = px.data.gapminder().query("year==2007") df = df.rename(columns=dict(pop="Population", ... | 7 | 9 |
61,746,001 | 2020-5-12 | https://stackoverflow.com/questions/61746001/plotly-how-to-specify-colors-for-a-group-using-go-bar | How to use plotly.graph_objs to plot pandas data in a similar way to plotly.express - specifically to color various data types? The plotly express functionality to group data types based on a value in a pandas column is really useful. Unfortunately I can't use express in my system (as I need to send the graph object to... | You could simply use a dictionary like this: colors = {'A':'steelblue', 'B':'firebrick'} The only challenge lies in grouping the dataframe for each unique type and adding a new trace for each type using a for loop. The code snippet below takes care of that to produce this plot: # imports import pandas as pd import pl... | 9 | 11 |
61,744,288 | 2020-5-12 | https://stackoverflow.com/questions/61744288/assigning-column-names-while-creating-dataframe-results-in-nan-values | I have a list of dict which is being converted to a dataframe. When I attempt to pass the columns argument the output values are all nan. # This code does not result in desired output l = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] pd.DataFrame(l, columns=['c', 'd']) c d 0 NaN NaN 1 NaN NaN # This code does result in desired... | Because if pass list of dictionaries from keys are created new columns names in DataFrame constructor: l = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}] print (pd.DataFrame(l)) a b 0 1 2 1 3 4 If pass columns parameter with some values not exist in keys of dictionaries then are filtered columns from dictonaries and for not exi... | 7 | 10 |
61,638,496 | 2020-5-6 | https://stackoverflow.com/questions/61638496/python-remove-square-brackets-and-extraneous-information-between-them | I'm trying to handle a file, and I need to remove extraneous information in the file; notably, I'm trying to remove brackets [] including text inside and between bracket [] [] blocks, Saying that everything between these blocks including them itself but print everything outside it. Below is my text File with data samp... | with one regex import re with open("smb", "r") as f: txt = f.read() txt = re.sub(r'(\n\[)(.*?)(\[]\n)', '', txt, flags=re.DOTALL) print(txt) regex explanation: (\n\[) find a sequence where there is a linebreak followed by a [ (\[]\n) find a sequence where there are [] followed by a linebreak (.*?) remove everything in... | 12 | 8 |
61,712,618 | 2020-5-10 | https://stackoverflow.com/questions/61712618/why-does-mypy-not-consider-a-class-as-iterable-if-it-has-len-and-getitem | I was playing around with mypy and some basic iteration in Python and wrote the below code base: from typing import Iterator from datetime import date, timedelta class DateIterator: def __init__(self, start_date, end_date): self.start_date = start_date self.end_date = end_date self._total_dates = self._get_all_dates() ... | Mypy -- and PEP 484 type checkers in general -- define an iterable to be any class that defines the __iter__ method. You can see the exact definition of the Iterable type in Typeshed, the collection of type hints for the standard library: https://github.com/python/typeshed/blob/master/stdlib/3/typing.pyi#L146 The reaso... | 9 | 9 |
61,720,708 | 2020-5-11 | https://stackoverflow.com/questions/61720708/how-do-you-save-a-tensorflow-dataset-to-a-file | There are at least two more questions like this on SO but not a single one has been answered. I have a dataset of the form: <TensorSliceDataset shapes: ((512,), (512,), (512,), ()), types: (tf.int32, tf.int32, tf.int32, tf.int32)> and another of the form: <BatchDataset shapes: ((None, 512), (None, 512), (None, 512), (... | TFRecordWriter seems to be the most convenient option, but unfortunately it can only write datasets with a single tensor per element. Here are a couple of workarounds you can use. First, since all your tensors have the same type and similar shape, you can concatenate them all into one, and split them back later on load... | 17 | 10 |
61,734,304 | 2020-5-11 | https://stackoverflow.com/questions/61734304/label-outliers-in-a-boxplot-python | I am analysing extreme weather events. My Dataframe is called df and looks like this: | Date | Qm | |------------|--------------| | 1993-01-01 | 4881.977061 | | 1993-02-01 | 4024.396839 | | 1993-03-01 | 3833.664650 | | 1993-04-01 | 4981.192526 | | 1993-05-01 | 6286.879798 | | 1993-06-01 | 6939.726070 | | 1993-07-01 | 6... | You could iterate through the dataframe and compare each value against the limits for the outliers. Default these limits are 1.5 times the IQR past the low and high quartiles. For each value outside that range, you can plot the year next to it. Feel free to adapt this definition if you would like to display more or les... | 7 | 11 |
61,628,503 | 2020-5-6 | https://stackoverflow.com/questions/61628503/flask-uploads-importerror-cannot-import-name-secure-filename | I want to create a form that allows to send a picture with a description using flask forms. I tried to use this video: https://www.youtube.com/watch?v=Exf8RbgKmhM but I had troubles when launching app.py: ➜ website git:(master) ✗ python3.6 app.py Traceback (most recent call last): File "app.py", line 10, in <module> fr... | In flask_uploads.py Change from werkzeug import secure_filename,FileStorage to from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage | 56 | 159 |
61,723,675 | 2020-5-11 | https://stackoverflow.com/questions/61723675/crop-a-video-in-python | I am wondering to create a function which can crop a video in a certain frame and save it on my disk (OpenCV,moviepy,or something like that) I am specifying my function with parameters as dimension of frame along with source and target name (location) def vid_crop(src,dest,l,t,r,b): # something # goes # here left = 1 #... | Ok I think you want this, import numpy as np import cv2 # Open the video cap = cv2.VideoCapture('vid.mp4') # Initialize frame counter cnt = 0 # Some characteristics from the original video w_frame, h_frame = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps, frames = cap.get(cv2.CAP_PR... | 8 | 14 |
61,720,217 | 2020-5-10 | https://stackoverflow.com/questions/61720217/error-cannot-use-a-string-pattern-on-a-bytes-like-object | Hy am using Python RegEx to show all internet wirless profiles connected to a computer.There is error (TypeError: cannot use a string pattern on a bytes-like object) in my Second last line pls anyone help to identifi my mistake.Thanks My Program import subprocess,re command = "netsh wlan show profile" output = subproce... | Python 3 distinguishes "bytes" and "string" types; this is especially important for Unicode strings, where each character may be more than one byte, depending on the character and the encoding. Regular expressions can work on either, but it has to be consistent — searching for bytes within bytes, or strings within stri... | 12 | 21 |
61,718,947 | 2020-5-10 | https://stackoverflow.com/questions/61718947/when-does-dataloader-shuffle-happen-for-pytorch | I have beening using shuffle option for pytorch dataloader for many times. But I was wondering when this shuffle happens and whether it is performed dynamically during iteration. Take the following code as an example: namesDataset = NamesDataset() namesTrainLoader = DataLoader(namesDataset, batch_size=16, shuffle=True)... | The shuffling happens when the iterator is created. In the case of the for loop, that happens just before the for loop starts. You can create the iterator manually with: # Iterator gets created, the data has been shuffled at this point. data_iterator = iter(namesTrainLoader) By default the data loader uses torch.utils... | 9 | 9 |
61,712,660 | 2020-5-10 | https://stackoverflow.com/questions/61712660/how-to-efficiently-get-the-mean-of-the-elements-in-two-list-of-lists-in-python | I have two lists as follows. mylist1 = [["lemon", 0.1], ["egg", 0.1], ["muffin", 0.3], ["chocolate", 0.5]] mylist2 = [["chocolate", 0.5], ["milk", 0.2], ["carrot", 0.8], ["egg", 0.8]] I want to get the mean of the common elements in the two lists as follows. myoutput = [["chocolate", 0.5], ["egg", 0.45]] My current c... | You can do it in O(n) (single pass over each list) by converting 1 to a dict, then per item in the 2nd list access that dict (in O(1)), like this: mylist1 = [["lemon", 0.1], ["egg", 0.1], ["muffin", 0.3], ["chocolate", 0.5]] mylist2 = [["chocolate", 0.5], ["milk", 0.2], ["carrot", 0.8], ["egg", 0.8]] l1_as_dict = dict(... | 51 | 37 |
61,711,896 | 2020-5-10 | https://stackoverflow.com/questions/61711896/combine-gridsearchcv-and-stackingclassifier | I want to use StackingClassifier to combine some classifiers and then use GridSearchCV to optimize the parameters: clf1 = RandomForestClassifier() clf2 = LogisticRegression() dt = DecisionTreeClassifier() sclf = StackingClassifier(estimators=[clf1, clf2],final_estimator=dt) params = {'randomforestclassifier__n_estimato... | First of all, the estimators need to be a list containing the models in tuples with the corresponding assigned names. estimators = [('model1', model()), # model() named model1 by myself ('model2', model2())] # model2() named model2 by myself Next, you need to use the names as they appear in sclf.get_params(). Also, t... | 9 | 11 |
61,702,357 | 2020-5-9 | https://stackoverflow.com/questions/61702357/how-to-add-a-spacy-model-to-a-requirements-txt-file | I have an app that uses the Spacy model "en_core_web_sm". I have tested the app on my local machine and it works fine. However when I deploy it to Heroku, it gives me this error: "Can't find model 'en_core_web_sm'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory." My requirem... | Ok, so after some more Googling and hunting for a solution, I found this solution that worked: I downloaded the tarball from the url that @tausif shared in his answer, to my local system. Saved it in the directory which had my requirements.txt file. Then I added this line to my requirements.txt file: ./en_core_web_sm-2... | 31 | 7 |
61,686,382 | 2020-5-8 | https://stackoverflow.com/questions/61686382/change-the-text-color-of-cells-in-plotly-table-based-on-value-string | I have the following script that turns a pandas dataframe into an interactive html table with Plotly: goals_output_df = pd.read_csv(os.path.join(question_dir, "data/output.csv")) fig = go.Figure(data=[go.Table( columnwidth = [15,170,15,35,35], header=dict(values=['<b>' + x + '</b>' for x in list(goals_output_df.column... | It's kind of implicit on this section cell-color-based-on-variable. Here what I'll do in your case. Data import pandas as pd import plotly.graph_objects as go df = pd.DataFrame({"name":["a", "b", "c", "d"], "value":[100,20,30,40], "output":["YES", "NO", "BORDERLINE", "NO"]}) map_color = {"YES":"green", "NO":"red", "BOR... | 7 | 17 |
61,698,133 | 2020-5-9 | https://stackoverflow.com/questions/61698133/docker-py-permissionerror13 | While I was running >>> import docker >>> client = docker.from_env() >>> client.containers.list() I encountered the following error requests.exceptions.ConnectionError: ('Connection aborted.', PermissionError(13, 'Permission denied')) I think it is because docker-py is not able to get access of the docker daemon. So ... | According to Docker docs you should create a group and attach your user to that group. Create Group sudo groupadd docker Attach User to Group sudo usermod -aG docker $USER Reload su -s ${USER} | 8 | 12 |
61,697,523 | 2020-5-9 | https://stackoverflow.com/questions/61697523/typeerror-int-argument-must-be-a-string-a-bytes-like-object-or-a-number-not | I am trying to run the simple below snippet port = int(os.getenv('PORT')) print("Starting app on port %d" % port) I can understand the PORT is s string but I need to cast to a int. Why I am getting the error TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' | You don't have an environment variable called PORT. os.getenv('PORT') -> returns None -> throws exception when you try to convert it to int Before running your script, create in your terminal the environment variable by: export PORT=1234 Or, you can provide a default port in case it's not defined as an environment var... | 7 | 9 |
61,694,481 | 2020-5-9 | https://stackoverflow.com/questions/61694481/splitting-a-list-of-tuples-to-several-lists-by-the-same-tuple-items | I am presented with a list made entirely of tuples, such as: lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue"), ("yo", "Green")] How can I split lst into as many lists as there are colours? In this case, 3 lists [("hello", "Blue"), ("hey", "Blue")] [("hi", "Red")] [("yo", "Green")] I just need to be able to wo... | You could use a collections.defaultdict to group by colour: from collections import defaultdict lst = [("hello", "Blue"), ("hi", "Red"), ("hey", "Blue"), ("yo", "Green")] colours = defaultdict(list) for word, colour in lst: colours[colour].append((word, colour)) print(colours) # defaultdict(<class 'list'>, {'Blue': [('... | 11 | 9 |
61,690,632 | 2020-5-9 | https://stackoverflow.com/questions/61690632/why-pandas-dataframe-sumaxis-0-returns-sum-of-values-in-each-column-where-axis | In pandas, axis=0 represent rows and axis=1 represent columns. Therefore to get the sum of values in each row in pandas, df.sum(axis=0) is called. But it returns a sum of values in each columns and vice-versa. Why??? import pandas as pd df=pd.DataFrame({"x":[1,2,3,4,5],"y":[2,4,6,8,10]}) df.sum(axis=0) Dataframe: x ... | I think the right way to interpret the axis parameter is what axis you sum 'over' (or 'across'), rather than the 'direction' the sum is computed in. Specifying axis = 0 computes the sum over the rows, giving you a total for each column; axis = 1 computes the sum across the columns, giving you a total for each row. | 12 | 16 |
61,690,731 | 2020-5-9 | https://stackoverflow.com/questions/61690731/pandas-read-csv-from-bytesio | I have a BytesIO file-like object, containing a CSV. I want to read it into a Pandas dataframe, without writing to disk in between. MWE In my use case I downloaded the file straight into BytesIO. For this MWE I'll have a file on disk, read it into BytesIO, then read that into Pandas. The disk step is just to make a MWE... | The error says the file is empty. That's because after writing to a BytesIO object, the file pointer is at the end of the file, ready to write more. So when Pandas tries to read it, it starts reading after the last byte that was written. So you need to move the pointer back to the start, for Pandas to read. bio.seek(0)... | 12 | 34 |
61,686,780 | 2020-5-8 | https://stackoverflow.com/questions/61686780/python-colorama-print-all-colors | I am new to learning Python, and I came across colorama. As a test project, I wanted to print out all the available colors in colorama. from colorama import Fore from colorama import init as colorama_init colorama_init(autoreset=True) colors = [x for x in dir(Fore) if x[0] != "_"] for color in colors: print(color + f"{... | The reason why it's printing the color name twice is well described in Patrick's comment on the question. Is their a way to access all the Fore Color property so they actualy work as in According to: https://pypi.org/project/colorama/ You can print a colored string using other ways than e.g.print(Fore.RED + 'some red t... | 10 | 10 |
61,669,939 | 2020-5-8 | https://stackoverflow.com/questions/61669939/git-pre-commit-hooks-keeps-modifying-files-even-after-i-have-staged-previously-m | I'm running git pre-commit and running black as one of the hooks. Now when I run commit, black fails and says: All done! ✨ 🍰 ✨ 15 files reformatted, 1 file left unchanged. I reviewed the reformatted files and I'm fine with them. So I stage those files and try running commit again, but I keep getting the same message ... | It appears you're using black and double-quote-strings-fixer together the former likes double quoted strings in python (you can disable this by configuring black to skip-string-normalization in pyproject.toml) the latter likes single quoted strings in python (you can remove it if you'd like double quoted strings) If ... | 13 | 24 |
61,676,156 | 2020-5-8 | https://stackoverflow.com/questions/61676156/how-to-use-the-new-numpy-random-number-generator | The fact that NumPy now recommends that new code uses the default_rng() instance instead of numpy.random for new code has got me thinking about how it should be used to yield good results, both performance vice and statistically. This first example is how I first wanted to write: import numpy as np class fancy_name(): ... | default_rng() isn't a singleton. It makes a new Generator backed by a new instance of the default BitGenerator class. Quoting the docs: Construct a new Generator with the default BitGenerator (PCG64). ... If seed is not a BitGenerator or a Generator, a new BitGenerator is instantiated. This function does not manage a ... | 9 | 9 |
61,644,638 | 2020-5-6 | https://stackoverflow.com/questions/61644638/conda-concurrent-futures-process-brokenprocesspool-a-process-in-the-process-po | I want to install Anaconda on my mac (version 10.9.5). The command I used: sh Anaconda3-2020.02-MacOSX-x86_64.sh Led to this error: Unpacking payload ... Traceback (most recent call last): File "entry_point.py", line 69, in <module> File "concurrent/futures/process.py", line 483, in _chain_from_iterable_of_lists File ... | I have discovered that conda cannot be run on mac v. 10.9.5; i first updated the mac to 10.11, and then from 10.11 to 10.13 (you have to do it in those two steps). Then conda installed and ran fine. | 11 | 0 |
61,631,230 | 2020-5-6 | https://stackoverflow.com/questions/61631230/plotly-how-to-change-the-background-color-of-each-subplot | I am trying to create different subplot and I want for each subplot to have a different background color. I'm using plotly and it makes the thing a little bit more difficult. Any idea? I think the equivalent in matplot is face_color or something like this. fig = make_subplots(rows=1, cols=2) fig.add_trace( go.Scatter( ... | fig.add_trace(go.Scatter(x=[-1,2],y= [2,2],fill='tozeroy'),row=1, col=1) This worked for me. This will draw a line from (-1,2) to (2,2) and will color everything below this points. It can help you color your background of each subplot just by adding in the row and col of subplots. It worked for me, I hope it will work... | 9 | 2 |
61,657,240 | 2020-5-7 | https://stackoverflow.com/questions/61657240/iterating-over-dictionary-using-getitem-in-python | I've implemented a python class to generate data as follows: class Array: def __init__(self): self.arr = [1,2,3,4,5,6,7,8] def __getitem__(self,key): return self.arr[key] a = Array() for i in a: print(i, end = " ") It runs as expected and I get following 1 2 3 4 5 6 7 8 However, I want to do the same thing for dict... | A for loop works with iterators, objects you can pass to next. An object is an iterator if it has a __next__ method. Neither of your classes does, so Python will first pass your object to iter to get an iterator. The first thing iter tries to do is call the object's __iter__ method. Neither of your classes defines __it... | 8 | 9 |
61,659,293 | 2020-5-7 | https://stackoverflow.com/questions/61659293/sums-of-variable-size-chunks-of-a-list-where-sizes-are-given-by-other-list | I would like to make the following sum given two lists: a = [0,1,2,3,4,5,6,7,8,9] b = [2,3,5] The result should be the sum of the every b element of a like: b[0] = 2 so the first sum result should be: sum(a[0:2]) b[1] = 3 so the second sum result should be: sum(a[2:5]) b[2] = 5 so the third sum result should be: sum(... | You can make use of np.bincount with weights: groups = np.repeat(np.arange(len(b)), b) np.bincount(groups, weights=a) Output: array([ 1., 9., 35.]) | 8 | 9 |
61,650,474 | 2020-5-7 | https://stackoverflow.com/questions/61650474/valueerror-columns-must-be-same-length-as-key-in-pandas | i have df below Cost,Reve 0,3 4,0 0,0 10,10 4,8 len(df['Cost']) = 300 len(df['Reve']) = 300 I need to divide df['Cost'] / df['Reve'] Below is my code df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric) I got the error ValueError: Columns must be same length as key df['C/R'] = df[['Cost']].div(df['Reve'].... | Problem is duplicated columns names, verify: #generate duplicates df = pd.concat([df, df], axis=1) print (df) Cost Reve Cost Reve 0 0 3 0 3 1 4 0 4 0 2 0 0 0 0 3 10 10 10 10 4 4 8 4 8 df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric) print (df) # ValueError: Columns must be same length as key You can find... | 7 | 12 |
61,632,584 | 2020-5-6 | https://stackoverflow.com/questions/61632584/understanding-input-shape-to-pytorch-lstm | This seems to be one of the most common questions about LSTMs in PyTorch, but I am still unable to figure out what should be the input shape to PyTorch LSTM. Even after following several posts (1, 2, 3) and trying out the solutions, it doesn't seem to work. Background: I have encoded text sequences (variable length) i... | You have explained the structure of your input, but you haven't made the connection between your input dimensions and the LSTM's expected input dimensions. Let's break down your input (assigning names to the dimensions): batch_size: 12 seq_len: 384 input_size / num_features: 768 That means the input_size of the LSTM ... | 26 | 28 |
61,648,065 | 2020-5-7 | https://stackoverflow.com/questions/61648065/split-list-into-n-sublists-with-approximately-equal-sums | I have a list of integers, and I need to split it into a given number of sublists (with no restrictions on order or the number of elements in each), in a way that minimizes the average difference in sums of each sublist. For example: >>> x = [4, 9, 1, 5] >>> sublist_creator(x, 2) [[9], [4, 1, 5]] because list(map(sum,... | Here's the outline: create N empty lists sort() your input array in ascending order pop() the last element from the sorted array append() the popped element to the list with the lowest sum() of the elements repeat 3 and 4 until input array is empty profit!!! With M=5000 elements and N=30 lists this approach might tak... | 11 | 7 |
61,631,955 | 2020-5-6 | https://stackoverflow.com/questions/61631955/python-requests-ssl-error-during-requests | I'm learning API requests using python requests for personal interest. I'm trying to simply download the URL 'https://live.euronext.com/fr/product/equities/fr0000120578-xpar/'. It works perfectly using postman : Screenshot of postman GET request I'm trying the same request in python using this code : import requests h... | I finally managed to find the issue, thanks to https://github.com/psf/requests/issues/4775 import requests import ssl from urllib3 import poolmanager url = 'https://live.euronext.com/fr/product/equities/FR0000120271-XPAR' class TLSAdapter(requests.adapters.HTTPAdapter): def init_poolmanager(self, connections, maxsize, ... | 13 | 21 |
61,642,034 | 2020-5-6 | https://stackoverflow.com/questions/61642034/displaying-full-content-of-dataframe-cell-without-ellipsis-truncating-the-text | I am trying to display the contents of an Excel file in a Jupyter Notebook. However, a column named definition of the Excel sheet contains long strings. So when I display the DataFrame in the notebook, the long strings are truncated by ellipsis (...). Is there a way to display the complete contents of the column in Ju... | You can use options.display.max_colwidth to specify you want to see more in the default representation: In [2]: df Out[2]: one 0 one 1 two 2 This is very long string very long string very... In [3]: pd.options.display.max_colwidth Out[3]: 50 In [4]: pd.options.display.max_colwidth = 100 In [5]: df Out[5]: one 0 one 1 t... | 11 | 11 |
61,634,759 | 2020-5-6 | https://stackoverflow.com/questions/61634759/python-futurewarning-indexing-with-multiple-keys-implicitly-converted-to-a-tup | I've recently upgraded Python to 3.7.6 and my existing code: df['Simple_Avg_Return'] = df.groupby(['YF_Ticker'])['Share_Price_Delta_Percent', 'Dividend_Percent'].transform( sum).divide(2).round(2) Is now throwing this warning: FutureWarning: Indexing with multiple keys (implicitly converted to a tuple of keys) will b... | You need to use an extra bracket around ['Share_Price_Delta_Percent', 'Dividend_Percent'] Like this, df['Simple_Avg_Return'] = df.groupby(['YF_Ticker'])[['Share_Price_Delta_Percent', 'Dividend_Percent']].transform( sum).divide(2).round(2) Quoting @ALollz comment The decision was made https://github.com/pandas-dev/pan... | 11 | 22 |
61,627,708 | 2020-5-6 | https://stackoverflow.com/questions/61627708/what-does-dictstr-any-mean-in-python | I'm referring to the documentation available here to understand how the return types are defined while using function annotations. I couldn't understand what the str in Dict[str, Any] refers to. Does str refer to the dictionary's keys and Any (meaning, it can be a string or an int) refer to the type of the dictionary's... | Yep! Normally python variables are mutable (types can change), but specifying it like this is good documentation and makes it very clear what goes where. More usage documentation can be found here! https://docs.python.org/3/library/typing.html EDIT: Elaborate on answer on updated question The PEP documentation you ref... | 13 | 11 |
61,620,036 | 2020-5-5 | https://stackoverflow.com/questions/61620036/how-to-run-python3-code-in-vscode-bin-sh-1-python-not-found | I'm trying to run a python file in VSCode using python3. I can run using integrated terminal like it says in the microsoft vscode tutorial on python. However, I would like the program to print in the output tab and not take up the terminal window. However I'm getting this error. The standard code runner config file la... | Solution in 2024 Step1 : Goto settings of Code Runner extension Step2 : Find the section Code-runner: Executor Map And click on Edit in settings.json Step3 : Now change the setting for python Before "code-runner.executorMap": { ... "python": "python -u" ... } Change this to "code-runner.executorMap": { ... "python... | 34 | 52 |
61,505,749 | 2020-4-29 | https://stackoverflow.com/questions/61505749/tensorflowcan-save-best-model-only-with-val-acc-available-skipping | I have an issue with tf.callbacks.ModelChekpoint. As you can see in my log file, the warning comes always before the last iteration where the val_acc is calculated. Therefore, Modelcheckpoint never finds the val_acc Epoch 1/30 1/8 [==>...........................] - ETA: 19s - loss: 1.4174 - accuracy: 0.3000 2/8 [======... | I know how frustrating these things can be sometimes..but tensorflow requires that you explicitly write out the name of metric you are wanting to calculate You will need to actually say 'val_accuracy' metric = 'val_accuracy' ModelCheckpoint(filepath=r"C:\Users\reda.elhail\Desktop\checkpoints\{}".format(Name), monitor=m... | 24 | 23 |
61,564,284 | 2020-5-2 | https://stackoverflow.com/questions/61564284/when-is-string-swapcase-swapcase-not-equal-to-string | Documentation for str.swapcase() method says: Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s. I can't think of an example where s.swapcase().swapcase() != s, can anyone think of one? | A simple example would be: s = "ß" print(s.swapcase().swapcase()) Ouput: ss ß is German lowercase double s (The "correct" uppercase version would be ẞ). The reason this happens is that the Unicode standard has defined the capitalization of ß to be SS: The data in this file, combined with # the simple case mappings... | 7 | 8 |
61,578,899 | 2020-5-3 | https://stackoverflow.com/questions/61578899/disable-black-formatting-of-dict-expression-within-mapping-comprehensions | I'm currently researching Black as our default formatter, but, I'm having some edge cases that don't format well and I want to know if there's a way to get the result I want. Black's documentation partially explores my problem, I have a dictionary expression spread horizontally, and I want to keep it that way since I'm... | It seems that black addressed this issue. At the time of writing this answer, using black version 20.8b1, the formatting is done as I was hoping for. As long as there is a magic trailing comma on the last item in the dictionary expression, black will format the code within the list comprehension. res = [ { "id": item.i... | 16 | 10 |
61,544,854 | 2020-5-1 | https://stackoverflow.com/questions/61544854/from-future-import-annotations | Python doc __future__ In the python docs about __future__ there is a table where it shows that annotations are "optional in" 3.7.0b1 and "mandatory in" 4.0 but I am still able to use annotations in 3.8.2 without importing annotations. Given that, what is the use of it? >>> def add_int(a:int, b:int) -> int: ... return a... | Mandatory is an interesting word choice. I guess it means that it's by default in the language. You don't have to enable it with from __future__ import annotations The annotations feature are referring to the PEP 563: Postponed evaluation of annotations. It's an enhancement to the existing annotations feature which was... | 115 | 167 |
61,606,095 | 2020-5-5 | https://stackoverflow.com/questions/61606095/false-boolean-is-not-showing-in-proto3-python | I'm using protoBuffer 3 in python it is not showing bool fields correctly. entity_proto message Foo { string id = 1; bool active = 3; } Setting values in python. foo = entity_proto.Foo(id='id-123', active=True) print(foo) # id: id-123 # active: True # But if you set the value False it does not show 'active' in print... | Protobuf has default values for fields, such as boolean false, numeric zero, or the empty string. It doesn't bother encoding those since it's a waste of space and/or bandwidth (when transmitting). That's probably why it's not showing up. A good way to check this would be to set id to an empty string and see if it behav... | 13 | 9 |
61,507,845 | 2020-4-29 | https://stackoverflow.com/questions/61507845/model-clean-vs-model-clean-fields | What is the difference between the Model.clean() method and the Model.clean_fields() method?. When should I use one or the other?. According to the Model.clean_fields() method documentation: This method will validate all fields on your model. The optional exclude argument lets you provide a list of field names to exc... | if I want to validate a field, in which of the two methods should I do it? Then you add that normally as validator [Django-doc]: from django.core.exceptions import ValidationError def even_validator(value): if value % 2: ValidationError('The value should be even') class MyModel(models.Model): my_fields = models.Integ... | 8 | 8 |
61,546,201 | 2020-5-1 | https://stackoverflow.com/questions/61546201/python-typehint-int-as-positive | I am curious what would be the best way to specify that a type is not just a int but a positive int in Python. Examples: # As function argument def my_age(age: int) -> str: return f"You are {age} years old." # As class property class User: id: int In both of these situations a negative value would be erroneous. It wou... | Little late to the party but there is now a library called annotated-types that provides exactly what you want and is the 'official' way to go about this, per PEP-593. So for your example of positive integers, you could make use of the built-in typing.Annotated and annotated-types' Gt predicate, like this: from typing ... | 24 | 22 |
61,569,324 | 2020-5-3 | https://stackoverflow.com/questions/61569324/type-annotation-for-callable-that-takes-kwargs | There is a function (f) which consumes a function signature (g) that takes a known first set of arguments and any number of keyword arguments **kwargs. Is there a way to include the **kwargs in the type signature of (g) that is described in (f)? For example: from typing import Callable, Any from functools import wraps ... | tl;dr: Protocol may be the closest feature that's implemented, but it's still not sufficient for what you need. See this issue for details. Full answer: I think the closest feature to what you're asking for is Protocol, which was introduced in Python 3.8 (and backported to older Pythons via typing_extensions). It allo... | 24 | 21 |
61,556,618 | 2020-5-2 | https://stackoverflow.com/questions/61556618/plotly-how-to-display-and-filter-a-dataframe-with-multiple-dropdowns | I'm new to Python, Pandas and Plotly so maybe the answer is easy but I couldn't find anything on the forum or anywhere else … I don’t want to use Dash nor ipywidgets since I want to be able to export in HTML using plotly.offline.plot (I need an interactive HTML file to dynamically control the figure without any server ... | It's certainly possible to display and filter a dataframe with multiple dropdowns. The code snippet below will do exactly that for you. The snippet has quite a few elements in common with your provided code, but I had to build it from scratch to make sure everything harmonized. Run the snippet below, and select A and R... | 10 | 11 |
61,535,744 | 2020-5-1 | https://stackoverflow.com/questions/61535744/return-aggregate-for-all-unique-in-a-group | The trouble is this. Lets say we have a pandas df that can be generated using the following: month=['dec','dec','dec','jan','feb','feb','mar','mar'] category =['a','a','b','b','a','b','b','b'] sales=[1,10,2,5,12,4,3,1] df = pd.DataFrame(list(zip(month,category,sales)), columns =['month', 'cat','sales']) print(df) | mo... | Continuing from where you stopped, a combo of stack and unstack will give you your required output: res = ( df.groupby(['month', 'cat']) .sales.sum() .unstack(fill_value=0) # Unstack and fill value for the null column .stack() # Return to groupby form and reset .reset_index(name='sales') ) The output of res: >>> res m... | 8 | 14 |
61,553,778 | 2020-5-2 | https://stackoverflow.com/questions/61553778/why-is-my-venv-using-a-different-pip-version-than-i-have-installed | I'm setting up virtual env. I was getting warnings about an outdated pip (19.2) so I updated pip on my (macos) system globally, sudo -H python3 -m pip install --upgrade pip. It seems to have worked, but when I make a new venv, I'm still getting the old pip version. % pip --version pip 20.1 from /Library/Frameworks/Pyth... | Pip is installed anew in any freshly created venv. The venv's default pip version is associated with the Python version, and is completely independent from whatever pip version you may have installed on the system. The older version comes from a wheel file bundled with the stdlib ensurepip module. This allows users to ... | 29 | 29 |
61,607,367 | 2020-5-5 | https://stackoverflow.com/questions/61607367/how-to-encrypt-json-in-python | I have a JSON file. I am running a program, in python, where data is extracted from the JSON file. Is there any way to encrypt the JSON file with a key, so that if someone randomly opens the file, it would be a mess of characters, but when the key is fed to the program, it decrypts it and is able to read it? Thanks in ... | Yes, you can encrypt a .json file. Make sure you install the cryptography package by typing pip install cryptography # or on windows: python -m pip install cryptography Then, you can make a program similar to mine: #this imports the cryptography package from cryptography.fernet import Fernet #this generates a key and ... | 9 | 12 |
61,545,680 | 2020-5-1 | https://stackoverflow.com/questions/61545680/postgresql-partition-and-sqlalchemy | SQLAlchemy doc explain how to create a partitioned table. But it does not explains how to create partitions. So if I have this : #Skipping create_engine and metadata Base = declarative_base() class Measure(Base): __tablename__ = 'measures' __table_args__ = { postgresql_partition_by: 'RANGE (log_date)' } city_id = Colum... | Maybe a bit late, but I would like to share what I built upon @moshevi 's and @Seb 's answers: In my IoT use-case, I required actual sub-partitioning (first level year, second level nodeid). Also I wanted to generalize it slightly. This is what I came up with: from sqlalchemy.ext.declarative import DeclarativeMeta from... | 18 | 5 |
61,582,142 | 2020-5-3 | https://stackoverflow.com/questions/61582142/test-pydantic-settings-in-fastapi | Suppose my main.py is like this (this is a simplified example, in my app I use an actual database and I have two different database URIs for development and testing): from fastapi import FastAPI from pydantic import BaseSettings app = FastAPI() class Settings(BaseSettings): ENVIRONMENT: str class Config: env_file = ".e... | PydanticSettings are mutable, so you can simply override them in your test.py: from main import settings settings.ENVIRONMENT = 'test' | 21 | 20 |
61,552,475 | 2020-5-1 | https://stackoverflow.com/questions/61552475/properly-set-up-exponential-decay-of-learning-rate-in-tensorflow | I need to apply an exponential decay of learning rate every 10 epochs. Initial learning rate is 0.000001, and decay factor is 0.95 is this the proper way to set it up? lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=0.000001, decay_steps=(my_steps_per_epoch*10), decay_rate=0.05) opt ... | decay_steps can be used to state after how many steps (processed batches) you will decay the learning rate. I find it quite useful to just specify the initial and the final learning rate and calculate the decay_factor automatically via the following: initial_learning_rate = 0.1 final_learning_rate = 0.0001 learning_rat... | 10 | 10 |
61,582,897 | 2020-5-3 | https://stackoverflow.com/questions/61582897/how-to-serve-a-flutter-web-app-with-django | After building a flutter web app with flutter build web I want to serve the app using a simple Django server. How can I do that? | After running the command, copy the build\web directory from the flutter project to your django project. Let's say you put it at the root and renamed it to flutter_web_app. So we have, djangoproject | djangoproject | settings.py | urls.py | ... | flutter_web_app | ... | other apps Now edit the base tag in flutter_web_... | 9 | 14 |
61,494,958 | 2020-4-29 | https://stackoverflow.com/questions/61494958/postgres-on-conflict-do-update-only-non-null-values-in-python | I have a table for which when processing records I get either the full record, else only the columns to be updated. I want to write a query to handle updates but only update the columns with non null values. For example, Existing table: 1 | John Doe | USA 2 | Jane Doe | UK Incoming records: (3, Kate Bill, Canada) (2,... | In the on conflict (pay particular attention to the do update set name = expression) you can use coalesce with the excluded values to update columns to the specified values (if not null), or the existing values (if specified is null); This would be that format: -- setup create table test1(id integer primary key, col1 t... | 9 | 13 |
61,547,620 | 2020-5-1 | https://stackoverflow.com/questions/61547620/import-error-no-module-named-secrets-python-manage-py-not-working-after-pul | I'm following along a course - Django development to deployment. After pulling it to Digital Ocean everything else ran smoothly. Until I tried running python manage.py help (env) djangoadmin@ubuntu-1:~/pyapps/btre_project_4$ python manage.py help and I get this error. Traceback (most recent call last): File "manage.p... | The secrets module was added to Python in version 3.6. Your host is using Python 3.5, hence the secrets module is unavailable. You need a host with Python 3.6+, or a version of Django that doesn't depend on the secrets module | 8 | 9 |
61,573,928 | 2020-5-3 | https://stackoverflow.com/questions/61573928/using-ipython-display-audio-to-play-audio-in-jupyter-notebook-not-working-when-u | When using the code below the sound plays: import IPython.display as ipd import numpy sr = 22050 # sample rate T = 0.5 # seconds t = numpy.linspace(0, T, int(T*sr), endpoint=False) # time variable x = 0.5*numpy.sin(2*numpy.pi*440*t) # pure sine wave at 440 Hz ipd.Audio(x, rate=sr, autoplay=True) # load a NumPy array B... | I was having this same problem, the sound was played when I called: from IPython.display import Audio Audio('/path/beep.mp3', autoplay=True) But it didn't work when it was inside a function. The problem is that the function call doesn't really play the sound, it's actually played by the resulting HTML that is returned... | 15 | 34 |
61,497,145 | 2020-4-29 | https://stackoverflow.com/questions/61497145/pydantic-model-for-array-of-jsons | I am using FastAPI to write a web service. It is good and fast. FastAPI is using pydantic models to validate input and output data, everything is good but when I want to declare a nested model for array of jsons like below: [ { "name": "name1", "family": "family1" }, { "name": "name2", "family": "family2" } ] I get em... | Update (26/09/2020) In Python 3.9 (not yet released), you can do the same as below but with the built-in list generic type (which is always in scope) rather than needing to import the capitalized List type from typing, e.g. @app.get("/tests", response_model=list[Test]) The issue here is that you are trying to create ... | 13 | 16 |
61,561,112 | 2020-5-2 | https://stackoverflow.com/questions/61561112/how-to-solve-getting-default-adapter-failed-error-when-launching-chrome-and-tr | I have updated Selenium but the error keeps occurring even though the web page loads. However, in some instances, the driver starts but it is stagnant. Is this causing an issue and if so, how do I resolve it? [11556:9032:0502/152954.314:ERROR:device_event_log_impl.cc(162)] [15:29:54.314] Bluetooth: bluetooth_adapter_wi... | This error message... ERROR:device_event_log_impl.cc(162)] [15:29:54.314] Bluetooth: bluetooth_adapter_winrt.cc:1055 Getting Default Adapter failed. ...implies that ScopedClosureRunner on_init failed in BluetoothAdapterWinrt::OnGetDefaultAdapter(). Analysis This error is defined in bluetooth_adapter_winrt.cc as follo... | 21 | 28 |
61,529,817 | 2020-4-30 | https://stackoverflow.com/questions/61529817/automate-outlook-on-mac-with-python | I can automate Outlook on windows with win32/COM, but does anyone know of a pure python way to do the same on mac osx? A simple use case would be: Open outlook/connect to the active instance Launch a blank new email I want to create an app to create email templates and attach files, then let the user finish editing t... | @ajrwhite adding attachments had one trick, you need to use 'Alias' from mactypes to convert a string/path object to a mactypes path. I'm not sure why but it works. here's a working example which creates messages with recipients and can add attachments: from appscript import app, k from mactypes import Alias from pathl... | 8 | 11 |
61,560,056 | 2020-5-2 | https://stackoverflow.com/questions/61560056/extracting-key-phrases-from-text-based-on-the-topic-with-python | I have a large dataset with 3 columns, columns are text, phrase and topic. I want to find a way to extract key-phrases (phrases column) based on the topic. Key-Phrase can be part of the text value or the whole text value. import pandas as pd text = ["great game with a lot of amazing goals from both teams", "goalkeepers... | It looks like a good approach here would be to use a Latent Dirichlet allocation model, which is an example of what are known as topic models. A LDA is a an unsupervised model that finds similar groups among a set of observations, which you can then use to assign a topic to each of them. Here I'll go through what coul... | 12 | 14 |
61,581,645 | 2020-5-3 | https://stackoverflow.com/questions/61581645/how-do-i-define-a-patch-globally-with-autouse | Right now I do this in a few tests to mock a 3rd party API: @patch("some.api.execute") def sometest( mock_the_api, blah, otherstuff ): mock_the_api.return_value = "mocked response" my_func_that_uses_api(blah, otherstuff) This works and prevents my_func_that_uses_api() (which calls the API) from making actual outbound ... | You can just use: from unittest import mock import pytest @pytest.fixture(autouse=True) def my_api_mock(): with mock.patch("some.api.execute") as api_mock: api_mock.return_value = "mocked response" yield api_mock def test_something(blah, otherstuff): my_func_that_uses_api(blah, otherstuff) The fixture lives as long as... | 9 | 11 |
61,578,927 | 2020-5-3 | https://stackoverflow.com/questions/61578927/use-a-local-file-as-the-set-image-file-discord-py | I am aware that in discord.py, you can make the set_image of an embed a url of an image. But, I want to use a local file on my computer for the set_image instead of a url of an image. embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) embed.set_image(url = "https://example.com/image.png") #this i... | Ok I just got it. The code for it is the following: embed = discord.Embed(title="Title", description="Desc", color=0x00ff00) #creates embed file = discord.File("path/to/image/file.png", filename="image.png") embed.set_image(url="attachment://image.png") await ctx.send(file=file, embed=embed) The only thing you should ... | 7 | 21 |
61,606,279 | 2020-5-5 | https://stackoverflow.com/questions/61606279/how-do-i-create-a-pdf-file-containing-a-signature-field-using-python | In order to be able to sign a PDF document using a token based DSC, I need a so-called signature field in my PDF. This is a rectangular field you can fill with a digital signature using e.g. Adobe Reader or Adobe Acrobat. I want to create this signable PDF in Python. I'm starting from plain text, or a rich-text docume... | Unfortunately, I couldn't find any (free) solutions. Just Python programs that sign PDF documents. But there is a Python PDF SDK called PDFTron that has a free trial. Here's a link to a specific article showing how to "add a certification signature field to a PDF document and sign it". # Open an existing PDF doc = PDFD... | 8 | 1 |
61,602,547 | 2020-5-4 | https://stackoverflow.com/questions/61602547/how-to-use-python-subprocess-with-bytes-instead-of-files | I can convert a mp4 to wav, using ffmpeg, by doing this: ffmpeg -vn test.wav -i test.mp4 I can also use subprocess to do the same, as long as my input and output are filepaths. But what if I wanted to use ffmpeg directly on bytes or a "file-like" object like io.BytesIO()? Here's an attempt at it: import subprocess fr... | Base on @thorwhalen's answer, here's how it would work from bytes to bytes. What you were probably missing @thorwhalen, is the actual pipe-to-pipe way to send and get data when interacting with a process. When sending bytes, the stdin should be closed before the process can read from it. def from_bytes_to_bytes( input... | 9 | 9 |
61,567,599 | 2020-5-2 | https://stackoverflow.com/questions/61567599/huggingface-bert-inputs-embeds-giving-unexpected-result | The HuggingFace BERT TensorFlow implementation allows us to feed in a precomputed embedding in place of the embedding lookup that is native to BERT. This is done using the model's call method's optional parameter inputs_embeds (in place of input_ids). To test this out, I wanted to make sure that if I did feed in BERT's... | My intuition about positional and token type embeddings being added in turned out to be correct. After looking closely at the code, I replaced the line: inputs_embeds = result[-1][0] with the lines: embeddings = bert_model.bert.get_input_embeddings().word_embeddings inputs_embeds = tf.gather(embeddings, input_ids) No... | 8 | 3 |
61,606,054 | 2020-5-5 | https://stackoverflow.com/questions/61606054/passing-ipython-variables-as-string-arguments-to-shell-command | How do I execute a shell command from Ipython/Jupyter notebook passing the value of a python string variable as a string in the bash argument like in this example: sp_name = 'littleGuy' #the variable sp_details = !az ad app list --filter "DisplayName eq '$sp_name'" #the shell command I've tried using $sp_name alone, $... | The main problem you encounters seems to come from the quotes needed in your string. You can keep the quotes in your string by using a format instruction and a raw string. Use a 'r' before the whole string to indicate it is to be read as raw string, ie: special caracters have to not be interpreted. A raw string is not ... | 8 | 14 |
61,574,984 | 2020-5-3 | https://stackoverflow.com/questions/61574984/no-module-named-pkg-resources-py2-warn-pyinstaller | I'm trying to make an executable file (.exe file for windows) for the code here. The main file to run is src/GUI.py. I found that pyinstaller is a better option to create the exe file. I tried both one folder and single executable file options. I tried creating the exe from root directory and as well as in src director... | This is an issue with setuptools as explained in this github ticket. Consider downgrading your setuptools to 44.0 or below with the command pip install --upgrade 'setuptools<45.0.0' | 17 | 9 |
61,594,447 | 2020-5-4 | https://stackoverflow.com/questions/61594447/python-kubernetes-client-equivalent-of-kubectl-get-custom-resource | With kubectl I can execute the following command: kubectl get serviceentries Then I receive some information back. But serviceentries is a custom resource. So how do I go about getting the same information back but then with the kubernetes client? Yaml looks like this for example: apiVersion: networking.istio.io/v1... | you should be able to pull it using the python client like this: kubernetes.client.CustomObjectsApi().list_cluster_custom_object(group="networking.istio.io", version="v1alpha3", plural="serviceentries") That method applies to every custom resource within kubernetes and doesn't require any further definition to the pyt... | 7 | 21 |
61,565,153 | 2020-5-2 | https://stackoverflow.com/questions/61565153/passing-arguments-to-an-entry-point-python-script-using-argparser | I am looking to pass a user entered arguments from the command line to an entry point for a python script. Thus far I have tried to used argparse to pass the arguments from the command line to the test.py script. When I try to pass the arguments they are not recognised and I recieve the following error. load_entry_po... | So it works now when I remove the the arguments from the function. def main(): parser = argparse.ArgumentParser(description='Enter string') parser.add_argument('string', type=str, help='Enter word or words', nargs='*') args = parser.parse_args() print(args.string) if __name__ == "__main__": main() I believe that it m... | 9 | 7 |
61,577,643 | 2020-5-3 | https://stackoverflow.com/questions/61577643/python-how-to-use-fastapi-and-uvicorn-run-without-blocking-the-thread | I'm looking for a possibility to use uvicorn.run() with a FastAPI app but without uvicorn.run() is blocking the thread. I already tried to use processes, subprocessesand threads but nothing worked. My problem is that I want to start the Server from another process that should go on with other tasks after starting the s... | According to Uvicorn documentation there is no programmatically way to stop the server. instead, you can stop the server only by pressing ctrl + c (officially). But I have a trick to solve this problem programmatically using multiprocessing standard lib with these three simple functions : A run function to run the se... | 29 | 2 |
61,624,276 | 2020-5-5 | https://stackoverflow.com/questions/61624276/group-related-constants-in-python | I'm looking for a pythonic way to define multiple related constants in a single file to be used in multiple modules. I came up with multiple options, but all of them have downsides. Approach 1 - simple global constants # file resources/resource_ids.py FOO_RESOURCE = 'foo' BAR_RESOURCE = 'bar' BAZ_RESOURCE = 'baz' QUX_R... | Use Enum and mix in str: @unique class ResourceIds(str, Enum): foo = 'foo' bar = 'bar' baz = 'baz' qux = 'qux' Then you won't need to compare against .value: >>> ResourceIds.foo == 'foo' True And you still get good debugging info: >>> ResourceIds.foo <ResourceIds.foo: 'foo'> >>> list(ResourceIds.foo.__class__) [ <Res... | 8 | 10 |
61,506,470 | 2020-4-29 | https://stackoverflow.com/questions/61506470/is-it-possible-to-have-a-red-squiggly-line-appear-under-words-in-a-tkinter-text | As per the question title: Is it possible to have a red squiggly line appear under words in a Tkinter text widget without using a canvas widget? (The same squiggle as when you misspell a word) I'm going for something like this: If so where would I start? | This is just an example of using user-defined XBM as the bgstipple of part of the text inside a Text widget to simulate the squiggly line effect: create a XBM image, for example squiggly.xbm, like below: A XBM with 10x20 pixels then you can config a tag in Text widget using the above XBM image file as bgstipple in ... | 20 | 18 |
61,606,746 | 2020-5-5 | https://stackoverflow.com/questions/61606746/python-pandas-valueerror-must-have-equal-len-keys-and-value-when-setting-with | I have a DataFrame that I want to change using df.loc[rowId,colId] = myDict to assign a dict to the entry [rowId,colId]. As a result I get following error: ValueError: Must have equal len keys and value when setting with an iterable Setting df.loc[rowId,colId] = 0 works! In my pinion the style to assign the value i... | It is possible by adding list: df.loc[rowId,colId] = [myDict] But for better performance in pandas is best working in pandas only with scalars. | 8 | 1 |
61,599,363 | 2020-5-4 | https://stackoverflow.com/questions/61599363/evaluate-consonant-vowel-composition-of-word-string-in-python | I'm trying to transform a Python string from its original form to its vowel/consonant combinations. Eg - 'Dog' becomes 'cvc' and 'Bike' becomes 'cvcv' In R I was able to employ the following method: con_vowel <- gsub("[aeiouAEIOU]","V",df$col_name) con_vowel <- gsub("[^V]","C",con_vowel) df[["composition"]] <- con_vow... | use string.replace with some regex to avoid the loop df = pd.DataFrame(['Cat', 'DOG', 'bike'], columns=['words']) # use string.replace df['new_word'] = df['words'].str.lower().str.replace(r"[^aeiuo]", 'c').str.replace(r"[aeiou]", 'v') print(df) words new_word 0 Cat cvc 1 DOG cvc 2 bike cvcv | 9 | 3 |
61,589,427 | 2020-5-4 | https://stackoverflow.com/questions/61589427/matplotlib-bar-vs-barh-plots-problem-with-barh | I've just noticed something strange and was wondering if someone could explain what's going on? I have a dictionary i'm plotting a horizontal and vertical bar charts from. plt.bar(food.keys(), food.values()) #works fine, but: plt.barh(food.keys(), food.values() #gives "unhashable type: 'dict_keys'" error. if dictionar... | The other answer is of course correct in how to solve the problem - simply convert to a list. The reason why it doesn't work in the first place involves digging into the matplotlib source code. bar and barh do both call matplotlib.axes.Axes.bar under the hood. When you plot a bar, x is the x position of the bars and he... | 8 | 13 |
61,587,974 | 2020-5-4 | https://stackoverflow.com/questions/61587974/how-to-create-a-list-of-lists-where-each-sub-list-increments-as-follows-1-0 | This works but is unwieldy and not very 'Pythonic'. I'd also like to be able to run through different values for 'numValues', say 4 to 40... innerList = [] outerList = [] numValues = 12 loopIter = 0 for i in range(numValues): innerList.append(0) for i in range(numValues): copyInnerList = innerList.copy() outerList.appe... | numValues = 12 result = [ [1] * i + [0] * (numValues - i) for i in range(1, numValues+1) ] | 11 | 12 |
61,583,991 | 2020-5-4 | https://stackoverflow.com/questions/61583991/opencv-python-error-unsupported-data-type-4-in-function-cvopt-avx2getmo | I'm trying to remove noise with morphology and the kernel is giving me errors: import skimage.io as io import numpy as np import cv2 c=io.imread('circles.png').astype('bool')*1 x=np.random.random_sample(c.shape) c[np.nonzero(x>0.95)]= 0 c[np.nonzero(x<=0.05)] = 1 opening = cv2.morphologyEx(c, cv2.MORPH_OPEN, np.ones((2... | Your data type (=4) is CV_32SC1, which is 32-bit signed single channel -- you need to convert your data into another data type, I'd recommend using CV_8UC1 because of the smallest memory footprint and ease of use: c = c.astype('uint8') # or c.astype(np.byte) | 9 | 13 |
61,528,860 | 2020-4-30 | https://stackoverflow.com/questions/61528860/sqlalchemy-engine-from-airflow-database-hook | What's the best way to get a SQLAlchemy engine from an Airflow connection ID? Currently I am creating a hook, retrieving its URI, then using it to create a SQLAlchemy engine. postgres_hook = PostgresHook(self.postgres_conn_id) engine = create_engine(postgres_hook.get_uri()) This works but both commands make a connecti... | To be clear, indeed your commands will make two database connections, but it's to two separate databases (unless you're trying to connect to your Postgres Airflow database). The first line of initializing the hook should not make any connections. Only the second line first grabs the connection details from the Airflow ... | 14 | 17 |
61,578,694 | 2020-5-3 | https://stackoverflow.com/questions/61578694/difference-between-rect-move-and-rect-move-ip-in-pygame | I was just going through the .rect method of pygame in the official docs. We have 2 cases , pygame.rect.move(arg1,arg2) which is used to move a .rect object on the screen and pygame.rect.move_ip(arg1,arg2) which is , according to the docs, also used to move a .rect object on the screen but it moves it in place I didn... | "In place" means the object self. While rect.move_ip changes the pygame.Rect object itself, rect.move does not change the object, but it returns a new object with the same size and "moved" position. Note, the return value of rect.move_ip is None, but the return value of rect.move is a new pygame.Rect object. rect.move_... | 9 | 15 |
61,576,659 | 2020-5-3 | https://stackoverflow.com/questions/61576659/how-to-hot-reload-in-reactjs-docker | This might sound simple, but I have this problem. I have two docker containers running. One is for my front-end and other is for my backend services. these are the Dockerfiles for both services. front-end Dockerfile : # Use an official node runtime as a parent image FROM node:8 WORKDIR /app # Install dependencies COPY ... | Try this in your docker-compose.yml version: "3.2" services: frontend: build: ./frontend environment: CHOKIDAR_USEPOLLING: "true" volumes: - /app/node_modules - ./frontend:/app ports: - 80:3000 depends_on: - backend backend: build: ./backends/banuka environment: CHOKIDAR_USEPOLLING: "true" volumes: - ./backends/banuka... | 27 | 36 |
61,577,168 | 2020-5-3 | https://stackoverflow.com/questions/61577168/filter-array-of-objects-in-python | I'm using Python to dig through a pretty big project and dig up information about it. I'm able to create an array of ProjectFiles, however I'm having a hard time figuring out how to filter it. class ProjectFile: def __init__(self, filename: str, number_of_lines: int, language: str, repo: str, size: int): self.filename ... | You can select attributes of a class using the dot notation. Suppose arr is an array of ProjectFile objects. Now you filter for SomeCocoapod using. filter(lambda p: p.repo == "SomeCocoapod", arr) NB: This returns a filter object, which is a generator. To have a filtered list back you can wrap it in a list constructo... | 18 | 21 |
61,564,609 | 2020-5-2 | https://stackoverflow.com/questions/61564609/does-a-python-virtual-environment-avoid-redundant-installs | I'm fairly new to python and I'm beginning to work with python virtual environments. When I create a virtual environment, I have to reinstall all the modules that I need for the current project that I'm working on. I'm wondering if the virtual environment somehow avoids redundancies in installation of modules if the sa... | Short Answer : If you work with virtual environment, you need to install every dependecy (package) that you need for your project even if you installed this package in another virtual environment before. That's exactly the purpose of virtual environment : each project has its own dependencies. That allows you to manag... | 15 | 14 |
61,566,808 | 2020-5-2 | https://stackoverflow.com/questions/61566808/manytomany-relationship-between-two-models-in-django | I am trying to build a website that users can add the courses they are taking. I want to know how should I add the ManyToMany relationship. Such that we can get all users in a course based on the course code or instructor or any field. And we can also get the courses user is enrolled in. Currently, my Database structur... | For a relational databases, the model where you define the ManyToManyField does not matter. Django will create an extra table with two ForeignKeys to the two models that are linked by the ManyToManyField. The related managers that are added, etc. is all Django logic. Behind the curtains, it will query the table in the ... | 10 | 16 |
61,566,711 | 2020-5-2 | https://stackoverflow.com/questions/61566711/which-characters-are-considered-whitespace-by-split | I am porting some Python 2 code that calls split() on strings, so I need to know its exact behavior. The documentation states that when you do not specify the sep argument, "runs of consecutive whitespace are regarded as a single separator". Unfortunately, it does not specify which characters that would be. There are s... | Unfortunately, it depends on whether your string is an str or a unicode (at least, in CPython - I don't know whether this behavior is actually mandated by a specification anywhere). If it is an str, the answer is straightforward: 0x09 Tab 0x0a Newline 0x0b Vertical Tab 0x0c Form Feed 0x0d Carriage Return 0x20 Space S... | 19 | 24 |
61,541,776 | 2020-5-1 | https://stackoverflow.com/questions/61541776/seaborn-ordering-of-facets | In a statement like: g = sns.FacetGrid(df, row="variable", col="state") I would like to control the order in which the variables and the states appear in the FacetGrid. I can't find where this is even possible. | You can use row_order and col_order: from sklearn.datasets import load_iris import pandas as pd import seaborn as sns import numpy as np import matplotlib.pyplot as plt data = load_iris() df = pd.DataFrame(data.data, columns=['sepal.length','sepal.width','petal.length','petal.width']) df['species'] = data.target df['su... | 13 | 16 |
61,522,624 | 2020-4-30 | https://stackoverflow.com/questions/61522624/how-to-create-an-optional-field-in-a-dataclass-that-is-inherited | from typing import Optional @dataclass class Event: id: str created_at: datetime updated_at: Optional[datetime] #updated_at: datetime = field(default_factory=datetime.now) CASE 1 #updated_at: Optional[datetime] = None CASE 2 @dataclass class NamedEvent(Event): name: str When creating an event instance I will generally... | The underlying problem that you have seems to be the same one that is described here. The short version of that post is that in a function signature (including the dataclass-generated __init__ method), obligatory arguments (like NamedEvent's name) can not follow after arguments with default values (which are necessary ... | 35 | 26 |
61,559,359 | 2020-5-2 | https://stackoverflow.com/questions/61559359/could-not-build-wheels-for-pyaudio-since-package-wheel-is-not-installed | I tried to install pyaudio, but it returns an error like this: Could not build wheels for pyaudio, since package 'wheel' is not installed. How can I fix this? | It looks like you just need to install the wheel package. You can do this by running pip install wheel at the terminal. | 18 | 23 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.