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:
I can't figure out this input
num = 0
def calculate1(player1, num):
if player1 == 1:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 2:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 3:
... | I can't figure out this input | num = 0
def calculate1(player1, num):
if player1 == 1:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 2:
num = num + player1
print(f"The number is {num}")
return (num)
elif player1 == 3:
num = num + player1
prin... | [
"If you only want to ask once:\n#yrn = yes or no\nyrn = input(\"Are you going to play game? (Y/N) : \").upper()\nif yrn == \"Y\":\n player1 = int(input(\"How many numbers are you going to add? : \"))\n if player1 > 3:\n player1 = int(input(\"How many numbers are you going to add? : \"))\n num = calc... | [
0,
0
] | [] | [] | [
"input",
"loops",
"numbers",
"python"
] | stackoverflow_0074625424_input_loops_numbers_python.txt |
Q:
Is there any way to concatenate tuples with a maximum lenght?
I'm concatenating three tuples from a csv but i´m thinking if there is any way to do it with a maximum lenght.
I´m doing this:
df = pd.read_csv(FILE_NAME, header = 0)
df['all'] = df['Header'] + df['Subtitle'] + df['Text']
I want df['all] to be at most ... | Is there any way to concatenate tuples with a maximum lenght? | I'm concatenating three tuples from a csv but i´m thinking if there is any way to do it with a maximum lenght.
I´m doing this:
df = pd.read_csv(FILE_NAME, header = 0)
df['all'] = df['Header'] + df['Subtitle'] + df['Text']
I want df['all] to be at most 500 characters
Thank you in advice
| [
"You can slice the concatenation:\ndf['all'] = (df['Header'] + df['Subtitle'] + df['Text']).str[:500]\n\n",
"You can use the df.head() function to get the first rows of a dataframe:\ndf = pd.read_csv(FILE_NAME, header = 0)\ndf_short = df.head(500)\ndf_short['all'] = df_short['Header'] + df_short['Subtitle'] + df_... | [
0,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074625535_pandas_python.txt |
Q:
Append value to each array in a numpy array
I have a numpy array of arrays, for example:
x = np.array([[1,2,3],[10,20,30]])
Now lets say I want to extend each array with [4,40], to generate the following resulting array:
[[1,2,3,4],[10,20,30,40]]
How can I do this without making a copy of the whole array? I trie... | Append value to each array in a numpy array | I have a numpy array of arrays, for example:
x = np.array([[1,2,3],[10,20,30]])
Now lets say I want to extend each array with [4,40], to generate the following resulting array:
[[1,2,3,4],[10,20,30,40]]
How can I do this without making a copy of the whole array? I tried to change the shape of the array in place but i... | [
"You can't do this. Numpy arrays allocate contiguous blocks of memory, if at all possible. Any change to the array size will force an inefficient copy of the whole array. You should use Python lists to grow your structure if possible, then convert the end result back to an array.\nHowever, if you know the final siz... | [
3,
1,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0053418727_arrays_numpy_python.txt |
Q:
How to feed a modified value back into the modification loop in Python
I have a list of string values (Telegram posts). Many of those individual values include string patterns I want to remove (JSON formatting).
An example string value would be, "['Оппозиционный российский политик Алесей Навальный впал в кому. Его... | How to feed a modified value back into the modification loop in Python | I have a list of string values (Telegram posts). Many of those individual values include string patterns I want to remove (JSON formatting).
An example string value would be, "['Оппозиционный российский политик Алесей Навальный впал в кому. Его соратники считают, что его отравили.\n\nСейчас Навальный находится в омской... | [
"Looks good, you only need to apply one after the other. No need for a clean text variable, calling a function with a string generates a new object (like call-by-value if you know the term, read more here).\ndef clean_message_text(dirty_text):\n corrections_data = load_corrections(corrections_filepath) \n for... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0074625411_python.txt |
Q:
How di I fix this Error? self.category_id.set(row[1]), IndexError: string index out of range
I'm adding data into sqlite table and when I try to update the table, I'm getting this error 'string index not in range'.
Again when I execute the update command, all the columms gets updated except the identity column but... | How di I fix this Error? self.category_id.set(row[1]), IndexError: string index out of range | I'm adding data into sqlite table and when I try to update the table, I'm getting this error 'string index not in range'.
Again when I execute the update command, all the columms gets updated except the identity column but my intention is only to update a selected row.
what I not doing right from the code below>
Your a... | [
"Your update function updates all the records exist. To avoid this you should use WHERE. Here its fixed version\ndef update_record(self):\n selected = self.trv.focus()\n \n oldValues = self.trv.item(selected)[\"values\"]\n\n self.trv.item(selected, values=(oldValues[0],\n self.category_id.get(), ... | [
0
] | [] | [] | [
"python",
"sqlite",
"tkinter"
] | stackoverflow_0074625300_python_sqlite_tkinter.txt |
Q:
why do I receive these errors "WARNING: Ignoring invalid distribution -yproj " while installing any python module in cmd
WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\appdata\local\programs\python\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\a... | why do I receive these errors "WARNING: Ignoring invalid distribution -yproj " while installing any python module in cmd | WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\appdata\local\programs\python\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\appdata\local\programs\python\python310\lib\site-packages)
WARNING: Ignoring invalid distribution -yproj (c:\users\space_junk\a... | [
"I was getting a similar message that turned out be caused by a previous failed pip upgrade. I had attempted to upgrade pip from a user account that didn't have the proper rights. There was a temp directory left behind in site-packages that began with ~ip which was causing pip to complain every time it ran. I re... | [
6,
0
] | [] | [] | [
"fiona",
"geopandas",
"osgeo",
"python",
"torch"
] | stackoverflow_0072547834_fiona_geopandas_osgeo_python_torch.txt |
Q:
Logic Python task with bitwise operators
I have a very specific task to complete and I am honestly lost in it. The goal is to define function in Python, that would remove all 1s in binary input that do not have any 1 next to it. I will show you in example.
Let's have input 0b11010 -–> the output of this would be 0... | Logic Python task with bitwise operators | I have a very specific task to complete and I am honestly lost in it. The goal is to define function in Python, that would remove all 1s in binary input that do not have any 1 next to it. I will show you in example.
Let's have input 0b11010 -–> the output of this would be 0b11000. Another example 0b10101 --> output wou... | [
"To break down the condition mathematically, the i-th bit of the output should be 1 if and only if:\n\nThe i-th bit of the input is 1.\nAnd either the (i-1)-th bit or the (i+1)-th bit of the input is also 1.\n\nLogically the condition is input[i] and (input[i-1] or input[i+1]) if the input is a bit vector. If the i... | [
3
] | [] | [] | [
"algorithm",
"bit",
"bitwise_operators",
"logic",
"python"
] | stackoverflow_0074625271_algorithm_bit_bitwise_operators_logic_python.txt |
Q:
Initialising variables in an init_vars() function
This code doesn't initializes the variables that I expect to be initialized.
a,b,c = [None]*3
def __init_abc():
a="a"
b="b"
c="c"
def print_abc():
__init_abc()
print(a,b,c)
print_abc()
Output is:
None None None
A:
Within the __init... | Initialising variables in an init_vars() function | This code doesn't initializes the variables that I expect to be initialized.
a,b,c = [None]*3
def __init_abc():
a="a"
b="b"
c="c"
def print_abc():
__init_abc()
print(a,b,c)
print_abc()
Output is:
None None None
| [
"Within the __init_abc function you need to specify the global variables a, b, c otherwise the variables are presumed to be local to the function.\na,b,c = [None]*3\n\ndef __init_abc():\n global a,b,c\n a=\"a\"\n b=\"b\"\n c=\"c\"\n \ndef print_abc():\n __init_abc()\n print(a,b,c)\n \nprint_... | [
0
] | [] | [] | [
"global_variables",
"python"
] | stackoverflow_0074577178_global_variables_python.txt |
Q:
The function np.dot multiplies the GF4 field matrices for a very long time
Multiplies large matrices for a very long time. How can this problem be solved. I use the galois library, and numpy, I think it should still work stably. I tried to implement my GF4 arithmetic and multiplied matrices using numpy, but it tak... | The function np.dot multiplies the GF4 field matrices for a very long time | Multiplies large matrices for a very long time. How can this problem be solved. I use the galois library, and numpy, I think it should still work stably. I tried to implement my GF4 arithmetic and multiplied matrices using numpy, but it takes even longer. Thank you for your reply.
When r = 2,3,4,5,6 multiplies quickly,... | [
"I'm not sure if it is actually faster but np.dot should be used for the dot product of two vectors, for matrix multiplication use A @ B. That's as efficient as you can get with Python as far as I know\n",
"Try using jax on a CUDA runtime. For example, you can try it out on Google Colab's free GPU. (Open a notebo... | [
0,
0
] | [] | [] | [
"galois_field",
"linear_algebra",
"math",
"numpy",
"python"
] | stackoverflow_0074625066_galois_field_linear_algebra_math_numpy_python.txt |
Q:
Django download a file
I'm quite new to using Django and I am trying to develop a website where the user is able to upload a number of excel files, these files are then stored in a media folder Webproject/project/media.
def upload(request):
if request.POST:
form = FileForm(request.POST, request.FILES)
... | Django download a file | I'm quite new to using Django and I am trying to develop a website where the user is able to upload a number of excel files, these files are then stored in a media folder Webproject/project/media.
def upload(request):
if request.POST:
form = FileForm(request.POST, request.FILES)
if form.is_valid():
... | [
"You missed underscore in argument document_root. But it's bad idea to use serve in production. Use something like this instead:\nimport os\nfrom django.conf import settings\nfrom django.http import HttpResponse, Http404\n\ndef download(request, path):\n file_path = os.path.join(settings.MEDIA_ROOT, path)\n i... | [
129,
59,
34,
7,
4,
2,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0036392510_django_python.txt |
Q:
How could I use 'assert' and a variable 'actual' to write a test code for a user input code for the conversion of time?
`
def conversion():
options = print('Would you like to convert hours to mins, or mins to hours?')
choice = input()
if choice == 'hours to mins':
hours = int(input('How many h... | How could I use 'assert' and a variable 'actual' to write a test code for a user input code for the conversion of time? | `
def conversion():
options = print('Would you like to convert hours to mins, or mins to hours?')
choice = input()
if choice == 'hours to mins':
hours = int(input('How many hours? '))
mins = hours * 60
print(mins, 'Minutes')
elif choice == 'mins to hours':
mins = int(inp... | [
"You can use pytest with the pytest-mock extension. Install them via pip or conda, or whatever you use.\n\nQuick Fix\nFirst I made a small change to your code to make it a bit easier to test: I added a return statement. Now the code will also return the result.\n# conversion.py\ndef conversion():\n print('Would ... | [
1,
0
] | [] | [] | [
"jupyter",
"jupyter_notebook",
"python",
"python_unittest",
"ubuntu"
] | stackoverflow_0074625146_jupyter_jupyter_notebook_python_python_unittest_ubuntu.txt |
Q:
Conway's Game of Life in Python - Competitive Programming - how to optimize
I am solving Game of Life problem on csacademy and I can't manage to beat the time on larger inputs. Any help on optimizing the code?
I tried changing things, like using np.array() instead of list, and not converting the original input to ... | Conway's Game of Life in Python - Competitive Programming - how to optimize | I am solving Game of Life problem on csacademy and I can't manage to beat the time on larger inputs. Any help on optimizing the code?
I tried changing things, like using np.array() instead of list, and not converting the original input to 1s and 0s (original is '*' and '-', and needs to be printed that way).
from copy ... | [
"This mathematical solution seems to help pass more tests, but there are still a few that fail.\ndef gameOfLife(mat, n, m, C):\n cells = deepcopy(mat)\n loop = n*m*4*3*5\n while loop % 16:\n loop *= 2\n num_iter = C % loop\n for c in range(num_iter):\n for i in range(n):\n fo... | [
0
] | [] | [] | [
"conways_game_of_life",
"numpy",
"optimization",
"performance",
"python"
] | stackoverflow_0071280998_conways_game_of_life_numpy_optimization_performance_python.txt |
Q:
How to fix Key error "Item" dynamodb, if item does not exist?
def func(name):
ddb = session.resource(service_name="dynamodb")
table = ddb.Table("TABLE_X")
response = table.get_item(Key={"employee": user})
data = response["Item"]
for item in data.items():
if data["employee"] == name:
... | How to fix Key error "Item" dynamodb, if item does not exist? | def func(name):
ddb = session.resource(service_name="dynamodb")
table = ddb.Table("TABLE_X")
response = table.get_item(Key={"employee": user})
data = response["Item"]
for item in data.items():
if data["employee"] == name:
manager = data["manager"]
return name, manager... | [
"You can check if a key is in a dictionary with 'foo' in bar. So judging from the comments you want to return False and print an error message if something is not found.\n\nexplicit check\nFor each key you want, check if it exists:\n\n\ndef func(name):\n ddb = session.resource(service_name=\"dynamodb\")\n tab... | [
0
] | [] | [] | [
"amazon_dynamodb",
"python"
] | stackoverflow_0074625105_amazon_dynamodb_python.txt |
Q:
How to pass a variable from one function to another function
I am making python based Email broadcasting in which i have created entries like email, pass, there is csv browse as well which will brose a Email_list_container file and a submit button which will call a send mail function to send bulk email along with... | How to pass a variable from one function to another function | I am making python based Email broadcasting in which i have created entries like email, pass, there is csv browse as well which will brose a Email_list_container file and a submit button which will call a send mail function to send bulk email along with attachment, problem is when browse is used to grab emails from cs... | [
"Just return recemail from browse function then pass it as argument to submit function:\n def browse():\n from itertools import chain\n file_path=filedialog.askopenfilename(title=\"Open CSV file\")\n with open(file_path) as csvfile:\n read = csv.reader(csvfile)\n for row i... | [
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0074618553_function_python.txt |
Q:
Selenium TimeoutException: Message using selenium
from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.web... | Selenium TimeoutException: Message using selenium | from selenium import webdriver
import time
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from bs4 import BeautifulSoup
import pandas as pd
from selenium.webdriver.support import expected_conditions as EC
from se... | [
"There are several issues you need to improve here:\n\nThe Aaaa89455bbfe4387b92529246ea52dc6114 class you trying to use is a dynamic value. This can't be used as a locator.\nThe first element you clicking to enter the system - you should wait for element clickability, not only visibility. These conditions are almos... | [
0
] | [] | [] | [
"python",
"selenium",
"web_scraping",
"webdriverwait",
"xpath"
] | stackoverflow_0074625443_python_selenium_web_scraping_webdriverwait_xpath.txt |
Q:
How to import GDAL embedded in new Fiona wheels
Since october 2022, Fiona's wheels include GDAL (according to the releases documentations). Many packages refer to GDAL using this command, but it won't work :
from osgeo import gdal
For instance, I've just loaded an environment using poetry (and python 3.9.15 on Li... | How to import GDAL embedded in new Fiona wheels | Since october 2022, Fiona's wheels include GDAL (according to the releases documentations). Many packages refer to GDAL using this command, but it won't work :
from osgeo import gdal
For instance, I've just loaded an environment using poetry (and python 3.9.15 on Linux) :
poetry new dummy
cd dummy
poetry add geopandas... | [
"Long story short : you can't simply switch from osgeo to Fiona.\nIn fact, Fiona doesn't includes GDAL python package (ie. the GDAL python bindings) but the shared library :\nFrom Sean Gillies :\n\nFiona's wheels contain a GDAL shared library (libgdal.dll or .so or .dylib) and its own library dependencies (libproj,... | [
0
] | [] | [] | [
"fiona",
"gdal",
"python"
] | stackoverflow_0074559182_fiona_gdal_python.txt |
Q:
ERROR in CNN Pytorch; shape '[-1, 192]' is invalid for input of size 300000
I want to change kernal size to 3, output channels of convolutional layers to 8 and 16 respectively. But when i try to change it i get an error message The following code is working fine but when I change kernal size and output channels li... | ERROR in CNN Pytorch; shape '[-1, 192]' is invalid for input of size 300000 | I want to change kernal size to 3, output channels of convolutional layers to 8 and 16 respectively. But when i try to change it i get an error message The following code is working fine but when I change kernal size and output channels like this:
self.conv1 = nn.Conv2d(in_channels=1,out_channels=**8**,kernel_size=... | [
"By changing your kernel size and output size in intermediate filters, you also change the size of your intermediate activations.\nI suppose your input data is of size (1,28,28) (the usual size for FashionMNIST).\nIn your original code, before the layer self.fc1, after two 2D convolutionnal layers and two maxpools,... | [
0
] | [] | [] | [
"conv_neural_network",
"python",
"pytorch"
] | stackoverflow_0074625420_conv_neural_network_python_pytorch.txt |
Q:
Get number from textbox
I have a textbox which is displayed in my window. I want to get the number from this textbox (inputted from the user) and use it for calculations
n=Text(window,width=6,height=2,bg="white").place(x=20,y=80)
num1=n.get(1.0,END)
A:
Try
num1=n.get("1.0","end")
| Get number from textbox | I have a textbox which is displayed in my window. I want to get the number from this textbox (inputted from the user) and use it for calculations
n=Text(window,width=6,height=2,bg="white").place(x=20,y=80)
num1=n.get(1.0,END)
| [
"Try\nnum1=n.get(\"1.0\",\"end\")\n"
] | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0074625727_python_tkinter.txt |
Q:
scikit learn output metrics.classification_report into CSV/tab-delimited format
I'm doing a multiclass text classification in Scikit-Learn. The dataset is being trained using the Multinomial Naive Bayes classifier having hundreds of labels. Here's an extract from the Scikit Learn script for fitting the MNB model
f... | scikit learn output metrics.classification_report into CSV/tab-delimited format | I'm doing a multiclass text classification in Scikit-Learn. The dataset is being trained using the Multinomial Naive Bayes classifier having hundreds of labels. Here's an extract from the Scikit Learn script for fitting the MNB model
from __future__ import print_function
# Read **`file.csv`** into a pandas DataFrame
... | [
"As of scikit-learn v0.20, the easiest way to convert a classification report to a pandas Dataframe is by simply having the report returned as a dict:\nreport = classification_report(y_test, y_pred, output_dict=True)\n\nand then construct a Dataframe and transpose it:\ndf = pandas.DataFrame(report).transpose()\n\nF... | [
110,
21,
13,
10,
6,
6,
4,
3,
3,
2,
2,
1,
1,
0,
0,
0,
0,
0
] | [
"The way I have always solved output problems is like what I've mentioned in my previous comment, I've converted my output to a DataFrame. Not only is it incredibly easy to send to files (see here), but Pandas is really easy to manipulate the data structure. The other way I have solved this is writing the output li... | [
-2
] | [
"classification",
"csv",
"python",
"scikit_learn",
"text"
] | stackoverflow_0039662398_classification_csv_python_scikit_learn_text.txt |
Q:
Running a Python function in BASH
I usually run Python on Google Colab, however I need to run a script in the terminal in Ubuntu.
I have the following script
test.py:
#!/usr/bin/env python
# testing a func
def hello(x):
if x > 5:
return "good"
else:
return "bad"
hello(2)
When executed it fails to r... | Running a Python function in BASH | I usually run Python on Google Colab, however I need to run a script in the terminal in Ubuntu.
I have the following script
test.py:
#!/usr/bin/env python
# testing a func
def hello(x):
if x > 5:
return "good"
else:
return "bad"
hello(2)
When executed it fails to return anything. Now I could just replac... | [
"You don't print anything to STDOUT so you won't see the good/bad in your terminal.\nYou should change hello(2) line to print(hello(2)) in your code (In this case the return value of hello(2) function call will be printed to STDOUT file descriptor) then you will see your result in your terminal.\n",
"In case you ... | [
2,
0
] | [] | [] | [
"bash",
"python",
"terminal"
] | stackoverflow_0074624724_bash_python_terminal.txt |
Q:
Problem triggering nested dependencies in Azure Function
I have a problem using the videohash package for python when deployed to Azure function.
My deployed azure function does not seem to be able to use a nested dependency properly. Specifically, I am trying to use the package “videohash” and the function VideoH... | Problem triggering nested dependencies in Azure Function | I have a problem using the videohash package for python when deployed to Azure function.
My deployed azure function does not seem to be able to use a nested dependency properly. Specifically, I am trying to use the package “videohash” and the function VideoHash from it. The
input to VideoHash is a SAS url token for a v... | [
"\nI have a work around where you download the video file on you own instead of the videohash using azure.storage.blob\n\nTo download you will need a BlobServiceClient , ContainerClient and connection string of azure storage account.\n\nPlease create two files called v1.mp3 and v2.mp3 before downloading the video.... | [
0
] | [] | [] | [
"azure",
"azure_functions",
"python",
"yt_dlp"
] | stackoverflow_0074552478_azure_azure_functions_python_yt_dlp.txt |
Q:
Selecting links within a div tag using beautiful soup
I am trying to run the following code
headers = {
'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
pa... | Selecting links within a div tag using beautiful soup | I am trying to run the following code
headers = {
'User-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36'
}
params = {
'q': 'Machine learning,
... | [
"The following is tested and works:\nimport requests\nfrom bs4 import BeautifulSoup as bs\n\nheaders = {\n'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.5112.79 Safari/537.36'\n}\n\nparams = {\n 'q': 'Machine learning',\n 'hl': 'en'\n }\nhtml = reques... | [
1
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074624730_beautifulsoup_html_python_web_scraping.txt |
Q:
reading pdf file using tabula
I have a pdf file with tables in it and would like to read it as a dataframe using tabula. But only the first page has column header. While reading using
tabula.read_pdf(pdf_file, pages='all', lattice = 'True')
the data is coming in desired format and all the pages are extracted prop... | reading pdf file using tabula | I have a pdf file with tables in it and would like to read it as a dataframe using tabula. But only the first page has column header. While reading using
tabula.read_pdf(pdf_file, pages='all', lattice = 'True')
the data is coming in desired format and all the pages are extracted properly however while using
pd.DataFra... | [
"You should actually do it this way (assumming your pdf doesn't contain both text and tables)\ntable = tabula.read_pdf(pdf_file, pages='all',output_format=\"dataframe\" ,lattice = 'True')\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"tabula"
] | stackoverflow_0074624251_dataframe_pandas_python_tabula.txt |
Q:
Type Narrowing of Class Attributes in Python (TypeGuard) without Subclassing
Consider I have a python class that has a attributes (i.e. a dataclass, pydantic, attrs, django model, ...) that consist of a union, i.e. None and and a state.
Now I have a complex checking function that checks some values.
If I use this ... | Type Narrowing of Class Attributes in Python (TypeGuard) without Subclassing | Consider I have a python class that has a attributes (i.e. a dataclass, pydantic, attrs, django model, ...) that consist of a union, i.e. None and and a state.
Now I have a complex checking function that checks some values.
If I use this checking function, I want to tell the type checker, that some of my class attribut... | [
"TL;DR: You cannot narrow the type of an attribute. You can only narrow the type of an object.\nAs I already mentioned in my comment, for typing.TypeGuard to be useful it relies on two distinct types T and S. Then, depending on the returned bool, the type guard function tells the type checker to assume the object t... | [
1
] | [] | [] | [
"python",
"python_typing",
"type_narrowing",
"typeguards"
] | stackoverflow_0074624626_python_python_typing_type_narrowing_typeguards.txt |
Q:
WebDriverWait by class name when there are more class with the same name
I’m trying to click on a button that has the same class as other 5 buttons.
This code is working but clicks on the first button that finds the class.
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5"... | WebDriverWait by class name when there are more class with the same name | I’m trying to click on a button that has the same class as other 5 buttons.
This code is working but clicks on the first button that finds the class.
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".com-ex-5"))).click()
How can I click on the 5th button?
This ain’t working :
WebDriver... | [
"presence_of_element_located returns single element. You need to use presence_of_all_elements_located.\nSo that your code would look like:\nWebDriverWait(driver, 10)\n .until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, \".com-ex-5\")))[4]\n .click()\n\nP.S. - If you need 5th button then you need to ... | [
0,
0
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"webdriverwait",
"xpath"
] | stackoverflow_0074623486_css_selectors_python_selenium_webdriverwait_xpath.txt |
Q:
how to make a system in python that support limited users? for instance, it should support 200 users
How to Limit the amount of user registration? a system that should support a limited amount of users? how can we do that? please someone suggest a tutorial, website, or any good source.
I try to search about it but... | how to make a system in python that support limited users? for instance, it should support 200 users | How to Limit the amount of user registration? a system that should support a limited amount of users? how can we do that? please someone suggest a tutorial, website, or any good source.
I try to search about it but I couldn't find any useful thing on the internet
| [
"Information you provided is little insufficient, but do you mean check of registered user before new registration?\nSomething like this?\ndef check_max_users(db_connection):\n users_count = db_connection.query(\"SELECT COUNT(*) AS users_count FROM users\").first().users_count\n if users_count > 200:\n raise M... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074625898_python.txt |
Q:
exploding a multi dictionnary columns
I have a data that contains +15 columns all of them with dictionnary as values. all of the dictionnary has the same keys but different values depending on th column and the key of course. i need to explode them into on data that has the keys as index;this a part of the data
i ... | exploding a multi dictionnary columns | I have a data that contains +15 columns all of them with dictionnary as values. all of the dictionnary has the same keys but different values depending on th column and the key of course. i need to explode them into on data that has the keys as index;this a part of the data
i ve tried this code ! but it only work on on... | [
"If you check explode function documentation in pandas, to explode multiple column you can achieve that in this format:\nDataFrame.explode(list(col1col2col3...))\n\nfor your case:\ndf.explode(list('halstead_volcyclomatic_complexityh1'), ignore_index=True)\n\nFor dictionary values try this:\nnew_df = df['halstead_vo... | [
0
] | [] | [] | [
"pandas",
"pandas_explode",
"python"
] | stackoverflow_0074625840_pandas_pandas_explode_python.txt |
Q:
AttributeError: 'str' object has no attribute 'readline' when trying to get all lines from a file
trying to get all lines in a file and print them out
topic = 1
if topic == 1:
allquestions = open("quizquestions1.txt","r")
allquestions = allquestions.read()
print(allquestions.readfile())
A:
It's only ... | AttributeError: 'str' object has no attribute 'readline' when trying to get all lines from a file | trying to get all lines in a file and print them out
topic = 1
if topic == 1:
allquestions = open("quizquestions1.txt","r")
allquestions = allquestions.read()
print(allquestions.readfile())
| [
"It's only allquestions in print..You alredy read lines before no need to read again.\ntopic = 1\nif topic == 1:\n allquestions = open(\"quizquestions1.txt\",\"r\")\n allquestions = allquestions.read()\n print(allquestions)\n\n",
"The read method for a file will return the file content. You can use help ... | [
1,
0
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0074625876_error_handling_python.txt |
Q:
Aggregate and concatenate multiple columns
I want to groupby my dataframe and concatenate the values/strings from the other columns together.
Year Letter Number Note Text
0 2022 a 1 8 hi
1 2022 b 1 7 hello
2 2022 a 1 6 bye
3 2022 b 3 5 ... | Aggregate and concatenate multiple columns | I want to groupby my dataframe and concatenate the values/strings from the other columns together.
Year Letter Number Note Text
0 2022 a 1 8 hi
1 2022 b 1 7 hello
2 2022 a 1 6 bye
3 2022 b 3 5 joe
To this:
Column
Year Letter... | [
"You can first join values per rows converted to strings by DataFrame.astype and DataFrame.agg and then aggregate join in GroupBy.agg:\ndf1 = (df.assign(Text= df[['Number','Note','Text']].astype(str).agg('|'.join, axis=1))\n .groupby(['Year', 'Letter'])['Text']\n .agg('; '.join)\n .to_frame(... | [
2,
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074625959_pandas_python.txt |
Q:
DateTime to quarter end in Pandas
My current date is in this format "202003", "202006", "202009". I want to change it to "2020-03-31", "2020-06-30", "2020-09-30".
Here is my code:
df6['Date'] = pd.to_datetime(df6['Date'], format = "%Y%m").dt.strftime('%Y-%m-%d')
df6['Date'] = df6['Date'] + pd.offsets.QuarterEnd(0)... | DateTime to quarter end in Pandas | My current date is in this format "202003", "202006", "202009". I want to change it to "2020-03-31", "2020-06-30", "2020-09-30".
Here is my code:
df6['Date'] = pd.to_datetime(df6['Date'], format = "%Y%m").dt.strftime('%Y-%m-%d')
df6['Date'] = df6['Date'] + pd.offsets.QuarterEnd(0)
TypeError: unsupported operand type(s... | [
"Add the date offset before converting to string with strftime, Ex:\nimport pandas as pd\n\ndf = pd.DataFrame({\"Date\": [\"202003\", \"202006\", \"202009\"]})\n\ndf['Date'] = pd.to_datetime(df['Date'], format=\"%Y%m\") + pd.offsets.QuarterEnd(0)\n\ndf['Date_str'] = df['Date'].dt.strftime('%Y-%m-%d')\n\ndf.head()\n... | [
0
] | [] | [] | [
"datetime",
"datetimeoffset",
"pandas",
"python",
"quarter"
] | stackoverflow_0074612190_datetime_datetimeoffset_pandas_python_quarter.txt |
Q:
Converting list of string to string variable doesn't retain the order of elements in python
I have an a list of strings like ["a", "b"]. When I convert it to the string variable separated by ", " it works fine when I test the test cases on the local machine via debugging and tox. It doesn't work fine in the pipeli... | Converting list of string to string variable doesn't retain the order of elements in python | I have an a list of strings like ["a", "b"]. When I convert it to the string variable separated by ", " it works fine when I test the test cases on the local machine via debugging and tox. It doesn't work fine in the pipeline once I commit the code on GitLab. The order of elements gets reversed. Sometimes it is retaine... | [
"sets are unordered, so you will get different results every time. You can use dict to retain the order\nto_drop = [\"a\", \"b\", \"a\"]\nto_drop = dict.fromkeys(to_drop)\ndrop_account_names = \", \".join(to_drop)\nprint(drop_account_names) # a, b\n\n"
] | [
0
] | [] | [] | [
"gitlab",
"python",
"python_3.x"
] | stackoverflow_0074626021_gitlab_python_python_3.x.txt |
Q:
Trying to use df.groupby function to group new dataframe according to year information
I need to use the groupby function to group new dataframe according to year. I have seen other topics on this issue however they don't have it reading from a csv file. I'm wondering am I already doing this right or if I am wrong... | Trying to use df.groupby function to group new dataframe according to year information | I need to use the groupby function to group new dataframe according to year. I have seen other topics on this issue however they don't have it reading from a csv file. I'm wondering am I already doing this right or if I am wrong what is the right way to do this
I tried using
df = pd.read_csv('data.csv', usecols= ['pric... | [
"You could do that in this way:\ndf = df.groupby('year')\n\nPrint first value in each group:\ndf.first()\n\nto get highest price for each year group:\ndf.groupby('year').max()\n\nOr:\n df.groupby('year')['price'].max()\n\n"
] | [
1
] | [] | [] | [
"dataframe",
"group_by",
"python"
] | stackoverflow_0074626077_dataframe_group_by_python.txt |
Q:
Selenium can not find elements in dynamic web page, page source does not be loaded completely
I try to recover some elements in a web page with selenium but the page_source I'm getting it does not have that elements loaded.
Find element returns elem.text empty and driver.page_source does not have the id titulotram... | Selenium can not find elements in dynamic web page, page source does not be loaded completely | I try to recover some elements in a web page with selenium but the page_source I'm getting it does not have that elements loaded.
Find element returns elem.text empty and driver.page_source does not have the id titulotramitedocu.
What am I missing?
Code:
URL = "https://seu.conselldemallorca.net/fitxa?key=91913"
driver ... | [
"To locate and print the text from the visible element instead of presence_of_element_located() you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:\n\nUsing CSS_SELECTOR:\nprint(WebDriverWait(driver, 20).until(EC.visibility_of_element_... | [
2
] | [] | [] | [
"dynamic",
"python",
"selenium",
"selenium_chromedriver",
"web_scraping"
] | stackoverflow_0074626150_dynamic_python_selenium_selenium_chromedriver_web_scraping.txt |
Q:
Iterating over data to combine
I'm fairly new to python and just now getting started with working with data. I'm attempting to combine different objects to display the data in a more readable way to view the comparison.
Here is the data i'm working with:
{
"flowDefinitionArn": "arn:aws:sagemaker:us-east-1:2345:flo... | Iterating over data to combine | I'm fairly new to python and just now getting started with working with data. I'm attempting to combine different objects to display the data in a more readable way to view the comparison.
Here is the data i'm working with:
{
"flowDefinitionArn": "arn:aws:sagemaker:us-east-1:2345:flow-definition/definition_name",
"huma... | [
"You can try something like this:\nd = json.loads(data)\ncols=[i['id'] for i in d['inputContent']['document']['fields'][2]['value']['columns']] # ['country', 'capital', 'population']\n\nextracted=d['humanAnswers'][0]['answerContent']\nextracted_vals=list(dict(filter(lambda e:e[0].startswith('extra'), extracted.item... | [
0
] | [] | [] | [
"json",
"loops",
"python"
] | stackoverflow_0074619933_json_loops_python.txt |
Q:
my afk system works on its own, but not when i insert it to the main
i am in the middle of making a demo of a game, and as part of it i made a system to check if the player is afk:
while lives != 0:
countdown.start()
while clicked != True:
if int(f"{time.perf_counter() - countdown.time_passed:0.0f}... | my afk system works on its own, but not when i insert it to the main | i am in the middle of making a demo of a game, and as part of it i made a system to check if the player is afk:
while lives != 0:
countdown.start()
while clicked != True:
if int(f"{time.perf_counter() - countdown.time_passed:0.0f}") == 5:
print("time passed")
Break = True
... | [
"I found out what the problem was. This occurred because I had a global variable in the code, while it was a local variable during testing.\nIf anybody has a similar issue, make sure that you handle your global variables with caution. Typically, they are constants and should neveer be changed, otherwise, be very in... | [
0
] | [] | [] | [
"python",
"python_turtle"
] | stackoverflow_0074559183_python_python_turtle.txt |
Q:
How to handle list of string stored in a map in python?
I am from C++ background and i am porting one of our tool to python, i am fairly a begginer with python and i am looking for way to store this data structure to python
i have a map or array with string key and it will have a content of an object or a json lik... | How to handle list of string stored in a map in python? | I am from C++ background and i am porting one of our tool to python, i am fairly a begginer with python and i am looking for way to store this data structure to python
i have a map or array with string key and it will have a content of an object or a json like so..
map["key1"] = {
{ 'name': 'user1', 'email': 'some... | [
"You want to use a Python dictionary which is denoted by squiggly brackets ({ and }). The data structure inside the dictionary entry is a list denoted by the square brackets ([ and ]).\n\n# Declare 'my_map' dictionary\nmy_map = {}\n\n# Add list of dictionaries to 'key_1'\nmy_map[\"key1\"] = [\n { 'name': 'user1... | [
1
] | [] | [] | [
"python"
] | stackoverflow_0074626166_python.txt |
Q:
Argument 2 to "join" has incompatible type "Optional[str]"; expected "str"
I'm running mypy pre commit hook to check for any possible type issues and it's keep giving me this error Argument 2 to "join" has incompatible type "Optional[str]"; expected "str" for the code below:
else:
renamed_paths_dict: CustomCon... | Argument 2 to "join" has incompatible type "Optional[str]"; expected "str" | I'm running mypy pre commit hook to check for any possible type issues and it's keep giving me this error Argument 2 to "join" has incompatible type "Optional[str]"; expected "str" for the code below:
else:
renamed_paths_dict: CustomConnectorRenameDict = {
"old_path": os.path.join(
self.tem... | [
"You have multiple options:\n\nignore errors from mypy for this line by adding the comment # type: ignore:\n\nelse:\n renamed_paths_dict: CustomConnectorRenameDict = {\n \"old_path\": os.path.join(\n self.temp_dir, change[\"file_path\"]\n ),\n \"new_path\": os.path.join(... | [
2,
2
] | [] | [] | [
"mypy",
"python",
"type_hinting"
] | stackoverflow_0074625904_mypy_python_type_hinting.txt |
Q:
xlsxwriter - Why shorter strings occupy the same size as twice larger strings?
I'm writing data into xlsx with xlsxwriter. There are columns business_unit, creator_login_sap, etc. Total records in xlsx 130 000. business_unit and creator_login_sap are strings. business_unit has constant length of 4 chars. creator_l... | xlsxwriter - Why shorter strings occupy the same size as twice larger strings? | I'm writing data into xlsx with xlsxwriter. There are columns business_unit, creator_login_sap, etc. Total records in xlsx 130 000. business_unit and creator_login_sap are strings. business_unit has constant length of 4 chars. creator_login_sap has average length of 10 chars.
import xlsxwriter
import io
output = io.By... | [
"The data is already compressed. xlsx is a ZIP package containing XML files. 130K rows in 450KB is less than 4 bytes per row. A text file with the same data would be 1.8MB. That's an impressive compression to 25% of the original size.\nThat said, it may be possible to reduce size even farther. You can test this by ... | [
3
] | [] | [] | [
"python",
"xlsxwriter"
] | stackoverflow_0074625551_python_xlsxwriter.txt |
Q:
Does GCP have an API call to check resource availability?
We keep getting ZONE_RESOURCE_POOL_EXHAUSTED when we try to deploy VMs in the zones of the us-central1 region. Apparently, GCP doesn't have enough VMs to fill the request.
We tried other regions one by one us-east1, us-east4, etc. all returned the same erro... | Does GCP have an API call to check resource availability? | We keep getting ZONE_RESOURCE_POOL_EXHAUSTED when we try to deploy VMs in the zones of the us-central1 region. Apparently, GCP doesn't have enough VMs to fill the request.
We tried other regions one by one us-east1, us-east4, etc. all returned the same error until finally found that us-east5 have VMs available and we'r... | [
"No such dashboards, API method (or) Feature to give the resource availability in GCP.\nBut while creating resources if you face any issues like ZONE_RESOURCE_POOL_EXHAUSTED, please follow the guidelines mentioned in the official document for\nTroubleshooting errors that you might encounter while creating or updati... | [
1
] | [] | [] | [
"gcloud",
"google_api_python_client",
"google_cloud_platform",
"google_compute_engine",
"python"
] | stackoverflow_0074624340_gcloud_google_api_python_client_google_cloud_platform_google_compute_engine_python.txt |
Q:
Tweepy (API V2) - Convert Response into dictionary
I want to get the information about the people followed by the Twitter account "POTUS" in a dictionary. My code:
import tweepy, json
client = tweepy.Client(bearer_token=x)
id = client.get_user(username="POTUS").data.id
users = client.get_users_following(id=id, ... | Tweepy (API V2) - Convert Response into dictionary | I want to get the information about the people followed by the Twitter account "POTUS" in a dictionary. My code:
import tweepy, json
client = tweepy.Client(bearer_token=x)
id = client.get_user(username="POTUS").data.id
users = client.get_users_following(id=id, user_fields=['created_at','description','entities','id',... | [
"Found the soloution! Adding return_type=dict to the client will return everything as a dictionary!\nclient = tweepy.Client(bearer_token=x, return_type=dict)\n\nHowever, you then have to change the line to get the User ID a bit:\nid = client.get_user(username=\"POTUS\")['data']['id']\n\n",
"You can do\nprevious_c... | [
0,
0
] | [] | [] | [
"dictionary",
"python",
"tweepy",
"twitter",
"twitter_api_v2"
] | stackoverflow_0074620166_dictionary_python_tweepy_twitter_twitter_api_v2.txt |
Q:
I'm not sure if this solution for my homework is right
So, the homework is: I need to write a code that will let the user to enter 3 numbers(this part is done.). Then my code should compare those numbers with each other(I think I know this too). But the hardest part is: if the first num is greater then code should... | I'm not sure if this solution for my homework is right | So, the homework is: I need to write a code that will let the user to enter 3 numbers(this part is done.). Then my code should compare those numbers with each other(I think I know this too). But the hardest part is: if the first num is greater then code should print 1st: true, if the second one is greater it should pri... | [
"use the code below:\nfirst = int(input('Write first number: '))\nsecond = int(input('Write second number: '))\nthird = int(input ('Write third number: '))\ntemp=first > second and first> third and print(\"1st:True\")\ntemp=second > first and second > third and print(\"2st:True\")\ntemp=third > first and third > se... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074625870_python.txt |
Q:
Fill different pandas columns based upon a list
I want to fill multiple columns with different values.
I have a df that looks as such:
df
'A' 'B' 'C'
0 1 dog red
1 5 cat yellow
2 4 moose blue
I would like to overwrite the columns based upon list values and so would look like this... | Fill different pandas columns based upon a list | I want to fill multiple columns with different values.
I have a df that looks as such:
df
'A' 'B' 'C'
0 1 dog red
1 5 cat yellow
2 4 moose blue
I would like to overwrite the columns based upon list values and so would look like this:
overwrite = [0, cat, orange]
df
'A' 'B' ... | [
"Simply assign the value to the columns, they will be broadcasted:\noverwrite = [0, 'cat', 'orange']\ndf[['A', 'B', 'C']] = overwrite\n\nOr maybe, if the overwrite list can be shorter than the number of columns:\ndf.iloc[:, :len(overwrite)] = overwrite\n\n# or\ndf[df.columns[:len(overwrite)]] = overwrite\n\nOutput:... | [
0
] | [
"Use DataFrame.assign with dictionary to overwrite the columns based upon list:\ndf = df.assign(**dict(zip(df.columns, overwrite)))\nprint (df)\n 'A' 'B' 'C'\n0 0 cat orange\n1 0 cat orange\n2 0 cat orange\n\nOr create DataFrame by constructor - values are not overwritten, but created new one ... | [
-1,
-3
] | [
"pandas",
"python"
] | stackoverflow_0074626345_pandas_python.txt |
Q:
How to compute average of image using Numpy and OpenCV
For one of my projects at university, I wish to use Python to select an image based on which is more salient.
To do this I know I will first have to use OpenCv's Saliency Detection. But after the output, where I am left with an image with its saliency map, how... | How to compute average of image using Numpy and OpenCV | For one of my projects at university, I wish to use Python to select an image based on which is more salient.
To do this I know I will first have to use OpenCv's Saliency Detection. But after the output, where I am left with an image with its saliency map, how do I compute the average saliency in the image? This would ... | [
"You are probably overthinking this. To the computer, an image is just a integer matrix.\nTo get an average value, compute the mean: https://numpy.org/doc/stable/reference/generated/numpy.mean.html\na = np.array([[1, 2], [3, 4]]) # this would be your image\nm = np.mean(a)\n\nOr count all white pixel and divide by t... | [
0
] | [] | [] | [
"numpy",
"object_detection",
"opencv",
"python"
] | stackoverflow_0074625896_numpy_object_detection_opencv_python.txt |
Q:
How to limit index column width/height when displaying a pandas dataframe?
I have a dataframe that looks like this:
df = pd.DataFrame(data=list(range(0,10)),
index=pd.MultiIndex.from_product([[str(list(range(0,1000)))],list(range(0,10))],
names=[... | How to limit index column width/height when displaying a pandas dataframe? | I have a dataframe that looks like this:
df = pd.DataFrame(data=list(range(0,10)),
index=pd.MultiIndex.from_product([[str(list(range(0,1000)))],list(range(0,10))],
names=["ind1","ind2"]),
columns=["col1"])
df['col2']=str(list(range(0... | [
"Here is one way to do it:\nimport pandas as pd\n\ndf = pd.DataFrame(\n data=list(range(0, 10)),\n index=pd.MultiIndex.from_product(\n [[str(list(range(0, 1000)))], list(range(0, 10))], names=[\"ind1\", \"ind2\"]\n ),\n columns=[\"col1\"],\n)\ndf[\"col2\"] = str(list(range(0, 1000)))\n\nIn the ne... | [
1
] | [] | [] | [
"dataframe",
"pandas",
"pandas_styles",
"python",
"visualization"
] | stackoverflow_0074509227_dataframe_pandas_pandas_styles_python_visualization.txt |
Q:
Unable to load the custom template tags in django
templatetags : myapp_extras.py
from django import template
register = template.Library()
@register.simple_tag
def my_url(value,field_name,urlencode=None):
url = '?{}={}'.format(field_name,value)
if urlencode:
querystring = urlencode.split('&')
... | Unable to load the custom template tags in django | templatetags : myapp_extras.py
from django import template
register = template.Library()
@register.simple_tag
def my_url(value,field_name,urlencode=None):
url = '?{}={}'.format(field_name,value)
if urlencode:
querystring = urlencode.split('&')
filtered_querystring = filter(lambda p:p.split('=... | [
"instead of this:\n@register.simple_tag\n\ntry this:\n@register.filter\n\nAnd load it in template:\n{% load filter_tags %}\n\nNote: you must create empty init.py file inside templatetags directory.\nAfter making above changes, you need to add this tag in settings.py file:\nIn settings.py file:\n'libraries':{\n ... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074626386_django_python.txt |
Q:
I am trying to merge data based on their dates
I am trying to achieve the following data frame format.
The first dataset is the results data with the date in a DateTime format whereas the second dataset is the rank_date in an object format. How do I merge the data based on their dates?
rank = rank.set_index(['rank... | I am trying to merge data based on their dates | I am trying to achieve the following data frame format.
The first dataset is the results data with the date in a DateTime format whereas the second dataset is the rank_date in an object format. How do I merge the data based on their dates?
rank = rank.set_index(['rank_date']).groupby(['country_full'], group_keys=False)... | [
"Probably, rank_date's type is string-object, not datetime:\nrank['rank_date']=pd.to_datetime(rank['rank_date'])\nrank = rank.set_index(['rank_date']).groupby(['country_full'], group_keys=False).resample('D').first().fillna(method='ffill').reset_index()\n\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"merge",
"python"
] | stackoverflow_0074621537_dataframe_merge_python.txt |
Q:
Unsure why output is 0. Trying to count months to pay downpayment
print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your d... | Unsure why output is 0. Trying to count months to pay downpayment | print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your dream home: ")
total_cost = float(input())
current_savings = 0
r = 0.0... | [
"You have n =+ 1 but I think you mean n += 1\nAlso int(.25) evaluates to 0, I think you want int(total_cost*.25). As your code is, the if statement will always evaluate to False because current_savings == 0 and portion_down_payment == 0\nMore generally, when your code isn't working as expected, you should put in ei... | [
1
] | [] | [] | [
"control_flow",
"if_statement",
"python"
] | stackoverflow_0074626524_control_flow_if_statement_python.txt |
Q:
How can I determine which element in a matrix is closest to a given point using numpy?
I have a matrix data of (x,y) coordinates which looks like this:
array([[3,4], [10,4], [1,3], [5,8]])
I want to write a piece of code that, given a numpy array with generic coordinates (x,y), finds the index of the row of the m... | How can I determine which element in a matrix is closest to a given point using numpy? | I have a matrix data of (x,y) coordinates which looks like this:
array([[3,4], [10,4], [1,3], [5,8]])
I want to write a piece of code that, given a numpy array with generic coordinates (x,y), finds the index of the row of the matrix which corresponds to the closest point to (x,y) (in terms of euclidean distance).
So f... | [
"There is probably a single-liner for this.\nimport numpy as np\ndata = np.array([[3,4],[10,4],[1,3],[5,8],[2,3]])\npoint = np.tile([2,3], (len(data),1))\nclosest_pt_idx = np.argmin(np.linalg.norm(data-point,axis=1))\nprint(np.linalg.norm(data-point,axis=1),closest_pt_idx)\n\n"
] | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074626343_numpy_python.txt |
Q:
How to get an executable Python path out of an Anaconda environment?
I am trying to profile my pyopencl project with CodeXL, and in order to work with .py files. I can't think of anything better than pointing at Python.exe and passing path to script as an argument. What makes things complicated is my use of Anacon... | How to get an executable Python path out of an Anaconda environment? | I am trying to profile my pyopencl project with CodeXL, and in order to work with .py files. I can't think of anything better than pointing at Python.exe and passing path to script as an argument. What makes things complicated is my use of Anaconda virtual environment to resolve conflicts between modules, because this ... | [
"You can find the location of your python exe using: \nwhere python\n\nSince you're using Anaconda, you can also try:\nwhere anaconda\n\nYou'll find the python exe in the parent directory of the result.\nIf this isn't what you need, you can find more info here.\n",
"The Python executable of a conda, virtualenv or... | [
2,
2,
0
] | [] | [] | [
"anaconda",
"codexl",
"python",
"windows_10"
] | stackoverflow_0054921271_anaconda_codexl_python_windows_10.txt |
Q:
How can I remove this specific section of a string without also removing the 'm' in the list
This is my code now:
def extract_categories(line: str):
new_line = re.sub('[ +++$+++]', '', line)
newer_line
print(new_line)
I want it to print this
['action', 'comedy', 'crime', 'drama', 'thriller']
but it p... | How can I remove this specific section of a string without also removing the 'm' in the list | This is my code now:
def extract_categories(line: str):
new_line = re.sub('[ +++$+++]', '', line)
newer_line
print(new_line)
I want it to print this
['action', 'comedy', 'crime', 'drama', 'thriller']
but it prints this:
m448hrs.19826.9022289['action','comedy','crime','drama','thriller']
This is the input... | [
"You can try breaking down the string based on pattern later you replace un wanted items as\nst = \"m4 +++$+++ 48 hrs. +++$+++ 1982 +++$+++ 6.90 +++$+++ 22289 +++$+++ ['action', 'comedy', 'crime', 'drama', 'thriller']\"\nnew = []\nmask = st.split(' +++$+++ ')[-1][1:-1].replace(\"'\",\"\").replace(\" \",\"\")\nnew.a... | [
0,
0
] | [] | [] | [
"list",
"python",
"string"
] | stackoverflow_0074625294_list_python_string.txt |
Q:
Is there any way to downgrade my python and all the package to 3.8?
I install python 3.10 in my new laptop, i used python 3.10 for a long time and i installed lot of package on it, but i need to downgrade it to python 3.8 because python 3.10 cannot support a package, and i found this post but if i remove the whole... | Is there any way to downgrade my python and all the package to 3.8? | I install python 3.10 in my new laptop, i used python 3.10 for a long time and i installed lot of package on it, but i need to downgrade it to python 3.8 because python 3.10 cannot support a package, and i found this post but if i remove the whole python, it will also remove all the package, that mean i need to install... | [
"You can use it pyenv for working with multiple python versions;\ncurl https://pyenv.run | bash\n\nLook at the available versions;\npyenv install --list\n\nInstalling selected version;\npyenv install -v 3.8.1\n\nfor more details;\nhttps://realpython.com/intro-to-pyenv/\n"
] | [
0
] | [] | [] | [
"downgrade",
"interpreter",
"python",
"python_3.x"
] | stackoverflow_0074626433_downgrade_interpreter_python_python_3.x.txt |
Q:
I can't scrape div ''some text" class = "" I think text cause to error
How can I scrape html like (<div data-v-28872a74="" class="col-lg-10 col-md-10 col-sm-12 col-12 offset-lg-1 offset-md-1 offset-sm-0 offset-0">).
I've tried soup.find_all('div', class_ = 'col-lg-10 col-md-10 col-sm-12 col-12 offset-lg-1 offs... | I can't scrape div ''some text" class = "" I think text cause to error | How can I scrape html like (<div data-v-28872a74="" class="col-lg-10 col-md-10 col-sm-12 col-12 offset-lg-1 offset-md-1 offset-sm-0 offset-0">).
I've tried soup.find_all('div', class_ = 'col-lg-10 col-md-10 col-sm-12 col-12 offset-lg-1 offset-md-1 offset-sm-0 offset-0') but output is just [].
Actually code:
div da... | [
"Try:\nimport re\nimport json\nimport requests\nimport pandas as pd\nfrom ast import literal_eval\n\nurl = \"https://remart.az/yasayis-kompleksi?cities=1&districts=\"\nhtml_doc = requests.get(url).text\n\ndata = re.search(r'window\\.__INITIAL_STATE__ = (\".*\")', html_doc).group(1)\ndata = json.loads(literal_eval(d... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074624370_beautifulsoup_html_python_web_scraping.txt |
Q:
How to find the change of text based on a unique value on another column in an excel file using Python
I have a excel file containing three columns as shown below,
ID
Name
Date
117
Laspringe
2019-04-08
117
Laspringe (FT)
2020-06-16
117
Laspringe (Ftp)
2020-07-24
999
Angelo
2020-04-15
999
Angelo(FT)
2021-03-0... | How to find the change of text based on a unique value on another column in an excel file using Python | I have a excel file containing three columns as shown below,
ID
Name
Date
117
Laspringe
2019-04-08
117
Laspringe (FT)
2020-06-16
117
Laspringe (Ftp)
2020-07-24
999
Angelo
2020-04-15
999
Angelo(FT)
2021-03-05
999
Angelo(Ftp)
2021-09-13
999
Angelo
2022-02-20
I wanted to find out that based on each... | [
"A simple way might be to check if the Name has any duplicate per group:\ns = df.duplicated(['ID', 'Name']).groupby(df['ID']).any()\nout = s[s].index.tolist()\n\nOutput: [999]\nIf you can have duplicates on successive dates (A -> A -> B shouldn't be a match):\ns = (df\n .sort_values(by='Date')\n .groupby('ID')['N... | [
2,
0
] | [] | [] | [
"csv",
"pandas",
"python",
"python_3.x"
] | stackoverflow_0074626179_csv_pandas_python_python_3.x.txt |
Q:
How to create a 2D array from 1D with the algorithm specified in the description?
Good afternoon,
I need to create a 2D array from 1D , according to the following rules:\
The 2d array must not contain
[["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"]...]
The array should not repeat, it's same for me
[["A1",... | How to create a 2D array from 1D with the algorithm specified in the description? | Good afternoon,
I need to create a 2D array from 1D , according to the following rules:\
The 2d array must not contain
[["A1", "A1"], ["A2", "A2"], ["A3", "A3"], ["A4", "A4"]...]
The array should not repeat, it's same for me
[["A1", "A2"], ["A2", "A1"], ....]\
For example
Input array
A ["A1", "A2", "A3", "A4"]
Output ... | [
"A simple if statement to check if the tuple already exists should be all you need:\n import numpy as np\n \n x = (\"A1\", \"A2\", \"A3\", \"A4\")\n \n arr = []\n for i in range(0, len(x)):\n for j in range(0, len(x)):\n if x[i] != x[j]:\n if not (x[j], x[i]) in ar... | [
2,
2
] | [] | [] | [
"algorithm",
"arrays",
"numpy",
"python"
] | stackoverflow_0074626544_algorithm_arrays_numpy_python.txt |
Q:
How do I print the string of tag that has multiple ?
firstHeader = mclarenHTML.find_all(re.compile('^h[2]'))[0] #finding header titles
print(firstHeader)
Output
<h2><strong><strong>1950-1953: </strong>Formula 1 begins: the super-charger years</strong></h2>
How do i get the string "1950-1953:Formula 1 begins: th... | How do I print the string of tag that has multiple ? | firstHeader = mclarenHTML.find_all(re.compile('^h[2]'))[0] #finding header titles
print(firstHeader)
Output
<h2><strong><strong>1950-1953: </strong>Formula 1 begins: the super-charger years</strong></h2>
How do i get the string "1950-1953:Formula 1 begins: the super-charger years"?
Tried using .string but it returns ... | [
"Use .text:\nfrom bs4 import BeautifulSoup\n\nsoup = BeautifulSoup(\n \"<h2><strong><strong>1950-1953: </strong>Formula 1 begins: the super-charger years</strong></h2>\",\n \"html.parser\",\n)\n\nheader = soup.h2\n\nprint(header.text)\n\nPrints:\n1950-1953: Formula 1 begins: the super-charger years\n\n\nOr us... | [
1
] | [] | [] | [
"beautifulsoup",
"jupyter_notebook",
"python",
"web_scraping"
] | stackoverflow_0074626624_beautifulsoup_jupyter_notebook_python_web_scraping.txt |
Q:
How to make dynamic imports in Python?
I have come across the following problem with the following code:
`
import MODULE as sem
import MODULE as mv
def find_group_day(enclave, day):
source = sem
EXTRA CODE
if num_week_year == sem.num_week_year:
source = f"PATH/{mv.year}.py"
EX... | How to make dynamic imports in Python? | I have come across the following problem with the following code:
`
import MODULE as sem
import MODULE as mv
def find_group_day(enclave, day):
source = sem
EXTRA CODE
if num_week_year == sem.num_week_year:
source = f"PATH/{mv.year}.py"
EXTRA CODE
x = list(source.__dict__.items... | [] | [] | [
"exec(...) runs specific code, where you can put variables. Example:\nmodule = 're'\nexec(f'import {module}')\n\nhttps://www.w3schools.com/python/ref_func_exec.asp\n"
] | [
-1
] | [
"dynamic",
"getattribute",
"import",
"python"
] | stackoverflow_0074626475_dynamic_getattribute_import_python.txt |
Q:
Installing BeautifulSoup4
I am running into problems installing BeautifulSoup4. This is the code I am using in a Jupiter notebook to import beautifulsoup
from selenium import webdriver
import beautifulsoup4
import pandas as pd
---------------------------------------------------------------------------
ModuleNotFo... | Installing BeautifulSoup4 | I am running into problems installing BeautifulSoup4. This is the code I am using in a Jupiter notebook to import beautifulsoup
from selenium import webdriver
import beautifulsoup4
import pandas as pd
---------------------------------------------------------------------------
ModuleNotFoundError ... | [
"Install with:\n$ pip install beautifulsoup4\n\nand then you should be using this import statement:\nfrom bs4 import BeautifulSoup\n\nnot:\nimport beautifulsoup4\n\nInstalling and importing BeautifulSoup.\n"
] | [
1
] | [
"To Install write\npip install beautifulsoup4\n\nand then import as\nfrom bs4 import BeautifulSoup\n\nFor more information refer https://www.crummy.com/software/BeautifulSoup/bs4/doc/\n"
] | [
-1
] | [
"beautifulsoup",
"jupyter",
"python"
] | stackoverflow_0074626656_beautifulsoup_jupyter_python.txt |
Q:
Django - AppRegistryNotReady("Models aren't loaded yet.") using cities_light library
I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as ex... | Django - AppRegistryNotReady("Models aren't loaded yet.") using cities_light library | I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as expected:
def index(request):
cities = City.objects.all()
context = {
'citie... | [
"In settings.py file add below code at the end of file:\nSOUTH_MIGRATION_MODULES = {\n 'cities_light': 'cities_light.south_migrations',\n}\n\nI think you did not add above code in settings.py file that's why you got that error.\nData update\nFinally, populate your database with command:\n./manage.py cities_light... | [
0,
0
] | [] | [] | [
"django",
"model",
"pip",
"python"
] | stackoverflow_0074625993_django_model_pip_python.txt |
Q:
Google OAuth error 400: redirect_uri_mismatch in Python
first time using OAuth here and I am stuck. I am building a web app that needs to make authorized calls to the YouTube Data API. I am testing the OAuth flow from my local computer.
I am stuck receiving Error 400: redirect_uri_mismatch when I try to run my Goo... | Google OAuth error 400: redirect_uri_mismatch in Python | first time using OAuth here and I am stuck. I am building a web app that needs to make authorized calls to the YouTube Data API. I am testing the OAuth flow from my local computer.
I am stuck receiving Error 400: redirect_uri_mismatch when I try to run my Google OAuth flow in Python. The error occurs when I access the ... | [
"Change redirect_uri to http://127.0.0.1/ or http://localhost/. I have faced a similar issue before with Google Drive API, and removing the port number worked for me.\n",
"The library seems to have a bug.\nI know it is not so good but in this case the hack is\nflow._OOB_REDIRECT_URI = = \"http://127.0.0.1:8080\"\... | [
0,
0
] | [] | [] | [
"google_api_python_client",
"google_oauth",
"oauth",
"python",
"youtube_data_api"
] | stackoverflow_0074320021_google_api_python_client_google_oauth_oauth_python_youtube_data_api.txt |
Q:
unable to create autoincrementing primary key with flask-sqlalchemy
I want my model's primary key to be an autoincrementing integer. Here is how my model looks like
class Region(db.Model):
__tablename__ = 'regions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Str... | unable to create autoincrementing primary key with flask-sqlalchemy | I want my model's primary key to be an autoincrementing integer. Here is how my model looks like
class Region(db.Model):
__tablename__ = 'regions'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(100))
parent_id = db.Column(db.Integer, db.ForeignKey('regions.id... | [
"Nothing is wrong with the above code. In fact, you don't even need autoincrement=True or db.Sequence('seq_reg_id', start=1, increment=1), as SQLAlchemy will automatically set the first Integer PK column that's not marked as a FK as autoincrement=True.\nHere, I've put together a working setup based on yours. SQLA... | [
78,
15,
13,
8,
4,
2,
1
] | [
"In my case, I just added the id as external parameter, without relying on sqlalchemy\n",
"Try this code out, it worked for me.\nWithin the __init__ function don't specify the id, so when you create a new \"User\" object SQLAlchemy will automatically generate an id number for you uniquely.\nfrom flask import Flas... | [
-1,
-1
] | [
"flask",
"flask_sqlalchemy",
"postgresql",
"python",
"sqlalchemy"
] | stackoverflow_0020848300_flask_flask_sqlalchemy_postgresql_python_sqlalchemy.txt |
Q:
How to create a function that search a list for a value that can be contained in a variable called key and print the array position of the key?
Write a function called find that will take a list of numbers, my_list, along with one other number, key. Have it search the list for the value contained in key. Each time... | How to create a function that search a list for a value that can be contained in a variable called key and print the array position of the key? | Write a function called find that will take a list of numbers, my_list, along with one other number, key. Have it search the list for the value contained in key. Each time your function finds the key value, print the array position of the key. You will need to juggle three variables, one for the list, one for the key, ... | [
"The function you have written should work if it is properly indented:\nmy_list = [36, 31, 79, 96, 36, 91, 77, 33, 19, 3, 34, 12, 70, 12, 54, 98, 86, 11, 17, 17]\n\n\ndef find(my_list, key):\n index = 0\n for element in my_list:\n if key == element:\n print(index)\n index += 1\n\nfind... | [
0,
0
] | [] | [] | [
"for_loop",
"python"
] | stackoverflow_0074622631_for_loop_python.txt |
Q:
while importing fiona module getting error
I have already install the Fiona using the command
pip3 install Fiona
Now in my .py file I'm trying to import Fiona using
import fiona
it gave me this error:
SBCs-MacBook-Pro:gis-python sbc$ python practice.py
Traceback (most recent call last):
File "/Users/sbc/Desktop... | while importing fiona module getting error | I have already install the Fiona using the command
pip3 install Fiona
Now in my .py file I'm trying to import Fiona using
import fiona
it gave me this error:
SBCs-MacBook-Pro:gis-python sbc$ python practice.py
Traceback (most recent call last):
File "/Users/sbc/Desktop/project_tudip/upl_tudip/gis-python/practice.py"... | [
"This error arises because MacOS High Sierra (10.13.6) doesn't have ____chkstk_darwin function.\nYou can locally force a specific Fiona version with pip, in particular the last one that supports High Sierra:\npip install fiona==1.6.4\n\n"
] | [
0
] | [] | [] | [
"fiona",
"python"
] | stackoverflow_0071826025_fiona_python.txt |
Q:
How to fix : Exception has occurred: ZeroDivisionError division by zero
Currently working on ML project for testing and training models and I got this zero division error on this line.
p_bar.set_description('{}. Testing Data of phoneme "{}" against all models \nResult: {}/{}
correct prediction;\n accuracy: {:.2f}... | How to fix : Exception has occurred: ZeroDivisionError division by zero | Currently working on ML project for testing and training models and I got this zero division error on this line.
p_bar.set_description('{}. Testing Data of phoneme "{}" against all models \nResult: {}/{}
correct prediction;\n accuracy: {:.2f}%'.format(
i+1,fc.get39Phon(i),count,len(test_lengths[i]),(count/len(test_len... | [
"It is giving you a division by zero error because len(test_lengths[i]) in count/len(test_lengths[i])*100 is 0, and you know that a number divided by zero is undefined, so it's giving you the error.\n"
] | [
1
] | [] | [] | [
"hmmlearn",
"machine_learning",
"python",
"scikit_learn",
"training_data"
] | stackoverflow_0074626848_hmmlearn_machine_learning_python_scikit_learn_training_data.txt |
Q:
How to fix locking failed in pipenv?
I'm using pipenv inside a docker container. I tried installing a package and found that the installation succeeds (gets added to the Pipfile), but the locking keeps failing. Everything was fine until yesterday. Here's the error:
(app) root@7284b7892266:/usr/src/app# pipenv inst... | How to fix locking failed in pipenv? | I'm using pipenv inside a docker container. I tried installing a package and found that the installation succeeds (gets added to the Pipfile), but the locking keeps failing. Everything was fine until yesterday. Here's the error:
(app) root@7284b7892266:/usr/src/app# pipenv install scrapy-djangoitem
Installing scrapy-dj... | [
"Here are my debugging notes. Still not sure which package is causing the problem, but this does seem to fix it.\nThe error you get when you first run pipenv install with pipenv version 2020.8.13.\nTraceback (most recent call last):\n File \"/usr/local/bin/pipenv\", line 8, in <module>\n sys.exit(cli())\n File... | [
15,
10,
0,
0,
0
] | [] | [] | [
"django",
"docker_compose",
"pipenv",
"pipenv_install",
"python"
] | stackoverflow_0064124931_django_docker_compose_pipenv_pipenv_install_python.txt |
Q:
python iterate from 0 to any Integer, positive or negative
I have to iterate from 0 to any Integer (call it x) that can be positive or negative (0 and x both included) (whether I iterate from x to 0 or from 0 to x does not matter)
I know I can use an if-else statement to first check if x is positive or negative an... | python iterate from 0 to any Integer, positive or negative | I have to iterate from 0 to any Integer (call it x) that can be positive or negative (0 and x both included) (whether I iterate from x to 0 or from 0 to x does not matter)
I know I can use an if-else statement to first check if x is positive or negative and then use range(x+1) if x>0 or range(x, 1) if x<0 (both will wo... | [
"You can simplify it by defining a function.\nget_range_args = lambda x: (0, x+1) if x > 0 else (x, 1)\nfor i in range(*get_range_args(x)):\n for j in range(*get_range_args(y)):\n pass\n\n",
"A simple solution that requires no functions\nfor i in range(min(x, 0), max(x, 0) + 1):\n for j in range(min(... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0074626812_python.txt |
Q:
Calculating the difference between the first non-na value and the last na-value based on a grouped condition
I am looking to calculate the percentage increase or decrease between the first and last non-na value for the following dataset:
Year
Company
Data
2019
X
341976.00
2020
X
1.000
2021
X
282872.00
2019
Y
... | Calculating the difference between the first non-na value and the last na-value based on a grouped condition | I am looking to calculate the percentage increase or decrease between the first and last non-na value for the following dataset:
Year
Company
Data
2019
X
341976.00
2020
X
1.000
2021
X
282872.00
2019
Y
NaN
2020
Y
NaN
2021
Y
NaN
2019
Z
4394.00
2020
Z
173.70
2021
Z
518478.00
As I want the relat... | [
"If aggregate GroupBy.first and\nGroupBy.last it omit missing values, so is possible divide values and subtract 1:\ns = df.groupby('Company')['Data'].agg(['last','first']).eval('last / first').sub(1)\n\nThen found index values for last non missing values per Company:\nidx = df.dropna(subset=['Data']).drop_duplicate... | [
1,
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074626911_pandas_python.txt |
Q:
What is the point in using PySpark over Pandas?
I've been learning Spark recently (PySpark to be more precise) and at first it seemed really useful and powerful to me. Like you can process Gb of data in parallel so it can me much faster than processing it with classical tool... right ? So I wanted to try by myself... | What is the point in using PySpark over Pandas? | I've been learning Spark recently (PySpark to be more precise) and at first it seemed really useful and powerful to me. Like you can process Gb of data in parallel so it can me much faster than processing it with classical tool... right ? So I wanted to try by myself to be convinced.
So I downloaded a csv file of almos... | [
"Spark is a distributed processing framework. That means that, in order to use it at it's full potential, you must deploy it on a cluster of machines (called nodes): the processing is then parallelized and distributed across them. This usually happens on cloud platforms like Google Cloud or AWS. Another interesting... | [
2
] | [] | [] | [
"pandas",
"preprocessor",
"pyspark",
"python"
] | stackoverflow_0074626809_pandas_preprocessor_pyspark_python.txt |
Q:
Missing 'path' argument in get() call
I am trying to test my views in Django, and when I run this i get the error
from django.test import TestCase, Client
from django.urls import reverse
from foodsystem_app.models import discount,menu
import json
class TestViews(TestCase):
def test_login_GET(self):
... | Missing 'path' argument in get() call | I am trying to test my views in Django, and when I run this i get the error
from django.test import TestCase, Client
from django.urls import reverse
from foodsystem_app.models import discount,menu
import json
class TestViews(TestCase):
def test_login_GET(self):
client = Client
response = clie... | [
"You need to instantiate the Client class, you are currently just referencing the class directly.\nclient = Client()\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074626915_django_python.txt |
Q:
Checking value inside Sqlalchemy queried data
I am querying Tags table and storing its values into varialble
all_tags = Tag.query.all() # <- Query all existing tags
Output:
>>> all_tags
[<Tag>: STM32, <Tag>: Linux, <Tag>: Unix, <Tag>: Skype, <Tag>: MCU, <Tag>: CPU, <Tag>: Silk, <Tag>: WAN]
I am receiving tag val... | Checking value inside Sqlalchemy queried data | I am querying Tags table and storing its values into varialble
all_tags = Tag.query.all() # <- Query all existing tags
Output:
>>> all_tags
[<Tag>: STM32, <Tag>: Linux, <Tag>: Unix, <Tag>: Skype, <Tag>: MCU, <Tag>: CPU, <Tag>: Silk, <Tag>: WAN]
I am receiving tag values from json client, after I want to skip existiin... | [
"You can query for every id, if exists skip the append operation, otherwise append it.\nfor tag in json_data['tags']:\n tag_q = Tag.query.filter_by(id=tag[\"id\"]).first()\n if tag_q is not None:\n continue\n myPost.tags.append(tag_q) # < - or add it\n\n"
] | [
0
] | [] | [] | [
"flask",
"flask_sqlalchemy",
"python"
] | stackoverflow_0074626275_flask_flask_sqlalchemy_python.txt |
Q:
CLOSED (Thank you)
Another total noob question: I am not sure why my answer is printing out as a decimal. Also, in the lab the dimes are expected to be listed first, not sure how I screwed that up? I appreciate the help!
Define a function called exact_change that takes the total change amount in cents and calculat... | CLOSED (Thank you) | Another total noob question: I am not sure why my answer is printing out as a decimal. Also, in the lab the dimes are expected to be listed first, not sure how I screwed that up? I appreciate the help!
Define a function called exact_change that takes the total change amount in cents and calculates the change using the ... | [
"I didn't run it, but it seems the code shouldn't produce \"floats\" on output, yet there is some room for improvement:\n\nYour program is not calling the function exact_change, it only defines it at the top of the module, but it's never called.\n\nUse f-string, not string concatenation and you don't have to explic... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0074623637_python.txt |
Q:
Isolate rows containing IDs in a column based on another column value, yet keeping all the records of original ID
I'd prefer to explain it grafically as it's hard for me to sum it up in the title.
Given a dataframe like this one below:
id type
1 new
2 new
2 new repeater
2 rep... | Isolate rows containing IDs in a column based on another column value, yet keeping all the records of original ID | I'd prefer to explain it grafically as it's hard for me to sum it up in the title.
Given a dataframe like this one below:
id type
1 new
2 new
2 new repeater
2 repeater
3 repeater
4 new
4 new repeater
5 new repeater
5 repeater
6 new
... | [
"Use GroupBy.cummax with bollean mask for test first match condition and filter in boolean indexing:\ndf = df[df['type'].eq('new').groupby(df['id']).cummax()]\nprint (df)\n id type\n0 1 new\n1 2 new\n2 2 new repeater\n3 2 repeater\n5 4 new\n6 4 new repeate... | [
1
] | [] | [] | [
"jupyter_lab",
"numpy",
"pandas",
"python"
] | stackoverflow_0074627059_jupyter_lab_numpy_pandas_python.txt |
Q:
How to update cells if row name is X And if column header is Y using openpyxl
I have an excel report and I want to update cells if row name is X And if column header is Y.
I have 53 columns with date, and 102 rows with names, so it's impossible to use 53 lines of code for each column, and 102 lines of code for eac... | How to update cells if row name is X And if column header is Y using openpyxl | I have an excel report and I want to update cells if row name is X And if column header is Y.
I have 53 columns with date, and 102 rows with names, so it's impossible to use 53 lines of code for each column, and 102 lines of code for each row, so I need code that checks if the row's value is for example SFR BOX HBD ECO... | [
"The screenshot of your Excel file shows the sheet \"CUMUL\" while your code describes \"VD CONQUETE DC\", but anyway, you can find below a proposition to update a value that match a given conditon. Feel free to readapt the code to fit your actual dataset.\nfrom openpyxl import load_workbook\nfrom datetime import d... | [
0
] | [] | [] | [
"openpyxl",
"python"
] | stackoverflow_0074626535_openpyxl_python.txt |
Q:
Python - Plot every three columns from dataframe in one figure for multiple figures
I have a dataframe with 150 columns and I want to plot every three together (the variable plus minus the standarddeviation) against the date, which means that I want to end up with 50 plots. Those 50 I want to have together in a X ... | Python - Plot every three columns from dataframe in one figure for multiple figures | I have a dataframe with 150 columns and I want to plot every three together (the variable plus minus the standarddeviation) against the date, which means that I want to end up with 50 plots. Those 50 I want to have together in a X by X matrix (whats best possible).
The pandas dataframe looks like this:
I also have thr... | [
"Try putting the plt.figure() and plt.plot() outside the for loop.\ne.g.\nplt.figure()\n\nfor colname in df.columns:\n plt.plot(df[\"date\"], df[colname])\n plt.plot(df[\"date\"], df[colname+\"_minus_stdev\"])\n plt.plot(df[\"date\"], df[colname+\"_plus_stdev\"])\n plt.savefig(colname+\".png\")\n\nplt.s... | [
0
] | [] | [] | [
"matplotlib",
"pandas",
"python",
"pythonplotter"
] | stackoverflow_0074622054_matplotlib_pandas_python_pythonplotter.txt |
Q:
Why is this function returning a list when called within another function?
My function is set to return a dictionary. When called, it returns the dictionary. However, if I call the function from within another function, it returns a list.
`
def draw(self, num: int) -> dict:
drawn_dict = {}
if num > len(s... | Why is this function returning a list when called within another function? | My function is set to return a dictionary. When called, it returns the dictionary. However, if I call the function from within another function, it returns a list.
`
def draw(self, num: int) -> dict:
drawn_dict = {}
if num > len(self.contents):
return self.contents
else:
while num >= 1:
... | [
"What is a type of the self.contents? I thing it is the list and this is answer to your question :-)\n\n def draw(self, num: int) -> dict:\n drawn_dict = {}\n if num > len(self.contents):\n return self.contents # <- THIS\n else:\n while num >= 1:\n drawn_num = self.contents.pop(random.ra... | [
0,
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074625995_python_python_3.x.txt |
Q:
use javascript to display django object
I want to implement below using javascript so row click it will get index and display object of this index.
in django template this is working.
<div>{{ project.0.customer_name}}</div>
<div>{{ project.1.customer_name}}</div>
but the below javascript are not working even I ge... | use javascript to display django object | I want to implement below using javascript so row click it will get index and display object of this index.
in django template this is working.
<div>{{ project.0.customer_name}}</div>
<div>{{ project.1.customer_name}}</div>
but the below javascript are not working even I get the correct ID.
var cell = row.getElementsB... | [
"You have to understand what is happening with your code:\nTemplates like this are processed on the server:\n'{{ project.id.customer_name}}'\n\nI believe you do not have project.id on your server side, so you get None in the above line, and the moustache tag becomes smth like an empty string, and actual JavaScript ... | [
0
] | [] | [] | [
"django",
"javascript",
"python"
] | stackoverflow_0074624791_django_javascript_python.txt |
Q:
Pandas filter dataframe by time
This is not a duplicate of: filter pandas dataframe by time because the solution offered there doesn't address the same column type that needs to be filtered.
I have the following dataframe:
i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
ts = pd.DataFrame({'A': [1, 2, 3,... | Pandas filter dataframe by time | This is not a duplicate of: filter pandas dataframe by time because the solution offered there doesn't address the same column type that needs to be filtered.
I have the following dataframe:
i = pd.date_range('2018-04-09', periods=4, freq='1D20min')
ts = pd.DataFrame({'A': [1, 2, 3, 4],
'B':i})
ts['date'... | [
"EDIT: Solution without B column:\nIf need filter by time column use Series.between:\nfrom datetime import time\n\ndf = ts[ts['time'].between(time(0,15,0), time(0,45,0))]\nprint (df)\n A B date time\n1 2 2018-04-10 00:20:00 2018-04-10 00:20:00\n2 3 2018-04-11 00:40:00 2018-04-1... | [
1
] | [] | [] | [
"date",
"datetime",
"pandas",
"python",
"time"
] | stackoverflow_0074627123_date_datetime_pandas_python_time.txt |
Q:
Is it possible to maintain login session in selenium-python?
I use Selenium below method.
open chrome by using chromedriver selenium
manually login
get information of webpage
However, after doing this, Selenium seems to get the html code when not logged in.
Is there a solution?
A:
Try this code:
from seleniu... | Is it possible to maintain login session in selenium-python? | I use Selenium below method.
open chrome by using chromedriver selenium
manually login
get information of webpage
However, after doing this, Selenium seems to get the html code when not logged in.
Is there a solution?
| [
"Try this code:\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium.webdriver.chrome.options import Options\n\noptions = Options()\n\n# path of the chrome's profile parent directory - change this path as per ... | [
0,
0
] | [] | [] | [
"html",
"python",
"selenium"
] | stackoverflow_0074624816_html_python_selenium.txt |
Q:
Python glob multiple filetypes
Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdow... | Python glob multiple filetypes | Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:
projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob( os.... | [
"Maybe there is a better way, but how about:\nimport glob\ntypes = ('*.pdf', '*.cpp') # the tuple of file types\nfiles_grabbed = []\nfor files in types:\n files_grabbed.extend(glob.glob(files))\n\n# files_grabbed is the list of pdf and cpp files\n\nPerhaps there is another way, so wait in case someone else comes... | [
219,
105,
66,
64,
47,
31,
20,
16,
11,
7,
6,
5,
4,
4,
3,
3,
3,
2,
2,
2,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [
"This Should Work:\nimport glob\nextensions = ('*.txt', '*.mdown', '*.markdown')\nfor i in extensions:\n for files in glob.glob(i):\n print (files)\n\n",
"For example:\nimport glob\nlst_img = []\nbase_dir = '/home/xy/img/'\n\n# get all the jpg file in base_dir \nlst_img += glob.glob(base_dir + '*.jpg')\... | [
-1,
-1,
-1,
-1,
-3,
-6
] | [
"glob",
"python"
] | stackoverflow_0004568580_glob_python.txt |
Q:
How to modify a dictionary from a csv file in raw python?
I have a file that looks like this, I want to get data from this file so that I can create a dictionary that takes the neighboruhood names as keys, with its values being ID, Population, and Low rate.
ID Neighbourhood Name Population Low r... | How to modify a dictionary from a csv file in raw python? | I have a file that looks like this, I want to get data from this file so that I can create a dictionary that takes the neighboruhood names as keys, with its values being ID, Population, and Low rate.
ID Neighbourhood Name Population Low rate
1 East Billin-Pickering 43567 1000
2... | [
"If you can install 3rd party library you can use pandas as following:\nimport pandas as pd\n\ndata = pd.read_csv(\"test.csv\", delimiter=\"\\t\") # Set delimiter and file name to your specific file \ndata = data.set_index(\"Neighbourhood Name\")\nfinal_dict = data.to_dict(orient=\"index\")\n\nFinal dict now contai... | [
2,
1,
1
] | [] | [] | [
"csv",
"for_loop",
"python"
] | stackoverflow_0074626946_csv_for_loop_python.txt |
Q:
Google people.listDirectoryPeople() method on python returns a slightly different list everytime
My organisation uses Google G Suite and contact details of all the employees are saved on the workspace directory. I've enabled people API for my work email (since it's part of G Suite) and tried listing out all employ... | Google people.listDirectoryPeople() method on python returns a slightly different list everytime | My organisation uses Google G Suite and contact details of all the employees are saved on the workspace directory. I've enabled people API for my work email (since it's part of G Suite) and tried listing out all employee contact details using people.listDirectoryPeople method.
Here's what I'm doing:
service = build... | [
"Not getting correct list because with open statement is inside the directory_people list for loop, move this out of loop like this:\n## I'M SAVING THE NEXT PAGE TOKEN HERE TO USE IN THE WHILE LOOP ##\nnext_page_token = results.get('nextPageToken')\n\nwith open('file.tsv', 'w') as f:\n f.write(\"Name\\tOrg\\tPhon... | [
0
] | [] | [] | [
"google_people_api",
"python"
] | stackoverflow_0067301671_google_people_api_python.txt |
Q:
Encoding Image to Base64 to MongoDB
Below is the Python code that am using to try to get this done.
I am trying to take an image and upload that to my MongoDB as base64. This issue is that whenever I try to put it into MongoDB it is giving me a different string.
I added the line of code to output enc_file to a te... | Encoding Image to Base64 to MongoDB | Below is the Python code that am using to try to get this done.
I am trying to take an image and upload that to my MongoDB as base64. This issue is that whenever I try to put it into MongoDB it is giving me a different string.
I added the line of code to output enc_file to a text document, and that is the correct Base... | [
"I just ran into this now as well.\nYou are turning the image into base64 and it seems mongodb does it as well, that is why you are seeing a different string -- you are getting a base64 of a base64.\nimport bson\nfrom bson import Binary\n\nwith open(image_location, \"rb\") as img_file:\n my_string = Binary(img_f... | [
0
] | [] | [] | [
"base64",
"mongodb",
"python"
] | stackoverflow_0074281617_base64_mongodb_python.txt |
Q:
How to make code sleep without using modules
I'm currently in a bit of a predicament, I'm trying to make a micro python program that has a small time delay for readability, but cannot use any imports. I would simply install the module onto the machine I'm working on, but the program is designed for the Casio-FX986... | How to make code sleep without using modules | I'm currently in a bit of a predicament, I'm trying to make a micro python program that has a small time delay for readability, but cannot use any imports. I would simply install the module onto the machine I'm working on, but the program is designed for the Casio-FX9860GIII Calculator.
My first thought was to use a lo... | [
"managed to figure it out, just used a for loop and did some testing using the Time function to get the timings right for my system, code looks like this\ndef systemSleep(s):\n i = 0\n for i in range(0, s*45100000):\n 3 * 3\n 3 * 3\n 3 * 3\n\n"
] | [
0
] | [] | [] | [
"micropython",
"python",
"sleep",
"time"
] | stackoverflow_0074627174_micropython_python_sleep_time.txt |
Q:
AttributeError: 'list' object has no attribute 'fit'
I am very new to python and I encountered this error saying:
AttributeError: 'list' object has no attribute 'fit'
from the following code:
models = [[GMMHMM(n_components=3,n_mix=2,verbose=False,n_iter=10) for i in range(39)]]
p_bar = tqdm(range(39))
#### ---- ... | AttributeError: 'list' object has no attribute 'fit' | I am very new to python and I encountered this error saying:
AttributeError: 'list' object has no attribute 'fit'
from the following code:
models = [[GMMHMM(n_components=3,n_mix=2,verbose=False,n_iter=10) for i in range(39)]]
p_bar = tqdm(range(39))
#### ---- Training the models ----
for i in range(39):
p_bar.s... | [] | [] | [
"In your code, models is a list of lists, because you have double brackets. Change the first line to:\nmodels = [GMMHMM(n_components=3,n_mix=2,verbose=False,n_iter=10) for i in range(39)]\n\n... and this sould work.\nP.S.: Please try to use reproducible code when asking quenstions.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0074627222_python.txt |
Q:
Groupby then sum doesn't work when running on large df
I'm trying to tidy up a long and messy csv file a bit, but my method doesn't seem to work until I tried splitting the raw data into several files. Just wondering if anyone can see what goes wrong here?
The original file looks like this, except there are 600+ r... | Groupby then sum doesn't work when running on large df | I'm trying to tidy up a long and messy csv file a bit, but my method doesn't seem to work until I tried splitting the raw data into several files. Just wondering if anyone can see what goes wrong here?
The original file looks like this, except there are 600+ rows:
Code Item Size Location Available
DD2 C... | [
"Change the data-type of the Available column, e.g. by:\ndf2[\"Available\"] = df2[\"Available\"].values.astype(float)\n\n"
] | [
1
] | [] | [] | [
"pandas",
"pivot_table",
"python",
"sum"
] | stackoverflow_0074627099_pandas_pivot_table_python_sum.txt |
Q:
Normalize spacy nlp vectors
I am working with an nlp model where I'd like to normalize the nlp.vocab.vectors. From the documentation about spacy vectors it states that it's an numpy ndarray.
I've googled a fair bit about normalizing numpy arrays as stated here, here and here.
As such I tried the following 3 approa... | Normalize spacy nlp vectors | I am working with an nlp model where I'd like to normalize the nlp.vocab.vectors. From the documentation about spacy vectors it states that it's an numpy ndarray.
I've googled a fair bit about normalizing numpy arrays as stated here, here and here.
As such I tried the following 3 approaches;
import spacy
import numpy a... | [
"nlp.vocab.vectors is a Vectors object. The numpy array is stored in nlp.vocab.vectors.data. See: https://spacy.io/api/vectors\n"
] | [
1
] | [] | [] | [
"arrays",
"normalize",
"numpy",
"python",
"spacy"
] | stackoverflow_0074626626_arrays_normalize_numpy_python_spacy.txt |
Q:
pandas rolling apply with NaNs
I can't understand the behaviour of pandas.rolling.apply with np.prod and NaNs. E.g.
import pandas as pd
import numpy as np
df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]}, index=pd.date_range('2013-01-01', '2013-01-05'))
Gives this dataframe:
B C
2... | pandas rolling apply with NaNs | I can't understand the behaviour of pandas.rolling.apply with np.prod and NaNs. E.g.
import pandas as pd
import numpy as np
df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]}, index=pd.date_range('2013-01-01', '2013-01-05'))
Gives this dataframe:
B C
2013-01-01 1.0 1
2013-01-02 1.0 2
2... | [
"It's very simple. You can try this code\nimport pandas as pd\nimport numpy as np\n\n\ndef foo(x):\n return np.prod(x, where=~np.isnan(x))\n\n\nif __name__ == '__main__':\n df = pd.DataFrame({'B': [1, 1, 2, np.nan, 4], 'C': [1, 2, 3, 4, 5]},\n index=pd.date_range('2013-01-01', '2013-01-05... | [
1,
0
] | [] | [] | [
"pandas",
"python",
"rolling_computation"
] | stackoverflow_0074621552_pandas_python_rolling_computation.txt |
Q:
How can I embed buttons to my message using discord.py?
I am making a discord bot using discord.py (with slash commands), but I am stuck on embedding buttons to my message. I can send the messages fine but once I try to put embeds there is always an error.
I've tried using:
from discord_components import Button
Bu... | How can I embed buttons to my message using discord.py? | I am making a discord bot using discord.py (with slash commands), but I am stuck on embedding buttons to my message. I can send the messages fine but once I try to put embeds there is always an error.
I've tried using:
from discord_components import Button
But here's the error message:
from discord_components import Bu... | [
"Your import might be wrong, try this.\nfrom discord.ui import Button, View\n\n"
] | [
0
] | [] | [] | [
"discord.py",
"discord_buttons",
"modulenotfounderror",
"python"
] | stackoverflow_0074394187_discord.py_discord_buttons_modulenotfounderror_python.txt |
Q:
Using a signal as an input to a function adds noise to the signal in Python
I have a signal X,
t,X = genS(f,T,L)that looks like this:
plt.plot(t,X)
Clearly it's a very clean signal with no noise. On the next line, I use this signal as input into a function. If I then plot the same signal again...
[p,d] = bopS(X,R... | Using a signal as an input to a function adds noise to the signal in Python | I have a signal X,
t,X = genS(f,T,L)that looks like this:
plt.plot(t,X)
Clearly it's a very clean signal with no noise. On the next line, I use this signal as input into a function. If I then plot the same signal again...
[p,d] = bopS(X,R,T,I,fs)
plt.plot(t,X)
There is nothing else done in the code between generati... | [
"If you could provide the details of genS & bopS, it would help. With not knowing what these functions do then no one will be able to help.\nAre these functions from a library? What library? If not share the function code.\nEDIT:\nI believe the issue is with you creating a \"shallow\" copy of the list in bopS\ns2 =... | [
1
] | [] | [] | [
"function",
"noise",
"python",
"signals",
"variables"
] | stackoverflow_0074627204_function_noise_python_signals_variables.txt |
Q:
Default MaxPoolingOp only supports NHWC on device type CPU
I tried to run a prediction on a SegNet model, but when the predict function its call I received an error.
I tried also to run the prediction with the with tf.device('/cpu:0'):, but I received the same error
if __name__ == '__main__':
# path to the mod... | Default MaxPoolingOp only supports NHWC on device type CPU | I tried to run a prediction on a SegNet model, but when the predict function its call I received an error.
I tried also to run the prediction with the with tf.device('/cpu:0'):, but I received the same error
if __name__ == '__main__':
# path to the model
model = tf.keras.models.load_model('segnet_weightsONNXbac... | [
"Without test4.jpg it's difficult to test solutions. However, the error Default MaxPoolingOp only supports NHWC on device type CPU\nmeans that the model only can accept inputs of the form n_examples x height x width x channels.\nI think your cv2.resize and subsequent np.reshape lines are not outputting the image in... | [
7,
1,
0
] | [] | [] | [
"keras",
"python",
"tensorflow"
] | stackoverflow_0058562582_keras_python_tensorflow.txt |
Q:
how to pass a context variable from a variable inside of an if statement?
Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without havin... | how to pass a context variable from a variable inside of an if statement? | Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement?
View
if request.me... | [
"This is happening because of variable scoping. check_order is declared within a branch of an if statement, but referenced outside of that branch - it's not in scope, so Python is throwing an error letting you know that you're using it before it is defined.\nYou can read more about Python scope here: https://realpy... | [
3
] | [] | [] | [
"django",
"python"
] | stackoverflow_0074626698_django_python.txt |
Q:
How to correcntly sort time values in a diagram in Python?
I am a beginner in Python and to start of I want to make some simple data visualizations.
To be precise I would like to plot a diagram with the runtimes of movies.
Here's how my code is looking right now:
# import matplotlib
import matplotlib.pyplot as plt... | How to correcntly sort time values in a diagram in Python? | I am a beginner in Python and to start of I want to make some simple data visualizations.
To be precise I would like to plot a diagram with the runtimes of movies.
Here's how my code is looking right now:
# import matplotlib
import matplotlib.pyplot as plt
# movie names
x=['titanic','ironman','avengers','sholay','thor'... | [
"For example by converting the string to datetime (assuming no movie is longer than 23h, 59m and 59s) and setting a formatter for it:\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\nx=['titanic','ironman','avengers','sholay','thor','caption america','dabang','... | [
1
] | [] | [] | [
"datetime",
"diagram",
"matplotlib",
"python"
] | stackoverflow_0074627049_datetime_diagram_matplotlib_python.txt |
Q:
1D Convolution of 2D arrays
I have 2 arrays of sets of signals, both 16x90000 arrays. In other words, 2 arrays with 16 signals in each. I want to perform matched filtering on the signals, row by row, correlating row 1 of array 1 with row 1 of array 2, and so forth. I've tried using scipy's signal.convolve2D but it... | 1D Convolution of 2D arrays | I have 2 arrays of sets of signals, both 16x90000 arrays. In other words, 2 arrays with 16 signals in each. I want to perform matched filtering on the signals, row by row, correlating row 1 of array 1 with row 1 of array 2, and so forth. I've tried using scipy's signal.convolve2D but it is extremely slow, taking tens o... | [
"Since you need to correlate the signals row by row, the most basic solution would be:\nimport numpy as np\nfrom scipy.signal import correlate\n\n# sample inputs: A and B both have n signals of length m\n\nn, m = 2, 5\nA = np.random.randn(n, m)\nB = np.random.randn(n, m)\n\nC = np.vstack([correlate(a, b, mode=\"sam... | [
0
] | [] | [] | [
"arrays",
"convolution",
"numpy",
"python",
"scipy"
] | stackoverflow_0074625948_arrays_convolution_numpy_python_scipy.txt |
Q:
Evenly spaced series of values from a list of (timestamp, value) tuples
I'm stuck on this because I'm not quite sure how to ask the question, so here's my best attempt!
I have a list of tuples which represent a temperature reading at a particular timestamp.
[
(datetime.datetime(2022, 11, 30, 8, 25, 10, 261853), ... | Evenly spaced series of values from a list of (timestamp, value) tuples | I'm stuck on this because I'm not quite sure how to ask the question, so here's my best attempt!
I have a list of tuples which represent a temperature reading at a particular timestamp.
[
(datetime.datetime(2022, 11, 30, 8, 25, 10, 261853), 19.82),
(datetime.datetime(2022, 11, 30, 8, 27, 22, 479093), 20.01),
(dat... | [
"Assuming lst the input list, you can use:\nimport pandas as pd\n\nout = (\n pd.DataFrame(lst).set_index(0).resample('5min')\n .mean().interpolate('linear')\n .reset_index().to_numpy().tolist()\n)\n\nIf you really want a list of tuples:\nout = list(map(tuple, out))\n\nOutput:\n[[Timestamp('2022-11-30 08:25:00')... | [
5
] | [] | [] | [
"numpy",
"pandas",
"python",
"python_imaging_library"
] | stackoverflow_0074627527_numpy_pandas_python_python_imaging_library.txt |
Q:
transform Csv file to list of lists with python?
I want to be able to turn csv file into a list of lists .
my csv file is like that :
['juridiction', 'audience', 'novembre'],['récapitulatif', 'information', 'important', 'octobre'],['terrain', 'entent', 'démocrate'],['porte-parole', 'tribunal', 'monastir', 'farid b... | transform Csv file to list of lists with python? | I want to be able to turn csv file into a list of lists .
my csv file is like that :
['juridiction', 'audience', 'novembre'],['récapitulatif', 'information', 'important', 'octobre'],['terrain', 'entent', 'démocrate'],['porte-parole', 'tribunal', 'monastir', 'farid ben', 'déclaration', 'vendredi', 'octobre', 'télévision... | [
"If your file really consists of only one long line, then here's a couple of options:\nUse eval: You need to add the brackets for the outer list.\nwith open(\"data.csv\", \"r\") as file:\n data = eval(\"[\" + file.read().strip() + \"]\")\n\nUse json: You need to (1) add the outer brackets, and (2) replace the ' ... | [
0
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0074626121_csv_list_python.txt |
Q:
Why Jupyter Notebook or Spyder execute way faster my Python code than the same .py called in windows shell?
My code does this:
reads an about 460 000 row × 45 column datatable from CSV file.
according to a filter table gives labels to the rows.
It goes through the whole table several times during running.
In Spy... | Why Jupyter Notebook or Spyder execute way faster my Python code than the same .py called in windows shell? | My code does this:
reads an about 460 000 row × 45 column datatable from CSV file.
according to a filter table gives labels to the rows.
It goes through the whole table several times during running.
In Spyder or Jupiter, the runtime is 12 seconds.
But when I run it from Windows PowerShell (python "C:\folders\xy.py") ... | [
"that because when you use shell the code must call the system first, otherwise, when you use IDE like spyder it already call when the IDE start. you can visit this link to know more Why is my Java program running 4 times faster via Eclipse than via shell?. Hope that help you. sorry if my english not good\n"
] | [
0
] | [] | [] | [
"anaconda",
"command_line",
"python",
"runtime",
"shell"
] | stackoverflow_0074627309_anaconda_command_line_python_runtime_shell.txt |
Q:
‘’The environment is inconsistent, please check the package plan carefully‘’ always appears
I tried to install new packages from anaconda and this message has appeared:
(base) C:\Users\lenovo>conda install anaconda
Collecting package metadata (current_repodata.json): done
Solving environment: \
The environment is ... | ‘’The environment is inconsistent, please check the package plan carefully‘’ always appears | I tried to install new packages from anaconda and this message has appeared:
(base) C:\Users\lenovo>conda install anaconda
Collecting package metadata (current_repodata.json): done
Solving environment: \
The environment is inconsistent, please check the package plan carefully
The following packages are causing the inco... | [
"I had a very similar problem as you: couldn't install fbprophet and failed to solve the environment when I tried to update conda. As suggested in this website and this stackoverflow question, I tried the command conda config --set channel_priority flexible. After that, I could run conda install anaconda and the en... | [
0
] | [] | [] | [
"anaconda",
"python"
] | stackoverflow_0071599829_anaconda_python.txt |
Q:
How do I get a cloned Django project running?
When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully
I tried python 'python3 -m pip install -U setuptools' but that didn't work.
A:
Remove psycopg2 from requirements.txt then use
'psycopg2-binary'
pip inst... | How do I get a cloned Django project running? | When I do 'pip install -r requirements.txt', I get this message: python setup.py egg_info did not run successfully
I tried python 'python3 -m pip install -U setuptools' but that didn't work.
| [
"Remove psycopg2 from requirements.txt then use\n'psycopg2-binary'\npip install psycopg2-binary\n\n"
] | [
0
] | [] | [] | [
"django",
"github",
"pip",
"python",
"web"
] | stackoverflow_0074627546_django_github_pip_python_web.txt |
Q:
How to AutoFilter Excel by RGB cell color with win32com in Python
Let me start by saying that I am not a very skilled programmer, so please keep your answers as simple as possible so I have a chance to understand :-)
I am trying to figure out how to use win32com to open Excel and AutoFilter a column based on cell ... | How to AutoFilter Excel by RGB cell color with win32com in Python | Let me start by saying that I am not a very skilled programmer, so please keep your answers as simple as possible so I have a chance to understand :-)
I am trying to figure out how to use win32com to open Excel and AutoFilter a column based on cell background colour.
The VBA code for what I want to do is this:
Selectio... | [
"The RGB macro comes from the Win32 API and is implemented in Python by pywin32.\nIn Python, if you have installed pywin32 (which you will have if you are using win32com), you can just write:\nfrom win32api import RGB\n\nn = RGB(255,255,0)\nprint(n)\n\nwhich yields 65535.\nSo if the OP simply adds the line from win... | [
0
] | [] | [] | [
"autofilter",
"python",
"win32com"
] | stackoverflow_0074620403_autofilter_python_win32com.txt |
Q:
Tensorflow dataset with variable number of elements
I need a dataset structured to handle a variable number of input images (a set of images) to regress against an integer target variable.
The code I am using to source the images is like this:
import tensorflow as tf
from tensorflow import convert_to_tensor
def r... | Tensorflow dataset with variable number of elements | I need a dataset structured to handle a variable number of input images (a set of images) to regress against an integer target variable.
The code I am using to source the images is like this:
import tensorflow as tf
from tensorflow import convert_to_tensor
def read_image_tf(path: str) -> tf.Tensor:
image = tf.ker... | [
"Maybe something like this:\nimport tensorflow as tf\n\ndef read_image_tf(path: str) -> tf.Tensor:\n img = tf.io.read_file(path)\n return tf.io.decode_png(img, channels=3) # more generic: tf.io.decode_image\n\ndef read_image_list(x, y):\n return tf.map_fn(read_image_tf, x, dtype=tf.uint8), y\n\npaths_list ... | [
1
] | [] | [] | [
"dataset",
"image",
"python",
"ragged_tensors",
"tensorflow"
] | stackoverflow_0074627040_dataset_image_python_ragged_tensors_tensorflow.txt |
Q:
Django issue saving data to database
username is saving but information such as first_name, email and etc are not.
`from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class RegisterSerializer(serializers.ModelSer... | Django issue saving data to database | username is saving but information such as first_name, email and etc are not.
`from django.contrib.auth.models import User
from django.contrib.auth.password_validation import validate_password
from rest_framework import serializers
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.CharFi... | [
"Add all the fields that you need to create that exist in model inside create method\nuser = User.objects.create(\n username=validated_data['username'], \n first_name =validated_data['first_name'],\n last_name =validated_data['last_name'], \n # Add other fields here\n)\n\n",
"You should also send o... | [
1,
0
] | [] | [] | [
"django",
"python",
"reactjs"
] | stackoverflow_0074627538_django_python_reactjs.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.