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:
Merge multiple timeseries dataframe Pandas
We have 20 different dataframes, each data frames contains historical stock price of company like this:
Date ISFT
0 2017-11-27 648.10
1 2017-11-28 649.90
2 2017-11-29 639.90
3 2017-11-30 697.10
4 2017-12-01 675.20
... .... | Merge multiple timeseries dataframe Pandas | We have 20 different dataframes, each data frames contains historical stock price of company like this:
Date ISFT
0 2017-11-27 648.10
1 2017-11-28 649.90
2 2017-11-29 639.90
3 2017-11-30 697.10
4 2017-12-01 675.20
... ...
1186 2022-11-15 109.00
1187 2022-11-16 11... | [
"Move Date into the index and use pd.concat to join the frames:\npd.concat([df.set_index(\"Date\") for df in df_list], axis=1)\n\n"
] | [
0
] | [] | [] | [
"dataframe",
"pandas",
"python",
"time_series"
] | stackoverflow_0074583559_dataframe_pandas_python_time_series.txt |
Q:
DataFrame pandas styling using applymap() not working in class, only in Jupyter cell
When I run applymap() in a Jupyter cell, it works fine. However, when I run the exact same code inside of my class, it doesn't style the DataFrame.
this code works as expected
#get the DataFrame from the class in the Jupyter cell
... | DataFrame pandas styling using applymap() not working in class, only in Jupyter cell | When I run applymap() in a Jupyter cell, it works fine. However, when I run the exact same code inside of my class, it doesn't style the DataFrame.
this code works as expected
#get the DataFrame from the class in the Jupyter cell
df = my_class.quality('headers')
# applymap() styles the table outside the class as expec... | [
"It works when you return the df.applymap() instead of styling and then returning.\ndef quality(self, key): \n df = unify.df(key) \n return df.style.applymap(self.quality_style) \n\n"
] | [
1
] | [] | [] | [
"dataframe",
"jupyter_notebook",
"pandas",
"python"
] | stackoverflow_0074583172_dataframe_jupyter_notebook_pandas_python.txt |
Q:
How to create a pandas dataframe from a txt file with comments?
I need to create a pandas dataframe based on 4 txt files with comments (to skip while reading) based on the following structure:
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=Tondeuse
# Propriétés générales
hauteur=0.5
masse=20.0
prix=110.00
#... | How to create a pandas dataframe from a txt file with comments? | I need to create a pandas dataframe based on 4 txt files with comments (to skip while reading) based on the following structure:
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=Tondeuse
# Propriétés générales
hauteur=0.5
masse=20.0
prix=110.00
# Propriétés du moteur
impulsion specifique=80
and
# Moteur conçu pa... | [
"Your data files look very close to configuration files. You can use configparser to generate a dictionary from each file:\nfrom pathlib import Path\nfrom configparser import ConfigParser\n\ndata = []\nfor file in Path(\"data\").glob(\"*.txt\"):\n parser = ConfigParser()\n # INI file requires a section header... | [
1,
1
] | [] | [] | [
"concatenation",
"dataframe",
"pandas",
"python",
"txt"
] | stackoverflow_0074583565_concatenation_dataframe_pandas_python_txt.txt |
Q:
Python List Extract data from a comma separated list
Im looking for best way to extract all the Count.AutoSlam.OAK4.3. [Weekly Avg: 0.56] from this list . I mainly need to know the 3 and the 0.56 positions. Then place them into seprate list for pandas.
['Label,Min,Avg,Max,Nov 23,11:00,Nov 23,12:00,Nov 23,13:00,Nov... | Python List Extract data from a comma separated list | Im looking for best way to extract all the Count.AutoSlam.OAK4.3. [Weekly Avg: 0.56] from this list . I mainly need to know the 3 and the 0.56 positions. Then place them into seprate list for pandas.
['Label,Min,Avg,Max,Nov 23,11:00,Nov 23,12:00,Nov 23,13:00,Nov 23,14:00,Nov 23,15:00,Nov 23,16:00,Nov 23,17:00,Nov 23,18... | [
"You could try using a regex to get matching groups and then just get the groups, e.g.\n/Count\\.AutoSlam\\.OAK4\\.(?P<autoslam>\\d+) \\[Weekly Avg: (?P<weekly_avrg>\\d\\.\\d{2})\\]/\n\nSee Example on Regex101.\nNow, you can capture the data in python with:\nimport re\n\npattern = re.compile(r\"Count\\.AutoSlam\\.O... | [
1
] | [] | [] | [
"element",
"pandas",
"python",
"selenium"
] | stackoverflow_0074577034_element_pandas_python_selenium.txt |
Q:
Connection' object has no attribute 'execute' pymysql
Every time I try to create an account I get this error message:
Connection' object has no attribute 'execute'
Thank you for helping me.
I am working on an absence management form.
I am in the account creation phase.
I have set up a MySQL database in order to be... | Connection' object has no attribute 'execute' pymysql | Every time I try to create an account I get this error message:
Connection' object has no attribute 'execute'
Thank you for helping me.
I am working on an absence management form.
I am in the account creation phase.
I have set up a MySQL database in order to be able to save the connection information in it.
I attach a ... | [
"I think it should be cur.execute() not con.execute().\nNote: Apart from that you have a couple of typos on commit() and close(), See Ref\nfrom tkinter import *\nfrom tkinter import ttk, messagebox\nfrom tkcalendar import *\nimport pymysql\nimport pymysql.cursors\nimport os\n\n\ncon = pymysql.connect(host=\"localho... | [
0
] | [] | [] | [
"connect",
"execute",
"pymysql",
"python"
] | stackoverflow_0074583820_connect_execute_pymysql_python.txt |
Q:
How to get the first 5 correct values from a cycle?
I am training a machine with reinforcements, everything is going well, but the task is to get the number of the game in which 5 victories were won in a row.
The algorithm consists of a loop that calculates 10,000 games, in each of which the agent walks on a froze... | How to get the first 5 correct values from a cycle? | I am training a machine with reinforcements, everything is going well, but the task is to get the number of the game in which 5 victories were won in a row.
The algorithm consists of a loop that calculates 10,000 games, in each of which the agent walks on a frozen lake using 100 steps (for each game). If the agent corr... | [
"I assume reward is 0 if the game was lost and 1 if it was won. If so, then you're gonna need to store two different results. Something like:\nfor game in tqdm(range(total_games)):\n //BODY OF CYCLE\n success += reward # COUNTS WINNING GAMES\n wins_in_a_row = wins_in_a_row + reward if reward else 0 # COUNT... | [
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0074583607_python.txt |
Q:
How to make Tkinter look good or natural on mac OS?
I developed a simple application using Tkinter, python 3.7.4 and on Mac OS Mojave 10.14.6.
I executed the same code on Ubuntu 18.04 and the latest Windows 10, and the application looks native. However, when I run it on my Macbook, it doesn't look native, like oth... | How to make Tkinter look good or natural on mac OS? | I developed a simple application using Tkinter, python 3.7.4 and on Mac OS Mojave 10.14.6.
I executed the same code on Ubuntu 18.04 and the latest Windows 10, and the application looks native. However, when I run it on my Macbook, it doesn't look native, like other mac GUI apps.
Look at this screenshot for instance:
N... | [
"The problem is that you put the label into the parent window, and not into the ttk frame. This is why the background color is different. You should set selfas the parent for the label.\nttk.Label(self, text=\"Youtube Url\").pack(side='top', anchor='w', **paddings)\n\n"
] | [
0
] | [
"You can manually change the background color of the tk or ttk labels to white, if the os is mac. To learn about that check How to identify on which OS Python is running on? (that is if you don't know)\nYou can see on windows it looks properly native\nOr you could try setting the theme to \"aqua\" which only works ... | [
-1,
-2
] | [
"macos",
"python",
"tkinter"
] | stackoverflow_0058052323_macos_python_tkinter.txt |
Q:
Python discord bot errors
I am getting the
TypeError: expected token to be a str, received NoneType instead
error in python when trying to run my bot. Here is the full error:
Traceback (most recent call last):
File "d:\Python\Projects\disco bot\ppap", line 20, in <module>
client.run(os.getenv('TOKEN'))
Fi... | Python discord bot errors | I am getting the
TypeError: expected token to be a str, received NoneType instead
error in python when trying to run my bot. Here is the full error:
Traceback (most recent call last):
File "d:\Python\Projects\disco bot\ppap", line 20, in <module>
client.run(os.getenv('TOKEN'))
File "C:\Users\Admin\AppData\Loca... | [
"Token Value Must Be A String\nSo , If You Are Using .env File For Token \nUse Something Like :\nimport os\nfrom dotenv import load_dotenv # pip install dotenv\nload_dotenv() # Load Every .env file in the application path\n.... # Stuff\nbot.run(os.getenv(\"BOTTOKEN\"))\n"
] | [
0
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python",
"python_3.9"
] | stackoverflow_0074583752_bots_discord_discord.py_python_python_3.9.txt |
Q:
Python Latex package not inserting graphic
I have a python program using the pdflatex PyPDF2 package to generate a LaTeX .tex file and then convert that to a .pdf file.
My problem is that the pdf file needs to include an image, and that image is not being inserted into the document.
The LaTeX file is generated by ... | Python Latex package not inserting graphic | I have a python program using the pdflatex PyPDF2 package to generate a LaTeX .tex file and then convert that to a .pdf file.
My problem is that the pdf file needs to include an image, and that image is not being inserted into the document.
The LaTeX file is generated by the following python code:
# compose a LaTex fil... | [
"Packages must not be loaded after \\begin{document}.\nSome other comments:\n\nAdding the current directory to the graphic path is also not necessary, the current directory is searched by default.\n\nyou shouldn't abuse \\\\ for line breaks, just leave an empty line to start a new paragraph\n\nif you make font size... | [
1
] | [] | [] | [
"google_colaboratory",
"latex",
"pdf",
"python"
] | stackoverflow_0074579685_google_colaboratory_latex_pdf_python.txt |
Q:
Python missing from /venv/bin/python folder in virtual environment Pycharm
I’ve recently migrated across to a new Mac computer and now when I try and run a Python file within a Pycharm virtual environment I get the message
Cannot Run program {Virtual_Environment_name}/venv/bin/python in directory {Virtual_Environ... | Python missing from /venv/bin/python folder in virtual environment Pycharm | I’ve recently migrated across to a new Mac computer and now when I try and run a Python file within a Pycharm virtual environment I get the message
Cannot Run program {Virtual_Environment_name}/venv/bin/python in directory {Virtual_Environment_name}/venv/bin/python, error = 2, "No such file or directory"
It looks lik... | [
"At the right bottom corner, there's an interpreter selection button. Press it. Now you've got two options:\n\nInterpreter settings\nAdd interpreter...\n\n\nChoose Interpreter settings. Your interpreter should be marked red, as it is not found. Press the gear button at the right and ask to Show all... interpreters.... | [
0
] | [] | [] | [
"pycharm",
"python",
"setup.py"
] | stackoverflow_0072036826_pycharm_python_setup.py.txt |
Q:
How to put each half of an image on the other half
I need to replace each half of an image with the other half:
Starting with this:
Ending with this:
I have tried to use crop, but I want the image to keep the same dimensions, and this seems to just cut it.
im = Image.open("image.png")
w, h = im.size
im = im.cr... | How to put each half of an image on the other half | I need to replace each half of an image with the other half:
Starting with this:
Ending with this:
I have tried to use crop, but I want the image to keep the same dimensions, and this seems to just cut it.
im = Image.open("image.png")
w, h = im.size
im = im.crop((0,0,int(w/2),h))
im.paste(im, (int(w/2),0,w,h))
im... | [
"How to rotate the x direction of an image\nYou are nearly there. You need to keep the left and right portion of the image into two separate variables and then paste them in opposite direction on the original image.\nfrom PIL import Image\noutput_image = 'test.png'\nim = Image.open(\"input.png\")\nw, h = im.size\nl... | [
3,
2
] | [] | [] | [
"image",
"python",
"python_imaging_library"
] | stackoverflow_0074583737_image_python_python_imaging_library.txt |
Q:
How to convert csv date and time with milliseconds to datetime with milliseconds
I have a difficult time converting separated date and time columns from a csv file into a merged dataframe datetime column with milliseconds.
original data:
Date Time
0 2014/9/2 08:30:00.0
1 2014/9/2 08:37:39.21
2 2... | How to convert csv date and time with milliseconds to datetime with milliseconds | I have a difficult time converting separated date and time columns from a csv file into a merged dataframe datetime column with milliseconds.
original data:
Date Time
0 2014/9/2 08:30:00.0
1 2014/9/2 08:37:39.21
2 2014/9/2 08:39:41.2
3 2014/9/2 08:41:23.9
4 2014/9/2 09:13:01.1
5 2014/9... | [
"The format code for microseconds is %f and not f% as per the documentation.\nTry this :\ndf['datetime'] = df['datetime'].apply(lambda x: datetime.strptime(x, '%Y/%m/%d %H:%M:%S.%f'))\n\nOr, in one shot :\n(\n pd.read_csv(\"test.csv\")\n .astype(str).agg(\" \".join, axis=1)\n .to_frame(\"datetime\"... | [
0
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074583869_pandas_python.txt |
Q:
How extract description in a google search using python?
I want to extract the description from the google search,
now I have this code:
from urlparse import urlparse, parse_qs
import urllib
from lxml.html import fromstring
from requests import get
url='https://www.google.com/search?q=Gotham'
raw = get(... | How extract description in a google search using python? | I want to extract the description from the google search,
now I have this code:
from urlparse import urlparse, parse_qs
import urllib
from lxml.html import fromstring
from requests import get
url='https://www.google.com/search?q=Gotham'
raw = get(url).text
pg = fromstring(raw)
v=[]
for result in... | [
"You can scrape Google Search Description Website using BeautifulSoup web scraping library.\nTo collect information from all pages you can use \"pagination\" with while True loop. The while loop is an endless loop, the exit from which in our case is the presence of a switch button to the next page, namely the CSS s... | [
0
] | [] | [] | [
"google_search",
"html",
"python"
] | stackoverflow_0046641941_google_search_html_python.txt |
Q:
How to select only one Radiobutton in tkinter
I have two radiobutton in my GUI but i want to able select only one at a time with the code below am able to select both radiobutton . I tried the checkbutton which also i can select both options.
from tkinter import *
def content():
if not option1.get() and not o... | How to select only one Radiobutton in tkinter | I have two radiobutton in my GUI but i want to able select only one at a time with the code below am able to select both radiobutton . I tried the checkbutton which also i can select both options.
from tkinter import *
def content():
if not option1.get() and not option2.get():
print("not allowed, select o... | [
"You must bind both radiobuttons to the same variable.\nBesides, the variable will receive the value specified in the value keyword argument.\nI suggest you do the following:\noption = StringVar()\nR1 = Radiobutton(root, text=\"MALE\", value=\"male\", var=option)\nR2 = Radiobutton(root, text=\"FEMALE\", value=\"fem... | [
4,
0,
0
] | [] | [] | [
"python",
"radio_button",
"tkinter"
] | stackoverflow_0048146801_python_radio_button_tkinter.txt |
Q:
Traceback (most recent call last): File "", line 1, in NameError: name 'p1' is not defined
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
I pasted a code from w3school, and idk why it is not working.
A:
Your error does not match your c... | Traceback (most recent call last): File "", line 1, in NameError: name 'p1' is not defined | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1)
I pasted a code from w3school, and idk why it is not working.
| [
"Your error does not match your code, but that doesn't matter, because printing the class directly isn't going to print it's attributes, without some modification. If you just want to print the attributes you can add the __str__ dunder method to your class, and create a custom string to return.\nclass Person:\n ... | [
0
] | [] | [] | [
"init",
"python"
] | stackoverflow_0074583896_init_python.txt |
Q:
Use asyncio and Tkinter (or another GUI lib) together without freezing the GUI
I want to use asyncio in combination with a tkinter GUI.
I am new to asyncio and my understanding of it is not very detailed.
The example here starts 10 task when clicking on the first button. The task are just simulating work with a sl... | Use asyncio and Tkinter (or another GUI lib) together without freezing the GUI | I want to use asyncio in combination with a tkinter GUI.
I am new to asyncio and my understanding of it is not very detailed.
The example here starts 10 task when clicking on the first button. The task are just simulating work with a sleep() for some seconds.
The example code is running fine with Python 3.6.4rc1. But
t... | [
"Trying to run both event loops at the same time is a dubious proposition. However, since root.mainloop simply calls root.update repeatedly, one can simulate mainloop by calling update repeatedly as an asyncio task. Here is a test program that does so. I presume adding asyncio tasks to the tkinter tasks would wo... | [
26,
18,
3,
2,
1,
1,
0
] | [
"I've had great luck running an I/O loop on another thread, started at the beginning of the app creation, and tossing tasks onto it using asyncio.run_coroutine_threadsafe(..). \nI'm kind of surprised that I can make changes to the tkinter widgets on the other asyncio loop/thread, and maybe it's a fluke that it wor... | [
-1
] | [
"asynchronous",
"python",
"python_asyncio",
"tkinter",
"user_interface"
] | stackoverflow_0047895765_asynchronous_python_python_asyncio_tkinter_user_interface.txt |
Q:
How to always scrape the first Link that pops up (no image links)
for i in range(1,len(companynameslist)):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[i+1])
driver.get("https://google.com")
driver.minimize_window()
googlebutton = driver.find_element(By.XPATH, '/html/body... | How to always scrape the first Link that pops up (no image links) | for i in range(1,len(companynameslist)):
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[i+1])
driver.get("https://google.com")
driver.minimize_window()
googlebutton = driver.find_element(By.XPATH, '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]')
googlebutton.clic... | [
"You need to improve your locators. Absolute XPaths are extremely breakable.\nI tested the following code on several company names and it worked correct.\nfrom selenium import webdriver\nfrom selenium.webdriver import Keys\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.option... | [
1
] | [] | [] | [
"css_selectors",
"python",
"selenium",
"selenium_webdriver",
"xpath"
] | stackoverflow_0074583154_css_selectors_python_selenium_selenium_webdriver_xpath.txt |
Q:
Comparing two lists for same value
Let's say I have 3 lists:
a = [0,0,0,1,1]
b = [1,0,0,0,0]
c = [1,1,1,0,0]
I want to return False whenever there are 1's at the same position, so for 'b & c' it would return False, because they both have a one at index 0, 'a & b' and 'a & c' should return True in this case.
The w... | Comparing two lists for same value | Let's say I have 3 lists:
a = [0,0,0,1,1]
b = [1,0,0,0,0]
c = [1,1,1,0,0]
I want to return False whenever there are 1's at the same position, so for 'b & c' it would return False, because they both have a one at index 0, 'a & b' and 'a & c' should return True in this case.
The way I would do it is:
for i in range(0, l... | [
"Are you looking for one liner. Here it is:\nany([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])\nSorry did not test it. Here is modified version with test:\n>>> a = [0,0,0,1,1]\n>>> b = [1,0,0,0,0]\n>>> c = [1,1,1,0,0]\n>>> def f(a,b):\n... return all([False if a[i] == 1 and b[i] == 1 els... | [
0,
0
] | [] | [] | [
"binary",
"list",
"python"
] | stackoverflow_0064254170_binary_list_python.txt |
Q:
Incorporating pagination scraping into my script
url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=electronics"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
names = soup.find_all("div", class_="s-item__title")
prices = soup.find_all("span", cla... | Incorporating pagination scraping into my script | url = "https://www.ebay.com/sch/i.html?_from=R40&_trksid=p2380057.m570.l1313&_nkw=electronics"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
names = soup.find_all("div", class_="s-item__title")
prices = soup.find_all("span", class_="s-item__price")
shippings = soup.find_all("span"... | [
"Just iterate link by pagination url query value\nbase_url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=electronics&_pgn='\nfor i in range(pages_count):\n base_url+f'{i}'\n\n # your code...\n response = requests.get(url)\n\n\nFor correct parsing by category, due to the specifics of the displayed pages... | [
0,
0
] | [] | [] | [
"beautifulsoup",
"pagination",
"python",
"web_scraping"
] | stackoverflow_0074384470_beautifulsoup_pagination_python_web_scraping.txt |
Q:
How to print the highest score on an external csv file
I've created a little top trumps game and have a csv file that stores all the scores from previous games. How do I get it to print the highest score?
field_names = ['player_name','score']
data = [{"player_name": player_name, 'score': score}]
with open("score.... | How to print the highest score on an external csv file | I've created a little top trumps game and have a csv file that stores all the scores from previous games. How do I get it to print the highest score?
field_names = ['player_name','score']
data = [{"player_name": player_name, 'score': score}]
with open("score.csv", "a") as csv_file:
spreadsheet = csv.DictWriter(csv... | [
"Create a variable to remember the highest score, and initialize it to zero.\nRead the csv file row by row. If you see a score that is higher than the previous highest score, remember it as the new highest score.\nAt the end of the loop, print the highest score.\n# initialize to a placeholder value\nhighest_score ... | [
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0074583891_csv_python.txt |
Q:
Authenticating Firebase connection in GitHub Action
Background
I have a Python script that reads data from an Excel file and uploads each row as a separate document to a collection in Firestore. I want this script to run when I push a new version of the Excel file to GitHub.
Setup
I placed the necessary credential... | Authenticating Firebase connection in GitHub Action | Background
I have a Python script that reads data from an Excel file and uploads each row as a separate document to a collection in Firestore. I want this script to run when I push a new version of the Excel file to GitHub.
Setup
I placed the necessary credentials in GitHub repo secrets and setup the following workflow... | [
"After hours of research, I found an easy way to store the Firestore service account JSON as a Github Secret.\nStep 1 : Convert your service account JSON to base-64\nLet's name the base-64 encoded JSON SERVICE_ACCOUNT_KEY. There are two ways to get this value:\nMethod 1 : Using command line\ncat path-to-your-servic... | [
1
] | [] | [] | [
"firebase",
"github_actions",
"google_cloud_firestore",
"python",
"yaml"
] | stackoverflow_0073965176_firebase_github_actions_google_cloud_firestore_python_yaml.txt |
Q:
How to create an update method for MongoDB
I am trying to create an update method in Jupyter Notebooks using Python and MongoDB, but whenever I run the program with my current update method, I get a TypeError saying "'Collection' object is not callable. If you meant to call the 'animals' method on a 'Database' obj... | How to create an update method for MongoDB | I am trying to create an update method in Jupyter Notebooks using Python and MongoDB, but whenever I run the program with my current update method, I get a TypeError saying "'Collection' object is not callable. If you meant to call the 'animals' method on a 'Database' object it is failing because no such method exist."... | [
"This form of the update method works:\ndef update(self, data, new_values):\n if self.database.animals.count(data):\n print(\"Data exist\")\n self.database.animals.update(data, new_values)\n else:\n print(\"Does not exist\")\n\nAnd this call works:\nif shelter.update(data, new_values):\np... | [
0
] | [] | [] | [
"mongodb",
"python"
] | stackoverflow_0074578917_mongodb_python.txt |
Q:
How to send utf-8 e-mail?
how to send utf8 e-mail please?
import sys
import smtplib
import email
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail(firm, fromEmail, to, template, subject, date):
with open(template, encoding="utf-8") as template_file:
... | How to send utf-8 e-mail? | how to send utf8 e-mail please?
import sys
import smtplib
import email
import re
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def sendmail(firm, fromEmail, to, template, subject, date):
with open(template, encoding="utf-8") as template_file:
message = template_file.r... | [
"You should just add 'utf-8' argument to your MIMEText calls (it assumes 'us-ascii' by default). \nFor example:\n# -*- encoding: utf-8 -*-\n\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\n\nmsg = MIMEMultipart(\"alternative\")\nmsg[\"Subject\"] = u'テストメール'\npart1 = MIMEText(u... | [
88,
7,
2,
0
] | [
"I did it using the standard packages: ssl, smtplib and email.\nimport configparser\nimport smtplib\nimport ssl\nfrom email.message import EmailMessage\n\n# define bcc:[str], cc: [str], from_email: str, to_email: str, subject: str, html_body: str, str_body: str\n... \n\n# save your login and server information in a... | [
-1
] | [
"email",
"python",
"smtp",
"utf_8"
] | stackoverflow_0005910104_email_python_smtp_utf_8.txt |
Q:
Check to see if two lists have the same value at the same index, if so return the index. If not return -1
So basically I am trying to compare two lists to see if they hold the same value at the same index at any point. If they do I return the index, if they do not, I return -1.
When I had first done this as a test... | Check to see if two lists have the same value at the same index, if so return the index. If not return -1 | So basically I am trying to compare two lists to see if they hold the same value at the same index at any point. If they do I return the index, if they do not, I return -1.
When I had first done this as a test I was having no issues however adding in the text has made it more difficult and my main issue is with the if ... | [
"I think a cleaner answer uses the built-in enumerate and zip functions:\nDlist = [17,13,10,6,2]\nIlist = [5,9,10,15,18]\n\ndef seqsearch(DS,IS):\n for idx, (d, s) in enumerate(zip(DS, IS)):\n if d == s:\n return f\"Yes! Found at index = {idx}\"\n\n return \"No!\\n-1\"\n\n\nprint(seqsearch(D... | [
0,
0
] | [
"i try use your code for better undrestand (but based of your use we have many option)\nDlist = [17, 13, 10, 6, 2]\nIlist = [5, 9, 10, 15, 18]\n\n\ndef seqsearch_with_print(DS, IS):\n \"\"\"this function only print not return!!!\n if you use return your function ended!\"\"\"\n for i in range(len(DS) - 1):\... | [
-1
] | [
"comparison",
"indexing",
"list",
"python"
] | stackoverflow_0074583790_comparison_indexing_list_python.txt |
Q:
Django: Why is create_user not working? (Custom BaseUserManager)
I am working on a Django project, where I have a custom AbstractBaseUser and a custom BaseUserManager. Logically I created those pretty early and since they were doing what they are supposed to, I went on in the project.
Now I am at a point, where I ... | Django: Why is create_user not working? (Custom BaseUserManager) | I am working on a Django project, where I have a custom AbstractBaseUser and a custom BaseUserManager. Logically I created those pretty early and since they were doing what they are supposed to, I went on in the project.
Now I am at a point, where I want to add the atribute userTag to the custom User and I want to call... | [
"I fixed it by replacing\nform.save()\n\nwith\naccount = get_user_model().objects.create_user(username=username, email=email, password=raw_password)\n\nin the registration view.\nIm still not sure what the problem was, so if sb can explain, id appreciate it.\n",
"When you create a user with forms, it avoids the m... | [
0,
0
] | [] | [] | [
"customization",
"django",
"python"
] | stackoverflow_0069192790_customization_django_python.txt |
Q:
Scrape videos using selenium python
I'm trying to scrape videos from any url that is entered by the user. The problem is that as I don't know the name of the video, or the specific website, I have no idea what I'm looking for. I tried using BeautifulSoup like this:
import requests
from bs4 import BeautifulSoup
r... | Scrape videos using selenium python | I'm trying to scrape videos from any url that is entered by the user. The problem is that as I don't know the name of the video, or the specific website, I have no idea what I'm looking for. I tried using BeautifulSoup like this:
import requests
from bs4 import BeautifulSoup
r = requests.get(Web_url)
soup = Beautif... | [
"AFAIK this isn't possible. At least with Selenium. Because each website have it own page structures etc. So you can't predict the elements you want to access on each possible website.\n"
] | [
0
] | [] | [] | [
"beautifulsoup",
"python",
"selenium",
"web_scraping"
] | stackoverflow_0074583044_beautifulsoup_python_selenium_web_scraping.txt |
Q:
How can I merge rows that contains a specific value in Pandas
I want to merge rows that contain a specific value, however, I want the merged row to have new columns.
Example
import pandas as pd
df = pd.DataFrame([{'Day': "Monday", 'Item_1': "Shirt", 'Item_2': "Mug", 'Item_3': "Pen"},
{'Day'... | How can I merge rows that contains a specific value in Pandas | I want to merge rows that contain a specific value, however, I want the merged row to have new columns.
Example
import pandas as pd
df = pd.DataFrame([{'Day': "Monday", 'Item_1': "Shirt", 'Item_2': "Mug", 'Item_3': "Pen"},
{'Day': "Monday", 'Item_1': "Shoes", 'Item_2': "Tea", 'Item_3': "Boo... | [
"I think you can use groupby here:\ndf = (df\n .groupby('Day', sort=False)\n .apply(lambda x: x.to_numpy())\n .apply(np.concatenate)\n .apply(pd.Series)\n .reset_index(drop=True)\n )\n\n# fix col names\ndf.columns = ['Day'] + [f'Item_{x}' for x in range(1, df.shape[1])]\n\nprint(df)\n\... | [
1
] | [] | [] | [
"dataframe",
"machine_learning",
"pandas",
"python"
] | stackoverflow_0074583934_dataframe_machine_learning_pandas_python.txt |
Q:
how to store arrays inside tuple in Python?
I have a simple question in python. How can I store arrays inside a tuple in Python. For example:
I want the output of my code to be like this:
bnds = ((0, 1), (0, 1), (0, 1), (0, 1))
So I want (0, 1) to be repeated for a specific number of times inside a tuple!
I have ... | how to store arrays inside tuple in Python? | I have a simple question in python. How can I store arrays inside a tuple in Python. For example:
I want the output of my code to be like this:
bnds = ((0, 1), (0, 1), (0, 1), (0, 1))
So I want (0, 1) to be repeated for a specific number of times inside a tuple!
I have tried to use the following code to loop over a tu... | [
"You could create a list, fill it up, then convert it to a tuple.\ng = []\nb1 = (0, 1)\n\nfor i in range(4):\n g.append(b1)\ng = tuple(g)\nprint(g)\n\nThere are cleaner ways to do it, but I wanted to adapt your code in order to help you understand what is happening.\n",
"you can do this way\n>>> result =tuple(... | [
1,
0,
0
] | [
"You can't change the items in tuple. Create g as a list then convert it into a tuple.\ng = []\nfor i in range(4):\n b1 = (0,1) * (i)\n g .append(b1)\ng = tuple(g)\n\nUsing list comprehension makes the code faster :\ng = tuple([(0,1)*i for i in range(4)])\n\nTo get the output asked:\ng = tuple([(0,1) for i in... | [
-1
] | [
"for_loop",
"loops",
"python",
"tuples"
] | stackoverflow_0074583998_for_loop_loops_python_tuples.txt |
Q:
Recursion function, random choices with probability from list
I need to make a simulator which makes, for the input list, a list (elements are random choices from rdm_lst) of lists.
I have:
lst = ["a", "a", "a"]
rdm_lst = ["a", "b", "c"]
def simulator(lst, rdm_lst):
sim = []
for i in lst:
if i == ... | Recursion function, random choices with probability from list | I need to make a simulator which makes, for the input list, a list (elements are random choices from rdm_lst) of lists.
I have:
lst = ["a", "a", "a"]
rdm_lst = ["a", "b", "c"]
def simulator(lst, rdm_lst):
sim = []
for i in lst:
if i == "a":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.... | [
"It sounds like you are trying to implement a Markov chain.\nYou could simplify a bit your code by defining your transitions with a dict (since your states are labeled, and you are currently using numpy -- in this case, a Pandas DataFrame would be more intuitive, but this will do).\nPx = {\n 'a': np.array([0.6, ... | [
0
] | [] | [] | [
"python",
"random",
"recursion"
] | stackoverflow_0074582319_python_random_recursion.txt |
Q:
How to iterate over a dictionary in Jinja2 using FastAPI?
I have a temp.py file and I have used FastAPI to return string or a dictionary with 2 get methods one for string another for dictionary.
I also have a temp.html file inside templates folder.
I am using Jinja2Templates as the template engine in HTML as the f... | How to iterate over a dictionary in Jinja2 using FastAPI? | I have a temp.py file and I have used FastAPI to return string or a dictionary with 2 get methods one for string another for dictionary.
I also have a temp.html file inside templates folder.
I am using Jinja2Templates as the template engine in HTML as the frontend view.
If the output result from FastAPI is string, I ju... | [
"The error is in your Jinja2 template when trying to access the items of the dictionary (you are actually missing an 's' at the end)—for future reference, make sure to have a look at the console running the app when coming across Internal Server Error; it should provide you with details regarding the error. That sh... | [
2
] | [] | [] | [
"dictionary",
"fastapi",
"html",
"jinja2",
"python"
] | stackoverflow_0074583110_dictionary_fastapi_html_jinja2_python.txt |
Q:
Django DecimalField fails to save even though I give it a floating number
class WithdrawRequests(models.Model):
withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True)
timestamp = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=255, unique=False, db_i... | Django DecimalField fails to save even though I give it a floating number | class WithdrawRequests(models.Model):
withdraw_hash = models.CharField(max_length=255, unique=True, db_index=True)
timestamp = models.DateTimeField(auto_now_add=True)
username = models.CharField(max_length=255, unique=False, db_index=True)
currency = models.CharField(max_length=255, unique=False, db_ind... | [
"“(0.011095555563904999,)” looks like string value, not float.\nYou should clean the withdraw_amount variable by removing braces, quotes and comma.\n",
"You can use the following code in your views:\nx=request.data[\"withdraw_amount\"]\nnum_list=\"0123456789.\"\nactual_str=\"\"\nfor i,k in enumerate(x):\n if k... | [
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"django_rest_framework",
"django_views",
"python"
] | stackoverflow_0074579557_django_django_models_django_rest_framework_django_views_python.txt |
Q:
How can we store a JSON credential to ENV variable in python?
{
"type": "service_account",
"project_id": "project_id",
"private_key_id": "private_key_id",
"private_key": "-----BEGIN PRIVATE KEY-----\n",
"client_email": "email",
"client_id": "id",
"auth_uri": "uri_auth",
"token_uri":... | How can we store a JSON credential to ENV variable in python? | {
"type": "service_account",
"project_id": "project_id",
"private_key_id": "private_key_id",
"private_key": "-----BEGIN PRIVATE KEY-----\n",
"client_email": "email",
"client_id": "id",
"auth_uri": "uri_auth",
"token_uri": "token_urin",
"auth_provider_x509_cert_url": "auth_provider_x5... | [
"Assuming your JSON file is creds.json\ncreds.json\n{\n \"type\": \"service_account\",\n \"project_id\": \"project_id\",\n \"private_key_id\": \"private_key_id\",\n \"private_key\": \"-----BEGIN PRIVATE KEY-----\\n\",\n \"client_email\": \"email\",\n \"client_id\": \"id\",\n \"auth_uri\": \"uri... | [
3,
0
] | [] | [] | [
"dotenv",
"json",
"python"
] | stackoverflow_0071544103_dotenv_json_python.txt |
Q:
how can i make this js code to python it's generate some kind of string and number
how can i do this code with python
it's generate some kind of string and numbre
for example 5ee8ead009f86895
a(16)
function a(t) {
function e() {
return n ? 15 & n[r++] : 16 * Math.random() | 0
... | how can i make this js code to python it's generate some kind of string and number | how can i do this code with python
it's generate some kind of string and numbre
for example 5ee8ead009f86895
a(16)
function a(t) {
function e() {
return n ? 15 & n[r++] : 16 * Math.random() | 0
}
var n = null
, r = 0
, o = windo... | [
"If i understand properly you want to write code in Python that can generate random tokens\nThis is written in Python3\nimport random as rd\n\ndef myToken(num):\n #num is the length of tokens\n myList = [1,2,3,4,5,6,7,8,9,0,\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"]\n #you can add more characters to the list abo... | [
0
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0074583636_python_python_3.x.txt |
Q:
Selenium Python - how to get deeply nested element
I am exploring Selenium Python and trying to grab a name property from Linkedin page in order to get its index later.
This is the HTML:
Here is how I try to do it:
all_span = driver.find_elements(By.TAG_NAME, "span")
all_span = [s for s in all_span if s.get_attr... | Selenium Python - how to get deeply nested element | I am exploring Selenium Python and trying to grab a name property from Linkedin page in order to get its index later.
This is the HTML:
Here is how I try to do it:
all_span = driver.find_elements(By.TAG_NAME, "span")
all_span = [s for s in all_span if s.get_attribute("aria-hidden") == "true"]
counter = 1
for i in al... | [
"The best way would be to use xpath. https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath\nLet's say you have this:\n\n\n<div id=\"this-div-contains-the-span-i-want\">\n <span aria-hidden=\"true\">\n <!--\n ...\n //-->\n </span>\n</div>\n\n\n\nThen, using xpath:\nxpath = \"//div[@id=... | [
0
] | [] | [] | [
"python",
"selenium",
"selenium_webdriver",
"web_scraping"
] | stackoverflow_0074583976_python_selenium_selenium_webdriver_web_scraping.txt |
Q:
Call render template variable on button click in Flask
I have a method where, I wanted to call the variable only when a button is clicked
@app.route("/select", methods = ['POST', 'GET'])
def select_data():
return render_template('select.html', select_csv = select_csv())
This is the variable i wanted to call, ... | Call render template variable on button click in Flask | I have a method where, I wanted to call the variable only when a button is clicked
@app.route("/select", methods = ['POST', 'GET'])
def select_data():
return render_template('select.html', select_csv = select_csv())
This is the variable i wanted to call, select_csv = select_csv()
This is the html,
<input type="but... | [
"if you don't have a problem in refreshing the page when the button in clicked then you can call the route again when button is clicked and place a condition in the route.\n@app.route(\"/select/<clicked>\", methods = ['POST', 'GET'])\ndef select_data(clicked=False):\n return render_template('select.html', selec... | [
0
] | [] | [] | [
"flask",
"python"
] | stackoverflow_0074583018_flask_python.txt |
Q:
Django unique slug field for two or more models
I have such structure:
class Category(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
parent = models.ForeignKey('self', blank=True, null=True,
related_name='children',
... | Django unique slug field for two or more models | I have such structure:
class Category(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
parent = models.ForeignKey('self', blank=True, null=True,
related_name='children',
on_delete=models.CASCADE
... | [
"You can override the save method for each, and then check if the given slug already exists for a product or category.\ndef is_slug_unique(slug):\n product_exists = Product.objects.filter(slug=slug).exists()\n category_exists = Category.objects.filter(slug=slug).exists()\n if product_exists or category_exi... | [
2,
1
] | [] | [] | [
"django",
"django_models",
"python",
"python_3.x"
] | stackoverflow_0074582446_django_django_models_python_python_3.x.txt |
Q:
Why can I use VS code with anaconda only when I open it from anaconda navigator?
I know this question is frequently asked, but none of the answers solved my problem.
I use VS code for bunch of things : Python, html css javascript php, Ruby etc.
I use anaconda for Python. However, I can only run python with anacond... | Why can I use VS code with anaconda only when I open it from anaconda navigator? | I know this question is frequently asked, but none of the answers solved my problem.
I use VS code for bunch of things : Python, html css javascript php, Ruby etc.
I use anaconda for Python. However, I can only run python with anaconda when I open VS code by the anaconda navigator.
I tried the to do the same thing as i... | [
"make sure you have your anaconda path added to the windows path.\nto add anaconda to the windows path follow this:\n\nsearch \"environment\" in windows search.\n\nclick on \"environment variables\"\n\n\nin the system variables area. look for \"path\" variable. select it and click on edit.\n\n\nadd the following (m... | [
0
] | [] | [] | [
"anaconda",
"python",
"visual_studio_code"
] | stackoverflow_0074584110_anaconda_python_visual_studio_code.txt |
Q:
Vectorized groupby with NumPy
Pandas has a widely-used groupby facility to split up a DataFrame based on a corresponding mapping, from which you can apply a calculation on each subgroup and recombine the results.
Can this be done flexibly in NumPy without a native Python for-loop? With a Python loop, this would l... | Vectorized groupby with NumPy | Pandas has a widely-used groupby facility to split up a DataFrame based on a corresponding mapping, from which you can apply a calculation on each subgroup and recombine the results.
Can this be done flexibly in NumPy without a native Python for-loop? With a Python loop, this would look like:
>>> import numpy as np
>... | [
"How about using scipy sparse matrix\nimport numpy as np\nfrom scipy import sparse\nimport time\n\nx_len = 500000\ng_len = 100\n\nX = np.arange(x_len * 2).reshape(x_len, 2)\ngroups = np.random.randint(0, g_len, x_len)\n\n# original\ns = time.time()\n\na = np.array([X[groups==i].sum() for i in np.unique(groups)])\n\... | [
8,
6,
5,
2,
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0049141969_numpy_python.txt |
Q:
Python Leetcode 3: Time limit exceeded
I am solving LeetCode problem https://leetcode.com/problems/longest-substring-without-repeating-characters/:
Given a string s, find the length of the longest substring without repeating characters.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits,... | Python Leetcode 3: Time limit exceeded | I am solving LeetCode problem https://leetcode.com/problems/longest-substring-without-repeating-characters/:
Given a string s, find the length of the longest substring without repeating characters.
Constraints:
0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.
If used this sliding ... | [
"Your algorithm running time is close to the timeout limit for some tests -- I even got the time-out with the version len(freqCounter). The difference between the two conditions you have tried cannot be that much different, so I would look into more drastic ways to improve the efficiency of the algorithm:\n\nInstea... | [
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0074583208_algorithm_python.txt |
Q:
Audio Steganography using lsb causing noise in audio with hidden message
I am trying to solve a problem in my audio steganography code. Afted hiding the message in wav audio file, there is some noice which of course should not be there considering the point of the whole audio steganography.
Thanks a lot for help !... | Audio Steganography using lsb causing noise in audio with hidden message | I am trying to solve a problem in my audio steganography code. Afted hiding the message in wav audio file, there is some noice which of course should not be there considering the point of the whole audio steganography.
Thanks a lot for help !
here is the code
import wave
import os
global chosen_audio
def hide():
... | [
"Your code is written to deal with wave files where sampwidth=1, but per your comment, the sampwidth of your file is 2. This means that your frame_bytes array is not an array of samples, it's an array of bytes in which every two bytes together form one sample. (And because nchannels is 1, there is one sample per fr... | [
0
] | [] | [] | [
"lsb",
"python"
] | stackoverflow_0074583881_lsb_python.txt |
Q:
PyQt5 - Custom widgets open in separate windows rather than in same window
I'm new at PyQt, and I'm trying to create a main window containing two custom widgets, the first being a data grapher, the second being a QGridLayout containing QLabels. Problem is: the two widgets open in separate windows and have no conte... | PyQt5 - Custom widgets open in separate windows rather than in same window | I'm new at PyQt, and I'm trying to create a main window containing two custom widgets, the first being a data grapher, the second being a QGridLayout containing QLabels. Problem is: the two widgets open in separate windows and have no content.
I've found multiple posts with a similar problem:
PyQt5 Custom Widget Opens... | [
"you should write fewer lines of code and debug slowly, if you are new to pyqt5 you should read carefully the basic Layout creation, like you are creating a website interface, link: https://www.pythonguis.com/tutorials/pyqt-layouts/\nThis is the code I have edited, you can can refer:\nimport sys\nfrom PyQt5.QtCore ... | [
1
] | [] | [] | [
"custom_widgets",
"pyqt",
"pyqt5",
"pyqtgraph",
"python"
] | stackoverflow_0074582879_custom_widgets_pyqt_pyqt5_pyqtgraph_python.txt |
Q:
How does "&" work in comparing two type of data in this code?
I am reading Python Cookbook: "1.17. Extracting a Subset of a Dictionary". I got confused with the "&" usage in one piece of the below code example. Who may help elaborate on it a bit?
How does prices.keys() & tech_names work here?
prices = {
'ACME'... | How does "&" work in comparing two type of data in this code? | I am reading Python Cookbook: "1.17. Extracting a Subset of a Dictionary". I got confused with the "&" usage in one piece of the below code example. Who may help elaborate on it a bit?
How does prices.keys() & tech_names work here?
prices = {
'ACME': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
... | [
"The & operator is used to create the intersection of the sets of keys in prices and the values in tech_names.\nSee the section on Dictionary view objects:\n\nKeys views are set-like since their entries are unique and hashable. [...] For set-like views, all of the operations defined for the abstract base class col... | [
4
] | [] | [] | [
"python"
] | stackoverflow_0074584284_python.txt |
Q:
Send email from Google colab Python
I am trying to send a dataframe as csv from google colab and is not working. In fact, I am having the error "'NoneType' object has no attribute 'replace'"
I try with this way:
from google.colab import files
from pathlib import Path
filepath = Path('mypath/forecast_productos.cs... | Send email from Google colab Python | I am trying to send a dataframe as csv from google colab and is not working. In fact, I am having the error "'NoneType' object has no attribute 'replace'"
I try with this way:
from google.colab import files
from pathlib import Path
filepath = Path('mypath/forecast_productos.csv')
filepath.parent.mkdir(parents=True,... | [
"I solved my problem.I was missing the parameter of attachments in yag.send. Now it has worked correctly sending a csv file:\n\nyag.send(to, subject, contents, attachments='my path in my desktop/forecast_productos.csv')\n\n\nIf you don't specify the attachments, it will send a table and not a file.\n"
] | [
0
] | [] | [] | [
"csv",
"email",
"google_colaboratory",
"html",
"python"
] | stackoverflow_0074583701_csv_email_google_colaboratory_html_python.txt |
Q:
Create new dataframe in Pandas that expands hourly data and hourly temperature reading to quarter-hour intervals
Edit: I figured it out:
df_weather_test = df_weather
df_weather_test['date_time'] = pd.to_datetime(df_weather['date_time'])
df_weather_test2 = df_weather_test.resample('15T', on='date_time').mean().inte... | Create new dataframe in Pandas that expands hourly data and hourly temperature reading to quarter-hour intervals | Edit: I figured it out:
df_weather_test = df_weather
df_weather_test['date_time'] = pd.to_datetime(df_weather['date_time'])
df_weather_test2 = df_weather_test.resample('15T', on='date_time').mean().interpolate()
I have a dataset that has hourly time intervals with each hour containing its own temperature reading. For ... | [
"# create the dataframe\nindex = pd.date_range('1/1/2018', periods=9, freq='H')\nseries = pd.Series([10,12,13,14,14,15,14,13,12], index=index)\ndf = pd.DataFrame(series, columns=['Temp'])\n# shift the Temp column\ndf['shifted'] = df.Temp.shift(-1)\ndf.shifted = df.shifted.ffill()\n# a function to fill the values in... | [
0
] | [] | [] | [
"dataframe",
"interpolation",
"pandas",
"python",
"resampling"
] | stackoverflow_0074583438_dataframe_interpolation_pandas_python_resampling.txt |
Q:
How do I fix 'x and y must be the same size' error on python?
I'm brand new to Python and struggling with this error 'x and y must be the same size'
Here is the code for my scatter plot
def plotNumericalConvergence(paramArr, GrArr, Label):
plt.figure()
x = paramArr
y = GrArr
plt.scatter(... | How do I fix 'x and y must be the same size' error on python? | I'm brand new to Python and struggling with this error 'x and y must be the same size'
Here is the code for my scatter plot
def plotNumericalConvergence(paramArr, GrArr, Label):
plt.figure()
x = paramArr
y = GrArr
plt.scatter(x=x,y=y)
plt.xlabel(Label)
plt.ylabel('Gr')
plt.tit... | [
"When you generate a scatter plot, then both x and y should be\n1-D arrays of equal size.\nCheck sizes of x and y, their sizes are probably different.\n"
] | [
0
] | [] | [] | [
"arrays",
"matplotlib",
"numpy",
"python"
] | stackoverflow_0074579732_arrays_matplotlib_numpy_python.txt |
Q:
Passing a matrix through multiple functions
A little complicated but I'll try to explain best I can, but I have values I am trying to calculate that are based on two other functions with multiple inputs. In the code below, my inputs are various theta values which then should create an array of m & n values. From t... | Passing a matrix through multiple functions | A little complicated but I'll try to explain best I can, but I have values I am trying to calculate that are based on two other functions with multiple inputs. In the code below, my inputs are various theta values which then should create an array of m & n values. From the m & n arrays, I then need to calculate the var... | [
"Instead of passing a list into function. pass each values differently might help!\n deg = np.array([math.cos(math.radians(theta[i])) for i in range(5)])\n\n news = pd.Series(theta,deg)\n\nSorry, I couldn't understand the q part exactly but if you explain it deeper than I'll try to help it too\n"
] | [
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0074584193_arrays_numpy_python.txt |
Q:
What's wrong with recursive Regex function code in python
I wrote a regex code which compares two strings. It recognises a special character '?' that allows zero or more instances of previous character. It works fine until there are two or more occasions of '?' in the string. And I can't make out why.
def single_c... | What's wrong with recursive Regex function code in python | I wrote a regex code which compares two strings. It recognises a special character '?' that allows zero or more instances of previous character. It works fine until there are two or more occasions of '?' in the string. And I can't make out why.
def single_character_string(a, b) -> "return True if characters match":
... | [
"Found the bag.\nReplace method replaces all instances of '?'. So the second '?' was replaced also and program didn't see it.\nI should add an argument 'count' to replace method that is equal to 1.\nk_1 = temp.replace(temp[0: 2], '', 1) # no char\n"
] | [
0
] | [] | [] | [
"python",
"recursion"
] | stackoverflow_0074583222_python_recursion.txt |
Q:
pandas to json using dict to give additional index
I'm trying to change csv to json.
my pandas dataframe has column named ['number','address','lat','long']
number address lat long
1 blah 37.1 127.2
2 doh 37.2 127.1
try to change to json as
[
{
"number":1
"address":"blahblah"
... | pandas to json using dict to give additional index | I'm trying to change csv to json.
my pandas dataframe has column named ['number','address','lat','long']
number address lat long
1 blah 37.1 127.2
2 doh 37.2 127.1
try to change to json as
[
{
"number":1
"address":"blahblah"
"location": {
"lat": 37.1
"long": 127.2... | [
"Assuming df is a variable that stores your dataframe.\nimport json\n\ndf['location'] = df.apply(lambda x:{'lat':x['lat'],'long':x['long']}, axis=1)\ndf = df.drop(['lat','long'], axis=1)\n\nprint(json.dumps(df.to_dict(orient='records'), indent=2))\n\nOutput:\n[\n {\n \"number\": 1,\n \"address\": \"blah\",\n... | [
0
] | [] | [] | [
"csv",
"dictionary",
"json",
"pandas",
"python"
] | stackoverflow_0060447139_csv_dictionary_json_pandas_python.txt |
Q:
How can I multiply all items in a list together with Python?
I need to write a function that takes
a list of numbers and multiplies them together. Example:
[1,2,3,4,5,6] will give me 1*2*3*4*5*6. I could really use your help.
A:
Python 3: use functools.reduce:
>>> from functools import reduce
>>> reduce(lambda x... | How can I multiply all items in a list together with Python? | I need to write a function that takes
a list of numbers and multiplies them together. Example:
[1,2,3,4,5,6] will give me 1*2*3*4*5*6. I could really use your help.
| [
"Python 3: use functools.reduce:\n>>> from functools import reduce\n>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])\n720\n\nPython 2: use reduce:\n>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])\n720\n\nFor compatible with 2 and 3 use pip install six, then:\n>>> from six.moves import reduce\n>>> reduce(lambda x, y: x*y, [1... | [
248,
190,
109,
74,
53,
15,
9,
7,
5,
5,
3,
2,
1,
1,
0,
0,
0
] | [
"'''the only simple method to understand the logic\nuse for loop'''\nLap=[2,5,7,7,9] \nx=1 \nfor i in Lap: \n x=i*x \nprint(x)\n",
"It is very simple do not import anything. This is my code.\nThis will define a function that multiplies all the items in a list and returns their product.\ndef myfunc(lst):\n m... | [
-2,
-3
] | [
"list",
"multiplication",
"python"
] | stackoverflow_0013840379_list_multiplication_python.txt |
Q:
Why doesnt it show the path?
Need help in identifying the problem of where it doesnt show the correct path taken, only shows 1 path taken but is supposed to show from start to finish.
A:
In your implementation where you iterate over the neighbours:
for v in _get_valid_neighbours(*u)
You don't append anything to... | Why doesnt it show the path? | Need help in identifying the problem of where it doesnt show the correct path taken, only shows 1 path taken but is supposed to show from start to finish.
| [
"In your implementation where you iterate over the neighbours:\nfor v in _get_valid_neighbours(*u)\n\nYou don't append anything to q, so the iteration stops there. As a result, in _reconstruct_path(), there is no prev node for the end point, and you get the path length as one.\n"
] | [
1
] | [] | [] | [
"algorithm",
"dijkstra",
"python"
] | stackoverflow_0074583250_algorithm_dijkstra_python.txt |
Q:
Interpolation CSV file with multiple columns
I have a CSV file containing data in the following form:
[( 7, 1818, 1, 8, 1818.021, 65, 10.2, 1, 1)
( 12, 1818, 1, 13, 1818.034, 37, 7.7, 1, 1)
( 16, 1818, 1, 17, 1818.045, 77, 11.1, 1, 1) ...
(73715, 2019, 10, 29, 2019.826, 0, 0. , 30, 0)
(73716, ... | Interpolation CSV file with multiple columns | I have a CSV file containing data in the following form:
[( 7, 1818, 1, 8, 1818.021, 65, 10.2, 1, 1)
( 12, 1818, 1, 13, 1818.034, 37, 7.7, 1, 1)
( 16, 1818, 1, 17, 1818.045, 77, 11.1, 1, 1) ...
(73715, 2019, 10, 29, 2019.826, 0, 0. , 30, 0)
(73716, 2019, 10, 30, 2019.829, 0, 0. , 24, 0)
(73717, ... | [
"Here is an example of how you can interpolate using some integer index values:\n#!/usr/bin/env ipython\nimport numpy as np\nimport pandas as pd\nimport datetime\n# --------------------------------------------------------------\n# let us generate the sample data, similar to data in question:\ndvec = [datetime.datet... | [
0
] | [] | [] | [
"interpolation",
"numpy",
"python"
] | stackoverflow_0074582817_interpolation_numpy_python.txt |
Q:
How do I use the markers parameter of a sympy plot?
The sympy plot command has a markers parameter:
markers : A list of dictionaries specifying the type the markers required. The keys in the dictionary should be equivalent to the arguments of the matplotlib's plot() function along with the marker related keyworde... | How do I use the markers parameter of a sympy plot? | The sympy plot command has a markers parameter:
markers : A list of dictionaries specifying the type the markers required. The keys in the dictionary should be equivalent to the arguments of the matplotlib's plot() function along with the marker related keyworded arguments.
How do I use the markers parameter? My fail... | [
"Nice find!\nThe documentation doesn't make things clear. Diving into the source code, leads to these lines in plot.py:\n for marker in parent.markers:\n # make a copy of the marker dictionary\n # so that it doesn't get altered\n m = marker.copy()\n ... | [
3,
1
] | [] | [] | [
"markers",
"plot",
"python",
"sympy"
] | stackoverflow_0071469474_markers_plot_python_sympy.txt |
Q:
Implementing 2D sliding window in Tensorflow
I have a 3-dim shape tensor and I'm trying to transverse it using 2D sliding window as illustrated below:
in this image, each letter represents an n-elements array and the window size is 3x3. The window is always squared such as 3x3, 5x5, etc
I'm failing to find a way ... | Implementing 2D sliding window in Tensorflow | I have a 3-dim shape tensor and I'm trying to transverse it using 2D sliding window as illustrated below:
in this image, each letter represents an n-elements array and the window size is 3x3. The window is always squared such as 3x3, 5x5, etc
I'm failing to find a way to implement this without numpy/loops. My object i... | [
"Let suppose creating a Matrix m with size n*n\n m =[\n ['a' , 'b' , 'c' , 'd' , 'e'],\n ['f' , 'g' , 'h' , 'i' , 'j'],\n ['k' , 'l' , 'm' , 'n' , 'o'],\n ['p', 'q' , 'r' , 's' , 't'],\n ['u' , 'v' , 'w' , 'y' , 'x']\n]\n\ndef conv_slide_window(matrix_len , pad_size, stride):\n\n matrix = tf.resh... | [
0
] | [] | [] | [
"python",
"sliding_window",
"tensorflow"
] | stackoverflow_0074574953_python_sliding_window_tensorflow.txt |
Q:
Implementing assertRaises unittest for class/class method
I have written a class in Python that is intialized with a few arguments.
Iam trying to write a test that check if all the arguments are int, otherwise throw TypeError.
Here is my attempt :
import unittest
from footer import Footer
class TestFooter(unittes... | Implementing assertRaises unittest for class/class method | I have written a class in Python that is intialized with a few arguments.
Iam trying to write a test that check if all the arguments are int, otherwise throw TypeError.
Here is my attempt :
import unittest
from footer import Footer
class TestFooter(unittest.TestCase):
def test_validInput(self):
footer = F... | [
"This is the wrong way to use assertRaises:\nimport unittest\n\n\ndef this_func_raises():\n raise ValueError\n\n\nclass TestClass(unittest.TestCase):\n def test1(self):\n self.assertRaises(ValueError, this_func_raises())\n\nNote that the ValueError will be raised if you include the (), since that would... | [
3
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0074584452_python_unit_testing.txt |
Q:
Run multiple functions on single videostream multiprocessing
Hey I am trying to run different face detection models simultaneously. I am using opencv library to open Video Stream and created different process objects for different face detection models. When I run the program the first method is running successfu... | Run multiple functions on single videostream multiprocessing | Hey I am trying to run different face detection models simultaneously. I am using opencv library to open Video Stream and created different process objects for different face detection models. When I run the program the first method is running successfully but second method exits with an error that can't receive fram... | [
"I have made various attempts:\n\nI tried using multiprocessing with a producer process and two consumer processes. The frame created by the producer must be converted to a shared-memory array and then converted back to a numpy array when retrieved by a consumer. There is sufficient overhead in these operations tha... | [
0
] | [] | [] | [
"multiprocessing",
"python",
"python_multiprocessing"
] | stackoverflow_0074567376_multiprocessing_python_python_multiprocessing.txt |
Q:
i cant pass data from python flask api to javascript by tojson
i am trying to send data from my flask api to javacript by return render_template("login.html",statef="0") but something hapening on javascript end keeping me from correctly recieving my data
the problem is in curr={{statef|tojson}} i tried (()) instea... | i cant pass data from python flask api to javascript by tojson | i am trying to send data from my flask api to javacript by return render_template("login.html",statef="0") but something hapening on javascript end keeping me from correctly recieving my data
the problem is in curr={{statef|tojson}} i tried (()) instead of {{}} but it doesnt work, it outputs me that tojson is not defin... | [
"Example of using tojson filter in flask template to parse JSON\nYou can pass data from Flask to Javascript and read it as JSON using the tojson filter in Flask template (documentation of tojson filter in Flask template) :\napp.py:\nfrom flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/log... | [
0
] | [] | [] | [
"flask",
"javascript",
"json",
"python"
] | stackoverflow_0074583764_flask_javascript_json_python.txt |
Q:
Variable definition as constraint in pyomo
This question is related to my previous question found here. I have managed to solve this problem (big thanks to @AirSquid!) My objective function is something like:
So the avgPrice_n variable is indexed by n. However, it is actually defined as
Meaning that it is indexe... | Variable definition as constraint in pyomo | This question is related to my previous question found here. I have managed to solve this problem (big thanks to @AirSquid!) My objective function is something like:
So the avgPrice_n variable is indexed by n. However, it is actually defined as
Meaning that it is indexed by n and i.
So at the moment my objective func... | [
"You have a couple options. Realize you do not need the model.avg_price variable because you can construct it from other variables and you would have to make some constraints to constrain the value, etc. etc. and pollute your model.\nThe basic building blocks in the model are pyomo expressions, so you could put in... | [
1
] | [] | [] | [
"optimization",
"pyomo",
"python"
] | stackoverflow_0074582337_optimization_pyomo_python.txt |
Q:
How to click button with Selenium
I tried with XPath but selenium can't click this image/button.
from undetected_chromedriver.v2 import Chrome
def test():
driver = Chrome()
driver.get('https://bandit.camp')
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"/html/body/div[... | How to click button with Selenium | I tried with XPath but selenium can't click this image/button.
from undetected_chromedriver.v2 import Chrome
def test():
driver = Chrome()
driver.get('https://bandit.camp')
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"/html/body/div[1]/div/main/div/div/div/div/div[5]/div/... | [
"Try the below one, I checked it, and it is working fine, while clicking on the link it is opening a separate window for login.\nfree_case = driver.find_element(By.XPATH, \".//p[contains(text(),'Open your free')]\")\n\ndriver.execute_script(\"arguments[0].scrollIntoView(true)\", free_case)\ntime.sleep(1)\ndriver.ex... | [
1,
1
] | [] | [] | [
"automation",
"python",
"scroll",
"selenium",
"webdriverwait"
] | stackoverflow_0074574715_automation_python_scroll_selenium_webdriverwait.txt |
Q:
How to automatize multiple (30143) images downloading from a website
There is a website that stores two videos as a list of thousands of PNGs, 31145 images in total. Is there a way to automate the downloading by generating the URLs? (I have no knowledge in coding.)
Here's the 1st video's first frame and its last ... | How to automatize multiple (30143) images downloading from a website | There is a website that stores two videos as a list of thousands of PNGs, 31145 images in total. Is there a way to automate the downloading by generating the URLs? (I have no knowledge in coding.)
Here's the 1st video's first frame and its last frame.
Here's the 2nd video's first frame and its last frame.
I couldn't... | [
"You need to get two things: generate URLs of images, then download them.\nGenerating URLs can be done using for loop and formatting, consider following simple example\ntemplate = 'xxx/%05dms/match/image.png'\nfor i in range(1,11): # limited for brevity sake, adjust as requires\n print(template % i)\n\ngives out... | [
1,
-1
] | [] | [] | [
"automation",
"download",
"python"
] | stackoverflow_0074583694_automation_download_python.txt |
Q:
U01 PDF and CDF using SymPy
Trying to define and get CDF of the U01 PDF, which, in turn, is just a box function
from sympy import Function, Symbol, integrate
from sympy.functions.elementary.complexes import sign
Ok, defining U01
x = Symbol('x')
a = Symbol('a')
w = Symbol('w')
u01 = Function('u01')
u01 = (sign(x)... | U01 PDF and CDF using SymPy | Trying to define and get CDF of the U01 PDF, which, in turn, is just a box function
from sympy import Function, Symbol, integrate
from sympy.functions.elementary.complexes import sign
Ok, defining U01
x = Symbol('x')
a = Symbol('a')
w = Symbol('w')
u01 = Function('u01')
u01 = (sign(x) + sign(1-x))/2
and output looks... | [
"With no additional assumptions, x is considered to be an arbitrary complex number. In your case you want x to be real:\nx_real = Symbol('x', real=True)\nu01_real = (sign(x_real) + sign(1-x_real))/2\nintegrate(u01_real,x_real)\n\nThis outputs\nPiecewise((0, x < 0), (x, x < 1), (1, True))\n\nSee this document on ass... | [
1
] | [] | [] | [
"python",
"sympy"
] | stackoverflow_0074584476_python_sympy.txt |
Q:
Pipe notation for more than two types in a type hint
I am trying:
def foo(x: int | float | str):
pass
foo(0)
and get the error:
TypeError: unsupported operand type(s) for |: 'type' and 'type'
Is it possible to use more than two types with pipe notation or I have to write Union?
EDIT It turns out that I have... | Pipe notation for more than two types in a type hint | I am trying:
def foo(x: int | float | str):
pass
foo(0)
and get the error:
TypeError: unsupported operand type(s) for |: 'type' and 'type'
Is it possible to use more than two types with pipe notation or I have to write Union?
EDIT It turns out that I have a version of python that does not support the pipe notati... | [
"Syntactic sugar like this to represent union types wasn't added until 3.10 with the introduction of PEP 604. Update to 3.10+ or use typing.Union.\n"
] | [
1
] | [] | [] | [
"python",
"type_hinting"
] | stackoverflow_0074584487_python_type_hinting.txt |
Q:
How to make list if text present in text file
Input text-
'''
Intro: hello, how are you
I am fine.
Intro: hey, how are you
Hope you are fine.
'''
Output:
[[hello,how are you i fine],[hey, how are you Hope you are fine]]
For text in f:
text= text.strip()
A:
Though I'm unaware and confused about the structure of y... | How to make list if text present in text file | Input text-
'''
Intro: hello, how are you
I am fine.
Intro: hey, how are you
Hope you are fine.
'''
Output:
[[hello,how are you i fine],[hey, how are you Hope you are fine]]
For text in f:
text= text.strip()
| [
"Though I'm unaware and confused about the structure of your .txt file, and framing of your question; still I would like to answer. Maybe it helps you.\nAssuming the structure of your .txt file is supposedly like this screenshot -\n\nFollowing code does the purpose -\nf_list = [] ## final or output list\n\nwith ... | [
0
] | [] | [] | [
"file",
"list",
"logic",
"python",
"text"
] | stackoverflow_0074582751_file_list_logic_python_text.txt |
Q:
How to implement sorting in Django Admin for calculated model properties without writing the logic twice?
In my Django model, I defined a @property which worked nicely and the property can be shown in the admin list_display without any problems.
I need this property not only in admin but in my code logic in other... | How to implement sorting in Django Admin for calculated model properties without writing the logic twice? | In my Django model, I defined a @property which worked nicely and the property can be shown in the admin list_display without any problems.
I need this property not only in admin but in my code logic in other places as well, so it makes sense to have it as property for my model.
Now I wanted to make the column of thi... | [
"TL/DR: Yes your solution seems to follow the only way that makes sense.\n\nWell, what you have composed here seems to be the recommended way from the sources you list in your question and for good reason.\nWhat is the good reason though?\nI haven't found a definitive, in the codebase, answer for that but I imagine... | [
5,
3,
2,
0,
0
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0058366953_django_django_admin_python.txt |
Q:
Create dataframe where column is a list of tuples
I'm trying to create a list of tuples within a dataframe. Using code below :
# creating the Numpy array
array = np.array([[('A' , 1)], [('B' , 2)]])
# creating a list of index names
index_values = ['x1', 'x2']
# creating a list of column names
column_values ... | Create dataframe where column is a list of tuples | I'm trying to create a list of tuples within a dataframe. Using code below :
# creating the Numpy array
array = np.array([[('A' , 1)], [('B' , 2)]])
# creating a list of index names
index_values = ['x1', 'x2']
# creating a list of column names
column_values = ['(a,b)']
# creating the dataframe
df = pd.DataFra... | [
"The way you are creating the numpy array is wrong. Since it is an array of tuples, you will have to specify the dtype of the elements of the tuple while creating the array, and then later cast it back to an object type using astype(object).\nDo the following -\narray = np.array([[('A',1)], [('B',2)]], dtype=('<U10... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074575243_pandas_python.txt |
Q:
Alpha argument not working for matplotlib.patches.FancyArrow
So I'm trying to expand on this code, which is the only code I could find to display Markov Chains as a diagram of nodes and arrows. Specifically, I needed it to work for more than 4 states and I have been editing it to suit my needs. Since right now I w... | Alpha argument not working for matplotlib.patches.FancyArrow | So I'm trying to expand on this code, which is the only code I could find to display Markov Chains as a diagram of nodes and arrows. Specifically, I needed it to work for more than 4 states and I have been editing it to suit my needs. Since right now I want to use it for n=7 where any two states have a transition proba... | [
"Ok I just realized my mistake (well sort of, I don't really understand the mechanics of why this works). I have to pass the alpha keyword in the PatchCollection() function. Then it works. Thank you to myself for figuring this out lol\n"
] | [
0
] | [] | [] | [
"matplotlib",
"python"
] | stackoverflow_0074584319_matplotlib_python.txt |
Q:
reverse lazy error NoReverseMatch at django DeleteView
I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url
So this is my model:
class PatientAnalysis(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
analysis_date = m... | reverse lazy error NoReverseMatch at django DeleteView | I'm trying to return back to patient analyses list after deleting 1 analysis. But can't manage proper success url
So this is my model:
class PatientAnalysis(models.Model):
patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
analysis_date = models.DateTimeField(help_text = "Разделяйте даты точками! Ис... | [
"You can override the .get_success_url() method [Django-doc] to return the path to which we redirect:\nfrom django.urls import reverse\n\n\nclass PatientAnalysisDeleteView(DeleteView):\n model = PatientAnalysis\n\n def get_success_url(self):\n return reverse(\n 'journal:patient_analysis',\n ... | [
1
] | [] | [] | [
"django",
"django_class_based_views",
"python"
] | stackoverflow_0074584677_django_django_class_based_views_python.txt |
Q:
Django FieldError: Unsupported lookup 'kategorie' for IntegerField or join on the field not permitted
I have a Django Table with Crispy Filter and I would like to filter in Data table based on Category. But I am getting FieldError.
I tried to define my filter field by this way in filters.py:
kategorie = django_fil... | Django FieldError: Unsupported lookup 'kategorie' for IntegerField or join on the field not permitted | I have a Django Table with Crispy Filter and I would like to filter in Data table based on Category. But I am getting FieldError.
I tried to define my filter field by this way in filters.py:
kategorie = django_filters.CharFilter(label="Kategorie", field_name="ucet__cislo__kategorie__jmeno", lookup_expr='icontains')
An... | [
"Since cislo is an IntegerField, you can not join on this. you probably want to join on Mustek in reverse however, so:\nkategorie = django_filters.CharFilter(\n label='Kategorie',\n field_name='ucet__mustek__kategorie__jmeno',\n lookup_expr='icontains',\n)\n"
] | [
1
] | [] | [] | [
"django",
"django_crispy_forms",
"django_tables2",
"python"
] | stackoverflow_0074584718_django_django_crispy_forms_django_tables2_python.txt |
Q:
HTTPS error 401 when running discord bot in python
I get this error whenever i run my bot:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File ... | HTTPS error 401 when running discord bot in python | I get this error whenever i run my bot:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 801, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\l... | [
"According to this question, you should try:\n\nResetting your token, it could be invalid\nEnabling intents on the developer portal\n\n"
] | [
1
] | [] | [] | [
"bots",
"discord",
"discord.py",
"python",
"python_3.9"
] | stackoverflow_0074584698_bots_discord_discord.py_python_python_3.9.txt |
Q:
Detect long-press using Keybow
I'm trying to use this python library https://github.com/pimoroni/keybow-python to control a raspberry pi (initiate events, e.g. launch a script or shutdown the pi).
This works will so far. I'm struggling to detect a long press. The API linked above allows 'catching' the event of pre... | Detect long-press using Keybow | I'm trying to use this python library https://github.com/pimoroni/keybow-python to control a raspberry pi (initiate events, e.g. launch a script or shutdown the pi).
This works will so far. I'm struggling to detect a long press. The API linked above allows 'catching' the event of pressing the button or releasing it. No... | [
"It sounds like your issue is that when the @keybow.on decorator attaches the callback it has a static value for now that doesn't get updated by the while loop which will be in a different scope. Repeatedly declaring the callback during the while loop looks wrong also.\nI don't have this hardware so it is not possi... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0074584067_python.txt |
Q:
How to instantiate object using iterable in Python?
I need to instantiate an object using iterable with multiple objects inside. I have to create another method to do it
class MyClass:
def __init__(self, *args):
self.args = args
def instantiate_from_iterable
#some clever code
I need to have a resul... | How to instantiate object using iterable in Python? | I need to instantiate an object using iterable with multiple objects inside. I have to create another method to do it
class MyClass:
def __init__(self, *args):
self.args = args
def instantiate_from_iterable
#some clever code
I need to have a result like this
MyClass.instantiate_from_iterable([1, 5, 3])... | [
"classmethod is what what you're after:\nfrom collections.abc import Iterable\n\nclass MyClass:\n def __init__(self, *args):\n self.args = args\n \n @classmethod\n def instantiate_from_iterable(cls, args: Iterable):\n return cls(*args)\n\n \na = MyClass(1, 5, 7)\nb = MyClass.instantiate_... | [
3,
0
] | [] | [] | [
"python",
"python_class"
] | stackoverflow_0074584717_python_python_class.txt |
Q:
Delete duplicate dictionary form a list of dictionaries
I want to find duplicate directories from a list of dictionaries and delete one of them but it's generating an error. name, age, group only all 3 should be same values to take it as duplicate dictionary. Without append to a new list of dictionaries
a = [
{"... | Delete duplicate dictionary form a list of dictionaries | I want to find duplicate directories from a list of dictionaries and delete one of them but it's generating an error. name, age, group only all 3 should be same values to take it as duplicate dictionary. Without append to a new list of dictionaries
a = [
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name":... | [
"If I understand you correctly, the duplicate is only when name, age and group match:\na = [\n {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Mark\", \"age\": 5, \"group\": \"sdo\", \"points\": 0},\n {\"name\": \"Pam\", \"age\": 7, \"group\": \"spp\", \"points\": 0},\n ... | [
4,
3
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0074584726_dictionary_list_python.txt |
Q:
IndexError: no such group - Python
Can anyone help with answering why I'm getting the following error?
Error :
File "./digiimport-s5.py", line 77, in processdir
finddate = (finddate[0:24] + ".jpeg")
IndexError: no such group
Code Snippet :
if f.startswith("signal"):
finddate = re.match("signal-(\d+-\d+-\d... | IndexError: no such group - Python | Can anyone help with answering why I'm getting the following error?
Error :
File "./digiimport-s5.py", line 77, in processdir
finddate = (finddate[0:24] + ".jpeg")
IndexError: no such group
Code Snippet :
if f.startswith("signal"):
finddate = re.match("signal-(\d+-\d+-\d+-\d+-\d+).jpeg",f)
if finddate:
... | [
"After running your code and taking a look at the stack trace, the faulty part seems to be finddate[0:24], which attempts to access 24 capture groups from the match object, which is failing because the object only contains 2 groups.\nPresumably you wanted to grab 24 characters from the original string (i.e. do f[:2... | [
0
] | [] | [] | [
"python",
"python_3.x",
"rename"
] | stackoverflow_0074579192_python_python_3.x_rename.txt |
Q:
Pysimplegui resizing images
I'm trying to resize images in pysimplegui however it crops the images instead of resizing.
My image element is written as:
ui.Image('{filename}'), size=(50,50)))
Which results to something like:
While the original looks like:
I've seen somewhere else that suggests PIL (link). Howeve... | Pysimplegui resizing images | I'm trying to resize images in pysimplegui however it crops the images instead of resizing.
My image element is written as:
ui.Image('{filename}'), size=(50,50)))
Which results to something like:
While the original looks like:
I've seen somewhere else that suggests PIL (link). However, this looks a lot longer than i... | [
"Peace\nhi\nto resize an image you need to take advantage of the pillow library, but you need to import other libraries too in order to convert it into bytes if needed, here is an example:\nimport PIL.Image\nimport io\nimport base64\n\ndef resize_image(image_path, resize=None): #image_path: \"C:User/Image/img.jpg\"... | [
0,
0
] | [] | [] | [
"pysimplegui",
"python",
"user_interface"
] | stackoverflow_0070496657_pysimplegui_python_user_interface.txt |
Q:
URI of MySQL for SQLAlchemy for connection without password
Could someone kindly advise how the uri of MySQL for SQLAlchemy for a connection without password should be set?
For the code as below, the pymysql part works, but the SQLAlchemy has the below error. I have tried other uri as well as commented below, all... | URI of MySQL for SQLAlchemy for connection without password | Could someone kindly advise how the uri of MySQL for SQLAlchemy for a connection without password should be set?
For the code as below, the pymysql part works, but the SQLAlchemy has the below error. I have tried other uri as well as commented below, all failed.
The database name is "finance_fdata_master"
Thanks a lot... | [
"Your code defines a connection URL string in the variable uri. Then you look up an environment variable with that name and it doesn't exist, so db_uri is None. Then you pass that (None value) to create_engine() and it fails.\nengine = create_engine(uri, echo=True) # not db_uri\n\nwill probably work better.\n"
] | [
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0074583988_mysql_python_sqlalchemy.txt |
Q:
How can I develop with Python libraries in editable mode on databricks?
On Databricks, it is possible to install Python packages directly from a git repo, or from the dbfs:
%pip install git+https://github/myrepo
%pip install /dbfs/my-library-0.0.0-py3-none-any.whl
Is there a way to enable a live package developm... | How can I develop with Python libraries in editable mode on databricks? | On Databricks, it is possible to install Python packages directly from a git repo, or from the dbfs:
%pip install git+https://github/myrepo
%pip install /dbfs/my-library-0.0.0-py3-none-any.whl
Is there a way to enable a live package development mode, similar to the usage of pip install -e, such that the databricks no... | [
"I would recommend to adopt the Databricks Repos functionality that allows to import Python code into a notebook as a normal package, including the automatic reload of the code when Python package code changes.\nYou need to add the following two lines to your notebook that uses the Python package that you're develo... | [
1,
0
] | [] | [] | [
"databricks",
"pip",
"python"
] | stackoverflow_0074126228_databricks_pip_python.txt |
Q:
The view post.views.view didn't return an HttpResponse object. It returned None instead
I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error:
(The view post.views.view didn't return an HttpResponse object. It returned None instead.)
view... | The view post.views.view didn't return an HttpResponse object. It returned None instead | I want to create a new post using PostCreateView and go to the details page of the new post in the next step, but I get this error:
(The view post.views.view didn't return an HttpResponse object. It returned None instead.)
views
class PostDetailView(View):
"""see detail post"""
def get(self, request, post_id, ... | [
"In case the form is not valid, you should rerender the template with the form, so:\nclass PostCreateView(LoginRequiredMixin, View):\n form_class = PostCreateUpdateForm\n\n def get(self, request, *args, **kwargs):\n form = self.form_class\n return render(request, \"post/create.html\", {\"form\":... | [
2,
2
] | [] | [] | [
"django",
"django_4.1",
"django_forms",
"python",
"python_3.x"
] | stackoverflow_0074584803_django_django_4.1_django_forms_python_python_3.x.txt |
Q:
Is there a way to add custom data into ListAPIView in django rest framework
So I've built an API for movies dataset which contain following structure:
Models.py
class Directors(models.Model):
id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
... | Is there a way to add custom data into ListAPIView in django rest framework | So I've built an API for movies dataset which contain following structure:
Models.py
class Directors(models.Model):
id = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=100, blank=True, null=True)
last_name = models.CharField(max_length=100, blank=True, null=True)
class M... | [
"If you want, the number of movies by genre for a given actor what you can do is annotate and count aggregate\nreturn Roles.objects.filter(\n actor_id=self.kwargs['pk']\n ).values('movie__movies_genres__genre').annotate(\n no_of_movies=Count('movie__movies_genres__genre'),\n ... | [
1,
0,
0
] | [] | [] | [
"api",
"django",
"django_rest_framework",
"python",
"rest"
] | stackoverflow_0074552043_api_django_django_rest_framework_python_rest.txt |
Q:
Responding with a custom non simple object from a Django/Python API to the front
I'm a newbie building APIs with django/python
I built a dictionary object (it has lists inside other lists in it), and I want to send it to the front through one of the responses: JsonResponse, HttpResponse, etc.
What could be the way... | Responding with a custom non simple object from a Django/Python API to the front | I'm a newbie building APIs with django/python
I built a dictionary object (it has lists inside other lists in it), and I want to send it to the front through one of the responses: JsonResponse, HttpResponse, etc.
What could be the way to do it?
I tried with several of them without a good response, I whether get an erro... | [
"I got it\nJust assume that you will send an array of objects, and the front end should access the first object it finds\n myResponse = []\n myResponse.append(myObject) \n return HttpResponse(myResponse, status=200) // status is optional\n\n"
] | [
0
] | [] | [] | [
"dictionary",
"django",
"httpresponse",
"jsonresponse",
"python"
] | stackoverflow_0074584425_dictionary_django_httpresponse_jsonresponse_python.txt |
Q:
why does the dictionary key not update to record the change in keys
the goal is to increase the dictionary key by 1 so all values generated by for loop are stored in a dictionary
code
counting = {}
numbers = 1
for i in range(1, 11):
counting[numbers] = (i)
numbers + 1
print(counting)
but in the final re... | why does the dictionary key not update to record the change in keys | the goal is to increase the dictionary key by 1 so all values generated by for loop are stored in a dictionary
code
counting = {}
numbers = 1
for i in range(1, 11):
counting[numbers] = (i)
numbers + 1
print(counting)
but in the final result the dictionary only has one key and one stored value that is
result... | [
"You have to put numbers += 1 or numbers = numbers + 1 instead of numbers + 1 if you want to update the variable.\nWhen python sees numbers + 1, it just evaluates that line, gets 2, and does nothing with that value. If you don't have an = sign, the variable will not be changed.\n",
"I don't think you realize, but... | [
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0074584836_dictionary_python.txt |
Q:
Extracting an element of a list in a pandas column
I have a DataFrame that contains a list on each column as shown in the example below with only two columns.
Gamma Beta
0 [1.4652917656926299, 0.9326935235505321, float] [91, 48.611034768515864, int]
1 [2.6008354611105995, 0.7608529935313189, float] [59,... | Extracting an element of a list in a pandas column | I have a DataFrame that contains a list on each column as shown in the example below with only two columns.
Gamma Beta
0 [1.4652917656926299, 0.9326935235505321, float] [91, 48.611034768515864, int]
1 [2.6008354611105995, 0.7608529935313189, float] [59, 42.38646954167245, int]
2 [2.6386970166722348, 0.9785... | [
"You can use the str accessor for lists, e.g.:\ndf_params['Gamma'].str[0]\n\nThis should work for all columns:\ndf_params.apply(lambda col: col.str[0])\n\n",
"Itertuples would be pretty slow. You could speed this up with the following:\nfor column_name in df_params.columns:\n df_params[column_name] = [i[0] for... | [
58,
3,
0,
0
] | [] | [] | [
"pandas",
"python",
"python_3.x"
] | stackoverflow_0045983017_pandas_python_python_3.x.txt |
Q:
Create row from previous and next rows if date are discontinuous
I need to create a row if Current End date compared to Start date from next row are discontinuous by each Employee Number. The dataframe looks like this:
Employee Number
Start Date
End Date
001
1999-11-29
2000-03-12
001
2000-03-13
2001-06-30
001
... | Create row from previous and next rows if date are discontinuous | I need to create a row if Current End date compared to Start date from next row are discontinuous by each Employee Number. The dataframe looks like this:
Employee Number
Start Date
End Date
001
1999-11-29
2000-03-12
001
2000-03-13
2001-06-30
001
2001-07-01
2002-01-01
002
2000-09-18
2000-10-05
002
2000-1... | [
"Plan A: (Filling in gaps)\n\nCreate a table of all possible dates (in the desired range). (This is easy to do on the fly in MariaDB by using a seq_..., but messier in MySQL.)\nSELECT ... FROM that-table-of-dates LEFT JOIN your-table ON ...\n\nAs for filling in the gaps with values before (or after) the given ho... | [
1
] | [] | [] | [
"dataframe",
"date",
"indexing",
"pandas",
"python"
] | stackoverflow_0074584590_dataframe_date_indexing_pandas_python.txt |
Q:
overlaying the ground truth mask on an image
In my project, I extracted frames from a video and in another folder I have ground truth for each frame.
I want to map the ground truth image of each frame of a video (in my case, it is saliency prediction ground truth) on its related frame image. As an example I have t... | overlaying the ground truth mask on an image | In my project, I extracted frames from a video and in another folder I have ground truth for each frame.
I want to map the ground truth image of each frame of a video (in my case, it is saliency prediction ground truth) on its related frame image. As an example I have the following frame:
And the following is ground t... | [
"I need to do similar things pretty often. In my favorite StackOverflow fashion, here is a script that you can copy and paste. I hope the code itself is self-explanatory. There are a few things that you can tune and try (e.g., color maps, overlay styles). It uses multiprocessing.Pool for faster batch-processing, re... | [
8,
4
] | [] | [] | [
"opencv",
"python",
"pytorch"
] | stackoverflow_0074546287_opencv_python_pytorch.txt |
Q:
Deleteing rows in a pandas dataframe if it contains a certain string
I have a list of columns in a dataframe that either contains a hashmark followed by a string or two hashmarks followed by a string. I wanted to eliminate the rows that contain only one hashmark.
df[df["column name"].str.contains("#") == False]
I'... | Deleteing rows in a pandas dataframe if it contains a certain string | I have a list of columns in a dataframe that either contains a hashmark followed by a string or two hashmarks followed by a string. I wanted to eliminate the rows that contain only one hashmark.
df[df["column name"].str.contains("#") == False]
I've tried using the code above but it erased the entire column. I hoped tha... | [
"can you try this:\ndf['len']=df['column name'].str.count('#') #how many \"#\" expressions are in the column.\n\ndf=df[df[\"len\"]>1]\n\n#or one line\n\ndf=df[df['column name'].str.count('#')>1]\n\n\n",
"if each of them have at least one '#' , and its either ## or #,\ndf[df[\"column name\"].str.contains(\"##\") =... | [
0,
0
] | [] | [] | [
"data_filtering",
"pandas",
"python"
] | stackoverflow_0074584816_data_filtering_pandas_python.txt |
Q:
how to find the most popular letter in a string that also has the lowest ascii value
Implement the function most_popular_character(my_string), which gets the string argument my_string and returns its most frequent letter. In case of a tie, break it by returning the letter of smaller ASCII value.
Note that lowercas... | how to find the most popular letter in a string that also has the lowest ascii value | Implement the function most_popular_character(my_string), which gets the string argument my_string and returns its most frequent letter. In case of a tie, break it by returning the letter of smaller ASCII value.
Note that lowercase and uppercase letters are considered different (e.g., ‘A’ < ‘a’). You may assume my_stri... | [
"Your dictionary didn't get off to a good start by you forgetting to add 1 to the character count, instead you are resetting to 1 each time.\nHave a look here to get the gist of getting the maximum value from a dict: https://datagy.io/python-get-dictionary-key-with-max-value/\ndef most_popular_character(my_string):... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"for_loop",
"if_statement",
"python",
"sorteddictionary"
] | stackoverflow_0074584404_dictionary_for_loop_if_statement_python_sorteddictionary.txt |
Q:
how to set foreign by post method in django?
models.py
class Courses(models.Model):
course_name=models.CharField(max_length=50)
course_price=models.IntegerField()
class Exam(models.Model):
exam_name=models.CharField(max_length=101)
course=models.ForeignKey(Courses,on_delete=models.CASCADE,defa... | how to set foreign by post method in django? | models.py
class Courses(models.Model):
course_name=models.CharField(max_length=50)
course_price=models.IntegerField()
class Exam(models.Model):
exam_name=models.CharField(max_length=101)
course=models.ForeignKey(Courses,on_delete=models.CASCADE,default='python')
exam_time=models.DateTimeField(... | [
"You should assign the primary key to course_id, so:\ndef Examadd(request):\n mycourses = Courses.objects.all()\n context = {'mycourses': mycourses}\n if request.method == 'POST':\n newexam = request.POST.get('examname')\n course = request.POST.get('courses')\n examtime = request.POST.... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0074583150_django_django_models_django_templates_django_views_python.txt |
Q:
Create column based on pandas.DataFrame.between_time() without time be the index column
I got a dataframe with a date/time in seconds, which I changed by:
df["start"] = pd.to_datetime(df["start"], unit='s')
df["time"] = df["start"].dt.time
Now I would like to add a column df["timeofday"], which include the t... | Create column based on pandas.DataFrame.between_time() without time be the index column | I got a dataframe with a date/time in seconds, which I changed by:
df["start"] = pd.to_datetime(df["start"], unit='s')
df["time"] = df["start"].dt.time
Now I would like to add a column df["timeofday"], which include the time of day string.
0:00 - 5:59 night
6:00 - 11:59 morning
12:00 - 17:59 afternoon
18:0... | [
"Found a solution\ndf.set_index(\"start\", inplace=True)\ndf[\"timeofday\"] = 'night'\n\nmask = df.between_time('06:00', '11:59')\ndf.loc[mask.index, 'timeofday'] = \"morning\"\n\nmask = df.between_time('12:00', '17:59')\ndf.loc[mask.index, 'timeofday'] = \"afternoon\"\n\nmask = df.between_time('18:00', '21:59')\nd... | [
0,
0
] | [] | [] | [
"dataframe",
"pandas",
"python"
] | stackoverflow_0074584137_dataframe_pandas_python.txt |
Q:
convert UNIX timestamp to US/Central using tz_convert
I'm trying to convert my UNIX timestamp to the US/Central timezone timestamp, but i keep getting the UTC output. I don't know what i'm doing wrong in the code.
import ccxt
import pandas as pd
from dateutil import tz
binance = ccxt.binance({
'enableRateLimi... | convert UNIX timestamp to US/Central using tz_convert | I'm trying to convert my UNIX timestamp to the US/Central timezone timestamp, but i keep getting the UTC output. I don't know what i'm doing wrong in the code.
import ccxt
import pandas as pd
from dateutil import tz
binance = ccxt.binance({
'enableRateLimit': True,
'apiKey': 'xxxxxxxxxxxxxxxxxxx',
'secret'... | [
"I think you want.\ndf[\"timestamp\"] = (\n pd.to_datetime(df[\"timestamp\"], unit=\"ms\")\n .dt.tz_localize(\"UTC\")\n .dt.tz_convert(\"US/Central\")\n .dt.tz_localize(None)\n)\n\n"
] | [
0
] | [] | [] | [
"ccxt",
"datetime",
"pandas",
"python"
] | stackoverflow_0074584171_ccxt_datetime_pandas_python.txt |
Q:
I am trying to web-scraping the historical price with python from this URL.
https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium
I checked developer tools on chrome browser, there is the information I'd like to get in the <script> which is located under the <div id="market-stats"> I had attached t... | I am trying to web-scraping the historical price with python from this URL.
https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium
I checked developer tools on chrome browser, there is the information I'd like to get in the <script> which is located under the <div id="market-stats"> I had attached the i... | [
"Below is an example how to grab the required script tag from API response and rest of your task.\nimport pandas as pd\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium'\nheaders={\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64... | [
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"web_scraping"
] | stackoverflow_0074584410_beautifulsoup_html_python_web_scraping.txt | |
Q:
airflow 2 / docker-compose: how to install Python dependencies for DAGs?
I have installed airflow 2.0.2 using docker-compose as described under https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html.
I have researched quite some time, but I don't find a way to install python dependencies for my DA... | airflow 2 / docker-compose: how to install Python dependencies for DAGs? | I have installed airflow 2.0.2 using docker-compose as described under https://airflow.apache.org/docs/apache-airflow/stable/start/docker.html.
I have researched quite some time, but I don't find a way to install python dependencies for my DAGs. I know how to do this using a Dockerfile (COPY requirements.txt /app / RUN... | [
"Instead of using\nimage: apache/airflow:x.x.x\n\nin your docker compose you want to set this to\nbuild:\n context: .\n dockerfile: Dockerfile\n\nand then write this to your Dockerfile\nFROM apache/airflow:x.x.x\n\nCOPY requirements.txt ./requirements.txt\n\nwhere your requirements.txt contains the python pac... | [
0
] | [] | [] | [
"airflow",
"dependencies",
"docker_compose",
"python"
] | stackoverflow_0067486845_airflow_dependencies_docker_compose_python.txt |
Q:
How to repeatedly execute a function every x seconds?
I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C or setTimeout in JS). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiri... | How to repeatedly execute a function every x seconds? | I want to repeatedly execute a function in Python every 60 seconds forever (just like an NSTimer in Objective C or setTimeout in JS). This code will run as a daemon and is effectively like calling the python script every minute using a cron, but without requiring that to be set up by the user.
In this question about a ... | [
"If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.\nimport sched, time\ns = sched.scheduler(time.time, time.sleep)\ndef do_something(sc): \n print(\"Doing stuff...\")\n # do your stuff\n sc.enter(60, 1, do_something, (sc,))\n\ns.ent... | [
369,
338,
101,
85,
47,
41,
35,
20,
10,
6,
5,
5,
4,
2,
2,
2,
2,
1,
1,
0,
0,
0
] | [] | [] | [
"python",
"timer"
] | stackoverflow_0000474528_python_timer.txt |
Q:
Custom Titlebar with frame in PyQt5
I'm working on an opensource markdown supported minimal note taking application for Windows/Linux. I'm trying to remove the title bar and add my own buttons. I want something like, a title bar with only two custom buttons as shown in the figure
Currently I have this:
I've tried... | Custom Titlebar with frame in PyQt5 | I'm working on an opensource markdown supported minimal note taking application for Windows/Linux. I'm trying to remove the title bar and add my own buttons. I want something like, a title bar with only two custom buttons as shown in the figure
Currently I have this:
I've tried modifying the window flags:
With not w... | [
"Here are the steps you just gotta follow:\n\nHave your MainWindow, be it a QMainWindow, or QWidget, or whatever [widget] you want to inherit.\nSet its flag, self.setWindowFlags(Qt.FramelessWindowHint)\nImplement your own moving around.\nImplement your own buttons (close, max, min)\nImplement your own resize.\n\nHe... | [
26,
5,
1,
0
] | [] | [] | [
"pyqt",
"pyqt5",
"python",
"qt",
"window"
] | stackoverflow_0044241612_pyqt_pyqt5_python_qt_window.txt |
Q:
Changes made are not reversing
I was trying to build a simple program that blocks the websites for a given time. The websites are listed in a txt file that I have locked for security reasons. This was my first time experimenting with filelock systems and the problem is that the execution of the website blockage wo... | Changes made are not reversing | I was trying to build a simple program that blocks the websites for a given time. The websites are listed in a txt file that I have locked for security reasons. This was my first time experimenting with filelock systems and the problem is that the execution of the website blockage works perfectly but once the time is o... | [
"It is a bit difficult ro reproduce. You probably need a main loop.\nSomething to reexecute your code or wait for the second part of your code which is easier for your code structure.\ntry:\nimport time\n\ndef block_websites():\n if datetime.now() < end_time:\n print(\"Block sites\")\n with open(ho... | [
0
] | [] | [] | [
"debugging",
"file_locking",
"locking",
"python",
"security"
] | stackoverflow_0074584552_debugging_file_locking_locking_python_security.txt |
Q:
Python: delete row in dataframe by condition
I want to drop all rows in the ratings df where the team has no game. So not in the fixtures df in HomeTeam or AwayTeam occur. following I tried:
fixtures = pd.DataFrame({'HomeTeam': ["Team1", "Team3", "Team5", "Team6"], 'AwayTeam': [
"Team2", "Team4", "Team6", "Tea... | Python: delete row in dataframe by condition | I want to drop all rows in the ratings df where the team has no game. So not in the fixtures df in HomeTeam or AwayTeam occur. following I tried:
fixtures = pd.DataFrame({'HomeTeam': ["Team1", "Team3", "Team5", "Team6"], 'AwayTeam': [
"Team2", "Team4", "Team6", "Team8"]})
ratings = pd.DataFrame({'team': ["Team1", ... | [
"Because both dataframes are not of equal size. You can use isin() instead.\nratings = ratings[~ratings.team.isin(fixtures.stack())]\n\n#output\n'''\n team rating\n6 Team7 0,9\n8 Team9 -0,6\n9 Team10 1,5\n10 Team11 0,2\n11 Team12 0,5\n\n'''\n\nDetails:\nprint(fixtures.stack())\n'''\n0 HomeTeam... | [
1
] | [] | [] | [
"pandas",
"python"
] | stackoverflow_0074585123_pandas_python.txt |
Q:
Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them
i have an assignment coming up in which i have to code a dice game . its multiplayer random luck with gambling points and etc
one of the things its asking for though is to save the winning p... | Im trying to do some code in python that reads a text file and picks out the 5 lines with the highest number and prints them | i have an assignment coming up in which i have to code a dice game . its multiplayer random luck with gambling points and etc
one of the things its asking for though is to save the winning players name and their score into a text file and at the end print the five highest scores in the text file with the five players n... | [
"If your data in file has this format:\nPlayer1 wins with 30 points\nPlayer2 wins with 40 points\nPlayer3 wins with 85 points\nPlayer5 wins with 45 points\nPlayer7 wins with 10 points\nPlayer6 wins with 80 points\nPlayer4 wins with 20 points\nPlayer9 wins with 90 points\nPlayer8 wins with 70 points\nPlayer11 wins w... | [
1,
0
] | [] | [] | [
"python",
"text_files"
] | stackoverflow_0074584806_python_text_files.txt |
Q:
Is there a way to add a 3rd, 4th and 5th y axis using Bokeh?
I would like to add multiple y axes to a bokeh plot (similar to the one achieved using matplotlib in the attached image).
Would this also be possible using bokeh? The resources I found demonstrate a second y axis.
Thanks in advance!
Best Regards,
Pranit ... | Is there a way to add a 3rd, 4th and 5th y axis using Bokeh? | I would like to add multiple y axes to a bokeh plot (similar to the one achieved using matplotlib in the attached image).
Would this also be possible using bokeh? The resources I found demonstrate a second y axis.
Thanks in advance!
Best Regards,
Pranit Iyengar
| [
"Yes, this is possible. To add a new axis to the figure p use p.extra_y_ranges[\"my_new_axis_name\"] = Range1d(...). Do not write p.extra_y_ranges = {\"my_new_axis_name\": Range1d(...)} if you want to add multiple axis, because this will overwrite and not extend the dictionary. Other range objects are also valid, t... | [
0
] | [] | [] | [
"bokeh",
"plot",
"python"
] | stackoverflow_0074572541_bokeh_plot_python.txt |
Q:
Numpy: Looking for efficient way to multiply a vector with a vandermonde matrix
Given two arrays A and B with the same size: N,
I'm trying to calculate the following product:
np.dot(A, np.vander(B, increasing=True))
However, If N becomes very large, I will eventually encounter an insufficient memory error.
This m... | Numpy: Looking for efficient way to multiply a vector with a vandermonde matrix | Given two arrays A and B with the same size: N,
I'm trying to calculate the following product:
np.dot(A, np.vander(B, increasing=True))
However, If N becomes very large, I will eventually encounter an insufficient memory error.
This makes sense since the memory complexity is N^2.
Is there an efficient way to do this w... | [
"Based on the documentation of the vandermonde matrix you can construct it in the following way:\nnp.vander(B, increasing=True) == np.column_stack([B**(i) for i in range(len(B))])\n\nSo your optimization would be to do dot product in-place:\nnp.column_stack([np.dot(A, B**(i)) for i in range(len(B))])\n\n"
] | [
0
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0074584855_numpy_python.txt |
Q:
How to save output of python function to GitHub actions?
How can I save the output of a Python function in mine GitHub Action code?
def example():
return "a"
if __name__ == "__main__":
example()
I tried to save to a variable, output and environment variable but it does not work. It only saves if I print ... | How to save output of python function to GitHub actions? | How can I save the output of a Python function in mine GitHub Action code?
def example():
return "a"
if __name__ == "__main__":
example()
I tried to save to a variable, output and environment variable but it does not work. It only saves if I print something in the function.
name: "Check Renamed files"
"on":... | [
"You could set it has a environment variable.\ndef example():\n return \"a\"\n\n\nif __name__ == \"__main__\":\n print(example())\n\n\nand then run:\npython3 test.py\n\nwill print to your console:\n\"a\"\n\nIn your Gitlab Actions, I would expect something like:\nname: GitHub Actions Demo\nrun-name: ${{ github... | [
0
] | [] | [] | [
"building_github_actions",
"github_actions",
"python",
"python_3.x"
] | stackoverflow_0074585271_building_github_actions_github_actions_python_python_3.x.txt |
Q:
Python add date value to column based on conditions
And thank you in advanced for the help.
Current pd.Dataframe:
event_name
start_date
end_date
Start
2010-11-12
2015-01-05
Phase 1
2015-01-05
2015-03-16
Phase 2
2015-04-04
2018-03-11
Phase 3
2018-03-11
2030-05-15
Phase 4
2030-05-15
2035-01-01
Phase 5
2035-01... | Python add date value to column based on conditions | And thank you in advanced for the help.
Current pd.Dataframe:
event_name
start_date
end_date
Start
2010-11-12
2015-01-05
Phase 1
2015-01-05
2015-03-16
Phase 2
2015-04-04
2018-03-11
Phase 3
2018-03-11
2030-05-15
Phase 4
2030-05-15
2035-01-01
Phase 5
2035-01-01
2035-04-01
Checkpoint
2025-12-25
NaT
... | [
"Since accessing the missing cells by index causes an exception, we had to add checks. Example with missing phase values 4 and 5.\ndt.txt\n\nevent_name start_date end_date\nStart 2010-11-12 2015-01-05\nPhase 1 2015-01-05 2015-03-16\nPhase 2 2015-04-04 2018-03-11\nPhase 3 2018-03-11 2030-05-15\nCheckpoint 2... | [
0
] | [] | [] | [
"logic",
"python",
"python_datetime"
] | stackoverflow_0074575024_logic_python_python_datetime.txt |
Q:
Cython- import class to pyx file
For example let's say we have two classe,
Bus- Implement The physical bus line.
src/bus/bus.pxd
cdef class Bus:
cdef int get_item(self)
src/bus/bus.pxd:
cdef class Bus:
cdef int get_item(self):
return 5
CPU- Implement The physical cpu processor
src/cpu/cpu... | Cython- import class to pyx file | For example let's say we have two classe,
Bus- Implement The physical bus line.
src/bus/bus.pxd
cdef class Bus:
cdef int get_item(self)
src/bus/bus.pxd:
cdef class Bus:
cdef int get_item(self):
return 5
CPU- Implement The physical cpu processor
src/cpu/cpu.pyx:
cimport bus.Bus as Bus
cdef clas... | [
"So, in cython we've to use pxd file for declaration in compile time.\nTherefor, adding __init__.pxd have to bee added for compilation import.\nIn Addition, I've created cpu.pxd file which inside I've wrote from bus cimport Bus.\n"
] | [
0
] | [] | [] | [
"cimport",
"cython",
"python"
] | stackoverflow_0074585217_cimport_cython_python.txt |
Q:
my jupyter notebook is pasting unncessary program lines inbetween
when I try to write any code jupyter notebook automatically paste any irrelevant / sometimes relevant program between the program, but I want to stop this shit, because it is irritating me. suggestions are different things. but this issue has arrive... | my jupyter notebook is pasting unncessary program lines inbetween | when I try to write any code jupyter notebook automatically paste any irrelevant / sometimes relevant program between the program, but I want to stop this shit, because it is irritating me. suggestions are different things. but this issue has arrived in my notebook for the past few days.you can see in this link exactly... | [
"looks like https://discourse.jupyter.org/t/jupyter-notebooks-annoying-grey-text-auto-show/16886/5, This is most likely a browser issue, what browser are you using? any extentions that could cause this? maybe try switching browsers?\n"
] | [
0
] | [] | [] | [
"jupyter_notebook",
"python"
] | stackoverflow_0074585277_jupyter_notebook_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.