def __init__(self, object_id, status, context_type, button, controller=None): object_id = object_id.strip() if controller: s = controller._checkId(object_id) if s: raise ValueError, 'Illegal template id: %s' % s status = status.strip() if not status: raise ValueError, 'Illegal status %s' % (status) if not context_type: context_type = ANY_CONTEXT if button is not None: button = button.strip() if not button: button = ANY_BUTTON Key.__init__(self, (object_id, status, context_type, button))
def __init__(self, master): self.master = master tk.Frame.__init__( self, master=master, bg='#EEEEEE' #Background color ) self.db = config.active_objects['db'] self.key_label = self.create_key_label() self.key = Key(self) self.phrase_label = self.create_phrase_label() self.phrase = Phrase(self) self.widget1 = self.key #To allow same call as TranslationMainFrame self.widget2 = self.phrase #To allow same call as TranslationMainFrame if config.get_show_buttons(): print('creating buttons') self.left_button = self.create_left_button() self.right_button = self.create_right_button() self.up_button = self.create_up_button() self.down_button = self.create_down_button() self.activate_get_mode() self.configure_gui() self.bind_event_handlers() if config.get_show_tutorial(): self.load_tutorial()
def __init__(self): # Initialize pygame for the game class, as well as initializing the font. pygame.init() pygame.font.init() # Set the display accordingly (x,y) and set the title for the game. self.screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Game") # Initialize the classes self.player = Node(0, 580, 3.5) self.key = Key(600, 0) self.door = Door(760, 550) #Current floor values are probably going to be level 1 self.floors = [ Floor(300, 0, 20, 50), Floor(500, 1, 20, 50), Floor(100, 2, 20, 50), Floor(200, 3, 20, 50), Floor(400, 4, 20, 50), Floor(250, 5, 20, 50), Floor(50, 6, 20, 50), Floor(150, 7, 20, 50), Floor(550, 8, 20, 50), Floor(450, 9, 20, 50) ] self.counter = Counter(675, 10) self.RUN = True self.playerFoundKey = False self.gameOver = False
def parse(self, node): self.id = int(node.attrib['id']) self.name = node.attrib['name'] for elem in node: k = Key(elem) self.keys[k.get_id()] = k
def __init__(self, master): self.master = master tk.Frame.__init__( self, master=master, bg='#EEEEEE' #Background color ) self.db = config.active_objects['db'] self.db_type = config.get_db_type() self.label_1 = self.create_label_1() self.label_2 = self.create_label_2() if self.db_type == 'standard': self.box_1 = Key(self) self.box_2 = Phrase(self) else: self.box_1 = Language1(self) self.box_2 = Language2(self) if config.get_show_buttons(): print('creating buttons') self.save_button = self.create_save_button() self.copy_button = self.create_copy_button() self.up_button = self.create_up_button() self.down_button = self.create_down_button() self.configure_gui() self.bind_event_handlers()
def get_encryption(self): true_text = '' key = Key() key_valid = [] key_valid = key.format_key() text = Text() text_valid = ' ' text_valid = text.get_text() i = 0 for characters in text_valid: number = key_valid[i] if ((96 < ord(characters) and ord(characters) < 123) or (64 < ord(characters) and ord(characters) < 91)) is False: true_text = true_text + ' ' if characters.isupper() and ord(characters) + number < 91: true_text = true_text + chr(ord(characters) + number) elif characters.isupper() and ord(characters) + number > 90: number = number % 26 true_text = true_text + chr(64 + number) elif characters.islower() and ord(characters) + number < 123: true_text = true_text + chr(ord(characters) + number) elif characters.islower() and ord(characters) + number > 122: number = number % 26 true_text = true_text + chr(96 + number) i += 1 if i == len(key_valid): i = 0 return true_text
def get_user_data(self): connection = self.connect_sqlite() if connection: cursor = connection.cursor() cursor.execute( "SELECT nombre, cedula, correo, servidor, clave, puerto_entrada, puerto_salida, ubicacion, codificador, p12, pin FROM user_data" ) data = cursor.fetchall() if data: if len(data) > 0: data = data[0] self.nombre = data[0] self.cedula = data[1] self.correo = data[2] self.servidor = data[3] self.puerto_entrada = data[5] self.puerto_salida = data[6] self.ubicacion = data[7] self.codificador = data[8] self.p12 = data[9] key = Key(key=self.codificador) self.clave = key.decrypt_message(data[4]) if len(data[10]) > 0: self.pin = key.decrypt_message(data[10]) else: self.pin = ""
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS)) self.v[:,:] = -float("inf") self.backptr = np.zeros((len(s) + 1, Key.NUMBER_OF_CHARS), dtype='int') # Initialization self.backptr[0,:] = Key.START_END self.v[0,:] = self.a[Key.START_END,:] + self.b[index[0],:] for t in range(1,len(s)): for k in range(Key.NUMBER_OF_CHARS): self.v[t][k] = np.max([(self.v[t-1][i] + self.a[i][k] + self.b[k][index[t]]) for i in range(Key.NUMBER_OF_CHARS)]) self.backptr[t][k] = np.argmax([(self.v[t-1][i] + self.a[i][k] + self.b[k][index[t]]) for i in range(Key.NUMBER_OF_CHARS)]) l = '' path = Key.NUMBER_OF_CHARS - 1 for i in range (len(s),1,-1): path = self.backptr[i-1][path] l = l + Key.index_to_char(path) l = l[::-1] return l
def setup(): global root root = tk.Tk() global key key = Key(root) key.pack() root.bind('<KeyPress>', handle_key_press) root.bind('<KeyRelease>', handle_key_release)
def crypt(self, key): key = Key(key) stringCrypted = list(self.clearString) #Loop on all upper characters in the string to crypt for c in str.upper(self.clearString): stringCrypted[key.getKeyIndex()] = self.encodeCharacter(c, key) key.incrementKeyIndex() return stringCrypted
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='double') self.v[:, :, :] = -float("inf") self.backptr = np.zeros( (len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='int') # Initialization # YOUR CODE HERE self.backptr[0, :, :] = Key.START_END self.v[0, Key.START_END, :] = self.a[ Key.START_END, Key.START_END, :] + self.b[index[0], :] # Induction step # YOUR CODE HERE for ndx in range(1, len(index)): for char in range(Key.NUMBER_OF_CHARS): for j in range(Key.NUMBER_OF_CHARS): maxProb = -float("inf") maxPrev = -1 for prev in range(Key.NUMBER_OF_CHARS): if self.v[ndx - 1, prev, j] + self.a[prev, j, char] > maxProb: maxProb = self.v[ndx - 1, prev, j] + self.a[prev, j, char] maxPrev = prev self.v[ndx, j, char] = maxProb + self.b[index[ndx], char] self.backptr[ndx, j, char] = maxPrev # Finally return the result mostLikelyString = "" curNdx = len(index) - 2 prevStateEnd = self.backptr[len(index) - 1, Key.START_END, Key.START_END] prevStateBgn = self.backptr[curNdx, prevStateEnd, Key.START_END] while curNdx > 0: curNdx -= 1 mostLikelyString += Key.index_to_char(prevStateEnd) tmp = prevStateBgn prevStateBgn = self.backptr[curNdx, prevStateBgn, prevStateEnd] prevStateEnd = tmp # REPLACE THE LINE BELOW WITH YOUR CODE return mostLikelyString[::-1]
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ words = s.replace('\r', ' ').split(" ") out = '' for s in words: if s == '': out += ' ' continue s += ' ' word = '' # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros( (len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='double') self.v[:, :, :] = -float("inf") self.backptr = np.zeros( (len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='int') # Initialization self.v[0, Key.START_END, :] = self.a[ Key.START_END, Key.START_END, :] + self.b[index[0], :] self.backptr[0, Key.START_END, :] = Key.START_END for t in range(1, len(s) - 1): for j in range(0, Key.NUMBER_OF_CHARS): for k in range(0, Key.NUMBER_OF_CHARS): score = self.v[t - 1, :, j] + self.a[:, j, k] maxScore = max(score) self.v[t, j, k] = self.b[index[t], k] + maxScore self.backptr[t, j, k] = int(np.argmax(score)) jArray = self.v[len(s) - 2, :, Key.START_END] l = [np.argmax(jArray)] jTemp = Key.START_END jArray = np.argmax(jArray) for i in range(len(s) - 1, 1, -1): temp = self.backptr[i - 1, jArray, jTemp] jTemp = jArray jArray = temp l.append(jArray) l.reverse() for i in l: word += Key.index_to_char(i) out += word return out
def main(): parser = argparse.ArgumentParser(description='ViterbiTrigram decoder') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--file', '-f', type=str, help='decode the contents of a file') group.add_argument('--string', '-s', type=str, help='decode a string') parser.add_argument('--probs', '-p', type=str, required=True, help='trigram probabilities file') parser.add_argument('--check', action='store_true', help='check if your answer is correct') arguments = parser.parse_args() if arguments.file: with codecs.open(arguments.file, 'r', 'utf-8') as f: s1 = f.read().replace('\n', '') elif arguments.string: s1 = arguments.string # Give the filename of the trigram probabilities as a command line argument d = ViterbiTrigramDecoder(arguments.probs) # Append two extra "END" symbols to the input string, to indicate end of sentence. result = d.viterbi(s1 + Key.index_to_char(Key.START_END) + Key.index_to_char(Key.START_END)) if arguments.check: payload = json.dumps({ 'a': d.a.tolist(), 'string': s1, 'result': result }) response = requests.post( 'https://language-engineering.herokuapp.com/lab3_trigram', data=payload, headers={'content-type': 'application/json'}) response_data = response.json() if response_data['correct']: print(result) print('Success! Your results are correct') else: print('Your results:') print(result) print('Your answer is {0:.0f}% similar to the servers'.format( response_data['result'] * 100)) else: print(result)
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS)) self.v[:, :] = -float("inf") self.backptr = np.zeros((len(s), Key.NUMBER_OF_CHARS), dtype='int') # Initialization self.backptr[0, :] = Key.START_END self.v[0, :] = self.a[Key.START_END, :] + self.b[index[0], :] # Induction step # YOUR CODE HERE # Emission, b[observation, character] -> prob of observation given character # Transition, a[prev_state, new_state] -> prob of new state given previous state n_states = len(self.a) n_obs = len(self.v) for obs_idx in range(1, n_obs): for state_idx in range(n_states): # Add previous state probabilities with state transition probabilities t_probs = self.v[obs_idx - 1] + self.a[:, state_idx] # Get most probable previous state self.backptr[obs_idx, state_idx] = np.argmax(t_probs) # Add emission probability to the best transition best_t = t_probs[self.backptr[obs_idx, state_idx]] self.v[obs_idx, state_idx] = best_t + self.b[index[obs_idx], state_idx] c = len(self.backptr) - 1 idx = Key.START_END msg = '' while c > 0: msg = Key.index_to_char(self.backptr[c][idx]) + msg idx = self.backptr[c][idx] c -= 1 # Finally return the result # REPLACE THE LINE BELOW WITH YOUR CODE return msg.strip()
def __init__(self, path): self.cuteloading = None self.asynckey = None try: self.key = Key() self.asynckey = threading.Thread(target=self.key.storechar, args=(), daemon=False) self.asynckey.start() self.time = time.time() width, height = shutil.get_terminal_size((80, 20)) Display.setdisplay(width - 1, height) self.skipupdate = False self.restart = False sys.stdout.write(Display.screen(True)) sys.stdout.flush() self.cuteloading = threading.Thread(target=Display.startloading, args=(width, ), daemon=False) self.cuteloading.start() self.path = path self.now = datetime.datetime.now() self.control = Control(self) self.filedisplay = Display(Display.width, Display.height - 1, 0, 0, False, False) self.infodisplay = Display(Display.width, Display.height, 0, 0, True, True) self.cmddisplay = Display(Display.width, Display.height, 0, 0, False, True) self.currentdisplay = self.filedisplay self.currentfile = self.filedisplay self.loadfile() Display.stoploading(self.cuteloading) self.update() self.key.settrackkeys(True) self.loop() finally: Display.stoploading(self.cuteloading) Key.close() self.asynckey.join() if not self.restart: sys.stdout.write(Display.screen(False)) sys.stdout.flush()
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS)) self.v[:, :] = -float("inf") self.backptr = np.zeros((len(s) + 1, Key.NUMBER_OF_CHARS), dtype='int') # Initialization self.backptr[0, :] = Key.START_END self.v[0, :] = self.a[Key.START_END, :] + self.b[index[0], :] # Induction step # TODO YOUR CODE HERE for ndx in range(1, len(index)): obs = index[ndx] # index of observed character for char in range(Key.NUMBER_OF_CHARS): maxProb = -float("inf") maxNdx = -1 for prevState in range(Key.NUMBER_OF_CHARS): if self.v[ndx - 1, prevState] + self.a[prevState, char] > maxProb: maxProb = self.v[ndx - 1, prevState] + self.a[prevState, char] maxNdx = prevState self.v[ndx, char] = maxProb + self.b[obs, char] self.backptr[ndx, char] = maxNdx # Finally return the result # REPLACE THE LINE BELOW WITH YOUR CODE mostLikelyString = "" prevState = self.backptr[len(index) - 1, Key.START_END] curNdx = len(index) - 2 while curNdx >= 0: mostLikelyString += Key.index_to_char(prevState) prevState = self.backptr[curNdx, prevState] curNdx -= 1 return mostLikelyString[::-1]
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS)) self.v[:, :] = -float("inf") self.backptr = np.zeros((len(s) + 1, Key.NUMBER_OF_CHARS), dtype='int') # Initialization self.backptr[0, :] = Key.START_END self.v[0, :] = self.a[Key.START_END, :] + self.b[index[0], :] # Induction step for observation in range(1, len(index)): for hidden_state in range(Key.NUMBER_OF_CHARS): likelihood_estimates = np.zeros(Key.NUMBER_OF_CHARS) likelihood_estimates[:] = -float("inf") for letter in range(Key.NUMBER_OF_CHARS): likelihood_estimates[letter] = self.v[ observation - 1][letter] + self.a[letter][hidden_state] + self.b[ hidden_state][index[observation]] self.v[observation][hidden_state] = max(likelihood_estimates) self.backptr[observation + 1][hidden_state] = np.argmax(likelihood_estimates) # YOUR CODE HERE legible_text = "" pointer = np.argmax(self.v[len(index) - 1]) for step in range(len(index), 0, -1): letter_in_legible_text = Key.index_to_char(pointer) legible_text = letter_in_legible_text + legible_text pointer = self.backptr[step][pointer] # Finally return the result # REPLACE THE LINE BELOW WITH YOUR CODE return legible_text.strip()
def check_keys_down_up(event): if event.type == pygame.KEYDOWN and key_in_list(event.key) is None: key_list.append(Key(event.key, Key.KeyState.DOWN)) elif event.type == pygame.KEYDOWN: key_in_list(event.key).set_down() elif event.type == pygame.KEYUP: key_in_list(event.key).set_up()
def __init__(self, scale=20, compass=(0, 88)): ''' Docstring goes here ''' # Dimensions self.dx = 2.0 * scale # Width of a white key self.dy = 13.5 * scale # Height of a white key self.bdx = 1.2 * scale # Width of a black key self.bdy = 8.5 * scale # Height of a black key # Settings self.keyUtils = Key(0, (self.dx, self.dy), (self.bdx, self.bdy)) # Key instance (gives us access to instance methods) self.compass = (self.keyUtils.normalize(compass[0]), self.keyUtils.normalize(compass[1])) # Range of keyboard debug(self.compass) # self.surface = pygame.Surface(self.size(padx=10, pady=10, compass=self.compass)) # TODO: Fix hard-coded values self.keys = self.build(self.compass) # Create the piano # Aesthetics self.labelOptions = {'fill': (0x0, 0x0, 0x0)} # self.padx = 10 self.pady = 10 # self.update() print('Range is {} to {}.'.format(*compass)) print('Range is {} to {}.'.format(*self.compass)) print('Index of {} is {}'.format(compass[0], self.compass[0])) print('Index of {} is {}'.format(compass[1], self.compass[1]))
def __init__(self, object_id, context_type, button, controller=None): object_id = object_id.strip() if controller: path_elements = object_id.split('/') for p in path_elements: s = controller._checkId(p) if s: raise ValueError, 'Illegal template id: %s' % s if not context_type: context_type = ANY_CONTEXT if button is not None: button = button.strip() if not button: button = ANY_BUTTON Key.__init__(self, (object_id, context_type, button))
class RSA: key = Key() def encrypt(self, crypt): return int(crypt ** self.key.getValues()["e"]) % self.key.getValues()["N"] def decrypt(self, crypt): return int(crypt ** self.key.getValues()["d"]) % self.key.getValues()["N"]
def test_generation_perf(n = 100): results = OrderedDict() for bits in (192, 224, 256, 384, 521): t = time.time() for i in xrange(n): k = Key.generate(bits) t = time.time() - t results[bits] = t return results
def test_generation_perf(n=100): results = OrderedDict() for bits in (192, 224, 256, 384, 521): t = time.time() for i in xrange(n): k = Key.generate(bits) t = time.time() - t results[bits] = t return results
def speed_test(): f_timer = 0 l_timer = 0 rm_timer = 0 t = 100 for i in range(t): keyf = Key() keyrm = Key() bitl = 512 m = "tempmesmesmes" #testinf fermat start_time = time.time() keyf.GenerateKeysFermat(bitl // 2) (e, n) = keyf.GetPublicKey() (d, n, q, p) = keyf.GetPrivateKey() num = comfunc.text_to_num(m) c = pow(num, e, n) d = pow(c, d, n) f_timer += time.time() - start_time #test rm start_time = time.time() keyrm.GenerateKeysRM(bitl // 2) (e, n) = keyrm.GetPublicKey() (d, n, q, p) = keyrm.GetPrivateKey() num = comfunc.text_to_num(m) c = pow(num, e, n) d = pow(c, d, n) rm_timer += time.time() - start_time #test lib start_time = time.time() (pub, priv) = rsa.newkeys(bitl) ms = m.encode("utf8") c = rsa.encrypt(ms, pub) d = rsa.decrypt(c, priv) ms = ms.decode("utf8") l_timer += time.time() - start_time print("512 bit len crypt encrypt time:") print("for fermat test: ", f_timer / t) print("for frm test: ", rm_timer / t) print("for rsa lib test: ", l_timer / t)
def test_signing_perf(n=100): results = OrderedDict() for bits in (192, 224, 256, 384, 521): k = Key.generate(bits) t = time.time() for i in xrange(n): k.sign("random string") t = time.time() - t results[bits] = t return results
def test_signing_perf(n = 100): results = OrderedDict() for bits in (192, 224, 256, 384, 521): k = Key.generate(bits) t = time.time() for i in xrange(n): k.sign("random string") t = time.time() - t results[bits] = t return results
def test_verification_perf(n=100): results = OrderedDict() for bits in (192, 224, 256, 384, 521): k = Key.generate(bits) s = k.sign('random string') t = time.time() for i in xrange(n): k.verify('random string', s) t = time.time() - t results[bits] = t return results
def getKyes(self, relation): Keys=[] for keys in relation.iter('keys'): for key in keys: key_obj=Key() for attribute in key.iter('attribute'): attribute_object = Attribute(attribute.text) key_obj.Attributes.append(attribute_object) Keys.append(key_obj) return Keys
def initializeKey(self, pathToKeys, delimiter='\t'): """ get the keys and create matrices from them @param pathToKeys: path to keys @return List of Matrices """ keyStringsList = [line for line in self.__open(pathToKeys) if len(line) > 0] keys = list() append = keys.append # loop through each line (i.e. matrix) in the keyStringsList for line in keyStringsList: # add Key objects key = Key(line, delimiter) print "Key validation:", key.getDeterminant() append(key) #print keyStringsList, matrix.matrix, keys return keys
def initializeKey(self, pathToKeys, delimiter='\t'): """ get the keys and create matrices from them @param pathToKeys: path to keys @return List of Matrices """ keyStringsList = [ line for line in self.__open(pathToKeys) if len(line) > 0 ] keys = list() append = keys.append # loop through each line (i.e. matrix) in the keyStringsList for line in keyStringsList: # add Key objects key = Key(line, delimiter) print "Key validation:", key.getDeterminant() append(key) #print keyStringsList, matrix.matrix, keys return keys
def __init__(self, key64, input_str): if len(key64) != 64: raise Exception('The length of key should be 64') # Get the key stream self.key = Key(key64) # Preprocess the input string # Padding at the end of string r = len(input_str) % 64 if r != 0: for i in range(64 - r): input_str += '0' self.input_list = textwrap.wrap(input_str, 64)
def init_b(self): """ Initializes the observation probabilities (the 'B' matrix). """ for i in range(Key.NUMBER_OF_CHARS): cs = Key.neighbour[i] # Initialize all log-probabilities to some small value. for j in range(Key.NUMBER_OF_CHARS): self.b[i][j] = -float("inf") # All neighbouring keys are assigned the probability 0.1 for j in range(len(cs)): self.b[i][Key.char_to_index(cs[j])] = math.log(0.1) # The remainder of the probability mass is given to the correct key. self.b[i][i] = math.log((10 - len(cs)) / 10.0)
def dbProcessSchemes(self): relationList = [] for table in self.tableNames: relObj = Relation() relObj.Name = table for columns in self.insp.get_columns(table): attribute_object = Attribute(columns['name']) attribute_object.Type = columns['type'] attribute_object.Autoincrement = columns['autoincrement'] attribute_object.Nullable = columns['nullable'] relObj.Attributes.append(attribute_object) #attribute_object = Attribute() #attribute_object.Name = columns['name'] key = Key() for att in self.insp.get_primary_keys(table): attribute_object = Attribute(att) key.Attributes.append(attribute_object) relObj.Keys.append(key) #relObj.FDs = self.getFunctionalDependencies(relation) relationList.append(relObj) return relationList
def save_user_data(self): connection = self.connect_sqlite() if connection: key = Key() key.generate_key() self.codificador = key.key self.clave = key.encrypt_message(self.clave) self.pin = key.encrypt_message(self.pin) cursor = connection.cursor() cursor.execute("DELETE FROM user_data") connection.commit() query_str = """INSERT INTO user_data (nombre, cedula, correo, servidor, clave, puerto_entrada, puerto_salida, ubicacion, codificador, p12, pin) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""" cursor.execute( query_str, (self.nombre, self.cedula, self.correo, self.servidor, self.clave, self.puerto_entrada, self.puerto_salida, self.ubicacion, self.codificador, self.p12, self.pin)) connection.commit() return True else: print("error") return False
class Piano(object): ''' Docstring goes here ''' def __init__(self, scale=20, compass=(0, 88)): ''' Docstring goes here ''' # Dimensions self.dx = 2.0 * scale # Width of a white key self.dy = 13.5 * scale # Height of a white key self.bdx = 1.2 * scale # Width of a black key self.bdy = 8.5 * scale # Height of a black key # Settings self.keyUtils = Key(0, (self.dx, self.dy), (self.bdx, self.bdy)) # Key instance (gives us access to instance methods) self.compass = (self.keyUtils.normalize(compass[0]), self.keyUtils.normalize(compass[1])) # Range of keyboard debug(self.compass) # self.surface = pygame.Surface(self.size(padx=10, pady=10, compass=self.compass)) # TODO: Fix hard-coded values self.keys = self.build(self.compass) # Create the piano # Aesthetics self.labelOptions = {'fill': (0x0, 0x0, 0x0)} # self.padx = 10 self.pady = 10 # self.update() print('Range is {} to {}.'.format(*compass)) print('Range is {} to {}.'.format(*self.compass)) print('Index of {} is {}'.format(compass[0], self.compass[0])) print('Index of {} is {}'.format(compass[1], self.compass[1])) def width(self, padx=None, dx=None, compass=None): ''' Docstring goes here ''' # NOTE: Many calculations include (compass[1]-compass[1])*7/12, # which is an unreliable way of calculating the number of white keys return (dx or self.dx) * self.whites(compass) + 2 * (padx or self.padx) def height(self, dy=None, pady=0): ''' Docstring goes here ''' return (dy or self.dy) + (pady or self.pady) * 2 def query(self): ''' Docstring goes here ''' # TODO: Rename, merge with Piano.key (?) raise NotImplementedError def whites(self, compass=None): ''' Total number of white keys in the given range (compass) ''' return sum(1 for i in range(*(compass or self.compass)) if i%12 in Key.whites) # TODO: Find more efficient algorithm (currently O(n)) def size(self, padx=0, pady=0, dx=None, dy=None, compass=None): ''' Size required to fit the entire piano, with optional padding. Use key word arguments to override self.dx, self.dy and self.compass if you so wish. ''' # TODO: Take borders into account (?) # TODO: Query methods for keys return self.width(dx=dx, padx=padx, compass=compass), self.height(dy=dy, pady=pady) def render(self, surface, position): ''' Docstring goes here ''' surface.blit(self.surface, position) def update(self, keys=True, labels=True, whole=True, accidentals=True): ''' Redraws keys and labels ''' # TODO: Implement options (Enums?) for key in self.keys: key.render(self.surface, outline=(0,0,0), origin=(self.padx, self.pady), labelled=(key.kind is Key.WHITE), **self.labelOptions) def key(self, key): # TODO: Use Key alias utilities (...) # TODO: Take offset into account (...) # TODO: Rename (?) # TODO: Make sure this is correct and doesn't break after each change debug('Retrieving key {!r} from piano'.format(key)) debug('Number of keys: ', len(self.keys)) return self.keys[self.keyUtils.alias(key, to=int)-self.compass[0]] # return self.keys[self.keyUtils.alias(key, to=int)] def translate(self, dx, dy, vertices): return [(vtx[0]+dx, vtx[1]+dy) for vtx in vertices] def build(self, compass): ''' Builds the components of the piano ''' # TODO: Options # TODO: Animation # TODO: Wavefront 3D model # TODO: Padding # TODO: Individually accessible keys, colour changes # TODO: Convert to class (?) # TODO: Class for individual keys (press, play, etc.) dx, dy = self.dx, self.dy bdx, bdy = self.bdx, self.bdy # | | # | | # | | # _| |_ # | | # | | # | | # | | # |______| # return [Key(i, (dx, dy), (bdx, bdy), first=compass[0]) for i in range(*compass)] keys = [Key(i, (dx, dy), (bdx, bdy), first=compass[0]) for i in range(*compass)] first = keys[5] print('Shape:', first.shape) print('First: {!r}'.format(first)) debug('Creating {} keys.'.format(len(keys))) debug('Creating {} keys.'.format(self.compass[1]-self.compass[0])) if first.shape in (Key.LEFT, Key.MIDDLE): # HACK: Solves problem with accidentals as the first key first.shape == Key.LEFT first.fill = (255, 50, 25) first.vertices = first.makeVertices((dx-5, dy-5), (bdx, bdy)) return keys def playChord(self, chord, fill=(210, 190, 50)): ''' Docstring goes here ''' for note in chord: self.key(note).play(fill=fill) self.update() def releaseChord(self, chord): ''' Docstring goes here ''' for note in chord: self.key(note).release() self.update()
def viterbi(self, s): """ Performs the Viterbi decoding and returns the most likely string. """ # First turn chars to integers, so that 'a' is represented by 0, # 'b' by 1, and so on. index = [Key.char_to_index(x) for x in s] # The Viterbi matrices self.v = np.zeros((len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='double') self.v[:,:,:] = -float("inf") self.backptr = np.zeros((len(s), Key.NUMBER_OF_CHARS, Key.NUMBER_OF_CHARS), dtype='int') # Initialization # YOUR CODE HERE self.v[0,:,:] = self.a[Key.START_END,Key.START_END,:] + self.b[index[0],:] # v[0,:,:] -> prob of all states at obs 0 for succeding state key.START_END # prob all states 0->26 transition | 26,26 # prob all states 0->26 emitting 26 -> only space can emit 26 self.backptr[0,:,:] = Key.START_END # a[i,j,k] -> prob of going to state k given preceding was j and the one before was i, P(i,j,k) = P(k|i,j) # b[i,k] -> prob of state k emitting oi # v[t,i,k] -> prob of being in state k, passing through most probable succeding state i after first t obs # Induction step # YOUR CODE HERE n_obs = len(s) n_states = len(self.a) for obs_idx in range(1, n_obs): for state_idx in range(n_states): for prec_idx in range(n_states): t_probs = self.v[obs_idx-1,:,prec_idx] + self.a[:,prec_idx,state_idx] self.v[obs_idx,prec_idx,state_idx] = max(t_probs) + self.b[index[obs_idx],state_idx] self.backptr[obs_idx,prec_idx,state_idx] = np.argmax(t_probs) c = len(self.v)-1 this = Key.START_END next_state = Key.START_END after_next = Key.START_END msg = '' while c >= -1: msg = Key.index_to_char(this) + msg this = next_state next_state = after_next after_next = self.backptr[c,next_state,this] c -= 1 # Finally return the result # REPLACE THE LINE BELOW WITH YOUR CODE return msg.strip()
def parse_mainline(self, node): for elem in node: k = Key(elem) self.mainline[k.get_id()] = k
ms = m.encode("utf8") c = rsa.encrypt(ms, pub) d = rsa.decrypt(c, priv) ms = ms.decode("utf8") l_timer += time.time() - start_time print("512 bit len crypt encrypt time:") print("for fermat test: ", f_timer / t) print("for frm test: ", rm_timer / t) print("for rsa lib test: ", l_timer / t) print("Input key bit key length") bitl = int(input()) key = Key() key.GenerateKeysRM(bitl // 2) (e, n) = key.GetPublicKey() (d, n, q, p) = key.GetPrivateKey() print("Input message") # bit length should be less than key lenght m = input() nm = comfunc.text_to_num(m) rndb = 5 nm = comfunc.add_rand_bits(nm, rndb) crypt = pow(nm, e, n) print("Encrypted message: ", crypt)
from Key import Key k = Key() #for x in range(10): #print k.get() print k.report(224000000, False) print k.report(227000000, True, "0xff002201")