content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
for i in range(1,9): print(i) a=2 b=1 print(a,b) #print a
for i in range(1, 9): print(i) a = 2 b = 1 print(a, b)
secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input('GUESS: ')) guess_count += 1 if guess == secret_number: print('YOU WON!') break else: print("SORRY YOU DID NOT GUESS THE CORRECT WORD")
secret_number = 9 guess_count = 0 guess_limit = 3 while guess_count < guess_limit: guess = int(input('GUESS: ')) guess_count += 1 if guess == secret_number: print('YOU WON!') break else: print('SORRY YOU DID NOT GUESS THE CORRECT WORD')
class Employee: company = "Google" salary = 100 location = "Delhi" @classmethod def changeSalary(cls,sal): cls.salary = sal print(f"The salary of the employee is {cls.salary}") e = Employee() e.changeSalary(455) print(e.salary) Employee.salary = 500 print(Employee.salary)
class Employee: company = 'Google' salary = 100 location = 'Delhi' @classmethod def change_salary(cls, sal): cls.salary = sal print(f'The salary of the employee is {cls.salary}') e = employee() e.changeSalary(455) print(e.salary) Employee.salary = 500 print(Employee.salary)
# -*- coding:utf-8 -*- ############################################################## # Created Date: Tuesday, December 29th 2020 # Contact Info: luoxiangyong01@gmail.com # Author/Copyright: Mr. Xiangyong Luo ############################################################## def writeTest(msg): print(msg) def writeTest1(msg): print(msg)
def write_test(msg): print(msg) def write_test1(msg): print(msg)
l = [{'key': 300}, {'key': 200}, {'key': 100}] print(l) l.sort(key = lambda x: x['key']) print(l)
l = [{'key': 300}, {'key': 200}, {'key': 100}] print(l) l.sort(key=lambda x: x['key']) print(l)
#!/usr/bin/env python # -*- coding: utf-8 -*- class MappingDocuments(object): def __init__(self): self.work_dir = None self.download_path = None self.ole_path = None self.id = None self.case_id = None self.case_name = None self.evdnc_id = None self.evdnc_name = None self.doc_id = None self.doc_type = None self.doc_type_sub = None self.full_path = None self.path_with_ext = None self.name = None self.ext = None self.creation_time = None self.last_access_time = None self.last_written_time = None self.original_size = None self.sha1_hash = None self.parent_full_path = None self.is_fail = None self.fail_code = None self.exclude_user_id = None #metadata self.has_metadata = None self.title = None self.subject = None self.author = None self.tags = None self.explanation = None self.lastsavedby = None self.lastprintedtime = None self.createdtime = None self.lastsavedtime = None self.comment = None self.revisionnumber = None self.category = None self.manager = None self.company = None self.programname = None self.totaltime = None self.creator = None self.trapped = None #content self.has_content = None self.content = None self.content_size = None self.is_damaged = None self.has_exif = None
class Mappingdocuments(object): def __init__(self): self.work_dir = None self.download_path = None self.ole_path = None self.id = None self.case_id = None self.case_name = None self.evdnc_id = None self.evdnc_name = None self.doc_id = None self.doc_type = None self.doc_type_sub = None self.full_path = None self.path_with_ext = None self.name = None self.ext = None self.creation_time = None self.last_access_time = None self.last_written_time = None self.original_size = None self.sha1_hash = None self.parent_full_path = None self.is_fail = None self.fail_code = None self.exclude_user_id = None self.has_metadata = None self.title = None self.subject = None self.author = None self.tags = None self.explanation = None self.lastsavedby = None self.lastprintedtime = None self.createdtime = None self.lastsavedtime = None self.comment = None self.revisionnumber = None self.category = None self.manager = None self.company = None self.programname = None self.totaltime = None self.creator = None self.trapped = None self.has_content = None self.content = None self.content_size = None self.is_damaged = None self.has_exif = None
num_0 = [ [1, 1, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1], [1, 1, 1] ] num_1 = [ [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0] ] num_2 = [ [1, 1, 1], [0, 0, 1], [1, 1, 1], [1, 0, 0], [1, 1, 1] ] num_3 = [ [1, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1] ] num_4 = [ [1, 0, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [0, 0, 1] ] num_5 = [ [1, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 1] ] num_6 = [ [1, 1, 1], [1, 0, 0], [1, 1, 1], [1, 0, 1], [1, 1, 1] ] num_7 = [ [1, 1, 1], [1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1] ] num_8 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1], [1, 0, 1], [1, 1, 1] ] num_9 = [ [1, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1] ] alpha_s = [ [0, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 0] ]
num_0 = [[1, 1, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1], [1, 1, 1]] num_1 = [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]] num_2 = [[1, 1, 1], [0, 0, 1], [1, 1, 1], [1, 0, 0], [1, 1, 1]] num_3 = [[1, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1]] num_4 = [[1, 0, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [0, 0, 1]] num_5 = [[1, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 1]] num_6 = [[1, 1, 1], [1, 0, 0], [1, 1, 1], [1, 0, 1], [1, 1, 1]] num_7 = [[1, 1, 1], [1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]] num_8 = [[1, 1, 1], [1, 0, 1], [1, 1, 1], [1, 0, 1], [1, 1, 1]] num_9 = [[1, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1]] alpha_s = [[0, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 0]]
class Application: def __init__(self,expaid,url,status,currentStatus,personid,oppid): self.id = expaid self.url=url self.status=status self.currentStatus=currentStatus self.personid=personid self.oppid=oppid
class Application: def __init__(self, expaid, url, status, currentStatus, personid, oppid): self.id = expaid self.url = url self.status = status self.currentStatus = currentStatus self.personid = personid self.oppid = oppid
n = [] while True: try: i = float(input('Enter a number or Enter to finish: ')) except: break else: n.append(i) print(f'Numbers: {n}') print(f'''Count: {len(n)} Sum: {sum(n)} Highest: {max(n)} Lowest: {min(n)} Mean: {sum(n)/len(n)} ''')
n = [] while True: try: i = float(input('Enter a number or Enter to finish: ')) except: break else: n.append(i) print(f'Numbers: {n}') print(f'Count: {len(n)}\nSum: {sum(n)}\nHighest: {max(n)}\nLowest: {min(n)}\nMean: {sum(n) / len(n)}\n')
value = 1 end = 10 while (value < end): print(value) value = value + 1 if (value == 5): break
value = 1 end = 10 while value < end: print(value) value = value + 1 if value == 5: break
pala = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO') for p in pala: print(f'\nNa palavra {p} temos', end=' ') for letra in p: if letra.lower() in 'aeiou': print(f'{letra}', end=' ')
pala = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO') for p in pala: print(f'\nNa palavra {p} temos', end=' ') for letra in p: if letra.lower() in 'aeiou': print(f'{letra}', end=' ')
class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices: return 0 profit = 0 buy = 9999999999999 for i,j in enumerate (prices): if j<buy: buy = j else: if j>buy: profit = max(profit, j-buy) return profit
class Solution: def max_profit(self, prices: List[int]) -> int: if not prices: return 0 profit = 0 buy = 9999999999999 for (i, j) in enumerate(prices): if j < buy: buy = j elif j > buy: profit = max(profit, j - buy) return profit
################################################################################ 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---+| .. .. |', '| || || || || || || || || || |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| .. .. || .. || .. || .. || .. || .. || .. || .. || .. || .. .. |', '| || || || || || || || || || |', '+-------++----+| .. |+----+| .. |+----+| .. |+----+| .. |+-------+']
# 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()
#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
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'}
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
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]
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)
# 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('-')
# 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'
# 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()
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 = '{}'"
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)
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]))
#!/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)])
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
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']}
# 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)
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
class Solution: def checkIfPangram(self, sentence: str) -> bool: words = set(sentence) if (len(words) != 26): return False else: return True
class Solution: def check_if_pangram(self, sentence: str) -> bool: words = set(sentence) if len(words) != 26: return False else: return True
TEXT = ''' <div class="row"> <div class="col-md-12"> <hr/> <div class="page-footer"> <p class="page-footer"><a href="/legal/privacypolicy" target="_blank">Privacy Policy <i class='fa fa-pencil' style='font-size:16px;color:red'></i></a></p> <p class="page-footer">Copyright &copy; theblueplanet.net 2019 all rights reserved, except content provided by third parties.</p> <p class="page-footer">We use cookies to enhance and improve our services. By using this site you agree to our <a href="/legal/cookies" target="_blank">use of cookies</a>.</p></div> </div> </div>'''
text = '\n<div class="row">\n <div class="col-md-12">\n <hr/>\n <div class="page-footer">\n <p class="page-footer"><a href="/legal/privacypolicy" target="_blank">Privacy Policy <i class=\'fa fa-pencil\' style=\'font-size:16px;color:red\'></i></a></p>\n <p class="page-footer">Copyright &copy; theblueplanet.net 2019 all rights reserved, except content provided by third parties.</p>\n <p class="page-footer">We use cookies to enhance and improve our services. By using this site you agree to our <a href="/legal/cookies" target="_blank">use of cookies</a>.</p></div>\n </div>\n</div>'
class Dataset: def __init__(self): self.dataset = None self.groundtruth = None self.camera_file = None self.camera = None self.quat = None self.init_pose = None self.rgb_image = None self.pre_assoc_file_path = None self.descr = None
class Dataset: def __init__(self): self.dataset = None self.groundtruth = None self.camera_file = None self.camera = None self.quat = None self.init_pose = None self.rgb_image = None self.pre_assoc_file_path = None self.descr = None
def policy(resource): if resource['MaxPasswordAge'] is None: return False return resource['MaxPasswordAge'] <= 90
def policy(resource): if resource['MaxPasswordAge'] is None: return False return resource['MaxPasswordAge'] <= 90
# ============================================================================= # Fog Metrics Utilities # ============================================================================= # # Miscellaneous utility functions used to compute metrics # ACCEPTABLE_TYPES = (set, frozenset, dict) def intersection_size(A, B): if A is B: return len(A) if not isinstance(A, ACCEPTABLE_TYPES): A = set(A) if not isinstance(B, ACCEPTABLE_TYPES): B = set(B) if len(A) > len(B): A, B = B, A if len(A) == 0: return 0 i = 0 for x in A: if x in B: i += 1 return i
acceptable_types = (set, frozenset, dict) def intersection_size(A, B): if A is B: return len(A) if not isinstance(A, ACCEPTABLE_TYPES): a = set(A) if not isinstance(B, ACCEPTABLE_TYPES): b = set(B) if len(A) > len(B): (a, b) = (B, A) if len(A) == 0: return 0 i = 0 for x in A: if x in B: i += 1 return i
def test(r): avg = round(sum(r) / len(r), 3) hal = { "h": 0, "a": 0, "l": 0 } for mark in r: if mark > 8: hal["h"] += 1 elif mark > 6: hal["a"] += 1 else: hal["l"] += 1 return [avg, hal, "They did well"] if hal["h"] == len(r) else [avg, hal]
def test(r): avg = round(sum(r) / len(r), 3) hal = {'h': 0, 'a': 0, 'l': 0} for mark in r: if mark > 8: hal['h'] += 1 elif mark > 6: hal['a'] += 1 else: hal['l'] += 1 return [avg, hal, 'They did well'] if hal['h'] == len(r) else [avg, hal]
print("import getmac") def get_mac_address(interface=None, ip=None, ip6=None, hostname=None, network_request=True): get_mac_address_content = f"{f'interface={interface}' if interface else ''}{f', ip={ip}' if ip else ''}{f', ip6={ip6}' if ip6 else ''}{f', hostname={hostname}' if hostname else ''}{f', network_request={network_request}' if network_request and not network_request == True else ''}" print(f'getmac.get_mac_address({get_mac_address_content})') return "00:00:00:00:00:00"
print('import getmac') def get_mac_address(interface=None, ip=None, ip6=None, hostname=None, network_request=True): get_mac_address_content = f"{(f'interface={interface}' if interface else '')}{(f', ip={ip}' if ip else '')}{(f', ip6={ip6}' if ip6 else '')}{(f', hostname={hostname}' if hostname else '')}{(f', network_request={network_request}' if network_request and (not network_request == True) else '')}" print(f'getmac.get_mac_address({get_mac_address_content})') return '00:00:00:00:00:00'
_base_ = '../../../base.py' # model settings model = dict( type='Classification', pretrained=None, backbone=dict( type='ResNet', depth=50, in_channels=3, out_indices=[4], # 0: conv-1, x: stage-x # TODO(cjrd) should we be using BN here??? norm_cfg=dict(type='BN')), head=dict( type='ClsHead', with_avg_pool=True, in_channels=2048, num_classes=10)) # dataset settings data_source_cfg = dict( type='ImageNet', memcached=False, mclient_path='/no/matter') data_train_list = "data/imagenet/meta/train_1000.txt" data_train_root = 'data/imagenet' data_val_list = "data/imagenet/meta/val_1000.txt" data_val_root = 'data/imagenet' data_test_list = "data/imagenet/meta/test_1000.txt" data_test_root = 'data/imagenet' dataset_type = 'ClassificationDataset' img_norm_cfg = dict(mean=[0.5,0.6,0.7], std=[0.1,0.2,0.3]) train_pipeline = [ dict(type='RandomResizedCrop', size=224), dict(type='RandomHorizontalFlip'), dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg), ] test_pipeline = [ dict(type='Resize', size=256), dict(type='CenterCrop', size=224), dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg), ] data = dict( imgs_per_gpu=128, # total 512 workers_per_gpu=4, train=dict( type=dataset_type, data_source=dict( list_file=data_train_list, root=data_train_root, **data_source_cfg), pipeline=train_pipeline), val=dict( type=dataset_type, data_source=dict( list_file=data_val_list, root=data_val_root, **data_source_cfg), pipeline=test_pipeline), test=dict( type=dataset_type, data_source=dict( list_file=data_test_list, root=data_test_root, **data_source_cfg), pipeline=test_pipeline)) prefetch=False
_base_ = '../../../base.py' model = dict(type='Classification', pretrained=None, backbone=dict(type='ResNet', depth=50, in_channels=3, out_indices=[4], norm_cfg=dict(type='BN')), head=dict(type='ClsHead', with_avg_pool=True, in_channels=2048, num_classes=10)) data_source_cfg = dict(type='ImageNet', memcached=False, mclient_path='/no/matter') data_train_list = 'data/imagenet/meta/train_1000.txt' data_train_root = 'data/imagenet' data_val_list = 'data/imagenet/meta/val_1000.txt' data_val_root = 'data/imagenet' data_test_list = 'data/imagenet/meta/test_1000.txt' data_test_root = 'data/imagenet' dataset_type = 'ClassificationDataset' img_norm_cfg = dict(mean=[0.5, 0.6, 0.7], std=[0.1, 0.2, 0.3]) train_pipeline = [dict(type='RandomResizedCrop', size=224), dict(type='RandomHorizontalFlip'), dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)] test_pipeline = [dict(type='Resize', size=256), dict(type='CenterCrop', size=224), dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)] data = dict(imgs_per_gpu=128, workers_per_gpu=4, train=dict(type=dataset_type, data_source=dict(list_file=data_train_list, root=data_train_root, **data_source_cfg), pipeline=train_pipeline), val=dict(type=dataset_type, data_source=dict(list_file=data_val_list, root=data_val_root, **data_source_cfg), pipeline=test_pipeline), test=dict(type=dataset_type, data_source=dict(list_file=data_test_list, root=data_test_root, **data_source_cfg), pipeline=test_pipeline)) prefetch = False