def to_graphs( self ): graphs = [] steps = [ Step() ] V, E = set(), set() for action in self._actions: action( steps ) V |= steps[ -1 ].V E |= steps[ -1 ].E for n, s in enumerate( steps ): graph = [ 'digraph G {' ] for v in V: graph.append( '{} {};'.format( v, s.node_format( v ) ) ) for e in E: graph.append( '{}->{} {};'.format( e[0], e[1], s.edge_format( e ) ) ) graph.append( '}' ) graphs.append( '\n'.join( graph ) ) return graphs
def test_duration_stats(self): assert_frame_equal( action(['PewDiePie'], start_date, end_date, API_key).duration_stats(), merge(['PewDiePie'], start_date, end_date, API_key).merge_duration().describe().ix[[ 'count', 'mean', 'std', 'min', 'max' ]].round(2))
def __init__(self, screen, estado, x, y, w, h, ncells): self.screen = screen self.estado = estado self.geometry = (x,y,w,h) self.ncells = ncells self.tamcells = (w/ncells) self.gencells() self.action = action(self.grid, self.geometry, self.tamcells) self.estado.action = self.action
def output(): ''' The function displays the output produced by the program. ''' while True: try: # Prompt user to enter a desired action. variable = input( 'Please choose one of the following actions: number, duration, or published \n> ' ) if variable == 'quit': break # If the user chooses "number", display the number of videos. elif variable == 'number': result = merge(channel_list, start_date, end_date, API_key) print(result.merge_number()) # If the user chooses "duration", display the summary statistics and plot the histograms of video durations. elif variable == 'duration': result = action(channel_list, start_date, end_date, API_key) print(result.duration_stats()) result.duration_hist() # If the user chooses "published", display the summary statistics and plot the barplots of video published times. elif variable == 'published': result = action(channel_list, start_date, end_date, API_key) print( p.concat([result.weekday_mode(), result.hour_mode()], ignore_index=True)) result.published_bar() else: raise ActionError # Need to specify break # In the case of ActionError or KeyboardInterrupt, prompt user to enter a desired action again. except ActionError: print( 'Invalid action: please choose from number, duration, and published' ) except KeyboardInterrupt: print('You have hit the interrupt key') # In the case of ChannelError or HttpError, end the program. except ChannelError: print('Invalid channel name(s)') break
def resolve(self, args, mode_help, rule_help): """ Find what action to and execute it. """ # specify all commands possible cf = ConfigCommands(self.config) rc = RuleCommands(self.config) fc = FileCommands(self.config) # actions reachable from cmd line args # special "_key" : key to find the value in args to find the next action # special "_help": help to use in case of unknown value action = { "_key": "mode", "_help": mode_help, "init": cf.init, "test": fc.test, "log": { "_key": "clear", "_help": None, False: fc.log, True: fc.clear_log }, "rename": fc.rename, "manual-test": fc.manual_test, "rules": { "_key": "action", "_help": rule_help, "add": rc.add, "list": rc.list, "remove": rc.remove }, } # resolve command to apply while not callable(action) and action is not None: key = action["_key"] help = lambda _, f=action["_help"]: f() next = getattr(args, key) action = action.get(next, help) # do action action(args)
def selection_sort(self): for i in range(self.length-1): # Find the minimum element in remaining min_idx = i for j in range(i+1, self.length): #notify two elements selected self.notify_observers(action(SELECTED, i, j, self.elements)) if self.elements[min_idx] > self.elements[j]: min_idx = j #notify new minimum element found self.notify_observers(action(FOUND_LOWER, j, None, self.elements)) # Swap the found minimum element with the first element self.elements[i], self.elements[min_idx] = self.elements[min_idx], self.elements[i] #notify the array modification self.notify_observers(action(MODIFIED, i, min_idx, self.elements)) #notify the element that is in its final position self.notify_observers(action(COMPARED, i, None, self.elements)) #notify array has ben sorted self.notify_observers(action(DONE, None, None, self.elements)) pass
def unpack(reader): subtype, = reader.peek('!H', 0) subclass = action.subtypes.get(subtype) if subclass: return subclass.unpack(reader) obj = action() obj.type = reader.read("!H")[0] _len = reader.read("!H")[0] orig_reader = reader reader = orig_reader.slice(_len - (2 + 2)) reader.skip(4) return obj
def bubble_sort(self): n = len(self.elements) # Traverse through all arrayay elements for i in range(n-1): # range(n) also work but outer loop will repeat one time more than needed if(i != n-1): # Last i elements are already in place for j in range(0, n-i-1): #notify two elements selected self.notify_observers(action(SELECTED, j, j+1, None)) # Swap if the element found is greater than the next element if self.elements[j] > self.elements[j+1] : #notify a grater element has been found self.notify_observers(action(FOUND_LOWER, j+1, None, None)) #modify the array self.elements[j], self.elements[j+1] = self.elements[j+1], self.elements[j] #notify the modification self.notify_observers(action(MODIFIED, j, j+1, self.elements)) #notify the element that is in its final position self.notify_observers(action(COMPARED, j+1, None, None)) #notify array has ben sorted self.notify_observers(action(DONE, None, None, None)) pass
def inquire_msg(msg, s, selfid): global total_pot act_count = 0 if len(flop) == 0 else len(flop) - 2 global cp for line in msg: if ':' not in line: line = line.strip().split(' ') pid = line[0] players[pid].jetton = int(line[1]) players[pid].money = int(line[2]) players[pid].bet = int(line[3]) if players[pid].turn >= players[selfid].turn and act_count > 0 and cp: players[pid].new_bet[act_count - 1] = int(line[3]) players[pid].action[act_count - 1] = line[4] else: players[pid].new_bet[act_count] = int(line[3]) players[pid].action[act_count] = line[4] else: l = line.strip().split(' ') total_pot = int(l[2]) cp = False send = action(hold_card, flop, selfid, players, act_count, total_pot, round_count, gamp, db) s.sendall(send + ' \n')
def __init__(self, socket, team, port, host): self._posX = 0 self._posY = 0 self._lenMapX = 0 self._lenMapY = 0 self._socket = socket self._orientation = 0 self._map = [] self._team = team self._inventaire = inventaire() self._action = action() self._queue = Queue.Queue() self._elevation = elevation() self._lvl = 1 self._nourritureMinimal = 0 self._foodToHelp = 0 self._foodToRequest = 0 self._ping = True self._toIncanteX = -1 self._toIncanteY = -1 self._leveling = False self._waiting = 0 self._call = False self._coolDown = 0 self._intervalle = 0 self._lead = False self._pong = False self._numClient = -1 self._answers = [] self._group = False self._port = port self._host = host self._id = 0 self._count = 0 self._arrived = False self._countAnswer = 0 self._boolAnswer = False
STYLES = { 'FINE': {'fg': 'green'}, 'ERROR': {'fg': 'red'}, 'WARNING': {'fg': 'yellow', 'bold': True}, } TITLES = { 'state': 'Status', 'creation_time': 'Creation Date', 'id': 'Identifier', 'desc': 'Description', 'name': 'Name',} MAX_COLUMN_WIDTHS = { 'desc': 50, 'name': 20,} output_option = click.option('-o', '--output', type=click.Choice(['text', 'json', 'tsv', 'yaml']), default='text', help='Use alternative output format')json_output_option = click.option('-o', '--output', type=click.Choice(['json', 'yaml']), default='json', help='Use alternative output format')watch_option = click.option('-w', '--watch', type=click.IntRange(1, 300), metavar='SECS', help='Auto update the screen every X seconds') def watching(watch: int): if watch: click.clear() yield 0 if watch: while True: time.sleep(watch) click.clear() yield 0 def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo('ClickClick Example {}'.format(__version__)) ctx.exit() @click.group(cls=AliasedGroup, context_settings=CONTEXT_SETTINGS)@click.option('-V', '--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True, help='Print the current version number and exit.')def cli(): pass @cli.command('list')@output_option@watch_optiondef list_dummy_states(output, watch): '''Example for Listings''' states = ['ERROR', 'FINE', 'WARNING'] i = 0 for _ in watching(watch): i += 1 rows = [] for y in (1, 2, 3): id = i * y - i rows.append({'id': id, 'name': 'Column #{}'.format(id), 'state': states[id % len(states)], 'creation_time': 1444911300, 'desc': 'this is a ve' + 'r' * 50 + 'y long description', 'without_title': 'column without title', 'missing_column': 'Column are not in output'}) with OutputFormat(output): print_table('id name state creation_time desc without_title'.split(), rows, styles=STYLES, titles=TITLES, max_column_widths=MAX_COLUMN_WIDTHS) @cli.command()@output_optiondef output(output): '''Example for all possible Echo Formats You see the message only, if the Output TEXT ''' with OutputFormat(output): action('This is a ok:') ok() action('This is a ok with message:') ok('all is fine') action('This is a warning:') warning('please check this') with Action('Start with working..') as act: # save_the_world() act.progress() act.progress() act.progress() act.progress() print_table('id name'.split(), [{'id': 1, 'name': 'Test #1'}, {'id': 2, 'name': 'Test #2'}]) info('Only FYI') action('This is a error:') error('this is wrong, please fix') action('This is a fatal error:') fatal_error('this is a fuckup') info('I\'am not printed, the process a dead') @cli.command()def localtime(): '''Print the localtime''' print('Localtime: {}'.format(get_now())) @cli.command('work-in-progress')def work_in_progress(): '''Work untile working is done''' with Action('do anything..'): pass try: with Action('create an excption..'): raise except: pass with Action('Start with working..') as act: # save_the_world() act.progress() act.progress() act.progress() act.progress() with Action('Calc 1 + 1..') as act: # save_the_world() act.ok(1+1) with Action('Oh, I make an error..') as act: # clear_the_oceans() act.error('work not complete done') with Action('Oh, I make a warning..') as act: # clear_the_air() act.warning('work is complicated') try: with Action('Start an exception..') as act: function_not_found() # noqa act.progress() except: pass with Action('Make a final error..') as act: act.fatal_error('this is the end..') with Action('This should not run..'): pass @cli.command()@click.argument('percentage', type=FloatRange(0, 100, clamp=True), required=True)def work_done(percentage): '''Work done in ?? %''' state = choice('Please select the state of your work', ['Done', 'In Progress', 'unknown', 'lost'], default='lost')
def steps( self ): steps = [ Step() ] for action in self._actions: action( steps ) return steps