content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
How to pad edge with black color (0 value) in affine registration using SimpleITK
I used SimpleITK to do affine registration and find that after transform the moving image was scaled smaller than its original size while the edge was padded with gray color. How to pad the edge with black color (0 value) instead?
Th... | How to pad edge with black color (0 value) in affine registration using SimpleITK | I used SimpleITK to do affine registration and find that after transform the moving image was scaled smaller than its original size while the edge was padded with gray color. How to pad the edge with black color (0 value) instead?
The output I got:
Moved Image
The output I want:
Expected Moved Image
# Read moving and f... | [
"You have the default pixel value set to 100 in the resampled. That's your grey. If you set it to 0, you'll get the black background you want.\n"
] | [
0
] | [] | [] | [
"affinetransform",
"padding",
"python",
"registration",
"simpleitk"
] | stackoverflow_0074621536_affinetransform_padding_python_registration_simpleitk.txt |
Q:
Could not load dynamic library 'cudnn64_8.dll'; dlerror: cudnn64_8.dll not found
Using tensorflow 2.4.1
When I run my program, I'm getting this error and can't use my gpu.
I'm using CUDA 11.0, cudnn 8.0
2021-02-07 03:36:18.132005: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened ... | Could not load dynamic library 'cudnn64_8.dll'; dlerror: cudnn64_8.dll not found | Using tensorflow 2.4.1
When I run my program, I'm getting this error and can't use my gpu.
I'm using CUDA 11.0, cudnn 8.0
2021-02-07 03:36:18.132005: I tensorflow/stream_executor/platform/default/dso_loader.cc:49] Successfully opened dynamic library cudart64_110.dll
WARNING:tensorflow:From D:/PycharmProjects/pythonProj... | [
"I think I can help you with providing a cudnn64_8.dll file (this is the download link: https://www.dll-files.com/cudnn64_8.dll.html). When you get the file, you can just put in your bin directory. For example, usually in windows platform, you can put it into C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v... | [
24,
19,
9,
5,
1,
0,
0,
0
] | [] | [] | [
"python",
"tensorflow"
] | stackoverflow_0066083545_python_tensorflow.txt |
Q:
Can't import module - python (unknown location)
EDIT: I was able to get the modules to work by doing import google.cloud.bigquery instead of from google.cloud import BigQuery - But I am not sure why that is....
I am trying to connect to BigQuery using python for my first time ever. I looked on here for answers but... | Can't import module - python (unknown location) | EDIT: I was able to get the modules to work by doing import google.cloud.bigquery instead of from google.cloud import BigQuery - But I am not sure why that is....
I am trying to connect to BigQuery using python for my first time ever. I looked on here for answers but I tried all answers I saw with no avail (Which my st... | [
"\nTo install the library, execute: pip install google-cloud\nAlthough\nthe documentation mentions 'BigQuery', the case-sensitive spelling to\nuse in the code is bigquery as in from google.cloud import bigquery\n\nOne thing annoying about python documentations in many libraries is that the internals (e.g., bigquery... | [
1
] | [] | [] | [
"google_bigquery",
"python",
"python_import"
] | stackoverflow_0074621095_google_bigquery_python_python_import.txt |
Q:
How do I represent a string as a number?
I need to represent a string as a number, however it is 8928313 characters long, note this string can contain more than just alphabet letters, and I have to be able to convert it back efficiently too. My current (too slow) code looks like this:
alpha = 'abcdefghijklmnopqrst... | How do I represent a string as a number? | I need to represent a string as a number, however it is 8928313 characters long, note this string can contain more than just alphabet letters, and I have to be able to convert it back efficiently too. My current (too slow) code looks like this:
alpha = 'abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ,.?!@()+-=[]/... | [
"Ok, since other people are giving awful answers, I'm going to step in.\n\nYou shouldn't do this.\nYou shouldn't do this.\nAn integer and an array of characters are ultimately the same thing: bytes. You can access the values in the same way.\nMost number representations cap out at 8 bytes (64-bits). You're looking ... | [
2,
1,
0,
0,
0
] | [] | [] | [
"numbers",
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0044833017_numbers_python_python_2.7_python_3.x.txt |
Q:
How to remove tuples in a list of tuples when the value of the first tuple in contained in an other list?
I have a list containing tuples and I would like to remove tuples that contain words in the first position of the tuple based on words from a second list.
list_of_tuples = [
("apple",2),
("banana",54),
("flow... | How to remove tuples in a list of tuples when the value of the first tuple in contained in an other list? | I have a list containing tuples and I would like to remove tuples that contain words in the first position of the tuple based on words from a second list.
list_of_tuples = [
("apple",2),
("banana",54),
("flower", 5),
("apple",4),
("fruit", 3)
]
list_of_words = [
"apple",
"banana"
]
The final result should look li... | [
"This code will do the trick:\nlist_of_tuples = [\n (\"apple\", 2),\n (\"banana\", 54),\n (\"flower\", 5),\n (\"apple\", 4),\n (\"fruit\", 3)\n]\n\nlist_of_words = [\n \"apple\",\n \"banana\"\n]\n\nfinal_list_of_tuples = [tup for tup in list_of_tuples if tup[0] not in list_of_words]\n\nprint(fi... | [
1,
0
] | [] | [] | [
"python",
"tuples"
] | stackoverflow_0074621520_python_tuples.txt |
Q:
Can overlapping matches with the same start position be found using regex?
I am looking for a regex or a regex flag in python/BigQuery that enables me to find overlapping occurrences.
For example, I have the string 1.2.5.6.8.10.12
and I would like to extract:
[1., 1.2., 1.2.5., 1.2.5.6., ..., 1.2.5.6.8.10.12]
I tr... | Can overlapping matches with the same start position be found using regex? | I am looking for a regex or a regex flag in python/BigQuery that enables me to find overlapping occurrences.
For example, I have the string 1.2.5.6.8.10.12
and I would like to extract:
[1., 1.2., 1.2.5., 1.2.5.6., ..., 1.2.5.6.8.10.12]
I tried running the python code
re.findall("^(\d+(?:\.|$))+", string)
and it resulte... | [
"While the regex parser walks down the string each position gets consumed. To extract substrings with the same starting position it would be needed to look behind and capture matches towards start. Capturing overlapping matches needs to be done inside a lookaround for not consuming the captured parts. Python re doe... | [
0,
0
] | [] | [] | [
"findall",
"google_bigquery",
"python",
"python_3.x",
"regex"
] | stackoverflow_0074618335_findall_google_bigquery_python_python_3.x_regex.txt |
Q:
Encrypting and Decrypting with python and nodejs
I'm trying to encrypt some content in Python and decrypt it in a nodejs application.
I'm struggling to get the two AES implementations to work together though. Here is where I am at.
In node:
var crypto = require('crypto');
var password = 'aaaaaaaaaaaaaaaaaaaaaaaaa... | Encrypting and Decrypting with python and nodejs | I'm trying to encrypt some content in Python and decrypt it in a nodejs application.
I'm struggling to get the two AES implementations to work together though. Here is where I am at.
In node:
var crypto = require('crypto');
var password = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
var input = 'hello world';
var encrypt = fu... | [
"OK, I've figured it out, node uses OpenSSL which uses PKCS5 to do padding. PyCrypto doesn't handle the padding so I was doing it myself just add ' ' in both.\nIf I add PKCS5 padding in the python code and remove the padding in the node code, it works.\nSo updated working code.\nNode:\nvar crypto = require('crypto'... | [
27,
3,
0,
0
] | [] | [] | [
"aes",
"encryption",
"node.js",
"python"
] | stackoverflow_0010548973_aes_encryption_node.js_python.txt |
Q:
Extract part of string based on a template in Python
I'd like to use Python to read in a list of directories and store data in variables based on a template such as /home/user/Music/%artist%/[%year%] %album%.
An example would be:
artist, year, album = None, None, None
template = "/home/user/Music/%artist%/[%year%... | Extract part of string based on a template in Python | I'd like to use Python to read in a list of directories and store data in variables based on a template such as /home/user/Music/%artist%/[%year%] %album%.
An example would be:
artist, year, album = None, None, None
template = "/home/user/Music/%artist%/[%year%] %album%"
path = "/home/user/Music/3 Doors Down/[2002] Aw... | [
"If your folder structure template is reliable the following should work without the need for regular expressions.\npath = \"/home/user/Music/3 Doors Down/[2002] Away From The Sun\"\n\npath_parts = path.split(\"/\") # divide up the path into array by slashes\n\nprint(path_parts) \n\nartist = path_parts[4] # get el... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074023028_python.txt |
Q:
How To Display Popup Message in Python
Currently have two functions, one to display for a win and one for a loss. I think I have it coded to where a popup occurs with a message and a button, but not exactly how I want it to be. I want the pop up to come up in the center of the screen, make the button larger, as we... | How To Display Popup Message in Python | Currently have two functions, one to display for a win and one for a loss. I think I have it coded to where a popup occurs with a message and a button, but not exactly how I want it to be. I want the pop up to come up in the center of the screen, make the button larger, as well as the popup. Any help is appreciated.
Th... | [
"The following code should resize your popup window and the button, I suppose you had problems with defining height and width beacuse of imports done as following:\nimport tkinter as tk # popup window\nfrom tkinter import ttk # popup window\n\nIn this code snippet second import is redundant and you should probbab... | [
0
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0074621603_python_tkinter_user_interface.txt |
Q:
Why does Anaconda install pytorch cpuonly when I install cuda?
I have created a Python 3.7 conda virtual environment and installed the following packages using this command:
conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch
They install fine, but then when I come to r... | Why does Anaconda install pytorch cpuonly when I install cuda? | I have created a Python 3.7 conda virtual environment and installed the following packages using this command:
conda install pytorch torchvision torchaudio cudatoolkit=11.3 matplotlib scipy opencv -c pytorch
They install fine, but then when I come to run my program I get the following error which suggests that a CUDA e... | [
"I ran into a similar problem when I tried to install Pytorch with CUDA 11.1. Although the anaconda site explicitly lists a pre-built version of Pytorch with CUDA 11.1 is available, conda still tries to install the cpu-only version. After a lot of trial-and-fail, I realize that the packages torchvision torchaudio a... | [
5,
1,
0,
0
] | [] | [] | [
"anaconda",
"conda",
"python",
"pytorch"
] | stackoverflow_0071162459_anaconda_conda_python_pytorch.txt |
Q:
Step Counter Python Lab
I'm trying to solve this programming problem in Python:
A pedometer treats walking 1 step as walking 2.5 feet. Define a function named feet_to_steps that takes a float as a parameter, representing the number of feet walked, and returns an integer that represents the number of steps walked.
... | Step Counter Python Lab | I'm trying to solve this programming problem in Python:
A pedometer treats walking 1 step as walking 2.5 feet. Define a function named feet_to_steps that takes a float as a parameter, representing the number of feet walked, and returns an integer that represents the number of steps walked.
Then, write a main program th... | [
"Your code is mostly fine, however, you are converting the answer from a float to an int too late in your code (outside of the feet_to_steps function). Try replacing return steps_walked with return int(steps_walked)\nLastly, if__name__=='main': is a way of telling Python to only run the next block of code if it is ... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0070372208_python.txt |
Q:
mypy complains about extended base class' attribute type
I have two base classes A and B that are defined like this:
class A(object):
def common_function(self):
pass
class B(object):
def __init__(self, a: A):
self.a = a
def another_common_function(self):
pass
Class A holds some... | mypy complains about extended base class' attribute type | I have two base classes A and B that are defined like this:
class A(object):
def common_function(self):
pass
class B(object):
def __init__(self, a: A):
self.a = a
def another_common_function(self):
pass
Class A holds some management information, whereas class B holds some other info... | [
"It is possible to ensure that self.a is of type dA by using assert:\nclass dB(B):\n def __init__(self, a: dA):\n super(A, self).__init__(a)\n def do(self):\n assert isinstance(self.a, dA)\n if self.a.t is None:\n print(\"something\")\n\nThis assert is recognized by mypy, so th... | [
1,
0
] | [] | [] | [
"derived_class",
"mypy",
"python",
"typechecking"
] | stackoverflow_0056479404_derived_class_mypy_python_typechecking.txt |
Q:
How to get a subproject from commit list
I'm trying to get all the commits from a GitLab repository, and it was all going smoothly and fine.
Because of another unrelated problem, I had to update my python from 3.7 to 3.9. Since then, every time I run my program I run this specific error:
Exception has occurred: V... | How to get a subproject from commit list | I'm trying to get all the commits from a GitLab repository, and it was all going smoothly and fine.
Because of another unrelated problem, I had to update my python from 3.7 to 3.9. Since then, every time I run my program I run this specific error:
Exception has occurred: ValueError
SHA b'7e944e65ee1a628e7ba0d53aac7a7b... | [
"A \"subproject commit\" (as printed this way by Git itself) is actually a gitlink, which is a very specific kind of item stored in one of two places:\n\nin Git's index, as a path name and mode 160000 plus a hash ID; or\nin a tree object, as a component name, mode 160000, and hash ID.\n\nThe hash ID in this case is... | [
1
] | [] | [] | [
"git",
"gitlab",
"python",
"repository",
"sha"
] | stackoverflow_0074616438_git_gitlab_python_repository_sha.txt |
Q:
Different strategies of memoization lead to vastly different runtime
I was trying to solve leetcode problem 416 - https://leetcode.com/problems/partition-equal-subset-sum/description/
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that th... | Different strategies of memoization lead to vastly different runtime | I was trying to solve leetcode problem 416 - https://leetcode.com/problems/partition-equal-subset-sum/description/
Given a non-empty array nums containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
I encountered some interestin... | [
"You forgot to stop recursing if you overshoot the target.\nUnrelated: note that some of the \"solutions\" in that solution link don't actually work. For example \"solution\" 3 fails on input [100, 125, 185, 60, 195, 25], because the memoization logic is broken - memoizing the index as well as the subset sum really... | [
1
] | [] | [] | [
"algorithm",
"python",
"recursion"
] | stackoverflow_0074621729_algorithm_python_recursion.txt |
Q:
import module from s3 in sagemaker
I have a .py file in an s3 bucket which I am trying to load in as a python module within Sagemaker
I've tried adding the file path to the sys path with:
sys.path.append('foo')
but get an error with :
import bar.py
I can read the py file with:
pd.read_csv('foo/bar.py')
but get... | import module from s3 in sagemaker | I have a .py file in an s3 bucket which I am trying to load in as a python module within Sagemaker
I've tried adding the file path to the sys path with:
sys.path.append('foo')
but get an error with :
import bar.py
I can read the py file with:
pd.read_csv('foo/bar.py')
but get an error with:
open('foo/bar.py)
Pleas... | [
"You can first download the from S3:\nimport os\nos.system(\"aws s3 cp s3://<S3location> .\")\n\nThen you can import the file.\n"
] | [
0
] | [] | [] | [
"amazon_s3",
"amazon_sagemaker",
"python",
"python_module"
] | stackoverflow_0074602697_amazon_s3_amazon_sagemaker_python_python_module.txt |
Q:
I have 2 dataframes. The first main dataframe has a column missing information that the second contains. I just need to add missing column to first
I am trying to move information from one dataframe to add to the main dataframe. They look like this
DF1 = |Year | V1 | V2 | V3 | V4 |
|--------------------... | I have 2 dataframes. The first main dataframe has a column missing information that the second contains. I just need to add missing column to first | I am trying to move information from one dataframe to add to the main dataframe. They look like this
DF1 = |Year | V1 | V2 | V3 | V4 |
|-----------------------------|
|2023 | X0 | Y0 | Z0 | A0 |
|2022 | X1 | Y1 | Z1 | A1 |
|2021 | X2 | Y2 | Z2 | A2 |
|2020 | NAN | Y3 | Z3 | ... | [
"here is one way to do it using map\n# map the value of V1 from DF2 based on year.\n# fill null mapping result with value from the DF\n\ndf['V1']=df['Year'].map(df2.set_index('Year')['V1']).fillna(df['V1'])\ndf\n\nYear V1 V2 V3 V4\n0 2023 X0 Y0 Z0 A0\n1 2022 X1 Y1 Z1 A1\n2 2021 X2 Y2 Z2... | [
1
] | [] | [] | [
"concatenation",
"join",
"merge",
"pandas",
"python"
] | stackoverflow_0074621808_concatenation_join_merge_pandas_python.txt |
Q:
Automate the execution of a .ipynb file in AWS SageMaker by Websocket
I have an issue. At November 10th before, my lambda code use websocket to communicate sagemaker which is okay to automatic execution of a .ipynb file. The code is below
import boto3
import time
from botocore.vendored import requests
import webso... | Automate the execution of a .ipynb file in AWS SageMaker by Websocket | I have an issue. At November 10th before, my lambda code use websocket to communicate sagemaker which is okay to automatic execution of a .ipynb file. The code is below
import boto3
import time
from botocore.vendored import requests
import websocket
def lambda_handler(event, context):
sm_client = boto3.client('sag... | [
"You could look at automating your notebook using SageMaker Processing Jobs.\nKindly see this blog post here: https://aws.amazon.com/blogs/machine-learning/scheduling-jupyter-notebooks-on-sagemaker-ephemeral-instances/\n"
] | [
0
] | [] | [] | [
"amazon_sagemaker",
"amazon_web_services",
"python",
"websocket"
] | stackoverflow_0074597843_amazon_sagemaker_amazon_web_services_python_websocket.txt |
Q:
How can i delete a couple lines of text that I inputted into a text file in python?
I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file... | How can i delete a couple lines of text that I inputted into a text file in python? | I am making a small simple password manager in python. I have the functions of creating an account which has 3 inputs, Username, Password, and Website. I have a function to view all the accounts which shows the contents of the file info.txt where all that information goes. Im trying to create a function to delete an en... | [
"Firstly, you're using the wrong tool for the problem. A good library to try is pandas, using .csv files (which one can think of as pore program oriented excel files). However, if you really want to use the text file based approach, your solution would look something like this:\nwith open(textfile, 'r+') as f:\n ... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074621844_python_python_3.x.txt |
Q:
Wrong attribution to second condition in permutation
I want my code to print:
Backflip Complete
Backflip Hyper
180 Round Complete
180 Round Mega
Gumbi Complete
But it insteat prints:
Backflip Complete
Backflip Hyper
180 Round Complete
180 Round Hyper
Gumbi Complete
Gumbi Hyper
It looks like it only takes the fir... | Wrong attribution to second condition in permutation | I want my code to print:
Backflip Complete
Backflip Hyper
180 Round Complete
180 Round Mega
Gumbi Complete
But it insteat prints:
Backflip Complete
Backflip Hyper
180 Round Complete
180 Round Hyper
Gumbi Complete
Gumbi Hyper
It looks like it only takes the first if argument for landing in def landings(tricks), so all... | [
"You could eliminate most of your variables since there is little point in having one variable for each string. You could also forget about itertools since you really don't want a product at all. Furthermore, the function landings can be replaced by a dictionary of the same name (the fact that you made landings a f... | [
0
] | [] | [] | [
"function",
"loops",
"permutation",
"python"
] | stackoverflow_0074621799_function_loops_permutation_python.txt |
Q:
How to properly use a dictionary?
This function was built in to try and know how to use a dictionary properly.
dict(d, 'bonjour')
hello
Unknown
Unknown
Unknown
It returns hello, and then Unknown. Why? It should only return hello. Help would be appreciated!
Thanks,
A:
def dict(d,s):
s = s.lower()
for e... | How to properly use a dictionary? | This function was built in to try and know how to use a dictionary properly.
dict(d, 'bonjour')
hello
Unknown
Unknown
Unknown
It returns hello, and then Unknown. Why? It should only return hello. Help would be appreciated!
Thanks,
| [
"def dict(d,s):\n\n s = s.lower()\n\n for e,f in d.items():\n if s == e:\n print (f) \n return\n elif s == f:\n print (e)\n return\n print ('Unknown')\n\n \nd = {\"hello\":\"bonjour\",\"Goodbye\":\"aurevoir\",\"eat\":\"mange\",\"world\":\... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074621877_python.txt |
Q:
Get all children of self-referencing Django model in nested hierarchy
Introduction
We’re currently working on a Django REST Framework project. It connects to a Postgres database that holds some hierarchical (tree structure) data, that goes a number of levels deep. We should offer an endpoint for GET requests that ... | Get all children of self-referencing Django model in nested hierarchy | Introduction
We’re currently working on a Django REST Framework project. It connects to a Postgres database that holds some hierarchical (tree structure) data, that goes a number of levels deep. We should offer an endpoint for GET requests that returns the entire nested tree structure (parent, children, grandchildren e... | [
"You can use depth attribute on your serializer ie\nclass Meta:\n model = Model\n fields = ['id', 'region', 'children', 'parent']\n depth = 2\n\nOr use to_representation method on your serializer:\ndef to_representation(self, instance):\n self.fields['parent'] = SerializerClass(many=False, read_only... | [
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_viewsets",
"python"
] | stackoverflow_0074074768_django_django_models_django_rest_framework_django_viewsets_python.txt |
Q:
List to dataframe conversion
Having data as below:
my_list=[(B_BC,0.3140561085683502, 0.27612272457883213)
(BR_BR,0.1968307181527823, 0.18806346643096217)]
I need to convert this to data frame with 3 column. First Column with location and second and third column should be a and b.
Expected Output
A:
I am assumi... | List to dataframe conversion | Having data as below:
my_list=[(B_BC,0.3140561085683502, 0.27612272457883213)
(BR_BR,0.1968307181527823, 0.18806346643096217)]
I need to convert this to data frame with 3 column. First Column with location and second and third column should be a and b.
Expected Output
| [
"I am assuming you are using Python, then this would work:\nmy_list = [('B_BC',0.3140561085683502, 0.27612272457883213),\n('BR_BR',0.1968307181527823, 0.18806346643096217)]\n \nimport pandas as pd\n\ndf = pd.DataFrame(my_list, columns = ['Location','A','B'])\n\nprint(df)\n\nLocation A B\n B_BC ... | [
1
] | [] | [] | [
"dataframe",
"list",
"pandas",
"python"
] | stackoverflow_0074620235_dataframe_list_pandas_python.txt |
Q:
Python variable not updating
Basically I'm creating a program to help with my work. It will send emails to people in an excel list and move down to the next first name and email address in the list until it's done. Heres the code so far
`#AutoMail Version 2
#Goal of new version is to run on any computer. With mini... | Python variable not updating | Basically I'm creating a program to help with my work. It will send emails to people in an excel list and move down to the next first name and email address in the list until it's done. Heres the code so far
`#AutoMail Version 2
#Goal of new version is to run on any computer. With minimal or no mouse and keyboard input... | [
"The issue is updating cell_value doesn't automatically updates all the data that was calculated with cell_value's old value. Once \"Hello \" + name_cell + \",\\n\\nThis is a test body\" evaluates, for example, the resulting string has no relation to name_cell, and wan't change when name_cell changes. If you want t... | [
0
] | [] | [] | [
"python",
"python_3.x",
"smtplib",
"variables",
"while_loop"
] | stackoverflow_0074621873_python_python_3.x_smtplib_variables_while_loop.txt |
Q:
How to communicate between 2 html pages in the same widget
I am using jupyter notebook to develop a sort of proof of concept for a project of mine, right now I have the 2 pages loaded in the same iframe in one jupyter notebook cell. Right now I don't know what approach to take to solve the communication between th... | How to communicate between 2 html pages in the same widget | I am using jupyter notebook to develop a sort of proof of concept for a project of mine, right now I have the 2 pages loaded in the same iframe in one jupyter notebook cell. Right now I don't know what approach to take to solve the communication between these 2 pages in the same widget.
My 2 pages:
<!DOCTYPE html>
<!--... | [
"HTML doesn't support modifying the contents of another html page in this way. You'll likely need some server-side code to facilitate this.\nIn your case, I'd recommend using Websockets. There are plenty of youtube tutorials for similar functionality - search \"Websockets Chat App\" which should give you a good und... | [
0
] | [] | [] | [
"html",
"javascript",
"jupyter_notebook",
"node.js",
"python"
] | stackoverflow_0074621832_html_javascript_jupyter_notebook_node.js_python.txt |
Q:
Trouble Understanding Pytest
I'm working through the auditor version of CS50P and am a bit confused on how pytest works, specifically on the test_twttr exercise.
The main program is to remove any vowels from a string and the below code is intended to test it
I believe my code is set up properly for pytest to test ... | Trouble Understanding Pytest | I'm working through the auditor version of CS50P and am a bit confused on how pytest works, specifically on the test_twttr exercise.
The main program is to remove any vowels from a string and the below code is intended to test it
I believe my code is set up properly for pytest to test my functions; however, when I run ... | [
"Pytest doesn't run you test code like a script. It loads the content as a module and then looks for functions/methods that start with test_ to create a list of items it needs to test. And because it's not run as a script, you don't need to create any main method yourself, that's part of what's offered by the pytes... | [
1
] | [] | [] | [
"cs50",
"pytest",
"python",
"testing"
] | stackoverflow_0074621975_cs50_pytest_python_testing.txt |
Q:
Visual Studio Code: Syntax Error: invalid syntax
Unfamiliar error message in VScode when using Python. SyntaxError: invalid syntax and <stdin> ?????
Yesterday, I was doing a normal python work and some assignments. Everything was normal.
On VS code on Mac, with python official plugin. all running latest version.
B... | Visual Studio Code: Syntax Error: invalid syntax | Unfamiliar error message in VScode when using Python. SyntaxError: invalid syntax and <stdin> ?????
Yesterday, I was doing a normal python work and some assignments. Everything was normal.
On VS code on Mac, with python official plugin. all running latest version.
But today, when I run this very simple code
while True:... | [
"You should distinguish two types of terminals: vscode integrated terminal and python interactive terminal.\nIf you create a new terminal directly in vscode, the vscode integrated terminal will be opened, which is the same as the external powershell window.\n\nIf you execute the python command in the terminal, the ... | [
0
] | [] | [] | [
"python",
"syntax_error",
"visual_studio_code"
] | stackoverflow_0074611311_python_syntax_error_visual_studio_code.txt |
Q:
Optimizing apply and lambda function with pandas
I am trying to optimize a function returning the value (wage)of a variable given a condition (largest enrollment within MSA) for every year. I thought combining apply and lambda would be efficient, but my actual dataset is large (shape of 321681x272) making the comp... | Optimizing apply and lambda function with pandas | I am trying to optimize a function returning the value (wage)of a variable given a condition (largest enrollment within MSA) for every year. I thought combining apply and lambda would be efficient, but my actual dataset is large (shape of 321681x272) making the computation extremely slow. Is there a faster way of going... | [
"Something like\ndf['main_wage'] = df.set_index('wage').groupby(['year', 'msa'])['enroll'].transform('idxmax').values\n\n"
] | [
1
] | [] | [] | [
"apply",
"lambda",
"pandas",
"python"
] | stackoverflow_0074621775_apply_lambda_pandas_python.txt |
Q:
How to display ID for each form in Django Formset
Need to make the UI more ordered, can i have indexing for the forms in formset or access the form ID?
<div class="card">
<div class="card-body">
<div id="form-container... | How to display ID for each form in Django Formset | Need to make the UI more ordered, can i have indexing for the forms in formset or access the form ID?
<div class="card">
<div class="card-body">
<div id="form-container">
{% csrf_toke... | [
"Yeah, you can use forloop.counter within your forloop like this, can assign the value to name or id\n<div class=\"card\">\n <div class=\"card-body\">\n <div id=\"form-container\">\n {% csrf_token %}\n {{ formset1.management_form }}\n {% for form in formset1 %}\n {% crispy ... | [
0
] | [] | [] | [
"django",
"django_forms",
"django_views",
"python"
] | stackoverflow_0072695194_django_django_forms_django_views_python.txt |
Q:
Use Regex to exclude numbers based on certain conditions
I am trying to match and extract numbers if:
They are not a single 2
They are not a single 4
They are not a 4-digit number
*Note: Placement of numbers in the string is completely random - the numbers can occur at the beginning, middle, or end and can be an... | Use Regex to exclude numbers based on certain conditions | I am trying to match and extract numbers if:
They are not a single 2
They are not a single 4
They are not a 4-digit number
*Note: Placement of numbers in the string is completely random - the numbers can occur at the beginning, middle, or end and can be any length other than 4.
Here is a table with examples of string... | [
"You could use negative lookarounds (?<!\\d) and (?!\\d) as boundaries:\n(?<!\\d)(?!([24]|\\d{4})(?!\\d))\\d+\n\nSee this demo at regex101\nInside the first negative lookahead disallowed numbers get alternated in a group.\n"
] | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074621957_python_regex.txt |
Q:
How do I replace column values of a dataframe with values of another dataframe based on a common column?
I have two dataframes, one that looks like this:
hec_df:
accident year
factor
age
2007
1.5
13
2008
1.6
11
2009
1.7
15
and hec_ldfs:
accident year
factor
2007
1.6
2008
1.64
2009
1.7
My goal is to repla... | How do I replace column values of a dataframe with values of another dataframe based on a common column? | I have two dataframes, one that looks like this:
hec_df:
accident year
factor
age
2007
1.5
13
2008
1.6
11
2009
1.7
15
and hec_ldfs:
accident year
factor
2007
1.6
2008
1.64
2009
1.7
My goal is to replace the factor value of df1 with the factor value of df2. My code for this is
hec_df['fac... | [
"you're mapping factor to the accident_year, instead of hec_df.accident_year to the hec_df.accident year\nhec_df['factor'] = hec_df['accident year'].map(hec_ldfs.set_index('accident year')['factor']).fillna(hec_df['factor'])\nhec_df\n\naccident year factor age\n0 2007 1.60 13\n1 2008 1.64 11\n2 ... | [
3
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074622022_pandas_python.txt |
Q:
How to normalize email addresses without regex
The problem is that no matter what I do, I cannot seem to make a function that normalizes (not validates) without the help of regex. For example, instead of my code printing invalid or valid email address, I want it to:
filter out + signs, . signs, etc. that are BEFO... | How to normalize email addresses without regex | The problem is that no matter what I do, I cannot seem to make a function that normalizes (not validates) without the help of regex. For example, instead of my code printing invalid or valid email address, I want it to:
filter out + signs, . signs, etc. that are BEFORE the @gmail.com part;
make it so that the program ... | [
"This seems like a trivial task for the str class methods:\naddresses = [\n 'johnsmith+panerabread@gmail.com',\n 'jOhN.sMiTh@gmail.com'\n]\n\nfor address in addresses:\n name, domain = map(str.lower, address.split('@'))\n if domain == 'gmail.com':\n name = name.replace('.', '')\n if '+' in... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0074622111_python_regex.txt |
Q:
ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI
The question is why I see the error message in the title when trying to import enchant. I am using Win64.
A:
On Ubuntu, run sudo apt-get install libenchant1c2a
A:
I found... | ImportError: The 'enchant' C library was not found. Please install it via your OS package manager, or use a pre-built binary wheel from PyPI | The question is why I see the error message in the title when trying to import enchant. I am using Win64.
| [
"On Ubuntu, run sudo apt-get install libenchant1c2a\n",
"I found the answer in this GitHub page.\nIn a nutshell, they have not shipped a wheel for the win_amd64 platform yet.\n",
"Resolved: On Win7-64 I ran\npip3 install pyenchant==1.6.6\nwhich seems to be the latest version of PyEnchant that still shipped with... | [
24,
13,
13,
7,
3,
2,
1,
0,
0
] | [] | [] | [
"enchant",
"file_not_found",
"import",
"python",
"win64"
] | stackoverflow_0029381919_enchant_file_not_found_import_python_win64.txt |
Q:
How to handle typing of member variable that is initialized during __post_init__() of dataclass
The variable below is initialized as none, but during __post_init__ it is replaced with an instance of outlook client.
@dataclass
class Config:
"""Outlook configuration"""
mailbox: str
inbox: str
mailb... | How to handle typing of member variable that is initialized during __post_init__() of dataclass | The variable below is initialized as none, but during __post_init__ it is replaced with an instance of outlook client.
@dataclass
class Config:
"""Outlook configuration"""
mailbox: str
inbox: str
mailbox_obj: Union["Mailbox", None] = None
However, static type analysis correctly informs that mailbox_o... | [
"Yes, you want to specify that it is not an init field, so you just want something like this:\nimport dataclasses\n\nclass Mailbox:\n pass\n\n@dataclasses.dataclass\nclass Config:\n \"\"\"Outlook configuration\"\"\"\n\n mailbox: str\n inbox: str\n mailbox_obj: \"Mailbox\" = dataclasses.field(init=Fal... | [
1
] | [] | [] | [
"python",
"python_3.x",
"python_dataclasses",
"python_typing"
] | stackoverflow_0074621969_python_python_3.x_python_dataclasses_python_typing.txt |
Q:
Kivy Access ids from .kv file to .py file
.
I'm new into kivy and I want to make an android app. I almost finish GUI, the front-end part, but I have a very big problem. I've searched all over the internet but without answer. I don't know how to access ids from .kv to use them into .py functions.
I've tried all of ... | Kivy Access ids from .kv file to .py file | .
I'm new into kivy and I want to make an android app. I almost finish GUI, the front-end part, but I have a very big problem. I've searched all over the internet but without answer. I don't know how to access ids from .kv to use them into .py functions.
I've tried all of what I've found on the internet, but didn't wor... | [
"I also had trouble with this as well when I was first leaning Kivy a couple years back, but I finally figured out the way. there is a bit of boilier-plate required to maintain the connection.\nin this example my_label is a kivy id and I am connecting it to a Python object of the same name. this is done with the ... | [
0
] | [] | [] | [
"kivy",
"kivymd",
"python"
] | stackoverflow_0074620837_kivy_kivymd_python.txt |
Q:
Can't scrape table BeautifulSoup
I'm trying to scrape the following table from this URL: https://baseballsavant.mlb.com/leaderboard/outs_above_average?type=Fielder&startYear=2022&endYear=2022&split=no&team=&range=year&min=10&pos=of&roles=&viz=show
This is my code:
import requests
from bs4 import BeautifulSoup
url... | Can't scrape table BeautifulSoup | I'm trying to scrape the following table from this URL: https://baseballsavant.mlb.com/leaderboard/outs_above_average?type=Fielder&startYear=2022&endYear=2022&split=no&team=&range=year&min=10&pos=of&roles=&viz=show
This is my code:
import requests
from bs4 import BeautifulSoup
url = "https://baseballsavant.mlb.com/lea... | [
"The webpage is loaded dynamically and relies on JavaScript, therefore requests won't support it. You could use another parser library such as selenium.\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.su... | [
2
] | [] | [] | [
"beautifulsoup",
"python",
"web_scraping"
] | stackoverflow_0074621973_beautifulsoup_python_web_scraping.txt |
Q:
python mysql delete statement not working
here I am trying to remove any users which containt a " in their email/username.
def removeQuote(self, tbl,record):
""" Updates the record """
statmt="select id from %s WHERE `email` LIKE '%%\"%%'" % (tbl)
self.cursor.execute(statmt)... | python mysql delete statement not working | here I am trying to remove any users which containt a " in their email/username.
def removeQuote(self, tbl,record):
""" Updates the record """
statmt="select id from %s WHERE `email` LIKE '%%\"%%'" % (tbl)
self.cursor.execute(statmt)
rows=list(self.cursor.fetchall())
... | [
"You need to commit the change, using the commit() method on the connection object. Most DBAPI interfaces use implicit transactions.\nAlso, don't use string formatting for SQL query generation! It will open you up to SQL injections:\nUNSAFE!!\n# What happens if id = \"1'; DROP DATABASE somedb\" ?\ndelstatmt = \"DEL... | [
27,
1,
0
] | [] | [] | [
"python",
"sql",
"transactional"
] | stackoverflow_0012082360_python_sql_transactional.txt |
Q:
connect to a postgres database inside of a docker container from django running on host machine
I have a postgres database running inside a container with pgadmin connected to it,
the docker-compose.yml is as follows:
postgres:
image: postgres:13.0-alpine
volumes:
- postgres:/var/lib/postgresql/data
port... | connect to a postgres database inside of a docker container from django running on host machine | I have a postgres database running inside a container with pgadmin connected to it,
the docker-compose.yml is as follows:
postgres:
image: postgres:13.0-alpine
volumes:
- postgres:/var/lib/postgresql/data
ports:
- "5432:5432"
env_file:
- $ENV_FILE
pgadmin:
image: dpage/pgadmin4
volumes:
- p... | [
"So for anyone that finds this, i was helped along hugely by this thread; Connecting to Postgresql in a docker container from outside\nThe problem ended up being that for some reason port 5432 was in use, i think by django itself (although if anyone knows the real answer that knowledge would be greatly appreciated)... | [
1
] | [] | [] | [
"django",
"docker_compose",
"postgresql",
"python"
] | stackoverflow_0074621910_django_docker_compose_postgresql_python.txt |
Q:
Can't adding my camera widget to the Screen to make the camera open in kivymd form .kv
I made a WebHomeScreen in which i make a two functions for my webcam to start/launch and read the live feed using opencv when i run my code the webcam starts but its not showing on the app screen.
Below is the code of my main.py... | Can't adding my camera widget to the Screen to make the camera open in kivymd form .kv | I made a WebHomeScreen in which i make a two functions for my webcam to start/launch and read the live feed using opencv when i run my code the webcam starts but its not showing on the app screen.
Below is the code of my main.py file.
`
class WebCamScreen(Screen):
def do_start(self):
self.capture = cv2.Vid... | [
"You can just add an Image to your kv:\n<WebCamScreen>:\n MDBoxLayout:\n MDRaisedButton:\n text: \"Start Camera\"\n size_hint_x: None\n size_hint_y: None\n md_bg_color: \"orange\"\n pos_hint: {\"center_x\": 0.2, \"center_y\": 0.5}\n on_pres... | [
0
] | [] | [] | [
"cross_platform",
"kivy",
"kivymd",
"python"
] | stackoverflow_0074619958_cross_platform_kivy_kivymd_python.txt |
Q:
Pandas lagged rolling average on aggregate data with multiple groups and missing dates
I'd like to calculate a lagged rolling average on a complicated time-series dataset. Consider the toy example as follows:
import numpy as np
import pandas as pd
np.random.seed(101)
fruit = ['apples', 'apples', 'apples', 'oran... | Pandas lagged rolling average on aggregate data with multiple groups and missing dates | I'd like to calculate a lagged rolling average on a complicated time-series dataset. Consider the toy example as follows:
import numpy as np
import pandas as pd
np.random.seed(101)
fruit = ['apples', 'apples', 'apples', 'oranges', 'apples', 'oranges', 'oranges',
'oranges', 'apples', 'oranges', 'apples', 'ap... | [
"import numpy as np\nimport pandas as pd\nimport datetime\n\nnp.random.seed(101)\n\nfruit = ['apples', 'apples', 'apples', 'oranges', 'apples', 'oranges', 'oranges',\n 'oranges', 'apples', 'oranges', 'apples', 'apples']\npeople = ['alice']*6+['bob']*6\ndate = ['2022-01-01', '2022-01-03', '2022-01-04', '2022... | [
1,
1
] | [] | [] | [
"dataframe",
"pandas",
"python",
"rolling_computation",
"time_series"
] | stackoverflow_0074620602_dataframe_pandas_python_rolling_computation_time_series.txt |
Q:
Pandas: `NaNs` when reading `.txt` file
I have a .txt file that I am attempting to read in pandas. When I open the .txt file, I see it has the content and data I expect. However, when I read the file in pandas, the data is missing and I only NaNs.
here's sample content from .txt file:
980145115 189699454 ... | Pandas: `NaNs` when reading `.txt` file | I have a .txt file that I am attempting to read in pandas. When I open the .txt file, I see it has the content and data I expect. However, when I read the file in pandas, the data is missing and I only NaNs.
here's sample content from .txt file:
980145115 189699454 SD Vacant Land Agricultural/H... | [
"It's probably due to the separator you have choosen in pandas.read_csv.\nTry to use whitespaces instead with sep=\"\\s\\s+\" :\ndf = pd.read_csv('s3://filepath', encoding='latin-1', sep=\"\\s\\s+\", engine=\"python\", header=None)\n\nOr with delim_whitespace=True :\ndf = pd.read_csv('s3://filepath', encoding='lati... | [
1,
1
] | [] | [] | [
"csv",
"pandas",
"python"
] | stackoverflow_0074620973_csv_pandas_python.txt |
Q:
How can I learn to CREATE a data visualization tool in Python or in any other Language?
I want to understand and learn how a data visualization tool works and is made.
Tried searching it on google but didn't found anything.
Only matplotlib tutorials.
I dont want to to learn to use a tool. I want to learn to create... | How can I learn to CREATE a data visualization tool in Python or in any other Language? | I want to understand and learn how a data visualization tool works and is made.
Tried searching it on google but didn't found anything.
Only matplotlib tutorials.
I dont want to to learn to use a tool. I want to learn to create one.
Tried searching it on google but didn't found anything.
Expecting to get an online docu... | [
"I would start with learning to create plots from scratch. Since you tagged python, look up python visual libraries like tk or PIL to get started. Once you make some basic visuals of dots, try to make a graph template, then add some dummy data on top of it.\n"
] | [
0
] | [] | [] | [
"c++",
"python",
"visualization"
] | stackoverflow_0074622230_c++_python_visualization.txt |
Q:
How do I write a Python code to check if the given sequence is a palindrome or not?
I wish to learn more about the rev_string
I tried to see if "MOM" is a palindrome and I wanted the result to be yes/no
A:
It's very simple, First, you need to reverse the String that you want to check whether it's a palindrome or... | How do I write a Python code to check if the given sequence is a palindrome or not? | I wish to learn more about the rev_string
I tried to see if "MOM" is a palindrome and I wanted the result to be yes/no
| [
"It's very simple, First, you need to reverse the String that you want to check whether it's a palindrome or not. Then Compare the reverse String with the input one. If it's the same then it's a palindrome else it's not.\nstring = \"MoM\"\nrevstring = \"\".join(reversed(string))\n\nprint(\"Yes\" if string == revstr... | [
0
] | [] | [] | [
"arrays",
"palindrome",
"python",
"reverse",
"string"
] | stackoverflow_0074622176_arrays_palindrome_python_reverse_string.txt |
Q:
Number Recognition on 7 segment using python
I am writing a code on Jupyter notebook using python to recognize the number on the device with 7segment(FND).
I used opencv and got the edge of the image.
import cv2
import matplotlib.pyplot as plt
def detect_edge(image):
''' function Detecting Edges '''
ima... | Number Recognition on 7 segment using python | I am writing a code on Jupyter notebook using python to recognize the number on the device with 7segment(FND).
I used opencv and got the edge of the image.
import cv2
import matplotlib.pyplot as plt
def detect_edge(image):
''' function Detecting Edges '''
image_with_edges = cv2.Canny(image , 100, 200)
i... | [
"I feel like using a CNN is overkill for a problem like this. Especially given that this is a 7-segment display we should be able to solve this without resorting to that kind of complexity.\nYou've marked out the corners so I'll assume that you can reliably crop out and un-rotate (make it flat) the display.\nWe wan... | [
6,
2,
0
] | [] | [] | [
"artificial_intelligence",
"deep_learning",
"image_processing",
"opencv",
"python"
] | stackoverflow_0065559254_artificial_intelligence_deep_learning_image_processing_opencv_python.txt |
Q:
Pandas time-series: aggregate by date and transpose
I have the following time series dataframe:
dataframe = pd.DataFrame({
'date': pd.to_datetime([
'2020-04-01', '2020-04-02', '2020-04-03',
'2020-04-01', '2020-04-02', '2020-04-03']),
'Ticker': ['A', 'A', 'A', 'AAPL', 'AAPL', 'AAPL'],
'... | Pandas time-series: aggregate by date and transpose | I have the following time series dataframe:
dataframe = pd.DataFrame({
'date': pd.to_datetime([
'2020-04-01', '2020-04-02', '2020-04-03',
'2020-04-01', '2020-04-02', '2020-04-03']),
'Ticker': ['A', 'A', 'A', 'AAPL', 'AAPL', 'AAPL'],
'Price': ['8', '10', '12', '100', '200', '50']})
... | [
"The operation you are trying to do is called pivoting. That is, creating new columns from the categorical values of a column.\nYou can do either of these (same results):\ndf = dataframe.set_index(\"date\").pivot(columns=\"Ticker\", values=\"Price\")\n\n\ndf = dataframe.pivot(index=\"date\", columns=\"Ticker\", val... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074622270_pandas_python.txt |
Q:
Reading Json text response from url with PowerBi Desktop
I am new to PowerBi.
I would like to get a table on PowerIb, from this JSON API
Sample of data:
{"data": [{"user_id": 54710, "hp_user_id": 5806514, "username": "Jay_J1", "user_profile_url": "https://h30434.www3.hp.com/t5/user/viewprofilepage/user-id/5806514"... | Reading Json text response from url with PowerBi Desktop | I am new to PowerBi.
I would like to get a table on PowerIb, from this JSON API
Sample of data:
{"data": [{"user_id": 54710, "hp_user_id": 5806514, "username": "Jay_J1", "user_profile_url": "https://h30434.www3.hp.com/t5/user/viewprofilepage/user-id/5806514", "user_blocked": 0, "hp_post_id": 8550808, "post_datetime": "... | [
"Fundamentally, you are converting a plain JSON to a table. The JSON just happens to be sourced as plaintext from a URL.\nJSON-to-table is well-explained in the docs - https://learn.microsoft.com/en-us/power-query/connectors/json.\nAdditionally, I highly recommend going through this excellent Power Query primer - h... | [
0
] | [
"I got an answer from another website and it worked:\nSteps to follow:\n\nfrom \"New Source\", select \"Blank Query\" (at the full bottom)\nInthe ribons, select \"Advanced Editor\"\nWrite \"your code\" in M (not easy...)\n\n= let\n Source = Json.Document(Web.Contents(\"https://hptrial.pythonanywhere.com/rest_api... | [
-1
] | [
"javascript",
"json",
"powerbi",
"python"
] | stackoverflow_0074621497_javascript_json_powerbi_python.txt |
Q:
need to limit BeautifulSoup href result to first occurence - or - account for an open parenthesis in href string
I want ONLY the <a href NPPES Data Dissemination in the Full Replacement Monthly NPI File section of https://download.cms.gov/nppes/NPI_Files.html. There are other <a href NPPES Data Dissemination file... | need to limit BeautifulSoup href result to first occurence - or - account for an open parenthesis in href string | I want ONLY the <a href NPPES Data Dissemination in the Full Replacement Monthly NPI File section of https://download.cms.gov/nppes/NPI_Files.html. There are other <a href NPPES Data Dissemination files in the Weekly Incremental NPI Files that I do NOT want. Here is the code that gets ALL NPPES Data Dissemination file... | [
"If what you need is only the first link\nSo what happen here is, the limit you set is the first regex found in the link\nBut you still loop searching it for all links\nThe simple solution to get the first link is just add break when you found so it will stop the loop\ndef get_urls(soup):\n urls = []\n for a ... | [
0
] | [] | [] | [
"beautifulsoup",
"href",
"limit",
"python"
] | stackoverflow_0074621951_beautifulsoup_href_limit_python.txt |
Q:
is there a way of comparing the similarities between these two sequences in python?
I am new to Python and I need your help in getting the similarity between two sequences. Assuming they are not of the same length and some may have (-) gap symbols.
So here is my code bellow in getting the similarity in only one se... | is there a way of comparing the similarities between these two sequences in python? | I am new to Python and I need your help in getting the similarity between two sequences. Assuming they are not of the same length and some may have (-) gap symbols.
So here is my code bellow in getting the similarity in only one sequence.
seq1 = "AAAATCCCTAGGGTCAT"
def similarity(seq1):
base_dic={}
for i in ran... | [
"There are 2 parts to this answer.\n\nPolishes to the code in question.\nStandard algorithm to find how similar 2 strings are.\n\nPart-1: Polishes to your code in the question.\nThe key takeaways here for you are to make your code more pythonic\nfrom collections import Counter\n\nseq1 = \"AAAATCCCTAGGGTCAT\"\nseq2 ... | [
0
] | [
"To avoid counting “-“, you can add an if clause when you enter the for loop. If the character is “-“, we skip the loop for that character and move to next one.\nif seq1[i] == “-“:\n continue\n\nThis will help solve your problem.\n\n"
] | [
-1
] | [
"bioinformatics",
"python",
"python_3.x",
"spyder"
] | stackoverflow_0074622122_bioinformatics_python_python_3.x_spyder.txt |
Q:
Django - Null Integrity error not allowing POST
The error that I am getting when trying to POST is:
django.db.utils.IntegrityError: null value in column "interest_category_id" of relation "teamStart_project" violates not-null constraint
Here are my Serializers:
class InterestSerializer(serializers.ModelSerializer... | Django - Null Integrity error not allowing POST | The error that I am getting when trying to POST is:
django.db.utils.IntegrityError: null value in column "interest_category_id" of relation "teamStart_project" violates not-null constraint
Here are my Serializers:
class InterestSerializer(serializers.ModelSerializer):
class Meta:
model = Interests
... | [
"change that interest_category_name = serializers.StringRelatedField() to\ninterest_category = serializers.SerializerMethodField()\nand add the following function to your ProjectsSerializer\ndef get_interest_category_name(self, instance):\n return instance.interest_category.interest_name\n\nand then add \"intere... | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074622177_django_python.txt |
Q:
Housing Data Set Not Able to Load From 'Hands-On Machine Learning'
I have followed other solutions that were posted on stackoverflow about trying to load the housing dataset which mostly included trying to call 'fetch_housing_data()' as well. However, even after I do that, I still get a filenotfound error indicati... | Housing Data Set Not Able to Load From 'Hands-On Machine Learning' | I have followed other solutions that were posted on stackoverflow about trying to load the housing dataset which mostly included trying to call 'fetch_housing_data()' as well. However, even after I do that, I still get a filenotfound error indicating that there is no dataset called 'datasets/housing'. Here is the code ... | [
"The traceback I got when running the code looked like:\nTraceback (most recent call last):\n File \"/home/hayesall/answer.py\", line 23, in <module>\n fetch_housing_data()\n File \"/home/hayesall/answer.py\", line 15, in fetch_housing_data\n os.mkdir(housing_path)\nFileNotFoundError: [Errno 2] No such file... | [
0
] | [] | [] | [
"machine_learning",
"python"
] | stackoverflow_0074622321_machine_learning_python.txt |
Q:
Why is my class not accepting arguments in python?
Context: The full code isn't below as to make it easier to read. Therefore some of the code may not make sense as it isn't used. Also the big picture is that I am attempting to make a object orientated text based adventure in python.
The problem I have is that I'm... | Why is my class not accepting arguments in python? | Context: The full code isn't below as to make it easier to read. Therefore some of the code may not make sense as it isn't used. Also the big picture is that I am attempting to make a object orientated text based adventure in python.
The problem I have is that I'm trying to have a gate object then create instances of i... | [
"The constructor should be called __init__ and not __innit__. Since your classes don't have a constructor, python provides a default, no arg constructor and you cannot pass any arguments to it, hence the error.\n"
] | [
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0074622374_oop_python.txt |
Q:
Python money denomination loop does not work on decimal
I am learning python and I what I need to achieve is to count how many denominations of 1000, 500, 200, 100, 50, 20, 10, 5, 1 , 0.25, 0.01 count base on my input data of 1575.78.This specific code bums me out.
def withdraw_money():
denoms = (1000, 500, 200, 1... | Python money denomination loop does not work on decimal | I am learning python and I what I need to achieve is to count how many denominations of 1000, 500, 200, 100, 50, 20, 10, 5, 1 , 0.25, 0.01 count base on my input data of 1575.78.This specific code bums me out.
def withdraw_money():
denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,.25,0.01)
while True:
try:
wit... | [
"After debugging the code, I found the error. Using round() solve the problem.\ndef withdraw_money():\n denoms = (1000, 500, 200, 100, 50, 20, 10,5,1,0.25,0.01)\n while True:\n try:\n withdraw = 1575.77\n break\n except Exception as e:\n print('Incorrect input: %... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0074622105_python.txt |
Q:
Login credentials not working with Gmail SMTP
I am attempting to send an email in Python, through Gmail. Here is my code:
import smtplib
fromaddr = '......................'
toaddrs = '......................'
msg = 'Spam email Test'
username = '.......'
password = '.......'
server = smtplib.SMTP('... | Login credentials not working with Gmail SMTP | I am attempting to send an email in Python, through Gmail. Here is my code:
import smtplib
fromaddr = '......................'
toaddrs = '......................'
msg = 'Spam email Test'
username = '.......'
password = '.......'
server = smtplib.SMTP('smtp.gmail.com', 587)
server.ehlo()
server.startt... | [
"UPDATE:\nThis feature is no longer supported as of May 30th, 2022. See https://support.google.com/accounts/answer/6010255?hl=en&visit_id=637896899107643254-869975220&p=less-secure-apps&rd=1#zippy=%2Cuse-an-app-password\nORIGINAL ANSWER (No longer working):\nI ran into a similar problem and stumbled on this questio... | [
311,
44,
21,
15,
12,
10,
7,
7,
4,
1,
0,
0,
0
] | [
"In my case, I allowed the access, but the problem was that I was using server.login('Name <email>', password). Please, make sure to use only your email here: server.login('youremail@gmail.com', password).\nResponse after change:\n(235, '2.7.0 Accepted')\n\nResponse prior:\nsmtplib.SMTPAuthenticationError: (535, b'... | [
-1,
-2
] | [
"authentication",
"gmail",
"python",
"smtp",
"smtp_auth"
] | stackoverflow_0016512592_authentication_gmail_python_smtp_smtp_auth.txt |
Q:
OpenCV stereo calibration error - (-3:Internal error) CALIB_CHECK_COND - Ill-conditioned matrix for input array 1 in function 'CalibrateExtrinsics'
opencv version is 3.4.9
I use this code to calibrate. My stereoscopic camera consists of two GoPro Session cameras (with settings - 1080p 30 fps, medium angle) fixed ... | OpenCV stereo calibration error - (-3:Internal error) CALIB_CHECK_COND - Ill-conditioned matrix for input array 1 in function 'CalibrateExtrinsics' | opencv version is 3.4.9
I use this code to calibrate. My stereoscopic camera consists of two GoPro Session cameras (with settings - 1080p 30 fps, medium angle) fixed on an aluminium plane 90 cm away from each other, also used a wifi remote controller for the cameras to be in sync. I shot a 2 minute video covering ever... | [
"So the error is raised here: https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fisheye.cpp#L1421 when evaluating the vector of singular values w output from Singular Value Decomposition (SVD). Specifically, the ratio of the first singular value and the last singular value (svd.w.at<double>(0) / svd.... | [
4,
0
] | [] | [] | [
"camera_calibration",
"computer_vision",
"opencv",
"python",
"stereoscopy"
] | stackoverflow_0061002436_camera_calibration_computer_vision_opencv_python_stereoscopy.txt |
Q:
How to use all() in python?
I want to check if all elements of a list are not present in a string.
ex :
l = ["abc","ghi"]
s1 = "xyzjkl"
s2 = "abcdef"
So , when l is compared with s1 it should return True,
when l is compared with s2 it should return False.
This is what i tried :
all(x for x in l if... | How to use all() in python? | I want to check if all elements of a list are not present in a string.
ex :
l = ["abc","ghi"]
s1 = "xyzjkl"
s2 = "abcdef"
So , when l is compared with s1 it should return True,
when l is compared with s2 it should return False.
This is what i tried :
all(x for x in l if x not in s1) = True
all(x fo... | [
"You need a list of True, False. But you were simply getting the matched items, so when you do an all on Truthy values you will get True. Instead do:\nall([x not in s1 for x in l])\nall([x not in s2 for x in l])\n\nor just without list comp, because all accepts an iterable.\nall(x not in s1 for x in l)\nall(x not i... | [
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074622440_python.txt |
Q:
eBay Digital Signatures for APIs signature header generation
Having read through eBay's guide for including digital signatures to certain of their REST API calls, I am having trouble with generating the signature header. Rather than including all of the documentation here (there is a lot!), I'll provide links to t... | eBay Digital Signatures for APIs signature header generation | Having read through eBay's guide for including digital signatures to certain of their REST API calls, I am having trouble with generating the signature header. Rather than including all of the documentation here (there is a lot!), I'll provide links to the appropriate pages and some of the documentation. The following ... | [
"Alright so this is where Im at right now, not using the content-digest as it's simply a GET request so just trying to get the basics working, but none of this seems to work.\n $public = \"xxx\";\n $private = \"yyy\";\n $jwe = \"jwe\";\n $path = \"/sell/fulfillment/v1/order/\" . \"11-xxxx-yyyy\";\n $... | [
0,
0
] | [] | [] | [
"digital_signature",
"ebay_api",
"python",
"python_3.x",
"rest"
] | stackoverflow_0074234508_digital_signature_ebay_api_python_python_3.x_rest.txt |
Q:
Python: How to find the second highest number in a list?
def second_highest(list):
""" (list of int) -> int
How do you find the second highest value from the list of integers without using remove, pop, or sort (which I tried) since I need to use the same list later on?
There will be no duplication of numbers.
lis... | Python: How to find the second highest number in a list? | def second_highest(list):
""" (list of int) -> int
How do you find the second highest value from the list of integers without using remove, pop, or sort (which I tried) since I need to use the same list later on?
There will be no duplication of numbers.
list.sort()
return list[-2]
I tried removing the highest number ... | [
"Use the builtin sorted oy mylist, which will not modify mylist(thanks to @Tofystedeth) \nmylist = [1, 2, 8, 3, 12]\nprint(sorted(mylist, reverse=True)[1])\n\n",
"data = [1,2,8,3,12]\n\nlargest = None\nsecond_largest = None\n\nfor a in data:\n if not largest or a > largest:\n if largest:\n se... | [
11,
4,
1,
1,
1,
0,
0,
0,
0
] | [
"\nCopy unique list elements to another list (if Already the list elements are unique, go to step 2) .\nYou should find the maximum in the list and save its index. Then remove it from the list using the remove() function and then find the maximum of the new list (with the original maximum value removed) and that wi... | [
-2,
-2
] | [
"python"
] | stackoverflow_0033486058_python.txt |
Q:
How I get data from a Input to run a function in Django
I'm following a django tutorial and I have troubles getting the data from a input in my HTML.
This is the code from the tutorial:
views.py
def buscar(request):
if request.GET["prd"]:
producto = request.GET["prd"]
articulo = Escucha.object... | How I get data from a Input to run a function in Django | I'm following a django tutorial and I have troubles getting the data from a input in my HTML.
This is the code from the tutorial:
views.py
def buscar(request):
if request.GET["prd"]:
producto = request.GET["prd"]
articulo = Escucha.objects.filter(user__icontains=producto)
return render(req... | [
"\nAnd the problem I get is: AttributeError at /pruebas/ 'WSGIRequest' object has no attribute 'get'\n\n\nY really don't know what's the problem, for me the two codes are similar.\n\nNo, the codes are not similar, if you look at it correctly, it should be request.GET[\"first\"] not request.get[\"first\"].\nAnd also... | [
0
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074621441_django_django_templates_django_views_python.txt |
Q:
Django SMTPAuthenticationError
I am new in django and developing a web application using django. I have successfully set the Signup functionality using Userena in my web application and can Register as a user with Verification Email.
I can show you my SMTP settings in my settings.py file
EMAIL_BACKEND = 'django.co... | Django SMTPAuthenticationError | I am new in django and developing a web application using django. I have successfully set the Signup functionality using Userena in my web application and can Register as a user with Verification Email.
I can show you my SMTP settings in my settings.py file
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
... | [
"A relatively recent change in Google's authentication system means you're going to have to \"allow less secure app access\" to your Google account, in order for this to work.\nIn your error, you are recommended to visit this link: https://support.google.com/mail/answer/78754\nOn that page:\nStep #2 asks you to try... | [
77,
6,
5,
3,
2,
2,
1,
1,
1,
0,
0,
0,
0
] | [
"I think you need to turn on google less secure apps. Login to your account and go to less secure apps to change your setting. It is not good but you can try your code.\n",
"If you already have allowed access to less secure apps and still having problems go to your account >> login and security >> notifications a... | [
-1,
-1,
-2
] | [
"authentication",
"django",
"gmail",
"python",
"smtp_auth"
] | stackoverflow_0026697565_authentication_django_gmail_python_smtp_auth.txt |
Q:
Python float mysteriously off by anywhere between 0.1 to 0.3
I'm writing a function to convert a weirdly formatted Degrees Minutes Seconds to Degrees Decimal.
My code is:
def fromDMS(coordinate):
lat_dms = coordinate[0:10]
lon_dms = coordinate[11:21]
lat_sign = lat_dms[0]
lat_deg = float(lat_dms[1... | Python float mysteriously off by anywhere between 0.1 to 0.3 | I'm writing a function to convert a weirdly formatted Degrees Minutes Seconds to Degrees Decimal.
My code is:
def fromDMS(coordinate):
lat_dms = coordinate[0:10]
lon_dms = coordinate[11:21]
lat_sign = lat_dms[0]
lat_deg = float(lat_dms[1:3])
lat_min = float(lat_dms[3:5])
lat_sec = float(lat_dms... | [
"According to https://www.fcc.gov/media/radio/dms-decimal, the decimal degrees should be -36.926389 and 174.900278.\nOne problem with this code is that it divides the seconds by 60 * 2 (i.e., 120) instead of 60 ** 2 (i.e., 3600). Making this change causes the latitude to be -36.92638888888889.\nThe second problem ... | [
3,
0
] | [] | [] | [
"floating_point",
"python",
"python_3.x"
] | stackoverflow_0074622426_floating_point_python_python_3.x.txt |
Q:
Modify bound variables of a closure in Python
Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
#... | Modify bound variables of a closure in Python | Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = local... | [
"It is quite possible in python 3 thanks to the magic of nonlocal.\ndef foo():\n var_a = 2\n var_b = 3\n\n def _closure(x, magic = None):\n nonlocal var_a\n if magic is not None:\n var_a = magic\n\n return var_a + var_b + x\n\n... | [
50,
22,
11,
10,
4,
1,
1,
1,
0,
0
] | [] | [] | [
"closures",
"functional_programming",
"python"
] | stackoverflow_0000392349_closures_functional_programming_python.txt |
Q:
stat() got an unexpected keyword argument 'follow_symlinks'
Web search found links to bugs, I don't write complicated code on Python, just want to confirm I understand syntax:
https://docs.python.org/3/library/pathlib.html
Path.stat(*, follow_symlinks=True)¶
But when I write Path(filepath).stat(follow_symlinks=Fal... | stat() got an unexpected keyword argument 'follow_symlinks' | Web search found links to bugs, I don't write complicated code on Python, just want to confirm I understand syntax:
https://docs.python.org/3/library/pathlib.html
Path.stat(*, follow_symlinks=True)¶
But when I write Path(filepath).stat(follow_symlinks=False) I'm getting "stat() got an unexpected keyword argument 'follo... | [
"You're reading it correctly. You just missed the footnote. From the page you linked\n\nChanged in version 3.10: The follow_symlinks parameter was added.\n\nSo if you want to use that keyword argument, you need Python 3.10 or newer. Otherwise, as you've already figured out, just use lstat.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074622601_python.txt |
Q:
Is there a way to set as initial camera in a 3D plot that the upper left corner is (0,0,0)? Plotly
I'm trying to set as initial camera of a 3D volume plot where the upper left corner is the origin (x, y, z = 0). I've read the documentation about the camera controls but cannot figure out how can I accomplish this.
... | Is there a way to set as initial camera in a 3D plot that the upper left corner is (0,0,0)? Plotly | I'm trying to set as initial camera of a 3D volume plot where the upper left corner is the origin (x, y, z = 0). I've read the documentation about the camera controls but cannot figure out how can I accomplish this.
The initial view I want it's something like this:
| [
"I tried it and this one work on me\nIf you want the front upper left corner as (0,0,0)\ncamera = dict(\n eye=dict(x=0, y=-0.5, z=-2.5)\n)\nfig.update_layout(scene_camera=camera, title=name)\nfig.show()\n\nwhat I understand from this eye is basically the position of the eye(or you) look at eyepoint(0,0,0) which ... | [
1
] | [] | [] | [
"plotly",
"plotly_python",
"python"
] | stackoverflow_0074622347_plotly_plotly_python_python.txt |
Q:
prints the sum of the numbers 1 to n in python
GOAL:
Write a program that asks the user for a number n and prints the sum
of the numbers 1 to n. The program keeps asking for a number until
the user enters 0.
expected output:
enter an integer number (0 to end): 5
1+2+3+4+5 = 15
I am able to solve the second probl... | prints the sum of the numbers 1 to n in python | GOAL:
Write a program that asks the user for a number n and prints the sum
of the numbers 1 to n. The program keeps asking for a number until
the user enters 0.
expected output:
enter an integer number (0 to end): 5
1+2+3+4+5 = 15
I am able to solve the second problem which is until the user enters 0.
the problem I'm... | [
"Several issues with your code:\n\nYour while loop will never end. Its intended purpose is not clear.\nYou are summing 1 instead of i each time in your loop.\nYour print statement only occurs at the end. You can include it within your loop.\nIn Python, range(n) excludes n, so use range(n + 1) instead.\nYou do not n... | [
3,
1,
0,
0,
0,
0
] | [
"n*(n+1)/2\n\"zBody zmust zbe zat zleast z30 zcharacters; zyou zentered z9 z...\"\n",
"num = int(input()) \ntotal = num \nfor x in range(num): \n total += x \nprint(total) \n\n"
] | [
-2,
-2
] | [
"python",
"python_3.x"
] | stackoverflow_0050971279_python_python_3.x.txt |
Q:
Round (floor) to the nearest member of the geometric sequence (2, 4, 8, 16, 32, 64, 128 . . . )?
As the title explains, how could I create a function func (using numpy or math modules) to find the nearest member of the geometric sequence (2, 4, 8, 16, 32, 64, 128 . . . )?
For example, func(3) should yield 2, func(... | Round (floor) to the nearest member of the geometric sequence (2, 4, 8, 16, 32, 64, 128 . . . )? | As the title explains, how could I create a function func (using numpy or math modules) to find the nearest member of the geometric sequence (2, 4, 8, 16, 32, 64, 128 . . . )?
For example, func(3) should yield 2, func(20) should yield 16, and func(128) should yield 128.
I cannot find any information on this problem. Mo... | [
"Use the concept of power and log\nimport numpy as np\ndef round_to_geometric(x):\n return int(2 ** np.floor(np.log2(x)))\n\noutput:\n> print(round_to_geometric(3))\n> print(round_to_geometric(20))\n> print(round_to_geometric(128))\n\n2\n16\n128\n\n",
"One way to think about this is in terms of the length of a... | [
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0074622579_python.txt |
Q:
how can Python's pd.qcut give the same result as R's statar::xtile?
I need to create bins based on one column in a dataframe. One problem is the values of that column are oddly distributed. Consequently, Python's pd.qcut may arbitrarily put observations into different bins, even though they have the same value.
In... | how can Python's pd.qcut give the same result as R's statar::xtile? | I need to create bins based on one column in a dataframe. One problem is the values of that column are oddly distributed. Consequently, Python's pd.qcut may arbitrarily put observations into different bins, even though they have the same value.
In R (or in Stata), I use the xtile function of the statar package. R is ab... | [
"Maybe there are better answers, but I have figured out a detour by calling the R function (statar::xtile) from within Python.\n# You need to first install rpy2\n# Activate rpy2 to use R functions/packages in Python \nimport rpy2\nimport rpy2.robjects as robjects\nfrom rpy2.robjects.packages import importr\n# in pa... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074555385_pandas_python.txt |
Q:
Rectangle function that takes in two points and makes a rectangle in a global matrix not working
I have a matrix of 50 by 50 that represents a grid of 25 by 25.
I want all the positives on the grid to get +25 and the negatives stay there absolute value.
But what my problem actually is I am creating a function that... | Rectangle function that takes in two points and makes a rectangle in a global matrix not working | I have a matrix of 50 by 50 that represents a grid of 25 by 25.
I want all the positives on the grid to get +25 and the negatives stay there absolute value.
But what my problem actually is I am creating a function that will create a rectangle based on the given values.
Code (Python 3.10.5):
def createRect(x,y,x1,y1,ite... | [
"I am a bit confused about your code there, as why you fill the matrix backwards (for i in range(x1,x,-1)) and why would you include a hardcoded 6 there (for j in range(1,6)) so I might as well not have understood what the problem is. But wouldn't the following create the rectangles as per the given points? :\ndef ... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074622435_python.txt |
Q:
Keyword argument repeated in python Flask
I'm trying to build restaurant list site using Flask.
This is a part of my application.py code.
@application.route("/list.html")
def list_restaurants():
page = request.args.get("page", 0, type=int)
limit = 4
category = request.args.get("category", "all")
p... | Keyword argument repeated in python Flask | I'm trying to build restaurant list site using Flask.
This is a part of my application.py code.
@application.route("/list.html")
def list_restaurants():
page = request.args.get("page", 0, type=int)
limit = 4
category = request.args.get("category", "all")
price = request.args.get("price", "all")
are... | [
" <input\n type=\"button\"\n name=\"search\"\n onclick=\"location.href='search3.html'\"\n name=\"search\"\n value=\"search\"\n />\n\nYou're using name=\"...\" twice.\n"
] | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074622657_flask_python.txt |
Q:
how to write an if-statement in python that incorporates platform.platform
i am trying to write a program that prints different things depending on the OS and i'm wanting to write an if-statement to do that.I'm new to python but after looking online for a bit i haven't been able to find any solution
import platfor... | how to write an if-statement in python that incorporates platform.platform | i am trying to write a program that prints different things depending on the OS and i'm wanting to write an if-statement to do that.I'm new to python but after looking online for a bit i haven't been able to find any solution
import platform
print('platform:', platform.platform())
if platform.platform == mac0S:
p... | [
"I'll be completing the previous answers and giving some examples.\nSo first of all you're going to want to check the platform Documentation\nThere you'll find that [platform.platform](https://docs.python.org/3/library/platform.html#platform.platform) is a function that returns a single string, but it includes the ... | [
1
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0074621783_if_statement_python.txt |
Q:
How do I get the correct outputs for this chess board?
I am trying to make a program of a chess board, When a user inputs an x and y value it will either output "black" or "white".
x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))
column = x % 2... | How do I get the correct outputs for this chess board? | I am trying to make a program of a chess board, When a user inputs an x and y value it will either output "black" or "white".
x = int(input("Please enter your (x) first number 1-8::"))
y = int(input("Please enter your (y) second number 1-8::"))
column = x % 2
row = y % 2
if column %2 == 0 and row %2 == 1:
pri... | [
"Instead of looking at x and y separately, just check the sum.\nIf the sum is even, it's black, if the sum is odd, it is white.\nI added a lookup of the name in a python dict, but you can just do it with if conditions if you prefer.\nx = int(input(\"Please enter your (x) first number 1-8::\"))\ny = int(input(\"Plea... | [
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074622572_python.txt |
Q:
Python restaurant program
I'm a beginner in python & this is my 3rd program.
I'm learning functions. The user should be able to choose a number first from the menu (1. appetizers, 2.mains 3. drinks, 4.view orders, 5.exit) each one has sub-choices (example appetizers include salad, chips...etc). User should be able... | Python restaurant program | I'm a beginner in python & this is my 3rd program.
I'm learning functions. The user should be able to choose a number first from the menu (1. appetizers, 2.mains 3. drinks, 4.view orders, 5.exit) each one has sub-choices (example appetizers include salad, chips...etc). User should be able to return back after choosing ... | [
"Ideally you do not want to keep your data in prints.\nWe can use data structures like lists or dicts\nHere's what I suggest:\n\nWe use a list for the client order, since we can keep adding to it and we'll be adding things sequentially.\nWe use dicts (python dictionaries) for the menus, so we can keep track of all ... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074622744_python.txt |
Q:
Check if user has Admin -- Discord.py
I would like to make a command that requires the user to have Administrator permission to execute the command.
An example is when a user first invited bot on the server, members must not be able to the use the so called "permissions" command. However members with the moderato... | Check if user has Admin -- Discord.py | I would like to make a command that requires the user to have Administrator permission to execute the command.
An example is when a user first invited bot on the server, members must not be able to the use the so called "permissions" command. However members with the moderator role should have access to it and execute... | [
"It's still not clear what you want to reserve who you want to command to be avaliable to however, the has_permissions decorator allows you to set what permissions a user can use to access a command. This can be set within the parameters\nFor example, if you just only want a member with Administrator permissions to... | [
4,
0
] | [] | [] | [
"discord.py",
"python"
] | stackoverflow_0066346332_discord.py_python.txt |
Q:
Pandas REGEX not returning expected results using "extract"
I am attempting to use REGEX to extract connection strings from blocks of text in a pandas dataframe.
My REGEX works on REGEX101.com (see Screenshot below). Link to my saved test here: https://regex101.com/r/ILnpS0/1
When I try to run the REGEX in a Pand... | Pandas REGEX not returning expected results using "extract" | I am attempting to use REGEX to extract connection strings from blocks of text in a pandas dataframe.
My REGEX works on REGEX101.com (see Screenshot below). Link to my saved test here: https://regex101.com/r/ILnpS0/1
When I try to run the REGEX in a Pandas dataframe, I don’t get any REGEX matches/extracts (but no an e... | [
"Try running your regex in dot all mode, so that .* will match across newlines:\nregex_db = r'(?=Source = DB2.Database)(.*?)(?=\\]\\))'\nmyDF[\"SQLDB connection2\"] = myDF[\"conn_str\"].str.extract(regex_db, expand=True, flags=re.S)\nmyDF\n\n"
] | [
1
] | [] | [] | [
"pandas",
"python",
"regex",
"regex_lookarounds"
] | stackoverflow_0074622819_pandas_python_regex_regex_lookarounds.txt |
Q:
How to use mariadb python connector in Docker?
I want to use the Python mariadb connector in a python container. Yet, until now, I've met only troubles and now I segfault when trying to pass arguments to my SQL queries.
here are my dockerfile and a script that highlight the problem.
FROM python:3.11-buster
RUN ap... | How to use mariadb python connector in Docker? | I want to use the Python mariadb connector in a python container. Yet, until now, I've met only troubles and now I segfault when trying to pass arguments to my SQL queries.
here are my dockerfile and a script that highlight the problem.
FROM python:3.11-buster
RUN apt-get install gcc wget
# https://stackoverflow.com/... | [
"Even if you installed a newer MariaDB Connector/C version, the preinstalled 3.1.13 version from 3.11-buster is still installed.\nAfter installation of MariaDB Connector/C 3.3.3 you have 2 versions installed:\n\n/usr/lib/x86_64-linux-gnu/libmariadb.so.3\n/usr/lib/mariadb/libmariadb.so.3\n\nNow when running your pyt... | [
1
] | [] | [] | [
"docker",
"mariadb",
"mariadb_connector_c",
"python"
] | stackoverflow_0074613306_docker_mariadb_mariadb_connector_c_python.txt |
Q:
Having trouble connecting with MySQL.connector in python
I am learning how to do MySQL in python using the mysql.connector module. However, whenever I try creating a connection, I get the error "mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (10061 No connection coul... | Having trouble connecting with MySQL.connector in python | I am learning how to do MySQL in python using the mysql.connector module. However, whenever I try creating a connection, I get the error "mysql.connector.errors.InterfaceError: 2003: Can't connect to MySQL server on 'localhost:3306' (10061 No connection could be made because the target machine actively refused it)".
I ... | [
"import mySQL.connector\nMybd=mysql.connector.connect(\n host='myusername',\n user='myusername', \n password='mypassword', \n database='mydatabase')\nCursor=mycon.cursor()\nCursor.execute('show databases')\nData=cursor.fetchall()\nfor row in data:\n Print(row)\nmycon.close()\n\n"
] | [
0
] | [] | [] | [
"mysql",
"mysql_connector",
"python",
"python_sql",
"sql"
] | stackoverflow_0074590321_mysql_mysql_connector_python_python_sql_sql.txt |
Q:
Is there a way to interface with Python's SpaCy using Haskell?
I've read a little about Haskell's foreign function interface, FFI, and it seems like it can call Python functions, but can it do something complicated, like parse a document using SpaCy, and then access all that document's properties in Haskell? If so... | Is there a way to interface with Python's SpaCy using Haskell? | I've read a little about Haskell's foreign function interface, FFI, and it seems like it can call Python functions, but can it do something complicated, like parse a document using SpaCy, and then access all that document's properties in Haskell? If so, what would that look like?
| [
"I'm a bit late to the party, but nowadays there a number of out of the box options for setting up SpaCy as an API, as described by alvas which do the trick rather nicely. eg. https://github.com/microsoft/cookiecutter-spacy-fastapi\n"
] | [
1
] | [] | [] | [
"haskell",
"nlp",
"python",
"spacy"
] | stackoverflow_0048014298_haskell_nlp_python_spacy.txt |
Q:
Add a space in 2D array when writing a text file
I am trying to store a 2D vector into a .DAT file and I would like to add a space at the start of every row. An example of a desired output looks like this:
0.0000000E+00 0.0000000E+00
2.0020020E-03 0.0000000E+00
4.0040040E-03 0.0000000E+00
6.0060060E-03 0.0... | Add a space in 2D array when writing a text file | I am trying to store a 2D vector into a .DAT file and I would like to add a space at the start of every row. An example of a desired output looks like this:
0.0000000E+00 0.0000000E+00
2.0020020E-03 0.0000000E+00
4.0040040E-03 0.0000000E+00
6.0060060E-03 0.0000000E+00
8.0080080E-03 0.0000000E+00
1.0010010E-0... | [
"Consider using fmt argument to np.savetxt function, please note this one will set also set the number precision the same as in your desired output. Also note the space in the beginning of fmt string:\nnp.savetxt(datfile, data, fmt=\" %1.7E %1.7E\")\nMore on this in NumPy documentation and Python string module docu... | [
1,
0
] | [] | [] | [
"genfromtxt",
"numpy",
"numpy_ndarray",
"python"
] | stackoverflow_0074622918_genfromtxt_numpy_numpy_ndarray_python.txt |
Q:
Unexpected token # in JSON at position 0 when opening ipynb file in vscode
I have a ipynb file (a jupyter notebook) which I am opening in vscode with python extension. I receive the error in the title
Unexpected token # in JSON at position 0
which I dont understand at all, since the file is supposed to be interpre... | Unexpected token # in JSON at position 0 when opening ipynb file in vscode | I have a ipynb file (a jupyter notebook) which I am opening in vscode with python extension. I receive the error in the title
Unexpected token # in JSON at position 0
which I dont understand at all, since the file is supposed to be interpreted as a python file.
I can change the extension to .py and its opened fine by v... | [
"I had a similar problem and when I opened the notebook with an editor I saw I had merge markings that git had put into the file. e.g.\n<<<<<<< HEAD\n...\n=======\n...\n>>>>>>> ...\n\nCleaning up these, allowed jupyter to parse the file and run the notebook.\n",
"This happens when you make a request to the serve... | [
4,
3,
3,
1,
0,
0,
0
] | [] | [] | [
"jupyter",
"python",
"visual_studio_code"
] | stackoverflow_0063238337_jupyter_python_visual_studio_code.txt |
Q:
Can the transparency of the link be specified in the list?
Abstract
I am trying to find a way to make the nodes transparent. In the simple case, the transparency of a node is simply specified by the "alpha" option of "nx.draw".
However, I thought I could specify the transparency with a list, just as I specified th... | Can the transparency of the link be specified in the list? | Abstract
I am trying to find a way to make the nodes transparent. In the simple case, the transparency of a node is simply specified by the "alpha" option of "nx.draw".
However, I thought I could specify the transparency with a list, just as I specified the color with a list, but failed. Do you know the reason for this... | [
"Passing an array or a list of alpha values is supported only in the nx.draw_networkx_nodes:\n\nalpha : float or array of floats (default=None)\nThe node transparency. This can be a single alpha value,\nin which case it will be applied to all the nodes of color. Otherwise,\nif it is an array, the elements of alpha... | [
0
] | [] | [] | [
"alpha",
"matplotlib",
"networkx",
"python",
"python_3.x"
] | stackoverflow_0074622898_alpha_matplotlib_networkx_python_python_3.x.txt |
Q:
How to transform Row data into column data using pandas?
I exported many reports from my system in xls in the same specific format and need to change them to another format:
Basically for every item description I need to insert the corresponding Account series it is in column J using pandas.
Data
CP
N0
N1
ITEM
DE... | How to transform Row data into column data using pandas? | I exported many reports from my system in xls in the same specific format and need to change them to another format:
Basically for every item description I need to insert the corresponding Account series it is in column J using pandas.
Data
CP
N0
N1
ITEM
DEBIT
CREDIT
NET
D/C
Account: (663)
31/10/202... | [
"try this:\nmask = df['Data'].str.startswith('Account')\ndf['Account'] = df.groupby(mask.cumsum())['Data'].transform('first').mask(mask)\nprint(df)\n\n# df data like this:\n\ndata = [{'Data': 'Account: (663)',\n 'CP': 'nan',\n 'N0': 'nan',\n 'N1': 'nan',\n 'ITEM': 'nan',\n 'DEBIT': 'nan',\n 'CREDIT': 'nan',\n... | [
0,
0
] | [] | [] | [
"etl",
"pandas",
"python"
] | stackoverflow_0074622662_etl_pandas_python.txt |
Q:
looping My Selenium Python webdriver code beginner
I am a beginner and I wrote my first webdriver selenium python code. My question is how can I loop this code infinitely- I want the webdriver to close and then RE-open to continue the same code over and over. Can I add some kind of loop at the end of my code in or... | looping My Selenium Python webdriver code beginner | I am a beginner and I wrote my first webdriver selenium python code. My question is how can I loop this code infinitely- I want the webdriver to close and then RE-open to continue the same code over and over. Can I add some kind of loop at the end of my code in order to start it up so i can leave my PC and not have to ... | [
"You can use While loop:\nwhile True:\n options = {\n 'proxy': {\n 'https': 'XXXXXXXXX:3402',\n 'no_proxy': 'XXXXXXXX:3403'\n }\n }\n\n driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), seleniumwire_options=options)\n driver.get('https://www.... | [
0
] | [] | [] | [
"google_chrome",
"python",
"selenium",
"webdriver"
] | stackoverflow_0074622493_google_chrome_python_selenium_webdriver.txt |
Q:
How to find the highest value of a specified group using Python
In the example below, how do I find out the highest price of 'mansion' ?
Data Description
this is a csv dataset contains three columns:h_type,h_price,y_year.
Under the first column h_type, there are two different types of house, (mansion and apartmen... | How to find the highest value of a specified group using Python | In the example below, how do I find out the highest price of 'mansion' ?
Data Description
this is a csv dataset contains three columns:h_type,h_price,y_year.
Under the first column h_type, there are two different types of house, (mansion and apartment). The row is a list of a transaction.
Usage
I want to be able to ... | [
"The built-in min() and max() have two different signatures that allow you to call them either with an iterable as their first argument or with two or more regular arguments. The signature that accepts a single iterable argument looks something like this:\nmin(iterable, *[, default, key]) -> minimum_value\nmax(iter... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074622979_python.txt |
Q:
NameError: name 'Class_Name' is not defined
I have an issue which is I keep getting the error of NameError: name 'Class_Name' is not defined. Which I understand. The tricky part is that my code looks something like this:
class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"... | NameError: name 'Class_Name' is not defined | I have an issue which is I keep getting the error of NameError: name 'Class_Name' is not defined. Which I understand. The tricky part is that my code looks something like this:
class FirstClass():
second_class: SecondClass
def __init__(self):
"""SOME CODE HERE"""
class SecondClass(firsClass: FirstClass):
d... | [
"\nfrom pprint import pp\n\nclass FirstClass():\n\n #for typing, if you want to indicate a class variable\n second_class: type[\"SecondClass\"]\n\n #for typing, if you want to indicate an instance variable\n second_class_instance: \"SecondClass\"\n\n def __init__(self):\n \"\"\"SOME CODE HERE\"\"\"\n\n ... | [
0,
0
] | [] | [] | [
"class",
"nameerror",
"python",
"structure"
] | stackoverflow_0074410324_class_nameerror_python_structure.txt |
Q:
python tracing a segmentation fault
I'm developing C extensions from python and I obtain some segfaults (inevitable during the development...).
I'm searching for a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how can I do that?
A:
If you are on li... | python tracing a segmentation fault | I'm developing C extensions from python and I obtain some segfaults (inevitable during the development...).
I'm searching for a way to display at which line of code the segfault happens (an idea is like tracing every single line of code), how can I do that?
| [
"If you are on linux, run python under gdb\ngdb python\n(gdb) run /path/to/script.py\n## wait for segfault ##\n(gdb) backtrace\n## stack trace of the c code\n\n",
"Here's a way to output the filename and line number of every line of Python your code runs:\nimport sys\n\ndef trace(frame, event, arg):\n print(\"... | [
98,
47,
19,
15,
6,
1,
1
] | [] | [] | [
"c",
"debugging",
"python"
] | stackoverflow_0002663841_c_debugging_python.txt |
Q:
How to apply a user defined function between rows in pandas using both rows values?
I have two rows of data in a Pandas data frame and want to operate each column separately with a function that includes both values e.g.
import pandas as pd
df = pd.DataFrame({"x": [1, 2], "z": [2, 6], "i": [3, 12], "j": [4, 20... | How to apply a user defined function between rows in pandas using both rows values? | I have two rows of data in a Pandas data frame and want to operate each column separately with a function that includes both values e.g.
import pandas as pd
df = pd.DataFrame({"x": [1, 2], "z": [2, 6], "i": [3, 12], "j": [4, 20], "y": [5, 30]})
x z i j y
0 1 2 3 4 5
1 2 6 12 20 30
The... | [
"df.diff(1).div(df)\n\noutput\n x z i j y\n0 NaN NaN NaN NaN NaN\n1 0.5 0.67 0.75 0.8 0.83\n\nWith a short example, I answered. If I'm misunderstanding something, edit your example more long. I'll answer again.\n"
] | [
0
] | [] | [] | [
"apply",
"dataframe",
"pandas",
"python"
] | stackoverflow_0074623034_apply_dataframe_pandas_python.txt |
Q:
Add "collection" of attributes directly to top level of a class
I am trying to capture (S3) logs in a structured way. I am capturing the access-related elements with this type of tuple:
class _Access(NamedTuple):
time: datetime
ip: str
actor: str
request_id: str
action: str
key: str
re... | Add "collection" of attributes directly to top level of a class | I am trying to capture (S3) logs in a structured way. I am capturing the access-related elements with this type of tuple:
class _Access(NamedTuple):
time: datetime
ip: str
actor: str
request_id: str
action: str
key: str
request_uri: str
status: int
error_code: str
I then have a cla... | [
"What you really need for your use case is an alternative constructor for your NamedTuple subclass to parse a string of a log entry into respective fields, which can be done by creating a class method that calls the __new__ method with arguments parsed from the input string.\nUsing just the fields of ip and action ... | [
4,
1
] | [] | [] | [
"attributes",
"class",
"python"
] | stackoverflow_0074574306_attributes_class_python.txt |
Q:
How to make sure con1D's output_shape is same as input_shape with time series in keras autoencoder?
Conv1D output shape incorrect in keras autoencoder model when running autoencoder fit.
I try to use keras autoencoder model to compress and decompress my time-series data. but when I change the layer with Conv1D, t... | How to make sure con1D's output_shape is same as input_shape with time series in keras autoencoder? | Conv1D output shape incorrect in keras autoencoder model when running autoencoder fit.
I try to use keras autoencoder model to compress and decompress my time-series data. but when I change the layer with Conv1D, the output shape is incorrect.
I have some time series data with the shape of (4000, 689), where represent... | [
"Using Convolutional layers, you need to infer your output size based on the input size, kernel size and other parameters. The simplest way to do so is to feed a data sample through the network and see the final vector size after your last convolutional layer. Then, you can define further layers based on that size.... | [
0
] | [] | [] | [
"autoencoder",
"conv_neural_network",
"keras",
"python",
"time_series"
] | stackoverflow_0055731225_autoencoder_conv_neural_network_keras_python_time_series.txt |
Q:
Python Tkinter GUI does not open when the script is called by C# program
`
var psierror = new ProcessStartInfo();
psierror.FileName = @"C:\Users\Acer\AppData\Local\Programs\Python\Python310\python.exe";
psierror.Arguments = $"\"{exception_case}\" \"{Image}\"";
psierror.UseShellExecute = fal... | Python Tkinter GUI does not open when the script is called by C# program | `
var psierror = new ProcessStartInfo();
psierror.FileName = @"C:\Users\Acer\AppData\Local\Programs\Python\Python310\python.exe";
psierror.Arguments = $"\"{exception_case}\" \"{Image}\"";
psierror.UseShellExecute = false;
psierror.CreateNoWindow = true;
psierror.RedirectStandardO... | [
"It was an issue with my python script and I also changed the CreateNoWindow to false\n"
] | [
0
] | [] | [] | [
"c#",
"python",
"tkinter"
] | stackoverflow_0074622862_c#_python_tkinter.txt |
Q:
Python Wikipedia Library does not find requested page eventhough it exists
So I want to search the wikipedia database for some keywords and then extract the text that the relative pages have to then use for a tf-idf module to later on implement in a text classification program. I am currently looping through a pan... | Python Wikipedia Library does not find requested page eventhough it exists | So I want to search the wikipedia database for some keywords and then extract the text that the relative pages have to then use for a tf-idf module to later on implement in a text classification program. I am currently looping through a pandas dataframe with all the keywords and then searching the wikipedia database fo... | [
"Try setting the auto_suggest flag to False:\nwiki = wikipedia.page(currentRow, auto_suggest=False)\n\nIf we try this on the problematic string, \"Customer_advocacy,\" it seems to work:\nimport wikipedia\n\nwiki = wikipedia.page(\"Customer advocacy\", auto_suggest=False)\nprint(wiki) # <WikipediaPage 'Customer advo... | [
0
] | [] | [] | [
"python",
"wikipedia",
"wikipedia_api"
] | stackoverflow_0074623142_python_wikipedia_wikipedia_api.txt |
Q:
Web Scraping with Python - Because when I use FOR IN it just returns a string
Because when I print the item "Vagas", they return all the strings I need, but when I print "on_click" it returns only one string. And from what I've seen, it returns only the last string, ignoring the others.
soup = BeautifulSoup(string... | Web Scraping with Python - Because when I use FOR IN it just returns a string | Because when I print the item "Vagas", they return all the strings I need, but when I print "on_click" it returns only one string. And from what I've seen, it returns only the last string, ignoring the others.
soup = BeautifulSoup(stringue, "html.parser")
Vagas = soup.find_all(title="Vaga disponível.")
for teste2 in ... | [
"Put the print statement inside the for loop:\nfor teste2 in Vagas:\n on_click = teste2.get('onclick')\n print(on_click)\n\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"pandas",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074620714_beautifulsoup_pandas_python_selenium_web_scraping.txt |
Q:
Trying to find Total Sales & Total Cost of 3 different Countries cars
Update: Below is the excel file link.
I am brand new to Python and was doing this graph but I am stuck, I am trying to show a horizontal bar graph with 3 different countries, spain, germany, switzerland and trying to show the the total sales and... | Trying to find Total Sales & Total Cost of 3 different Countries cars | Update: Below is the excel file link.
I am brand new to Python and was doing this graph but I am stuck, I am trying to show a horizontal bar graph with 3 different countries, spain, germany, switzerland and trying to show the the total sales and total costs. I keep getting an error but not sure If my formula is correct... | [
"I don't think that you defined total in this part of the code. So, you may need to do totals.plot. You also didn't close the brackets.\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nsales= pd.read_excel('Simplified Car Sales Data.xlsx')\n\nspa= sales[sales['CountryName'] == 'Spain']\n\nspa_totals = spa.s... | [
0
] | [] | [] | [
"jupyter",
"python"
] | stackoverflow_0074623090_jupyter_python.txt |
Q:
Get the current version of the current package in Python
I am building a Python library and I have the requirement inside one of the modules to get the current version of this same library and make decisions based on the current version.
Is this possible in Python? What do you think is the best approach?
A:
You ... | Get the current version of the current package in Python | I am building a Python library and I have the requirement inside one of the modules to get the current version of this same library and make decisions based on the current version.
Is this possible in Python? What do you think is the best approach?
| [
"You should use dir(package) to see all the possible options for that package. If there is __version__, you can use that.\n",
"I found that the version of my library is being pulled from Github upon every release by setuptools_scm. The developers of setuptools_scm provide some tips on retrieving package version a... | [
0,
0
] | [] | [] | [
"python",
"python_3.x",
"version"
] | stackoverflow_0074623054_python_python_3.x_version.txt |
Q:
Google colab: downloading dataframes as csv or excel or google sheets
I am trying to save a dataframe from my google colab code to a csv, excel, or google sheet so that i can work with it in that form. I have been successful in downloading it however the format in the excel doc is off.
I want three columns (year/m... | Google colab: downloading dataframes as csv or excel or google sheets | I am trying to save a dataframe from my google colab code to a csv, excel, or google sheet so that i can work with it in that form. I have been successful in downloading it however the format in the excel doc is off.
I want three columns (year/mean/std) which i have in my dataframe. when I download it, it labels the co... | [
"Because you are using tab separation. You should remove sep='\\t' and download again.\n"
] | [
0
] | [] | [] | [
"export_to_csv",
"google_colaboratory",
"python"
] | stackoverflow_0074621626_export_to_csv_google_colaboratory_python.txt |
Q:
VS Code / Pylance / Pylint Cannot resolve import
The Summary
I have a python import that works when run from the VS Code terminal, but that VS Code's editor is giving warnings about. Also, "Go to Definition" doesn't work.
The Problem
I have created a docker container from the image tensorflow/tensorflow:1.15.2-py3... | VS Code / Pylance / Pylint Cannot resolve import | The Summary
I have a python import that works when run from the VS Code terminal, but that VS Code's editor is giving warnings about. Also, "Go to Definition" doesn't work.
The Problem
I have created a docker container from the image tensorflow/tensorflow:1.15.2-py3, then attach to it using VS Code's "Remote- Container... | [
"tldr;\nTensorFlow defines some of its modules in a way that pylint & pylance aren't able to recognize. These errors don't necessarily indicate an incorrect setup.\nTo Fix:\n\npylint: The pylint warnings are safely ignored.\nIntellisense: The best way I know of at the moment to fix Intellisense is to replace the im... | [
7,
3,
1,
1,
0
] | [] | [] | [
"pylance",
"pylint",
"python",
"tensorflow",
"visual_studio_code"
] | stackoverflow_0065271399_pylance_pylint_python_tensorflow_visual_studio_code.txt |
Q:
The Python Tools server crashed 5 times in the last 3 minutes. The server will not be restarted
The Python Server Crashes Unexpectedly. Am able to run in debug mode but the Linting is not working. Could anybody help me out please?
A:
I had a similar issue, which I resolved based on this answer. What I found was ... | The Python Tools server crashed 5 times in the last 3 minutes. The server will not be restarted | The Python Server Crashes Unexpectedly. Am able to run in debug mode but the Linting is not working. Could anybody help me out please?
| [
"I had a similar issue, which I resolved based on this answer. What I found was opening the folders individually seemed to work fine, but if I opened the workspace it caused the issues.\nDeleting the workspace and creating a new one seemed to solve the issue.\n",
"If anyone is facing this issue in the containers ... | [
1,
0,
0,
0
] | [] | [] | [
"python",
"visual_studio_code",
"vscode_extensions",
"vscode_settings"
] | stackoverflow_0068783077_python_visual_studio_code_vscode_extensions_vscode_settings.txt |
Q:
How to correctly write a merge sort algorithm with the use of a temporary list
I'm writing a merge sort with recursion, but it doesn't print out the correct message, however when I'm hand writing through the code, it seems right. could anyone help me to find out why?
def mergeSort1(arr):
if len(arr)<=1: #bas... | How to correctly write a merge sort algorithm with the use of a temporary list | I'm writing a merge sort with recursion, but it doesn't print out the correct message, however when I'm hand writing through the code, it seems right. could anyone help me to find out why?
def mergeSort1(arr):
if len(arr)<=1: #base case
return arr
else :
breakN =len(arr)//2
left = arr[:breakN]
r... | [
"Since you are not modifying the input list arr in-place and are returning a new list temp instead, you should assign the returning value of the function to a variable.\nChange:\nmergeSort1(left)\nmergeSort1(right)\n\nto:\nleft = mergeSort1(left)\nright = mergeSort1(right)\n\nAnd change:\nmergeSort1(arr)\nprint(arr... | [
0
] | [] | [] | [
"data_structures",
"mergesort",
"python",
"recursion"
] | stackoverflow_0074623297_data_structures_mergesort_python_recursion.txt |
Q:
Solving Canadian Computing Competition: "24"
I am trying to solve the problem above (Here is the link: https://dmoj.ca/problem/ccc08s4) using python but am running into difficulties. The problem asks to determine if 4 number when multiplied, subtracted, added, or divided can yield 24. Parenthesis are also allowed ... | Solving Canadian Computing Competition: "24" | I am trying to solve the problem above (Here is the link: https://dmoj.ca/problem/ccc08s4) using python but am running into difficulties. The problem asks to determine if 4 number when multiplied, subtracted, added, or divided can yield 24. Parenthesis are also allowed to specify precedence. If such a value is not poss... | [
"One way is to consider the postfix expression instead of the infix expression.\nE.g, for the infix expression (A+B)*(C-D), we'll consider the postfix expression AB+CD-* instead.\nIt can be observed that there will be no need for parenthesis in postfix expression, which makes them more friendly to machine.\nSo you ... | [
1
] | [] | [] | [
"algorithm",
"python",
"python_3.x"
] | stackoverflow_0074621629_algorithm_python_python_3.x.txt |
Q:
Python Openpyxl - Append many excel files into 1 file
I have 10 Excel files (they have same number of columns, and varying number of rows)
I need to append data from those 10 files into one single Excel file using Openpyxl Python library
Read data from File1, append it to new_file
Read data from File2, append it t... | Python Openpyxl - Append many excel files into 1 file | I have 10 Excel files (they have same number of columns, and varying number of rows)
I need to append data from those 10 files into one single Excel file using Openpyxl Python library
Read data from File1, append it to new_file
Read data from File2, append it to new_file
...
Is this possible? Can anyone help me?
Thank ... | [
"There are some missing details in the question, as raised by @moken. Let's make some assumptions that all files have a single sheet named 'Sheet 1' and identical column headers. And the final output will start with file10's content, then file9 etc and we will skip copying the column headers.\nFor the sake of simpl... | [
1
] | [] | [] | [
"excel",
"openpyxl",
"python"
] | stackoverflow_0074621496_excel_openpyxl_python.txt |
Q:
Unable to perform join in mongodb using a package and code specified in https://pypi.org/project/mongojoin/
Unable to execute $lookup in mongodb. I need to perform join in mongodb using Python, but the code and package specified in https://pypi.org/project/mongojoin/ is not working.
Also, can $lookup be run from m... | Unable to perform join in mongodb using a package and code specified in https://pypi.org/project/mongojoin/ | Unable to execute $lookup in mongodb. I need to perform join in mongodb using Python, but the code and package specified in https://pypi.org/project/mongojoin/ is not working.
Also, can $lookup be run from mongoshell, and if yes, how?
I am using the following code:
from mongojoin.mongojoin import MongoJoin, MongoCollec... | [
"I have converted the cursors to lists then appended one list with another.\nIt worked...\n",
"enter image description here\nDownload the zip file of mongojoin from GIT and paste the files in same loaction of the file from where you are trying to import the mongojoin packages.\nuse Imports as Following:\n**\n\nfr... | [
0,
0
] | [
"Update the below changes to mongo.py library after installing \"pip install process-data & pip install sklearn\"\n\"from process_data.setup.collections import CollectionsProcessedData\"\n\n"
] | [
-1
] | [
"join",
"lookup",
"mongodb",
"python"
] | stackoverflow_0064872133_join_lookup_mongodb_python.txt |
Q:
Check if an array contains values from a list and add list as columns
I have a data_frame as below,
Id
Col1
1
[["A", "B", "E", "F"]]
2
[["A", "D", "E"]]
I have a list as ["A", "B", "C"]
I would like to add the elements in the list as columns and check if the exist in col1 or not. So my expected output will be ... | Check if an array contains values from a list and add list as columns | I have a data_frame as below,
Id
Col1
1
[["A", "B", "E", "F"]]
2
[["A", "D", "E"]]
I have a list as ["A", "B", "C"]
I would like to add the elements in the list as columns and check if the exist in col1 or not. So my expected output will be like,
Id
Col1
A
B
C
1
[["A", "B", "E", "F"]]
1
1
0
2
[[... | [
"This can be achieved using a list comprehension.\n\nls = [\"A\", \"B\", \"C\"]\n...\ndf = df.select('*', *[F.array_contains('col1', c).cast('int').alias(c) for c in ls])\n\n"
] | [
0
] | [] | [] | [
"apache_spark_sql",
"arrays",
"pyspark",
"python"
] | stackoverflow_0074623329_apache_spark_sql_arrays_pyspark_python.txt |
Q:
If column header = specific value condition
I am trying to create a condition where if the column headers in my dataframe are equal to
Unnamed: 0 VALUE VALUE.1 VALUE.2 then i want to do drop the first two rows and rename the headers
Unnamed: 0 VALUE VALUE.1 VALUE.2
Name Hobbies D... | If column header = specific value condition | I am trying to create a condition where if the column headers in my dataframe are equal to
Unnamed: 0 VALUE VALUE.1 VALUE.2 then i want to do drop the first two rows and rename the headers
Unnamed: 0 VALUE VALUE.1 VALUE.2
Name Hobbies Dislikes Favorite Color
Ben NaN ... | [
"Firstly, you only need to drop row 0 cause columns is not a row.\nThen the == should be used in the if statement, and it's a list comparison, so add .all()\nimport pandas as pd\n\ndf = pd.DataFrame(columns=[\"Unnamed: 0\", \"VALUE\", \"VALUE.1\", \"VALUE.2\"])\ndf.loc[0] = ['Name', 'Hobbies', 'Dislikes', 'Favorite... | [
2,
2,
0
] | [] | [] | [
"dataframe",
"if_statement",
"pandas",
"python"
] | stackoverflow_0074623137_dataframe_if_statement_pandas_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.