def decimal_to_factoradic(decimal): def _print(cq, p, q, r): print('{} / {} = {} r{}'.format(cq, p, q, r)) """Converts a decimal number to factoradic form. Args: decimal (int) - the decimal number to convert Returns: res (int) - the decimal number that has been converted >>> decimal_to_factoradic(463) >>> 341010 """ digits, position = '', 1 quotient, rem = divmod(decimal, position) prev_quotient = quotient _print(prev_quotient, position, quotient, rem) while quotient != 0: # Add digit immediately digits += str(rem) # Update position and quotient/remainder for next iteration position += 1 # Store a copy of previous quotient for visualization purposes. prev_quotient = quotient quotient, rem = divmod(quotient, position) _print(prev_quotient, position, quotient, rem) # Add final remainder after while loop terminates digits += str(rem) digits = digits[::-1] print_simple('dec2fac result', digits) return int(digits)
def _print(text, title, thing): members = [ ref for ref in dir(thing) if not ref.startswith('__') and not ref.endswith('__') ] print_simple('{} << {} >>'.format(text, title), [thing] + members, newline=False)
def factoradic_to_decimal(factoradic): """Converts a factoradic number to decimal form. Args: factoradic (int) - the factoradic number to convert Returns: res (int) - the converted decimal >>> factoradic_to_decimal('341010') >>> 463 """ res = 0 digits = list(str(factoradic)) positions = list(reversed(range(0, len(digits)))) print_simple('Positions', positions, newline=False) for k, digit in enumerate(digits): # digit x k ! # e.g. 5 x 5 ! = 5 x (5!) res += factpos(int(digit), positions[k]) print_simple('fac2dec result', res, newline=False) return res
if DEBUG: with Section('Retroactive data structures'): print_h2('Partially retroactive node') partial = PartiallyRetroactiveNode() _example = {'foo': 'bam'} partial['foo'] = _example partial['bar'] = {'foo': 'bam'} # Do some updates to test. for x in range(4): partial['foo'] = { '{}{}'.format(x, k): v for k, v in _example.iteritems() } # Test plain values partial['foo'] = 133332 print_simple('Partially retroactive data:', partial.versions) print_simple('All data for `foo`:', partial['foo']) print_h2('Fully retroactive node') full = FullyRetroactiveNode() # Values with the longest prefix also can be used to indicate # the number of updates done, if the token value is unique enough. # E.g. 'value': '_foo' => 'value': '___foo' indicates 'foo' # was updated three times. full['name'] = {'first': 'Chris', 'last': 'Tabor'} full['dob'] = {'month': 'Jan', 'day': '05', 'year': '1986'} full['name'] = {'first': 'Christopher', 'last': 'Tabor'} full['name'] = {'first': 'Christobot', 'last': 'Taborium'} full['name'] = {'first': 'Christobonicus', 'last': 'Taboriot'} print_simple('Fully retroactive data:', full.versions)
# Values are randomly seeded and will not describe a # network topology appropriately, but are used for # illustrating the general idea. for n in range(4): # Create a test ip + random ips for using in code below ip = faker.ipv4() if n > 0 else '192.168.0.0' rt.add({ 'destination': ip, 'network_mask': subnet_mask(), 'gateway': faker.ipv4(), 'interface': faker.ipv4(), 'metric': rr(1, 10), 'protocol': u'Local' }) print(rt) print_simple('Destinations', rt.get_all('destination')) print_simple('Network Mask', rt.get_all('network_mask')) print_simple('Gateway', rt.get_all('gateway')) print_simple('Metrics', rt.get_all('metric')) print_simple('Network ID', rt.get_networkid('192.168.0.0')) _bin = encoders.dec_to_bin print('{} {} {} {}'.format( _bin(192), _bin(168), _bin(100), _bin(41)))
2 | integer ---------------------------- """ def format_table(code_string): s_table = symtable(code_string, 'string', 'exec') table = [] for child in s_table.get_children(): row = { 'name': child.get_name(), 'scope': 'global', 'children': [subchild.get_name() for subchild in child.get_children()] } table.append(row) return s_table, table if DEBUG: with Section('Data structure - symbol table'): """Messing around with built-in symbol table parser.""" prnt('Some example code...', test_func) symbols, formatted = format_table(test_func) assert len(symbols.lookup('Maths').get_namespaces()) == 1 assert len(symbols.lookup('Words').get_namespaces()) == 1 print_simple('Output using stdlib symtable module:', [symbols, formatted]) prnt('Which might be translated to...', example_output)
from MOAL.helpers.display import Section from MOAL.helpers.display import print_success from MOAL.helpers.display import print_error from MOAL.helpers.display import print_simple from itertools import permutations DEBUG = True if __name__ == '__main__' else False def bigrams(conditions): _bigrams = [] for k, condition in enumerate(conditions): if k < len(conditions) - 1: _bigrams.append([conditions[k + 1], condition, True, False]) _bigrams.append([conditions[k + 1], condition, True, True]) _bigrams.append([conditions[k + 1], condition, False, True]) _bigrams.append([conditions[k + 1], condition, False, False]) return _bigrams if DEBUG: with Section('All-pairs testing'): conditions = ['user', 'email', 'pass', 'pass2'] perms = [p for p in permutations(conditions)] print_simple('Long way', perms, newline=False) print_error('Length: {}'.format(len(perms)), prefix='[LONG]') bgrams = bigrams(conditions) print_simple('Short (all-pairs) way', bgrams, newline=False) print_success('Length: {}'.format(len(bgrams)), prefix='[SHORT]')
try: # Should not work, since it exists, # and is no longer the current item. pnode['foo'] = {'foo': 'bar'} except MutableAccessException: print('Successfully blocked write of existing version.') print_h2('Persistent full node') pfatnode = FullyPersistentNode() # Updating and overriding existing data print(pfatnode) pfatnode['foo'] = {'bar': 'baz'} print(pfatnode) pfatnode['bar'] = {'baz': 'bar'} print(pfatnode) print_simple('Current fat node data', pfatnode.get_current()) for _ in range(2): pfatnode[gibberish2()] = {gibberish2(): gibberish2()} print_simple('Fat node data', pfatnode.versions) print_h2('Persistent confluent') confluent = ConfluentlyPersistentNode() confluent['foo'] = {gibberish2(): gibberish2()} confluent['bar'] = {gibberish2(): gibberish2()} confluent['bim'] = {gibberish2(): gibberish2()} confluent['baz'] = {gibberish2(): gibberish2()} print_simple('Confluent node data', confluent.versions) confluent.meld('melded_example', versions=['foo', 'bar', 'baz', 'bim']) print_simple('Confluent node data', confluent.versions)
def get_invoices(self): print_simple('All invoices', self.invoices.get_all())
def _show_program(self): cmd_title('PROGRAM') print_simple('States list', self.states) print_simple('Transitions', self.transitions) print_simple('Tape', self.tape)
prnt('Testing value update', '', newlines=False) for node in linked_list: print(node) assert node.cargo print_h2('Parallel arrays') # "Parallel" arrays MAX_ITEMS = 10 names = [faker.name() for _ in range(MAX_ITEMS)] emails = [faker.email() for _ in range(MAX_ITEMS)] parallel = [names, emails] for index in range(MAX_ITEMS): print('Name: {}, Email: {}'.format(names[index], emails[index])) print_h2('Matrix/Vector arrays') matrix = dm.random_matrix(rows=5, columns=5, choices=range(20)) print_simple('Matrix', matrix) print_h2('Sorted array') # Props to John Neumann for "inventing" it orig = range(10) shuffle(orig) print('Shuffled: {}'.format(orig)) print('Sorted: {}'.format(sorted(orig))) # Wikipedia glossary practice singleton = [1] not_singleton = [1, 2]
for thing in ['cat', 1, 'dog', 2, range(0, 3), 0.03]: assert thing == id(thing) print(thing, id(thing)) print_h4('Function composition') res = compose_hybrid('composition is neat!', f=dictify, g=listify) print(res) print_h4('Random funcs') print(listify('foo')) print(dictify('foo')) print_h4('Higher order function composition') f2 = compose_hybrid_hof(f=listify, g=dictify) print(f2('composition yay!')) print_h4('Function composition on a "stream" or incoming set') res = [compose_hybrid(str(x), f=fooify, g=bazify) for x in range(4)] print(res) print_h4('Messing around...') res = ''.join(res) for x in range(4): res += compose_hybrid(x, f=fooify, g=bazify) print(res) res = '' for x in range(10): # Just to make things interesting... res += compose_hybrid(random_dna(), f=delimit, g=prefix) print(res) composed = f_g(f, g, 4) print_simple('Traditional composed example:', composed, newline=False)
version = self._handlenode(version['data']) if DEBUG: with Section('Retroactive data structures'): print_h2('Partially retroactive node') partial = PartiallyRetroactiveNode() _example = {'foo': 'bam'} partial['foo'] = _example partial['bar'] = {'foo': 'bam'} # Do some updates to test. for x in range(4): partial['foo'] = { '{}{}'.format(x, k): v for k, v in _example.iteritems()} # Test plain values partial['foo'] = 133332 print_simple('Partially retroactive data:', partial.versions) print_simple('All data for `foo`:', partial['foo']) print_h2('Fully retroactive node') full = FullyRetroactiveNode() # Values with the longest prefix also can be used to indicate # the number of updates done, if the token value is unique enough. # E.g. 'value': '_foo' => 'value': '___foo' indicates 'foo' # was updated three times. full['name'] = {'first': 'Chris', 'last': 'Tabor'} full['dob'] = {'month': 'Jan', 'day': '05', 'year': '1986'} full['name'] = {'first': 'Christopher', 'last': 'Tabor'} full['name'] = {'first': 'Christobot', 'last': 'Taborium'} full['name'] = {'first': 'Christobonicus', 'last': 'Taboriot'} print_simple('Fully retroactive data:', full.versions)
self.count = 0 def add_leaf(self, leaves): if len(self.top) + leaves % 2 != 0: raise ValueError('Leaf count must be a power of 2!') for n in range(leaves): self.count += 1 self.top.append([]) def add(self, leaf, items): if len(self.top[leaf]) + len(items) % 2 != 0: raise ValueError('Items count not a power of 2') self.top[leaf] += items def __str__(self): return '[{}]'.format(', '.join(map(str, self.top))) if DEBUG: with Section('Hashed array tree'): hat = HashedArrayTree() hat.add_leaf(4) print_simple('HAT', hat) try: hat.add(1, ['foo', 'bar', 'bim', 'baz', 'bim']) except ValueError: print('- Prevented unexpected value.') hat.add(1, ['foo', 'bar', 'bim', 'baz']) hat.add(2, ['foo', 'baz']) print(hat)
if __name__ == '__main__': from os import getcwd from os import sys sys.path.append(getcwd()) from MOAL.helpers.display import Section from MOAL.helpers.display import print_simple from MOAL.helpers.display import print_h2 import tiger import hashlib import hmac DEBUG = True if __name__ == '__main__' else False if DEBUG: with Section('Message digest cryptography functions'): sekrit = 'A very very secret thing' print_h2('Hashlib algorithms') for algo in hashlib.algorithms: hashed = hashlib.new(algo).hexdigest() print_simple(algo, hashed, newline=False) print_h2('HMAC') _hmac = hmac.new('*****@*****.**', sekrit) print(_hmac.hexdigest()) _tiger = tiger.new(sekrit).hexdigest() print_simple('Tiger (TTH)', _tiger)
if DEBUG: with Section('Data structure - routing table'): rt = RoutingTable() # Values are randomly seeded and will not describe a # network topology appropriately, but are used for # illustrating the general idea. for n in range(4): # Create a test ip + random ips for using in code below ip = faker.ipv4() if n > 0 else '192.168.0.0' rt.add({ 'destination': ip, 'network_mask': subnet_mask(), 'gateway': faker.ipv4(), 'interface': faker.ipv4(), 'metric': rr(1, 10), 'protocol': u'Local' }) print(rt) print_simple('Destinations', rt.get_all('destination')) print_simple('Network Mask', rt.get_all('network_mask')) print_simple('Gateway', rt.get_all('gateway')) print_simple('Metrics', rt.get_all('metric')) print_simple('Network ID', rt.get_networkid('192.168.0.0')) _bin = encoders.dec_to_bin print('{} {} {} {}'.format(_bin(192), _bin(168), _bin(100), _bin(41)))
def __str__(self): print_simple('<PriorityQueue>', self.items) return ''
for x in count: index = choice(count) # Truncate for visual purposes (e.g. nested brackets, etc) chars = self.string[0:self._max] # Make sure it contains both, since the form language definition # requires it. if chars[-1] == self.left: chars += self.right print('Dyck language subset: {}'.format(''.join(chars))) # Insert brackets at random locations, as this can produce # variations that show possible nesting. self.string.insert(index, '{}{}{}'.format( self.left, '', self.right)) def show_equation(self, equation): eq = list(equation) eq = filter(lambda x: x.strip() in [self.right, self.left], eq) print(''.join(eq)) return ''.join(eq) if DEBUG: with Section('Dyck language'): dycklang = Dyck(12) dycklang.run() print(dycklang) print_simple('Absolute value:', abs(dycklang), newline=False) assert dycklang.is_balanced() assert dycklang.show_equation( '(2x - 3 + (7 / 2)) + ((3x x (4 - 2)) + (4x - (1 * (3 + 5))))')
__author__ = """Chris Tabor ([email protected])""" if __name__ == '__main__': from os import getcwd from os import sys sys.path.append(getcwd()) from MOAL.helpers.display import Section from MOAL.helpers.display import print_simple from MOAL.helpers.display import print_h2 import tiger import hashlib import hmac DEBUG = True if __name__ == '__main__' else False if DEBUG: with Section('Message digest cryptography functions'): sekrit = 'A very very secret thing' print_h2('Hashlib algorithms') for algo in hashlib.algorithms: hashed = hashlib.new(algo).hexdigest() print_simple(algo, hashed, newline=False) print_h2('HMAC') _hmac = hmac.new('*****@*****.**', sekrit) print(_hmac.hexdigest()) _tiger = tiger.new(sekrit).hexdigest() print_simple('Tiger (TTH)', _tiger)
It has nothing to do with lightmaps -- it's just to experiment with example 'ascii lighting' for more interesting visualizations. """ self.lighting = [] pixels = self.height * self.width if recipe == 1: for k in xrange(pixels): self.lighting.append(rr(0, 255)) elif recipe == 2: for k in xrange(pixels): self.lighting.append(rr(0, (k + 1) * 5)) elif recipe == 3: for k in xrange(pixels): if self.width < self.height: self.lighting.append(rr(self.width, self.height)) else: self.lighting.append(rr(self.height, self.width)) if DEBUG: with Section('Lightmap - 3d renderer'): lightmap = Lightmap(height=10, width=80) lightmap.compute() print_simple(lightmap, 'recipe #1') lightmap.compute(recipe=2) print_simple(lightmap, 'recipe #2') lightmap.compute(recipe=3) print_simple(lightmap, 'recipe #3')
def _print(text, title, thing): members = [ref for ref in dir(thing) if not ref.startswith('__') and not ref.endswith('__')] print_simple('{} << {} >>'.format( text, title), [thing] + members, newline=False)
def __str__(self): print_simple('Actions', self.actions, newline=False) return ''
# Truncate for visual purposes (e.g. nested brackets, etc) chars = self.string[0:self._max] # Make sure it contains both, since the form language definition # requires it. if chars[-1] == self.left: chars += self.right print('Dyck language subset: {}'.format(''.join(chars))) # Insert brackets at random locations, as this can produce # variations that show possible nesting. self.string.insert(index, '{}{}{}'.format(self.left, '', self.right)) def show_equation(self, equation): eq = list(equation) eq = filter(lambda x: x.strip() in [self.right, self.left], eq) print(''.join(eq)) return ''.join(eq) if DEBUG: with Section('Dyck language'): dycklang = Dyck(12) dycklang.run() print(dycklang) print_simple('Absolute value:', abs(dycklang), newline=False) assert dycklang.is_balanced() assert dycklang.show_equation( '(2x - 3 + (7 / 2)) + ((3x x (4 - 2)) + (4x - (1 * (3 + 5))))') dycklang = Dyck(12, left='[', right=']') dycklang.run()
y | def var '{}{}' | string object 2 | integer ---------------------------- """ def format_table(code_string): s_table = symtable(code_string, "string", "exec") table = [] for child in s_table.get_children(): row = { "name": child.get_name(), "scope": "global", "children": [subchild.get_name() for subchild in child.get_children()], } table.append(row) return s_table, table if DEBUG: with Section("Data structure - symbol table"): """Messing around with built-in symbol table parser.""" prnt("Some example code...", test_func) symbols, formatted = format_table(test_func) assert len(symbols.lookup("Maths").get_namespaces()) == 1 assert len(symbols.lookup("Words").get_namespaces()) == 1 print_simple("Output using stdlib symtable module:", [symbols, formatted]) prnt("Which might be translated to...", example_output)