def getPartime(curstats, data): print "A quiz timer has been implemented." print "Enter a floating-point number to select a par time in seconds." print "If you don't want to play with a timer, choose 0." partime = -1 while partime < 0: try: cin, pcval = utils.getInput(curstats, data, "Enter another command, or choose a par time.") if pcval == -1: print "Exiting Quiz mode." return partime, cin partime = float(cin) if partime < 0: print "You need to choose a nonnegative par time." except: print "That's not a valid input." if partime == 0: print "Timed mode is OFF." else: print "Timed mode is ON, with par time set to "+ str(partime) + "." print "The time bonus you will receive for each correct answer is" print "20 * par/(time + par^2) - 20 * par/(par + par^2)" print "Note that entering commands will NOT reset or invalidate" print "the timer, except for exiting." print "Press <ENTER> or enter any non-command to begin." cin, pcval = utils.getInput(curstats, data, "Press <ENTER> or enter any non-command to begin.") if pcval == -1: print "Exiting Quiz mode." return partime, cin return partime, None
def getNeuralNetFromUser(): neural_net_file = "resources/neural_net" #JSON in a text file used to load the neural network net = None print "Load Neural Network from file?" value = getInput("-1 for training a new network, other key to load a trained one: ") if (value == '-1'): net_layers = [TOTAL_SIZE] #List of neurons, input layer == N pixels i = 1 print "For each layer, insert the number of neurons\nInsert -1 to finish: " while(True): s_layer = "Layer {}: ".format(i) layer = int(getInput(s_layer)) if(layer == -1): break net_layers.append(layer) i += 1 net_layers.append(N_ELEMENTS) #Output layer == N possible output values net = network2.Network(net_layers, cost=network2.CrossEntropyCost) net.large_weight_initializer() else: value = getInput("-1 for specifying the neural network file. Other to load the default '{}': ".format(neural_net_file)) if(value == '-1'): neural_net_file = getInput("Insert file name of the neural net to be loaded: ") while(True): if (isfile(neural_net_file)): break neural_net_file = getInput("Insert file name of the neural net to be loaded: ") print "Name invalid, please try again" net = network2.load(neural_net_file) #Loads an existing neural network from a file return net
def processUserNeuralSettings(): epochs = int(getInput("epochs: ")) batch = int(getInput("batch-size: ")) eta = float(getInput("learning rate (< 1): ")) lmbda = float(getInput("lambda: ")) return epochs, batch, eta, lmbda
def launchUseSkills(*args): try: forWin = win32gui.GetForegroundWindow() utils.positionWindows(False, 0, 0, 770, 332, True, False, True) choices = { '1': "Clones", '2': "Jacky Lee", '3': "Cthulhu", '4': "Doppelganger", '5': "D. Evelope", '6': "gods" } if len(args) > 1: choice = args[1] else: choice = '' while choice == '': choice = utils.getInput( "Fight: " + ', '.join([') '.join([k, v]) for k, v in choices.items()]) + '\n') return skillControl.useSkills(choices[choice]) except OSError: try: skills skillControl.saveSkills(skills) except UnboundLocalError: pass logging.getLogger(__name__).exception("Program terminated") print("Restarting script") os.execl(sys.executable, sys.argv[0], sys.argv[0], '2', choice) return ''
def askChoice(*args): choices = { '1': launchAfky, '2': launchUseSkills, '3': launchCalcCreations, '4': launchCalcPets, '5': launchCalcDivGen, '6': launchCalcBestMonumentPath, '7': launchSkillTraining, 'q': sys.exit } choice = args[0] while True: utils.positionWindows(False, 0, 0, 770, 332, False, True, False) if choice == '' or choice is None: choice = utils.getInput( 'Choose: 1) Afky, 2) Use Skills, 3) Calc creation, 4) Pet Clone Stat calc\n 5) Div Gen, 6) Monument Path, 7) Skill Training, or q) Exit\n' ) if choice in choices.keys(): if len(args) == 1: choice = choices[choice]() else: choice = choices[choice](*args) else: print("Invalid selection. Choose:", ', '.join([k for k in choices.keys()])) choice = '' return
def quiz(curstats, data): printStartText() partime, cin = getPartime(curstats, data) if cin is not None: return cin # Trackers so more recent keys aren't as likely to be generated. turns = 0 lastused = {} for key in curstats.wins: lastused[key] = 0 while True: turns = turns + 1 starttime = time.clock() if random.randint(0, 1) == 0: letter = utils.getKey(data["letters"], lastused, turns, curstats.wins, curstats.losses, data["debug"]) lastused[letter] = turns lastused[data["morse"][letter]] = turns print "Type the code for: "+letter cin, pcval = utils.getInput(curstats, data, "Type the code for: "+letter) if cin == "//" or cin == "??" or cin == "idk": print "Okay, the correct answer is: ", data["morse"][letter] print "Try it!" curstats.losses[letter] = curstats.losses[letter] + 1 curstats.tl = curstats.tl + 1 cin, pcval = utils.getInput(curstats, data, "Type the code for: "+letter) if pcval == -1: print "Exiting Quiz mode." return cin processAnswer(cin.upper(), partime, starttime, letter, data["morse"][letter], curstats) else: code = utils.getKey(data["codes"], lastused, turns, curstats.wins, curstats.losses, data["debug"]) lastused[code] = turns lastused[data["demorse"][code]] = turns print "Type the character for: "+code cin, pcval = utils.getInput(curstats, data, "Type the character for: "+code) if cin == "//" or cin == "??" or cin == "idk": print "Okay, the correct answer is: ", data["demorse"][code] print "Try it!" curstats.tl = curstats.tl + 1 curstats.losses[code] = curstats.losses[code] + 1 cin, pcval = utils.getInput(curstats, data, "Type the character for: "+code) if pcval == -1: print "Exiting Quiz mode." return cin processAnswer(cin.upper(), partime, starttime, code, data["demorse"][code], curstats)
def launchCalcPets(*args): utils.positionWindows(False, 0, 0, 0, 0, True, False, True) while True: choice = utils.getInput("1) Pet Hunger 2) Pet Clone Stats") if choice == '1': return pets.petHunger() elif choice == '2': return pets.petClone()
def listen(curstats, data): printStartText() tunit, pcval = inputTUnit(curstats, data) if pcval == -1: return tunit # Trackers so more recent keys aren't as likely to be generated. turns = 0 lastused = {} for key in curstats.wins: lastused[key] = 0 adcmd = [] adcmd.append("/replay") adcmd.append("/repeat") while True: turns = turns + 1 # starttime = time.clock() key = utils.getKey(data["codes"], lastused, turns, curstats.wins, curstats.losses, data["debug"]) lastused[key] = turns lastused[data["demorse"][key]] = turns print "Type the character for the following: " playCode(key, tunit) cin, pcval = utils.getInput(curstats, data, "Type /replay to replay the code.", adcmd) while cin == "/replay" or cin == "/repeat": playCode(key, tunit) cin, pcval = utils.getInput(curstats, data, "Type /replay to replay the code.", adcmd) if cin == "//" or cin == "??" or cin == "idk": print "Okay, the correct answer is: ", data["demorse"][key] print "Try it!" # curstats.losses[key] = curstats.losses[key] + 1 # curstats.tl = curstats.tl + 1 cin, pcval = utils.getInput(curstats, data, "Type /replay to replay the code.", adcmd) if pcval == -1: print "Exiting Listen Mode." return cin while cin == "/replay" or cin == "/repeat": playCode(key, tunit) cin, pcval = utils.getInput(curstats, data, "Type /replay to replay the code.", adcmd) quiz.processAnswer(cin.upper(), 0, 0, key, data["demorse"][key], curstats)
def launchSkillTraining(*args): utils.positionWindows(False, 0, 0, 0, 0, True, False, False) level = utils.getInput("Start at how many clones? Blank for 500\n") if level == "": return skillControl.training() level = eval(level) if isinstance(level, int) and level % 500 == 0: return skillControl.training(int(level)) else: print("Invalid level") choice = ''
def inputTUnit(curstats, data): print "Specify a unit time in milliseconds. This will be the length" print "of a dot. The recommended time is 120. Note that the sound" print "may not play correctly if the unit time is too short." tunit = -1 while tunit <= 0: tunit, pcval = utils.getInput(curstats, data, "Specify a unit time in ms.") if pcval == -1: return tunit, pcval try: tunit = int(tunit) if tunit <= 0: print "Specify a positive integer time." tunit = tunit + 0 # Verify that it's not a string somehow except: print "Specify a positive integer time." tunit = -1 return tunit, 0
def classify(self, candidateAndFillerAndOffsetList): ############## # TEST MODEL # ############## logger.info('... testing') index = T.lscalar() # index to a [mini]batch if self.gotNetwork == 0: return [] inputMatrixDev_a, inputMatrixDev_b, inputMatrixDev_c, lengthListDev_a, lengthListDev_b, lengthListDev_c, inputFeaturesDev, _ = getInput( candidateAndFillerAndOffsetList, self.representationsize, self.contextsize, self.filtersize, self.wordvectors, self.vectorsize) # create input matrix and save them in valid_set dt = theano.config.floatX valid_set_xa = theano.shared(numpy.matrix(inputMatrixDev_a, dtype=dt)) valid_set_xb = theano.shared(numpy.matrix(inputMatrixDev_b, dtype=dt)) valid_set_xc = theano.shared(numpy.matrix(inputMatrixDev_c, dtype=dt)) valid_mlp = theano.shared(numpy.matrix(inputFeaturesDev, dtype=dt)) # compute number of minibatches for testing n_valid_batches = valid_set_xa.get_value(borrow=True).shape[0] n_valid_batches /= self.batch_size test_model_confidence = theano.function( [index], self.layer3.results(), givens={ self.xa: valid_set_xa[index * self.batch_size:(index + 1) * self.batch_size], self.xb: valid_set_xb[index * self.batch_size:(index + 1) * self.batch_size], self.xc: valid_set_xc[index * self.batch_size:(index + 1) * self.batch_size], self.additionalFeatures: valid_mlp[index * self.batch_size:(index + 1) * self.batch_size] }) resultList = [ test_model_confidence(i) for i in xrange(n_valid_batches) ] return resultList
import math import operator from functools import reduce from typing import Callable import utils input = utils.getInput(13).splitlines() start = int(input[0]) class Bus: def __init__(self, id, position) -> None: super().__init__() self.id = int(id) self.position = int(position) self.last = None def __str__(self) -> str: return f"{self.id}" def next(self, after: int): return self.id * math.ceil(after / self.id) busses = [ Bus(i, p) for p, i in enumerate(input[1].split(","), start=0) if i != "x" ] min = None
else: print 'No Data to output' if __name__=="__main__": #parse arguments from initial startup -should only be called once parser = argparse.ArgumentParser() parser.add_argument("-d","--debug", help="Optional Debug Mode for stack traces", action="store_true") parser.add_argument("file", help="File to import data from", nargs='?') args = parser.parse_args() #Retrieve all the operations we can do on the data functionalities = dict([func for func in inspect.getmembers(functionality) if inspect.isfunction(func[1])]) # Make sure we have a csv extension if not ask the user again and attempt to load the file while args.file == None or args.file[-4:] != '.csv': args.file = utils.getInput('The file provided is not a csv file. Please provide a csv file to load ("override" to override and continue) <-1 to exit>: ', str, None) if args.file == 'override': break elif args.file == '-1': print 'Bye Bye' sys.exit() people = loadData(args.file, args.debug) while people == None: args.file = utils.getInput('The file provided could not be found or opened please provide another csv file <-1 to exit>: ', str, None) if args.file == '-1': print 'Bye Bye' sys.exit() people = loadData(args.file, args.debug)
if (argv[2]): if (not isdir(argv[2])): printErrorMsg("'" + argv[2] + "'" + " is not a valid directory\n" + USE) exit(1) vPath = argv[2] if (argv[3]): if (not isdir(argv[3])): printErrorMsg("'" + argv[3] + "'" + " is not a valid directory\n" + USE) exit(1) testPath = argv[3] training_data, validation_data, test_data = loadImgs(tPath, vPath, testPath) value = getInput("-1 to expand training data, skip otherwise: ") if (value == '-1'): training_data = expandTrainingData(training_data) epochs = 20 batch = 10 eta = 0.1 lmbda = 0.1 print "\nDefinition of the neural network" print "################################" net = getNeuralNetFromUser( ) # Allows to load an existing network or creating a new network value = getInput("-1 to manually specify parameters, other key for default: ") if (value == '-1'): epochs, batch, eta, lmbda = processUserNeuralSettings()
from itertools import combinations from math import prod import utils input = [int(i) for i in utils.getInput(1).splitlines()] for i in (1, 2): for combo in combinations(input, 1 + i): if sum(combo) == 2020: print(f"part {i}: {prod(combo)}") break
def classify(self, candidateAndFillerAndOffsetList, slot): ############## # TEST MODEL # ############## slotIndex = self.slotList.index(slot) logger.info('... testing') logger.info("boosting CNN score if best path goes through class") index = T.lscalar() # index to a [mini]batch if self.gotNetwork == 0: return [] inputMatrixDev_a, inputMatrixDev_b, inputMatrixDev_c, lengthListDev_a, lengthListDev_b, lengthListDev_c, inputFeaturesDev, _ = getInput( candidateAndFillerAndOffsetList, self.representationsize, self.contextsize, self.filtersize, self.wordvectors, self.vectorsize) # create input matrix and save them in valid_set dt = theano.config.floatX valid_set_xa = theano.shared(numpy.matrix(inputMatrixDev_a, dtype=dt)) valid_set_xb = theano.shared(numpy.matrix(inputMatrixDev_b, dtype=dt)) valid_set_xc = theano.shared(numpy.matrix(inputMatrixDev_c, dtype=dt)) valid_mlp = theano.shared(numpy.matrix(inputFeaturesDev, dtype=dt)) # compute number of minibatches for testing n_valid_batches = valid_set_xa.get_value(borrow=True).shape[0] n_valid_batches /= self.batch_size input_dict = {} input_dict[self.xa] = valid_set_xa[index * self.batch_size:(index + 1) * self.batch_size] input_dict[self.xb] = valid_set_xb[index * self.batch_size:(index + 1) * self.batch_size] input_dict[self.xc] = valid_set_xc[index * self.batch_size:(index + 1) * self.batch_size] input_dict[ self.additionalFeatures] = valid_mlp[index * self.batch_size:(index + 1) * self.batch_size] test_model = theano.function([index], self.relation_scores_global, givens=input_dict) predictions_model = theano.function([index], self.predictions_global, givens=input_dict) resultList = [test_model(i) for i in xrange(n_valid_batches)] predictionsList = [ predictions_model(i)[0][0, 2] for i in xrange(n_valid_batches) ] confidenceList = [] for r in range(len(resultList)): predclass = predictionsList[r] conf = resultList[r][0, slotIndex] if predclass == slotIndex: conf = max( 1.0, conf + 0.75) # boost confidence if best path goes through class confidenceList.append(conf) return confidenceList
from utils import getInput, getTokens # YOUR IMPLEMENTATION # Thoroughly comment your code to make it easy to follow if __name__ == "__main__": # 1. Load your saved model tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) maxSentLen = 295 # 80 percentile sentence length in training dataset. model = load_model("models/20829490_NLP_model.model") # 2. Load your testing data test_raw, labels = getInput('test') # Tokenizing, removing stop words and lemmetizing. tokens1 = getTokens(test_raw) # Truncating longer sentences to 80 percentile sentence length. truncatedData = [' '.join(seq[:maxSentLen]) for seq in tokens1] # Processing Test Data. tokenizer = pickle.load(open("data/token.p", "rb")) final_data = tokenizer.texts_to_sequences(truncatedData) # Padding the data. final_data = pad_sequences(final_data, maxlen=maxSentLen, padding='post') # 3. Run prediction on the test data and print the test accuracy
def classify(self, candidateAndFillerAndOffsetList, slot): ############## # TEST MODEL # ############## logger.info('... testing') index = T.lscalar() # index to a [mini]batch if self.gotNetwork == 0: return [] inputMatrixDev_a, inputMatrixDev_b, inputMatrixDev_c, lengthListDev_a, lengthListDev_b, lengthListDev_c, inputFeaturesDev, _ = getInput(candidateAndFillerAndOffsetList, self.representationsize, self.contextsize, self.filtersize, self.wordvectors, self.vectorsize) # create input matrix and save them in valid_set slot2types, binarizer, numTypes = getSlot2Types() yner1Dev = [] yner2Dev = [] type1bin = binarizer.transform([slot2types[slot][0]]) type2bin = binarizer.transform([slot2types[slot][1]]) dt = theano.config.floatX for item in range(len(inputMatrixDev_a)): yner1Dev.append(type1bin) yner2Dev.append(type2bin) yner1DevNumpy = numpy.array(yner1Dev, dtype = numpy.int32) yner2DevNumpy = numpy.array(yner2Dev, dtype = numpy.int32) valid_set_xa = theano.shared(numpy.matrix(inputMatrixDev_a, dtype = dt)) valid_set_xb = theano.shared(numpy.matrix(inputMatrixDev_b, dtype = dt)) valid_set_xc = theano.shared(numpy.matrix(inputMatrixDev_c, dtype = dt)) valid_mlp = theano.shared(numpy.matrix(inputFeaturesDev, dtype = dt)) valid_yner1 = theano.shared(yner1DevNumpy.reshape(yner1DevNumpy.shape[0], yner1DevNumpy.shape[2])) valid_yner2 = theano.shared(yner2DevNumpy.reshape(yner2DevNumpy.shape[0], yner2DevNumpy.shape[2])) # compute number of minibatches for testing n_valid_batches = valid_set_xa.get_value(borrow=True).shape[0] n_valid_batches /= self.batch_size input_dict = {} input_dict[self.xa] = valid_set_xa[index * self.batch_size: (index + 1) * self.batch_size] input_dict[self.xb] = valid_set_xb[index * self.batch_size: (index + 1) * self.batch_size] input_dict[self.xc] = valid_set_xc[index * self.batch_size: (index + 1) * self.batch_size] input_dict[self.yNER1] = valid_yner1[index * self.batch_size: (index + 1) * self.batch_size] input_dict[self.yNER2] = valid_yner2[index * self.batch_size: (index + 1) * self.batch_size] input_dict[self.additionalFeatures] = valid_mlp[index * self.batch_size: (index + 1) * self.batch_size] test_model_confidence = theano.function([index], self.layer3.results(), givens = input_dict) resultList = [test_model_confidence(i) for i in xrange(n_valid_batches)] return resultList
def iprompt(self, out=sys.stdout): """Start a prompt listening to user input.""" cmds = """ Commands: i -- index: print current iteration index p -- pause: interrupt sampling and return to the main console. Sampling can be resumed later with icontinue(). h -- halt: stop sampling and truncate trace. Sampling cannot be resumed for this chain. b -- bg: return to the main console. The sampling will still run in a background thread. There is a possibility of malfunction if you interfere with the Sampler's state or the database during sampling. Use this at your own risk. """ print >> out, """============== PyMC console ============== PyMC is now sampling. Use the following commands to query or pause the sampler. """ print >> out, cmds prompt = True try: while self.status in ['running', 'paused']: # sys.stdout.write('pymc> ') if prompt: out.write('pymc > ') out.flush() if self._exc_info is not None: a,b,c = self._exc_info raise a, b, c cmd = utils.getInput().strip() if cmd == 'i': print >> out, 'Current iteration: ', self._current_iter prompt = True elif cmd == 'p': self.status = 'paused' break elif cmd == 'h': self.status = 'halt' break elif cmd == 'b': return elif cmd == '\n': prompt = True pass elif cmd == '': prompt = False else: print >> out, 'Unknown command: ', cmd print >> out, cmds prompt = True except KeyboardInterrupt: if not self.status == 'ready': self.status = 'halt' if self.status == 'ready': print >> out, "Sampling terminated successfully." else: print >> out, 'Waiting for current iteration to finish...' while self._sampling_thread.isAlive(): sleep(.1) print >> out, 'Exiting interactive prompt...' if self.status == 'paused': print >> out, 'Call icontinue method to continue, or call halt method to truncate traces and stop.'
from collections import defaultdict import utils input = [int(i) for i in utils.getInput(15).split(",")] lookup = defaultdict(lambda: []) for i, m in enumerate(input): lookup[m].append(i + 1) last = input[-1] for i in range(len(input), 30000000): try: last = lookup[last][-1] - lookup[last][-2] except IndexError: last = 0 lookup[last].append(i + 1) if i == 2019: print(f"part 1: {last}") print(f"part 2: {last}")
" respectively.", sep='') if __name__ == "__main__": # 1. load your training data # 2. Train your network # Make sure to print your training loss and accuracy within training to show progress # Make sure you print the final training accuracy # 3. Save your model tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) # Reading the training data. train_raw, labels = getInput('train') # Tokenizing the training data. tokens = getTokens(train_raw) # tokens = removeStopWords(tokens) opt_dim = 50 # Finding the 80 percentile sentence length. # percentile = int(np.percentile([len(seq) for seq in tokens], 80)) # print('80th Percentile Sentence Length:', percentile) percentile = 295 # 80th Percentile Sentence Length, Found using above two lines. # Truncate the data at 80 percentile sentence length. truncatedData = [' '.join(seq[:percentile]) for seq in tokens]
def useSkills(fightWhat): idleGodshwdn = findWindowHandle("Idling to Rule The Gods") skills = determineAvailSkills(loadSkills()) fightButtonCoords = { 'Clones': (991, 406), 'Jacky Lee': (1245, 400), 'Cthulhu': (1655, 405), 'Doppelganger': (845, 475), 'D. Evelope': (1245, 470), 'gods': (1640, 470) } if len(sys.argv) <= 1: answer = getInput( "Do you wish to update the number of uses per skill? y/n \n") if answer == 'y': skills = setUses(skills) while True: focus = getInput( "Focus defeating 1) enemy or 2) using non-one cloned skills\n") if focus != '1' and focus != '2': print('Invalid choice, choose 1 or 2') else: break nextSkill = '' for key in skills: if not skills[key].avail: nextSkill = key else: break atkDelay = 0.25 if focus == '1': skillsToUse = [ 'Shadow Fist', 'Invisible Hand', 'Big Bang', 'Unlimited Creation Works', 'Aura Ball', 'High Kick', 'Ionioi Hero Summon', 'Whirling Foot', '108 Fists', 'Double Punch' ] ignore = skillsToUse.copy() else: skillsToUse = orderSkills(skills) ignore = [] # Shadow Clones button if py.pixelMatchesColor(991, 406, (3, 3, 3), tolerance=10): clicky(*fightButtonCoords[fightWhat]) coolDowns = [time.time()] * len(skillsToUse) while True: if detectKeypress(): break if py.pixelMatchesColor(1151, 405, (4, 4, 4), tolerance=10): skills[key].uses -= 1 if min(coolDowns) >= time.time(): sleep(min(coolDowns) - time.time() + 0.5) skills, nextSkill = detectEndFight(skills, fightButtonCoords[fightWhat], nextSkill) if win32gui.GetForegroundWindow() != idleGodshwdn: win32gui.SetForegroundWindow(idleGodshwdn) for x in range(len(skillsToUse)): key = skillsToUse[x] if key in skills and skills[key].useMove(): coolDowns[x] = skills[key].nextUse sleepTime = max(min(coolDowns) - time.time() + 0.3, atkDelay) if 'focused' not in key.lower( ) and key not in ignore and not skills[key].needUse(): ignore.append(key) skillsToUse.append(key) skillsToUse.remove(key) sleep(sleepTime) break else: if key not in skills: print("Key:", key, "not in skills") elif skills[key].nextUse < time.time() and skills[key].avail: print("Skill:", key, "off cooldown but not able to be used") saveSkills(skills) atexit.unregister(saveSkills) return ''
data = functionality.getIdsByLastName(GLOB['people'], lastname) return jsonify(**{'ids': data[0]}) if __name__ == '__main__': global GLOB parser = argparse.ArgumentParser() parser.add_argument("-d","--debug", help="Optional Debug Mode for stack traces", action="store_true") parser.add_argument("port", help="File to import data from", type=int) #since this is a web app the load data is required (should eventually load through a POST request parser.add_argument("file", help="File to import data from") args = parser.parse_args() # Make sure we have the data loaded before we continue data = people.loadData(args.file, args.debug) while data == None: args.file = utils.getInput('The file provided could not be found or opened please provide another csv file <-1 to exit>: ', str, None) if args.file == '-1': print 'Bye Bye' sys.exit() data = people.loadData(args.file, args.debug) # Set up the app GLOB['people'] = data app.debug=args.debug app.run(host='0.0.0.0', port=args.port)
from collections import defaultdict import utils input = utils.getInput(24) class Grid: WHITE = True BLACK = False START = WHITE moves = { "e": (1, -1, 0), "se": (0, -1, 1), "sw": (-1, 0, 1), "w": (-1, 1, 0), "nw": (0, 1, -1), "ne": (1, 0, -1), } def __init__(self) -> None: super().__init__() self.grid = self._newGrid() self.reset() def _newGrid(self): return defaultdict(lambda: self.START) def _copyGrid(self): new = self._newGrid()
if len(argv) < 2: printErrorMsg("Param number incorrect\n"+USE) exit(1) tPath = argv[1] vPath = None if not isdir(tPath): printErrorMsg("'"+tPath+"'"+" is not a valid directory\n"+USE) exit(1) if (argv[2]): if (not isdir(argv[2])): printErrorMsg("'"+argv[2]+"'"+" is not a valid directory\n"+USE) exit(1) vPath = argv[2] training_data, test_data = loadImgs(tPath, vPath) value = getInput("-1 to expand training data, skip otherwise: ") if (value == '-1'): training_data = expandTrainingData(training_data) epochs = 20 batch = 10 eta = 0.1 lmbda = 0.1 print "\nDefinition of the neural network" print "################################" net = getNeuralNetFromUser() #Allows to load an existing network or creating a new network value = getInput("-1 to manually specify parameters, other key for default: ") if (value == '-1'): epochs, batch, eta, lmbda = processUserNeuralSettings() while(True):
logger.info("batch size " + str(batch_size)) myLambda1 = 0 if "lambda1" in config: myLambda1 = float(config["lambda1"]) myLambda2 = 0 if "lambda2" in config: myLambda2 = float(config["lambda2"]) logger.info("lambda1 " + str(myLambda1)) logger.info("lambda2 " + str(myLambda2)) # load model architecture and word vectors etc binaryCNN = CNN(configfile, train=True) trainfilehandle = open(trainfile) inputMatrixTrain_a, inputMatrixTrain_b, inputMatrixTrain_c, length_a, length_b, length_c, inputFeaturesTrain, resultVectorTrain = getInput( trainfilehandle, binaryCNN.representationsize, binaryCNN.contextsize, binaryCNN.filtersize, binaryCNN.wordvectors, binaryCNN.vectorsize) trainfilehandle.close() devfilehandle = open(devfile) inputMatrixDev_a, inputMatrixDev_b, inputMatrixDev_c, length_a, length_b, length_c, inputFeaturesDev, resultVectorDev = getInput( devfilehandle, binaryCNN.representationsize, binaryCNN.contextsize, binaryCNN.filtersize, binaryCNN.wordvectors, binaryCNN.vectorsize) devfilehandle.close() dt = theano.config.floatX train_set_xa = theano.shared(numpy.matrix(inputMatrixTrain_a, dtype=dt), borrow=True) valid_set_xa = theano.shared(numpy.matrix(inputMatrixDev_a, dtype=dt), borrow=True) train_set_xb = theano.shared(numpy.matrix(inputMatrixTrain_b, dtype=dt),
from utils import getInput, displayList list = [] for i in range(0, 3): list.append(getInput()) displayList(list)
def iprompt(self, out=sys.stdout): """Start a prompt listening to user input.""" cmds = """ Commands: i -- index: print current iteration index p -- pause: interrupt sampling and return to the main console. Sampling can be resumed later with icontinue(). h -- halt: stop sampling and truncate trace. Sampling cannot be resumed for this chain. b -- bg: return to the main console. The sampling will still run in a background thread. There is a possibility of malfunction if you interfere with the Sampler's state or the database during sampling. Use this at your own risk. """ print >> out, """============== PyMC console ============== PyMC is now sampling. Use the following commands to query or pause the sampler. """ print >> out, cmds prompt = True try: while self.status in ['running', 'paused']: # sys.stdout.write('pymc> ') if prompt: out.write('pymc > ') out.flush() if self._exc_info is not None: a, b, c = self._exc_info raise a, b, c cmd = utils.getInput().strip() if cmd == 'i': print >> out, 'Current iteration: ', self._current_iter prompt = True elif cmd == 'p': self.status = 'paused' break elif cmd == 'h': self.status = 'halt' break elif cmd == 'b': return elif cmd == '\n': prompt = True pass elif cmd == '': prompt = False else: print >> out, 'Unknown command: ', cmd print >> out, cmds prompt = True except KeyboardInterrupt: if not self.status == 'ready': self.status = 'halt' if self.status == 'ready': print >> out, "Sampling terminated successfully." else: print >> out, 'Waiting for current iteration to finish...' while self._sampling_thread.isAlive(): sleep(.1) print >> out, 'Exiting interactive prompt...' if self.status == 'paused': print >> out, 'Call icontinue method to continue, or call halt method to truncate traces and stop.'
import utils input = utils.getInput(18) input = "5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))" lines = [l.strip() for l in input.replace(" ", "").splitlines()] def lex(line): i = 0 tree = [] while i < len(line): if line[i].isnumeric(): tree.append(int(line[i])) elif line[i] in "+*": tree.append(line[i]) elif line[i] == "(": _i, branch = lex(line[i + 1:]) i += _i + 1 tree.append(branch) elif line[i] == ")": return i, tree i += 1 return i, tree def calc(tree): tot = 0 op = "+" for i in tree:
import re import utils input = utils.getInput(4).split("\n\n") passports = [s.replace("\n", " ").split(" ") for s in input] hairPattern = re.compile("^#[0-9a-f]{6}$") pidPattern = re.compile("^[0-9]{9}$") def cmVal(v): return v[-2:] == "cm" and int(v[:-2]) >= 150 and int(v[:-2]) <= 193 def inVal(v): return v[-2:] == "in" and int(v[:-2]) >= 59 and int(v[:-2]) <= 76 validation = { "byr": lambda v: int(v) >= 1920 and int(v) <= 2002, "iyr": lambda v: int(v) >= 2010 and int(v) <= 2020, "eyr": lambda v: int(v) >= 2020 and int(v) <= 2030, "hgt": lambda v: cmVal(v) or inVal(v), "hcl": lambda v: bool(hairPattern.match(v)), "ecl": lambda v: v in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"], "pid": lambda v: bool(pidPattern.match(v)), "cid": lambda v: True, }
from typing import Dict, List, Set import utils inputBlocks = utils.getInput(16).split("\n\n") class Rule: def __init__(self, name: str, ranges: list) -> None: super().__init__() self.name = name self.ranges = ranges def __str__(self) -> str: return f"{self.name}: {self.ranges}" @classmethod def parse(cls, row): name, ranges = [s.strip() for s in row.split(":")] parsedRanges = [[int(r) for r in range.split("-")] for range in [s.strip() for s in ranges.split("or")]] return cls(name, parsedRanges) class Ticket: def __init__(self, numbers: list) -> None: super().__init__() self.numbers = numbers
def launchCalcCreations(*args): creation = utils.getInput('Which creation?\n').lower() num = eval(utils.getInput('How many?\n')) return creations.create(creation, num)
import utils input = utils.getInput(8).split("\n") def run(program): acc = 0 pos = 0 prev = [] while True: if pos in prev: return acc, 1 if pos >= len(program): return acc, 0 prev.append(pos) cmd, val = program[pos].split(" ") if cmd == "acc": acc += int(val) pos += 1 elif cmd == "jmp": pos += int(val) elif cmd == "nop": pos += 1 acc = run(input)[0] print(f"part 1: {acc}")
import utils input = [int(i) for i in utils.getInput(9).split("\n")] inputLength = len(input) preableSize = 25 part1 = None part2 = None for i in range(preableSize, inputLength): found = False for j in range(i - preableSize, i): for k in range(i - preableSize, i): if input[j] != input[k] and (input[j] + input[k]) == input[i]: found = True if not found: part1 = input[i] break if part1 is None: exit(1) print(f"part 1: {part1}") for i in range(inputLength): for j in range(inputLength): if j - i < 2: continue currentRange = input[i:j] rangeSum = sum(currentRange)