def access_store(driver, store_id): utils.input(driver, "txtSearch", store_id) utils.button_click(driver, "SubmitText") time.sleep(1) try: utils.deal_with_error_message(driver) utils.button_click(driver, "agree") time.sleep(5) return True except RedirectException: return access_store(driver, store_id)
def solve1(): """Solve first puzzle""" r_in = input(convert_fn=lambda x: x.split()) mv = {'forward': (0, 1), 'down': (1, 0), 'up': (-1, 0)} # multiply each movement vector with length r_in = [np.array(mv[x[0]]) * int(x[1]) for x in r_in] return np.prod(sum(r_in))
def solve1(): """Solve first puzzle""" # parse to matrix r_in = np.array(input(convert_fn=lambda x: [int(n) for n in list(x)])) # get dominant bit per column epsilon = np.count_nonzero(r_in, axis=0) > (r_in.shape[0] / 2) gamma = np.invert(epsilon) return bits_to_dec(epsilon) * bits_to_dec(gamma)
def solve1(): """Solve first puzzle""" r_in = np.array( [int(n) for n in input(convert_fn=lambda x: x.split(','))[0]]) fuel = [] for i in range(np.max(r_in) + 1): fuel.append(np.sum(np.abs(r_in - i))) return np.min(fuel)
def solve2(): """Solve second puzzle""" # parse to matrix r_in = np.array(input(convert_fn=lambda x: [int(n) for n in list(x)])) oxy = rec_search(r_in, 0, lambda x: np.count_nonzero(x) >= (len(x) / 2))[0] scrub = rec_search(r_in, 0, lambda x: np.count_nonzero(x) < (len(x) / 2))[0] # convert to bit patterns to 16 bit format for np.packbits return bits_to_dec(oxy) * bits_to_dec(scrub)
def solve2(): """Solve first puzzle""" r_in = np.array( [int(n) for n in input(convert_fn=lambda x: x.split(','))[0]]) fuel = [] costs = list(range(1, np.max(r_in) + 1)) for i in range(np.max(r_in) + 1): fuel.append(sum([sum(costs[:c]) for c in np.abs(r_in - i)])) return np.min(fuel)
def solve2(): """Solve second puzzle""" cave_map = np.array(input(convert_fn=lambda r: [int(c) for c in r])) # 4 connected components kernel = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) # use connected components labeling detection labels, ncomp = label(cave_map != 9, kernel) basins = [] for n in range(1, ncomp + 1): basins.append(np.count_nonzero(labels == n)) return prod((sorted(basins, reverse=True)[:3]))
def solve2(): """Solve second puzzle""" r_in = input(convert_fn=lambda x: x.split()) mv = {'forward': (1, 1, 0), 'down': (0, 0, 1), 'up': (0, 0, -1)} r_in = [np.array(mv[x[0]]) * int(x[1]) for x in r_in] aim = 0 yx = (0, 0) for r in r_in: aim += r[2] yx = (yx[0] + aim * r[0], yx[1] + r[1]) return yx[0] * yx[1]
def solve1(): """Solve first puzzle""" cave_map = np.array(input(convert_fn=lambda r: [int(c) for c in r])) # pad array, to handle edge cases cave_map = np.pad(cave_map, (1, 1), 'constant', constant_values=(10, 10)) risk = 0 for x in range(1, cave_map.shape[1] - 1): for y in range(1, cave_map.shape[0] - 1): cc = conn_comp(cave_map, (x, y)) print(cc) height = cave_map[y, x] if len([True for h in cc if h > height]) == 4: risk += height + 1 return risk
def main(): parser = utils.create_basic_parser('Add an administrator to the signing ' 'server', '~/.sigul/server.conf') utils.optparse_add_batch_option(parser) parser.add_option('-n', '--name', metavar='USER', help='Administrator user name') options = utils.optparse_parse_options_only(parser) logging.basicConfig(format='%(levelname)s: %(message)s', level=utils.logging_level_from_options(options)) try: config = AddAdminConfiguration(options.config_file) except utils.ConfigurationError as e: sys.exit(str(e)) config.batch_mode = options.batch try: utils.set_regid(config) utils.set_reuid(config) utils.update_HOME_for_uid(config) except: # The failing function has already logged the exception sys.exit(1) try: utils.nss_init(config) except utils.NSSInitError as e: sys.exit(str(e)) if options.name is not None: name = options.name else: # readline import makes raw_input more usable. Import only here to # avoid sending escape sequences to stdout when not interactive. import readline name = utils.input('Administrator user name: ') password = utils.read_password(config, 'Administrator password: '******'Administrator password (again): ') if password != p2: sys.exit('Passwords don\'t match.') db = server_common.db_open(config) user = server_common.User(name, clear_password=password, admin=True) db.add(user) db.commit()
def main(): #Primer dialogo para el saludo inicial def firstDialog(conversation): print(u'Bienvenido. ¿Cómo estás?') answer = utils.input() conversation.getNextSentence(answer, actions.BotActions.GREETING) return answer print("Prueba bot DASI") conversation = Conversation() answer = firstDialog(conversation) #Mientras no salgas del dialogo while answer.lower().strip() != "exit": answer = utils.input() #se envia lo recogido por consola a nuestra conversacion conversation.getNextSentence(answer)
def solve(no_diag=False): """Solve first or second puzzle""" r_in = input(convert_fn=lambda x: x.split('->')) r_in = [(c[0].split(','), c[1].split(',')) for c in r_in] r_in = [sorted([(int(c[0]), int(c[1])) for c in e]) for e in r_in] if no_diag: r_in = [c for c in r_in if c[0][0] == c[1][0] or c[0][1] == c[1][1]] max_xy = np.max(r_in, axis=0).max(axis=1) obstacles = np.zeros(max_xy + 1) for line in r_in: x1, y1, x2, y2 = *line[0], *line[1] d_x = x2 - x1 d_y = y2 - y1 if x1 == x2: obstacles[y1:y2 + 1, x1] += 1 elif y1 == y2: obstacles[y1, x1:x2 + 1] += 1 else: for x in range(x1, x2 + 1): y = int(y2 + d_y * (x - x2) / d_x) obstacles[y, x] += 1 return np.count_nonzero(obstacles > 1)
def solve(won_board_i): """Solve first or second puzzle""" BOARD_SIZE = 5 r_in = input() numbers = [int(n) for n in r_in[0].split(',')] boards = [ r_in[i:i + BOARD_SIZE] for i in range(2, len(r_in) - (BOARD_SIZE - 1), (BOARD_SIZE + 1)) ] boards = [[row.split() for row in b] for b in boards] boards = list( map(lambda x: np.array([[int(n) for n in row] for row in x]), boards)) # mask arrays to mark all numbers crossed, per board hits = [np.zeros(b.shape, dtype=np.bool) for b in boards] # remember which boards have won, with which number won_boards = OrderedDict() for n in numbers: # mark all boards that have not finished yet for i, h in enumerate(hits): if i not in won_boards: hits[i] = np.bitwise_or(h, boards[i] == n) # check for complete row or column for i, h in enumerate(hits): if BOARD_SIZE in np.count_nonzero( h, axis=0) or 5 in np.count_nonzero(h, axis=1): # ummarked numbers if i not in won_boards: won_boards[i] = n # the board_id of the i-th won board and the number won with b_id, won_n = list(won_boards.keys())[won_board_i], list( won_boards.values())[won_board_i] return np.sum(boards[b_id][hits[b_id] == False]) * won_n
return node['weight'] compute_weight(root) def printtree(node, indent=0): print('\t' * indent + node['name'] + ' ' + str(node['weight'])) if 'children' in node: for n in node['children']: printtree(n, indent + 1) printtree(root) # non_leaf = set() # for word in count: # if word not in leaf: # non_leaf.add(word) # return count def solve(file): return build_tree(file) part1 = solve(ut.input(7)) print(part1) # Part 2 part2 = '' print(part2)
import re import itertools from collections import Counter, defaultdict import utils as ut # Part 1 def interpret(code, regs): "Execute instructions until pc goes off the end." maxreg = 0 code = map(str.split, code) for inst in code: x, op, value, cond = inst[0], inst[1], int( inst[2]), 'regs[inst[4]] ' + inst[5] + ' ' + inst[6] if eval(cond): if op == 'inc': regs[x] += value elif op == 'dec': regs[x] -= value maxreg = max(maxreg, max(regs.values())) return maxreg part1 = interpret(ut.input(8).readlines(), defaultdict(int)) print(part1) # Part 2 part2 = '' print(part2)
frontier.append(s2) return len(visited) def solve2(lookup): left = set(lookup.keys()) num_groups = 0 while left: frontier = deque([left.pop()]) num_groups += 1 visited = set() while frontier: s = frontier.popleft() if s not in visited: visited.add(s) if s in left: left.remove(s) for s2 in lookup[s]: if s2 not in visited: frontier.append(s2) return num_groups part1 = solve(parse(ut.input(12))) print(part1) part2 = solve2(parse(ut.input(12))) print(part2)
def defKey(self, key): self.key=key utils.input(self.defValue, "value")
def main(): if args.dataset == 'ggblocks': train_data = GGBlocks(N=args.dataset_size, sigma_n=args.sigma_n) test_data = GGBlocks(N=200, sigma_n=args.sigma_n) elif args.dataset == 'correlated': patterns = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [0, 0, 1, 1]]) freq = np.array([0.1, 0.1, 0.1, 0.1, 0.3, 0.3]) train_data = GGBlocks(N=args.dataset_size, sigma_n=args.sigma_n, patterns=patterns, freq=freq) test_data = GGBlocks(N=200, sigma_n=args.sigma_n, patterns=patterns, freq=freq) else: raise NotImplementedError train_loader = torch.utils.data.DataLoader(train_data, batch_size=args.batch_size, shuffle=True, **kwargs) test_loader = torch.utils.data.DataLoader(test_data, batch_size=args.batch_size, shuffle=True, **kwargs) # compute the initialization of the model init = compute_init(args.init, train_data.train_data, args.truncation) # cross-model dictionary to initialize it model_kwargs = { 'max_truncation_level': args.truncation, 'alpha0': args.alpha0, 'sigma_n': args.sigma_n, 'init': init } # All switching logic is here. if args.model == 'ibp': model_cls = MF_IBP_VAE else: raise NotImplementedError # set up objects for use model = model_cls(**model_kwargs).to(device) model_kwargs.pop('init') optimizer = optim.Adam(filter(lambda x: x.requires_grad, model.parameters()), lr=args.lr) if args.scheduler is not None: scheduler = StepLR(optimizer, args.scheduler, 0.7) logs = [] def flush(params): if args.traj: params.update({'model': model.to(cpu)}) logs.append(params) # run experiment try: best_score = np.inf for epoch in range(1, args.epochs + 1): train_score = model.train_epoch(train_loader, optimizer, epoch, args, device, args.n_samples) eval_score = model.evaluate(test_loader, args, device, 10) if eval_score['ELBO'] < best_score: model_to_save = model_cls(**model_kwargs).to(cpu) model_to_save.load_state_dict(model.state_dict()) if not args.quiet: s = ''.join([ "| {} {:<5.1f}".format(k, v) for k, v in eval_score.items() ]) s += '| Train: {:.1f}'.format(train_score) print("[Epoch {:<4}] ".format(epoch) + s) # print(model.A_mean.sum().item()) flush(eval_score) if args.scheduler is not None: scheduler.step() except KeyboardInterrupt: save = input( "\n save learned features and trajectories anyway? [y/n] ") if save.strip() not in ('y', 'yes'): sys.exit(0) # Save everything here torch.save({'model': model_to_save, 'logs': logs}, args.save) # Just for debugging, save the output learned features to `learned_features.npy` np.save('learned_features.npy', model.A_mean.data.to(cpu).numpy())
def solve(k_size=3): """Solve first or second part of the puzzle""" r_in = input(convert_fn=int) sw_sum = [sum(r_in[i:i + k_size]) for i in range(len(r_in) - (k_size - 1))] return len( [True for i in range(1, len(sw_sum)) if sw_sum[i] - sw_sum[i - 1] > 0])
def get_cookie(driver, store_id, config): if access_store(driver, store_id): date = utils.get_last_visit_date(config["week_frequency"]) formatted = utils.format_date(date, driver.find_element_by_id("answ5195").get_attribute("placeholder")) utils.input(driver, "answ5195", formatted, False) utils.input(driver, "answHour5195", config["hour"], False) utils.input(driver, "answMinute5195", config["minute"], False) utils.set_vote(driver, "answc5197", config["recommend_to_friend"]) utils.set_vote(driver, "answ5198", config["general_experience"]) utils.set_vote(driver, "answ51990", config["food_quality"]) utils.set_vote(driver, "answ51991", config["food_quality"]) utils.set_vote(driver, "answ51992", config["polite_staff"]) utils.set_vote(driver, "answ51993", config["cleaning"]) utils.set_vote(driver, "answ51994", config["comfort"]) utils.set_vote(driver, "answ51995", config["general_experience"]) utils.set_drop_down(driver, "answ5220", config["compliment"]) if config["compliment"]: utils.input(driver, "answ5221", config["compliment_message"]) utils.set_drop_down(driver, "answ5222", config["warning"]) if config["warning"]: utils.input(driver, "answ5223", config["warning_message"]) utils.input(driver, "answ5224", config["fast_food_in_month"]) utils.input(driver, "answ5225", config["subway_in_month"]) utils.input(driver, "answ5218", config["my_email"]) utils.set_drop_down(driver, "answ5219", config["receive_newsletter"]) utils.set_drop_down(driver, "DdlContact", config["contact_me"]) utils.button_click(driver, "btnSubmit") time.sleep(1) utils.deal_with_error_message(driver) time.sleep(5) return driver.find_element_by_id("ctl03_lblTag").text
import re import itertools from collections import Counter import utils as ut # Part 1 def solve(text): return part1 = sum(map(solve, ut.input(4))) print(part1) # Part 2 part2 = '' print(part2)
score = 0 total_score = 0 for c in text: if c == '{': score += 1 elif c == '}': total_score += score score -= 1 return total_score def solve2(text): return sum(map(lambda x: len(x) - 2, re.findall(r'<.*?>', filter(text)))) print(solve('{}')) print(solve('{{{}}}')) print(solve('{<a>,<a>,<a>,<a>}')) print(solve('{<{},{},{{}}>}')) print(solve('{{<a>},{<a>},{<a>},{<a>}}')) print(solve('{{<!>},{<!>},{<!>},{<a>}}')) part1 = solve(ut.input(9).read()) print(part1) # Part 2 part2 = solve2(ut.input(9).read()) print(part2)
c = grid[y][x] if c == ' ': break if c.isalpha(): labels.append(c) if c == '+': if dir in 'ud': if grid[y][x - 1] != ' ': dir = 'l' if grid[y][x + 1] != ' ': dir = 'r' else: if grid[y - 1][x] != ' ': dir = 'u' if grid[y + 1][x] != ' ': dir = 'd' if dir == 'u': y -= 1 if dir == 'd': y += 1 if dir == 'l': x -= 1 if dir == 'r': x += 1 steps += 1 # print(c, dir) print(''.join(labels)) print(steps) solve(ut.input(19))
import re import itertools from collections import Counter import utils as ut # Part 1 def solve(layers, delay): caughts = [d for d, r in layers.items() if (d + delay) % ((r - 1) * 2) == 0] # return sum(map(lambda c: layers[c] * c, caughts)) return len(caughts) def solve2(file): layers = { int(t[0]): int(t[1]) for t in [re.findall(r'(\d+)', line) for line in file] } delay = 0 while True: if solve(layers, delay) == 0: return delay delay += 1 print(solve2(ut.input(13)))
for p in ps: update(p) distances = list(map(dist, ps)) return distances.index(min(distances)) def remove(ps): positions = defaultdict(list) for p in ps: t = tuple(p[0]) positions[t].append(p) for v in positions.values(): if len(v) > 1: for p in v: ps.remove(p) def solve2(file): ps = [parse(line) for line in file] for _ in range(2000): for p in ps: update(p) remove(ps) return len(ps) part2 = solve2(ut.input(20)) print(part2)
def main(): #Arg parser parser = argparse.ArgumentParser( description= 'This is a little python script which converts any file whose format is accepted by ffmpeg ( also mp4, mov... ) into a desired format, keeping metadatas, editing bitrate, audio channels, and even normalizing them using mp3gain.' ) parser.add_argument('-i', '--input', nargs='+', metavar='My Music', type=str, help='Input directory name ( No / ).', required=True) parser.add_argument('-o', '--output', nargs='+', metavar='My Converted Music', type=str, help='Output directory name ( No / ).', required=True) parser.add_argument('-f', '--format', metavar='mp3', type=str, help="Output file format (mp3,flac,wav ... ) .", required=True) parser.add_argument( '-b', '--bitrate', metavar='320', type=int, help="Change the bitrate of the output file (128kbps by default ).", required=False) parser.add_argument('-c', '--channels', metavar='2', type=int, help="Output audio channels (Stereo by default).", required=False) parser.add_argument( '-t', '--threads', metavar='10', type=int, help= "Set number of thread to use while converting a file, be careful with this setting, it's suggested not to use higher value than 10 (1 By default ) .", required=False) parser.add_argument( '-d', '--decibel', metavar='1.0', help= "Modify suggested dB gain of the normalization ( Works only if normalization is enabled, 1.0 by default ).", required=False) parser.add_argument( '-n', '--normalize', help= "Enable normalization of converted files using mp3gain ( Disabled by default ).", action='store_true', required=False) parser.add_argument( '-v', '--verbosity', help= "Increase verbosity if toggled, show ffmpeg and mp3gain commands output ( Disabled by default ).", action='store_true', required=False) args = parser.parse_args() #Load args into variables inputdir = ' '.join(args.input) outputdir = ' '.join(args.output) outformat = args.format #Check if non required args are not empty, and if yes set a default value if args.bitrate != None: bitrate = args.bitrate else: bitrate = "128" if args.verbosity != None: verbosity = args.verbosity else: verbosity = False if args.threads != None: threads = args.threads else: threads = "1" if args.channels != None: channels = args.channels else: channels = "2" if args.normalize != None: normalize = args.normalize else: normalize = False if args.decibel != None: decibel = float(args.decibel) else: decibel = 1.0 utils.init() if normalize == True: if utils.mp3gain() == False: utils.alert( "In order to normalize your files you need to install mp3gain." ) return if utils.ffmpeg() == False: return #Check if input directory exists if not os.path.exists(inputdir): utils.alert("Input directory doesn't exist, quitting...") return #If the directory doesn't exist create it if not os.path.exists(outputdir): os.system("mkdir " + utils.cleanstr(outputdir)) #Load files to be converted in a list toconvert = [ os.path.join(root, name) for root, dirs, files in os.walk(os.getcwd() + "/" + inputdir) for name in files if name.endswith(tuple(all_files)) ] #http://stackoverflow.com/questions/5817209/browse-files-and-subfolders-in-python #Load the new files to be converted in a list new = utils.alreadyConverted(inputdir, outputdir, outformat) mans = '' if new != -1: while mans != 'no' and mans != 'yes' and mans != 'y' and mans != 'n': mans = utils.input( "Found " + str(len(new) - 1) + " new files to be converted. Would you like to convert only the new ones?(y/n): " ) if mans == 'y' or mans == 'yes': new.pop() toconvert = new #Create Converter instance MyConverter = Converter(toconvert, outformat, inputdir, outputdir, threads, channels, bitrate, normalize, decibel, verbosity) utils.action(str(len(toconvert)) + " files loaded.") utils.action("Size of files to be converted: " + str(utils.getdirsize(inputdir)) + " MB.") utils.action("Estimated conversion time (normalization not included): " + str((utils.getdirsize(inputdir) * cspeed / 60) / int(threads)) + " minutes.") MyConverter.getSettings() ans = '' while ans != 'no' and ans != 'yes' and ans != 'y' and ans != 'n': ans = utils.input( "These are your settings, would you like to continue?(y/n): ") if ans == 'no' or ans == 'n': utils.action("Quitting.") return start_time = timeit.default_timer() try: conv = MyConverter.convert() except KeyboardInterrupt: return if normalize == True: MyConverter.normalize() elapsed = timeit.default_timer() - start_time utils.action("Converted " + str(conv) + "/" + str(len(toconvert)) + " files in " + str(int(elapsed) / 60) + " minutes.")
def firstDialog(conversation): print(u'Bienvenido. ¿Cómo estás?') answer = utils.input() conversation.getNextSentence(answer, actions.BotActions.GREETING) return answer
def run(self, edit): utils.input(self.defKey, "key")
def solve(combination_size): """Solve first or second part of the puzzle""" raw_input = input(convert_fn=int) for c in combinations(raw_input, combination_size): if sum(c) == 2020: return prod(c)
import re import itertools from collections import Counter import utils as ut # Part 1 def valid(text): text = text.split() return len(set(text)) == len(text) part1 = sum(map(valid, ut.input(4))) print(part1) # Part 2 def valid2(text): text = [''.join(sorted(t)) for t in text.split()] return len(set(text)) == len(text) part2 = sum(map(valid2, ut.input(4))) print(part2)
's': (0, 1), 'ne': (1, -1), 'se': (1, 0), 'nw': (-1, 0), 'sw': (-1, 1) } def move(x, y, dir): return dirs[dir][0] + x, dirs[dir][1] + y def dist(x, y): return (abs(x) + abs(y) + abs(x + y)) / 2 def solve(text): x, y = 0, 0 max_steps = 0 for dir in text.split(','): x, y = move(x, y, dir) max_steps = max(max_steps, dist(x, y)) return dist(x, y) print(solve('se,sw,se,sw,sw')) part1 = solve(ut.input(11).read()) print(part1) # Part 2 part2 = '' print(part2)
import re import itertools from collections import Counter import utils as ut # Part 1 def solve(code): pc = 0 steps = 0 while pc < len(code): oldpc = pc pc += code[pc] # jump # code[oldpc] += 1 # inc code[oldpc] += (-1 if code[oldpc] >= 3 else 1) # inc # print(code) steps += 1 return steps code = [int(x) for x in ut.input(5)] part1 = solve(code) print(part1)