content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
################################################################################ level_number = 13 dungeon_name = 'The Tower' wall_style = 'Mangar' monster_difficulty = 6 goes_down = False entry_position = (255, 255) phase_door = False level_teleport = [ (11, True), (12, True), (13, True), (14, False), (15, False), ] stairs_previous = [(19, 11)] stairs_next = [] portal_down = [] portal_up = [] teleports = [ ((3, 6), (3, 14)), ((10, 19), (10, 7)), ] encounters = [ ((18, 9), (98, 1)), ((16, 11), (98, 1)), ((12, 3), (98, 1)), ((9, 14), (98, 1)), ((8, 20), (98, 1)), ((4, 20), (98, 1)), ((14, 15), (98, 1)), ((21, 20), (98, 1)), ] messages = [ ((7, 9), 'On the wall is etched:\n\nDo not scry,\n the first is lie.'), ((8, 13), "On the wall is etched:\n\nThe One God's\nsecond is surely with."), ((15, 21), 'On the wall is etched:\n\nAs the One God has said, the third is passion if you have love and life.'), ((9, 19), 'On the wall is etched:\n\nIn all the land,\n the fourth is and'), ((12, 11), 'On the wall is etched:\n\nWe speak of One God, eternal is he, his fifth is almost certainly be.'), ((19, 1), 'On the wall is etched:\n\nOn the many levels, several are ancient but the sixth is forever.'), ((21, 0), 'On the wall is etched:\n\nThe One has said that the first man is blessed and the last is damned.'), ((21, 4), 'You smell burning coals...'), ] specials = [ ((12, 19), (45, 255)), ((4, 10), (46, 255)), ] smoke_zones = [] darkness = [(0, 4), (0, 7), (0, 8), (0, 11), (0, 12), (0, 15), (0, 16), (0, 19), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16), (1, 17), (1, 18), (1, 19), (2, 0), (2, 4), (2, 10), (2, 16), (3, 0), (3, 4), (3, 10), (3, 16), (4, 0), (4, 4), (4, 10), (4, 16), (5, 0), (5, 4), (5, 10), (5, 16), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (6, 16), (6, 17), (6, 18), (6, 19), (6, 20), (7, 0), (7, 4), (7, 10), (7, 16), (7, 17), (7, 18), (7, 19), (7, 20), (7, 21), (8, 0), (8, 4), (8, 10), (8, 16), (8, 17), (8, 18), (8, 19), (8, 20), (8, 21), (9, 0), (9, 4), (9, 10), (9, 16), (9, 17), (9, 18), (9, 20), (9, 21), (10, 0), (10, 4), (10, 10), (10, 16), (10, 17), (10, 18), (10, 19), (10, 20), (10, 21), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 11), (11, 12), (11, 13), (11, 14), (11, 15), (11, 16), (11, 17), (11, 18), (11, 19), (11, 20), (11, 21), (12, 0), (12, 4), (12, 10), (12, 16), (13, 0), (13, 4), (13, 10), (13, 16), (14, 0), (14, 4), (14, 5), (14, 6), (14, 10), (14, 16), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 17), (15, 18), (15, 19), (16, 2), (16, 3), (16, 4), (16, 5), (16, 6), (16, 17), (16, 18), (16, 19), (17, 2), (17, 3), (17, 18), (17, 19), (18, 2), (18, 3), (18, 4), (18, 5), (18, 6), (18, 7), (18, 8), (18, 9), (18, 10), (18, 11), (18, 12), (18, 13), (18, 14), (18, 15), (18, 16), (18, 17), (18, 18), (18, 19), (19, 0), (19, 1), (19, 2), (19, 3), (19, 4), (19, 5), (19, 6), (19, 7), (19, 8), (19, 9), (19, 10), (19, 11), (19, 12), (19, 13), (19, 14), (19, 15), (19, 16), (19, 17), (19, 18), (19, 19), (19, 20), (19, 21), (20, 0), (20, 1), (20, 2), (20, 19), (20, 20), (20, 21), (21, 0), (21, 1), (21, 2), (21, 19), (21, 20), (21, 21)] antimagic_zones = [(15, 16), (10, 4), (12, 20)] spinners = [(15, 10), (10, 10)] traps = [(1, 4), (1, 10), (1, 16), (6, 4), (6, 10), (6, 16), (11, 0), (11, 4), (11, 10), (11, 16)] hitpoint_damage = [(21, 1), (21, 2), (21, 3)] spellpoint_restore = [] stasis_chambers = [] random_encounter = [(0, 0), (0, 1), (0, 10), (0, 13), (0, 18), (2, 1), (2, 2), (2, 11), (2, 12), (2, 13), (3, 13), (3, 14), (3, 18), (3, 20), (4, 5), (4, 6), (4, 12), (4, 14), (5, 3), (5, 5), (5, 7), (5, 12), (5, 13), (5, 20), (7, 7), (7, 8), (7, 11), (8, 1), (10, 5), (10, 9), (12, 11), (13, 1), (13, 6), (13, 13), (14, 3), (14, 9), (14, 13), (17, 6), (17, 8), (17, 13), (20, 4), (20, 8), (20, 12), (20, 17)] specials_other = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 20), (2, 1), (3, 9), (5, 11), (6, 10), (6, 16), (6, 21), (7, 15), (9, 3), (9, 11), (9, 19), (9, 20), (11, 4), (11, 10), (11, 19), (12, 14), (12, 19), (13, 13), (13, 20), (14, 9), (17, 10), (17, 20), (18, 6)] map = [ '+-++-++-++-++-+| .. |+----+| .. |+----+| .. |+----+| .. |+-++----+', '| DD DD DD DD || || || || || || || || DD |', '+-++-++-++-+| |+---S+| .. |+----+| .. |+----+| .. |+---S+| || .. |', '+-----------. .------. .. .----S-. .. .-S----. .. .------. || .. |', '| || |', '| .---------. .---------------. .----------D----. .--------++----+', '| |+-++----+| |+----++-------+| |+-++-++-++D++-+| |+-++----++----+', '| || || || DD || || || || DD DD DD || DD || || |', '| |+S++D---+| || .--++--. .. || |+D++D++-++D++-+| |+D+| .. || .. |', '| |+S--D---+| || |+----+| .. || |+D++D++-++D++-+| |+D+| .. || .. |', '| || || || || || DD || DD DD || SS || || DD || |', '| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-++----++D---+', '| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-------++D---+', '| || || || DD || || || || DD DD DD || || || |', '| |+---D--S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |', '| |+---D++S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |', '| || || || || DD DD || || || || || DD DD DD || |', '| |+---D++-+| |+-++----++---D+| |+D++-++-++-++-+| |+-------++D---+', '| .----D----. .-------------D-. .-D-------------. .----------D++-+', '| SS |', '| .---------. .-------D--D----. .---------------. .-----------++-+', '| |+-------+| |+------D++D---+| |+-------++----+| |+-------------+', '| || || || || || DD || DD || |', '| || .. .. || || .. .. || .. || || .. .. || .. || || .---------. |', '| || .. .. || || .. .. || .. || || .. .. || .. || || |+-------+| |', '| DD || || || || || || || || || || |', '| |+-------+| |+-------++----+| |+-------++----+| || || .---. || |', '| |+-------+| |+----++-------+| |+-++----++----+| || || |+-+| || |', '| || DD || || || || DD || || || || || DD || |', '| || .. .. || || .. || .. .. || |+-+| .. || .. || || || |+-++-+| |', '| || .. .. || || .. || .. .. || |+-+| .. || .. || || || .------. |', '| || || || || DD || DD || DD || || |', '| |+-------+| |+D---++-------+| |+-++---D++----+| |+D++----------+', '. .---------. .-D-------------. .-------D-------. .-D-------------', ' ', '. .---------. .-D-----------D-. .-D--------D----. .---------------', '| |+-------+| |+D---++------D+| |+D------++D---+| |+----++-++----+', '| || || || || || || || || || DD || |', '| || .. .. || |+---S+| .. .. || || .. .-D+| .. || |+D---++-+| .. |', '| || .. .. || |+---S+| .. .. || || .. |+D+| .. || |+D------+| .. |', '| || || || || || || || || || || DD |', '| |+D------+| |+----++------S+| |+----++-+| .. || || .. .. |+----+', '| |+D------+| .-----++----++S+| |+-------+| .. || || .. .. |+----+', '| || DD || || || || DD || || DD |', '| |+-------++-----. || .. |+-++D++--. .. |+----++S++D------+| .. |', '| .--------------+| || .. |+---D---+| .. |+----++S++D------+| .. |', '| || || || || || DD || || |', '+-----. .. .. .. || || .. || .. .. || .. || .. || || .. .. |+----+', '-----+| .. .. .. || || .. || .. .. || .. || .. || || .. .. |+-----', ' || || DD || || || || || || ', '. .. || .. .-----++-++----++---S---++----++----++-++--. .. || .. .', '. .. || .. |+----++----++----++S---++----++----++----+| .. || .. .', ' DD DD DD DD || || DD DD DD DD ', '. .. || .. |+----++----++----++----++----++----++----+| .. || .. .', '. .. || .. .------------------------------------------. .. || .. .', ' || || ', '-----+| .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. |+-----', '+-----. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .-----+', '| |', '| .. .. .----D--D--------D--D--------D--D--------D--D----. .. .. |', '| .. .. |+---D++D---++---D++D---++---D++D---++---D++D---+| .. .. |', '| || || || || || || || || || |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| || || || || || || || || || |', '+-------++----+| .. |+----+| .. |+----+| .. |+----+| .. |+-------+', ]
level_number = 13 dungeon_name = 'The Tower' wall_style = 'Mangar' monster_difficulty = 6 goes_down = False entry_position = (255, 255) phase_door = False level_teleport = [(11, True), (12, True), (13, True), (14, False), (15, False)] stairs_previous = [(19, 11)] stairs_next = [] portal_down = [] portal_up = [] teleports = [((3, 6), (3, 14)), ((10, 19), (10, 7))] encounters = [((18, 9), (98, 1)), ((16, 11), (98, 1)), ((12, 3), (98, 1)), ((9, 14), (98, 1)), ((8, 20), (98, 1)), ((4, 20), (98, 1)), ((14, 15), (98, 1)), ((21, 20), (98, 1))] messages = [((7, 9), 'On the wall is etched:\n\nDo not scry,\n the first is lie.'), ((8, 13), "On the wall is etched:\n\nThe One God's\nsecond is surely with."), ((15, 21), 'On the wall is etched:\n\nAs the One God has said, the third is passion if you have love and life.'), ((9, 19), 'On the wall is etched:\n\nIn all the land,\n the fourth is and'), ((12, 11), 'On the wall is etched:\n\nWe speak of One God, eternal is he, his fifth is almost certainly be.'), ((19, 1), 'On the wall is etched:\n\nOn the many levels, several are ancient but the sixth is forever.'), ((21, 0), 'On the wall is etched:\n\nThe One has said that the first man is blessed and the last is damned.'), ((21, 4), 'You smell burning coals...')] specials = [((12, 19), (45, 255)), ((4, 10), (46, 255))] smoke_zones = [] darkness = [(0, 4), (0, 7), (0, 8), (0, 11), (0, 12), (0, 15), (0, 16), (0, 19), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (1, 11), (1, 12), (1, 13), (1, 14), (1, 15), (1, 16), (1, 17), (1, 18), (1, 19), (2, 0), (2, 4), (2, 10), (2, 16), (3, 0), (3, 4), (3, 10), (3, 16), (4, 0), (4, 4), (4, 10), (4, 16), (5, 0), (5, 4), (5, 10), (5, 16), (6, 0), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6), (6, 7), (6, 8), (6, 9), (6, 10), (6, 11), (6, 12), (6, 13), (6, 14), (6, 15), (6, 16), (6, 17), (6, 18), (6, 19), (6, 20), (7, 0), (7, 4), (7, 10), (7, 16), (7, 17), (7, 18), (7, 19), (7, 20), (7, 21), (8, 0), (8, 4), (8, 10), (8, 16), (8, 17), (8, 18), (8, 19), (8, 20), (8, 21), (9, 0), (9, 4), (9, 10), (9, 16), (9, 17), (9, 18), (9, 20), (9, 21), (10, 0), (10, 4), (10, 10), (10, 16), (10, 17), (10, 18), (10, 19), (10, 20), (10, 21), (11, 0), (11, 1), (11, 2), (11, 3), (11, 4), (11, 5), (11, 6), (11, 7), (11, 8), (11, 9), (11, 10), (11, 11), (11, 12), (11, 13), (11, 14), (11, 15), (11, 16), (11, 17), (11, 18), (11, 19), (11, 20), (11, 21), (12, 0), (12, 4), (12, 10), (12, 16), (13, 0), (13, 4), (13, 10), (13, 16), (14, 0), (14, 4), (14, 5), (14, 6), (14, 10), (14, 16), (15, 0), (15, 1), (15, 2), (15, 3), (15, 4), (15, 5), (15, 6), (15, 17), (15, 18), (15, 19), (16, 2), (16, 3), (16, 4), (16, 5), (16, 6), (16, 17), (16, 18), (16, 19), (17, 2), (17, 3), (17, 18), (17, 19), (18, 2), (18, 3), (18, 4), (18, 5), (18, 6), (18, 7), (18, 8), (18, 9), (18, 10), (18, 11), (18, 12), (18, 13), (18, 14), (18, 15), (18, 16), (18, 17), (18, 18), (18, 19), (19, 0), (19, 1), (19, 2), (19, 3), (19, 4), (19, 5), (19, 6), (19, 7), (19, 8), (19, 9), (19, 10), (19, 11), (19, 12), (19, 13), (19, 14), (19, 15), (19, 16), (19, 17), (19, 18), (19, 19), (19, 20), (19, 21), (20, 0), (20, 1), (20, 2), (20, 19), (20, 20), (20, 21), (21, 0), (21, 1), (21, 2), (21, 19), (21, 20), (21, 21)] antimagic_zones = [(15, 16), (10, 4), (12, 20)] spinners = [(15, 10), (10, 10)] traps = [(1, 4), (1, 10), (1, 16), (6, 4), (6, 10), (6, 16), (11, 0), (11, 4), (11, 10), (11, 16)] hitpoint_damage = [(21, 1), (21, 2), (21, 3)] spellpoint_restore = [] stasis_chambers = [] random_encounter = [(0, 0), (0, 1), (0, 10), (0, 13), (0, 18), (2, 1), (2, 2), (2, 11), (2, 12), (2, 13), (3, 13), (3, 14), (3, 18), (3, 20), (4, 5), (4, 6), (4, 12), (4, 14), (5, 3), (5, 5), (5, 7), (5, 12), (5, 13), (5, 20), (7, 7), (7, 8), (7, 11), (8, 1), (10, 5), (10, 9), (12, 11), (13, 1), (13, 6), (13, 13), (14, 3), (14, 9), (14, 13), (17, 6), (17, 8), (17, 13), (20, 4), (20, 8), (20, 12), (20, 17)] specials_other = [(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 20), (2, 1), (3, 9), (5, 11), (6, 10), (6, 16), (6, 21), (7, 15), (9, 3), (9, 11), (9, 19), (9, 20), (11, 4), (11, 10), (11, 19), (12, 14), (12, 19), (13, 13), (13, 20), (14, 9), (17, 10), (17, 20), (18, 6)] map = ['+-++-++-++-++-+| .. |+----+| .. |+----+| .. |+----+| .. |+-++----+', '| DD DD DD DD || || || || || || || || DD |', '+-++-++-++-+| |+---S+| .. |+----+| .. |+----+| .. |+---S+| || .. |', '+-----------. .------. .. .----S-. .. .-S----. .. .------. || .. |', '| || |', '| .---------. .---------------. .----------D----. .--------++----+', '| |+-++----+| |+----++-------+| |+-++-++-++D++-+| |+-++----++----+', '| || || || DD || || || || DD DD DD || DD || || |', '| |+S++D---+| || .--++--. .. || |+D++D++-++D++-+| |+D+| .. || .. |', '| |+S--D---+| || |+----+| .. || |+D++D++-++D++-+| |+D+| .. || .. |', '| || || || || || DD || DD DD || SS || || DD || |', '| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-++----++D---+', '| || .. .. || |+D+| .. |+----+| |+D++D++-++-++-+| |+-------++D---+', '| || || || DD || || || || DD DD DD || || || |', '| |+---D--S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |', '| |+---D++S+| |+-++----+| .. || |+D++S++D++-++-+| || .. .. || .. |', '| || || || || DD DD || || || || || DD DD DD || |', '| |+---D++-+| |+-++----++---D+| |+D++-++-++-++-+| |+-------++D---+', '| .----D----. .-------------D-. .-D-------------. .----------D++-+', '| SS |', '| .---------. .-------D--D----. .---------------. .-----------++-+', '| |+-------+| |+------D++D---+| |+-------++----+| |+-------------+', '| || || || || || DD || DD || |', '| || .. .. || || .. .. || .. || || .. .. || .. || || .---------. |', '| || .. .. || || .. .. || .. || || .. .. || .. || || |+-------+| |', '| DD || || || || || || || || || || |', '| |+-------+| |+-------++----+| |+-------++----+| || || .---. || |', '| |+-------+| |+----++-------+| |+-++----++----+| || || |+-+| || |', '| || DD || || || || DD || || || || || DD || |', '| || .. .. || || .. || .. .. || |+-+| .. || .. || || || |+-++-+| |', '| || .. .. || || .. || .. .. || |+-+| .. || .. || || || .------. |', '| || || || || DD || DD || DD || || |', '| |+-------+| |+D---++-------+| |+-++---D++----+| |+D++----------+', '. .---------. .-D-------------. .-------D-------. .-D-------------', ' ', '. .---------. .-D-----------D-. .-D--------D----. .---------------', '| |+-------+| |+D---++------D+| |+D------++D---+| |+----++-++----+', '| || || || || || || || || || DD || |', '| || .. .. || |+---S+| .. .. || || .. .-D+| .. || |+D---++-+| .. |', '| || .. .. || |+---S+| .. .. || || .. |+D+| .. || |+D------+| .. |', '| || || || || || || || || || || DD |', '| |+D------+| |+----++------S+| |+----++-+| .. || || .. .. |+----+', '| |+D------+| .-----++----++S+| |+-------+| .. || || .. .. |+----+', '| || DD || || || || DD || || DD |', '| |+-------++-----. || .. |+-++D++--. .. |+----++S++D------+| .. |', '| .--------------+| || .. |+---D---+| .. |+----++S++D------+| .. |', '| || || || || || DD || || |', '+-----. .. .. .. || || .. || .. .. || .. || .. || || .. .. |+----+', '-----+| .. .. .. || || .. || .. .. || .. || .. || || .. .. |+-----', ' || || DD || || || || || || ', '. .. || .. .-----++-++----++---S---++----++----++-++--. .. || .. .', '. .. || .. |+----++----++----++S---++----++----++----+| .. || .. .', ' DD DD DD DD || || DD DD DD DD ', '. .. || .. |+----++----++----++----++----++----++----+| .. || .. .', '. .. || .. .------------------------------------------. .. || .. .', ' || || ', '-----+| .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. |+-----', '+-----. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .-----+', '| |', '| .. .. .----D--D--------D--D--------D--D--------D--D----. .. .. |', '| .. .. |+---D++D---++---D++D---++---D++D---++---D++D---+| .. .. |', '| || || || || || || || || || |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| || || || || || || || || || |', '+-------++----+| .. |+----+| .. |+----+| .. |+----+| .. |+-------+']
""" Configuration for docs """ # source_link = "https://github.com/[org_name]/college" # docs_base_url = "https://[org_name].github.io/college" # headline = "App that does everything" # sub_heading = "Yes, you got that right the first time, everything" def get_context(context): context.brand_html = "college"
""" Configuration for docs """ def get_context(context): context.brand_html = 'college'
# Given a binary tree, return the level of the tree with minimum sum. class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def min_level_sum(node): min_sum = float('inf') cur_levle = [node] while cur_levle: next_level = [] total = 0 for n in cur_levle: total += n.value if n.left: next_level.append(n.left) if n.right: next_level.append(n.right) if total < min_sum: min_sum = total cur_levle = next_level return min_sum if __name__ == '__main__': tree = Node(23, Node(20, Node(12), Node(8)), Node(5, Node(1))) print(min_level_sum(tree))
class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def min_level_sum(node): min_sum = float('inf') cur_levle = [node] while cur_levle: next_level = [] total = 0 for n in cur_levle: total += n.value if n.left: next_level.append(n.left) if n.right: next_level.append(n.right) if total < min_sum: min_sum = total cur_levle = next_level return min_sum if __name__ == '__main__': tree = node(23, node(20, node(12), node(8)), node(5, node(1))) print(min_level_sum(tree))
#PREPARACION CUARTO LABORATORIO #EJERCICIO 1: def obtener_cadena(): cadena=input("Ingrese cadena deseada: ") if cadena != "fin": if len(cadena)<1: print("ingrese al menos un caracter: ") cadena=input("Ingrese cadena deseada: ") if "1" in cadena or "2" in cadena or "3" in cadena or "4" in cadena or "5" in cadena or "6" in cadena or "7" in cadena or "8" in cadena or "9" in cadena or "0" in cadena: print("No puede ingresar numeros: ") cadena=input("Ingrese cadena deseada: ") print(cadena) if cadena == "fin": print("Ha finalizado la escritura") #obtener_cadena() #EJERCICIO 2: def palindromos (cadena): resultado = [] cadena=cadena.lower().split(" ") for palabra in cadena: if palabra == palabra [::-1]: resultado.append(palabra) return resultado print(palindromos("Hay que reconocer seres extraterrestres"))
def obtener_cadena(): cadena = input('Ingrese cadena deseada: ') if cadena != 'fin': if len(cadena) < 1: print('ingrese al menos un caracter: ') cadena = input('Ingrese cadena deseada: ') if '1' in cadena or '2' in cadena or '3' in cadena or ('4' in cadena) or ('5' in cadena) or ('6' in cadena) or ('7' in cadena) or ('8' in cadena) or ('9' in cadena) or ('0' in cadena): print('No puede ingresar numeros: ') cadena = input('Ingrese cadena deseada: ') print(cadena) if cadena == 'fin': print('Ha finalizado la escritura') def palindromos(cadena): resultado = [] cadena = cadena.lower().split(' ') for palabra in cadena: if palabra == palabra[::-1]: resultado.append(palabra) return resultado print(palindromos('Hay que reconocer seres extraterrestres'))
def comboboxListOptions(window_struct, object_struct,handle=None): if handle == None: result = getObject(window_struct,object_struct) handle = result['handle'] list_options=[] if handle.getChildCount() > 0: for childlvl_1 in range(0,handle.getChildCount()): cur_handle_childlvl_1 = handle.getChildAtIndex(childlvl_1) for childlvl_2 in range(0,cur_handle_childlvl_1.getChildCount()): cur_handle_childlvl_2 = cur_handle_childlvl_1.getChildAtIndex(childlvl_2) list_options.append(cur_handle_childlvl_2.name) return list_options def comboboxGetSelected(window_struct, object_struct,handle=None): if handle == None: result = getObject(window_struct,object_struct) handle = result['handle'] list_options=[] return handle.name
def combobox_list_options(window_struct, object_struct, handle=None): if handle == None: result = get_object(window_struct, object_struct) handle = result['handle'] list_options = [] if handle.getChildCount() > 0: for childlvl_1 in range(0, handle.getChildCount()): cur_handle_childlvl_1 = handle.getChildAtIndex(childlvl_1) for childlvl_2 in range(0, cur_handle_childlvl_1.getChildCount()): cur_handle_childlvl_2 = cur_handle_childlvl_1.getChildAtIndex(childlvl_2) list_options.append(cur_handle_childlvl_2.name) return list_options def combobox_get_selected(window_struct, object_struct, handle=None): if handle == None: result = get_object(window_struct, object_struct) handle = result['handle'] list_options = [] return handle.name
class Foo(object): A = 1 B = 2 def __init__(self): self.class_var = "V" def main(): f = Foo() g = Foo() f.A = 12 g.A = 33 Foo.A = 34 print("f.A: {}".format(f.A)) print("g.A: {}".format(g.A)) print("Foo.A: {}".format(Foo.A)) print("f.class_var: {}".format(f.class_var)) if __name__ == '__main__': main()
class Foo(object): a = 1 b = 2 def __init__(self): self.class_var = 'V' def main(): f = foo() g = foo() f.A = 12 g.A = 33 Foo.A = 34 print('f.A: {}'.format(f.A)) print('g.A: {}'.format(g.A)) print('Foo.A: {}'.format(Foo.A)) print('f.class_var: {}'.format(f.class_var)) if __name__ == '__main__': main()
#!/usr/bin/env python3 #-*- coding: utf-8 -*- """ @Time 15/05/2018 11:41 AM 2018 @Author HJ@USTC @Email jhsa26@mail.ustc.edu.cn @Blog jhsa26.github.io """ class Config(object): def __init__(self): # self.filepath_disp_training = '../DataSet/TrainingData/0.5km/China/disp_combine_gaussian_map_5-10/' self.filepath_disp_training = '../DataSet/TrainingData/0.5km/USA/disp_combine_gaussian_map/' #self.filepath_vs_training = '../DataSet/TrainingData/0.5km/China/vs_curve_5-10/' self.filepath_vs_training = '../DataSet/TrainingData/0.5km/USA/vs_curve/' # self.filepath_disp_pred = '../../DataSet/TestData/real-8s-50s/USA/disp_combine_gaussian_map_utah/' self.filepath_vs_pred = '../DataSet/TestData/real-8-50s/vs_syn_gaussian/' self.filepath_disp_pred = '../DataSet/TestData/real-8s-50s/China/disp_combine_gaussian_map_test_4512/' self.batch_size = 64 # training batch size self.nEpochs = 300 # umber of epochs to train for self.lr = 0.000005 self.seed = 123 # random seed to use. Default=123 self.plot = True self.alpha=0.0000 # damping self.testsize=0.2 self.pretrained =True self.start=600 self.pretrain_net = "./model_para_USA/model_epoch_"+str(self.start)+".pth" if __name__ == '__main__': pass
""" @Time 15/05/2018 11:41 AM 2018 @Author HJ@USTC @Email jhsa26@mail.ustc.edu.cn @Blog jhsa26.github.io """ class Config(object): def __init__(self): self.filepath_disp_training = '../DataSet/TrainingData/0.5km/USA/disp_combine_gaussian_map/' self.filepath_vs_training = '../DataSet/TrainingData/0.5km/USA/vs_curve/' self.filepath_vs_pred = '../DataSet/TestData/real-8-50s/vs_syn_gaussian/' self.filepath_disp_pred = '../DataSet/TestData/real-8s-50s/China/disp_combine_gaussian_map_test_4512/' self.batch_size = 64 self.nEpochs = 300 self.lr = 5e-06 self.seed = 123 self.plot = True self.alpha = 0.0 self.testsize = 0.2 self.pretrained = True self.start = 600 self.pretrain_net = './model_para_USA/model_epoch_' + str(self.start) + '.pth' if __name__ == '__main__': pass
"""Configures the node dependencies for the markdown functionality.""" load("@build_bazel_rules_nodejs//:index.bzl", "node_repositories", "yarn_install") def markdown_register_node_deps(name = "cgrindel_bazel_starlib_markdown_npm"): """Configures the installation of the Javascript node dependencies for the markdown functionality. Args: name: Optional. The name of the `yarn` repository that will be defined. """ node_repositories( node_version = "16.13.2", yarn_version = "1.22.17", ) yarn_install( name = name, package_json = "@cgrindel_bazel_starlib//markdown/private:package.json", yarn_lock = "@cgrindel_bazel_starlib//markdown/private:yarn.lock", )
"""Configures the node dependencies for the markdown functionality.""" load('@build_bazel_rules_nodejs//:index.bzl', 'node_repositories', 'yarn_install') def markdown_register_node_deps(name='cgrindel_bazel_starlib_markdown_npm'): """Configures the installation of the Javascript node dependencies for the markdown functionality. Args: name: Optional. The name of the `yarn` repository that will be defined. """ node_repositories(node_version='16.13.2', yarn_version='1.22.17') yarn_install(name=name, package_json='@cgrindel_bazel_starlib//markdown/private:package.json', yarn_lock='@cgrindel_bazel_starlib//markdown/private:yarn.lock')
#Answer Key #1.1 print (100 * 1.02 ** 8) #1.2 pig3 = "2.85" print(type(pig3)) float(pig3) print(pig3) #1.3 hall = 6.25 kit = 11.0 liv = 40.0 bed = 17.75 bath = 11.50 # Adapt list areas areas = [str("hallway"),hall, "kitchen", kit, str("living room"), liv, "bedroom",bed, str("bathroom"),bath] #Still need to convert to string, but can actually do calculation within the string conversion... print ("The sum area of bedroom and bathroom is "+ str(areas[-1]+areas[-3]) + " square meters.") #1.4 Jerry = 102 Jason = 100 Mary = "A" Molly = "A-" Martin = "B+" Shin = "C-" Shook = 65 Foster = 51 grades = ["Jerry", Jerry, "Jason", Jason, "Mary", Mary, "Molly", Molly, "Martin", Martin, "Shin", Shin,"Shook", Shook, "Foster", Foster] print (grades) okstudent = grades[:12] print(okstudent) notokstudent = grades[12:] print(notokstudent) #1.5 pig= "PiGgy" smallpig = pig.lower() print(smallpig) #because python discriminates upper and lower case letter, use the following code will do the work bigpig= pig.upper() print(bigpig.count("G"))
print(100 * 1.02 ** 8) pig3 = '2.85' print(type(pig3)) float(pig3) print(pig3) hall = 6.25 kit = 11.0 liv = 40.0 bed = 17.75 bath = 11.5 areas = [str('hallway'), hall, 'kitchen', kit, str('living room'), liv, 'bedroom', bed, str('bathroom'), bath] print('The sum area of bedroom and bathroom is ' + str(areas[-1] + areas[-3]) + ' square meters.') jerry = 102 jason = 100 mary = 'A' molly = 'A-' martin = 'B+' shin = 'C-' shook = 65 foster = 51 grades = ['Jerry', Jerry, 'Jason', Jason, 'Mary', Mary, 'Molly', Molly, 'Martin', Martin, 'Shin', Shin, 'Shook', Shook, 'Foster', Foster] print(grades) okstudent = grades[:12] print(okstudent) notokstudent = grades[12:] print(notokstudent) pig = 'PiGgy' smallpig = pig.lower() print(smallpig) bigpig = pig.upper() print(bigpig.count('G'))
favorite_languages = { 'jen': 'Python', 'sarah': 'C', 'edward': 'Ruby', 'phil': 'Python' } for name in favorite_languages.keys(): print(name.title()) for value in favorite_languages.values(): print(value.title()) # print(f"\n Sarah's favorite languages is " + favorite_languages['sarah'].title() + ".\n")
favorite_languages = {'jen': 'Python', 'sarah': 'C', 'edward': 'Ruby', 'phil': 'Python'} for name in favorite_languages.keys(): print(name.title()) for value in favorite_languages.values(): print(value.title())
class rectangle(): def __init__(self, length, breadth): self.length = length self.breadth = breadth def area(self): return self.length * self.breadth a = int(input("Enter length of rectangle : ")) b = int(input("Enter a breadth of rectangle : ")) obj = rectangle(a, b) print("Area of rectangle : ", obj.area())
class Rectangle: def __init__(self, length, breadth): self.length = length self.breadth = breadth def area(self): return self.length * self.breadth a = int(input('Enter length of rectangle : ')) b = int(input('Enter a breadth of rectangle : ')) obj = rectangle(a, b) print('Area of rectangle : ', obj.area())
# Program to check if a is a primitive root mod q # Written by Benjamin Mestdagh def calculate(a, q): powers = [] for i in range(1, q): result = (a**i) % q if result in powers: return False else: powers.append(result) return True try: a = int(input("Enter a: ")) q = int(input("Enter q: ")) result = calculate(a,q) if result: print('{0} is a primitive root mod {1}'.format(a, q)) else: print('{0} is NOT a primitive root mod {1}'.format(a,q)) except: print("Error")
def calculate(a, q): powers = [] for i in range(1, q): result = a ** i % q if result in powers: return False else: powers.append(result) return True try: a = int(input('Enter a: ')) q = int(input('Enter q: ')) result = calculate(a, q) if result: print('{0} is a primitive root mod {1}'.format(a, q)) else: print('{0} is NOT a primitive root mod {1}'.format(a, q)) except: print('Error')
nums=[2,3,3,4] def combines(nums): assert(nums) if len(nums) == 1: return [(nums[0], [])] out = [] for i in range(1,len(nums)): for j in range(i): n1 = nums[j] n2 = nums[i] if nums.index(n1) != j: continue if nums.index(n2) not in [i,j]: continue other_nums = nums[:j] + nums[j+1:i] + nums[i+1:] options = [ (n1+n2, "{}+{}".format(n1, n2)), (n1-n2, "{}-{}".format(n1, n2)), (n2-n1, "{}-{}".format(n2, n1)), (n1*n2, "{}*{}".format(n1, n2)), ] if n1 >= 0 and n2 <= 32 and not (n1 == 0 and n2 < 0): options.append((n1**n2, "{}^{}".format(n1, n2))) if n2 >= 0 and n1 <= 32 and not (n2 == 0 and n1 < 0): options.append((n2**n1, "{}^{}".format(n2, n1))) if n2 != 0: options.append((n1/n2, "{}/{}".format(n1, n2))) if n1 != 0: options.append((n2/n1, "{}/{}".format(n2, n1))) for (n, s) in options: assert(n > 0 or n <= 0) new_nums = other_nums + [n] assert(len(new_nums) == len(nums) - 1) results = combines(new_nums) for (result, method) in results: p = (result, [s] + method) out.append(p) return out results = combines([2,3,3,4]) for result, method in results: if result == 24: print(result, method)
nums = [2, 3, 3, 4] def combines(nums): assert nums if len(nums) == 1: return [(nums[0], [])] out = [] for i in range(1, len(nums)): for j in range(i): n1 = nums[j] n2 = nums[i] if nums.index(n1) != j: continue if nums.index(n2) not in [i, j]: continue other_nums = nums[:j] + nums[j + 1:i] + nums[i + 1:] options = [(n1 + n2, '{}+{}'.format(n1, n2)), (n1 - n2, '{}-{}'.format(n1, n2)), (n2 - n1, '{}-{}'.format(n2, n1)), (n1 * n2, '{}*{}'.format(n1, n2))] if n1 >= 0 and n2 <= 32 and (not (n1 == 0 and n2 < 0)): options.append((n1 ** n2, '{}^{}'.format(n1, n2))) if n2 >= 0 and n1 <= 32 and (not (n2 == 0 and n1 < 0)): options.append((n2 ** n1, '{}^{}'.format(n2, n1))) if n2 != 0: options.append((n1 / n2, '{}/{}'.format(n1, n2))) if n1 != 0: options.append((n2 / n1, '{}/{}'.format(n2, n1))) for (n, s) in options: assert n > 0 or n <= 0 new_nums = other_nums + [n] assert len(new_nums) == len(nums) - 1 results = combines(new_nums) for (result, method) in results: p = (result, [s] + method) out.append(p) return out results = combines([2, 3, 3, 4]) for (result, method) in results: if result == 24: print(result, method)
df_referendum['Department code'] = df_referendum['Department code'].apply( lambda x: '0' + x if len(x) == 1 else x ) df_referendum.head()
df_referendum['Department code'] = df_referendum['Department code'].apply(lambda x: '0' + x if len(x) == 1 else x) df_referendum.head()
size = int(input()) matrix = [ [int(_) for _ in input().split()] for i in range(size) ] bombs = [_.split(",") for _ in input().split()] for bomb in bombs: current_bomb = matrix[int(bomb[0])][int(bomb[1])] c_b_row = int(bomb[0]) c_b_col = int(bomb[1]) damage = current_bomb around_squares = [ (c_b_row-1, c_b_col -1), (c_b_row-1, c_b_col), (c_b_row-1, c_b_col +1), (c_b_row, c_b_col - 1), (c_b_row, c_b_col +1), (c_b_row + 1, c_b_col - 1), (c_b_row+1, c_b_col), (c_b_row+1, c_b_col +1) ] for square in around_squares: row = square[0] col = square[1] if (row < 0 or row > size-1) or (col < 0 or col > size-1): continue current_square = matrix[row][col] if current_square > 0: matrix[row][col] -= damage matrix[int(bomb[0])][int(bomb[1])] = 0 alive_cells = [] for i in matrix: for j in i: if j > 0: alive_cells.append(j) print(f"Alive cells: {len(alive_cells)}") print(f"Sum: {sum(alive_cells)}") print('\n'.join([' '.join(map(str, m)) for m in matrix]))
size = int(input()) matrix = [[int(_) for _ in input().split()] for i in range(size)] bombs = [_.split(',') for _ in input().split()] for bomb in bombs: current_bomb = matrix[int(bomb[0])][int(bomb[1])] c_b_row = int(bomb[0]) c_b_col = int(bomb[1]) damage = current_bomb around_squares = [(c_b_row - 1, c_b_col - 1), (c_b_row - 1, c_b_col), (c_b_row - 1, c_b_col + 1), (c_b_row, c_b_col - 1), (c_b_row, c_b_col + 1), (c_b_row + 1, c_b_col - 1), (c_b_row + 1, c_b_col), (c_b_row + 1, c_b_col + 1)] for square in around_squares: row = square[0] col = square[1] if (row < 0 or row > size - 1) or (col < 0 or col > size - 1): continue current_square = matrix[row][col] if current_square > 0: matrix[row][col] -= damage matrix[int(bomb[0])][int(bomb[1])] = 0 alive_cells = [] for i in matrix: for j in i: if j > 0: alive_cells.append(j) print(f'Alive cells: {len(alive_cells)}') print(f'Sum: {sum(alive_cells)}') print('\n'.join([' '.join(map(str, m)) for m in matrix]))
description = 'resolution args of chopper real table' group = 'lowlevel' includes = ['chopper', 'detector', 'real_flight_path'] devices = dict( resolution = device('nicos_mlz.refsans.devices.resolution.Resolution', description = description, chopper = 'chopper', flightpath = 'real_flight_path', ), )
description = 'resolution args of chopper real table' group = 'lowlevel' includes = ['chopper', 'detector', 'real_flight_path'] devices = dict(resolution=device('nicos_mlz.refsans.devices.resolution.Resolution', description=description, chopper='chopper', flightpath='real_flight_path'))
def main(): # input N = int(input()) As = [*map(int, input().split())] # compute studentss = [] for i, A in enumerate(As): studentss.append([A, i]) anss = [] for _, num in sorted(studentss): anss.append(num + 1) # output print(*anss) if __name__ == '__main__': main()
def main(): n = int(input()) as = [*map(int, input().split())] studentss = [] for (i, a) in enumerate(As): studentss.append([A, i]) anss = [] for (_, num) in sorted(studentss): anss.append(num + 1) print(*anss) if __name__ == '__main__': main()
expected_output = { "ip_statistics": { "ip_rcvd_total": 2823, "ip_rcvd_local_destination": 2823, "ip_rcvd_format_errors": 0, "ip_rcvd_checksum_errors": 0, "ip_rcvd_bad_hop": 0, "ip_rcvd_unknwn_protocol": 0, "ip_rcvd_not_gateway": 0, "ip_rcvd_sec_failures": 0, "ip_rcvd_bad_optns": 0, "ip_rcvd_with_optns": 0, "ip_opts_end": 0, "ip_opts_nop": 0, "ip_opts_basic_security": 0, "ip_opts_loose_src_route": 0, "ip_opts_timestamp": 0, "ip_opts_extended_security": 0, "ip_opts_record_route": 0, "ip_opts_strm_id": 0, "ip_opts_strct_src_route": 0, "ip_opts_alert": 0, "ip_opts_cipso": 0, "ip_opts_ump": 0, "ip_opts_other": 0, "ip_frags_reassembled": 0, "ip_frags_timeouts": 0, "ip_frags_no_reassembled": 0, "ip_frags_fragmented": 0, "ip_frags_fragments": 0, "ip_frags_no_fragmented": 0, "ip_bcast_received": 0, "ip_bcast_sent": 0, "ip_mcast_received": 78, "ip_mcast_sent": 75, "ip_sent_generated": 2799, "ip_sent_forwarded": 0, "ip_drop_encap_failed": 1, "ip_drop_unresolved": 0, "ip_drop_no_adj": 0, "ip_drop_no_route": 0, "ip_drop_unicast_rpf": 0, "ip_drop_forced_drop": 0, "ip_drop_opts_denied": 0, }, "icmp_statistics": { "icmp_received_format_errors": 0, "icmp_received_checksum_errors": 0, "icmp_received_redirects": 0, "icmp_received_unreachable": 0, "icmp_received_echo": 0, "icmp_received_echo_reply": 0, "icmp_received_mask_requests": 0, "icmp_received_mask_replies": 0, "icmp_received_quench": 0, "icmp_received_parameter": 0, "icmp_received_timestamp": 0, "icmp_received_info_request": 0, "icmp_received_other": 0, "icmp_received_irdp_solicitations": 0, "icmp_received_irdp_advertisements": 0, "icmp_sent_redirects": 0, "icmp_sent_unreachable": 0, "icmp_sent_echo": 0, "icmp_sent_echo_reply": 0, "icmp_sent_mask_requests": 0, "icmp_sent_mask_replies": 0, "icmp_sent_quench": 0, "icmp_sent_timestamp": 0, "icmp_sent_info_reply": 0, "icmp_sent_time_exceeded": 0, "icmp_sent_parameter_problem": 0, "icmp_sent_irdp_solicitations": 0, "icmp_sent_irdp_advertisements": 0, }, "tcp_statistics": { "tcp_received_total": 2739, "tcp_received_checksum_errors": 0, "tcp_received_no_port": 2, "tcp_sent_total": 2718, }, "bgp_statistics": { "bgp_received_total": 0, "bgp_received_opens": 0, "bgp_received_notifications": 0, "bgp_received_updates": 0, "bgp_received_keepalives": 0, "bgp_received_route_refresh": 0, "bgp_received_unrecognized": 0, "bgp_sent_total": 0, "bgp_sent_opens": 0, "bgp_sent_notifications": 0, "bgp_sent_updates": 0, "bgp_sent_keepalives": 0, "bgp_sent_route_refresh": 0, }, "eigrp_ipv4_statistics": { "eigrp_ipv4_received_total": 0, "eigrp_ipv4_sent_total": 0, }, "pimv2_statistics": { "pimv2_total": "0/0", "pimv2_checksum_errors": 0, "pimv2_format_errors": 0, "pimv2_registers": "0/0", "pimv2_non_rp": 0, "pimv2_non_sm_group": 0, "pimv2_registers_stops": "0/0", "pimv2_hellos": "0/0", "pimv2_join_prunes": "0/0", "pimv2_asserts": "0/0", "pimv2_grafts": "0/0", "pimv2_bootstraps": "0/0", "pimv2_candidate_rp_advs": "0/0", "pimv2_queue_drops": 0, "pimv2_state_refresh": "0/0", }, "igmp_statistics": { "igmp_total": "0/0", "igmp_format_errors": "0/0", "igmp_checksum_errors": "0/0", "igmp_host_queries": "0/0", "igmp_host_reports": "0/0", "igmp_host_leaves": "0/0", "igmp_dvmrp": "0/0", "igmp_pim": "0/0", "igmp_queue_drops": 0, }, "udp_statistics": { "udp_received_total": 0, "udp_received_udp_checksum_errors": 0, "udp_received_no_port": 0, "udp_sent_total": 0, "udp_sent_fwd_broadcasts": 0, }, "ospf_statistics": { "ospf_received_total": 84, "ospf_received_checksum_errors": 0, "ospf_received_hello": 74, "ospf_received_database_desc": 3, "ospf_received_link_state_req": 1, "ospf_received_lnk_st_updates": 5, "ospf_received_lnk_st_acks": 1, "ospf_sent_total": 82, "ospf_sent_hello": 74, "ospf_sent_database_desc": 4, "ospf_sent_lnk_st_acks": 2, "ospf_sent_lnk_st_updates": 2, }, "arp_statistics": { "arp_in_requests": 40, "arp_in_replies": 4, "arp_in_reverse": 0, "arp_in_other": 0, "arp_out_requests": 1, "arp_out_replies": 4, "arp_out_proxy": 0, "arp_out_reverse": 0, }, }
expected_output = {'ip_statistics': {'ip_rcvd_total': 2823, 'ip_rcvd_local_destination': 2823, 'ip_rcvd_format_errors': 0, 'ip_rcvd_checksum_errors': 0, 'ip_rcvd_bad_hop': 0, 'ip_rcvd_unknwn_protocol': 0, 'ip_rcvd_not_gateway': 0, 'ip_rcvd_sec_failures': 0, 'ip_rcvd_bad_optns': 0, 'ip_rcvd_with_optns': 0, 'ip_opts_end': 0, 'ip_opts_nop': 0, 'ip_opts_basic_security': 0, 'ip_opts_loose_src_route': 0, 'ip_opts_timestamp': 0, 'ip_opts_extended_security': 0, 'ip_opts_record_route': 0, 'ip_opts_strm_id': 0, 'ip_opts_strct_src_route': 0, 'ip_opts_alert': 0, 'ip_opts_cipso': 0, 'ip_opts_ump': 0, 'ip_opts_other': 0, 'ip_frags_reassembled': 0, 'ip_frags_timeouts': 0, 'ip_frags_no_reassembled': 0, 'ip_frags_fragmented': 0, 'ip_frags_fragments': 0, 'ip_frags_no_fragmented': 0, 'ip_bcast_received': 0, 'ip_bcast_sent': 0, 'ip_mcast_received': 78, 'ip_mcast_sent': 75, 'ip_sent_generated': 2799, 'ip_sent_forwarded': 0, 'ip_drop_encap_failed': 1, 'ip_drop_unresolved': 0, 'ip_drop_no_adj': 0, 'ip_drop_no_route': 0, 'ip_drop_unicast_rpf': 0, 'ip_drop_forced_drop': 0, 'ip_drop_opts_denied': 0}, 'icmp_statistics': {'icmp_received_format_errors': 0, 'icmp_received_checksum_errors': 0, 'icmp_received_redirects': 0, 'icmp_received_unreachable': 0, 'icmp_received_echo': 0, 'icmp_received_echo_reply': 0, 'icmp_received_mask_requests': 0, 'icmp_received_mask_replies': 0, 'icmp_received_quench': 0, 'icmp_received_parameter': 0, 'icmp_received_timestamp': 0, 'icmp_received_info_request': 0, 'icmp_received_other': 0, 'icmp_received_irdp_solicitations': 0, 'icmp_received_irdp_advertisements': 0, 'icmp_sent_redirects': 0, 'icmp_sent_unreachable': 0, 'icmp_sent_echo': 0, 'icmp_sent_echo_reply': 0, 'icmp_sent_mask_requests': 0, 'icmp_sent_mask_replies': 0, 'icmp_sent_quench': 0, 'icmp_sent_timestamp': 0, 'icmp_sent_info_reply': 0, 'icmp_sent_time_exceeded': 0, 'icmp_sent_parameter_problem': 0, 'icmp_sent_irdp_solicitations': 0, 'icmp_sent_irdp_advertisements': 0}, 'tcp_statistics': {'tcp_received_total': 2739, 'tcp_received_checksum_errors': 0, 'tcp_received_no_port': 2, 'tcp_sent_total': 2718}, 'bgp_statistics': {'bgp_received_total': 0, 'bgp_received_opens': 0, 'bgp_received_notifications': 0, 'bgp_received_updates': 0, 'bgp_received_keepalives': 0, 'bgp_received_route_refresh': 0, 'bgp_received_unrecognized': 0, 'bgp_sent_total': 0, 'bgp_sent_opens': 0, 'bgp_sent_notifications': 0, 'bgp_sent_updates': 0, 'bgp_sent_keepalives': 0, 'bgp_sent_route_refresh': 0}, 'eigrp_ipv4_statistics': {'eigrp_ipv4_received_total': 0, 'eigrp_ipv4_sent_total': 0}, 'pimv2_statistics': {'pimv2_total': '0/0', 'pimv2_checksum_errors': 0, 'pimv2_format_errors': 0, 'pimv2_registers': '0/0', 'pimv2_non_rp': 0, 'pimv2_non_sm_group': 0, 'pimv2_registers_stops': '0/0', 'pimv2_hellos': '0/0', 'pimv2_join_prunes': '0/0', 'pimv2_asserts': '0/0', 'pimv2_grafts': '0/0', 'pimv2_bootstraps': '0/0', 'pimv2_candidate_rp_advs': '0/0', 'pimv2_queue_drops': 0, 'pimv2_state_refresh': '0/0'}, 'igmp_statistics': {'igmp_total': '0/0', 'igmp_format_errors': '0/0', 'igmp_checksum_errors': '0/0', 'igmp_host_queries': '0/0', 'igmp_host_reports': '0/0', 'igmp_host_leaves': '0/0', 'igmp_dvmrp': '0/0', 'igmp_pim': '0/0', 'igmp_queue_drops': 0}, 'udp_statistics': {'udp_received_total': 0, 'udp_received_udp_checksum_errors': 0, 'udp_received_no_port': 0, 'udp_sent_total': 0, 'udp_sent_fwd_broadcasts': 0}, 'ospf_statistics': {'ospf_received_total': 84, 'ospf_received_checksum_errors': 0, 'ospf_received_hello': 74, 'ospf_received_database_desc': 3, 'ospf_received_link_state_req': 1, 'ospf_received_lnk_st_updates': 5, 'ospf_received_lnk_st_acks': 1, 'ospf_sent_total': 82, 'ospf_sent_hello': 74, 'ospf_sent_database_desc': 4, 'ospf_sent_lnk_st_acks': 2, 'ospf_sent_lnk_st_updates': 2}, 'arp_statistics': {'arp_in_requests': 40, 'arp_in_replies': 4, 'arp_in_reverse': 0, 'arp_in_other': 0, 'arp_out_requests': 1, 'arp_out_replies': 4, 'arp_out_proxy': 0, 'arp_out_reverse': 0}}
experiment_ID = "transfer_learning_6" mc_run_number = 50 babbling_time = 3 number_of_refinements = 5 errors_all_A_A = np.zeros([2, number_of_refinements+1, mc_run_number]) errors_all_A_B = np.zeros([2, number_of_refinements+1, mc_run_number]) errors_all_B_B = np.zeros([2, number_of_refinements+1, mc_run_number]) stiffness_version_A = 5 MuJoCo_model_name_A="nmi_leg_w_chassis_air_v{}.xml".format(stiffness_version_A) stiffness_version_B = 2 MuJoCo_model_name_B="nmi_leg_w_chassis_air_v{}.xml".format(stiffness_version_B)
experiment_id = 'transfer_learning_6' mc_run_number = 50 babbling_time = 3 number_of_refinements = 5 errors_all_a_a = np.zeros([2, number_of_refinements + 1, mc_run_number]) errors_all_a_b = np.zeros([2, number_of_refinements + 1, mc_run_number]) errors_all_b_b = np.zeros([2, number_of_refinements + 1, mc_run_number]) stiffness_version_a = 5 mu_jo_co_model_name_a = 'nmi_leg_w_chassis_air_v{}.xml'.format(stiffness_version_A) stiffness_version_b = 2 mu_jo_co_model_name_b = 'nmi_leg_w_chassis_air_v{}.xml'.format(stiffness_version_B)
__all__ = ['EvaluationDistance'] # Work in progress class EvaluationDistance: def __init__(self): self.arg_map = {} def set_arg_map(self, value): self.arg_map.update(value) def preprocess(self, x): raise NotImplementedError def calculate_distance(self, x1, x2): raise NotImplementedError def metric_ops(self, generator, **kwargs): raise NotImplementedError def __call__(self, x1, x2): return self.calculate_distance(self.preprocess(x1), self.preprocess(x2))
__all__ = ['EvaluationDistance'] class Evaluationdistance: def __init__(self): self.arg_map = {} def set_arg_map(self, value): self.arg_map.update(value) def preprocess(self, x): raise NotImplementedError def calculate_distance(self, x1, x2): raise NotImplementedError def metric_ops(self, generator, **kwargs): raise NotImplementedError def __call__(self, x1, x2): return self.calculate_distance(self.preprocess(x1), self.preprocess(x2))
salario = float(input()) if salario >= 0 and salario <= 2000: print("Isento") else: valor_ir = 0 if salario > 4500: valor_ir += (salario - 4500) * 0.28 salario = 4500 if salario >= 3000.01 and salario <= 4500: valor_ir += (salario - 3000.01) * 0.18 salario = 3000 if salario >= 2000.01 and salario <= 3000: valor_ir += (salario - 2000.01) * 0.08 salario = 2000 print("R$ %.2f" % (valor_ir))
salario = float(input()) if salario >= 0 and salario <= 2000: print('Isento') else: valor_ir = 0 if salario > 4500: valor_ir += (salario - 4500) * 0.28 salario = 4500 if salario >= 3000.01 and salario <= 4500: valor_ir += (salario - 3000.01) * 0.18 salario = 3000 if salario >= 2000.01 and salario <= 3000: valor_ir += (salario - 2000.01) * 0.08 salario = 2000 print('R$ %.2f' % valor_ir)
# AUTOGENERATED! DO NOT EDIT! File to edit: notebooks/Infousa.ipynb (unless otherwise specified). __all__ = ['totemp', 'totemp', 'totemp', 'totemp', 'sml', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'biz1', 'biz1', 'biz1', 'biz1', 'biz1', 'biz2', 'biz2', 'biz2', 'biz2', 'biz2', 'biz4', 'biz4', 'biz4', 'biz4', 'biz4', 'neiind', 'neiind', 'neiind', 'neiind', 'neiind', 'neiind', 'neibus', 'neibus', 'neibus', 'neibus', 'neibus', 'neibus', 'neiemp', 'neiemp', 'neiemp', 'neiemp', 'neiemp', 'neiemp'] # Cell infoUsaCsaTotals.to_csv('numbus18.csv', index=False) # Cell # Aggregate Numeric Values by Sum totemp = infoUsaCsa.groupby('CSA2010')[ ['CSA2010','empl_size'] ].sum(numeric_only=True) totemp = totemp.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) totemp = totemp.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'empl_size': totemp['empl_size'].sum() }, ignore_index=True) totemp['totemp'] = totemp['empl_size'] totemp = totemp.drop('empl_size', axis=1) totemp.tail() # Cell sml = infoUsaCsa.copy() smlbus = sml[ ( sml['empl_rng'].isin(['1 to 4']) ) ] smlbus.to_csv('smlbus_empl_rng1 to 4.csv') print('empl_rng 1 to 4: ', smlbus.size / len(smlbus.columns) ) # Cell smlbus = sml[ ( sml['empl_rng'].isin(['5 to 9']) ) ] smlbus.to_csv('smlbus_empl_rng5 to 9.csv') print('empl_rng 5 to 9: ', smlbus.size / len(smlbus.columns) ) # Cell smlbus = sml[ ( sml['empl_rng'].isin(['10 to 19']) ) ] smlbus.to_csv('smlbus_empl_rng10 to 19.csv') print('empl_rng 10 to 19: ', smlbus.size / len(smlbus.columns) ) # Cell smlbus = sml[ ( sml['empl_rng'].isin(['20 to 49']) ) ] smlbus.to_csv('smlbus_empl_rng20 to 49.csv') print('empl_rng 20 to 49: ', smlbus.size / len(smlbus.columns) ) # Cell # Filter for small businesses smlbus = sml[ ( sml['empl_rng'].isin(['1 to 4', '5 to 9', '10 to 19', '20 to 49']) ) ] smlbus.to_csv('smlbus18_filtered_points.csv') print('empl_rng 1 to 49: ', smlbus.size / len(smlbus.columns) ) # Cell # Aggregate Numeric Values by Sum smlbus['smlbus'] = 1 smlbus = smlbus.groupby('CSA2010')[ ['CSA2010','smlbus'] ].sum(numeric_only=True) smlbus = smlbus.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) smlbus = smlbus.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'smlbus': gdf2['smlbus'].sum() }, ignore_index=True) smlbus.tail() # Cell # 145 -biz1XX # Filter for small businesses biz1 = infoUsaCsa[ ( infoUsaCsa['first_year'].isin( ['2018'] ) ) ] print('Count: first_year == 2018: ', biz1.size / len(biz1.columns) ) biz1 = biz1[ ['CSA2010'] ] #numerator.to_csv('biz18_numerator_csasWithCounts.csv') biz1['biz1Count'] = 1 # Cell # Aggregate Numeric Values by Sum biz1 = biz1.groupby('CSA2010').sum(numeric_only=True) biz1 = biz1.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) biz1 = biz1.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'biz1Count': biz1['biz1Count'].mean() }, ignore_index=True) biz1.tail(1) # Cell # Create the Indicator biz1['biz1'] = biz1['biz1Count'] / infoUsaCsaTotals['numbus'] biz1.head() # Cell # 151 - biz2XX # Filter for small businesses biz2 = infoUsaCsa[ ( infoUsaCsa['first_year'].isin( ['2016', '2017', '2018'] ) ) ] print('Count: first_year == 2018, 2017, 2016: ', biz2.size / len(biz2.columns) ) biz2 = biz2[ ['CSA2010'] ] #numerator.to_csv('biz18_numerator_csasWithCounts.csv') biz2['biz2Count'] = 1 # Cell # Aggregate Numeric Values by Sum biz2 = biz2.groupby('CSA2010').sum(numeric_only=True) biz2 = biz2.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) biz2 = biz2.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'biz2Count': biz2['biz2Count'].mean() }, ignore_index=True) biz2.tail(1) # Cell # 152 - biz4XX # Filter for small businesses biz4 = infoUsaCsa[ ( infoUsaCsa['first_year'].isin( ['2015', '2016', '2017', '2018'] ) ) ] print('Count: first_year == 2018, 2017, 2016, 2015: ', biz2.size / len(biz2.columns) ) biz4 = biz4[ ['CSA2010'] ] #numerator.to_csv('biz18_numerator_csasWithCounts.csv') biz4['biz4Count'] = 1 # Cell # Aggregate Numeric Values by Sum biz4 = biz4.groupby('CSA2010').sum(numeric_only=True) biz4 = biz4.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) biz4 = biz4.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'biz4Count': biz4['biz4Count'].mean() }, ignore_index=True) biz4.tail(1) # Cell # 157 - neiindXX # Filter for small businesses neiind = infoUsaCsa.copy() neiind['naics_extra_short'] = neiind.prim_naics.astype(str).str[:-6].astype(np.int64) neiind = infoUsaCsa[ ( neiind['naics_extra_short'].isin( [44, 45, 52, 54, 62, 71, 72, 81] ) ) ] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neiind.size / len(neiind.columns) ) neiind = neiind[ ['CSA2010'] ] #numerator.to_csv('biz18_numerator_csasWithCounts.csv') neiind['neiind'] = 1 # Cell # Aggregate Numeric Values by Sum neiind = neiind.groupby('CSA2010').sum(numeric_only=True) neiind = neiind.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) neiind = neiind.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'neiind': neiind['neiind'].sum() }, ignore_index=True) neiind.tail(1) # Cell # 158 - neibus # Filter for small businesses neibus = infoUsaCsa.copy() neibus['naics_extra_short'] = neibus.prim_naics.astype(str).str[:-6].astype(np.int64) neibus = infoUsaCsa[ ( neibus['naics_extra_short'].isin( [44, 45, 52, 54, 62, 71, 72, 81] ) ) ] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neibus.size / len(neibus.columns) ) neibus = neibus[ ['CSA2010'] ] #numerator.to_csv('biz18_numerator_csasWithCounts.csv') neibus['neibus'] = 1 neibus.head() # Cell # Aggregate Numeric Values by Sum neibus = neibus.groupby('CSA2010').sum(numeric_only=True) neibus = neibus.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) neibus = neibus.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'neibus': neibus['neibus'].sum() }, ignore_index=True) neibus['neibus'] = neibus['neibus'] * 1000 / neibus['tpop10'] neibus.tail(1) # Cell # 159 - neiempXX # Filter for small businesses neiemp = infoUsaCsa.copy() neiemp['naics_extra_short'] = neiemp.prim_naics.astype(str).str[:-6].astype(np.int64) neiemp = infoUsaCsa[ ( neiemp['naics_extra_short'].isin( [44, 45, 52, 54, 62, 71, 72, 81] ) ) ] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neiemp.size / len(neiemp.columns) ) #numerator.to_csv('biz18_numerator_csasWithCounts.csv') # Cell # Aggregate Numeric Values by Sum neiemp = neiemp.groupby('CSA2010')[ ['CSA2010','empl_size'] ].sum(numeric_only=True) neiemp = neiemp.merge( csa[ ['CSA2010','tpop10'] ], left_on='CSA2010', right_on='CSA2010' ) neiemp = neiemp.append( {'CSA2010': 'Baltimore City' , 'tpop10' : 620961, 'empl_size': neiemp['empl_size'].sum() }, ignore_index=True) neiemp['neiemp'] = neiemp['empl_size'] neiemp = neiemp.drop('empl_size', axis=1) neiemp.tail()
__all__ = ['totemp', 'totemp', 'totemp', 'totemp', 'sml', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'smlbus', 'biz1', 'biz1', 'biz1', 'biz1', 'biz1', 'biz2', 'biz2', 'biz2', 'biz2', 'biz2', 'biz4', 'biz4', 'biz4', 'biz4', 'biz4', 'neiind', 'neiind', 'neiind', 'neiind', 'neiind', 'neiind', 'neibus', 'neibus', 'neibus', 'neibus', 'neibus', 'neibus', 'neiemp', 'neiemp', 'neiemp', 'neiemp', 'neiemp', 'neiemp'] infoUsaCsaTotals.to_csv('numbus18.csv', index=False) totemp = infoUsaCsa.groupby('CSA2010')[['CSA2010', 'empl_size']].sum(numeric_only=True) totemp = totemp.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') totemp = totemp.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'empl_size': totemp['empl_size'].sum()}, ignore_index=True) totemp['totemp'] = totemp['empl_size'] totemp = totemp.drop('empl_size', axis=1) totemp.tail() sml = infoUsaCsa.copy() smlbus = sml[sml['empl_rng'].isin(['1 to 4'])] smlbus.to_csv('smlbus_empl_rng1 to 4.csv') print('empl_rng 1 to 4: ', smlbus.size / len(smlbus.columns)) smlbus = sml[sml['empl_rng'].isin(['5 to 9'])] smlbus.to_csv('smlbus_empl_rng5 to 9.csv') print('empl_rng 5 to 9: ', smlbus.size / len(smlbus.columns)) smlbus = sml[sml['empl_rng'].isin(['10 to 19'])] smlbus.to_csv('smlbus_empl_rng10 to 19.csv') print('empl_rng 10 to 19: ', smlbus.size / len(smlbus.columns)) smlbus = sml[sml['empl_rng'].isin(['20 to 49'])] smlbus.to_csv('smlbus_empl_rng20 to 49.csv') print('empl_rng 20 to 49: ', smlbus.size / len(smlbus.columns)) smlbus = sml[sml['empl_rng'].isin(['1 to 4', '5 to 9', '10 to 19', '20 to 49'])] smlbus.to_csv('smlbus18_filtered_points.csv') print('empl_rng 1 to 49: ', smlbus.size / len(smlbus.columns)) smlbus['smlbus'] = 1 smlbus = smlbus.groupby('CSA2010')[['CSA2010', 'smlbus']].sum(numeric_only=True) smlbus = smlbus.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') smlbus = smlbus.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'smlbus': gdf2['smlbus'].sum()}, ignore_index=True) smlbus.tail() biz1 = infoUsaCsa[infoUsaCsa['first_year'].isin(['2018'])] print('Count: first_year == 2018: ', biz1.size / len(biz1.columns)) biz1 = biz1[['CSA2010']] biz1['biz1Count'] = 1 biz1 = biz1.groupby('CSA2010').sum(numeric_only=True) biz1 = biz1.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') biz1 = biz1.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'biz1Count': biz1['biz1Count'].mean()}, ignore_index=True) biz1.tail(1) biz1['biz1'] = biz1['biz1Count'] / infoUsaCsaTotals['numbus'] biz1.head() biz2 = infoUsaCsa[infoUsaCsa['first_year'].isin(['2016', '2017', '2018'])] print('Count: first_year == 2018, 2017, 2016: ', biz2.size / len(biz2.columns)) biz2 = biz2[['CSA2010']] biz2['biz2Count'] = 1 biz2 = biz2.groupby('CSA2010').sum(numeric_only=True) biz2 = biz2.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') biz2 = biz2.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'biz2Count': biz2['biz2Count'].mean()}, ignore_index=True) biz2.tail(1) biz4 = infoUsaCsa[infoUsaCsa['first_year'].isin(['2015', '2016', '2017', '2018'])] print('Count: first_year == 2018, 2017, 2016, 2015: ', biz2.size / len(biz2.columns)) biz4 = biz4[['CSA2010']] biz4['biz4Count'] = 1 biz4 = biz4.groupby('CSA2010').sum(numeric_only=True) biz4 = biz4.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') biz4 = biz4.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'biz4Count': biz4['biz4Count'].mean()}, ignore_index=True) biz4.tail(1) neiind = infoUsaCsa.copy() neiind['naics_extra_short'] = neiind.prim_naics.astype(str).str[:-6].astype(np.int64) neiind = infoUsaCsa[neiind['naics_extra_short'].isin([44, 45, 52, 54, 62, 71, 72, 81])] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neiind.size / len(neiind.columns)) neiind = neiind[['CSA2010']] neiind['neiind'] = 1 neiind = neiind.groupby('CSA2010').sum(numeric_only=True) neiind = neiind.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') neiind = neiind.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'neiind': neiind['neiind'].sum()}, ignore_index=True) neiind.tail(1) neibus = infoUsaCsa.copy() neibus['naics_extra_short'] = neibus.prim_naics.astype(str).str[:-6].astype(np.int64) neibus = infoUsaCsa[neibus['naics_extra_short'].isin([44, 45, 52, 54, 62, 71, 72, 81])] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neibus.size / len(neibus.columns)) neibus = neibus[['CSA2010']] neibus['neibus'] = 1 neibus.head() neibus = neibus.groupby('CSA2010').sum(numeric_only=True) neibus = neibus.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') neibus = neibus.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'neibus': neibus['neibus'].sum()}, ignore_index=True) neibus['neibus'] = neibus['neibus'] * 1000 / neibus['tpop10'] neibus.tail(1) neiemp = infoUsaCsa.copy() neiemp['naics_extra_short'] = neiemp.prim_naics.astype(str).str[:-6].astype(np.int64) neiemp = infoUsaCsa[neiemp['naics_extra_short'].isin([44, 45, 52, 54, 62, 71, 72, 81])] print('Count of Naics Starting With: 44, 45, 52, 54, 62, 71, 72, 81: ', neiemp.size / len(neiemp.columns)) neiemp = neiemp.groupby('CSA2010')[['CSA2010', 'empl_size']].sum(numeric_only=True) neiemp = neiemp.merge(csa[['CSA2010', 'tpop10']], left_on='CSA2010', right_on='CSA2010') neiemp = neiemp.append({'CSA2010': 'Baltimore City', 'tpop10': 620961, 'empl_size': neiemp['empl_size'].sum()}, ignore_index=True) neiemp['neiemp'] = neiemp['empl_size'] neiemp = neiemp.drop('empl_size', axis=1) neiemp.tail()
#!/usr/bin/env python NAME = 'Teros (Citrix Systems)' def is_waf(self): if self.matchcookie(r'^st8id='): return True return False
name = 'Teros (Citrix Systems)' def is_waf(self): if self.matchcookie('^st8id='): return True return False
#/usr/bin/env python # -*- coding: utf-8 -*- def makeSplash(splash, key): """ take as imput the *splash* dictionary and the realtive key to generate a splash page based on the dict keys :param dict splash: :param string key: :return: raw notebok to be rendered as html :rtype: str """ title = splash[key]['title'] description = splash[key]['description'] credits = splash[key]['credits'] home = splash[key]['home'] sourcedata = splash[key]['sourcedata'] nbviewer = splash[key]['nbviewer'] repository = splash[key]['repository'] download = splash[key]['download'] template = """{ "metadata": { "name": "", "signature": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<!DOCTYPE html>\\n", " <html>\\n", " <body>\\n", " <div style=\\"background-image:url(http://www.floridasportsman.com/files/2013/02/noaa-logo1.png);padding:5px;width:100%%;height:230px;border:1px solid white;background-repeat:no-repeat;\\">\\n", " </div>\\n", " <br>\\n", " <h3><b>%s</b><br></h3>\\n", " <div> \\n", " <br>\\n", " %s\\n", " <br>\\n", " <br>\\n", " %s\\n", " <br>\\n", " <br>\\n", " <li><a href=\\"%s\\" target=\\"_blank\\" >%s</a></li>\\n", " <br>\\n", " <li><a href=\\"%s\\" target=\\"_blank\\" >%s</a></li>\\n", " <br>\\n", " </div>\\n", " <hr>\\n", " <br>\\n", " <div>\\n", " <b>Source code used in the IPython Notebook session</b>\\n", " <br> \\n", " <br> \\n", " <li><a href=\\"%s\\" target=\\"_blank\\" >IPython Notebook</a></li>\\n", " <br> \\n", " <li><a href=\\"%s\\" target=\\"_blank\\" >Code repository</a></li>\\n", " <br>\\n", " <li><a href=\\"%s\\" target=\\"_blank\\" >Downloads</a></li>\\n", " <br>\\n", " </div>\\n", " </body>\\n", " </html>" ] } ], "metadata": {} } ] }""" % (title, description, credits, home[0], home[1], sourcedata[0],sourcedata[1], nbviewer, repository, download) return template
def make_splash(splash, key): """ take as imput the *splash* dictionary and the realtive key to generate a splash page based on the dict keys :param dict splash: :param string key: :return: raw notebok to be rendered as html :rtype: str """ title = splash[key]['title'] description = splash[key]['description'] credits = splash[key]['credits'] home = splash[key]['home'] sourcedata = splash[key]['sourcedata'] nbviewer = splash[key]['nbviewer'] repository = splash[key]['repository'] download = splash[key]['download'] template = '{\n "metadata": {\n "name": "",\n "signature": ""\n },\n "nbformat": 3,\n "nbformat_minor": 0,\n "worksheets": [\n {\n "cells": [\n {\n "cell_type": "markdown",\n "metadata": {},\n "source": [\n "<!DOCTYPE html>\\n",\n " <html>\\n",\n " <body>\\n",\n " <div style=\\"background-image:url(http://www.floridasportsman.com/files/2013/02/noaa-logo1.png);padding:5px;width:100%%;height:230px;border:1px solid white;background-repeat:no-repeat;\\">\\n",\n " </div>\\n",\n " <br>\\n",\n " <h3><b>%s</b><br></h3>\\n",\n " <div> \\n",\n " <br>\\n",\n " %s\\n",\n " <br>\\n",\n " <br>\\n",\n " %s\\n",\n " <br>\\n",\n " <br>\\n",\n " <li><a href=\\"%s\\" target=\\"_blank\\" >%s</a></li>\\n",\n " <br>\\n",\n " <li><a href=\\"%s\\" target=\\"_blank\\" >%s</a></li>\\n",\n " <br>\\n",\n " </div>\\n",\n " <hr>\\n",\n " <br>\\n",\n " <div>\\n",\n " <b>Source code used in the IPython Notebook session</b>\\n",\n " <br> \\n",\n " <br> \\n",\n " <li><a href=\\"%s\\" target=\\"_blank\\" >IPython Notebook</a></li>\\n",\n " <br> \\n",\n " <li><a href=\\"%s\\" target=\\"_blank\\" >Code repository</a></li>\\n",\n " <br>\\n",\n " <li><a href=\\"%s\\" target=\\"_blank\\" >Downloads</a></li>\\n",\n " <br>\\n",\n " </div>\\n",\n " </body>\\n",\n " </html>"\n ]\n }\n ],\n "metadata": {}\n }\n ]\n }' % (title, description, credits, home[0], home[1], sourcedata[0], sourcedata[1], nbviewer, repository, download) return template
def mouly(word,num): final = [] for elm in word: for selm in word: fnum = abs(elm-selm) if fnum !=0 and fnum == num: templst = [elm,selm] if templst[::-1] not in final: final.append([elm,selm]) if len(final) >0: return(final) else: return f"Not Possible" print(mouly([1, 5, 9, 13], 5))
def mouly(word, num): final = [] for elm in word: for selm in word: fnum = abs(elm - selm) if fnum != 0 and fnum == num: templst = [elm, selm] if templst[::-1] not in final: final.append([elm, selm]) if len(final) > 0: return final else: return f'Not Possible' print(mouly([1, 5, 9, 13], 5))
for _ in range(int(input())): f = [] for _ in range(int(input())): s = input().split() if s[1] == 'chirrin' and s[0] not in f:f.append(s[0]) elif s[1] == 'chirrion' and s[0] in f:f.remove(s[0]) f.sort() print('TOTAL') print(*f,sep="\n")
for _ in range(int(input())): f = [] for _ in range(int(input())): s = input().split() if s[1] == 'chirrin' and s[0] not in f: f.append(s[0]) elif s[1] == 'chirrion' and s[0] in f: f.remove(s[0]) f.sort() print('TOTAL') print(*f, sep='\n')
# n = n # time = O(n) # space = O(1) # done time = 20m class Solution: def findTheWinner(self, n: int, k: int) -> int: res = 0 for i in range(1, n + 1): res = (res + k) % i return res + 1
class Solution: def find_the_winner(self, n: int, k: int) -> int: res = 0 for i in range(1, n + 1): res = (res + k) % i return res + 1
REGIONS = { 'ABC': 'Africa', 'JKLMNPR': 'Asia', 'STUVWXYZ': 'Europe', '123457': 'North America', '6': 'Oceania', '89': 'South America', }
regions = {'ABC': 'Africa', 'JKLMNPR': 'Asia', 'STUVWXYZ': 'Europe', '123457': 'North America', '6': 'Oceania', '89': 'South America'}
# day_2/if_main.py def example_function(): string = 'Hello' if __name__ == '__main__': print('DEBUG: only want to see this debug if im running this file') return string """ If you check if the current script is the main script you can execute code in it and not have to worry about it executing that code when you import it into other files. """ if __name__ == '__main__': print(example_function())
def example_function(): string = 'Hello' if __name__ == '__main__': print('DEBUG: only want to see this debug if im running this file') return string '\nIf you check if the current script is the main script you can execute code in it\nand not have to worry about it executing that code when you import it into other\nfiles.\n' if __name__ == '__main__': print(example_function())
friends = [] for count in range(3): name = input("Enter friend's name: ") friends.append(name) str_friends = ", ".join(friends) print('Your friends are: ' + str_friends)
friends = [] for count in range(3): name = input("Enter friend's name: ") friends.append(name) str_friends = ', '.join(friends) print('Your friends are: ' + str_friends)
def make_me_a_sandwich(): get_bread() get_butter_knife() get_peanut_butter() spread_pb_on_bread() get_bread() get_butter_knife() get_peanut_butter() spread_jelly_on_bread() put_on_other_bread() def cleanup(): print("Put away peanut butter") print("put away jelly") print("put away butter knife") print("put away bread") def get_bread(): print("Got bread") def get_butter_knife(): print("Got butterknife") def get_peanut_butter(): print("Got peanut butter") def spread_pb_on_bread(): print("Spread peanut butter on bread") def spread_jelly_on_bread(): print("Spread spread jelly on bread") def put_on_other_bread(): print("Put on other bread") for i in range(0, 1): make_me_a_sandwich() print("****made {} sandwiches so far....".format(i)) cleanup()
def make_me_a_sandwich(): get_bread() get_butter_knife() get_peanut_butter() spread_pb_on_bread() get_bread() get_butter_knife() get_peanut_butter() spread_jelly_on_bread() put_on_other_bread() def cleanup(): print('Put away peanut butter') print('put away jelly') print('put away butter knife') print('put away bread') def get_bread(): print('Got bread') def get_butter_knife(): print('Got butterknife') def get_peanut_butter(): print('Got peanut butter') def spread_pb_on_bread(): print('Spread peanut butter on bread') def spread_jelly_on_bread(): print('Spread spread jelly on bread') def put_on_other_bread(): print('Put on other bread') for i in range(0, 1): make_me_a_sandwich() print('****made {} sandwiches so far....'.format(i)) cleanup()
''' Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' i = 0 f = True while (f): i = i + 1 p1 = [c for c in str(i)] if p1[0] == '1': p2 = [c for c in str(i * 2)] p1.sort() p2.sort() if p1 == p2: p3 = [c for c in str(i * 3)] p3.sort() if p2 == p3: p4 = [c for c in str(i * 4)] p4.sort() if p3 == p4: p5 = [c for c in str(i * 5)] p5.sort() if p4 == p5: p6 = [c for c in str(i * 6)] p6.sort() if p5 == p6: print(i) f = False
""" Permuted multiples Problem 52 It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. """ i = 0 f = True while f: i = i + 1 p1 = [c for c in str(i)] if p1[0] == '1': p2 = [c for c in str(i * 2)] p1.sort() p2.sort() if p1 == p2: p3 = [c for c in str(i * 3)] p3.sort() if p2 == p3: p4 = [c for c in str(i * 4)] p4.sort() if p3 == p4: p5 = [c for c in str(i * 5)] p5.sort() if p4 == p5: p6 = [c for c in str(i * 6)] p6.sort() if p5 == p6: print(i) f = False
'''input 3 4 2 7 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem A if __name__ == '__main__': a = int(input()) b = int(input()) h = int(input()) print(int((a + b) * h / 2))
"""input 3 4 2 7 """ if __name__ == '__main__': a = int(input()) b = int(input()) h = int(input()) print(int((a + b) * h / 2))
def path_to_root(node): path = [] while node is not None: path.append(node) node = node.parent return path def lowest_common_ancestor(first, second): '''Finds the lowest common ancestor of two nodes in a binary tree. >>> from utils.binary_tree import Node >>> tree = Node.from_list_representation(list(range(2**5 - 1))) >>> lowest_common_ancestor(tree.left.left, tree.left.right) is tree.left True >>> lowest_common_ancestor(tree, tree.left.right) is tree True >>> lowest_common_ancestor(tree.left.left.right.left, tree.left.right.left) is tree.left True ''' first_path = path_to_root(first) second_path = path_to_root(second) common_parent = None for first_parent, second_parent in zip(reversed(first_path), reversed(second_path)): if first_parent is not second_parent: return common_parent common_parent = first_parent return common_parent
def path_to_root(node): path = [] while node is not None: path.append(node) node = node.parent return path def lowest_common_ancestor(first, second): """Finds the lowest common ancestor of two nodes in a binary tree. >>> from utils.binary_tree import Node >>> tree = Node.from_list_representation(list(range(2**5 - 1))) >>> lowest_common_ancestor(tree.left.left, tree.left.right) is tree.left True >>> lowest_common_ancestor(tree, tree.left.right) is tree True >>> lowest_common_ancestor(tree.left.left.right.left, tree.left.right.left) is tree.left True """ first_path = path_to_root(first) second_path = path_to_root(second) common_parent = None for (first_parent, second_parent) in zip(reversed(first_path), reversed(second_path)): if first_parent is not second_parent: return common_parent common_parent = first_parent return common_parent
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-20 Last_modify: 2016-03-20 ****************************************** ''' ''' Find the contiguous subarray within an array (containing at least one number) which has the largest product. For example, given the array [2,3,-2,4], the contiguous subarray [2,3] has the largest product = 6. ''' class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return nums[0] pMax, nMax = 0, 0 res = 0 for n in nums: if n < 0: pMax, nMax = nMax, pMax pMax = max(pMax * n, n) nMax = min(nMax * n, n) res = max(res, pMax) return res
""" ***************************************** Author: zhlinh Email: zhlinhng@gmail.com Version: 0.0.1 Created Time: 2016-03-20 Last_modify: 2016-03-20 ****************************************** """ '\nFind the contiguous subarray within an array\n(containing at least one number) which has the largest product.\n\nFor example, given the array [2,3,-2,4],\nthe contiguous subarray [2,3] has the largest product = 6.\n' class Solution(object): def max_product(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) == 1: return nums[0] (p_max, n_max) = (0, 0) res = 0 for n in nums: if n < 0: (p_max, n_max) = (nMax, pMax) p_max = max(pMax * n, n) n_max = min(nMax * n, n) res = max(res, pMax) return res
def setup(app): app.add_crossref_type( directivename="setting", rolename="setting", indextemplate="pair: %s; setting", ) return { 'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True, }
def setup(app): app.add_crossref_type(directivename='setting', rolename='setting', indextemplate='pair: %s; setting') return {'version': 'builtin', 'parallel_read_safe': True, 'parallel_write_safe': True}
l = list(map(int, input().split())) score = 0 current = 1 for i in l: if i == 0: break elif i == 1: current = 1 score += current else: if current == 1: current = 2 else: current += 2 score += current print(score)
l = list(map(int, input().split())) score = 0 current = 1 for i in l: if i == 0: break elif i == 1: current = 1 score += current else: if current == 1: current = 2 else: current += 2 score += current print(score)
# Config k = 15 # output sampling size count = 100 # experiment times output_type = 1 input_file_path = 'macReversedSample.csv'
k = 15 count = 100 output_type = 1 input_file_path = 'macReversedSample.csv'
# Description # Given an unsorted array nums, reorder it in-place such that # # nums[0] <= nums[1] >= nums[2] <= nums[3].... # Please complete the problem in-place. # # Have you met this question in a real interview? # Example # Given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. # Approach #1 (Sorting) class Solution: def wiggleSort(self, nums): # write your code here nums.sort() i = 1 while i < len(nums) - 1: nums[i], nums[i+1] = nums[i+1], nums[i] i += 2 #Approach #2 (One-pass Swap) class Solution: def wiggleSort(self, nums): # write your code here for i in range(len(nums)-1): if ((i%2 == 0) and nums[i] > nums[i+1] ) or ((i%2 == 1) and nums[i] < nums[i+1]): nums[i] , nums[i+1] = nums[i+1] , nums[i]
class Solution: def wiggle_sort(self, nums): nums.sort() i = 1 while i < len(nums) - 1: (nums[i], nums[i + 1]) = (nums[i + 1], nums[i]) i += 2 class Solution: def wiggle_sort(self, nums): for i in range(len(nums) - 1): if i % 2 == 0 and nums[i] > nums[i + 1] or (i % 2 == 1 and nums[i] < nums[i + 1]): (nums[i], nums[i + 1]) = (nums[i + 1], nums[i])
# factorial calculation using recursion def calculateFactorial(x): if x == 1: return 1 else: return (x * calculateFactorial(x-1)) num = 20 facorial_number = calculateFactorial(num) print("Factorial of ", num, "is 1 * 2 * 3 * 4 = ", facorial_number)
def calculate_factorial(x): if x == 1: return 1 else: return x * calculate_factorial(x - 1) num = 20 facorial_number = calculate_factorial(num) print('Factorial of ', num, 'is 1 * 2 * 3 * 4 = ', facorial_number)
def oneline(inputArray): return max([inputArray[i]*inputArray[i+1] for i in range(len(inputArray) - 1)]) def expanded(inputArray): ''' EXPLANATION ------------------------------------------------------------------- The previous solution uses a list comprehension that accomplishes the same as below. Comments are added to explain the process. List comprehensions are generally computationally cheaper, as they always utilize Python's list.append() function. However, they can quickly become hard to read. This algorithm is a simple one, and it already showcases that difference, which only increases as complexity increases. ------------------------------------------------------------------- ''' products = [] # only iterate to second to last value, since it will be the last pair for i in range(0, len(inputArray) - 1): x = i # first index in pair y = i + 1 # second index in pair z = inputArray[x] * inputArray[y] # product of pair products.append(z) # add product to output list return max(products) # return largest product found from list
def oneline(inputArray): return max([inputArray[i] * inputArray[i + 1] for i in range(len(inputArray) - 1)]) def expanded(inputArray): """ EXPLANATION ------------------------------------------------------------------- The previous solution uses a list comprehension that accomplishes the same as below. Comments are added to explain the process. List comprehensions are generally computationally cheaper, as they always utilize Python's list.append() function. However, they can quickly become hard to read. This algorithm is a simple one, and it already showcases that difference, which only increases as complexity increases. ------------------------------------------------------------------- """ products = [] for i in range(0, len(inputArray) - 1): x = i y = i + 1 z = inputArray[x] * inputArray[y] products.append(z) return max(products)
def quadratic_f(x): ''' test objective ''' return x[0]**2 + 10 * x[1]**2 + x[0] * x[1] def quadratic_g(x): ''' test constraint g(x) <= 0 ''' return 1 - x[0] - x[1]
def quadratic_f(x): """ test objective """ return x[0] ** 2 + 10 * x[1] ** 2 + x[0] * x[1] def quadratic_g(x): """ test constraint g(x) <= 0 """ return 1 - x[0] - x[1]
''' URL: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons Time complexity: O(nlogn) Space complexity: O(1) ''' class Solution(object): def findMinArrowShots(self, points): """ :type points: List[List[int]] :rtype: int """ if len(points) in (0, 1): return len(points) points.sort(key=lambda x: x[1]) total_arrows = 1 curr_end = points[0][1] for i in range(1, len(points)): next_point = points[i] if next_point[0] > curr_end: curr_end = next_point[1] total_arrows += 1 return total_arrows
""" URL: https://leetcode.com/problems/minimum-number-of-arrows-to-burst-balloons Time complexity: O(nlogn) Space complexity: O(1) """ class Solution(object): def find_min_arrow_shots(self, points): """ :type points: List[List[int]] :rtype: int """ if len(points) in (0, 1): return len(points) points.sort(key=lambda x: x[1]) total_arrows = 1 curr_end = points[0][1] for i in range(1, len(points)): next_point = points[i] if next_point[0] > curr_end: curr_end = next_point[1] total_arrows += 1 return total_arrows
DATA = [ ("Load JS/WebAssembly", 2, 2, 2, 2, 2), ("Load /tmp/lines.txt", 225, 222, 218, 209, 202), ("From JS new Fzf() until ready to ....", 7825, 8548, 1579, 2592, 15069), ("Calling fzf-lib's fzf.New()", 1255, 3121, 963, 612, 899), ("return from fzfNew() function", 358, 7, 0, 18, 1), ("search() until library has result", 4235, 1394, 12132, 4069, 11805), ("Returning search result to JS callback", 1908, 1378, 416, 1173, 6400), ] def create_plot(ax): labels = ["Go", "TinyGo", "GopherJS", "Go with JSON", "GopherJS with JSON"] bottoms = [0, 0, 0, 0, 0] for row in DATA: ax.bar(labels, row[1:], label=row[0], bottom=bottoms) bottoms = [bottoms[i] + row[1:][i] for i in range(len(bottoms))] ax.set_ylabel("Time (ms)") ax.set_ylim([0, 45000]) ax.legend(ncol=2)
data = [('Load JS/WebAssembly', 2, 2, 2, 2, 2), ('Load /tmp/lines.txt', 225, 222, 218, 209, 202), ('From JS new Fzf() until ready to ....', 7825, 8548, 1579, 2592, 15069), ("Calling fzf-lib's fzf.New()", 1255, 3121, 963, 612, 899), ('return from fzfNew() function', 358, 7, 0, 18, 1), ('search() until library has result', 4235, 1394, 12132, 4069, 11805), ('Returning search result to JS callback', 1908, 1378, 416, 1173, 6400)] def create_plot(ax): labels = ['Go', 'TinyGo', 'GopherJS', 'Go with JSON', 'GopherJS with JSON'] bottoms = [0, 0, 0, 0, 0] for row in DATA: ax.bar(labels, row[1:], label=row[0], bottom=bottoms) bottoms = [bottoms[i] + row[1:][i] for i in range(len(bottoms))] ax.set_ylabel('Time (ms)') ax.set_ylim([0, 45000]) ax.legend(ncol=2)
# Copyright (C) 2015 Haruhiko Matsuo <halm.matsuo@gmail.com> # # Distributed under the MIT License. # See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT """Library of pyproffx"""
"""Library of pyproffx"""
""" In this program, we need to copy all the elements of one array into another. This can be accomplished by looping through the first array and store the elements of the first array into the second array at the corresponding position. """ n = int(input("Enter the elements of the array: ")) arr = input() # takes the whole line of n numbers l = list(map(int,arr.split(' '))) """split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5]) """ #Create another array say arr1 with size of arr arr1 = [None]*len(arr) #Copying all elements of one array into another for i in range(0,len(arr)): arr1[i] = arr[i] #Display elements of original array arr print("Elements of original array: ") for i in range(0,len(arr)): print(arr[i]) print() #Displaying elements of new array arr1 print("Elements of new array: ") for i in range(0,len(arr1)): print(arr1[i])
""" In this program, we need to copy all the elements of one array into another. This can be accomplished by looping through the first array and store the elements of the first array into the second array at the corresponding position. """ n = int(input('Enter the elements of the array: ')) arr = input() l = list(map(int, arr.split(' '))) "split those numbers with space( becomes ['2','3','6','6','5']) \nand then map every element into int (becomes [2,3,6,6,5]) " arr1 = [None] * len(arr) for i in range(0, len(arr)): arr1[i] = arr[i] print('Elements of original array: ') for i in range(0, len(arr)): print(arr[i]) print() print('Elements of new array: ') for i in range(0, len(arr1)): print(arr1[i])
class Tree: """Abstract base class representing a tree structure.""" # ------------------------ nested Position class ------------- class Position: """An abstraction representing the location of a single element.""" def element(self): """Return the element stored at this Position.""" raise NotImplementedError('must be implemented by subclass') def __eq__(self, other): """Return True if other Position represents the same location.""" raise NotImplementedError('must be implemented by subclass') def __ne__(self, other): """Return True if other does not represent the same location.""" return not (self == other) # opposite of __eq__ # ------- abstract methods that concrete subclass must support --------- def root(self): """Return Position representing the tree's root (or None if empty).""" raise NotImplementedError('must be implemented by subclass') def parent(self, p): """Return Position representing p's parent (or None if p is root).""" raise NotImplementedError('must be implemented by subclass') def num_children(self, p): """Return the number of children that Position p has.""" raise NotImplementedError('must be implemented by subclass') def children(self, p): """Generate an iteration of Positions representing p's children.""" raise NotImplementedError('must be implemented by subclass') def __len__(self): """Return the total number of elements in the tree.""" raise NotImplementedError('must be implemented by subclass') # --------- concrete methods implemented in this class ------------------- def is_root(self, p): """Return True if Position p represents the root of the tree.""" return self.root() == p def is_leaf(self, p): """Return True if Position p does not have any children.""" return self.num_children(p) == 0 def is_empty(self): """Return True if the tree is empty.""" return len(self) == 0 def _height1(self): # Illustrative example from DSAP, inferior O(n^2) running time """Return the height of the tree.""" return max(self.depth(p) for p in self.positions() if self.is_leaf(p)) def _height2(self, p: Position) -> int: """Return the height of the subtree rooted at Position p.""" # Runs in O(n) where n is number of positions in tree T if self.is_leaf(p): return 0 # base case: A leaf's height is zero because no children else: return 1 + max(self._height2(c) for c in self.children(p)) # ^ return the height of the tallest child of p (plus one). def height(self, p: Position=None) -> int: # The public height method # Confirmed this is correct syntax for type hint where an arg # has a default value. """Return the height of the subtree rooted at Position p. If p is None, return height of the entire tree.""" # Basically a wrapper. Checks if value of p should default to root, then # calls _height2(p) on the appropriate value of p. if p is None: p = self.root() return self._height2(p)
class Tree: """Abstract base class representing a tree structure.""" class Position: """An abstraction representing the location of a single element.""" def element(self): """Return the element stored at this Position.""" raise not_implemented_error('must be implemented by subclass') def __eq__(self, other): """Return True if other Position represents the same location.""" raise not_implemented_error('must be implemented by subclass') def __ne__(self, other): """Return True if other does not represent the same location.""" return not self == other def root(self): """Return Position representing the tree's root (or None if empty).""" raise not_implemented_error('must be implemented by subclass') def parent(self, p): """Return Position representing p's parent (or None if p is root).""" raise not_implemented_error('must be implemented by subclass') def num_children(self, p): """Return the number of children that Position p has.""" raise not_implemented_error('must be implemented by subclass') def children(self, p): """Generate an iteration of Positions representing p's children.""" raise not_implemented_error('must be implemented by subclass') def __len__(self): """Return the total number of elements in the tree.""" raise not_implemented_error('must be implemented by subclass') def is_root(self, p): """Return True if Position p represents the root of the tree.""" return self.root() == p def is_leaf(self, p): """Return True if Position p does not have any children.""" return self.num_children(p) == 0 def is_empty(self): """Return True if the tree is empty.""" return len(self) == 0 def _height1(self): """Return the height of the tree.""" return max((self.depth(p) for p in self.positions() if self.is_leaf(p))) def _height2(self, p: Position) -> int: """Return the height of the subtree rooted at Position p.""" if self.is_leaf(p): return 0 else: return 1 + max((self._height2(c) for c in self.children(p))) def height(self, p: Position=None) -> int: """Return the height of the subtree rooted at Position p. If p is None, return height of the entire tree.""" if p is None: p = self.root() return self._height2(p)
# Christina Andrea Putri - Universitas Kristen Duta Wacana #Buatlah algoritma dan program yang dapat menentukan jenis tunjangan dan tambahan gaji yang didapat karyawan # Tunjangan anak hanya didapatkan oleh karyawan yang sudah menikah dan memiliki anak # Tunjangan keluarga hanya diberikan kepada karyawan laki-laki yang sudah menikah # Untuk karyawan yang memiliki anak < 3 atau gaji < Rp3.000.000,- akan diberikan tambahan gaji sebesar 10% dari gaji karyawan #Input : gaji, status, jk, punya anak/tidak, jml anak #Proses : menentukan jenis tunjangan yang didapat dan tambahan gaji yang didapat #Output : jenis tunjangan dan tambahan gaji try: nama = input("Nama Anda : ") gaji = int(input("Gaji Anda : Rp ")) jk = input("Jenis Kelamin (L/P) : ") status = input("Menikah/Belum Menikah : ") tambahan = gaji*0.1 if status=="Menikah": anak = input("Punya Anak/Tidak Punya Anak : ") if anak == "Punya Anak" : jml_anak = int(input("Jumlah Anak : ")) if jml_anak < 3 or gaji < 3000000 : print("Selamat Anda mendapatkan tambahan gaji sebesar Rp", tambahan) if jk == "L": print("Selamat Anda juga mendapatkan tunjangan keluarga!") else : print("Maaf Anda tidak mendapatkan tunjangan keluarga.") elif anak == "Tidak Punya Anak" and jk=="L": print("Anda hanya mendapatkan tunjangan keluarga. \n Silahkan gunakan dengan bijaksana.") else : print("Maaf Anda tidak mendapat tunjangan dari perusahaan. \n Terimakasih atas pengertiannya") else : print("Maaf Anda tidak mendapat tunjangan dari perusahaan. \n Terimakasih atas pengertiannya.") except : print("Terjadi kesalahan saat input data. Silahkan coba lagi.")
try: nama = input('Nama Anda : ') gaji = int(input('Gaji Anda : Rp ')) jk = input('Jenis Kelamin (L/P) : ') status = input('Menikah/Belum Menikah : ') tambahan = gaji * 0.1 if status == 'Menikah': anak = input('Punya Anak/Tidak Punya Anak : ') if anak == 'Punya Anak': jml_anak = int(input('Jumlah Anak : ')) if jml_anak < 3 or gaji < 3000000: print('Selamat Anda mendapatkan tambahan gaji sebesar Rp', tambahan) if jk == 'L': print('Selamat Anda juga mendapatkan tunjangan keluarga!') else: print('Maaf Anda tidak mendapatkan tunjangan keluarga.') elif anak == 'Tidak Punya Anak' and jk == 'L': print('Anda hanya mendapatkan tunjangan keluarga. \n Silahkan gunakan dengan bijaksana.') else: print('Maaf Anda tidak mendapat tunjangan dari perusahaan. \n Terimakasih atas pengertiannya') else: print('Maaf Anda tidak mendapat tunjangan dari perusahaan. \n Terimakasih atas pengertiannya.') except: print('Terjadi kesalahan saat input data. Silahkan coba lagi.')
# -*- coding: utf-8 -*- __author__ = 'Stephen Larroque' __email__ = 'LRQ3000@gmail.com' # Definition of the version number version_info = 2, 3, 1 # major, minor, patch, extra # Nice string for the version (mimic how IPython composes its version str) __version__ = '-'.join(map(str, version_info)).replace('-', '.').strip('-')
__author__ = 'Stephen Larroque' __email__ = 'LRQ3000@gmail.com' version_info = (2, 3, 1) __version__ = '-'.join(map(str, version_info)).replace('-', '.').strip('-')
class Solution: def findMaxConsecutiveOnes(self, nums): """ :type nums: List[int] :rtype: int """ cons=[0,0] for num in nums: if num==1:cons[1]+=1 else:cons[1]=0 cons[0]=max(cons[0],cons[1]) return cons[0]
class Solution: def find_max_consecutive_ones(self, nums): """ :type nums: List[int] :rtype: int """ cons = [0, 0] for num in nums: if num == 1: cons[1] += 1 else: cons[1] = 0 cons[0] = max(cons[0], cons[1]) return cons[0]
# Project Euler - Question 2 - Even Fibonacci Numbers # Each new term in the Fibonacci sequence is generated by # adding the previous two terms. By starting with 1 and 2, # the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... # By considering the terms in the Fibonacci sequence whose values do # not exceed four million, find the sum of the even-valued terms. # Answer = 4613732 ans = 0 # Variable to hold sum num1 = 0 # First number num2 = 1 # Second number # While the second number is less than 4000000 # This ensures the first number is less after moving while num2 < 4e6: num1, num2 = num2, num1 + num2 # If the number is eve, add to sum if num1 % 2 == 0: ans += num1 # Print results print('The sum is: ' + str(ans))
ans = 0 num1 = 0 num2 = 1 while num2 < 4000000.0: (num1, num2) = (num2, num1 + num2) if num1 % 2 == 0: ans += num1 print('The sum is: ' + str(ans))
def rule(event): return (event['resource'].get('type') == 'gcs_bucket' and event['protoPayload'].get('methodName') == 'storage.setIamPermissions') def dedup(event): return event['resource'].get('labels', {}).get('project_id', '<PROJECT_NOT_FOUND>')
def rule(event): return event['resource'].get('type') == 'gcs_bucket' and event['protoPayload'].get('methodName') == 'storage.setIamPermissions' def dedup(event): return event['resource'].get('labels', {}).get('project_id', '<PROJECT_NOT_FOUND>')
# model settings model = dict( type='ResNetTransformer', pretrained=dict( encoder_pretrained=dict( backbone_pretrained='open-mmlab://res2net101_v1d_26w_4s'), decoder_pretrained=dict( transformer_pretrained='Default') ), ffnn_hidden_dims=[512], ffnn_num_layers=3, encoder=dict( type='Res2NetEncoder', backbone_feats=2048, pos_feats=128, pos_temperature=10000, pos_norm=True, backbone=dict( type='Res2Net', depth=101, scales=4, base_width=26, strides=(1, 2, 2, 1) ) ), decoder=dict( type='TextDecoder', hidden_dim=256, pad_token_id=0, max_position_embeddings=128, layer_norm_eps=1e-12, dropout=0.1, vocab_size=35000, enc_layers=6, dec_layers=6, dim_feedforward=2048, nheads=8, pre_norm=True ) ) train_cfg = dict( decoding_cfg=dict( type='topktopp', topk=1, topp=1 ) ) test_cfg = dict( decoding_cfg=dict( type='topktopp', topk=1, topp=1 ) )
model = dict(type='ResNetTransformer', pretrained=dict(encoder_pretrained=dict(backbone_pretrained='open-mmlab://res2net101_v1d_26w_4s'), decoder_pretrained=dict(transformer_pretrained='Default')), ffnn_hidden_dims=[512], ffnn_num_layers=3, encoder=dict(type='Res2NetEncoder', backbone_feats=2048, pos_feats=128, pos_temperature=10000, pos_norm=True, backbone=dict(type='Res2Net', depth=101, scales=4, base_width=26, strides=(1, 2, 2, 1))), decoder=dict(type='TextDecoder', hidden_dim=256, pad_token_id=0, max_position_embeddings=128, layer_norm_eps=1e-12, dropout=0.1, vocab_size=35000, enc_layers=6, dec_layers=6, dim_feedforward=2048, nheads=8, pre_norm=True)) train_cfg = dict(decoding_cfg=dict(type='topktopp', topk=1, topp=1)) test_cfg = dict(decoding_cfg=dict(type='topktopp', topk=1, topp=1))
# # PySNMP MIB module CISCOSB-LBD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-LBD-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:22:53 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint") switch001, = mibBuilder.importSymbols("CISCOSB-MIB", "switch001") PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") ObjectIdentity, IpAddress, iso, Unsigned32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, ModuleIdentity, NotificationType, TimeTicks, Counter64, Bits, Gauge32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "iso", "Unsigned32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "ModuleIdentity", "NotificationType", "TimeTicks", "Counter64", "Bits", "Gauge32", "Counter32") TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue") rlLbd = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127)) rlLbd.setRevisions(('2007-11-07 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rlLbd.setRevisionsDescriptions(('Initial version of this MIB.',)) if mibBuilder.loadTexts: rlLbd.setLastUpdated('200711070000Z') if mibBuilder.loadTexts: rlLbd.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: rlLbd.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>') if mibBuilder.loadTexts: rlLbd.setDescription('The private MIB module definition for Loopback Detection MIB.') rlLbdEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 1), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlLbdEnable.setStatus('current') if mibBuilder.loadTexts: rlLbdEnable.setDescription('Enable/Disable Loopback Detection in the switch.') rlLbdDetectionInterval = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(30, 60))).setUnits('seconds').setMaxAccess("readwrite") if mibBuilder.loadTexts: rlLbdDetectionInterval.setStatus('current') if mibBuilder.loadTexts: rlLbdDetectionInterval.setDescription('The time in seconds that should pass between unicast LBD packets.') rlLbdMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("source-mac-addr", 1), ("base-mac-addr", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlLbdMode.setStatus('current') if mibBuilder.loadTexts: rlLbdMode.setDescription('Loopback detection mode.') rlLbdIfAdminStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 4), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlLbdIfAdminStatus.setStatus('current') if mibBuilder.loadTexts: rlLbdIfAdminStatus.setDescription("Loopback Detection admin status. Each port of the system is represented by a single bit within the value of this object. If that bit has a value of '1' then that port has enabled admin status,; if the port is disabled, its bit has a value of '0'.") mibBuilder.exportSymbols("CISCOSB-LBD-MIB", rlLbd=rlLbd, rlLbdEnable=rlLbdEnable, PYSNMP_MODULE_ID=rlLbd, rlLbdDetectionInterval=rlLbdDetectionInterval, rlLbdMode=rlLbdMode, rlLbdIfAdminStatus=rlLbdIfAdminStatus)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, constraints_union, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint') (switch001,) = mibBuilder.importSymbols('CISCOSB-MIB', 'switch001') (port_list,) = mibBuilder.importSymbols('Q-BRIDGE-MIB', 'PortList') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (object_identity, ip_address, iso, unsigned32, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, module_identity, notification_type, time_ticks, counter64, bits, gauge32, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'IpAddress', 'iso', 'Unsigned32', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'ModuleIdentity', 'NotificationType', 'TimeTicks', 'Counter64', 'Bits', 'Gauge32', 'Counter32') (textual_convention, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'TruthValue') rl_lbd = module_identity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127)) rlLbd.setRevisions(('2007-11-07 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rlLbd.setRevisionsDescriptions(('Initial version of this MIB.',)) if mibBuilder.loadTexts: rlLbd.setLastUpdated('200711070000Z') if mibBuilder.loadTexts: rlLbd.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: rlLbd.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>') if mibBuilder.loadTexts: rlLbd.setDescription('The private MIB module definition for Loopback Detection MIB.') rl_lbd_enable = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 1), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlLbdEnable.setStatus('current') if mibBuilder.loadTexts: rlLbdEnable.setDescription('Enable/Disable Loopback Detection in the switch.') rl_lbd_detection_interval = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 2), integer32().subtype(subtypeSpec=value_range_constraint(30, 60))).setUnits('seconds').setMaxAccess('readwrite') if mibBuilder.loadTexts: rlLbdDetectionInterval.setStatus('current') if mibBuilder.loadTexts: rlLbdDetectionInterval.setDescription('The time in seconds that should pass between unicast LBD packets.') rl_lbd_mode = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('source-mac-addr', 1), ('base-mac-addr', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlLbdMode.setStatus('current') if mibBuilder.loadTexts: rlLbdMode.setDescription('Loopback detection mode.') rl_lbd_if_admin_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 127, 4), port_list()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlLbdIfAdminStatus.setStatus('current') if mibBuilder.loadTexts: rlLbdIfAdminStatus.setDescription("Loopback Detection admin status. Each port of the system is represented by a single bit within the value of this object. If that bit has a value of '1' then that port has enabled admin status,; if the port is disabled, its bit has a value of '0'.") mibBuilder.exportSymbols('CISCOSB-LBD-MIB', rlLbd=rlLbd, rlLbdEnable=rlLbdEnable, PYSNMP_MODULE_ID=rlLbd, rlLbdDetectionInterval=rlLbdDetectionInterval, rlLbdMode=rlLbdMode, rlLbdIfAdminStatus=rlLbdIfAdminStatus)
def newton( function, function1, startingInt ): # function is the f(x) and function1 is the f'(x) x_n = startingInt while True: x_n1 = x_n - function(x_n) / function1(x_n) if abs(x_n - x_n1) < 0.00001: return x_n1 x_n = x_n1 def f(x): return (x ** 3) - 2 * x - 5 def f1(x): return 3 * (x ** 2) - 2 print(newton(f, f1, 3))
def newton(function, function1, startingInt): x_n = startingInt while True: x_n1 = x_n - function(x_n) / function1(x_n) if abs(x_n - x_n1) < 1e-05: return x_n1 x_n = x_n1 def f(x): return x ** 3 - 2 * x - 5 def f1(x): return 3 * x ** 2 - 2 print(newton(f, f1, 3))
# This code is licensed under the MIT License (see LICENSE file for details) def _make_command(*elements): return ' '.join(map(str, elements)) def wait_high(pin): return _make_command('wh', pin) def wait_low(pin): return _make_command('wl', pin) def wait_change(pin): return _make_command('wc', pin) def wait_time(time): return _make_command('wt', time) def read_digital(pin): return _make_command('rd', pin) def read_analog(pin): return _make_command('ra', pin) def delay_ms(delay): return _make_command('dm', delay) def delay_us(delay): return _make_command('du', delay) def timer_begin(): return _make_command('tb') def timer_end(): return _make_command('te') def pwm(pin, value): return _make_command('pm', pin, value) def set_high(pin): return _make_command('sh', pin) def set_low(pin): return _make_command('sl', pin) def set_tristate(pin): return _make_command('st', pin) def char_transmit(byte): return _make_command('ct', byte) def char_receive(): return _make_command('cr') def loop(index, count): return _make_command('lo', index, count) def goto(index): return _make_command('go', index)
def _make_command(*elements): return ' '.join(map(str, elements)) def wait_high(pin): return _make_command('wh', pin) def wait_low(pin): return _make_command('wl', pin) def wait_change(pin): return _make_command('wc', pin) def wait_time(time): return _make_command('wt', time) def read_digital(pin): return _make_command('rd', pin) def read_analog(pin): return _make_command('ra', pin) def delay_ms(delay): return _make_command('dm', delay) def delay_us(delay): return _make_command('du', delay) def timer_begin(): return _make_command('tb') def timer_end(): return _make_command('te') def pwm(pin, value): return _make_command('pm', pin, value) def set_high(pin): return _make_command('sh', pin) def set_low(pin): return _make_command('sl', pin) def set_tristate(pin): return _make_command('st', pin) def char_transmit(byte): return _make_command('ct', byte) def char_receive(): return _make_command('cr') def loop(index, count): return _make_command('lo', index, count) def goto(index): return _make_command('go', index)
lst_of_languages = ['Spanish', 'English', 'Arabic', 'Dutch'] print(lst_of_languages) # Accessing Elements in a List & Using Individual Values from a List. print(f'{lst_of_languages[0]} is my native language.') # Modifying Elements in a List lst_of_languages[-1] = 'French' print(lst_of_languages) # Appending Elements to the End of a List. lst_of_languages.append('Chinese') print(lst_of_languages) # Inserting Elements into a List. lst_of_languages.insert(-1, 'Dutch') print(lst_of_languages) # Removing an Item Using the pop() Method. lst_of_languages.pop() print(lst_of_languages) # Popping Items from any Position in a List. lst_of_languages.pop(-1) print(lst_of_languages) # Removing an Item by Value. lst_of_languages.remove('French') print(lst_of_languages) # Removing an Item Using the del Statement. del lst_of_languages[-1] print(lst_of_languages) # Sorting a List Temporarily with the sorted() Function. print(sorted(lst_of_languages)) # Printing a List in Reverse Order. lst_of_languages.reverse() print(lst_of_languages) # Finding the Length of a List. print(len(lst_of_languages)) # Sorting a List Permanently with the sort() Method. lst_of_languages.sort() print(lst_of_languages) lst_of_languages.sort(reverse=True) print(lst_of_languages)
lst_of_languages = ['Spanish', 'English', 'Arabic', 'Dutch'] print(lst_of_languages) print(f'{lst_of_languages[0]} is my native language.') lst_of_languages[-1] = 'French' print(lst_of_languages) lst_of_languages.append('Chinese') print(lst_of_languages) lst_of_languages.insert(-1, 'Dutch') print(lst_of_languages) lst_of_languages.pop() print(lst_of_languages) lst_of_languages.pop(-1) print(lst_of_languages) lst_of_languages.remove('French') print(lst_of_languages) del lst_of_languages[-1] print(lst_of_languages) print(sorted(lst_of_languages)) lst_of_languages.reverse() print(lst_of_languages) print(len(lst_of_languages)) lst_of_languages.sort() print(lst_of_languages) lst_of_languages.sort(reverse=True) print(lst_of_languages)
# -*- coding: utf-8 -*- class Solution: def countPrimeSetBits(self, L, R): def countSetBits(n): result = 0 while n: n &= n - 1 result += 1 return result result = 0 primes = {2, 3, 5, 7, 11, 13, 17, 19} for n in range(L, R + 1): if countSetBits(n) in primes: result += 1 return result if __name__ == '__main__': solution = Solution() assert 4 == solution.countPrimeSetBits(6, 10) assert 5 == solution.countPrimeSetBits(10, 15)
class Solution: def count_prime_set_bits(self, L, R): def count_set_bits(n): result = 0 while n: n &= n - 1 result += 1 return result result = 0 primes = {2, 3, 5, 7, 11, 13, 17, 19} for n in range(L, R + 1): if count_set_bits(n) in primes: result += 1 return result if __name__ == '__main__': solution = solution() assert 4 == solution.countPrimeSetBits(6, 10) assert 5 == solution.countPrimeSetBits(10, 15)
FILE_FIELD = 'file' # TODO: Change to '_file' ? FLASK_REQ_FILE_FILED = 'file' RESULT_FIELD = 'result' # TODO: Change to '_result' _SOURCE = '_source' _ARGS = '_args' _JSON = '_json' _ROUTE = '_route'
file_field = 'file' flask_req_file_filed = 'file' result_field = 'result' _source = '_source' _args = '_args' _json = '_json' _route = '_route'
#I love my family # message = 'I love Connie' # String Mvariable lovestring = 'I love Connie' print(lovestring) #variable number My_integer1=40 _integer2_my = 80 print(My_integer1) print(My_integer1 + _integer2_my + 200) print(_integer2_my) My_integer1 = 20 _integer2_my = 40 print (My_integer1) print(My_integer1 + _integer2_my +200) print(_integer2_my) #float variable current_balance = 529.58 print(current_balance) #Boolean variables is_mandeep_married = True print("is mandeep married") print(is_mandeep_married) is_mandeep_single = False print("mandeep is single") print(is_mandeep_single)
lovestring = 'I love Connie' print(lovestring) my_integer1 = 40 _integer2_my = 80 print(My_integer1) print(My_integer1 + _integer2_my + 200) print(_integer2_my) my_integer1 = 20 _integer2_my = 40 print(My_integer1) print(My_integer1 + _integer2_my + 200) print(_integer2_my) current_balance = 529.58 print(current_balance) is_mandeep_married = True print('is mandeep married') print(is_mandeep_married) is_mandeep_single = False print('mandeep is single') print(is_mandeep_single)
table = [ ('a', 0x1E, 0x9E), ('b', 0x30, 0xB0), ('c', 0x2E, 0xAE), ('d', 0x20, 0xA0), ('e', 0x12, 0x92), ('f', 0x21, 0xA1), ('g', 0x22, 0xA2), ('h', 0x23, 0xA3), ('i', 0x17, 0x97), ('j', 0x24, 0xA4), ('k', 0x25, 0xA5), ('l', 0x26, 0xA6), ('m', 0x32, 0xB2), ('n', 0x31, 0xB1), ('o', 0x18, 0x98), ('p', 0x19, 0x99), ('q', 0x10, 0x90), ('r', 0x13, 0x93), ('s', 0x1F, 0x9F), ('t', 0x14, 0x94), ('u', 0x16, 0x96), ('v', 0x2F, 0xAF), ('w', 0x11, 0x91), ('x', 0x2D, 0xAD), ('y', 0x15, 0x95), ('z', 0x2C, 0xAC), ('0', 0x0B, 0x8B), ('1', 0x2, 0x82), ('2', 0x3, 0x83), ('3', 0x4, 0x84), ('4', 0x5, 0x85), ('5', 0x6, 0x86), ('6', 0x7, 0x87), ('7', 0x8, 0x88), ('8', 0x9, 0x89), ('9', 0x0A, 0x8A), ('`', 0x29, 0x89), ('-', 0x0C, 0x8C), ('=', 0x0D, 0x8D), ('\\', 0x2B, 0xAB), (' ', 0x39, 0xB9), ('\n', 0x1C, 0x9C), ('[', 0x1A, 0x9A), ('*', 0x37, 0xB7), ('-', 0x4A, 0xCA), ('+', 0x4E, 0xCE), ('.', 0x53, 0xD3), ('0', 0x52, 0xD2), ('1', 0x4F, 0xCF), ('2', 0x50, 0xD0), ('3', 0x51, 0xD1), ('4', 0x4B, 0xCB), ('5', 0x4C, 0xCC), ('6', 0x4D, 0xCD), ('7', 0x47, 0xC7), ('8', 0x48, 0xC8), ('9', 0x49, 0xC9), (']', 0x1B, 0x9B), (';', 0x27, 0xA7), ('\'', 0x28, 0xA8), (',', 0x33, 0xB3), ('.', 0x34, 0xB4), ('/', 0x35, 0xB5), ] keymap = [0] * 256 for (ch, pressed, released) in table: keymap[pressed] = ord(ch) keymap[released] = ord(ch) | 0x80 print(keymap)
table = [('a', 30, 158), ('b', 48, 176), ('c', 46, 174), ('d', 32, 160), ('e', 18, 146), ('f', 33, 161), ('g', 34, 162), ('h', 35, 163), ('i', 23, 151), ('j', 36, 164), ('k', 37, 165), ('l', 38, 166), ('m', 50, 178), ('n', 49, 177), ('o', 24, 152), ('p', 25, 153), ('q', 16, 144), ('r', 19, 147), ('s', 31, 159), ('t', 20, 148), ('u', 22, 150), ('v', 47, 175), ('w', 17, 145), ('x', 45, 173), ('y', 21, 149), ('z', 44, 172), ('0', 11, 139), ('1', 2, 130), ('2', 3, 131), ('3', 4, 132), ('4', 5, 133), ('5', 6, 134), ('6', 7, 135), ('7', 8, 136), ('8', 9, 137), ('9', 10, 138), ('`', 41, 137), ('-', 12, 140), ('=', 13, 141), ('\\', 43, 171), (' ', 57, 185), ('\n', 28, 156), ('[', 26, 154), ('*', 55, 183), ('-', 74, 202), ('+', 78, 206), ('.', 83, 211), ('0', 82, 210), ('1', 79, 207), ('2', 80, 208), ('3', 81, 209), ('4', 75, 203), ('5', 76, 204), ('6', 77, 205), ('7', 71, 199), ('8', 72, 200), ('9', 73, 201), (']', 27, 155), (';', 39, 167), ("'", 40, 168), (',', 51, 179), ('.', 52, 180), ('/', 53, 181)] keymap = [0] * 256 for (ch, pressed, released) in table: keymap[pressed] = ord(ch) keymap[released] = ord(ch) | 128 print(keymap)
datasets = { 'era-interim': { 'class': 'ei', 'dataset': 'interim', 'expver': '1', 'grid': '0.75/0.75', 'stream': 'oper'}}
datasets = {'era-interim': {'class': 'ei', 'dataset': 'interim', 'expver': '1', 'grid': '0.75/0.75', 'stream': 'oper'}}
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n ) : s = set ( ) sum = 0 for i in range ( n ) : if arr [ i ] not in s : s.add ( arr [ i ] ) for i in s : sum = sum + i return sum #TOFILL if __name__ == '__main__': param = [ ([5, 6, 8, 10, 21, 22, 27, 32, 35, 36, 43, 44, 46, 48, 49, 55, 60, 61, 69, 69, 71, 72, 73, 78, 88, 94],24,), ([80, 94, 16, -74, 32, -64, -84, -66, -10],6,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],27,), ([99, 4, 96, 39, 39, 24, 15, 47, 25, 74, 7, 98, 88, 91, 62, 12, 31, 14, 48, 26, 37, 25, 11, 32, 34, 64, 72, 5, 80, 86, 6],15,), ([-86, -84, -84, -78, -78, -76, -74, -68, -66, -64, -60, -60, -56, -50, -42, -42, -38, -34, -32, -22, -16, -14, -10, -6, -6, 4, 4, 26, 36, 36, 54, 62, 64, 68, 70, 76, 76, 76, 84, 92, 92, 94, 96],27,), ([1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1],25,), ([3, 3, 5, 8, 32, 33, 35, 35, 42, 48, 67, 71, 71, 74, 77, 80, 94, 96, 96, 97],19,), ([-50, -18, -66, 76, -54, 96, 98, 26, 42, 64, -60],9,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],15,), ([70, 21, 44, 82, 62, 41, 86],3,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(arr, n): s = set() sum = 0 for i in range(n): if arr[i] not in s: s.add(arr[i]) for i in s: sum = sum + i return sum if __name__ == '__main__': param = [([5, 6, 8, 10, 21, 22, 27, 32, 35, 36, 43, 44, 46, 48, 49, 55, 60, 61, 69, 69, 71, 72, 73, 78, 88, 94], 24), ([80, 94, 16, -74, 32, -64, -84, -66, -10], 6), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 27), ([99, 4, 96, 39, 39, 24, 15, 47, 25, 74, 7, 98, 88, 91, 62, 12, 31, 14, 48, 26, 37, 25, 11, 32, 34, 64, 72, 5, 80, 86, 6], 15), ([-86, -84, -84, -78, -78, -76, -74, -68, -66, -64, -60, -60, -56, -50, -42, -42, -38, -34, -32, -22, -16, -14, -10, -6, -6, 4, 4, 26, 36, 36, 54, 62, 64, 68, 70, 76, 76, 76, 84, 92, 92, 94, 96], 27), ([1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1], 25), ([3, 3, 5, 8, 32, 33, 35, 35, 42, 48, 67, 71, 71, 74, 77, 80, 94, 96, 96, 97], 19), ([-50, -18, -66, 76, -54, 96, 98, 26, 42, 64, -60], 9), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 15), ([70, 21, 44, 82, 62, 41, 86], 3)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
def main(): # squares = [] # for i in range(1, 101): # if i % 3 != 0: # squares.append(i**2) # list comprehension donde numeros al cuadrado no sean multiplo de 3. squares = [i**2 for i in range(1, 101) if i % 3 != 0] print('Reto 1') print(squares) print('*'*30) # list comprehension donde los numeros sean multiplos de 4, 6 y 9 en un rango de numeros con hasta 5 digitos squares_2 = [i for i in range(1, 9999) if i % 4 == 0 and i % 6 == 0 and i % 9 == 0][:10] print('Reto 2') print(squares_2) print('*'*30) if __name__ == '__main__': main()
def main(): squares = [i ** 2 for i in range(1, 101) if i % 3 != 0] print('Reto 1') print(squares) print('*' * 30) squares_2 = [i for i in range(1, 9999) if i % 4 == 0 and i % 6 == 0 and (i % 9 == 0)][:10] print('Reto 2') print(squares_2) print('*' * 30) if __name__ == '__main__': main()
# A configuration file for the Docker image POSTGRES = dict( database = 'wikidata', host = 'db', port = 5432, user = 'postgres', password = 'postgres', ) METADATA_DIR = '/src/metadata'
postgres = dict(database='wikidata', host='db', port=5432, user='postgres', password='postgres') metadata_dir = '/src/metadata'
""" This class contains details around the contents of a server, mostly based on its type. Will contain one of the following: - Files - Contain a set of metadata for a file - Banks Accounts - Contain metadata for account - Databases - Contains a list of tables/rows """ class Contents: def __init__(self, contents: list): self.data: list = contents def add_data(self, data): self.data.append(data) def remove_data(self, data): self.data.remove(data) def update_data(self, data_to_update, new_data): self.data = [new_data if item == data_to_update else item for item in self.data] def __str__(self): return str(self.data) class File(Contents): def __init__(self, files: list): self.files: list = files def add_file(self, file): self.files.append(file) def remove_file(self, file): self.files.remove(file) # TODO: Need to extend Files class further # TODO: Add additional methods for altering file contents class Bank(Contents): def __init__(self, accounts: list): self.accounts: list = accounts def add_account(self, account): self.accounts.append(account) def remove_account(self, account): self.accounts.remove(account) # TODO: Need to refactor account, once class is built ([account_num, account_owner, account_balance]) def update_account_balance(self, account_to_update, amount): for account in self.accounts: if account == account_to_update: account[2] = account[2] + amount return True return False class Database(Contents): def __init__(self, records: list): self.records: list = records def add_record(self, record): self.records.append(record) def remove_record(self, record): self.records.remove(record) def update_record(self, record): # TODO: Update method to allow modification of existing record pass
""" This class contains details around the contents of a server, mostly based on its type. Will contain one of the following: - Files - Contain a set of metadata for a file - Banks Accounts - Contain metadata for account - Databases - Contains a list of tables/rows """ class Contents: def __init__(self, contents: list): self.data: list = contents def add_data(self, data): self.data.append(data) def remove_data(self, data): self.data.remove(data) def update_data(self, data_to_update, new_data): self.data = [new_data if item == data_to_update else item for item in self.data] def __str__(self): return str(self.data) class File(Contents): def __init__(self, files: list): self.files: list = files def add_file(self, file): self.files.append(file) def remove_file(self, file): self.files.remove(file) class Bank(Contents): def __init__(self, accounts: list): self.accounts: list = accounts def add_account(self, account): self.accounts.append(account) def remove_account(self, account): self.accounts.remove(account) def update_account_balance(self, account_to_update, amount): for account in self.accounts: if account == account_to_update: account[2] = account[2] + amount return True return False class Database(Contents): def __init__(self, records: list): self.records: list = records def add_record(self, record): self.records.append(record) def remove_record(self, record): self.records.remove(record) def update_record(self, record): pass
# http://www.faqs.org/rfcs/rfc1071.html def checksum(source_string): sum = 0 countTo = (len(source_string)/2)*2 count = 0 while count < countTo: thisVal = ord(source_string[count + 1])*256 + ord(source_string[count]) sum = sum + thisVal sum = sum & 0xffffffff # Necessary? count = count + 2 if countTo < len(source_string): sum = sum + ord(source_string[len(source_string) - 1]) sum = sum & 0xffffffff # Necessary? sum = (sum >> 16) + (sum & 0xffff) sum = sum + (sum >> 16) answer = ~sum answer = answer & 0xffff # Swap bytes. Bugger me if I know why. answer = answer >> 8 | (answer << 8 & 0xff00) return answer
def checksum(source_string): sum = 0 count_to = len(source_string) / 2 * 2 count = 0 while count < countTo: this_val = ord(source_string[count + 1]) * 256 + ord(source_string[count]) sum = sum + thisVal sum = sum & 4294967295 count = count + 2 if countTo < len(source_string): sum = sum + ord(source_string[len(source_string) - 1]) sum = sum & 4294967295 sum = (sum >> 16) + (sum & 65535) sum = sum + (sum >> 16) answer = ~sum answer = answer & 65535 answer = answer >> 8 | answer << 8 & 65280 return answer
# Shibboleth authentication settings SHIBBOLETH_LOGOUT_URL = '/Shibboleth.sso/Logout?target=%s' SHIBBOLETH_LOGOUT_REDIRECT_URL = '/administration/accounts/logged-out' SHIBBOLETH_REMOTE_USER_HEADER = 'HTTP_SHIB_UID' SHIBBOLETH_ATTRIBUTE_MAP = { # Automatic user fields 'HTTP_SHIB_GIVENNAME': (False, 'first_name'), 'HTTP_SHIB_SN': (False, 'last_name'), 'HTTP_SHIB_MAIL': (False, 'email'), # Entitlement field (which we handle manually) 'HTTP_SHIB_ENTITLEMENT': (True, 'entitlement'), } # If the user has this entitlement, they will be a superuser/admin SHIBBOLETH_ADMIN_ENTITLEMENT = 'preservation-admin'
shibboleth_logout_url = '/Shibboleth.sso/Logout?target=%s' shibboleth_logout_redirect_url = '/administration/accounts/logged-out' shibboleth_remote_user_header = 'HTTP_SHIB_UID' shibboleth_attribute_map = {'HTTP_SHIB_GIVENNAME': (False, 'first_name'), 'HTTP_SHIB_SN': (False, 'last_name'), 'HTTP_SHIB_MAIL': (False, 'email'), 'HTTP_SHIB_ENTITLEMENT': (True, 'entitlement')} shibboleth_admin_entitlement = 'preservation-admin'
class MaxSumSubArray: def maxSum(self, array): max = runSum = array[0] for num in array[1:]: runSum += num if(num > runSum): runSum = num if (max < runSum): max = runSum return max if __name__ == '__main__': maxSumSubArray = MaxSumSubArray() array = [-2, -3, 4, -1, -2, 1, 5, -3] print (maxSumSubArray.maxSum(array))
class Maxsumsubarray: def max_sum(self, array): max = run_sum = array[0] for num in array[1:]: run_sum += num if num > runSum: run_sum = num if max < runSum: max = runSum return max if __name__ == '__main__': max_sum_sub_array = max_sum_sub_array() array = [-2, -3, 4, -1, -2, 1, 5, -3] print(maxSumSubArray.maxSum(array))
lista_compras = [] print("### Aplicativo de lista de compras ###") print(" ") print("Digite os produtos que deseja adicionar na lista e tecle <ENTER>") print("Para terminar e imprimir a lista, digite -1 e tecle <ENTER>") print(" ") r = input("Digite o primeiro item da lista: ") while r != "-1": lista_compras.append(r) r = input("Digite outro item (-1=sair): ") print(" ") print(" ") print("----------- Sua lista de compras -----------------") print("-"*50) print(lista_compras) print("-"*50) contador = 1 for item in lista_compras: print("#{} - {}".format(contador, item)) contador += 1 print("-"*50)
lista_compras = [] print('### Aplicativo de lista de compras ###') print(' ') print('Digite os produtos que deseja adicionar na lista e tecle <ENTER>') print('Para terminar e imprimir a lista, digite -1 e tecle <ENTER>') print(' ') r = input('Digite o primeiro item da lista: ') while r != '-1': lista_compras.append(r) r = input('Digite outro item (-1=sair): ') print(' ') print(' ') print('----------- Sua lista de compras -----------------') print('-' * 50) print(lista_compras) print('-' * 50) contador = 1 for item in lista_compras: print('#{} - {}'.format(contador, item)) contador += 1 print('-' * 50)
class RangeModule: def __init__(self): self.ranges=[] def addRange(self, left: int, right: int) -> None: #print('add range '+str(left)+', '+str(right)) index=bisect_left(self.ranges, [left, right]) end=index while end<len(self.ranges): if self.ranges[end][0]>right: break right=max(right, self.ranges[end][1]) end+=1 if index>0 and self.ranges[index-1][1]>=left: if self.ranges[index-1][1]>=right: return index-=1 left=self.ranges[index][0] del self.ranges[index:end] self.ranges.insert(index, [left, right]) #print(self.ranges) def queryRange(self, left: int, right: int) -> bool: #print('query range '+str(left)+', '+str(right)) #print(self.ranges) index=bisect_right(self.ranges, [left, 1000000000]) if index>0 and self.ranges[index-1][0]<=left and self.ranges[index-1][1]>=right: return True return False def removeRange(self, left: int, right: int) -> None: #print('remove range '+str(left)+', '+str(right)) index=bisect_left(self.ranges, [left, left]) #print('index='+str(index)) if index>0 and self.ranges[index-1][1]>left: if self.ranges[index-1][1]>right: self.ranges.insert(index,[right, self.ranges[index-1][1]]) self.ranges[index-1][1]=left if index==len(self.ranges) or self.ranges[index][0]>=right: return end=index while end<len(self.ranges): if self.ranges[end][1]>=right: self.ranges[end][0]=max(right, self.ranges[end][0]) break end+=1 #print('del '+str(end)) del self.ranges[index:end] #print(self.ranges) # Your RangeModule object will be instantiated and called as such: # obj = RangeModule() # obj.addRange(left,right) # param_2 = obj.queryRange(left,right) # obj.removeRange(left,right)
class Rangemodule: def __init__(self): self.ranges = [] def add_range(self, left: int, right: int) -> None: index = bisect_left(self.ranges, [left, right]) end = index while end < len(self.ranges): if self.ranges[end][0] > right: break right = max(right, self.ranges[end][1]) end += 1 if index > 0 and self.ranges[index - 1][1] >= left: if self.ranges[index - 1][1] >= right: return index -= 1 left = self.ranges[index][0] del self.ranges[index:end] self.ranges.insert(index, [left, right]) def query_range(self, left: int, right: int) -> bool: index = bisect_right(self.ranges, [left, 1000000000]) if index > 0 and self.ranges[index - 1][0] <= left and (self.ranges[index - 1][1] >= right): return True return False def remove_range(self, left: int, right: int) -> None: index = bisect_left(self.ranges, [left, left]) if index > 0 and self.ranges[index - 1][1] > left: if self.ranges[index - 1][1] > right: self.ranges.insert(index, [right, self.ranges[index - 1][1]]) self.ranges[index - 1][1] = left if index == len(self.ranges) or self.ranges[index][0] >= right: return end = index while end < len(self.ranges): if self.ranges[end][1] >= right: self.ranges[end][0] = max(right, self.ranges[end][0]) break end += 1 del self.ranges[index:end]
''' Created on Mar 6, 2019 @author: hzhang0418 ''' ''' for each individual dataset, get its excluded attributes '''
""" Created on Mar 6, 2019 @author: hzhang0418 """ '\nfor each individual dataset, get its excluded attributes\n'
def calculateStats(numbers): compStats = {'avg': 0 , 'min': 0,'max': 0 } if not numbers: compStats['avg'] = 'nan' compStats['min'] = 'nan' compStats['max'] = 'nan' else: for num in numbers: compStats['avg'] += num compStats['min'] = min(numbers) compStats['max'] = max(numbers) compStats['avg'] /= len(numbers) return compStats
def calculate_stats(numbers): comp_stats = {'avg': 0, 'min': 0, 'max': 0} if not numbers: compStats['avg'] = 'nan' compStats['min'] = 'nan' compStats['max'] = 'nan' else: for num in numbers: compStats['avg'] += num compStats['min'] = min(numbers) compStats['max'] = max(numbers) compStats['avg'] /= len(numbers) return compStats
print(longpoll[pack['userid']]['object']) if 'reply_message' in longpoll[pack['userid']]['object']: kickid = longpoll[pack['userid']]['object']['reply_message']['from_id'] else: kickid = longpoll[pack['userid']]['object']['fwd_messages'][0]['from_id'] data = {'access_token':config['group_token'],'chat_id':pack['toho']-2000000000,'member_id':kickid,'v':'5.90'} requests.post('https://api.vk.com/method/messages.removeChatUser',data=data)
print(longpoll[pack['userid']]['object']) if 'reply_message' in longpoll[pack['userid']]['object']: kickid = longpoll[pack['userid']]['object']['reply_message']['from_id'] else: kickid = longpoll[pack['userid']]['object']['fwd_messages'][0]['from_id'] data = {'access_token': config['group_token'], 'chat_id': pack['toho'] - 2000000000, 'member_id': kickid, 'v': '5.90'} requests.post('https://api.vk.com/method/messages.removeChatUser', data=data)
def toolchain_container_sha256s(): return { ########################################################### # Base images # ########################################################### # gcr.io/cloud-marketplace/google/debian8:latest "debian8": "sha256:a6df7738c401aef6bf9c113eb1eea7f3921417fd4711ea28100681f2fe483ea2", # gcr.io/cloud-marketplace/google/debian9:latest "debian9": "sha256:1d6a9a6d106bd795098f60f4abb7083626354fa6735e81743c7f8cfca11259f0", # gcr.io/cloud-marketplace/google/ubuntu16_04:latest "ubuntu16_04": "sha256:8a12cc26c62e2f9824aada8d13c1f0c2d2847d18191560e1500d651a709d6550", ########################################################### # Python3 images # ########################################################### # gcr.io/cloud-marketplace/google/python:latest # Pinned to ace668f0f01e5e562ad09c3f128488ec33fa9126313f16505a86ae77865d1696 as it is the # latest *debian8* based python3 image. Newer ones are ubuntu16_04 based. "debian8_python3": "sha256:ace668f0f01e5e562ad09c3f128488ec33fa9126313f16505a86ae77865d1696", # gcr.io/google-appengine/python:latest "ubuntu16_04_python3": "sha256:67fd35064a812fd0ba0a6e9485410f9f2710ebf7b0787a7b350ce6a20f166bfe", ########################################################### # Clang images # ########################################################### # gcr.io/cloud-marketplace/google/clang-debian8:r337145 "debian8_clang": "sha256:de1116d36eafe16890afd64b6bc6809a3ed5b3597ed7bc857980749270894677", # gcr.io/cloud-marketplace/google/clang-ubuntu:r337145 "ubuntu16_04_clang": "sha256:fbf123ca7c7696f53864da4f7d1d9470f9ef4ebfabc4344f44173d1951faee6f", }
def toolchain_container_sha256s(): return {'debian8': 'sha256:a6df7738c401aef6bf9c113eb1eea7f3921417fd4711ea28100681f2fe483ea2', 'debian9': 'sha256:1d6a9a6d106bd795098f60f4abb7083626354fa6735e81743c7f8cfca11259f0', 'ubuntu16_04': 'sha256:8a12cc26c62e2f9824aada8d13c1f0c2d2847d18191560e1500d651a709d6550', 'debian8_python3': 'sha256:ace668f0f01e5e562ad09c3f128488ec33fa9126313f16505a86ae77865d1696', 'ubuntu16_04_python3': 'sha256:67fd35064a812fd0ba0a6e9485410f9f2710ebf7b0787a7b350ce6a20f166bfe', 'debian8_clang': 'sha256:de1116d36eafe16890afd64b6bc6809a3ed5b3597ed7bc857980749270894677', 'ubuntu16_04_clang': 'sha256:fbf123ca7c7696f53864da4f7d1d9470f9ef4ebfabc4344f44173d1951faee6f'}
''' Bucket Sort Bucket sort works as follows: 1. Set up an array of initially empty "buckets". 2. Scatter: Go over the original array, putting each object in its bucket. 3. Sort each non-empty bucket. 4. Gather: Visit the buckets in order and put all elements back into the original array. https://en.wikipedia.org/wiki/Bucket_sort Complexity: O(n^2) The complexity is dominated by nextSort ''' def bucket_sort(arr): # The number of buckets and make buckets num_buckets = len(arr) buckets = [[] for bucket in range(num_buckets)] # Assign values into bucket_sort for value in arr: index = value * num_buckets // (max(arr) + 1) buckets[index].append(value) # Sort sorted_list = [] for i in range(num_buckets): sorted_list.extend(next_sort(buckets[i])) return sorted_list def next_sort(arr): # We will use insertion sort here. for i in range(1, len(arr)): j = i - 1 key = arr[i] while arr[j] > key and j >= 0: arr[j+1] = arr[j] j = j - 1 arr[j + 1] = key return arr def main(): array = [1,5,8,0,150,44,4,3,6] #static inputs result = bucket_sort(array) print(result) if __name__=="__main__": main()
""" Bucket Sort Bucket sort works as follows: 1. Set up an array of initially empty "buckets". 2. Scatter: Go over the original array, putting each object in its bucket. 3. Sort each non-empty bucket. 4. Gather: Visit the buckets in order and put all elements back into the original array. https://en.wikipedia.org/wiki/Bucket_sort Complexity: O(n^2) The complexity is dominated by nextSort """ def bucket_sort(arr): num_buckets = len(arr) buckets = [[] for bucket in range(num_buckets)] for value in arr: index = value * num_buckets // (max(arr) + 1) buckets[index].append(value) sorted_list = [] for i in range(num_buckets): sorted_list.extend(next_sort(buckets[i])) return sorted_list def next_sort(arr): for i in range(1, len(arr)): j = i - 1 key = arr[i] while arr[j] > key and j >= 0: arr[j + 1] = arr[j] j = j - 1 arr[j + 1] = key return arr def main(): array = [1, 5, 8, 0, 150, 44, 4, 3, 6] result = bucket_sort(array) print(result) if __name__ == '__main__': main()
""" Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: 9 / \ 7 15 / \ \ 3 8 20 BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false IDEA: 1) collect on the stack the list of all leftmost nodes 2) alg for each node: a) return the cur elem on the stack (which is always the leftmost) b) check the right branch - if exists, invoke leftmostInorder() """ class Solution173: pass
""" Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST. Calling next() will return the next smallest number in the BST. Example: 9 / 7 15 / \\ 3 8 20 BSTIterator iterator = new BSTIterator(root); iterator.next(); // return 3 iterator.next(); // return 7 iterator.hasNext(); // return true iterator.next(); // return 9 iterator.hasNext(); // return true iterator.next(); // return 15 iterator.hasNext(); // return true iterator.next(); // return 20 iterator.hasNext(); // return false IDEA: 1) collect on the stack the list of all leftmost nodes 2) alg for each node: a) return the cur elem on the stack (which is always the leftmost) b) check the right branch - if exists, invoke leftmostInorder() """ class Solution173: pass
CREATE_NEW_USER = "CREATE TABLE user{}(bot_name text NOT NULL, " \ "greeting text NOT NULL, " \ "delay text NOT NULL, " \ "active text NOT NULL," \ "second_greeting text NOT NULL," \ "token text NOT NULL," \ "users text NOT NULL," \ "banned_users text NOT NULL," \ "user_id text NOT NULL," \ "ad bigint NOT NULL default 1," \ "second_greeting_active bigint NOT NULL default 0);" CREATE_USERS_TABLE = "CREATE TABLE user{}users(user_id text NOT NULL," \ "user_name text NOT NULL);" CREATE_COMMANDS_TABLE = "CREATE TABLE user{}commands(command_name text NOT NULL," \ "value text NOT NULL," \ "image text NOT NULL);" CREATE_BANNED_USERS_TABLE = "CREATE TABLE banned{}(user_id text NOT NULL);" INSERT_NEW_BOT = "INSERT INTO user{}(bot_name, " \ "greeting, " \ "second_greeting, " \ "delay, " \ "active," \ "token," \ "user_id," \ "banned_users," \ "users," \ "second_greeting_active) VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', {})" SELECT_ALL_USER_BOTS = "SELECT bot_name FROM user{}" GET_ALL_TABLES = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'" SELECT_GREETING = "SELECT greeting FROM user{} WHERE bot_name = '{}'" DELETE_COMMAND = "DELETE FROM user{}commands WHERE command_name = '{}';" ADD_COMMAND = "INSERT INTO user{}commands(command_name, value, image) VALUES('{}', '{}', '{}')" UPDATE_COMMAND = "UPDATE user{}commands SET value = '{}' WHERE command_name = '{}';" GET_COMMAND = "SELECT command_name FROM user{}commands" GET_COMMAND_VALUE = "SELECT value FROM user{}commands WHERE command_name = '{}'" DELETE_BOT = "DELETE FROM user{} WHERE bot_name = '{}';" SELECT_DELAY = "SELECT delay FROM user{} WHERE bot_name = '{}'" RESET_GREETING = "UPDATE user{} SET active = '{}' WHERE bot_name = '{}';" GET_GREETING_STATUS = "SELECT active FROM user{} WHERE bot_name = '{}';" SET_GREETING_STATUS_FOR_ALL = "UPDATE user{} SET active = '{}';" SET_GREETING_DELAY = "UPDATE user{} SET delay = '{}' WHERE bot_name = '{}';" SET_GREETING_DELAY_FOR_ALL = "UPDATE user{} SET active = '{}';" RESET_GREETING_MESSAGE = "UPDATE user{} SET greeting = '{}' WHERE bot_name = '{}';" RESET_GREETING_MESSAGE_FOR_ALL = "UPDATE user{} SET greeting = '{}';" SELECT_ALL_TOKENS = "SELECT token, user_id FROM {}" DELETE_INVALID_TOKEN = "DELETE FROM user{} WHERE token = '{}'" SET_SECOND_GREETING = "UPDATE user{} SET second_greeting = '{}' WHERE bot_name = '{}';" SET_SECOND_GREETING_FOR_ALL = "UPDATE user{} SET second_greeting = '{}';" SELECT_SECOND_GREETING = "SELECT second_greeting FROM user{} WHERE bot_name = '{}'" ADD_USER = "UPDATE user{} SET users = '{}' WHERE bot_name = '{}';" GET_ALL_USERS = "SELECT users FROM user{} WHERE bot_name = '{}';" GET_USERS_DUMP = "SELECT user_id FROM user{}users" INSERT_USER_INTO_DUMP = "INSERT INTO user{}users(user_id, user_name) VALUES('{}', '{}')" SELECT_ONE_TIME_TOKEN = "SELECT token FROM user{} WHERE bot_name = '{}';" DELETE_ALL_BOTS = "DELETE FROM user{}" SELECT_INFO_FOR_ALL_DISPATCH = "SELECT token, users FROM user{}" GET_BANNED_USERS_FOR_ONE_BOT = "SELECT banned_users FROM user{} WHERE bot_name = '{}';" ADD_NEW_BANNED_USER = "UPDATE user{} SET banned_users = '{}' WHERE bot_name = '{}';" SELECT_AD_STATUS = "SELECT ad FROM user{} WHERE bot_name = '{}'" SELECT_AD_STATUS_FOR_ALL = "SELECT ad FROM user{}" SET_AD = "UPDATE user{} SET ad = {} WHERE bot_name = '{}'" SET_AD_FOR_ALL = "UPDATE user{} SET ad = {}" GET_SECOND_GREETING_STATUS = "SELECT second_greeting_active FROM user{} WHERE bot_name = '{}'" GET_ALL_SECOND_GREETING_STATUS = "SELECT second_greeting_active FROM user{}" UPDATE_SECOND_GREETING_ACTIVE = "UPDATE user{} SET second_greeting_active = {} WHERE bot_name = '{}'" UPDATE_SECOND_GREETING_ACTIVE_ALL = "UPDATE user{} SET second_greeting_active = {}" CREATE_BUTTONS_TABLE = "CREATE TABLE user{}buttons(name text NOT NULL," \ "bot text NOT NULL," \ "value text NOT NULL," \ "active text NOT NULL);" ADD_BUTTON = "INSERT INTO user{}buttons(name, bot, value, active) VALUES('{}', '{}', '{}', '1')" GET_BUTTONS = "SELECT name FROM user{}buttons WHERE bot = '{}'" GET_BUTTON_VAL = "SELECT value FROM user{}buttons WHERE name = '{}' and bot = '{}'"
create_new_user = 'CREATE TABLE user{}(bot_name text NOT NULL, greeting text NOT NULL, delay text NOT NULL, active text NOT NULL,second_greeting text NOT NULL,token text NOT NULL,users text NOT NULL,banned_users text NOT NULL,user_id text NOT NULL,ad bigint NOT NULL default 1,second_greeting_active bigint NOT NULL default 0);' create_users_table = 'CREATE TABLE user{}users(user_id text NOT NULL,user_name text NOT NULL);' create_commands_table = 'CREATE TABLE user{}commands(command_name text NOT NULL,value text NOT NULL,image text NOT NULL);' create_banned_users_table = 'CREATE TABLE banned{}(user_id text NOT NULL);' insert_new_bot = "INSERT INTO user{}(bot_name, greeting, second_greeting, delay, active,token,user_id,banned_users,users,second_greeting_active) VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', {})" select_all_user_bots = 'SELECT bot_name FROM user{}' get_all_tables = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'" select_greeting = "SELECT greeting FROM user{} WHERE bot_name = '{}'" delete_command = "DELETE FROM user{}commands WHERE command_name = '{}';" add_command = "INSERT INTO user{}commands(command_name, value, image) VALUES('{}', '{}', '{}')" update_command = "UPDATE user{}commands SET value = '{}' WHERE command_name = '{}';" get_command = 'SELECT command_name FROM user{}commands' get_command_value = "SELECT value FROM user{}commands WHERE command_name = '{}'" delete_bot = "DELETE FROM user{} WHERE bot_name = '{}';" select_delay = "SELECT delay FROM user{} WHERE bot_name = '{}'" reset_greeting = "UPDATE user{} SET active = '{}' WHERE bot_name = '{}';" get_greeting_status = "SELECT active FROM user{} WHERE bot_name = '{}';" set_greeting_status_for_all = "UPDATE user{} SET active = '{}';" set_greeting_delay = "UPDATE user{} SET delay = '{}' WHERE bot_name = '{}';" set_greeting_delay_for_all = "UPDATE user{} SET active = '{}';" reset_greeting_message = "UPDATE user{} SET greeting = '{}' WHERE bot_name = '{}';" reset_greeting_message_for_all = "UPDATE user{} SET greeting = '{}';" select_all_tokens = 'SELECT token, user_id FROM {}' delete_invalid_token = "DELETE FROM user{} WHERE token = '{}'" set_second_greeting = "UPDATE user{} SET second_greeting = '{}' WHERE bot_name = '{}';" set_second_greeting_for_all = "UPDATE user{} SET second_greeting = '{}';" select_second_greeting = "SELECT second_greeting FROM user{} WHERE bot_name = '{}'" add_user = "UPDATE user{} SET users = '{}' WHERE bot_name = '{}';" get_all_users = "SELECT users FROM user{} WHERE bot_name = '{}';" get_users_dump = 'SELECT user_id FROM user{}users' insert_user_into_dump = "INSERT INTO user{}users(user_id, user_name) VALUES('{}', '{}')" select_one_time_token = "SELECT token FROM user{} WHERE bot_name = '{}';" delete_all_bots = 'DELETE FROM user{}' select_info_for_all_dispatch = 'SELECT token, users FROM user{}' get_banned_users_for_one_bot = "SELECT banned_users FROM user{} WHERE bot_name = '{}';" add_new_banned_user = "UPDATE user{} SET banned_users = '{}' WHERE bot_name = '{}';" select_ad_status = "SELECT ad FROM user{} WHERE bot_name = '{}'" select_ad_status_for_all = 'SELECT ad FROM user{}' set_ad = "UPDATE user{} SET ad = {} WHERE bot_name = '{}'" set_ad_for_all = 'UPDATE user{} SET ad = {}' get_second_greeting_status = "SELECT second_greeting_active FROM user{} WHERE bot_name = '{}'" get_all_second_greeting_status = 'SELECT second_greeting_active FROM user{}' update_second_greeting_active = "UPDATE user{} SET second_greeting_active = {} WHERE bot_name = '{}'" update_second_greeting_active_all = 'UPDATE user{} SET second_greeting_active = {}' create_buttons_table = 'CREATE TABLE user{}buttons(name text NOT NULL,bot text NOT NULL,value text NOT NULL,active text NOT NULL);' add_button = "INSERT INTO user{}buttons(name, bot, value, active) VALUES('{}', '{}', '{}', '1')" get_buttons = "SELECT name FROM user{}buttons WHERE bot = '{}'" get_button_val = "SELECT value FROM user{}buttons WHERE name = '{}' and bot = '{}'"
CONTENT = """Welcome to WhiteFly! =================== Create Change ------------- Create the change by editing the files **update.sql** and **rollback.sql**. Setting Environments ------------- Run below command to add a new environment: ``` whitefly env add <env-name> <connection-str> ``` Commit Change ------------- Run below command to commit your change: ``` whitefly commit -m "Your commit message" ``` """
content = 'Welcome to WhiteFly!\n===================\n\nCreate Change\n-------------\n\nCreate the change by editing the files **update.sql** and **rollback.sql**.\n\n\nSetting Environments\n-------------\nRun below command to add a new environment:\n```\nwhitefly env add <env-name> <connection-str>\n```\n\n\nCommit Change\n-------------\nRun below command to commit your change:\n```\nwhitefly commit -m "Your commit message"\n```\n'
class GithubUser: def __init__(self): self.id = None self.githubLogin = None self.userLogin = None def from_record(self, record): self.id = record[0] self.githubLogin = record[1] self.userLogin = record[2]
class Githubuser: def __init__(self): self.id = None self.githubLogin = None self.userLogin = None def from_record(self, record): self.id = record[0] self.githubLogin = record[1] self.userLogin = record[2]
def ehprimo(n): if n == 1 or n == 2: return True t = int(n**0.5 + 2) for i in range(2, t): if n % i == 0: return False return True n, m = [int(x) for x in input().split()] p1 = p2 = 0 while not p1: if ehprimo(n): p1 = n else: n -= 1 while not p2: if ehprimo(m): p2 = m else: m -= 1 print(p1*p2)
def ehprimo(n): if n == 1 or n == 2: return True t = int(n ** 0.5 + 2) for i in range(2, t): if n % i == 0: return False return True (n, m) = [int(x) for x in input().split()] p1 = p2 = 0 while not p1: if ehprimo(n): p1 = n else: n -= 1 while not p2: if ehprimo(m): p2 = m else: m -= 1 print(p1 * p2)
class MatrixCache: """ Possibility to store matrices in a Python cache outside of Visum. """ def __init__(self, logging): self.logging = logging self.matrix_cache = {} self.prob_matrices = {} self.skims_cache = {} def add_skim_to_cache(self, key, values): self.skims_cache[key] = values def get_skim(self, key): return self.skims_cache[key] def add_prob_mat_to_cache(self, key, matrix): self.prob_matrices[key] = matrix def get_prob_mat(self, key): self.logging.info("get matrix for segment " + key + " from cache.") return self.prob_matrices[key] def has_prob_mat(self, key): if key in self.prob_matrices.keys(): return True else: return False def add_matrix_to_cache(self, key, matrix): self.matrix_cache[key] = matrix def get_matrix(self, key): return self.matrix_cache[key] def has_matrix(self, key): if key in self.matrix_cache.keys(): return True else: return False
class Matrixcache: """ Possibility to store matrices in a Python cache outside of Visum. """ def __init__(self, logging): self.logging = logging self.matrix_cache = {} self.prob_matrices = {} self.skims_cache = {} def add_skim_to_cache(self, key, values): self.skims_cache[key] = values def get_skim(self, key): return self.skims_cache[key] def add_prob_mat_to_cache(self, key, matrix): self.prob_matrices[key] = matrix def get_prob_mat(self, key): self.logging.info('get matrix for segment ' + key + ' from cache.') return self.prob_matrices[key] def has_prob_mat(self, key): if key in self.prob_matrices.keys(): return True else: return False def add_matrix_to_cache(self, key, matrix): self.matrix_cache[key] = matrix def get_matrix(self, key): return self.matrix_cache[key] def has_matrix(self, key): if key in self.matrix_cache.keys(): return True else: return False
n = int(input()) for i in range(n): e = str(input()) print(int(e[2:4]) + int(e[5:8]) + int(e[11:13]))
n = int(input()) for i in range(n): e = str(input()) print(int(e[2:4]) + int(e[5:8]) + int(e[11:13]))
# -*- coding: utf-8 -*- template_engine_file_str = "no feature ospf" config_result = [["no feature ospf"], [{}]] initial_config = [ "\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:48 2019\n!Time: Wed Dec 4 15:33:55 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname n9k-device\ninstall feature-set fex\nvdc n9k-device id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature ospf\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 192.168.0.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 192.168.0.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n" ] modified_config = [ "\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:56 2019\n!Time: Wed Dec 4 15:33:56 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname n9k-device\ninstall feature-set fex\nvdc n9k-device id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 192.168.0.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 192.168.0.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n" ] config_input_file = """ feature bgp ! router bgp 55 address-family ipv4 unicast no client-to-client reflection additional-paths send """ template_engine_file_str_file = config_input_file config_result_file = [ [ "feature bgp", "!", "router bgp 55", " address-family ipv4 unicast", " no client-to-client reflection", " additional-paths send", ], [{}, {}, {}, {}, {}, {}], ] initial_config_file = [ "\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:56 2019\n!Time: Wed Dec 4 15:55:51 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname dt-n9k5-1\ninstall feature-set fex\nvdc dt-n9k5-1 id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 10.122.197.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 10.122.197.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n" ] modified_config_file = [ "\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:55:55 2019\n!Time: Wed Dec 4 15:55:55 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname dt-n9k5-1\ninstall feature-set fex\nvdc dt-n9k5-1 id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature bgp\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 10.122.197.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 10.122.197.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \nrouter bgp 55\n address-family ipv4 unicast\n no client-to-client reflection\n additional-paths send\n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n" ] delete_config = """ COMMAND_LIST: no feature bgp --- +++ @@ -19,7 +19,6 @@ feature bash-shell cfs eth distribute feature ngmvpn -feature bgp feature pim feature lldp @@ -234,10 +233,6 @@ line console line vty boot nxos bootflash:/nxos.9.2.4.bin -router bgp 55 - address-family ipv4 unicast - no client-to-client reflection - additional-paths send no logging logfile no logging monitor """ remove_user = """ COMMAND_LIST: no username salt_test --- +++ @@ -25,8 +25,6 @@ username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin username devops_user password 5 ! role network-operator username devops_user passphrase lifetime 99999 warntime 14 gracetime 3 -username salt_test password 5 $5$k8DulS4J$GGvG0RPTZdjklgJ4o6X25/AGpEHw1p1Dz8lI0.J77y3 role network-operator -username salt_test passphrase lifetime 99999 warntime 14 gracetime 3 ip domain-lookup ip name-server 1.1.1.1 2.2.2.2 no system default switchport @@ -39,7 +37,6 @@ copp profile strict snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey snmp-server user devops_user network-operator -snmp-server user salt_test network-operator auth md5 0x6a4237693d3e515b67264a7872476132 priv 0x6a4237693d3e515b67264a7872476132 localizedkey rmon event 1 description FATAL(1) owner PMON@FATAL rmon event 2 description CRITICAL(2) owner PMON@CRITICAL rmon event 3 description ERROR(3) owner PMON@ERROR """ save_running_config = """ COMMAND_LIST: copy running-config startup-config [# ] 1% [# ] 2% [## ] 3% [## ] 4% [### ] 5% [### ] 6% [### ] 7% [#### ] 8% [#### ] 9% [##### ] 10% [##### ] 11% [##### ] 12% [###### ] 13% [###### ] 14% [####### ] 15% [####### ] 16% [####### ] 17% [######## ] 18% [######## ] 19% [######### ] 20% [######### ] 21% [######### ] 22% [########## ] 23% [########## ] 24% [########### ] 25% [########### ] 26% [########### ] 27% [############ ] 28% [############ ] 29% [############# ] 30% [############# ] 31% [############# ] 32% [############## ] 33% [############## ] 34% [############### ] 35% [############### ] 36% [############### ] 37% [################ ] 38% [################ ] 39% [################# ] 40% [################# ] 41% [################# ] 42% [################## ] 43% [################## ] 44% [################### ] 45% [################### ] 46% [################### ] 47% [#################### ] 48% [##################### ] 50% [##################### ] 51% [##################### ] 52% [###################### ] 53% [###################### ] 54% [####################### ] 55% [####################### ] 56% [####################### ] 57% [######################## ] 58% [######################## ] 59% [######################### ] 60% [######################### ] 61% [######################### ] 62% [########################## ] 63% [########################## ] 64% [########################### ] 65% [########################### ] 66% [########################### ] 67% [############################ ] 68% [############################ ] 69% [############################# ] 70% [############################# ] 71% [############################# ] 72% [############################## ] 73% [############################## ] 74% [############################### ] 75% [############################### ] 76% [############################### ] 77% [################################ ] 78% [################################ ] 79% [################################# ] 80% [################################# ] 81% [################################# ] 82% [################################## ] 83% [################################## ] 84% [################################### ] 85% [################################### ] 86% [################################### ] 87% [#################################### ] 88% [#################################### ] 89% [##################################### ] 90% [##################################### ] 91% [##################################### ] 92% [###################################### ] 93% [###################################### ] 94% [####################################### ] 95% [####################################### ] 96% [####################################### ] 97% [########################################] 98% [########################################] 100% Copy complete, now saving to disk (please wait)... Copy complete. """ set_role = """ COMMAND_LIST: username salt_test role vdc-admin warning: password for user:salt_test not set. S/he may not be able to login --- +++ @@ -26,6 +26,8 @@ username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin username devops_user password 5 ! role network-operator username devops_user passphrase lifetime 99999 warntime 14 gracetime 3 +username salt_test password 5 ! role vdc-admin +username salt_test passphrase lifetime 99999 warntime 14 gracetime 3 ip domain-lookup ip name-server 1.1.1.1 2.2.2.2 no system default switchport @@ -38,6 +40,7 @@ copp profile strict snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey snmp-server user devops_user network-operator +snmp-server user salt_test vdc-admin rmon event 1 description FATAL(1) owner PMON@FATAL rmon event 2 description CRITICAL(2) owner PMON@CRITICAL rmon event 3 description ERROR(3) owner PMON@ERROR """ unset_role = """ COMMAND_LIST: no username salt_test role vdc-admin --- +++ @@ -26,8 +26,7 @@ username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin username ansible password 5 ! role network-operator username ansible passphrase lifetime 99999 warntime 14 gracetime 3 -username salt_test password 5 ! role vdc-admin -username salt_test role network-operator +username salt_test password 5 ! role network-operator username salt_test passphrase lifetime 99999 warntime 14 gracetime 3 ip domain-lookup ip name-server 1.1.1.1 2.2.2.2 @@ -41,8 +40,7 @@ copp profile strict snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey snmp-server user ansible network-operator -snmp-server user salt_test vdc-admin -snmp-server user salt_test network-operator +snmp-server user salt_test network-operator rmon event 1 description FATAL(1) owner PMON@FATAL rmon event 2 description CRITICAL(2) owner PMON@CRITICAL rmon event 3 description ERROR(3) owner PMON@ERROR """
template_engine_file_str = 'no feature ospf' config_result = [['no feature ospf'], [{}]] initial_config = ['\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:48 2019\n!Time: Wed Dec 4 15:33:55 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname n9k-device\ninstall feature-set fex\nvdc n9k-device id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature ospf\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 192.168.0.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 192.168.0.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n'] modified_config = ['\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:56 2019\n!Time: Wed Dec 4 15:33:56 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname n9k-device\ninstall feature-set fex\nvdc n9k-device id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 192.168.0.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 192.168.0.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n'] config_input_file = '\nfeature bgp\n!\nrouter bgp 55\n address-family ipv4 unicast\n no client-to-client reflection\n additional-paths send\n' template_engine_file_str_file = config_input_file config_result_file = [['feature bgp', '!', 'router bgp 55', ' address-family ipv4 unicast', ' no client-to-client reflection', ' additional-paths send'], [{}, {}, {}, {}, {}, {}]] initial_config_file = ['\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:33:56 2019\n!Time: Wed Dec 4 15:55:51 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname dt-n9k5-1\ninstall feature-set fex\nvdc dt-n9k5-1 id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 10.122.197.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 10.122.197.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n'] modified_config_file = ['\n!Command: show running-config\n!Running configuration last done at: Wed Dec 4 15:55:55 2019\n!Time: Wed Dec 4 15:55:55 2019\n\nversion 9.2(4) Bios:version 07.66 \nhostname dt-n9k5-1\ninstall feature-set fex\nvdc dt-n9k5-1 id 1\n allow feature-set fex\n limit-resource vlan minimum 16 maximum 4094\n limit-resource vrf minimum 2 maximum 4096\n limit-resource port-channel minimum 0 maximum 256\n limit-resource u4route-mem minimum 248 maximum 248\n limit-resource u6route-mem minimum 96 maximum 96\n limit-resource m4route-mem minimum 58 maximum 58\n limit-resource m6route-mem minimum 8 maximum 8\nfeature-set fex\n\nfeature privilege\nfeature telnet\nfeature nxapi\nfeature bash-shell\ncfs eth distribute\nfeature ngmvpn\nfeature bgp\nfeature pim\nfeature lldp\n\nusername admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\nusername devops_user password 5 ! role network-operator\nusername devops_user passphrase lifetime 99999 warntime 14 gracetime 3\nusername salt_test password 5 $5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC role network-operator\nusername salt_test passphrase lifetime 99999 warntime 14 gracetime 3\nip domain-lookup\nip name-server 1.1.1.1 2.2.2.2\nno system default switchport\nsystem default switchport shutdown\nno logging event link-status default\nno logging event link-status enable\nno logging event trunk-status enable\ntime-range ans-range\ntime-range my_range\ncopp profile strict\nsnmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\nsnmp-server user devops_user network-operator \nsnmp-server user salt_test network-operator auth md5 0x3a16a4d0a569be282cc5fbc96138fac8 priv 0x3a16a4d0a569be282cc5fbc96138fac8 localizedkey\nrmon event 1 description FATAL(1) owner PMON@FATAL\nrmon event 2 description CRITICAL(2) owner PMON@CRITICAL\nrmon event 3 description ERROR(3) owner PMON@ERROR\nrmon event 4 description WARNING(4) owner PMON@WARNING\nrmon event 5 description INFORMATION(5) owner PMON@INFO\nno snmp-server enable traps entity entity_mib_change\nno snmp-server enable traps entity entity_module_status_change\nno snmp-server enable traps entity entity_power_status_change\nno snmp-server enable traps entity entity_module_inserted\nno snmp-server enable traps entity entity_module_removed\nno snmp-server enable traps entity entity_unrecognised_module\nno snmp-server enable traps entity entity_fan_status_change\nno snmp-server enable traps entity entity_power_out_change\nno snmp-server enable traps link linkDown\nno snmp-server enable traps link linkUp\nno snmp-server enable traps link extended-linkDown\nno snmp-server enable traps link extended-linkUp\nno snmp-server enable traps link cieLinkDown\nno snmp-server enable traps link cieLinkUp\nno snmp-server enable traps link delayed-link-state-change\nno snmp-server enable traps rf redundancy_framework\nno snmp-server enable traps license notify-license-expiry\nno snmp-server enable traps license notify-no-license-for-feature\nno snmp-server enable traps license notify-licensefile-missing\nno snmp-server enable traps license notify-license-expiry-warning\nno snmp-server enable traps upgrade UpgradeOpNotifyOnCompletion\nno snmp-server enable traps upgrade UpgradeJobStatusNotify\nno snmp-server enable traps rmon risingAlarm\nno snmp-server enable traps rmon fallingAlarm\nno snmp-server enable traps rmon hcRisingAlarm\nno snmp-server enable traps rmon hcFallingAlarm\nno snmp-server enable traps entity entity_sensor\nno snmp-server enable traps entity cefcMIBEnableStatusNotification\nno snmp-server enable traps generic coldStart\nno snmp-server enable traps generic warmStart\nno snmp-server enable traps storm-control cpscEventRev1\nno snmp-server enable traps link cErrDisableInterfaceEventRev1\nno snmp-server enable traps link cmn-mac-move-notification\nntp server 10.81.254.202 use-vrf management\n\nip pim ssm range none\nvlan 1\n\nvrf context management\n ip route 0.0.0.0/0 10.122.197.1\nvrf context myvrf\nvrf context testing\nnxapi http port 80\nno nxapi https\nnxapi ssl ciphers weak\nnxapi ssl protocols TLSv1 \n\n\ninterface port-channel19\n\ninterface port-channel42\n\ninterface port-channel55\n\ninterface port-channel66\n\ninterface Ethernet1/1\n\ninterface Ethernet1/2\n\ninterface Ethernet1/3\n no shutdown\n\ninterface Ethernet1/4\n\ninterface Ethernet1/5\n\ninterface Ethernet1/6\n\ninterface Ethernet1/7\n\ninterface Ethernet1/8\n\ninterface Ethernet1/9\n\ninterface Ethernet1/10\n\ninterface Ethernet1/11\n\ninterface Ethernet1/12\n\ninterface Ethernet1/13\n\ninterface Ethernet1/14\n\ninterface Ethernet1/15\n\ninterface Ethernet1/16\n\ninterface Ethernet1/17\n\ninterface Ethernet1/18\n\ninterface Ethernet1/19\n\ninterface Ethernet1/20\n\ninterface Ethernet1/21\n\ninterface Ethernet1/22\n\ninterface Ethernet1/23\n\ninterface Ethernet1/24\n\ninterface Ethernet1/25\n\ninterface Ethernet1/26\n\ninterface Ethernet1/27\n\ninterface Ethernet1/28\n\ninterface Ethernet1/29\n\ninterface Ethernet1/30\n\ninterface Ethernet1/31\n\ninterface Ethernet1/32\n\ninterface Ethernet1/33\n\ninterface Ethernet1/34\n\ninterface Ethernet1/35\n\ninterface Ethernet1/36\n\ninterface Ethernet1/37\n\ninterface Ethernet1/38\n\ninterface Ethernet1/39\n\ninterface Ethernet1/40\n\ninterface Ethernet1/41\n\ninterface Ethernet1/42\n\ninterface Ethernet1/43\n\ninterface Ethernet1/44\n\ninterface Ethernet1/45\n\ninterface Ethernet1/46\n\ninterface Ethernet1/47\n\ninterface Ethernet1/48\n\ninterface Ethernet2/1\n\ninterface Ethernet2/2\n\ninterface Ethernet2/3\n\ninterface Ethernet2/4\n\ninterface Ethernet2/5\n\ninterface Ethernet2/6\n\ninterface Ethernet2/7\n\ninterface Ethernet2/8\n\ninterface Ethernet2/9\n\ninterface Ethernet2/10\n\ninterface Ethernet2/11\n\ninterface Ethernet2/12\n\ninterface mgmt0\n vrf member management\n ip address 10.122.197.192/24\n\ninterface loopback0\n\ninterface loopback1\ncli alias name wr copy running startup-config\nline console\nline vty\nboot nxos bootflash:/nxos.9.2.4.bin \nrouter bgp 55\n address-family ipv4 unicast\n no client-to-client reflection\n additional-paths send\n\nno logging logfile\nno logging monitor\nno logging module\nno logging console\n\n\n'] delete_config = '\nCOMMAND_LIST: no feature bgp\n\n---\n+++\n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature bgp\n feature pim\n feature lldp\n\n@@ -234,10 +233,6 @@\n line console\n line vty\n boot nxos bootflash:/nxos.9.2.4.bin\n-router bgp 55\n- address-family ipv4 unicast\n- no client-to-client reflection\n- additional-paths send\n\n no logging logfile\n no logging monitor\n ' remove_user = '\nCOMMAND_LIST: no username salt_test\n\n---\n+++\n@@ -25,8 +25,6 @@\n username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\n username devops_user password 5 ! role network-operator\n username devops_user passphrase lifetime 99999 warntime 14 gracetime 3\n-username salt_test password 5 $5$k8DulS4J$GGvG0RPTZdjklgJ4o6X25/AGpEHw1p1Dz8lI0.J77y3 role network-operator\n-username salt_test passphrase lifetime 99999 warntime 14 gracetime 3\n ip domain-lookup\n ip name-server 1.1.1.1 2.2.2.2\n no system default switchport\n@@ -39,7 +37,6 @@\n copp profile strict\n snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\n snmp-server user devops_user network-operator\n-snmp-server user salt_test network-operator auth md5 0x6a4237693d3e515b67264a7872476132 priv 0x6a4237693d3e515b67264a7872476132 localizedkey\n rmon event 1 description FATAL(1) owner PMON@FATAL\n rmon event 2 description CRITICAL(2) owner PMON@CRITICAL\n rmon event 3 description ERROR(3) owner PMON@ERROR\n ' save_running_config = '\nCOMMAND_LIST: copy running-config startup-config\n\n[# ] 1%\n[# ] 2%\n[## ] 3%\n[## ] 4%\n[### ] 5%\n[### ] 6%\n[### ] 7%\n[#### ] 8%\n[#### ] 9%\n[##### ] 10%\n[##### ] 11%\n[##### ] 12%\n[###### ] 13%\n[###### ] 14%\n[####### ] 15%\n[####### ] 16%\n[####### ] 17%\n[######## ] 18%\n[######## ] 19%\n[######### ] 20%\n[######### ] 21%\n[######### ] 22%\n[########## ] 23%\n[########## ] 24%\n[########### ] 25%\n[########### ] 26%\n[########### ] 27%\n[############ ] 28%\n[############ ] 29%\n[############# ] 30%\n[############# ] 31%\n[############# ] 32%\n[############## ] 33%\n[############## ] 34%\n[############### ] 35%\n[############### ] 36%\n[############### ] 37%\n[################ ] 38%\n[################ ] 39%\n[################# ] 40%\n[################# ] 41%\n[################# ] 42%\n[################## ] 43%\n[################## ] 44%\n[################### ] 45%\n[################### ] 46%\n[################### ] 47%\n[#################### ] 48%\n[##################### ] 50%\n[##################### ] 51%\n[##################### ] 52%\n[###################### ] 53%\n[###################### ] 54%\n[####################### ] 55%\n[####################### ] 56%\n[####################### ] 57%\n[######################## ] 58%\n[######################## ] 59%\n[######################### ] 60%\n[######################### ] 61%\n[######################### ] 62%\n[########################## ] 63%\n[########################## ] 64%\n[########################### ] 65%\n[########################### ] 66%\n[########################### ] 67%\n[############################ ] 68%\n[############################ ] 69%\n[############################# ] 70%\n[############################# ] 71%\n[############################# ] 72%\n[############################## ] 73%\n[############################## ] 74%\n[############################### ] 75%\n[############################### ] 76%\n[############################### ] 77%\n[################################ ] 78%\n[################################ ] 79%\n[################################# ] 80%\n[################################# ] 81%\n[################################# ] 82%\n[################################## ] 83%\n[################################## ] 84%\n[################################### ] 85%\n[################################### ] 86%\n[################################### ] 87%\n[#################################### ] 88%\n[#################################### ] 89%\n[##################################### ] 90%\n[##################################### ] 91%\n[##################################### ] 92%\n[###################################### ] 93%\n[###################################### ] 94%\n[####################################### ] 95%\n[####################################### ] 96%\n[####################################### ] 97%\n[########################################] 98%\n[########################################] 100%\nCopy complete, now saving to disk (please wait)...\nCopy complete.\n' set_role = '\nCOMMAND_LIST: username salt_test role vdc-admin\nwarning: password for user:salt_test not set. S/he may not be able to login\n\n---\n+++\n@@ -26,6 +26,8 @@\n username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\n username devops_user password 5 ! role network-operator\n username devops_user passphrase lifetime 99999 warntime 14 gracetime 3\n+username salt_test password 5 ! role vdc-admin\n+username salt_test passphrase lifetime 99999 warntime 14 gracetime 3\n ip domain-lookup\n ip name-server 1.1.1.1 2.2.2.2\n no system default switchport\n@@ -38,6 +40,7 @@\n copp profile strict\n snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\n snmp-server user devops_user network-operator\n+snmp-server user salt_test vdc-admin\n rmon event 1 description FATAL(1) owner PMON@FATAL\n rmon event 2 description CRITICAL(2) owner PMON@CRITICAL\n rmon event 3 description ERROR(3) owner PMON@ERROR\n' unset_role = '\nCOMMAND_LIST: no username salt_test role vdc-admin\n\n---\n+++\n@@ -26,8 +26,7 @@\n username admin password 5 $5$mOJsBDrL$lhsuyA8VT/fkWM/5XaZcgHlJIYaaS/J5fh8qdDr6fU3 role network-admin\n username ansible password 5 ! role network-operator\n username ansible passphrase lifetime 99999 warntime 14 gracetime 3\n-username salt_test password 5 ! role vdc-admin\n-username salt_test role network-operator\n+username salt_test password 5 ! role network-operator\n username salt_test passphrase lifetime 99999 warntime 14 gracetime 3\n ip domain-lookup\n ip name-server 1.1.1.1 2.2.2.2\n@@ -41,8 +40,7 @@\n copp profile strict\n snmp-server user admin network-admin auth md5 0xbb62c3df89880933539503f7675e8aa8 priv 0xbb62c3df89880933539503f7675e8aa8 localizedkey\n snmp-server user ansible network-operator\n-snmp-server user salt_test vdc-admin\n-snmp-server user salt_test network-operator\n+snmp-server user salt_test network-operator\n rmon event 1 description FATAL(1) owner PMON@FATAL\n rmon event 2 description CRITICAL(2) owner PMON@CRITICAL\n rmon event 3 description ERROR(3) owner PMON@ERROR\n'
#!/usr/bin/env python3 with open("input") as f: expenses = [int(num.strip()) for num in f.readlines()] def part1(expenses, target=2020): seen = set() for value in expenses: if target - value in seen: return value * (target - value) seen.add(value) def part2(expenses: set): expenses = set(expenses) target = 2020 for a in expenses: for b in expenses: if target - a - b in expenses: return a * b * (target - a - b) print(f"part1: {part1(expenses)}") # 858496 print(f"part2: {part2(expenses)}") # 263819430
with open('input') as f: expenses = [int(num.strip()) for num in f.readlines()] def part1(expenses, target=2020): seen = set() for value in expenses: if target - value in seen: return value * (target - value) seen.add(value) def part2(expenses: set): expenses = set(expenses) target = 2020 for a in expenses: for b in expenses: if target - a - b in expenses: return a * b * (target - a - b) print(f'part1: {part1(expenses)}') print(f'part2: {part2(expenses)}')
_base_ = './kd_resnet18_resnet50_cifar100_equal.py' # model settings model = dict( adaptive=True, adaptation = dict(out_channels=[256, 512, 1024, 2048], in_channels=[64, 128, 256, 512]), distill_losses=[ dict(type='FeatureMap', mode='feature', loss_weight=1.0), dict(type='SoftmaxRegression', mode='softmax_regression', loss_weight=1.0), ])
_base_ = './kd_resnet18_resnet50_cifar100_equal.py' model = dict(adaptive=True, adaptation=dict(out_channels=[256, 512, 1024, 2048], in_channels=[64, 128, 256, 512]), distill_losses=[dict(type='FeatureMap', mode='feature', loss_weight=1.0), dict(type='SoftmaxRegression', mode='softmax_regression', loss_weight=1.0)])
""" Create new series holding images of the same slice location. If images are selected from multiple studies then a new series is created inside each study. """ def enable(weasel): return False def main(weasel): images = weasel.images() studies = images.parent.parent for study in studies: imgs = study.all_images new_study_description = 'Sorted by slice location_' + study.studyID series_number = 1 for loc in weasel.unique_elements(imgs.get_value("SliceLocation")): imgs_loc = imgs.where("SliceLocation", "==", loc) series = imgs_loc.merge(series_number=series_number, series_name='Slice location [' + str(loc) + ']', study_name=new_study_description, progress_bar=False, overwrite=False) series_number += 1 # loc can be series_number actually weasel.refresh() def suggestion(weasel): # Get all images checked by the user images = weasel.images() # Loop over the studies that the images are part of for study in images.studies(): # Get the part of the images that are in the study imgs = images.of(study) # Create a new study new_study = study.new_sibling(StudyDescription = 'Sorted by slice location') # Loop over the unique slice locations for loc in imgs.SliceLocation.unique(): # get the images at slice location loc imgs_loc = imgs.where("SliceLocation" == loc) # store those images in a new series of the new study series = new_study.new_child(imgs_loc) # rename the series with the slice location series.SeriesDescription = 'Slice location [' + str(loc) + ']'
""" Create new series holding images of the same slice location. If images are selected from multiple studies then a new series is created inside each study. """ def enable(weasel): return False def main(weasel): images = weasel.images() studies = images.parent.parent for study in studies: imgs = study.all_images new_study_description = 'Sorted by slice location_' + study.studyID series_number = 1 for loc in weasel.unique_elements(imgs.get_value('SliceLocation')): imgs_loc = imgs.where('SliceLocation', '==', loc) series = imgs_loc.merge(series_number=series_number, series_name='Slice location [' + str(loc) + ']', study_name=new_study_description, progress_bar=False, overwrite=False) series_number += 1 weasel.refresh() def suggestion(weasel): images = weasel.images() for study in images.studies(): imgs = images.of(study) new_study = study.new_sibling(StudyDescription='Sorted by slice location') for loc in imgs.SliceLocation.unique(): imgs_loc = imgs.where('SliceLocation' == loc) series = new_study.new_child(imgs_loc) series.SeriesDescription = 'Slice location [' + str(loc) + ']'
a = 5 #chk>{{{ #chk>gANDIEfymvjN9EowcCGj+XNtin7uihFyNxXkbW2Myny7GZzJcQAugAN9cQAoWAwAAABfX2J1aWx0aW5z #chk>X19xAWNidWlsdGlucwpfX2RpY3RfXwpYAQAAAGFxAksFdS4= #chk>}}} print(a) #o> 5
a = 5 print(a)
__author__ = 'Robert Eviston' def caesar(s, k, decrypt=False): if decrypt: k = 26 - k r = "" for i in s: if (ord(i) >= 65 and ord(i) <= 90): r += chr((ord(i) - 65 + k) % 26 +65) elif (ord(i) >= 97 and ord(i) <= 122): r += chr((ord(i) - 97 + k) % 26 + 97) else: r += i return r def encrypt(p, k): return caesar(p, k) def decrypt(c, k): return caesar(c, k, True) def main(): string1 = "And I shall remain satisfied, and proud to have been the first who has ever enjoyed the fruit " + "of his writings as fully as he could desire; for my desire has been no other than to deliver " + "over to the detestation of manking the false and foolish tales of the books of chivalry, which, " + "thanks to that of my true Don Quixote, are even now tottering, and doubtless doomed to fall for " + "ever. Farewell." key = -3 print("Original String1: " + string1 + "\n") beforeString1 = encrypt(string1, key) print("Encrypted string1: " + beforeString1 + "\n") afterString1 = (decrypt(beforeString1, key)) print("Decrypted string1: " + afterString1 + "\n") if __name__ == "__main__": main()
__author__ = 'Robert Eviston' def caesar(s, k, decrypt=False): if decrypt: k = 26 - k r = '' for i in s: if ord(i) >= 65 and ord(i) <= 90: r += chr((ord(i) - 65 + k) % 26 + 65) elif ord(i) >= 97 and ord(i) <= 122: r += chr((ord(i) - 97 + k) % 26 + 97) else: r += i return r def encrypt(p, k): return caesar(p, k) def decrypt(c, k): return caesar(c, k, True) def main(): string1 = 'And I shall remain satisfied, and proud to have been the first who has ever enjoyed the fruit ' + 'of his writings as fully as he could desire; for my desire has been no other than to deliver ' + 'over to the detestation of manking the false and foolish tales of the books of chivalry, which, ' + 'thanks to that of my true Don Quixote, are even now tottering, and doubtless doomed to fall for ' + 'ever. Farewell.' key = -3 print('Original String1: ' + string1 + '\n') before_string1 = encrypt(string1, key) print('Encrypted string1: ' + beforeString1 + '\n') after_string1 = decrypt(beforeString1, key) print('Decrypted string1: ' + afterString1 + '\n') if __name__ == '__main__': main()
def get_tree_h(tree): if not isinstance(tree, BST): raise ValueError("input must be a binary search tree") h = 0 curnodes = [tree.head] nextnodes = [] while len(curnodes) > 0: for n in curnodes: if n.right: nextnodes.append(n.right) if n.left: nextnodes.append(n.left) curnodes = nextnodes[:] nextnodes = [] h += 1 return h - 1
def get_tree_h(tree): if not isinstance(tree, BST): raise value_error('input must be a binary search tree') h = 0 curnodes = [tree.head] nextnodes = [] while len(curnodes) > 0: for n in curnodes: if n.right: nextnodes.append(n.right) if n.left: nextnodes.append(n.left) curnodes = nextnodes[:] nextnodes = [] h += 1 return h - 1
# -*- coding: utf-8 -*- """ Created on Thu Dec 7 20:05:53 2017 @author: User """ #without helper functions def draw(a,b): c, d = 0, b for i in range(b): print(a*b) b -= 1 if b == 0: print('============', end="") for i in range(d): print(a*c) c += 1 # with helper functions #def draw(a,b): # updraw(a,b) # print('============') # downdraw(a,b) # #def updraw(a,b): # for i in range(b): # print(a*b) # b -= 1 #def downdraw(a,b): # c = 0 # for i in range(b): # c += 1 # print(a*c) draw('~', 10) draw('*', 12)
""" Created on Thu Dec 7 20:05:53 2017 @author: User """ def draw(a, b): (c, d) = (0, b) for i in range(b): print(a * b) b -= 1 if b == 0: print('============', end='') for i in range(d): print(a * c) c += 1 draw('~', 10) draw('*', 12)
def dict_generator(words_dict): def _generator(field: dict, strategies): for n in words_dict: yield n return _generator
def dict_generator(words_dict): def _generator(field: dict, strategies): for n in words_dict: yield n return _generator
class Solution(object): def merge(self, intervals): if not intervals: return [] length = len(intervals) if length == 1: return intervals intervals.sort(key=lambda x: x[0]) res = [intervals[0]] for i in range(length): if intervals[i][0] <= res[-1][1]: res[-1][1] = max(intervals[i][1], res[-1][1]) else: res.append(intervals[i]) return res intervals = [[1,3],[2,6],[8,10],[15,18]] res = Solution().merge(intervals) print(res)
class Solution(object): def merge(self, intervals): if not intervals: return [] length = len(intervals) if length == 1: return intervals intervals.sort(key=lambda x: x[0]) res = [intervals[0]] for i in range(length): if intervals[i][0] <= res[-1][1]: res[-1][1] = max(intervals[i][1], res[-1][1]) else: res.append(intervals[i]) return res intervals = [[1, 3], [2, 6], [8, 10], [15, 18]] res = solution().merge(intervals) print(res)
class Consumers: def __init__(self, consumer_id, consumer_name, consumer_age, consumer_cep, consumer_wallet): self.orders_errors = 0 self.consumer_id = consumer_id self.consumer_name = consumer_name self.consumer_age = consumer_age self.consumer_CEP = consumer_cep self.consumer_wallet = consumer_wallet self.bad_orders = [] def subtract_wallet(self, quantity): if float(quantity) <= float(self.consumer_wallet): self.consumer_wallet = float(self.consumer_wallet) - float(quantity) return True else: return False def add_order_error(self, order_id, product_id, product_name): bad_orders = { 'Order_id': order_id, 'Product_id': product_id, 'Product_name': product_name } self.bad_orders.append(bad_orders) def error_number(self): return len(self.bad_orders) def get_errors(self): return self.bad_orders
class Consumers: def __init__(self, consumer_id, consumer_name, consumer_age, consumer_cep, consumer_wallet): self.orders_errors = 0 self.consumer_id = consumer_id self.consumer_name = consumer_name self.consumer_age = consumer_age self.consumer_CEP = consumer_cep self.consumer_wallet = consumer_wallet self.bad_orders = [] def subtract_wallet(self, quantity): if float(quantity) <= float(self.consumer_wallet): self.consumer_wallet = float(self.consumer_wallet) - float(quantity) return True else: return False def add_order_error(self, order_id, product_id, product_name): bad_orders = {'Order_id': order_id, 'Product_id': product_id, 'Product_name': product_name} self.bad_orders.append(bad_orders) def error_number(self): return len(self.bad_orders) def get_errors(self): return self.bad_orders
__name__ = 'notebook_autorun' name_url = __name__.replace('_', '-') __version__ = '0.1.7' __description__ = 'Auto run certain cells upon notebook start - if trusted' __author__ = 'oscar6echo' __author_email__ = 'olivier.borderies@gmail.com' __url__ = 'https://github.com/oscar6echo/{}'.format(name_url) __download_url__ = 'https://github.com/oscar6echo/{}/tarball/{}'.format(name_url, __version__) __keywords__ = ['python', 'display', 'javascript'] __license__ = 'MIT' __classifiers__ = ['Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6' ] __include_package_data__ = True __package_data__ = { 'templates': ['templates/getCellsFromComment.js', 'templates/getCellsFromMetadata.js', 'templates/getCellsFromString.js', 'templates/notice_short.md', 'templates/notice_long.md', 'templates/notice_safe.txt' ] }
__name__ = 'notebook_autorun' name_url = __name__.replace('_', '-') __version__ = '0.1.7' __description__ = 'Auto run certain cells upon notebook start - if trusted' __author__ = 'oscar6echo' __author_email__ = 'olivier.borderies@gmail.com' __url__ = 'https://github.com/oscar6echo/{}'.format(name_url) __download_url__ = 'https://github.com/oscar6echo/{}/tarball/{}'.format(name_url, __version__) __keywords__ = ['python', 'display', 'javascript'] __license__ = 'MIT' __classifiers__ = ['Development Status :: 4 - Beta', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6'] __include_package_data__ = True __package_data__ = {'templates': ['templates/getCellsFromComment.js', 'templates/getCellsFromMetadata.js', 'templates/getCellsFromString.js', 'templates/notice_short.md', 'templates/notice_long.md', 'templates/notice_safe.txt']}
# Time: O(n) # Space: O(k) class Solution(object): def checkSubarraySum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ count = 0 lookup = {0: -1} for i, num in enumerate(nums): count += num if k: count %= k if count in lookup: if i - lookup[count] > 1: return True else: lookup[count] = i return False
class Solution(object): def check_subarray_sum(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ count = 0 lookup = {0: -1} for (i, num) in enumerate(nums): count += num if k: count %= k if count in lookup: if i - lookup[count] > 1: return True else: lookup[count] = i return False
# Twitter keys and access tokens need to be specified once you create your twitter application. # The information in this file is meant for private use so be careful not to share your keys consumer_key = 'Enter consumer_key obtained from twitter' consumer_secret = 'Enter consumer_secret obtained from twitter' access_token = 'Enter access_token obtained from twitter' access_token_secret = 'Enter access_token_secret obtained from twitter'
consumer_key = 'Enter consumer_key obtained from twitter' consumer_secret = 'Enter consumer_secret obtained from twitter' access_token = 'Enter access_token obtained from twitter' access_token_secret = 'Enter access_token_secret obtained from twitter'
#~ def product(x,y,z=10): #~ print(x*y*z) #~ product(2,3) #~ def product(x=1,y=10,z): #~ print(x*y*z) #~ product(2,3) def product(x,y,z=10): print(x) print(y) print(z) #~ print(x*y*z) #~ product(2,3) product(2,3,100)
def product(x, y, z=10): print(x) print(y) print(z) product(2, 3, 100)
""" RPi.Relay Version: 0.1.0 Homepage: https://github.com/ricco386/RPi/tree/master/RPi.Relay This software is licensed as described in the README.rst and LICENSE files, which you should have received as part of this distribution. """ __version__ = '0.1.0'
""" RPi.Relay Version: 0.1.0 Homepage: https://github.com/ricco386/RPi/tree/master/RPi.Relay This software is licensed as described in the README.rst and LICENSE files, which you should have received as part of this distribution. """ __version__ = '0.1.0'
class fHDHR_Detect(): def __init__(self, fhdhr): self.fhdhr = fhdhr self.fhdhr.db.delete_fhdhr_value("ssdp_detect", "list") def set(self, location): detect_list = self.fhdhr.db.get_fhdhr_value("ssdp_detect", "list") or [] if location not in detect_list: detect_list.append(location) self.fhdhr.db.set_fhdhr_value("ssdp_detect", "list", detect_list) def get(self): return self.fhdhr.db.get_fhdhr_value("ssdp_detect", "list") or [] class Plugin_OBJ(): def __init__(self, fhdhr, plugin_utils, broadcast_ip, max_age): self.fhdhr = fhdhr self.detect_method = fHDHR_Detect(fhdhr) self.broadcast_ip = broadcast_ip self.device_xml_path = '/cluster/device.xml' self.schema = "upnp:rootdevice" self.max_age = max_age @property def enabled(self): return self.fhdhr.config.dict["cluster"]["enabled"] @property def notify(self): data = '' data_command = "NOTIFY * HTTP/1.1" data_dict = { "HOST": "%s:%d" % ("239.255.255.250", 1900), "NTS": "ssdp:alive", "USN": 'uuid:%s::%s' % (self.fhdhr.config.dict["main"]["uuid"], self.schema), "LOCATION": "%s%s" % (self.fhdhr.api.base, self.device_xml_path), "EXT": '', "SERVER": 'fHDHR/%s UPnP/1.0' % self.fhdhr.version, "Cache-Control:max-age=": self.max_age, "NT": self.schema, } data += "%s\r\n" % data_command for data_key in list(data_dict.keys()): data += "%s:%s\r\n" % (data_key, data_dict[data_key]) data += "\r\n" return data def on_recv(self, headers, cmd, ssdp_handling): if cmd[0] == 'NOTIFY' and cmd[1] == '*': try: if headers["server"].startswith("fHDHR"): if headers["location"].endswith("/device.xml"): savelocation = headers["location"].split("/device.xml")[0] if savelocation.endswith("/cluster"): savelocation = savelocation.replace("/cluster", '') if savelocation != self.fhdhr.api.base: self.detect_method.set(savelocation) except KeyError: return
class Fhdhr_Detect: def __init__(self, fhdhr): self.fhdhr = fhdhr self.fhdhr.db.delete_fhdhr_value('ssdp_detect', 'list') def set(self, location): detect_list = self.fhdhr.db.get_fhdhr_value('ssdp_detect', 'list') or [] if location not in detect_list: detect_list.append(location) self.fhdhr.db.set_fhdhr_value('ssdp_detect', 'list', detect_list) def get(self): return self.fhdhr.db.get_fhdhr_value('ssdp_detect', 'list') or [] class Plugin_Obj: def __init__(self, fhdhr, plugin_utils, broadcast_ip, max_age): self.fhdhr = fhdhr self.detect_method = f_hdhr__detect(fhdhr) self.broadcast_ip = broadcast_ip self.device_xml_path = '/cluster/device.xml' self.schema = 'upnp:rootdevice' self.max_age = max_age @property def enabled(self): return self.fhdhr.config.dict['cluster']['enabled'] @property def notify(self): data = '' data_command = 'NOTIFY * HTTP/1.1' data_dict = {'HOST': '%s:%d' % ('239.255.255.250', 1900), 'NTS': 'ssdp:alive', 'USN': 'uuid:%s::%s' % (self.fhdhr.config.dict['main']['uuid'], self.schema), 'LOCATION': '%s%s' % (self.fhdhr.api.base, self.device_xml_path), 'EXT': '', 'SERVER': 'fHDHR/%s UPnP/1.0' % self.fhdhr.version, 'Cache-Control:max-age=': self.max_age, 'NT': self.schema} data += '%s\r\n' % data_command for data_key in list(data_dict.keys()): data += '%s:%s\r\n' % (data_key, data_dict[data_key]) data += '\r\n' return data def on_recv(self, headers, cmd, ssdp_handling): if cmd[0] == 'NOTIFY' and cmd[1] == '*': try: if headers['server'].startswith('fHDHR'): if headers['location'].endswith('/device.xml'): savelocation = headers['location'].split('/device.xml')[0] if savelocation.endswith('/cluster'): savelocation = savelocation.replace('/cluster', '') if savelocation != self.fhdhr.api.base: self.detect_method.set(savelocation) except KeyError: return