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
... ...
1186 2022-11-15 109.00
1187 2022-11-16 117.50
1188 2022-11-17 132.85
1189 2022-11-18 133.80
1190 2022-11-21 122.65
We want to merge all dataframes together with key columns for the operation are 'Date' like this:
Date ISFT CARTRADE
0 2017-11-27 648.10 NaN
1 2017-11-28 649.90 NaN
2 2017-11-29 639.90 NaN
3 2017-11-30 697.10 NaN
4 2017-12-01 675.20 NaN
... ... ...
1187 2022-11-16 117.50 502.00
1188 2022-11-17 132.85 495.35
1189 2022-11-18 133.80 490.65
1190 2022-11-21 122.65 489.70
1191 2022-10-13 NaN 588.80
how can we do this for 20 dataframes in the quickliest way? Thank you.
We tried to use a For-loop by looping through the list of dataframes and merge the new columns to the previous dataframe. However, it doesn't work.
df_list = [PACE, NYKAA,ASRL, ZOMATO]
for i in df_list:
df_merge = df_merge.merge(i, on = 'Date', how = 'outer')
A:
Move Date into the index and use pd.concat to join the frames:
pd.concat([df.set_index("Date") for df in df_list], axis=1)
|
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 117.50
1188 2022-11-17 132.85
1189 2022-11-18 133.80
1190 2022-11-21 122.65
We want to merge all dataframes together with key columns for the operation are 'Date' like this:
Date ISFT CARTRADE
0 2017-11-27 648.10 NaN
1 2017-11-28 649.90 NaN
2 2017-11-29 639.90 NaN
3 2017-11-30 697.10 NaN
4 2017-12-01 675.20 NaN
... ... ...
1187 2022-11-16 117.50 502.00
1188 2022-11-17 132.85 495.35
1189 2022-11-18 133.80 490.65
1190 2022-11-21 122.65 489.70
1191 2022-10-13 NaN 588.80
how can we do this for 20 dataframes in the quickliest way? Thank you.
We tried to use a For-loop by looping through the list of dataframes and merge the new columns to the previous dataframe. However, it doesn't work.
df_list = [PACE, NYKAA,ASRL, ZOMATO]
for i in df_list:
df_merge = df_merge.merge(i, on = 'Date', how = 'outer')
|
[
"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
df = my_class.quality('headers')
# applymap() styles the table outside the class as expected
df.style.applymap(my_class.quality_style_null_val)
However, calling applymap inside the class doesn't style table
#functions in my_class
def quality(self, key=None):
df = self.df(key)
df.style.applymap(self.test)
return df
def test(val, params={'background-color':'green', "color":'white'}):
return 'color: red'
in Jupyter cell
#instantiate my_class and call function:
df = my_class.quality('headers')
A:
It works when you return the df.applymap() instead of styling and then returning.
def quality(self, key):
df = unify.df(key)
return df.style.applymap(self.quality_style)
|
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 expected
df.style.applymap(my_class.quality_style_null_val)
However, calling applymap inside the class doesn't style table
#functions in my_class
def quality(self, key=None):
df = self.df(key)
df.style.applymap(self.test)
return df
def test(val, params={'background-color':'green', "color":'white'}):
return 'color: red'
in Jupyter cell
#instantiate my_class and call function:
df = my_class.quality('headers')
|
[
"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
# Propriétés du moteur
impulsion specifique=80
and
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=Civic VTEC
# Propriétés générales
hauteur=2.0
masse=3000.0
prix=2968.00
# Propriétés du moteur
impulsion specifique=205
and
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=VelociRAPTOR
# Propriétés générales
hauteur=4.0
masse=2000.0
prix=6000.00
# Propriétés du moteur
impulsion specifique=250
and
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=La Puissance
# Propriétés générales
hauteur=12.0
masse=15000.0
prix=39000.00
# Propriétés du moteur
impulsion specifique=295
That's the result I need to have:
nom hauteur masse prix impulsion specifique
0 Tondeuse 0.5 20.0 110.0 80
1 Civic VTEC 2.0 3000.0 2968.0 205
2 VelociRAPTOR 4.0 2000.0 6000.0 250
3 La Puissance 12.0 15000.0 39000.0 295
I don't know if it's possible, but that's what i was asked to do
A:
Your data files look very close to configuration files. You can use configparser to generate a dictionary from each file:
from pathlib import Path
from configparser import ConfigParser
data = []
for file in Path("data").glob("*.txt"):
parser = ConfigParser()
# INI file requires a section header. Yours don't have one.
# So let's give it one called DEFAULT
parser.read_string("[DEFAULT]\n" + file.read_text())
data.append(dict(parser.items("DEFAULT")))
df = pd.DataFrame(data)
A:
welcome to Stackoverflow! :)
If your txt files have their content like you just showed, you could read them in using pandas as a CSV file.
The pandas.read_csv function has multiple things that will help you here:
It outputs a dataframe, which is the format you would like to end up with
Has a comment input argument, with which you can define lines that are to be ignored
You can use the = sign as a separator, which will make you able to split up your data in the wanted sections
Now, let's try to read one of your files using the read_csv function:
import pandas as pd
df = pd.read_csv(file, comment='#', sep='=', header=None)
df
nom Tondeuse
0 hauteur 0.5
1 masse 20.0
2 prix 110.0
3 impulsion specifique 80.0
We're not completely there yet. We want to remove that index column that gives no info, and we want to transpose the dataframe (rows <-> columns) to be able to concatenate all dataframes together. Let's do it!
import pandas as pd
df = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T
df
0 nom hauteur masse prix impulsion specifique
1 Tondeuse 0.5 20.0 110.00 80
That's looking way better! Putting index_col=0 makes the lefternmost column be the index column, and the .T at the end transposes your dataframe. Now we just need to put this inside of a loop and make a complete script out of it!
import pandas as pd
import glob
import os
files = glob.glob(os.path.join(path, '*.csv'))
all_dfs = []
for file in files:
current_df = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T
all_dfs.append(current_df)
total_df = pd.concat(all_dfs)
total_df
0 nom hauteur masse prix impulsion specifique
1 La Puissance 12.0 15000.0 39000.00 295
1 Civic VTEC 2.0 3000.0 2968.00 205
1 VelociRAPTOR 4.0 2000.0 6000.00 250
1 Tondeuse 0.5 20.0 110.00 80
Notice that you still have that lefternmost column with the index number, I did not clean it out because I wasn't sure of what you wanted there.
Also, importantly, you need to be aware that if there is a slight difference in the names of the columns in your files (e.g. impulsion specifique vs impulsion spécifique) this will bring errors. You will need to create error handling procedures for these. Or maybe enforcing a certain schema, but that is out of the scope of this question.
I hope this helps!
|
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 par le Poly Propulsion Lab (PPL)
nom=Civic VTEC
# Propriétés générales
hauteur=2.0
masse=3000.0
prix=2968.00
# Propriétés du moteur
impulsion specifique=205
and
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=VelociRAPTOR
# Propriétés générales
hauteur=4.0
masse=2000.0
prix=6000.00
# Propriétés du moteur
impulsion specifique=250
and
# Moteur conçu par le Poly Propulsion Lab (PPL)
nom=La Puissance
# Propriétés générales
hauteur=12.0
masse=15000.0
prix=39000.00
# Propriétés du moteur
impulsion specifique=295
That's the result I need to have:
nom hauteur masse prix impulsion specifique
0 Tondeuse 0.5 20.0 110.0 80
1 Civic VTEC 2.0 3000.0 2968.0 205
2 VelociRAPTOR 4.0 2000.0 6000.0 250
3 La Puissance 12.0 15000.0 39000.0 295
I don't know if it's possible, but that's what i was asked to do
|
[
"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. Yours don't have one.\n # So let's give it one called DEFAULT\n parser.read_string(\"[DEFAULT]\\n\" + file.read_text())\n data.append(dict(parser.items(\"DEFAULT\")))\n\ndf = pd.DataFrame(data)\n\n",
"welcome to Stackoverflow! :)\nIf your txt files have their content like you just showed, you could read them in using pandas as a CSV file.\nThe pandas.read_csv function has multiple things that will help you here:\n\nIt outputs a dataframe, which is the format you would like to end up with\nHas a comment input argument, with which you can define lines that are to be ignored\nYou can use the = sign as a separator, which will make you able to split up your data in the wanted sections\n\nNow, let's try to read one of your files using the read_csv function:\nimport pandas as pd\ndf = pd.read_csv(file, comment='#', sep='=', header=None)\ndf\n nom Tondeuse \n0 hauteur 0.5 \n1 masse 20.0 \n2 prix 110.0 \n3 impulsion specifique 80.0\n\nWe're not completely there yet. We want to remove that index column that gives no info, and we want to transpose the dataframe (rows <-> columns) to be able to concatenate all dataframes together. Let's do it!\nimport pandas as pd\ndf = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T\ndf\n\n0 nom hauteur masse prix impulsion specifique \n1 Tondeuse 0.5 20.0 110.00 80\n\nThat's looking way better! Putting index_col=0 makes the lefternmost column be the index column, and the .T at the end transposes your dataframe. Now we just need to put this inside of a loop and make a complete script out of it!\nimport pandas as pd\nimport glob\nimport os\n\nfiles = glob.glob(os.path.join(path, '*.csv'))\n\nall_dfs = []\nfor file in files:\n current_df = pd.read_csv(file, comment='#', sep='=', header=None, index_col=0).T\n all_dfs.append(current_df)\n\ntotal_df = pd.concat(all_dfs)\ntotal_df\n\n0 nom hauteur masse prix impulsion specifique \n1 La Puissance 12.0 15000.0 39000.00 295 \n1 Civic VTEC 2.0 3000.0 2968.00 205 \n1 VelociRAPTOR 4.0 2000.0 6000.00 250 \n1 Tondeuse 0.5 20.0 110.00 80\n\nNotice that you still have that lefternmost column with the index number, I did not clean it out because I wasn't sure of what you wanted there.\nAlso, importantly, you need to be aware that if there is a slight difference in the names of the columns in your files (e.g. impulsion specifique vs impulsion spécifique) this will bring errors. You will need to create error handling procedures for these. Or maybe enforcing a certain schema, but that is out of the scope of this question.\nI hope this helps!\n"
] |
[
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 23,14:00,Nov 23,15:00,Nov 23,16:00,Nov 23,17:00,Nov 23,18:00,Nov 23,19:00,Nov 23,20:00,Nov 23,21:00,Nov 23,22:00,Nov 23,23:00,Nov 24,00:00,Nov 24,01:00,Nov 24,02:00,Nov 24,03:00,Nov 24,04:00,Nov 24,05:00,Nov 24,06:00,Nov 24,07:00,Nov 24,08:00,Nov 24,09:00,Nov 24,10:00,Nov 24,11:00,Nov 24,12:00,Nov 24,13:00,Nov 24,14:00,Nov 24,15:00,Nov 24,16:00,Nov 24,17:00,Nov 24,18:00,Nov 24,19:00,Nov 24,20:00,Nov 24,21:00,Nov 24,22:00,Nov 24,23:00,Nov 25,00:00,Nov 25,01:00,Nov 25,02:00,Nov 25,03:00,Nov 25,04:00,Nov 25,05:00,Nov 25,06:00,Nov 25,07:00,Nov 25,08:00,Nov 25,09:00,2 - Count.AutoSlam.OAK4.3. [Weekly Avg: 0.56] 0.0 0.56 2.38 0.0 2.27 0.0 0.0 0.16 0.30 0.25 1.07 1.79 2.38 0.0 0.98 0.0 0.0 0.0 0.0 0.41 0.47 0.60,7 - Count.AutoSlam.OAK4.18 [Weekly Avg: 0.29] 0.0 0.29 2.34 0.0 0.0 0.0 0.0 0.0 0.0 2.34 0.0,5 - Count.AutoSlam.OAK4.13 [Weekly Avg: 0.34] 0.0 0.34 2.08 0.83 0.30 0.32 0.19 0.26 0.47 0.36 0.0 0.22 0.11 0.36 0.65 0.41 0.52 0.85 0.88 1.28 0.0 0.0 1.19 0.0 0.0 0.0 0.0 0.0 2.08 0.0 0.0 0.45 0.79 0.32 0.0 0.0 0.0 0.0 0.0 0.35 0.0 0.15,1 - Count.AutoSlam.OAK4.6. [Weekly Avg: 0.59] 0.0 0.59 1.79 0.0 0.34 0.11 0.38 0.24 0.19 0.15 0.42 0.69 0.56 0.26 1.26 0.71 1.79 1.51 0.82 1.10 1.40 0.57 0.0 0.85 0.34 0.0 0.15 0.29 0.86 0.35 0.39 0.78 1.09 1.35 0.68 0.70 1.02 1.66 1.15 0.31 0.0 0.0 0.0 0.077 0.13,11 - Count.AutoSlam.OAK4.19 [Weekly Avg: 0.23]']
A:
You could try using a regex to get matching groups and then just get the groups, e.g.
/Count\.AutoSlam\.OAK4\.(?P<autoslam>\d+) \[Weekly Avg: (?P<weekly_avrg>\d\.\d{2})\]/
See Example on Regex101.
Now, you can capture the data in python with:
import re
pattern = re.compile(r"Count\.AutoSlam\.OAK4\.(?P<autoslam>\d+) \[Weekly Avg: (?P<weekly_avrg>\d\.\d{2})\]")
# find all matches to groups
for match in pattern.finditer(string_list[0]):
print(match.group('autoslam'))
print(match.group('weekly_avrg'))
Find details on capturing groups for instance on pynative.com. If your list contains multiple strings like that you either need to merge (join) them or process them individually...
|
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:00,Nov 23,19:00,Nov 23,20:00,Nov 23,21:00,Nov 23,22:00,Nov 23,23:00,Nov 24,00:00,Nov 24,01:00,Nov 24,02:00,Nov 24,03:00,Nov 24,04:00,Nov 24,05:00,Nov 24,06:00,Nov 24,07:00,Nov 24,08:00,Nov 24,09:00,Nov 24,10:00,Nov 24,11:00,Nov 24,12:00,Nov 24,13:00,Nov 24,14:00,Nov 24,15:00,Nov 24,16:00,Nov 24,17:00,Nov 24,18:00,Nov 24,19:00,Nov 24,20:00,Nov 24,21:00,Nov 24,22:00,Nov 24,23:00,Nov 25,00:00,Nov 25,01:00,Nov 25,02:00,Nov 25,03:00,Nov 25,04:00,Nov 25,05:00,Nov 25,06:00,Nov 25,07:00,Nov 25,08:00,Nov 25,09:00,2 - Count.AutoSlam.OAK4.3. [Weekly Avg: 0.56] 0.0 0.56 2.38 0.0 2.27 0.0 0.0 0.16 0.30 0.25 1.07 1.79 2.38 0.0 0.98 0.0 0.0 0.0 0.0 0.41 0.47 0.60,7 - Count.AutoSlam.OAK4.18 [Weekly Avg: 0.29] 0.0 0.29 2.34 0.0 0.0 0.0 0.0 0.0 0.0 2.34 0.0,5 - Count.AutoSlam.OAK4.13 [Weekly Avg: 0.34] 0.0 0.34 2.08 0.83 0.30 0.32 0.19 0.26 0.47 0.36 0.0 0.22 0.11 0.36 0.65 0.41 0.52 0.85 0.88 1.28 0.0 0.0 1.19 0.0 0.0 0.0 0.0 0.0 2.08 0.0 0.0 0.45 0.79 0.32 0.0 0.0 0.0 0.0 0.0 0.35 0.0 0.15,1 - Count.AutoSlam.OAK4.6. [Weekly Avg: 0.59] 0.0 0.59 1.79 0.0 0.34 0.11 0.38 0.24 0.19 0.15 0.42 0.69 0.56 0.26 1.26 0.71 1.79 1.51 0.82 1.10 1.40 0.57 0.0 0.85 0.34 0.0 0.15 0.29 0.86 0.35 0.39 0.78 1.09 1.35 0.68 0.70 1.02 1.66 1.15 0.31 0.0 0.0 0.0 0.077 0.13,11 - Count.AutoSlam.OAK4.19 [Weekly Avg: 0.23]']
|
[
"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\\.OAK4\\.(?P<autoslam>\\d+) \\[Weekly Avg: (?P<weekly_avrg>\\d\\.\\d{2})\\]\")\n\n# find all matches to groups\nfor match in pattern.finditer(string_list[0]):\n print(match.group('autoslam'))\n print(match.group('weekly_avrg'))\n\n\nFind details on capturing groups for instance on pynative.com. If your list contains multiple strings like that you either need to merge (join) them or process them individually...\n"
] |
[
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 able to save the connection information in it.
I attach a part of my code and the libraries :
from tkinter import *
from tkinter import ttk, messagebox
from tkcalendar import *
import pymysql
import pymysql.cursors
import os
con = pymysql.connect(host="localhost",port=3306, user="root", password="", database="database")
cur= con.cursor()
con.execute("select * from compte where var=%s", self.var.get())
row = cur.fetchone()
con.comit()
con.close
A:
I think it should be cur.execute() not con.execute().
Note: Apart from that you have a couple of typos on commit() and close(), See Ref
from tkinter import *
from tkinter import ttk, messagebox
from tkcalendar import *
import pymysql
import pymysql.cursors
import os
con = pymysql.connect(host="localhost",port=3306, user="root", password="", database="database")
cur= con.cursor()
cur.execute("select * from compte where var=%s", self.var.get())
row = cur.fetchone()
con.commit()
con.close()
|
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 part of my code and the libraries :
from tkinter import *
from tkinter import ttk, messagebox
from tkcalendar import *
import pymysql
import pymysql.cursors
import os
con = pymysql.connect(host="localhost",port=3306, user="root", password="", database="database")
cur= con.cursor()
con.execute("select * from compte where var=%s", self.var.get())
row = cur.fetchone()
con.comit()
con.close
|
[
"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=\"localhost\",port=3306, user=\"root\", password=\"\", database=\"database\")\ncur= con.cursor()\ncur.execute(\"select * from compte where var=%s\", self.var.get())\nrow = cur.fetchone() \ncon.commit()\ncon.close()\n\n"
] |
[
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 frozen lake using 100 steps (for each game). If the agent correctly passes the lake, this is considered a victory, and so 10,000 games (iterations).
I got 7914 winning games - this is the correct answer.
And the next question is:
Complete the following code so that as a result of training the model, you can find out the number of wins and the number of the game (game) in which the agent won the fifth win in a row for the first time.
Here is my code:
for game in tqdm(range(total_games)):
//BODY OF CYCLE
success += reward # COUNTS WINNING GAMES
I need a simple algorithm that will select the first five wins in a row and put it in a variable. Something like this, but it's of course wrong:
if success==5:
game5Success = game
A:
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:
for game in tqdm(range(total_games)):
//BODY OF CYCLE
success += reward # COUNTS WINNING GAMES
wins_in_a_row = wins_in_a_row + reward if reward else 0 # COUNTS WINS IN A ROW
And then you can get your fifth game in the same way:
if wins_in_a_row == 5:
game5Success = game
A:
Since I don't have more information I created an own little example. You should get the idea.
Create a seperate counter, which also adds 1 when the game is one. If the game isn't won, the counter resets to 0.
# [random.choice([1,0]) for i in range(25)]
# resulted in this:
lst = [0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1]
counter = 0
success = 0
only_first = True
for idx, num in enumerate(lst):
if num == 1: # equivalent to win this game
success += 1 # or reward, but I guess it is just plus 1
counter += 1
else:
counter = 0 # reset Counter if game isn't a win
if counter == 3 and only_first: # check for the number of consecutive wins you want to know and if it is the first time
print(f"First 3 successively won games at game No: {idx}")
only_first = False
Output:
First 3 successively won games at game No: 6
|
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 correctly passes the lake, this is considered a victory, and so 10,000 games (iterations).
I got 7914 winning games - this is the correct answer.
And the next question is:
Complete the following code so that as a result of training the model, you can find out the number of wins and the number of the game (game) in which the agent won the fifth win in a row for the first time.
Here is my code:
for game in tqdm(range(total_games)):
//BODY OF CYCLE
success += reward # COUNTS WINNING GAMES
I need a simple algorithm that will select the first five wins in a row and put it in a variable. Something like this, but it's of course wrong:
if success==5:
game5Success = game
|
[
"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 # COUNTS WINS IN A ROW\n\nAnd then you can get your fifth game in the same way:\nif wins_in_a_row == 5: \n game5Success = game\n\n",
"Since I don't have more information I created an own little example. You should get the idea.\nCreate a seperate counter, which also adds 1 when the game is one. If the game isn't won, the counter resets to 0.\n# [random.choice([1,0]) for i in range(25)] \n# resulted in this:\nlst = [0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1]\n\ncounter = 0\nsuccess = 0\nonly_first = True\n\nfor idx, num in enumerate(lst):\n if num == 1: # equivalent to win this game\n success += 1 # or reward, but I guess it is just plus 1\n counter += 1\n else: \n counter = 0 # reset Counter if game isn't a win\n \n if counter == 3 and only_first: # check for the number of consecutive wins you want to know and if it is the first time\n print(f\"First 3 successively won games at game No: {idx}\")\n only_first = False\n\nOutput:\nFirst 3 successively won games at game No: 6\n\n"
] |
[
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 other mac GUI apps.
Look at this screenshot for instance:
Notice the gray backgrounds on widgets.
Here's the code for this:
import datetime
import gettext
import sys
import time
import os
import tkinter
import tkinter.ttk as ttk
from tkinter.filedialog import askopenfilename
from tkinter import *
from tkinter import filedialog
# All translations provided for illustrative purposes only.
# english
_ = lambda s: s
class MainFrame(ttk.Frame):
"Main area of user interface content."
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
self.parent = parent
paddings = {'padx': 6, 'pady': 6}
self.download_location = '/'.join(os.getcwd().split('/')[:3]) + '/Downloads'
ttk.Label(parent, text="Youtube Url").pack(side='top', anchor='w', **paddings)
self.entry = ttk.Entry(parent, )
self.entry.pack(side='top', fill='x', **paddings)
# todo delete this line
self.entry.insert(0, 'https://www.youtube.com/watch?v=nXait2wHOQc')
self.button = ttk.Button(parent, text="Download", command=self.do_download)
self.button.pack(side='top', **paddings, anchor='w')
# style = ttk.Style()
# style.configure('TButton', foreground="red")
# self.button.config(style='Alarm.TButton')
self.location_button = ttk.Button(parent, text="Location", command=self.browse_button)
self.location_button.pack(side='top', **paddings, anchor='w')
self.statusStringVar = StringVar()
self.statusStringVar.set('status here')
self.status = ttk.Label(parent, textvariable=self.statusStringVar, text='status', )
self.status.pack(side='top', anchor='w', fill='x', **paddings)
self.locStringVar = StringVar()
self.locStringVar.set(f"Location: {self.download_location}")
self.locationLabel = ttk.Label(parent, textvariable=self.locStringVar, )
self.locationLabel.pack(side='top', anchor='w', fill='x', **paddings)
self.mp3_check_value = StringVar()
self.mp3_checkbox = ttk.Checkbutton(parent, text='Convert to MP3')
self.mp3_checkbox.config(variable=self.mp3_check_value, onvalue='yes', offvalue='no')
self.mp3_check_value.set('yes')
self.mp3_checkbox.pack(side='top', anchor='w', **paddings)
self.progressIntVar = IntVar()
self.progressIntVar.set(0)
self.mpb = ttk.Progressbar(parent, orient="horizontal", length=200, mode="determinate")
self.mpb['variable'] = self.progressIntVar
self.mpb.pack(side='top', anchor='w', fill='x', **paddings)
self.mpb["maximum"] = 100
# self.mpb["value"] = 0
def do_download(self):
pass
def progress_hook(self, d):
pass
def browse_button(self):
filename = filedialog.askdirectory()
print(filename)
self.download_location = filename
self.locStringVar.set(f"Location: {self.download_location}")
class Application(tkinter.Tk):
"Create top-level Tkinter widget containing all other widgets."
def __init__(self):
tkinter.Tk.__init__(self)
self.wm_title('Tkinter YDL')
self.wm_geometry('640x480')
self.mainframe = MainFrame(self)
self.mainframe.pack(side='right', fill='y')
if __name__ == '__main__':
APPLICATION_GUI = Application()
APPLICATION_GUI.mainloop()
Am I missing something here? Please help.
A:
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.
ttk.Label(self, text="Youtube Url").pack(side='top', anchor='w', **paddings)
|
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:
Notice the gray backgrounds on widgets.
Here's the code for this:
import datetime
import gettext
import sys
import time
import os
import tkinter
import tkinter.ttk as ttk
from tkinter.filedialog import askopenfilename
from tkinter import *
from tkinter import filedialog
# All translations provided for illustrative purposes only.
# english
_ = lambda s: s
class MainFrame(ttk.Frame):
"Main area of user interface content."
def __init__(self, parent):
ttk.Frame.__init__(self, parent)
self.parent = parent
paddings = {'padx': 6, 'pady': 6}
self.download_location = '/'.join(os.getcwd().split('/')[:3]) + '/Downloads'
ttk.Label(parent, text="Youtube Url").pack(side='top', anchor='w', **paddings)
self.entry = ttk.Entry(parent, )
self.entry.pack(side='top', fill='x', **paddings)
# todo delete this line
self.entry.insert(0, 'https://www.youtube.com/watch?v=nXait2wHOQc')
self.button = ttk.Button(parent, text="Download", command=self.do_download)
self.button.pack(side='top', **paddings, anchor='w')
# style = ttk.Style()
# style.configure('TButton', foreground="red")
# self.button.config(style='Alarm.TButton')
self.location_button = ttk.Button(parent, text="Location", command=self.browse_button)
self.location_button.pack(side='top', **paddings, anchor='w')
self.statusStringVar = StringVar()
self.statusStringVar.set('status here')
self.status = ttk.Label(parent, textvariable=self.statusStringVar, text='status', )
self.status.pack(side='top', anchor='w', fill='x', **paddings)
self.locStringVar = StringVar()
self.locStringVar.set(f"Location: {self.download_location}")
self.locationLabel = ttk.Label(parent, textvariable=self.locStringVar, )
self.locationLabel.pack(side='top', anchor='w', fill='x', **paddings)
self.mp3_check_value = StringVar()
self.mp3_checkbox = ttk.Checkbutton(parent, text='Convert to MP3')
self.mp3_checkbox.config(variable=self.mp3_check_value, onvalue='yes', offvalue='no')
self.mp3_check_value.set('yes')
self.mp3_checkbox.pack(side='top', anchor='w', **paddings)
self.progressIntVar = IntVar()
self.progressIntVar.set(0)
self.mpb = ttk.Progressbar(parent, orient="horizontal", length=200, mode="determinate")
self.mpb['variable'] = self.progressIntVar
self.mpb.pack(side='top', anchor='w', fill='x', **paddings)
self.mpb["maximum"] = 100
# self.mpb["value"] = 0
def do_download(self):
pass
def progress_hook(self, d):
pass
def browse_button(self):
filename = filedialog.askdirectory()
print(filename)
self.download_location = filename
self.locStringVar.set(f"Location: {self.download_location}")
class Application(tkinter.Tk):
"Create top-level Tkinter widget containing all other widgets."
def __init__(self):
tkinter.Tk.__init__(self)
self.wm_title('Tkinter YDL')
self.wm_geometry('640x480')
self.mainframe = MainFrame(self)
self.mainframe.pack(side='right', fill='y')
if __name__ == '__main__':
APPLICATION_GUI = Application()
APPLICATION_GUI.mainloop()
Am I missing something here? Please help.
|
[
"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 on mac\n",
"I just saw this theme posted on reddit:\nhttps://github.com/rdbende/Sun-Valley-ttk-theme\nIt's based on a Microsoft visual style but it definitely looks better than the default ttk theme.\nAlso scroll to the bottom for two other themes by the same author.\n"
] |
[
-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'))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
This is my code:
import discord
import os
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
I dont have any extra files with the code. This is the only file in the project.
How would i fix the error? Thanks!
I have looked on other peoples posts but nothing has helped so far.
A:
Token Value Must Be A String
So , If You Are Using .env File For Token
Use Something Like :
import os
from dotenv import load_dotenv # pip install dotenv
load_dotenv() # Load Every .env file in the application path
.... # Stuff
bot.run(os.getenv("BOTTOKEN"))
|
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\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 577, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
This is my code:
import discord
import os
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv('TOKEN'))
I dont have any extra files with the code. This is the only file in the project.
How would i fix the error? Thanks!
I have looked on other peoples posts but nothing has helped so far.
|
[
"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 the following python code:
# compose a LaTex file
content = r'''\documentclass{article}
\begin{document}
\usepackage{graphicx}
\graphicspath{./}
\includegraphics{Image.jpg}
\textbf{\huge DSC 501\\}
\textit{Programming for Data Science\\}
\vspace{1cm}
\textbf{Andrew Coleman\\}
19 November 2022\\
\textbf{\Large Southern Connecticut State University \\}
\section{IMDb movie analysis}
Here we are...\\
\end{document}
# specify the file name without an extension so we can reuse it
from datetime import datetime
outfile = 'scsu-dsc501-pdflatex-demo'
timestamped_outfile = data_path + outfile + '_' + datetime.now().strftime("%Y-%m-%d_at_%H-%M-%S")
# store a LaTex file
with open(timestamped_outfile+'.tex','w') as f:
f.write(content)
When this is converted to a pdf file, instead of the image (Image.jpg, which is in the same directory as the .tex file), the pdf file contains "graphicx ./Image.jpg"
How do I get the image itself to appear in the pdf?
This is running via Colab on a Mac laptop.
A:
Packages must not be loaded after \begin{document}.
Some other comments:
Adding the current directory to the graphic path is also not necessary, the current directory is searched by default.
you shouldn't abuse \\ for line breaks, just leave an empty line to start a new paragraph
if you make font size changes and switch back to normal font before the end of the paragraph, your line spacing will be wrong.
\documentclass{article}
\usepackage{graphicx}
%\graphicspath{./}
\begin{document}
\includegraphics{example-image-duck}
{\huge\textbf{DSC 501}\par}
\textit{Programming for Data Science}
\vspace{1cm}
\textbf{Andrew Coleman}
19 November 2022
{\Large\textbf{Southern Connecticut State University}\par}
\section{IMDb movie analysis}
Here we are...
\end{document}
|
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 file
content = r'''\documentclass{article}
\begin{document}
\usepackage{graphicx}
\graphicspath{./}
\includegraphics{Image.jpg}
\textbf{\huge DSC 501\\}
\textit{Programming for Data Science\\}
\vspace{1cm}
\textbf{Andrew Coleman\\}
19 November 2022\\
\textbf{\Large Southern Connecticut State University \\}
\section{IMDb movie analysis}
Here we are...\\
\end{document}
# specify the file name without an extension so we can reuse it
from datetime import datetime
outfile = 'scsu-dsc501-pdflatex-demo'
timestamped_outfile = data_path + outfile + '_' + datetime.now().strftime("%Y-%m-%d_at_%H-%M-%S")
# store a LaTex file
with open(timestamped_outfile+'.tex','w') as f:
f.write(content)
When this is converted to a pdf file, instead of the image (Image.jpg, which is in the same directory as the .tex file), the pdf file contains "graphicx ./Image.jpg"
How do I get the image itself to appear in the pdf?
This is running via Colab on a Mac laptop.
|
[
"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 changes and switch back to normal font before the end of the paragraph, your line spacing will be wrong.\n\n\n\\documentclass{article}\n\\usepackage{graphicx}\n%\\graphicspath{./}\n\\begin{document}\n\\includegraphics{example-image-duck}\n\n{\\huge\\textbf{DSC 501}\\par}\n\\textit{Programming for Data Science}\n\n\\vspace{1cm}\n\\textbf{Andrew Coleman}\n\n19 November 2022\n\n{\\Large\\textbf{Southern Connecticut State University}\\par}\n\\section{IMDb movie analysis}\nHere we are...\n\n\\end{document}\n\n\n"
] |
[
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_Environment_name}/venv/bin/python, error = 2, "No such file or directory"
It looks like Python is not installed in the folder {Virtual_Environment_name}/venv/bin/python.
How can I install Python at this location? Are my assumptions correct?
A:
At the right bottom corner, there's an interpreter selection button. Press it. Now you've got two options:
Interpreter settings
Add interpreter...
Choose 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. You may choose to edit your interpreter's path here, or remove the interpreter and make it anew.
|
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 like Python is not installed in the folder {Virtual_Environment_name}/venv/bin/python.
How can I install Python at this location? Are my assumptions correct?
|
[
"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. You may choose to edit your interpreter's path here, or remove the interpreter and make it anew.\n\n"
] |
[
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.crop((0,0,int(w/2),h))
im.paste(im, (int(w/2),0,w,h))
im.save('test.png')
A:
How to rotate the x direction of an image
You 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.
from PIL import Image
output_image = 'test.png'
im = Image.open("input.png")
w, h = im.size
left_x = int(w / 2) - 2
right_x = w - left_x
left_portion = im.crop((0, 0, left_x, h))
right_portion = im.crop((right_x, 0, w, h))
im.paste(right_portion, (0, 0, left_x, h))
im.paste(left_portion, (right_x, 0, w, h))
im.save(output_image)
print(f"saved image {output_image}")
input.png:
output.png:
Explanation:
I used left_x = int(w / 2) - 2 as to keep the middle border line in the middle. You may change it as it fits to your case.
References:
Documentation on pillow module
A:
Actually, you can use ImageChops.offset to do that very simply:
from PIL import Image, ImageChops
# Open image
im = Image.open('...')
# Roll image by half its width in x-direction, and not at all in y-direction
ImageChops.offset(im, xoffset=int(im.width/2), yoffset=0).save('result.png')
Other libraries/packages, such as ImageMagick, refer to this operation as "rolling" an image, because the pixels that roll off one edge roll into the opposite edge.
Here's a little animation showing what it is doing:
|
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.save('test.png')
|
[
"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\nleft_x = int(w / 2) - 2\nright_x = w - left_x\nleft_portion = im.crop((0, 0, left_x, h))\nright_portion = im.crop((right_x, 0, w, h))\nim.paste(right_portion, (0, 0, left_x, h))\nim.paste(left_portion, (right_x, 0, w, h))\nim.save(output_image)\nprint(f\"saved image {output_image}\")\n\ninput.png:\n\noutput.png:\n\nExplanation:\n\nI used left_x = int(w / 2) - 2 as to keep the middle border line in the middle. You may change it as it fits to your case.\n\nReferences:\n\nDocumentation on pillow module\n\n",
"Actually, you can use ImageChops.offset to do that very simply:\nfrom PIL import Image, ImageChops\n\n# Open image\nim = Image.open('...')\n\n# Roll image by half its width in x-direction, and not at all in y-direction\nImageChops.offset(im, xoffset=int(im.width/2), yoffset=0).save('result.png')\n\nOther libraries/packages, such as ImageMagick, refer to this operation as \"rolling\" an image, because the pixels that roll off one edge roll into the opposite edge.\nHere's a little animation showing what it is doing:\n\n"
] |
[
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 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/2 09:43:02.49
6 2014/9/2 10:49:16.115
7 2014/9/2 10:58:46.39
8 2014/9/2 11:46:18.5
9 2014/9/2 12:03:43.0
10 2014/9/2 12:56:22.0
11 2014/9/2 13:13:01.0
12 2014/9/2 14:42:22.39
13 2014/9/2 14:50:00.74
14 2014/9/3 08:30:00.0
15 2014/9/3 08:30:11.57
16 2014/9/3 08:39:02.18
17 2014/9/3 08:44:31.74
18 2014/9/3 08:45:16.105
19 2014/9/3 08:47:52.57
concatenating date + time column
df['datetime'] = df.Date + str(' ') + df.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/2 09:43:02.49
6 2014/9/2 10:49:16.115
7 2014/9/2 10:58:46.39
8 2014/9/2 11:46:18.5
9 2014/9/2 12:03:43.0
Trying to parse the string to datetime object:
df['datetime'] = df['datetime'].apply(lambda x: datetime.strptime(x, '%Y/%m/%d %H:%M:%S.f%'))
fails:
ValueError: stray % in format '%Y/%m/%d %H:%M:%S.f%'
What is wrong with that and how to solve it?
A:
The format code for microseconds is %f and not f% as per the documentation.
Try this :
df['datetime'] = df['datetime'].apply(lambda x: datetime.strptime(x, '%Y/%m/%d %H:%M:%S.%f'))
Or, in one shot :
(
pd.read_csv("test.csv")
.astype(str).agg(" ".join, axis=1)
.to_frame("datetime")
.apply(lambda _: pd.to_datetime(_, format= '%Y/%m/%d %H:%M:%S.%f'))
)
# Output :
datetime
0 2014-09-02 08:30:00.000
1 2014-09-02 08:37:39.210
2 2014-09-02 08:39:41.200
3 2014-09-02 08:41:23.900
4 2014-09-02 09:13:01.100
.. ...
15 2014-09-03 08:30:11.570
16 2014-09-03 08:39:02.180
17 2014-09-03 08:44:31.740
18 2014-09-03 08:45:16.105
19 2014-09-03 08:47:52.570
[20 rows x 1 columns]
#dtypes
datetime datetime64[ns]
dtype: object
|
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/2 09:43:02.49
6 2014/9/2 10:49:16.115
7 2014/9/2 10:58:46.39
8 2014/9/2 11:46:18.5
9 2014/9/2 12:03:43.0
10 2014/9/2 12:56:22.0
11 2014/9/2 13:13:01.0
12 2014/9/2 14:42:22.39
13 2014/9/2 14:50:00.74
14 2014/9/3 08:30:00.0
15 2014/9/3 08:30:11.57
16 2014/9/3 08:39:02.18
17 2014/9/3 08:44:31.74
18 2014/9/3 08:45:16.105
19 2014/9/3 08:47:52.57
concatenating date + time column
df['datetime'] = df.Date + str(' ') + df.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/2 09:43:02.49
6 2014/9/2 10:49:16.115
7 2014/9/2 10:58:46.39
8 2014/9/2 11:46:18.5
9 2014/9/2 12:03:43.0
Trying to parse the string to datetime object:
df['datetime'] = df['datetime'].apply(lambda x: datetime.strptime(x, '%Y/%m/%d %H:%M:%S.f%'))
fails:
ValueError: stray % in format '%Y/%m/%d %H:%M:%S.f%'
What is wrong with that and how to solve it?
|
[
"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\")\n .apply(lambda _: pd.to_datetime(_, format= '%Y/%m/%d %H:%M:%S.%f'))\n)\n\n# Output :\n datetime\n0 2014-09-02 08:30:00.000\n1 2014-09-02 08:37:39.210\n2 2014-09-02 08:39:41.200\n3 2014-09-02 08:41:23.900\n4 2014-09-02 09:13:01.100\n.. ...\n15 2014-09-03 08:30:11.570\n16 2014-09-03 08:39:02.180\n17 2014-09-03 08:44:31.740\n18 2014-09-03 08:45:16.105\n19 2014-09-03 08:47:52.570\n\n[20 rows x 1 columns]\n\n#dtypes\ndatetime datetime64[ns]\ndtype: object\n\n"
] |
[
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(url).text
pg = fromstring(raw)
v=[]
for result in pg.cssselect(".r a"):
url = result.get("href")
if url.startswith("/url?"):
url = parse_qs(urlparse(url).query)['q']
print url[0]
that extract urls related with the search, how can I extract the description that appears under the url?
A:
You can scrape Google Search Description Website using BeautifulSoup web scraping library.
To 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 selector ".d6cvqb a[id=pnnext]":
if soup.select_one('.d6cvqb a[id=pnnext]'):
params["start"] += 10
else:
break
You can use CSS selectors search to find all the information you need (description, title, etc.) which are easy to identify on the page using a SelectorGadget Chrome extension (not always work perfectly if the website is rendered via JavaScript).
Make sure you're using request headers user-agent to act as a "real" user visit. Because default requests user-agent is python-requests and websites understand that it's most likely a script that sends a request. Check what's your user-agent.
Check code in online IDE.
from bs4 import BeautifulSoup
import requests, json, lxml
# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
params = {
"q": "gotham", # query
"hl": "en", # language
"gl": "us", # country of the search, US -> USA
"start": 0, # number page by default up to 0
#"num": 100 # parameter defines the maximum number of results to return.
}
# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
}
page_num = 0
website_data = []
while True:
page_num += 1
print(f"page: {page_num}")
html = requests.get("https://www.google.com/search", params=params, headers=headers, timeout=30)
soup = BeautifulSoup(html.text, 'lxml')
for result in soup.select(".tF2Cxc"):
website_name = result.select_one(".yuRUbf a")["href"]
try:
description = result.select_one(".lEBKkf").text
except:
description = None
website_data.append({
"website_name": website_name,
"description": description
})
if soup.select_one('.d6cvqb a[id=pnnext]'):
params["start"] += 10
else:
break
print(json.dumps(website_data, indent=2, ensure_ascii=False))
Example output:
[
{
"website_name": "https://www.imdb.com/title/tt3749900/",
"description": "The show follows Jim as he cracks strange cases whilst trying to help a young Bruce Wayne solve the mystery of his parents' murder. It seemed each week for a ..."
},
{
"website_name": "https://www.netflix.com/watch/80023082",
"description": "When the key witness in a homicide ends up dead while being held for questioning, Gordon suspects an inside job and seeks details from an old friend."
},
{
"website_name": "https://www.gothamknightsgame.com/",
"description": "Gotham Knights is an open-world, action RPG set in the most dynamic and interactive Gotham City yet. In either solo-play or with one other hero, ..."
},
# ...
]
Or you can also use Google Search Engine Results API from SerpApi. It's a paid API with the free plan.
The difference is that it will bypass blocks (including CAPTCHA) from Google, no need to create the parser and maintain it.
Code example:
from serpapi import GoogleSearch
from urllib.parse import urlsplit, parse_qsl
import json, os
params = {
"api_key": os.getenv("API_KEY"), # serpapi key
"engine": "google", # serpapi parser engine
"q": "gotham", # search query
"num": "100" # number of results per page (100 per page in this case)
# other search parameters: https://serpapi.com/search-api#api-parameters
}
search = GoogleSearch(params) # where data extraction happens
organic_results_data = []
page_num = 0
while True:
results = search.get_dict() # JSON -> Python dictionary
page_num += 1
for result in results["organic_results"]:
organic_results_data.append({
"title": result.get("title"),
"snippet": result.get("snippet")
})
if "next_link" in results.get("serpapi_pagination", []):
search.params_dict.update(dict(parse_qsl(urlsplit(results.get("serpapi_pagination").get("next_link")).query)))
else:
break
print(json.dumps(organic_results_data, indent=2, ensure_ascii=False))
Output:
[
{
"title": "Gotham (TV Series 2014–2019) - IMDb",
"snippet": "The show follows Jim as he cracks strange cases whilst trying to help a young Bruce Wayne solve the mystery of his parents' murder. It seemed each week for a ..."
},
{
"title": "Gotham (TV series) - Wikipedia",
"snippet": "Gotham is an American superhero crime drama television series developed by Bruno Heller, produced by Warner Bros. Television and based on characters from ..."
},
# ...
]
|
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 pg.cssselect(".r a"):
url = result.get("href")
if url.startswith("/url?"):
url = parse_qs(urlparse(url).query)['q']
print url[0]
that extract urls related with the search, how can I extract the description that appears under the url?
|
[
"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 selector \".d6cvqb a[id=pnnext]\":\nif soup.select_one('.d6cvqb a[id=pnnext]'):\n params[\"start\"] += 10\nelse:\n break\n\nYou can use CSS selectors search to find all the information you need (description, title, etc.) which are easy to identify on the page using a SelectorGadget Chrome extension (not always work perfectly if the website is rendered via JavaScript).\nMake sure you're using request headers user-agent to act as a \"real\" user visit. Because default requests user-agent is python-requests and websites understand that it's most likely a script that sends a request. Check what's your user-agent.\nCheck code in online IDE.\nfrom bs4 import BeautifulSoup\nimport requests, json, lxml\n\n# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls\nparams = {\n \"q\": \"gotham\", # query\n \"hl\": \"en\", # language\n \"gl\": \"us\", # country of the search, US -> USA\n \"start\": 0, # number page by default up to 0\n #\"num\": 100 # parameter defines the maximum number of results to return.\n}\n\n# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36\"\n}\n\npage_num = 0\n\nwebsite_data = []\n\nwhile True:\n page_num += 1\n print(f\"page: {page_num}\")\n \n html = requests.get(\"https://www.google.com/search\", params=params, headers=headers, timeout=30)\n soup = BeautifulSoup(html.text, 'lxml')\n \n for result in soup.select(\".tF2Cxc\"):\n website_name = result.select_one(\".yuRUbf a\")[\"href\"]\n try:\n description = result.select_one(\".lEBKkf\").text\n except:\n description = None\n \n website_data.append({\n \"website_name\": website_name,\n \"description\": description \n })\n \n if soup.select_one('.d6cvqb a[id=pnnext]'):\n params[\"start\"] += 10\n else:\n break\n\nprint(json.dumps(website_data, indent=2, ensure_ascii=False))\n\nExample output:\n[\n {\n \"website_name\": \"https://www.imdb.com/title/tt3749900/\",\n \"description\": \"The show follows Jim as he cracks strange cases whilst trying to help a young Bruce Wayne solve the mystery of his parents' murder. It seemed each week for a ...\"\n },\n {\n \"website_name\": \"https://www.netflix.com/watch/80023082\",\n \"description\": \"When the key witness in a homicide ends up dead while being held for questioning, Gordon suspects an inside job and seeks details from an old friend.\"\n },\n {\n \"website_name\": \"https://www.gothamknightsgame.com/\",\n \"description\": \"Gotham Knights is an open-world, action RPG set in the most dynamic and interactive Gotham City yet. In either solo-play or with one other hero, ...\"\n },\n # ...\n]\n\n\nOr you can also use Google Search Engine Results API from SerpApi. It's a paid API with the free plan.\nThe difference is that it will bypass blocks (including CAPTCHA) from Google, no need to create the parser and maintain it.\nCode example:\nfrom serpapi import GoogleSearch\nfrom urllib.parse import urlsplit, parse_qsl\nimport json, os\n\nparams = {\n \"api_key\": os.getenv(\"API_KEY\"), # serpapi key\n \"engine\": \"google\", # serpapi parser engine\n \"q\": \"gotham\", # search query\n \"num\": \"100\" # number of results per page (100 per page in this case)\n # other search parameters: https://serpapi.com/search-api#api-parameters\n}\n\nsearch = GoogleSearch(params) # where data extraction happens\n\norganic_results_data = []\npage_num = 0\n\nwhile True:\n results = search.get_dict() # JSON -> Python dictionary\n \n page_num += 1\n \n for result in results[\"organic_results\"]:\n organic_results_data.append({\n \"title\": result.get(\"title\"),\n \"snippet\": result.get(\"snippet\") \n })\n \n if \"next_link\" in results.get(\"serpapi_pagination\", []):\n search.params_dict.update(dict(parse_qsl(urlsplit(results.get(\"serpapi_pagination\").get(\"next_link\")).query)))\n else:\n break\n \nprint(json.dumps(organic_results_data, indent=2, ensure_ascii=False))\n\nOutput:\n[\n {\n \"title\": \"Gotham (TV Series 2014–2019) - IMDb\",\n \"snippet\": \"The show follows Jim as he cracks strange cases whilst trying to help a young Bruce Wayne solve the mystery of his parents' murder. It seemed each week for a ...\"\n },\n {\n \"title\": \"Gotham (TV series) - Wikipedia\",\n \"snippet\": \"Gotham is an American superhero crime drama television series developed by Bruno Heller, produced by Warner Bros. Television and based on characters from ...\"\n },\n # ...\n]\n\n"
] |
[
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 option2.get():
print("not allowed, select one dude")
else:
print("welcome dude")
option1.set(False)
option2.set(False)
root = Tk()
root.geometry("400x400")
option1 = BooleanVar(value=False)
R1 = Radiobutton(root, text="MALE", value=1, var=option1)
R1.pack()
option2 = BooleanVar(value=False)
R2 = Radiobutton(root, text="FEMALE", value=2, var=option2)
R2.pack()
b = Button(root, text="print", command=content)
b.pack(side="bottom")
root.mainloop()
A:
You must bind both radiobuttons to the same variable.
Besides, the variable will receive the value specified in the value keyword argument.
I suggest you do the following:
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
You can know what item is currently selected, by tracing the option variable, and by calling its get method.
For instance, the following will print either "male" or "female" whenever the corresponding radiobutton is checked.
def print_var(*_):
print(option.get())
root = Tk()
root.geometry("400x400")
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
R1.pack()
R2.pack()
option.trace('w', print_var)
root.mainloop()
A more complete example, according to your demand.
This script will display a window with two radiobuttons and a button.
When the button is clicked, a message is printed that depends upon whether an option was selected or not.
from tkinter import *
def validate():
value = option.get()
if value == "male":
print("Welcome dude")
elif value == "female":
print("Welcome gurl")
else:
print("An option must be selected")
root = Tk()
root.geometry("400x400")
option = StringVar()
R1 = Radiobutton(root, text="MALE", value="male", var=option)
R2 = Radiobutton(root, text="FEMALE", value="female", var=option)
button = Button(root, text="OK", command=validate)
R1.pack()
R2.pack()
button.pack()
root.mainloop()
As a side note, you should never import a module with a star, eg from tkinter import *.
In short, it pollutes the namespace. More on this post.
A:
I presume you are wanting to create one radio button with multiple values which only allows one selection? You would be better to populate an array and run a loop to fill the radio button. Perhaps something like this?
from tkinter import *
root = Tk()
root.geometry("400x400")
GENDERS = [
("Male", "M"),
("Female", "F"),
("Other", "O")
]
v = StringVar()
v.set("L") # initialize
for text, gender in GENDERS:
b = Radiobutton(root, text=text,
variable=v, value=gender)
b.pack(anchor=W)
root.mainloop()
A:
The easiest way to do it that i found is this -
you have to give them both the same variable so that compiler can know that the user can only choose one...
from tkinter import *
window = Tk()
window.geometry("100x100")
var = IntVar()
radio = Radiobutton(window, text="this", variable=var, value=1)
radio.pack()
radio2 = Radiobutton(window, text="or this", variable=var, value=2)
radio2.pack()
window.mainloop()
|
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 one dude")
else:
print("welcome dude")
option1.set(False)
option2.set(False)
root = Tk()
root.geometry("400x400")
option1 = BooleanVar(value=False)
R1 = Radiobutton(root, text="MALE", value=1, var=option1)
R1.pack()
option2 = BooleanVar(value=False)
R2 = Radiobutton(root, text="FEMALE", value=2, var=option2)
R2.pack()
b = Button(root, text="print", command=content)
b.pack(side="bottom")
root.mainloop()
|
[
"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=\"female\", var=option)\n\nYou can know what item is currently selected, by tracing the option variable, and by calling its get method.\nFor instance, the following will print either \"male\" or \"female\" whenever the corresponding radiobutton is checked.\ndef print_var(*_):\n print(option.get())\n\nroot = Tk()\nroot.geometry(\"400x400\")\n\noption = StringVar()\nR1 = Radiobutton(root, text=\"MALE\", value=\"male\", var=option)\nR2 = Radiobutton(root, text=\"FEMALE\", value=\"female\", var=option)\nR1.pack()\nR2.pack()\n\noption.trace('w', print_var)\n\nroot.mainloop()\n\nA more complete example, according to your demand.\nThis script will display a window with two radiobuttons and a button.\nWhen the button is clicked, a message is printed that depends upon whether an option was selected or not.\nfrom tkinter import *\n\ndef validate():\n value = option.get()\n if value == \"male\":\n print(\"Welcome dude\")\n elif value == \"female\":\n print(\"Welcome gurl\")\n else:\n print(\"An option must be selected\")\n\nroot = Tk()\nroot.geometry(\"400x400\")\n\noption = StringVar()\nR1 = Radiobutton(root, text=\"MALE\", value=\"male\", var=option)\nR2 = Radiobutton(root, text=\"FEMALE\", value=\"female\", var=option)\nbutton = Button(root, text=\"OK\", command=validate)\n\nR1.pack()\nR2.pack()\nbutton.pack()\n\nroot.mainloop()\n\n\nAs a side note, you should never import a module with a star, eg from tkinter import *.\nIn short, it pollutes the namespace. More on this post.\n",
"I presume you are wanting to create one radio button with multiple values which only allows one selection? You would be better to populate an array and run a loop to fill the radio button. Perhaps something like this?\nfrom tkinter import *\n\n\n\n\nroot = Tk()\nroot.geometry(\"400x400\")\n\nGENDERS = [\n (\"Male\", \"M\"),\n (\"Female\", \"F\"),\n (\"Other\", \"O\")\n]\n\nv = StringVar()\nv.set(\"L\") # initialize\n\nfor text, gender in GENDERS:\n b = Radiobutton(root, text=text,\n variable=v, value=gender)\n b.pack(anchor=W)\n\nroot.mainloop()\n\n",
"The easiest way to do it that i found is this -\nyou have to give them both the same variable so that compiler can know that the user can only choose one...\nfrom tkinter import *\nwindow = Tk()\nwindow.geometry(\"100x100\")\nvar = IntVar()\n\nradio = Radiobutton(window, text=\"this\", variable=var, value=1)\nradio.pack()\nradio2 = Radiobutton(window, text=\"or this\", variable=var, value=2)\nradio2.pack()\n\nwindow.mainloop()\n\n"
] |
[
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 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.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'name: {self.name}, age: {self.age}'
p1 = Person("John", 36)
print(p1) #name: John, age: 36
Personally, I prefer using dataclasses for classes that need a printable representation or a json structure.
from dataclasses import dataclass, asdict
@dataclass
class Person:
name: str
age : int
p1 = Person("John", 36)
print(p1) #Person(name='John', age=36)
print(asdict(p1)) #{"name":"John", "age":36}
|
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 def __init__(self, name, age):\n self.name = name\n self.age = age\n \n def __str__(self):\n return f'name: {self.name}, age: {self.age}'\n\np1 = Person(\"John\", 36)\n\nprint(p1) #name: John, age: 36\n\nPersonally, I prefer using dataclasses for classes that need a printable representation or a json structure.\nfrom dataclasses import dataclass, asdict\n\n@dataclass\nclass Person:\n name: str \n age : int\n\np1 = Person(\"John\", 36)\n\nprint(p1) #Person(name='John', age=36)\n\nprint(asdict(p1)) #{\"name\":\"John\", \"age\":36}\n\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 sleep() for some seconds.
The example code is running fine with Python 3.6.4rc1. But
the problem is that the GUI is freezed. When I press the first button and start the 10 asyncio-tasks I am not able to press the second button in the GUI until all tasks are done. The GUI should never freeze - that is my goal.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import messagebox
import asyncio
import random
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
def do_tasks():
""" Button-Event-Handler starting the asyncio part. """
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(do_urls())
finally:
loop.close()
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [
one_url(url)
for url in range(10)
]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
if __name__ == '__main__':
root = Tk()
buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
buttonT.pack()
buttonX = Button(master=root, text='Freezed???', command=do_freezed)
buttonX.pack()
root.mainloop()
A _side problem
...is that I am not able to run the task a second time because of this error.
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "./tk_simple.py", line 17, in do_tasks
loop.run_until_complete(do_urls())
File "/usr/lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete
self._check_closed()
File "/usr/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Multithreading
Whould multithreading be a possible solution? Only two threads - each loop has it's own thread?
EDIT: After reviewing this question and the answers it is related to nearly all GUI libs (e.g. PygObject/Gtk, wxWidgets, Qt, ...).
A:
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 work. I checked that it still runs with 3.7.0a2.
"""Proof of concept: integrate tkinter, asyncio and async iterator.
Terry Jan Reedy, 2016 July 25
"""
import asyncio
from random import randrange as rr
import tkinter as tk
class App(tk.Tk):
def __init__(self, loop, interval=1/120):
super().__init__()
self.loop = loop
self.protocol("WM_DELETE_WINDOW", self.close)
self.tasks = []
self.tasks.append(loop.create_task(self.rotator(1/60, 2)))
self.tasks.append(loop.create_task(self.updater(interval)))
async def rotator(self, interval, d_per_tick):
canvas = tk.Canvas(self, height=600, width=600)
canvas.pack()
deg = 0
color = 'black'
arc = canvas.create_arc(100, 100, 500, 500, style=tk.CHORD,
start=0, extent=deg, fill=color)
while await asyncio.sleep(interval, True):
deg, color = deg_color(deg, d_per_tick, color)
canvas.itemconfigure(arc, extent=deg, fill=color)
async def updater(self, interval):
while True:
self.update()
await asyncio.sleep(interval)
def close(self):
for task in self.tasks:
task.cancel()
self.loop.stop()
self.destroy()
def deg_color(deg, d_per_tick, color):
deg += d_per_tick
if 360 <= deg:
deg %= 360
color = '#%02x%02x%02x' % (rr(0, 256), rr(0, 256), rr(0, 256))
return deg, color
loop = asyncio.get_event_loop()
app = App(loop)
loop.run_forever()
loop.close()
Both the tk update overhead and time resolution increase as the interval is decreased. For gui updates, as opposed to animations, 20 per second may be enough.
I recently succeeded in running async def coroutines containing tkinter calls and awaits with mainloop. The prototype uses asyncio Tasks and Futures, but I don't know if adding normal asyncio tasks would work. If one wants to run asyncio and tkinter tasks together, I think running tk update with an asyncio loop is a better idea.
EDIT: A least as used above, exception without async def coroutines kill the coroutine but are somewhere caught and discarded. Silent error are pretty obnoxious.
EDIT2: Additional code and comments at
https://bugs.python.org/issue27546
A:
In a slight modification to your code, I created the asyncio event_loop in the main thread and passed it as an argument to the asyncio thread. Now Tkinter won't freeze while the urls are fetched.
from tkinter import *
from tkinter import messagebox
import asyncio
import threading
import random
def _asyncio_thread(async_loop):
async_loop.run_until_complete(do_urls())
def do_tasks(async_loop):
""" Button-Event-Handler starting the asyncio part. """
threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()
async def one_url(url):
""" One task. """
sec = random.randint(1, 8)
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [one_url(url) for url in range(10)]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
def do_freezed():
messagebox.showinfo(message='Tkinter is reacting.')
def main(async_loop):
root = Tk()
Button(master=root, text='Asyncio Tasks', command= lambda:do_tasks(async_loop)).pack()
Button(master=root, text='Freezed???', command=do_freezed).pack()
root.mainloop()
if __name__ == '__main__':
async_loop = asyncio.get_event_loop()
main(async_loop)
A:
I'm a bit late to the party but if you are not targeting Windows you can use aiotkinter to achieve what you want. I modified your code to show you how to use this package:
from tkinter import *
from tkinter import messagebox
import asyncio
import random
import aiotkinter
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
def do_tasks():
task = asyncio.ensure_future(do_urls())
task.add_done_callback(tasks_done)
def tasks_done(task):
messagebox.showinfo(message='Tasks done.')
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [
one_url(url)
for url in range(10)
]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
if __name__ == '__main__':
asyncio.set_event_loop_policy(aiotkinter.TkinterEventLoopPolicy())
loop = asyncio.get_event_loop()
root = Tk()
buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
buttonT.pack()
buttonX = Button(master=root, text='Freezed???', command=do_freezed)
buttonX.pack()
loop.run_forever()
A:
You can keep the GUI alive after pressing the Button by adding a call to root.update_idletasks() in the right spot:
from tkinter import *
from tkinter import messagebox
import asyncio
import random
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
def do_tasks():
""" Button-Event-Handler starting the asyncio part. """
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(do_urls())
finally:
loop.close()
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
root.update_idletasks() # ADDED: Allow tkinter to update gui.
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [one_url(url) for url in range(10)]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
if __name__ == '__main__':
root = Tk()
buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
buttonT.pack()
buttonX = Button(master=root, text='Freezed???', command=do_freezed)
buttonX.pack()
root.mainloop()
A:
I had similar task solved with multiprocessing.
Major parts:
Main process is Tk's process with mainloop.
daemon=True process with aiohttp service that executes commands.
Intercom using duplex Pipe so each process can use it's end.
Additionaly, I'm making Tk's virtual events to simplify massage tracking on app's side. You will need to apply patch manually. You can check python's bug tracker for details.
I'm checking Pipe each 0.25 seconds on both sides.
$ python --version
Python 3.7.3
main.py
import asyncio
import multiprocessing as mp
from ws import main
from app import App
class WebSocketProcess(mp.Process):
def __init__(self, pipe, *args, **kw):
super().__init__(*args, **kw)
self.pipe = pipe
def run(self):
loop = asyncio.get_event_loop()
loop.create_task(main(self.pipe))
loop.run_forever()
if __name__ == '__main__':
pipe = mp.Pipe()
WebSocketProcess(pipe, daemon=True).start()
App(pipe).mainloop()
app.py
import tkinter as tk
class App(tk.Tk):
def __init__(self, pipe, *args, **kw):
super().__init__(*args, **kw)
self.app_pipe, _ = pipe
self.ws_check_interval = 250;
self.after(self.ws_check_interval, self.ws_check)
def join_channel(self, channel_str):
self.app_pipe.send({
'command': 'join',
'data': {
'channel': channel_str
}
})
def ws_check(self):
while self.app_pipe.poll():
msg = self.app_pipe.recv()
self.event_generate('<<ws-event>>', data=json.dumps(msg), when='tail')
self.after(self.ws_check_interval, self.ws_check)
ws.py
import asyncio
import aiohttp
async def read_pipe(session, ws, ws_pipe):
while True:
while ws_pipe.poll():
msg = ws_pipe.recv()
# web socket send
if msg['command'] == 'join':
await ws.send_json(msg['data'])
# html request
elif msg['command'] == 'ticker':
async with session.get('https://example.com/api/ticker/') as response:
ws_pipe.send({'event': 'ticker', 'data': await response.json()})
await asyncio.sleep(.25)
async def main(pipe, loop):
_, ws_pipe = pipe
async with aiohttp.ClientSession() as session:
async with session.ws_connect('wss://example.com/') as ws:
task = loop.create_task(read_pipe(session, ws, ws_pipe))
async for msg in ws:
if msg.type == aiohttp.WSMsgType.TEXT:
if msg.data == 'close cmd':
await ws.close()
break
ws_pipe.send(msg.json())
elif msg.type == aiohttp.WSMsgType.ERROR:
break
A:
Using Python3.9, it could be done by making several async functions with one of them responsible to the Tk update(). While in the main loop, ensure_future() can be used to invoke all these async functions before starting the asyncio loop.
#!/usr/bin/env python3.9
import aioredis
import asyncio
import tkinter as tk
import tkinter.scrolledtext as st
import json
async def redis_main(logs):
redisS = await aioredis.create_connection(('localhost', 6379))
subCh = aioredis.Channel('pylog', is_pattern=False)
await redisS.execute_pubsub('subscribe', subCh)
while await subCh.wait_message():
msg = await subCh.get()
jmsg = json.loads(msg.decode('utf-8'))
logs.insert(tk.INSERT, jmsg['msg'] + '\n')
async def tk_main(root):
while True:
root.update()
await asyncio.sleep(0.05)
def on_closing():
asyncio.get_running_loop().stop()
if __name__ == '__main__':
root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", on_closing)
logs = st.ScrolledText(root, width=30, height=8)
logs.grid()
tkmain = asyncio.ensure_future(tk_main(root))
rdmain = asyncio.ensure_future(redis_main(logs))
loop = asyncio.get_event_loop()
try:
loop.run_forever()
except KeyboardInterrupt:
pass
tkmain.cancel()
rdmain.cancel()
A:
A solution using async_tkinter_loop module (which is written by me).
Internally, the approach is similar to the code from the answer of Terry Jan Reedy, but the usage is much simpler: you just need to wrap your asynchronous handlers into async_handler function calls, and use them as a command or an event handlers, and use async_mainloop(root) in place of root.mainloop().
from tkinter import *
from tkinter import messagebox
import asyncio
import random
from async_tkinter_loop import async_handler, async_mainloop
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [
asyncio.create_task(one_url(url)) # added create_task to remove warning "The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11."
for url in range(10)
]
print("Started")
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
print("Finished")
if __name__ == '__main__':
root = Tk()
# Wrap async function into async_handler to use it as a button handler or an event handler
buttonT = Button(master=root, text='Asyncio Tasks', command=async_handler(do_urls))
buttonT.pack()
buttonX = Button(master=root, text='Freezed???', command=do_freezed)
buttonX.pack()
# Use async_mainloop(root) instead of root.mainloop()
async_mainloop(root)
|
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
the problem is that the GUI is freezed. When I press the first button and start the 10 asyncio-tasks I am not able to press the second button in the GUI until all tasks are done. The GUI should never freeze - that is my goal.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from tkinter import *
from tkinter import messagebox
import asyncio
import random
def do_freezed():
""" Button-Event-Handler to see if a button on GUI works. """
messagebox.showinfo(message='Tkinter is reacting.')
def do_tasks():
""" Button-Event-Handler starting the asyncio part. """
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(do_urls())
finally:
loop.close()
async def one_url(url):
""" One task. """
sec = random.randint(1, 15)
await asyncio.sleep(sec)
return 'url: {}\tsec: {}'.format(url, sec)
async def do_urls():
""" Creating and starting 10 tasks. """
tasks = [
one_url(url)
for url in range(10)
]
completed, pending = await asyncio.wait(tasks)
results = [task.result() for task in completed]
print('\n'.join(results))
if __name__ == '__main__':
root = Tk()
buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)
buttonT.pack()
buttonX = Button(master=root, text='Freezed???', command=do_freezed)
buttonX.pack()
root.mainloop()
A _side problem
...is that I am not able to run the task a second time because of this error.
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
File "./tk_simple.py", line 17, in do_tasks
loop.run_until_complete(do_urls())
File "/usr/lib/python3.6/asyncio/base_events.py", line 443, in run_until_complete
self._check_closed()
File "/usr/lib/python3.6/asyncio/base_events.py", line 357, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Multithreading
Whould multithreading be a possible solution? Only two threads - each loop has it's own thread?
EDIT: After reviewing this question and the answers it is related to nearly all GUI libs (e.g. PygObject/Gtk, wxWidgets, Qt, ...).
|
[
"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 work. I checked that it still runs with 3.7.0a2.\n\"\"\"Proof of concept: integrate tkinter, asyncio and async iterator.\n\nTerry Jan Reedy, 2016 July 25\n\"\"\"\n\nimport asyncio\nfrom random import randrange as rr\nimport tkinter as tk\n\n\nclass App(tk.Tk):\n \n def __init__(self, loop, interval=1/120):\n super().__init__()\n self.loop = loop\n self.protocol(\"WM_DELETE_WINDOW\", self.close)\n self.tasks = []\n self.tasks.append(loop.create_task(self.rotator(1/60, 2)))\n self.tasks.append(loop.create_task(self.updater(interval)))\n\n async def rotator(self, interval, d_per_tick):\n canvas = tk.Canvas(self, height=600, width=600)\n canvas.pack()\n deg = 0\n color = 'black'\n arc = canvas.create_arc(100, 100, 500, 500, style=tk.CHORD,\n start=0, extent=deg, fill=color)\n while await asyncio.sleep(interval, True):\n deg, color = deg_color(deg, d_per_tick, color)\n canvas.itemconfigure(arc, extent=deg, fill=color)\n\n async def updater(self, interval):\n while True:\n self.update()\n await asyncio.sleep(interval)\n\n def close(self):\n for task in self.tasks:\n task.cancel()\n self.loop.stop()\n self.destroy()\n\n\ndef deg_color(deg, d_per_tick, color):\n deg += d_per_tick\n if 360 <= deg:\n deg %= 360\n color = '#%02x%02x%02x' % (rr(0, 256), rr(0, 256), rr(0, 256))\n return deg, color\n\nloop = asyncio.get_event_loop()\napp = App(loop)\nloop.run_forever()\nloop.close()\n\nBoth the tk update overhead and time resolution increase as the interval is decreased. For gui updates, as opposed to animations, 20 per second may be enough.\nI recently succeeded in running async def coroutines containing tkinter calls and awaits with mainloop. The prototype uses asyncio Tasks and Futures, but I don't know if adding normal asyncio tasks would work. If one wants to run asyncio and tkinter tasks together, I think running tk update with an asyncio loop is a better idea.\nEDIT: A least as used above, exception without async def coroutines kill the coroutine but are somewhere caught and discarded. Silent error are pretty obnoxious.\nEDIT2: Additional code and comments at\nhttps://bugs.python.org/issue27546\n",
"In a slight modification to your code, I created the asyncio event_loop in the main thread and passed it as an argument to the asyncio thread. Now Tkinter won't freeze while the urls are fetched.\nfrom tkinter import *\nfrom tkinter import messagebox\nimport asyncio\nimport threading\nimport random\n\ndef _asyncio_thread(async_loop):\n async_loop.run_until_complete(do_urls())\n\n\ndef do_tasks(async_loop):\n \"\"\" Button-Event-Handler starting the asyncio part. \"\"\"\n threading.Thread(target=_asyncio_thread, args=(async_loop,)).start()\n\n \nasync def one_url(url):\n \"\"\" One task. \"\"\"\n sec = random.randint(1, 8)\n await asyncio.sleep(sec)\n return 'url: {}\\tsec: {}'.format(url, sec)\n\nasync def do_urls():\n \"\"\" Creating and starting 10 tasks. \"\"\"\n tasks = [one_url(url) for url in range(10)]\n completed, pending = await asyncio.wait(tasks)\n results = [task.result() for task in completed]\n print('\\n'.join(results))\n\n\ndef do_freezed():\n messagebox.showinfo(message='Tkinter is reacting.')\n\ndef main(async_loop):\n root = Tk()\n Button(master=root, text='Asyncio Tasks', command= lambda:do_tasks(async_loop)).pack()\n Button(master=root, text='Freezed???', command=do_freezed).pack()\n root.mainloop()\n\nif __name__ == '__main__':\n async_loop = asyncio.get_event_loop()\n main(async_loop)\n\n",
"I'm a bit late to the party but if you are not targeting Windows you can use aiotkinter to achieve what you want. I modified your code to show you how to use this package:\nfrom tkinter import *\nfrom tkinter import messagebox\nimport asyncio\nimport random\n\nimport aiotkinter\n\ndef do_freezed():\n \"\"\" Button-Event-Handler to see if a button on GUI works. \"\"\"\n messagebox.showinfo(message='Tkinter is reacting.')\n\ndef do_tasks():\n task = asyncio.ensure_future(do_urls())\n task.add_done_callback(tasks_done)\n\ndef tasks_done(task):\n messagebox.showinfo(message='Tasks done.')\n\nasync def one_url(url):\n \"\"\" One task. \"\"\"\n sec = random.randint(1, 15)\n await asyncio.sleep(sec)\n return 'url: {}\\tsec: {}'.format(url, sec)\n\nasync def do_urls():\n \"\"\" Creating and starting 10 tasks. \"\"\"\n tasks = [\n one_url(url)\n for url in range(10)\n ]\n completed, pending = await asyncio.wait(tasks)\n results = [task.result() for task in completed]\n print('\\n'.join(results))\n\nif __name__ == '__main__':\n asyncio.set_event_loop_policy(aiotkinter.TkinterEventLoopPolicy())\n loop = asyncio.get_event_loop()\n root = Tk()\n buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)\n buttonT.pack()\n buttonX = Button(master=root, text='Freezed???', command=do_freezed)\n buttonX.pack()\n loop.run_forever()\n\n",
"You can keep the GUI alive after pressing the Button by adding a call to root.update_idletasks() in the right spot:\nfrom tkinter import *\nfrom tkinter import messagebox\nimport asyncio\nimport random\n\ndef do_freezed():\n \"\"\" Button-Event-Handler to see if a button on GUI works. \"\"\"\n messagebox.showinfo(message='Tkinter is reacting.')\n\ndef do_tasks():\n \"\"\" Button-Event-Handler starting the asyncio part. \"\"\"\n loop = asyncio.get_event_loop()\n try:\n loop.run_until_complete(do_urls())\n finally:\n loop.close()\n\nasync def one_url(url):\n \"\"\" One task. \"\"\"\n sec = random.randint(1, 15)\n root.update_idletasks() # ADDED: Allow tkinter to update gui.\n await asyncio.sleep(sec)\n return 'url: {}\\tsec: {}'.format(url, sec)\n\nasync def do_urls():\n \"\"\" Creating and starting 10 tasks. \"\"\"\n tasks = [one_url(url) for url in range(10)]\n completed, pending = await asyncio.wait(tasks)\n results = [task.result() for task in completed]\n print('\\n'.join(results))\n\n\nif __name__ == '__main__':\n root = Tk()\n\n buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)\n buttonT.pack()\n buttonX = Button(master=root, text='Freezed???', command=do_freezed)\n buttonX.pack()\n\n root.mainloop()\n\n",
"I had similar task solved with multiprocessing.\nMajor parts:\n\nMain process is Tk's process with mainloop.\ndaemon=True process with aiohttp service that executes commands.\nIntercom using duplex Pipe so each process can use it's end.\n\nAdditionaly, I'm making Tk's virtual events to simplify massage tracking on app's side. You will need to apply patch manually. You can check python's bug tracker for details.\nI'm checking Pipe each 0.25 seconds on both sides.\n$ python --version\nPython 3.7.3\n\nmain.py\nimport asyncio\nimport multiprocessing as mp\n\nfrom ws import main\nfrom app import App\n\n\nclass WebSocketProcess(mp.Process):\n\n def __init__(self, pipe, *args, **kw):\n super().__init__(*args, **kw)\n self.pipe = pipe\n\n def run(self):\n loop = asyncio.get_event_loop()\n loop.create_task(main(self.pipe))\n loop.run_forever()\n\n\nif __name__ == '__main__':\n pipe = mp.Pipe()\n WebSocketProcess(pipe, daemon=True).start()\n App(pipe).mainloop()\n\napp.py\nimport tkinter as tk\n\n\nclass App(tk.Tk):\n\n def __init__(self, pipe, *args, **kw):\n super().__init__(*args, **kw)\n self.app_pipe, _ = pipe\n self.ws_check_interval = 250;\n self.after(self.ws_check_interval, self.ws_check)\n\n def join_channel(self, channel_str):\n self.app_pipe.send({\n 'command': 'join',\n 'data': {\n 'channel': channel_str\n }\n })\n\n def ws_check(self):\n while self.app_pipe.poll():\n msg = self.app_pipe.recv()\n self.event_generate('<<ws-event>>', data=json.dumps(msg), when='tail')\n self.after(self.ws_check_interval, self.ws_check)\n\nws.py\nimport asyncio\n\nimport aiohttp\n\n\nasync def read_pipe(session, ws, ws_pipe):\n while True:\n while ws_pipe.poll():\n msg = ws_pipe.recv()\n\n # web socket send\n if msg['command'] == 'join':\n await ws.send_json(msg['data'])\n\n # html request\n elif msg['command'] == 'ticker':\n async with session.get('https://example.com/api/ticker/') as response:\n ws_pipe.send({'event': 'ticker', 'data': await response.json()})\n\n await asyncio.sleep(.25)\n\n\nasync def main(pipe, loop):\n _, ws_pipe = pipe\n async with aiohttp.ClientSession() as session:\n async with session.ws_connect('wss://example.com/') as ws:\n task = loop.create_task(read_pipe(session, ws, ws_pipe))\n async for msg in ws:\n if msg.type == aiohttp.WSMsgType.TEXT:\n if msg.data == 'close cmd':\n await ws.close()\n break\n ws_pipe.send(msg.json())\n elif msg.type == aiohttp.WSMsgType.ERROR:\n break\n\n",
"Using Python3.9, it could be done by making several async functions with one of them responsible to the Tk update(). While in the main loop, ensure_future() can be used to invoke all these async functions before starting the asyncio loop.\n#!/usr/bin/env python3.9\n\nimport aioredis\nimport asyncio\nimport tkinter as tk \nimport tkinter.scrolledtext as st \nimport json\n\nasync def redis_main(logs):\n redisS = await aioredis.create_connection(('localhost', 6379)) \n subCh = aioredis.Channel('pylog', is_pattern=False)\n await redisS.execute_pubsub('subscribe', subCh)\n while await subCh.wait_message():\n msg = await subCh.get()\n jmsg = json.loads(msg.decode('utf-8'))\n logs.insert(tk.INSERT, jmsg['msg'] + '\\n')\n\nasync def tk_main(root):\n while True:\n root.update()\n await asyncio.sleep(0.05)\n\ndef on_closing():\n asyncio.get_running_loop().stop()\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.protocol(\"WM_DELETE_WINDOW\", on_closing)\n logs = st.ScrolledText(root, width=30, height=8)\n logs.grid()\n \n tkmain = asyncio.ensure_future(tk_main(root))\n rdmain = asyncio.ensure_future(redis_main(logs))\n \n loop = asyncio.get_event_loop()\n try:\n loop.run_forever()\n except KeyboardInterrupt:\n pass\n\n tkmain.cancel()\n rdmain.cancel()\n\n",
"A solution using async_tkinter_loop module (which is written by me).\nInternally, the approach is similar to the code from the answer of Terry Jan Reedy, but the usage is much simpler: you just need to wrap your asynchronous handlers into async_handler function calls, and use them as a command or an event handlers, and use async_mainloop(root) in place of root.mainloop().\nfrom tkinter import *\nfrom tkinter import messagebox\nimport asyncio\nimport random\nfrom async_tkinter_loop import async_handler, async_mainloop\n\n\ndef do_freezed():\n \"\"\" Button-Event-Handler to see if a button on GUI works. \"\"\"\n messagebox.showinfo(message='Tkinter is reacting.')\n\n\nasync def one_url(url):\n \"\"\" One task. \"\"\"\n sec = random.randint(1, 15)\n await asyncio.sleep(sec)\n return 'url: {}\\tsec: {}'.format(url, sec)\n\n\nasync def do_urls():\n \"\"\" Creating and starting 10 tasks. \"\"\"\n tasks = [\n asyncio.create_task(one_url(url)) # added create_task to remove warning \"The explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.\"\n for url in range(10)\n ]\n print(\"Started\")\n completed, pending = await asyncio.wait(tasks)\n results = [task.result() for task in completed]\n print('\\n'.join(results))\n print(\"Finished\")\n\n\nif __name__ == '__main__':\n root = Tk()\n\n # Wrap async function into async_handler to use it as a button handler or an event handler\n buttonT = Button(master=root, text='Asyncio Tasks', command=async_handler(do_urls))\n buttonT.pack()\n buttonX = Button(master=root, text='Freezed???', command=do_freezed)\n buttonX.pack()\n\n # Use async_mainloop(root) instead of root.mainloop()\n async_mainloop(root)\n\n"
] |
[
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 works for me -- but it does work.\nNotice that while the asyncio tasks are happening, the other button is still alive and responding. I always like to the disable/enable thing on the other button so you don't fire off multiple tasks accidentally, but that's just a UI thing.\nimport threading\nfrom functools import partial\nfrom tkinter import *\nfrom tkinter import messagebox\nimport asyncio\nimport random\n\n\n# Please wrap all this code in a nice App class, of course\n\ndef _run_aio_loop(loop):\n asyncio.set_event_loop(loop)\n loop.run_forever()\naioloop = asyncio.new_event_loop()\nt = threading.Thread(target=partial(_run_aio_loop, aioloop))\nt.daemon = True # Optional depending on how you plan to shutdown the app\nt.start()\n\nbuttonT = None\n\ndef do_freezed():\n \"\"\" Button-Event-Handler to see if a button on GUI works. \"\"\"\n messagebox.showinfo(message='Tkinter is reacting.')\n\ndef do_tasks():\n \"\"\" Button-Event-Handler starting the asyncio part. \"\"\"\n buttonT.configure(state=DISABLED)\n asyncio.run_coroutine_threadsafe(do_urls(), aioloop)\n\nasync def one_url(url):\n \"\"\" One task. \"\"\"\n sec = random.randint(1, 3)\n # root.update_idletasks() # We can delete this now\n await asyncio.sleep(sec)\n return 'url: {}\\tsec: {}'.format(url, sec)\n\nasync def do_urls():\n \"\"\" Creating and starting 10 tasks. \"\"\"\n tasks = [one_url(url) for url in range(3)]\n completed, pending = await asyncio.wait(tasks)\n results = [task.result() for task in completed]\n print('\\n'.join(results))\n buttonT.configure(state=NORMAL) # Tk doesn't seem to care that this is called on another thread\n\n\nif __name__ == '__main__':\n root = Tk()\n\n buttonT = Button(master=root, text='Asyncio Tasks', command=do_tasks)\n buttonT.pack()\n buttonX = Button(master=root, text='Freezed???', command=do_freezed)\n buttonX.pack()\n\n root.mainloop()\n\n"
] |
[
-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/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]')
googlebutton.click()
linkedinsearch = 'site:www.linkedin.com “{}”'.format(companynameslist2[i])
search = driver.find_element(By.XPATH, '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input')
search.click()
search.send_keys(linkedinsearch)
search.send_keys(Keys.ENTER)
currenturl = driver.current_url
source2 = requests.get(currenturl).text
soup2 = BeautifulSoup(source2, 'lxml')
links = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div[1]/div/a').click()
print(driver.current_url)
Hey guys, this program should scrape the LinkedIn company page of a google search input. i thought this would be the best way to do it (without having to log into LinkedIn), but the problem is that the XPath i used is sometimes invalid, if the google search shows images before the links. I can I skip these images and only scrape the company page?
Any help much appreciated!!!
A:
You need to improve your locators. Absolute XPaths are extremely breakable.
I tested the following code on several company names and it worked correct.
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
options.add_argument('--disable-notifications')
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)
url = "https://google.com"
driver.get(url)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='q']"))).send_keys("Microsoft" + Keys.ENTER)
link = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#search a[href]"))).get_attribute("href")
print(link)
The output is
https://www.microsoft.com/
So, actually all your code is changed here to 2 lines.
Again, I tested it on several company names. In case there will be exclusions - please let me know and I'll try to check more general solution if needed.
|
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.click()
linkedinsearch = 'site:www.linkedin.com “{}”'.format(companynameslist2[i])
search = driver.find_element(By.XPATH, '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input')
search.click()
search.send_keys(linkedinsearch)
search.send_keys(Keys.ENTER)
currenturl = driver.current_url
source2 = requests.get(currenturl).text
soup2 = BeautifulSoup(source2, 'lxml')
links = driver.find_element_by_xpath('//*[@id="rso"]/div[1]/div/div/div[1]/div/a').click()
print(driver.current_url)
Hey guys, this program should scrape the LinkedIn company page of a google search input. i thought this would be the best way to do it (without having to log into LinkedIn), but the problem is that the XPath i used is sometimes invalid, if the google search shows images before the links. I can I skip these images and only scrape the company page?
Any help much appreciated!!!
|
[
"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.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument('--disable-notifications')\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://google.com\"\ndriver.get(url)\n\n\nwait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, \"[name='q']\"))).send_keys(\"Microsoft\" + Keys.ENTER)\nlink = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, \"#search a[href]\"))).get_attribute(\"href\")\nprint(link)\n\nThe output is\nhttps://www.microsoft.com/\n\nSo, actually all your code is changed here to 2 lines.\nAgain, I tested it on several company names. In case there will be exclusions - please let me know and I'll try to check more general solution if needed.\n"
] |
[
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 way I would do it is:
for i in range(0, len(a)):
if a[i] == 1 and b[i] == 1:
return False
return True
Though I feel this is very inefficient. Is there an easier and more efficient way to do this? I was thinking of using binary AND, but not sure how to implement that.
A:
Are you looking for one liner. Here it is:
any([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
Sorry did not test it. Here is modified version with test:
>>> a = [0,0,0,1,1]
>>> b = [1,0,0,0,0]
>>> c = [1,1,1,0,0]
>>> def f(a,b):
... return all([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
...
>>> print(f(a,b), f(b,c), f(a,c))
True False True
A:
Using zip makes it a bit more robust, as you don't need to worry about IndexErrors:
for elem_a, elem_b in zip(a, b):
if elem_a and elem_b:
return False
return True
You don't need binary and if you know the lists contain either 0s or 1s. Python interprets 0 as False in this case.
|
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, len(a)):
if a[i] == 1 and b[i] == 1:
return False
return True
Though I feel this is very inefficient. Is there an easier and more efficient way to do this? I was thinking of using binary AND, but not sure how to implement that.
|
[
"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 else True for i in range(0, len(a))])\n...\n>>> print(f(a,b), f(b,c), f(a,c))\nTrue False True\n\n",
"Using zip makes it a bit more robust, as you don't need to worry about IndexErrors:\nfor elem_a, elem_b in zip(a, b):\n if elem_a and elem_b:\n return False\nreturn True\n\nYou don't need binary and if you know the lists contain either 0s or 1s. Python interprets 0 as False in this case.\n"
] |
[
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", class_="s-item__price")
shippings = soup.find_all("span", class_="s-item__shipping s-item__logisticsCost"
for name,price,shipping in zip(names,prices,shippings):
print(name.text, price.text, shipping.text)
Right now, this script works perfectly. It prints everything that needs to be printed.
But... I want to be able to go to the next page and scrape everything off of there as well.
The class for the next page is "pagination__next icon-link"
I'm not sure how I would go about it.
A:
Just iterate link by pagination url query value
base_url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=electronics&_pgn='
for i in range(pages_count):
base_url+f'{i}'
# your code...
response = requests.get(url)
For correct parsing by category, due to the specifics of the displayed pages of the site, I advise you to refer to the pagination object for each request, look at the last page number and substitute it in the request
Take last number of available page on current page:
ol = soup.find("ol", class_="pagination__items")
lis = ol.find_all("li")
print(f"Last available number of post on current page {lis[-1].text}")
A:
In order to collect all the information from all pages, you can use the while loop which dynamically paginates through all pages.
The while loop will be executed until there is a stop command, in our case, the command to end the loop will be to check for the presence of the next page, for which the CSS selector is responsible - ".pagination__next".
Also, there's a URL parameter that is responsible for pagination: _pgn which is used to increase page number by 1 and thus selects the next page:
if soup.select_one(".pagination__next"):
params['_pgn'] += 1
else:
break
See the full code in online IDE.
from bs4 import BeautifulSoup
import requests, json, lxml
# https://requests.readthedocs.io/en/latest/user/quickstart/#custom-headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36",
}
params = {
"_nkw": "electronics", # search query
"_pgn": 1 # page number
}
data = []
while True:
page = requests.get('https://www.ebay.com/sch/i.html', params=params, headers=headers, timeout=30)
soup = BeautifulSoup(page.text, 'lxml')
print(f"Extracting page: {params['_pgn']}")
print("-" * 10)
for products in soup.select(".s-item__info"):
title = products.select_one(".s-item__title span").text
price = products.select_one(".s-item__price").text
link = products.select_one(".s-item__link")["href"]
data.append({
"title" : title,
"price" : price,
"link" : link
})
if soup.select_one(".pagination__next"):
params['_pgn'] += 1
else:
break
print(json.dumps(data, indent=2, ensure_ascii=False))
Example output:
[
{
"title": "Nintendo DSi XL Japan Import Console & USB Charger - Pick Your Color TESTED",
"price": "$69.99",
"link": "https://www.ebay.com/itm/165773301243?hash=item2698dbd5fb:g:HFcAAOSwTdNhnqy~&amdata=enc%3AAQAHAAAA4MXRmWPDY6vBlTlYLy%2BEQPsi1HJM%2BFzt2TWJ%2BjCbK6Q2mreLV7ZpKmZOvU%2FMGqxY2oQZ91aPaHW%2FS%2BRCUW3zUKWDIDoN2ITF3ooZptkWCkd8x%2FIOIaR7t2rSYDHwQEFUD7N6wdnY%2Bh6SpljeSkCPkoKi%2FDCpU0YLOO3mpuLVjgO8GQYKhrlXG59BDDw8IyaayjRVdWyjh534fuIRToSqFrki97dJMVXE0LNE%2BtPmJN96WbYIlqmo4%2B278nkNigJHI8djvwHMmqYUBQhQLN2ScD%2FLnApPlMJXirqegMet0DZQ%7Ctkp%3ABk9SR7K0tsSSYQ"
},
{
"title": "Anbernic RG351P White, Samsung 64 GB SD Card AmberElec & Case",
"price": "$89.99",
"link": "https://www.ebay.com/itm/144690079314?hash=item21b0336652:g:8qwAAOSw93ZjO6n~&amdata=enc%3AAQAHAAAAoNGQWvtymUdp2cEYaKyfTAzWm0oZvBODZsm2oeHl3s%2F6jF9k3nAIpsQkpiZBFI657Cg53X9zAgExAxQAfmev0Bgh7%2FjEtC5FU8O5%2FfoQ3tp8XYtyKdoRy%2FwdebmsGKD%2FIKvW1lWzCNN%2FpSAUDLrPgPN9%2Fs8igeU7jqAT4NFn3FU7W4%2BoFV%2B2gNOj8nhxYlm3HZ6vm21T4P3IAA4KXJZhW2E%3D%7Ctkp%3ABk9SR7K0tsSSYQ"
},
{
"title": "New ListingWhite wii console ONLY Tested Working",
"price": "$24.99",
"link": "https://www.ebay.com/itm/385243730852?hash=item59b250d3a4:g:t3YAAOSwZBBjctqi&amdata=enc%3AAQAHAAAAoH9I%2BSQlJpKebgObGE7Idppe2cewzEiV0SdZ6pEu0sVpIJK5%2F3q15ygTFAdPRElY232LwDKIMXjkIwag1FUN76geBg2vCnPfd3x8BAHzXn%2B1u5zF9cBITLCuawKTYnfUeCYMavO4cBmpnsrvUOSokvnTacfB078MF95%2FH1sUQH%2BfIjDtPzFoFTJrTtKLINRlXZ9edD%2BVW%2FB2TLYZ%2FHMAHkE%3D%7Ctkp%3ABk9SR7K0tsSSYQ"
},
# ...
]
As an alternative, you can use Ebay Organic Results API from SerpApi. It's a paid API with a free plan that handles blocks and parsing on their backend.
Example code that paginates through all pages:
from serpapi import EbaySearch
from urllib.parse import (parse_qsl, urlsplit)
import os, json
params = {
"api_key": os.getenv("API_KEY"), # serpapi api key
"engine": "ebay", # search engine
"ebay_domain": "ebay.com", # ebay domain
"_nkw": "electronics", # search query
}
search = EbaySearch(params) # where data extraction happens
page_num = 0
data = []
while True:
results = search.get_dict() # JSON -> Python dict
if "error" in results:
print(results["error"])
break
for organic_result in results.get("organic_results", []):
link = organic_result.get("link")
price = organic_result.get("price")
data.append({
"price" : price,
"link" : link
})
page_num += 1
print(page_num)
next_page_query_dict = dict(parse_qsl(urlsplit(results["serpapi_pagination"]["next"]).query))
current_page = results["serpapi_pagination"]["current"] # 1,2,3...
# looks for the next page data (_pgn):
if "next" in results.get("pagination", {}):
# if current_page = 20 and next_page_query_dict["_pgn"] = 20: break
if int(current_page) == int(next_page_query_dict["_pgn"]):
break
# update next page data
search.params_dict.update(next_page_query_dict)
else:
break
print(json.dumps(data, indent=2))
Output:
[
{
"price": {
"raw": "$169.00",
"extracted": 169.0
},
"link": "https://www.ebay.com/itm/113356737439?hash=item1a64968b9f:g:4qoAAOSwQypdKgT6&amdata=enc%3AAQAHAAAA4N8GJRRCbG8WIU7%2BzjrvsRMMmKaTEnA0l7Nz9nOWUUSin3gZ5Ho41Fc4A2%2FFLtlLzbb5UuTtU5s3Qo7Ky%2FWB%2FTEuDKBhFldxMZUzVoixZXII6T1CTtgG5YFJWs0Zj8QldjdM9PwBFuiLNJbsRzG38k7v1rJdg4QGzVUOauPxH0kiANtefqiBhnYHWZ0RfMqwh4S%2BbQ59JYQWSZjAefL61WYyNwkfSdrfcq%2BW2B7b%2BR8QEfynka5CE6g7YPpoWWp4Bk3IOvd4CZxAzTpgvOPoMMKPy0VCW1gPJDG4R2CsfDEv%7Ctkp%3ABk9SR56IpsWSYQ"
},
{
"price": {
"raw": "$239.00",
"extracted": 239.0
},
"link": "https://www.ebay.com/itm/115600879000?hash=item1aea596d98:g:F3YAAOSwsXxjbuYn&amdata=enc%3AAQAHAAAA4LuAhrdA4ahkT85Gf15%2FtEH9GBe%2B0qlDZfEt4p9O0YPmJZVPyq%2Fkuz%2FV86SF3%2B7SYY%2BlK04XQtCyS3NGyNi03GurFWx2dYwoKFUj2G7YsLw%2BalUKmdiv5bC3jJaRTnXuBOJGPXQxw2IwTHcvZ%2Fu8T7tEnYF5ih3HGMg69vCVZdVHqRa%2FYehvk14wVwj3OwBTVrNM8dq7keGeoLKUdYDHCMAH6Y4je4mTR6PX4pWFS6S7lJ8Zrk5YhyHQInwWYXwkclgaWadC4%2BLwOzUjcKepXl5mDnxUXe6pPcccYL3u8g4O%7Ctkp%3ABk9SR56IpsWSYQ"
},
# ...
]
|
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", class_="s-item__shipping s-item__logisticsCost"
for name,price,shipping in zip(names,prices,shippings):
print(name.text, price.text, shipping.text)
Right now, this script works perfectly. It prints everything that needs to be printed.
But... I want to be able to go to the next page and scrape everything off of there as well.
The class for the next page is "pagination__next icon-link"
I'm not sure how I would go about it.
|
[
"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 of the site, I advise you to refer to the pagination object for each request, look at the last page number and substitute it in the request\nTake last number of available page on current page:\nol = soup.find(\"ol\", class_=\"pagination__items\")\nlis = ol.find_all(\"li\")\n\nprint(f\"Last available number of post on current page {lis[-1].text}\")\n\n",
"In order to collect all the information from all pages, you can use the while loop which dynamically paginates through all pages.\nThe while loop will be executed until there is a stop command, in our case, the command to end the loop will be to check for the presence of the next page, for which the CSS selector is responsible - \".pagination__next\".\nAlso, there's a URL parameter that is responsible for pagination: _pgn which is used to increase page number by 1 and thus selects the next page:\nif soup.select_one(\".pagination__next\"):\n params['_pgn'] += 1\nelse:\n break\n\nSee the full code in online IDE.\nfrom bs4 import BeautifulSoup\nimport requests, json, lxml\n\n# https://requests.readthedocs.io/en/latest/user/quickstart/#custom-headers\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.60 Safari/537.36\",\n }\n \nparams = {\n \"_nkw\": \"electronics\", # search query \n \"_pgn\": 1 # page number\n }\n\ndata = []\n\nwhile True:\n page = requests.get('https://www.ebay.com/sch/i.html', params=params, headers=headers, timeout=30)\n soup = BeautifulSoup(page.text, 'lxml')\n \n print(f\"Extracting page: {params['_pgn']}\")\n\n print(\"-\" * 10)\n \n for products in soup.select(\".s-item__info\"):\n title = products.select_one(\".s-item__title span\").text\n price = products.select_one(\".s-item__price\").text\n link = products.select_one(\".s-item__link\")[\"href\"]\n \n data.append({\n \"title\" : title,\n \"price\" : price,\n \"link\" : link\n })\n\n if soup.select_one(\".pagination__next\"):\n params['_pgn'] += 1\n else:\n break\n\nprint(json.dumps(data, indent=2, ensure_ascii=False))\n\nExample output:\n[\n {\n \"title\": \"Nintendo DSi XL Japan Import Console & USB Charger - Pick Your Color TESTED\",\n \"price\": \"$69.99\",\n \"link\": \"https://www.ebay.com/itm/165773301243?hash=item2698dbd5fb:g:HFcAAOSwTdNhnqy~&amdata=enc%3AAQAHAAAA4MXRmWPDY6vBlTlYLy%2BEQPsi1HJM%2BFzt2TWJ%2BjCbK6Q2mreLV7ZpKmZOvU%2FMGqxY2oQZ91aPaHW%2FS%2BRCUW3zUKWDIDoN2ITF3ooZptkWCkd8x%2FIOIaR7t2rSYDHwQEFUD7N6wdnY%2Bh6SpljeSkCPkoKi%2FDCpU0YLOO3mpuLVjgO8GQYKhrlXG59BDDw8IyaayjRVdWyjh534fuIRToSqFrki97dJMVXE0LNE%2BtPmJN96WbYIlqmo4%2B278nkNigJHI8djvwHMmqYUBQhQLN2ScD%2FLnApPlMJXirqegMet0DZQ%7Ctkp%3ABk9SR7K0tsSSYQ\"\n },\n {\n \"title\": \"Anbernic RG351P White, Samsung 64 GB SD Card AmberElec & Case\",\n \"price\": \"$89.99\",\n \"link\": \"https://www.ebay.com/itm/144690079314?hash=item21b0336652:g:8qwAAOSw93ZjO6n~&amdata=enc%3AAQAHAAAAoNGQWvtymUdp2cEYaKyfTAzWm0oZvBODZsm2oeHl3s%2F6jF9k3nAIpsQkpiZBFI657Cg53X9zAgExAxQAfmev0Bgh7%2FjEtC5FU8O5%2FfoQ3tp8XYtyKdoRy%2FwdebmsGKD%2FIKvW1lWzCNN%2FpSAUDLrPgPN9%2Fs8igeU7jqAT4NFn3FU7W4%2BoFV%2B2gNOj8nhxYlm3HZ6vm21T4P3IAA4KXJZhW2E%3D%7Ctkp%3ABk9SR7K0tsSSYQ\"\n },\n {\n \"title\": \"New ListingWhite wii console ONLY Tested Working\",\n \"price\": \"$24.99\",\n \"link\": \"https://www.ebay.com/itm/385243730852?hash=item59b250d3a4:g:t3YAAOSwZBBjctqi&amdata=enc%3AAQAHAAAAoH9I%2BSQlJpKebgObGE7Idppe2cewzEiV0SdZ6pEu0sVpIJK5%2F3q15ygTFAdPRElY232LwDKIMXjkIwag1FUN76geBg2vCnPfd3x8BAHzXn%2B1u5zF9cBITLCuawKTYnfUeCYMavO4cBmpnsrvUOSokvnTacfB078MF95%2FH1sUQH%2BfIjDtPzFoFTJrTtKLINRlXZ9edD%2BVW%2FB2TLYZ%2FHMAHkE%3D%7Ctkp%3ABk9SR7K0tsSSYQ\"\n },\n # ...\n]\n\n\nAs an alternative, you can use Ebay Organic Results API from SerpApi. It's a paid API with a free plan that handles blocks and parsing on their backend.\nExample code that paginates through all pages:\nfrom serpapi import EbaySearch\nfrom urllib.parse import (parse_qsl, urlsplit)\nimport os, json\n\nparams = {\n \"api_key\": os.getenv(\"API_KEY\"), # serpapi api key \n \"engine\": \"ebay\", # search engine\n \"ebay_domain\": \"ebay.com\", # ebay domain\n \"_nkw\": \"electronics\", # search query \n}\n\nsearch = EbaySearch(params) # where data extraction happens\n\npage_num = 0\n\ndata = []\n\nwhile True:\n results = search.get_dict() # JSON -> Python dict\n\n if \"error\" in results:\n print(results[\"error\"])\n break\n \n for organic_result in results.get(\"organic_results\", []):\n link = organic_result.get(\"link\")\n price = organic_result.get(\"price\")\n\n data.append({\n \"price\" : price,\n \"link\" : link\n })\n \n page_num += 1\n print(page_num)\n \n next_page_query_dict = dict(parse_qsl(urlsplit(results[\"serpapi_pagination\"][\"next\"]).query)) \n current_page = results[\"serpapi_pagination\"][\"current\"] # 1,2,3...\n\n # looks for the next page data (_pgn):\n if \"next\" in results.get(\"pagination\", {}):\n \n # if current_page = 20 and next_page_query_dict[\"_pgn\"] = 20: break\n if int(current_page) == int(next_page_query_dict[\"_pgn\"]):\n break\n \n # update next page data\n search.params_dict.update(next_page_query_dict)\n else:\n break\n print(json.dumps(data, indent=2))\n\nOutput:\n[\n {\n \"price\": {\n \"raw\": \"$169.00\",\n \"extracted\": 169.0\n },\n \"link\": \"https://www.ebay.com/itm/113356737439?hash=item1a64968b9f:g:4qoAAOSwQypdKgT6&amdata=enc%3AAQAHAAAA4N8GJRRCbG8WIU7%2BzjrvsRMMmKaTEnA0l7Nz9nOWUUSin3gZ5Ho41Fc4A2%2FFLtlLzbb5UuTtU5s3Qo7Ky%2FWB%2FTEuDKBhFldxMZUzVoixZXII6T1CTtgG5YFJWs0Zj8QldjdM9PwBFuiLNJbsRzG38k7v1rJdg4QGzVUOauPxH0kiANtefqiBhnYHWZ0RfMqwh4S%2BbQ59JYQWSZjAefL61WYyNwkfSdrfcq%2BW2B7b%2BR8QEfynka5CE6g7YPpoWWp4Bk3IOvd4CZxAzTpgvOPoMMKPy0VCW1gPJDG4R2CsfDEv%7Ctkp%3ABk9SR56IpsWSYQ\"\n },\n {\n \"price\": {\n \"raw\": \"$239.00\",\n \"extracted\": 239.0\n },\n \"link\": \"https://www.ebay.com/itm/115600879000?hash=item1aea596d98:g:F3YAAOSwsXxjbuYn&amdata=enc%3AAQAHAAAA4LuAhrdA4ahkT85Gf15%2FtEH9GBe%2B0qlDZfEt4p9O0YPmJZVPyq%2Fkuz%2FV86SF3%2B7SYY%2BlK04XQtCyS3NGyNi03GurFWx2dYwoKFUj2G7YsLw%2BalUKmdiv5bC3jJaRTnXuBOJGPXQxw2IwTHcvZ%2Fu8T7tEnYF5ih3HGMg69vCVZdVHqRa%2FYehvk14wVwj3OwBTVrNM8dq7keGeoLKUdYDHCMAH6Y4je4mTR6PX4pWFS6S7lJ8Zrk5YhyHQInwWYXwkclgaWadC4%2BLwOzUjcKepXl5mDnxUXe6pPcccYL3u8g4O%7Ctkp%3ABk9SR56IpsWSYQ\"\n },\n # ...\n]\n\n"
] |
[
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.csv", "a") as csv_file:
spreadsheet = csv.DictWriter(csv_file, fieldnames=field_names)
spreadsheet.writerows(data)
with open('score.csv', 'r') as csv_file:
spreadsheet = csv.DictReader(csv_file)
for row in spreadsheet:
print(dict(row))
A:
Create a variable to remember the highest score, and initialize it to zero.
Read 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.
At the end of the loop, print the highest score.
# initialize to a placeholder value
highest_score = 0
# read the csv file
with open('score.csv', 'r') as csv_file:
spreadsheet = csv.DictReader(csv_file)
for row in spreadsheet:
# convert the score column to an integer
intscore = int(row['score'])
# if this score is the highest so far, remember it
if intscore > highest_score:
highest_score = intscore
print(highest_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_file, fieldnames=field_names)
spreadsheet.writerows(data)
with open('score.csv', 'r') as csv_file:
spreadsheet = csv.DictReader(csv_file)
for row in spreadsheet:
print(dict(row))
|
[
"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\n\n# read the csv file\nwith open('score.csv', 'r') as csv_file:\n spreadsheet = csv.DictReader(csv_file)\n for row in spreadsheet:\n # convert the score column to an integer\n intscore = int(row['score'])\n\n # if this score is the highest so far, remember it\n if intscore > highest_score:\n highest_score = intscore\n\nprint(highest_score)\n\n"
] |
[
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 credentials in GitHub repo secrets and setup the following workflow to run on push to my data/ directory:
name: update_firestore
on:
push:
branches:
- main
paths:
- data/**.xlsx
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repo content
uses: actions/checkout@v2 # checkout the repository content to github runner.
- name: setup python
uses: actions/setup-python@v4
with:
python-version: '3.*' # install the latest python version
- name: install python packages
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: execute python script
env:
TYPE: service_account
PROJECT_ID: ${{ secrets.PROJECT_ID }}
PRIVATE_KEY_ID: ${{ secrets.PRIVATE_KEY_ID }}
PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
CLIENT_EMAIL: ${{ secrets.CLIENT_EMAIL }}
TOKEN_URI: ${{ secrets.TOKEN_URI }}
run: python src/update_database.py -n ideas -delete -add
The Problem
I keep getting the following error:
Traceback (most recent call last):
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/firebase_admin/credentials.py", line 96, in __init__
self._g_credential = service_account.Credentials.from_service_account_info(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/oauth2/service_account.py", line 221, in from_service_account_info
signer = _service_account_info.from_dict(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/_service_account_info.py", line 58, in from_dict
signer = crypt.RSASigner.from_service_account_info(data)
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/crypt/base.py", line 113, in from_service_account_info
return cls.from_string(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/crypt/_python_rsa.py", line 171, in from_string
raise ValueError("No key could be detected.")
ValueError: No key could be detected.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/work/IRIS/IRIS/src/update_database.py", line 9, in <module>
import fire
File "/home/runner/work/IRIS/IRIS/src/fire/__init__.py", line 35, in <module>
cred = credentials.Certificate(create_keyfile_dict())
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/firebase_admin/credentials.py", line 99, in __init__
raise ValueError('Failed to initialize a certificate credential. '
ValueError: Failed to initialize a certificate credential. Caused by: "No key could be detected."
Error: Process completed with exit code 1.
My Attempted Solutions
I have tried a variety of approaches including what I show above, just hardcoding each of the secrets, and copying the .json formatted credentials directly as a single secret. I know there are some issues dealing with multiline environment variables which the PRIVATE_KEY is. I have tried:
Pasting the PRIVATE_KEY str directly from the download firebase provides which includes \n
Removing escape characters and formatting the secret like:
-----BEGIN PRIVATE KEY-----
BunC40fL3773R5AndNumb3r5
...
rAndomLettersANDNumb3R5==
-----END PRIVATE KEY-----
I feel like the solution should be pretty straight-forward but have been struggling and my knowledge with all this is a bit limited.
Thank you in advance!
A:
After hours of research, I found an easy way to store the Firestore service account JSON as a Github Secret.
Step 1 : Convert your service account JSON to base-64
Let's name the base-64 encoded JSON SERVICE_ACCOUNT_KEY. There are two ways to get this value:
Method 1 : Using command line
cat path-to-your-service-account.json | base64 | xargs
This will return a single line representing the encoded service account JSON. Copy this value.
Method 2 : Using python
import json
import base64
service_key = {
"type": "service_account",
"project_id": "xxx",
"private_key_id": "xxx",
"private_key": "-----BEGIN PRIVATE KEY-----\nxxxxx\n-----END PRIVATE KEY-----\n",
"client_email": "xxxx.com",
"client_id": "xxxx",
"auth_uri": "xxxx",
"token_uri": "xxxx",
"auth_provider_x509_cert_url": "xxxx",
"client_x509_cert_url": "xxxx"
}
# convert json to a string
service_key = json.dumps(service_key)
# encode service key
SERVICE_ACCOUNT_KEY= base64.b64encode(service_key.encode('utf-8'))
print(SERVICE_ACCOUNT_KEY)
# FORMAT: b'a_long_string'
Copy only the value between the quotes. (copy a_long_string instead of b'a_long_string')
Step 2 : Create your environment variable
I am using dotenv library to read environment variables. You will have to install it first using pip install python-dotenv. Also add this dependency in your requirements.txt for github actions.
Create a Github repository secret SERVICE_ACCOUNT_KEY which will store the base-64 value.
In your Github YML file, add the environment variable:
- name: execute py script
env:
SERVICE_ACCOUNT_KEY: ${{ secrets.SERVICE_ACCOUNT_KEY }}
run: python src/main.py
To be able to test your program locally, you might also want to add SERVICE_ACCOUNT_KEY together with its value to your .env file (which should be in the root directory of your project). Remember to add .env to your .gitignore file to avoid exposing your key on Github.
Step 3 : Decoding the service key
You will now need to get the value of SERVICE_ACCOUNT_KEY in your Python code and convert this value back to a JSON. I am using the dotenv library to get the value of the SERVICE_ACCOUNT_KEY.
import json
import base64
import os
from dotenv import load_dotenv, find_dotenv
# get the value of `SERVICE_ACCOUNT_KEY`environment variable
load_dotenv(find_dotenv())
encoded_key = os.getenv("SERVICE_ACCOUNT_KEY")
# decode
SERVICE_ACCOUNT_JSON = json.loads(base64.b64decode(encoded_key).decode('utf-8'))
# Use `SERVICE_ACCOUNT_JSON` later to initialse firestore db:
# cred = credentials.Certificate(SERVICE_ACCOUNT_JSON)
# firebase_admin.initialize_app(cred)
|
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 to run on push to my data/ directory:
name: update_firestore
on:
push:
branches:
- main
paths:
- data/**.xlsx
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: checkout repo content
uses: actions/checkout@v2 # checkout the repository content to github runner.
- name: setup python
uses: actions/setup-python@v4
with:
python-version: '3.*' # install the latest python version
- name: install python packages
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: execute python script
env:
TYPE: service_account
PROJECT_ID: ${{ secrets.PROJECT_ID }}
PRIVATE_KEY_ID: ${{ secrets.PRIVATE_KEY_ID }}
PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
CLIENT_EMAIL: ${{ secrets.CLIENT_EMAIL }}
TOKEN_URI: ${{ secrets.TOKEN_URI }}
run: python src/update_database.py -n ideas -delete -add
The Problem
I keep getting the following error:
Traceback (most recent call last):
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/firebase_admin/credentials.py", line 96, in __init__
self._g_credential = service_account.Credentials.from_service_account_info(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/oauth2/service_account.py", line 221, in from_service_account_info
signer = _service_account_info.from_dict(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/_service_account_info.py", line 58, in from_dict
signer = crypt.RSASigner.from_service_account_info(data)
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/crypt/base.py", line 113, in from_service_account_info
return cls.from_string(
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/google/auth/crypt/_python_rsa.py", line 171, in from_string
raise ValueError("No key could be detected.")
ValueError: No key could be detected.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/runner/work/IRIS/IRIS/src/update_database.py", line 9, in <module>
import fire
File "/home/runner/work/IRIS/IRIS/src/fire/__init__.py", line 35, in <module>
cred = credentials.Certificate(create_keyfile_dict())
File "/opt/hostedtoolcache/Python/3.10.7/x64/lib/python3.10/site-packages/firebase_admin/credentials.py", line 99, in __init__
raise ValueError('Failed to initialize a certificate credential. '
ValueError: Failed to initialize a certificate credential. Caused by: "No key could be detected."
Error: Process completed with exit code 1.
My Attempted Solutions
I have tried a variety of approaches including what I show above, just hardcoding each of the secrets, and copying the .json formatted credentials directly as a single secret. I know there are some issues dealing with multiline environment variables which the PRIVATE_KEY is. I have tried:
Pasting the PRIVATE_KEY str directly from the download firebase provides which includes \n
Removing escape characters and formatting the secret like:
-----BEGIN PRIVATE KEY-----
BunC40fL3773R5AndNumb3r5
...
rAndomLettersANDNumb3R5==
-----END PRIVATE KEY-----
I feel like the solution should be pretty straight-forward but have been struggling and my knowledge with all this is a bit limited.
Thank you in advance!
|
[
"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-service-account.json | base64 | xargs\n\nThis will return a single line representing the encoded service account JSON. Copy this value.\nMethod 2 : Using python\nimport json\nimport base64\n\n\nservice_key = {\n \"type\": \"service_account\",\n \"project_id\": \"xxx\",\n \"private_key_id\": \"xxx\",\n \"private_key\": \"-----BEGIN PRIVATE KEY-----\\nxxxxx\\n-----END PRIVATE KEY-----\\n\",\n \"client_email\": \"xxxx.com\",\n \"client_id\": \"xxxx\",\n \"auth_uri\": \"xxxx\",\n \"token_uri\": \"xxxx\",\n \"auth_provider_x509_cert_url\": \"xxxx\",\n \"client_x509_cert_url\": \"xxxx\"\n}\n\n# convert json to a string\nservice_key = json.dumps(service_key)\n\n# encode service key\nSERVICE_ACCOUNT_KEY= base64.b64encode(service_key.encode('utf-8'))\n\nprint(SERVICE_ACCOUNT_KEY)\n# FORMAT: b'a_long_string'\n\nCopy only the value between the quotes. (copy a_long_string instead of b'a_long_string')\nStep 2 : Create your environment variable\nI am using dotenv library to read environment variables. You will have to install it first using pip install python-dotenv. Also add this dependency in your requirements.txt for github actions.\n\nCreate a Github repository secret SERVICE_ACCOUNT_KEY which will store the base-64 value.\nIn your Github YML file, add the environment variable:\n\n - name: execute py script \n env:\n SERVICE_ACCOUNT_KEY: ${{ secrets.SERVICE_ACCOUNT_KEY }}\n run: python src/main.py \n\n\nTo be able to test your program locally, you might also want to add SERVICE_ACCOUNT_KEY together with its value to your .env file (which should be in the root directory of your project). Remember to add .env to your .gitignore file to avoid exposing your key on Github.\n\nStep 3 : Decoding the service key\nYou will now need to get the value of SERVICE_ACCOUNT_KEY in your Python code and convert this value back to a JSON. I am using the dotenv library to get the value of the SERVICE_ACCOUNT_KEY.\nimport json\nimport base64\nimport os\nfrom dotenv import load_dotenv, find_dotenv\n\n# get the value of `SERVICE_ACCOUNT_KEY`environment variable\nload_dotenv(find_dotenv())\nencoded_key = os.getenv(\"SERVICE_ACCOUNT_KEY\")\n\n# decode\nSERVICE_ACCOUNT_JSON = json.loads(base64.b64decode(encoded_key).decode('utf-8'))\n\n# Use `SERVICE_ACCOUNT_JSON` later to initialse firestore db:\n# cred = credentials.Certificate(SERVICE_ACCOUNT_JSON)\n# firebase_admin.initialize_app(cred)\n\n"
] |
[
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' object it is failing because no such method exist." How do I fix the update method to where it changes the "outcome_type":"Transfer" to "outcome_type":"Adopt" for a dog with "name":"Rhonda"? Here is my code:
animal_shelter.py
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self,username,password):
# Initializing the MongoClient. This helps to
# access the MongoDB databases and collections.
# init to connect to mongodb without authentication
self.client = MongoClient('mongodb://localhost:55996')
# init connect to mongodb with authentication
# self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
self.database = self.client['AAC']
# Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
self.database.animals.insert(data) # data should be dictionary
return True # Tells whether the create function ran successfully
else:
raise Exception("Nothing to save ...")
# Create method to implement the R in CRUD.
def read(self, data):
return self.database.animals.find_one(data) #returns only one
# Update method to implement the U in CRUD.
def update(self, data, {"$set": {"outcome_type":"Adopt"}}):
if data in self.database.animals():
print("Data exist, ", end =" ")
self.database.animals.update(data)
else:
print("Does not exist")`
testing_script.ipynb
from animal_shelter import AnimalShelter
# now need to create the object from the class
shelter = AnimalShelter("aacuser","Superman")
data = {"age_upon_outcome":"2 years","animal_type":"Dog","breed":"Dachshund","color":"Black and tan","name":"Rhonda","outcome_subtype":"SCRP","outcome_type":"Transfer","sex_upon_outcome":"Female"}
# if shelter.create(data):
# print("Animal added")
# else:
# print("Failed to add animal")
# Calls the read function
# shelter.read(data)
# Calls the update function
if shelter.update(data):
print(data)
I tried changing
self.database.animals.update(data)
to
self.database.animals.update({"$set": {"outcome_type":"Adopt"}})
and I was expecting to get a different outcome
A:
This form of the update method works:
def update(self, data, new_values):
if self.database.animals.count(data):
print("Data exist")
self.database.animals.update(data, new_values)
else:
print("Does not exist")
And this call works:
if shelter.update(data, new_values):
print(data)
|
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." How do I fix the update method to where it changes the "outcome_type":"Transfer" to "outcome_type":"Adopt" for a dog with "name":"Rhonda"? Here is my code:
animal_shelter.py
from pymongo import MongoClient
from bson.objectid import ObjectId
class AnimalShelter(object):
""" CRUD operations for Animal collection in MongoDB """
def __init__(self,username,password):
# Initializing the MongoClient. This helps to
# access the MongoDB databases and collections.
# init to connect to mongodb without authentication
self.client = MongoClient('mongodb://localhost:55996')
# init connect to mongodb with authentication
# self.client = MongoClient('mongodb://%s:%s@localhost:55996/?authMechanism=DEFAULT&authSource=AAC'%(username, password))
self.database = self.client['AAC']
# Complete this create method to implement the C in CRUD.
def create(self, data):
if data is not None:
self.database.animals.insert(data) # data should be dictionary
return True # Tells whether the create function ran successfully
else:
raise Exception("Nothing to save ...")
# Create method to implement the R in CRUD.
def read(self, data):
return self.database.animals.find_one(data) #returns only one
# Update method to implement the U in CRUD.
def update(self, data, {"$set": {"outcome_type":"Adopt"}}):
if data in self.database.animals():
print("Data exist, ", end =" ")
self.database.animals.update(data)
else:
print("Does not exist")`
testing_script.ipynb
from animal_shelter import AnimalShelter
# now need to create the object from the class
shelter = AnimalShelter("aacuser","Superman")
data = {"age_upon_outcome":"2 years","animal_type":"Dog","breed":"Dachshund","color":"Black and tan","name":"Rhonda","outcome_subtype":"SCRP","outcome_type":"Transfer","sex_upon_outcome":"Female"}
# if shelter.create(data):
# print("Animal added")
# else:
# print("Failed to add animal")
# Calls the read function
# shelter.read(data)
# Calls the update function
if shelter.update(data):
print(data)
I tried changing
self.database.animals.update(data)
to
self.database.animals.update({"$set": {"outcome_type":"Adopt"}})
and I was expecting to get a different outcome
|
[
"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):\nprint(data)\n\n"
] |
[
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:
message = template_file.read()
message = re.sub(r"{{\s*firm\s*}}", firm, message)
message = re.sub(r"{{\s*date\s*}}", date, message)
message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
message = re.sub(r"{{\s*to\s*}}", to, message)
message = re.sub(r"{{\s*subject\s*}}", subject, message)
msg = MIMEMultipart("alternative")
msg.set_charset("utf-8")
msg["Subject"] = subject
msg["From"] = fromEmail
msg["To"] = to
#Read from template
html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
text = message[message.find("text:") + len("text:"):].strip()
part1 = MIMEText(html, "html")
part2 = MIMEText(text, "plain")
msg.attach(part1)
msg.attach(part2)
try:
server = smtplib.SMTP("10.0.0.5")
server.sendmail(fromEmail, [to], msg.as_string())
return 0
except Exception as ex:
#log error
#return -1
#debug
raise ex
finally:
server.quit()
if __name__ == "__main__":
#debug
sys.argv.append("Moje")
sys.argv.append("newsletter@example.cz")
sys.argv.append("subscriber@example.com")
sys.argv.append("may2011.template")
sys.argv.append("This is subject")
sys.argv.append("This is date")
if len(sys.argv) != 7:
exit(-2)
firm = sys.argv[1]
fromEmail = sys.argv[2]
to = sys.argv[3]
template = sys.argv[4]
subject = sys.argv[5]
date = sys.argv[6]
exit(sendmail(firm, fromEmail, to, template, subject, date))
Output
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 69, in <module>
exit(sendmail(firm, fromEmail, to, template, subject, date))
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 45, in sendmail
raise ex
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 39, in sendmail
server.sendmail(fromEmail, [to], msg.as_string())
File "C:\Python32\lib\smtplib.py", line 716, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\u011b' in position 385: ordinal not in range(128)
A:
You should just add 'utf-8' argument to your MIMEText calls (it assumes 'us-ascii' by default).
For example:
# -*- encoding: utf-8 -*-
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
msg = MIMEMultipart("alternative")
msg["Subject"] = u'テストメール'
part1 = MIMEText(u'\u3053\u3093\u306b\u3061\u306f\u3001\u4e16\u754c\uff01\n',
"plain", "utf-8")
msg.attach(part1)
print msg.as_string().encode('ascii')
A:
The question asked by Martin Drlík is 7 years and 8 months old... And nowadays, thanks to the developers of Python, encoding problems are solved with version 3 of Python.
Consequently, it is no longer necessary to specify that one must use the utf-8 encoding:
#!/usr/bin/python2
# -*- encoding: utf-8 -*-
...
part2 = MIMEText(text, "plain", "utf-8")
We will simply write:
#!/usr/bin/python3
...
part2 = MIMEText(text, "plain")
Ultimate consequence: Martin Drlík's script works perfectly well!
However, it would be better to use the email.parser module, as suggested in email: Examples.
A:
The previous answers here were adequate for Python 2 and earlier versions of Python 3. Starting with Python 3.6, new code should generally use the modern EmailMessage API rather than the old email.message.Message class or the related MIMEMultipart, MIMEText etc classes. The newer API was unofficially introduced already in Python 3.3, and so the old one should no longer be necessary unless you need portability back to Python 2 (or 3.2, which nobody in their right mind would want anyway).
With the new API, you no longer need to manually assemble an explicit MIME structure from parts, or explicitly select body-part encodings etc. Nor is Unicode a special case any longer; the email library will transparently select a suitable container type and encoding for regular text.
import sys
import re
import smtplib
from email.message import EmailMessage
def sendmail(firm, fromEmail, to, template, subject, date):
with open(template, "r", encoding="utf-8") as template_file:
message = template_file.read()
message = re.sub(r"{{\s*firm\s*}}", firm, message)
message = re.sub(r"{{\s*date\s*}}", date, message)
message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
message = re.sub(r"{{\s*to\s*}}", to, message)
message = re.sub(r"{{\s*subject\s*}}", subject, message)
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = fromEmail
msg["To"] = to
html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
text = message[message.find("text:") + len("text:"):].strip()
msg.set_content(text)
msg.add_alternative(html, subtype="html")
try:
server = smtplib.SMTP("10.0.0.5")
server.send_message(msg)
return 0
# XXX FIXME: useless
except Exception as ex:
raise ex
finally:
server.quit()
# Explicitly return error
return 1
if __name__ == "__main__":
if len(sys.argv) != 7:
# Can't return negative
exit(2)
exit(sendmail(*sys.argv[1:]))
I'm not sure I completely understand the template handling here. Practitioners with even slightly different needs should probably instead review the Python email examples documentation
which contains several simple examples of how to implement common email use cases.
The blanket except is clearly superfluous here, but I left it in as a placeholder in case you want to see what exception handling might look like if you had something useful to put there.
Perhaps notice also that smtplib allows you to say with SMTP("10.9.8.76") as server: with a context manager.
A:
For whom it might interest, I've written a Mailer library that uses SMTPlib, and deals with headers, ssl/tls security, attachments and bulk email sending.
Of course it also deals with UTF-8 mail encoding for subject and body.
You may find the code at: https://github.com/netinvent/ofunctions/blob/master/ofunctions/mailer/__init__.py
The relevant encoding part is
message["Subject"] = Header(subject, 'utf-8')
message.attach(MIMEText(body, "plain", 'utf-8'))
TL;DR: Install with pip install ofunctions.mailer
Usage:
from ofunctions.mailer import Mailer
mailer = Mailer(smtp_server='myserver', smtp_port=587)
mailer.send_email(sender_mail='me@example.com', recipient_mails=['them@example.com', 'otherguy@example.com'])
Encoding is already set as UTF-8, but you could change encoding to whatever you need by using mailer = Mailer(smtp_srever='...', encoding='latin1')
|
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.read()
message = re.sub(r"{{\s*firm\s*}}", firm, message)
message = re.sub(r"{{\s*date\s*}}", date, message)
message = re.sub(r"{{\s*from\s*}}", fromEmail, message)
message = re.sub(r"{{\s*to\s*}}", to, message)
message = re.sub(r"{{\s*subject\s*}}", subject, message)
msg = MIMEMultipart("alternative")
msg.set_charset("utf-8")
msg["Subject"] = subject
msg["From"] = fromEmail
msg["To"] = to
#Read from template
html = message[message.find("html:") + len("html:"):message.find("text:")].strip()
text = message[message.find("text:") + len("text:"):].strip()
part1 = MIMEText(html, "html")
part2 = MIMEText(text, "plain")
msg.attach(part1)
msg.attach(part2)
try:
server = smtplib.SMTP("10.0.0.5")
server.sendmail(fromEmail, [to], msg.as_string())
return 0
except Exception as ex:
#log error
#return -1
#debug
raise ex
finally:
server.quit()
if __name__ == "__main__":
#debug
sys.argv.append("Moje")
sys.argv.append("newsletter@example.cz")
sys.argv.append("subscriber@example.com")
sys.argv.append("may2011.template")
sys.argv.append("This is subject")
sys.argv.append("This is date")
if len(sys.argv) != 7:
exit(-2)
firm = sys.argv[1]
fromEmail = sys.argv[2]
to = sys.argv[3]
template = sys.argv[4]
subject = sys.argv[5]
date = sys.argv[6]
exit(sendmail(firm, fromEmail, to, template, subject, date))
Output
Traceback (most recent call last):
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 69, in <module>
exit(sendmail(firm, fromEmail, to, template, subject, date))
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 45, in sendmail
raise ex
File "C:\Documents and Settings\Administrator\Plocha\Newsletter-build-desktop\sendmail.py", line 39, in sendmail
server.sendmail(fromEmail, [to], msg.as_string())
File "C:\Python32\lib\smtplib.py", line 716, in sendmail
msg = _fix_eols(msg).encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode character '\u011b' in position 385: ordinal not in range(128)
|
[
"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'\\u3053\\u3093\\u306b\\u3061\\u306f\\u3001\\u4e16\\u754c\\uff01\\n',\n \"plain\", \"utf-8\")\nmsg.attach(part1)\n\nprint msg.as_string().encode('ascii')\n\n",
"The question asked by Martin Drlík is 7 years and 8 months old... And nowadays, thanks to the developers of Python, encoding problems are solved with version 3 of Python.\nConsequently, it is no longer necessary to specify that one must use the utf-8 encoding:\n#!/usr/bin/python2\n# -*- encoding: utf-8 -*-\n...\n part2 = MIMEText(text, \"plain\", \"utf-8\")\n\nWe will simply write:\n#!/usr/bin/python3\n...\n part2 = MIMEText(text, \"plain\")\n\nUltimate consequence: Martin Drlík's script works perfectly well!\nHowever, it would be better to use the email.parser module, as suggested in email: Examples.\n",
"The previous answers here were adequate for Python 2 and earlier versions of Python 3. Starting with Python 3.6, new code should generally use the modern EmailMessage API rather than the old email.message.Message class or the related MIMEMultipart, MIMEText etc classes. The newer API was unofficially introduced already in Python 3.3, and so the old one should no longer be necessary unless you need portability back to Python 2 (or 3.2, which nobody in their right mind would want anyway).\nWith the new API, you no longer need to manually assemble an explicit MIME structure from parts, or explicitly select body-part encodings etc. Nor is Unicode a special case any longer; the email library will transparently select a suitable container type and encoding for regular text.\nimport sys\nimport re\nimport smtplib\nfrom email.message import EmailMessage\n\ndef sendmail(firm, fromEmail, to, template, subject, date):\n with open(template, \"r\", encoding=\"utf-8\") as template_file:\n message = template_file.read()\n\n message = re.sub(r\"{{\\s*firm\\s*}}\", firm, message)\n message = re.sub(r\"{{\\s*date\\s*}}\", date, message)\n message = re.sub(r\"{{\\s*from\\s*}}\", fromEmail, message)\n message = re.sub(r\"{{\\s*to\\s*}}\", to, message)\n message = re.sub(r\"{{\\s*subject\\s*}}\", subject, message)\n\n msg = EmailMessage() \n msg[\"Subject\"] = subject\n msg[\"From\"] = fromEmail\n msg[\"To\"] = to\n\n html = message[message.find(\"html:\") + len(\"html:\"):message.find(\"text:\")].strip()\n text = message[message.find(\"text:\") + len(\"text:\"):].strip()\n\n msg.set_content(text)\n msg.add_alternative(html, subtype=\"html\")\n\n try:\n server = smtplib.SMTP(\"10.0.0.5\")\n server.send_message(msg)\n return 0\n # XXX FIXME: useless\n except Exception as ex:\n raise ex\n finally:\n server.quit()\n # Explicitly return error\n return 1\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 7:\n # Can't return negative\n exit(2)\n\n exit(sendmail(*sys.argv[1:]))\n\nI'm not sure I completely understand the template handling here. Practitioners with even slightly different needs should probably instead review the Python email examples documentation\nwhich contains several simple examples of how to implement common email use cases.\nThe blanket except is clearly superfluous here, but I left it in as a placeholder in case you want to see what exception handling might look like if you had something useful to put there.\nPerhaps notice also that smtplib allows you to say with SMTP(\"10.9.8.76\") as server: with a context manager.\n",
"For whom it might interest, I've written a Mailer library that uses SMTPlib, and deals with headers, ssl/tls security, attachments and bulk email sending.\nOf course it also deals with UTF-8 mail encoding for subject and body.\nYou may find the code at: https://github.com/netinvent/ofunctions/blob/master/ofunctions/mailer/__init__.py\nThe relevant encoding part is\nmessage[\"Subject\"] = Header(subject, 'utf-8')\nmessage.attach(MIMEText(body, \"plain\", 'utf-8'))\n\nTL;DR: Install with pip install ofunctions.mailer\nUsage:\nfrom ofunctions.mailer import Mailer\n\nmailer = Mailer(smtp_server='myserver', smtp_port=587)\nmailer.send_email(sender_mail='me@example.com', recipient_mails=['them@example.com', 'otherguy@example.com'])\n\nEncoding is already set as UTF-8, but you could change encoding to whatever you need by using mailer = Mailer(smtp_srever='...', encoding='latin1')\n"
] |
[
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 settings.ini file\ncfg.read(os.path.join(os.path.dirname(os.path.realpath(__file__)), \"settings.ini\"))\n\nmsg = EmailMessage()\nmsg['Bcc'] = \", \".join(bcc)\nmsg['Cc'] = \", \".join(cc)\nmsg['From'] = from_email\nmsg['To'] = to_email\nmsg['Subject'] = subject\n\nmsg.set_content(str_body)\nmsg.add_alternative(html_body, subtype=\"html\")\n\n# add SSL (layer of security)\ncontext = ssl.create_default_context()\n\n# log in and send the email\nwith smtplib.SMTP_SSL(cfg.get(\"mail\", \"server\"), cfg.getint(\"mail\", \"port\"), context=context) as smtp:\n smtp.login(cfg.get(\"mail\", \"username\"), cfg.get(\"mail\", \"password\"))\n smtp.send_message(msg=msg)\n\n"
] |
[
-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 I was having no issues however adding in the text has made it more difficult and my main issue is with the if else statement. I seem to be able to only get one message to work, either yes or no, not both based on the case.
A:
I think a cleaner answer uses the built-in enumerate and zip functions:
Dlist = [17,13,10,6,2]
Ilist = [5,9,10,15,18]
def seqsearch(DS,IS):
for idx, (d, s) in enumerate(zip(DS, IS)):
if d == s:
return f"Yes! Found at index = {idx}"
return "No!\n-1"
print(seqsearch(Dlist,Ilist))
It's unclear whether you want to return just the first index, or all the indices with matching elements. In either case, it is probably better if you just return the desired value and then add any formatting and print statements outside of the function's scope.
A:
You could loop over both lists like so:
Dlist = [17, 13, 10, 6, 2]
Ilist = [5, 9, 10, 15, 18]
def seqsearch(DS, IS):
for index_1, element_1 in enumerate(DS):
for index_2, element_2 in enumerate(IS):
if (element_1 == element_2) and (index_1 == index_2):
print(f"Yes! Found at index ={index_1}")
return index_1
print("No!")
return -1
print(seqsearch(Dlist, Ilist))
However, there are more improvements you can make. zip() indeed is a better option, but slightly more complicated to understand.
Also, please note that return is not the same as print. You were not returning -1; you were printing it.
|
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 else statement. I seem to be able to only get one message to work, either yes or no, not both based on the case.
|
[
"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(Dlist,Ilist))\n\nIt's unclear whether you want to return just the first index, or all the indices with matching elements. In either case, it is probably better if you just return the desired value and then add any formatting and print statements outside of the function's scope.\n",
"You could loop over both lists like so:\nDlist = [17, 13, 10, 6, 2]\nIlist = [5, 9, 10, 15, 18]\n\n\ndef seqsearch(DS, IS):\n\n for index_1, element_1 in enumerate(DS):\n for index_2, element_2 in enumerate(IS):\n\n if (element_1 == element_2) and (index_1 == index_2):\n print(f\"Yes! Found at index ={index_1}\")\n return index_1\n print(\"No!\")\n return -1\n\n\nprint(seqsearch(Dlist, Ilist))\n\nHowever, there are more improvements you can make. zip() indeed is a better option, but slightly more complicated to understand.\nAlso, please note that return is not the same as print. You were not returning -1; you were printing it.\n"
] |
[
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):\n if DS[i] == IS[i]:\n print(f\"Yes! Found at index {i}\")\n else:\n print(f\"No not equal in {i} index\")\n\n\ndef seqsearch_with_list(DS, IS):\n \"\"\"this function save history of (equal index or not: as 1, -1)\"\"\"\n temp_list = []\n for i in range(len(DS) - 1):\n if DS[i] == IS[i]:\n temp_list.append(1)\n else:\n temp_list.append(-1)\n return temp_list\n\n\ndef seqsearch_with_list_dict(DS, IS):\n \"\"\"this function save history of (equal index or not: as 1, -1)\n as key, value (key== index, value==list item)\"\"\"\n temp_list = []\n for i in range(len(DS) - 1):\n if DS[i] == IS[i]:\n temp_list.append({i: 1})\n else:\n temp_list.append({i: -1})\n return temp_list\n\n\n# no need print(in function we used print)\nseqsearch_with_print(Dlist, Ilist)\n\"\"\"\nreturn of function: \n No not equal in 0 index\n No not equal in 1 index\n Yes! Found at index 2\n No not equal in 3 index\"\"\"\n\n# save history of search index in list\nprint(seqsearch_with_list(Dlist, Ilist))\n\"\"\"\nreturn of function with print:\n [-1, -1, 1, -1]\n\"\"\"\n# save history as dict key value\nprint(seqsearch_with_list_dict(Dlist, Ilist))\n\"\"\"\nreturn of function with print\n [{0: -1}, {1: -1}, {2: 1}, {3: -1}]\n\"\"\"\n\n\n"
] |
[
-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 want to add the atribute userTag to the custom User and I want to call the function generate_userTag, when an user is created (same for superuser). So I added the fuction to the create_user I already had "working"; at least I thought it would. Turns out, no changes I make in the create_user function are getting applyed or have any impact on the project. Its like the fuction never gets called. I added an ValueError that should raise erytime the function is getting called, but when I register a new user from the testsite, there is no error and the user gets created without the userTag.
Now the weird part: I tested to create a superuser and to my surprise it was working flawlessly. The superuser gets created, with the userTag. Everything fine.
So my question: What could cause Django to not call the custom create_user, when creating a user, but call the custom create_superuser, when creating a superuser?
thanks for helping
account/models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
userTag=generate_userTag(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
userTag = models.CharField(max_length=35, default="#00000")
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image)
hide_email = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.username
account/views.py
def register_view(request, *args, **kwargs):
user = request.user
if user.is_authenticated:
return HttpResponse("You are already authenticated as " + str(user.username))
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email').lower()
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
destination = kwargs.get("next")
if destination:
return redirect(destination)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'account/register.html', context)
settings.py
AUTH_USER_MODEL = 'account.Account'
A:
I fixed it by replacing
form.save()
with
account = get_user_model().objects.create_user(username=username, email=email, password=raw_password)
in the registration view.
Im still not sure what the problem was, so if sb can explain, id appreciate it.
A:
When you create a user with forms, it avoids the model manager. It calls model_instance.save() method instead of model.objects.create_user(). So you can add logic in model's save() method.
Maybe something like this could do the work:
class Account(AbstractBaseUser):
...
def save(self, *args, **kwargs):
# some logic, for example:
if self._state.adding and self.username:
self.userTag=generate_userTag(self.username)
# then super
super().save(*args, **kwargs)
But notice: the method user_create() calls save() at the end, so your logic can work twice, we need to anticipate it in advance.
I believe there is a better solution for this problem. Nevertheless, it helped me in my project.
|
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 the function generate_userTag, when an user is created (same for superuser). So I added the fuction to the create_user I already had "working"; at least I thought it would. Turns out, no changes I make in the create_user function are getting applyed or have any impact on the project. Its like the fuction never gets called. I added an ValueError that should raise erytime the function is getting called, but when I register a new user from the testsite, there is no error and the user gets created without the userTag.
Now the weird part: I tested to create a superuser and to my surprise it was working flawlessly. The superuser gets created, with the userTag. Everything fine.
So my question: What could cause Django to not call the custom create_user, when creating a user, but call the custom create_superuser, when creating a superuser?
thanks for helping
account/models.py
class MyAccountManager(BaseUserManager):
def create_user(self, email, username, password=None):
if not email:
raise ValueError('Users must have an email address')
if not username:
raise ValueError('Users must have a username')
user = self.model(
email=self.normalize_email(email),
username=username,
userTag=generate_userTag(username),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password):
user = self.create_user(
email=self.normalize_email(email),
password=password,
username=username,
)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class Account(AbstractBaseUser):
email = models.EmailField(verbose_name="email", max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
userTag = models.CharField(max_length=35, default="#00000")
date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True)
last_login = models.DateTimeField(verbose_name='last login', auto_now=True)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
profile_image = models.ImageField(max_length=255, upload_to=get_profile_image_filepath, null=True, blank=True, default=get_default_profile_image)
hide_email = models.BooleanField(default=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
objects = MyAccountManager()
def __str__(self):
return self.username
account/views.py
def register_view(request, *args, **kwargs):
user = request.user
if user.is_authenticated:
return HttpResponse("You are already authenticated as " + str(user.username))
context = {}
if request.POST:
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
email = form.cleaned_data.get('email').lower()
raw_password = form.cleaned_data.get('password1')
account = authenticate(email=email, password=raw_password)
login(request, account)
destination = kwargs.get("next")
if destination:
return redirect(destination)
return redirect('home')
else:
context['registration_form'] = form
else:
form = RegistrationForm()
context['registration_form'] = form
return render(request, 'account/register.html', context)
settings.py
AUTH_USER_MODEL = 'account.Account'
|
[
"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 model manager. It calls model_instance.save() method instead of model.objects.create_user(). So you can add logic in model's save() method.\nMaybe something like this could do the work:\nclass Account(AbstractBaseUser):\n ...\n def save(self, *args, **kwargs):\n # some logic, for example:\n if self._state.adding and self.username:\n self.userTag=generate_userTag(self.username)\n # then super\n super().save(*args, **kwargs)\n\nBut notice: the method user_create() calls save() at the end, so your logic can work twice, we need to anticipate it in advance.\n\nI believe there is a better solution for this problem. Nevertheless, it helped me in my project.\n"
] |
[
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 = requests.get(Web_url)
soup = BeautifulSoup(r.content, 'html.parser')
video_tags = soup.findAll('video')
for video_tag in video_tags:
video_url = video_tag.find("a")['href']
print(video_url)
But from what I can tell this may only work if the video is inside the html. I've tried alot of websites with this and nothing seems to show up. I've also tried:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
videos = driver.find_element(By.TAG_NAME, 'video')
for video in videos:
print(video.get_attribute('src'))
But this gave me the error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"video"} (Session info: headless chrome=107.0.5304.107)
I'm not sure what else to try. Alot of resources on google are for scraping Youtube videos specifically and half of those tell me to use a Youtube download module. I'd appreciate any help with this problem. Thanks
A:
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.
|
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 = BeautifulSoup(r.content, 'html.parser')
video_tags = soup.findAll('video')
for video_tag in video_tags:
video_url = video_tag.find("a")['href']
print(video_url)
But from what I can tell this may only work if the video is inside the html. I've tried alot of websites with this and nothing seems to show up. I've also tried:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
videos = driver.find_element(By.TAG_NAME, 'video')
for video in videos:
print(video.get_attribute('src'))
But this gave me the error:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"video"} (Session info: headless chrome=107.0.5304.107)
I'm not sure what else to try. Alot of resources on google are for scraping Youtube videos specifically and half of those tell me to use a Youtube download module. I'd appreciate any help with this problem. Thanks
|
[
"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': "Monday", 'Item_1': "Shoes", 'Item_2': "Tea", 'Item_3': "Book"},
{'Day': "Tuesday", 'Item_1':"Charger", 'Item_2': "Router",'Item_3': "Phone"},
{'Day': "Tuesday", 'Item_1':"Monitor", 'Item_2': "Toy", 'Item_3': "Chair"},
{'Day': "Friday", 'Item_1': "Shirt", 'Item_2': "TV", 'Item_3': "Desk"}])
df
Day Item_1 Item_2 Item_3
0 Monday Shirt Mug Pen
1 Monday Shoes Tea Book
2 Tuesday Charger Router Phone
3 Tuesday Monitor Toy Chair
4 Friday Shirt TV Desk
I want any row that has the same day to be merged like this
Day Item_1 Item_2 Item_3 Item_1_1 Item_2_1 Item_3_1
Monday Shirt Mug Pen Shoes Tea Book
Tuesday Charger Router Phone Monitor Toy Chair
Friday Shirt TV Desk NaN NaN NaN
is there a way to do it like this?
A:
I think you can use groupby here:
df = (df
.groupby('Day', sort=False)
.apply(lambda x: x.to_numpy())
.apply(np.concatenate)
.apply(pd.Series)
.reset_index(drop=True)
)
# fix col names
df.columns = ['Day'] + [f'Item_{x}' for x in range(1, df.shape[1])]
print(df)
Day Item_1 Item_2 Item_3 Item_4 Item_5 Item_6 Item_7
0 Monday Shirt Mug Pen Monday Shoes Tea Book
1 Tuesday Charger Router Phone Tuesday Monitor Toy Chair
2 Friday Shirt TV Desk NaN NaN NaN NaN
|
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': "Book"},
{'Day': "Tuesday", 'Item_1':"Charger", 'Item_2': "Router",'Item_3': "Phone"},
{'Day': "Tuesday", 'Item_1':"Monitor", 'Item_2': "Toy", 'Item_3': "Chair"},
{'Day': "Friday", 'Item_1': "Shirt", 'Item_2': "TV", 'Item_3': "Desk"}])
df
Day Item_1 Item_2 Item_3
0 Monday Shirt Mug Pen
1 Monday Shoes Tea Book
2 Tuesday Charger Router Phone
3 Tuesday Monitor Toy Chair
4 Friday Shirt TV Desk
I want any row that has the same day to be merged like this
Day Item_1 Item_2 Item_3 Item_1_1 Item_2_1 Item_3_1
Monday Shirt Mug Pen Shoes Tea Book
Tuesday Charger Router Phone Monitor Toy Chair
Friday Shirt TV Desk NaN NaN NaN
is there a way to do it like this?
|
[
"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\n Day Item_1 Item_2 Item_3 Item_4 Item_5 Item_6 Item_7\n0 Monday Shirt Mug Pen Monday Shoes Tea Book\n1 Tuesday Charger Router Phone Tuesday Monitor Toy Chair\n2 Friday Shirt TV Desk NaN NaN NaN NaN\n\n\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 tried to use the following code to loop over a tuple:
g = (())
for i in range(4):
b1 = (0,1) * (i)
g = (g) + (b1)
print(g)
However, the output is :
(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
Maybe this is a simple question but I am still beginner in python!
Any help!
A:
You could create a list, fill it up, then convert it to a tuple.
g = []
b1 = (0, 1)
for i in range(4):
g.append(b1)
g = tuple(g)
print(g)
There are cleaner ways to do it, but I wanted to adapt your code in order to help you understand what is happening.
A:
you can do this way
>>> result =tuple((0,1) for _ in range(4))
>>> result
((0, 1), (0, 1), (0, 1), (0, 1))
A:
A possible solution is this one:
g = tuple((0,1) for i in range(4))
|
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 tuple:
g = (())
for i in range(4):
b1 = (0,1) * (i)
g = (g) + (b1)
print(g)
However, the output is :
(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1)
Maybe this is a simple question but I am still beginner in python!
Any help!
|
[
"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((0,1) for _ in range(4))\n>>> result \n((0, 1), (0, 1), (0, 1), (0, 1))\n\n",
"A possible solution is this one:\ng = tuple((0,1) for i in range(4))\n"
] |
[
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 range(4)])\n\n"
] |
[
-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 == "a":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.6, 0.2, 0.2]).tolist()[0])
elif i == "b":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.6, 0.2]).tolist()[0])
elif i == "c":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.2, 0.6]).tolist()[0])
return sim
simulator(rdm_lst)
The output is one list, the problem I have is, that I do not know how to repete this function k time, having as a result list of lists, where the input of a simulator() will be the previous list, not the first one.
I tried, put:
return simulator(sim)
instead:
return sim
bun an error occurs.
Kindly help.
A:
It sounds like you are trying to implement a Markov chain.
You 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).
Px = {
'a': np.array([0.6, 0.2, 0.2]),
'b': np.array([0.2, 0.6, 0.2]),
'c': np.array([0.2, 0.2, 0.6]),
}
def simulator(xs, Px, k=1):
labels = list(Px)
return [
xs := [np.random.choice(labels, p=Px[x]) for x in xs]
for _ in range(k)
]
Example
np.random.seed(0)
>>> simulator(['a', 'b', 'c'], Px, k=10)
[['a', 'b', 'c'],
['a', 'b', 'c'],
['a', 'c', 'c'],
['a', 'c', 'c'],
['a', 'c', 'a'],
['a', 'a', 'c'],
['b', 'c', 'c'],
['b', 'c', 'c'],
['a', 'c', 'a'],
['c', 'c', 'a']]
Explanation
Given xs a list of initial states, we make a new list of states with the list comprehension: [np.random.choice(labels, p=Px[x]) for x in xs]. We then assign this back to xs (with the "walrus operator"), and iterate k times.
Fun stuff
The more usual definition of a finite state Markov chain is with the transition matrix:
P = np.c_[list(Px.values())]
>>> P
array([[0.6, 0.2, 0.2],
[0.2, 0.6, 0.2],
[0.2, 0.2, 0.6]])
(And you can map the labels separately, or use pandas with labels as index and columns).
What is the expected state distribution after two transitions given an initial state (1,0,0) ('a')?
>>> np.array((1,0,0)) @ P @ P
array([0.44, 0.28, 0.28])
What is the terminal expected state distribution given an initial state (1,0,0)?
# approximation of v @ P^inf
>>> np.array((1,0,0)) @ np.linalg.matrix_power(P, int(10**9))
array([0.33333334, 0.33333334, 0.33333334])
More precisely: what is the stationary distribution (a state distribution such that it is unchanged by transition P)?
w, v = np.linalg.eig(P.T) # left eigen system
k = np.argmax(w)
assert np.allclose(w[k], 1), 'no stationary state!'
e = v[:, k]
e /= e.sum()
>>> e
array([0.33333333, 0.33333333, 0.33333333])
>>> e @ P
array([0.33333333, 0.33333333, 0.33333333])
So, the expected distribution after a large number of transitions is 1/3 for each state, regardless of the initial state (because all states are reachable from any initial state).
|
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.6, 0.2, 0.2]).tolist()[0])
elif i == "b":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.6, 0.2]).tolist()[0])
elif i == "c":
sim.append(np.random.choice(rdm_lst, size=1, p=[0.2, 0.2, 0.6]).tolist()[0])
return sim
simulator(rdm_lst)
The output is one list, the problem I have is, that I do not know how to repete this function k time, having as a result list of lists, where the input of a simulator() will be the previous list, not the first one.
I tried, put:
return simulator(sim)
instead:
return sim
bun an error occurs.
Kindly help.
|
[
"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.2, 0.2]),\n 'b': np.array([0.2, 0.6, 0.2]),\n 'c': np.array([0.2, 0.2, 0.6]),\n}\n\ndef simulator(xs, Px, k=1):\n labels = list(Px)\n return [\n xs := [np.random.choice(labels, p=Px[x]) for x in xs]\n for _ in range(k)\n ]\n\nExample\nnp.random.seed(0)\n>>> simulator(['a', 'b', 'c'], Px, k=10)\n[['a', 'b', 'c'],\n ['a', 'b', 'c'],\n ['a', 'c', 'c'],\n ['a', 'c', 'c'],\n ['a', 'c', 'a'],\n ['a', 'a', 'c'],\n ['b', 'c', 'c'],\n ['b', 'c', 'c'],\n ['a', 'c', 'a'],\n ['c', 'c', 'a']]\n\nExplanation\nGiven xs a list of initial states, we make a new list of states with the list comprehension: [np.random.choice(labels, p=Px[x]) for x in xs]. We then assign this back to xs (with the \"walrus operator\"), and iterate k times.\nFun stuff\nThe more usual definition of a finite state Markov chain is with the transition matrix:\nP = np.c_[list(Px.values())]\n>>> P\narray([[0.6, 0.2, 0.2],\n [0.2, 0.6, 0.2],\n [0.2, 0.2, 0.6]])\n\n(And you can map the labels separately, or use pandas with labels as index and columns).\nWhat is the expected state distribution after two transitions given an initial state (1,0,0) ('a')?\n>>> np.array((1,0,0)) @ P @ P\narray([0.44, 0.28, 0.28])\n\nWhat is the terminal expected state distribution given an initial state (1,0,0)?\n# approximation of v @ P^inf\n>>> np.array((1,0,0)) @ np.linalg.matrix_power(P, int(10**9))\narray([0.33333334, 0.33333334, 0.33333334])\n\nMore precisely: what is the stationary distribution (a state distribution such that it is unchanged by transition P)?\nw, v = np.linalg.eig(P.T) # left eigen system\nk = np.argmax(w)\nassert np.allclose(w[k], 1), 'no stationary state!'\ne = v[:, k]\ne /= e.sum()\n>>> e\narray([0.33333333, 0.33333333, 0.33333333])\n\n>>> e @ P\narray([0.33333333, 0.33333333, 0.33333333])\n\nSo, the expected distribution after a large number of transitions is 1/3 for each state, regardless of the initial state (because all states are reachable from any initial state).\n"
] |
[
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 frontend view.
If the output result from FastAPI is string, I just want to display, as it is.
But if the output variable is dictionary, I want to iterate over it and print each key and value pair in a new line.
I have tried this piece of code but I am getting Internal Server error while calling the get method for printing dictionary output.
Backend
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
import uvicorn
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/hello")
async def form_get(request: Request):
output = "HELLO"
return templates.TemplateResponse('temp.html', context={'request': request, 'result': output})
@app.get("/dic")
async def form_post(request: Request):
test = {1: 56, 2: 45, 3: 46, 4: 35, 5: 69}
return templates.TemplateResponse('temp.html', context={'request': request, 'result': test})
if __name__ == "__main__":
uvicorn.run("temp:app", reload=True)
Frontend
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<p>
{% if result == "HELLO" %}
{{ result }}
{% else %}
{% for key, value in result.item() %}
{{ key }} : {{ value }}
{% endfor %}
{% endif %}
</p>
</body>
</html>
A:
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 should be:
{% for key, value in result.items() %}
{{ key }} : {{ value }}
{% endfor %}
Also, I would suggest you take a look at this answer to understand the difference between defining your endpoint with the normal def and async def.
|
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 just want to display, as it is.
But if the output variable is dictionary, I want to iterate over it and print each key and value pair in a new line.
I have tried this piece of code but I am getting Internal Server error while calling the get method for printing dictionary output.
Backend
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, Request
import uvicorn
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.get("/hello")
async def form_get(request: Request):
output = "HELLO"
return templates.TemplateResponse('temp.html', context={'request': request, 'result': output})
@app.get("/dic")
async def form_post(request: Request):
test = {1: 56, 2: 45, 3: 46, 4: 35, 5: 69}
return templates.TemplateResponse('temp.html', context={'request': request, 'result': test})
if __name__ == "__main__":
uvicorn.run("temp:app", reload=True)
Frontend
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<p>
{% if result == "HELLO" %}
{{ result }}
{% else %}
{% for key, value in result.item() %}
{{ key }} : {{ value }}
{% endfor %}
{% endif %}
</p>
</body>
</html>
|
[
"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 should be:\n{% for key, value in result.items() %}\n {{ key }} : {{ value }}\n{% endfor %}\n\nAlso, I would suggest you take a look at this answer to understand the difference between defining your endpoint with the normal def and async def.\n"
] |
[
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_index=True)
currency = models.CharField(max_length=255, unique=False, db_index=True)
user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150)
withdraw_address = models.CharField(max_length=255, unique=False, db_index=True)
withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15)
This is my models.py file.
currency = request.data['currency']
payload = jwt.decode(token, settings.SECRET_KEY)
user = User.objects.get(id=payload['user_id'])
timestamp = datetime.datetime.now()
timestamp = timestamp.timestamp()
withdraw_hash = hashlib.sha256()
withdraw_hash.update(str(timestamp).encode("utf-8"))
withdraw_hash = withdraw_hash.hexdigest()
username = user.username
currency_balance = GAME_CURRENCIES[request.data['currency']]
user_balance = getattr(user, currency_balance)
withdraw_address = request.data['withdraw_address']
withdraw_amount = request.data['withdraw_amount']
if user_balance < withdraw_amount:
return Response({
"message": "Not enough funds."
})
else:
# row format - hash timestamp username currency user_balance withdraw_address withdraw_amount
withdraw = WithdrawRequests()
withdraw.withdraw_hash = withdraw_hash,
withdraw.timestamp = datetime.datetime.now(),
withdraw.username = username,
withdraw.currency = currency,
withdraw.user_balance = user_balance,
withdraw.withdraw_address = withdraw_address,
withdraw.withdraw_amount = withdraw_amount
withdraw.save()
And here is the views.py file. Whatever I do the error is the following.
...
File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.']
As you can see with user_balance everything is fine and it's floating number.
Edited: added the whole view and the other model so that it will be more clear.
A:
“(0.011095555563904999,)” looks like string value, not float.
You should clean the withdraw_amount variable by removing braces, quotes and comma.
A:
You can use the following code in your views:
x=request.data["withdraw_amount"]
num_list="0123456789."
actual_str=""
for i,k in enumerate(x):
if k in num_list:
actual_str+=k
withdraw_amount=float(actual_str)
print(withdraw_amount)
So:
currency = request.data['currency']
payload = jwt.decode(token, settings.SECRET_KEY)
user = User.objects.get(id=payload['user_id'])
timestamp = datetime.datetime.now()
timestamp = timestamp.timestamp()
withdraw_hash = hashlib.sha256()
withdraw_hash.update(str(timestamp).encode("utf-8"))
withdraw_hash = withdraw_hash.hexdigest()
username = user.username
currency_balance = GAME_CURRENCIES[request.data['currency']]
user_balance = getattr(user, currency_balance)
withdraw_address = request.data['withdraw_address']
x=request.data["withdraw_amount"]
num_list="0123456789."
actual_str=""
for i,k in enumerate(x):
if k in num_list:
actual_str+=k
withdraw_amount=float(actual_str)
print(withdraw_amount)
if user_balance < withdraw_amount:
return Response({
"message": "Not enough funds."
})
else:
# row format - hash timestamp username currency user_balance withdraw_address withdraw_amount
withdraw = WithdrawRequests()
withdraw.withdraw_hash = withdraw_hash,
withdraw.timestamp = datetime.datetime.now(),
withdraw.username = username,
withdraw.currency = currency,
withdraw.user_balance = user_balance,
withdraw.withdraw_address = withdraw_address,
withdraw.withdraw_amount = withdraw_amount
withdraw.save()
A:
I didn't notice when writing the code but as @AbdulAzizBarkat mentioned the solution was very basic, to remove commas after several lines like so
withdraw.withdraw_hash = withdraw_hash,
withdraw.timestamp = datetime.datetime.now()
withdraw.username = username
withdraw.currency = currency
withdraw.user_balance = user_balance
withdraw.withdraw_address = withdraw_address
|
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_index=True)
user_balance = models.DecimalField(max_digits=300, default=0.0, decimal_places=150)
withdraw_address = models.CharField(max_length=255, unique=False, db_index=True)
withdraw_amount = models.DecimalField(max_digits=30, default=0.0, decimal_places=15)
This is my models.py file.
currency = request.data['currency']
payload = jwt.decode(token, settings.SECRET_KEY)
user = User.objects.get(id=payload['user_id'])
timestamp = datetime.datetime.now()
timestamp = timestamp.timestamp()
withdraw_hash = hashlib.sha256()
withdraw_hash.update(str(timestamp).encode("utf-8"))
withdraw_hash = withdraw_hash.hexdigest()
username = user.username
currency_balance = GAME_CURRENCIES[request.data['currency']]
user_balance = getattr(user, currency_balance)
withdraw_address = request.data['withdraw_address']
withdraw_amount = request.data['withdraw_amount']
if user_balance < withdraw_amount:
return Response({
"message": "Not enough funds."
})
else:
# row format - hash timestamp username currency user_balance withdraw_address withdraw_amount
withdraw = WithdrawRequests()
withdraw.withdraw_hash = withdraw_hash,
withdraw.timestamp = datetime.datetime.now(),
withdraw.username = username,
withdraw.currency = currency,
withdraw.user_balance = user_balance,
withdraw.withdraw_address = withdraw_address,
withdraw.withdraw_amount = withdraw_amount
withdraw.save()
And here is the views.py file. Whatever I do the error is the following.
...
File "C:\Users\Msi\cover_game\cover\lib\site-packages\django\db\models\fields\__init__.py", line 1554, in to_python
raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“(0.011095555563904999,)” value must be a decimal number.']
As you can see with user_balance everything is fine and it's floating number.
Edited: added the whole view and the other model so that it will be more clear.
|
[
"“(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 in num_list:\n actual_str+=k\nwithdraw_amount=float(actual_str)\nprint(withdraw_amount)\n\nSo:\ncurrency = request.data['currency']\n payload = jwt.decode(token, settings.SECRET_KEY)\n user = User.objects.get(id=payload['user_id'])\n timestamp = datetime.datetime.now()\n timestamp = timestamp.timestamp()\n withdraw_hash = hashlib.sha256()\n withdraw_hash.update(str(timestamp).encode(\"utf-8\"))\n withdraw_hash = withdraw_hash.hexdigest()\n username = user.username\n currency_balance = GAME_CURRENCIES[request.data['currency']]\n user_balance = getattr(user, currency_balance)\n withdraw_address = request.data['withdraw_address']\n \n x=request.data[\"withdraw_amount\"]\n num_list=\"0123456789.\"\n actual_str=\"\"\n for i,k in enumerate(x):\n if k in num_list:\n actual_str+=k\n \n withdraw_amount=float(actual_str)\n print(withdraw_amount)\n\n if user_balance < withdraw_amount:\n return Response({\n \"message\": \"Not enough funds.\"\n })\n else:\n # row format - hash timestamp username currency user_balance withdraw_address withdraw_amount\n withdraw = WithdrawRequests()\n withdraw.withdraw_hash = withdraw_hash,\n withdraw.timestamp = datetime.datetime.now(),\n withdraw.username = username,\n withdraw.currency = currency,\n withdraw.user_balance = user_balance,\n withdraw.withdraw_address = withdraw_address,\n withdraw.withdraw_amount = withdraw_amount\n\n withdraw.save()\n\n",
"I didn't notice when writing the code but as @AbdulAzizBarkat mentioned the solution was very basic, to remove commas after several lines like so\nwithdraw.withdraw_hash = withdraw_hash,\nwithdraw.timestamp = datetime.datetime.now()\nwithdraw.username = username\nwithdraw.currency = currency\nwithdraw.user_balance = user_balance\nwithdraw.withdraw_address = withdraw_address\n\n"
] |
[
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": "token_urin",
"auth_provider_x509_cert_url": "auth_provider_x509_cert_url",
"client_x509_cert_url": "client_x509_cert_url"
}
I tried encoding and decoding the JSON but it didn't work
I even tried using /// in place of " "
So I am using sheets-api. What I want to achieve is loading the path-for-json-file from .env variable
scope=['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(r"path-for-json-file", scope)
client = gspread.authorize(credentials)
A:
Assuming your JSON file is creds.json
creds.json
{
"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_x509_cert_url",
"client_x509_cert_url": "client_x509_cert_url"
}
main.py
import json
data = json.load(open('creds.json'))
f = open(".env", "x")
for key, value in data.items():
f.write(f"{key.upper()}={value}\n")
creds.env will be generated
TYPE=service_account
PROJECT_ID=project_id
PRIVATE_KEY_ID=private_key_id
PRIVATE_KEY=-----BEGIN PRIVATE KEY-----
CLIENT_EMAIL=email
CLIENT_ID=id
AUTH_URI=uri_auth
TOKEN_URI=token_urin
AUTH_PROVIDER_X509_CERT_URL=auth_provider_x509_cert_url
CLIENT_X509_CERT_URL=client_x509_cert_url
create_keyfile_dict() basically returns a dict called variable_keys
from dotenv import load_dotenv
load_dotenv()
def create_keyfile_dict():
variables_keys = {
"type": os.getenv("TYPE"),
"project_id": os.getenv("PROJECT_ID"),
"private_key_id": os.getenv("PRIVATE_KEY_ID"),
"private_key": os.getenv("PRIVATE_KEY"),
"client_email": os.getenv("CLIENT_EMAIL"),
"client_id": os.getenv("CLIENT_ID"),
"auth_uri": os.getenv("AUTH_URI"),
"token_uri": os.getenv("TOKEN_URI"),
"auth_provider_x509_cert_url": os.getenv("AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.getenv("CLIENT_X509_CERT_URL")
}
return variables_keys
scope=['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(create_keyfile_dict(), scope)
client = gspread.authorize(credentials)
A:
A simpler way using a single env variable
First encode your JSON in base-64 as follows:
import json
import base64
import os
from dotenv import load_dotenv, find_dotenv
service_key = {
"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_x509_cert_url",
"client_x509_cert_url": "client_x509_cert_url"
}
# convert json to a string
service_key = json.dumps(service_key)
# encode service key
encoded_service_key = base64.b64encode(service_key.encode('utf-8'))
print(encoded_service_key)
# b'many_characters_here'
In your .env file, add an environment variable SERVICE_ACCOUNT_KEY with the value of encoded_service_key:
SERVICE_ACCOUNT_KEY = b'a_long_string'
Now to convert the encoded string back to JSON:
# get the value of `SERVICE_ACCOUNT_KEY`environment variable
load_dotenv(find_dotenv())
encoded_key = os.getenv("SERVICE_ACCOUNT_KEY")
# remove the first two chars and the last char in the key
encoded_key = str(encoded_key)[2:-1]
# decode
original_service_key= json.loads(base64.b64decode(encoded_key).decode('utf-8'))
print(original_service_key['private_key_id'])
# private_key_id
# credentials = ServiceAccountCredentials.from_json_keyfile_name(
# original_service_key, scope)
# client = gspread.authorize(credentials)
|
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_x509_cert_url",
"client_x509_cert_url": "client_x509_cert_url"
}
I tried encoding and decoding the JSON but it didn't work
I even tried using /// in place of " "
So I am using sheets-api. What I want to achieve is loading the path-for-json-file from .env variable
scope=['https://spreadsheets.google.com/feeds',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file',
'https://www.googleapis.com/auth/spreadsheets'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(r"path-for-json-file", scope)
client = gspread.authorize(credentials)
|
[
"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_auth\",\n \"token_uri\": \"token_urin\",\n \"auth_provider_x509_cert_url\": \"auth_provider_x509_cert_url\",\n \"client_x509_cert_url\": \"client_x509_cert_url\"\n}\n\nmain.py\nimport json\n\ndata = json.load(open('creds.json'))\n\nf = open(\".env\", \"x\")\n\nfor key, value in data.items():\n f.write(f\"{key.upper()}={value}\\n\")\n\ncreds.env will be generated\nTYPE=service_account\nPROJECT_ID=project_id\nPRIVATE_KEY_ID=private_key_id\nPRIVATE_KEY=-----BEGIN PRIVATE KEY-----\n\nCLIENT_EMAIL=email\nCLIENT_ID=id\nAUTH_URI=uri_auth\nTOKEN_URI=token_urin\nAUTH_PROVIDER_X509_CERT_URL=auth_provider_x509_cert_url\nCLIENT_X509_CERT_URL=client_x509_cert_url\n\ncreate_keyfile_dict() basically returns a dict called variable_keys\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\ndef create_keyfile_dict():\n variables_keys = {\n \"type\": os.getenv(\"TYPE\"),\n \"project_id\": os.getenv(\"PROJECT_ID\"),\n \"private_key_id\": os.getenv(\"PRIVATE_KEY_ID\"),\n \"private_key\": os.getenv(\"PRIVATE_KEY\"),\n \"client_email\": os.getenv(\"CLIENT_EMAIL\"),\n \"client_id\": os.getenv(\"CLIENT_ID\"),\n \"auth_uri\": os.getenv(\"AUTH_URI\"),\n \"token_uri\": os.getenv(\"TOKEN_URI\"),\n \"auth_provider_x509_cert_url\": os.getenv(\"AUTH_PROVIDER_X509_CERT_URL\"),\n \"client_x509_cert_url\": os.getenv(\"CLIENT_X509_CERT_URL\")\n }\n return variables_keys\n\nscope=['https://spreadsheets.google.com/feeds',\n 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/drive.file',\n 'https://www.googleapis.com/auth/spreadsheets'\n ]\ncredentials = ServiceAccountCredentials.from_json_keyfile_name(create_keyfile_dict(), scope)\nclient = gspread.authorize(credentials)\n\n",
"A simpler way using a single env variable\n\nFirst encode your JSON in base-64 as follows:\n\nimport json\nimport base64\nimport os\nfrom dotenv import load_dotenv, find_dotenv\n\n\nservice_key = {\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_auth\",\n \"token_uri\": \"token_urin\",\n \"auth_provider_x509_cert_url\": \"auth_provider_x509_cert_url\",\n \"client_x509_cert_url\": \"client_x509_cert_url\"\n}\n\n# convert json to a string\nservice_key = json.dumps(service_key)\n\n# encode service key\nencoded_service_key = base64.b64encode(service_key.encode('utf-8'))\n\nprint(encoded_service_key)\n# b'many_characters_here'\n\n\nIn your .env file, add an environment variable SERVICE_ACCOUNT_KEY with the value of encoded_service_key:\n\nSERVICE_ACCOUNT_KEY = b'a_long_string'\n\n\nNow to convert the encoded string back to JSON:\n\n# get the value of `SERVICE_ACCOUNT_KEY`environment variable\nload_dotenv(find_dotenv())\nencoded_key = os.getenv(\"SERVICE_ACCOUNT_KEY\")\n\n# remove the first two chars and the last char in the key\nencoded_key = str(encoded_key)[2:-1]\n\n# decode\noriginal_service_key= json.loads(base64.b64decode(encoded_key).decode('utf-8'))\n\nprint(original_service_key['private_key_id'])\n# private_key_id\n\n# credentials = ServiceAccountCredentials.from_json_keyfile_name(\n# original_service_key, scope)\n# client = gspread.authorize(credentials)\n\n"
] |
[
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
}
var n = null
, r = 0
, o = window.crypto || window.msCrypto;
o && o.getRandomValues && Uint8Array && (n = o.getRandomValues(new Uint8Array(t)));
for (var i = [], a = 0; a < t; a++)
i.push(e().toString(16));
return i.join("")
}
A:
If i understand properly you want to write code in Python that can generate random tokens
This is written in Python3
import random as rd
def myToken(num):
#num is the length of tokens
myList = [1,2,3,4,5,6,7,8,9,0,"a","b","c","d","e","f"]
#you can add more characters to the list above
myStr = ""
randChars = (rd.choices(myList, weights=None,cum_weights=None,k=num))
for i in randChars:
myStr += str(i)
print(myStr)
return myStr
myToken(16)
|
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 = window.crypto || window.msCrypto;
o && o.getRandomValues && Uint8Array && (n = o.getRandomValues(new Uint8Array(t)));
for (var i = [], a = 0; a < t; a++)
i.push(e().toString(16));
return i.join("")
}
|
[
"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 above\n myStr = \"\"\n randChars = (rd.choices(myList, weights=None,cum_weights=None,k=num))\n for i in randChars:\n myStr += str(i)\n print(myStr)\n return myStr\n\nmyToken(16)\n\n"
] |
[
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_attribute("aria-hidden") == "true"]
counter = 1
for i in all_span:
print(counter)
print(i.text)
counter += 1
The problem is there are other spans on the same page that also have aria-hidden=true attribute, but not relevant and that messes up the index.
So I need to reach that span that contains name from one of its its parent divs but I don't know how.
Looking at documentation here: https://selenium-python.readthedocs.io/locating-elements.html# I cant seem to find how to target deeply neseted elements.
I need to get the name that is in span element.
The link
A:
The best way would be to use xpath. https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath
Let's say you have this:
<div id="this-div-contains-the-span-i-want">
<span aria-hidden="true">
<!--
...
//-->
</span>
</div>
Then, using xpath:
xpath = "//div[@id='this-div-contains-the-span-i-want']/span[@aria-hidden='true']"
span_i_want = driver.find_element(By.XPATH, xpath)
So, in your example, you could use:
xpath = "//a[@class='app-aware-link']/span[@dir='ltr']/span[@aria-hidden='true']"
span_i_want = driver.find_element(By.XPATH, xpath)
print(span_i_want.text)
No typos but
print(span_i_want) - returns [] empty array
|
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 all_span:
print(counter)
print(i.text)
counter += 1
The problem is there are other spans on the same page that also have aria-hidden=true attribute, but not relevant and that messes up the index.
So I need to reach that span that contains name from one of its its parent divs but I don't know how.
Looking at documentation here: https://selenium-python.readthedocs.io/locating-elements.html# I cant seem to find how to target deeply neseted elements.
I need to get the name that is in span element.
The link
|
[
"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='this-div-contains-the-span-i-want']/span[@aria-hidden='true']\"\nspan_i_want = driver.find_element(By.XPATH, xpath)\n\nSo, in your example, you could use:\nxpath = \"//a[@class='app-aware-link']/span[@dir='ltr']/span[@aria-hidden='true']\"\nspan_i_want = driver.find_element(By.XPATH, xpath)\nprint(span_i_want.text)\n\nNo typos but\nprint(span_i_want) - returns [] empty array\n\n"
] |
[
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, select_csv = select_csv()
This is the html,
<input type="button" value={{ subscription_csv }}>
The moment get into the html page, the variable gets called,
rather i wanted to call the variable only once the button is clicked.
Complete html,
<form action = "/select" method="POST">
<div class = "subscription_report">
<label for = "Month_From"> Month From </label>
<input type="month" id = "Month_From" name = "Month_From" />
<label for = "Month_To"> Month To </label>
<input type="month" id = "Month_To" name = "Month_To" />
<label for = "submit"></label>
<button type = "Submit">Submit</button>
</div>
</form>
<img src="static/images/subscription_monthly_report.jpg" width="1250" height="500" />
<table>
......
</table>
<form>
<button type="button" value = {{ select_csv }}>Download</button>
</form>
A:
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.
@app.route("/select/<clicked>", methods = ['POST', 'GET'])
def select_data(clicked=False):
return render_template('select.html', select_csv=select_csv() if clicked else None)
Now in html call the same route onclick:
href="{{url_for('app.select_data', clicked=1)}}"
|
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="button" value={{ subscription_csv }}>
The moment get into the html page, the variable gets called,
rather i wanted to call the variable only once the button is clicked.
Complete html,
<form action = "/select" method="POST">
<div class = "subscription_report">
<label for = "Month_From"> Month From </label>
<input type="month" id = "Month_From" name = "Month_From" />
<label for = "Month_To"> Month To </label>
<input type="month" id = "Month_To" name = "Month_To" />
<label for = "submit"></label>
<button type = "Submit">Submit</button>
</div>
</form>
<img src="static/images/subscription_monthly_report.jpg" width="1250" height="500" />
<table>
......
</table>
<form>
<button type="button" value = {{ select_csv }}>Download</button>
</form>
|
[
"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', select_csv=select_csv() if clicked else None)\n\nNow in html call the same route onclick:\nhref=\"{{url_for('app.select_data', clicked=1)}}\"\n\n"
] |
[
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',
on_delete=models.CASCADE
)
slug = models.SlugField(max_length=255, null=False, unique=True)
class Product(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
to_category = models.ForeignKey(Category, on_delete=models.SET_NULL,
blank=True, null=True,
)
slug = models.SlugField(max_length=255, null=False, unique=True)
I have created one category with slug "test". When I try to create new category with slug "test" I got warning message and it is Ok. But If I try to create product with slug "test" I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model?
A:
You can override the save method for each, and then check if the given slug already exists for a product or category.
def is_slug_unique(slug):
product_exists = Product.objects.filter(slug=slug).exists()
category_exists = Category.objects.filter(slug=slug).exists()
if product_exists or category_exists:
return False
else:
return True
class Category(models.Model)
...
def save(self, *args, **kwargs):
slug_unique = is_slug_unique(self.slug)
if not slug_unique:
# do something when the slug is not unique
else:
# do something when the slug is unique
super().save(*args, **kwargs)
class Product(models.Model)
...
def save(self, *args, **kwargs):
slug_unique = is_slug_unique(self.slug)
if not slug_unique:
# do something when the slug is not unique
else:
# do something when the slug is unique
super().save(*args, **kwargs)
A:
An idea might be to create a Slug model that stores all the slugs, optionally with a backreference to the object:
class Slug(models.Model):
slug = models.SlugField(max_length=255, primary_key=True)
Then the slugs in your models are ForeignKeys to that Slug model, and you check if such slug already exists:
from django.core.exceptions import ValidationError
class Product(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
to_category = models.ForeignKey(
Category, on_delete=models.SET_NULL, blank=True, null=True
)
slug = models.ForeignKey(Slug, on_delete=models.PROTECT)
def validate_slug(self):
if self.pk is not None and Slug.objects.filter(pk=self.slug_id).exclude(
product__pk=self.pk
):
raise ValidationError('The slug is already used.')
def clean(self, *args, **kwargs):
self.validate_slug()
return super().clean(*args, **kwargs)
def save(self, *args, **kwargs):
self.validate_slug()
return super().save(*args, **kwargs)
That being said, often overlapping slugs for different entity types are allowed.
|
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
)
slug = models.SlugField(max_length=255, null=False, unique=True)
class Product(models.Model):
name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])
to_category = models.ForeignKey(Category, on_delete=models.SET_NULL,
blank=True, null=True,
)
slug = models.SlugField(max_length=255, null=False, unique=True)
I have created one category with slug "test". When I try to create new category with slug "test" I got warning message and it is Ok. But If I try to create product with slug "test" I dont have warning and this is not good in my case. Is there a solution or method to validate slug field for uniqueness with Product and Category model?
|
[
"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_exists:\n return False\n else:\n return True\n\nclass Category(models.Model)\n ...\n\n def save(self, *args, **kwargs):\n slug_unique = is_slug_unique(self.slug)\n if not slug_unique:\n # do something when the slug is not unique\n else:\n # do something when the slug is unique\n super().save(*args, **kwargs)\n\nclass Product(models.Model)\n ...\n\n def save(self, *args, **kwargs):\n slug_unique = is_slug_unique(self.slug)\n if not slug_unique:\n # do something when the slug is not unique\n else:\n # do something when the slug is unique\n super().save(*args, **kwargs)\n\n\n\n",
"An idea might be to create a Slug model that stores all the slugs, optionally with a backreference to the object:\nclass Slug(models.Model):\n slug = models.SlugField(max_length=255, primary_key=True)\n\nThen the slugs in your models are ForeignKeys to that Slug model, and you check if such slug already exists:\nfrom django.core.exceptions import ValidationError\n\n\nclass Product(models.Model):\n name = models.CharField(max_length=255, validators=[MinLengthValidator(3)])\n to_category = models.ForeignKey(\n Category, on_delete=models.SET_NULL, blank=True, null=True\n )\n slug = models.ForeignKey(Slug, on_delete=models.PROTECT)\n\n def validate_slug(self):\n if self.pk is not None and Slug.objects.filter(pk=self.slug_id).exclude(\n product__pk=self.pk\n ):\n raise ValidationError('The slug is already used.')\n\n def clean(self, *args, **kwargs):\n self.validate_slug()\n return super().clean(*args, **kwargs)\n\n def save(self, *args, **kwargs):\n self.validate_slug()\n return super().save(*args, **kwargs)\nThat being said, often overlapping slugs for different entity types are allowed.\n"
] |
[
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 anaconda when I open VS code by the anaconda navigator.
I tried the to do the same thing as it automatically does with anaconda navigator :
Setting the same interpreter, the good language etc.
But when I try conda activate base (which is automatically written with anaconda and works), it gives me an error. It's not an huge problem, but it's just annoying to open anaconda everytime. What should I do ?
A:
make sure you have your anaconda path added to the windows path.
to add anaconda to the windows path follow this:
search "environment" in windows search.
click on "environment variables"
in the system variables area. look for "path" variable. select it and click on edit.
add the following (make sure the addresses are correct in your case first).
if you do not know where is anaconda installed on your PC. open cmd from anaconda navigator and write "where conda"
|
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 it automatically does with anaconda navigator :
Setting the same interpreter, the good language etc.
But when I try conda activate base (which is automatically written with anaconda and works), it gives me an error. It's not an huge problem, but it's just annoying to open anaconda everytime. What should I do ?
|
[
"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 (make sure the addresses are correct in your case first).\n\n\n\nif you do not know where is anaconda installed on your PC. open cmd from anaconda navigator and write \"where conda\"\n"
] |
[
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 look like:
>>> import numpy as np
>>> X = np.arange(10).reshape(5, 2)
>>> groups = np.array([0, 0, 0, 1, 1])
# Split up elements (rows) of `X` based on their element wise group
>>> np.array([X[groups==i].sum() for i in np.unique(groups)])
array([15, 30])
Above 15 is the sum of the first three rows of X, and 30 is the sum of the remaining two.
By "flexibly,” I just mean that we aren't focusing on one particular computation such as sum, count, maximum, etc, but rather passing any computation to the grouped arrays.
If not, is there a faster approach than the above?
A:
How about using scipy sparse matrix
import numpy as np
from scipy import sparse
import time
x_len = 500000
g_len = 100
X = np.arange(x_len * 2).reshape(x_len, 2)
groups = np.random.randint(0, g_len, x_len)
# original
s = time.time()
a = np.array([X[groups==i].sum() for i in np.unique(groups)])
print(time.time() - s)
# using scipy sparse matrix
s = time.time()
x_sum = X.sum(axis=1)
b = np.array(sparse.coo_matrix(
(
x_sum,
(groups, np.arange(len(x_sum)))
),
shape=(g_len, x_len)
).sum(axis=1)).ravel()
print(time.time() - s)
#compare
print(np.abs((a-b)).sum())
result on my PC
0.15915322303771973
0.012875080108642578
0
More than 10 times faster.
Update!
Let's benchmark answers of @Paul Panzer and @Daniel F. It is summation only benchmark.
import numpy as np
from scipy import sparse
import time
# by @Daniel F
def groupby_np(X, groups, axis = 0, uf = np.add, out = None, minlength = 0, identity = None):
if minlength < groups.max() + 1:
minlength = groups.max() + 1
if identity is None:
identity = uf.identity
i = list(range(X.ndim))
del i[axis]
i = tuple(i)
n = out is None
if n:
if identity is None: # fallback to loops over 0-index for identity
assert np.all(np.in1d(np.arange(minlength), groups)), "No valid identity for unassinged groups"
s = [slice(None)] * X.ndim
for i_ in i:
s[i_] = 0
out = np.array([uf.reduce(X[tuple(s)][groups == i]) for i in range(minlength)])
else:
out = np.full((minlength,), identity, dtype = X.dtype)
uf.at(out, groups, uf.reduce(X, i))
if n:
return out
x_len = 500000
g_len = 200
X = np.arange(x_len * 2).reshape(x_len, 2)
groups = np.random.randint(0, g_len, x_len)
print("original")
s = time.time()
a = np.array([X[groups==i].sum() for i in np.unique(groups)])
print(time.time() - s)
print("use scipy coo matrix")
s = time.time()
x_sum = X.sum(axis=1)
b = np.array(sparse.coo_matrix(
(
x_sum,
(groups, np.arange(len(x_sum)))
),
shape=(g_len, x_len)
).sum(axis=1)).ravel()
print(time.time() - s)
#compare
print(np.abs((a-b)).sum())
print("use scipy csr matrix @Daniel F")
s = time.time()
x_sum = X.sum(axis=1)
c = np.array(sparse.csr_matrix(
(
x_sum,
groups,
np.arange(len(groups)+1)
),
shape=(len(groups), g_len)
).sum(axis=0)).ravel()
print(time.time() - s)
#compare
print(np.abs((a-c)).sum())
print("use bincount @Paul Panzer @Daniel F")
s = time.time()
d = np.bincount(groups, X.sum(axis=1), g_len)
print(time.time() - s)
#compare
print(np.abs((a-d)).sum())
print("use ufunc @Daniel F")
s = time.time()
e = groupby_np(X, groups)
print(time.time() - s)
#compare
print(np.abs((a-e)).sum())
STDOUT
original
0.2882847785949707
use scipy coo matrix
0.012301445007324219
0
use scipy csr matrix @Daniel F
0.01046299934387207
0
use bincount @Paul Panzer @Daniel F
0.007468223571777344
0.0
use ufunc @Daniel F
0.04431319236755371
0
The winner is the bincount solution. But the csr matrix solution is also very interesting.
A:
@klim's sparse matrix solution would at first sight appear to be tied to summation. We can, however, use it in the general case by converting between the csr and csc formats:
Let's look at a small example:
>>> m, n = 3, 8
>>> idx = np.random.randint(0, m, (n,))
>>> data = np.arange(n)
>>>
>>> M = sparse.csr_matrix((data, idx, np.arange(n+1)), (n, m))
>>>
>>> idx
array([0, 2, 2, 1, 1, 2, 2, 0])
>>>
>>> M = M.tocsc()
>>>
>>> M.indptr, M.indices
(array([0, 2, 4, 8], dtype=int32), array([0, 7, 3, 4, 1, 2, 5, 6], dtype=int32))
As we can see after conversion the internal representation of the sparse matrix yields the indices grouped and sorted:
>>> groups = np.split(M.indices, M.indptr[1:-1])
>>> groups
[array([0, 7], dtype=int32), array([3, 4], dtype=int32), array([1, 2, 5, 6], dtype=int32)]
>>>
We could have obtained the same using a stable argsort:
>>> np.argsort(idx, kind='mergesort')
array([0, 7, 3, 4, 1, 2, 5, 6])
>>>
But sparse matrices are actually faster, even when we allow argsort to use a faster non-stable algorithm:
>>> m, n = 1000, 100000
>>> idx = np.random.randint(0, m, (n,))
>>> data = np.arange(n)
>>>
>>> timeit('sparse.csr_matrix((data, idx, np.arange(n+1)), (n, m)).tocsc()', **kwds)
2.250748165184632
>>> timeit('np.argsort(idx)', **kwds)
5.783584725111723
If we require argsort to keep groups sorted, the difference is even larger:
>>> timeit('np.argsort(idx, kind="mergesort")', **kwds)
10.507467685034499
A:
If you want a more flexible implementation of groupby that can group using any of numpy's ufuncs:
def groupby_np(X, groups, axis = 0, uf = np.add, out = None, minlength = 0, identity = None):
if minlength < groups.max() + 1:
minlength = groups.max() + 1
if identity is None:
identity = uf.identity
i = list(range(X.ndim))
del i[axis]
i = tuple(i)
n = out is None
if n:
if identity is None: # fallback to loops over 0-index for identity
assert np.all(np.in1d(np.arange(minlength), groups)), "No valid identity for unassinged groups"
s = [slice(None)] * X.ndim
for i_ in i:
s[i_] = 0
out = np.array([uf.reduce(X[tuple(s)][groups == i]) for i in range(minlength)])
else:
out = np.full((minlength,), identity, dtype = X.dtype)
uf.at(out, groups, uf.reduce(X, i))
if n:
return out
groupby_np(X, groups)
array([15, 30])
groupby_np(X, groups, uf = np.multiply)
array([ 0, 3024])
groupby_np(X, groups, uf = np.maximum)
array([5, 9])
groupby_np(X, groups, uf = np.minimum)
array([0, 6])
A:
There's probably a faster way than this (both of the operands are making copies right now), but:
np.bincount(np.broadcast_to(groups, X.T.shape).ravel(), X.T.ravel())
array([ 15., 30.])
A:
If you want to extend the answer to a ndarray, and still have a fast computation, you could extend the Daniel's solution :
x_len = 500000
g_len = 200
y_len = 2
X = np.arange(x_len * y_len).reshape(x_len, y_len)
groups = np.random.randint(0, g_len, x_len)
# original
a = np.array([X[groups==i].sum(axis=0) for i in np.unique(groups)])
# alternative
bins = [0] + list(np.bincount(groups, minlength=g_len).cumsum())
Z = np.argsort(groups)
d = np.array([X.take(Z[bins[i]:bins[i+1]],0).sum(axis=0) for i in range(g_len)])
It took about 30 ms (15ms for creating bins + 15ms for summing) instead of 280 ms on the original way in this example.
d.shape
>>> (1000, 2)
|
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
>>> X = np.arange(10).reshape(5, 2)
>>> groups = np.array([0, 0, 0, 1, 1])
# Split up elements (rows) of `X` based on their element wise group
>>> np.array([X[groups==i].sum() for i in np.unique(groups)])
array([15, 30])
Above 15 is the sum of the first three rows of X, and 30 is the sum of the remaining two.
By "flexibly,” I just mean that we aren't focusing on one particular computation such as sum, count, maximum, etc, but rather passing any computation to the grouped arrays.
If not, is there a faster approach than the above?
|
[
"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\nprint(time.time() - s)\n\n# using scipy sparse matrix\ns = time.time()\n\nx_sum = X.sum(axis=1)\nb = np.array(sparse.coo_matrix(\n (\n x_sum,\n (groups, np.arange(len(x_sum)))\n ),\n shape=(g_len, x_len)\n).sum(axis=1)).ravel()\n\nprint(time.time() - s)\n\n#compare\nprint(np.abs((a-b)).sum())\n\nresult on my PC\n0.15915322303771973\n0.012875080108642578\n0\n\nMore than 10 times faster.\n\nUpdate!\nLet's benchmark answers of @Paul Panzer and @Daniel F. It is summation only benchmark.\nimport numpy as np\nfrom scipy import sparse\nimport time\n\n# by @Daniel F\ndef groupby_np(X, groups, axis = 0, uf = np.add, out = None, minlength = 0, identity = None):\n if minlength < groups.max() + 1:\n minlength = groups.max() + 1\n if identity is None:\n identity = uf.identity\n i = list(range(X.ndim))\n del i[axis]\n i = tuple(i)\n n = out is None\n if n:\n if identity is None: # fallback to loops over 0-index for identity\n assert np.all(np.in1d(np.arange(minlength), groups)), \"No valid identity for unassinged groups\"\n s = [slice(None)] * X.ndim\n for i_ in i:\n s[i_] = 0\n out = np.array([uf.reduce(X[tuple(s)][groups == i]) for i in range(minlength)])\n else:\n out = np.full((minlength,), identity, dtype = X.dtype)\n uf.at(out, groups, uf.reduce(X, i))\n if n:\n return out\n\nx_len = 500000\ng_len = 200\n\nX = np.arange(x_len * 2).reshape(x_len, 2)\ngroups = np.random.randint(0, g_len, x_len)\n\nprint(\"original\")\ns = time.time()\n\na = np.array([X[groups==i].sum() for i in np.unique(groups)])\n\nprint(time.time() - s)\n\nprint(\"use scipy coo matrix\")\ns = time.time()\n\nx_sum = X.sum(axis=1)\nb = np.array(sparse.coo_matrix(\n (\n x_sum,\n (groups, np.arange(len(x_sum)))\n ),\n shape=(g_len, x_len)\n).sum(axis=1)).ravel()\n\nprint(time.time() - s)\n\n#compare\nprint(np.abs((a-b)).sum())\n\n\nprint(\"use scipy csr matrix @Daniel F\")\ns = time.time()\nx_sum = X.sum(axis=1)\nc = np.array(sparse.csr_matrix(\n (\n x_sum,\n groups,\n np.arange(len(groups)+1)\n ),\n shape=(len(groups), g_len)\n).sum(axis=0)).ravel()\n\nprint(time.time() - s)\n\n#compare\nprint(np.abs((a-c)).sum())\n\n\nprint(\"use bincount @Paul Panzer @Daniel F\")\ns = time.time()\nd = np.bincount(groups, X.sum(axis=1), g_len)\nprint(time.time() - s)\n\n#compare\nprint(np.abs((a-d)).sum())\n\nprint(\"use ufunc @Daniel F\")\ns = time.time()\ne = groupby_np(X, groups)\nprint(time.time() - s)\n\n#compare\nprint(np.abs((a-e)).sum())\n\nSTDOUT\noriginal\n0.2882847785949707\nuse scipy coo matrix\n0.012301445007324219\n0\nuse scipy csr matrix @Daniel F\n0.01046299934387207\n0\nuse bincount @Paul Panzer @Daniel F\n0.007468223571777344\n0.0\nuse ufunc @Daniel F\n0.04431319236755371\n0\n\nThe winner is the bincount solution. But the csr matrix solution is also very interesting.\n",
"@klim's sparse matrix solution would at first sight appear to be tied to summation. We can, however, use it in the general case by converting between the csr and csc formats:\nLet's look at a small example:\n>>> m, n = 3, 8 \n>>> idx = np.random.randint(0, m, (n,))\n>>> data = np.arange(n)\n>>> \n>>> M = sparse.csr_matrix((data, idx, np.arange(n+1)), (n, m)) \n>>> \n>>> idx \narray([0, 2, 2, 1, 1, 2, 2, 0]) \n>>> \n>>> M = M.tocsc()\n>>> \n>>> M.indptr, M.indices\n(array([0, 2, 4, 8], dtype=int32), array([0, 7, 3, 4, 1, 2, 5, 6], dtype=int32))\n\nAs we can see after conversion the internal representation of the sparse matrix yields the indices grouped and sorted:\n>>> groups = np.split(M.indices, M.indptr[1:-1])\n>>> groups\n[array([0, 7], dtype=int32), array([3, 4], dtype=int32), array([1, 2, 5, 6], dtype=int32)]\n>>> \n\nWe could have obtained the same using a stable argsort:\n>>> np.argsort(idx, kind='mergesort')\narray([0, 7, 3, 4, 1, 2, 5, 6])\n>>> \n\nBut sparse matrices are actually faster, even when we allow argsort to use a faster non-stable algorithm:\n>>> m, n = 1000, 100000\n>>> idx = np.random.randint(0, m, (n,))\n>>> data = np.arange(n)\n>>> \n>>> timeit('sparse.csr_matrix((data, idx, np.arange(n+1)), (n, m)).tocsc()', **kwds)\n2.250748165184632\n>>> timeit('np.argsort(idx)', **kwds)\n5.783584725111723\n\nIf we require argsort to keep groups sorted, the difference is even larger:\n>>> timeit('np.argsort(idx, kind=\"mergesort\")', **kwds)\n10.507467685034499\n\n",
"If you want a more flexible implementation of groupby that can group using any of numpy's ufuncs:\ndef groupby_np(X, groups, axis = 0, uf = np.add, out = None, minlength = 0, identity = None):\n if minlength < groups.max() + 1:\n minlength = groups.max() + 1\n if identity is None:\n identity = uf.identity\n i = list(range(X.ndim))\n del i[axis]\n i = tuple(i)\n n = out is None\n if n:\n if identity is None: # fallback to loops over 0-index for identity\n assert np.all(np.in1d(np.arange(minlength), groups)), \"No valid identity for unassinged groups\"\n s = [slice(None)] * X.ndim\n for i_ in i:\n s[i_] = 0\n out = np.array([uf.reduce(X[tuple(s)][groups == i]) for i in range(minlength)])\n else:\n out = np.full((minlength,), identity, dtype = X.dtype)\n uf.at(out, groups, uf.reduce(X, i))\n if n:\n return out\n\ngroupby_np(X, groups)\narray([15, 30])\n\ngroupby_np(X, groups, uf = np.multiply)\narray([ 0, 3024])\n\ngroupby_np(X, groups, uf = np.maximum)\narray([5, 9])\n\ngroupby_np(X, groups, uf = np.minimum)\narray([0, 6])\n\n",
"There's probably a faster way than this (both of the operands are making copies right now), but:\nnp.bincount(np.broadcast_to(groups, X.T.shape).ravel(), X.T.ravel())\n\narray([ 15., 30.])\n\n",
"If you want to extend the answer to a ndarray, and still have a fast computation, you could extend the Daniel's solution :\nx_len = 500000\ng_len = 200\ny_len = 2\n\nX = np.arange(x_len * y_len).reshape(x_len, y_len)\ngroups = np.random.randint(0, g_len, x_len)\n\n# original\na = np.array([X[groups==i].sum(axis=0) for i in np.unique(groups)])\n\n# alternative\nbins = [0] + list(np.bincount(groups, minlength=g_len).cumsum())\nZ = np.argsort(groups)\nd = np.array([X.take(Z[bins[i]:bins[i+1]],0).sum(axis=0) for i in range(g_len)])\n\nIt took about 30 ms (15ms for creating bins + 15ms for summing) instead of 280 ms on the original way in this example.\nd.shape\n>>> (1000, 2)\n\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, symbols and spaces.
If used this sliding window algorithm:
def lengthOfLongestSubstring(str):
# define base case
if (len(str) < 2): return len(str)
# define pointers and frequency counter
left = 0
right = 0
freqCounter = {} # used to store the character count
maxLen = 0
while (right < len(str)):
# adds the character count into the frequency counter dictionary
if (str[right] not in freqCounter):
freqCounter[str[right]] = 1
else:
freqCounter[str[right]] += 1
# print (freqCounter)
# runs the while loop if we have a key-value with value greater than 1.
# this means that there are repeated characters in the substring.
# we want to move the left pointer by 1 until that value decreases to 1 again. E.g., {'a':2,'b':1,'c':1} to {'a':1,'b':1,'c':1}
while (len(freqCounter) != right-left+1):
# while (freqCounter[str[right]] > 1): ## Time Limit Exceeded Error
print(len(freqCounter), freqCounter)
freqCounter[str[left]] -= 1
# remove the key-value if value is 0
if (freqCounter[str[left]] == 0):
del freqCounter[str[left]]
left += 1
maxLen = max(maxLen, right-left+1)
# print(freqCounter, maxLen)
right += 1
return maxLen
print(lengthOfLongestSubstring("abcabcbb")) # 3 'abc'
I got the error "Time Limit Exceeded" when I submitted with this while loop:
while (freqCounter[str[right]] > 1):
instead of
while (len(freqCounter) != right-left+1):
I thought the first is accessing an element in a dictionary, which has a time complexity of O(1). Not sure why this would be significantly slower than the second version. This seems to mean my approach is not optimal in either case. I thought sliding window would be the most efficient algorithm; did I implement it wrong?
A:
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:
Instead of counting the frequency of letters, you could store the index of where you last found the character. This allows you to update left in one go, avoiding a second loop where you had to decrease frequencies at each unit step.
Performing a del is really not necessary.
You can also use some more pythonic looping, like with enumerate
Here is the update of your code applying those ideas (the first one is the most important one):
class Solution(object):
def lengthOfLongestSubstring(self, s):
lastpos = {}
left = 0
maxLen = 0
for right, ch in enumerate(s):
if lastpos.setdefault(ch, -1) >= left:
left = lastpos[ch] + 1
else:
maxLen = max(maxLen, right - left + 1)
lastpos[ch] = right
return maxLen
Another boost can be achieved when you work with ASCII codes instead of characters, as then you can use a list instead of a dictionary. As the code challenge guarantees the characters are from a small set of basic characters, we don't need to take other character codes into consideration:
class Solution(object):
def lengthOfLongestSubstring(self, s):
lastpos = [-1] * 128
left = 0
maxLen = 0
for right, asc in enumerate(map(ord, s)):
if lastpos[asc] >= left:
left = lastpos[asc] + 1
else:
maxLen = max(maxLen, right - left + 1)
lastpos[asc] = right
return maxLen
When submitting this, it scored very well in terms of running time.
|
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 window algorithm:
def lengthOfLongestSubstring(str):
# define base case
if (len(str) < 2): return len(str)
# define pointers and frequency counter
left = 0
right = 0
freqCounter = {} # used to store the character count
maxLen = 0
while (right < len(str)):
# adds the character count into the frequency counter dictionary
if (str[right] not in freqCounter):
freqCounter[str[right]] = 1
else:
freqCounter[str[right]] += 1
# print (freqCounter)
# runs the while loop if we have a key-value with value greater than 1.
# this means that there are repeated characters in the substring.
# we want to move the left pointer by 1 until that value decreases to 1 again. E.g., {'a':2,'b':1,'c':1} to {'a':1,'b':1,'c':1}
while (len(freqCounter) != right-left+1):
# while (freqCounter[str[right]] > 1): ## Time Limit Exceeded Error
print(len(freqCounter), freqCounter)
freqCounter[str[left]] -= 1
# remove the key-value if value is 0
if (freqCounter[str[left]] == 0):
del freqCounter[str[left]]
left += 1
maxLen = max(maxLen, right-left+1)
# print(freqCounter, maxLen)
right += 1
return maxLen
print(lengthOfLongestSubstring("abcabcbb")) # 3 'abc'
I got the error "Time Limit Exceeded" when I submitted with this while loop:
while (freqCounter[str[right]] > 1):
instead of
while (len(freqCounter) != right-left+1):
I thought the first is accessing an element in a dictionary, which has a time complexity of O(1). Not sure why this would be significantly slower than the second version. This seems to mean my approach is not optimal in either case. I thought sliding window would be the most efficient algorithm; did I implement it wrong?
|
[
"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\nInstead of counting the frequency of letters, you could store the index of where you last found the character. This allows you to update left in one go, avoiding a second loop where you had to decrease frequencies at each unit step.\n\nPerforming a del is really not necessary.\n\nYou can also use some more pythonic looping, like with enumerate\n\n\nHere is the update of your code applying those ideas (the first one is the most important one):\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n lastpos = {}\n left = 0\n maxLen = 0\n\n for right, ch in enumerate(s):\n if lastpos.setdefault(ch, -1) >= left:\n left = lastpos[ch] + 1\n else:\n maxLen = max(maxLen, right - left + 1)\n lastpos[ch] = right\n return maxLen\n\nAnother boost can be achieved when you work with ASCII codes instead of characters, as then you can use a list instead of a dictionary. As the code challenge guarantees the characters are from a small set of basic characters, we don't need to take other character codes into consideration:\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n lastpos = [-1] * 128\n left = 0\n maxLen = 0\n\n for right, asc in enumerate(map(ord, s)):\n if lastpos[asc] >= left:\n left = lastpos[asc] + 1\n else:\n maxLen = max(maxLen, right - left + 1)\n lastpos[asc] = right\n return maxLen\n\nWhen submitting this, it scored very well in terms of running time.\n"
] |
[
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 !
here is the code
import wave
import os
global chosen_audio
def hide():
hide_menu()
global chosen_audio
message = input('Input message to be hidden: \n')
print('hiding message ... \n')
audio = wave.open(chosen_audio, 'rb')
frame_bytes = bytearray(list(audio.readframes(audio.getnframes())))
message = message + int((len(frame_bytes) - (len(message) * 8 * 8)) / 8) * '#'
bits = list(
map(int, ''.join([bin(ord(i)).lstrip('0b').rjust(8, '0') for i in message])))
for i, bit in enumerate(bits):
frame_bytes[i] = (frame_bytes[i] & 254) | bit # replace lsb
frames_modified = bytes(frame_bytes)
with wave.open('C:/Users/*****/PycharmProjects/steganography/modified_audio.wav', 'wb') as modified_audio:
modified_audio.setparams(audio.getparams())
modified_audio.writeframes(frames_modified)
print('message hidden ... \n')
modified_audio.close()
audio.close()
def reveal():
modified_audio = wave.open('C:/Users/*****/PycharmProjects/steganography/modified_audio.wav', 'rb')
frame_bytes = bytearray(list(modified_audio.readframes(modified_audio.getnframes())))
ls_bits = [frame_bytes[i] & 1 for i in range(len(frame_bytes))]
text = "".join(chr(int("".join(map(str, ls_bits[i:i + 8])), 2)) for i in range(0, len(ls_bits), 8))
message = text.split("###")[0]
modified_audio.close()
return message
def mode():
method = input(
' \n\t\t\tPLEASE, CHOOSE THE PROCEDURE! \n\n \tPRESS H FOR HIDING THE MESSAGE \t PRESS R FOR REVEALING THE MESSAGE FROM THE AUDIO\n')
if method == 'H' or method == 'h':
hide()
elif method == 'r' or method == 'R':
reveal()
else:
print('I don\'t think we have such a option')
mode()
def hide_menu():
global chosen_audio
chosen_option = ''
print(chosen_option)
chosen_option = ''
chosen_audio = ''
print(' \nCHOOSE YOUR AUDIO FILE! ')
chosen_option = (
input('\t press 1 & ENTER for your own audio path\n''\t press 2 & ENTER for default audio file\n'))
if chosen_option == '1':
file_path = input('Enter a file path: ')
if os.path.exists(file_path):
print('The path is okay, file exists!')
chosen_audio = file_path
else:
print('The specified file in this path does NOT exist')
hide_menu()
elif chosen_option == '2':
chosen_audio_option = input(
'\t press V & enter to use voice audio \t press S & enter to use sound audio\t press M & enter to use '
'song audio\n')
if chosen_audio_option == 'M' or chosen_audio_option == 'm':
chosen_audio = 'C:\\Users\\*****\\PycharmProjects\\steganography\\song_audio.wav'
elif chosen_audio_option == 'v' or chosen_audio_option == 'V':
chosen_audio = 'C:\\Users\\*****\\PycharmProjects\\steganography\\voice_audio.wav'
elif chosen_audio_option == 's' or chosen_audio_option == 'S':
chosen_audio = 'C:\\Users\\*****\\Desktop\\audio\\hracka_pes.wav'
else:
print('No such a option !')
hide_menu()
else:
print('I don\'t think we have such a option')
hide_menu()
def reveal_menu():
global chosen_audio
chosen_audio = ''
print(' \nCHOOSE YOUR AUDIO FILE! ')
chosen_option = int(
input('\t press 1 & ENTER for your own audio path\n''\t press 2 & ENTER for default audio file\n'))
if chosen_option == 1:
file_path = input('Enter a file path: ')
if os.path.exists(file_path):
print('The path is okay, file exists!')
chosen_audio = file_path
else:
print('The specified file in this path does NOT exist')
hide_menu()
elif chosen_option == 2:
pass
mode()
# menu()
# hide()
note - cannot use library for steganography
Hearing the noise in the modified_audio is the main problem
A:
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 frame, mono audio.) So when you changed the LSB of all the bytes, you were changing not only the LSB of each sample, but also a bit in the middle of it.
You should convert this to an array of samples, and then change the samples LSBs. You can use array for this:
import array
samples = array.array('h', frame_bytes) # signed 16-bit
# ... modify the samples ...
frames_modified = samples.tobytes()
Of course, it would be best if your code checked beforehand if you're dealing with signed shorts (sampsize==2) or unsigned bytes (sampsize==1), and then handle them accordingly. You might do something like:
samples = array.array('h' if sampsize == 2 else 'B', frame_bytes)
for i, bit in enumerate(bits):
samples[i] = samples[i] & -2 | bit
(I have not tested this much)
|
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():
hide_menu()
global chosen_audio
message = input('Input message to be hidden: \n')
print('hiding message ... \n')
audio = wave.open(chosen_audio, 'rb')
frame_bytes = bytearray(list(audio.readframes(audio.getnframes())))
message = message + int((len(frame_bytes) - (len(message) * 8 * 8)) / 8) * '#'
bits = list(
map(int, ''.join([bin(ord(i)).lstrip('0b').rjust(8, '0') for i in message])))
for i, bit in enumerate(bits):
frame_bytes[i] = (frame_bytes[i] & 254) | bit # replace lsb
frames_modified = bytes(frame_bytes)
with wave.open('C:/Users/*****/PycharmProjects/steganography/modified_audio.wav', 'wb') as modified_audio:
modified_audio.setparams(audio.getparams())
modified_audio.writeframes(frames_modified)
print('message hidden ... \n')
modified_audio.close()
audio.close()
def reveal():
modified_audio = wave.open('C:/Users/*****/PycharmProjects/steganography/modified_audio.wav', 'rb')
frame_bytes = bytearray(list(modified_audio.readframes(modified_audio.getnframes())))
ls_bits = [frame_bytes[i] & 1 for i in range(len(frame_bytes))]
text = "".join(chr(int("".join(map(str, ls_bits[i:i + 8])), 2)) for i in range(0, len(ls_bits), 8))
message = text.split("###")[0]
modified_audio.close()
return message
def mode():
method = input(
' \n\t\t\tPLEASE, CHOOSE THE PROCEDURE! \n\n \tPRESS H FOR HIDING THE MESSAGE \t PRESS R FOR REVEALING THE MESSAGE FROM THE AUDIO\n')
if method == 'H' or method == 'h':
hide()
elif method == 'r' or method == 'R':
reveal()
else:
print('I don\'t think we have such a option')
mode()
def hide_menu():
global chosen_audio
chosen_option = ''
print(chosen_option)
chosen_option = ''
chosen_audio = ''
print(' \nCHOOSE YOUR AUDIO FILE! ')
chosen_option = (
input('\t press 1 & ENTER for your own audio path\n''\t press 2 & ENTER for default audio file\n'))
if chosen_option == '1':
file_path = input('Enter a file path: ')
if os.path.exists(file_path):
print('The path is okay, file exists!')
chosen_audio = file_path
else:
print('The specified file in this path does NOT exist')
hide_menu()
elif chosen_option == '2':
chosen_audio_option = input(
'\t press V & enter to use voice audio \t press S & enter to use sound audio\t press M & enter to use '
'song audio\n')
if chosen_audio_option == 'M' or chosen_audio_option == 'm':
chosen_audio = 'C:\\Users\\*****\\PycharmProjects\\steganography\\song_audio.wav'
elif chosen_audio_option == 'v' or chosen_audio_option == 'V':
chosen_audio = 'C:\\Users\\*****\\PycharmProjects\\steganography\\voice_audio.wav'
elif chosen_audio_option == 's' or chosen_audio_option == 'S':
chosen_audio = 'C:\\Users\\*****\\Desktop\\audio\\hracka_pes.wav'
else:
print('No such a option !')
hide_menu()
else:
print('I don\'t think we have such a option')
hide_menu()
def reveal_menu():
global chosen_audio
chosen_audio = ''
print(' \nCHOOSE YOUR AUDIO FILE! ')
chosen_option = int(
input('\t press 1 & ENTER for your own audio path\n''\t press 2 & ENTER for default audio file\n'))
if chosen_option == 1:
file_path = input('Enter a file path: ')
if os.path.exists(file_path):
print('The path is okay, file exists!')
chosen_audio = file_path
else:
print('The specified file in this path does NOT exist')
hide_menu()
elif chosen_option == 2:
pass
mode()
# menu()
# hide()
note - cannot use library for steganography
Hearing the noise in the modified_audio is the main problem
|
[
"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 frame, mono audio.) So when you changed the LSB of all the bytes, you were changing not only the LSB of each sample, but also a bit in the middle of it.\nYou should convert this to an array of samples, and then change the samples LSBs. You can use array for this:\nimport array\n\nsamples = array.array('h', frame_bytes) # signed 16-bit\n# ... modify the samples ...\nframes_modified = samples.tobytes()\n\nOf course, it would be best if your code checked beforehand if you're dealing with signed shorts (sampsize==2) or unsigned bytes (sampsize==1), and then handle them accordingly. You might do something like:\nsamples = array.array('h' if sampsize == 2 else 'B', frame_bytes)\nfor i, bit in enumerate(bits):\n samples[i] = samples[i] & -2 | bit\n\n(I have not tested this much)\n"
] |
[
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 content.
I've found multiple posts with a similar problem:
PyQt5 Custom Widget Opens in Another Window
Custom widget does not appear on Main Window
PyQt5 Custom Widget Opens in Another Window
And even a FAQ on this specific problem: https://www.pythonguis.com/faq/pyqt-widgets-appearing-as-separate-windows/
But I haven't been able to figure out why my code doesn't work. My aim is to obtain a result as shown below on the left, but instead I'm getting a result as shown on the right:
My code is the following (can be copied and run as it is):
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QGridLayout
from PyQt5.QtGui import QFont
import sys
import pyqtgraph as pg
class CustomWidget_1(QWidget):
def __init__(self):
super(CustomWidget_1, self).__init__()
self.channels = [1, 2, 3, 4, 5, 6, 7, 8]
self.win = pg.GraphicsLayoutWidget(title='Plot', size=(800, 600))
self.plots = list()
self.curves = list()
for i in range(len(self.channels)):
p = self.win.addPlot(row=i, col=0)
p.showAxis('left', False)
p.setMenuEnabled('left', False)
p.showAxis('bottom', False)
p.setMenuEnabled('bottom', False)
self.plots.append(p)
curve = p.plot()
self.curves.append(curve)
self.win.show()
print('CustomWidget_1 initialized.')
class CustomWidget_2(QWidget):
def __init__(self, labelnames):
super(CustomWidget_2, self).__init__()
self.grid = QGridLayout()
self.labelnames = labelnames
self.qlabels = []
for label in self.labelnames:
labelBox = QLabel(label)
labelBox.setFont(QFont('Arial', 16))
labelBox.setStyleSheet('border: 2px solid black;')
labelBox.setAlignment(Qt.AlignCenter)
self.qlabels.append(labelBox)
index = self.labelnames.index(label)
q, r = divmod(index, 6)
self.grid.addWidget(labelBox, q, r)
print('CustomWidget_2 initialized.')
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.labelnames = ['label 1', 'label 2', 'label 3']
self.CustomWidget_1 = CustomWidget_1()
self.CustomWidget_1.setParent(self)
self.CustomWidget_1.show()
self.CustomWidget_2 = CustomWidget_2(self.labelnames)
self.CustomWidget_2.setParent(self)
self.CustomWidget_2.show()
self.mainLayout = QVBoxLayout()
self.mainLayout.addWidget(self.CustomWidget_1)
self.mainLayout.addWidget(self.CustomWidget_2)
self.setLayout(self.mainLayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
predictVisualizer = MainWindow()
sys.exit(app.exec())
Could anyone tell me what I'm doing wrong and how I could fix it? Any pointers towards tutorials and/or templates would be greatly appreciated as well! Thanks!
A:
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/
This is the code I have edited, you can can refer:
import sys
from PyQt5.QtCore import QSize,Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget,QGridLayout,QVBoxLayout,QLabel,QHBoxLayout
from PyQt5.QtGui import QPalette, QColor
class CustomWidget_1(QWidget):
def __init__(self,color):
super(CustomWidget_1, self).__init__()
self.setAutoFillBackground(True)
layout = QGridLayout()
self.setLayout(layout)
self.setFixedSize(QSize(400,300))
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
class CustomWidget_2(QWidget):
def __init__(self,color):
super(CustomWidget_2, self).__init__()
self.setAutoFillBackground(True)
layout = QHBoxLayout()
self.setLayout(layout)
self.setFixedSize(QSize(400,134))
layout.setContentsMargins(70,0,0,0)
palette = self.palette()
palette.setColor(QPalette.Window, QColor(color))
self.setPalette(palette)
Label1 = QLabel()
Label1.setText('abc')
Label2 = QLabel()
Label2.setText('sad')
Label3 = QLabel()
Label3.setText('qv')
layout.addWidget(Label1)
layout.addWidget(Label2)
layout.addWidget(Label3)
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowTitle("My App")
layout = QVBoxLayout()
layout.addWidget(CustomWidget_1("blue"))
layout.addWidget(CustomWidget_2("red"))
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
|
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 in Another Window
Custom widget does not appear on Main Window
PyQt5 Custom Widget Opens in Another Window
And even a FAQ on this specific problem: https://www.pythonguis.com/faq/pyqt-widgets-appearing-as-separate-windows/
But I haven't been able to figure out why my code doesn't work. My aim is to obtain a result as shown below on the left, but instead I'm getting a result as shown on the right:
My code is the following (can be copied and run as it is):
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QGridLayout
from PyQt5.QtGui import QFont
import sys
import pyqtgraph as pg
class CustomWidget_1(QWidget):
def __init__(self):
super(CustomWidget_1, self).__init__()
self.channels = [1, 2, 3, 4, 5, 6, 7, 8]
self.win = pg.GraphicsLayoutWidget(title='Plot', size=(800, 600))
self.plots = list()
self.curves = list()
for i in range(len(self.channels)):
p = self.win.addPlot(row=i, col=0)
p.showAxis('left', False)
p.setMenuEnabled('left', False)
p.showAxis('bottom', False)
p.setMenuEnabled('bottom', False)
self.plots.append(p)
curve = p.plot()
self.curves.append(curve)
self.win.show()
print('CustomWidget_1 initialized.')
class CustomWidget_2(QWidget):
def __init__(self, labelnames):
super(CustomWidget_2, self).__init__()
self.grid = QGridLayout()
self.labelnames = labelnames
self.qlabels = []
for label in self.labelnames:
labelBox = QLabel(label)
labelBox.setFont(QFont('Arial', 16))
labelBox.setStyleSheet('border: 2px solid black;')
labelBox.setAlignment(Qt.AlignCenter)
self.qlabels.append(labelBox)
index = self.labelnames.index(label)
q, r = divmod(index, 6)
self.grid.addWidget(labelBox, q, r)
print('CustomWidget_2 initialized.')
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.labelnames = ['label 1', 'label 2', 'label 3']
self.CustomWidget_1 = CustomWidget_1()
self.CustomWidget_1.setParent(self)
self.CustomWidget_1.show()
self.CustomWidget_2 = CustomWidget_2(self.labelnames)
self.CustomWidget_2.setParent(self)
self.CustomWidget_2.show()
self.mainLayout = QVBoxLayout()
self.mainLayout.addWidget(self.CustomWidget_1)
self.mainLayout.addWidget(self.CustomWidget_2)
self.setLayout(self.mainLayout)
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
predictVisualizer = MainWindow()
sys.exit(app.exec())
Could anyone tell me what I'm doing wrong and how I could fix it? Any pointers towards tutorials and/or templates would be greatly appreciated as well! Thanks!
|
[
"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 import QSize,Qt\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QWidget,QGridLayout,QVBoxLayout,QLabel,QHBoxLayout\nfrom PyQt5.QtGui import QPalette, QColor\n\nclass CustomWidget_1(QWidget):\n def __init__(self,color):\n super(CustomWidget_1, self).__init__()\n \n self.setAutoFillBackground(True)\n layout = QGridLayout()\n self.setLayout(layout)\n self.setFixedSize(QSize(400,300))\n \n palette = self.palette()\n palette.setColor(QPalette.Window, QColor(color))\n self.setPalette(palette) \n\nclass CustomWidget_2(QWidget):\n def __init__(self,color):\n super(CustomWidget_2, self).__init__()\n \n self.setAutoFillBackground(True)\n layout = QHBoxLayout()\n self.setLayout(layout)\n self.setFixedSize(QSize(400,134))\n layout.setContentsMargins(70,0,0,0)\n \n palette = self.palette()\n palette.setColor(QPalette.Window, QColor(color))\n self.setPalette(palette)\n \n Label1 = QLabel()\n Label1.setText('abc')\n Label2 = QLabel()\n Label2.setText('sad')\n Label3 = QLabel()\n Label3.setText('qv') \n layout.addWidget(Label1)\n layout.addWidget(Label2)\n layout.addWidget(Label3)\n \nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.setWindowTitle(\"My App\")\n\n layout = QVBoxLayout()\n \n layout.addWidget(CustomWidget_1(\"blue\"))\n layout.addWidget(CustomWidget_2(\"red\"))\n\n widget = QWidget()\n widget.setLayout(layout)\n self.setCentralWidget(widget)\n\napp = QApplication(sys.argv)\n\nwindow = MainWindow()\nwindow.show()\n\napp.exec()\n\n"
] |
[
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': 45.23,
'AAPL': 612.78,
'IBM': 205.55,
'HPQ': 37.20,
'FB': 10.75
}
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: prices[key] for key in prices.keys() & tech_names}
A:
The & operator is used to create the intersection of the sets of keys in prices and the values in tech_names.
See the section on Dictionary view objects:
Keys 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 collections.abc.Set are available (for example, ==, <, or ^).
Also see the intersection methods section for set:
set & other & ...
Return a new set with elements common to the set and all others.
So, the code only defines the prices for the symbols listed in the tech_names set.
Another way of spelling this would be to use a if filter in the dictionary comprehension; this has the advantage that you can then use prices.items() and access the symbol and the price at the same time:
p2 = {symbol: price for symbol, price in prices.values() if symbol in tech_names}
|
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,
'FB': 10.75
}
tech_names = {'AAPL', 'IBM', 'HPQ', 'MSFT'}
p2 = {key: prices[key] for key in prices.keys() & tech_names}
|
[
"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 collections.abc.Set are available (for example, ==, <, or ^).\n\nAlso see the intersection methods section for set:\n\n set & other & ...\n\nReturn a new set with elements common to the set and all others.\n\nSo, the code only defines the prices for the symbols listed in the tech_names set.\nAnother way of spelling this would be to use a if filter in the dictionary comprehension; this has the advantage that you can then use prices.items() and access the symbol and the price at the same time:\np2 = {symbol: price for symbol, price in prices.values() if symbol in tech_names}\n\n"
] |
[
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.csv')
filepath.parent.mkdir(parents=True, exist_ok=True)
forecast_productos.to_csv(filepath)
import yagmail
user = 'xxxxx@gmail.com' # my email
app_password = 'XXXXXXXXXX' # a token for gmail
to = 'xxxxx@gmail.com' # to any email
subject = 'Forecast GDU Tesis'
forecast_productos.fillna(0)
content = [forecast_productos.to_csv(filepath)]
with yagmail.SMTP(user, app_password) as yag:
yag.send(to, subject, content)
print('Sent email successfully')
AttributeError: 'NoneType' object has no attribute 'replace'
The Problem is not the code itself, because if I repalce the content with a string it works. The Problem is sending a file. It's worked for me sending a table (the dataframe) to my email, but I only want a csv file or an html file as well.
I did the filna(0) because I read that the replace problem May arise if you have Nan valúes. I don't know if it's correct in my case.
Does anyone knows? Thanks
A:
I solved my problem.I was missing the parameter of attachments in yag.send. Now it has worked correctly sending a csv file:
yag.send(to, subject, contents, attachments='my path in my desktop/forecast_productos.csv')
If you don't specify the attachments, it will send a table and not a file.
|
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, exist_ok=True)
forecast_productos.to_csv(filepath)
import yagmail
user = 'xxxxx@gmail.com' # my email
app_password = 'XXXXXXXXXX' # a token for gmail
to = 'xxxxx@gmail.com' # to any email
subject = 'Forecast GDU Tesis'
forecast_productos.fillna(0)
content = [forecast_productos.to_csv(filepath)]
with yagmail.SMTP(user, app_password) as yag:
yag.send(to, subject, content)
print('Sent email successfully')
AttributeError: 'NoneType' object has no attribute 'replace'
The Problem is not the code itself, because if I repalce the content with a string it works. The Problem is sending a file. It's worked for me sending a table (the dataframe) to my email, but I only want a csv file or an html file as well.
I did the filna(0) because I read that the replace problem May arise if you have Nan valúes. I don't know if it's correct in my case.
Does anyone knows? Thanks
|
[
"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().interpolate()
I have a dataset that has hourly time intervals with each hour containing its own temperature reading. For the purposes of my project, I want to change the time intervals to quarter-hour time intervals and have the temperatures be the estimated in-between readings from base hour 1 to base hour 2.
For example, I have this:
date_time. Temperature [°C]
2018-01-01 01:00:00 10
2018-01-01 02:00:00. 12
and I would like a new dataframe that looks like this:
date_time. Temperature [°C]
2018-01-01 01:00:00 10
2018-01-01 01:15:00. 10.5
2018-01-01 01:30:00 11
2018-01-01 01:45:00. 11.5
2018-01-01 02:00:00. 12
How would I go about adding in the extra three rows per hour and then having each be the base temperature plus 25%, 50%, and 75%, respectively of the total hourly temperature change?
I know I can use this to insert a row into the dataframe at a given location:
df_test.loc[1.5] = ['time', 'temp_old', 'temp_new']
df_test = df_test.sort_index().reset_index(drop=True)
Do I need a loop that starts at row 1 of the original dataframe, takes the temperature difference from row 1 to row 0, divides it by 4 and then adds that value to a new inserted column in the dataframe, that value * 2 to a second inserted column in the dataframe, and that value *3 to a third inserted column in the dataframe?
Does anyone have any idea of what that may look like?
I tried the above (inserting into the dataframe and then manually adding in the values), but I'm not sure how I would use this for the entire 5000+ row dataset.
A:
# create the dataframe
index = pd.date_range('1/1/2018', periods=9, freq='H')
series = pd.Series([10,12,13,14,14,15,14,13,12], index=index)
df = pd.DataFrame(series, columns=['Temp'])
# shift the Temp column
df['shifted'] = df.Temp.shift(-1)
df.shifted = df.shifted.ffill()
# a function to fill the values in between intervals
def fill_temp(x):
diff = x.shifted - x.Temp
if x['index'].minute == 15:
temp = x.Temp + .25 * diff
elif x['index'].minute == 30:
temp = x.Temp + .5 * diff
elif x['index'].minute == 45:
temp = x.Temp + .75 * diff
else:
temp = x.Temp
return temp
# do a resample
df_resampled = df.resample('.25H').ffill().reset_index()
# apply the function to modify the values and add them into a new column
df_resampled['Temperature'] = df_resampled.apply(fill_temp, axis=1)
df_resampled = df_resampled[['index','Temperature']].rename(columns={'index':'DateTime'})
print (df_resampled)
|
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 the purposes of my project, I want to change the time intervals to quarter-hour time intervals and have the temperatures be the estimated in-between readings from base hour 1 to base hour 2.
For example, I have this:
date_time. Temperature [°C]
2018-01-01 01:00:00 10
2018-01-01 02:00:00. 12
and I would like a new dataframe that looks like this:
date_time. Temperature [°C]
2018-01-01 01:00:00 10
2018-01-01 01:15:00. 10.5
2018-01-01 01:30:00 11
2018-01-01 01:45:00. 11.5
2018-01-01 02:00:00. 12
How would I go about adding in the extra three rows per hour and then having each be the base temperature plus 25%, 50%, and 75%, respectively of the total hourly temperature change?
I know I can use this to insert a row into the dataframe at a given location:
df_test.loc[1.5] = ['time', 'temp_old', 'temp_new']
df_test = df_test.sort_index().reset_index(drop=True)
Do I need a loop that starts at row 1 of the original dataframe, takes the temperature difference from row 1 to row 0, divides it by 4 and then adds that value to a new inserted column in the dataframe, that value * 2 to a second inserted column in the dataframe, and that value *3 to a third inserted column in the dataframe?
Does anyone have any idea of what that may look like?
I tried the above (inserting into the dataframe and then manually adding in the values), but I'm not sure how I would use this for the entire 5000+ row dataset.
|
[
"# 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 between intervals\ndef fill_temp(x):\n diff = x.shifted - x.Temp\n if x['index'].minute == 15:\n temp = x.Temp + .25 * diff\n elif x['index'].minute == 30:\n temp = x.Temp + .5 * diff\n elif x['index'].minute == 45:\n temp = x.Temp + .75 * diff\n else:\n temp = x.Temp\n return temp\n\n# do a resample\ndf_resampled = df.resample('.25H').ffill().reset_index()\n# apply the function to modify the values and add them into a new column\ndf_resampled['Temperature'] = df_resampled.apply(fill_temp, axis=1)\n\ndf_resampled = df_resampled[['index','Temperature']].rename(columns={'index':'DateTime'})\nprint (df_resampled)\n\n"
] |
[
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(x=x,y=y)
plt.xlabel(Label)
plt.ylabel('Gr')
plt.title('title')
plt.show()
and here is the code for what its taking in to plot:
def numericalConvergence(Position, Velocity, Charge, Mass, dt, B):
gyroArr = np.array([])
gyroArr2 = np.array([])
gyroArr3 = np.array([])
dtArr = np.array([])
fieldArr = np.array([])
chargeArr = np.array([])
dtArr = np.append(dtArr, [dt])
gyroArr = np.append(gyroArr, [6.324555320336759])
gyroArr2 = np.append(gyroArr, [6.324555320336759])
gyroArr3 = np.append(gyroArr, [6.324555320336759])
fieldArr = np.append(fieldArr, [[0,0,1]])
chargeArr = np.append(chargeArr, Charge)
# Incrementing timestep
for i in range (10):
start = time.time()
dt = dt + 0.1000
print('\n'"Timestep", i+1)
trv= pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr = np.append(gyroArr, [Gr])
dtArr = np.append(dtArr, [dt])
end = time.time()
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt) # need to fix this## Predicted gyro radius
Label = "DT"
plotNumericalConvergence(dtArr, gyroArr, Label)
# Incrementing magnetic field
for i in range (10):
start = time.time()
dt=0.001
B = [float(x) + 1 for x in B] # Increments all numbers in magnetic field array by 1
print('\n'"Magnetic Field", i+1)
trv = pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr2 = np.append(gyroArr2, [Gr])
fieldArr = np.append(fieldArr, [[B]])
end = time.time()
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt)
Label = "Magnetic Field"
plotNumericalConvergence(fieldArr, gyroArr2, Label)
# Incrementing Charge
for i in range (10):
start = time.time()
B = [0,0,1]
Charge = Charge + 0.1
print('\n'"Charge", i+1)
# add label param for y, new gr array each loop - no 2nd method needed
trv=pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr3 = np.append(gyroArr3, [Gr])
chargeArr = np.append(chargeArr, [Charge])
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt)
Label = "Charge"
print(gyroArr3)
print(chargeArr)
plotNumericalConvergence(chargeArr, gyroArr3, Label)
The plot works for the dt, but not the magnetic field or charge. I've seen stuff on here about reshaping arrays and something along the lines of [:,0] kind of thing but I am really stuck and don't understand Python 100% lol. Thanks!
EDIT - Full traceback:
ValueError Traceback (most recent call last)
Cell In [249], line 25
22 bf=EvalB(ipos)
23 vel = Boris(qom,ivel,ef,bf,-0.5*dt)
---> 25 numericalConvergence(ipos, vel, Charge, Mass, dt, B)
26 #print(gyroArr)
27 #print(dtArr)
28 #plotNumericalConvergence(dtArr, gyroArr)
Cell In [246], line 101, in numericalConvergence(Position, Velocity, Charge, Mass, dt, B)
99 print(gyroArr3)
100 print(chargeArr)
--> 101 plotNumericalConvergence(chargeArr, gyroArr3, Label)
103 return gyroArr, dtArr
Cell In [247], line 8, in plotNumericalConvergence(paramArr, GrArr, Label)
5 x = paramArr
6 y = GrArr
----> 8 plt.scatter(x=x,y=y)
10 plt.xlabel(Label)
11 plt.ylabel('Gr')
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/pyplot.py:2790, in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, data, **kwargs)
2785 @_copy_docstring_and_deprecators(Axes.scatter)
2786 def scatter(
2787 x, y, s=None, c=None, marker=None, cmap=None, norm=None,
2788 vmin=None, vmax=None, alpha=None, linewidths=None, *,
2789 edgecolors=None, plotnonfinite=False, data=None, **kwargs):
-> 2790 __ret = gca().scatter(
2791 x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
2792 vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
2793 edgecolors=edgecolors, plotnonfinite=plotnonfinite,
2794 **({"data": data} if data is not None else {}), **kwargs)
2795 sci(__ret)
2796 return __ret
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/__init__.py:1423, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1420 @functools.wraps(func)
1421 def inner(ax, *args, data=None, **kwargs):
1422 if data is None:
-> 1423 return func(ax, *map(sanitize_sequence, args), **kwargs)
1425 bound = new_sig.bind(ax, *args, **kwargs)
1426 auto_label = (bound.arguments.get(label_namer)
1427 or bound.kwargs.get(label_namer))
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/axes/_axes.py:4520, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
4518 y = np.ma.ravel(y)
4519 if x.size != y.size:
-> 4520 raise ValueError("x and y must be the same size")
4522 if s is None:
4523 s = (20 if mpl.rcParams['_internal.classic_mode'] else
4524 mpl.rcParams['lines.markersize'] ** 2.0)
ValueError: x and y must be the same size
A:
When you generate a scatter plot, then both x and y should be
1-D arrays of equal size.
Check sizes of x and y, their sizes are probably different.
|
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.title('title')
plt.show()
and here is the code for what its taking in to plot:
def numericalConvergence(Position, Velocity, Charge, Mass, dt, B):
gyroArr = np.array([])
gyroArr2 = np.array([])
gyroArr3 = np.array([])
dtArr = np.array([])
fieldArr = np.array([])
chargeArr = np.array([])
dtArr = np.append(dtArr, [dt])
gyroArr = np.append(gyroArr, [6.324555320336759])
gyroArr2 = np.append(gyroArr, [6.324555320336759])
gyroArr3 = np.append(gyroArr, [6.324555320336759])
fieldArr = np.append(fieldArr, [[0,0,1]])
chargeArr = np.append(chargeArr, Charge)
# Incrementing timestep
for i in range (10):
start = time.time()
dt = dt + 0.1000
print('\n'"Timestep", i+1)
trv= pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr = np.append(gyroArr, [Gr])
dtArr = np.append(dtArr, [dt])
end = time.time()
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt) # need to fix this## Predicted gyro radius
Label = "DT"
plotNumericalConvergence(dtArr, gyroArr, Label)
# Incrementing magnetic field
for i in range (10):
start = time.time()
dt=0.001
B = [float(x) + 1 for x in B] # Increments all numbers in magnetic field array by 1
print('\n'"Magnetic Field", i+1)
trv = pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr2 = np.append(gyroArr2, [Gr])
fieldArr = np.append(fieldArr, [[B]])
end = time.time()
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt)
Label = "Magnetic Field"
plotNumericalConvergence(fieldArr, gyroArr2, Label)
# Incrementing Charge
for i in range (10):
start = time.time()
B = [0,0,1]
Charge = Charge + 0.1
print('\n'"Charge", i+1)
# add label param for y, new gr array each loop - no 2nd method needed
trv=pstep(qom,Position,Velocity,0.0,dt,N_t)
Gr = MeasuredGr(trv)
PredGr = GyroRadius(Position, Velocity, Charge, Mass, dt, B)
gyroArr3 = np.append(gyroArr3, [Gr])
chargeArr = np.append(chargeArr, [Charge])
print("Predicted gyro radius =", PredGr)
print("Measured gryo radius =", Gr)
print("Timestep =", dt)
print("Magnetic Field =", B)
print("Charge =", Charge)
print("nt =",(end - start)/dt)
Label = "Charge"
print(gyroArr3)
print(chargeArr)
plotNumericalConvergence(chargeArr, gyroArr3, Label)
The plot works for the dt, but not the magnetic field or charge. I've seen stuff on here about reshaping arrays and something along the lines of [:,0] kind of thing but I am really stuck and don't understand Python 100% lol. Thanks!
EDIT - Full traceback:
ValueError Traceback (most recent call last)
Cell In [249], line 25
22 bf=EvalB(ipos)
23 vel = Boris(qom,ivel,ef,bf,-0.5*dt)
---> 25 numericalConvergence(ipos, vel, Charge, Mass, dt, B)
26 #print(gyroArr)
27 #print(dtArr)
28 #plotNumericalConvergence(dtArr, gyroArr)
Cell In [246], line 101, in numericalConvergence(Position, Velocity, Charge, Mass, dt, B)
99 print(gyroArr3)
100 print(chargeArr)
--> 101 plotNumericalConvergence(chargeArr, gyroArr3, Label)
103 return gyroArr, dtArr
Cell In [247], line 8, in plotNumericalConvergence(paramArr, GrArr, Label)
5 x = paramArr
6 y = GrArr
----> 8 plt.scatter(x=x,y=y)
10 plt.xlabel(Label)
11 plt.ylabel('Gr')
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/pyplot.py:2790, in scatter(x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, data, **kwargs)
2785 @_copy_docstring_and_deprecators(Axes.scatter)
2786 def scatter(
2787 x, y, s=None, c=None, marker=None, cmap=None, norm=None,
2788 vmin=None, vmax=None, alpha=None, linewidths=None, *,
2789 edgecolors=None, plotnonfinite=False, data=None, **kwargs):
-> 2790 __ret = gca().scatter(
2791 x, y, s=s, c=c, marker=marker, cmap=cmap, norm=norm,
2792 vmin=vmin, vmax=vmax, alpha=alpha, linewidths=linewidths,
2793 edgecolors=edgecolors, plotnonfinite=plotnonfinite,
2794 **({"data": data} if data is not None else {}), **kwargs)
2795 sci(__ret)
2796 return __ret
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/__init__.py:1423, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
1420 @functools.wraps(func)
1421 def inner(ax, *args, data=None, **kwargs):
1422 if data is None:
-> 1423 return func(ax, *map(sanitize_sequence, args), **kwargs)
1425 bound = new_sig.bind(ax, *args, **kwargs)
1426 auto_label = (bound.arguments.get(label_namer)
1427 or bound.kwargs.get(label_namer))
File /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/matplotlib/axes/_axes.py:4520, in Axes.scatter(self, x, y, s, c, marker, cmap, norm, vmin, vmax, alpha, linewidths, edgecolors, plotnonfinite, **kwargs)
4518 y = np.ma.ravel(y)
4519 if x.size != y.size:
-> 4520 raise ValueError("x and y must be the same size")
4522 if s is None:
4523 s = (20 if mpl.rcParams['_internal.classic_mode'] else
4524 mpl.rcParams['lines.markersize'] ** 2.0)
ValueError: x and y must be the same size
|
[
"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 the m & n arrays, I then need to calculate the various Q_bar terms which should output an array for each term as well.
theta = np.array([0, 25, -80, 90, 20])
m = math.cos(math.radians(theta)) #[deg]
n = math.sin(math.radians(theta)) #[deg]
Q_bar11 = Q11*(m**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(n**4)
Q_bar12 = (Q11 + Q22 - 4*Q66)*(n**2)*(m**2) + Q12*(n**4 + m**4)
Q_bar16 = (Q11 - Q12 - 2*Q66)*n*(m**3) + (Q12 - Q22 + 2*Q66)*(n**3)*m
Q_bar22 = Q11*(n**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(m**4)
Q_bar26 = (Q11 - Q12 - 2*Q66)*(n**3)*m + (Q12 - Q22 + 2*Q66)*n*(m**3)
Q_bar66 = (Q11 + Q22 - 2*Q12 - 2*Q66)*(n**2)*(m**2) + Q66*(n**4 + m**4)
I've seen similar posts about passing arrays through functions however I have not been successful in implementing them, any help would be much appreciated!
A:
Instead of passing a list into function. pass each values differently might help!
deg = np.array([math.cos(math.radians(theta[i])) for i in range(5)])
news = pd.Series(theta,deg)
Sorry, I couldn't understand the q part exactly but if you explain it deeper than I'll try to help it too
|
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 various Q_bar terms which should output an array for each term as well.
theta = np.array([0, 25, -80, 90, 20])
m = math.cos(math.radians(theta)) #[deg]
n = math.sin(math.radians(theta)) #[deg]
Q_bar11 = Q11*(m**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(n**4)
Q_bar12 = (Q11 + Q22 - 4*Q66)*(n**2)*(m**2) + Q12*(n**4 + m**4)
Q_bar16 = (Q11 - Q12 - 2*Q66)*n*(m**3) + (Q12 - Q22 + 2*Q66)*(n**3)*m
Q_bar22 = Q11*(n**4) + 2*(Q12 + 2*Q66)*(n**2)*(m**2) + Q22*(m**4)
Q_bar26 = (Q11 - Q12 - 2*Q66)*(n**3)*m + (Q12 - Q22 + 2*Q66)*n*(m**3)
Q_bar66 = (Q11 + Q22 - 2*Q12 - 2*Q66)*(n**2)*(m**2) + Q66*(n**4 + m**4)
I've seen similar posts about passing arrays through functions however I have not been successful in implementing them, any help would be much appreciated!
|
[
"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_character_string(a, b) -> "return True if characters match":
"""check if two characters match"""
if len(a) == 0:
return True
elif len(b) == 0:
return False
else:
if a == '.':
return True
else:
if a == b:
return True
else:
return False
def meta_question_result(temp):
if len(temp) >= 2:
if temp[1] == '?':
k_1 = temp.replace(temp[0: 2], '') # no char
k_2 = temp.replace(temp[1], '') # char
return k_1, k_2
def check_pair_by_pair(template, check_string) -> "Strings are of Equal length! " \
"return True if lines are identical":
"""check if two strings match symbol by symbol. template may be less than string, the opposite
is False"""
if not template: # exit from recursion
return True
if not check_string: # exit from recursion
return False
if meta_question_result(template):
t_1, t_2 = meta_question_result(template)
if single_character_string(t_1[0], check_string[0]):
return check_pair_by_pair(t_1[1:], check_string[1:])
if single_character_string(t_2[0], check_string[0]):
return check_pair_by_pair(t_2[1:], check_string[1:])
else:
return False
elif single_character_string(template[0], check_string[0]):
return check_pair_by_pair(template[1:], check_string[1:])
else:
return False
reg, st = input().split("|")
print(check_pair_by_pair(reg, st))
reg = "co?lou?r"
st = "colour"
gives True as expected,
reg = "co?lou?r"
st = "clor"
gives True as expected,
but...
reg = "co?lou?r"
st = "color"
gives False. I expected True.
A:
Found the bag.
Replace method replaces all instances of '?'. So the second '?' was replaced also and program didn't see it.
I should add an argument 'count' to replace method that is equal to 1.
k_1 = temp.replace(temp[0: 2], '', 1) # no char
|
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":
"""check if two characters match"""
if len(a) == 0:
return True
elif len(b) == 0:
return False
else:
if a == '.':
return True
else:
if a == b:
return True
else:
return False
def meta_question_result(temp):
if len(temp) >= 2:
if temp[1] == '?':
k_1 = temp.replace(temp[0: 2], '') # no char
k_2 = temp.replace(temp[1], '') # char
return k_1, k_2
def check_pair_by_pair(template, check_string) -> "Strings are of Equal length! " \
"return True if lines are identical":
"""check if two strings match symbol by symbol. template may be less than string, the opposite
is False"""
if not template: # exit from recursion
return True
if not check_string: # exit from recursion
return False
if meta_question_result(template):
t_1, t_2 = meta_question_result(template)
if single_character_string(t_1[0], check_string[0]):
return check_pair_by_pair(t_1[1:], check_string[1:])
if single_character_string(t_2[0], check_string[0]):
return check_pair_by_pair(t_2[1:], check_string[1:])
else:
return False
elif single_character_string(template[0], check_string[0]):
return check_pair_by_pair(template[1:], check_string[1:])
else:
return False
reg, st = input().split("|")
print(check_pair_by_pair(reg, st))
reg = "co?lou?r"
st = "colour"
gives True as expected,
reg = "co?lou?r"
st = "clor"
gives True as expected,
but...
reg = "co?lou?r"
st = "color"
gives False. I expected True.
|
[
"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"
"location": {
"lat": 37.1
"long": 127.2
}
},
{
"number":1
"address":"doh"
"location": {
"lat": 37.2
"long": 127.1
}
},....
]
I have found out I could use either multiindex on pandas or pandas->dict->json.
However, the problem is that 'number' and 'address' does not belong to any hierarchy, only 'lat' and 'long' does. Then should I use pandas->dict->json method? Below method failed.
df.groupby('number','address',('location')[['long', 'lat']]).apply(lambda g: g.to_dict(orient='record')).to_dict()
A:
Assuming df is a variable that stores your dataframe.
import json
df['location'] = df.apply(lambda x:{'lat':x['lat'],'long':x['long']}, axis=1)
df = df.drop(['lat','long'], axis=1)
print(json.dumps(df.to_dict(orient='records'), indent=2))
Output:
[
{
"number": 1,
"address": "blah",
"location": {
"lat": 37.1,
"long": 127.2
}
},
{
"number": 2,
"address": "doh",
"location": {
"lat": 37.2,
"long": 127.1
}
}
]
|
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
}
},
{
"number":1
"address":"doh"
"location": {
"lat": 37.2
"long": 127.1
}
},....
]
I have found out I could use either multiindex on pandas or pandas->dict->json.
However, the problem is that 'number' and 'address' does not belong to any hierarchy, only 'lat' and 'long' does. Then should I use pandas->dict->json method? Below method failed.
df.groupby('number','address',('location')[['long', 'lat']]).apply(lambda g: g.to_dict(orient='record')).to_dict()
|
[
"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 \"location\": {\n \"lat\": 37.1,\n \"long\": 127.2\n }\n },\n {\n \"number\": 2,\n \"address\": \"doh\",\n \"location\": {\n \"lat\": 37.2,\n \"long\": 127.1\n }\n }\n]\n\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, y: x*y, [1,2,3,4,5,6])
720
Python 2: use reduce:
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
For compatible with 2 and 3 use pip install six, then:
>>> from six.moves import reduce
>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
720
A:
You can use:
import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)
See reduce and operator.mul documentations for an explanation.
You need the import functools line in Python 3+.
A:
I would use the numpy.prod to perform the task. See below.
import numpy as np
mylist = [1, 2, 3, 4, 5, 6]
result = np.prod(np.array(mylist))
A:
If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop
product = 1 # Don't use 0 here, otherwise, you'll get zero
# because anything times zero will be zero.
list = [1, 2, 3]
for x in list:
product *= x
A:
Starting Python 3.8, a .prod function has been included to the math module in the standard library:
math.prod(iterable, *, start=1)
The method returns the product of a start value (default: 1) times an iterable of numbers:
import math
math.prod([1, 2, 3, 4, 5, 6])
>>> 720
If the iterable is empty, this will produce 1 (or the start value, if provided).
A:
Here's some performance measurements from my machine. Relevant in case this is performed for small inputs in a long-running loop:
import functools, operator, timeit
import numpy as np
def multiply_numpy(iterable):
return np.prod(np.array(iterable))
def multiply_functools(iterable):
return functools.reduce(operator.mul, iterable)
def multiply_manual(iterable):
prod = 1
for x in iterable:
prod *= x
return prod
sizesToTest = [5, 10, 100, 1000, 10000, 100000]
for size in sizesToTest:
data = [1] * size
timerNumpy = timeit.Timer(lambda: multiply_numpy(data))
timerFunctools = timeit.Timer(lambda: multiply_functools(data))
timerManual = timeit.Timer(lambda: multiply_manual(data))
repeats = int(5e6 / size)
resultNumpy = timerNumpy.timeit(repeats)
resultFunctools = timerFunctools.timeit(repeats)
resultManual = timerManual.timeit(repeats)
print(f'Input size: {size:>7d} Repeats: {repeats:>8d} Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')
Results:
Input size: 5 Repeats: 1000000 Numpy: 4.670, Functools: 0.586, Manual: 0.459
Input size: 10 Repeats: 500000 Numpy: 2.443, Functools: 0.401, Manual: 0.321
Input size: 100 Repeats: 50000 Numpy: 0.505, Functools: 0.220, Manual: 0.197
Input size: 1000 Repeats: 5000 Numpy: 0.303, Functools: 0.207, Manual: 0.185
Input size: 10000 Repeats: 500 Numpy: 0.265, Functools: 0.194, Manual: 0.187
Input size: 100000 Repeats: 50 Numpy: 0.266, Functools: 0.198, Manual: 0.185
You can see that Numpy is quite a bit slower on smaller inputs, since it allocates an array before multiplication is performed. Also, watch out for the overflow in Numpy.
A:
I personally like this for a function that multiplies all elements of a generic list together:
def multiply(n):
total = 1
for i in range(0, len(n)):
total *= n[i]
print total
It's compact, uses simple things (a variable and a for loop), and feels intuitive to me (it looks like how I'd think of the problem, just take one, multiply it, then multiply by the next, and so on!)
A:
Numpy has the prod() function that returns the product of a list, or in this case since it's numpy, it's the product of an array over a given axis:
import numpy
a = [1,2,3,4,5,6]
b = numpy.prod(a)
...or else you can just import numpy.prod():
from numpy import prod
a = [1,2,3,4,5,6]
b = prod(a)
A:
nums = str(tuple([1,2,3]))
mul_nums = nums.replace(',','*')
print(eval(mul_nums))
A:
The simple way is:
import numpy as np
np.exp(np.log(your_array).sum())
A:
Just wanna add a Python 3.10 One-liner answer:
def multiply(l):
return [b := 1, [b := b * a for a in l]][-1][-1]
print(multiply([2, 3, 8, 10]))
output:
480
explanation:
[b := 1, is for defining a temporary variable
...[b := b * a for a in l] is for iterating over the list and multiplying b by every element
...[-1][-1] is because the final list is [b, [b * l[0], b * l[1], ..., b * l[-1]]]. and so the element in the final position is the multiplication of all of the elements in the list.
A:
Found this question today but I noticed that it does not have the case where there are None's in the list. So, the complete solution would be:
from functools import reduce
a = [None, 1, 2, 3, None, 4]
print(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))
In the case of addition, we have:
print(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))
A:
I would like this in following way:
def product_list(p):
total =1 #critical step works for all list
for i in p:
total=total*i # this will ensure that each elements are multiplied by itself
return total
print product_list([2,3,4,2]) #should print 48
A:
This is my code:
def product_list(list_of_numbers):
xxx = 1
for x in list_of_numbers:
xxx = xxx*x
return xxx
print(product_list([1,2,3,4]))
result : ('1*1*2*3*4', 24)
A:
How about using recursion?
def multiply(lst):
if len(lst) > 1:
return multiply(lst[:-1])* lst[-1]
else:
return lst[0]
A:
My solution:
def multiply(numbers):
a = 1
for num in numbers:
a *= num
return a
A:
There are many good answers in this thread. If you want to do multiply a list in actual production I recommend using standard numpy or math packages.
If you are just looking for a quick and dirty solution and you don’t want to import anything you can do this:
l = [1,2,3,4,5,6]
def list_multiply(l):
return eval('*'.join(map(str,l)))
print(list_multiply(l))
#Output: 720
map(str,l) converts each element in the list to a string. join combines each element into one string separated by the * symbol. eval converts the string back into a function that can evaluated.
Warning: eval is considered dangerous to use, especially if the program accepts user input because a user can potentially inject any function into the code and compromise your system.
|
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,2,3,4,5,6])\n720\n\n",
"You can use:\nimport operator\nimport functools\nfunctools.reduce(operator.mul, [1,2,3,4,5,6], 1)\n\nSee reduce and operator.mul documentations for an explanation.\nYou need the import functools line in Python 3+.\n",
"I would use the numpy.prod to perform the task. See below.\nimport numpy as np\nmylist = [1, 2, 3, 4, 5, 6] \nresult = np.prod(np.array(mylist)) \n\n",
"If you want to avoid importing anything and avoid more complex areas of Python, you can use a simple for loop\nproduct = 1 # Don't use 0 here, otherwise, you'll get zero \n # because anything times zero will be zero.\nlist = [1, 2, 3]\nfor x in list:\n product *= x\n\n",
"Starting Python 3.8, a .prod function has been included to the math module in the standard library:\n\nmath.prod(iterable, *, start=1)\n\nThe method returns the product of a start value (default: 1) times an iterable of numbers:\nimport math\nmath.prod([1, 2, 3, 4, 5, 6])\n\n>>> 720\n\nIf the iterable is empty, this will produce 1 (or the start value, if provided).\n",
"Here's some performance measurements from my machine. Relevant in case this is performed for small inputs in a long-running loop:\nimport functools, operator, timeit\nimport numpy as np\n\ndef multiply_numpy(iterable):\n return np.prod(np.array(iterable))\n\ndef multiply_functools(iterable):\n return functools.reduce(operator.mul, iterable)\n\ndef multiply_manual(iterable):\n prod = 1\n for x in iterable:\n prod *= x\n\n return prod\n\nsizesToTest = [5, 10, 100, 1000, 10000, 100000]\n\nfor size in sizesToTest:\n data = [1] * size\n\n timerNumpy = timeit.Timer(lambda: multiply_numpy(data))\n timerFunctools = timeit.Timer(lambda: multiply_functools(data))\n timerManual = timeit.Timer(lambda: multiply_manual(data))\n\n repeats = int(5e6 / size)\n resultNumpy = timerNumpy.timeit(repeats)\n resultFunctools = timerFunctools.timeit(repeats)\n resultManual = timerManual.timeit(repeats)\n print(f'Input size: {size:>7d} Repeats: {repeats:>8d} Numpy: {resultNumpy:.3f}, Functools: {resultFunctools:.3f}, Manual: {resultManual:.3f}')\n\nResults:\nInput size: 5 Repeats: 1000000 Numpy: 4.670, Functools: 0.586, Manual: 0.459\nInput size: 10 Repeats: 500000 Numpy: 2.443, Functools: 0.401, Manual: 0.321\nInput size: 100 Repeats: 50000 Numpy: 0.505, Functools: 0.220, Manual: 0.197\nInput size: 1000 Repeats: 5000 Numpy: 0.303, Functools: 0.207, Manual: 0.185\nInput size: 10000 Repeats: 500 Numpy: 0.265, Functools: 0.194, Manual: 0.187\nInput size: 100000 Repeats: 50 Numpy: 0.266, Functools: 0.198, Manual: 0.185\n\nYou can see that Numpy is quite a bit slower on smaller inputs, since it allocates an array before multiplication is performed. Also, watch out for the overflow in Numpy.\n",
"I personally like this for a function that multiplies all elements of a generic list together:\ndef multiply(n):\n total = 1\n for i in range(0, len(n)):\n total *= n[i]\n print total\n\nIt's compact, uses simple things (a variable and a for loop), and feels intuitive to me (it looks like how I'd think of the problem, just take one, multiply it, then multiply by the next, and so on!) \n",
"Numpy has the prod() function that returns the product of a list, or in this case since it's numpy, it's the product of an array over a given axis:\nimport numpy\na = [1,2,3,4,5,6]\nb = numpy.prod(a)\n\n...or else you can just import numpy.prod():\nfrom numpy import prod\na = [1,2,3,4,5,6]\nb = prod(a)\n\n",
"nums = str(tuple([1,2,3]))\nmul_nums = nums.replace(',','*')\nprint(eval(mul_nums))\n\n",
"The simple way is:\nimport numpy as np\nnp.exp(np.log(your_array).sum())\n\n",
"Just wanna add a Python 3.10 One-liner answer:\ndef multiply(l):\n return [b := 1, [b := b * a for a in l]][-1][-1]\n\n\nprint(multiply([2, 3, 8, 10]))\n\noutput:\n480\n\nexplanation:\n\n[b := 1, is for defining a temporary variable\n\n...[b := b * a for a in l] is for iterating over the list and multiplying b by every element\n\n...[-1][-1] is because the final list is [b, [b * l[0], b * l[1], ..., b * l[-1]]]. and so the element in the final position is the multiplication of all of the elements in the list.\n\n\n",
"Found this question today but I noticed that it does not have the case where there are None's in the list. So, the complete solution would be:\nfrom functools import reduce\n\na = [None, 1, 2, 3, None, 4]\nprint(reduce(lambda x, y: (x if x else 1) * (y if y else 1), a))\n\nIn the case of addition, we have: \nprint(reduce(lambda x, y: (x if x else 0) + (y if y else 0), a))\n\n",
"I would like this in following way:\n def product_list(p):\n total =1 #critical step works for all list\n for i in p:\n total=total*i # this will ensure that each elements are multiplied by itself\n return total\n print product_list([2,3,4,2]) #should print 48\n\n",
"This is my code:\ndef product_list(list_of_numbers):\n xxx = 1\n for x in list_of_numbers:\n xxx = xxx*x\n return xxx\n\nprint(product_list([1,2,3,4]))\n\nresult : ('1*1*2*3*4', 24)\n",
"How about using recursion? \ndef multiply(lst):\n if len(lst) > 1:\n return multiply(lst[:-1])* lst[-1]\n else:\n return lst[0]\n\n",
"My solution:\ndef multiply(numbers):\n a = 1\n for num in numbers:\n a *= num\n return a\n\n",
"There are many good answers in this thread. If you want to do multiply a list in actual production I recommend using standard numpy or math packages.\nIf you are just looking for a quick and dirty solution and you don’t want to import anything you can do this:\nl = [1,2,3,4,5,6]\n\ndef list_multiply(l):\n return eval('*'.join(map(str,l)))\n \nprint(list_multiply(l))\n#Output: 720\n\nmap(str,l) converts each element in the list to a string. join combines each element into one string separated by the * symbol. eval converts the string back into a function that can evaluated.\nWarning: eval is considered dangerous to use, especially if the program accepts user input because a user can potentially inject any function into the code and compromise your system.\n"
] |
[
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 multi=1\n for product in lst:\n multi*=product\n return product\n\n"
] |
[
-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 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.
|
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, 2019, 10, 30, 2019.829, 0, 0. , 24, 0)
(73717, 2019, 10, 31, 2019.832, 0, 0. , 28, 0)]
each column corresponding to different data. The 2nd column corresponds to the year. I have to interpolate all the data in 1000 time steps from 1900 to 2000.
The difficulty lies in the fact that it's a CSV file with multiple columns which I have to interpolate each in 1000 time steps.
What I first did is collect all the data from 1900 to 2000 with this piece of code:
index1 = np.where(arr['year']==1900)[0][0]
index2 = np.where(arr['year']==2000)[0][-1]
data = arr[index1:index2]
which gives:
[(29950, 1900, 1, 1, 1900.001, 12, 3. , 1, 1)
(29951, 1900, 1, 2, 1900.004, 12, 3. , 1, 1)
(29952, 1900, 1, 3, 1900.007, 3, 2. , 1, 1) ...
(66836, 2000, 12, 28, 2000.99 , 162, 7. , 13, 1)
(66837, 2000, 12, 29, 2000.993, 151, 11.7, 15, 1)
(66838, 2000, 12, 30, 2000.996, 152, 10.6, 11, 1)]
The length of this piece of data is 36889. Now I need to interpolate this in 1000 time steps.
I've got no idea how to do this. I've been going back and forth with np.interpd() and interp1d from scipy, but I keep getting stuck since there are no clear examples as to how to do this with each column from a csv file.
I want this done without pandas and without for loops.
A:
Here is an example of how you can interpolate using some integer index values:
#!/usr/bin/env ipython
import numpy as np
import pandas as pd
import datetime
# --------------------------------------------------------------
# let us generate the sample data, similar to data in question:
dvec = [datetime.datetime(1818,1,1)+ii*datetime.timedelta(days=1) for ii in range(200*365)]
# --------------------------------------------------------------
yy = [vv.year for vv in dvec]
mm = [vv.month for vv in dvec]
dd = [vv.day for vv in dvec]
c1 = np.random.random(np.size(yy))
c2 = np.random.random(np.size(yy))
c3 = np.random.random(np.size(yy))
datain = np.vstack((yy,mm,dd,c1,c2,c3)).T
# --------------------------------------------------------------
# let us convert our data to pandas dataframe:
ddict = {ii:datain[:,ii] for ii in range(datain.shape[1])}
# we can also add just some index values for the interpolation:
# --------------------------------------------------------------
# let us interpolate to wished values using integer values:
kk = [kk for kk,val in enumerate(dvec,1) if val.year>=1900 and val.year<2000]
iout = np.linspace(kk[0],kk[-1],1000)
ddict['index'] = np.linspace(1,datain.shape[0],datain.shape[0])
# ------------------------------------------------------------
df = pd.DataFrame.from_dict(ddict);
dfi = df.set_index('index');
dfo = dfi.reindex(dfi.index|iout) # add new index values to the dataframe
dfo = dfo.interpolate(method='linear').loc[iout]
|
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, 2019, 10, 31, 2019.832, 0, 0. , 28, 0)]
each column corresponding to different data. The 2nd column corresponds to the year. I have to interpolate all the data in 1000 time steps from 1900 to 2000.
The difficulty lies in the fact that it's a CSV file with multiple columns which I have to interpolate each in 1000 time steps.
What I first did is collect all the data from 1900 to 2000 with this piece of code:
index1 = np.where(arr['year']==1900)[0][0]
index2 = np.where(arr['year']==2000)[0][-1]
data = arr[index1:index2]
which gives:
[(29950, 1900, 1, 1, 1900.001, 12, 3. , 1, 1)
(29951, 1900, 1, 2, 1900.004, 12, 3. , 1, 1)
(29952, 1900, 1, 3, 1900.007, 3, 2. , 1, 1) ...
(66836, 2000, 12, 28, 2000.99 , 162, 7. , 13, 1)
(66837, 2000, 12, 29, 2000.993, 151, 11.7, 15, 1)
(66838, 2000, 12, 30, 2000.996, 152, 10.6, 11, 1)]
The length of this piece of data is 36889. Now I need to interpolate this in 1000 time steps.
I've got no idea how to do this. I've been going back and forth with np.interpd() and interp1d from scipy, but I keep getting stuck since there are no clear examples as to how to do this with each column from a csv file.
I want this done without pandas and without for loops.
|
[
"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.datetime(1818,1,1)+ii*datetime.timedelta(days=1) for ii in range(200*365)]\n# --------------------------------------------------------------\nyy = [vv.year for vv in dvec]\nmm = [vv.month for vv in dvec]\ndd = [vv.day for vv in dvec]\nc1 = np.random.random(np.size(yy))\nc2 = np.random.random(np.size(yy))\nc3 = np.random.random(np.size(yy))\ndatain = np.vstack((yy,mm,dd,c1,c2,c3)).T\n# --------------------------------------------------------------\n# let us convert our data to pandas dataframe:\nddict = {ii:datain[:,ii] for ii in range(datain.shape[1])}\n# we can also add just some index values for the interpolation:\n# --------------------------------------------------------------\n# let us interpolate to wished values using integer values:\nkk = [kk for kk,val in enumerate(dvec,1) if val.year>=1900 and val.year<2000]\niout = np.linspace(kk[0],kk[-1],1000)\nddict['index'] = np.linspace(1,datain.shape[0],datain.shape[0])\n# ------------------------------------------------------------\ndf = pd.DataFrame.from_dict(ddict);\ndfi = df.set_index('index');\ndfo = dfi.reindex(dfi.index|iout) # add new index values to the dataframe\ndfo = dfo.interpolate(method='linear').loc[iout]\n\n"
] |
[
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 keyworded arguments.
How do I use the markers parameter? My failed attempts range from
from sympy import *
x = symbols ('x')
plot (sin (x), markers = 'o')
to
plot (sin (x), markers = list (dict (marker = 'o')))
A:
Nice find!
The documentation doesn't make things clear. Diving into the source code, leads to these lines in plot.py:
for marker in parent.markers:
# make a copy of the marker dictionary
# so that it doesn't get altered
m = marker.copy()
args = m.pop('args')
ax.plot(*args, **m)
So, sympy just calls matplotlib's plot with:
the args key of the dictionary as positional parameters
all the other keys of the dictionary as keyword parameters
As matplotlib's plot allows a huge variety of parameters, they all are supported here. They are primarily meant to show extra markers onto the plot (you need to give their positions).
An example:
from sympy import symbols, sin, plot
x = symbols('x')
plot(sin(x), markers=[{'args': [2, 0, 'go']},
{'args': [[1, 3], [1, 1], 'r*'], 'ms': 20},
{'args': [[2, 4, 6], [-1, 0, -1], ], 'color': 'turquoise', 'ls': '--', 'lw': 3}])
These get converted to:
ax.plot(2, 0, 'go') # draw a green dot at position 2,0
ax.plot([3, 5], [1, 1], 'r*', ms=20) # draw red stars of size 20 at positions 3,1 and 5,1
ax.plot([2, 4, 6], [-1, 0, -1], ], color='turquoise', ls='--', lw=3)
# draw a dotted line from 2,-1 over 4,0 to 6,-1
PS: The source code shows a similar approach for dictionaries with annotations, rectangles and fills (using plt.fillbetween()):
if parent.annotations:
for a in parent.annotations:
ax.annotate(**a)
if parent.rectangles:
for r in parent.rectangles:
rect = self.matplotlib.patches.Rectangle(**r)
ax.add_patch(rect)
if parent.fill:
ax.fill_between(**parent.fill)
A:
(Updated using @cards suggestion (in comments) and this post.
You can add markers directly to the axis using the Matplotlib backend.
import sympy as sp
from sympy.plotting.plot import MatplotlibBackend
# plot with sympy
x = sp.symbols('x')
p0 = sp.plot(sp.sin(x),(x,-sp.pi,sp.pi),line_color='b',legend=True,show=False)
# point to be displayed
x0 = float(sp.pi/2)
y0 = float(sp.sin(sp.pi/2))
# plot with the commands from the backend (default matplotlib)
be = MatplotlibBackend(p0)
be.process_series()
plt = be.plt
plt.plot([x0,-x0],[y0,-y0],'r*',markersize=10,label="Star marker")
# Update the legend to include markers
plt.legend()
plt.show()
This solution also updates the legend with the markers.
|
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 failed attempts range from
from sympy import *
x = symbols ('x')
plot (sin (x), markers = 'o')
to
plot (sin (x), markers = list (dict (marker = 'o')))
|
[
"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 args = m.pop('args')\n ax.plot(*args, **m)\n\nSo, sympy just calls matplotlib's plot with:\n\nthe args key of the dictionary as positional parameters\nall the other keys of the dictionary as keyword parameters\n\nAs matplotlib's plot allows a huge variety of parameters, they all are supported here. They are primarily meant to show extra markers onto the plot (you need to give their positions).\nAn example:\nfrom sympy import symbols, sin, plot\n\nx = symbols('x')\nplot(sin(x), markers=[{'args': [2, 0, 'go']},\n {'args': [[1, 3], [1, 1], 'r*'], 'ms': 20},\n {'args': [[2, 4, 6], [-1, 0, -1], ], 'color': 'turquoise', 'ls': '--', 'lw': 3}])\n\nThese get converted to:\nax.plot(2, 0, 'go') # draw a green dot at position 2,0\nax.plot([3, 5], [1, 1], 'r*', ms=20) # draw red stars of size 20 at positions 3,1 and 5,1\nax.plot([2, 4, 6], [-1, 0, -1], ], color='turquoise', ls='--', lw=3)\n # draw a dotted line from 2,-1 over 4,0 to 6,-1\n\n\nPS: The source code shows a similar approach for dictionaries with annotations, rectangles and fills (using plt.fillbetween()):\n if parent.annotations:\n for a in parent.annotations:\n ax.annotate(**a)\n if parent.rectangles:\n for r in parent.rectangles:\n rect = self.matplotlib.patches.Rectangle(**r)\n ax.add_patch(rect)\n if parent.fill:\n ax.fill_between(**parent.fill)\n\n",
"(Updated using @cards suggestion (in comments) and this post.\nYou can add markers directly to the axis using the Matplotlib backend.\nimport sympy as sp\nfrom sympy.plotting.plot import MatplotlibBackend\n\n# plot with sympy\nx = sp.symbols('x')\n\np0 = sp.plot(sp.sin(x),(x,-sp.pi,sp.pi),line_color='b',legend=True,show=False)\n\n# point to be displayed\nx0 = float(sp.pi/2)\ny0 = float(sp.sin(sp.pi/2))\n\n# plot with the commands from the backend (default matplotlib)\nbe = MatplotlibBackend(p0)\nbe.process_series()\n\nplt = be.plt\nplt.plot([x0,-x0],[y0,-y0],'r*',markersize=10,label=\"Star marker\")\n\n# Update the legend to include markers\nplt.legend()\n\nplt.show()\n\nThis solution also updates the legend with the markers.\n\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 to implement this without numpy/loops. My object is using only tensorflow vectorized operations. Any ideas?
A:
Let suppose creating a Matrix m with size n*n
m =[
['a' , 'b' , 'c' , 'd' , 'e'],
['f' , 'g' , 'h' , 'i' , 'j'],
['k' , 'l' , 'm' , 'n' , 'o'],
['p', 'q' , 'r' , 's' , 't'],
['u' , 'v' , 'w' , 'y' , 'x']
]
def conv_slide_window(matrix_len , pad_size, stride):
matrix = tf.reshape(tf.range(matrix_len**2)+1, (matrix_len , matrix_len))
conv_window = (len(matrix) - pad_size)
assert conv_window%stride==0 , "Please choose a stride which can be divisible by the convolution window"
conv_window = conv_window//stride + 1
conv_window = conv_window **2
image = tf.image.extract_patches(images=matrix[None,...,None],
sizes=[1, pad_size, pad_size, 1],
strides=[1, stride, stride, 1],
rates=[1, 1, 1, 1], padding='VALID').numpy().reshape(-1,1).tolist()
return tf.squeeze(tf.reshape(tokenize.sequences_to_texts(image) , (pad_size , pad_size , conv_window))) if pad_size >= conv_window else tf.squeeze(tf.split(tf.reshape(tokenize.sequences_to_texts(image) , (pad_size , pad_size , conv_window)) , conv_window , axis=-1))
#First do some pre-processing
#Define Tokenizer to tokenize the alphabets first you cannot directly map the alphabets
tokenize = tf.keras.preprocessing.text.Tokenizer()
tokenize.fit_on_sequences(m)
tokenize.fit_on_texts(m)
pad_size = 3
#can also use the stride, in your case the stride is 1.
stride = 1
conv_slide_window(len(m) , pad_size, stride)
<tf.Tensor: shape=(9, 3, 3), dtype=string, numpy=
array([[[b'a', b'b', b'c'],
[b'f', b'g', b'h'],
[b'k', b'l', b'm']],
[[b'b', b'c', b'd'],
[b'g', b'h', b'i'],
[b'l', b'm', b'n']],
[[b'c', b'd', b'e'],
[b'h', b'i', b'j'],
[b'm', b'n', b'o']],
[[b'f', b'g', b'h'],
[b'k', b'l', b'm'],
[b'p', b'q', b'r']],
[[b'g', b'h', b'i'],
[b'l', b'm', b'n'],
[b'q', b'r', b's']],
[[b'h', b'i', b'j'],
[b'm', b'n', b'o'],
[b'r', b's', b't']],
[[b'k', b'l', b'm'],
[b'p', b'q', b'r'],
[b'u', b'v', b'w']],
[[b'l', b'm', b'n'],
[b'q', b'r', b's'],
[b'v', b'w', b'y']],
[[b'm', b'n', b'o'],
[b'r', b's', b't'],
[b'w', b'y', b'x']]], dtype=object)>
|
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 is using only tensorflow vectorized operations. Any ideas?
|
[
"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.reshape(tf.range(matrix_len**2)+1, (matrix_len , matrix_len))\n\n conv_window = (len(matrix) - pad_size)\n assert conv_window%stride==0 , \"Please choose a stride which can be divisible by the convolution window\" \n conv_window = conv_window//stride + 1\n\n conv_window = conv_window **2\n\n image = tf.image.extract_patches(images=matrix[None,...,None], \n sizes=[1, pad_size, pad_size, 1], \n strides=[1, stride, stride, 1], \n rates=[1, 1, 1, 1], padding='VALID').numpy().reshape(-1,1).tolist()\n\n return tf.squeeze(tf.reshape(tokenize.sequences_to_texts(image) , (pad_size , pad_size , conv_window))) if pad_size >= conv_window else tf.squeeze(tf.split(tf.reshape(tokenize.sequences_to_texts(image) , (pad_size , pad_size , conv_window)) , conv_window , axis=-1)) \n\n#First do some pre-processing\n#Define Tokenizer to tokenize the alphabets first you cannot directly map the alphabets\ntokenize = tf.keras.preprocessing.text.Tokenizer()\ntokenize.fit_on_sequences(m)\ntokenize.fit_on_texts(m)\n \npad_size = 3\n#can also use the stride, in your case the stride is 1.\nstride = 1\nconv_slide_window(len(m) , pad_size, stride)\n\n<tf.Tensor: shape=(9, 3, 3), dtype=string, numpy=\narray([[[b'a', b'b', b'c'],\n [b'f', b'g', b'h'],\n [b'k', b'l', b'm']],\n\n [[b'b', b'c', b'd'],\n [b'g', b'h', b'i'],\n [b'l', b'm', b'n']],\n\n [[b'c', b'd', b'e'],\n [b'h', b'i', b'j'],\n [b'm', b'n', b'o']],\n\n [[b'f', b'g', b'h'],\n [b'k', b'l', b'm'],\n [b'p', b'q', b'r']],\n\n [[b'g', b'h', b'i'],\n [b'l', b'm', b'n'],\n [b'q', b'r', b's']],\n\n [[b'h', b'i', b'j'],\n [b'm', b'n', b'o'],\n [b'r', b's', b't']],\n\n [[b'k', b'l', b'm'],\n [b'p', b'q', b'r'],\n [b'u', b'v', b'w']],\n\n [[b'l', b'm', b'n'],\n [b'q', b'r', b's'],\n [b'v', b'w', b'y']],\n\n [[b'm', b'n', b'o'],\n [b'r', b's', b't'],\n [b'w', b'y', b'x']]], dtype=object)>\n\n"
] |
[
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(unittest.TestCase):
def test_validInput(self):
footer = Footer(4,5,1,0)
self.assertTrue(footer.validInput())
#attempt 1:
footer1 = Footer("four","five",1,0)
self.assertRaises(TypeError, footer1.validInput())
#attempt 2:
with self.assertRaises(TypeError):
Footer("four",5,1,0)
if __name__ == '__main__':
unittest.main()
However, this will not work. I don't understand why.
Here is the class, I'am writting the test for:
class Footer:
def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):
self.current_page = current_page
self.total_pages = total_pages
self.boundaries = boundaries
self.around = around
try:
if (self.validInput()):
footer = self.createFooter()
self.addEllipsis(footer)
except Exception as e:
print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e)
def validInput(self) -> bool:
if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(self.current_page) != int ):
raise TypeError("Invalid input. All the arguments must be of type int.")
if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):
raise ValueError("Invalid values. Please do not provide negative values.")
if (self.current_page > self.total_pages):
raise ValueError("Current page must be within the total number of pages")
return True
def createFooter(self) -> list:
footer = []
for page in range(1, self.total_pages + 1):
if (page <= self.boundaries):
footer.append(page)
elif (page > self.total_pages-self.boundaries):
footer.append(page)
elif (page == self.current_page):
footer.append(page)
elif ((page > self.current_page and page <= (self.current_page + self.around)) or (page < self.current_page and page >= self.current_page - self.around)):
footer.append(page)
return footer
def addEllipsis(self, footer: list) -> None:
final_footer = []
i = 0
for page in footer:
try :
final_footer.append(page)
if(footer[i + 1] - footer[i] > 1):
final_footer.append("...")
except IndexError:
break
i += 1
print("\n", ' '.join(str(page) for page in final_footer))
Here is the output for the test :
A:
This is the wrong way to use assertRaises:
import unittest
def this_func_raises():
raise ValueError
class TestClass(unittest.TestCase):
def test1(self):
self.assertRaises(ValueError, this_func_raises())
Note that the ValueError will be raised if you include the (), since that would execute this_func_raises and the exception will not be caught.
And this is the right way:
import unittest
def this_func_raises():
raise ValueError
class TestClass(unittest.TestCase):
def test1(self):
self.assertRaises(ValueError, this_func_raises)
Note that there are several other problems in your code.
For example this:
with self.assertRaises(TypeError):
Footer("four", 5, 1, 0)
Should be like so:
with self.assertRaises(TypeError):
Footer("four", 5, 1, 0).validInput()
Lastly, you need to replace self.createFooter() with a pass until you implement it, or else you'll get another error.
This is how your code should look like in order to pass the tests:
class Footer:
def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):
self.current_page = current_page
self.total_pages = total_pages
self.boundaries = boundaries
self.around = around
try:
if (self.validInput()):
# self.createFooter()
pass
except Exception as e:
print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e)
def validInput(self) -> bool:
if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(
self.current_page) != int):
raise TypeError("Invalid input. All the arguments must be of type int.")
if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):
raise ValueError("Invalid values. Please do not provide negative values.")
if (self.current_page > self.total_pages):
raise ValueError("Current page must be within the total number of pages")
return True
test file:
import unittest
class TestFooter(unittest.TestCase):
def test_validInput(self):
footer = Footer(4, 5, 1, 0)
self.assertTrue(footer.validInput())
# attempt 1:
footer1 = Footer("four", "five", 1, 0)
self.assertRaises(TypeError, footer1.validInput)
# attempt 2:
with self.assertRaises(TypeError):
Footer("four", 5, 1, 0).validInput()
if __name__ == '__main__':
unittest.main()
|
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 = Footer(4,5,1,0)
self.assertTrue(footer.validInput())
#attempt 1:
footer1 = Footer("four","five",1,0)
self.assertRaises(TypeError, footer1.validInput())
#attempt 2:
with self.assertRaises(TypeError):
Footer("four",5,1,0)
if __name__ == '__main__':
unittest.main()
However, this will not work. I don't understand why.
Here is the class, I'am writting the test for:
class Footer:
def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):
self.current_page = current_page
self.total_pages = total_pages
self.boundaries = boundaries
self.around = around
try:
if (self.validInput()):
footer = self.createFooter()
self.addEllipsis(footer)
except Exception as e:
print(f"\nError while initializing Footer Class ({e.__class__}).\n Please fix the following: ", e)
def validInput(self) -> bool:
if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(self.current_page) != int ):
raise TypeError("Invalid input. All the arguments must be of type int.")
if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):
raise ValueError("Invalid values. Please do not provide negative values.")
if (self.current_page > self.total_pages):
raise ValueError("Current page must be within the total number of pages")
return True
def createFooter(self) -> list:
footer = []
for page in range(1, self.total_pages + 1):
if (page <= self.boundaries):
footer.append(page)
elif (page > self.total_pages-self.boundaries):
footer.append(page)
elif (page == self.current_page):
footer.append(page)
elif ((page > self.current_page and page <= (self.current_page + self.around)) or (page < self.current_page and page >= self.current_page - self.around)):
footer.append(page)
return footer
def addEllipsis(self, footer: list) -> None:
final_footer = []
i = 0
for page in footer:
try :
final_footer.append(page)
if(footer[i + 1] - footer[i] > 1):
final_footer.append("...")
except IndexError:
break
i += 1
print("\n", ' '.join(str(page) for page in final_footer))
Here is the output for the test :
|
[
"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 execute this_func_raises and the exception will not be caught.\nAnd this is the right way:\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\n\nNote that there are several other problems in your code.\nFor example this:\nwith self.assertRaises(TypeError):\n Footer(\"four\", 5, 1, 0)\n\nShould be like so:\nwith self.assertRaises(TypeError):\n Footer(\"four\", 5, 1, 0).validInput()\n\n\nLastly, you need to replace self.createFooter() with a pass until you implement it, or else you'll get another error.\n\nThis is how your code should look like in order to pass the tests:\nclass Footer:\n def __init__(self, current_page: int, total_pages: int, boundaries: int, around: int):\n self.current_page = current_page\n self.total_pages = total_pages\n self.boundaries = boundaries\n self.around = around\n try:\n if (self.validInput()):\n # self.createFooter()\n pass\n except Exception as e:\n print(f\"\\nError while initializing Footer Class ({e.__class__}).\\n Please fix the following: \", e)\n\n def validInput(self) -> bool:\n if (type(self.total_pages) != int or type(self.boundaries) != int or type(self.around) != int or type(\n self.current_page) != int):\n raise TypeError(\"Invalid input. All the arguments must be of type int.\")\n if (self.total_pages < 0 or self.boundaries < 0 or self.around < 0 or self.current_page < 0):\n raise ValueError(\"Invalid values. Please do not provide negative values.\")\n if (self.current_page > self.total_pages):\n raise ValueError(\"Current page must be within the total number of pages\")\n return True\n\ntest file:\nimport unittest\n\n\nclass TestFooter(unittest.TestCase):\n\n def test_validInput(self):\n footer = Footer(4, 5, 1, 0)\n self.assertTrue(footer.validInput())\n # attempt 1:\n footer1 = Footer(\"four\", \"five\", 1, 0)\n self.assertRaises(TypeError, footer1.validInput)\n # attempt 2:\n with self.assertRaises(TypeError):\n Footer(\"four\", 5, 1, 0).validInput()\n\nif __name__ == '__main__':\n unittest.main()\n\n"
] |
[
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 successfully but second method exits with an error that can't receive frame.
The major challenge is the while loop for reading the capture source(cap) which makes it different from the question posted on stackoverflow before
The code is as follows:
import cv2
import dlib
from multiprocessing import Process
def haar_cascade():
while True:
ret,frame=cap.read()
cv2.imshow('input',frame)
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')
faces = classifier.detectMultiScale(frame)
for result in faces:
x, y, w, h = result
x1, y1 = x + w, y + h
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
if cv2.waitKey(1) == ord('q'):
break
cv2.imshow('harr-cascade',frame)
def dlib_hog():
while True:
ret,frame=cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
detector = dlib.get_frontal_face_detector()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1) # result
#to draw faces on image
for result in faces:
x = result.left()
y = result.top()
x1 = result.right()
y1 = result.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
if cv2.waitKey(1) == ord('q'):
break
cv2.imshow('dlib-hog',frame)
if __name__ == "__main__":
cap =cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
harrProcess=Process(target=haar_cascade)
harrProcess.start()
dlibProcess=Process(target=dlib_hog)
dlibProcess.start()
# When everything done, release the capture
harrProcess.join()
dlibProcess.join()
cap.release()
cv2.destroyAllWindows()
How can I create a multiprocessing model that read source from single source and perform independent operation?
A:
I have made various attempts:
I 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 that I was finding that frames were being lost.
I tried using multithreading with a producer thread and two consumer threads. This has less overhead with regards to passing frames from the producer and consumer. The problem, of course, with multithreading is that due to contention for the Global Interpreter Lock, any CPU-intensive processing required by a consumer cannot be run in parallel with CPU-intensive processing required by the other consumer and could even cause the producer to miss frames. Unfortunately, I don't know if when using a camera for input whether there is a way to detect missed frames on the part of the producer. To remediate these problems I pass a multiprocessing pool to the consumer threads to which they can submit tasks that perform the CPU-intensive processing on the frames. Here, too, there is sufficient overhead in passing frames from one process to another and frames are lost.
As in bullet point 2 above, I use multithreading but instead of submitting CPU-intensive work to the multiprocessing pool, I perform it within the consumer thread. This seems to cause fewer missed frames for the consumer. But I can't tell if it is causing the producer now to miss frames it would not otherwise miss. So using a multiprocessing pool for doing the CPU-intensive work seems to be the wiser approach. Of course, if your CPU is fast enough, neither the consumer not producer should miss frames. But option 1 (see second code example), i.e. using just multiprocessing, is probably best.
In the following demos, since I don't have access to your XML file, I have dummied out the processing for one of your consumers. You terminate the program by just hitting the enter key:
Using Multithreading
Set USE_POOL_FOR_COMPUTATION = False to perform CPU-intensive processing by direct call instead of submitting the work to a multiprocessing pool:
#!/usr/bin/env python3
import threading
import multiprocessing
import cv2
import dlib
USE_POOL_FOR_COMPUTATION = True
class Producer:
def __init__(self):
# Create shared memory version of a numpy array:
self._frame = None
self._condition = threading.Condition()
self._running = True
# The latest frame number retrieved
self._latest_frame_number = 0
def run(self, cap):
while self._running:
ret, self._frame = cap.read()
if not ret:
self._running = False
else:
self._latest_frame_number += 1
with self._condition:
self._condition.notify_all()
def stop(self):
self._running = False
def get_frame(self, sequence_number):
with self._condition:
# We block until we find a frame sequence number >= sequence_number.
self._condition.wait_for(lambda: not self._running or self._latest_frame_number >= sequence_number)
# Even after the stop method has been called and we are no longer running,
# there could still be an unprocessed frame. But when we are called again, the current
# frame number will be < the expected frame number:
return (self._latest_frame_number, None if self._latest_frame_number < sequence_number else self._frame)
def process_haar_cascade(frame):
classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')
faces = classifier.detectMultiScale(frame)
for result in faces:
x, y, w, h = result
x1, y1 = x + w, y + h
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
return frame
def haar_cascade(producer, pool):
last_sequence_number = 0
while True:
expected = last_sequence_number + 1
sequence_number, frame = producer.get_frame(expected)
if frame is None:
break
cv2.waitKey(1) # allow window to update
if sequence_number != expected:
print(f'haar_cascade missed frames {expected} to {sequence_number-1}', flush=True)
last_sequence_number = sequence_number
cv2.imshow('input', frame) # Unmodified frame
# Since I don't have required xml file, just skip processing:
"""
if USE_POOL_FOR_COMPUTATION:
frame = pool.apply(process_haar_cascade, args=(frame,))
else:
frame = process_haar_cascade(frame)
"""
cv2.imshow('harr-cascade', frame)
def process_dlib_hog(frame):
detector = dlib.get_frontal_face_detector()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1) # result
#to draw faces on image
for result in faces:
x = result.left()
y = result.top()
x1 = result.right()
y1 = result.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
return frame
def dlib_hog(producer, pool):
last_sequence_number = 0
while True:
expected = last_sequence_number + 1
sequence_number, frame = producer.get_frame(expected)
if frame is None:
break
cv2.waitKey(1) # allow window to update
if sequence_number != expected:
print(f'dlib_hog missed frames {expected} to {sequence_number-1}', flush=True)
last_sequence_number = sequence_number
if USE_POOL_FOR_COMPUTATION:
frame = pool.apply(process_dlib_hog, args=(frame,))
else:
frame = process_dlib_hog(frame)
cv2.imshow('dlib-hog', frame)
def main():
producer = Producer()
pool = multiprocessing.Pool(2) if USE_POOL_FOR_COMPUTATION else None
# Pass pool for CPU-Intensive work:
consumer1_thread = threading.Thread(target=haar_cascade, args=(producer, pool))
consumer1_thread.start()
consumer2_thread = threading.Thread(target=dlib_hog, args=(producer, pool))
consumer2_thread.start()
cap = cv2.VideoCapture(0)
producer_thread = threading.Thread(target=producer.run, args=(cap,))
producer_thread.start()
input('Hit enter to terminate:\n')
producer.stop()
producer_thread.join()
consumer1_thread.join()
consumer2_thread.join()
cap.release()
cv2.destroyAllWindows()
if USE_POOL_FOR_COMPUTATION:
pool.close()
pool.join()
if __name__ == '__main__':
main()
Using Multiprocessing
The multiprocessing.RawArray that is used to hold the sharable frame must be allocated before the consumer process is run so that all processes have access to this array. This requires knowing in advance how large an array to create:
#!/usr/bin/env python3
import multiprocessing
import ctypes
import cv2
import numpy as np
import dlib
class Producer:
def __init__(self):
# Discover how large a framesize is by getting the first frame
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
if ret:
self._shape = frame.shape
frame_size = self._shape[0] * self._shape[1] * self._shape[2]
self._shared_array = multiprocessing.RawArray(ctypes.c_ubyte, frame_size)
else:
self._arr = None
cap.release()
self._condition = multiprocessing.Condition()
self._running = multiprocessing.RawValue('i', 1)
# The latest frame number retrieved
self._latest_frame_number = multiprocessing.RawValue('i', 0)
self._lock = multiprocessing.Lock()
def run(self):
cap = cv2.VideoCapture(0)
while self._running.value:
ret, frame = cap.read()
if not ret:
self._running.value = 0
with self._condition:
self._condition.notify_all()
cap.release()
break
with self._lock:
self._latest_frame_number.value += 1
# np array to shared_array
temp = np.frombuffer(self._shared_array, dtype=frame.dtype)
temp[:] = frame.flatten(order='C')
with self._condition:
self._condition.notify_all()
def stop(self):
self._running.value = 0
def get_frame(self, sequence_number):
with self._condition:
# We block until we find a frame sequence number >= sequence_number.
self._condition.wait_for(lambda: not self._running.value or self._latest_frame_number.value >= sequence_number)
# Even after the stop method has been called and we are no longer running,
# there could still be an unprocessed frame. But when we are called again, the current
# frame number will be < the expected frame number:
if self._latest_frame_number.value < sequence_number:
return (self._latest_frame_number.value, None)
with self._lock:
# Convert to np array:
return self._latest_frame_number.value, np.ctypeslib.as_array(self._shared_array).reshape(self._shape)
def process_haar_cascade(frame):
classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')
faces = classifier.detectMultiScale(frame)
for result in faces:
x, y, w, h = result
x1, y1 = x + w, y + h
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
return frame
def haar_cascade(producer):
last_sequence_number = 0
while True:
expected = last_sequence_number + 1
sequence_number, frame = producer.get_frame(expected)
if frame is None:
break
cv2.waitKey(1) # allow window to update
if sequence_number != expected:
print(f'haar_cascade missed frames {expected} to {sequence_number-1}', flush=True)
last_sequence_number = sequence_number
cv2.imshow('input', frame) # Unmodified frame
# Since I don't have required xml file, just skip processing:
#frame = process_haar_cascade(frame)
cv2.imshow('harr-cascade', frame)
def process_dlib_hog(frame):
detector = dlib.get_frontal_face_detector()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1) # result
#to draw faces on image
for result in faces:
x = result.left()
y = result.top()
x1 = result.right()
y1 = result.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
return frame
def dlib_hog(producer):
last_sequence_number = 0
while True:
expected = last_sequence_number + 1
sequence_number, frame = producer.get_frame(expected)
if frame is None:
break
cv2.waitKey(1) # allow window to update
if sequence_number != expected:
print(f'dlib_hog missed frames {expected} to {sequence_number-1}', flush=True)
last_sequence_number = sequence_number
frame = process_dlib_hog(frame)
cv2.imshow('dlib-hog', frame)
def main():
producer = Producer()
# Pass pool for CPU-Intensive work:
consumer1_process = multiprocessing.Process(target=haar_cascade, args=(producer,))
consumer1_process.start()
consumer2_process = multiprocessing.Process(target=dlib_hog, args=(producer,))
consumer2_process.start()
producer_process = multiprocessing.Process(target=producer.run)
producer_process.start()
input('Hit enter to terminate:\n')
producer.stop()
producer_process.join()
consumer1_process.join()
consumer2_process.join()
if __name__ == '__main__':
main()
|
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 frame.
The major challenge is the while loop for reading the capture source(cap) which makes it different from the question posted on stackoverflow before
The code is as follows:
import cv2
import dlib
from multiprocessing import Process
def haar_cascade():
while True:
ret,frame=cap.read()
cv2.imshow('input',frame)
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')
faces = classifier.detectMultiScale(frame)
for result in faces:
x, y, w, h = result
x1, y1 = x + w, y + h
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
if cv2.waitKey(1) == ord('q'):
break
cv2.imshow('harr-cascade',frame)
def dlib_hog():
while True:
ret,frame=cap.read()
if not ret:
print("Can't receive frame (stream end?). Exiting ...")
break
detector = dlib.get_frontal_face_detector()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = detector(gray, 1) # result
#to draw faces on image
for result in faces:
x = result.left()
y = result.top()
x1 = result.right()
y1 = result.bottom()
cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)
if cv2.waitKey(1) == ord('q'):
break
cv2.imshow('dlib-hog',frame)
if __name__ == "__main__":
cap =cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
exit()
harrProcess=Process(target=haar_cascade)
harrProcess.start()
dlibProcess=Process(target=dlib_hog)
dlibProcess.start()
# When everything done, release the capture
harrProcess.join()
dlibProcess.join()
cap.release()
cv2.destroyAllWindows()
How can I create a multiprocessing model that read source from single source and perform independent operation?
|
[
"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 that I was finding that frames were being lost.\nI tried using multithreading with a producer thread and two consumer threads. This has less overhead with regards to passing frames from the producer and consumer. The problem, of course, with multithreading is that due to contention for the Global Interpreter Lock, any CPU-intensive processing required by a consumer cannot be run in parallel with CPU-intensive processing required by the other consumer and could even cause the producer to miss frames. Unfortunately, I don't know if when using a camera for input whether there is a way to detect missed frames on the part of the producer. To remediate these problems I pass a multiprocessing pool to the consumer threads to which they can submit tasks that perform the CPU-intensive processing on the frames. Here, too, there is sufficient overhead in passing frames from one process to another and frames are lost.\nAs in bullet point 2 above, I use multithreading but instead of submitting CPU-intensive work to the multiprocessing pool, I perform it within the consumer thread. This seems to cause fewer missed frames for the consumer. But I can't tell if it is causing the producer now to miss frames it would not otherwise miss. So using a multiprocessing pool for doing the CPU-intensive work seems to be the wiser approach. Of course, if your CPU is fast enough, neither the consumer not producer should miss frames. But option 1 (see second code example), i.e. using just multiprocessing, is probably best.\n\nIn the following demos, since I don't have access to your XML file, I have dummied out the processing for one of your consumers. You terminate the program by just hitting the enter key:\nUsing Multithreading\nSet USE_POOL_FOR_COMPUTATION = False to perform CPU-intensive processing by direct call instead of submitting the work to a multiprocessing pool:\n#!/usr/bin/env python3\n\nimport threading\nimport multiprocessing\nimport cv2\nimport dlib\n\nUSE_POOL_FOR_COMPUTATION = True\n\nclass Producer:\n def __init__(self):\n\n # Create shared memory version of a numpy array:\n self._frame = None\n\n self._condition = threading.Condition()\n\n self._running = True\n\n # The latest frame number retrieved\n self._latest_frame_number = 0\n\n def run(self, cap):\n while self._running:\n ret, self._frame = cap.read()\n if not ret:\n self._running = False\n else:\n self._latest_frame_number += 1\n with self._condition:\n self._condition.notify_all()\n\n def stop(self):\n self._running = False\n\n def get_frame(self, sequence_number):\n with self._condition:\n # We block until we find a frame sequence number >= sequence_number.\n self._condition.wait_for(lambda: not self._running or self._latest_frame_number >= sequence_number)\n # Even after the stop method has been called and we are no longer running,\n # there could still be an unprocessed frame. But when we are called again, the current\n # frame number will be < the expected frame number:\n return (self._latest_frame_number, None if self._latest_frame_number < sequence_number else self._frame)\n\ndef process_haar_cascade(frame):\n classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')\n faces = classifier.detectMultiScale(frame)\n for result in faces:\n x, y, w, h = result\n x1, y1 = x + w, y + h\n cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)\n return frame\n\ndef haar_cascade(producer, pool):\n last_sequence_number = 0\n\n while True:\n expected = last_sequence_number + 1\n sequence_number, frame = producer.get_frame(expected)\n if frame is None:\n break\n\n cv2.waitKey(1) # allow window to update\n if sequence_number != expected:\n print(f'haar_cascade missed frames {expected} to {sequence_number-1}', flush=True)\n last_sequence_number = sequence_number\n\n cv2.imshow('input', frame) # Unmodified frame\n\n # Since I don't have required xml file, just skip processing:\n \"\"\"\n if USE_POOL_FOR_COMPUTATION:\n frame = pool.apply(process_haar_cascade, args=(frame,))\n else:\n frame = process_haar_cascade(frame)\n \"\"\"\n cv2.imshow('harr-cascade', frame)\n\n\ndef process_dlib_hog(frame):\n detector = dlib.get_frontal_face_detector()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = detector(gray, 1) # result\n #to draw faces on image\n for result in faces:\n x = result.left()\n y = result.top()\n x1 = result.right()\n y1 = result.bottom()\n cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)\n return frame\n\ndef dlib_hog(producer, pool):\n last_sequence_number = 0\n\n while True:\n expected = last_sequence_number + 1\n sequence_number, frame = producer.get_frame(expected)\n if frame is None:\n break\n\n cv2.waitKey(1) # allow window to update\n if sequence_number != expected:\n print(f'dlib_hog missed frames {expected} to {sequence_number-1}', flush=True)\n last_sequence_number = sequence_number\n\n if USE_POOL_FOR_COMPUTATION:\n frame = pool.apply(process_dlib_hog, args=(frame,))\n else:\n frame = process_dlib_hog(frame)\n cv2.imshow('dlib-hog', frame)\n\ndef main():\n producer = Producer()\n\n pool = multiprocessing.Pool(2) if USE_POOL_FOR_COMPUTATION else None\n # Pass pool for CPU-Intensive work:\n consumer1_thread = threading.Thread(target=haar_cascade, args=(producer, pool))\n consumer1_thread.start()\n consumer2_thread = threading.Thread(target=dlib_hog, args=(producer, pool))\n consumer2_thread.start()\n\n cap = cv2.VideoCapture(0)\n producer_thread = threading.Thread(target=producer.run, args=(cap,))\n producer_thread.start()\n\n input('Hit enter to terminate:\\n')\n producer.stop()\n producer_thread.join()\n consumer1_thread.join()\n consumer2_thread.join()\n\n cap.release()\n cv2.destroyAllWindows()\n\n if USE_POOL_FOR_COMPUTATION:\n pool.close()\n pool.join()\n\n\nif __name__ == '__main__':\n main()\n\nUsing Multiprocessing\nThe multiprocessing.RawArray that is used to hold the sharable frame must be allocated before the consumer process is run so that all processes have access to this array. This requires knowing in advance how large an array to create:\n#!/usr/bin/env python3\n\nimport multiprocessing\nimport ctypes\nimport cv2\nimport numpy as np\nimport dlib\n\n\nclass Producer:\n def __init__(self):\n # Discover how large a framesize is by getting the first frame\n cap = cv2.VideoCapture(0)\n ret, frame = cap.read()\n if ret:\n self._shape = frame.shape\n frame_size = self._shape[0] * self._shape[1] * self._shape[2]\n self._shared_array = multiprocessing.RawArray(ctypes.c_ubyte, frame_size)\n else:\n self._arr = None\n cap.release()\n\n self._condition = multiprocessing.Condition()\n\n self._running = multiprocessing.RawValue('i', 1)\n\n # The latest frame number retrieved\n self._latest_frame_number = multiprocessing.RawValue('i', 0)\n\n self._lock = multiprocessing.Lock()\n\n def run(self):\n cap = cv2.VideoCapture(0)\n\n while self._running.value:\n ret, frame = cap.read()\n if not ret:\n self._running.value = 0\n with self._condition:\n self._condition.notify_all()\n cap.release()\n break\n\n with self._lock:\n self._latest_frame_number.value += 1\n\n # np array to shared_array\n temp = np.frombuffer(self._shared_array, dtype=frame.dtype)\n temp[:] = frame.flatten(order='C')\n\n with self._condition:\n self._condition.notify_all()\n\n\n def stop(self):\n self._running.value = 0\n\n\n def get_frame(self, sequence_number):\n with self._condition:\n # We block until we find a frame sequence number >= sequence_number.\n self._condition.wait_for(lambda: not self._running.value or self._latest_frame_number.value >= sequence_number)\n # Even after the stop method has been called and we are no longer running,\n # there could still be an unprocessed frame. But when we are called again, the current\n # frame number will be < the expected frame number:\n if self._latest_frame_number.value < sequence_number:\n return (self._latest_frame_number.value, None)\n\n with self._lock:\n # Convert to np array:\n return self._latest_frame_number.value, np.ctypeslib.as_array(self._shared_array).reshape(self._shape)\n\ndef process_haar_cascade(frame):\n classifier = cv2.CascadeClassifier('haarcascade_frontalface2.xml')\n faces = classifier.detectMultiScale(frame)\n for result in faces:\n x, y, w, h = result\n x1, y1 = x + w, y + h\n cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)\n return frame\n\ndef haar_cascade(producer):\n last_sequence_number = 0\n\n while True:\n expected = last_sequence_number + 1\n sequence_number, frame = producer.get_frame(expected)\n if frame is None:\n break\n\n cv2.waitKey(1) # allow window to update\n if sequence_number != expected:\n print(f'haar_cascade missed frames {expected} to {sequence_number-1}', flush=True)\n last_sequence_number = sequence_number\n\n cv2.imshow('input', frame) # Unmodified frame\n # Since I don't have required xml file, just skip processing:\n #frame = process_haar_cascade(frame)\n cv2.imshow('harr-cascade', frame)\n\n\ndef process_dlib_hog(frame):\n detector = dlib.get_frontal_face_detector()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = detector(gray, 1) # result\n #to draw faces on image\n for result in faces:\n x = result.left()\n y = result.top()\n x1 = result.right()\n y1 = result.bottom()\n cv2.rectangle(frame, (x, y), (x1, y1), (0, 0, 255), 2)\n return frame\n\ndef dlib_hog(producer):\n last_sequence_number = 0\n\n while True:\n expected = last_sequence_number + 1\n sequence_number, frame = producer.get_frame(expected)\n if frame is None:\n break\n\n cv2.waitKey(1) # allow window to update\n if sequence_number != expected:\n print(f'dlib_hog missed frames {expected} to {sequence_number-1}', flush=True)\n last_sequence_number = sequence_number\n\n frame = process_dlib_hog(frame)\n cv2.imshow('dlib-hog', frame)\n\ndef main():\n producer = Producer()\n\n # Pass pool for CPU-Intensive work:\n consumer1_process = multiprocessing.Process(target=haar_cascade, args=(producer,))\n consumer1_process.start()\n consumer2_process = multiprocessing.Process(target=dlib_hog, args=(producer,))\n consumer2_process.start()\n\n producer_process = multiprocessing.Process(target=producer.run)\n producer_process.start()\n\n input('Hit enter to terminate:\\n')\n producer.stop()\n producer_process.join()\n consumer1_process.join()\n consumer2_process.join()\n\n\nif __name__ == '__main__':\n main()\n\n"
] |
[
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 (()) instead of {{}} but it doesnt work, it outputs me that tojson is not defined.
here is my api code:
return render_template('login.html',statef="0")
and here is my javascript:
<script>
var statef=document.getElementById("state"), curr= {{statef|tojson}}
document.getElementById('state').innerHTML=curr
console.log(curr);
console.log(statef);
</script>
A:
Example of using tojson filter in flask template to parse JSON
You 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) :
app.py:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/login', methods=['GET', 'POST'])
def show_login():
statef_data = {
"email": "demo@example.com",
"name": "Alice"
}
return render_template('login.html', statef=statef_data)
login.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<div id="state">
</div>
<script>
var curr= {{ statef|tojson }};
console.log(curr);
console.log(typeof(curr));
document.getElementById('state').innerHTML=curr["email"] + "<br>"+curr["name"];
</script>
</body>
</html>
Output:
Console log:
{email: 'demo@example.com', name: 'Alice'}
login:14 object
References:
Documentation of tojson filter in Flask template
|
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 defined.
here is my api code:
return render_template('login.html',statef="0")
and here is my javascript:
<script>
var statef=document.getElementById("state"), curr= {{statef|tojson}}
document.getElementById('state').innerHTML=curr
console.log(curr);
console.log(statef);
</script>
|
[
"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('/login', methods=['GET', 'POST'])\ndef show_login():\n statef_data = {\n \"email\": \"demo@example.com\",\n \"name\": \"Alice\"\n }\n return render_template('login.html', statef=statef_data)\n\nlogin.html:\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Login</title>\n</head>\n<body>\n <div id=\"state\">\n\n </div>\n<script>\n var curr= {{ statef|tojson }};\n console.log(curr);\n console.log(typeof(curr));\n document.getElementById('state').innerHTML=curr[\"email\"] + \"<br>\"+curr[\"name\"];\n</script>\n</body>\n</html>\n\nOutput:\n\nConsole log:\n{email: 'demo@example.com', name: 'Alice'}\nlogin:14 object\n\nReferences:\n\nDocumentation of tojson filter in Flask template\n\n"
] |
[
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 indexed by n and i.
So at the moment my objective function is very messy as I have three sums. It looks something like (I expanded the brackets in the objective function and added each component separately, so the avgPrice_n*demand_n looks like):
expr += sum(sum(sum((1/12)*model.c[i]*model.allocation[i,n] for i in model.MP[t]) for t in model.M)*model.demand_n[n] for n in model.N)
And while this works, debugging was quite difficult because the terms are very long. So intead of using the actual definition of avgPrice_n, I was wondering if it would be possible to create a avgPrice_n variable, use this in the objective function and then create a constraint where I define avgPrice_n as I showed above.
The issue I am having is that I created my decision variable, x_{i,n}, as a variable but apparently I can't create a avgPrice_n as a variable where I index it by x_{i,n} as this results in a TypeError: Cannot apply a Set operator to an indexed Var component (allocation) error.
So as of now my decision variable looks like:
model.x = Var(model.NP_flat, domain = NonNegativeReals)
And I tried to create:
model.avg_Price = Var(model.x, domain = NonNegativeReals)
Which resulted in the above error. Any ideas or suggestions would be much appreciated!
A:
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.
The basic building blocks in the model are pyomo expressions, so you could put in a little "helper function" to build expressions (the cost function shown, which is dependent on n) which are not defined within the model, but just pop out an expression...totally legal). You can also "break up" large expressions into smaller expressions (like the other_stuff below) and then just kludge them all together in the objective (or where needed) this gives you the opportunity to evaluate them independently. I've made several models with an objective function that has a "cost" component and a "penalty" component by dividing it into 2 expressions.... Then when solved, you can inspect them independently.
My suggestion (if you don't like the triple sum in your current model) is to make an avg_cost(n) function to build the expression similar to what is done in the nonsensical function below, and use that as a substitute for a new variable.
Note: the initialization of the variables here is generally unnecessary. I just did it to "simulate solving" or they would be None...
Code:
import pyomo.environ as pyo
m = pyo.ConcreteModel()
m.N = pyo.Set(initialize=[0,1,2])
m.x = pyo.Var(m.N, initialize = 2.0)
def cost(n):
return m.x[n] + 2*m.x[n+1]
m.other_stuff = 3 * m.x[1] + 4 * m.x[2]
m.costs = sum(cost(n) for n in {0,1})
m.obj_expr = m.costs + m.other_stuff
m.obj = pyo.Objective(expr= m.obj_expr)
# inspect cost at a particular value of n...
print(cost(1))
print(pyo.value(cost(1)))
# inspect the pyomo expressions "other_stuff" and total costs...
print(m.other_stuff)
print(pyo.value(m.other_stuff))
print(m.costs)
print(pyo.value(m.costs))
# inspect the objective... which can be accessed by pprint() and display()
m.obj.pprint()
m.obj.display()
Output:
x[1] + 2*x[2]
6.0
3*x[1] + 4*x[2]
14.0
12.0
obj : Size=1, Index=None, Active=True
Key : Active : Sense : Expression
None : True : minimize : x[0] + 2*x[1] + x[1] + 2*x[2] + 3*x[1] + 4*x[2]
obj : Size=1, Index=None, Active=True
Key : Active : Value
None : True : 26.0
|
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 function is very messy as I have three sums. It looks something like (I expanded the brackets in the objective function and added each component separately, so the avgPrice_n*demand_n looks like):
expr += sum(sum(sum((1/12)*model.c[i]*model.allocation[i,n] for i in model.MP[t]) for t in model.M)*model.demand_n[n] for n in model.N)
And while this works, debugging was quite difficult because the terms are very long. So intead of using the actual definition of avgPrice_n, I was wondering if it would be possible to create a avgPrice_n variable, use this in the objective function and then create a constraint where I define avgPrice_n as I showed above.
The issue I am having is that I created my decision variable, x_{i,n}, as a variable but apparently I can't create a avgPrice_n as a variable where I index it by x_{i,n} as this results in a TypeError: Cannot apply a Set operator to an indexed Var component (allocation) error.
So as of now my decision variable looks like:
model.x = Var(model.NP_flat, domain = NonNegativeReals)
And I tried to create:
model.avg_Price = Var(model.x, domain = NonNegativeReals)
Which resulted in the above error. Any ideas or suggestions would be much appreciated!
|
[
"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 a little \"helper function\" to build expressions (the cost function shown, which is dependent on n) which are not defined within the model, but just pop out an expression...totally legal). You can also \"break up\" large expressions into smaller expressions (like the other_stuff below) and then just kludge them all together in the objective (or where needed) this gives you the opportunity to evaluate them independently. I've made several models with an objective function that has a \"cost\" component and a \"penalty\" component by dividing it into 2 expressions.... Then when solved, you can inspect them independently.\nMy suggestion (if you don't like the triple sum in your current model) is to make an avg_cost(n) function to build the expression similar to what is done in the nonsensical function below, and use that as a substitute for a new variable.\nNote: the initialization of the variables here is generally unnecessary. I just did it to \"simulate solving\" or they would be None...\nCode:\nimport pyomo.environ as pyo\n\nm = pyo.ConcreteModel()\n\nm.N = pyo.Set(initialize=[0,1,2])\n\nm.x = pyo.Var(m.N, initialize = 2.0)\n\ndef cost(n):\n return m.x[n] + 2*m.x[n+1]\n\nm.other_stuff = 3 * m.x[1] + 4 * m.x[2]\n\nm.costs = sum(cost(n) for n in {0,1})\n\nm.obj_expr = m.costs + m.other_stuff\n\nm.obj = pyo.Objective(expr= m.obj_expr)\n\n\n# inspect cost at a particular value of n...\nprint(cost(1))\nprint(pyo.value(cost(1)))\n\n# inspect the pyomo expressions \"other_stuff\" and total costs...\nprint(m.other_stuff)\nprint(pyo.value(m.other_stuff))\nprint(m.costs)\nprint(pyo.value(m.costs))\n\n# inspect the objective... which can be accessed by pprint() and display()\nm.obj.pprint()\nm.obj.display()\n\nOutput:\nx[1] + 2*x[2]\n6.0\n3*x[1] + 4*x[2]\n14.0\n12.0\nobj : Size=1, Index=None, Active=True\n Key : Active : Sense : Expression\n None : True : minimize : x[0] + 2*x[1] + x[1] + 2*x[2] + 3*x[1] + 4*x[2]\nobj : Size=1, Index=None, Active=True\n Key : Active : Value\n None : True : 26.0\n\n"
] |
[
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[1]/div/main/div/div/div/div/div[5]/div/div[2]/div/div[3]/div"))).click()
if __name__ == "__main__":
test()
A:
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.
free_case = driver.find_element(By.XPATH, ".//p[contains(text(),'Open your free')]")
driver.execute_script("arguments[0].scrollIntoView(true)", free_case)
time.sleep(1)
driver.execute_script("arguments[0].click();", free_case)
A:
First you need to wait for presence of that element.
Then you need to scroll the page down to make that element visible since initially this element is out of the visible screen so you can't click it.
Now you can click it and it works.
The code below is working:
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("start-maximized")
options.add_argument('--disable-notifications')
webdriver_service = Service('C:\webdrivers\chromedriver.exe')
driver = webdriver.Chrome(options=options, service=webdriver_service)
wait = WebDriverWait(driver, 10)
url = "https://bandit.camp/"
driver.get(url)
element = wait.until(EC.presence_of_element_located((By.XPATH, "//div[contains(.,'daily case')][contains(@class,'v-responsive__content')]")))
element.location_once_scrolled_into_view
time.sleep(0.3)
element.click()
|
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/div[2]/div/div[3]/div"))).click()
if __name__ == "__main__":
test()
|
[
"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.execute_script(\"arguments[0].click();\", free_case)\n\n",
"First you need to wait for presence of that element.\nThen you need to scroll the page down to make that element visible since initially this element is out of the visible screen so you can't click it.\nNow you can click it and it works.\nThe code below is working:\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\noptions = Options()\noptions.add_argument(\"start-maximized\")\noptions.add_argument('--disable-notifications')\n\nwebdriver_service = Service('C:\\webdrivers\\chromedriver.exe')\ndriver = webdriver.Chrome(options=options, service=webdriver_service)\nwait = WebDriverWait(driver, 10)\n\nurl = \"https://bandit.camp/\"\ndriver.get(url)\n\nelement = wait.until(EC.presence_of_element_located((By.XPATH, \"//div[contains(.,'daily case')][contains(@class,'v-responsive__content')]\")))\nelement.location_once_scrolled_into_view\ntime.sleep(0.3)\nelement.click()\n\n"
] |
[
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 frame.
Here's the 2nd video's first frame and its last frame.
I couldn't access the directory and batch download the files.
I took a look at this answer but it doesn't apply to me as I use Windows 10, and also checked this answer; I tried to merge them into for /l %x in (1, 1, 19999) do (wget https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%%xms/match/image.png) which did not work obviously.
I then downloaded Python 3.11 to try this answer but doesn't work, it's probably too old as it tells me urllib2 doesn't exist.
A:
You need to get two things: generate URLs of images, then download them.
Generating URLs can be done using for loop and formatting, consider following simple example
template = 'xxx/%05dms/match/image.png'
for i in range(1,11): # limited for brevity sake, adjust as requires
print(template % i)
gives output
xxx/00001ms/match/image.png
xxx/00002ms/match/image.png
xxx/00003ms/match/image.png
xxx/00004ms/match/image.png
xxx/00005ms/match/image.png
xxx/00006ms/match/image.png
xxx/00007ms/match/image.png
xxx/00008ms/match/image.png
xxx/00009ms/match/image.png
xxx/00010ms/match/image.png
%05d denotes put decimal number here, prefixed by zeros to width of 5 characters.
For downloading you might use urllib.urlretrieve rembering to furnish unique names, consider following simple example
import urllib
template_url = 'xxx/%05dms/match/image.png'
template_name = 'image%05d.png'
for i in range(1,11):
urllib.urlretrieve(template_url % i, template_name % i)
which after you set template_url to real one should download images to current working directory as image00001.png and so on.
Note: as you are using xrange I assume you must use python2 AT ANY PRICE, thus I use urllib.urlretrieve rather than urllib.request.urlretrieve and ancient method of string formatting rather than so-called f-strings.
A:
On Python 3.11 for Windows 10 64-bit
import urllib
import urllib.request
template_url = 'https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%05dms/match/image.png'
template_name = 'image%05d.png'
for i in range(0,20000):
f = template_name % i
urllib.request.urlretrieve(template_url % i, f)
It is very slow, it took me at least 5 hours to download everything as it does it 1-by-1 and sometimes stops working (due to the website) and doesn't restart automatically. And almost 80% of the images downloaded are duplicates so it's extremely unpractical (7 Go). And all the images are downloaded to a temp folder. But the code works! I believe it was made to replicate Minecraft but in software like After Effects so all the frames are just a teeny tiny bit different from each other...
Sources: Python 1
2 3 4 5 ; Stackoverflow 1 2 3 4 ; and @Daweo's help
|
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 access the directory and batch download the files.
I took a look at this answer but it doesn't apply to me as I use Windows 10, and also checked this answer; I tried to merge them into for /l %x in (1, 1, 19999) do (wget https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%%xms/match/image.png) which did not work obviously.
I then downloaded Python 3.11 to try this answer but doesn't work, it's probably too old as it tells me urllib2 doesn't exist.
|
[
"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 output\nxxx/00001ms/match/image.png\nxxx/00002ms/match/image.png\nxxx/00003ms/match/image.png\nxxx/00004ms/match/image.png\nxxx/00005ms/match/image.png\nxxx/00006ms/match/image.png\nxxx/00007ms/match/image.png\nxxx/00008ms/match/image.png\nxxx/00009ms/match/image.png\nxxx/00010ms/match/image.png\n\n%05d denotes put decimal number here, prefixed by zeros to width of 5 characters.\nFor downloading you might use urllib.urlretrieve rembering to furnish unique names, consider following simple example\nimport urllib\ntemplate_url = 'xxx/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(1,11):\n urllib.urlretrieve(template_url % i, template_name % i)\n\nwhich after you set template_url to real one should download images to current working directory as image00001.png and so on.\nNote: as you are using xrange I assume you must use python2 AT ANY PRICE, thus I use urllib.urlretrieve rather than urllib.request.urlretrieve and ancient method of string formatting rather than so-called f-strings.\n",
"On Python 3.11 for Windows 10 64-bit\nimport urllib\nimport urllib.request\ntemplate_url = 'https://cf-images.eu-west-1.prod.boltdns.net/v1/jit/719509184001/570e9336-d36c-4d41-8cbe-a67fe3bdc2b6/main/1280x720/%05dms/match/image.png'\ntemplate_name = 'image%05d.png'\nfor i in range(0,20000):\n f = template_name % i\n urllib.request.urlretrieve(template_url % i, f)\n\n\nIt is very slow, it took me at least 5 hours to download everything as it does it 1-by-1 and sometimes stops working (due to the website) and doesn't restart automatically. And almost 80% of the images downloaded are duplicates so it's extremely unpractical (7 Go). And all the images are downloaded to a temp folder. But the code works! I believe it was made to replicate Minecraft but in software like After Effects so all the frames are just a teeny tiny bit different from each other...\n\nSources: Python 1\n2 3 4 5 ; Stackoverflow 1 2 3 4 ; and @Daweo's help\n"
] |
[
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) + sign(1-x))/2
and output looks ok
But when trying to integrate PDF
integrate(u01,x)
I won't get CDF, just
So, question is, how to get it work
A:
With no additional assumptions, x is considered to be an arbitrary complex number. In your case you want x to be real:
x_real = Symbol('x', real=True)
u01_real = (sign(x_real) + sign(1-x_real))/2
integrate(u01_real,x_real)
This outputs
Piecewise((0, x < 0), (x, x < 1), (1, True))
See this document on assumptions for more details.
|
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 ok
But when trying to integrate PDF
integrate(u01,x)
I won't get CDF, just
So, question is, how to get it work
|
[
"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 assumptions for more details.\n"
] |
[
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 a version of python that does not support the pipe notation at all, even for two types...
A:
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.
|
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 notation at all, even for two types...
|
[
"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 your .txt file, and framing of your question; still I would like to answer. Maybe it helps you.
Assuming the structure of your .txt file is supposedly like this screenshot -
Following code does the purpose -
f_list = [] ## final or output list
with open('sample-file.txt', encoding='utf8') as f:
for line in f:
line_as_list = [] ## store `line` inside a list
line_as_list.append(line.strip('Intro: ').strip())
f_list.append(line_as_list)
f_list => [['hello, how are you I am fine.'], ['hey, how are you Hope you are fine.']]
|
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 open('sample-file.txt', encoding='utf8') as f:\n for line in f:\n line_as_list = [] ## store `line` inside a list\n line_as_list.append(line.strip('Intro: ').strip())\n f_list.append(line_as_list)\n\nf_list => [['hello, how are you I am fine.'], ['hey, how are you Hope you are fine.']]\n"
] |
[
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 places as well, so it makes sense to have it as property for my model.
Now I wanted to make the column of this property sortable, and with help of the Django documentation of the When object, this StackOverflow question for the F()-calculation and this link for the sorting I managed to build the working solution shown below.
The reason for posing a question here is: In fact, I implemented my logic twice, once in python and once in form of an expression, which is against the design rule of implementing the same logic only once. So I wanted to ask whether I missed a better solution to my problem. Any ideas are appreciated.
This is the model (identifyers modified):
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
# [several_attributes, Meta, __str__() removed for readability]
@property
def s_d(self):
if self.fr:
return self.de
else:
return self.gd + self.na
This is the Model Admin:
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d", "gd", "na", "de", "fr" )
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(
_s_d=Case(
When(fr=True, then='s_d'),
When(fr=False, then=F('gd') + F('na')),
default=Value(0),
output_field=IntegerField(),
)
)
return queryset
def s_d(self, obj):
return obj._s_d
s_d.admin_order_field = '_s_d'
If there is no other way, I would also appreciate confirmation of the fact as an answer.
A:
TL/DR: Yes your solution seems to follow the only way that makes sense.
Well, what you have composed here seems to be the recommended way from the sources you list in your question and for good reason.
What is the good reason though?
I haven't found a definitive, in the codebase, answer for that but I imagine that it has to do with the way @property decorator works in Python.
When we set a property with the decorator then we cannot add attributes to it and since the admin_order_field is an attribute then we can't have that in there. That statement seems to be reinforced from the Django Admin's list_display documentation where the following passage exists:
Elements of list_display can also be properties. Please note however, that due to the way properties work in Python, setting short_description on a property is only possible when using the property() function and not with the @property decorator.
That quote in combination with this QA: AttributeError: 'property' object has no attribute 'admin_order_field' seems to explain why it is not possible to have an orderable from a model property directly into the admin panel.
That explained (probably?) it is time for some mental gymnastics!!
In the previously mentioned part of the documentation we can also see that the admin_order_field can accept query expressions since version 2.1:
Query expressions may be used in admin_order_field. For example:
from django.db.models import Value
from django.db.models.functions import Concat
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def full_name(self):
return self.first_name + ' ' + self.last_name
full_name.admin_order_field = Concat('first_name', Value(' '), 'last_name')
That in conjunction with the previous part about the property() method, allows us to refactor your code and essentially move the annotation part to the model:
class De(models.Model):
...
def calculate_s_d(self):
if self.fr:
return self.de
else:
return self.gd + self.na
calculate_s_d.admin_order_field = Case(
When(fr=True, then='s_d'),
When(fr=False, then=F('gd') + F('na')),
default=Value(0),
output_field=IntegerField(),
)
s_d = property(calculate_s_d)
Finally, on the admin.py we only need:
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d")
A:
Although I think your solution is very good (or even better), the another approach can be to extract admin query to the model manager:
class DeManager(models.Manager):
def get_queryset(self):
return super().get_queryset().annotate(
s_d=Case(
When(fr=True, then='s_d'),
When(fr=False, then=F('gd') + F('na')),
default=Value(0),
output_field=IntegerField(),
)
)
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
objects = DeManager()
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d", "gd", "na", "de", "fr" )
In this case you don't need the property because each object will have s_d attribute, although this is true only for existing objects (from the database). If you create a new object in Python and try to access obj.s_d you will get an error. Another disadvantage is that each query will be annotated with this attribute even if you don't use it, but this can be solved by customizing the manager's queryset.
A:
Unfortunately, this is impossible in current stable Django version (up to 2.2) due to Django admin not fetching admin_order_field from object properties.
Fortunately, it will be possible in upcoming Django version (3.0 and up) which should be released on 2nd of December.
The way to achieve it:
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
# [several_attributes, Meta, __str__() removed for readability]
def s_d(self):
if self.fr:
return self.de
else:
return self.gd + self.na
s_d.admin_order_field = '_s_d'
s_d = property(s_d)
Alternatively, you can create some decorator that will add any attribute to function, before converting it to property:
def decorate(**kwargs):
def wrap(function):
for name, value in kwargs.iteritems():
setattr(function, name, value)
return function
return wrap
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
# [several_attributes, Meta, __str__() removed for readability]
@property
@decorate(admin_order_field='_s_d')
def s_d(self):
if self.fr:
return self.de
else:
return self.gd + self.na
A:
Another possible solution might be to convert the s_d property to a model field and override the model save method to keep it up to date.
# models.py
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
s_d = models.SmallIntegerField("[...]", blank=True)
# [several_attributes, Meta, __str__() removed for readability]
def save(self, *args, **kwargs):
if self.fr:
self.s_d = self.de
else:
self.s_d = self.gd + self.na
super().save(*args, **kwargs)
# admin.py
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d", "gd", "na", "de", "fr" )
The default sorting in admin.py will be applied and the value of s_d will be updated every time the model is saved.
There is a caveat to this method if you plan to do a lot of bulk operations, such as bulk_create, update, or delete.
Overridden model methods are not called on bulk operations
Note that the delete() method for an object is not necessarily called
when deleting objects in bulk using a QuerySet or as a result of a
cascading delete. To ensure customized delete logic gets executed, you
can use pre_delete and/or post_delete signals.
Unfortunately, there isn’t a workaround when creating or updating
objects in bulk, since none of save(), pre_save, and post_save are
called.
A:
The solutions presented in answers to this question work only if the property inherits ordering from one or more db columns. In this answer I share a solution that works with any property and operates on queryset results with some limitations on multiple ordering.
I am using Django 4.1.
Given the model in the question I put a random value generation in the property just as an example of values retrieved independent from db columns so that we cannot retrieve ordering from db.
import random
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
# [several_attributes, Meta, __str__() removed for readability]
def s_d(self):
"""
Just as example: adds a perturbation so it is not possible
to inherit ordering by db columns
"""
X = random.randrange(128)
if self.fr:
return self.de*X
else:
return self.gd*X + self.na
s_d.admin_order_field = 'cielcio_to_be_removed'
s_d = property(s_d)
The solution I have used sets ChangeList.result_list overloading the ModelAdmin.paginator. This choice has the benefit to operate on computed results while the cons of not using the database ordering.
I use also a class DeChangeList inherited from ChangeList to remove the fake field set as value of admin_order_field so that I got the admin table header clickable.
from django.contrib import admin
from django.contrib.admin.views.main import ChangeList
class DeChangeList(ChangeList):
def get_ordering(self, request, queryset):
"""
Removes the fake field used to show upper
and lower arrow in changelist table header
"""
ordering = super().get_ordering(request, queryset)
if 'cielcio_to_be_removed' in ordering:
ordering.remove('cielcio_to_be_removed')
if '-cielcio_to_be_removed' in ordering:
ordering.remove('-cielcio_to_be_removed')
return ordering
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d", "gd", "na", "de", "fr" )
def get_changelist(self, request, **kwargs):
return DeChangeList
def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):
"""
Intercepts queryset and order by values with 'sorted'
"""
index_s_p = self.list_display.index('s_p')
ordering = request.GET.get('o', "99999")
instances = []
for nf in ordering.split("."):
reverse = int(nf) < 0
if abs(int(nf)) == index_s_p+1:
instances = sorted(
queryset,
key=lambda a: (a.s_p is not None if reverse else a.s_p is None, a.s_p),
reverse=reverse
)
return super().get_paginator(
request, instances or queryset,
per_page, orphans, allow_empty_first_page)
|
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 this property sortable, and with help of the Django documentation of the When object, this StackOverflow question for the F()-calculation and this link for the sorting I managed to build the working solution shown below.
The reason for posing a question here is: In fact, I implemented my logic twice, once in python and once in form of an expression, which is against the design rule of implementing the same logic only once. So I wanted to ask whether I missed a better solution to my problem. Any ideas are appreciated.
This is the model (identifyers modified):
class De(models.Model):
fr = models.BooleanField("[...]")
de = models.SmallIntegerField("[...]")
gd = models.SmallIntegerField("[...]")
na = models.SmallIntegerField("[...]")
# [several_attributes, Meta, __str__() removed for readability]
@property
def s_d(self):
if self.fr:
return self.de
else:
return self.gd + self.na
This is the Model Admin:
class DeAdmin(admin.ModelAdmin):
list_display = ("[...]", "s_d", "gd", "na", "de", "fr" )
def get_queryset(self, request):
queryset = super().get_queryset(request)
queryset = queryset.annotate(
_s_d=Case(
When(fr=True, then='s_d'),
When(fr=False, then=F('gd') + F('na')),
default=Value(0),
output_field=IntegerField(),
)
)
return queryset
def s_d(self, obj):
return obj._s_d
s_d.admin_order_field = '_s_d'
If there is no other way, I would also appreciate confirmation of the fact as an answer.
|
[
"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 that it has to do with the way @property decorator works in Python. \nWhen we set a property with the decorator then we cannot add attributes to it and since the admin_order_field is an attribute then we can't have that in there. That statement seems to be reinforced from the Django Admin's list_display documentation where the following passage exists:\n\nElements of list_display can also be properties. Please note however, that due to the way properties work in Python, setting short_description on a property is only possible when using the property() function and not with the @property decorator.\n\nThat quote in combination with this QA: AttributeError: 'property' object has no attribute 'admin_order_field' seems to explain why it is not possible to have an orderable from a model property directly into the admin panel.\n\nThat explained (probably?) it is time for some mental gymnastics!!\nIn the previously mentioned part of the documentation we can also see that the admin_order_field can accept query expressions since version 2.1:\n\nQuery expressions may be used in admin_order_field. For example:\nfrom django.db.models import Value\nfrom django.db.models.functions import Concat\n\nclass Person(models.Model):\n first_name = models.CharField(max_length=50)\n last_name = models.CharField(max_length=50)\n\n def full_name(self):\n return self.first_name + ' ' + self.last_name\n full_name.admin_order_field = Concat('first_name', Value(' '), 'last_name')\n\n\nThat in conjunction with the previous part about the property() method, allows us to refactor your code and essentially move the annotation part to the model:\nclass De(models.Model):\n ...\n def calculate_s_d(self):\n if self.fr:\n return self.de\n else:\n return self.gd + self.na\n\n calculate_s_d.admin_order_field = Case(\n When(fr=True, then='s_d'),\n When(fr=False, then=F('gd') + F('na')),\n default=Value(0),\n output_field=IntegerField(),\n )\n\n s_d = property(calculate_s_d)\n\nFinally, on the admin.py we only need:\nclass DeAdmin(admin.ModelAdmin):\n list_display = (\"[...]\", \"s_d\")\n\n",
"Although I think your solution is very good (or even better), the another approach can be to extract admin query to the model manager:\nclass DeManager(models.Manager):\n def get_queryset(self):\n return super().get_queryset().annotate(\n s_d=Case(\n When(fr=True, then='s_d'),\n When(fr=False, then=F('gd') + F('na')),\n default=Value(0),\n output_field=IntegerField(),\n )\n )\n\n\nclass De(models.Model):\n fr = models.BooleanField(\"[...]\")\n de = models.SmallIntegerField(\"[...]\")\n gd = models.SmallIntegerField(\"[...]\")\n na = models.SmallIntegerField(\"[...]\")\n objects = DeManager()\n\n\nclass DeAdmin(admin.ModelAdmin):\n list_display = (\"[...]\", \"s_d\", \"gd\", \"na\", \"de\", \"fr\" )\n\nIn this case you don't need the property because each object will have s_d attribute, although this is true only for existing objects (from the database). If you create a new object in Python and try to access obj.s_d you will get an error. Another disadvantage is that each query will be annotated with this attribute even if you don't use it, but this can be solved by customizing the manager's queryset.\n",
"Unfortunately, this is impossible in current stable Django version (up to 2.2) due to Django admin not fetching admin_order_field from object properties.\nFortunately, it will be possible in upcoming Django version (3.0 and up) which should be released on 2nd of December.\nThe way to achieve it:\nclass De(models.Model):\n\n fr = models.BooleanField(\"[...]\")\n de = models.SmallIntegerField(\"[...]\")\n gd = models.SmallIntegerField(\"[...]\")\n na = models.SmallIntegerField(\"[...]\")\n # [several_attributes, Meta, __str__() removed for readability]\n\n def s_d(self):\n if self.fr:\n return self.de\n else:\n return self.gd + self.na\n s_d.admin_order_field = '_s_d'\n s_d = property(s_d)\n\nAlternatively, you can create some decorator that will add any attribute to function, before converting it to property:\ndef decorate(**kwargs):\n def wrap(function):\n for name, value in kwargs.iteritems():\n setattr(function, name, value)\n\n return function\n return wrap\n\nclass De(models.Model):\n\n fr = models.BooleanField(\"[...]\")\n de = models.SmallIntegerField(\"[...]\")\n gd = models.SmallIntegerField(\"[...]\")\n na = models.SmallIntegerField(\"[...]\")\n # [several_attributes, Meta, __str__() removed for readability]\n\n @property\n @decorate(admin_order_field='_s_d')\n def s_d(self):\n if self.fr:\n return self.de\n else:\n return self.gd + self.na\n\n",
"Another possible solution might be to convert the s_d property to a model field and override the model save method to keep it up to date.\n# models.py\n\nclass De(models.Model):\n\n fr = models.BooleanField(\"[...]\")\n de = models.SmallIntegerField(\"[...]\")\n gd = models.SmallIntegerField(\"[...]\")\n na = models.SmallIntegerField(\"[...]\")\n s_d = models.SmallIntegerField(\"[...]\", blank=True)\n\n # [several_attributes, Meta, __str__() removed for readability]\n\n def save(self, *args, **kwargs):\n if self.fr:\n self.s_d = self.de\n else:\n self.s_d = self.gd + self.na\n super().save(*args, **kwargs)\n\n# admin.py\n\nclass DeAdmin(admin.ModelAdmin):\n list_display = (\"[...]\", \"s_d\", \"gd\", \"na\", \"de\", \"fr\" )\n\nThe default sorting in admin.py will be applied and the value of s_d will be updated every time the model is saved.\nThere is a caveat to this method if you plan to do a lot of bulk operations, such as bulk_create, update, or delete.\n\nOverridden model methods are not called on bulk operations\nNote that the delete() method for an object is not necessarily called\n when deleting objects in bulk using a QuerySet or as a result of a\n cascading delete. To ensure customized delete logic gets executed, you\n can use pre_delete and/or post_delete signals.\nUnfortunately, there isn’t a workaround when creating or updating\n objects in bulk, since none of save(), pre_save, and post_save are\n called.\n\n",
"The solutions presented in answers to this question work only if the property inherits ordering from one or more db columns. In this answer I share a solution that works with any property and operates on queryset results with some limitations on multiple ordering.\nI am using Django 4.1.\nGiven the model in the question I put a random value generation in the property just as an example of values retrieved independent from db columns so that we cannot retrieve ordering from db.\nimport random\n\nclass De(models.Model):\n\n fr = models.BooleanField(\"[...]\")\n de = models.SmallIntegerField(\"[...]\")\n gd = models.SmallIntegerField(\"[...]\")\n na = models.SmallIntegerField(\"[...]\")\n # [several_attributes, Meta, __str__() removed for readability]\n\n def s_d(self):\n \"\"\"\n Just as example: adds a perturbation so it is not possible\n to inherit ordering by db columns\n \"\"\"\n X = random.randrange(128)\n if self.fr:\n return self.de*X\n else:\n return self.gd*X + self.na\n s_d.admin_order_field = 'cielcio_to_be_removed'\n s_d = property(s_d)\n\nThe solution I have used sets ChangeList.result_list overloading the ModelAdmin.paginator. This choice has the benefit to operate on computed results while the cons of not using the database ordering.\nI use also a class DeChangeList inherited from ChangeList to remove the fake field set as value of admin_order_field so that I got the admin table header clickable.\nfrom django.contrib import admin\nfrom django.contrib.admin.views.main import ChangeList\n\nclass DeChangeList(ChangeList):\n\n def get_ordering(self, request, queryset):\n \"\"\"\n Removes the fake field used to show upper\n and lower arrow in changelist table header\n \"\"\"\n ordering = super().get_ordering(request, queryset)\n if 'cielcio_to_be_removed' in ordering:\n ordering.remove('cielcio_to_be_removed')\n if '-cielcio_to_be_removed' in ordering:\n ordering.remove('-cielcio_to_be_removed')\n return ordering\n\n\nclass DeAdmin(admin.ModelAdmin):\n\n list_display = (\"[...]\", \"s_d\", \"gd\", \"na\", \"de\", \"fr\" )\n\n def get_changelist(self, request, **kwargs):\n return DeChangeList\n\n def get_paginator(self, request, queryset, per_page, orphans=0, allow_empty_first_page=True):\n \"\"\"\n Intercepts queryset and order by values with 'sorted'\n \"\"\"\n\n index_s_p = self.list_display.index('s_p')\n ordering = request.GET.get('o', \"99999\")\n\n instances = []\n for nf in ordering.split(\".\"):\n reverse = int(nf) < 0\n if abs(int(nf)) == index_s_p+1:\n instances = sorted(\n queryset,\n key=lambda a: (a.s_p is not None if reverse else a.s_p is None, a.s_p),\n reverse=reverse\n )\n\n return super().get_paginator(\n request, instances or queryset,\n per_page, orphans, allow_empty_first_page)\n\n"
] |
[
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 = ['(a,b)']
# creating the dataframe
df = pd.DataFrame(data = array,
index = index_values,
columns = column_values)
df
returns :
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_45/2020978637.py in <module>
13 df = pd.DataFrame(data = array,
14 index = index_values,
---> 15 columns = column_values)
16
17 df
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
676 dtype=dtype,
677 copy=copy,
--> 678 typ=manager,
679 )
680
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in ndarray_to_mgr(values, index, columns, dtype, copy, typ)
302 # by definition an array here
303 # the dtypes will be coerced to a single dtype
--> 304 values = _prep_ndarray(values, copy=copy)
305
306 if dtype is not None and not is_dtype_equal(values.dtype, dtype):
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in _prep_ndarray(values, copy)
553 values = values.reshape((values.shape[0], 1))
554 elif values.ndim != 2:
--> 555 raise ValueError(f"Must pass 2-d input. shape={values.shape}")
556
557 return values
ValueError: Must pass 2-d input. shape=(2, 1, 2)
Using a single element tuple :
array = np.array([[(1)], [(2)]])
A:
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).
Do the following -
array = np.array([[('A',1)], [('B',2)]], dtype=('<U10,int')).astype(object)
index_values = ['x1', 'x2']
column_values = ['(a,b)']
df = pd.DataFrame(data = array, index = index_values, columns = column_values)
Output:
>>> df
(a,b)
x1 (A, 1)
x2 (B, 2)
|
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.DataFrame(data = array,
index = index_values,
columns = column_values)
df
returns :
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/tmp/ipykernel_45/2020978637.py in <module>
13 df = pd.DataFrame(data = array,
14 index = index_values,
---> 15 columns = column_values)
16
17 df
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
676 dtype=dtype,
677 copy=copy,
--> 678 typ=manager,
679 )
680
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in ndarray_to_mgr(values, index, columns, dtype, copy, typ)
302 # by definition an array here
303 # the dtypes will be coerced to a single dtype
--> 304 values = _prep_ndarray(values, copy=copy)
305
306 if dtype is not None and not is_dtype_equal(values.dtype, dtype):
/opt/oss/conda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in _prep_ndarray(values, copy)
553 values = values.reshape((values.shape[0], 1))
554 elif values.ndim != 2:
--> 555 raise ValueError(f"Must pass 2-d input. shape={values.shape}")
556
557 return values
ValueError: Must pass 2-d input. shape=(2, 1, 2)
Using a single element tuple :
array = np.array([[(1)], [(2)]])
|
[
"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,int')).astype(object)\n\nindex_values = ['x1', 'x2']\n\ncolumn_values = ['(a,b)']\n\ndf = pd.DataFrame(data = array, index = index_values, columns = column_values)\n\nOutput:\n>>> df\n (a,b)\nx1 (A, 1)\nx2 (B, 2)\n\n"
] |
[
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 want to use it for n=7 where any two states have a transition probability, it can get very messy with all the arrows, which is why I wanted to use the parameter alpha in the matplotlib.patches.FancyArrow() function.
However, I have tested it and while I get an error if I give it a value outside of the interval [0,1], any value in that interval seems to do nothing, whether it's 0.001 or 0.999. The documentation isn't great, it includes alpha as a possible kwarg but the description just says "unknown". In the "Arrow Guide" there is no mention of this parameter at all. So does anyone know how I can make my arrows more transparent?
Here is a code example where you can change alpha and see no change:
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(20,20))
plt.xlim(-10,10)
plt.ylim(-10,10)
coords = [(5,7),(3,-6),(0,5),(-2,-4)]
for (x,y) in coords:
arrow = mpatches.FancyArrow(0,0,x,y,
width = .2,
head_width = 1,
length_includes_head = True,
alpha = 0.1)
p = PatchCollection(
[arrow],
edgecolor = '#a3a3a3',
facecolor = '#a3a3a3'
)
ax.add_collection(p)
plt.axis("off")
plt.show()
A:
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
|
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 probability, it can get very messy with all the arrows, which is why I wanted to use the parameter alpha in the matplotlib.patches.FancyArrow() function.
However, I have tested it and while I get an error if I give it a value outside of the interval [0,1], any value in that interval seems to do nothing, whether it's 0.001 or 0.999. The documentation isn't great, it includes alpha as a possible kwarg but the description just says "unknown". In the "Arrow Guide" there is no mention of this parameter at all. So does anyone know how I can make my arrows more transparent?
Here is a code example where you can change alpha and see no change:
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(20,20))
plt.xlim(-10,10)
plt.ylim(-10,10)
coords = [(5,7),(3,-6),(0,5),(-2,-4)]
for (x,y) in coords:
arrow = mpatches.FancyArrow(0,0,x,y,
width = .2,
head_width = 1,
length_includes_head = True,
alpha = 0.1)
p = PatchCollection(
[arrow],
edgecolor = '#a3a3a3',
facecolor = '#a3a3a3'
)
ax.add_collection(p)
plt.axis("off")
plt.show()
|
[
"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 = models.DateTimeField(help_text = "Разделяйте даты точками! Используйте '/' или '-'")
# analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу
analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1)
analysis_data = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.patient}"
def get_analysis_type(self):
return f"{self.analysis_type}"
def get_absolute_url(self):
return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk})
class Meta:
unique_together = ('analysis_date','analysis_type',)
Here's the class for list all analyses per patient
class PatientAnalysisListView(ListView):
model = PatientAnalysis
template_name = 'journal/patient_analysis.html'
context_object_name = 'analysis'
def get_context_data(self, *, object_list=None, **kwargs):
<...>
return context
def get_queryset(self):
return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date')
And here i stuck with next code:
class PatientAnalysisDeleteView(DeleteView):
# Form --> Confirm Delete Button
# model_confirm_delete.html
model = PatientAnalysis
success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient})
And getting error:
NoReverseMatch at /journal/patientanalysis_delete/49
Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\\Z']
Request Method: POST
Request URL: http://127.0.0.1:8000/journal/patientanalysis_delete/49
Django Version: 4.1.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\\Z']
Exception Location: /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix
Raised during: journal.views.PatientAnalysisDeleteView
Python Executable: /usr/bin/python3
Python Version: 3.10.6
Python Path:
['/home/verts/Documents/social-network/social_network/medicine',
'/usr/lib/python310.zip',
'/usr/lib/python3.10',
'/usr/lib/python3.10/lib-dynload',
'/home/verts/.local/lib/python3.10/site-packages',
'/usr/local/lib/python3.10/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 26 Nov 2022 21:24:52 +0300`
Tried to make a funtion to get succes url but unsuccesfully.
EDIT: Additionally to Willem Van Onsem solution you can simply reverse via html code:
<form action="../patient_analysis/{{patientanalysis.patient.hist_num}}" method="POST">
A:
You can override the .get_success_url() method [Django-doc] to return the path to which we redirect:
from django.urls import reverse
class PatientAnalysisDeleteView(DeleteView):
model = PatientAnalysis
def get_success_url(self):
return reverse(
'journal:patient_analysis',
kwargs={'hist_num_slug': self.object.patient_id},
)
|
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 = "Разделяйте даты точками! Используйте '/' или '-'")
# analysis_type = models.IntegerField(choices = ANALYSIS_CHOICES) #перевести в таблицу
analysis_type = models.ForeignKey(AnalysisType, on_delete=models.CASCADE, default=1)
analysis_data = models.DecimalField(max_digits=5, decimal_places=2)
def __str__(self):
return f"{self.patient}"
def get_analysis_type(self):
return f"{self.analysis_type}"
def get_absolute_url(self):
return reverse('journal:patient_analysis', kwargs={'hist_num_slug':self.patient.pk})
class Meta:
unique_together = ('analysis_date','analysis_type',)
Here's the class for list all analyses per patient
class PatientAnalysisListView(ListView):
model = PatientAnalysis
template_name = 'journal/patient_analysis.html'
context_object_name = 'analysis'
def get_context_data(self, *, object_list=None, **kwargs):
<...>
return context
def get_queryset(self):
return PatientAnalysis.objects.filter(patient__hist_num=self.kwargs['hist_num_slug']).order_by('-analysis_date')
And here i stuck with next code:
class PatientAnalysisDeleteView(DeleteView):
# Form --> Confirm Delete Button
# model_confirm_delete.html
model = PatientAnalysis
success_url = reverse_lazy('journal:patient_analysis', kwargs={'key': model.patient})
And getting error:
NoReverseMatch at /journal/patientanalysis_delete/49
Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\\Z']
Request Method: POST
Request URL: http://127.0.0.1:8000/journal/patientanalysis_delete/49
Django Version: 4.1.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'patient_analysis' with keyword arguments '{'key': <django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x7fb88b8c0d90>}' not found. 1 pattern(s) tried: ['journal/patient_analysis/(?P<hist_num_slug>[-a-zA-Z0-9_]+)\\Z']
Exception Location: /home/verts/.local/lib/python3.10/site-packages/django/urls/resolvers.py, line 828, in _reverse_with_prefix
Raised during: journal.views.PatientAnalysisDeleteView
Python Executable: /usr/bin/python3
Python Version: 3.10.6
Python Path:
['/home/verts/Documents/social-network/social_network/medicine',
'/usr/lib/python310.zip',
'/usr/lib/python3.10',
'/usr/lib/python3.10/lib-dynload',
'/home/verts/.local/lib/python3.10/site-packages',
'/usr/local/lib/python3.10/dist-packages',
'/usr/lib/python3/dist-packages']
Server time: Sat, 26 Nov 2022 21:24:52 +0300`
Tried to make a funtion to get succes url but unsuccesfully.
EDIT: Additionally to Willem Van Onsem solution you can simply reverse via html code:
<form action="../patient_analysis/{{patientanalysis.patient.hist_num}}" method="POST">
|
[
"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 kwargs={'hist_num_slug': self.object.patient_id},\n )\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_filters.CharFilter(label="Kategorie", field_name="ucet__cislo__kategorie__jmeno", lookup_expr='icontains')
And I have following structure of models in models.py:
class Data(models.Model):
ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True)
class Ucty(models.Model):
cislo = models.IntegerField("Účet", blank=True, null=True)
class Mustek(models.Model):
ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE)
kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE)
class Kategorie(models.Model):
jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True)
Any idea how to correct field_name definition in filter?
A:
Since cislo is an IntegerField, you can not join on this. you probably want to join on Mustek in reverse however, so:
kategorie = django_filters.CharFilter(
label='Kategorie',
field_name='ucet__mustek__kategorie__jmeno',
lookup_expr='icontains',
)
|
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')
And I have following structure of models in models.py:
class Data(models.Model):
ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE, null=True, blank=True)
class Ucty(models.Model):
cislo = models.IntegerField("Účet", blank=True, null=True)
class Mustek(models.Model):
ucet = models.ForeignKey(Ucty, on_delete=models.CASCADE)
kategorie = models.ForeignKey(Kategorie, on_delete=models.CASCADE)
class Kategorie(models.Model):
jmeno = models.CharField("Kategorie", max_length=20, blank=True, null=True)
Any idea how to correct field_name definition in filter?
|
[
"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 "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\Python\Projects\disco bot\ppap", line 21, in <module>
client.run(os.getenv("K"))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C2A7BA30D0>
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
This is the code:
import discord
import os
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv("K"))
I have my bot key stored in an .env file and the key is correct.
I have reset the key multiple times and enabled all intent settings for the bot but nothing has helped. How would i fix this?
A:
According to this question, you should try:
Resetting your token, it could be invalid
Enabling intents on the developer portal
|
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\lib\site-packages\discord\http.py", line 744, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "d:\Python\Projects\disco bot\ppap", line 21, in <module>
client.run(os.getenv("K"))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\runners.py", line 44, in run
return loop.run_until_complete(main)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 647, in run_until_complete
return future.result()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 817, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 745, in start
await self.login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 580, in login
data = await self.http.static_login(token)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 805, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C2A7BA30D0>
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
This is the code:
import discord
import os
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run(os.getenv("K"))
I have my bot key stored in an .env file and the key is correct.
I have reset the key multiple times and enabled all intent settings for the bot but nothing has helped. How would i fix this?
|
[
"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 pressing the button or releasing it. Not sure how I go about measuring the time between one and the other... I tried this:
`
def time_string_to_decimals(time_string):
fields = time_string.split(":")
hours = fields[0] if len(fields) > 0 else 0.0
minutes = fields[1] if len(fields) > 1 else 0.0
seconds = fields[2] if len(fields) > 2 else 0.0
return float(hours) + (float(minutes) / 60.0) + (float(seconds) / pow(60.0, 2))
while True:
t = datetime.now().strftime('%H:%M:%S')
now = time_string_to_decimals(t)
@keybow.on()
def handle_key(index, state):
key0Up = 0
key0Down = 0
if index == 0 and state:
key0Down = now
print ("down: " + str(now))
if index == 0 and not state:
key0Up = now
downtime = key0Up - key0Down
print ("down: " + str(now))
print ("up: " + str(now))
print ("downtime: " + str(downtime))
if downtime >= 0.001:
print ("shutdown!")
if index == 3 and not state:
print ("Hello!")
if index == 6 and not state:
print ("World!")
`
... the print commands are just to follow what's going on. The problem is that the key0Down also get's set to the current time when the button is released. I'm stumped. Can anyone point me in the right direction?
Thanks!
Best regards,
Andrew
See above... I keep getting the same 'timestamp' for the key Down und key Up event...
A:
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.
I don't have this hardware so it is not possible for me to test this. However, looking through the repository you linked to I would be tempted to do the following...
As you need to share the key events timings between functions I would put them into a class and have class variables for the key0up and key0down values.
I have also gone for different event handlers for the different keys to simplify the complex chain of if statements.
I was not sure if the keybow on decorator would do the right thing if used inside a class, so I have attached callbacks to keys without using a decorator.
import keybow
import time
class MyKeys:
key0Up = 0
key0Down = 0
def handle_key0(self, index, state):
if state:
self.key0Down = time.time()
print("down: ", self.key0Down)
elif not state:
self.key0Up = time.time()
downtime = self.key0Up - self.key0Down
print("down: ", self.key0Down)
print("up: ", self.key0Up)
print("downtime: ", downtime)
if downtime >= 1: # Greater than 1 second
print("shutdown!")
def handle_key3(self, index, state):
if not state:
print("Hello!")
def handle_key6(self, index, state):
if not state:
print("World!")
def main():
my_keys = MyKeys()
keybow.on(0, my_keys.handle_key0)
keybow.on(3, my_keys.handle_key3)
keybow.on(6, my_keys.handle_key6)
while True:
keybow.show()
time.sleep(1.0 / 60.0)
if __name__ == '__main__':
main()
|
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. Not sure how I go about measuring the time between one and the other... I tried this:
`
def time_string_to_decimals(time_string):
fields = time_string.split(":")
hours = fields[0] if len(fields) > 0 else 0.0
minutes = fields[1] if len(fields) > 1 else 0.0
seconds = fields[2] if len(fields) > 2 else 0.0
return float(hours) + (float(minutes) / 60.0) + (float(seconds) / pow(60.0, 2))
while True:
t = datetime.now().strftime('%H:%M:%S')
now = time_string_to_decimals(t)
@keybow.on()
def handle_key(index, state):
key0Up = 0
key0Down = 0
if index == 0 and state:
key0Down = now
print ("down: " + str(now))
if index == 0 and not state:
key0Up = now
downtime = key0Up - key0Down
print ("down: " + str(now))
print ("up: " + str(now))
print ("downtime: " + str(downtime))
if downtime >= 0.001:
print ("shutdown!")
if index == 3 and not state:
print ("Hello!")
if index == 6 and not state:
print ("World!")
`
... the print commands are just to follow what's going on. The problem is that the key0Down also get's set to the current time when the button is released. I'm stumped. Can anyone point me in the right direction?
Thanks!
Best regards,
Andrew
See above... I keep getting the same 'timestamp' for the key Down und key Up event...
|
[
"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 possible for me to test this. However, looking through the repository you linked to I would be tempted to do the following...\nAs you need to share the key events timings between functions I would put them into a class and have class variables for the key0up and key0down values.\nI have also gone for different event handlers for the different keys to simplify the complex chain of if statements.\nI was not sure if the keybow on decorator would do the right thing if used inside a class, so I have attached callbacks to keys without using a decorator.\nimport keybow\nimport time\n\n\nclass MyKeys:\n key0Up = 0\n key0Down = 0\n\n def handle_key0(self, index, state):\n if state:\n self.key0Down = time.time()\n print(\"down: \", self.key0Down)\n elif not state:\n self.key0Up = time.time()\n downtime = self.key0Up - self.key0Down\n print(\"down: \", self.key0Down)\n print(\"up: \", self.key0Up)\n print(\"downtime: \", downtime)\n if downtime >= 1: # Greater than 1 second\n print(\"shutdown!\")\n\n def handle_key3(self, index, state):\n if not state:\n print(\"Hello!\")\n\n def handle_key6(self, index, state):\n if not state:\n print(\"World!\")\n\n\ndef main():\n my_keys = MyKeys()\n keybow.on(0, my_keys.handle_key0)\n keybow.on(3, my_keys.handle_key3)\n keybow.on(6, my_keys.handle_key6)\n while True:\n keybow.show()\n time.sleep(1.0 / 60.0)\n\n\nif __name__ == '__main__':\n main()\n\n"
] |
[
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 result like this
MyClass.instantiate_from_iterable([1, 5, 3]) == MyClass(1, 5, 3)
MyClass.instantiate_from_iterable((3, 1, 7)) == MyClass(3, 1, 7)
I have no idea how to do this. If someone could help, I would appreciate it very much!
A:
classmethod is what what you're after:
from collections.abc import Iterable
class MyClass:
def __init__(self, *args):
self.args = args
@classmethod
def instantiate_from_iterable(cls, args: Iterable):
return cls(*args)
a = MyClass(1, 5, 7)
b = MyClass.instantiate_from_iterable([1, 5, 7])
print(a.args) # -> (1, 5, 7)
print(b.args) # -> (1, 5, 7)
A:
I am not sure what you would like to do.
Try the following:
class MyClass:
def __init__(self, *args):
self.args = args
def __eq__(self, other):
if not isinstance(other, MyClass):
return False
else:
return self.args == other.args
assert MyClass(1, 5, 3) == MyClass(*[1, 5, 3])
There would be no need for a clever function. Just unpack the list with the * before the list or tuple.
You would make the object comparably using the magic function __eq__ to make them comparable.
|
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]) == MyClass(1, 5, 3)
MyClass.instantiate_from_iterable((3, 1, 7)) == MyClass(3, 1, 7)
I have no idea how to do this. If someone could help, I would appreciate it very much!
|
[
"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_from_iterable([1, 5, 7])\n \nprint(a.args) # -> (1, 5, 7)\nprint(b.args) # -> (1, 5, 7)\n\n",
"I am not sure what you would like to do.\nTry the following:\nclass MyClass:\n\n def __init__(self, *args):\n self.args = args\n\n \n def __eq__(self, other):\n if not isinstance(other, MyClass):\n return False\n else:\n return self.args == other.args\n\nassert MyClass(1, 5, 3) == MyClass(*[1, 5, 3]) \n\nThere would be no need for a clever function. Just unpack the list with the * before the list or tuple.\nYou would make the object comparably using the magic function __eq__ to make them comparable.\n"
] |
[
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 = [
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name": "Mark", "age": 5,"group":"sdo","points":0},
{"name": "Pam", "age": 7,"group":"spp","points":0},
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name": "Buke", "age": 31,"group":"pool","points":0}
]
print(a)
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i] == a[j]:
a.pop[j]
print(a)
A:
If I understand you correctly, the duplicate is only when name, age and group match:
a = [
{"name": "Tom", "age": 21, "group": "sdd", "points": 0},
{"name": "Mark", "age": 5, "group": "sdo", "points": 0},
{"name": "Pam", "age": 7, "group": "spp", "points": 0},
{"name": "Tom", "age": 21, "group": "sdd", "points": 0},
{"name": "Buke", "age": 31, "group": "pool", "points": 0},
]
out, seen = [], set()
for d in a:
tpl = d["name"], d["age"], d["group"]
if tpl not in seen:
seen.add(tpl)
out.append(d)
print(out)
Prints:
[
{"name": "Tom", "age": 21, "group": "sdd", "points": 0},
{"name": "Mark", "age": 5, "group": "sdo", "points": 0},
{"name": "Pam", "age": 7, "group": "spp", "points": 0},
{"name": "Buke", "age": 31, "group": "pool", "points": 0},
]
A:
You can convert each dict to a tuple, then apply set to remove duplicates. At the end back to the list of dicts.
a = [
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name": "Mark", "age": 5,"group":"sdo","points":0},
{"name": "Pam", "age": 7,"group":"spp","points":0},
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name": "Buke", "age": 31,"group":"pool","points":0}
]
a_new = list(map(dict, set(tuple(dct.items()) for dct in a)))
print(a_new)
Output:
[{'name': 'Mark', 'age': 5, 'group': 'sdo', 'points': 0},
{'name': 'Tom', 'age': 21, 'group': 'sdd', 'points': 0},
{'name': 'Buke', 'age': 31, 'group': 'pool', 'points': 0},
{'name': 'Pam', 'age': 7, 'group': 'spp', 'points': 0}]
Explanation:
In python, a set contains no duplicates. Thus, you can convert a list to an set (and optionally back to a list again) to remove duplicates.
In your case, the simple conversion a = list(set(a)) is not sufficient, since a contains dictionaries, which aren't hashable (requirement for sets). Therefore, we first map the dictionaries to tuples of key-value tuples.
This solution is short, but not great performance-wise, as we have to iterate through a multiple times.
|
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": "Mark", "age": 5,"group":"sdo","points":0},
{"name": "Pam", "age": 7,"group":"spp","points":0},
{"name": "Tom", "age": 21,"group":"sdd","points":0},
{"name": "Buke", "age": 31,"group":"pool","points":0}
]
print(a)
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i] == a[j]:
a.pop[j]
print(a)
|
[
"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 {\"name\": \"Tom\", \"age\": 21, \"group\": \"sdd\", \"points\": 0},\n {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n\nout, seen = [], set()\nfor d in a:\n tpl = d[\"name\"], d[\"age\"], d[\"group\"]\n if tpl not in seen:\n seen.add(tpl)\n out.append(d)\n\nprint(out)\n\nPrints:\n[\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 {\"name\": \"Buke\", \"age\": 31, \"group\": \"pool\", \"points\": 0},\n]\n\n",
"You can convert each dict to a tuple, then apply set to remove duplicates. At the end back to the list of dicts.\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 {\"name\": \"Tom\", \"age\": 21,\"group\":\"sdd\",\"points\":0},\n {\"name\": \"Buke\", \"age\": 31,\"group\":\"pool\",\"points\":0}\n]\n\na_new = list(map(dict, set(tuple(dct.items()) for dct in a)))\nprint(a_new)\n\nOutput:\n[{'name': 'Mark', 'age': 5, 'group': 'sdo', 'points': 0},\n {'name': 'Tom', 'age': 21, 'group': 'sdd', 'points': 0},\n {'name': 'Buke', 'age': 31, 'group': 'pool', 'points': 0},\n {'name': 'Pam', 'age': 7, 'group': 'spp', 'points': 0}]\n\n\nExplanation:\nIn python, a set contains no duplicates. Thus, you can convert a list to an set (and optionally back to a list again) to remove duplicates.\nIn your case, the simple conversion a = list(set(a)) is not sufficient, since a contains dictionaries, which aren't hashable (requirement for sets). Therefore, we first map the dictionaries to tuples of key-value tuples.\nThis solution is short, but not great performance-wise, as we have to iterate through a multiple times.\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+-\d+-\d+).jpeg",f)
if finddate:
finddate = (finddate[0:24] + ".jpeg")
desttime = datetime.strptime(finddate.groups()[0], "%Y-%m-%d-%H%M%S")
else:
print(f"{f} has not the right convention ", end='')`
I'm trying to strip out the "-8" out of a signal picture name signal-2022-04-08-124608-8.jpeg so that it can be parsed by strptime.
A:
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.
Presumably you wanted to grab 24 characters from the original string (i.e. do f[:24]) rather than groups from the match object finddate.
IndexError Traceback (most recent call last)
<ipython-input-38-90d301324e49> in <module>
2 finddate = re.match("signal-(\d+-\d+-\d+-\d+-\d+).jpeg",f)
3 if finddate:
----> 4 finddate = (finddate[0:24] + ".jpeg")
5 desttime = datetime.strptime(finddate.groups()[0], "%Y-%m-%d-%H%M%S")
6 else:
IndexError: no such group
|
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:
finddate = (finddate[0:24] + ".jpeg")
desttime = datetime.strptime(finddate.groups()[0], "%Y-%m-%d-%H%M%S")
else:
print(f"{f} has not the right convention ", end='')`
I'm trying to strip out the "-8" out of a signal picture name signal-2022-04-08-124608-8.jpeg so that it can be parsed by strptime.
|
[
"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[:24]) rather than groups from the match object finddate.\nIndexError Traceback (most recent call last)\n<ipython-input-38-90d301324e49> in <module>\n 2 finddate = re.match(\"signal-(\\d+-\\d+-\\d+-\\d+-\\d+).jpeg\",f)\n 3 if finddate:\n----> 4 finddate = (finddate[0:24] + \".jpeg\")\n 5 desttime = datetime.strptime(finddate.groups()[0], \"%Y-%m-%d-%H%M%S\")\n 6 else:\n\nIndexError: no such group\n\n"
] |
[
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). However, this looks a lot longer than i liked and was wondering if there is an easier way to do this.
A:
Peace
hi
to 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:
import PIL.Image
import io
import base64
def resize_image(image_path, resize=None): #image_path: "C:User/Image/img.jpg"
if isinstance(image_path, str):
img = PIL.Image.open(image_path)
else:
try:
img = PIL.Image.open(io.BytesIO(base64.b64decode(image_path)))
except Exception as e:
data_bytes_io = io.BytesIO(image_path)
img = PIL.Image.open(data_bytes_io)
cur_width, cur_height = img.size
if resize:
new_width, new_height = resize
scale = min(new_height/cur_height, new_width/cur_width)
img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS)
bio = io.BytesIO()
img.save(bio, format="PNG")
del img
return bio.getvalue()
ui.Image(key="-PHOTO-",size=(50,50) #after some change
elif event == "-IMG-": # the"-IMG-" key is in [ui.I(key="IMG",enable_events=True), ui.FileBrowse()]
window['-PHOTO-'].update(data=resize_image(value["-IMG-"],resize=(50,50)))
I hope this helps
A:
Helloooo, heres my workaround to resize images in pysimplegui:
read the image stored in the path 'old_path'.
resize this image to my desired dimensions.
store the resized image in a folder as a 'png' file.
finally display the resized image.
old_path = os.path.join(
values["-FOLDER-"], values["-FILE LIST-"][0]
)
# read image using old_path
im = cv2.imread(old_path)
# resize image to desired dimensions
im = cv2.resize(im,[700,500])
# save image to temporary folder (new_path) as png
new_path ='temp_storage/image_to_show.png'
cv2.imwrite(new_path,im)
# update window with new resized image
window["-IMAGE-"].update(new_path)
if you need the full code let me know. The image storing folder only stores the image to be shown, it will override every time you choose a new image so no worries about images pilling up.
cv2 needed for reading, resizing and writing. (or PIL)
Goodluck!
|
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 liked and was wondering if there is an easier way to do this.
|
[
"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\"\n if isinstance(image_path, str):\n img = PIL.Image.open(image_path)\n else:\n try:\n img = PIL.Image.open(io.BytesIO(base64.b64decode(image_path)))\n except Exception as e:\n data_bytes_io = io.BytesIO(image_path)\n img = PIL.Image.open(data_bytes_io)\n\n cur_width, cur_height = img.size\n if resize:\n new_width, new_height = resize\n scale = min(new_height/cur_height, new_width/cur_width)\n img = img.resize((int(cur_width*scale), int(cur_height*scale)), PIL.Image.ANTIALIAS)\n bio = io.BytesIO()\n img.save(bio, format=\"PNG\")\n del img\n return bio.getvalue()\n\n\nui.Image(key=\"-PHOTO-\",size=(50,50) #after some change\nelif event == \"-IMG-\": # the\"-IMG-\" key is in [ui.I(key=\"IMG\",enable_events=True), ui.FileBrowse()]\n window['-PHOTO-'].update(data=resize_image(value[\"-IMG-\"],resize=(50,50)))\n\nI hope this helps\n",
"Helloooo, heres my workaround to resize images in pysimplegui:\n\nread the image stored in the path 'old_path'.\nresize this image to my desired dimensions.\nstore the resized image in a folder as a 'png' file.\nfinally display the resized image.\n\n old_path = os.path.join(\n values[\"-FOLDER-\"], values[\"-FILE LIST-\"][0]\n )\n # read image using old_path\n im = cv2.imread(old_path)\n # resize image to desired dimensions\n im = cv2.resize(im,[700,500])\n # save image to temporary folder (new_path) as png\n new_path ='temp_storage/image_to_show.png'\n cv2.imwrite(new_path,im)\n # update window with new resized image\n window[\"-IMAGE-\"].update(new_path)\n\nif you need the full code let me know. The image storing folder only stores the image to be shown, it will override every time you choose a new image so no worries about images pilling up.\ncv2 needed for reading, resizing and writing. (or PIL)\nGoodluck!\n"
] |
[
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 failed.
The database name is "finance_fdata_master"
Thanks a lot
# Using pymysql
import pymysql
dbcon = pymysql.connect(host='localhost', user='root', password='', database='finance_fdata_master')
# Using SQLAlchemy
from os import environ
from sqlalchemy import create_engine
uri = 'mysql+pymysql://root@localhost/finance_fdata_master'
db_uri = environ.get(uri)
engine = create_engine(db_uri, echo=True)
# uri = 'pymysql://root@localhost:3306/finance_fdata_master'
# uri = r'mysql://root@127.0.0.1:3306/finance_fdata_master'
# uri = r'mysql://root:@127.0.0.1:3306/finance_fdata_master'
# uri = r'mysql://root@localhost/finance_fdata_master'
Traceback (most recent call last):
File C:\PythonProjects\TradeAnalysis\Test\TestSQLAlchemy.py:23 in <module>
engine = create_engine(db_uri, echo=True)
File <string>:2 in create_engine
File ~\anaconda3\lib\site-packages\sqlalchemy\util\deprecations.py:309 in warned
return fn(*args, **kwargs)
File ~\anaconda3\lib\site-packages\sqlalchemy\engine\create.py:532 in create_engine
u, plugins, kwargs = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
A:
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.
engine = create_engine(uri, echo=True) # not db_uri
will probably work better.
|
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
# Using pymysql
import pymysql
dbcon = pymysql.connect(host='localhost', user='root', password='', database='finance_fdata_master')
# Using SQLAlchemy
from os import environ
from sqlalchemy import create_engine
uri = 'mysql+pymysql://root@localhost/finance_fdata_master'
db_uri = environ.get(uri)
engine = create_engine(db_uri, echo=True)
# uri = 'pymysql://root@localhost:3306/finance_fdata_master'
# uri = r'mysql://root@127.0.0.1:3306/finance_fdata_master'
# uri = r'mysql://root:@127.0.0.1:3306/finance_fdata_master'
# uri = r'mysql://root@localhost/finance_fdata_master'
Traceback (most recent call last):
File C:\PythonProjects\TradeAnalysis\Test\TestSQLAlchemy.py:23 in <module>
engine = create_engine(db_uri, echo=True)
File <string>:2 in create_engine
File ~\anaconda3\lib\site-packages\sqlalchemy\util\deprecations.py:309 in warned
return fn(*args, **kwargs)
File ~\anaconda3\lib\site-packages\sqlalchemy\engine\create.py:532 in create_engine
u, plugins, kwargs = u._instantiate_plugins(kwargs)
AttributeError: 'NoneType' object has no attribute '_instantiate_plugins'
|
[
"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 development mode, similar to the usage of pip install -e, such that the databricks notebook references the library files as is, and it's possible to update the library files on the go?
E.g. something like
%pip install /dbfs/my-library/ -e
combined with a way to keep my-library up-to-date?
Thanks!
A:
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.
You need to add the following two lines to your notebook that uses the Python package that you're developing:
%load_ext autoreload
%autoreload 2
Your library is recognized as the Databricks Repos main folders are automatically added to sys.path. If your library is in a Repo subfolder, you can add it via:
import os, sys
sys.path.append(os.path.abspath('/Workspace/Repos/<username>/path/to/your/library'))
This works for the notebook node, however not for worker nodes.
P.S. You can see examples in this Databricks cookbook and in this repository.
A:
You can do %pip install -e in notebook scope. But you will need to do that every time reattach. The code changes does not seem to reload with auto reload since editable mode does not append to syspath; rather a symblink on site-packages.
However editable mode in cluster scope does not seem to work for me
|
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 notebook references the library files as is, and it's possible to update the library files on the go?
E.g. something like
%pip install /dbfs/my-library/ -e
combined with a way to keep my-library up-to-date?
Thanks!
|
[
"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 developing:\n%load_ext autoreload\n%autoreload 2\n\nYour library is recognized as the Databricks Repos main folders are automatically added to sys.path. If your library is in a Repo subfolder, you can add it via:\nimport os, sys\nsys.path.append(os.path.abspath('/Workspace/Repos/<username>/path/to/your/library'))\n\nThis works for the notebook node, however not for worker nodes.\nP.S. You can see examples in this Databricks cookbook and in this repository.\n",
"You can do %pip install -e in notebook scope. But you will need to do that every time reattach. The code changes does not seem to reload with auto reload since editable mode does not append to syspath; rather a symblink on site-packages.\nHowever editable mode in cluster scope does not seem to work for me\n"
] |
[
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.)
views
class PostDetailView(View):
"""see detail post"""
def get(self, request, post_id, post_slug):
post = Post.objects.get(pk=post_id, slug=post_slug)
return render(request, "post/detail.html", {"post": post})
class PostCreateView(LoginRequiredMixin, View):
form_class = PostCreateUpdateForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, "post/create.html", {"form": form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data["body"][:20])
new_post.user = request.user
new_post.save()
messages.success(request, "you created a new post", "success")
return redirect("post:post-detail", new_post.id, new_post.slug)
models
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
slug = models.SlugField()
img = models.ImageField(upload_to="%Y/%m/%d/")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
urls
app_name = 'post'
urlpatterns = [
path('', views.BlogView.as_view(), name="home"),
path('detail/<int:post_id>/<slug:post_slug>/', views.PostDetailView.as_view(), name="post-detail"),
path('delete/<int:post_id>/', views.PostDeleteView.as_view(), name="post-delete"),
path('update/<int:post_id>/', views.PostUpdateView.as_view(), name="post-update"),
path('create/', views.PostCreateView.as_view(), name="post-create"),
]
A:
In case the form is not valid, you should rerender the template with the form, so:
class PostCreateView(LoginRequiredMixin, View):
form_class = PostCreateUpdateForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, "post/create.html", {"form": form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data['body'][:20])
new_post.user = request.user
new_post.save()
messages.success(request, 'you created a new post', 'success')
return redirect('post:post-detail', new_post.id, new_post.slug)
return render(request, 'post/create.html', {'form': form})
But you are implementing a lot of boilerplate code here. What you here do is implementing a CreateView [Django-doc]:
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView
class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
form_class = PostCreateUpdateForm
template_name = 'post/create.html'
success_message = 'you created a new post'
def form_valid(self, form):
form.instance.slug = slugify(form.cleaned_data['body'][:20])
form.instance.user = request.user
return super().form_valid()
def get_success_url(self):
return reverse('post:post-detail', args=(new_post.id, new_post.slug))
A:
Your "post" method in PostCreateView only returns a response if the form is valid. If it isn't valid, it will return None, causing an error.
Modify that method so it looks like this:
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data["body"][:20])
new_post.user = request.user
new_post.save()
messages.success(request, "you created a new post", "success")
return redirect("post:post-detail", new_post.id, new_post.slug)
return render(request, "post/create.html", {"form": form})
|
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, post_slug):
post = Post.objects.get(pk=post_id, slug=post_slug)
return render(request, "post/detail.html", {"post": post})
class PostCreateView(LoginRequiredMixin, View):
form_class = PostCreateUpdateForm
def get(self, request, *args, **kwargs):
form = self.form_class
return render(request, "post/create.html", {"form": form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.slug = slugify(form.cleaned_data["body"][:20])
new_post.user = request.user
new_post.save()
messages.success(request, "you created a new post", "success")
return redirect("post:post-detail", new_post.id, new_post.slug)
models
class Post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
slug = models.SlugField()
img = models.ImageField(upload_to="%Y/%m/%d/")
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
urls
app_name = 'post'
urlpatterns = [
path('', views.BlogView.as_view(), name="home"),
path('detail/<int:post_id>/<slug:post_slug>/', views.PostDetailView.as_view(), name="post-detail"),
path('delete/<int:post_id>/', views.PostDeleteView.as_view(), name="post-delete"),
path('update/<int:post_id>/', views.PostUpdateView.as_view(), name="post-update"),
path('create/', views.PostCreateView.as_view(), name="post-create"),
]
|
[
"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\": form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n new_post = form.save(commit=False)\n new_post.slug = slugify(form.cleaned_data['body'][:20])\n new_post.user = request.user\n new_post.save()\n messages.success(request, 'you created a new post', 'success')\n return redirect('post:post-detail', new_post.id, new_post.slug)\n return render(request, 'post/create.html', {'form': form})\nBut you are implementing a lot of boilerplate code here. What you here do is implementing a CreateView [Django-doc]:\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.views.generic import CreateView\n\n\nclass PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):\n form_class = PostCreateUpdateForm\n template_name = 'post/create.html'\n success_message = 'you created a new post'\n\n def form_valid(self, form):\n form.instance.slug = slugify(form.cleaned_data['body'][:20])\n form.instance.user = request.user\n return super().form_valid()\n\n def get_success_url(self):\n return reverse('post:post-detail', args=(new_post.id, new_post.slug))\n",
"Your \"post\" method in PostCreateView only returns a response if the form is valid. If it isn't valid, it will return None, causing an error.\nModify that method so it looks like this:\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n new_post = form.save(commit=False)\n new_post.slug = slugify(form.cleaned_data[\"body\"][:20])\n new_post.user = request.user\n new_post.save()\n messages.success(request, \"you created a new post\", \"success\")\n return redirect(\"post:post-detail\", new_post.id, new_post.slug)\n return render(request, \"post/create.html\", {\"form\": form})\n\n"
] |
[
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)
last_name = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'directors'
ordering = ['-id']
class Movies(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
year = models.IntegerField(blank=True, null=True)
rank = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'movies'
ordering = ['-id']
class Actors(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)
gender = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = 'actors'
ordering = ['-id']
class DirectorsGenres(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
prob = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'directors_genres'
ordering = ['-director']
class MoviesDirectors(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors')
class Meta:
db_table = 'movies_directors'
ordering = ['-director']
class MoviesGenres(models.Model):
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'movies_genres'
ordering = ['-movie']
class Roles(models.Model):
actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles')
role = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'roles'
ordering = ['-actor']
urls.py
from django.urls import path, include
from . import views
from api.views import getMovies, getGenres, getActors
urlpatterns = [
path('', views.getRoutes),
path('movies/', getMovies.as_view(), name='movies'),
path('movies/genres/', getGenres.as_view(), name='genres'),
path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'),
]
serializer.py
from rest_framework import serializers
from movies.models import *
class MoviesSerializer(serializers.ModelSerializer):
class Meta:
model = Movies
fields = '__all__'
class DirectorsSerializer(serializers.ModelSerializer):
class Meta:
model = Directors
fields = '__all__'
class ActorsSerializer(serializers.ModelSerializer):
class Meta:
model = Actors
fields = '__all__'
class DirectorsGenresSerializer(serializers.ModelSerializer):
class Meta:
model = DirectorsGenres
fields = '__all__'
class MoviesDirectorsSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
director = DirectorsSerializer(many = False)
class Meta:
model = MoviesDirectors
fields = '__all__'
class MoviesGenresSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
class Meta:
model = MoviesGenres
fields = '__all__'
class RolesSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
actor = ActorsSerializer(many = False)
class Meta:
model = Roles
fields = '__all__'
views.py
class getMovies(ListAPIView):
directors = Directors.objects.all()
queryset = MoviesDirectors.objects.filter(director__in=directors)
serializer_class = MoviesDirectorsSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['director__first_name', 'director__last_name']
class getGenres(ListAPIView):
movies = Movies.objects.all()
queryset = MoviesGenres.objects.filter(movie__in=movies).order_by('-genre')
serializer_class = MoviesGenresSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['genre']
class getActors(ListAPIView):
queryset = Roles.objects.all()
serializer_class = RolesSerializer
pagination_class = CustomPagination
def get_queryset(self):
return super().get_queryset().filter(
actor_id=self.kwargs['pk']
)
Now I want to count number of movies by genre that actor with specific pk played in getActors class.
Like the number of movies by genre that actor participated in. E.g. Drama: 2, Horror: 3
Right now I am getting the overall count of movies count: 2:
GET /api/actor_stats/17
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 800480,
"movie": {
"id": 105231,
"name": "Everybody's Business",
"year": 1993,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Grandfather"
},
{
"id": 800481,
"movie": {
"id": 242453,
"name": "OP Pro 88 - Barra Rio",
"year": 1988,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Himself"
}
]
}
What is the optimized way of achieving the following:
number_of_movies_by_genre
Drama: 2
Horror: 3
UPDATE
class RolesSerializer(serializers.Serializer):
id = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
top_genre = serializers.SerializerMethodField()
number_of_movies = serializers.SerializerMethodField()
number_of_movies_by_genre = serializers.SerializerMethodField()
most_frequent_partner = serializers.SerializerMethodField()
class Meta:
model = Roles
fields = '__all__'
def get_id(self, obj):
return obj.actor.id
def get_name(self, obj):
return f'{obj.actor.first_name} {obj.actor.last_name}'
def get_top_genre(self, obj):
number_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre = F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
)
data = [s['number_of_movies'] for s in number_by_genre]
highest = max(data)
result = [s for s in data if s == highest]
return result
def get_number_of_movies(self, obj):
number_of_movies = Roles.objects.filter(actor = obj.actor.id
).values('movie__name').count()
return number_of_movies
def get_number_of_movies_by_genre(self, obj):
number_of_movies_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre=F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
).values('genre', 'number_of_movies')
return number_of_movies_by_genre
def get_most_frequent_partner(self, obj):
partners = Roles.objects.filter(actor = obj.actor.id
).values('movie__id')
result = Roles.objects.filter(movie__in = partners
).values('actor').exclude(actor=obj.actor.id).annotate(
partner_actor_id = F('actor'),
partner_actor_name = Concat(F('actor__first_name'), Value(' '), F('actor__last_name')),
number_of_shared_movies =Count('actor'),
).values('partner_actor_id', 'partner_actor_name', 'number_of_shared_movies')
return result
The problem with that code is: It repeats the results by the number of movies. For instance if the actor have 5 movies the results will be repeated 5 times. Another issue is: in order to get top_genre and most_frequent_partner I'm using max() but then I just get the numbers and not the actual name of genre in (top_genre) and actor name in (most_frequent_partner). Since I use max() in a way to get more than one value. For instance in the top_genre: If the actor have 3 Drama, 3 Comedy, 1 Horror, 1 Documentary, I get the max in that way: [3,3], but how can I get the actual names out of these results? Same goes to most_frequent_partner.
Results looks like this so far:
{
"next": null,
"previous": null,
"count": 4,
"pagenum": null,
"results": [
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
}
]
}
What I want to see in the end:
{
"next": null,
"previous": null,
"count": 2,
"results": [
{
"id": 18 (actor_id),
"name": Bruce Buffer (actor_name),
"number of movies": 2,
"top genre": Drama, Documentary,
"number of movies by genre": Drama: 1, Documentary: 1,
"most frequent partner": partner_actor_id, partner_actor_name, number_of_shared_movies,
}
]
}
A:
If you want, the number of movies by genre for a given actor what you can do is annotate and count aggregate
return Roles.objects.filter(
actor_id=self.kwargs['pk']
).values('movie__movies_genres__genre').annotate(
no_of_movies=Count('movie__movies_genres__genre'),
genre=F('movie__movies_genres__genre'),
)
Here first we filtered roles for a given actor
then values will group by genre then annotation is computed over all members of the group that count and get genre
and you can use SerializerMethodField to these calculated results
if you have a huge dataset it will not perform well, but you can create indexes accordingly still it will cost you 2-3 queries
you can learn more about Django queryset API
A:
There many ways to implement this route, it depends on many criteria and how much it will be used .
i think a correct way is to create a dedicated model that would store actor stats with a one to one relation to actor and recompute the value each time a movie is added. But If you add movie often it could slow down your database.
You can also accept to have some outdated data for a while and update the table regularly using a background job and maybe using custom sql query that will ensure you better performance (bulk update).
A:
I would start from your model, you have genres defined as a CharField in two of your models. By not isolating them anywhere, you need to look in both tables for all types of genres. If do not, then you are just supposing that all the genres you have in one table is also on the other one, which could not be true.
Also, querying string fields is not very efficient when in comparison to a int PK, so from the point of view of scaling this is bad. (Of course, i am saying that in general, as a good practice and not focused specifically in movie genres)
Your best option would be to have either a Genre Model or a choice field, where you define all possible genres.
As for the counting, you would do that inside your serializer class, by using a serializermethodfield.
|
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 Meta:
db_table = 'directors'
ordering = ['-id']
class Movies(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100, blank=True, null=True)
year = models.IntegerField(blank=True, null=True)
rank = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'movies'
ordering = ['-id']
class Actors(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)
gender = models.CharField(max_length=20, blank=True, null=True)
class Meta:
db_table = 'actors'
ordering = ['-id']
class DirectorsGenres(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='directors_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
prob = models.FloatField(blank=True, null=True)
class Meta:
db_table = 'directors_genres'
ordering = ['-director']
class MoviesDirectors(models.Model):
director = models.ForeignKey(Directors,on_delete=models.CASCADE,related_name='movies_directors')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_directors')
class Meta:
db_table = 'movies_directors'
ordering = ['-director']
class MoviesGenres(models.Model):
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='movies_genres')
genre = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'movies_genres'
ordering = ['-movie']
class Roles(models.Model):
actor = models.ForeignKey(Actors,on_delete=models.CASCADE,related_name='roles')
movie = models.ForeignKey(Movies,on_delete=models.CASCADE,related_name='roles')
role = models.CharField(max_length=100, blank=True, null=True)
class Meta:
db_table = 'roles'
ordering = ['-actor']
urls.py
from django.urls import path, include
from . import views
from api.views import getMovies, getGenres, getActors
urlpatterns = [
path('', views.getRoutes),
path('movies/', getMovies.as_view(), name='movies'),
path('movies/genres/', getGenres.as_view(), name='genres'),
path('actor_stats/<pk>', getActors.as_view(), name='actor_stats'),
]
serializer.py
from rest_framework import serializers
from movies.models import *
class MoviesSerializer(serializers.ModelSerializer):
class Meta:
model = Movies
fields = '__all__'
class DirectorsSerializer(serializers.ModelSerializer):
class Meta:
model = Directors
fields = '__all__'
class ActorsSerializer(serializers.ModelSerializer):
class Meta:
model = Actors
fields = '__all__'
class DirectorsGenresSerializer(serializers.ModelSerializer):
class Meta:
model = DirectorsGenres
fields = '__all__'
class MoviesDirectorsSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
director = DirectorsSerializer(many = False)
class Meta:
model = MoviesDirectors
fields = '__all__'
class MoviesGenresSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
class Meta:
model = MoviesGenres
fields = '__all__'
class RolesSerializer(serializers.ModelSerializer):
movie = MoviesSerializer(many = False)
actor = ActorsSerializer(many = False)
class Meta:
model = Roles
fields = '__all__'
views.py
class getMovies(ListAPIView):
directors = Directors.objects.all()
queryset = MoviesDirectors.objects.filter(director__in=directors)
serializer_class = MoviesDirectorsSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['director__first_name', 'director__last_name']
class getGenres(ListAPIView):
movies = Movies.objects.all()
queryset = MoviesGenres.objects.filter(movie__in=movies).order_by('-genre')
serializer_class = MoviesGenresSerializer
pagination_class = CustomPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['genre']
class getActors(ListAPIView):
queryset = Roles.objects.all()
serializer_class = RolesSerializer
pagination_class = CustomPagination
def get_queryset(self):
return super().get_queryset().filter(
actor_id=self.kwargs['pk']
)
Now I want to count number of movies by genre that actor with specific pk played in getActors class.
Like the number of movies by genre that actor participated in. E.g. Drama: 2, Horror: 3
Right now I am getting the overall count of movies count: 2:
GET /api/actor_stats/17
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 800480,
"movie": {
"id": 105231,
"name": "Everybody's Business",
"year": 1993,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Grandfather"
},
{
"id": 800481,
"movie": {
"id": 242453,
"name": "OP Pro 88 - Barra Rio",
"year": 1988,
"rank": null
},
"actor": {
"id": 17,
"first_name": "Luis Roberto",
"last_name": "Formiga",
"gender": "M"
},
"role": "Himself"
}
]
}
What is the optimized way of achieving the following:
number_of_movies_by_genre
Drama: 2
Horror: 3
UPDATE
class RolesSerializer(serializers.Serializer):
id = serializers.SerializerMethodField()
name = serializers.SerializerMethodField()
top_genre = serializers.SerializerMethodField()
number_of_movies = serializers.SerializerMethodField()
number_of_movies_by_genre = serializers.SerializerMethodField()
most_frequent_partner = serializers.SerializerMethodField()
class Meta:
model = Roles
fields = '__all__'
def get_id(self, obj):
return obj.actor.id
def get_name(self, obj):
return f'{obj.actor.first_name} {obj.actor.last_name}'
def get_top_genre(self, obj):
number_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre = F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
)
data = [s['number_of_movies'] for s in number_by_genre]
highest = max(data)
result = [s for s in data if s == highest]
return result
def get_number_of_movies(self, obj):
number_of_movies = Roles.objects.filter(actor = obj.actor.id
).values('movie__name').count()
return number_of_movies
def get_number_of_movies_by_genre(self, obj):
number_of_movies_by_genre = Roles.objects.filter(actor = obj.actor.id
).values('movie__movies_genres__genre').annotate(
genre=F('movie__movies_genres__genre'),
number_of_movies=Count('movie__movies_genres__genre'),
).values('genre', 'number_of_movies')
return number_of_movies_by_genre
def get_most_frequent_partner(self, obj):
partners = Roles.objects.filter(actor = obj.actor.id
).values('movie__id')
result = Roles.objects.filter(movie__in = partners
).values('actor').exclude(actor=obj.actor.id).annotate(
partner_actor_id = F('actor'),
partner_actor_name = Concat(F('actor__first_name'), Value(' '), F('actor__last_name')),
number_of_shared_movies =Count('actor'),
).values('partner_actor_id', 'partner_actor_name', 'number_of_shared_movies')
return result
The problem with that code is: It repeats the results by the number of movies. For instance if the actor have 5 movies the results will be repeated 5 times. Another issue is: in order to get top_genre and most_frequent_partner I'm using max() but then I just get the numbers and not the actual name of genre in (top_genre) and actor name in (most_frequent_partner). Since I use max() in a way to get more than one value. For instance in the top_genre: If the actor have 3 Drama, 3 Comedy, 1 Horror, 1 Documentary, I get the max in that way: [3,3], but how can I get the actual names out of these results? Same goes to most_frequent_partner.
Results looks like this so far:
{
"next": null,
"previous": null,
"count": 4,
"pagenum": null,
"results": [
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
},
{
"id": 36,
"name": "Benjamin 2X",
"top_genre": [
2,
2
],
"number_of_movies": 4,
"number_of_movies_by_genre": [
{
"movie__movies_genres__genre": null,
"genre": null,
"number_of_movies": 0
},
{
"movie__movies_genres__genre": "Documentary",
"genre": "Documentary",
"number_of_movies": 2
},
{
"movie__movies_genres__genre": "Music",
"genre": "Music",
"number_of_movies": 2
}
],
"most_frequent_partner": []
}
]
}
What I want to see in the end:
{
"next": null,
"previous": null,
"count": 2,
"results": [
{
"id": 18 (actor_id),
"name": Bruce Buffer (actor_name),
"number of movies": 2,
"top genre": Drama, Documentary,
"number of movies by genre": Drama: 1, Documentary: 1,
"most frequent partner": partner_actor_id, partner_actor_name, number_of_shared_movies,
}
]
}
|
[
"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 genre=F('movie__movies_genres__genre'),\n )\n\nHere first we filtered roles for a given actor\nthen values will group by genre then annotation is computed over all members of the group that count and get genre\nand you can use SerializerMethodField to these calculated results\nif you have a huge dataset it will not perform well, but you can create indexes accordingly still it will cost you 2-3 queries\nyou can learn more about Django queryset API\n",
"There many ways to implement this route, it depends on many criteria and how much it will be used .\ni think a correct way is to create a dedicated model that would store actor stats with a one to one relation to actor and recompute the value each time a movie is added. But If you add movie often it could slow down your database.\nYou can also accept to have some outdated data for a while and update the table regularly using a background job and maybe using custom sql query that will ensure you better performance (bulk update).\n",
"I would start from your model, you have genres defined as a CharField in two of your models. By not isolating them anywhere, you need to look in both tables for all types of genres. If do not, then you are just supposing that all the genres you have in one table is also on the other one, which could not be true.\nAlso, querying string fields is not very efficient when in comparison to a int PK, so from the point of view of scaling this is bad. (Of course, i am saying that in general, as a good practice and not focused specifically in movie genres)\nYour best option would be to have either a Genre Model or a choice field, where you define all possible genres.\nAs for the counting, you would do that inside your serializer class, by using a serializermethodfield.\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 to do it?
I tried with several of them without a good response, I whether get an error, or a bad response
Thanks in advance
Rafael
A:
I got it
Just assume that you will send an array of objects, and the front end should access the first object it finds
myResponse = []
myResponse.append(myObject)
return HttpResponse(myResponse, status=200) // status is optional
|
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 error, or a bad response
Thanks in advance
Rafael
|
[
"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 result the dictionary only has one key and one stored value that is
result of running the code
{1: 10}
how do i make it that the keys changes with each loop and stores all the values generated
but in the final result the dictionary only has one key and one stored value that is
result of running the code
{1: 10}
how do i make it that the keys changes with each loop and stores all the values generated
A:
You have to put numbers += 1 or numbers = numbers + 1 instead of numbers + 1 if you want to update the variable.
When 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.
A:
I don't think you realize, but there's a silly typo in your code. After assigning the value to dictionary, you increasing the count of numbers, but not assigning it. So, just use += assignment operator.
counting = {}
numbers = 1
for i in range(1, 11):
counting[numbers] = (i)
numbers += 1
print(counting)
O/P:
{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
|
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 of running the code
{1: 10}
how do i make it that the keys changes with each loop and stores all the values generated
but in the final result the dictionary only has one key and one stored value that is
result of running the code
{1: 10}
how do i make it that the keys changes with each loop and stores all the values generated
|
[
"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 there's a silly typo in your code. After assigning the value to dictionary, you increasing the count of numbers, but not assigning it. So, just use += assignment operator.\ncounting = {}\nnumbers = 1\n\n\nfor i in range(1, 11):\n counting[numbers] = (i)\n numbers += 1\n\nprint(counting)\n\nO/P:\n{1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}\n\n"
] |
[
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, 42.38646954167245, int]
2 [2.6386970166722348, 0.9785848171888037, float] [89, 37.9011122659478, int]
3 [3.49336632573625, 1.0411524946972244, float] [115, 36.211134224288344, int]
4 [2.193991200007534, 0.7955134305428825, float] [128, 50.03563864975485, int]
5 [3.4574527664490997, 0.9399880977511021, float] [120, 41.841146628802875, int]
6 [3.1190582380554863, 1.0839109431114795, float] [148, 55.990072419824514, int]
7 [2.7757359940789916, 0.8889801332053203, float] [142, 51.08885697101243, int]
8 [3.23820908493237, 1.0587479742892683, float] [183, 43.831293356668425, int]
9 [2.2509032790941985, 0.8896196407231622, float] [66, 35.9377662201882, int]
I'd like to extract for every column the first position of the list on each row to get a DataFrame looking as follows.
Gamma Beta
0 1.4652917656926299 91
1 2.6008354611105995 59
2 2.6386970166722348 89
...
Up to now, my solution would be like [row[1][0] for row in df_params.itertuples()], which I could iterate for every column index of the row and then compose my new DataFrame.
An alternative is new_df = df_params['Gamma'].apply(lambda x: x[0]) and then to iterate to go through all the columns.
My question is, is there a less cumbersome way to perform this operation?
A:
You can use the str accessor for lists, e.g.:
df_params['Gamma'].str[0]
This should work for all columns:
df_params.apply(lambda col: col.str[0])
A:
Itertuples would be pretty slow. You could speed this up with the following:
for column_name in df_params.columns:
df_params[column_name] = [i[0] for i in df_params[column_name]]
A:
It's also possible for Series.str.get
df_params['Gamma'].str.get(0)
A:
The given answer fails if your inputs length vary.
Then, you can unnest column-wise and drop the unnecessary ones.
Here is how to unnest. Taken from this answer.
def unnesting(df, explode, axis):
if axis==1:
df1 = pd.concat([df[x].explode() for x in explode], axis=1)
return df1.join(df.drop(explode, 1), how='left')
else :
df1 = pd.concat([
pd.DataFrame(df[x].tolist(), index=df.index).add_prefix(x) for x in explode], axis=1)
return df1.join(df.drop(explode, 1), how='left')
|
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.9785848171888037, float] [89, 37.9011122659478, int]
3 [3.49336632573625, 1.0411524946972244, float] [115, 36.211134224288344, int]
4 [2.193991200007534, 0.7955134305428825, float] [128, 50.03563864975485, int]
5 [3.4574527664490997, 0.9399880977511021, float] [120, 41.841146628802875, int]
6 [3.1190582380554863, 1.0839109431114795, float] [148, 55.990072419824514, int]
7 [2.7757359940789916, 0.8889801332053203, float] [142, 51.08885697101243, int]
8 [3.23820908493237, 1.0587479742892683, float] [183, 43.831293356668425, int]
9 [2.2509032790941985, 0.8896196407231622, float] [66, 35.9377662201882, int]
I'd like to extract for every column the first position of the list on each row to get a DataFrame looking as follows.
Gamma Beta
0 1.4652917656926299 91
1 2.6008354611105995 59
2 2.6386970166722348 89
...
Up to now, my solution would be like [row[1][0] for row in df_params.itertuples()], which I could iterate for every column index of the row and then compose my new DataFrame.
An alternative is new_df = df_params['Gamma'].apply(lambda x: x[0]) and then to iterate to go through all the columns.
My question is, is there a less cumbersome way to perform this operation?
|
[
"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 i in df_params[column_name]]\n\n",
"It's also possible for Series.str.get\ndf_params['Gamma'].str.get(0)\n\n",
"The given answer fails if your inputs length vary.\nThen, you can unnest column-wise and drop the unnecessary ones.\nHere is how to unnest. Taken from this answer.\ndef unnesting(df, explode, axis):\n if axis==1:\n df1 = pd.concat([df[x].explode() for x in explode], axis=1)\n return df1.join(df.drop(explode, 1), how='left')\n else :\n df1 = pd.concat([\n pd.DataFrame(df[x].tolist(), index=df.index).add_prefix(x) for x in explode], axis=1)\n return df1.join(df.drop(explode, 1), how='left')\n\n"
] |
[
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
2001-07-01
2002-01-01
002
2000-09-18
2000-10-05
002
2000-10-06
2001-06-30
002
2004-05-01
2005-12-31
002
2008-01-01
2008-11-25
A Continuous flag column needs to identify these discontinuous values:
Employee Number
Start Date
End Date
Continuous Flag
Explanation
001
1999-11-29
2000-03-12
Y
2000-03-13 is 1d after 2000-03-12
001
2000-03-13
2001-06-30
Y
2001-07-01 is 1d after 2001-06-30
001
2001-07-01
2002-01-01
NaN
missing 2023-01-01 End Date row
002
2000-09-18
2000-10-05
Y
2000-10-06 is 1d after 2000-10-05
002
2000-10-06
2001-06-30
N
2004-05-01 is not 1d after 2001-06-30
002
2004-05-01
2005-12-31
N
2008-01-01 is not 1d after 2005-12-31
002
2008-01-01
2008-11-25
NaN
missing 2023-01-01 End Date row
Then, for those rows that are 'N', a row needs to be inserted with the discontinuous dates to make them continuous in between rows. If there is no next row, use '2023-01-01' by default. Here is the expected output:
Employee Number
Start Date
End Date
Continuous Flag
001
1999-11-29
2000-03-12
Y
001
2000-03-13
2001-06-30
Y
001
2001-07-01
2002-01-01
Y
001
2002-01-02
2023-01-01
NaN
002
2000-09-18
2000-10-05
Y
002
2000-10-06
2001-06-30
Y
002
2001-07-01
2004-04-30
Y
002
2004-05-01
2005-12-31
Y
002
2006-01-01
2007-12-31
Y
002
2008-01-01
2008-11-25
Y
002
2008-11-26
2023-01-01
NaN
I tried idx for loop without success
A:
Plan A: (Filling in gaps)
Create 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.)
SELECT ... FROM that-table-of-dates LEFT JOIN your-table ON ...
As for filling in the gaps with values before (or after) the given hole. I don't understand the goals.
Plan B: (Simply discovering gaps)
Do a "self-join" of the table with itself. For this you must have consecutive ids. Since you don't have such, I am not sure what to do.
Then check whether the (end_date + INTERVAL 1 DAY) of one row matches the start_date of the 'next' row.
Plan C: (requires MySQL 8.0 or MariaDB 10.2)
Use LAG() (or `LEAD() windowing functions to compare a value in one row to the previous (or next) row.
This may be the simplest way to set the "continuous flag".
Be sure to check for discontinuity in EmployeeId as well as INTERVAL 1 DAY as mentioned above.
|
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-10-06
2001-06-30
002
2004-05-01
2005-12-31
002
2008-01-01
2008-11-25
A Continuous flag column needs to identify these discontinuous values:
Employee Number
Start Date
End Date
Continuous Flag
Explanation
001
1999-11-29
2000-03-12
Y
2000-03-13 is 1d after 2000-03-12
001
2000-03-13
2001-06-30
Y
2001-07-01 is 1d after 2001-06-30
001
2001-07-01
2002-01-01
NaN
missing 2023-01-01 End Date row
002
2000-09-18
2000-10-05
Y
2000-10-06 is 1d after 2000-10-05
002
2000-10-06
2001-06-30
N
2004-05-01 is not 1d after 2001-06-30
002
2004-05-01
2005-12-31
N
2008-01-01 is not 1d after 2005-12-31
002
2008-01-01
2008-11-25
NaN
missing 2023-01-01 End Date row
Then, for those rows that are 'N', a row needs to be inserted with the discontinuous dates to make them continuous in between rows. If there is no next row, use '2023-01-01' by default. Here is the expected output:
Employee Number
Start Date
End Date
Continuous Flag
001
1999-11-29
2000-03-12
Y
001
2000-03-13
2001-06-30
Y
001
2001-07-01
2002-01-01
Y
001
2002-01-02
2023-01-01
NaN
002
2000-09-18
2000-10-05
Y
002
2000-10-06
2001-06-30
Y
002
2001-07-01
2004-04-30
Y
002
2004-05-01
2005-12-31
Y
002
2006-01-01
2007-12-31
Y
002
2008-01-01
2008-11-25
Y
002
2008-11-26
2023-01-01
NaN
I tried idx for loop without success
|
[
"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 hole. I don't understand the goals.\nPlan B: (Simply discovering gaps)\nDo a \"self-join\" of the table with itself. For this you must have consecutive ids. Since you don't have such, I am not sure what to do.\nThen check whether the (end_date + INTERVAL 1 DAY) of one row matches the start_date of the 'next' row.\nPlan C: (requires MySQL 8.0 or MariaDB 10.2)\nUse LAG() (or `LEAD() windowing functions to compare a value in one row to the previous (or next) row.\nThis may be the simplest way to set the \"continuous flag\".\nBe sure to check for discontinuity in EmployeeId as well as INTERVAL 1 DAY as mentioned above.\n"
] |
[
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 the following frame:
And the following is ground truth mask:
and the following is the mapping of ground truth on the frame.
How can I do that. Also, I have two folders that inside each of them, there are several folders that inside each of them the there are stored frames. How can I do this operation with these batch data?
This is the hierarchy of my folders:
frame_folder: folder_1, folder_2, ......
├── frames
│ ├── 601 (601 and 602 and etc are folders that in the inside there are image frames that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
├── ground truth
│ ├── 601 (601 and 602 and etc are folders that in the inside there are ground truth masks that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
Update:
Using the answer proposed by @hkchengrex , I faced with an error. When there is only one folder in the paths, it works well but when I put several folders (frames of different videos) based on the question I face with the following error. the details are in below:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
TypeError: process_video() takes 1 positional argument but 6 were given
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/Video_processing/Saliency_mapping.py", line 69, in <module>
pool.apply(process_video, videos)
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 357, in apply
return self.apply_async(func, args, kwds).get()
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 771, in get
raise self._value
TypeError: process_video() takes 1 positional argument but 6 were given
A:
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, resizes the mask to match the shape of the image, assumes the mask is in .png format, and depends on the file structure that you posted.
import os
from os import path
import cv2
import numpy as np
from argparse import ArgumentParser
from multiprocessing import Pool
def create_overlay(image, mask):
"""
image: H*W*3 numpy array
mask: H*W numpy array
If dimensions do not match, the mask is upsampled to match that of the image
Returns a H*W*3 numpy array
"""
h, w = image.shape[:2]
mask = cv2.resize(mask, dsize=(w,h), interpolation=cv2.INTER_CUBIC)
# color options: https://docs.opencv.org/4.x/d3/d50/group__imgproc__colormap.html
mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_HOT).astype(np.float32)
mask = mask[:, :, None] # create trailing dimension for broadcasting
mask = mask.astype(np.float32)/255
# different other options that you can use to merge image/mask
overlay = (image*(1-mask)+mask_color*mask).astype(np.uint8)
# overlay = (image*0.5 + mask_color*0.5).astype(np.uint8)
# overlay = (image + mask_color).clip(0,255).astype(np.uint8)
return overlay
def process_video(video_name):
"""
Processing frames in a single video
"""
vid_image_path = path.join(image_path, video_name)
vid_mask_path = path.join(mask_path, video_name)
vid_output_path = path.join(output_path, video_name)
os.makedirs(vid_output_path, exist_ok=True)
frames = sorted(os.listdir(vid_image_path))
for f in frames:
image = cv2.imread(path.join(vid_image_path, f))
mask = cv2.imread(path.join(vid_mask_path, f.replace('.jpg','.png')), cv2.IMREAD_GRAYSCALE)
overlay = create_overlay(image, mask)
cv2.imwrite(path.join(vid_output_path, f), overlay)
parser = ArgumentParser()
parser.add_argument('--image_path')
parser.add_argument('--mask_path')
parser.add_argument('--output_path')
args = parser.parse_args()
image_path = args.image_path
mask_path = args.mask_path
output_path = args.output_path
if __name__ == '__main__':
videos = sorted(
list(set(os.listdir(image_path)).intersection(
set(os.listdir(mask_path))))
)
print(f'Processing {len(videos)} videos.')
pool = Pool()
pool.map(process_video, videos)
print('Done.')
Output:
EDIT: Made it work on Windows; changed pool.apply to pool.map.
A:
This is not much different from @hkchengrex solution, so he deserves the credit, since his answer was first. I mainly wanted to point out the use of cv2.addWeighted
Here is one way to blend the image and ground truth in Python/OpenCV.
I would suggest resizing the ground truth once to the size of the images for all your video frames rather than resizing every video frame to the size of the ground truth.
One simple resizes the ground truth to the size of the image. Then colorize the ground truth using a color map. Then simply use cv2.addWeighted to blend the two for every frame of your video.
I leave it to you to read your video to access each frame. The following simply shows how to process any given frame
Input:
Ground Truth Overlay:
import cv2
import numpy as np
# read image
img = cv2.imread('bullfight.png')
hh, ww = img.shape[:2]
# read ground truth overlay
overlay = cv2.imread('truth.png')
# resize the overlay to match the size of the image
over_resize = cv2.resize(overlay, (ww,hh), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)
# colorize the over_resized image
over_color = cv2.applyColorMap(over_resize, cv2.COLORMAP_HOT)
# blend over_color and image (adjust weights for different effects)
result = cv2.addWeighted(img, 1, over_color, 1, 0)
# save output image
cv2.imwrite('bullfight_overlay.png', result)
# display images
cv2.imshow('overcolor', over_color)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
Result:
|
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 truth mask:
and the following is the mapping of ground truth on the frame.
How can I do that. Also, I have two folders that inside each of them, there are several folders that inside each of them the there are stored frames. How can I do this operation with these batch data?
This is the hierarchy of my folders:
frame_folder: folder_1, folder_2, ......
├── frames
│ ├── 601 (601 and 602 and etc are folders that in the inside there are image frames that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
├── ground truth
│ ├── 601 (601 and 602 and etc are folders that in the inside there are ground truth masks that their name is like 0001.png,0002.png, ...)
│ ├── 602
.
.
.
│ └── 700
Update:
Using the answer proposed by @hkchengrex , I faced with an error. When there is only one folder in the paths, it works well but when I put several folders (frames of different videos) based on the question I face with the following error. the details are in below:
multiprocessing.pool.RemoteTraceback:
"""
Traceback (most recent call last):
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 125, in worker
result = (True, func(*args, **kwds))
TypeError: process_video() takes 1 positional argument but 6 were given
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/user/Video_processing/Saliency_mapping.py", line 69, in <module>
pool.apply(process_video, videos)
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 357, in apply
return self.apply_async(func, args, kwds).get()
File "/home/user/miniconda3/envs/vtn/lib/python3.10/multiprocessing/pool.py", line 771, in get
raise self._value
TypeError: process_video() takes 1 positional argument but 6 were given
|
[
"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, resizes the mask to match the shape of the image, assumes the mask is in .png format, and depends on the file structure that you posted.\nimport os\nfrom os import path\nimport cv2\nimport numpy as np\n\nfrom argparse import ArgumentParser\nfrom multiprocessing import Pool\n\n\ndef create_overlay(image, mask):\n \"\"\"\n image: H*W*3 numpy array\n mask: H*W numpy array\n If dimensions do not match, the mask is upsampled to match that of the image\n\n Returns a H*W*3 numpy array\n \"\"\"\n h, w = image.shape[:2]\n mask = cv2.resize(mask, dsize=(w,h), interpolation=cv2.INTER_CUBIC)\n\n # color options: https://docs.opencv.org/4.x/d3/d50/group__imgproc__colormap.html\n mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_HOT).astype(np.float32)\n mask = mask[:, :, None] # create trailing dimension for broadcasting\n mask = mask.astype(np.float32)/255\n\n # different other options that you can use to merge image/mask\n overlay = (image*(1-mask)+mask_color*mask).astype(np.uint8)\n # overlay = (image*0.5 + mask_color*0.5).astype(np.uint8)\n # overlay = (image + mask_color).clip(0,255).astype(np.uint8)\n\n return overlay\n\ndef process_video(video_name):\n \"\"\"\n Processing frames in a single video\n \"\"\"\n vid_image_path = path.join(image_path, video_name)\n vid_mask_path = path.join(mask_path, video_name)\n vid_output_path = path.join(output_path, video_name)\n os.makedirs(vid_output_path, exist_ok=True)\n\n frames = sorted(os.listdir(vid_image_path))\n for f in frames:\n image = cv2.imread(path.join(vid_image_path, f))\n mask = cv2.imread(path.join(vid_mask_path, f.replace('.jpg','.png')), cv2.IMREAD_GRAYSCALE)\n overlay = create_overlay(image, mask)\n cv2.imwrite(path.join(vid_output_path, f), overlay)\n\n\nparser = ArgumentParser()\nparser.add_argument('--image_path')\nparser.add_argument('--mask_path')\nparser.add_argument('--output_path')\nargs = parser.parse_args()\n\nimage_path = args.image_path\nmask_path = args.mask_path\noutput_path = args.output_path\n\nif __name__ == '__main__':\n videos = sorted(\n list(set(os.listdir(image_path)).intersection(\n set(os.listdir(mask_path))))\n )\n\n print(f'Processing {len(videos)} videos.')\n\n pool = Pool()\n pool.map(process_video, videos)\n\n print('Done.')\n\n\nOutput:\n\nEDIT: Made it work on Windows; changed pool.apply to pool.map.\n",
"This is not much different from @hkchengrex solution, so he deserves the credit, since his answer was first. I mainly wanted to point out the use of cv2.addWeighted\nHere is one way to blend the image and ground truth in Python/OpenCV.\nI would suggest resizing the ground truth once to the size of the images for all your video frames rather than resizing every video frame to the size of the ground truth.\nOne simple resizes the ground truth to the size of the image. Then colorize the ground truth using a color map. Then simply use cv2.addWeighted to blend the two for every frame of your video.\nI leave it to you to read your video to access each frame. The following simply shows how to process any given frame\nInput:\n\nGround Truth Overlay:\n\nimport cv2\nimport numpy as np\n\n# read image\nimg = cv2.imread('bullfight.png')\nhh, ww = img.shape[:2]\n\n# read ground truth overlay\noverlay = cv2.imread('truth.png')\n\n# resize the overlay to match the size of the image\nover_resize = cv2.resize(overlay, (ww,hh), fx=0, fy=0, interpolation=cv2.INTER_CUBIC)\n\n# colorize the over_resized image\nover_color = cv2.applyColorMap(over_resize, cv2.COLORMAP_HOT)\n\n# blend over_color and image (adjust weights for different effects)\nresult = cv2.addWeighted(img, 1, over_color, 1, 0)\n\n# save output image\ncv2.imwrite('bullfight_overlay.png', result) \n\n# display images\ncv2.imshow('overcolor', over_color)\ncv2.imshow('result', result)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\nResult:\n\n"
] |
[
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've tried using the code above but it erased the entire column. I hoped that it would erase only the rows including only one hashmark. I do not know what to do.
A:
can you try this:
df['len']=df['column name'].str.count('#') #how many "#" expressions are in the column.
df=df[df["len"]>1]
#or one line
df=df[df['column name'].str.count('#')>1]
A:
if each of them have at least one '#' , and its either ## or #,
df[df["column name"].str.contains("##") == False]
above code will get you one # ones.
df[df["column name"].str.contains("##") == True]
above code will eliminate #'s and get you ## ones.
|
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 that it would erase only the rows including only one hashmark. I do not know what to do.
|
[
"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(\"##\") == False]\n\nabove code will get you one # ones.\ndf[df[\"column name\"].str.contains(\"##\") == True]\n\nabove code will eliminate #'s and get you ## ones.\n"
] |
[
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 lowercase and uppercase letters are considered different (e.g., ‘A’ < ‘a’). You may assume my_string consists of English letters only, and is not empty.
Example 1: >>> most_popular_character("HelloWorld") >>> 'l'
Example 2: >>> most_popular_character("gggcccbb") >>> 'c'
Explanation: cee and gee appear three times each (and bee twice), but cee precedes gee lexicographically.
Hints (you may ignore these):
Build a dictionary mapping letters to their frequency;
Find the largest frequency;
Find the smallest letter having that frequency.
def most_popular_character(my_string):
char_count = {} # define dictionary
for c in my_string:
if c in char_count: #if c is in the dictionary:
char_count[c] = 1
else: # if c isn't in the dictionary - create it and put 1
char_count[c] = 1
sorted_chars = sorted(char_count) # sort the dictionary
char_count = char_count.keys() # place the dictionary in a list
max_per = 0
for i in range(len(sorted_chars) - 1):
if sorted_chars[i] >= sorted_chars[i+1]:
max_per = sorted_chars[i]
break
return max_per
my function returns 0 right now, and I think the problem is in the last for loop and if statement - but I can't figure out what the problem is..
If you have any suggestions on how to adjust the code it would be very appreciated!
A:
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.
Have 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/
def most_popular_character(my_string):
# NOTE: you might want to convert the entire sting to upper or lower case, first, depending on the use
# e.g. my_string = my_string.lower()
char_count = {} # define dictionary
for c in my_string:
if c in char_count: #if c is in the dictionary:
char_count[c] += 1 # add 1 to it
else: # if c isn't in the dictionary - create it and put 1
char_count[c] = 1
# Never under estimate the power of print in debugging
print(char_count)
# max(char_count.values()) will give the highest value
# But there may be more than 1 item with the highest count, so get them all
max_keys = [key for key, value in char_count.items() if value == max(char_count.values())]
# Choose the lowest by sorting them and pick the first item
low_item = sorted(max_keys)[0]
return low_item, max(char_count.values())
print(most_popular_character("HelloWorld"))
print(most_popular_character("gggcccbb"))
print(most_popular_character("gggHHHAAAAaaaccccbb 12 3"))
Result:
{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}
('l', 3)
{'g': 3, 'c': 3, 'b': 2}
('c', 3)
{'g': 3, 'H': 3, 'A': 4, 'a': 3, 'c': 4, 'b': 2, ' ': 2, '1': 1, '2': 1, '3': 1}
('A', 4)
So: l and 3, c and 3, A and 4
A:
def most_popular_character(my_string):
history_l = [l for l in my_string] #each letter in string
char_dict = {} #creating dict
for item in history_l: #for each letter in string
char_dict[item] = history_l.count(item)
return [max(char_dict.values()),min(char_dict.values())]
I didn't understand the last part of minimum frequency, so I make this function return a maximum frequency and a minimum frequency as a list!
A:
Use a Counter to count the characters, and use the max function to select the "biggest" character according to your two criteria.
>>> from collections import Counter
>>> def most_popular_character(my_string):
... chars = Counter(my_string)
... return max(chars, key=lambda c: (chars[c], -ord(c)))
...
>>> most_popular_character("HelloWorld")
'l'
>>> most_popular_character("gggcccbb")
'c'
Note that using max is more efficient than sorting the entire dictionary, because it only needs to iterate over the dictionary once and find the single largest item, as opposed to sorting every item relative to every other item.
|
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_string consists of English letters only, and is not empty.
Example 1: >>> most_popular_character("HelloWorld") >>> 'l'
Example 2: >>> most_popular_character("gggcccbb") >>> 'c'
Explanation: cee and gee appear three times each (and bee twice), but cee precedes gee lexicographically.
Hints (you may ignore these):
Build a dictionary mapping letters to their frequency;
Find the largest frequency;
Find the smallest letter having that frequency.
def most_popular_character(my_string):
char_count = {} # define dictionary
for c in my_string:
if c in char_count: #if c is in the dictionary:
char_count[c] = 1
else: # if c isn't in the dictionary - create it and put 1
char_count[c] = 1
sorted_chars = sorted(char_count) # sort the dictionary
char_count = char_count.keys() # place the dictionary in a list
max_per = 0
for i in range(len(sorted_chars) - 1):
if sorted_chars[i] >= sorted_chars[i+1]:
max_per = sorted_chars[i]
break
return max_per
my function returns 0 right now, and I think the problem is in the last for loop and if statement - but I can't figure out what the problem is..
If you have any suggestions on how to adjust the code it would be very appreciated!
|
[
"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):\n # NOTE: you might want to convert the entire sting to upper or lower case, first, depending on the use\n # e.g. my_string = my_string.lower()\n char_count = {} # define dictionary\n for c in my_string:\n if c in char_count: #if c is in the dictionary:\n char_count[c] += 1 # add 1 to it\n else: # if c isn't in the dictionary - create it and put 1\n char_count[c] = 1\n\n # Never under estimate the power of print in debugging\n print(char_count)\n\n # max(char_count.values()) will give the highest value\n # But there may be more than 1 item with the highest count, so get them all\n max_keys = [key for key, value in char_count.items() if value == max(char_count.values())]\n\n # Choose the lowest by sorting them and pick the first item\n low_item = sorted(max_keys)[0]\n\n return low_item, max(char_count.values())\n\nprint(most_popular_character(\"HelloWorld\"))\nprint(most_popular_character(\"gggcccbb\"))\nprint(most_popular_character(\"gggHHHAAAAaaaccccbb 12 3\"))\n\nResult:\n{'H': 1, 'e': 1, 'l': 3, 'o': 2, 'W': 1, 'r': 1, 'd': 1}\n('l', 3)\n{'g': 3, 'c': 3, 'b': 2}\n('c', 3)\n{'g': 3, 'H': 3, 'A': 4, 'a': 3, 'c': 4, 'b': 2, ' ': 2, '1': 1, '2': 1, '3': 1}\n('A', 4)\n\nSo: l and 3, c and 3, A and 4\n",
"def most_popular_character(my_string):\n history_l = [l for l in my_string] #each letter in string\n char_dict = {} #creating dict\n for item in history_l: #for each letter in string\n char_dict[item] = history_l.count(item)\n\n return [max(char_dict.values()),min(char_dict.values())]\n\nI didn't understand the last part of minimum frequency, so I make this function return a maximum frequency and a minimum frequency as a list!\n",
"Use a Counter to count the characters, and use the max function to select the \"biggest\" character according to your two criteria.\n>>> from collections import Counter\n>>> def most_popular_character(my_string):\n... chars = Counter(my_string)\n... return max(chars, key=lambda c: (chars[c], -ord(c)))\n...\n>>> most_popular_character(\"HelloWorld\")\n'l'\n>>> most_popular_character(\"gggcccbb\")\n'c'\n\nNote that using max is more efficient than sorting the entire dictionary, because it only needs to iterate over the dictionary once and find the single largest item, as opposed to sorting every item relative to every other item.\n"
] |
[
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,default='python')
exam_time=models.DateTimeField()
views.py
def Examadd(request):
mycourses = Courses.objects.all()
context = {'mycourses': mycourses}
if request.method == 'POST':
newexam = request.POST.get('examname')
course = request.POST.get('courses')
examtime = request.POST.get('time')
new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime)
new.save()
messages.success(request, "Course created successfully")
return redirect('Courselist')
return render(request,'addexam.html',context)
addexam.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Add New Exam</h1>
<form method="post">
{% csrf_token %}
<label>Examname:</label>
<input type="text" name="examname">
<label>Course:</label>
<select name="courses">
{% for i in mycourses %}
<option value={{i.id}}>{{i.course_name}}</option>
{% endfor %}
</select>
<label>Exam time and date:</label>
<input type="text" name="examtime">
<button type="submit">Add</button>
</form>
</body>
</html>
I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance.
A:
You should assign the primary key to course_id, so:
def Examadd(request):
mycourses = Courses.objects.all()
context = {'mycourses': mycourses}
if request.method == 'POST':
newexam = request.POST.get('examname')
course = request.POST.get('courses')
examtime = request.POST.get('time')
new = Exam.objects.create(
exam_name=newexam, course_id=course, exam_time=examtime
)
messages.success(request, "Course created successfully")
return redirect('Courselist')
return render(request, 'addexam.html', context)
I would however advise to use a ModelForm, this makes saving the data easier and less error-prone, but will also do proper validation: for example checking that time is indeed passed, and that it is formatted as a correct datetime string.
Note: normally a Django model is given a singular name, so Course instead of Courses.
Note: Normally model fields have no prefix with the name of the model. This makes
queries longer to read, and often want uses inheritance of (abstract) models to
inherit fields, so using a prefix would make it less reusable. Therefore it
might be better to rename your field course_name to name.
A:
At first, create() method doesn't require save() method to be called, and you can directly assign course id in the Exam model, so the view should be:
def Examadd(request):
mycourses = Courses.objects.all()
context = {'mycourses': mycourses}
if request.method == 'POST':
newexam = request.POST.get('examname')
course = request.POST.get('courses')
examtime = request.POST.get('time')
new = Exam.objects.create(exam_name=newexam,course__id=course,exam_time=examtime)
messages.success(request, "Course created successfully")
return redirect('Courselist')
return render(request,'addexam.html',context)
|
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()
views.py
def Examadd(request):
mycourses = Courses.objects.all()
context = {'mycourses': mycourses}
if request.method == 'POST':
newexam = request.POST.get('examname')
course = request.POST.get('courses')
examtime = request.POST.get('time')
new = Exam.objects.create(exam_name=newexam,course=course,exam_time=examtime)
new.save()
messages.success(request, "Course created successfully")
return redirect('Courselist')
return render(request,'addexam.html',context)
addexam.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Add New Exam</h1>
<form method="post">
{% csrf_token %}
<label>Examname:</label>
<input type="text" name="examname">
<label>Course:</label>
<select name="courses">
{% for i in mycourses %}
<option value={{i.id}}>{{i.course_name}}</option>
{% endfor %}
</select>
<label>Exam time and date:</label>
<input type="text" name="examtime">
<button type="submit">Add</button>
</form>
</body>
</html>
I am doing a project elearning.I want a dropdown list with courses and pass its ids to Exam table.course id is a foreign key.I want to pass the courseid to course column in Exam table.By this code I gets error as,Cannot assign "'1'": "Exam.course" must be a "Courses" instance.
|
[
"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.get('time')\n new = Exam.objects.create(\n exam_name=newexam, course_id=course, exam_time=examtime\n )\n messages.success(request, \"Course created successfully\")\n return redirect('Courselist')\n return render(request, 'addexam.html', context)\nI would however advise to use a ModelForm, this makes saving the data easier and less error-prone, but will also do proper validation: for example checking that time is indeed passed, and that it is formatted as a correct datetime string.\n\n\nNote: normally a Django model is given a singular name, so Course instead of Courses.\n\n\n\nNote: Normally model fields have no prefix with the name of the model. This makes\nqueries longer to read, and often want uses inheritance of (abstract) models to\ninherit fields, so using a prefix would make it less reusable. Therefore it\nmight be better to rename your field course_name to name.\n\n",
"At first, create() method doesn't require save() method to be called, and you can directly assign course id in the Exam model, so the view should be:\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.get('time')\n new = Exam.objects.create(exam_name=newexam,course__id=course,exam_time=examtime)\n messages.success(request, \"Course created successfully\")\n return redirect('Courselist')\n return render(request,'addexam.html',context)\n\n"
] |
[
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 time of day string.
0:00 - 5:59 night
6:00 - 11:59 morning
12:00 - 17:59 afternoon
18:00 - 21:59 evening
22:00 - 23:59 night
I assume that I need to use a for loop with between_time() on df.time.
However, this does not work because I seem to need to use the column time as the index column of the dataframe. However, the dataframe has an index that I don't want to lose.
Even if I could add a second index and then filter on each time period, it would not be clear to me how to insert the respective string into the new column timeofday.
I tried to filter like
df.time.between_time('02:00', '03:30')
Which leads to
TypeError: Index must be DatetimeIndex
So I assumed I need to set the time column as new index
df.set_index("time", inplace=True)
df["timeofday"] = 'night'
df["timeofday"][df.time.between_time('06:00', '11:59')] = "morning"
which leads to the same
TypeError: Index must be DatetimeIndex
After that I tried
df.set_index("start", inplace=True)
df["timeofday"] = 'night'
df["timeofday"][df.between_time('06:00', '11:59')] = "morning"
Leads to
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
InvalidIndexError
A:
Found a solution
df.set_index("start", inplace=True)
df["timeofday"] = 'night'
mask = df.between_time('06:00', '11:59')
df.loc[mask.index, 'timeofday'] = "morning"
mask = df.between_time('12:00', '17:59')
df.loc[mask.index, 'timeofday'] = "afternoon"
mask = df.between_time('18:00', '21:59')
df.loc[mask.index, 'timeofday'] = "evening"
df.reset_index(inplace=True)
A:
We can use pandas.DataFrame.loc and pandas.Series.between to accomplish this. Here is a full example.
Solution
import pandas as pd
from io import StringIO
# Example data with expected result so we can check our work later
input_data = """
start,expected_timeofday
2022-11-26 01:41:26,night
2022-11-26 03:13:06,night
2022-11-26 04:40:58,night
2022-11-26 06:07:06,morning
2022-11-26 06:27:14,morning
2022-11-26 06:28:16,morning
2022-11-26 07:34:46,morning
2022-11-26 10:01:44,morning
2022-11-26 13:45:08,afternoon
2022-11-26 15:40:36,afternoon
2022-11-26 15:59:00,afternoon
2022-11-26 16:51:03,afternoon
2022-11-26 17:15:42,afternoon
2022-11-26 18:24:02,evening
2022-11-26 18:34:37,evening
2022-11-26 19:21:00,evening
2022-11-26 19:41:17,evening
2022-11-26 21:53:10,evening
2022-11-26 23:16:29,night
2022-11-26 23:36:08,night
""".strip()
# Read example data from CSV-formatted string
df = pd.read_csv(StringIO(input_data), parse_dates=['start'])
class TimeOfDay():
MORNING = 'morning'
AFTERNOON = 'afternoon'
EVENING = 'evening'
NIGHT = 'night'
# Set `timeofday` category by using a filter on the
# hour property of the datetime column `start`.
df['timeofday'] = None
df.loc[df.start.dt.hour.between(0, 6, inclusive='left'), 'timeofday'] = TimeOfDay.NIGHT
df.loc[df.start.dt.hour.between(6, 12, inclusive='left'), 'timeofday'] = TimeOfDay.MORNING
df.loc[df.start.dt.hour.between(12, 18, inclusive='left'), 'timeofday'] = TimeOfDay.AFTERNOON
df.loc[df.start.dt.hour.between(18, 22, inclusive='left'), 'timeofday'] = TimeOfDay.EVENING
df.loc[df.start.dt.hour.between(22, 24, inclusive='left'), 'timeofday'] = TimeOfDay.NIGHT
# Check our work; raises an exception if we made a mistake
assert((df.timeofday == df.expected_timeofday).all())
# Result
print(df)
Result
start expected_timeofday timeofday
0 2022-11-26 01:41:26 night night
1 2022-11-26 03:13:06 night night
2 2022-11-26 04:40:58 night night
3 2022-11-26 06:07:06 morning morning
4 2022-11-26 06:27:14 morning morning
5 2022-11-26 06:28:16 morning morning
6 2022-11-26 07:34:46 morning morning
7 2022-11-26 10:01:44 morning morning
8 2022-11-26 13:45:08 afternoon afternoon
9 2022-11-26 15:40:36 afternoon afternoon
10 2022-11-26 15:59:00 afternoon afternoon
11 2022-11-26 16:51:03 afternoon afternoon
12 2022-11-26 17:15:42 afternoon afternoon
13 2022-11-26 18:24:02 evening evening
14 2022-11-26 18:34:37 evening evening
15 2022-11-26 19:21:00 evening evening
16 2022-11-26 19:41:17 evening evening
17 2022-11-26 21:53:10 evening evening
18 2022-11-26 23:16:29 night night
19 2022-11-26 23:36:08 night night
|
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:00 - 21:59 evening
22:00 - 23:59 night
I assume that I need to use a for loop with between_time() on df.time.
However, this does not work because I seem to need to use the column time as the index column of the dataframe. However, the dataframe has an index that I don't want to lose.
Even if I could add a second index and then filter on each time period, it would not be clear to me how to insert the respective string into the new column timeofday.
I tried to filter like
df.time.between_time('02:00', '03:30')
Which leads to
TypeError: Index must be DatetimeIndex
So I assumed I need to set the time column as new index
df.set_index("time", inplace=True)
df["timeofday"] = 'night'
df["timeofday"][df.time.between_time('06:00', '11:59')] = "morning"
which leads to the same
TypeError: Index must be DatetimeIndex
After that I tried
df.set_index("start", inplace=True)
df["timeofday"] = 'night'
df["timeofday"][df.between_time('06:00', '11:59')] = "morning"
Leads to
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
InvalidIndexError
|
[
"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')\ndf.loc[mask.index, 'timeofday'] = \"evening\"\n\ndf.reset_index(inplace=True)\n\n",
"We can use pandas.DataFrame.loc and pandas.Series.between to accomplish this. Here is a full example.\nSolution\nimport pandas as pd\nfrom io import StringIO\n\n# Example data with expected result so we can check our work later\ninput_data = \"\"\"\nstart,expected_timeofday\n2022-11-26 01:41:26,night\n2022-11-26 03:13:06,night\n2022-11-26 04:40:58,night\n2022-11-26 06:07:06,morning\n2022-11-26 06:27:14,morning\n2022-11-26 06:28:16,morning\n2022-11-26 07:34:46,morning\n2022-11-26 10:01:44,morning\n2022-11-26 13:45:08,afternoon\n2022-11-26 15:40:36,afternoon\n2022-11-26 15:59:00,afternoon\n2022-11-26 16:51:03,afternoon\n2022-11-26 17:15:42,afternoon\n2022-11-26 18:24:02,evening\n2022-11-26 18:34:37,evening\n2022-11-26 19:21:00,evening\n2022-11-26 19:41:17,evening\n2022-11-26 21:53:10,evening\n2022-11-26 23:16:29,night\n2022-11-26 23:36:08,night\n\"\"\".strip()\n\n# Read example data from CSV-formatted string\ndf = pd.read_csv(StringIO(input_data), parse_dates=['start'])\n\nclass TimeOfDay():\n MORNING = 'morning'\n AFTERNOON = 'afternoon'\n EVENING = 'evening'\n NIGHT = 'night'\n\n# Set `timeofday` category by using a filter on the\n# hour property of the datetime column `start`.\ndf['timeofday'] = None\ndf.loc[df.start.dt.hour.between(0, 6, inclusive='left'), 'timeofday'] = TimeOfDay.NIGHT\ndf.loc[df.start.dt.hour.between(6, 12, inclusive='left'), 'timeofday'] = TimeOfDay.MORNING\ndf.loc[df.start.dt.hour.between(12, 18, inclusive='left'), 'timeofday'] = TimeOfDay.AFTERNOON\ndf.loc[df.start.dt.hour.between(18, 22, inclusive='left'), 'timeofday'] = TimeOfDay.EVENING\ndf.loc[df.start.dt.hour.between(22, 24, inclusive='left'), 'timeofday'] = TimeOfDay.NIGHT\n\n# Check our work; raises an exception if we made a mistake\nassert((df.timeofday == df.expected_timeofday).all())\n\n# Result\nprint(df)\n\nResult\n start expected_timeofday timeofday\n0 2022-11-26 01:41:26 night night\n1 2022-11-26 03:13:06 night night\n2 2022-11-26 04:40:58 night night\n3 2022-11-26 06:07:06 morning morning\n4 2022-11-26 06:27:14 morning morning\n5 2022-11-26 06:28:16 morning morning\n6 2022-11-26 07:34:46 morning morning\n7 2022-11-26 10:01:44 morning morning\n8 2022-11-26 13:45:08 afternoon afternoon\n9 2022-11-26 15:40:36 afternoon afternoon\n10 2022-11-26 15:59:00 afternoon afternoon\n11 2022-11-26 16:51:03 afternoon afternoon\n12 2022-11-26 17:15:42 afternoon afternoon\n13 2022-11-26 18:24:02 evening evening\n14 2022-11-26 18:34:37 evening evening\n15 2022-11-26 19:21:00 evening evening\n16 2022-11-26 19:41:17 evening evening\n17 2022-11-26 21:53:10 evening evening\n18 2022-11-26 23:16:29 night night\n19 2022-11-26 23:36:08 night night\n\n"
] |
[
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({
'enableRateLimit': True,
'apiKey': 'xxxxxxxxxxxxxxxxxxx',
'secret': 'xxxxxxxxxxxxx'
})
symbol = 'ETHUSDT'
timeframe = '15m'
limit = 500
bars = binance.fetch_ohlcv (symbol, timeframe = timeframe, limit = limit)
df = pd.DataFrame(bars, columns = ['timestamp','open','high','low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit = 'ms').dt.tz_localize(tz='US/Central')
df['timestamp'] = pd.to_datetime(df['timestamp'], unit = 'ms').dt.tz_convert(tz='US/Central')
print(df)
timestamp open high low close volume
0 2022-11-21 12:15:00-06:00 1120.63 1122.74 1118.26 1119.31 3278.5060
1 2022-11-21 12:30:00-06:00 1119.30 1127.48 1115.10 1125.31 11065.4442
2 2022-11-21 12:45:00-06:00 1125.32 1128.36 1123.92 1127.30 5447.6054
3 2022-11-21 13:00:00-06:00 1127.30 1136.75 1125.67 1133.81 15977.1500
4 2022-11-21 13:15:00-06:00 1133.82 1146.99 1132.77 1139.39 21009.7356
.. ... ... ... ... ... ...
495 2022-11-26 16:00:00-06:00 1210.90 1212.87 1208.77 1212.54 3822.1327
496 2022-11-26 16:15:00-06:00 1212.55 1213.92 1212.09 1213.63 2414.2695
497 2022-11-26 16:30:00-06:00 1213.62 1213.63 1211.05 1212.89 2461.4644
498 2022-11-26 16:45:00-06:00 1212.89 1212.94 1209.00 1209.76 2544.8965
499 2022-11-26 17:00:00-06:00 1209.75 1210.00 1207.74 1209.77 1638.1446
A:
I think you want.
df["timestamp"] = (
pd.to_datetime(df["timestamp"], unit="ms")
.dt.tz_localize("UTC")
.dt.tz_convert("US/Central")
.dt.tz_localize(None)
)
|
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': 'xxxxxxxxxxxxx'
})
symbol = 'ETHUSDT'
timeframe = '15m'
limit = 500
bars = binance.fetch_ohlcv (symbol, timeframe = timeframe, limit = limit)
df = pd.DataFrame(bars, columns = ['timestamp','open','high','low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit = 'ms').dt.tz_localize(tz='US/Central')
df['timestamp'] = pd.to_datetime(df['timestamp'], unit = 'ms').dt.tz_convert(tz='US/Central')
print(df)
timestamp open high low close volume
0 2022-11-21 12:15:00-06:00 1120.63 1122.74 1118.26 1119.31 3278.5060
1 2022-11-21 12:30:00-06:00 1119.30 1127.48 1115.10 1125.31 11065.4442
2 2022-11-21 12:45:00-06:00 1125.32 1128.36 1123.92 1127.30 5447.6054
3 2022-11-21 13:00:00-06:00 1127.30 1136.75 1125.67 1133.81 15977.1500
4 2022-11-21 13:15:00-06:00 1133.82 1146.99 1132.77 1139.39 21009.7356
.. ... ... ... ... ... ...
495 2022-11-26 16:00:00-06:00 1210.90 1212.87 1208.77 1212.54 3822.1327
496 2022-11-26 16:15:00-06:00 1212.55 1213.92 1212.09 1213.63 2414.2695
497 2022-11-26 16:30:00-06:00 1213.62 1213.63 1211.05 1212.89 2461.4644
498 2022-11-26 16:45:00-06:00 1212.89 1212.94 1209.00 1209.76 2544.8965
499 2022-11-26 17:00:00-06:00 1209.75 1210.00 1207.74 1209.77 1638.1446
|
[
"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 the image of the elements. I used beautifulsoup to scrape out the data but it seems like that information in the <script> never appears in the terminal. My assumption is this section of information may not be allow for scraping?
from bs4 import BeautifulSoup
import requests
url = "https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.text, "html.parser")
data = soup.find('div', id_ = 'market-stats')
print(data)
A:
Below is an example how to grab the required script tag from API response and rest of your task.
import pandas as pd
import requests
from bs4 import BeautifulSoup
url = 'https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium'
headers={
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
}
soup = BeautifulSoup(requests.get(url,headers=headers).text, 'html.parser')
token = soup.select_one('meta[name="csrf-token"]').get('content')
header = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
'x-csrf-token': token,
'x-requested-with': 'XMLHttpRequest'
}
api_url= 'https://www.dotproperty.co.th/en/market-stats/project-page/condo/?key=2945&pv_id=sea_th_pv_4df81b83-00a9-4453-97b3-80c92eea45b9'
data=[]
res=requests.get(api_url,headers=header).json()['msg']
soup = BeautifulSoup(res,'html.parser')
#print(soup.prettify())
script = soup.find('script').get_text(strip=True)
print(script)
Output:
function getChartDataSets(type) {
var chartData = {
'sale': {
data : {
dataSets : {
'left':{
// yAxisID: "y-axis-0",
radius: 0,
data:[4850000,4962500,4770833],
borderColor: "rgb(79,190,75)",
backgroundColor: "rgb(79,190,75)",
fill:false,
showLine:true,
label:'Median sale price'
},
'right': {
// yAxisID: "y-axis-1",
radius: 0,
data:[4917801,5167798,5124463],
borderColor: "rgb(204,51,51)",
backgroundColor: "rgb(204,51,51)",
fill:false,
showLine:true,
label: 'Mueang Phuket' + ' Median sale price'
}
}
},
yAxes : {
min: 4450000,
max: 5450000,
stepSize: 250000,
}
},
'sqmSale': {
data : {
dataSets : {
'left':{
// yAxisID: "y-axis-0",
radius: 0,
data:[88867,94915,94594],
borderColor: "rgb(79,190,75)",
backgroundColor: "rgb(79,190,75)",
fill:false,
showLine:true,
label:'Median sale price/sqm.'
},
'right': {
// yAxisID: "y-axis-1",
radius: 0,
data:[97669,91350,92066],
borderColor: "rgb(204,51,51)",
backgroundColor: "rgb(204,51,51)",
fill:false,
showLine:true,
label: htmlDecode('Mueang Phuket' + ' Median sale price/sqm.')
}
}
},
yAxes : {
min: 83000,
max: 103000,
stepSize: 5000,
}
},
}
return chartData[type];
}
function getDataSets(chartType){
var dataSetsAr = getChartDataSets(chartType);
var dataSets;
if (dataSetsAr.data.dataSets.right) {
datasets = [dataSetsAr.data.dataSets.left, dataSetsAr.data.dataSets.right];
}else{
datasets = [dataSetsAr.data.dataSets.left];
}
var dataSets = {
labels: ["Sep 2022","Oct 2022","Nov 2022"],
datasets: datasets
}
return dataSets;
}
function getOptions(chartType){
var dataSetsArr = getChartDataSets(chartType);
// console.log(getChartOptionsDataSets(chartType).scales.left.ticks.max);
var options = {
maintainAspectRatio: false,
responsive: true,
maintainAspectRatio: false,
legend: {
display: true,
position: 'bottom',
onClick: function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;
var anyOthersAlreadyHidden = false;
var allOthersHidden = true;
// figure out the current state of the labels
ci.data.datasets.forEach(function(e, i) {
var meta = ci.getDatasetMeta(i);
if (i !== index) {
if (meta.hidden) {
anyOthersAlreadyHidden = true;
} else {
allOthersHidden = false;
}
}
});
// if the label we clicked is already hidden
// then we now want to unhide (with any others already unhidden)
if (alreadyHidden) {
ci.getDatasetMeta(index).hidden = null;
} else {
// otherwise, lets figure out how to toggle visibility based upon the current state
ci.data.datasets.forEach(function(e, i) {
var meta = ci.getDatasetMeta(i);
if (i !== index) {
// handles logic when we click on visible hidden label and there is currently at least
// one other label that is visible and at least one other label already hidden
// (we want to keep those already hidden still hidden)
if (anyOthersAlreadyHidden && !allOthersHidden) {
meta.hidden = true;
} else {
// toggle visibility
meta.hidden = meta.hidden === null ? !meta.hidden : null;
}
} else {
meta.hidden = null;
}
});
}
if (!allOthersHidden && !anyOthersAlreadyHidden && !alreadyHidden) {
delete ci.options.scales.yAxes[0].ticks.min
delete ci.options.scales.yAxes[0].ticks.max
delete ci.options.scales.yAxes[0].ticks.stepSize
}else{
updateChart();
return;
}
ci.update();
},
},
hover: {
mode: 'nearest',
intersect: false,
},
title:{
display: false,
text: 'Median Sale'
},
tooltips: {
intersect: false,
mode: 'index',
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ฿' + addCommas(label);
}
},
// custom: function(tooltip) {
// if (!tooltip) return;
// // disable displaying the color box;
// tooltip.displayColors = false;
// },
},
scales: {
xAxes: [{
// padding: 100,
display: true,
gridLines : {
display : false
}
}],
yAxes: [{
gridLines : {
display : true
},
ticks: {
// beginAtZero:true,
fontColor: "rgb(79,190,75)",
min:dataSetsArr.yAxes.min,
max: dataSetsArr.yAxes.max,
stepSize: dataSetsArr.yAxes.stepSize,
fontSize: 10,
beginAtZero: false,
userCallback: function(value, index, values) {
value = value.toString();
return '฿' + nFormatter(value);
}
},
}]
}
}
return options;
}
var ctx = document.getElementById("market-stats-chart").getContext('2d');
var chartType = $('#market-stats-type').val();
marketStatsChart = new Chart(ctx, {
type: 'line',
data: getDataSets(chartType),
options: getOptions(chartType)
});
// document.getElementById('indicator-graph-panel').style.display = 'none';
function updateChart(){
var newType = $('#market-stats-type').val();
var newDataSets = getChartDataSets(newType);
var dataSets;
if (newDataSets.data.dataSets.right) {
datasets = [newDataSets.data.dataSets.left, newDataSets.data.dataSets.right];
}else{
datasets = [newDataSets.data.dataSets.left];
}
marketStatsChart.options.scales.yAxes[0].ticks.min = newDataSets.yAxes.min;
marketStatsChart.options.scales.yAxes[0].ticks.max = newDataSets.yAxes.max;
marketStatsChart.options.scales.yAxes[0].ticks.stepSize = newDataSets.yAxes.stepSize;
marketStatsChart.data.datasets = datasets;
marketStatsChart.update();
}
$('#market-stats-type').on('change', updateChart);
function nFormatter(num) {
if (num >= 1000000000) {
return ( Math.round( ((num / 1000000000) * 100)) / 100).toFixed(1) + 'B';
// return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
}
if (num >= 1000000) {
return (Math.round( ((num / 1000000) * 100) ) / 100 ).toFixed(1)+ 'M';
// return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
}
if (num >= 1000) {
return (Math.round( ((num / 1000) * 100) ) / 100).toFixed(1) + 'K';
// return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
}
return num;
}
|
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 image of the elements. I used beautifulsoup to scrape out the data but it seems like that information in the <script> never appears in the terminal. My assumption is this section of information may not be allow for scraping?
from bs4 import BeautifulSoup
import requests
url = "https://www.dotproperty.co.th/en/condo/2945/nai-harn-beach-condominium"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.text, "html.parser")
data = soup.find('div', id_ = 'market-stats')
print(data)
|
[
"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; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'\n }\nsoup = BeautifulSoup(requests.get(url,headers=headers).text, 'html.parser')\ntoken = soup.select_one('meta[name=\"csrf-token\"]').get('content')\n\nheader = {\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',\n 'x-csrf-token': token,\n 'x-requested-with': 'XMLHttpRequest'\n \n}\napi_url= 'https://www.dotproperty.co.th/en/market-stats/project-page/condo/?key=2945&pv_id=sea_th_pv_4df81b83-00a9-4453-97b3-80c92eea45b9'\n\ndata=[]\n\nres=requests.get(api_url,headers=header).json()['msg']\nsoup = BeautifulSoup(res,'html.parser')\n#print(soup.prettify())\nscript = soup.find('script').get_text(strip=True)\nprint(script)\n\nOutput:\nfunction getChartDataSets(type) {\n var chartData = {\n 'sale': {\n data : {\n dataSets : {\n 'left':{\n // yAxisID: \"y-axis-0\",\n radius: 0,\n data:[4850000,4962500,4770833],\n borderColor: \"rgb(79,190,75)\",\n backgroundColor: \"rgb(79,190,75)\",\n fill:false,\n showLine:true,\n label:'Median sale price'\n },\n 'right': {\n // yAxisID: \"y-axis-1\",\n radius: 0,\n data:[4917801,5167798,5124463],\n borderColor: \"rgb(204,51,51)\",\n backgroundColor: \"rgb(204,51,51)\",\n fill:false,\n showLine:true,\n label: 'Mueang Phuket' + ' Median sale price'\n }\n }\n },\n yAxes : {\n min: 4450000,\n max: 5450000,\n stepSize: 250000,\n }\n\n },\n 'sqmSale': {\n data : {\n dataSets : {\n 'left':{\n // yAxisID: \"y-axis-0\",\n radius: 0,\n data:[88867,94915,94594],\n borderColor: \"rgb(79,190,75)\",\n backgroundColor: \"rgb(79,190,75)\",\n fill:false,\n showLine:true,\n label:'Median sale price/sqm.'\n },\n 'right': {\n // yAxisID: \"y-axis-1\",\n radius: 0,\n data:[97669,91350,92066],\n borderColor: \"rgb(204,51,51)\",\n backgroundColor: \"rgb(204,51,51)\",\n fill:false,\n showLine:true,\n label: htmlDecode('Mueang Phuket' + ' Median sale price/sqm.')\n }\n }\n },\n yAxes : {\n min: 83000,\n max: 103000,\n stepSize: 5000,\n }\n\n },\n }\n return chartData[type];\n }\n function getDataSets(chartType){\n var dataSetsAr = getChartDataSets(chartType);\n var dataSets;\n if (dataSetsAr.data.dataSets.right) {\n datasets = [dataSetsAr.data.dataSets.left, dataSetsAr.data.dataSets.right]; \n }else{\n datasets = [dataSetsAr.data.dataSets.left];\n }\n var dataSets = {\n labels: [\"Sep 2022\",\"Oct 2022\",\"Nov 2022\"],\n datasets: datasets\n }\n return dataSets;\n }\n function getOptions(chartType){\n var dataSetsArr = getChartDataSets(chartType);\n // console.log(getChartOptionsDataSets(chartType).scales.left.ticks.max);\n var options = {\n maintainAspectRatio: false,\n responsive: true,\n maintainAspectRatio: false,\n legend: {\n display: true,\n position: 'bottom',\n onClick: function(e, legendItem) {\n var index = legendItem.datasetIndex;\n var ci = this.chart;\n var alreadyHidden = (ci.getDatasetMeta(index).hidden === null) ? false : ci.getDatasetMeta(index).hidden;\n var anyOthersAlreadyHidden = false;\n var allOthersHidden = true;\n\n // figure out the current state of the labels\n ci.data.datasets.forEach(function(e, i) {\n var meta = ci.getDatasetMeta(i);\n\n if (i !== index) {\n if (meta.hidden) {\n anyOthersAlreadyHidden = true;\n } else {\n allOthersHidden = false;\n }\n }\n });\n\n // if the label we clicked is already hidden\n // then we now want to unhide (with any others already unhidden)\n if (alreadyHidden) {\n ci.getDatasetMeta(index).hidden = null;\n } else {\n // otherwise, lets figure out how to toggle visibility based upon the current state\n ci.data.datasets.forEach(function(e, i) {\n var meta = ci.getDatasetMeta(i);\n\n if (i !== index) {\n // handles logic when we click on visible hidden label and there is currently at least\n // one other label that is visible and at least one other label already hidden\n // (we want to keep those already hidden still hidden)\n if (anyOthersAlreadyHidden && !allOthersHidden) {\n meta.hidden = true;\n } else {\n // toggle visibility\n meta.hidden = meta.hidden === null ? !meta.hidden : null;\n }\n } else {\n meta.hidden = null;\n }\n });\n }\n if (!allOthersHidden && !anyOthersAlreadyHidden && !alreadyHidden) { \n delete ci.options.scales.yAxes[0].ticks.min\n delete ci.options.scales.yAxes[0].ticks.max\n delete ci.options.scales.yAxes[0].ticks.stepSize\n }else{\n updateChart();\n return;\n }\n ci.update();\n },\n },\n hover: {\n mode: 'nearest',\n intersect: false,\n },\n title:{\n display: false,\n text: 'Median Sale'\n },\n tooltips: {\n intersect: false,\n mode: 'index',\n callbacks: {\n label: function(tooltipItem, data) {\n var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];\n return ' ฿' + addCommas(label);\n }\n },\n // custom: function(tooltip) {\n // if (!tooltip) return;\n // // disable displaying the color box;\n // tooltip.displayColors = false;\n // },\n },\n\n scales: {\n xAxes: [{\n // padding: 100,\n display: true,\n\n gridLines : {\n display : false\n }\n }],\n yAxes: [{\n gridLines : {\n display : true\n },\n ticks: {\n // beginAtZero:true,\n fontColor: \"rgb(79,190,75)\",\n min:dataSetsArr.yAxes.min,\n max: dataSetsArr.yAxes.max,\n stepSize: dataSetsArr.yAxes.stepSize,\n fontSize: 10,\n beginAtZero: false,\n userCallback: function(value, index, values) {\n value = value.toString();\n return '฿' + nFormatter(value);\n }\n },\n }]\n }\n }\n\n return options;\n }\n var ctx = document.getElementById(\"market-stats-chart\").getContext('2d');\n var chartType = $('#market-stats-type').val();\n\n marketStatsChart = new Chart(ctx, {\n type: 'line',\n data: getDataSets(chartType),\n options: getOptions(chartType)\n });\n // document.getElementById('indicator-graph-panel').style.display = 'none';\n function updateChart(){\n var newType = $('#market-stats-type').val();\n var newDataSets = getChartDataSets(newType);\n\n\n var dataSets;\n if (newDataSets.data.dataSets.right) {\n datasets = [newDataSets.data.dataSets.left, newDataSets.data.dataSets.right]; \n }else{\n datasets = [newDataSets.data.dataSets.left];\n }\n\n marketStatsChart.options.scales.yAxes[0].ticks.min = newDataSets.yAxes.min;\n marketStatsChart.options.scales.yAxes[0].ticks.max = newDataSets.yAxes.max;\n marketStatsChart.options.scales.yAxes[0].ticks.stepSize = newDataSets.yAxes.stepSize; \n\n marketStatsChart.data.datasets = datasets;\n marketStatsChart.update();\n }\n $('#market-stats-type').on('change', updateChart);\n\n function nFormatter(num) {\n if (num >= 1000000000) {\n return ( Math.round( ((num / 1000000000) * 100)) / 100).toFixed(1) + 'B'; \n // return (num / 1000000000).toFixed(1).replace(/\\.0$/, '') + 'G';\n }\n if (num >= 1000000) {\n return (Math.round( ((num / 1000000) * 100) ) / 100 ).toFixed(1)+ 'M';\n // return (num / 1000000).toFixed(1).replace(/\\.0$/, '') + 'M';\n }\n if (num >= 1000) {\n return (Math.round( ((num / 1000) * 100) ) / 100).toFixed(1) + 'K';\n // return (num / 1000).toFixed(1).replace(/\\.0$/, '') + 'K';\n }\n return num;\n }\n\n"
] |
[
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 DAGs. I know how to do this using a Dockerfile (COPY requirements.txt /app / RUN pip install -r requirements.txt), but there is no Dockerfile involved here.
How to install python dependencies in airflow 2.0.2 / docker-compose?
On which of the six containers which are deployed when using the custom docker-compose do I need to install the dependencies?
A:
Instead of using
image: apache/airflow:x.x.x
in your docker compose you want to set this to
build:
context: .
dockerfile: Dockerfile
and then write this to your Dockerfile
FROM apache/airflow:x.x.x
COPY requirements.txt ./requirements.txt
where your requirements.txt contains the python packages. So you're not using the image but instead build it again with also installing the python packages.
|
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 pip install -r requirements.txt), but there is no Dockerfile involved here.
How to install python dependencies in airflow 2.0.2 / docker-compose?
On which of the six containers which are deployed when using the custom docker-compose do I need to install the dependencies?
|
[
"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 packages. So you're not using the image but instead build it again with also installing the python packages.\n"
] |
[
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 requiring that to be set up by the user.
In this question about a cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work
while True:
# Code executed here
time.sleep(60)
Are there any foreseeable problems with this code?
A:
If your program doesn't have a event loop already, use the sched module, which implements a general purpose event scheduler.
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print("Doing stuff...")
# do your stuff
sc.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
If you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.
A:
Lock your time loop to the system clock like this:
import time
starttime = time.time()
while True:
print("tick")
time.sleep(60.0 - ((time.time() - starttime) % 60.0))
A:
If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.
Here's the code I've posted in a similar question, with start() and stop() control:
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
Usage:
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
Features:
Standard library only, no external dependencies
start() and stop() are safe to call multiple times even if the timer has already started/stopped
function to be called can have positional and named arguments
You can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!
A:
You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.
from twisted.internet import task, reactor
timeout = 60.0 # Sixty seconds
def doWork():
#do work here
pass
l = task.LoopingCall(doWork)
l.start(timeout) # call every sixty seconds
reactor.run()
While "while True: sleep(60)" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution
A:
Here's an update to the code from MestreLion that avoids drifiting over time.
The RepeatedTimer class here calls the given function every "interval" seconds as requested by the OP; the schedule doesn't depend on how long the function takes to execute. I like this solution since it doesn't have external library dependencies; this is just pure python.
import threading
import time
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.next_call = time.time()
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self.next_call += self.interval
self._timer = threading.Timer(self.next_call - time.time(), self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
Sample usage (copied from MestreLion's answer):
from time import sleep
def hello(name):
print "Hello %s!" % name
print "starting..."
rt = RepeatedTimer(1, hello, "World") # it auto-starts, no need of rt.start()
try:
sleep(5) # your long-running job goes here...
finally:
rt.stop() # better in a try/finally block to make sure the program ends!
A:
import time, traceback
def every(delay, task):
next_time = time.time() + delay
while True:
time.sleep(max(0, next_time - time.time()))
try:
task()
except Exception:
traceback.print_exc()
# in production code you might want to have this instead of course:
# logger.exception("Problem while executing repetitive task.")
# skip tasks if we are behind schedule:
next_time += (time.time() - next_time) // delay * delay + delay
def foo():
print("foo", time.time())
every(5, foo)
If you want to do this without blocking your remaining code, you can use this to let it run in its own thread:
import threading
threading.Thread(target=lambda: every(5, foo)).start()
This solution combines several features rarely found combined in the other solutions:
Exception handling: As far as possible on this level, exceptions are handled properly, i. e. get logged for debugging purposes without aborting our program.
No chaining: The common chain-like implementation (for scheduling the next event) you find in many answers is brittle in the aspect that if anything goes wrong within the scheduling mechanism (threading.Timer or whatever), this will terminate the chain. No further executions will happen then, even if the reason of the problem is already fixed. A simple loop and waiting with a simple sleep() is much more robust in comparison.
No drift: My solution keeps an exact track of the times it is supposed to run at. There is no drift depending on the execution time (as in many other solutions).
Skipping: My solution will skip tasks if one execution took too much time (e. g. do X every five seconds, but X took 6 seconds). This is the standard cron behavior (and for a good reason). Many other solutions then simply execute the task several times in a row without any delay. For most cases (e. g. cleanup tasks) this is not wished. If it is wished, simply use next_time += delay instead.
A:
The easier way I believe to be:
import time
def executeSomething():
#code here
time.sleep(60)
while True:
executeSomething()
This way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc...
No need to complicate things :D
A:
I ended up using the schedule module. The API is nice.
import schedule
import time
def job():
print("I'm working...")
schedule.every(10).minutes.do(job)
schedule.every().hour.do(job)
schedule.every().day.at("10:30").do(job)
schedule.every(5).to(10).minutes.do(job)
schedule.every().monday.do(job)
schedule.every().wednesday.at("13:15").do(job)
schedule.every().minute.at(":17").do(job)
while True:
schedule.run_pending()
time.sleep(1)
A:
Alternative flexibility solution is Apscheduler.
pip install apscheduler
from apscheduler.schedulers.background import BlockingScheduler
def print_t():
pass
sched = BlockingScheduler()
sched.add_job(print_t, 'interval', seconds =60) #will do the print_t work for every 60 seconds
sched.start()
Also, apscheduler provides so many schedulers as follow.
BlockingScheduler: use when the scheduler is the only thing running in your process
BackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application
AsyncIOScheduler: use if your application uses the asyncio module
GeventScheduler: use if your application uses gevent
TornadoScheduler: use if you’re building a Tornado application
TwistedScheduler: use if you’re building a Twisted application
QtScheduler: use if you’re building a Qt application
A:
I faced a similar problem some time back. May be http://cronus.readthedocs.org might help?
For v0.2, the following snippet works
import cronus.beat as beat
beat.set_rate(2) # 2 Hz
while beat.true():
# do some time consuming work here
beat.sleep() # total loop duration would be 0.5 sec
A:
The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.
A:
If drift is not a concern
import threading, time
def print_every_n_seconds(n=2):
while True:
print(time.ctime())
time.sleep(n)
thread = threading.Thread(target=print_every_n_seconds, daemon=True)
thread.start()
Which asynchronously outputs.
#Tue Oct 16 17:29:40 2018
#Tue Oct 16 17:29:42 2018
#Tue Oct 16 17:29:44 2018
If the task being run takes appreciable amount of time, then the interval becomes 2 seconds + task time, so if you need precise scheduling then this is not for you.
Note the daemon=True flag means this thread won't block the app from shutting down. For example, had issue where pytest would hang indefinitely after running tests waiting for this thead to cease.
A:
Simply use
import time
while True:
print("this will run after every 30 sec")
#Your code here
time.sleep(30)
A:
One possible answer:
import time
t=time.time()
while True:
if time.time()-t>10:
#run your task here
t=time.time()
A:
I use Tkinter after() method, which doesn't "steal the game" (like the sched module that was presented earlier), i.e. it allows other things to run in parallel:
import Tkinter
def do_something1():
global n1
n1 += 1
if n1 == 6: # (Optional condition)
print "* do_something1() is done *"; return
# Do your stuff here
# ...
print "do_something1() "+str(n1)
tk.after(1000, do_something1)
def do_something2():
global n2
n2 += 1
if n2 == 6: # (Optional condition)
print "* do_something2() is done *"; return
# Do your stuff here
# ...
print "do_something2() "+str(n2)
tk.after(500, do_something2)
tk = Tkinter.Tk();
n1 = 0; n2 = 0
do_something1()
do_something2()
tk.mainloop()
do_something1() and do_something2() can run in parallel and in whatever interval speed. Here, the 2nd one will be executed twice as fast.Note also that I have used a simple counter as a condition to terminate either function. You can use whatever other contition you like or none if you what a function to run until the program terminates (e.g. a clock).
A:
Here's an adapted version to the code from MestreLion.
In addition to the original function, this code:
1) add first_interval used to fire the timer at a specific time(caller need to calculate the first_interval and pass in)
2) solve a race-condition in original code. In the original code, if control thread failed to cancel the running timer("Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage." quoted from https://docs.python.org/2/library/threading.html), the timer will run endlessly.
class RepeatedTimer(object):
def __init__(self, first_interval, interval, func, *args, **kwargs):
self.timer = None
self.first_interval = first_interval
self.interval = interval
self.func = func
self.args = args
self.kwargs = kwargs
self.running = False
self.is_started = False
def first_start(self):
try:
# no race-condition here because only control thread will call this method
# if already started will not start again
if not self.is_started:
self.is_started = True
self.timer = Timer(self.first_interval, self.run)
self.running = True
self.timer.start()
except Exception as e:
log_print(syslog.LOG_ERR, "timer first_start failed %s %s"%(e.message, traceback.format_exc()))
raise
def run(self):
# if not stopped start again
if self.running:
self.timer = Timer(self.interval, self.run)
self.timer.start()
self.func(*self.args, **self.kwargs)
def stop(self):
# cancel current timer in case failed it's still OK
# if already stopped doesn't matter to stop again
if self.timer:
self.timer.cancel()
self.running = False
A:
Here is another solution without using any extra libaries.
def delay_until(condition_fn, interval_in_sec, timeout_in_sec):
"""Delay using a boolean callable function.
`condition_fn` is invoked every `interval_in_sec` until `timeout_in_sec`.
It can break early if condition is met.
Args:
condition_fn - a callable boolean function
interval_in_sec - wait time between calling `condition_fn`
timeout_in_sec - maximum time to run
Returns: None
"""
start = last_call = time.time()
while time.time() - start < timeout_in_sec:
if (time.time() - last_call) > interval_in_sec:
if condition_fn() is True:
break
last_call = time.time()
A:
I use this to cause 60 events per hour with most events occurring at the same number of seconds after the whole minute:
import math
import time
import random
TICK = 60 # one minute tick size
TICK_TIMING = 59 # execute on 59th second of the tick
TICK_MINIMUM = 30 # minimum catch up tick size when lagging
def set_timing():
now = time.time()
elapsed = now - info['begin']
minutes = math.floor(elapsed/TICK)
tick_elapsed = now - info['completion_time']
if (info['tick']+1) > minutes:
wait = max(0,(TICK_TIMING-(time.time() % TICK)))
print ('standard wait: %.2f' % wait)
time.sleep(wait)
elif tick_elapsed < TICK_MINIMUM:
wait = TICK_MINIMUM-tick_elapsed
print ('minimum wait: %.2f' % wait)
time.sleep(wait)
else:
print ('skip set_timing(); no wait')
drift = ((time.time() - info['begin']) - info['tick']*TICK -
TICK_TIMING + info['begin']%TICK)
print ('drift: %.6f' % drift)
info['tick'] = 0
info['begin'] = time.time()
info['completion_time'] = info['begin'] - TICK
while 1:
set_timing()
print('hello world')
#random real world event
time.sleep(random.random()*TICK_MINIMUM)
info['tick'] += 1
info['completion_time'] = time.time()
Depending upon actual conditions you might get ticks of length:
60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.
but at the end of 60 minutes you'll have 60 ticks; and most of them will occur at the correct offset to the minute you prefer.
On my system I get typical drift of < 1/20th of a second until need for correction arises.
The advantage of this method is resolution of clock drift; which can cause issues if you're doing things like appending one item per tick and you expect 60 items appended per hour. Failure to account for drift can cause secondary indications like moving averages to consider data too deep into the past resulting in faulty output.
A:
e.g., Display current local time
import datetime
import glib
import logger
def get_local_time():
current_time = datetime.datetime.now().strftime("%H:%M")
logger.info("get_local_time(): %s",current_time)
return str(current_time)
def display_local_time():
logger.info("Current time is: %s", get_local_time())
return True
# call every minute
glib.timeout_add(60*1000, display_local_time)
A:
''' tracking number of times it prints'''
import threading
global timeInterval
count=0
def printit():
threading.Timer(timeInterval, printit).start()
print( "Hello, World!")
global count
count=count+1
print(count)
printit
if __name__ == "__main__":
timeInterval= int(input('Enter Time in Seconds:'))
printit()
A:
I think it depends what you want to do and your question didn't specify lots of details.
For me I want to do an expensive operation in one of my already multithreaded processes. So I have that leader process check the time and only her do the expensive op (checkpointing a deep learning model). To do this I increase the counter to make sure 5 then 10 then 15 seconds have passed to save every 5 seconds (or use modular arithmetic with math.floor):
def print_every_5_seconds_have_passed_exit_eventually():
"""
https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds
https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds
:return:
"""
opts = argparse.Namespace(start=time.time())
next_time_to_print = 0
while True:
current_time_passed = time.time() - opts.start
if current_time_passed >= next_time_to_print:
next_time_to_print += 5
print(f'worked and {current_time_passed=}')
print(f'{current_time_passed % 5=}')
print(f'{math.floor(current_time_passed % 5) == 0}')
starting __main__ at __init__
worked and current_time_passed=0.0001709461212158203
current_time_passed % 5=0.0001709461212158203
True
worked and current_time_passed=5.0
current_time_passed % 5=0.0
True
worked and current_time_passed=10.0
current_time_passed % 5=0.0
True
worked and current_time_passed=15.0
current_time_passed % 5=0.0
True
To me the check of the if statement is what I need. Having threads, schedulers in my already complicated multiprocessing multi-gpu code is not a complexity I want to add if I can avoid it and it seems I can. Checking the worker id is easy to make sure only 1 process is doing this.
Note I used the True print statements to really make sure the modular arithemtic trick worked since checking for exact time is obviously not going to work! But to my pleasant surprised the floor did the trick.
A:
interval-timer can do that to high precision (i.e. < 1 ms) as it's synchronized to the system clock. It won't drift over time and isn't affected by the length of the code execution time (provided that's less than the interval period of course).
A simple, blocking example:
from interval_timer import IntervalTimer
for interval in IntervalTimer(60):
# Execute code here
...
You could easily make it non-blocking by running it in a thread:
from threading import Thread
from interval_timer import IntervalTimer
def periodic():
for interval in IntervalTimer(60):
# Execute code here
...
thread = Thread(target=periodic)
thread.start()
|
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 cron implemented in Python, the solution appears to effectively just sleep() for x seconds. I don't need such advanced functionality so perhaps something like this would work
while True:
# Code executed here
time.sleep(60)
Are there any foreseeable problems with this code?
|
[
"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.enter(60, 1, do_something, (s,))\ns.run()\n\nIf you're already using an event loop library like asyncio, trio, tkinter, PyQt5, gobject, kivy, and many others - just schedule the task using your existing event loop library's methods, instead.\n",
"Lock your time loop to the system clock like this:\nimport time\nstarttime = time.time()\nwhile True:\n print(\"tick\")\n time.sleep(60.0 - ((time.time() - starttime) % 60.0))\n\n",
"If you want a non-blocking way to execute your function periodically, instead of a blocking infinite loop I'd use a threaded timer. This way your code can keep running and perform other tasks and still have your function called every n seconds. I use this technique a lot for printing progress info on long, CPU/Disk/Network intensive tasks.\nHere's the code I've posted in a similar question, with start() and stop() control:\nfrom threading import Timer\n\nclass RepeatedTimer(object):\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self._timer = Timer(self.interval, self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\nUsage:\nfrom time import sleep\n\ndef hello(name):\n print \"Hello %s!\" % name\n\nprint \"starting...\"\nrt = RepeatedTimer(1, hello, \"World\") # it auto-starts, no need of rt.start()\ntry:\n sleep(5) # your long-running job goes here...\nfinally:\n rt.stop() # better in a try/finally block to make sure the program ends!\n\nFeatures:\n\nStandard library only, no external dependencies\nstart() and stop() are safe to call multiple times even if the timer has already started/stopped\nfunction to be called can have positional and named arguments\nYou can change interval anytime, it will be effective after next run. Same for args, kwargs and even function!\n\n",
"You might want to consider Twisted which is a Python networking library that implements the Reactor Pattern.\nfrom twisted.internet import task, reactor\n\ntimeout = 60.0 # Sixty seconds\n\ndef doWork():\n #do work here\n pass\n\nl = task.LoopingCall(doWork)\nl.start(timeout) # call every sixty seconds\n\nreactor.run()\n\nWhile \"while True: sleep(60)\" will probably work Twisted probably already implements many of the features that you will eventually need (daemonization, logging or exception handling as pointed out by bobince) and will probably be a more robust solution\n",
"Here's an update to the code from MestreLion that avoids drifiting over time. \nThe RepeatedTimer class here calls the given function every \"interval\" seconds as requested by the OP; the schedule doesn't depend on how long the function takes to execute. I like this solution since it doesn't have external library dependencies; this is just pure python.\nimport threading \nimport time\n\nclass RepeatedTimer(object):\n def __init__(self, interval, function, *args, **kwargs):\n self._timer = None\n self.interval = interval\n self.function = function\n self.args = args\n self.kwargs = kwargs\n self.is_running = False\n self.next_call = time.time()\n self.start()\n\n def _run(self):\n self.is_running = False\n self.start()\n self.function(*self.args, **self.kwargs)\n\n def start(self):\n if not self.is_running:\n self.next_call += self.interval\n self._timer = threading.Timer(self.next_call - time.time(), self._run)\n self._timer.start()\n self.is_running = True\n\n def stop(self):\n self._timer.cancel()\n self.is_running = False\n\nSample usage (copied from MestreLion's answer):\nfrom time import sleep\n\ndef hello(name):\n print \"Hello %s!\" % name\n\nprint \"starting...\"\nrt = RepeatedTimer(1, hello, \"World\") # it auto-starts, no need of rt.start()\ntry:\n sleep(5) # your long-running job goes here...\nfinally:\n rt.stop() # better in a try/finally block to make sure the program ends!\n\n",
"import time, traceback\n\ndef every(delay, task):\n next_time = time.time() + delay\n while True:\n time.sleep(max(0, next_time - time.time()))\n try:\n task()\n except Exception:\n traceback.print_exc()\n # in production code you might want to have this instead of course:\n # logger.exception(\"Problem while executing repetitive task.\")\n # skip tasks if we are behind schedule:\n next_time += (time.time() - next_time) // delay * delay + delay\n\ndef foo():\n print(\"foo\", time.time())\n\nevery(5, foo)\n\nIf you want to do this without blocking your remaining code, you can use this to let it run in its own thread:\nimport threading\nthreading.Thread(target=lambda: every(5, foo)).start()\n\nThis solution combines several features rarely found combined in the other solutions:\n\nException handling: As far as possible on this level, exceptions are handled properly, i. e. get logged for debugging purposes without aborting our program.\nNo chaining: The common chain-like implementation (for scheduling the next event) you find in many answers is brittle in the aspect that if anything goes wrong within the scheduling mechanism (threading.Timer or whatever), this will terminate the chain. No further executions will happen then, even if the reason of the problem is already fixed. A simple loop and waiting with a simple sleep() is much more robust in comparison.\nNo drift: My solution keeps an exact track of the times it is supposed to run at. There is no drift depending on the execution time (as in many other solutions).\nSkipping: My solution will skip tasks if one execution took too much time (e. g. do X every five seconds, but X took 6 seconds). This is the standard cron behavior (and for a good reason). Many other solutions then simply execute the task several times in a row without any delay. For most cases (e. g. cleanup tasks) this is not wished. If it is wished, simply use next_time += delay instead.\n\n",
"The easier way I believe to be:\nimport time\n\ndef executeSomething():\n #code here\n time.sleep(60)\n\nwhile True:\n executeSomething()\n\nThis way your code is executed, then it waits 60 seconds then it executes again, waits, execute, etc...\nNo need to complicate things :D\n",
"I ended up using the schedule module. The API is nice.\nimport schedule\nimport time\n\ndef job():\n print(\"I'm working...\")\n\nschedule.every(10).minutes.do(job)\nschedule.every().hour.do(job)\nschedule.every().day.at(\"10:30\").do(job)\nschedule.every(5).to(10).minutes.do(job)\nschedule.every().monday.do(job)\nschedule.every().wednesday.at(\"13:15\").do(job)\nschedule.every().minute.at(\":17\").do(job)\n\nwhile True:\n schedule.run_pending()\n time.sleep(1)\n\n",
"Alternative flexibility solution is Apscheduler.\npip install apscheduler\n\nfrom apscheduler.schedulers.background import BlockingScheduler\ndef print_t():\n pass\n\nsched = BlockingScheduler()\nsched.add_job(print_t, 'interval', seconds =60) #will do the print_t work for every 60 seconds\n\nsched.start()\n\nAlso, apscheduler provides so many schedulers as follow.\n\nBlockingScheduler: use when the scheduler is the only thing running in your process\n\nBackgroundScheduler: use when you’re not using any of the frameworks below, and want the scheduler to run in the background inside your application\n\nAsyncIOScheduler: use if your application uses the asyncio module\n\nGeventScheduler: use if your application uses gevent\n\nTornadoScheduler: use if you’re building a Tornado application\n\nTwistedScheduler: use if you’re building a Twisted application\n\nQtScheduler: use if you’re building a Qt application\n\n\n",
"I faced a similar problem some time back. May be http://cronus.readthedocs.org might help?\nFor v0.2, the following snippet works\nimport cronus.beat as beat\n\nbeat.set_rate(2) # 2 Hz\nwhile beat.true():\n # do some time consuming work here\n beat.sleep() # total loop duration would be 0.5 sec\n\n",
"The main difference between that and cron is that an exception will kill the daemon for good. You might want to wrap with an exception catcher and logger.\n",
"If drift is not a concern\nimport threading, time\n\ndef print_every_n_seconds(n=2):\n while True:\n print(time.ctime())\n time.sleep(n)\n \nthread = threading.Thread(target=print_every_n_seconds, daemon=True)\nthread.start()\n\n\nWhich asynchronously outputs.\n#Tue Oct 16 17:29:40 2018\n#Tue Oct 16 17:29:42 2018\n#Tue Oct 16 17:29:44 2018\n\nIf the task being run takes appreciable amount of time, then the interval becomes 2 seconds + task time, so if you need precise scheduling then this is not for you.\nNote the daemon=True flag means this thread won't block the app from shutting down. For example, had issue where pytest would hang indefinitely after running tests waiting for this thead to cease.\n",
"Simply use\nimport time\n\nwhile True:\n print(\"this will run after every 30 sec\")\n #Your code here\n time.sleep(30)\n\n",
"One possible answer:\nimport time\nt=time.time()\n\nwhile True:\n if time.time()-t>10:\n #run your task here\n t=time.time()\n\n",
"I use Tkinter after() method, which doesn't \"steal the game\" (like the sched module that was presented earlier), i.e. it allows other things to run in parallel:\nimport Tkinter\n\ndef do_something1():\n global n1\n n1 += 1\n if n1 == 6: # (Optional condition)\n print \"* do_something1() is done *\"; return\n # Do your stuff here\n # ...\n print \"do_something1() \"+str(n1)\n tk.after(1000, do_something1)\n\ndef do_something2(): \n global n2\n n2 += 1\n if n2 == 6: # (Optional condition)\n print \"* do_something2() is done *\"; return\n # Do your stuff here\n # ...\n print \"do_something2() \"+str(n2)\n tk.after(500, do_something2)\n\ntk = Tkinter.Tk(); \nn1 = 0; n2 = 0\ndo_something1()\ndo_something2()\ntk.mainloop()\n\ndo_something1() and do_something2() can run in parallel and in whatever interval speed. Here, the 2nd one will be executed twice as fast.Note also that I have used a simple counter as a condition to terminate either function. You can use whatever other contition you like or none if you what a function to run until the program terminates (e.g. a clock). \n",
"Here's an adapted version to the code from MestreLion.\nIn addition to the original function, this code:\n1) add first_interval used to fire the timer at a specific time(caller need to calculate the first_interval and pass in)\n2) solve a race-condition in original code. In the original code, if control thread failed to cancel the running timer(\"Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.\" quoted from https://docs.python.org/2/library/threading.html), the timer will run endlessly.\nclass RepeatedTimer(object):\ndef __init__(self, first_interval, interval, func, *args, **kwargs):\n self.timer = None\n self.first_interval = first_interval\n self.interval = interval\n self.func = func\n self.args = args\n self.kwargs = kwargs\n self.running = False\n self.is_started = False\n\ndef first_start(self):\n try:\n # no race-condition here because only control thread will call this method\n # if already started will not start again\n if not self.is_started:\n self.is_started = True\n self.timer = Timer(self.first_interval, self.run)\n self.running = True\n self.timer.start()\n except Exception as e:\n log_print(syslog.LOG_ERR, \"timer first_start failed %s %s\"%(e.message, traceback.format_exc()))\n raise\n\ndef run(self):\n # if not stopped start again\n if self.running:\n self.timer = Timer(self.interval, self.run)\n self.timer.start()\n self.func(*self.args, **self.kwargs)\n\ndef stop(self):\n # cancel current timer in case failed it's still OK\n # if already stopped doesn't matter to stop again\n if self.timer:\n self.timer.cancel()\n self.running = False\n\n",
"Here is another solution without using any extra libaries.\ndef delay_until(condition_fn, interval_in_sec, timeout_in_sec):\n \"\"\"Delay using a boolean callable function.\n\n `condition_fn` is invoked every `interval_in_sec` until `timeout_in_sec`.\n It can break early if condition is met.\n\n Args:\n condition_fn - a callable boolean function\n interval_in_sec - wait time between calling `condition_fn`\n timeout_in_sec - maximum time to run\n\n Returns: None\n \"\"\"\n start = last_call = time.time()\n while time.time() - start < timeout_in_sec:\n if (time.time() - last_call) > interval_in_sec:\n if condition_fn() is True:\n break\n last_call = time.time()\n\n",
"I use this to cause 60 events per hour with most events occurring at the same number of seconds after the whole minute:\nimport math\nimport time\nimport random\n\nTICK = 60 # one minute tick size\nTICK_TIMING = 59 # execute on 59th second of the tick\nTICK_MINIMUM = 30 # minimum catch up tick size when lagging\n\ndef set_timing():\n\n now = time.time()\n elapsed = now - info['begin']\n minutes = math.floor(elapsed/TICK)\n tick_elapsed = now - info['completion_time']\n if (info['tick']+1) > minutes:\n wait = max(0,(TICK_TIMING-(time.time() % TICK)))\n print ('standard wait: %.2f' % wait)\n time.sleep(wait)\n elif tick_elapsed < TICK_MINIMUM:\n wait = TICK_MINIMUM-tick_elapsed\n print ('minimum wait: %.2f' % wait)\n time.sleep(wait)\n else:\n print ('skip set_timing(); no wait')\n drift = ((time.time() - info['begin']) - info['tick']*TICK -\n TICK_TIMING + info['begin']%TICK)\n print ('drift: %.6f' % drift)\n\ninfo['tick'] = 0\ninfo['begin'] = time.time()\ninfo['completion_time'] = info['begin'] - TICK\n\nwhile 1:\n\n set_timing()\n\n print('hello world')\n\n #random real world event\n time.sleep(random.random()*TICK_MINIMUM)\n\n info['tick'] += 1\n info['completion_time'] = time.time()\n\nDepending upon actual conditions you might get ticks of length:\n60,60,62,58,60,60,120,30,30,60,60,60,60,60...etc.\n\nbut at the end of 60 minutes you'll have 60 ticks; and most of them will occur at the correct offset to the minute you prefer.\nOn my system I get typical drift of < 1/20th of a second until need for correction arises.\nThe advantage of this method is resolution of clock drift; which can cause issues if you're doing things like appending one item per tick and you expect 60 items appended per hour. Failure to account for drift can cause secondary indications like moving averages to consider data too deep into the past resulting in faulty output. \n",
"e.g., Display current local time\nimport datetime\nimport glib\nimport logger\n\ndef get_local_time():\n current_time = datetime.datetime.now().strftime(\"%H:%M\")\n logger.info(\"get_local_time(): %s\",current_time)\n return str(current_time)\n\ndef display_local_time():\n logger.info(\"Current time is: %s\", get_local_time())\n return True\n\n# call every minute\nglib.timeout_add(60*1000, display_local_time)\n\n",
" ''' tracking number of times it prints'''\nimport threading\n\nglobal timeInterval\ncount=0\ndef printit():\n threading.Timer(timeInterval, printit).start()\n print( \"Hello, World!\")\n global count\n count=count+1\n print(count)\nprintit\n\nif __name__ == \"__main__\":\n timeInterval= int(input('Enter Time in Seconds:'))\n printit()\n\n",
"I think it depends what you want to do and your question didn't specify lots of details.\nFor me I want to do an expensive operation in one of my already multithreaded processes. So I have that leader process check the time and only her do the expensive op (checkpointing a deep learning model). To do this I increase the counter to make sure 5 then 10 then 15 seconds have passed to save every 5 seconds (or use modular arithmetic with math.floor):\ndef print_every_5_seconds_have_passed_exit_eventually():\n \"\"\"\n https://stackoverflow.com/questions/3393612/run-certain-code-every-n-seconds\n https://stackoverflow.com/questions/474528/what-is-the-best-way-to-repeatedly-execute-a-function-every-x-seconds\n :return:\n \"\"\"\n opts = argparse.Namespace(start=time.time())\n next_time_to_print = 0\n while True:\n current_time_passed = time.time() - opts.start\n if current_time_passed >= next_time_to_print:\n next_time_to_print += 5\n print(f'worked and {current_time_passed=}')\n print(f'{current_time_passed % 5=}')\n print(f'{math.floor(current_time_passed % 5) == 0}')\n\nstarting __main__ at __init__\nworked and current_time_passed=0.0001709461212158203\ncurrent_time_passed % 5=0.0001709461212158203\nTrue\nworked and current_time_passed=5.0\ncurrent_time_passed % 5=0.0\nTrue\nworked and current_time_passed=10.0\ncurrent_time_passed % 5=0.0\nTrue\nworked and current_time_passed=15.0\ncurrent_time_passed % 5=0.0\nTrue\n\nTo me the check of the if statement is what I need. Having threads, schedulers in my already complicated multiprocessing multi-gpu code is not a complexity I want to add if I can avoid it and it seems I can. Checking the worker id is easy to make sure only 1 process is doing this.\nNote I used the True print statements to really make sure the modular arithemtic trick worked since checking for exact time is obviously not going to work! But to my pleasant surprised the floor did the trick.\n",
"interval-timer can do that to high precision (i.e. < 1 ms) as it's synchronized to the system clock. It won't drift over time and isn't affected by the length of the code execution time (provided that's less than the interval period of course).\nA simple, blocking example:\nfrom interval_timer import IntervalTimer\n\nfor interval in IntervalTimer(60):\n # Execute code here\n ...\n\nYou could easily make it non-blocking by running it in a thread:\nfrom threading import Thread\nfrom interval_timer import IntervalTimer\n\ndef periodic():\n for interval in IntervalTimer(60):\n # Execute code here\n ...\n\nthread = Thread(target=periodic)\nthread.start()\n\n"
] |
[
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 modifying the window flags:
With not window flags, the window is both re-sizable and movable. But no custom buttons.
Using self.setWindowFlags(QtCore.Qt.FramelessWindowHint), the window has no borders, but cant move or resize the window
Using self.setWindowFlags(QtCore.Qt.CustomizeWindowHint), the window is resizable but cannot move and also cant get rid of the white part at the top of the window.
Any help appreciated. You can find the project on GitHub here.
Thanks..
This is my python code:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, uic
import sys
import os
import markdown2 # https://github.com/trentm/python-markdown2
from PyQt5.QtCore import QRect
from PyQt5.QtGui import QFont
simpleUiForm = uic.loadUiType("Simple.ui")[0]
class SimpleWindow(QtWidgets.QMainWindow, simpleUiForm):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.markdown = markdown2.Markdown()
self.css = open(os.path.join("css", "default.css")).read()
self.editNote.setPlainText("")
#self.noteView = QtWebEngineWidgets.QWebEngineView(self)
self.installEventFilter(self)
self.displayNote.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.WindowActivate:
print("widget window has gained focus")
self.editNote.show()
self.displayNote.hide()
elif event.type() == QtCore.QEvent.WindowDeactivate:
print("widget window has lost focus")
note = self.editNote.toPlainText()
htmlNote = self.getStyledPage(note)
# print(note)
self.editNote.hide()
self.displayNote.show()
# print(htmlNote)
self.displayNote.setHtml(htmlNote)
elif event.type() == QtCore.QEvent.FocusIn:
print("widget has gained keyboard focus")
elif event.type() == QtCore.QEvent.FocusOut:
print("widget has lost keyboard focus")
return False
The UI file is created in the following hierarchy
A:
Here are the steps you just gotta follow:
Have your MainWindow, be it a QMainWindow, or QWidget, or whatever [widget] you want to inherit.
Set its flag, self.setWindowFlags(Qt.FramelessWindowHint)
Implement your own moving around.
Implement your own buttons (close, max, min)
Implement your own resize.
Here is a small example with move around, and buttons implemented. You should still have to implement the resize using the same logic.
import sys
from PyQt5.QtCore import QPoint
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWidgets import QHBoxLayout
from PyQt5.QtWidgets import QLabel
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtWidgets import QVBoxLayout
from PyQt5.QtWidgets import QWidget
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.layout = QVBoxLayout()
self.layout.addWidget(MyBar(self))
self.setLayout(self.layout)
self.layout.setContentsMargins(0,0,0,0)
self.layout.addStretch(-1)
self.setMinimumSize(800,400)
self.setWindowFlags(Qt.FramelessWindowHint)
self.pressing = False
class MyBar(QWidget):
def __init__(self, parent):
super(MyBar, self).__init__()
self.parent = parent
print(self.parent.width())
self.layout = QHBoxLayout()
self.layout.setContentsMargins(0,0,0,0)
self.title = QLabel("My Own Bar")
btn_size = 35
self.btn_close = QPushButton("x")
self.btn_close.clicked.connect(self.btn_close_clicked)
self.btn_close.setFixedSize(btn_size,btn_size)
self.btn_close.setStyleSheet("background-color: red;")
self.btn_min = QPushButton("-")
self.btn_min.clicked.connect(self.btn_min_clicked)
self.btn_min.setFixedSize(btn_size, btn_size)
self.btn_min.setStyleSheet("background-color: gray;")
self.btn_max = QPushButton("+")
self.btn_max.clicked.connect(self.btn_max_clicked)
self.btn_max.setFixedSize(btn_size, btn_size)
self.btn_max.setStyleSheet("background-color: gray;")
self.title.setFixedHeight(35)
self.title.setAlignment(Qt.AlignCenter)
self.layout.addWidget(self.title)
self.layout.addWidget(self.btn_min)
self.layout.addWidget(self.btn_max)
self.layout.addWidget(self.btn_close)
self.title.setStyleSheet("""
background-color: black;
color: white;
""")
self.setLayout(self.layout)
self.start = QPoint(0, 0)
self.pressing = False
def resizeEvent(self, QResizeEvent):
super(MyBar, self).resizeEvent(QResizeEvent)
self.title.setFixedWidth(self.parent.width())
def mousePressEvent(self, event):
self.start = self.mapToGlobal(event.pos())
self.pressing = True
def mouseMoveEvent(self, event):
if self.pressing:
self.end = self.mapToGlobal(event.pos())
self.movement = self.end-self.start
self.parent.setGeometry(self.mapToGlobal(self.movement).x(),
self.mapToGlobal(self.movement).y(),
self.parent.width(),
self.parent.height())
self.start = self.end
def mouseReleaseEvent(self, QMouseEvent):
self.pressing = False
def btn_close_clicked(self):
self.parent.close()
def btn_max_clicked(self):
self.parent.showMaximized()
def btn_min_clicked(self):
self.parent.showMinimized()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
sys.exit(app.exec_())
Here are some tips:
Option 1:
Have a QGridLayout with widget in each corner and side(e.g. left, top-left, menubar, top-right, right, bottom-right, bottom and bottom left)
With the approach (1) you would know when you are clicking in each border, you just got to define each one size and add each one on their place.
When you click on each one treat them in their respective ways, for example, if you click in the left one and drag to the left, you gotta resize it larger and at the same time move it to the left so it will appear to be stopped at the right place and grow width.
Apply this reasoning to each edge, each one behaving in the way it has to.
Option 2:
Instead of having a QGridLayout you can detect in which place you are clicking by the click pos.
Verify if the x of the click is smaller than the x of the moving pos to know if it's moving left or right and where it's being clicked.
The calculation is made in the same way of the Option1
Option 3:
Probably there are other ways, but those are the ones I just thought of. For example using the CustomizeWindowHint you said you are able to resize, so you just would have to implement what I gave you as example. BEAUTIFUL!
Tips:
Be careful with the localPos(inside own widget), globalPos(related to your screen). For example: If you click in the very left of your left widget its 'x' will be zero, if you click in the very left of the middle(content)it will be also zero, although if you mapToGlobal you will having different values according to the pos of the screen.
Pay attention when resizing, or moving, when you have to add width or subtract, or just move, or both, I'd recommend you to draw on a paper and figure out how the logic of resizing works before implementing it out of blue.
GOOD LUCK :D
A:
While the accepted answer can be considered valid, it has some issues.
using setGeometry() is not appropriate (and the reason for using it was wrong) since it doesn't consider possible frame margins set by the style;
the position computation is unnecessarily complex;
resizing the title bar to the total width is wrong, since it doesn't consider the buttons and can also cause recursion problems in certain situations (like not setting the minimum size of the main window); also, if the title is too big, it makes impossible to resize the main window;
buttons should not accept focus;
setting a layout creates a restraint for the "main widget" or layout, so the title should not be added, but the contents margins of the widget should be used instead;
I revised the code to provide a better base for the main window, simplify the moving code, and add other features like the Qt windowTitle() property support, standard QStyle icons for buttons (instead of text), and proper maximize/normal button icons. Note that the title label is not added to the layout.
class MainWindow(QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)
self.titleBar = MyBar(self)
self.setContentsMargins(0, self.titleBar.height(), 0, 0)
self.resize(640, self.titleBar.height() + 480)
def changeEvent(self, event):
if event.type() == event.WindowStateChange:
self.titleBar.windowStateChanged(self.windowState())
def resizeEvent(self, event):
self.titleBar.resize(self.width(), self.titleBar.height())
class MyBar(QWidget):
clickPos = None
def __init__(self, parent):
super(MyBar, self).__init__(parent)
self.setAutoFillBackground(True)
self.setBackgroundRole(QPalette.Shadow)
# alternatively:
# palette = self.palette()
# palette.setColor(palette.Window, Qt.black)
# palette.setColor(palette.WindowText, Qt.white)
# self.setPalette(palette)
layout = QHBoxLayout(self)
layout.setContentsMargins(1, 1, 1, 1)
layout.addStretch()
self.title = QLabel("My Own Bar", self, alignment=Qt.AlignCenter)
# if setPalette() was used above, this is not required
self.title.setForegroundRole(QPalette.Light)
style = self.style()
ref_size = self.fontMetrics().height()
ref_size += style.pixelMetric(style.PM_ButtonMargin) * 2
self.setMaximumHeight(ref_size + 2)
btn_size = QSize(ref_size, ref_size)
for target in ('min', 'normal', 'max', 'close'):
btn = QToolButton(self, focusPolicy=Qt.NoFocus)
layout.addWidget(btn)
btn.setFixedSize(btn_size)
iconType = getattr(style,
'SP_TitleBar{}Button'.format(target.capitalize()))
btn.setIcon(style.standardIcon(iconType))
if target == 'close':
colorNormal = 'red'
colorHover = 'orangered'
else:
colorNormal = 'palette(mid)'
colorHover = 'palette(light)'
btn.setStyleSheet('''
QToolButton {{
background-color: {};
}}
QToolButton:hover {{
background-color: {}
}}
'''.format(colorNormal, colorHover))
signal = getattr(self, target + 'Clicked')
btn.clicked.connect(signal)
setattr(self, target + 'Button', btn)
self.normalButton.hide()
self.updateTitle(parent.windowTitle())
parent.windowTitleChanged.connect(self.updateTitle)
def updateTitle(self, title=None):
if title is None:
title = self.window().windowTitle()
width = self.title.width()
width -= self.style().pixelMetric(QStyle.PM_LayoutHorizontalSpacing) * 2
self.title.setText(self.fontMetrics().elidedText(
title, Qt.ElideRight, width))
def windowStateChanged(self, state):
self.normalButton.setVisible(state == Qt.WindowMaximized)
self.maxButton.setVisible(state != Qt.WindowMaximized)
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.clickPos = event.windowPos().toPoint()
def mouseMoveEvent(self, event):
if self.clickPos is not None:
self.window().move(event.globalPos() - self.clickPos)
def mouseReleaseEvent(self, QMouseEvent):
self.clickPos = None
def closeClicked(self):
self.window().close()
def maxClicked(self):
self.window().showMaximized()
def normalClicked(self):
self.window().showNormal()
def minClicked(self):
self.window().showMinimized()
def resizeEvent(self, event):
self.title.resize(self.minButton.x(), self.height())
self.updateTitle()
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
layout = QVBoxLayout(mw)
widget = QTextEdit()
layout.addWidget(widget)
mw.show()
mw.setWindowTitle('My custom window with a very, very long title')
sys.exit(app.exec_())
A:
This is for the people who are going to implement custom title bar in PyQt6 or PySide6
The below changes should be done in the answer given by @musicamante
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
# self.clickPos = event.windowPos().toPoint()
self.clickPos = event.scenePosition().toPoint()
def mouseMoveEvent(self, event):
if self.clickPos is not None:
# self.window().move(event.globalPos() - self.clickPos)
self.window().move(event.globalPosition().toPoint() - self.clickPos)
if __name__ == "__main__":
app = QApplication(sys.argv)
mw = MainWindow()
mw.show()
# sys.exit(app.exec_())
sys.exit(app.exec())
References:
QMouseEvent.globalPosition(),
QMouseEvent.scenePosition()
This method of moving Windows with Custom Widget doesn't work with WAYLAND. If anybody has a solution for that please post it here for future reference
A:
Working functions for WAYLAND and PyQT6/PySide6 :
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self._move()
return super().mousePressEvent(event)
def _move(self):
window = self.window().windowHandle()
window.startSystemMove()
Please check.
|
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 window flags, the window is both re-sizable and movable. But no custom buttons.
Using self.setWindowFlags(QtCore.Qt.FramelessWindowHint), the window has no borders, but cant move or resize the window
Using self.setWindowFlags(QtCore.Qt.CustomizeWindowHint), the window is resizable but cannot move and also cant get rid of the white part at the top of the window.
Any help appreciated. You can find the project on GitHub here.
Thanks..
This is my python code:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets, uic
import sys
import os
import markdown2 # https://github.com/trentm/python-markdown2
from PyQt5.QtCore import QRect
from PyQt5.QtGui import QFont
simpleUiForm = uic.loadUiType("Simple.ui")[0]
class SimpleWindow(QtWidgets.QMainWindow, simpleUiForm):
def __init__(self, parent=None):
QtWidgets.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.markdown = markdown2.Markdown()
self.css = open(os.path.join("css", "default.css")).read()
self.editNote.setPlainText("")
#self.noteView = QtWebEngineWidgets.QWebEngineView(self)
self.installEventFilter(self)
self.displayNote.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
#self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
def eventFilter(self, object, event):
if event.type() == QtCore.QEvent.WindowActivate:
print("widget window has gained focus")
self.editNote.show()
self.displayNote.hide()
elif event.type() == QtCore.QEvent.WindowDeactivate:
print("widget window has lost focus")
note = self.editNote.toPlainText()
htmlNote = self.getStyledPage(note)
# print(note)
self.editNote.hide()
self.displayNote.show()
# print(htmlNote)
self.displayNote.setHtml(htmlNote)
elif event.type() == QtCore.QEvent.FocusIn:
print("widget has gained keyboard focus")
elif event.type() == QtCore.QEvent.FocusOut:
print("widget has lost keyboard focus")
return False
The UI file is created in the following hierarchy
|
[
"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\nHere is a small example with move around, and buttons implemented. You should still have to implement the resize using the same logic.\nimport sys\n\nfrom PyQt5.QtCore import QPoint\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtWidgets import QApplication\nfrom PyQt5.QtWidgets import QHBoxLayout\nfrom PyQt5.QtWidgets import QLabel\nfrom PyQt5.QtWidgets import QPushButton\nfrom PyQt5.QtWidgets import QVBoxLayout\nfrom PyQt5.QtWidgets import QWidget\n\n\n\nclass MainWindow(QWidget):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n self.layout = QVBoxLayout()\n self.layout.addWidget(MyBar(self))\n self.setLayout(self.layout)\n self.layout.setContentsMargins(0,0,0,0)\n self.layout.addStretch(-1)\n self.setMinimumSize(800,400)\n self.setWindowFlags(Qt.FramelessWindowHint)\n self.pressing = False\n\n\nclass MyBar(QWidget):\n\n def __init__(self, parent):\n super(MyBar, self).__init__()\n self.parent = parent\n print(self.parent.width())\n self.layout = QHBoxLayout()\n self.layout.setContentsMargins(0,0,0,0)\n self.title = QLabel(\"My Own Bar\")\n\n btn_size = 35\n\n self.btn_close = QPushButton(\"x\")\n self.btn_close.clicked.connect(self.btn_close_clicked)\n self.btn_close.setFixedSize(btn_size,btn_size)\n self.btn_close.setStyleSheet(\"background-color: red;\")\n\n self.btn_min = QPushButton(\"-\")\n self.btn_min.clicked.connect(self.btn_min_clicked)\n self.btn_min.setFixedSize(btn_size, btn_size)\n self.btn_min.setStyleSheet(\"background-color: gray;\")\n\n self.btn_max = QPushButton(\"+\")\n self.btn_max.clicked.connect(self.btn_max_clicked)\n self.btn_max.setFixedSize(btn_size, btn_size)\n self.btn_max.setStyleSheet(\"background-color: gray;\")\n\n self.title.setFixedHeight(35)\n self.title.setAlignment(Qt.AlignCenter)\n self.layout.addWidget(self.title)\n self.layout.addWidget(self.btn_min)\n self.layout.addWidget(self.btn_max)\n self.layout.addWidget(self.btn_close)\n\n self.title.setStyleSheet(\"\"\"\n background-color: black;\n color: white;\n \"\"\")\n self.setLayout(self.layout)\n\n self.start = QPoint(0, 0)\n self.pressing = False\n\n def resizeEvent(self, QResizeEvent):\n super(MyBar, self).resizeEvent(QResizeEvent)\n self.title.setFixedWidth(self.parent.width())\n\n def mousePressEvent(self, event):\n self.start = self.mapToGlobal(event.pos())\n self.pressing = True\n\n def mouseMoveEvent(self, event):\n if self.pressing:\n self.end = self.mapToGlobal(event.pos())\n self.movement = self.end-self.start\n self.parent.setGeometry(self.mapToGlobal(self.movement).x(),\n self.mapToGlobal(self.movement).y(),\n self.parent.width(),\n self.parent.height())\n self.start = self.end\n\n def mouseReleaseEvent(self, QMouseEvent):\n self.pressing = False\n\n\n def btn_close_clicked(self):\n self.parent.close()\n\n def btn_max_clicked(self):\n self.parent.showMaximized()\n\n def btn_min_clicked(self):\n self.parent.showMinimized()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n mw = MainWindow()\n mw.show()\n sys.exit(app.exec_())\n\nHere are some tips:\nOption 1:\n\nHave a QGridLayout with widget in each corner and side(e.g. left, top-left, menubar, top-right, right, bottom-right, bottom and bottom left)\nWith the approach (1) you would know when you are clicking in each border, you just got to define each one size and add each one on their place.\nWhen you click on each one treat them in their respective ways, for example, if you click in the left one and drag to the left, you gotta resize it larger and at the same time move it to the left so it will appear to be stopped at the right place and grow width.\nApply this reasoning to each edge, each one behaving in the way it has to.\n\nOption 2:\n\nInstead of having a QGridLayout you can detect in which place you are clicking by the click pos.\nVerify if the x of the click is smaller than the x of the moving pos to know if it's moving left or right and where it's being clicked.\nThe calculation is made in the same way of the Option1\n\nOption 3:\n\nProbably there are other ways, but those are the ones I just thought of. For example using the CustomizeWindowHint you said you are able to resize, so you just would have to implement what I gave you as example. BEAUTIFUL!\n\nTips:\n\nBe careful with the localPos(inside own widget), globalPos(related to your screen). For example: If you click in the very left of your left widget its 'x' will be zero, if you click in the very left of the middle(content)it will be also zero, although if you mapToGlobal you will having different values according to the pos of the screen.\nPay attention when resizing, or moving, when you have to add width or subtract, or just move, or both, I'd recommend you to draw on a paper and figure out how the logic of resizing works before implementing it out of blue. \n\nGOOD LUCK :D\n",
"While the accepted answer can be considered valid, it has some issues.\n\nusing setGeometry() is not appropriate (and the reason for using it was wrong) since it doesn't consider possible frame margins set by the style;\nthe position computation is unnecessarily complex;\nresizing the title bar to the total width is wrong, since it doesn't consider the buttons and can also cause recursion problems in certain situations (like not setting the minimum size of the main window); also, if the title is too big, it makes impossible to resize the main window;\nbuttons should not accept focus;\nsetting a layout creates a restraint for the \"main widget\" or layout, so the title should not be added, but the contents margins of the widget should be used instead;\n\nI revised the code to provide a better base for the main window, simplify the moving code, and add other features like the Qt windowTitle() property support, standard QStyle icons for buttons (instead of text), and proper maximize/normal button icons. Note that the title label is not added to the layout.\nclass MainWindow(QWidget):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.setWindowFlags(self.windowFlags() | Qt.FramelessWindowHint)\n\n self.titleBar = MyBar(self)\n self.setContentsMargins(0, self.titleBar.height(), 0, 0)\n\n self.resize(640, self.titleBar.height() + 480)\n\n def changeEvent(self, event):\n if event.type() == event.WindowStateChange:\n self.titleBar.windowStateChanged(self.windowState())\n\n def resizeEvent(self, event):\n self.titleBar.resize(self.width(), self.titleBar.height())\n\n\nclass MyBar(QWidget):\n clickPos = None\n def __init__(self, parent):\n super(MyBar, self).__init__(parent)\n self.setAutoFillBackground(True)\n \n self.setBackgroundRole(QPalette.Shadow)\n # alternatively:\n # palette = self.palette()\n # palette.setColor(palette.Window, Qt.black)\n # palette.setColor(palette.WindowText, Qt.white)\n # self.setPalette(palette)\n\n layout = QHBoxLayout(self)\n layout.setContentsMargins(1, 1, 1, 1)\n layout.addStretch()\n\n self.title = QLabel(\"My Own Bar\", self, alignment=Qt.AlignCenter)\n # if setPalette() was used above, this is not required\n self.title.setForegroundRole(QPalette.Light)\n\n style = self.style()\n ref_size = self.fontMetrics().height()\n ref_size += style.pixelMetric(style.PM_ButtonMargin) * 2\n self.setMaximumHeight(ref_size + 2)\n\n btn_size = QSize(ref_size, ref_size)\n for target in ('min', 'normal', 'max', 'close'):\n btn = QToolButton(self, focusPolicy=Qt.NoFocus)\n layout.addWidget(btn)\n btn.setFixedSize(btn_size)\n\n iconType = getattr(style, \n 'SP_TitleBar{}Button'.format(target.capitalize()))\n btn.setIcon(style.standardIcon(iconType))\n\n if target == 'close':\n colorNormal = 'red'\n colorHover = 'orangered'\n else:\n colorNormal = 'palette(mid)'\n colorHover = 'palette(light)'\n btn.setStyleSheet('''\n QToolButton {{\n background-color: {};\n }}\n QToolButton:hover {{\n background-color: {}\n }}\n '''.format(colorNormal, colorHover))\n\n signal = getattr(self, target + 'Clicked')\n btn.clicked.connect(signal)\n\n setattr(self, target + 'Button', btn)\n\n self.normalButton.hide()\n\n self.updateTitle(parent.windowTitle())\n parent.windowTitleChanged.connect(self.updateTitle)\n\n def updateTitle(self, title=None):\n if title is None:\n title = self.window().windowTitle()\n width = self.title.width()\n width -= self.style().pixelMetric(QStyle.PM_LayoutHorizontalSpacing) * 2\n self.title.setText(self.fontMetrics().elidedText(\n title, Qt.ElideRight, width))\n\n def windowStateChanged(self, state):\n self.normalButton.setVisible(state == Qt.WindowMaximized)\n self.maxButton.setVisible(state != Qt.WindowMaximized)\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.clickPos = event.windowPos().toPoint()\n\n def mouseMoveEvent(self, event):\n if self.clickPos is not None:\n self.window().move(event.globalPos() - self.clickPos)\n\n def mouseReleaseEvent(self, QMouseEvent):\n self.clickPos = None\n\n def closeClicked(self):\n self.window().close()\n\n def maxClicked(self):\n self.window().showMaximized()\n\n def normalClicked(self):\n self.window().showNormal()\n\n def minClicked(self):\n self.window().showMinimized()\n\n def resizeEvent(self, event):\n self.title.resize(self.minButton.x(), self.height())\n self.updateTitle()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n mw = MainWindow()\n layout = QVBoxLayout(mw)\n widget = QTextEdit()\n layout.addWidget(widget)\n mw.show()\n mw.setWindowTitle('My custom window with a very, very long title')\n sys.exit(app.exec_())\n\n",
"This is for the people who are going to implement custom title bar in PyQt6 or PySide6\nThe below changes should be done in the answer given by @musicamante\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n # self.clickPos = event.windowPos().toPoint()\n self.clickPos = event.scenePosition().toPoint()\n\n def mouseMoveEvent(self, event):\n if self.clickPos is not None:\n # self.window().move(event.globalPos() - self.clickPos)\n self.window().move(event.globalPosition().toPoint() - self.clickPos)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n mw = MainWindow()\n mw.show()\n # sys.exit(app.exec_())\n sys.exit(app.exec())\n\nReferences:\nQMouseEvent.globalPosition(),\nQMouseEvent.scenePosition()\nThis method of moving Windows with Custom Widget doesn't work with WAYLAND. If anybody has a solution for that please post it here for future reference\n",
"Working functions for WAYLAND and PyQT6/PySide6 :\ndef mousePressEvent(self, event):\n if event.button() == Qt.MouseButton.LeftButton:\n self._move()\n return super().mousePressEvent(event)\n\ndef _move(self):\n window = self.window().windowHandle()\n window.startSystemMove()\n\nPlease check.\n"
] |
[
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 works perfectly but once the time is over the websites remain locked. I would be really thankful if anyone can let me know what could be the reason that the websites remain locked. I am really not into filelock module so there could be something that I might have done wrong.
Also after I locked the text files, all the text disappeared, is that normal and what would that be for?
`
from datetime import datetime
from filelock import FileLock
date = str(datetime.date(datetime.now()))
year = int(date[:4])
month = int(date[5:7])
day = int(date[8:])
hour = int(input("When do you want to end this trial : "))
minute = input("What minute do you want to end this trial : ")
if minute in 'Qq':
end_time = datetime(year, month, day, hour)
else:
end_time = datetime(year, month, day, hour, int(minute))
lock = FileLock('./blocked_sites.txt.lock')
with lock:
with open('./blocked_sites.txt', mode='r+') as sites:
sites_to_block = sites.readlines()
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = '127.0.0.1'
def block_websites():
if datetime.now() < end_time:
print("Block sites")
with open(hosts_path, 'r+') as hostfile:
hosts_content = hostfile.read()
lock.acquire()
for site in sites_to_block:
if site not in hosts_content:
hostfile.write(redirect + ' ' + site + '\n')
else:
print('Unblock sites')
with open(hosts_path, 'r+') as hostfile:
lines = hostfile.readlines()
hostfile.seek(0)
for line in lines:
if not any(site in line for site in sites_to_block):
hostfile.write(line)
hostfile.truncate()
if __name__ == '__main__':
block_websites()
`
A:
It is a bit difficult ro reproduce. You probably need a main loop.
Something to reexecute your code or wait for the second part of your code which is easier for your code structure.
try:
import time
def block_websites():
if datetime.now() < end_time:
print("Block sites")
with open(hosts_path, 'r+') as hostfile:
hosts_content = hostfile.read()
lock.acquire()
for site in sites_to_block:
if site not in hosts_content:
hostfile.write(redirect + ' ' + site + '\n')
# add this code snipped
else:
return
while datetime.now() < end_time:
time.sleep(1.0)
print('Unblock sites')
with open(hosts_path, 'r+') as hostfile:
lines = hostfile.readlines()
hostfile.seek(0)
for line in lines:
if not any(site in line for site in sites_to_block):
hostfile.write(line)
hostfile.truncate()
I would recomend using the datetime and date attributes instead of string manipulation.
from datetime import datetime
date = datetime.now().date()
year = date.year
month = date.month
day = date.day
hour = input("At what hour do you want to end this trial : ")
minute = input("What minute do you want to end this trial : ")
if minute in 'Qq':
end_time = datetime(year, month, day, 0, 0)
else:
end_time = datetime(year, month, day, int(hour), int(minute))
|
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 over the websites remain locked. I would be really thankful if anyone can let me know what could be the reason that the websites remain locked. I am really not into filelock module so there could be something that I might have done wrong.
Also after I locked the text files, all the text disappeared, is that normal and what would that be for?
`
from datetime import datetime
from filelock import FileLock
date = str(datetime.date(datetime.now()))
year = int(date[:4])
month = int(date[5:7])
day = int(date[8:])
hour = int(input("When do you want to end this trial : "))
minute = input("What minute do you want to end this trial : ")
if minute in 'Qq':
end_time = datetime(year, month, day, hour)
else:
end_time = datetime(year, month, day, hour, int(minute))
lock = FileLock('./blocked_sites.txt.lock')
with lock:
with open('./blocked_sites.txt', mode='r+') as sites:
sites_to_block = sites.readlines()
hosts_path = r"C:\Windows\System32\drivers\etc\hosts"
redirect = '127.0.0.1'
def block_websites():
if datetime.now() < end_time:
print("Block sites")
with open(hosts_path, 'r+') as hostfile:
hosts_content = hostfile.read()
lock.acquire()
for site in sites_to_block:
if site not in hosts_content:
hostfile.write(redirect + ' ' + site + '\n')
else:
print('Unblock sites')
with open(hosts_path, 'r+') as hostfile:
lines = hostfile.readlines()
hostfile.seek(0)
for line in lines:
if not any(site in line for site in sites_to_block):
hostfile.write(line)
hostfile.truncate()
if __name__ == '__main__':
block_websites()
`
|
[
"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(hosts_path, 'r+') as hostfile:\n hosts_content = hostfile.read()\n\n lock.acquire()\n for site in sites_to_block:\n if site not in hosts_content:\n hostfile.write(redirect + ' ' + site + '\\n')\n # add this code snipped\n else:\n return\n while datetime.now() < end_time:\n time.sleep(1.0)\n\n print('Unblock sites')\n with open(hosts_path, 'r+') as hostfile:\n lines = hostfile.readlines()\n hostfile.seek(0)\n for line in lines:\n if not any(site in line for site in sites_to_block):\n hostfile.write(line)\n hostfile.truncate()\n\nI would recomend using the datetime and date attributes instead of string manipulation.\nfrom datetime import datetime\ndate = datetime.now().date()\nyear = date.year\nmonth = date.month\nday = date.day\n\nhour = input(\"At what hour do you want to end this trial : \")\nminute = input(\"What minute do you want to end this trial : \")\n\nif minute in 'Qq':\n end_time = datetime(year, month, day, 0, 0)\nelse:\n end_time = datetime(year, month, day, int(hour), int(minute))\n\n"
] |
[
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", "Team8"]})
ratings = pd.DataFrame({'team': ["Team1", "Team2", "Team3", "Team4", "Team5",
"Team6", "Team7", "Team8", "Team9", "Team10", "Team11", "Team12"], "rating": ["1,5", "0,2", "0,5", "2", "3", "4,8", "0,9", "-0,4", "-0,6", "1,5", "0,2", "0,5"]})
ratings = ratings[(ratings.team != fixtures.HomeTeam) &
(ratings.team != fixtures.AwayTeam)]
but I get the error message:
ValueError: Can only compare identically-labeled Series objects
what can i do to stop the error from occurring?
A:
Because both dataframes are not of equal size. You can use isin() instead.
ratings = ratings[~ratings.team.isin(fixtures.stack())]
#output
'''
team rating
6 Team7 0,9
8 Team9 -0,6
9 Team10 1,5
10 Team11 0,2
11 Team12 0,5
'''
Details:
print(fixtures.stack())
'''
0 HomeTeam Team1
AwayTeam Team2
1 HomeTeam Team3
AwayTeam Team4
2 HomeTeam Team5
AwayTeam Team6
3 HomeTeam Team6
AwayTeam Team8
dtype: object
'''
As you can see this returns all values in fixtures. Using the ~ operator in the isin function, we filter out those that do not contain these values.
|
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", "Team2", "Team3", "Team4", "Team5",
"Team6", "Team7", "Team8", "Team9", "Team10", "Team11", "Team12"], "rating": ["1,5", "0,2", "0,5", "2", "3", "4,8", "0,9", "-0,4", "-0,6", "1,5", "0,2", "0,5"]})
ratings = ratings[(ratings.team != fixtures.HomeTeam) &
(ratings.team != fixtures.AwayTeam)]
but I get the error message:
ValueError: Can only compare identically-labeled Series objects
what can i do to stop the error from occurring?
|
[
"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 Team1\n AwayTeam Team2\n1 HomeTeam Team3\n AwayTeam Team4\n2 HomeTeam Team5\n AwayTeam Team6\n3 HomeTeam Team6\n AwayTeam Team8\ndtype: object\n'''\n\nAs you can see this returns all values in fixtures. Using the ~ operator in the isin function, we filter out those that do not contain these values.\n"
] |
[
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 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 names, ive got the code so that it saves the players name and score along with some text but have absolutely no idea on how to read the whole text file and and pick out lines that have the 5 largest integers and print them
`
name = str(input("Player 1 name"))
name2 = str(input("Player 2 name"))
score = str(input("Player 1 score"))
score2 = str(input("Player 2 score"))
text_file = open("CH30.txt", "r+")
if score > score2:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write(name)
text_file.write (" wins with ")
text_file.write (score)
text_file.write (" points")
else:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write (name2)
text_file.write (" wins with ")
text_file.write (score2)
text_file.write (" points")
`
the full game is not attached as I'm at my dads house currently and forgot to bring my usb stick
any help on how to do this would be much appreciated :)
A:
If your data in file has this format:
Player1 wins with 30 points
Player2 wins with 40 points
Player3 wins with 85 points
Player5 wins with 45 points
Player7 wins with 10 points
Player6 wins with 80 points
Player4 wins with 20 points
Player9 wins with 90 points
Player8 wins with 70 points
Player11 wins with 120 points
Player10 wins with 15 points
and there is no space in the first line of the file, because you have text_file.write("\n") written in the first line. Please add it at the end of the line, i.e the last file write.
For example:
text_file.write(name)
text_file.write (" wins with ")
text_file.write (score)
text_file.write (" points")
text_file.write("\n")
Here is how to get the 5 highest scores of the file:
text_file = open('CH30.txt.', 'r')
Lines = text_file.readlines()
PlayersScores = []
# read each line get the player name and points
for line in Lines:
# split the line into list of strings
line = line.split(" ")
# removing \n from last element
line[-1] = line[-1].replace("\n", "")
print(line)
# find player name position
playerName = line.index("wins") - 1
# find points position
points = line.index("points") - 1
# add the tuple (playerName, points) in a list
PlayersScores.append((line[playerName], line[points]))
# descending order sort by player score
PlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)
# get the first 5 players
print("Highest Scores:\n")
for i in range(5):
print(str(i+1) + ". " + PlayersScores[i][0] + " " + PlayersScores[i][1] + " points")
Output example:
Highest Scores:
1. Player11 120 points
2. Player9 90 points
3. Player3 85 points
4. Player6 80 points
5. Player8 70 points
A:
First of all, you should read the file to a list of lines. If you don`t know how to do this, check:
How to read a file line-by-line into a list?
Next, you have to sort the lines. We can use lambda to achieve it. Assuming, that the single line looks like this:
"Rick wins with 98 points"
Sorting function would look like this:
scores.sort(key= lambda x : int(x.split(" ")[3]))
Then, you just need to slice the last five elements.
Please note, this solution is prone to many errors, as you use the file in human-readable format. What's easily readable for us, is often hard to read by computer (and vice versa). So, if you don't want to use the file as a bedtime reading, consider using some formats, that are easier to parse - i.e. CSV
|
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 names, ive got the code so that it saves the players name and score along with some text but have absolutely no idea on how to read the whole text file and and pick out lines that have the 5 largest integers and print them
`
name = str(input("Player 1 name"))
name2 = str(input("Player 2 name"))
score = str(input("Player 1 score"))
score2 = str(input("Player 2 score"))
text_file = open("CH30.txt", "r+")
if score > score2:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write(name)
text_file.write (" wins with ")
text_file.write (score)
text_file.write (" points")
else:
content = text_file.readlines(30)
if len(content) > 0 :
text_file.write("\n")
text_file.write (name2)
text_file.write (" wins with ")
text_file.write (score2)
text_file.write (" points")
`
the full game is not attached as I'm at my dads house currently and forgot to bring my usb stick
any help on how to do this would be much appreciated :)
|
[
"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 with 120 points\nPlayer10 wins with 15 points\n\nand there is no space in the first line of the file, because you have text_file.write(\"\\n\") written in the first line. Please add it at the end of the line, i.e the last file write.\nFor example:\ntext_file.write(name)\ntext_file.write (\" wins with \")\ntext_file.write (score)\ntext_file.write (\" points\")\ntext_file.write(\"\\n\")\n\nHere is how to get the 5 highest scores of the file:\ntext_file = open('CH30.txt.', 'r')\nLines = text_file.readlines()\nPlayersScores = []\n\n# read each line get the player name and points \nfor line in Lines:\n # split the line into list of strings\n line = line.split(\" \")\n # removing \\n from last element\n line[-1] = line[-1].replace(\"\\n\", \"\")\n print(line)\n # find player name position\n playerName = line.index(\"wins\") - 1\n # find points position\n points = line.index(\"points\") - 1\n # add the tuple (playerName, points) in a list\n PlayersScores.append((line[playerName], line[points]))\n# descending order sort by player score\nPlayersScores = sorted(PlayersScores, key=lambda t: t[1], reverse=True)\n\n# get the first 5 players\nprint(\"Highest Scores:\\n\")\nfor i in range(5):\n print(str(i+1) + \". \" + PlayersScores[i][0] + \" \" + PlayersScores[i][1] + \" points\")\n\nOutput example:\nHighest Scores:\n\n1. Player11 120 points\n2. Player9 90 points\n3. Player3 85 points\n4. Player6 80 points\n5. Player8 70 points\n\n",
"First of all, you should read the file to a list of lines. If you don`t know how to do this, check:\nHow to read a file line-by-line into a list?\nNext, you have to sort the lines. We can use lambda to achieve it. Assuming, that the single line looks like this:\n\"Rick wins with 98 points\"\nSorting function would look like this:\nscores.sort(key= lambda x : int(x.split(\" \")[3]))\nThen, you just need to slice the last five elements.\nPlease note, this solution is prone to many errors, as you use the file in human-readable format. What's easily readable for us, is often hard to read by computer (and vice versa). So, if you don't want to use the file as a bedtime reading, consider using some formats, that are easier to parse - i.e. CSV\n"
] |
[
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 Iyengar
A:
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, too.
Minimal example
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import LinearAxis, Range1d
output_notebook()
data_x = [1,2,3,4,5]
data_y = [1,2,3,4,5]
color = ['red', 'green', 'magenta', 'black']
p = figure(plot_width=500, plot_height=300)
p.line(data_x, data_y, color='blue')
for i, c in enumerate(color, start=1):
name = f'extra_range_{i}'
lable = f'extra range {i}'
p.extra_y_ranges[name] = Range1d(start=0, end=10*i)
p.add_layout(LinearAxis(axis_label=lable, y_range_name=name), 'left')
p.line(data_x, data_y, color=c, y_range_name=name)
show(p)
Output
Official example
See also the twin axis example (axis) on the official webpage. This example uses the same syntax with only two axis. Another example is the twin axis example for models.
|
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, too.\nMinimal example\nfrom bokeh.plotting import figure, show, output_notebook\nfrom bokeh.models import LinearAxis, Range1d\noutput_notebook()\n\ndata_x = [1,2,3,4,5]\ndata_y = [1,2,3,4,5]\ncolor = ['red', 'green', 'magenta', 'black']\np = figure(plot_width=500, plot_height=300)\np.line(data_x, data_y, color='blue')\n\nfor i, c in enumerate(color, start=1):\n name = f'extra_range_{i}'\n lable = f'extra range {i}'\n p.extra_y_ranges[name] = Range1d(start=0, end=10*i)\n\n p.add_layout(LinearAxis(axis_label=lable, y_range_name=name), 'left')\n p.line(data_x, data_y, color=c, y_range_name=name)\nshow(p)\n\nOutput\n\nOfficial example\nSee also the twin axis example (axis) on the official webpage. This example uses the same syntax with only two axis. Another example is the twin axis example for models.\n"
] |
[
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 makes sense since the memory complexity is N^2.
Is there an efficient way to do this with memory complexity of N (i.e. avoiding initializing the vandermonde matrix), without using any loops?
Any help will be appreciated!
A:
Based on the documentation of the vandermonde matrix you can construct it in the following way:
np.vander(B, increasing=True) == np.column_stack([B**(i) for i in range(len(B))])
So your optimization would be to do dot product in-place:
np.column_stack([np.dot(A, B**(i)) for i in range(len(B))])
|
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 with memory complexity of N (i.e. avoiding initializing the vandermonde matrix), without using any loops?
Any help will be appreciated!
|
[
"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 something in the function.
name: "Check Renamed files"
"on":
pull_request:
branches:
- main
jobs:
prose:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.8
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Check renamed files
run: |
INPUT_STORE=$(python3 test.py)
echo $INPUT_STORE
Also, tried this for multi-line output:
MY_STRING="{$(python test.py }})} EOF"
echo "MY_STRING<<EOF" >> $GITHUB_ENV
echo "$MY_STRING" >> $GITHUB_ENV
But nothing worked
A:
You could set it has a environment variable.
def example():
return "a"
if __name__ == "__main__":
print(example())
and then run:
python3 test.py
will print to your console:
"a"
In your Gitlab Actions, I would expect something like:
name: GitHub Actions Demo
run-name: ${{ github.actor }} is testing out GitHub Actions
on: [push]
jobs:
Explore-GitHub-Actions:
runs-on: ubuntu-latest
steps:
- name: Check out repository code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.8
- name: Print from test.py
run: |
export INPUT_STORE=$(python test.py)
echo "Access direct: "
echo $INPUT_STORE
And the result:
|
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":
pull_request:
branches:
- main
jobs:
prose:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: 3.8
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Check renamed files
run: |
INPUT_STORE=$(python3 test.py)
echo $INPUT_STORE
Also, tried this for multi-line output:
MY_STRING="{$(python test.py }})} EOF"
echo "MY_STRING<<EOF" >> $GITHUB_ENV
echo "$MY_STRING" >> $GITHUB_ENV
But nothing worked
|
[
"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.actor }} is testing out GitHub Actions \non: [push]\njobs:\n Explore-GitHub-Actions:\n runs-on: ubuntu-latest\n steps:\n - name: Check out repository code\n uses: actions/checkout@v3\n - name: Set up Python\n uses: actions/setup-python@v4\n with:\n python-version: 3.8\n - name: Print from test.py\n run: |\n export INPUT_STORE=$(python test.py)\n echo \"Access direct: \"\n echo $INPUT_STORE\n\nAnd the result:\n\n"
] |
[
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-01
2035-04-01
Checkpoint
2025-12-25
NaT
Expected 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
2030-05-15
Logic:
'Checkpoint' end_date needs to either be the start_date for 'Phase 4' OR the start_date for 'Phase 5'.
If either of those aren't present, then the end_date for 'Checkpoint' will be 30 days after the start_date.
Thank you again!
I've tried various forms of df.loc. But I cannot get the logic to work.
d_end = df.loc[(df['evet_name']== "Phase 4") | (df['event_name']== "Phase 5"), ['event_name','start_date']]
d_end = pd.DataFrame(d_end)
print("Printing d_end test {}".format((d_end)))
A:
Since accessing the missing cells by index causes an exception, we had to add checks. Example with missing phase values 4 and 5.
dt.txt
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
Checkpoint 2025-12-25 NaT
import pandas as pd
df = pd.read_table('dt.txt')
# We collect data on the cells we need.
phase_4_start = df.loc[df['event_name'] == 'Phase 4', 'start_date']
phase_5_start = df.loc[df['event_name'] == 'Phase 5', 'start_date']
checkpoint_start = df.loc[df['event_name'] == 'Checkpoint', 'start_date']
# We add 30 days, first converting the string to a date, then back to a string.
checkpoint_end = (pd.to_datetime(checkpoint_start, format='%Y-%m-%d') + pd.Timedelta(days=30)).dt.strftime('%Y-%m-%d')
# We immediately determine the completion date in case there are no phases 4 and 5.
checkpoint_end_date = checkpoint_end.get(checkpoint_end.index[0])
# We change the end date depending on the availability of phases 4 and 5.
if not phase_5_start.empty:
checkpoint_end_date = phase_5_start.get(phase_5_start.index[0])
if not phase_4_start.empty:
checkpoint_end_date = phase_4_start.get(phase_4_start.index[0])
# Set the end date of the Checkpoint.
df['end_date'] = df['end_date'].mask(df['end_date'] == 'NaT', checkpoint_end_date)
print(df)
------------------------------------------
event_name start_date end_date
0 Start 2010-11-12 2015-01-05
1 Phase 1 2015-01-05 2015-03-16
2 Phase 2 2015-04-04 2018-03-11
3 Phase 3 2018-03-11 2030-05-15
4 Checkpoint 2025-12-25 2026-01-24
|
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
Expected 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
2030-05-15
Logic:
'Checkpoint' end_date needs to either be the start_date for 'Phase 4' OR the start_date for 'Phase 5'.
If either of those aren't present, then the end_date for 'Checkpoint' will be 30 days after the start_date.
Thank you again!
I've tried various forms of df.loc. But I cannot get the logic to work.
d_end = df.loc[(df['evet_name']== "Phase 4") | (df['event_name']== "Phase 5"), ['event_name','start_date']]
d_end = pd.DataFrame(d_end)
print("Printing d_end test {}".format((d_end)))
|
[
"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 2025-12-25 NaT\n\nimport pandas as pd\n\n\ndf = pd.read_table('dt.txt')\n\n# We collect data on the cells we need.\nphase_4_start = df.loc[df['event_name'] == 'Phase 4', 'start_date']\nphase_5_start = df.loc[df['event_name'] == 'Phase 5', 'start_date']\ncheckpoint_start = df.loc[df['event_name'] == 'Checkpoint', 'start_date']\n\n# We add 30 days, first converting the string to a date, then back to a string.\ncheckpoint_end = (pd.to_datetime(checkpoint_start, format='%Y-%m-%d') + pd.Timedelta(days=30)).dt.strftime('%Y-%m-%d')\n\n# We immediately determine the completion date in case there are no phases 4 and 5.\ncheckpoint_end_date = checkpoint_end.get(checkpoint_end.index[0])\n\n# We change the end date depending on the availability of phases 4 and 5.\nif not phase_5_start.empty:\n checkpoint_end_date = phase_5_start.get(phase_5_start.index[0])\nif not phase_4_start.empty:\n checkpoint_end_date = phase_4_start.get(phase_4_start.index[0])\n\n# Set the end date of the Checkpoint.\ndf['end_date'] = df['end_date'].mask(df['end_date'] == 'NaT', checkpoint_end_date)\nprint(df)\n\n------------------------------------------\n\n event_name start_date end_date\n0 Start 2010-11-12 2015-01-05\n1 Phase 1 2015-01-05 2015-03-16\n2 Phase 2 2015-04-04 2018-03-11\n3 Phase 3 2018-03-11 2030-05-15\n4 Checkpoint 2025-12-25 2026-01-24\n\n"
] |
[
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.pyx:
cimport bus.Bus as Bus
cdef class Cpu:
cdef Bus bus
cdef __cinit__(self, Bus bus):
self.bus = bus
setup.py:
from setuptools import setup, Extension
import sys
import numpy
USE_CYTHON = False
files = [
('src.bus', 'src/bus/bus'),
('src.cpu', 'src/cpu/cpu'),
]
if '--use-cython' in sys.argv:
USE_CYTHON = True
sys.argv.remove('--use-cython')
ext = '.pyx' if USE_CYTHON else '.c'
extensions = []
for package_path, file_path in files:
extensions.append(
Extension(package_path,[f"{file_path}{ext}"],
language='c',
include_dirs=['src/c/'])
)
if USE_CYTHON:
from Cython.Build import cythonize
extensions = cythonize(extensions)
setup(
ext_modules=extensions,
include_dirs=[numpy.get_include()]
)
However, when compiling this example the compiler raise error of 'Bus' is not a type identifier. Any suggestion?
A:
So, in cython we've to use pxd file for declaration in compile time.
Therefor, adding __init__.pxd have to bee added for compilation import.
In Addition, I've created cpu.pxd file which inside I've wrote from bus cimport Bus.
|
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 class Cpu:
cdef Bus bus
cdef __cinit__(self, Bus bus):
self.bus = bus
setup.py:
from setuptools import setup, Extension
import sys
import numpy
USE_CYTHON = False
files = [
('src.bus', 'src/bus/bus'),
('src.cpu', 'src/cpu/cpu'),
]
if '--use-cython' in sys.argv:
USE_CYTHON = True
sys.argv.remove('--use-cython')
ext = '.pyx' if USE_CYTHON else '.c'
extensions = []
for package_path, file_path in files:
extensions.append(
Extension(package_path,[f"{file_path}{ext}"],
language='c',
include_dirs=['src/c/'])
)
if USE_CYTHON:
from Cython.Build import cythonize
extensions = cythonize(extensions)
setup(
ext_modules=extensions,
include_dirs=[numpy.get_include()]
)
However, when compiling this example the compiler raise error of 'Bus' is not a type identifier. Any suggestion?
|
[
"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 arrived in my notebook for the past few days.you can see in this link exactly what happening in this link
how can I get rid of it? please help me out. The error lines are in green color whereas normal program looks like thisSee this line in grey color is suggested by notebook
I am just confused. I don't know how it started. I didn't get any solution on it anywhere
A:
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?
|
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 what happening in this link
how can I get rid of it? please help me out. The error lines are in green color whereas normal program looks like thisSee this line in grey color is suggested by notebook
I am just confused. I don't know how it started. I didn't get any solution on it anywhere
|
[
"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.