code
stringlengths
26
870k
docstring
stringlengths
1
65.6k
func_name
stringlengths
1
194
language
stringclasses
1 value
repo
stringlengths
8
68
path
stringlengths
5
194
url
stringlengths
46
254
license
stringclasses
4 values
async def on_friendship(self, friendship: Friendship) -> None: """when receive a new friendship application, or accept a new friendship Args: friendship (Friendship): contains the status and friendship info, eg: hello text, friend contact object """ MAX_ROOM_MEMBER_COUNT = 500 # 1. receive a new friendship from someone if friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE: hello_text: str = friendship.hello() # accept friendship when there is a keyword in hello text if 'wechaty' in hello_text.lower(): await friendship.accept() # 2. you have a new friend to your contact list elif friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM: # 2.1 invite the user to wechaty group # find the topic of room which contains Wechaty keyword wechaty_rooms: List[Room] = await self.Room.find_all('Wechaty') # 2.2 find the suitable room for wechaty_room in wechaty_rooms: members: List[Contact] = await wechaty_room.member_list() if len(members) < MAX_ROOM_MEMBER_COUNT: contact: Contact = friendship.contact() await wechaty_room.add(contact) break
when receive a new friendship application, or accept a new friendship Args: friendship (Friendship): contains the status and friendship info, eg: hello text, friend contact object
on_friendship
python
Python-World/python-mini-projects
projects/chatbot/bot.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/chatbot/bot.py
MIT
async def on_room_join(self, room: Room, invitees: List[Contact], inviter: Contact, date: datetime) -> None: """on_room_join when there are new contacts to the room Args: room (Room): the room instance invitees (List[Contact]): the new contacts to the room inviter (Contact): the inviter who share qrcode or manual invite someone date (datetime): the datetime to join the room """ # 1. say something to welcome the new arrivals names: List[str] = [] for invitee in invitees: await invitee.ready() names.append(invitee.name) await room.say(f'welcome {",".join(names)} to the wechaty group !')
on_room_join when there are new contacts to the room Args: room (Room): the room instance invitees (List[Contact]): the new contacts to the room inviter (Contact): the inviter who share qrcode or manual invite someone date (datetime): the datetime to join the room
on_room_join
python
Python-World/python-mini-projects
projects/chatbot/bot.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/chatbot/bot.py
MIT
async def main() -> None: """doc""" bot = MyBot() await bot.start()
doc
main
python
Python-World/python-mini-projects
projects/chatbot/bot.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/chatbot/bot.py
MIT
def display_hangman(tries): stages = [""" -------- | | | 0 | \\|/ | | | / \\ - """, """ -------- | | | 0 | \\|/ | | | / - """, """ -------- | | | 0 | \\|/ | | | - """, """ -------- | | | 0 | \\| | | | - """, """ -------- | | | 0 | | | | | - """, """ -------- | | | 0 | | | - """, """ -------- | | | | | | - """ ] return stages[tries]
,
display_hangman
python
Python-World/python-mini-projects
projects/Terminal_Based_Hangman_Game/hangman.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Terminal_Based_Hangman_Game/hangman.py
MIT
def print_out_ascii(array): """prints the coded image with symbols""" for row in array: for e in row: # select symbol based on the type of coding print(symbols_list[int(e) % len(symbols_list)], end="") print()
prints the coded image with symbols
print_out_ascii
python
Python-World/python-mini-projects
projects/Ascii_art/make_art.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Ascii_art/make_art.py
MIT
def img_to_ascii(image): """returns the numeric coded image""" # resizing parameters # adjust these parameters if the output doesn't fit to the screen height, width = image.shape new_width = int(width / 20) new_height = int(height / 40) # resize image to fit the printing screen resized_image = cv2.resize(image, (new_width, new_height),) thresh_image = np.zeros(resized_image.shape) for i, threshold in enumerate(threshold_list): # assign corresponding values according to the index of threshold applied thresh_image[resized_image > threshold] = i return thresh_image
returns the numeric coded image
img_to_ascii
python
Python-World/python-mini-projects
projects/Ascii_art/make_art.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Ascii_art/make_art.py
MIT
def get_load_time(url): """This function takes a user defined url as input and returns the time taken to load that url in seconds. Args: url (string): The user defined url. Returns: time_to_load (float): The time taken to load the website in seconds. """ if ("https" or "http") in url: # Checking for presence of protocols open_this_url = urlopen(url) # Open the url as entered by the user else: open_this_url = urlopen("https://" + url) # Adding https to the url start_time = time.time() # Time stamp before the reading of url starts open_this_url.read() # Reading the user defined url end_time = time.time() # Time stamp after the reading of the url open_this_url.close() # Closing the instance of the urlopen object time_to_load = end_time - start_time return time_to_load
This function takes a user defined url as input and returns the time taken to load that url in seconds. Args: url (string): The user defined url. Returns: time_to_load (float): The time taken to load the website in seconds.
get_load_time
python
Python-World/python-mini-projects
projects/Time_to_load_website/time_to_load_website.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Time_to_load_website/time_to_load_website.py
MIT
def getJPG(): '''Function to get image location and open it with pillow''' global im1 import_file_path = filedialog.askopenfilename() im1 = Image.open(import_file_path)
Function to get image location and open it with pillow
getJPG
python
Python-World/python-mini-projects
projects/Convert_JPEG_to_PNG/converter_GUI.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Convert_JPEG_to_PNG/converter_GUI.py
MIT
def convertToPNG(): '''Function to change file extenstion to png and save it to User's prefered location ''' global im1 if im1 is None: tk.messagebox.showerror("Error", "No File selected") else: export_file_path = filedialog.asksaveasfilename(defaultextension='.png') im1.save(export_file_path)
Function to change file extenstion to png and save it to User's prefered location
convertToPNG
python
Python-World/python-mini-projects
projects/Convert_JPEG_to_PNG/converter_GUI.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Convert_JPEG_to_PNG/converter_GUI.py
MIT
def Cal_IoU(GT_bbox, Pred_bbox): ''' Args: GT_bbox: the bounding box of the ground truth Pred_bbox: the bounding box of the predicted Returns: IoU: Intersection over Union ''' #1. Calculate the area of the intersecting area ixmin = max(GT_bbox[0], Pred_bbox[0]) iymin = max(GT_bbox[1], Pred_bbox[1]) ixmax = min(GT_bbox[2], Pred_bbox[2]) iymax = min(GT_bbox[3], Pred_bbox[3]) iw = np.maximum(ixmax - ixmin + 1., 0.) # the weight of the area ih = np.maximum(iymax - iymin + 1., 0.) # the height of the area area = iw * ih #2. Calculate the area of all area #S = S1 + S2 - area S1 = (Pred_bbox[2] - GT_bbox[0] + 1) * (Pred_bbox[3] - GT_bbox[1] + 1) S2 = (GT_bbox[2] - GT_bbox[0] + 1) * (GT_bbox[3] - GT_bbox[1] + 1) S = S1 + S2 - area #3. Calculate the IoU iou = area / S return iou
Args: GT_bbox: the bounding box of the ground truth Pred_bbox: the bounding box of the predicted Returns: IoU: Intersection over Union
Cal_IoU
python
Python-World/python-mini-projects
projects/Compute_IoU/Compute_IoU.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Compute_IoU/Compute_IoU.py
MIT
def download(url, file_name): ''' downloading the file and saving it ''' with open(file_name, "wb") as file: response = get(url) file.write(response.content)
downloading the file and saving it
download
python
Python-World/python-mini-projects
projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_windows.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_windows.py
MIT
def download(url, file_name): ''' downloading the file and saving it ''' with open(file_name, "wb") as file: response = get(url) file.write(response.content)
downloading the file and saving it
download
python
Python-World/python-mini-projects
projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_linux.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_linux.py
MIT
def setup(pathtofile): ''' setting the up file ''' system("nitrogen --set-auto {}".format(path.join(getcwd(), pathtofile)))
setting the up file
setup
python
Python-World/python-mini-projects
projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_linux.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_a_script_to_download_a_random_image_from_unsplash_and_set_it_as_wallpaper/background_linux.py
MIT
def __init__(self, file_path): ''' initializing directory where the captured frames will be stored. Also truncating the directory where captured frames are stored, if exists. ''' self.directory = "captured_frames" self.file_path = file_path if os.path.exists(self.directory): shutil.rmtree(self.directory) os.mkdir(self.directory)
initializing directory where the captured frames will be stored. Also truncating the directory where captured frames are stored, if exists.
__init__
python
Python-World/python-mini-projects
projects/Capture_Video_Frames/capture_video_frames.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Capture_Video_Frames/capture_video_frames.py
MIT
def capture_frames(self): ''' This method captures the frames from the video file provided. This program makes use of openCV library ''' cv2_object = cv2.VideoCapture(self.file_path) frame_number = 0 frame_found = 1 while frame_found: frame_found, image = cv2_object.read() capture = f'{self.directory}/frame{frame_number}.jpg' cv2.imwrite(capture, image) frame_number += 1
This method captures the frames from the video file provided. This program makes use of openCV library
capture_frames
python
Python-World/python-mini-projects
projects/Capture_Video_Frames/capture_video_frames.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Capture_Video_Frames/capture_video_frames.py
MIT
def add_proxies_to_file(csv_path: str, proxies: list): '''This function will add one or multiple proxies to the CSV file.''' if not csv_path.exists(): pr_file: pd.DataFrame = pd.DataFrame( columns=['proxy_type', 'proxy_address', 'proxy_status']) logging.info('New CSV file will be created') else: pr_file: pd.DataFrame = pd.read_csv(csv_path) logging.info('Existing CSV file has been loaded') for proxy in proxies: if len(pr_file) == 0: # First proxy in the file pr_file = pr_file.append(proxy, ignore_index=True) else: if len(pr_file.loc[(pr_file['proxy_type'] == proxy['proxy_type']) & (pr_file['proxy_address'] == proxy['proxy_address'])]) > 0: # Proxy is already in the file pr_file.loc[(pr_file['proxy_type'] == proxy['proxy_type']) & (pr_file['proxy_address'] == proxy['proxy_address']), ['proxy_status']] = proxy['proxy_status'] else: # Proxy is not yet in the file pr_file = pr_file.append(proxy, ignore_index=True) pr_file = pr_file.drop_duplicates() pr_file.to_csv(csv_path, index=False) logging.info('CSV file has been written')
This function will add one or multiple proxies to the CSV file.
add_proxies_to_file
python
Python-World/python-mini-projects
projects/cli_proxy_tester/proxytest.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/proxytest.py
MIT
def test_proxy(proxy_type: str, proxy_address: str, iptest: str): '''This function takes a proxy (type, address) and tests it against a given iptest adress.''' logging.info(f'Testing proxy: {proxy_address}') try: proxies = {proxy_type: proxy_address} proxy_status: str = '' if proxy_type == 'https': r = requests.get(f'https://{iptest}', proxies=proxies) else: r = requests.get(f'http://{iptest}', proxies=proxies) try: json_response: dict = r.json() if json_response["ip"] in proxy_address: proxy_status = 'Proxy functional' else: logging.warning(f'Proxy "{proxy_address}"' f'returned {json_response}') proxy_status = 'Proxy not functional' except JSONDecodeError: proxy_status = 'Invalid response' except ProxyError: proxy_status = 'Proxy error' logging.info(f'Proxy {proxy_address}: {proxy_status}') return {'proxy_type': proxy_type, 'proxy_address': proxy_address, 'proxy_status': proxy_status}
This function takes a proxy (type, address) and tests it against a given iptest adress.
test_proxy
python
Python-World/python-mini-projects
projects/cli_proxy_tester/proxytest.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/proxytest.py
MIT
def test_single_proxy(proxy: str, iptest: str, csv_path: str): '''This function tests an individual proxy and adds it to the CSV file.''' proxy_type, proxy_address = proxy.split('://') result: dict = test_proxy(proxy_type, proxy_address, iptest) add_proxies_to_file(Path(csv_path), [result])
This function tests an individual proxy and adds it to the CSV file.
test_single_proxy
python
Python-World/python-mini-projects
projects/cli_proxy_tester/proxytest.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/proxytest.py
MIT
def test_csv_file(iptest: str, csv_path: str): '''This function (re)tests every proxy in a given CSV file.''' csv_path: Path = Path(csv_path) if csv_path.exists(): pr_file: pd.DataFrame = pd.read_csv(csv_path) else: raise FileNotFoundError proxies: list = [] for index, proxy in pr_file.iterrows(): proxies.append(test_proxy(proxy['proxy_type'], proxy['proxy_address'], iptest)) add_proxies_to_file(csv_path, proxies)
This function (re)tests every proxy in a given CSV file.
test_csv_file
python
Python-World/python-mini-projects
projects/cli_proxy_tester/proxytest.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/proxytest.py
MIT
def add_from_text_file(iptest: str, text_path: str, csv_path: str): ''' This function adds a list of proxies from a text file (line by line).''' text_path: Path = Path(text_path) if text_path.exists(): proxies: list = text_path.read_text().splitlines() for proxy in proxies: '''We will treat each proxy as a single proxy and leverage the existing function''' test_single_proxy(proxy, iptest, csv_path) else: raise FileNotFoundError
This function adds a list of proxies from a text file (line by line).
add_from_text_file
python
Python-World/python-mini-projects
projects/cli_proxy_tester/proxytest.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/proxytest.py
MIT
def validate_proxy(ctx, param, value): '''Validate proxy input. The RegEx crudely matches both IPv4 and URLs.''' validator = re.compile(r'(https|http|socks4|socks5):\/\/' r'((?:[0-9]{1,3}\.){3}[0-9]{1,3}(:[0-9]{2,5})?' r'|([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?)') if not validator.match(value): raise click.BadParameter('Please provide a proxy in the format' 'type://address (e.g., https://42.42.42.42)') else: return value
Validate proxy input. The RegEx crudely matches both IPv4 and URLs.
validate_proxy
python
Python-World/python-mini-projects
projects/cli_proxy_tester/cli.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/cli_proxy_tester/cli.py
MIT
def getfoldername(filename): ''' 'Test.txt' --> 't' '010.txt' --> 'misc' 'zebra.txt' --> 'z' 'Alpha@@.txt' --> 'a' '!@#.txt' --> 'misc' ''' if filename[0].isalpha(): return filename[0].lower() else: return 'misc'
'Test.txt' --> 't' '010.txt' --> 'misc' 'zebra.txt' --> 'z' 'Alpha@@.txt' --> 'a' '!@#.txt' --> 'misc'
getfoldername
python
Python-World/python-mini-projects
projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
MIT
def readdirectory(): ''' read the filename in the current directory and append them to a list ''' global filenames for files in os.listdir(os.getcwd()): if os.path.isfile(os.path.join(os.getcwd(), files)): filenames.append(files) filenames.remove('main.py') # removing script from the file list
read the filename in the current directory and append them to a list
readdirectory
python
Python-World/python-mini-projects
projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
MIT
def createfolder(): ''' creating a folders ''' global filenames for f in filenames: if os.path.isdir(getfoldername(f)): print("folder already created") else: os.mkdir(getfoldername(f)) print('creating folder...')
creating a folders
createfolder
python
Python-World/python-mini-projects
projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
MIT
def movetofolder(): ''' movetofolder('zebra.py','z') 'zebra.py'(moved to) 'z' ''' global filenames for i in filenames: filename = i file = getfoldername(i) source = os.path.join(os.getcwd(), filename) destination = os.path.join(os.getcwd(), file) print(f"moving {source} to {destination}") shutil.move(source, destination)
movetofolder('zebra.py','z') 'zebra.py'(moved to) 'z'
movetofolder
python
Python-World/python-mini-projects
projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Write_script_to_move_files_into_alphabetically_ordered_folder/main.py
MIT
def get_baidu_poi(roi_key, city_str, baidu_ak, output): """ inputs: roi_key: poi name city_str: city name baidu_ak: baidu web API AK output: file save path """ now_time = time.strftime("%Y-%m-%d") page_num = 0 logfile = open(output + "/" + now_time + ".log", "a+", encoding="utf-8") file = open(output + "/" + now_time + ".txt", "a+", encoding="utf-8") while True: try: URL = "http://api.map.baidu.com/place/v2/search?query=" + roi_key + \ "&region=" + city_str + \ "&output=json" + \ "&ak=" + baidu_ak + \ "&scope=2" + \ "&page_size=20" + \ "&page_num=" + str(page_num) resp = requests.get(URL) res = json.loads(resp.text) if len(res["results"]) == 0: logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n") break else: for r in res["results"]: j_name = r["name"] j_lat = r["location"]["lat"] j_lon = r["location"]["lng"] j_area = r["area"] j_add = r["address"] j_str = str(j_name) + "," + str(j_lon) + "," + str(j_lat) + "," + str(j_area) + "," + str(j_add) + "\n" file.writelines(j_str) page_num += 1 time.sleep(1) except: print("except") logfile.writelines(time.strftime("%Y-%m-%d-%H-%M-%S") + " " + city_str + " " + str(page_num) + "\n") break
inputs: roi_key: poi name city_str: city name baidu_ak: baidu web API AK output: file save path
get_baidu_poi
python
Python-World/python-mini-projects
projects/Baidu_POI_crawl/util.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Baidu_POI_crawl/util.py
MIT
def get_files(path): ''' return a list of files avialable in given folder ''' files = glob.glob(f'{path}/*') return files
return a list of files avialable in given folder
get_files
python
Python-World/python-mini-projects
projects/Split_folder_into_subfolders/split_and_copy.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Split_folder_into_subfolders/split_and_copy.py
MIT
def getfullpath(path): ''' Return absolute path of given file ''' return os.path.abspath(path)
Return absolute path of given file
getfullpath
python
Python-World/python-mini-projects
projects/Split_folder_into_subfolders/split_and_copy.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Split_folder_into_subfolders/split_and_copy.py
MIT
def copyfiles(src, dst): ''' This function copy file from src to dst if dst dir is not there it will create new ''' if not os.path.isdir(dst): os.makedirs(dst) copy2(src, dst)
This function copy file from src to dst if dst dir is not there it will create new
copyfiles
python
Python-World/python-mini-projects
projects/Split_folder_into_subfolders/split_and_copy.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Split_folder_into_subfolders/split_and_copy.py
MIT
def split(data, count): ''' Split Given list of files and return generator ''' for i in range(1, len(data), count): if i + count-1 > len(data): start, end = (i-1, len(data)) else: start, end = (i-1, i+count-1) yield data[start:end]
Split Given list of files and return generator
split
python
Python-World/python-mini-projects
projects/Split_folder_into_subfolders/split_and_copy.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Split_folder_into_subfolders/split_and_copy.py
MIT
def todo(ctx): '''Simple CLI Todo App''' ctx.ensure_object(dict) #Open todo.txt – first line contains latest ID, rest contain tasks and IDs with open('./todo.txt') as f: content = f.readlines() #Transfer data from todo.txt to the context ctx.obj['LATEST'] = int(content[:1][0]) ctx.obj['TASKS'] = {en.split('```')[0]:en.split('```')[1][:-1] for en in content[1:]}
Simple CLI Todo App
todo
python
Python-World/python-mini-projects
projects/Cli_todo/todo.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Cli_todo/todo.py
MIT
def tasks(ctx): '''Display tasks''' if ctx.obj['TASKS']: click.echo('YOUR TASKS\n**********') #Iterate through all the tasks stored in the context for i, task in ctx.obj['TASKS'].items(): click.echo('• ' + task + ' (ID: ' + i + ')') click.echo('') else: click.echo('No tasks yet! Use ADD to add one.\n')
Display tasks
tasks
python
Python-World/python-mini-projects
projects/Cli_todo/todo.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Cli_todo/todo.py
MIT
def add(ctx, add_task): '''Add a task''' if add_task: #Add task to list in context ctx.obj['TASKS'][ctx.obj['LATEST']] = add_task click.echo('Added task "' + add_task + '" with ID ' + str(ctx.obj['LATEST'])) #Open todo.txt and write current index and tasks with IDs (separated by " ``` ") curr_ind = [str(ctx.obj['LATEST'] + 1)] tasks = [str(i) + '```' + t for (i, t) in ctx.obj['TASKS'].items()] with open('./todo.txt', 'w') as f: f.writelines(['%s\n' % en for en in curr_ind + tasks])
Add a task
add
python
Python-World/python-mini-projects
projects/Cli_todo/todo.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Cli_todo/todo.py
MIT
def done(ctx, fin_taskid): '''Delete a task by ID''' #Find task with associated ID if str(fin_taskid) in ctx.obj['TASKS'].keys(): task = ctx.obj['TASKS'][str(fin_taskid)] #Delete task from task list in context del ctx.obj['TASKS'][str(fin_taskid)] click.echo('Finished and removed task "' + task + '" with id ' + str(fin_taskid)) #Open todo.txt and write current index and tasks with IDs (separated by " ``` ") if ctx.obj['TASKS']: curr_ind = [str(ctx.obj['LATEST'] + 1)] tasks = [str(i) + '```' + t for (i, t) in ctx.obj['TASKS'].items()] with open('./todo.txt', 'w') as f: f.writelines(['%s\n' % en for en in curr_ind + tasks]) else: #Resets ID tracker to 0 if list is empty with open('./todo.txt', 'w') as f: f.writelines([str(0) + '\n']) else: click.echo('Error: no task with id ' + str(fin_taskid))
Delete a task by ID
done
python
Python-World/python-mini-projects
projects/Cli_todo/todo.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Cli_todo/todo.py
MIT
def __init__(self, file, word_list, threads) -> None: """Initialized function for ZipBruter""" self.file = file self.word_list = word_list self.threads = threads # Create FIFO queue self.queue = Queue()
Initialized function for ZipBruter
__init__
python
Python-World/python-mini-projects
projects/Zip_Bruter/zipbruter.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Zip_Bruter/zipbruter.py
MIT
def worker(self) -> None: """ Basically it listen queue and gets target password from FIFO queue and checks if zip passwd is true """ while True: # gets target passwd passwd = self.queue.get() self.queue.task_done() if passwd is None: break try: with ZipFile(self.file) as zipfile: zipfile.extractall(pwd=passwd.encode()) print('Found passwd: %s' % passwd) except (RuntimeError, BadZipfile): pass
Basically it listen queue and gets target password from FIFO queue and checks if zip passwd is true
worker
python
Python-World/python-mini-projects
projects/Zip_Bruter/zipbruter.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Zip_Bruter/zipbruter.py
MIT
def start_workers(self) -> None: """Start threads""" for _ in range(self.threads): start_new_thread(self.worker, ())
Start threads
start_workers
python
Python-World/python-mini-projects
projects/Zip_Bruter/zipbruter.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Zip_Bruter/zipbruter.py
MIT
def main(self) -> None: """Main entrypoint for program""" self.start_workers() for target_passwd in self.read_wordlist(): self.queue.put(target_passwd) for _ in range(self.threads): self.queue.put(None) self.queue.join()
Main entrypoint for program
main
python
Python-World/python-mini-projects
projects/Zip_Bruter/zipbruter.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Zip_Bruter/zipbruter.py
MIT
def read_wordlist(self) -> str: """Read given wordlist file and yield target passwds""" with open(self.word_list, 'r') as file: for line in file.readlines(): yield line.strip()
Read given wordlist file and yield target passwds
read_wordlist
python
Python-World/python-mini-projects
projects/Zip_Bruter/zipbruter.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Zip_Bruter/zipbruter.py
MIT
def main(username): banner() '''main function accept instagram username return an dictionary object containging profile deatils ''' url = "https://www.instagram.com/{}/?hl=en".format(username) page = requests.get(url) tree = html.fromstring(page.content) data = tree.xpath('//meta[starts-with(@name,"description")]/@content') if data: data = tree.xpath('//meta[starts-with(@name,"description")]/@content') data = data[0].split(', ') followers = data[0][:-9].strip() following = data[1][:-9].strip() posts = re.findall(r'\d+[,]*', data[2])[0] name = re.findall(r'name":"([^"]+)"', page.text)[0] aboutinfo = re.findall(r'"description":"([^"]+)"', page.text)[0] instagram_profile = { 'success': True, 'profile': { 'name': name, 'profileurl': url, 'username': username, 'followers': followers, 'following': following, 'posts': posts, 'aboutinfo': aboutinfo } } else: instagram_profile = { 'success': False, 'profile': {} } return instagram_profile
main function accept instagram username return an dictionary object containging profile deatils
main
python
Python-World/python-mini-projects
projects/Instagram_profile/main.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Instagram_profile/main.py
MIT
def main(username): '''main function accept instagram username return an dictionary object containging profile deatils ''' url = "https://www.instagram.com/{}/?hl=en".format(username) page = requests.get(url) tree = html.fromstring(page.content) data = tree.xpath('//meta[starts-with(@name,"description")]/@content') if data: data = tree.xpath('//meta[starts-with(@name,"description")]/@content') data = data[0].split(', ') followers = data[0][:-9].strip() following = data[1][:-9].strip() posts = re.findall(r'\d+[,]*', data[2])[0] name = re.findall(r'name":"\w*[\s]+\w*"', page.text)[-1][7:-1] aboutinfo = re.findall(r'"description":"([^"]+)"', page.text)[0] instagram_profile = { 'success': True, 'profile': { 'name': name, 'profileurl': url, 'username': username, 'followers': followers, 'following': following, 'posts': posts, 'aboutinfo': aboutinfo } } else: instagram_profile = { 'success': False, 'profile': {} } return instagram_profile
main function accept instagram username return an dictionary object containging profile deatils
main
python
Python-World/python-mini-projects
projects/Instagram_profile/InstgramProfile.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/Instagram_profile/InstgramProfile.py
MIT
def getPNG(): '''Function to get png image location and open it with pillow''' global img import_file_path = tk.filedialog.askopenfilename(filetypes=[("PNG File",'.png')]) img = Image.open(import_file_path)
Function to get png image location and open it with pillow
getPNG
python
Python-World/python-mini-projects
projects/convert_png_images_to_ico_format/convertUI.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/convert_png_images_to_ico_format/convertUI.py
MIT
def convertToICO(): global img '''Function to convert image from png to ico format with pillow and save to user specified location''' if img is None: tk.messagebox.showerror("Error", "No File selected") else: export_file_path = tk.filedialog.asksaveasfilename(defaultextension='.ico') img.save(export_file_path) tk.messagebox.showinfo("Success", "File converted and saved")
Function to convert image from png to ico format with pillow and save to user specified location
convertToICO
python
Python-World/python-mini-projects
projects/convert_png_images_to_ico_format/convertUI.py
https://github.com/Python-World/python-mini-projects/blob/master/projects/convert_png_images_to_ico_format/convertUI.py
MIT
def register_websocket_handlers(hass: HomeAssistant): """Register the websocket handlers.""" async_register_command(hass, websocket_device_action) async_register_command(hass, websocket_device_remove) async_register_command(hass, websocket_device_trigger) async_register_command(hass, websocket_discovery) async_register_command(hass, websocket_entity) async_register_command(hass, websocket_config_update) async_register_command(hass, websocket_version) async_register_command(hass, websocket_webhook) async_register_command(hass, websocket_sentence) async_register_command(hass, websocket_sentence_response)
Register the websocket handlers.
register_websocket_handlers
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
async def websocket_device_action( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Sensor command.""" context = connection.context(msg) platform = await device_automation.async_get_device_automation_platform( hass, msg["action"][CONF_DOMAIN], DeviceAutomationType.ACTION ) try: if "entity_id" in msg["action"]: entity_registry = async_get(hass) entity_id = entity_registry.async_get(msg["action"]["entity_id"]).entity_id msg["action"]["entity_id"] = entity_id await platform.async_call_action_from_config(hass, msg["action"], {}, context) connection.send_message(result_message(msg[CONF_ID])) except InvalidDeviceAutomationConfig as err: connection.send_message(error_message(msg[CONF_ID], "invalid_config", str(err))) except DeviceNotFound as err: connection.send_message( error_message(msg[CONF_ID], "device_not_found", str(err)) ) except Exception as err: connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err)))
Sensor command.
websocket_device_action
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
async def websocket_device_remove( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Remove a device.""" device_registry = dr.async_get(hass) device = device_registry.async_get_device({(DOMAIN, msg[CONF_NODE_ID])}) if device is not None: entity_registry = async_get(hass) entries = async_entries_for_device(entity_registry, device.id) # Remove entities from device before removing device so the entities are not removed from HA if entries: for entry in entries: entity_registry.async_update_entity(entry.entity_id, device_id=None) device_registry.async_remove_device(device.id) connection.send_message(result_message(msg[CONF_ID]))
Remove a device.
websocket_device_remove
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def websocket_discovery( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Sensor command.""" async_dispatcher_send( hass, NODERED_DISCOVERY.format(msg[CONF_COMPONENT]), msg, connection ) connection.send_message(result_message(msg[CONF_ID]))
Sensor command.
websocket_discovery
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def websocket_entity( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Sensor command.""" async_dispatcher_send( hass, NODERED_ENTITY.format(msg[CONF_SERVER_ID], msg[CONF_NODE_ID]), msg ) connection.send_message(result_message(msg[CONF_ID]))
Sensor command.
websocket_entity
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def websocket_config_update( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Sensor command.""" async_dispatcher_send( hass, NODERED_CONFIG_UPDATE.format(msg[CONF_SERVER_ID], msg[CONF_NODE_ID]), msg ) connection.send_message(result_message(msg[CONF_ID]))
Sensor command.
websocket_config_update
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def websocket_version( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Version command.""" connection.send_message(result_message(msg[CONF_ID], VERSION))
Version command.
websocket_version
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
async def handle_webhook(hass, id, request): """Handle webhook callback.""" body = await request.text() try: payload = json.loads(body) if body else {} except ValueError: payload = body data = { "payload": payload, "headers": dict(request.headers), "params": dict(request.query), } _LOGGER.debug(f"Webhook received {id[:15]}..: {data}") connection.send_message(event_message(msg[CONF_ID], {"data": data}))
Handle webhook callback.
websocket_webhook.handle_webhook
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def remove_webhook() -> None: """Remove webhook command.""" try: webhook_async_unregister(hass, webhook_id) except ValueError: pass _LOGGER.info(f"Webhook removed: {webhook_id[:15]}..") connection.send_message(result_message(msg[CONF_ID]))
Remove webhook command.
websocket_webhook.remove_webhook
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
async def websocket_webhook( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Create webhook command.""" webhook_id = msg[CONF_WEBHOOK_ID] allowed_methods = msg.get(CONF_ALLOWED_METHODS) @callback async def handle_webhook(hass, id, request): """Handle webhook callback.""" body = await request.text() try: payload = json.loads(body) if body else {} except ValueError: payload = body data = { "payload": payload, "headers": dict(request.headers), "params": dict(request.query), } _LOGGER.debug(f"Webhook received {id[:15]}..: {data}") connection.send_message(event_message(msg[CONF_ID], {"data": data})) def remove_webhook() -> None: """Remove webhook command.""" try: webhook_async_unregister(hass, webhook_id) except ValueError: pass _LOGGER.info(f"Webhook removed: {webhook_id[:15]}..") connection.send_message(result_message(msg[CONF_ID])) try: webhook_async_register( hass, DOMAIN, msg[CONF_NAME], webhook_id, handle_webhook, allowed_methods=allowed_methods, ) except ValueError as err: connection.send_message(error_message(msg[CONF_ID], "value_error", str(err))) return except Exception as err: connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err))) return _LOGGER.info(f"Webhook created: {webhook_id[:15]}..") connection.subscriptions[msg[CONF_ID]] = remove_webhook connection.send_message(result_message(msg[CONF_ID]))
Create webhook command.
websocket_webhook
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def forward_trigger(event, context=None): """Forward events to websocket.""" message = event_message( msg[CONF_ID], {"type": "device_trigger", "data": event["trigger"]}, ) connection.send_message( json.dumps(message, cls=NodeRedJSONEncoder, allow_nan=False) )
Forward events to websocket.
websocket_device_trigger.forward_trigger
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def unsubscribe() -> None: """Remove device trigger.""" remove_trigger() _LOGGER.info(f"Device trigger removed: {node_id}")
Remove device trigger.
websocket_device_trigger.unsubscribe
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
async def websocket_device_trigger( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Create device trigger.""" node_id = msg[CONF_NODE_ID] trigger_data = msg[CONF_DEVICE_TRIGGER] def forward_trigger(event, context=None): """Forward events to websocket.""" message = event_message( msg[CONF_ID], {"type": "device_trigger", "data": event["trigger"]}, ) connection.send_message( json.dumps(message, cls=NodeRedJSONEncoder, allow_nan=False) ) def unsubscribe() -> None: """Remove device trigger.""" remove_trigger() _LOGGER.info(f"Device trigger removed: {node_id}") try: trigger_config = await trigger.async_validate_trigger_config( hass, [trigger_data] ) remove_trigger = await trigger.async_initialize_triggers( hass, trigger_config, forward_trigger, DOMAIN, DOMAIN, _LOGGER.log, ) except vol.MultipleInvalid as err: _LOGGER.error( f"Error initializing device trigger '{node_id}': {str(err)}", ) connection.send_message( error_message(msg[CONF_ID], "invalid_trigger", str(err)) ) return except Exception as err: _LOGGER.error( f"Error initializing device trigger '{node_id}': {str(err)}", ) connection.send_message(error_message(msg[CONF_ID], "unknown_error", str(err))) return _LOGGER.info(f"Device trigger created: {node_id}") _LOGGER.debug(f"Device trigger config for {node_id}: {trigger_data}") connection.subscriptions[msg[CONF_ID]] = unsubscribe connection.send_message(result_message(msg[CONF_ID]))
Create device trigger.
websocket_device_trigger
python
zachowj/hass-node-red
custom_components/nodered/websocket.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/websocket.py
MIT
def __init__(self): """Initialize.""" self._errors = {}
Initialize.
__init__
python
zachowj/hass-node-red
custom_components/nodered/config_flow.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/config_flow.py
MIT
async def async_step_user(self, user_input=None): """Handle a user initiated set up flow to create a webhook.""" if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") if self.hass.data.get(DOMAIN): return self.async_abort(reason="single_instance_allowed") if user_input is None: return self.async_show_form(step_id="user") return self.async_create_entry( title=CONF_NAME, data={}, )
Handle a user initiated set up flow to create a webhook.
async_step_user
python
zachowj/hass-node-red
custom_components/nodered/config_flow.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/config_flow.py
MIT
def default(self, o: Any) -> Any: """Convert timedelta objects. Hand other objects to the Home Assistant JSONEncoder. """ if isinstance(o, timedelta): return o.total_seconds() return JSONEncoder.default(self, o)
Convert timedelta objects. Hand other objects to the Home Assistant JSONEncoder.
default
python
zachowj/hass-node-red
custom_components/nodered/utils.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/utils.py
MIT
async def async_setup_entry(hass, config_entry, async_add_devices): """Set up sensor platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_devices) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_BINARY_SENSOR), async_discover, )
Set up sensor platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/binary_sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/binary_sensor.py
MIT
async def _async_setup_entity(hass, config, async_add_devices): """Set up the Node-RED binary-sensor.""" async_add_devices([NodeRedBinarySensor(hass, config)])
Set up the Node-RED binary-sensor.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/binary_sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/binary_sensor.py
MIT
def __init__(self, hass, config): """Initialize the binary sensor.""" super().__init__(hass, config) self._attr_state = config.get(CONF_STATE)
Initialize the binary sensor.
__init__
python
zachowj/hass-node-red
custom_components/nodered/binary_sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/binary_sensor.py
MIT
def is_on(self): """Return true if the binary sensor is on.""" value = self._attr_state if value is None: return None if isinstance(value, bool): return value if isinstance(value, str): value = value.lower().strip() if value in NodeRedBinarySensor.on_states: return True elif isinstance(value, Number): return value != 0 return False
Return true if the binary sensor is on.
is_on
python
zachowj/hass-node-red
custom_components/nodered/binary_sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/binary_sensor.py
MIT
def update_entity_state_attributes(self, msg): """Update entity state attributes.""" super().update_entity_state_attributes(msg) self._attr_state = msg.get(CONF_STATE)
Update entity state attributes.
update_entity_state_attributes
python
zachowj/hass-node-red
custom_components/nodered/binary_sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/binary_sensor.py
MIT
async def handle_trigger( sentence: str, result: RecognizeResult | None = None, device_id: str | None = None, ) -> str: """ Handle Sentence trigger. RecognizeResult was added in 2023.8.0 device_id was added in 2024.4.0 """ # RecognizeResult in 2024.12 is not serializable, so we need to convert it to a serializable format serialized = convert_recognize_result_to_dict(result) _LOGGER.debug(f"Sentence trigger: {sentence}") connection.send_message( event_message( message_id, { "data": { "sentence": sentence, "result": serialized, "deviceId": device_id, "responseId": message_id, } }, ) ) if response_type == ResponseType.DYNAMIC: async with response_lock: if message_id not in response_futures: response_futures[message_id] = hass.loop.create_future() try: result = await asyncio.wait_for( response_futures[message_id], response_timeout ) _LOGGER.debug( f"Sentence response {message_id} received with response: {result}" ) return result except asyncio.TimeoutError: _LOGGER.debug( f"Timeout reached for sentence response {message_id}. Continuing..." ) # Remove the event from the dictionary after timeout del response_futures[message_id] return response
Handle Sentence trigger. RecognizeResult was added in 2023.8.0 device_id was added in 2024.4.0
websocket_sentence.handle_trigger
python
zachowj/hass-node-red
custom_components/nodered/sentence.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sentence.py
MIT
def remove_trigger() -> None: """Remove sentence trigger.""" async def _remove_future() -> None: async with response_lock: if message_id in response_futures: del response_futures[message_id] hass.async_create_task(_remove_future()) _remove_trigger() _LOGGER.info(f"Sentence trigger removed: {sentences}")
Remove sentence trigger.
websocket_sentence.remove_trigger
python
zachowj/hass-node-red
custom_components/nodered/sentence.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sentence.py
MIT
async def websocket_sentence( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Create sentence trigger.""" message_id = msg[CONF_ID] sentences = msg["sentences"] response = msg["response"] response_timeout = msg["response_timeout"] response_type = msg["response_type"] @callback async def handle_trigger( sentence: str, result: RecognizeResult | None = None, device_id: str | None = None, ) -> str: """ Handle Sentence trigger. RecognizeResult was added in 2023.8.0 device_id was added in 2024.4.0 """ # RecognizeResult in 2024.12 is not serializable, so we need to convert it to a serializable format serialized = convert_recognize_result_to_dict(result) _LOGGER.debug(f"Sentence trigger: {sentence}") connection.send_message( event_message( message_id, { "data": { "sentence": sentence, "result": serialized, "deviceId": device_id, "responseId": message_id, } }, ) ) if response_type == ResponseType.DYNAMIC: async with response_lock: if message_id not in response_futures: response_futures[message_id] = hass.loop.create_future() try: result = await asyncio.wait_for( response_futures[message_id], response_timeout ) _LOGGER.debug( f"Sentence response {message_id} received with response: {result}" ) return result except asyncio.TimeoutError: _LOGGER.debug( f"Timeout reached for sentence response {message_id}. Continuing..." ) # Remove the event from the dictionary after timeout del response_futures[message_id] return response def remove_trigger() -> None: """Remove sentence trigger.""" async def _remove_future() -> None: async with response_lock: if message_id in response_futures: del response_futures[message_id] hass.async_create_task(_remove_future()) _remove_trigger() _LOGGER.info(f"Sentence trigger removed: {sentences}") try: default_agent = hass.data[DATA_DEFAULT_ENTITY] assert isinstance(default_agent, DefaultAgent) _remove_trigger = default_agent.register_trigger(sentences, handle_trigger) except ValueError as err: connection.send_message(error_message(message_id, "value_error", str(err))) return except Exception as err: connection.send_message(error_message(message_id, "unknown_error", str(err))) return if response_type == ResponseType.FIXED: _LOGGER.info(f"Sentence trigger created: {sentences}") else: _LOGGER.info( f"Sentence trigger created: {sentences} with dynamic response #{message_id} and timeout of {response_timeout} seconds" ) connection.subscriptions[msg[CONF_ID]] = remove_trigger connection.send_message(result_message(message_id))
Create sentence trigger.
websocket_sentence
python
zachowj/hass-node-red
custom_components/nodered/sentence.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sentence.py
MIT
async def websocket_sentence_response( hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any] ) -> None: """Send response to sentence trigger.""" message_id = msg[CONF_ID] response_id = msg["response_id"] response = msg["response"] async with response_lock: # Print the current response_futures keys (ids) if response_id in response_futures: # Set the message as the result response_futures[response_id].set_result(response) # Remove the event from the dictionary after dispatching del response_futures[response_id] _LOGGER.info(f"Sentence response received: {response}") connection.send_message(result_message(message_id)) else: message = f"Sentence response not found for id: {response_id}" _LOGGER.warning(message) connection.send_message( error_message(message_id, "sentence_response_not_found", message), )
Send response to sentence trigger.
websocket_sentence_response
python
zachowj/hass-node-red
custom_components/nodered/sentence.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sentence.py
MIT
def convert_recognize_result_to_dict(result: Any) -> dict: """ Serializes a RecognizeResult object into a JSON-serializable dictionary. """ def serialize(obj): if isinstance(obj, Sentence): # Custom serialization for Sentence return { "text": obj.text, "pattern": obj.pattern.pattern if obj.pattern else None, } elif hasattr(obj, "__dict__"): # For objects with attributes, serialize attributes return {key: serialize(value) for key, value in vars(obj).items()} elif isinstance(obj, list): # Recursively handle lists return [serialize(item) for item in obj] elif isinstance(obj, dict): # Recursively handle dictionaries return {key: serialize(value) for key, value in obj.items()} elif isinstance(obj, (int, float, str, type(None))): # Primitive types are already serializable return obj else: # Fallback for non-serializable types return str(obj) return serialize(result)
Serializes a RecognizeResult object into a JSON-serializable dictionary.
convert_recognize_result_to_dict
python
zachowj/hass-node-red
custom_components/nodered/sentence.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sentence.py
MIT
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up button platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_entities, connection) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_BUTTON), async_discover, )
Set up button platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/button.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/button.py
MIT
async def _async_setup_entity(hass, config, async_add_entities, connection): """Set up the Node-RED button.""" async_add_entities([NodeRedButton(hass, config, connection)])
Set up the Node-RED button.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/button.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/button.py
MIT
def __init__(self, hass, config, connection): """Initialize the button.""" super().__init__(hass, config) self._message_id = config[CONF_ID] self._connection = connection
Initialize the button.
__init__
python
zachowj/hass-node-red
custom_components/nodered/button.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/button.py
MIT
def press(self) -> None: """Handle the button press.""" self._connection.send_message( event_message( self._message_id, { CONF_TYPE: EVENT_TRIGGER_NODE, "data": { "entity": self.hass.states.get(self.entity_id), }, }, ) )
Handle the button press.
press
python
zachowj/hass-node-red
custom_components/nodered/button.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/button.py
MIT
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the time platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_entities, connection) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_TIME), async_discover, )
Set up the time platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
async def _async_setup_entity(hass, config, async_add_entities, connection): """Set up the Node-RED time.""" async_add_entities([NodeRedTime(hass, config, connection)])
Set up the Node-RED time.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
def _convert_string_to_time(value): """Convert string to time.""" if value is None: return None try: return parser.parse(value).time() except ValueError: _LOGGER.error(f"Unable to parse time: {value}") return None
Convert string to time.
_convert_string_to_time
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
def __init__(self, hass, config, connection): """Initialize the time.""" super().__init__(hass, config) self._message_id = config[CONF_ID] self._connection = connection
Initialize the time.
__init__
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
async def async_set_value(self, value) -> None: """Set new value.""" self._connection.send_message( event_message( self._message_id, {CONF_TYPE: EVENT_VALUE_CHANGE, CONF_VALUE: value} ) )
Set new value.
async_set_value
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
def update_entity_state_attributes(self, msg): """Update the entity state attributes.""" super().update_entity_state_attributes(msg) self._attr_native_value = _convert_string_to_time(msg.get(CONF_STATE))
Update the entity state attributes.
update_entity_state_attributes
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
def update_discovery_config(self, msg): """Update the entity config.""" super().update_discovery_config(msg) self._attr_icon = msg[CONF_CONFIG].get(CONF_ICON, TIME_ICON)
Update the entity config.
update_discovery_config
python
zachowj/hass-node-red
custom_components/nodered/time.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/time.py
MIT
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up sensor platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_entities) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_SENSOR), async_discover, )
Set up sensor platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
async def _async_setup_entity(hass, config, async_add_entities): """Set up the Node-RED sensor.""" async_add_entities([NodeRedSensor(hass, config)])
Set up the Node-RED sensor.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def __init__(self, hass, config): """Initialize the sensor.""" super().__init__(hass, config) self._attr_unit_of_measurement = None self._attr_native_value = self.convert_state(config.get(CONF_STATE)) self._attr_native_unit_of_measurement = self._config.get( CONF_UNIT_OF_MEASUREMENT ) self._attr_state_class = self._config.get(CONF_STATE_CLASS)
Initialize the sensor.
__init__
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def last_reset(self) -> Optional[datetime]: """Return the last reset.""" reset = self._config.get(CONF_LAST_RESET) if reset is not None: try: return parser.parse(reset) except (ValueError, TypeError): _LOGGER.error( f"Invalid ISO date string ({reset}): {self.entity_id} requires last_reset to be an iso date formatted string" ) return None
Return the last reset.
last_reset
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def convert_state(self, state) -> Union[datetime, float, int, str, bool]: """Convert state if needed.""" if state is not None and self.device_class in [ SensorDeviceClass.TIMESTAMP, SensorDeviceClass.DATE, ]: try: datetime = parser.parse(state) if self.device_class is SensorDeviceClass.DATE: return datetime.date() return datetime except (ValueError, TypeError): _LOGGER.error( f"Invalid ISO date string ({state}): {self.entity_id} has a timestamp device class" ) return None return state
Convert state if needed.
convert_state
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def update_entity_state_attributes(self, msg): """Update entity state attributes.""" super().update_entity_state_attributes(msg) self._attr_native_value = self.convert_state(msg.get(CONF_STATE))
Update entity state attributes.
update_entity_state_attributes
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def update_discovery_config(self, msg): """Update entity config.""" super().update_discovery_config(msg) self._attr_native_unit_of_measurement = msg[CONF_CONFIG].get( CONF_UNIT_OF_MEASUREMENT ) self._attr_unit_of_measurement = None self._attr_state_class = msg[CONF_CONFIG].get(CONF_STATE_CLASS)
Update entity config.
update_discovery_config
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
def entity_category_mapper(self, category): """Map Node-RED category to Home Assistant entity category.""" if category == "config": _LOGGER.warning( f"Sensor {self.name} has category 'config' which is not supported" ) if category == "diagnostic": return EntityCategory.DIAGNOSTIC return None
Map Node-RED category to Home Assistant entity category.
entity_category_mapper
python
zachowj/hass-node-red
custom_components/nodered/sensor.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/sensor.py
MIT
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the text platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_entities, connection) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_TEXT), async_discover, )
Set up the text platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
async def _async_setup_entity(hass, config, async_add_entities, connection): """Set up the Node-RED text.""" async_add_entities([NodeRedText(hass, config, connection)])
Set up the Node-RED text.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
def __init__(self, hass, config, connection): """Initialize the number.""" super().__init__(hass, config) self._message_id = config[CONF_ID] self._connection = connection
Initialize the number.
__init__
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
async def async_added_to_hass(self) -> None: """Restore native_*.""" await super().async_added_to_hass() if (last_text_data := await self.async_get_last_text_data()) is None: return self._attr_native_max = last_text_data.native_max self._attr_native_min = last_text_data.native_min self._attr_native_value = last_text_data.native_value
Restore native_*.
async_added_to_hass
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
async def async_set_value(self, value: str) -> None: """Set new value.""" self._connection.send_message( event_message( self._message_id, {CONF_TYPE: EVENT_VALUE_CHANGE, CONF_VALUE: value} ) )
Set new value.
async_set_value
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
def update_entity_state_attributes(self, msg): """Update the entity state attributes.""" super().update_entity_state_attributes(msg) self._attr_native_value = msg.get(CONF_STATE)
Update the entity state attributes.
update_entity_state_attributes
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
def update_discovery_config(self, msg): """Update the entity config.""" super().update_discovery_config(msg) self._attr_icon = self._config.get(CONF_ICON, TEXT_ICON) self._attr_native_min = self._config.get(CONF_MIN_LENGTH, DEFAULT_MIN_LENGTH) self._attr_native_max = self._config.get(CONF_MAX_LENGTH, DEFAULT_MAX_LENGTH) self._attr_pattern = self._config.get(CONF_PATTERN, None) self._attr_mode = TextMode(self._config.get(CONF_MODE, DEFAULT_MODE))
Update the entity config.
update_discovery_config
python
zachowj/hass-node-red
custom_components/nodered/text.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/text.py
MIT
async def async_device_message_received(msg, connection): """Process the received message.""" component = msg[CONF_COMPONENT] server_id = msg[CONF_SERVER_ID] node_id = msg[CONF_NODE_ID] if component not in SUPPORTED_COMPONENTS: _LOGGER.warning(f"Integration {component} is not supported") return discovery_hash = f"{DOMAIN}-{server_id}-{node_id}" data = hass.data[DOMAIN_DATA] _LOGGER.debug(f"Discovery message: {msg}") if ALREADY_DISCOVERED not in data: data[ALREADY_DISCOVERED] = {} if discovery_hash in data[ALREADY_DISCOVERED]: if data[ALREADY_DISCOVERED][discovery_hash] != component: # Remove old log_text = f"Changing {data[ALREADY_DISCOVERED][discovery_hash]} to" msg[CONF_REMOVE] = CHANGE_ENTITY_TYPE elif CONF_REMOVE in msg: log_text = "Removing" else: # Dispatch update log_text = "Updating" _LOGGER.info(f"{log_text} {component} {server_id} {node_id}") data[ALREADY_DISCOVERED][discovery_hash] = component async_dispatcher_send( hass, NODERED_DISCOVERY_UPDATED.format(discovery_hash), msg, connection ) else: # Add component _LOGGER.info(f"Creating {component} {server_id} {node_id}") data[ALREADY_DISCOVERED][discovery_hash] = component async with data[CONFIG_ENTRY_LOCK]: if component not in data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setups( config_entry, [component] ) data[CONFIG_ENTRY_IS_SETUP].add(component) async_dispatcher_send( hass, NODERED_DISCOVERY_NEW.format(component), msg, connection )
Process the received message.
start_discovery.async_device_message_received
python
zachowj/hass-node-red
custom_components/nodered/discovery.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/discovery.py
MIT
async def start_discovery(hass: HomeAssistant, hass_config, config_entry=None) -> bool: """Initialize of Node-RED Discovery.""" async def async_device_message_received(msg, connection): """Process the received message.""" component = msg[CONF_COMPONENT] server_id = msg[CONF_SERVER_ID] node_id = msg[CONF_NODE_ID] if component not in SUPPORTED_COMPONENTS: _LOGGER.warning(f"Integration {component} is not supported") return discovery_hash = f"{DOMAIN}-{server_id}-{node_id}" data = hass.data[DOMAIN_DATA] _LOGGER.debug(f"Discovery message: {msg}") if ALREADY_DISCOVERED not in data: data[ALREADY_DISCOVERED] = {} if discovery_hash in data[ALREADY_DISCOVERED]: if data[ALREADY_DISCOVERED][discovery_hash] != component: # Remove old log_text = f"Changing {data[ALREADY_DISCOVERED][discovery_hash]} to" msg[CONF_REMOVE] = CHANGE_ENTITY_TYPE elif CONF_REMOVE in msg: log_text = "Removing" else: # Dispatch update log_text = "Updating" _LOGGER.info(f"{log_text} {component} {server_id} {node_id}") data[ALREADY_DISCOVERED][discovery_hash] = component async_dispatcher_send( hass, NODERED_DISCOVERY_UPDATED.format(discovery_hash), msg, connection ) else: # Add component _LOGGER.info(f"Creating {component} {server_id} {node_id}") data[ALREADY_DISCOVERED][discovery_hash] = component async with data[CONFIG_ENTRY_LOCK]: if component not in data[CONFIG_ENTRY_IS_SETUP]: await hass.config_entries.async_forward_entry_setups( config_entry, [component] ) data[CONFIG_ENTRY_IS_SETUP].add(component) async_dispatcher_send( hass, NODERED_DISCOVERY_NEW.format(component), msg, connection ) hass.data[DOMAIN_DATA][CONFIG_ENTRY_LOCK] = asyncio.Lock() hass.data[DOMAIN_DATA][CONFIG_ENTRY_IS_SETUP] = set() hass.data[DOMAIN_DATA][DISCOVERY_DISPATCHED] = async_dispatcher_connect( hass, NODERED_DISCOVERY, async_device_message_received, )
Initialize of Node-RED Discovery.
start_discovery
python
zachowj/hass-node-red
custom_components/nodered/discovery.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/discovery.py
MIT
def stop_discovery(hass: HomeAssistant): """Remove discovery dispatcher.""" hass.data[DOMAIN_DATA][DISCOVERY_DISPATCHED]()
Remove discovery dispatcher.
stop_discovery
python
zachowj/hass-node-red
custom_components/nodered/discovery.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/discovery.py
MIT
async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the text platform.""" async def async_discover(config, connection): await _async_setup_entity(hass, config, async_add_entities, connection) async_dispatcher_connect( hass, NODERED_DISCOVERY_NEW.format(CONF_SELECT), async_discover, )
Set up the text platform.
async_setup_entry
python
zachowj/hass-node-red
custom_components/nodered/select.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/select.py
MIT
async def _async_setup_entity(hass, config, async_add_entities, connection): """Set up the Node-RED text.""" async_add_entities([NodeRedSelect(hass, config, connection)])
Set up the Node-RED text.
_async_setup_entity
python
zachowj/hass-node-red
custom_components/nodered/select.py
https://github.com/zachowj/hass-node-red/blob/master/custom_components/nodered/select.py
MIT