question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-07-15 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
63,162,354
2020-7-29
https://stackoverflow.com/questions/63162354/pip-install-via-requirements-txt-specify-a-direct-github-private-repo-branch-n
I am trying to add a package to my requirements.txt file that is: From a private GitHub repo I'm a member of the private repo I have ssh configured for the private repo From a branch besides master, whose name has a slash in it Using ssh protocol All over the internet, there are questions on this topic. Here are t...
I figured out my problem in both cases... syntax Attempt #1 Mistake: needed to say git@github.com Correct method: -e git+ssh://git@github.com/Organization/repo-name.git@branch/name#egg=foo Attempt #2 Mistake: didn't know one can use @ twice Correct method: -e git+git@github.com:Organization/repo-name.git@branch/name...
13
14
63,207,385
2020-8-1
https://stackoverflow.com/questions/63207385/how-do-i-install-pip-for-python-3-8-on-ubuntu-without-changing-any-defaults
I'm trying to install pip for Python 3.8 on an Ubuntu 18.04 LTS. I know this has been asked way too many times. But those questions do not concern keeping Ubuntu's defaults specifically. And the answers on those questions either don't work or go on to suggest something so drastic that it would break the system - e.g....
While we can use pip directly as a Python module (the recommended way): python -m pip --version This is how I installed it (so it can be called directly): Firstly, make sure that command pip is available and it isn't being used by pip for Python 2.7 sudo apt remove python-pip Now if you write pip in the Terminal, yo...
38
42
63,161,585
2020-7-29
https://stackoverflow.com/questions/63161585/what-is-the-purpose-of-pydantics-secretstr
I am learning the Pydantic module, trying to adopt its features/benefits via a toy FastAPI web backend as an example implementation. I chose to use Pydantic's SecretStr to "hide" passwords. I know it is not really secure, and I am also using passlib for proper password encryption in DB storage (and using HTTPS for secu...
You already answered a big part of the question yourself. You can use the SecretStr and the SecretBytes data types for storing sensitive information that you do not want to be visible in logging or tracebacks. I would like to add another benefit. Developers are constantly reminded that they are working with secrets b...
17
33
63,182,075
2020-7-30
https://stackoverflow.com/questions/63182075/python-opencv-centroid-determination-in-bacterial-clusters
I am currently working on developing an algorithm to determine centroid positions from (Brightfield) microscopy images of bacterial clusters. This is currently a major open problem in image processing. This question is a follow-up to: Python/OpenCV — Matching Centroid Points of Bacteria in Two Images. Currently, the al...
The mask is always the weak point in identifying objects, and the most important step. This will improve identifying images with high numbers of bacteria. I have modified your e_d function by adding an OPEN and another ERODE pass with the kernal, and changed the it (number of iterations) variable (to 1, 2 instead of 1,...
9
5
63,163,251
2020-7-29
https://stackoverflow.com/questions/63163251/how-to-easily-share-a-sample-dataframe-using-df-to-dict
Despite the clear guidance on How do I ask a good question? and How to create a Minimal, Reproducible Example, many just seem to ignore to include a reproducible data sample in their question. So what is a practical and easy way to reproduce a data sample when a simple pd.DataFrame(np.random.random(size=(5, 5))) is not...
The answer: In many situations, using an approach with df.to_dict() will do the job perfectly! Here are two cases that come to mind: Case 1: You've got a dataframe built or loaded in Python from a local source Case 2: You've got a table in another application (like Excel) The details: Case 1: You've got a dataframe bu...
15
20
63,196,320
2020-7-31
https://stackoverflow.com/questions/63196320/installing-opencv-with-conda-and-spyder
I'm having trouble installing OpenCV with Conda. I tried running numerous commands, none of which worked. For example, when I ran conda install -c anaconda opencv (as per https://anaconda.org/anaconda/opencv) I get this error: UnsatisfiableError: The following specifications were found to be incompatible with the exist...
The answer for this issue is updating Anaconda to the newest version: conda update -n base -c defaults conda then you can install opencv normally using: conda install -c conda-forge opencv
10
12
63,163,027
2020-7-29
https://stackoverflow.com/questions/63163027/how-to-use-pyinstaller-with-matplotlib-in-use
I have this script that I attached a GUI to the front of and wanted to distribute it to other DnD DMs for them to use to overlay grids onto images. Only issue is that everytime I try to package the python script using Pyinstaller, it keeps throwing two different errors. If I run pyinstaller --hidden-import matplotlib m...
You can try to solve this problem by installing older versions of the matplotlib package. eg: pip install matplotlib==3.2.2
9
8
63,220,629
2020-8-2
https://stackoverflow.com/questions/63220629/inverse-of-numpy-gradient-function
I need to create a function which would be the inverse of the np.gradient function. Where the Vx,Vy arrays (Velocity component vectors) are the input and the output would be an array of anti-derivatives (Arrival Time) at the datapoints x,y. I have data on a (x,y) grid with scalar values (time) at each point. I have use...
TL;DR; You have multiple challenges to address in this issue, mainly: Potential reconstruction (scalar field) from its gradient (vector field) But also: Observation in a concave hull with non rectangular grid; Numerical 2D line integration and numerical inaccuracy; It seems it can be solved by choosing an adhoc int...
9
7
63,201,036
2020-8-1
https://stackoverflow.com/questions/63201036/add-additional-layers-to-the-huggingface-transformers
I want to add additional Dense layer after pretrained TFDistilBertModel, TFXLNetModel and TFRobertaModel Huggingface models. I have already seen how I can do this with the TFBertModel, e.g. in this notebook: output = bert_model([input_ids,attention_masks]) output = output[1] output = tf.keras.layers.Dense(32,activation...
It looks like pooler_output is a Roberta and Bert specific output. But instead of using pooler_output we can use a few hidden_states(so, not only last hidden state) with all models, we want to use them because papers report that hidden_states can give more accuracy than just one last_hidden_state. # Import the needed m...
7
7
63,200,489
2020-8-1
https://stackoverflow.com/questions/63200489/pygame-basic-calculator
I am trying to make a basic calculator but the problem I am having is how do I output the text? How do I make it so when I click plus it allows me to add or if I click divide it allows me to divide and shows the output on the yellow part on my screen This is what I have right now. You could run it; there is nothing sp...
You could add a = button, so every time user clicks it, calculate the user input with python eval() function. As for the user input, you first need to record it globally . Then you can pass user input to the string field of inputtap = button((253,100,32),10,280,450,50,"") to show it on the window. import pygame, math p...
6
6
63,248,354
2020-8-4
https://stackoverflow.com/questions/63248354/how-to-check-does-a-file-imports-from-another-file-in-python
Suppose i have a project structure like this src └── app ├── main.py ├── db │ └── database.py ├── models │ ├── model_a.py │ └── model_b.py └── tests ├── test_x.py └── test_y.py I want to check which file uses a class or a function from another file. I have a class called Test in main.py class Test: pass I used that c...
What you are looking for is to find import dependencies in your package modules. You can run a static analysis on your package directory and parse the import nodes in the syntax trees (ast), and build a dependency graph. Something like below: import os from ast import NodeVisitor, parse import networkx as nx class Depe...
9
3
63,232,732
2020-8-3
https://stackoverflow.com/questions/63232732/how-to-use-the-past-with-huggingface-transformers-gpt-2
I have: context = torch.tensor(context, dtype=torch.long, device=self.device) context = context.unsqueeze(0) generated = context with torch.no_grad(): past_outputs = None for i in trange(num_words): print(i, num_words) inputs = {"input_ids": generated} outputs, past_outputs = self.model( **inputs, past=past_outputs ) ...
I did: outputs, past_outputs = self.models[model_name]( context, past=past_outputs ) context = next_token.unsqueeze(0)
7
0
63,195,577
2020-7-31
https://stackoverflow.com/questions/63195577/how-to-locate-qr-code-in-large-image-to-improve-decoding-performance
Background I need to detect and decode a relatively small QR code (110x110 pixels) in a large image (2500x2000) on a Raspberry Pi. The QR code can be at any location in the frame, but the orientation is expected to be normal, i.e. top-up. We are using high quality industrial cameras and lenses, so images are generally ...
I think I have found a simple yet reliable way in which the corners of the QR code can be detected. However, my approach assumes there is some contrast (the more the better) between the QR and its surrounding area. Also, we have to keep in mind that neither pyzbar nor opencv.QRCodeDetector are 100% reliable. So, here i...
17
22
63,160,370
2020-7-29
https://stackoverflow.com/questions/63160370/how-can-i-accept-and-run-users-code-securely-on-my-web-app
I am working on a django based web app that takes python file as input which contains some function, then in backend i have some lists that are passed as parameters through the user's function,which will generate a single value output.The result generated will be used for some further computation. Here is how the funct...
It is an important question. In python sandboxing is not trivial. It is one of the few cases where the question which version of python interpreter you are using. For example, Jyton generates Java bytecode, and JVM has its own mechanism to run code securely. For CPython, the default interpreter, originally there were s...
14
11
63,174,054
2020-7-30
https://stackoverflow.com/questions/63174054/what-is-a-good-design-pattern-to-combine-datasets-that-are-related-but-stored-in
Suppose we want to construct a stock portfolio. To decide which stocks to include in the portfolio and what weight to assign to these stocks, we use different metrics such as e.g., price, earnings-per-share (eps), dividend yield, etc... All these metrics are stored in individual pandas dataframes where rows specify a c...
If I understand your questions correctly, you basically have 2 (or multiple) dataframes that are related and you want to join together let's try it out with 2. I do realize that this mainly a design pattern question but I'm showing you that you can easily have them as separate dataframes and then efficiently combine th...
7
1
63,235,326
2020-8-3
https://stackoverflow.com/questions/63235326/works-with-urrlib-request-but-doesnt-work-with-requests
I am trying to send a request wtih post method to an API, my code looks like the following one: import urllib.request import json url = "https://api.cloudflareclient.com/v0a745/reg" referrer = "e7b507ed-5256-4bfc-8f17-2652d3f0851f" body = {"referrer": referrer} data = json.dumps(body).encode('utf8') headers = {'User-Ag...
The issue seems to be with how the host is handling ssl. Newer versions of requests uses certifi which in your case is having issues with the host server. I downgraded requests to an earlier version and it worked. (2.1.0). You can fix the version in your requirements.txt and it should work with any python version. http...
11
3
63,215,752
2020-8-2
https://stackoverflow.com/questions/63215752/how-to-use-fileupload-widget-in-jupyter-lab
I want to use the FileUpload widget in jupyter lab. I have the following lines of code in my notebook cell: uploader = widgets.FileUpload() uploader In jupyter notebook, the output of the cell is a clickable button that I can use to upload a file. In jupyter lab, the output is the following : FileUpload(value={}, desc...
If you're using jupyterlab out the box, it doesn't have ipywidgets enabled by default, you need to rebuild it after enabling the extension. Follow the steps from here: Install nodeJS pip install ipywidgets jupyter nbextension enable --py widgetsnbextension jupyter labextension install @jupyter-widgets/jupyterlab-manag...
18
15
63,160,595
2020-7-29
https://stackoverflow.com/questions/63160595/implementing-a-recursive-algorithm-in-pyspark-to-find-pairings-within-a-datafram
I have a spark dataframe (prof_student_df) that lists student/professor pair for a timestamp. There are 4 professors and 4 students for each timestamp and each professor-student pair has a “score” (so there are 16 rows per time frame). For each time frame, I need to find the one to one pairing between professors/studen...
Edit: As discussed in comments, to fix the issue mentioned in your update, we can convert student_id at each time into generalized sequence-id using dense_rank, go through Step 1 to 3 (using student column) and then use join to convert student at each time back to their original student_id. see below Step-0 and Step-4....
7
5
63,248,340
2020-8-4
https://stackoverflow.com/questions/63248340/sqlalchemy-when-does-an-object-become-not-persistent
I have a function that has a semi-long running session that I use for a bunch of database rows... and at a certain point I want to reload or "refresh" one of the rows to make sure none of the state has changed. most of the time this code works fine, but every now and then I get this error sqlalchemy.exc.InvalidRequestE...
I am fairly certain that the root cause in this case is a race condition. Using a scoped session in its default configuration manages scope based on the thread only. Using coroutines on top can mean that 2 or more end up sharing the same session, and in case of event_white_check_mark_handler they then race to commit/ro...
8
8
63,248,112
2020-8-4
https://stackoverflow.com/questions/63248112/how-to-implement-oauth-to-fastapi-with-client-id-secret
I have followed the docs about Oauth2 but it does not describe the proccess to add client id and secret https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/ and what this does class UserInDB(User): hashed_password: str from the original example
In documentation it uses OAuth2PasswordRequestForm to authenticate the user this class has basically 6 different Fields, grant_type: str = Form(None, regex="password"), username: str = Form(...), password: str = Form(...), scope: str = Form(""), client_id: Optional[str] = Form(None), client_secret: Optional[str] = Form...
12
11
63,255,631
2020-8-4
https://stackoverflow.com/questions/63255631/mlflow-invalid-parameter-value-unsupported-uri-mlruns-for-model-registry-s
I got this error when I was trying to have a model registered in the model registry. Could someone help me? RestException: INVALID_PARAMETER_VALUE: Unsupported URI './mlruns' for model registry store. Supported schemes are: ['postgresql', 'mysql', 'sqlite', 'mssql']. See https://www.mlflow.org/docs/latest/tracking.html...
Mlflow required DB as datastore for Model Registry So you have to run tracking server with DB as backend-store and log model to this tracking server. The easiest way to use DB is to use SQLite. mlflow server \ --backend-store-uri sqlite:///mlflow.db \ --default-artifact-root ./artifacts \ --host 0.0.0.0 And set MLFLOW...
10
32
63,246,100
2020-8-4
https://stackoverflow.com/questions/63246100/how-to-draw-character-with-gradient-colors-using-pil
I have the function that generates character images from a font file using PIL. For the current example, it generates a white background image and a red character text. What I want now is that instead of pure red or any other color I can generate a gradient color. Is this possible with my current code? I have seen this...
One fairly easy way of doing it is to draw the text in white on a black background and then use that as the alpha/transparency channel over a background with a gradient. Here's a background gradient: #!/usr/bin/env python3 from PIL import Image, ImageDraw, ImageFont w, h = 400, 150 image = Image.open('gradient.jpg').r...
9
11
63,255,485
2020-8-4
https://stackoverflow.com/questions/63255485/python-argparse-how-to-reference-a-parameter-with-a-dash-in-it
I'm using argparse and I'd like to specify the positional argument with a dash in it. argparse seems to let me do this. Indeed, it shows up in the Namespace of parse_args(), but I cannot figure out how to reference the corresponding value. Here's a minimal example (notice the dash in 'a-string'): #!/usr/bin/env python3...
The arguments are given as attributes of the namespace object returned by parse_args(). But identifiers (including attributes) can't have a hyphen in them (at least not if you want to access them directly), because it's a minus sign, and that means something else. If you want your argument to be named "a-string" to the...
6
10
63,247,803
2020-8-4
https://stackoverflow.com/questions/63247803/pipenv-requires-python-3-7-but-installed-version-is-3-8-and-wont-install
I know a little of Python and more than a year ago I wrote a small script, using pipenv to manage the dependencies. The old platform was Windows 7, the current platform is Windows 10. At that time I probably had Python 3.7 installed, now I have 3.8.3 but running: pipenv install Complained that: Warning: Python 3.7 was...
You can download Python 3.7 from the official site - https://www.python.org/downloads/
33
3
63,241,608
2020-8-4
https://stackoverflow.com/questions/63241608/install-opencv-from-source-to-conda-environment
I would like to install opencv to my conda environment from source. Since I'm using Jetson, there is no pip or conda packages that are available for opencv. I use this command for installing from source, -D BUILD_EXAMPLES=OFF -D BUILD_opencv_python2=ON -D BUILD_opencv_python3=ON -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_IN...
By default it will install to your system Python path which you can see by entering: which python in the terminal. In your cmake commands (the above list you posted) you need to tell it which python executable path you want to build to. At the moment your build is pointing to the above default Python location, and now...
23
8
63,187,161
2020-7-31
https://stackoverflow.com/questions/63187161/error-while-import-pytorch-module-the-specified-module-could-not-be-found
I just newly install python 3.8 via anaconda installer and install pytorch using command conda install pytorch torchvision cpuonly -c pytorch when i try to import torch, I got this error message. OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\chunc\anaconda3\lib\site-packages\...
I had the same problem, you should check if you installed Microsoft Visual C++ Redistributable, because if you didn't this may lead to the DLL load failure. Here is a link to download it: https://aka.ms/vs/16/release/vc_redist.x64.exe
9
30
63,232,724
2020-8-3
https://stackoverflow.com/questions/63232724/how-to-add-documentation-for-required-query-parameters
I'm trying to create a fastapi API endpoint that relies on HTTP GET parameters, has them documented and uses fastapi's validation capabilities. Consider the following minimal example: import fastapi app = fastapi.FastAPI( ) @app.get("/endpoint") def example_endpoint( par1: int = fastapi.Query( None, description="exampl...
You can use Ellipsis, If you hadn't seen that ... before: it is a special single value that makes query required from fastapi import Query Query(...,description="example documentation1") So in your case answer below can do the job @app.get("/endpoint") def example_endpoint( par1: int = fastapi.Query(..., description="...
6
11
63,231,163
2020-8-3
https://stackoverflow.com/questions/63231163/what-is-the-usermixin-in-flask
from datetime import datetime from werkzeug.security import generate_password_hash from werkzeug.security import check_password_hash from flask_login import UserMixin from app import db class User(UserMixin, db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(64), index=True, unique=T...
Flask-login requires a User model with the following properties: has an is_authenticated() method that returns True if the user has provided valid credentials has an is_active() method that returns True if the user’s account is active has an is_anonymous() method that returns True if the current user is an anonymous u...
24
51
63,231,615
2020-8-3
https://stackoverflow.com/questions/63231615/apply-function-to-pandas-row-row-cross-product
I have two pandas DataFrames / Series containing one row each. df1 = pd.DataFrame([1, 2, 3, 4]) df2 = pd.DataFrame(['one', 'two', 'three', 'four']) I now want to get all possible combinations into an n*n matrix / DataFrame with values for all cross-products being the output from a custom function. def my_function(x, y...
Let us try np.add.outer df = pd.DataFrame(np.add.outer(df1[0].astype(str).values,':'+df2[0].values).T) Out[258]: 0 1 2 3 0 1:one 2:one 3:one 4:one 1 1:two 2:two 3:two 4:two 2 1:three 2:three 3:three 4:three 3 1:four 2:four 3:four 4:four
14
9
63,229,017
2020-8-3
https://stackoverflow.com/questions/63229017/how-can-i-count-a-pandas-dataframe-over-duplications
My initial dataframe is: Name Info1 Info2 0 Name1 Name1-Info1 Name1-Info2 1 Name1 Name1-Info1 Name1-Info2 2 Name1 Name1-Info1 Name1-Info2 3 Name2 Name2-Info1 Name2-Info2 4 Name2 Name2-Info1 Name2-Info2 and i would like to return the number of repetitions of each row as such: Name Info1 Info2 Count 0 Name1 Name1-Info...
df.groupby(['Name', 'Info1', 'Info2']).size().reset_index().rename(columns={0:"count"})
9
9
63,225,707
2020-8-3
https://stackoverflow.com/questions/63225707/plotly-dash-refreshing-global-data-on-reload
Imagine I have a dash application where I want the global data to refresh on page reload. I'm using a function to serve the layout as described here. However, I'm note sure how/where I should define df such that I can use it in callbacks (like in a case where I'd like to subset the df based on some input and pass it to...
The most common approach for sharing data between callbacks is to save the data in a dash_core_components.Store object, def serve_layout(): df = # Fetch data from DB store = Store(id="mystore", data=df.to_json()) # The store must be added to the layout return # Layout You can then add the store as a State argument for...
8
10
63,226,700
2020-8-3
https://stackoverflow.com/questions/63226700/overwrite-existing-files-with-pythons-wget
I have installed wget on my Python, and I'm downloading files from different URLs with it. So far my code looks like this: import wget urls = ['https://www.iedb.org/downloader.php?file_name=doc/epitope_full_v3.zip', 'https://www.iedb.org/downloader.php?file_name=doc/tcell_full_v3.zip', 'https://www.iedb.org/downloader....
Although wget doesn't mentioned that, you could change it by yourself.Use os.path.basename() to get the filename, and check whether it exists.Like this: import wget import os urls = ['https://www.iedb.org/downloader.php?file_name=doc/epitope_full_v3.zip', 'https://www.iedb.org/downloader.php?file_name=doc/tcell_full_v3...
7
8
63,200,201
2020-7-31
https://stackoverflow.com/questions/63200201/create-a-bigquery-table-from-pandas-dataframe-without-specifying-schema-explici
I have a pandas dataframe and want to create a BigQuery table from it. I understand that there are many posts asking about this question, but all the answers I can find so far require explicitly specifying the schema of every column. For example: from google.cloud import bigquery as bq client = bq.Client() dataset_ref ...
Here's a code snippet to load a DataFrame to BQ: import pandas as pd from google.cloud import bigquery # Example data df = pd.DataFrame({'a': [1,2,4], 'b': ['123', '456', '000']}) # Load client client = bigquery.Client(project='your-project-id') # Define table name, in format dataset.table_name table = 'your-dataset.yo...
13
20
63,217,735
2020-8-2
https://stackoverflow.com/questions/63217735/import-pyzbar-pyzbar-unable-to-find-zbar-shared-library
I want to make a script for detecting and reading QR codes from photos. I would like to use PyZbar for that, but I have a problem with some errors. I'm working in google colaboratory !sudo apt install tesseract-ocr !pip install pytesseract !pip install pyzbar[scripts] import shutil import os import random import re imp...
Before you can !pip install pyzbar, you need to install libzbar with this command. !apt install libzbar0 Then, pyzbar should work.
7
9
63,223,548
2020-8-3
https://stackoverflow.com/questions/63223548/pycharm-error-cannot-run-program-error-2-no-such-file-or-directory
I am getting the following error message when attempting to execute Python code in PyCharm: Cannot run program "/Users/x/.virtualenvs/untitled/bin/python" (in directory "/Users/x/PycharmProjects/untitled"): error=2, No such file or directory I made sure everything was updated and restarted my computer, but I still ge...
If it helps at all this is what my venv settings looks like. I don't have the answer as to why it happens, but I find its usually when renaming the project. In the past i've recreated the project and copied the project files directly from the old folder to the new one in a file explorer (not pycharm) and its fixed it.
12
4
63,221,997
2020-8-2
https://stackoverflow.com/questions/63221997/how-to-get-class-path-in-python
In Python, we can define a class and print it as such: class a: num = 1 b = a() print(b) And we would get the output: <class '__main__.a'> I'm trying to identify unique classes, and I have some classes with longer paths. I would like to extract the "class path", or __main__.a in the case above. For example, if I prin...
The __module__ attribute can be used to access the "path" of a class (where it was defined) and the __name__ attribute returns the name of the class as a string print(f'{YourClass.__module__}.{YourClass.__name__}')
8
13
63,218,987
2020-8-2
https://stackoverflow.com/questions/63218987/convert-x-escaped-string-into-readable-string-in-python
Is there a way to convert a \x escaped string like "\\xe8\\xaa\\x9e\\xe8\\xa8\\x80" into readable form: "語言"? >>> a = "\\xe8\\xaa\\x9e\\xe8\\xa8\\x80" >>> print(a) \xe8\xaa\x9e\xe8\xa8\x80 I am aware that there is a similar question here, but it seems the solution is only for latin characters. How can I convert this f...
Decode it first using 'unicode-escape', then as 'utf8': a = "\\xe8\\xaa\\x9e\\xe8\\xa8\\x80" decoded = a.encode('latin1').decode('unicode_escape').encode('latin1').decode('utf8') print(decoded) # 語言 Note that since we can only decode bytes objects, we need to transparently encode it in between, using 'latin1'.
7
14
63,201,014
2020-8-1
https://stackoverflow.com/questions/63201014/display-grouped-list-of-items-from-python-list-cyclically
I have an array, given number of items in a group and number of groups, I need to print the array cyclically in a loop. Array-[1,2,3,4,5,6] Group- 4 Iterations- 7 Output should be: ['1', '2', '3', '4'] ['5', '6', '1', '2'] ['3', '4', '5', '6'] ['1', '2', '3', '4'] ['5', '6', '1', '2'] ['3', '4', '5', '6'] ['1', '2', '3...
One solution is to combine itertools.cycle with itertools.slice. from itertools import cycle, islice def format_print(iterable, group_size, iterations): iterable = cycle(iterable) for _ in range(iterations): print(list(islice(iterable, 0, group_size))) format_print(range(1, 7), 4, 7) Output: [1, 2, 3, 4] [5, 6, 1, 2] ...
10
5
63,212,888
2020-8-2
https://stackoverflow.com/questions/63212888/sum-of-consecutive-pairs-in-a-list-including-a-sum-of-the-last-element-with-the
I have a list of elements like [1,3,5,6,8,7]. I want a list of sums of two consecutive elements of the list in a way that the last element is also added with the first element of the list. I mean in the above case, I want this list: [4,8,11,14,15,8] But when it comes to the addition of the last and the first element du...
List2 = [List1[i] + List1[(i+1)%len(List1)] for i in range (len(List1))]
7
4
63,207,734
2020-8-1
https://stackoverflow.com/questions/63207734/implementing-inplace-operations-for-methods-in-a-class
In pandas lot's of methods have the keyword argument inplace. This means if inplace=True, the called function will be performed on the object itself, and returns None, on the other hand if inplace=False the original object will be untouched, and the method is performed on the returned new instance. I've managed to impl...
If your method has return self, the following works: import copy def inplacify(method): def wrap(self,*a,**k): inplace = k.pop("inplace",True) if inplace: method(self,*a,**k) else: return method(copy.copy(self),*a,**k) return wrap class classy: def __init__(self,n): self.n=n @inplacify def func(self,val): self.n+=val r...
7
5
63,185,157
2020-7-31
https://stackoverflow.com/questions/63185157/can-i-make-my-custom-pytorch-modules-behave-differently-when-train-or-eval-a
According to the official documents, using train() or eval() will have effects on certain modules. However, now I wish to achieve a similar thing with my custom module, i.e. it does something when train() is turned on, and something different when eval() is turned on. How can I do this?
Yes, you can. As you can see in the source code, eval() and train() are basically changing a flag called self.training (note that it is called recursively): def train(self: T, mode: bool = True) -> T: self.training = mode for module in self.children(): module.train(mode) return self def eval(self: T) -> T: return self....
7
7
63,194,140
2020-7-31
https://stackoverflow.com/questions/63194140/how-to-sort-a-group-in-a-way-that-i-get-the-largest-number-in-the-first-row-and
So I have a df like this In [1]:data= {'Group': ['A','A','A','A','A','A','B','B','B','B'], 'Name': [ ' Sheldon Webb',' Traci Dean',' Chad Webster',' Ora Harmon',' Elijah Mendoza',' June Strickland',' Beth Vasquez',' Betty Sutton',' Joel Gill',' Vernon Stone'], 'Performance':[33,64,142,116,122,68,95,127,132,80]} In [2]:...
Take the sorted order and then apply a quadratic function to it where the root is 1/2 the length of the array (plus some small offset). This way the highest rank is given to the extremal values (the sign of the eps offset determines whether you want a the highest value ranked above the lowest value). I added a small gr...
8
4
63,194,917
2020-7-31
https://stackoverflow.com/questions/63194917/python-how-to-solve-oserror-errno-22-invalid-argument
I am learning about file objects in python but whenever i try to open file it shows the following error. I have already checked that file is in same directory and it exists this error occurs only if i name my file as test if i use any other name then it works fine here's my CODE f = open('C:\\Users\Tanishq\Desktop\pyth...
Your issue is with backslashing characters like \T : Try: f = open(r'C:\\Users\Tanishq\Desktop\python tutorials\test.txt', 'r') Python uses \ to denote special characters. Therefore, the string you provided does not actually truly represent the correct filepath, since Python will interpret \Tanishq\ differently than t...
10
14
63,191,845
2020-7-31
https://stackoverflow.com/questions/63191845/confusion-related-to-pythons-in-operator
I found strange behavior with Python's in operator d = {} 'k' in d == False # False! I thought it's because of precedence: ('k' in d) == False # True, it's okay 'k' in (d == False) # Error, it's also okay But, what precedence evaluates the following expression then? d = {} 'k' in d == False If it's because of wrong ...
in is considered a comparison operator, and so it is subject to comparison chaining. 'k' in d == False is equivalent to 'k' in d and d == False because both in and == are comparison operators. You virtually never need direct comparison to Boolean literals, though. The "correct" expression here is 'k' not in d. For r...
13
23
63,183,234
2020-7-31
https://stackoverflow.com/questions/63183234/trying-to-understand-init-py-combined-with-getattr
I am trying to understand a piece of Python code. First, I have the following file structure: folder1-- model __init__.py file1.py file2.py __init__.py The __init__.py in the folder folder1 has nothing. The __init__.py in the folder model has the following: import os files = os.listdir(os.path.split(os.path.realpath(_...
If you desire to have a folder as a python module, the folder must contain an __init__.py, even if it is empty. Then you can import the rest. import os files = os.listdir(os.path.split(os.path.realpath(__file__))[0]) #get the folder's content files.remove('__init__.py') #remove __init__.py since it is empty for file in...
7
5
63,184,392
2020-7-31
https://stackoverflow.com/questions/63184392/pandas-merge-and-keep-only-non-matching-records
How can I merge/join these two dataframes ONLY on "id". Produce 3 new dataframes: 1)R1 = Merged records 2)R2 = (DF1 - Merged records) 3)R3 = (DF2 - Merged records) Using pandas in Python. First dataframe (DF1) | id | name | |-----------|-------| | 1 | Mark | | 2 | Dart | | 3 | Julia | | 4 | Oolia | | 5 | Talia | Se...
You can turn on indicator in merge and look for the corresponding values: total_merge = df1.merge(df2, on='id', how='outer', indicator=True) R1 = total_merge[total_merge['_merge']=='both'] R2 = total_merge[total_merge['_merge']=='left_only'] R3 = total_merge[total_merge['_merge']=='right_only'] Update: Ben's suggesti...
6
14
63,162,731
2020-7-29
https://stackoverflow.com/questions/63162731/how-can-i-automate-slicing-of-a-dataframe-into-batches-so-as-to-avoid-memoryerro
I have a dataframe with 2.7 million rows as you see below- df Out[10]: ClaimId ServiceSubCodeKey ClaimRowNumber SscRowNumber 0 1902659 183 1 1 1 1902659 2088 1 2 2 1902663 3274 2 1 3 1902674 12 3 1 4 1902674 23 3 2 ... ... ... ... 2793010 2563847 3109 603037 4 2793011 2563883 3109 603038 1 2793012 2564007 3626 603039 1...
onehot = [] for groupi, group in df.groupby(df.index//1e5): # encode each group separately onehot.expand(group_onehot) df = df.assign(onehot=onehot) Will give you 28 groups to work on individually. However, looking at your code, the line: codes_values = [int(''.join(r)) for r in columns.itertuples(index=False)] Is cr...
7
2
63,179,049
2020-7-30
https://stackoverflow.com/questions/63179049/whats-the-purpose-of-the-new-method-int-as-integer-ratio-in-python-3-8
I was taking a look at the new features that were implemented in python 3.8, and I found out about a new function numerator, denominator = x.as_integer_ratio(). They state in the documentation that it Return a pair of integers whose ratio is exactly equal to the original integer and with a positive denominator. The in...
It appears the main reason for the changes were to implement uniformity, and typing for mypy, so that an int can be a subtype of float msg313780 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2018-03-13 21:25 Goal: make int() more interoperable with float by making a float/Decimal method al...
7
3
63,177,236
2020-7-30
https://stackoverflow.com/questions/63177236/how-to-calculate-signal-to-noise-ratio-using-python
Dear experts i have a data set.i just want to calculate signal to noise ratio of the data. data is loaded here https://i.fluffy.cc/jwg9d7nRNDFqdzvg1Qthc0J7CNtKd5CV.html my code is given below: import numpy as np from scipy import signaltonoise import scipy.io dat=scipy.io.loadmat('./data.mat') arr=dat['dn'] snr=scipy.s...
scipy.stats.signaltonoise was removed in scipy 1.0.0. You can either downgrade your scipy version or create the function yourself: def signaltonoise(a, axis=0, ddof=0): a = np.asanyarray(a) m = a.mean(axis) sd = a.std(axis=axis, ddof=ddof) return np.where(sd == 0, 0, m/sd) Source: https://github.com/scipy/scipy/blob/v...
8
12
63,166,479
2020-7-30
https://stackoverflow.com/questions/63166479/valueerror-validation-split-is-only-supported-for-tensors-or-numpy-arrays-fo
When I tried to add validation_split in my LSTM model, I got this error ValueError: `validation_split` is only supported for Tensors or NumPy arrays, found: (<tensorflow.python.keras.preprocessing.sequence.TimeseriesGenerator object) This is the code from keras.preprocessing.sequence import TimeseriesGenerator train_...
Your first intution is right that you can't use the validation_split when using dataset generator. You will have to understand how the functioninig of dataset generator happens. The model.fit API does not know how many records or batch your dataset has in its first epoch. As the data is generated or supplied for each b...
8
17
63,157,909
2020-7-29
https://stackoverflow.com/questions/63157909/how-to-determine-if-two-sentences-talk-about-similar-topics
I would like to ask you a question. Is there any algorithm/tool which can allow me to do some association between words? For example: I have the following group of sentences: (1) "My phone is on the table" "I cannot find the charger". # no reference on phone (2) "My phone is on the table" "I cannot find the phone's cha...
In Python I'm pretty sure you have a Sequence Matcher that you can usee from difflib import SequenceMatcher def similar(a, b): return SequenceMatcher(None, a, b).ratio() If you want your own algorithm I would suggest a Levenstains Distance (it calculates how many operations you need to turn one string(sentance) into a...
7
4
63,152,656
2020-7-29
https://stackoverflow.com/questions/63152656/installing-rdkit-in-google-colab
I cannot figure out how to fix the following issue. Up until today I was using the following code snippet for installing RDKit in Google Colab: !wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh !chmod +x Miniconda3-latest-Linux-x86_64.sh !time bash ./Miniconda3-latest-Linux-x86_64.sh -b -f ...
I think you need to specify python 3.7 when you install Miniconda (the current rdkit build supports python 3.7), the latest Miniconda version is py3.8: !wget -c https://repo.continuum.io/miniconda/Miniconda3-py37_4.8.3-Linux-x86_64.sh !chmod +x Miniconda3-py37_4.8.3-Linux-x86_64.sh !time bash ./Miniconda3-py37_4.8.3-Li...
6
3
63,156,252
2020-7-29
https://stackoverflow.com/questions/63156252/python-compare-two-sentence-by-words-using-difflib
Im using difflib and tried to compare the two sentence and get the difference. Somewhat like this. i have this code but instead of word by word it analyzed letter by letter. import difflib # define original text # taken from: https://en.wikipedia.org/wiki/Internet_Information_Services original = ["IIS 8.5 has several ...
If you remove the []'s from your strings, and call .split() on them in the .compare() perhaps you'll get what you want. import difflib # define original text # taken from: https://en.wikipedia.org/wiki/Internet_Information_Services original = "IIS 8.5 has several improvements related" # define modified text edited = "I...
6
15
63,153,629
2020-7-29
https://stackoverflow.com/questions/63153629/use-data-coords-for-x-axis-coords-for-y-for-text-annotations
From the documentation: The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes: >>> text(0.5, 0.5, 'matplotlib', horizontalalignment='center', ... verticalalignme...
This is known as a "blended transformation" you can create a blended transformation that uses the data coordinates for the x axis and axes coordinates for the y axis, like so: import matplotlib.transforms as transforms trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) In your minimal example: im...
19
21
63,145,532
2020-7-29
https://stackoverflow.com/questions/63145532/how-to-convert-ragged-tensor-to-tensor-in-python
I have a ragged tensor, and upon trying to create a model, and use model.fit(), I get an error: TypeError: Failed to convert object of type <class 'tensorflow.python.ops.ragged.ragged_tensor.RaggedTensor'> to Tensor. Contents: tf.RaggedTensor(values=Tensor("Cast_1:0", shape=(None,), dtype=float32), row_splits=Tensor("R...
Every RaggedTensor has an associated to_tensor() method, call that. Check your input data transformations, that is where the RaggedTensor is getting created. Some ops return RaggedTensor.
9
19
63,146,892
2020-7-29
https://stackoverflow.com/questions/63146892/how-to-load-a-keras-model-saved-as-pb
I'd like to load a keras model that i've trained and saved it as .pb. Here's the code, Am using a jupyter notebook. The model is successfully saved as saved_model.pb under the same directory. But the code is unable to access it. Can anybody see to it, how can i access this keras model that's saved in .pb extension....
The function tf.keras.models.load_model load a SavedModel into a tf.keras -model. The argument of the function is path to a saved model. So try model = tf.keras.models.load_model('model')
10
14
63,125,259
2020-7-28
https://stackoverflow.com/questions/63125259/what-is-the-proper-way-to-type-hint-the-return-value-of-an-asynccontextmanager
What is the proper way to add type hints for the return of a function with the @asynccontextmanager decorator? Here are two attempts I made that both fail. from contextlib import asynccontextmanager from typing import AsyncContextManager async def caller(): async with return_str() as i: print(i) async with return_Async...
You have to hint AsyncIterator as the return type, like this: @asynccontextmanager async def my_acm() -> AsyncIterator[str]: yield "this works" async def caller(): async with my_acm() as val: print(val) This is because the yield keyword is used to create generators. Consider: def a_number_generator(): for x in range(1...
16
17
63,107,594
2020-7-27
https://stackoverflow.com/questions/63107594/how-to-deal-with-multi-level-column-names-downloaded-with-yfinance
I have a list of tickers (tickerStrings) that I have to download all at once. When I try to use Pandas' read_csv it doesn't read the CSV file in the way it does when I download the data from yfinance. I usually access my data by ticker like this: data['AAPL'] or data['AAPL'].Close, but when I read the data from the CSV...
In dealing with financial data from multiple tickers, specifically using yfinance and pandas, the process can be broken down into a few key steps: downloading the data, organizing it in a structured format, and accessing it in a way that aligns with the user's needs. Below, the answer is organized into clear, actionabl...
13
42
63,135,648
2020-7-28
https://stackoverflow.com/questions/63135648/how-to-reorder-the-keys-of-a-dictionary
I have multiple dictionaries inside the list. I want to sort the dictionary with the custom key. In my case, I want to sort it using Date key. By that, I mean to move the Date key to the first position. What is the efficient way to sort the dictionary using Date key? PS: I don't want to sort by the value of the Date. [...
If you are using a Python version that preserves key insertion order (i.e. 3.7 or newer) you can do this: print([{"Date": di["Date"], **di} for di in my_list]) [ { 'Date': '2020-07-01', 'AmazonS3': 6.54, 'AmazonEC2': 27.55, 'AmazonCloudWatch': 0.51 }, { 'Date': '2020-07-02', 'AmazonEC2': 27.8 }, { 'Date': '2020-07-03...
7
9
63,085,356
2020-7-25
https://stackoverflow.com/questions/63085356/oserror-errno-30-read-only-file-system-user-macos-catalina
I was coding sorter for downloads folder. I'm getting this error, I tried to change permissions: chmod: Unable to change file mode on Users: Operation not permitted import os from_dir = os.path.dirname('/Users/user/Downloads/') working_dir = os.walk(from_dir) to_dir = os.path.dirname('/User/user/Downloads/New Folder/'...
That error message is bit misleading. In this case, the problem is that there is no /User directory on macOS. The directory is named /Users. In the following line to_dir = os.path.dirname('/User/user/Downloads/New Folder/') User should be Users to_dir = os.path.dirname('/Users/user/Downloads/New Folder/') What's happen...
14
7
63,059,979
2020-7-23
https://stackoverflow.com/questions/63059979/cannot-install-tensorflow-1-x
I am trying to install Tensorflow 1.14 for a package that I am trying to use. I tried: pip3 uninstall tensorflow Then I tried to install Tensorflow 1.14 using: pip3 install tensorflow==1.14 and I get the following error ERROR: Could not find a version that satisfies the requirement tensorflow==1.14 (from versions: 2.2....
What I've found on discourse: You just need to make sure you’re using Python 3.5, 3.6 or 3.7. TensorFlow 1.15 does not support Python 3.8
23
25
63,119,831
2020-7-27
https://stackoverflow.com/questions/63119831/how-to-solve-valueerror-operands-could-not-be-broadcast-together-with-shapes
I have to sum 2 arrays with broadcasting. This is the first: a = [0 1 2 3] And this is the second: A = [[ 0 1 2 3 4 5] [ 6 7 8 9 10 11] [12 13 14 15 16 17] [18 19 20 21 22 23]] This is the code I had tried until now: a = np.array(a) A = np.array(A) G = a + A print(G) But when I run, it throws this error: ValueError:...
Arrays need to have compatible shapes and same number of dimensions when performing a mathematical operation. That is, you can't add two arrays of shape (4,) and (4, 6), but you can add arrays of shape (4, 1) and (4, 6). You can add that extra dimension as follows: a = np.array(a) a = np.expand_dims(a, axis=-1) # Add a...
9
13
63,101,307
2020-7-26
https://stackoverflow.com/questions/63101307/does-python-3-8-2-have-ensurepip-do-i-need-to-install-ensurepip-to-use-it
I'm using python 3.8.2 on ubuntu on windows 10. I'm reading an OOP pdf and I'm at the third-party libraries section. It says that pip doesn't come with python, but python 3.4 contains a useful tool called ensurepip, which will install it: python -m ensurepip. But when I press enter, it says no module named ensurepip /u...
The module ensurepip is part of Python's standard library. It should be there. You say you're on Windows, but then you show /usr/bin/python3 in your question, which is obviously not a Windows path (rather Linux). My assumption is that you might be using WSL (or WSL2), which is actually Linux running on Windows (without...
8
26
63,108,452
2020-7-27
https://stackoverflow.com/questions/63108452/python-specify-type-with-multiple-bases-typing-and-operator
I understand (as explained in this question and the docs) that a type hint of X or Y can be expressed as: Union[X,Y] But how does one express a type hint of X and Y? This would be useful when expressing that the object in question must be a subclass of both X and Y. The following example works as long as all classes t...
Python type hints does not support explicit intersection annotation. But you have at least two workarounds: You could introduce a mix class, e.g: class A: def foo_a(self): pass class B: def foo_b(self): pass class Mix(A, B): pass def foo(p: Mix) -> None: p.foo_a() p.foo_b() Or use structural subtyping, Protocol, e.g.:...
11
11
63,084,049
2020-7-25
https://stackoverflow.com/questions/63084049/sslerrorcant-connect-to-https-url-because-the-ssl-module-is-not-available
In my Ubuntu 20.04. I am using two python versions. One of them is Python3.8.2 which came with my Ubuntu installation and another one is Python3.7.5. I installed Python3.7.5 using update-alternatives alongside the system default version. But now the problem is no pip command is working on Python3.7.5. Although pip is a...
TL;DR you're probably missing some system dependencies. sudo apt install build-essential zlib1g-dev libncurses5-dev libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev wget Read below for the full details on how we got there. The error states that the SSL python module is not available; meaning you either don...
15
22
63,105,799
2020-7-26
https://stackoverflow.com/questions/63105799/understanding-python-contextvars
Regarding the following SO answer . I've made some changes in order to understand the difference between do use Contextvars and don't. I expect at some point the variable myid gets corrupted but changing the range to a higher number seems doesn't affect at all. import asyncio import contextvars # declare context var re...
Context variables are convenient when you need to pass a variable along the chain of calls so that they share the same context, in the case when this cannot be done through a global variable in case of concurrency. Context variables can be used as an alternative to global variables both in multi-threaded code and in as...
24
46
63,136,177
2020-7-28
https://stackoverflow.com/questions/63136177/how-to-set-the-maximum-image-size-to-upload-image-in-django-ckeditor
I am using django-ckeditor for my project to upload image along with text content. I used body = RichTextUploadingField(blank=True, null=True) in model. Now I want to restrict the user to upload large size images in content or larger than predefined maximum height/width. I want the uploaded images in content of particu...
You can set CKEDITOR_THUMBNAIL_SIZE in setting.py CKEDITOR_THUMBNAIL_SIZE = (500, 500) With the pillow backend, you can change the thumbnail size with the CKEDITOR_THUMBNAIL_SIZE setting (formerly THUMBNAIL_SIZE). Default value: (75, 75) With the pillow backend, you can convert and compress the uploaded images to jpeg...
9
0
63,057,468
2020-7-23
https://stackoverflow.com/questions/63057468/how-to-ignore-and-initialize-missing-keys-in-state-dict
My saved state_dict does not contain all the layers that are in my model. How can I ignore the Missing key(s) in state_dict error and initialize the remaining weights?
This can be achieved by passing strict=False to load_state_dict. load_state_dict(state_dict, strict=False) Documentation
13
32
63,090,280
2020-7-25
https://stackoverflow.com/questions/63090280/i-cant-get-certain-guild-with-discord-py
I'm trying to take certain roles when bot starting. First i need to take guild but i couldn't achieve it. takenGuild = client.get_guild(myServerID) takenGuild returning None When i try to loop guilds for guild in client.guilds: print(guild.id) it's not printing anything. My whole code : import discord from discord.ex...
You have to wait for the bot to be ready you can use this. FYI bot is more common now after the updates than client import discord from discord.ext import commands, tasks from discord.utils import get bot = commands.Bot(command_prefix = '.') @bot.event async def on_ready(): print("I am running on " + bot.user.name) pri...
8
8
63,069,190
2020-7-24
https://stackoverflow.com/questions/63069190/how-to-capture-arbitrary-paths-at-one-route-in-fastapi
I'm serving React app from FastAPI by mounting app.mount("/static", StaticFiles(directory="static"), name="static") @app.route('/session') async def renderReactApp(request: Request): return templates.TemplateResponse("index.html", {"request": request}) by this React app get served and React routing also works fine at ...
Since FastAPI is based on Starlette, you can use what they call "converters" with your route parameters, using type path in this case, which "returns the rest of the path, including any additional / characers." See https://www.starlette.io/routing/#path-parameters for reference. If your react (or vue or ...) app is usi...
55
59
63,080,326
2020-7-24
https://stackoverflow.com/questions/63080326/could-not-find-module-atari-py-ale-interface-ale-c-dll-or-one-of-its-dependenc
I'm trying to work with the openai gym module but I get this error: >>> import atari_py Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Users\ssit5\AppData\Local\Programs\Python\Python38\lib\site-packages\atari_py\__init__.py", line 1, in <module> from .ale_python_interface import * File...
I was facing the same error. Fortunately, I was able to find one workaround. Follow this steps and you should be good to go. Download ale_c.dll from here. Copy it in C:\Users\Deep Raval\AppData\Local\Programs\Python\Python38\Lib\site-packages\atari_py\ale_interface (Your path can be different).
9
15
63,140,037
2020-7-28
https://stackoverflow.com/questions/63140037/how-to-remove-hidden-marks-from-images-using-python-opencv
I wanted to work on a small project to challenge my computer vision and image processing skills. I came across a project where I want to remove the hidden marks from the image. Hidden here refers to the watermarks that are not easily visible in rgb space but when you convert into hsv or some other space the marks becom...
I didn't find any answer that completely solved the question. I appreciate everyone's effort though (Thank you). I did something on my own and would like to share. It results in little quality loss (a little bluish blurriness) but successfully removes the watermarks. The solution is very simple but took time to analyze...
13
2
63,069,595
2020-7-24
https://stackoverflow.com/questions/63069595/how-to-transpile-python-compare-ast-nodes-to-c
Let's start by considering python3.8.5's grammar, in this case I'm interested to figure out how to transpile python Comparisons to c. For the sake of simplicity, let's assume we're dealing with a very little python trivial subset and we just want to transpile trivial Compare expressions: expr = Compare(expr left, cmpop...
An additional complication when converting Compare expressions is that you want to prevent sub-expressions that are used more than once after the split from being evaluated more than once, which is particularly important if there are side effects such as a function call. One could take the sub-expressions and declare t...
7
2
63,094,847
2020-7-26
https://stackoverflow.com/questions/63094847/how-to-scale-target-values-of-a-keras-autoencoder-model-using-a-sklearn-pipeline
I'm using sklearn pipelines to build a Keras autoencoder model and use gridsearch to find the best hyperparameters. This works fine if I use a Multilayer Perceptron model for classification; however, in the autoencoder I need the output values to be the same as input. In other words, I am using a StandardScalar instanc...
You can use TransformedTargetRegressor to apply arbitrary transformations on the target values (i.e. y) by providing either a function (i.e. using func argument) or a transformer (i.e. transformer argument). In this case (i.e. fitting an auto-encoder model), since you want to apply the same StandardScalar instance on t...
7
2
63,035,551
2020-7-22
https://stackoverflow.com/questions/63035551/how-to-scrape-all-topics-from-twitter
All topics in twitter can be found in this link I would like to scrape all of them with each of the subcategory inside. BeautifulSoup doesn't seem to be useful here. I tried using selenium, but I don't know how to match the Xpaths that come after clicking the main category. from selenium import webdriver from selenium....
To scrape all the main topics e.g. Arts & culture, Business & finance, etc using Selenium and python you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies: Using XPATH and text attribute: driver.get("https://twitter.com/i/flow/topics_select...
7
8
63,067,807
2020-7-24
https://stackoverflow.com/questions/63067807/sharing-array-of-objects-with-python-multiprocessing
For this question, I refer to the example in Python docs discussing the "use of the SharedMemory class with NumPy arrays, accessing the same numpy.ndarray from two distinct Python shells". A major change that I'd like to implement is manipulate array of class objects rather than integer values as I demonstrate below. i...
So, I did a bit of research (Shared Memory Objects in Multiprocessing) and came up with a few ideas: Pass numpy array of bytes Serialize the objects, then save them as byte strings to a numpy array. Problematic here is that One one needs to pass the data type from the creator of 'psm_test0' to any consumer of 'psm_tes...
10
3
63,078,267
2020-7-24
https://stackoverflow.com/questions/63078267/x-axis-in-matplotlib-print-random-numbers-instead-of-the-years
Im new in this Pandas and Matplotlib, I follow an example from a book and apparently it give me a warning "MatplotlibDeprecationWarning: The epoch2num function was deprecated in Matplotlib 3.3 and will be removed two minor releases later. base = dates.epoch2num(dt.asi8 / 1.0e9)" and the X value of axis change from year...
This was caused by a temporary bad interaction between Matplotlib and Pandas and is fixed in both projects. To work around until the new versions are available: plt.rcParams['date.epoch'] = '0000-12-31'
8
10
63,129,163
2020-7-28
https://stackoverflow.com/questions/63129163/how-can-i-correctly-include-a-path-dependency-in-pyproject-toml
I have 2 projects structured as below: /abc-lib / abc / __init__.py / main.py / pyproject.toml /abc-web-api / src / __init__.py / main.py / pyproject.toml I attempted to include abc-lib as a dependency in abc-web-api, thus having a abc-web-api/pyproject.toml as below: [tool.poetry] name = "abc-web-api" version = "0.0....
Your folder structure looks a bit weird. It looks like your prefer the "src" variant. So I would suggest the following: ./ ├── abc-lib │ ├── pyproject.toml │ └── src │ └── abc_lib │ ├── __init__.py │ └── main.py └── abc-web-api ├── pyproject.toml └── src └── abc_web_api ├── __init__.py └── main.py With this pyproject....
13
11
63,115,867
2020-7-27
https://stackoverflow.com/questions/63115867/isolation-forest-vs-robust-random-cut-forest-in-outlier-detection
I am examining different methods in outlier detection. I came across sklearn's implementation of Isolation Forest and Amazon sagemaker's implementation of RRCF (Robust Random Cut Forest). Both are ensemble methods based on decision trees, aiming to isolate every single point. The more isolation steps there are, the mor...
In part of my answers I'll assume you refer to Sklearn's Isolation Forest. I believe those are the 4 main differences: Code availability: Isolation Forest has a popular open-source implementation in Scikit-Learn (sklearn.ensemble.IsolationForest), while both AWS implementation of Robust Random Cut Forest (RRCF) are cl...
8
12
63,128,641
2020-7-28
https://stackoverflow.com/questions/63128641/weighted-average-of-pytorch-tensors
I have two Pytorch tensors of the form [y11, y12] and [y21, y22]. How do I get the weighted mean of the two tensors?
you can add two tensors using torch.add and then get the mean of output tensor using torch.mean assuming weight as 0.6 for tensor1 and 0.4 for tensor2 example: tensor1 = [y11, y12] * 0.6 # multiplying with weight tensor2 = [y21, y22] * 0.4 # multiplying with weight pt_addition_result_ex = tensor1.add(tensor2) # additio...
9
8
63,132,402
2020-7-28
https://stackoverflow.com/questions/63132402/how-to-combine-numeric-columns-in-pandas-dataframe-with-nan
I have a dataframe with this format: ID measurement_1 measurement_2 0 3 NaN 1 NaN 5 2 NaN 7 3 NaN NaN I want to combine to: ID measurement measurement_type 0 3 1 1 5 2 2 7 2 For each row there will be a value in either measurement_1 or measurement_2 column, not in both, the other column will be NaN. In some rows both...
Use DataFrame.stack to reshape the dataframe then use reset_index and use DataFrame.assign to assign the column measurement_type by using Series.str.split + Series.str[:1] on level_1: df1 = ( df.set_index('ID').stack().reset_index(name='measurement') .assign(mesurement_type=lambda x: x.pop('level_1').str.split('_').str...
12
12
63,109,897
2020-7-27
https://stackoverflow.com/questions/63109897/keyerror-requested-level-date-does-not-match-index-name-none
I got error while reshaping my dataframe data. KeyError: 'Requested level (date) does not match index name (None)' More details are as below: # dataframe # print(df.head(3)) ... account_id entity ae is_pc is_new_customer agency related_entity type medium our_side_entity settlement_title settlement_short_title settleme...
You are grouping by columns with all none values. In your example, the value for related_entity is None, which leads to an empty dataframe: In [7]: df.groupby(list(indices.keys())).sum() Out[7]: Empty DataFrame Columns: [] Index: [] I suggest that you remove this column from the groupby clause [EDIT]: to set the value...
7
5
63,127,402
2020-7-28
https://stackoverflow.com/questions/63127402/how-to-get-the-time-of-5-minutes-ago-in-python
I'm using python to get time of 5 minutes ago. Code: import datetime import time now = datetime.datetime.now() current_time = now.strftime(f"%Y-%m-%d %H:%M") print(current_time) 2020-07-27 08:35:00 My question is how to get the time of 5 minutes ago. something like current_time-5mins
You may use datetime.timedelta(): datetime.datetime.now() - datetime.timedelta(minutes=5)
18
28
63,109,987
2020-7-27
https://stackoverflow.com/questions/63109987/nameerror-name-mysql-is-not-defined-after-setting-change-to-mysql
I have a running Django blog with sqlite3 db at my local machine. What I want is to convert sqlite3 db to mysql db change Django settings.py file to serve MySQL db Before I ran into the first step, I jumped into the second first. I followed this web page (on MacOS). I created databases called djangolocaldb on root us...
So as a full answer: If you use the python package mysqlclient you still need to install the mysql client from Oracle/MySQL. This contains the C-library that the python package uses. To make things more confusing: the python package is in fact written in C for speed increases. To install this library on MacOS: % brew i...
40
14
63,109,860
2020-7-27
https://stackoverflow.com/questions/63109860/how-to-install-python-packages-for-spyder
I am using the IDE called Spyder for learning Python. I would like to know in how to go about in installing Python packages for Spyder?
step 1. First open Spyder and click Tools --> Open command prompt. For more details click visit this link, https://miamioh.instructure.com/courses/38817/pages/downloading-and-installing-packages
23
9
63,106,109
2020-7-26
https://stackoverflow.com/questions/63106109/how-to-display-graphs-of-loss-and-accuracy-on-pytorch-using-matplotlib
I am new to pytorch, and i would like to know how to display graphs of loss and accuraccy And how exactly should i store these values,knowing that i'm applying a cnn model for image classification using CIFAR10. here is my current implementation : def train(num_epochs,optimizer,criterion,model): for epoch in range(num...
What you need to do is: Average the loss over all the batches and then append it to a variable after every epoch and then plot it. Implementation would be something like this: import matplotlib.pyplot as plt def my_plot(epochs, loss): plt.plot(epochs, loss) def train(num_epochs,optimizer,criterion,model): loss_vals= []...
7
10
63,103,703
2020-7-26
https://stackoverflow.com/questions/63103703/calculate-min-and-max-value-of-a-transition-with-index-of-first-occurrence-in-pa
I have a DataFrame: df = pd.DataFrame({'ID':['a','b','d','d','a','b','c','b','d','a','b','a'], 'sec':[3,6,2,0,4,7,10,19,40,3,1,2]}) print(df) ID sec 0 a 3 1 b 6 2 d 2 3 d 0 4 a 4 5 b 7 6 c 10 7 b 19 8 d 40 9 a 3 10 b 1 11 a 2 I want to calculate how many times a transition has occurred. Here in the ID column a->b is c...
You have transitions of the form from -> to. 'transition_index' is based on the index of the "from" row, while the 'sec' aggregations are based on the value associated with the "to" row. We can shift the index and group on the ID and the shifted the ID, allowing us to use a single groupby with named aggregations to get...
10
10
63,101,601
2020-7-26
https://stackoverflow.com/questions/63101601/import-error-no-module-named-utils-when-using-pickle-load
I firstly dump some stuff into a pickle file using pickle.dump. in utils.load_data, my project hierarchy looks like this project1 -utils -__init__.py -load_data.py -data (other folder...) Then it outputs a pickle file into a data folder. Then I move the .pickle file to another project, the project hierarchy is project...
By default, unpickling will import any class that it finds in the pickle data. This means if you have pickled a custom class and you are unpickling it somewhere, pickle will try import the module (utils in this case). So you need to have the utils module inside project2 folder Follow this for more information
6
10
63,103,090
2020-7-26
https://stackoverflow.com/questions/63103090/how-do-i-count-specific-values-across-multiple-columns-in-pandas
I have the DataFrame df = pd.DataFrame({ 'colA':['?',2,3,4,'?'], 'colB':[1,2,'?',3,4], 'colC':['?',2,3,4,5] }) I would like to get the count the the number of '?' in each column and return the following output - colA - 2 colB - 1 colC - 1 Is there a way to return this output at once. Right now the only way I know how...
looks like the simple way is df[df == '?'].count() the result is colA 2 colB 1 colC 1 dtype: int64 where df[df == '?'] give us DataFrame with ? and Nan colA colB colC 0 ? NaN ? 1 NaN NaN NaN 2 NaN ? NaN 3 NaN NaN NaN 4 ? NaN NaN and the count non-NA cells for each column. Please, look on the other solutions: good re...
6
10
63,101,913
2020-7-26
https://stackoverflow.com/questions/63101913/unable-to-parse-string-at-position-0-problem
I use """Data taken from https://datos.gob.mx/busca/organization/conapo and https://es.wikipedia.org/wiki/Anexo:Entidades_federativas_de_M%C3%A9xico_por_superficie,_poblaci%C3%B3n_y_densidad """ total_population_segmentation = pd.read_html('professional_segmentation_mexico.html') population_segmentation = pd.read_html(...
it looks like you’ve got [NO-BREAK SPACE][1] character xa0 You should normalize your data first & convert it from string to integer. One way to do this is (this is just for one column) is like that: $ df = pd.DataFrame([ {'Entidad':'BajaCaliforniaSur', '2010': '3\xa0224\xa0884', '2015': '763\xa0321', '2030': '763\xa032...
7
2
63,096,810
2020-7-26
https://stackoverflow.com/questions/63096810/python-destructor-called-in-the-wrong-order-based-on-reference-count
As far as I understand Python destructors should be called when the reference count of an object reaches 0. But this assumption seems not to be correct. Look at the following code: class A: def __init__(self, b): self.__b = b print("Construct A") def __del__(self): # It seems that the destructor of B is called here. pr...
So, since the objects are still alive when the interpreter shuts down, you are actually not even guaranteed that __del__ will be called. At this point, the language makes no guarantees about when the finalizer is called. From the docs: It is not guaranteed that __del__() methods are called for objects that still exist...
9
6
63,094,078
2020-7-25
https://stackoverflow.com/questions/63094078/pandas-drop-duplicate-rows-including-index
I know how to drop duplicate rows based on column data. I also know how to drop dublicate rows based on row index. My question is: is there a way to drop duplicate rows based on index and one column? Thanks!
This can be done by turning the index into a column. Below is a sample data set (fyi, I think someone downvoted your question because it didn't include a sample data set): df=pd.DataFrame({'a':[1,2,2,3,4,4,5], 'b':[2,2,2,3,4,5,5]}, index=[0,1,1,2,3,5,5]) Output: a b 0 1 2 1 2 2 1 2 2 2 3 3 3 4 4 5 4 5 5 5 5 Then you...
7
6
63,093,045
2020-7-25
https://stackoverflow.com/questions/63093045/keras-softmax-output-and-accuracy
This is the last layer of a Keras model. model.add(Dense(3, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) I know that the output of the softmax layer is an array, with probability summing up to 1, such as [0.1, 0.4, 0.5]. I have one question about using a...
e.g., when the true class is [0, 0, 1] and predicted probability is [0.1, 0.4, 0.5], even if 0.5 is the largest probability, the accuracy of this prediction should be 0, because 0.5 != 1. Is that correct? No. You treat the index with the maximum value as the prediction of the model. So in your example, this sample pr...
8
6
63,087,188
2020-7-25
https://stackoverflow.com/questions/63087188/can-you-run-google-colab-on-your-local-computer
My PC is rocking a 2080TI so I don't really need the GPU computation of Google Colab, but I do find it a nice development environment (in comparison to jupyter notebooks) and I like the fact that I can access my files from anywhere, so, is it possible to use Google Colab but let my local pc do the computation?
Steps: Go to Google colab and click on connect to local runtime, a pop-up comes. Go to your terminal and execute: jupyter notebook --NotebookApp.allow_origin='https://colab.research.google.com' --port=8888 --NotebookApp.port_retries=0 If this shows error: ERROR: the notebook server could not be started because po...
10
9
63,076,512
2020-7-24
https://stackoverflow.com/questions/63076512/how-to-set-a-help-message-for-a-flask-command-group
I'm trying to adapt an example from Flask documentation to create a custom command in a group: import click from flask import Flask from flask.cli import AppGroup app = Flask(__name__) user_cli = AppGroup('user') @user_cli.command('create') @click.argument('name') def create_user(name): ... app.cli.add_command(user_cli...
Use the short_help parameter. AppGroup inherits from Group which inherits from MultiCommand which inherits from Command. See Click source code for Command. For example: import click from flask import Flask from flask.cli import AppGroup user_cli = AppGroup('user', short_help="Adds a user") @user_cli.command('create') @...
10
5
63,068,639
2020-7-24
https://stackoverflow.com/questions/63068639/valueerror-unknown-layer-functional
I made a CNN in colab and saved the models at every epoch. I exported the h5 file and now am trying to run the model on some test images. Here's the main error: ValueError: Unknown layer: Functional Here's the code I used to run the model and save at each epoch: epochs = 50 callbacks = [ tf.keras.callbacks.TensorBoard...
Rebuilt the network from scratch: image_size = (212, 212) batch_size = 32 data_augmentation = keras.Sequential( [ layers.experimental.preprocessing.RandomFlip("horizontal_and_vertical"), layers.experimental.preprocessing.RandomRotation(0.8), ] ) def make_model(input_shape, num_classes): inputs = keras.Input(shape=input...
24
9
63,068,332
2020-7-24
https://stackoverflow.com/questions/63068332/does-pytorch-allow-to-apply-given-transformations-to-bounding-box-coordinates-of
In Pytorch, I know that certain image processing transformations can be composed as such: import torchvision.transforms as transforms transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) In my case, each image has a corresponding annotation of bounding box co...
The transformations that you used as examples do not change the bounding box coordinates. ToTensor() converts a PIL image to a torch tensor and Normalize() is used to normalize the channels of the image. Transformations such as RandomCrop() and RandomRotation() will cause a mismatch between the location of the bounding...
7
6
63,065,134
2020-7-24
https://stackoverflow.com/questions/63065134/how-to-reference-self-in-dataclass-fields
I am trying to do the equivalent of: class A: def __init__(self): self.b = self.get_b() def get_b(self): return 1 using @dataclass. I want to use a @dataclass here because there are other (omitted) fields initialized from provided constructor arguments. b is one of the fields that is initialized from an instance metho...
Use the __post_init__ method. from dataclasses import dataclass, field @dataclass class A: b: int = field(init=False) def __post_init__(self): self.b = self.get_b() Not exactly an improvement, is it? The default value assigned to a field is equivalent to a default parameter value in __init__, e.g., def __init__(self, ...
12
12
63,061,398
2020-7-23
https://stackoverflow.com/questions/63061398/all-arguments-should-have-the-same-length-plotly
I try to do a bar graph using plotly.express but I find this problem All arguments should have the same length. The length of argument y is 51, whereas the length of previously-processed arguments ['x'] is 4399 and this my code import pandas as pd import plotly.express as px df= pd.read_csv('...../datasets-723010-125...
df['state'] has all the rows from the dataframe while c only contains a row for each unique value of state. you should use c.index instead: px.bar(y=c, x=c.index)
7
3
63,057,939
2020-7-23
https://stackoverflow.com/questions/63057939/altair-create-a-mark-line-chart-with-a-max-min-band-similar-to-mark-errorband
I've been working to create a chart similar to this EIA Chart (data at linked page): I've seen a similar example using Altair in the line chart with confidence interval band gallery example but I do not see a way to explicitly set the "extent" with my own values using the mark_errorband method. The documentation provi...
You can use an area mark with the y and y2 encodings. For example: import altair as alt import pandas as pd import numpy as np x = np.linspace(0, 10) y = np.sin(x) + 0.1 * np.random.randn(len(x)) df = pd.DataFrame({ 'x': x, 'y': y, 'upper': y + 0.5 * (1 + np.random.rand(len(x))), 'lower': y - 0.5 * (1 + np.random.rand(...
8
12