Best Python code snippet using ATX
parse_window_dump.py
Source:parse_window_dump.py  
1import logging, sys, argparse, re2import xml.etree.ElementTree as ET3SCRIPT_NAME="WINDOW_DUMP_XML_PARSER"4def buitify_tweet(tweet):5	tweet=tweet.replace('\n','')6	tweet=tweet.replace('hashtag ','#')7	return tweet.strip()8def get_tweet(content_desc_line):9	usernames_and_time = content_desc_line.split(". . .")[0] 10	tweet = content_desc_line.split(". . .")[1]11	try:12		meta = content_desc_line.split(". . .")[2] 13	except:14		meta=""15	tweet = buitify_tweet(tweet)16	return usernames_and_time,tweet,meta17def get_time(usernames_and_time):18	time_arr = usernames_and_time.split(". ")19	time = time_arr[len(time_arr)-1]20	usernames = usernames_and_time[0:len(usernames_and_time)-len(time)-2] # -2 = ". " 21	return usernames, time22def get_usernames(usernames):23		user_arr = usernames.split("@")24		username = user_arr[len(user_arr)-1]25		username = "@"+username26		given_username = usernames[0:len(usernames)-len(username)]27		return given_username,username28def set_action_bounds(tweet_dict,inline_action_bounds):29	import math30	button_width = math.floor(inline_action_bounds[2] / 4) # number of buttons31	tweet_dict["reply_tweet_bounds"] = [inline_action_bounds[0], inline_action_bounds[1], button_width, inline_action_bounds[3]]32	tweet_dict["re_tweet_bounds"] = [button_width+1, inline_action_bounds[1], button_width * 2, inline_action_bounds[3]]33	tweet_dict["like_tweet_bounds"] =  [(button_width * 2) + 1, inline_action_bounds[1], button_width * 3, inline_action_bounds[3]]34	tweet_dict["share_bounds"] = [(button_width * 3) + 1, inline_action_bounds[1], inline_action_bounds[2], inline_action_bounds[3]]35	tweet_dict["inline_actions_bounds"] = inline_action_bounds36def bounds_str_to_list(bounds_str):37	R = re.compile("\\[(?P<x_start>[0-9]+),(?P<y_start>[0-9]+)\\]\\[(?P<x_end>[0-9]+),(?P<y_end>[0-9]+)\\]")38	match = R.match(bounds_str)39	if match:40		cords = match.groupdict()41	return [int(cords["x_start"]), # 4 item list42			int(cords["y_start"]),43			int(cords["x_end"]),44			int(cords["y_end"])]45def get_xml_tree(xml_filename):46	try:47		tree = ET.parse(xml_filename)48	except:49		logging.error("{}: Unable to parse XML file ...".format(SCRIPT_NAME))50		sys.exit(1)51	return tree52def parse_main_activity_dump(xml_filename):53	main_activity = {}54	main_activity["home_menu"] = {}55	tree = get_xml_tree(xml_filename)56	child = tree.getroot()57	tweet_items = []58	tmp_child = []59	while child is not None:60		for c in child:61			if(c.attrib["content-desc"] is not ""):62				# parse tweet button63				if (c.attrib["resource-id"] == "com.twitter.android:id/row"):64					tweet_items.append(c)65				# parse tweets66				if c.attrib["content-desc"] == "New Tweet":67					main_activity["new_tweet_bounds"] = bounds_str_to_list(c.attrib["bounds"])68			# parse bottom bar69			if c.attrib["class"] == "android.support.v7.app.ActionBar$Tab":70				if c.attrib["content-desc"] == "Home":71					main_activity["home_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])72				elif c.attrib["content-desc"] == "Search and Explore Tab":73					main_activity["search_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])74				elif c.attrib["content-desc"] == "Notifications":75					main_activity["notification_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])76				elif c.attrib["content-desc"] == "Messages":77					main_activity["message_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])78			# parse top home button79			if c.attrib["class"] == "android.widget.ImageButton":80				if c.attrib["content-desc"] == "Show navigation drawer":81					82					main_activity["home_menu"]["home_button_bounds"] = bounds_str_to_list(c.attrib["bounds"]) 83			# if home button was pressed84			if (c.attrib["resource-id"] == "com.twitter.android:id/name"):85				main_activity["home_menu"]["unfolded"] = True86				main_activity["home_menu"]["name"] = c.attrib["text"]87			if (c.attrib["resource-id"] == "com.twitter.android:id/username"):88				main_activity["home_menu"]["username"] = c.attrib["text"]89			if (c.attrib["resource-id"] == "com.twitter.android:id/title"):90				if c.attrib["text"] == "Profile":91					main_activity["home_menu"]["profile_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])92					# UNTESTED - requires total screen size93					main_activity["home_menu"]["return_bounds"] = [94																	main_activity["home_menu"]["profile_button_bounds"][2]+2,95																	main_activity["home_menu"]["profile_button_bounds"][1],96																	main_activity["home_menu"]["profile_button_bounds"][2]+100,97																	(main_activity["home_menu"]["profile_button_bounds"][3]-main_activity["home_menu"]["profile_button_bounds"][1]) * 4,98																	]99				if c.attrib["text"] == "Lists":100					main_activity["home_menu"]["lists_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])101				if c.attrib["text"] == "Bookmarks":102					main_activity["home_menu"]["bookmarks_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])103				if c.attrib["text"] == "Moments":104					main_activity["home_menu"]["moments_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])105				if c.attrib["text"] == "Settings and privacy":106					main_activity["home_menu"]["settings_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])107				if c.attrib["text"] == "Help Center":108					main_activity["home_menu"]["help_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])109			tmp_child.append(c)110		try:111			child=tmp_child.pop(0)112		except:113			child=None114	main_activity["tweets"] = []115	# example: content-desc='Coldamber @Coldamber. 15 hours ago. . . Ich habe heute im Seminar 116	# "Sprache und Geschlecht" die Studierenden gefragt: "Angenommen, es muesste dein Musikgeschmack117	# im Pass stehen: Waere es bei dir Pop oder Metal?" Und meine Guete war die Empoerung gross.. . . Sascha Bors liked. .'118	for tweet_obj in tweet_items:119		tweet_dict = {}120		cd_line = tweet_obj.attrib["content-desc"]121		usernames_and_time, tweet, meta = get_tweet(cd_line)122		usernames , time = get_time(usernames_and_time) 		123		given_username, username = get_usernames(usernames)124		tweet_dict["username"] = username125		tweet_dict["given_username"] = given_username126		tweet_dict["tweet"] = tweet127		tweet_dict["time"] = time128		tweet_dict["bounds"] = bounds_str_to_list(tweet_obj.attrib["bounds"])129		for c in tweet_obj:130			if c.attrib["resource-id"] == "com.twitter.android:id/tweet_inline_actions":131				set_action_bounds(	tweet_dict=tweet_dict,132									inline_action_bounds=bounds_str_to_list(c.attrib["bounds"]))133		main_activity["tweets"].append(tweet_dict)134	return main_activity135def parse_challenge_activity_dump(xml_filename):136	tree = get_xml_tree(xml_filename)137	child = tree.getroot()138	tmp_child = []139	challenge_dicts = {}140	text_box_bounds = None141	submit_button_bounds = None142	while child is not None:143			for c in child:144				if c.attrib["class"] == "android.widget.EditText":145					if c.attrib["content-desc"] == "Phone number":146						challenge_dicts["phone_number_text_box"] = bounds_str_to_list(c.attrib["bounds"])147				if c.attrib["class"] == "android.widget.Button":148					if c.attrib["content-desc"] == "Submit":149						challenge_dicts["submit_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])150				tmp_child.append(c)151			try:152				child=tmp_child.pop(0)153			except: 154				child=None155	return challenge_dicts156def parse_onboarding_activity_dump(xml_filename):157	tree = get_xml_tree(xml_filename)158	child = tree.getroot()159	tmp_child = []160	login_button_bounds = None161	162	while child is not None:163		for c in child:164			if c.attrib["text"] == "Have an account already? Log in":165				login_button_bounds = bounds_str_to_list(c.attrib["bounds"])166			tmp_child.append(c)167		try:168			child=tmp_child.pop(0)169		except:170			child=None171	if login_button_bounds is None:172		raise ValueError173	import math174	login_button_wdith = math.floor((login_button_bounds[2]-login_button_bounds[0]) / 6) 175	login_button_bounds[0] = login_button_bounds[2] - login_button_wdith # original bounds include non clickable text first176	return login_button_bounds177def parse_login_activity_dump(xml_filename):178	login_activity = {}179	tree = get_xml_tree(xml_filename)180	child = tree.getroot()181	tmp_child = []182	while child is not None:183		for c in child:184			if c.attrib["resource-id"] == "com.twitter.android:id/login_password":185				login_activity["login_password_bounds"] = bounds_str_to_list(c.attrib["bounds"])186			if c.attrib["resource-id"] == "com.twitter.android:id/login_identifier":187				login_activity["login_identifier_bounds"] = bounds_str_to_list(c.attrib["bounds"])188			if c.attrib["resource-id"] == "com.twitter.android:id/login_login":189				login_activity["login_button_bounds"] = bounds_str_to_list(c.attrib["bounds"])190			tmp_child.append(c)191		try:192			child=tmp_child.pop(0)193		except:194			child=None195	return login_activity196def main():197	logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)198	parser = argparse.ArgumentParser()199	parser.add_argument("-xmlfile",type=str,help="provide window_dump.xml")200	parser.add_argument("-activity",type=str,help="activity the dump is from (onboarding,login,main")201	args = parser.parse_args()202	if args.activity == "challenge":203		print(parse_challenge_activity_dump(args.xmlfile))204	elif args.activity == "onboarding":205		print(parse_onboarding_activity_dump(args.xmlfile))206	elif args.activity == "main":207		main_activity=parse_main_activity_dump(args.xmlfile)208		import pprint209		pp = pprint.PrettyPrinter(indent=4)210		pp.pprint(main_activity)211	elif args.activity == "login":212		print(parse_login_activity_dump(args.xmlfile))213	else:214		logging.error("Not support parameter {} ...".format(args.activity))215	exit(0)216if __name__ == '__main__':...fusion.py
Source:fusion.py  
1#!/usr/bin/env python2import pandas, time, math3class Fusion:4    def merge_activities(self, main_activity, cardio_activity):5        complete_cardio = self._interpolate_cardio(main_activity, cardio_activity)6        # and merge it back into the main activity7        for trackpoint in main_activity.trackpoints:8            timestamp = self._date_to_timestamp(trackpoint.time)9            try:10                bpm = float(complete_cardio[timestamp])11                bpm = 0 if math.isnan(bpm) else int(bpm)12            except KeyError:13                bpm = 014            trackpoint.heart_rate = bpm15    def _interpolate_cardio(self, main_activity, cardio_activity):16        # determine the workout bounds17        main_start = self._date_to_timestamp(main_activity.started_at)18        main_end = self._date_to_timestamp(main_activity.completed_at)19        # interpolate the cardio data20        cardio_map = {self._date_to_timestamp(t.time): t.heart_rate for t in cardio_activity.trackpoints}21        cardio_map_interpolated = pandas.Series(cardio_map, index=range(main_start, main_end + 1))22        cardio_map_interpolated = cardio_map_interpolated.interpolate()23        return cardio_map_interpolated.to_dict()24    def _date_to_timestamp(self, date):...Laddu.py
Source:Laddu.py  
1# 22# 4 INDIAN3# CONTEST_WON 14# TOP_CONTRIBUTOR5# BUG_FOUND 1006# CONTEST_HOSTED7# 4 NON_INDIAN8# CONTEST_WON 19# TOP_CONTRIBUTOR10# BUG_FOUND 10011# CONTEST_HOSTED12T = int(input())13while (T!=0):14    totalpoints = 015    activities,origin = input().split()16    for _ in range(int(activities)):17        main_activity = input().split()18        if main_activity[0]=="CONTEST_WON":19            if int(main_activity[1])<21:20                totalpoints+=300+(20-int(main_activity[1]))21            else:22                totalpoints+=30023        elif main_activity[0]=="TOP_CONTRIBUTOR":24            totalpoints+=30025        elif main_activity[0]=="BUG_FOUND":26            totalpoints+=int(main_activity[1])27        elif main_activity[0]=="CONTEST_HOSTED":28            totalpoints+=5029    if origin=="INDIAN":30        print(totalpoints//200)31    elif origin=="NON_INDIAN":32        print(totalpoints//400)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
