code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def auto_convert_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=True): ''' Performs a first step conversion of the cell to check it's type or try to convert if a valid conversion exists. Args: parens_as_neg: Converts numerics surrounded by parens to negative values ''' conversion = cell # Is an numeric? if isinstance(cell, (int, float)): pass # Is a string? elif isinstance(cell, basestring): # Blank cell? if not cell: conversion = None else: conversion = auto_convert_string_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=parens_as_neg) # Is something else?? Convert to string elif cell != None: # Since we shouldn't get this event from most file types, # make this a warning level conversion flag flagable.flag_change(flags, 'warning', position, worksheet, flagable.FLAGS['unknown-to-string']) conversion = str(cell) # Empty cell? if not conversion: conversion = None else: # Otherwise we have an empty cell pass return conversion
def function[auto_convert_cell, parameter[flagable, cell, position, worksheet, flags, units, parens_as_neg]]: constant[ Performs a first step conversion of the cell to check it's type or try to convert if a valid conversion exists. Args: parens_as_neg: Converts numerics surrounded by parens to negative values ] variable[conversion] assign[=] name[cell] if call[name[isinstance], parameter[name[cell], tuple[[<ast.Name object at 0x7da20c992530>, <ast.Name object at 0x7da20c9932e0>]]]] begin[:] pass return[name[conversion]]
keyword[def] identifier[auto_convert_cell] ( identifier[flagable] , identifier[cell] , identifier[position] , identifier[worksheet] , identifier[flags] , identifier[units] , identifier[parens_as_neg] = keyword[True] ): literal[string] identifier[conversion] = identifier[cell] keyword[if] identifier[isinstance] ( identifier[cell] ,( identifier[int] , identifier[float] )): keyword[pass] keyword[elif] identifier[isinstance] ( identifier[cell] , identifier[basestring] ): keyword[if] keyword[not] identifier[cell] : identifier[conversion] = keyword[None] keyword[else] : identifier[conversion] = identifier[auto_convert_string_cell] ( identifier[flagable] , identifier[cell] , identifier[position] , identifier[worksheet] , identifier[flags] , identifier[units] , identifier[parens_as_neg] = identifier[parens_as_neg] ) keyword[elif] identifier[cell] != keyword[None] : identifier[flagable] . identifier[flag_change] ( identifier[flags] , literal[string] , identifier[position] , identifier[worksheet] , identifier[flagable] . identifier[FLAGS] [ literal[string] ]) identifier[conversion] = identifier[str] ( identifier[cell] ) keyword[if] keyword[not] identifier[conversion] : identifier[conversion] = keyword[None] keyword[else] : keyword[pass] keyword[return] identifier[conversion]
def auto_convert_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=True): """ Performs a first step conversion of the cell to check it's type or try to convert if a valid conversion exists. Args: parens_as_neg: Converts numerics surrounded by parens to negative values """ conversion = cell # Is an numeric? if isinstance(cell, (int, float)): pass # depends on [control=['if'], data=[]] # Is a string? elif isinstance(cell, basestring): # Blank cell? if not cell: conversion = None # depends on [control=['if'], data=[]] else: conversion = auto_convert_string_cell(flagable, cell, position, worksheet, flags, units, parens_as_neg=parens_as_neg) # depends on [control=['if'], data=[]] # Is something else?? Convert to string elif cell != None: # Since we shouldn't get this event from most file types, # make this a warning level conversion flag flagable.flag_change(flags, 'warning', position, worksheet, flagable.FLAGS['unknown-to-string']) conversion = str(cell) # Empty cell? if not conversion: conversion = None # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['cell']] else: # Otherwise we have an empty cell pass return conversion
def lookup_path(self, mold_id_path, default=_marker): """ For the given mold_id_path, look up the mold_id and translate that path to its filesystem equivalent. """ fragments = mold_id_path.split('/') mold_id = '/'.join(fragments[:2]) try: subpath = [] for piece in fragments[2:]: if (sep in piece or (altsep and altsep in piece) or piece == pardir): raise KeyError elif piece and piece != '.': subpath.append(piece) path = self.mold_id_to_path(mold_id) except KeyError: if default is _marker: raise return default return join(path, *subpath)
def function[lookup_path, parameter[self, mold_id_path, default]]: constant[ For the given mold_id_path, look up the mold_id and translate that path to its filesystem equivalent. ] variable[fragments] assign[=] call[name[mold_id_path].split, parameter[constant[/]]] variable[mold_id] assign[=] call[constant[/].join, parameter[call[name[fragments]][<ast.Slice object at 0x7da18dc9bd00>]]] <ast.Try object at 0x7da18dc9a770> return[call[name[join], parameter[name[path], <ast.Starred object at 0x7da18dc98cd0>]]]
keyword[def] identifier[lookup_path] ( identifier[self] , identifier[mold_id_path] , identifier[default] = identifier[_marker] ): literal[string] identifier[fragments] = identifier[mold_id_path] . identifier[split] ( literal[string] ) identifier[mold_id] = literal[string] . identifier[join] ( identifier[fragments] [: literal[int] ]) keyword[try] : identifier[subpath] =[] keyword[for] identifier[piece] keyword[in] identifier[fragments] [ literal[int] :]: keyword[if] ( identifier[sep] keyword[in] identifier[piece] keyword[or] ( identifier[altsep] keyword[and] identifier[altsep] keyword[in] identifier[piece] ) keyword[or] identifier[piece] == identifier[pardir] ): keyword[raise] identifier[KeyError] keyword[elif] identifier[piece] keyword[and] identifier[piece] != literal[string] : identifier[subpath] . identifier[append] ( identifier[piece] ) identifier[path] = identifier[self] . identifier[mold_id_to_path] ( identifier[mold_id] ) keyword[except] identifier[KeyError] : keyword[if] identifier[default] keyword[is] identifier[_marker] : keyword[raise] keyword[return] identifier[default] keyword[return] identifier[join] ( identifier[path] ,* identifier[subpath] )
def lookup_path(self, mold_id_path, default=_marker): """ For the given mold_id_path, look up the mold_id and translate that path to its filesystem equivalent. """ fragments = mold_id_path.split('/') mold_id = '/'.join(fragments[:2]) try: subpath = [] for piece in fragments[2:]: if sep in piece or (altsep and altsep in piece) or piece == pardir: raise KeyError # depends on [control=['if'], data=[]] elif piece and piece != '.': subpath.append(piece) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['piece']] path = self.mold_id_to_path(mold_id) # depends on [control=['try'], data=[]] except KeyError: if default is _marker: raise # depends on [control=['if'], data=[]] return default # depends on [control=['except'], data=[]] return join(path, *subpath)
def play_match(black_model, white_model, games, sgf_dir): """Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player """ with utils.logged_timer("Loading weights"): black_net = dual_net.DualNetwork(black_model) white_net = dual_net.DualNetwork(white_model) readouts = FLAGS.num_readouts black = MCTSPlayer(black_net, two_player_mode=True) white = MCTSPlayer(white_net, two_player_mode=True) black_name = os.path.basename(black_net.save_file) white_name = os.path.basename(white_net.save_file) for i in range(games): num_move = 0 # The move number of the current game for player in [black, white]: player.initialize_game() first_node = player.root.select_leaf() prob, val = player.network.run(first_node.position) first_node.incorporate_results(prob, val, first_node) while True: start = time.time() active = white if num_move % 2 else black inactive = black if num_move % 2 else white current_readouts = active.root.N while active.root.N < current_readouts + readouts: active.tree_search() # print some stats on the search if FLAGS.verbose >= 3: print(active.root.position) # First, check the roots for hopeless games. if active.should_resign(): # Force resign active.set_result(-1 * active.root.position.to_play, was_resign=True) inactive.set_result( active.root.position.to_play, was_resign=True) if active.is_done(): fname = "{:d}-{:s}-vs-{:s}-{:d}.sgf".format(int(time.time()), white_name, black_name, i) active.set_result(active.root.position.result(), was_resign=False) with gfile.GFile(os.path.join(sgf_dir, fname), 'w') as _file: sgfstr = sgf_wrapper.make_sgf(active.position.recent, active.result_string, black_name=black_name, white_name=white_name) _file.write(sgfstr) print("Finished game", i, active.result_string) break move = active.pick_move() active.play_move(move) inactive.play_move(move) dur = time.time() - start num_move += 1 if (FLAGS.verbose > 1) or (FLAGS.verbose == 1 and num_move % 10 == 9): timeper = (dur / readouts) * 100.0 print(active.root.position) print("%d: %d readouts, %.3f s/100. (%.2f sec)" % (num_move, readouts, timeper, dur))
def function[play_match, parameter[black_model, white_model, games, sgf_dir]]: constant[Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player ] with call[name[utils].logged_timer, parameter[constant[Loading weights]]] begin[:] variable[black_net] assign[=] call[name[dual_net].DualNetwork, parameter[name[black_model]]] variable[white_net] assign[=] call[name[dual_net].DualNetwork, parameter[name[white_model]]] variable[readouts] assign[=] name[FLAGS].num_readouts variable[black] assign[=] call[name[MCTSPlayer], parameter[name[black_net]]] variable[white] assign[=] call[name[MCTSPlayer], parameter[name[white_net]]] variable[black_name] assign[=] call[name[os].path.basename, parameter[name[black_net].save_file]] variable[white_name] assign[=] call[name[os].path.basename, parameter[name[white_net].save_file]] for taget[name[i]] in starred[call[name[range], parameter[name[games]]]] begin[:] variable[num_move] assign[=] constant[0] for taget[name[player]] in starred[list[[<ast.Name object at 0x7da20c7cba90>, <ast.Name object at 0x7da20c7c8d60>]]] begin[:] call[name[player].initialize_game, parameter[]] variable[first_node] assign[=] call[name[player].root.select_leaf, parameter[]] <ast.Tuple object at 0x7da20c7cacb0> assign[=] call[name[player].network.run, parameter[name[first_node].position]] call[name[first_node].incorporate_results, parameter[name[prob], name[val], name[first_node]]] while constant[True] begin[:] variable[start] assign[=] call[name[time].time, parameter[]] variable[active] assign[=] <ast.IfExp object at 0x7da20c7cb220> variable[inactive] assign[=] <ast.IfExp object at 0x7da20c7c8280> variable[current_readouts] assign[=] name[active].root.N while compare[name[active].root.N less[<] binary_operation[name[current_readouts] + name[readouts]]] begin[:] call[name[active].tree_search, parameter[]] if compare[name[FLAGS].verbose greater_or_equal[>=] constant[3]] begin[:] call[name[print], parameter[name[active].root.position]] if call[name[active].should_resign, parameter[]] begin[:] call[name[active].set_result, parameter[binary_operation[<ast.UnaryOp object at 0x7da18c4cfee0> * name[active].root.position.to_play]]] call[name[inactive].set_result, parameter[name[active].root.position.to_play]] if call[name[active].is_done, parameter[]] begin[:] variable[fname] assign[=] call[constant[{:d}-{:s}-vs-{:s}-{:d}.sgf].format, parameter[call[name[int], parameter[call[name[time].time, parameter[]]]], name[white_name], name[black_name], name[i]]] call[name[active].set_result, parameter[call[name[active].root.position.result, parameter[]]]] with call[name[gfile].GFile, parameter[call[name[os].path.join, parameter[name[sgf_dir], name[fname]]], constant[w]]] begin[:] variable[sgfstr] assign[=] call[name[sgf_wrapper].make_sgf, parameter[name[active].position.recent, name[active].result_string]] call[name[_file].write, parameter[name[sgfstr]]] call[name[print], parameter[constant[Finished game], name[i], name[active].result_string]] break variable[move] assign[=] call[name[active].pick_move, parameter[]] call[name[active].play_move, parameter[name[move]]] call[name[inactive].play_move, parameter[name[move]]] variable[dur] assign[=] binary_operation[call[name[time].time, parameter[]] - name[start]] <ast.AugAssign object at 0x7da18c4cf580> if <ast.BoolOp object at 0x7da18c4cf490> begin[:] variable[timeper] assign[=] binary_operation[binary_operation[name[dur] / name[readouts]] * constant[100.0]] call[name[print], parameter[name[active].root.position]] call[name[print], parameter[binary_operation[constant[%d: %d readouts, %.3f s/100. (%.2f sec)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da18c4ced70>, <ast.Name object at 0x7da18c4cf820>, <ast.Name object at 0x7da18c4cdfc0>, <ast.Name object at 0x7da18c4cc8b0>]]]]]
keyword[def] identifier[play_match] ( identifier[black_model] , identifier[white_model] , identifier[games] , identifier[sgf_dir] ): literal[string] keyword[with] identifier[utils] . identifier[logged_timer] ( literal[string] ): identifier[black_net] = identifier[dual_net] . identifier[DualNetwork] ( identifier[black_model] ) identifier[white_net] = identifier[dual_net] . identifier[DualNetwork] ( identifier[white_model] ) identifier[readouts] = identifier[FLAGS] . identifier[num_readouts] identifier[black] = identifier[MCTSPlayer] ( identifier[black_net] , identifier[two_player_mode] = keyword[True] ) identifier[white] = identifier[MCTSPlayer] ( identifier[white_net] , identifier[two_player_mode] = keyword[True] ) identifier[black_name] = identifier[os] . identifier[path] . identifier[basename] ( identifier[black_net] . identifier[save_file] ) identifier[white_name] = identifier[os] . identifier[path] . identifier[basename] ( identifier[white_net] . identifier[save_file] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[games] ): identifier[num_move] = literal[int] keyword[for] identifier[player] keyword[in] [ identifier[black] , identifier[white] ]: identifier[player] . identifier[initialize_game] () identifier[first_node] = identifier[player] . identifier[root] . identifier[select_leaf] () identifier[prob] , identifier[val] = identifier[player] . identifier[network] . identifier[run] ( identifier[first_node] . identifier[position] ) identifier[first_node] . identifier[incorporate_results] ( identifier[prob] , identifier[val] , identifier[first_node] ) keyword[while] keyword[True] : identifier[start] = identifier[time] . identifier[time] () identifier[active] = identifier[white] keyword[if] identifier[num_move] % literal[int] keyword[else] identifier[black] identifier[inactive] = identifier[black] keyword[if] identifier[num_move] % literal[int] keyword[else] identifier[white] identifier[current_readouts] = identifier[active] . identifier[root] . identifier[N] keyword[while] identifier[active] . identifier[root] . identifier[N] < identifier[current_readouts] + identifier[readouts] : identifier[active] . identifier[tree_search] () keyword[if] identifier[FLAGS] . identifier[verbose] >= literal[int] : identifier[print] ( identifier[active] . identifier[root] . identifier[position] ) keyword[if] identifier[active] . identifier[should_resign] (): identifier[active] . identifier[set_result] (- literal[int] * identifier[active] . identifier[root] . identifier[position] . identifier[to_play] , identifier[was_resign] = keyword[True] ) identifier[inactive] . identifier[set_result] ( identifier[active] . identifier[root] . identifier[position] . identifier[to_play] , identifier[was_resign] = keyword[True] ) keyword[if] identifier[active] . identifier[is_done] (): identifier[fname] = literal[string] . identifier[format] ( identifier[int] ( identifier[time] . identifier[time] ()), identifier[white_name] , identifier[black_name] , identifier[i] ) identifier[active] . identifier[set_result] ( identifier[active] . identifier[root] . identifier[position] . identifier[result] (), identifier[was_resign] = keyword[False] ) keyword[with] identifier[gfile] . identifier[GFile] ( identifier[os] . identifier[path] . identifier[join] ( identifier[sgf_dir] , identifier[fname] ), literal[string] ) keyword[as] identifier[_file] : identifier[sgfstr] = identifier[sgf_wrapper] . identifier[make_sgf] ( identifier[active] . identifier[position] . identifier[recent] , identifier[active] . identifier[result_string] , identifier[black_name] = identifier[black_name] , identifier[white_name] = identifier[white_name] ) identifier[_file] . identifier[write] ( identifier[sgfstr] ) identifier[print] ( literal[string] , identifier[i] , identifier[active] . identifier[result_string] ) keyword[break] identifier[move] = identifier[active] . identifier[pick_move] () identifier[active] . identifier[play_move] ( identifier[move] ) identifier[inactive] . identifier[play_move] ( identifier[move] ) identifier[dur] = identifier[time] . identifier[time] ()- identifier[start] identifier[num_move] += literal[int] keyword[if] ( identifier[FLAGS] . identifier[verbose] > literal[int] ) keyword[or] ( identifier[FLAGS] . identifier[verbose] == literal[int] keyword[and] identifier[num_move] % literal[int] == literal[int] ): identifier[timeper] =( identifier[dur] / identifier[readouts] )* literal[int] identifier[print] ( identifier[active] . identifier[root] . identifier[position] ) identifier[print] ( literal[string] %( identifier[num_move] , identifier[readouts] , identifier[timeper] , identifier[dur] ))
def play_match(black_model, white_model, games, sgf_dir): """Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player """ with utils.logged_timer('Loading weights'): black_net = dual_net.DualNetwork(black_model) white_net = dual_net.DualNetwork(white_model) # depends on [control=['with'], data=[]] readouts = FLAGS.num_readouts black = MCTSPlayer(black_net, two_player_mode=True) white = MCTSPlayer(white_net, two_player_mode=True) black_name = os.path.basename(black_net.save_file) white_name = os.path.basename(white_net.save_file) for i in range(games): num_move = 0 # The move number of the current game for player in [black, white]: player.initialize_game() first_node = player.root.select_leaf() (prob, val) = player.network.run(first_node.position) first_node.incorporate_results(prob, val, first_node) # depends on [control=['for'], data=['player']] while True: start = time.time() active = white if num_move % 2 else black inactive = black if num_move % 2 else white current_readouts = active.root.N while active.root.N < current_readouts + readouts: active.tree_search() # depends on [control=['while'], data=[]] # print some stats on the search if FLAGS.verbose >= 3: print(active.root.position) # depends on [control=['if'], data=[]] # First, check the roots for hopeless games. if active.should_resign(): # Force resign active.set_result(-1 * active.root.position.to_play, was_resign=True) inactive.set_result(active.root.position.to_play, was_resign=True) # depends on [control=['if'], data=[]] if active.is_done(): fname = '{:d}-{:s}-vs-{:s}-{:d}.sgf'.format(int(time.time()), white_name, black_name, i) active.set_result(active.root.position.result(), was_resign=False) with gfile.GFile(os.path.join(sgf_dir, fname), 'w') as _file: sgfstr = sgf_wrapper.make_sgf(active.position.recent, active.result_string, black_name=black_name, white_name=white_name) _file.write(sgfstr) # depends on [control=['with'], data=['_file']] print('Finished game', i, active.result_string) break # depends on [control=['if'], data=[]] move = active.pick_move() active.play_move(move) inactive.play_move(move) dur = time.time() - start num_move += 1 if FLAGS.verbose > 1 or (FLAGS.verbose == 1 and num_move % 10 == 9): timeper = dur / readouts * 100.0 print(active.root.position) print('%d: %d readouts, %.3f s/100. (%.2f sec)' % (num_move, readouts, timeper, dur)) # depends on [control=['if'], data=[]] # depends on [control=['while'], data=[]] # depends on [control=['for'], data=['i']]
def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512])) return unsigned_chksum, signed_chksum
def function[calc_chksums, parameter[buf]]: constant[Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. ] variable[unsigned_chksum] assign[=] binary_operation[constant[256] + call[name[sum], parameter[binary_operation[call[name[struct].unpack, parameter[constant[148B], call[name[buf]][<ast.Slice object at 0x7da1b2064400>]]] + call[name[struct].unpack, parameter[constant[356B], call[name[buf]][<ast.Slice object at 0x7da1b2064580>]]]]]]] variable[signed_chksum] assign[=] binary_operation[constant[256] + call[name[sum], parameter[binary_operation[call[name[struct].unpack, parameter[constant[148b], call[name[buf]][<ast.Slice object at 0x7da1b2064520>]]] + call[name[struct].unpack, parameter[constant[356b], call[name[buf]][<ast.Slice object at 0x7da1b2067130>]]]]]]] return[tuple[[<ast.Name object at 0x7da1b20679d0>, <ast.Name object at 0x7da1b2067970>]]]
keyword[def] identifier[calc_chksums] ( identifier[buf] ): literal[string] identifier[unsigned_chksum] = literal[int] + identifier[sum] ( identifier[struct] . identifier[unpack] ( literal[string] , identifier[buf] [: literal[int] ])+ identifier[struct] . identifier[unpack] ( literal[string] , identifier[buf] [ literal[int] : literal[int] ])) identifier[signed_chksum] = literal[int] + identifier[sum] ( identifier[struct] . identifier[unpack] ( literal[string] , identifier[buf] [: literal[int] ])+ identifier[struct] . identifier[unpack] ( literal[string] , identifier[buf] [ literal[int] : literal[int] ])) keyword[return] identifier[unsigned_chksum] , identifier[signed_chksum]
def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack('148B', buf[:148]) + struct.unpack('356B', buf[156:512])) signed_chksum = 256 + sum(struct.unpack('148b', buf[:148]) + struct.unpack('356b', buf[156:512])) return (unsigned_chksum, signed_chksum)
def upload_file(self, room_id, description, file, message, **kwargs): """ Upload file to room :param room_id: :param description: :param file: :param kwargs: :return: """ return UploadFile(settings=self.settings, **kwargs).call( room_id=room_id, description=description, file=file, message=message, **kwargs )
def function[upload_file, parameter[self, room_id, description, file, message]]: constant[ Upload file to room :param room_id: :param description: :param file: :param kwargs: :return: ] return[call[call[name[UploadFile], parameter[]].call, parameter[]]]
keyword[def] identifier[upload_file] ( identifier[self] , identifier[room_id] , identifier[description] , identifier[file] , identifier[message] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[UploadFile] ( identifier[settings] = identifier[self] . identifier[settings] ,** identifier[kwargs] ). identifier[call] ( identifier[room_id] = identifier[room_id] , identifier[description] = identifier[description] , identifier[file] = identifier[file] , identifier[message] = identifier[message] , ** identifier[kwargs] )
def upload_file(self, room_id, description, file, message, **kwargs): """ Upload file to room :param room_id: :param description: :param file: :param kwargs: :return: """ return UploadFile(settings=self.settings, **kwargs).call(room_id=room_id, description=description, file=file, message=message, **kwargs)
def return_error(self, status, payload=None): """Error handler called by request handlers when an error occurs and the request should be aborted. Usage:: def handle_post_request(self, *args, **kwargs): self.request_handler = self.get_request_handler() try: self.request_handler.process(self.get_data()) except SomeException as e: self.return_error(400, payload=self.request_handler.errors) return self.return_create_response() """ resp = None if payload is not None: payload = json.dumps(payload) resp = self.make_response(payload, status=status) if status in [405]: abort(status) else: abort(status, response=resp)
def function[return_error, parameter[self, status, payload]]: constant[Error handler called by request handlers when an error occurs and the request should be aborted. Usage:: def handle_post_request(self, *args, **kwargs): self.request_handler = self.get_request_handler() try: self.request_handler.process(self.get_data()) except SomeException as e: self.return_error(400, payload=self.request_handler.errors) return self.return_create_response() ] variable[resp] assign[=] constant[None] if compare[name[payload] is_not constant[None]] begin[:] variable[payload] assign[=] call[name[json].dumps, parameter[name[payload]]] variable[resp] assign[=] call[name[self].make_response, parameter[name[payload]]] if compare[name[status] in list[[<ast.Constant object at 0x7da1b0627790>]]] begin[:] call[name[abort], parameter[name[status]]]
keyword[def] identifier[return_error] ( identifier[self] , identifier[status] , identifier[payload] = keyword[None] ): literal[string] identifier[resp] = keyword[None] keyword[if] identifier[payload] keyword[is] keyword[not] keyword[None] : identifier[payload] = identifier[json] . identifier[dumps] ( identifier[payload] ) identifier[resp] = identifier[self] . identifier[make_response] ( identifier[payload] , identifier[status] = identifier[status] ) keyword[if] identifier[status] keyword[in] [ literal[int] ]: identifier[abort] ( identifier[status] ) keyword[else] : identifier[abort] ( identifier[status] , identifier[response] = identifier[resp] )
def return_error(self, status, payload=None): """Error handler called by request handlers when an error occurs and the request should be aborted. Usage:: def handle_post_request(self, *args, **kwargs): self.request_handler = self.get_request_handler() try: self.request_handler.process(self.get_data()) except SomeException as e: self.return_error(400, payload=self.request_handler.errors) return self.return_create_response() """ resp = None if payload is not None: payload = json.dumps(payload) resp = self.make_response(payload, status=status) # depends on [control=['if'], data=['payload']] if status in [405]: abort(status) # depends on [control=['if'], data=['status']] else: abort(status, response=resp)
def delete(names, yes): """ Delete a training job. """ failures = False for name in names: try: experiment = ExperimentClient().get(normalize_job_name(name)) except FloydException: experiment = ExperimentClient().get(name) if not experiment: failures = True continue if not yes and not click.confirm("Delete Job: {}?".format(experiment.name), abort=False, default=False): floyd_logger.info("Job {}: Skipped.".format(experiment.name)) continue if not ExperimentClient().delete(experiment.id): failures = True else: floyd_logger.info("Job %s Deleted", experiment.name) if failures: sys.exit(1)
def function[delete, parameter[names, yes]]: constant[ Delete a training job. ] variable[failures] assign[=] constant[False] for taget[name[name]] in starred[name[names]] begin[:] <ast.Try object at 0x7da1b0dc1c00> if <ast.UnaryOp object at 0x7da1b0dc0fd0> begin[:] variable[failures] assign[=] constant[True] continue if <ast.BoolOp object at 0x7da1b0dc38b0> begin[:] call[name[floyd_logger].info, parameter[call[constant[Job {}: Skipped.].format, parameter[name[experiment].name]]]] continue if <ast.UnaryOp object at 0x7da1b0dc0bb0> begin[:] variable[failures] assign[=] constant[True] if name[failures] begin[:] call[name[sys].exit, parameter[constant[1]]]
keyword[def] identifier[delete] ( identifier[names] , identifier[yes] ): literal[string] identifier[failures] = keyword[False] keyword[for] identifier[name] keyword[in] identifier[names] : keyword[try] : identifier[experiment] = identifier[ExperimentClient] (). identifier[get] ( identifier[normalize_job_name] ( identifier[name] )) keyword[except] identifier[FloydException] : identifier[experiment] = identifier[ExperimentClient] (). identifier[get] ( identifier[name] ) keyword[if] keyword[not] identifier[experiment] : identifier[failures] = keyword[True] keyword[continue] keyword[if] keyword[not] identifier[yes] keyword[and] keyword[not] identifier[click] . identifier[confirm] ( literal[string] . identifier[format] ( identifier[experiment] . identifier[name] ), identifier[abort] = keyword[False] , identifier[default] = keyword[False] ): identifier[floyd_logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[experiment] . identifier[name] )) keyword[continue] keyword[if] keyword[not] identifier[ExperimentClient] (). identifier[delete] ( identifier[experiment] . identifier[id] ): identifier[failures] = keyword[True] keyword[else] : identifier[floyd_logger] . identifier[info] ( literal[string] , identifier[experiment] . identifier[name] ) keyword[if] identifier[failures] : identifier[sys] . identifier[exit] ( literal[int] )
def delete(names, yes): """ Delete a training job. """ failures = False for name in names: try: experiment = ExperimentClient().get(normalize_job_name(name)) # depends on [control=['try'], data=[]] except FloydException: experiment = ExperimentClient().get(name) # depends on [control=['except'], data=[]] if not experiment: failures = True continue # depends on [control=['if'], data=[]] if not yes and (not click.confirm('Delete Job: {}?'.format(experiment.name), abort=False, default=False)): floyd_logger.info('Job {}: Skipped.'.format(experiment.name)) continue # depends on [control=['if'], data=[]] if not ExperimentClient().delete(experiment.id): failures = True # depends on [control=['if'], data=[]] else: floyd_logger.info('Job %s Deleted', experiment.name) # depends on [control=['for'], data=['name']] if failures: sys.exit(1) # depends on [control=['if'], data=[]]
def create(self, path, data=None): """Send a POST CRUD API request to the given path using the given data which will be converted to json""" return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH, path), data=json.dumps(data)))
def function[create, parameter[self, path, data]]: constant[Send a POST CRUD API request to the given path using the given data which will be converted to json] return[call[name[self].handleresult, parameter[call[name[self].r.post, parameter[call[name[urljoin], parameter[binary_operation[name[self].url + name[CRUD_PATH]], name[path]]]]]]]]
keyword[def] identifier[create] ( identifier[self] , identifier[path] , identifier[data] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[handleresult] ( identifier[self] . identifier[r] . identifier[post] ( identifier[urljoin] ( identifier[self] . identifier[url] + identifier[CRUD_PATH] , identifier[path] ), identifier[data] = identifier[json] . identifier[dumps] ( identifier[data] )))
def create(self, path, data=None): """Send a POST CRUD API request to the given path using the given data which will be converted to json""" return self.handleresult(self.r.post(urljoin(self.url + CRUD_PATH, path), data=json.dumps(data)))
def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry.""" # we call str() on nameservers to convert it from unicode to ascii nameservers = str(nameservers) split_char = self._determine_split_char(nameservers) ns_list = nameservers.split(split_char) for ns in ns_list: if not ns in self.nameservers: self.nameservers.append(ns)
def function[_config_win32_nameservers, parameter[self, nameservers]]: constant[Configure a NameServer registry entry.] variable[nameservers] assign[=] call[name[str], parameter[name[nameservers]]] variable[split_char] assign[=] call[name[self]._determine_split_char, parameter[name[nameservers]]] variable[ns_list] assign[=] call[name[nameservers].split, parameter[name[split_char]]] for taget[name[ns]] in starred[name[ns_list]] begin[:] if <ast.UnaryOp object at 0x7da1b0ab8b20> begin[:] call[name[self].nameservers.append, parameter[name[ns]]]
keyword[def] identifier[_config_win32_nameservers] ( identifier[self] , identifier[nameservers] ): literal[string] identifier[nameservers] = identifier[str] ( identifier[nameservers] ) identifier[split_char] = identifier[self] . identifier[_determine_split_char] ( identifier[nameservers] ) identifier[ns_list] = identifier[nameservers] . identifier[split] ( identifier[split_char] ) keyword[for] identifier[ns] keyword[in] identifier[ns_list] : keyword[if] keyword[not] identifier[ns] keyword[in] identifier[self] . identifier[nameservers] : identifier[self] . identifier[nameservers] . identifier[append] ( identifier[ns] )
def _config_win32_nameservers(self, nameservers): """Configure a NameServer registry entry.""" # we call str() on nameservers to convert it from unicode to ascii nameservers = str(nameservers) split_char = self._determine_split_char(nameservers) ns_list = nameservers.split(split_char) for ns in ns_list: if not ns in self.nameservers: self.nameservers.append(ns) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['ns']]
def x_axis_transform(compound, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None): """Move a compound such that the x-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_x_axis : mb.Compound or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new x-axis. point_on_xy_plane : mb.Compound, or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new xy-plane. """ import mbuild as mb if new_origin is None: new_origin = np.array([0, 0, 0]) elif isinstance(new_origin, mb.Compound): new_origin = new_origin.pos elif isinstance(new_origin, (tuple, list,np.ndarray)): new_origin = np.asarray(new_origin) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of length 3 or None for the new_origin' ' parameter. User passed type: {}.'.format(type(new_origin))) if point_on_x_axis is None: point_on_x_axis = np.array([1.0, 0.0, 0.0]) elif isinstance(point_on_x_axis, mb.Compound): point_on_x_axis = point_on_x_axis.pos elif isinstance(point_on_x_axis, (list, tuple, np.ndarray)): point_on_x_axis = np.asarray(point_on_x_axis) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_x_axis' ' parameter. User passed type: {}.'.format(type(point_on_x_axis))) if point_on_xy_plane is None: point_on_xy_plane = np.array([1.0, 1.0, 0.0]) elif isinstance(point_on_xy_plane, mb.Compound): point_on_xy_plane = point_on_xy_plane.pos elif isinstance(point_on_xy_plane, (list, tuple, np.ndarray)): point_on_xy_plane = np.asarray(point_on_xy_plane) else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept' ' mb.Compounds, list-like of size 3, or None for the point_on_xy_plane' ' parameter. User passed type: {}.'.format(type(point_on_xy_plane))) atom_positions = compound.xyz_with_ports transform = AxisTransform(new_origin=new_origin, point_on_x_axis=point_on_x_axis, point_on_xy_plane=point_on_xy_plane) atom_positions = transform.apply_to(atom_positions) compound.xyz_with_ports = atom_positions
def function[x_axis_transform, parameter[compound, new_origin, point_on_x_axis, point_on_xy_plane]]: constant[Move a compound such that the x-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_x_axis : mb.Compound or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new x-axis. point_on_xy_plane : mb.Compound, or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new xy-plane. ] import module[mbuild] as alias[mb] if compare[name[new_origin] is constant[None]] begin[:] variable[new_origin] assign[=] call[name[np].array, parameter[list[[<ast.Constant object at 0x7da18bc73af0>, <ast.Constant object at 0x7da18bc73eb0>, <ast.Constant object at 0x7da18bc73400>]]]] if compare[name[point_on_x_axis] is constant[None]] begin[:] variable[point_on_x_axis] assign[=] call[name[np].array, parameter[list[[<ast.Constant object at 0x7da1b1e03fd0>, <ast.Constant object at 0x7da1b1e02c80>, <ast.Constant object at 0x7da1b1e01b10>]]]] if compare[name[point_on_xy_plane] is constant[None]] begin[:] variable[point_on_xy_plane] assign[=] call[name[np].array, parameter[list[[<ast.Constant object at 0x7da1b1e03df0>, <ast.Constant object at 0x7da1b1e034c0>, <ast.Constant object at 0x7da1b1e039a0>]]]] variable[atom_positions] assign[=] name[compound].xyz_with_ports variable[transform] assign[=] call[name[AxisTransform], parameter[]] variable[atom_positions] assign[=] call[name[transform].apply_to, parameter[name[atom_positions]]] name[compound].xyz_with_ports assign[=] name[atom_positions]
keyword[def] identifier[x_axis_transform] ( identifier[compound] , identifier[new_origin] = keyword[None] , identifier[point_on_x_axis] = keyword[None] , identifier[point_on_xy_plane] = keyword[None] ): literal[string] keyword[import] identifier[mbuild] keyword[as] identifier[mb] keyword[if] identifier[new_origin] keyword[is] keyword[None] : identifier[new_origin] = identifier[np] . identifier[array] ([ literal[int] , literal[int] , literal[int] ]) keyword[elif] identifier[isinstance] ( identifier[new_origin] , identifier[mb] . identifier[Compound] ): identifier[new_origin] = identifier[new_origin] . identifier[pos] keyword[elif] identifier[isinstance] ( identifier[new_origin] ,( identifier[tuple] , identifier[list] , identifier[np] . identifier[ndarray] )): identifier[new_origin] = identifier[np] . identifier[asarray] ( identifier[new_origin] ) keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] literal[string] . identifier[format] ( identifier[type] ( identifier[new_origin] ))) keyword[if] identifier[point_on_x_axis] keyword[is] keyword[None] : identifier[point_on_x_axis] = identifier[np] . identifier[array] ([ literal[int] , literal[int] , literal[int] ]) keyword[elif] identifier[isinstance] ( identifier[point_on_x_axis] , identifier[mb] . identifier[Compound] ): identifier[point_on_x_axis] = identifier[point_on_x_axis] . identifier[pos] keyword[elif] identifier[isinstance] ( identifier[point_on_x_axis] ,( identifier[list] , identifier[tuple] , identifier[np] . identifier[ndarray] )): identifier[point_on_x_axis] = identifier[np] . identifier[asarray] ( identifier[point_on_x_axis] ) keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] literal[string] . identifier[format] ( identifier[type] ( identifier[point_on_x_axis] ))) keyword[if] identifier[point_on_xy_plane] keyword[is] keyword[None] : identifier[point_on_xy_plane] = identifier[np] . identifier[array] ([ literal[int] , literal[int] , literal[int] ]) keyword[elif] identifier[isinstance] ( identifier[point_on_xy_plane] , identifier[mb] . identifier[Compound] ): identifier[point_on_xy_plane] = identifier[point_on_xy_plane] . identifier[pos] keyword[elif] identifier[isinstance] ( identifier[point_on_xy_plane] ,( identifier[list] , identifier[tuple] , identifier[np] . identifier[ndarray] )): identifier[point_on_xy_plane] = identifier[np] . identifier[asarray] ( identifier[point_on_xy_plane] ) keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] literal[string] . identifier[format] ( identifier[type] ( identifier[point_on_xy_plane] ))) identifier[atom_positions] = identifier[compound] . identifier[xyz_with_ports] identifier[transform] = identifier[AxisTransform] ( identifier[new_origin] = identifier[new_origin] , identifier[point_on_x_axis] = identifier[point_on_x_axis] , identifier[point_on_xy_plane] = identifier[point_on_xy_plane] ) identifier[atom_positions] = identifier[transform] . identifier[apply_to] ( identifier[atom_positions] ) identifier[compound] . identifier[xyz_with_ports] = identifier[atom_positions]
def x_axis_transform(compound, new_origin=None, point_on_x_axis=None, point_on_xy_plane=None): """Move a compound such that the x-axis lies on specified points. Parameters ---------- compound : mb.Compound The compound to move. new_origin : mb.Compound or list-like of size 3, optional, default=[0.0, 0.0, 0.0] Where to place the new origin of the coordinate system. point_on_x_axis : mb.Compound or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new x-axis. point_on_xy_plane : mb.Compound, or list-like of size 3, optional, default=[1.0, 0.0, 0.0] A point on the new xy-plane. """ import mbuild as mb if new_origin is None: new_origin = np.array([0, 0, 0]) # depends on [control=['if'], data=['new_origin']] elif isinstance(new_origin, mb.Compound): new_origin = new_origin.pos # depends on [control=['if'], data=[]] elif isinstance(new_origin, (tuple, list, np.ndarray)): new_origin = np.asarray(new_origin) # depends on [control=['if'], data=[]] else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept mb.Compounds, list-like of length 3 or None for the new_origin parameter. User passed type: {}.'.format(type(new_origin))) if point_on_x_axis is None: point_on_x_axis = np.array([1.0, 0.0, 0.0]) # depends on [control=['if'], data=['point_on_x_axis']] elif isinstance(point_on_x_axis, mb.Compound): point_on_x_axis = point_on_x_axis.pos # depends on [control=['if'], data=[]] elif isinstance(point_on_x_axis, (list, tuple, np.ndarray)): point_on_x_axis = np.asarray(point_on_x_axis) # depends on [control=['if'], data=[]] else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept mb.Compounds, list-like of size 3, or None for the point_on_x_axis parameter. User passed type: {}.'.format(type(point_on_x_axis))) if point_on_xy_plane is None: point_on_xy_plane = np.array([1.0, 1.0, 0.0]) # depends on [control=['if'], data=['point_on_xy_plane']] elif isinstance(point_on_xy_plane, mb.Compound): point_on_xy_plane = point_on_xy_plane.pos # depends on [control=['if'], data=[]] elif isinstance(point_on_xy_plane, (list, tuple, np.ndarray)): point_on_xy_plane = np.asarray(point_on_xy_plane) # depends on [control=['if'], data=[]] else: raise TypeError('x_axis_transform, y_axis_transform, and z_axis_transform only accept mb.Compounds, list-like of size 3, or None for the point_on_xy_plane parameter. User passed type: {}.'.format(type(point_on_xy_plane))) atom_positions = compound.xyz_with_ports transform = AxisTransform(new_origin=new_origin, point_on_x_axis=point_on_x_axis, point_on_xy_plane=point_on_xy_plane) atom_positions = transform.apply_to(atom_positions) compound.xyz_with_ports = atom_positions
def get_resource_record_types(self): """Gets all the resource record types supported. return: (osid.type.TypeList) - the list of supported resource record types *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceProfile.get_resource_record_types_template record_type_maps = get_registry('RESOURCE_RECORD_TYPES', self._runtime) record_types = [] for record_type_map in record_type_maps: record_types.append(Type(**record_type_maps[record_type_map])) return TypeList(record_types)
def function[get_resource_record_types, parameter[self]]: constant[Gets all the resource record types supported. return: (osid.type.TypeList) - the list of supported resource record types *compliance: mandatory -- This method must be implemented.* ] variable[record_type_maps] assign[=] call[name[get_registry], parameter[constant[RESOURCE_RECORD_TYPES], name[self]._runtime]] variable[record_types] assign[=] list[[]] for taget[name[record_type_map]] in starred[name[record_type_maps]] begin[:] call[name[record_types].append, parameter[call[name[Type], parameter[]]]] return[call[name[TypeList], parameter[name[record_types]]]]
keyword[def] identifier[get_resource_record_types] ( identifier[self] ): literal[string] identifier[record_type_maps] = identifier[get_registry] ( literal[string] , identifier[self] . identifier[_runtime] ) identifier[record_types] =[] keyword[for] identifier[record_type_map] keyword[in] identifier[record_type_maps] : identifier[record_types] . identifier[append] ( identifier[Type] (** identifier[record_type_maps] [ identifier[record_type_map] ])) keyword[return] identifier[TypeList] ( identifier[record_types] )
def get_resource_record_types(self): """Gets all the resource record types supported. return: (osid.type.TypeList) - the list of supported resource record types *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for # osid.resource.ResourceProfile.get_resource_record_types_template record_type_maps = get_registry('RESOURCE_RECORD_TYPES', self._runtime) record_types = [] for record_type_map in record_type_maps: record_types.append(Type(**record_type_maps[record_type_map])) # depends on [control=['for'], data=['record_type_map']] return TypeList(record_types)
def strsplit(self, pattern): """ Split the strings in the target column on the given regular expression pattern. :param str pattern: The split pattern. :returns: H2OFrame containing columns of the split strings. """ fr = H2OFrame._expr(expr=ExprNode("strsplit", self, pattern)) fr._ex._cache.nrows = self.nrow return fr
def function[strsplit, parameter[self, pattern]]: constant[ Split the strings in the target column on the given regular expression pattern. :param str pattern: The split pattern. :returns: H2OFrame containing columns of the split strings. ] variable[fr] assign[=] call[name[H2OFrame]._expr, parameter[]] name[fr]._ex._cache.nrows assign[=] name[self].nrow return[name[fr]]
keyword[def] identifier[strsplit] ( identifier[self] , identifier[pattern] ): literal[string] identifier[fr] = identifier[H2OFrame] . identifier[_expr] ( identifier[expr] = identifier[ExprNode] ( literal[string] , identifier[self] , identifier[pattern] )) identifier[fr] . identifier[_ex] . identifier[_cache] . identifier[nrows] = identifier[self] . identifier[nrow] keyword[return] identifier[fr]
def strsplit(self, pattern): """ Split the strings in the target column on the given regular expression pattern. :param str pattern: The split pattern. :returns: H2OFrame containing columns of the split strings. """ fr = H2OFrame._expr(expr=ExprNode('strsplit', self, pattern)) fr._ex._cache.nrows = self.nrow return fr
def kv_format(*args, **kwargs): """Formats any given list of Key-Value pairs or dictionaries in ``*args`` and any given keyword argument in ``**kwargs``. Any item within a given list or dictionary will also be visited and added to the output. Strings will be escaped to prevent leaking binary data, ambiguous characters or other control sequences. Strings with escaped characters or spaces will be encapsulated in quotes. Other objects will be converted into a string and will be treated as a string afterwards. :param \*args: Values to format. :type \*args: any Iterable or Mapping :param \*\*kwargs: Keyword Values to format :return: Formatted content of ``*args`` and ``**kwargs``. :rtype: :data:`six.text_type <six:six.text_type>` """ pairs = ((dump_dict(arg) if isinstance(arg, Mapping) else (dump_key_values(arg) if isinstance(arg, Iterable) else None)) for arg in args + (kwargs, )) return _format_pairs(chain.from_iterable(p for p in pairs if p))
def function[kv_format, parameter[]]: constant[Formats any given list of Key-Value pairs or dictionaries in ``*args`` and any given keyword argument in ``**kwargs``. Any item within a given list or dictionary will also be visited and added to the output. Strings will be escaped to prevent leaking binary data, ambiguous characters or other control sequences. Strings with escaped characters or spaces will be encapsulated in quotes. Other objects will be converted into a string and will be treated as a string afterwards. :param \*args: Values to format. :type \*args: any Iterable or Mapping :param \*\*kwargs: Keyword Values to format :return: Formatted content of ``*args`` and ``**kwargs``. :rtype: :data:`six.text_type <six:six.text_type>` ] variable[pairs] assign[=] <ast.GeneratorExp object at 0x7da1b1351750> return[call[name[_format_pairs], parameter[call[name[chain].from_iterable, parameter[<ast.GeneratorExp object at 0x7da2041d85b0>]]]]]
keyword[def] identifier[kv_format] (* identifier[args] ,** identifier[kwargs] ): literal[string] identifier[pairs] =(( identifier[dump_dict] ( identifier[arg] ) keyword[if] identifier[isinstance] ( identifier[arg] , identifier[Mapping] ) keyword[else] ( identifier[dump_key_values] ( identifier[arg] ) keyword[if] identifier[isinstance] ( identifier[arg] , identifier[Iterable] ) keyword[else] keyword[None] )) keyword[for] identifier[arg] keyword[in] identifier[args] +( identifier[kwargs] ,)) keyword[return] identifier[_format_pairs] ( identifier[chain] . identifier[from_iterable] ( identifier[p] keyword[for] identifier[p] keyword[in] identifier[pairs] keyword[if] identifier[p] ))
def kv_format(*args, **kwargs): """Formats any given list of Key-Value pairs or dictionaries in ``*args`` and any given keyword argument in ``**kwargs``. Any item within a given list or dictionary will also be visited and added to the output. Strings will be escaped to prevent leaking binary data, ambiguous characters or other control sequences. Strings with escaped characters or spaces will be encapsulated in quotes. Other objects will be converted into a string and will be treated as a string afterwards. :param \\*args: Values to format. :type \\*args: any Iterable or Mapping :param \\*\\*kwargs: Keyword Values to format :return: Formatted content of ``*args`` and ``**kwargs``. :rtype: :data:`six.text_type <six:six.text_type>` """ pairs = (dump_dict(arg) if isinstance(arg, Mapping) else dump_key_values(arg) if isinstance(arg, Iterable) else None for arg in args + (kwargs,)) return _format_pairs(chain.from_iterable((p for p in pairs if p)))
def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = { 'prefix': arg } v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print("Prefix %s not found in %s." % (arg, vrf_format(v)), file=sys.stderr) return p = res[0] for avp in opts.get('extra-attribute', []): try: key, value = avp.split('=', 1) except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) if key in p.avps: print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr) sys.exit(1) p.avps[key] = value try: p.save() except NipapError as exc: print("Could not save prefix changes: %s" % str(exc), file=sys.stderr) sys.exit(1) print("Prefix %s in %s saved." % (p.display_prefix, vrf_format(p.vrf)))
def function[prefix_attr_add, parameter[arg, opts, shell_opts]]: constant[ Add attributes to a prefix ] variable[spec] assign[=] dictionary[[<ast.Constant object at 0x7da20c7cba60>], [<ast.Name object at 0x7da20c7cbf10>]] variable[v] assign[=] call[name[get_vrf], parameter[call[name[opts].get, parameter[constant[vrf_rt]]]]] call[name[spec]][constant[vrf_rt]] assign[=] name[v].rt variable[res] assign[=] call[name[Prefix].list, parameter[name[spec]]] if compare[call[name[len], parameter[name[res]]] equal[==] constant[0]] begin[:] call[name[print], parameter[binary_operation[constant[Prefix %s not found in %s.] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da20c7c9db0>, <ast.Call object at 0x7da20c7ca890>]]]]] return[None] variable[p] assign[=] call[name[res]][constant[0]] for taget[name[avp]] in starred[call[name[opts].get, parameter[constant[extra-attribute], list[[]]]]] begin[:] <ast.Try object at 0x7da20c7cb8b0> if compare[name[key] in name[p].avps] begin[:] call[name[print], parameter[binary_operation[constant[Unable to add extra-attribute: '%s' already exists.] <ast.Mod object at 0x7da2590d6920> name[key]]]] call[name[sys].exit, parameter[constant[1]]] call[name[p].avps][name[key]] assign[=] name[value] <ast.Try object at 0x7da20c7ca2f0> call[name[print], parameter[binary_operation[constant[Prefix %s in %s saved.] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da20c7ca1a0>, <ast.Call object at 0x7da20c7c86d0>]]]]]
keyword[def] identifier[prefix_attr_add] ( identifier[arg] , identifier[opts] , identifier[shell_opts] ): literal[string] identifier[spec] ={ literal[string] : identifier[arg] } identifier[v] = identifier[get_vrf] ( identifier[opts] . identifier[get] ( literal[string] ), identifier[abort] = keyword[True] ) identifier[spec] [ literal[string] ]= identifier[v] . identifier[rt] identifier[res] = identifier[Prefix] . identifier[list] ( identifier[spec] ) keyword[if] identifier[len] ( identifier[res] )== literal[int] : identifier[print] ( literal[string] %( identifier[arg] , identifier[vrf_format] ( identifier[v] )), identifier[file] = identifier[sys] . identifier[stderr] ) keyword[return] identifier[p] = identifier[res] [ literal[int] ] keyword[for] identifier[avp] keyword[in] identifier[opts] . identifier[get] ( literal[string] ,[]): keyword[try] : identifier[key] , identifier[value] = identifier[avp] . identifier[split] ( literal[string] , literal[int] ) keyword[except] identifier[ValueError] : identifier[print] ( literal[string] % identifier[avp] , identifier[file] = identifier[sys] . identifier[stderr] ) identifier[sys] . identifier[exit] ( literal[int] ) keyword[if] identifier[key] keyword[in] identifier[p] . identifier[avps] : identifier[print] ( literal[string] % identifier[key] , identifier[file] = identifier[sys] . identifier[stderr] ) identifier[sys] . identifier[exit] ( literal[int] ) identifier[p] . identifier[avps] [ identifier[key] ]= identifier[value] keyword[try] : identifier[p] . identifier[save] () keyword[except] identifier[NipapError] keyword[as] identifier[exc] : identifier[print] ( literal[string] % identifier[str] ( identifier[exc] ), identifier[file] = identifier[sys] . identifier[stderr] ) identifier[sys] . identifier[exit] ( literal[int] ) identifier[print] ( literal[string] %( identifier[p] . identifier[display_prefix] , identifier[vrf_format] ( identifier[p] . identifier[vrf] )))
def prefix_attr_add(arg, opts, shell_opts): """ Add attributes to a prefix """ spec = {'prefix': arg} v = get_vrf(opts.get('vrf_rt'), abort=True) spec['vrf_rt'] = v.rt res = Prefix.list(spec) if len(res) == 0: print('Prefix %s not found in %s.' % (arg, vrf_format(v)), file=sys.stderr) return # depends on [control=['if'], data=[]] p = res[0] for avp in opts.get('extra-attribute', []): try: (key, value) = avp.split('=', 1) # depends on [control=['try'], data=[]] except ValueError: print("ERROR: Incorrect extra-attribute: %s. Accepted form: 'key=value'\n" % avp, file=sys.stderr) sys.exit(1) # depends on [control=['except'], data=[]] if key in p.avps: print("Unable to add extra-attribute: '%s' already exists." % key, file=sys.stderr) sys.exit(1) # depends on [control=['if'], data=['key']] p.avps[key] = value # depends on [control=['for'], data=['avp']] try: p.save() # depends on [control=['try'], data=[]] except NipapError as exc: print('Could not save prefix changes: %s' % str(exc), file=sys.stderr) sys.exit(1) # depends on [control=['except'], data=['exc']] print('Prefix %s in %s saved.' % (p.display_prefix, vrf_format(p.vrf)))
def _marshal_json(self, extras=()): """ Marshal various policies into json str/bytes. """ policies = self.policies[:] policies.extend(extras) if self._content_length_range: policies.append(['content-length-range'] + list(self._content_length_range)) policy_stmt = { "expiration": self._expiration.strftime( "%Y-%m-%dT%H:%M:%S.000Z"), } if len(policies) > 0: policy_stmt["conditions"] = policies return json.dumps(policy_stmt)
def function[_marshal_json, parameter[self, extras]]: constant[ Marshal various policies into json str/bytes. ] variable[policies] assign[=] call[name[self].policies][<ast.Slice object at 0x7da1b1ece740>] call[name[policies].extend, parameter[name[extras]]] if name[self]._content_length_range begin[:] call[name[policies].append, parameter[binary_operation[list[[<ast.Constant object at 0x7da1b1ecee60>]] + call[name[list], parameter[name[self]._content_length_range]]]]] variable[policy_stmt] assign[=] dictionary[[<ast.Constant object at 0x7da1b1eccd60>], [<ast.Call object at 0x7da1b1ece6b0>]] if compare[call[name[len], parameter[name[policies]]] greater[>] constant[0]] begin[:] call[name[policy_stmt]][constant[conditions]] assign[=] name[policies] return[call[name[json].dumps, parameter[name[policy_stmt]]]]
keyword[def] identifier[_marshal_json] ( identifier[self] , identifier[extras] =()): literal[string] identifier[policies] = identifier[self] . identifier[policies] [:] identifier[policies] . identifier[extend] ( identifier[extras] ) keyword[if] identifier[self] . identifier[_content_length_range] : identifier[policies] . identifier[append] ([ literal[string] ]+ identifier[list] ( identifier[self] . identifier[_content_length_range] )) identifier[policy_stmt] ={ literal[string] : identifier[self] . identifier[_expiration] . identifier[strftime] ( literal[string] ), } keyword[if] identifier[len] ( identifier[policies] )> literal[int] : identifier[policy_stmt] [ literal[string] ]= identifier[policies] keyword[return] identifier[json] . identifier[dumps] ( identifier[policy_stmt] )
def _marshal_json(self, extras=()): """ Marshal various policies into json str/bytes. """ policies = self.policies[:] policies.extend(extras) if self._content_length_range: policies.append(['content-length-range'] + list(self._content_length_range)) # depends on [control=['if'], data=[]] policy_stmt = {'expiration': self._expiration.strftime('%Y-%m-%dT%H:%M:%S.000Z')} if len(policies) > 0: policy_stmt['conditions'] = policies # depends on [control=['if'], data=[]] return json.dumps(policy_stmt)
def description(self) -> str: '''Test name in nose output (intended to be overridden).''' return '{0.uuid.hex}—{1}'.format(self, self.context.module)
def function[description, parameter[self]]: constant[Test name in nose output (intended to be overridden).] return[call[constant[{0.uuid.hex}—{1}].format, parameter[name[self], name[self].context.module]]]
keyword[def] identifier[description] ( identifier[self] )-> identifier[str] : literal[string] keyword[return] literal[string] . identifier[format] ( identifier[self] , identifier[self] . identifier[context] . identifier[module] )
def description(self) -> str: """Test name in nose output (intended to be overridden).""" return '{0.uuid.hex}—{1}'.format(self, self.context.module)
def staged_predict(self, X): """Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples. """ check_is_fitted(self, 'estimators_') # if dropout wasn't used during training, proceed as usual, # otherwise consider scaling factor of individual trees if not hasattr(self, "scale_"): for y in self._staged_decision_function(X): yield self._scale_prediction(y.ravel()) else: for y in self._dropout_staged_decision_function(X): yield self._scale_prediction(y.ravel())
def function[staged_predict, parameter[self, X]]: constant[Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples. ] call[name[check_is_fitted], parameter[name[self], constant[estimators_]]] if <ast.UnaryOp object at 0x7da1b1726500> begin[:] for taget[name[y]] in starred[call[name[self]._staged_decision_function, parameter[name[X]]]] begin[:] <ast.Yield object at 0x7da1b1727700>
keyword[def] identifier[staged_predict] ( identifier[self] , identifier[X] ): literal[string] identifier[check_is_fitted] ( identifier[self] , literal[string] ) keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ): keyword[for] identifier[y] keyword[in] identifier[self] . identifier[_staged_decision_function] ( identifier[X] ): keyword[yield] identifier[self] . identifier[_scale_prediction] ( identifier[y] . identifier[ravel] ()) keyword[else] : keyword[for] identifier[y] keyword[in] identifier[self] . identifier[_dropout_staged_decision_function] ( identifier[X] ): keyword[yield] identifier[self] . identifier[_scale_prediction] ( identifier[y] . identifier[ravel] ())
def staged_predict(self, X): """Predict hazard at each stage for X. This method allows monitoring (i.e. determine error on testing set) after each stage. Parameters ---------- X : array-like, shape = (n_samples, n_features) The input samples. Returns ------- y : generator of array of shape = (n_samples,) The predicted value of the input samples. """ check_is_fitted(self, 'estimators_') # if dropout wasn't used during training, proceed as usual, # otherwise consider scaling factor of individual trees if not hasattr(self, 'scale_'): for y in self._staged_decision_function(X): yield self._scale_prediction(y.ravel()) # depends on [control=['for'], data=['y']] # depends on [control=['if'], data=[]] else: for y in self._dropout_staged_decision_function(X): yield self._scale_prediction(y.ravel()) # depends on [control=['for'], data=['y']]
def get_qc(name: str, *, as_qvm: bool = None, noisy: bool = None, connection: ForestConnection = None) -> QuantumComputer: """ Get a quantum computer. A quantum computer is an object of type :py:class:`QuantumComputer` and can be backed either by a QVM simulator ("Quantum/Quil Virtual Machine") or a physical Rigetti QPU ("Quantum Processing Unit") made of superconducting qubits. You can choose the quantum computer to target through a combination of its name and optional flags. There are multiple ways to get the same quantum computer. The following are equivalent:: >>> qc = get_qc("Aspen-1-16Q-A-noisy-qvm") >>> qc = get_qc("Aspen-1-16Q-A", as_qvm=True, noisy=True) and will construct a simulator of an Aspen-1 lattice with a noise model based on device characteristics. We also provide a means for constructing generic quantum simulators that are not related to a given piece of Rigetti hardware:: >>> qc = get_qc("9q-square-qvm") >>> qc = get_qc("9q-square", as_qvm=True) Finally, you can get request a QVM with "no" topology of a given number of qubits (technically, it's a fully connected graph among the given number of qubits) with:: >>> qc = get_qc("5q-qvm") # or "6q-qvm", or "34q-qvm", ... These less-realistic, fully-connected QVMs will also be more lenient on what types of programs they will ``run``. Specifically, you do not need to do any compilation. For the other, realistic QVMs you must use :py:func:`qc.compile` or :py:func:`qc.compiler.native_quil_to_executable` prior to :py:func:`qc.run`. The Rigetti QVM must be downloaded from https://www.rigetti.com/forest and run as a server alongside your python program. To use pyQuil's built-in QVM, replace all ``"-qvm"`` suffixes with ``"-pyqvm"``:: >>> qc = get_qc("5q-pyqvm") Redundant flags are acceptable, but conflicting flags will raise an exception:: >>> qc = get_qc("9q-square-qvm") # qc is fully specified by its name >>> qc = get_qc("9q-square-qvm", as_qvm=True) # redundant, but ok >>> qc = get_qc("9q-square-qvm", as_qvm=False) # Error! Use :py:func:`list_quantum_computers` to retrieve a list of known qc names. This method is provided as a convenience to quickly construct and use QVM's and QPU's. Power users may wish to have more control over the specification of a quantum computer (e.g. custom noise models, bespoke topologies, etc.). This is possible by constructing a :py:class:`QuantumComputer` object by hand. Please refer to the documentation on :py:class:`QuantumComputer` for more information. :param name: The name of the desired quantum computer. This should correspond to a name returned by :py:func:`list_quantum_computers`. Names ending in "-qvm" will return a QVM. Names ending in "-pyqvm" will return a :py:class:`PyQVM`. Names ending in "-noisy-qvm" will return a QVM with a noise model. Otherwise, we will return a QPU with the given name. :param as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If specified and set to ``True``, a QVM-backed quantum computer will be returned regardless of the name's suffix :param noisy: An optional flag to force inclusion of a noise model. If specified and set to ``True``, a quantum computer with a noise model will be returned regardless of the name's suffix. The noise model for QVMs based on a real QPU is an empirically parameterized model based on real device noise characteristics. The generic QVM noise model is simple T1 and T2 noise plus readout error. See :py:func:`~pyquil.noise.decoherence_noise_with_asymmetric_ro`. :param connection: An optional :py:class:`ForestConnection` object. If not specified, the default values for URL endpoints will be used. If you deign to change any of these parameters, pass your own :py:class:`ForestConnection` object. :return: A pre-configured QuantumComputer """ # 1. Parse name, check for redundant options, canonicalize names. prefix, qvm_type, noisy = _parse_name(name, as_qvm, noisy) del as_qvm # do not use after _parse_name name = _canonicalize_name(prefix, qvm_type, noisy) # 2. Check for unrestricted {n}q-qvm ma = re.fullmatch(r'(\d+)q', prefix) if ma is not None: n_qubits = int(ma.group(1)) if qvm_type is None: raise ValueError("Please name a valid device or run as a QVM") return _get_unrestricted_qvm(name=name, connection=connection, noisy=noisy, n_qubits=n_qubits, qvm_type=qvm_type) # 3. Check for "9q-square" qvm if prefix == '9q-generic' or prefix == '9q-square': if prefix == '9q-generic': warnings.warn("Please prefer '9q-square' instead of '9q-generic'", DeprecationWarning) if qvm_type is None: raise ValueError("The device '9q-square' is only available as a QVM") return _get_9q_square_qvm(name=name, connection=connection, noisy=noisy, qvm_type=qvm_type) # 4. Not a special case, query the web for information about this device. device = get_lattice(prefix) if qvm_type is not None: # 4.1 QVM based on a real device. return _get_qvm_based_on_real_device(name=name, device=device, noisy=noisy, connection=connection, qvm_type=qvm_type) else: # 4.2 A real device if noisy is not None and noisy: warnings.warn("You have specified `noisy=True`, but you're getting a QPU. This flag " "is meant for controlling noise models on QVMs.") return QuantumComputer(name=name, qam=QPU( endpoint=pyquil_config.qpu_url, user=pyquil_config.user_id), device=device, compiler=QPUCompiler( quilc_endpoint=pyquil_config.quilc_url, qpu_compiler_endpoint=pyquil_config.qpu_compiler_url, device=device, name=prefix))
def function[get_qc, parameter[name]]: constant[ Get a quantum computer. A quantum computer is an object of type :py:class:`QuantumComputer` and can be backed either by a QVM simulator ("Quantum/Quil Virtual Machine") or a physical Rigetti QPU ("Quantum Processing Unit") made of superconducting qubits. You can choose the quantum computer to target through a combination of its name and optional flags. There are multiple ways to get the same quantum computer. The following are equivalent:: >>> qc = get_qc("Aspen-1-16Q-A-noisy-qvm") >>> qc = get_qc("Aspen-1-16Q-A", as_qvm=True, noisy=True) and will construct a simulator of an Aspen-1 lattice with a noise model based on device characteristics. We also provide a means for constructing generic quantum simulators that are not related to a given piece of Rigetti hardware:: >>> qc = get_qc("9q-square-qvm") >>> qc = get_qc("9q-square", as_qvm=True) Finally, you can get request a QVM with "no" topology of a given number of qubits (technically, it's a fully connected graph among the given number of qubits) with:: >>> qc = get_qc("5q-qvm") # or "6q-qvm", or "34q-qvm", ... These less-realistic, fully-connected QVMs will also be more lenient on what types of programs they will ``run``. Specifically, you do not need to do any compilation. For the other, realistic QVMs you must use :py:func:`qc.compile` or :py:func:`qc.compiler.native_quil_to_executable` prior to :py:func:`qc.run`. The Rigetti QVM must be downloaded from https://www.rigetti.com/forest and run as a server alongside your python program. To use pyQuil's built-in QVM, replace all ``"-qvm"`` suffixes with ``"-pyqvm"``:: >>> qc = get_qc("5q-pyqvm") Redundant flags are acceptable, but conflicting flags will raise an exception:: >>> qc = get_qc("9q-square-qvm") # qc is fully specified by its name >>> qc = get_qc("9q-square-qvm", as_qvm=True) # redundant, but ok >>> qc = get_qc("9q-square-qvm", as_qvm=False) # Error! Use :py:func:`list_quantum_computers` to retrieve a list of known qc names. This method is provided as a convenience to quickly construct and use QVM's and QPU's. Power users may wish to have more control over the specification of a quantum computer (e.g. custom noise models, bespoke topologies, etc.). This is possible by constructing a :py:class:`QuantumComputer` object by hand. Please refer to the documentation on :py:class:`QuantumComputer` for more information. :param name: The name of the desired quantum computer. This should correspond to a name returned by :py:func:`list_quantum_computers`. Names ending in "-qvm" will return a QVM. Names ending in "-pyqvm" will return a :py:class:`PyQVM`. Names ending in "-noisy-qvm" will return a QVM with a noise model. Otherwise, we will return a QPU with the given name. :param as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If specified and set to ``True``, a QVM-backed quantum computer will be returned regardless of the name's suffix :param noisy: An optional flag to force inclusion of a noise model. If specified and set to ``True``, a quantum computer with a noise model will be returned regardless of the name's suffix. The noise model for QVMs based on a real QPU is an empirically parameterized model based on real device noise characteristics. The generic QVM noise model is simple T1 and T2 noise plus readout error. See :py:func:`~pyquil.noise.decoherence_noise_with_asymmetric_ro`. :param connection: An optional :py:class:`ForestConnection` object. If not specified, the default values for URL endpoints will be used. If you deign to change any of these parameters, pass your own :py:class:`ForestConnection` object. :return: A pre-configured QuantumComputer ] <ast.Tuple object at 0x7da1b1bc1750> assign[=] call[name[_parse_name], parameter[name[name], name[as_qvm], name[noisy]]] <ast.Delete object at 0x7da1b1bc0a30> variable[name] assign[=] call[name[_canonicalize_name], parameter[name[prefix], name[qvm_type], name[noisy]]] variable[ma] assign[=] call[name[re].fullmatch, parameter[constant[(\d+)q], name[prefix]]] if compare[name[ma] is_not constant[None]] begin[:] variable[n_qubits] assign[=] call[name[int], parameter[call[name[ma].group, parameter[constant[1]]]]] if compare[name[qvm_type] is constant[None]] begin[:] <ast.Raise object at 0x7da1b1bd3370> return[call[name[_get_unrestricted_qvm], parameter[]]] if <ast.BoolOp object at 0x7da1b1bd2f50> begin[:] if compare[name[prefix] equal[==] constant[9q-generic]] begin[:] call[name[warnings].warn, parameter[constant[Please prefer '9q-square' instead of '9q-generic'], name[DeprecationWarning]]] if compare[name[qvm_type] is constant[None]] begin[:] <ast.Raise object at 0x7da1b1bd31f0> return[call[name[_get_9q_square_qvm], parameter[]]] variable[device] assign[=] call[name[get_lattice], parameter[name[prefix]]] if compare[name[qvm_type] is_not constant[None]] begin[:] return[call[name[_get_qvm_based_on_real_device], parameter[]]]
keyword[def] identifier[get_qc] ( identifier[name] : identifier[str] ,*, identifier[as_qvm] : identifier[bool] = keyword[None] , identifier[noisy] : identifier[bool] = keyword[None] , identifier[connection] : identifier[ForestConnection] = keyword[None] )-> identifier[QuantumComputer] : literal[string] identifier[prefix] , identifier[qvm_type] , identifier[noisy] = identifier[_parse_name] ( identifier[name] , identifier[as_qvm] , identifier[noisy] ) keyword[del] identifier[as_qvm] identifier[name] = identifier[_canonicalize_name] ( identifier[prefix] , identifier[qvm_type] , identifier[noisy] ) identifier[ma] = identifier[re] . identifier[fullmatch] ( literal[string] , identifier[prefix] ) keyword[if] identifier[ma] keyword[is] keyword[not] keyword[None] : identifier[n_qubits] = identifier[int] ( identifier[ma] . identifier[group] ( literal[int] )) keyword[if] identifier[qvm_type] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[return] identifier[_get_unrestricted_qvm] ( identifier[name] = identifier[name] , identifier[connection] = identifier[connection] , identifier[noisy] = identifier[noisy] , identifier[n_qubits] = identifier[n_qubits] , identifier[qvm_type] = identifier[qvm_type] ) keyword[if] identifier[prefix] == literal[string] keyword[or] identifier[prefix] == literal[string] : keyword[if] identifier[prefix] == literal[string] : identifier[warnings] . identifier[warn] ( literal[string] , identifier[DeprecationWarning] ) keyword[if] identifier[qvm_type] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[return] identifier[_get_9q_square_qvm] ( identifier[name] = identifier[name] , identifier[connection] = identifier[connection] , identifier[noisy] = identifier[noisy] , identifier[qvm_type] = identifier[qvm_type] ) identifier[device] = identifier[get_lattice] ( identifier[prefix] ) keyword[if] identifier[qvm_type] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[_get_qvm_based_on_real_device] ( identifier[name] = identifier[name] , identifier[device] = identifier[device] , identifier[noisy] = identifier[noisy] , identifier[connection] = identifier[connection] , identifier[qvm_type] = identifier[qvm_type] ) keyword[else] : keyword[if] identifier[noisy] keyword[is] keyword[not] keyword[None] keyword[and] identifier[noisy] : identifier[warnings] . identifier[warn] ( literal[string] literal[string] ) keyword[return] identifier[QuantumComputer] ( identifier[name] = identifier[name] , identifier[qam] = identifier[QPU] ( identifier[endpoint] = identifier[pyquil_config] . identifier[qpu_url] , identifier[user] = identifier[pyquil_config] . identifier[user_id] ), identifier[device] = identifier[device] , identifier[compiler] = identifier[QPUCompiler] ( identifier[quilc_endpoint] = identifier[pyquil_config] . identifier[quilc_url] , identifier[qpu_compiler_endpoint] = identifier[pyquil_config] . identifier[qpu_compiler_url] , identifier[device] = identifier[device] , identifier[name] = identifier[prefix] ))
def get_qc(name: str, *, as_qvm: bool=None, noisy: bool=None, connection: ForestConnection=None) -> QuantumComputer: """ Get a quantum computer. A quantum computer is an object of type :py:class:`QuantumComputer` and can be backed either by a QVM simulator ("Quantum/Quil Virtual Machine") or a physical Rigetti QPU ("Quantum Processing Unit") made of superconducting qubits. You can choose the quantum computer to target through a combination of its name and optional flags. There are multiple ways to get the same quantum computer. The following are equivalent:: >>> qc = get_qc("Aspen-1-16Q-A-noisy-qvm") >>> qc = get_qc("Aspen-1-16Q-A", as_qvm=True, noisy=True) and will construct a simulator of an Aspen-1 lattice with a noise model based on device characteristics. We also provide a means for constructing generic quantum simulators that are not related to a given piece of Rigetti hardware:: >>> qc = get_qc("9q-square-qvm") >>> qc = get_qc("9q-square", as_qvm=True) Finally, you can get request a QVM with "no" topology of a given number of qubits (technically, it's a fully connected graph among the given number of qubits) with:: >>> qc = get_qc("5q-qvm") # or "6q-qvm", or "34q-qvm", ... These less-realistic, fully-connected QVMs will also be more lenient on what types of programs they will ``run``. Specifically, you do not need to do any compilation. For the other, realistic QVMs you must use :py:func:`qc.compile` or :py:func:`qc.compiler.native_quil_to_executable` prior to :py:func:`qc.run`. The Rigetti QVM must be downloaded from https://www.rigetti.com/forest and run as a server alongside your python program. To use pyQuil's built-in QVM, replace all ``"-qvm"`` suffixes with ``"-pyqvm"``:: >>> qc = get_qc("5q-pyqvm") Redundant flags are acceptable, but conflicting flags will raise an exception:: >>> qc = get_qc("9q-square-qvm") # qc is fully specified by its name >>> qc = get_qc("9q-square-qvm", as_qvm=True) # redundant, but ok >>> qc = get_qc("9q-square-qvm", as_qvm=False) # Error! Use :py:func:`list_quantum_computers` to retrieve a list of known qc names. This method is provided as a convenience to quickly construct and use QVM's and QPU's. Power users may wish to have more control over the specification of a quantum computer (e.g. custom noise models, bespoke topologies, etc.). This is possible by constructing a :py:class:`QuantumComputer` object by hand. Please refer to the documentation on :py:class:`QuantumComputer` for more information. :param name: The name of the desired quantum computer. This should correspond to a name returned by :py:func:`list_quantum_computers`. Names ending in "-qvm" will return a QVM. Names ending in "-pyqvm" will return a :py:class:`PyQVM`. Names ending in "-noisy-qvm" will return a QVM with a noise model. Otherwise, we will return a QPU with the given name. :param as_qvm: An optional flag to force construction of a QVM (instead of a QPU). If specified and set to ``True``, a QVM-backed quantum computer will be returned regardless of the name's suffix :param noisy: An optional flag to force inclusion of a noise model. If specified and set to ``True``, a quantum computer with a noise model will be returned regardless of the name's suffix. The noise model for QVMs based on a real QPU is an empirically parameterized model based on real device noise characteristics. The generic QVM noise model is simple T1 and T2 noise plus readout error. See :py:func:`~pyquil.noise.decoherence_noise_with_asymmetric_ro`. :param connection: An optional :py:class:`ForestConnection` object. If not specified, the default values for URL endpoints will be used. If you deign to change any of these parameters, pass your own :py:class:`ForestConnection` object. :return: A pre-configured QuantumComputer """ # 1. Parse name, check for redundant options, canonicalize names. (prefix, qvm_type, noisy) = _parse_name(name, as_qvm, noisy) del as_qvm # do not use after _parse_name name = _canonicalize_name(prefix, qvm_type, noisy) # 2. Check for unrestricted {n}q-qvm ma = re.fullmatch('(\\d+)q', prefix) if ma is not None: n_qubits = int(ma.group(1)) if qvm_type is None: raise ValueError('Please name a valid device or run as a QVM') # depends on [control=['if'], data=[]] return _get_unrestricted_qvm(name=name, connection=connection, noisy=noisy, n_qubits=n_qubits, qvm_type=qvm_type) # depends on [control=['if'], data=['ma']] # 3. Check for "9q-square" qvm if prefix == '9q-generic' or prefix == '9q-square': if prefix == '9q-generic': warnings.warn("Please prefer '9q-square' instead of '9q-generic'", DeprecationWarning) # depends on [control=['if'], data=[]] if qvm_type is None: raise ValueError("The device '9q-square' is only available as a QVM") # depends on [control=['if'], data=[]] return _get_9q_square_qvm(name=name, connection=connection, noisy=noisy, qvm_type=qvm_type) # depends on [control=['if'], data=[]] # 4. Not a special case, query the web for information about this device. device = get_lattice(prefix) if qvm_type is not None: # 4.1 QVM based on a real device. return _get_qvm_based_on_real_device(name=name, device=device, noisy=noisy, connection=connection, qvm_type=qvm_type) # depends on [control=['if'], data=['qvm_type']] else: # 4.2 A real device if noisy is not None and noisy: warnings.warn("You have specified `noisy=True`, but you're getting a QPU. This flag is meant for controlling noise models on QVMs.") # depends on [control=['if'], data=[]] return QuantumComputer(name=name, qam=QPU(endpoint=pyquil_config.qpu_url, user=pyquil_config.user_id), device=device, compiler=QPUCompiler(quilc_endpoint=pyquil_config.quilc_url, qpu_compiler_endpoint=pyquil_config.qpu_compiler_url, device=device, name=prefix))
def reporter(self): """ Parse the results into a report """ # Initialise variables header = '' row = '' databasedict = dict() # Load the database sequence type into a dictionary strainprofile = os.path.join(self.profilelocation, 'strainprofiles.txt') databaseprofile = DictReader(open(strainprofile)) # Put the strain profile dictionary into a more easily searchable format for data in databaseprofile: databasedict[data['Strain']] = data['SequenceType'] for sample in self.metadata.samples: closestmatches = list() if sample[self.analysistype].reportdir != 'NA': if type(sample[self.analysistype].allelenames) == list: # Populate the header with the appropriate data, including all the genes in the list of targets header = 'Strain,SequenceType,Matches,Mismatches,NA,TotalGenes,ClosestDatabaseMatch,{},\n' \ .format(','.join(sorted(sample[self.analysistype].allelenames))) sortedmatches = sorted(sample[self.analysistype].profilematches.items(), key=operator.itemgetter(1), reverse=True)[0] closestseqtype = sortedmatches[0] # Pull out the closest database match for strain, seqtype in databasedict.items(): if seqtype == closestseqtype: closestmatches.append(strain) sample[self.analysistype].closestseqtype = closestseqtype nummatches = int(sortedmatches[1]) numna = 0 queryallele = list() # Get all the alleles into a list for gene, allele in sorted(sample[self.analysistype].profiledata[closestseqtype].items()): try: # Extract the allele (anything after the -) from the allele matches query = sample[self.analysistype].allelematches[gene].split('-')[1] if allele == query: queryallele.append(query) else: queryallele.append('{} ({})'.format(query, allele)) except KeyError: queryallele.append('NA') numna += 1 mismatches = len(sample[self.analysistype].alleles) - nummatches - numna row += '{},{},{},{},{},{},{},{}'\ .format(sample.name, closestseqtype, nummatches, mismatches, numna, len(sample[self.analysistype].alleles), ','.join(closestmatches), ','.join(queryallele)) row += '\n' # Create the report folder make_path(self.reportpath) # Create the report containing all the data from all samples with open(os.path.join(self.reportpath, '{}.csv'.format(self.analysistype)), 'w') as combinedreport: # Write the results to this report combinedreport.write(header) combinedreport.write(row)
def function[reporter, parameter[self]]: constant[ Parse the results into a report ] variable[header] assign[=] constant[] variable[row] assign[=] constant[] variable[databasedict] assign[=] call[name[dict], parameter[]] variable[strainprofile] assign[=] call[name[os].path.join, parameter[name[self].profilelocation, constant[strainprofiles.txt]]] variable[databaseprofile] assign[=] call[name[DictReader], parameter[call[name[open], parameter[name[strainprofile]]]]] for taget[name[data]] in starred[name[databaseprofile]] begin[:] call[name[databasedict]][call[name[data]][constant[Strain]]] assign[=] call[name[data]][constant[SequenceType]] for taget[name[sample]] in starred[name[self].metadata.samples] begin[:] variable[closestmatches] assign[=] call[name[list], parameter[]] if compare[call[name[sample]][name[self].analysistype].reportdir not_equal[!=] constant[NA]] begin[:] if compare[call[name[type], parameter[call[name[sample]][name[self].analysistype].allelenames]] equal[==] name[list]] begin[:] variable[header] assign[=] call[constant[Strain,SequenceType,Matches,Mismatches,NA,TotalGenes,ClosestDatabaseMatch,{}, ].format, parameter[call[constant[,].join, parameter[call[name[sorted], parameter[call[name[sample]][name[self].analysistype].allelenames]]]]]] variable[sortedmatches] assign[=] call[call[name[sorted], parameter[call[call[name[sample]][name[self].analysistype].profilematches.items, parameter[]]]]][constant[0]] variable[closestseqtype] assign[=] call[name[sortedmatches]][constant[0]] for taget[tuple[[<ast.Name object at 0x7da18f09d3c0>, <ast.Name object at 0x7da18f09f310>]]] in starred[call[name[databasedict].items, parameter[]]] begin[:] if compare[name[seqtype] equal[==] name[closestseqtype]] begin[:] call[name[closestmatches].append, parameter[name[strain]]] call[name[sample]][name[self].analysistype].closestseqtype assign[=] name[closestseqtype] variable[nummatches] assign[=] call[name[int], parameter[call[name[sortedmatches]][constant[1]]]] variable[numna] assign[=] constant[0] variable[queryallele] assign[=] call[name[list], parameter[]] for taget[tuple[[<ast.Name object at 0x7da18f09ea40>, <ast.Name object at 0x7da18f09d330>]]] in starred[call[name[sorted], parameter[call[call[call[name[sample]][name[self].analysistype].profiledata][name[closestseqtype]].items, parameter[]]]]] begin[:] <ast.Try object at 0x7da18f09de10> variable[mismatches] assign[=] binary_operation[binary_operation[call[name[len], parameter[call[name[sample]][name[self].analysistype].alleles]] - name[nummatches]] - name[numna]] <ast.AugAssign object at 0x7da18f09c250> <ast.AugAssign object at 0x7da18f09e5c0> call[name[make_path], parameter[name[self].reportpath]] with call[name[open], parameter[call[name[os].path.join, parameter[name[self].reportpath, call[constant[{}.csv].format, parameter[name[self].analysistype]]]], constant[w]]] begin[:] call[name[combinedreport].write, parameter[name[header]]] call[name[combinedreport].write, parameter[name[row]]]
keyword[def] identifier[reporter] ( identifier[self] ): literal[string] identifier[header] = literal[string] identifier[row] = literal[string] identifier[databasedict] = identifier[dict] () identifier[strainprofile] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[profilelocation] , literal[string] ) identifier[databaseprofile] = identifier[DictReader] ( identifier[open] ( identifier[strainprofile] )) keyword[for] identifier[data] keyword[in] identifier[databaseprofile] : identifier[databasedict] [ identifier[data] [ literal[string] ]]= identifier[data] [ literal[string] ] keyword[for] identifier[sample] keyword[in] identifier[self] . identifier[metadata] . identifier[samples] : identifier[closestmatches] = identifier[list] () keyword[if] identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[reportdir] != literal[string] : keyword[if] identifier[type] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[allelenames] )== identifier[list] : identifier[header] = literal[string] . identifier[format] ( literal[string] . identifier[join] ( identifier[sorted] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[allelenames] ))) identifier[sortedmatches] = identifier[sorted] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[profilematches] . identifier[items] (), identifier[key] = identifier[operator] . identifier[itemgetter] ( literal[int] ), identifier[reverse] = keyword[True] )[ literal[int] ] identifier[closestseqtype] = identifier[sortedmatches] [ literal[int] ] keyword[for] identifier[strain] , identifier[seqtype] keyword[in] identifier[databasedict] . identifier[items] (): keyword[if] identifier[seqtype] == identifier[closestseqtype] : identifier[closestmatches] . identifier[append] ( identifier[strain] ) identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[closestseqtype] = identifier[closestseqtype] identifier[nummatches] = identifier[int] ( identifier[sortedmatches] [ literal[int] ]) identifier[numna] = literal[int] identifier[queryallele] = identifier[list] () keyword[for] identifier[gene] , identifier[allele] keyword[in] identifier[sorted] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[profiledata] [ identifier[closestseqtype] ]. identifier[items] ()): keyword[try] : identifier[query] = identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[allelematches] [ identifier[gene] ]. identifier[split] ( literal[string] )[ literal[int] ] keyword[if] identifier[allele] == identifier[query] : identifier[queryallele] . identifier[append] ( identifier[query] ) keyword[else] : identifier[queryallele] . identifier[append] ( literal[string] . identifier[format] ( identifier[query] , identifier[allele] )) keyword[except] identifier[KeyError] : identifier[queryallele] . identifier[append] ( literal[string] ) identifier[numna] += literal[int] identifier[mismatches] = identifier[len] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[alleles] )- identifier[nummatches] - identifier[numna] identifier[row] += literal[string] . identifier[format] ( identifier[sample] . identifier[name] , identifier[closestseqtype] , identifier[nummatches] , identifier[mismatches] , identifier[numna] , identifier[len] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[alleles] ), literal[string] . identifier[join] ( identifier[closestmatches] ), literal[string] . identifier[join] ( identifier[queryallele] )) identifier[row] += literal[string] identifier[make_path] ( identifier[self] . identifier[reportpath] ) keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[reportpath] , literal[string] . identifier[format] ( identifier[self] . identifier[analysistype] )), literal[string] ) keyword[as] identifier[combinedreport] : identifier[combinedreport] . identifier[write] ( identifier[header] ) identifier[combinedreport] . identifier[write] ( identifier[row] )
def reporter(self): """ Parse the results into a report """ # Initialise variables header = '' row = '' databasedict = dict() # Load the database sequence type into a dictionary strainprofile = os.path.join(self.profilelocation, 'strainprofiles.txt') databaseprofile = DictReader(open(strainprofile)) # Put the strain profile dictionary into a more easily searchable format for data in databaseprofile: databasedict[data['Strain']] = data['SequenceType'] # depends on [control=['for'], data=['data']] for sample in self.metadata.samples: closestmatches = list() if sample[self.analysistype].reportdir != 'NA': if type(sample[self.analysistype].allelenames) == list: # Populate the header with the appropriate data, including all the genes in the list of targets header = 'Strain,SequenceType,Matches,Mismatches,NA,TotalGenes,ClosestDatabaseMatch,{},\n'.format(','.join(sorted(sample[self.analysistype].allelenames))) # depends on [control=['if'], data=[]] sortedmatches = sorted(sample[self.analysistype].profilematches.items(), key=operator.itemgetter(1), reverse=True)[0] closestseqtype = sortedmatches[0] # Pull out the closest database match for (strain, seqtype) in databasedict.items(): if seqtype == closestseqtype: closestmatches.append(strain) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] sample[self.analysistype].closestseqtype = closestseqtype nummatches = int(sortedmatches[1]) numna = 0 queryallele = list() # Get all the alleles into a list for (gene, allele) in sorted(sample[self.analysistype].profiledata[closestseqtype].items()): try: # Extract the allele (anything after the -) from the allele matches query = sample[self.analysistype].allelematches[gene].split('-')[1] if allele == query: queryallele.append(query) # depends on [control=['if'], data=['query']] else: queryallele.append('{} ({})'.format(query, allele)) # depends on [control=['try'], data=[]] except KeyError: queryallele.append('NA') numna += 1 # depends on [control=['except'], data=[]] # depends on [control=['for'], data=[]] mismatches = len(sample[self.analysistype].alleles) - nummatches - numna row += '{},{},{},{},{},{},{},{}'.format(sample.name, closestseqtype, nummatches, mismatches, numna, len(sample[self.analysistype].alleles), ','.join(closestmatches), ','.join(queryallele)) row += '\n' # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['sample']] # Create the report folder make_path(self.reportpath) # Create the report containing all the data from all samples with open(os.path.join(self.reportpath, '{}.csv'.format(self.analysistype)), 'w') as combinedreport: # Write the results to this report combinedreport.write(header) combinedreport.write(row) # depends on [control=['with'], data=['combinedreport']]
def _brace_key(self, key): """ key: 'x' -> '{x}' """ if isinstance(key, six.integer_types): t = str key = t(key) else: t = type(key) return t(u'{') + key + t(u'}')
def function[_brace_key, parameter[self, key]]: constant[ key: 'x' -> '{x}' ] if call[name[isinstance], parameter[name[key], name[six].integer_types]] begin[:] variable[t] assign[=] name[str] variable[key] assign[=] call[name[t], parameter[name[key]]] return[binary_operation[binary_operation[call[name[t], parameter[constant[{]]] + name[key]] + call[name[t], parameter[constant[}]]]]]
keyword[def] identifier[_brace_key] ( identifier[self] , identifier[key] ): literal[string] keyword[if] identifier[isinstance] ( identifier[key] , identifier[six] . identifier[integer_types] ): identifier[t] = identifier[str] identifier[key] = identifier[t] ( identifier[key] ) keyword[else] : identifier[t] = identifier[type] ( identifier[key] ) keyword[return] identifier[t] ( literal[string] )+ identifier[key] + identifier[t] ( literal[string] )
def _brace_key(self, key): """ key: 'x' -> '{x}' """ if isinstance(key, six.integer_types): t = str key = t(key) # depends on [control=['if'], data=[]] else: t = type(key) return t(u'{') + key + t(u'}')
def blog_post_list(request, tag=None, year=None, month=None, username=None, category=None, template="blog/blog_post_list.html", extra_context=None): """ Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked for using the name ``blog/blog_post_list_XXX.html`` where ``XXX`` is either the category slug or author's username if given. """ templates = [] blog_posts = BlogPost.objects.published(for_user=request.user) if tag is not None: tag = get_object_or_404(Keyword, slug=tag) blog_posts = blog_posts.filter(keywords__keyword=tag) if year is not None: blog_posts = blog_posts.filter(publish_date__year=year) if month is not None: blog_posts = blog_posts.filter(publish_date__month=month) try: month = _(month_name[int(month)]) except IndexError: raise Http404() if category is not None: category = get_object_or_404(BlogCategory, slug=category) blog_posts = blog_posts.filter(categories=category) templates.append(u"blog/blog_post_list_%s.html" % str(category.slug)) author = None if username is not None: author = get_object_or_404(User, username=username) blog_posts = blog_posts.filter(user=author) templates.append(u"blog/blog_post_list_%s.html" % username) prefetch = ("categories", "keywords__keyword") blog_posts = blog_posts.select_related("user").prefetch_related(*prefetch) blog_posts = paginate(blog_posts, request.GET.get("page", 1), settings.BLOG_POST_PER_PAGE, settings.MAX_PAGING_LINKS) context = {"blog_posts": blog_posts, "year": year, "month": month, "tag": tag, "category": category, "author": author} context.update(extra_context or {}) templates.append(template) return TemplateResponse(request, templates, context)
def function[blog_post_list, parameter[request, tag, year, month, username, category, template, extra_context]]: constant[ Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked for using the name ``blog/blog_post_list_XXX.html`` where ``XXX`` is either the category slug or author's username if given. ] variable[templates] assign[=] list[[]] variable[blog_posts] assign[=] call[name[BlogPost].objects.published, parameter[]] if compare[name[tag] is_not constant[None]] begin[:] variable[tag] assign[=] call[name[get_object_or_404], parameter[name[Keyword]]] variable[blog_posts] assign[=] call[name[blog_posts].filter, parameter[]] if compare[name[year] is_not constant[None]] begin[:] variable[blog_posts] assign[=] call[name[blog_posts].filter, parameter[]] if compare[name[month] is_not constant[None]] begin[:] variable[blog_posts] assign[=] call[name[blog_posts].filter, parameter[]] <ast.Try object at 0x7da2041d8250> if compare[name[category] is_not constant[None]] begin[:] variable[category] assign[=] call[name[get_object_or_404], parameter[name[BlogCategory]]] variable[blog_posts] assign[=] call[name[blog_posts].filter, parameter[]] call[name[templates].append, parameter[binary_operation[constant[blog/blog_post_list_%s.html] <ast.Mod object at 0x7da2590d6920> call[name[str], parameter[name[category].slug]]]]] variable[author] assign[=] constant[None] if compare[name[username] is_not constant[None]] begin[:] variable[author] assign[=] call[name[get_object_or_404], parameter[name[User]]] variable[blog_posts] assign[=] call[name[blog_posts].filter, parameter[]] call[name[templates].append, parameter[binary_operation[constant[blog/blog_post_list_%s.html] <ast.Mod object at 0x7da2590d6920> name[username]]]] variable[prefetch] assign[=] tuple[[<ast.Constant object at 0x7da2054a5960>, <ast.Constant object at 0x7da2054a46a0>]] variable[blog_posts] assign[=] call[call[name[blog_posts].select_related, parameter[constant[user]]].prefetch_related, parameter[<ast.Starred object at 0x7da2054a4730>]] variable[blog_posts] assign[=] call[name[paginate], parameter[name[blog_posts], call[name[request].GET.get, parameter[constant[page], constant[1]]], name[settings].BLOG_POST_PER_PAGE, name[settings].MAX_PAGING_LINKS]] variable[context] assign[=] dictionary[[<ast.Constant object at 0x7da2054a7b80>, <ast.Constant object at 0x7da2054a40d0>, <ast.Constant object at 0x7da2054a67a0>, <ast.Constant object at 0x7da2054a53f0>, <ast.Constant object at 0x7da2054a73a0>, <ast.Constant object at 0x7da2054a7700>], [<ast.Name object at 0x7da2054a46d0>, <ast.Name object at 0x7da2054a7010>, <ast.Name object at 0x7da2054a6800>, <ast.Name object at 0x7da2054a79a0>, <ast.Name object at 0x7da2054a5480>, <ast.Name object at 0x7da2054a7e50>]] call[name[context].update, parameter[<ast.BoolOp object at 0x7da2054a6e30>]] call[name[templates].append, parameter[name[template]]] return[call[name[TemplateResponse], parameter[name[request], name[templates], name[context]]]]
keyword[def] identifier[blog_post_list] ( identifier[request] , identifier[tag] = keyword[None] , identifier[year] = keyword[None] , identifier[month] = keyword[None] , identifier[username] = keyword[None] , identifier[category] = keyword[None] , identifier[template] = literal[string] , identifier[extra_context] = keyword[None] ): literal[string] identifier[templates] =[] identifier[blog_posts] = identifier[BlogPost] . identifier[objects] . identifier[published] ( identifier[for_user] = identifier[request] . identifier[user] ) keyword[if] identifier[tag] keyword[is] keyword[not] keyword[None] : identifier[tag] = identifier[get_object_or_404] ( identifier[Keyword] , identifier[slug] = identifier[tag] ) identifier[blog_posts] = identifier[blog_posts] . identifier[filter] ( identifier[keywords__keyword] = identifier[tag] ) keyword[if] identifier[year] keyword[is] keyword[not] keyword[None] : identifier[blog_posts] = identifier[blog_posts] . identifier[filter] ( identifier[publish_date__year] = identifier[year] ) keyword[if] identifier[month] keyword[is] keyword[not] keyword[None] : identifier[blog_posts] = identifier[blog_posts] . identifier[filter] ( identifier[publish_date__month] = identifier[month] ) keyword[try] : identifier[month] = identifier[_] ( identifier[month_name] [ identifier[int] ( identifier[month] )]) keyword[except] identifier[IndexError] : keyword[raise] identifier[Http404] () keyword[if] identifier[category] keyword[is] keyword[not] keyword[None] : identifier[category] = identifier[get_object_or_404] ( identifier[BlogCategory] , identifier[slug] = identifier[category] ) identifier[blog_posts] = identifier[blog_posts] . identifier[filter] ( identifier[categories] = identifier[category] ) identifier[templates] . identifier[append] ( literal[string] % identifier[str] ( identifier[category] . identifier[slug] )) identifier[author] = keyword[None] keyword[if] identifier[username] keyword[is] keyword[not] keyword[None] : identifier[author] = identifier[get_object_or_404] ( identifier[User] , identifier[username] = identifier[username] ) identifier[blog_posts] = identifier[blog_posts] . identifier[filter] ( identifier[user] = identifier[author] ) identifier[templates] . identifier[append] ( literal[string] % identifier[username] ) identifier[prefetch] =( literal[string] , literal[string] ) identifier[blog_posts] = identifier[blog_posts] . identifier[select_related] ( literal[string] ). identifier[prefetch_related] (* identifier[prefetch] ) identifier[blog_posts] = identifier[paginate] ( identifier[blog_posts] , identifier[request] . identifier[GET] . identifier[get] ( literal[string] , literal[int] ), identifier[settings] . identifier[BLOG_POST_PER_PAGE] , identifier[settings] . identifier[MAX_PAGING_LINKS] ) identifier[context] ={ literal[string] : identifier[blog_posts] , literal[string] : identifier[year] , literal[string] : identifier[month] , literal[string] : identifier[tag] , literal[string] : identifier[category] , literal[string] : identifier[author] } identifier[context] . identifier[update] ( identifier[extra_context] keyword[or] {}) identifier[templates] . identifier[append] ( identifier[template] ) keyword[return] identifier[TemplateResponse] ( identifier[request] , identifier[templates] , identifier[context] )
def blog_post_list(request, tag=None, year=None, month=None, username=None, category=None, template='blog/blog_post_list.html', extra_context=None): """ Display a list of blog posts that are filtered by tag, year, month, author or category. Custom templates are checked for using the name ``blog/blog_post_list_XXX.html`` where ``XXX`` is either the category slug or author's username if given. """ templates = [] blog_posts = BlogPost.objects.published(for_user=request.user) if tag is not None: tag = get_object_or_404(Keyword, slug=tag) blog_posts = blog_posts.filter(keywords__keyword=tag) # depends on [control=['if'], data=['tag']] if year is not None: blog_posts = blog_posts.filter(publish_date__year=year) if month is not None: blog_posts = blog_posts.filter(publish_date__month=month) try: month = _(month_name[int(month)]) # depends on [control=['try'], data=[]] except IndexError: raise Http404() # depends on [control=['except'], data=[]] # depends on [control=['if'], data=['month']] # depends on [control=['if'], data=['year']] if category is not None: category = get_object_or_404(BlogCategory, slug=category) blog_posts = blog_posts.filter(categories=category) templates.append(u'blog/blog_post_list_%s.html' % str(category.slug)) # depends on [control=['if'], data=['category']] author = None if username is not None: author = get_object_or_404(User, username=username) blog_posts = blog_posts.filter(user=author) templates.append(u'blog/blog_post_list_%s.html' % username) # depends on [control=['if'], data=['username']] prefetch = ('categories', 'keywords__keyword') blog_posts = blog_posts.select_related('user').prefetch_related(*prefetch) blog_posts = paginate(blog_posts, request.GET.get('page', 1), settings.BLOG_POST_PER_PAGE, settings.MAX_PAGING_LINKS) context = {'blog_posts': blog_posts, 'year': year, 'month': month, 'tag': tag, 'category': category, 'author': author} context.update(extra_context or {}) templates.append(template) return TemplateResponse(request, templates, context)
def fit_plane_to_points(points, return_meta=False): """ Fits a plane to a set of points Parameters ---------- points : np.ndarray Size n by 3 array of points to fit a plane through return_meta : bool If true, also returns the center and normal used to generate the plane """ data = np.array(points) center = data.mean(axis=0) result = np.linalg.svd(data - center) normal = np.cross(result[2][0], result[2][1]) plane = vtki.Plane(center=center, direction=normal) if return_meta: return plane, center, normal return plane
def function[fit_plane_to_points, parameter[points, return_meta]]: constant[ Fits a plane to a set of points Parameters ---------- points : np.ndarray Size n by 3 array of points to fit a plane through return_meta : bool If true, also returns the center and normal used to generate the plane ] variable[data] assign[=] call[name[np].array, parameter[name[points]]] variable[center] assign[=] call[name[data].mean, parameter[]] variable[result] assign[=] call[name[np].linalg.svd, parameter[binary_operation[name[data] - name[center]]]] variable[normal] assign[=] call[name[np].cross, parameter[call[call[name[result]][constant[2]]][constant[0]], call[call[name[result]][constant[2]]][constant[1]]]] variable[plane] assign[=] call[name[vtki].Plane, parameter[]] if name[return_meta] begin[:] return[tuple[[<ast.Name object at 0x7da204620b20>, <ast.Name object at 0x7da204620b80>, <ast.Name object at 0x7da204623610>]]] return[name[plane]]
keyword[def] identifier[fit_plane_to_points] ( identifier[points] , identifier[return_meta] = keyword[False] ): literal[string] identifier[data] = identifier[np] . identifier[array] ( identifier[points] ) identifier[center] = identifier[data] . identifier[mean] ( identifier[axis] = literal[int] ) identifier[result] = identifier[np] . identifier[linalg] . identifier[svd] ( identifier[data] - identifier[center] ) identifier[normal] = identifier[np] . identifier[cross] ( identifier[result] [ literal[int] ][ literal[int] ], identifier[result] [ literal[int] ][ literal[int] ]) identifier[plane] = identifier[vtki] . identifier[Plane] ( identifier[center] = identifier[center] , identifier[direction] = identifier[normal] ) keyword[if] identifier[return_meta] : keyword[return] identifier[plane] , identifier[center] , identifier[normal] keyword[return] identifier[plane]
def fit_plane_to_points(points, return_meta=False): """ Fits a plane to a set of points Parameters ---------- points : np.ndarray Size n by 3 array of points to fit a plane through return_meta : bool If true, also returns the center and normal used to generate the plane """ data = np.array(points) center = data.mean(axis=0) result = np.linalg.svd(data - center) normal = np.cross(result[2][0], result[2][1]) plane = vtki.Plane(center=center, direction=normal) if return_meta: return (plane, center, normal) # depends on [control=['if'], data=[]] return plane
def put_all(self, map): """ Copies all of the mappings from the specified map to this map. No atomicity guarantees are given. In the case of a failure, some of the key-value tuples may get written, while others are not. :param map: (dict), map which includes mappings to be stored in this map. """ check_not_none(map, "map can't be None") if not map: return ImmediateFuture(None) partition_service = self._client.partition_service partition_map = {} for key, value in six.iteritems(map): check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") entry = (self._to_data(key), self._to_data(value)) partition_id = partition_service.get_partition_id(entry[0]) try: partition_map[partition_id].append(entry) except KeyError: partition_map[partition_id] = [entry] futures = [] for partition_id, entry_list in six.iteritems(partition_map): future = self._encode_invoke_on_partition(map_put_all_codec, partition_id, entries=dict(entry_list)) futures.append(future) return combine_futures(*futures)
def function[put_all, parameter[self, map]]: constant[ Copies all of the mappings from the specified map to this map. No atomicity guarantees are given. In the case of a failure, some of the key-value tuples may get written, while others are not. :param map: (dict), map which includes mappings to be stored in this map. ] call[name[check_not_none], parameter[name[map], constant[map can't be None]]] if <ast.UnaryOp object at 0x7da1b17232e0> begin[:] return[call[name[ImmediateFuture], parameter[constant[None]]]] variable[partition_service] assign[=] name[self]._client.partition_service variable[partition_map] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da1b1723340>, <ast.Name object at 0x7da1b1722ad0>]]] in starred[call[name[six].iteritems, parameter[name[map]]]] begin[:] call[name[check_not_none], parameter[name[key], constant[key can't be None]]] call[name[check_not_none], parameter[name[value], constant[value can't be None]]] variable[entry] assign[=] tuple[[<ast.Call object at 0x7da1b17232b0>, <ast.Call object at 0x7da1b1721210>]] variable[partition_id] assign[=] call[name[partition_service].get_partition_id, parameter[call[name[entry]][constant[0]]]] <ast.Try object at 0x7da1b1721ed0> variable[futures] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b17216c0>, <ast.Name object at 0x7da1b1722560>]]] in starred[call[name[six].iteritems, parameter[name[partition_map]]]] begin[:] variable[future] assign[=] call[name[self]._encode_invoke_on_partition, parameter[name[map_put_all_codec], name[partition_id]]] call[name[futures].append, parameter[name[future]]] return[call[name[combine_futures], parameter[<ast.Starred object at 0x7da1b16bde40>]]]
keyword[def] identifier[put_all] ( identifier[self] , identifier[map] ): literal[string] identifier[check_not_none] ( identifier[map] , literal[string] ) keyword[if] keyword[not] identifier[map] : keyword[return] identifier[ImmediateFuture] ( keyword[None] ) identifier[partition_service] = identifier[self] . identifier[_client] . identifier[partition_service] identifier[partition_map] ={} keyword[for] identifier[key] , identifier[value] keyword[in] identifier[six] . identifier[iteritems] ( identifier[map] ): identifier[check_not_none] ( identifier[key] , literal[string] ) identifier[check_not_none] ( identifier[value] , literal[string] ) identifier[entry] =( identifier[self] . identifier[_to_data] ( identifier[key] ), identifier[self] . identifier[_to_data] ( identifier[value] )) identifier[partition_id] = identifier[partition_service] . identifier[get_partition_id] ( identifier[entry] [ literal[int] ]) keyword[try] : identifier[partition_map] [ identifier[partition_id] ]. identifier[append] ( identifier[entry] ) keyword[except] identifier[KeyError] : identifier[partition_map] [ identifier[partition_id] ]=[ identifier[entry] ] identifier[futures] =[] keyword[for] identifier[partition_id] , identifier[entry_list] keyword[in] identifier[six] . identifier[iteritems] ( identifier[partition_map] ): identifier[future] = identifier[self] . identifier[_encode_invoke_on_partition] ( identifier[map_put_all_codec] , identifier[partition_id] , identifier[entries] = identifier[dict] ( identifier[entry_list] )) identifier[futures] . identifier[append] ( identifier[future] ) keyword[return] identifier[combine_futures] (* identifier[futures] )
def put_all(self, map): """ Copies all of the mappings from the specified map to this map. No atomicity guarantees are given. In the case of a failure, some of the key-value tuples may get written, while others are not. :param map: (dict), map which includes mappings to be stored in this map. """ check_not_none(map, "map can't be None") if not map: return ImmediateFuture(None) # depends on [control=['if'], data=[]] partition_service = self._client.partition_service partition_map = {} for (key, value) in six.iteritems(map): check_not_none(key, "key can't be None") check_not_none(value, "value can't be None") entry = (self._to_data(key), self._to_data(value)) partition_id = partition_service.get_partition_id(entry[0]) try: partition_map[partition_id].append(entry) # depends on [control=['try'], data=[]] except KeyError: partition_map[partition_id] = [entry] # depends on [control=['except'], data=[]] # depends on [control=['for'], data=[]] futures = [] for (partition_id, entry_list) in six.iteritems(partition_map): future = self._encode_invoke_on_partition(map_put_all_codec, partition_id, entries=dict(entry_list)) futures.append(future) # depends on [control=['for'], data=[]] return combine_futures(*futures)
def calc_cf_sm_v1(self): """Calculate capillary flow and update soil moisture. Required control parameters: |NmbZones| |ZoneType| |FC| |CFlux| Required fluxes sequence: |R| Required state sequence: |UZ| Calculated flux sequence: |CF| Updated state sequence: |SM| Basic equations: :math:`\\frac{dSM}{dt} = CF` \n :math:`CF = CFLUX \\cdot (1 - \\frac{SM}{FC})` Examples: Initialize six zones of different types. The field capacity of als fields and forests is set to 200mm, the maximum capillary flow rate is 4mm/d: >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> nmbzones(6) >>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD) >>> fc(200.0) >>> cflux(4.0) Note that the assumed length of the simulation step is only a half day. Hence the maximum capillary flow per simulation step is 2 instead of 4: >>> cflux cflux(4.0) >>> cflux.values array([ 2., 2., 2., 2., 2., 2.]) For fields and forests, the actual capillary return flow depends on the relative soil moisture deficite, if either the upper zone layer provides enough water... >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 20.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) ...our enough effective precipitation is generated, which can be rerouted directly: >>> cflux(4.0) >>> fluxes.r = 10.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) If the upper zone layer is empty and no effective precipitation is generated, capillary flow is zero: >>> cflux(4.0) >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0) Here an example, where both the upper zone layer and effective precipitation provide water for the capillary flow, but less then the maximum flow rate times the relative soil moisture: >>> cflux(4.0) >>> fluxes.r = 0.1 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.2 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.3, 0.3, 0.3, 0.0) >>> states.sm sm(0.0, 0.0, 100.3, 100.3, 0.3, 200.0) Even unrealistic high maximum capillary flow rates do not result in overfilled soils: >>> cflux(1000.0) >>> fluxes.r = 200.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 200.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 100.0, 100.0, 200.0, 0.0) >>> states.sm sm(0.0, 0.0, 200.0, 200.0, 200.0, 200.0) For (unrealistic) soils with zero field capacity, capillary flow is always zero: >>> fc(0.0) >>> states.sm = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess sta = self.sequences.states.fastaccess for k in range(con.nmbzones): if con.zonetype[k] in (FIELD, FOREST): if con.fc[k] > 0.: flu.cf[k] = con.cflux[k]*(1.-sta.sm[k]/con.fc[k]) flu.cf[k] = min(flu.cf[k], sta.uz+flu.r[k]) flu.cf[k] = min(flu.cf[k], con.fc[k]-sta.sm[k]) else: flu.cf[k] = 0. sta.sm[k] += flu.cf[k] else: flu.cf[k] = 0. sta.sm[k] = 0.
def function[calc_cf_sm_v1, parameter[self]]: constant[Calculate capillary flow and update soil moisture. Required control parameters: |NmbZones| |ZoneType| |FC| |CFlux| Required fluxes sequence: |R| Required state sequence: |UZ| Calculated flux sequence: |CF| Updated state sequence: |SM| Basic equations: :math:`\frac{dSM}{dt} = CF` :math:`CF = CFLUX \cdot (1 - \frac{SM}{FC})` Examples: Initialize six zones of different types. The field capacity of als fields and forests is set to 200mm, the maximum capillary flow rate is 4mm/d: >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> nmbzones(6) >>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD) >>> fc(200.0) >>> cflux(4.0) Note that the assumed length of the simulation step is only a half day. Hence the maximum capillary flow per simulation step is 2 instead of 4: >>> cflux cflux(4.0) >>> cflux.values array([ 2., 2., 2., 2., 2., 2.]) For fields and forests, the actual capillary return flow depends on the relative soil moisture deficite, if either the upper zone layer provides enough water... >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 20.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) ...our enough effective precipitation is generated, which can be rerouted directly: >>> cflux(4.0) >>> fluxes.r = 10.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) If the upper zone layer is empty and no effective precipitation is generated, capillary flow is zero: >>> cflux(4.0) >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0) Here an example, where both the upper zone layer and effective precipitation provide water for the capillary flow, but less then the maximum flow rate times the relative soil moisture: >>> cflux(4.0) >>> fluxes.r = 0.1 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.2 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.3, 0.3, 0.3, 0.0) >>> states.sm sm(0.0, 0.0, 100.3, 100.3, 0.3, 200.0) Even unrealistic high maximum capillary flow rates do not result in overfilled soils: >>> cflux(1000.0) >>> fluxes.r = 200.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 200.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 100.0, 100.0, 200.0, 0.0) >>> states.sm sm(0.0, 0.0, 200.0, 200.0, 200.0, 200.0) For (unrealistic) soils with zero field capacity, capillary flow is always zero: >>> fc(0.0) >>> states.sm = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) ] variable[con] assign[=] name[self].parameters.control.fastaccess variable[flu] assign[=] name[self].sequences.fluxes.fastaccess variable[sta] assign[=] name[self].sequences.states.fastaccess for taget[name[k]] in starred[call[name[range], parameter[name[con].nmbzones]]] begin[:] if compare[call[name[con].zonetype][name[k]] in tuple[[<ast.Name object at 0x7da2041da890>, <ast.Name object at 0x7da2041da740>]]] begin[:] if compare[call[name[con].fc][name[k]] greater[>] constant[0.0]] begin[:] call[name[flu].cf][name[k]] assign[=] binary_operation[call[name[con].cflux][name[k]] * binary_operation[constant[1.0] - binary_operation[call[name[sta].sm][name[k]] / call[name[con].fc][name[k]]]]] call[name[flu].cf][name[k]] assign[=] call[name[min], parameter[call[name[flu].cf][name[k]], binary_operation[name[sta].uz + call[name[flu].r][name[k]]]]] call[name[flu].cf][name[k]] assign[=] call[name[min], parameter[call[name[flu].cf][name[k]], binary_operation[call[name[con].fc][name[k]] - call[name[sta].sm][name[k]]]]] <ast.AugAssign object at 0x7da2044c25c0>
keyword[def] identifier[calc_cf_sm_v1] ( identifier[self] ): literal[string] identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess] identifier[flu] = identifier[self] . identifier[sequences] . identifier[fluxes] . identifier[fastaccess] identifier[sta] = identifier[self] . identifier[sequences] . identifier[states] . identifier[fastaccess] keyword[for] identifier[k] keyword[in] identifier[range] ( identifier[con] . identifier[nmbzones] ): keyword[if] identifier[con] . identifier[zonetype] [ identifier[k] ] keyword[in] ( identifier[FIELD] , identifier[FOREST] ): keyword[if] identifier[con] . identifier[fc] [ identifier[k] ]> literal[int] : identifier[flu] . identifier[cf] [ identifier[k] ]= identifier[con] . identifier[cflux] [ identifier[k] ]*( literal[int] - identifier[sta] . identifier[sm] [ identifier[k] ]/ identifier[con] . identifier[fc] [ identifier[k] ]) identifier[flu] . identifier[cf] [ identifier[k] ]= identifier[min] ( identifier[flu] . identifier[cf] [ identifier[k] ], identifier[sta] . identifier[uz] + identifier[flu] . identifier[r] [ identifier[k] ]) identifier[flu] . identifier[cf] [ identifier[k] ]= identifier[min] ( identifier[flu] . identifier[cf] [ identifier[k] ], identifier[con] . identifier[fc] [ identifier[k] ]- identifier[sta] . identifier[sm] [ identifier[k] ]) keyword[else] : identifier[flu] . identifier[cf] [ identifier[k] ]= literal[int] identifier[sta] . identifier[sm] [ identifier[k] ]+= identifier[flu] . identifier[cf] [ identifier[k] ] keyword[else] : identifier[flu] . identifier[cf] [ identifier[k] ]= literal[int] identifier[sta] . identifier[sm] [ identifier[k] ]= literal[int]
def calc_cf_sm_v1(self): """Calculate capillary flow and update soil moisture. Required control parameters: |NmbZones| |ZoneType| |FC| |CFlux| Required fluxes sequence: |R| Required state sequence: |UZ| Calculated flux sequence: |CF| Updated state sequence: |SM| Basic equations: :math:`\\frac{dSM}{dt} = CF` :math:`CF = CFLUX \\cdot (1 - \\frac{SM}{FC})` Examples: Initialize six zones of different types. The field capacity of als fields and forests is set to 200mm, the maximum capillary flow rate is 4mm/d: >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> nmbzones(6) >>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD) >>> fc(200.0) >>> cflux(4.0) Note that the assumed length of the simulation step is only a half day. Hence the maximum capillary flow per simulation step is 2 instead of 4: >>> cflux cflux(4.0) >>> cflux.values array([ 2., 2., 2., 2., 2., 2.]) For fields and forests, the actual capillary return flow depends on the relative soil moisture deficite, if either the upper zone layer provides enough water... >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 20.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) ...our enough effective precipitation is generated, which can be rerouted directly: >>> cflux(4.0) >>> fluxes.r = 10.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0) >>> states.sm sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0) If the upper zone layer is empty and no effective precipitation is generated, capillary flow is zero: >>> cflux(4.0) >>> fluxes.r = 0.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0) Here an example, where both the upper zone layer and effective precipitation provide water for the capillary flow, but less then the maximum flow rate times the relative soil moisture: >>> cflux(4.0) >>> fluxes.r = 0.1 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 0.2 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.3, 0.3, 0.3, 0.0) >>> states.sm sm(0.0, 0.0, 100.3, 100.3, 0.3, 200.0) Even unrealistic high maximum capillary flow rates do not result in overfilled soils: >>> cflux(1000.0) >>> fluxes.r = 200.0 >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0 >>> states.uz = 200.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 100.0, 100.0, 200.0, 0.0) >>> states.sm sm(0.0, 0.0, 200.0, 200.0, 200.0, 200.0) For (unrealistic) soils with zero field capacity, capillary flow is always zero: >>> fc(0.0) >>> states.sm = 0.0 >>> model.calc_cf_sm_v1() >>> fluxes.cf cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) >>> states.sm sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess sta = self.sequences.states.fastaccess for k in range(con.nmbzones): if con.zonetype[k] in (FIELD, FOREST): if con.fc[k] > 0.0: flu.cf[k] = con.cflux[k] * (1.0 - sta.sm[k] / con.fc[k]) flu.cf[k] = min(flu.cf[k], sta.uz + flu.r[k]) flu.cf[k] = min(flu.cf[k], con.fc[k] - sta.sm[k]) # depends on [control=['if'], data=[]] else: flu.cf[k] = 0.0 sta.sm[k] += flu.cf[k] # depends on [control=['if'], data=[]] else: flu.cf[k] = 0.0 sta.sm[k] = 0.0 # depends on [control=['for'], data=['k']]
def changes(self): """ Return a tuple with the removed and added facts since last run. """ try: return self.added, self.removed finally: self.added = list() self.removed = list()
def function[changes, parameter[self]]: constant[ Return a tuple with the removed and added facts since last run. ] <ast.Try object at 0x7da1b1e76950>
keyword[def] identifier[changes] ( identifier[self] ): literal[string] keyword[try] : keyword[return] identifier[self] . identifier[added] , identifier[self] . identifier[removed] keyword[finally] : identifier[self] . identifier[added] = identifier[list] () identifier[self] . identifier[removed] = identifier[list] ()
def changes(self): """ Return a tuple with the removed and added facts since last run. """ try: return (self.added, self.removed) # depends on [control=['try'], data=[]] finally: self.added = list() self.removed = list()
def convergence_of_galaxies_from_grid(grid, galaxies): """Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \ of each galaxy's mass profile. If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \ original regular grid by taking the mean value of every set of sub-pixels. If no galaxies are entered into the function, an array of all zeros is returned. Parameters ----------- grid : RegularGrid The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \ convergence is calculated on. galaxies : [galaxy.Galaxy] The galaxies whose mass profiles are used to compute the convergence. """ if galaxies: return sum(map(lambda g: g.convergence_from_grid(grid), galaxies)) else: return np.full((grid.shape[0]), 0.0)
def function[convergence_of_galaxies_from_grid, parameter[grid, galaxies]]: constant[Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence of each galaxy's mass profile. If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the original regular grid by taking the mean value of every set of sub-pixels. If no galaxies are entered into the function, an array of all zeros is returned. Parameters ----------- grid : RegularGrid The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the convergence is calculated on. galaxies : [galaxy.Galaxy] The galaxies whose mass profiles are used to compute the convergence. ] if name[galaxies] begin[:] return[call[name[sum], parameter[call[name[map], parameter[<ast.Lambda object at 0x7da2046223e0>, name[galaxies]]]]]]
keyword[def] identifier[convergence_of_galaxies_from_grid] ( identifier[grid] , identifier[galaxies] ): literal[string] keyword[if] identifier[galaxies] : keyword[return] identifier[sum] ( identifier[map] ( keyword[lambda] identifier[g] : identifier[g] . identifier[convergence_from_grid] ( identifier[grid] ), identifier[galaxies] )) keyword[else] : keyword[return] identifier[np] . identifier[full] (( identifier[grid] . identifier[shape] [ literal[int] ]), literal[int] )
def convergence_of_galaxies_from_grid(grid, galaxies): """Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence of each galaxy's mass profile. If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the original regular grid by taking the mean value of every set of sub-pixels. If no galaxies are entered into the function, an array of all zeros is returned. Parameters ----------- grid : RegularGrid The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the convergence is calculated on. galaxies : [galaxy.Galaxy] The galaxies whose mass profiles are used to compute the convergence. """ if galaxies: return sum(map(lambda g: g.convergence_from_grid(grid), galaxies)) # depends on [control=['if'], data=[]] else: return np.full(grid.shape[0], 0.0)
def verify(self, data, require_x509=True, x509_cert=None, cert_subject_name=None, ca_pem_file=None, ca_path=None, hmac_key=None, validate_schema=True, parser=None, uri_resolver=None, id_attribute=None, expect_references=1): """ Verify the XML signature supplied in the data and return the XML node signed by the signature, or raise an exception if the signature is not valid. By default, this requires the signature to be generated using a valid X.509 certificate. To enable other means of signature validation, set the **require_x509** argument to `False`. .. admonition:: See what is signed It is important to understand and follow the best practice rule of "See what is signed" when verifying XML signatures. The gist of this rule is: if your application neglects to verify that the information it trusts is what was actually signed, the attacker can supply a valid signature but point you to malicious data that wasn't signed by that signature. In SignXML, you can ensure that the information signed is what you expect to be signed by only trusting the data returned by the ``verify()`` method. The return value is the XML node or string that was signed. Also, depending on the signature settings used, comments in the XML data may not be subject to signing, so may need to be untrusted. **Recommended reading:** http://www.w3.org/TR/xmldsig-bestpractices/#practices-applications .. admonition:: Establish trust If you do not supply any keyword arguments to ``verify()``, the default behavior is to trust **any** valid XML signature generated using a valid X.509 certificate trusted by your system's CA store. This means anyone can get an SSL certificate and generate a signature that you will trust. To establish trust in the signer, use the ``x509_cert`` argument to specify a certificate that was pre-shared out-of-band (e.g. via SAML metadata, as shown in :ref:`Verifying SAML assertions <verifying-saml-assertions>`), or ``cert_subject_name`` to specify a subject name that must be in the signing X.509 certificate given by the signature (verified as if it were a domain name), or ``ca_pem_file``/``ca_path`` to give a custom CA. :param data: Signature data to verify :type data: String, file-like object, or XML ElementTree Element API compatible object :param require_x509: If ``True``, a valid X.509 certificate-based signature with an established chain of trust is required to pass validation. If ``False``, other types of valid signatures (e.g. HMAC or RSA public key) are accepted. :type require_x509: boolean :param x509_cert: A trusted external X.509 certificate, given as a PEM-formatted string or OpenSSL.crypto.X509 object, to use for verification. Overrides any X.509 certificate information supplied by the signature. If left set to ``None``, requires that the signature supply a valid X.509 certificate chain that validates against the known certificate authorities. Implies **require_x509=True**. :type x509_cert: string or OpenSSL.crypto.X509 :param ca_pem_file: Filename of a PEM file containing certificate authority information to use when verifying certificate-based signatures. :type ca_pem_file: string or bytes :param ca_path: Path to a directory containing PEM-formatted certificate authority files to use when verifying certificate-based signatures. If neither **ca_pem_file** nor **ca_path** is given, the Mozilla CA bundle provided by :py:mod:`certifi` will be loaded. :type ca_path: string :param cert_subject_name: Subject Common Name to check the signing X.509 certificate against. Implies **require_x509=True**. :type cert_subject_name: string :param hmac_key: If using HMAC, a string containing the shared secret. :type hmac_key: string :param validate_schema: Whether to validate **data** against the XML Signature schema. :type validate_schema: boolean :param parser: Custom XML parser instance to use when parsing **data**. :type parser: :py:class:`lxml.etree.XMLParser` compatible parser :param uri_resolver: Function to use to resolve reference URIs that don't start with "#". :type uri_resolver: callable :param id_attribute: Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID". :type id_attribute: string :param expect_references: Number of references to expect in the signature. If this is not 1, an array of VerifyResults is returned. If set to a non-integer, any number of references is accepted (otherwise a mismatch raises an error). :type expect_references: int or boolean :raises: :py:class:`cryptography.exceptions.InvalidSignature` :returns: VerifyResult object with the signed data, signed xml and signature xml :rtype: VerifyResult """ self.hmac_key = hmac_key self.require_x509 = require_x509 self.x509_cert = x509_cert self._parser = parser if x509_cert: self.require_x509 = True if id_attribute is not None: self.id_attributes = (id_attribute, ) root = self.get_root(data) if root.tag == ds_tag("Signature"): signature_ref = root else: signature_ref = self._find(root, "Signature", anywhere=True) # HACK: deep copy won't keep root's namespaces signature = fromstring(etree.tostring(signature_ref), parser=parser) if validate_schema: self.schema().assertValid(signature) signed_info = self._find(signature, "SignedInfo") c14n_method = self._find(signed_info, "CanonicalizationMethod") c14n_algorithm = c14n_method.get("Algorithm") signature_method = self._find(signed_info, "SignatureMethod") signature_value = self._find(signature, "SignatureValue") signature_alg = signature_method.get("Algorithm") raw_signature = b64decode(signature_value.text) x509_data = signature.find("ds:KeyInfo/ds:X509Data", namespaces=namespaces) signed_info_c14n = self._c14n(signed_info, algorithm=c14n_algorithm) if x509_data is not None or self.require_x509: from OpenSSL.crypto import load_certificate, X509, FILETYPE_PEM, verify, Error as OpenSSLCryptoError if self.x509_cert is None: if x509_data is None: raise InvalidInput("Expected a X.509 certificate based signature") certs = [cert.text for cert in self._findall(x509_data, "X509Certificate")] if not certs: msg = "Expected to find an X509Certificate element in the signature" msg += " (X509SubjectName, X509SKI are not supported)" raise InvalidInput(msg) cert_chain = [load_certificate(FILETYPE_PEM, add_pem_header(cert)) for cert in certs] signing_cert = verify_x509_cert_chain(cert_chain, ca_pem_file=ca_pem_file, ca_path=ca_path) elif isinstance(self.x509_cert, X509): signing_cert = self.x509_cert else: signing_cert = load_certificate(FILETYPE_PEM, add_pem_header(self.x509_cert)) if cert_subject_name and signing_cert.get_subject().commonName != cert_subject_name: raise InvalidSignature("Certificate subject common name mismatch") signature_digest_method = self._get_signature_digest_method(signature_alg).name try: verify(signing_cert, raw_signature, signed_info_c14n, signature_digest_method) except OpenSSLCryptoError as e: try: lib, func, reason = e.args[0][0] except Exception: reason = e raise InvalidSignature("Signature verification failed: {}".format(reason)) # TODO: CN verification goes here # TODO: require one of the following to be set: either x509_cert or (ca_pem_file or ca_path) or common_name # Use ssl.match_hostname or code from it to perform match elif "hmac-sha" in signature_alg: if self.hmac_key is None: raise InvalidInput('Parameter "hmac_key" is required when verifying a HMAC signature') from cryptography.hazmat.primitives.hmac import HMAC signer = HMAC(key=ensure_bytes(self.hmac_key), algorithm=self._get_hmac_digest_method(signature_alg), backend=default_backend()) signer.update(signed_info_c14n) if raw_signature != signer.finalize(): raise InvalidSignature("Signature mismatch (HMAC)") else: key_value = signature.find("ds:KeyInfo/ds:KeyValue", namespaces=namespaces) if key_value is None: raise InvalidInput("Expected to find either KeyValue or X509Data XML element in KeyInfo") self._verify_signature_with_pubkey(signed_info_c14n, raw_signature, key_value, signature_alg) verify_results = [] for reference in self._findall(signed_info, "Reference"): transforms = self._find(reference, "Transforms", require=False) digest_algorithm = self._find(reference, "DigestMethod").get("Algorithm") digest_value = self._find(reference, "DigestValue") payload = self._resolve_reference(root, reference, uri_resolver=uri_resolver) payload_c14n = self._apply_transforms(payload, transforms, signature_ref, c14n_algorithm) if digest_value.text != self._get_digest(payload_c14n, self._get_digest_method(digest_algorithm)): raise InvalidDigest("Digest mismatch for reference {}".format(len(verify_results))) # We return the signed XML (and only that) to ensure no access to unsigned data happens try: payload_c14n_xml = fromstring(payload_c14n) except etree.XMLSyntaxError: payload_c14n_xml = None verify_results.append(VerifyResult(payload_c14n, payload_c14n_xml, signature)) if type(expect_references) is int and len(verify_results) != expect_references: msg = "Expected to find {} references, but found {}" raise InvalidSignature(msg.format(expect_references, len(verify_results))) return verify_results if expect_references > 1 else verify_results[0]
def function[verify, parameter[self, data, require_x509, x509_cert, cert_subject_name, ca_pem_file, ca_path, hmac_key, validate_schema, parser, uri_resolver, id_attribute, expect_references]]: constant[ Verify the XML signature supplied in the data and return the XML node signed by the signature, or raise an exception if the signature is not valid. By default, this requires the signature to be generated using a valid X.509 certificate. To enable other means of signature validation, set the **require_x509** argument to `False`. .. admonition:: See what is signed It is important to understand and follow the best practice rule of "See what is signed" when verifying XML signatures. The gist of this rule is: if your application neglects to verify that the information it trusts is what was actually signed, the attacker can supply a valid signature but point you to malicious data that wasn't signed by that signature. In SignXML, you can ensure that the information signed is what you expect to be signed by only trusting the data returned by the ``verify()`` method. The return value is the XML node or string that was signed. Also, depending on the signature settings used, comments in the XML data may not be subject to signing, so may need to be untrusted. **Recommended reading:** http://www.w3.org/TR/xmldsig-bestpractices/#practices-applications .. admonition:: Establish trust If you do not supply any keyword arguments to ``verify()``, the default behavior is to trust **any** valid XML signature generated using a valid X.509 certificate trusted by your system's CA store. This means anyone can get an SSL certificate and generate a signature that you will trust. To establish trust in the signer, use the ``x509_cert`` argument to specify a certificate that was pre-shared out-of-band (e.g. via SAML metadata, as shown in :ref:`Verifying SAML assertions <verifying-saml-assertions>`), or ``cert_subject_name`` to specify a subject name that must be in the signing X.509 certificate given by the signature (verified as if it were a domain name), or ``ca_pem_file``/``ca_path`` to give a custom CA. :param data: Signature data to verify :type data: String, file-like object, or XML ElementTree Element API compatible object :param require_x509: If ``True``, a valid X.509 certificate-based signature with an established chain of trust is required to pass validation. If ``False``, other types of valid signatures (e.g. HMAC or RSA public key) are accepted. :type require_x509: boolean :param x509_cert: A trusted external X.509 certificate, given as a PEM-formatted string or OpenSSL.crypto.X509 object, to use for verification. Overrides any X.509 certificate information supplied by the signature. If left set to ``None``, requires that the signature supply a valid X.509 certificate chain that validates against the known certificate authorities. Implies **require_x509=True**. :type x509_cert: string or OpenSSL.crypto.X509 :param ca_pem_file: Filename of a PEM file containing certificate authority information to use when verifying certificate-based signatures. :type ca_pem_file: string or bytes :param ca_path: Path to a directory containing PEM-formatted certificate authority files to use when verifying certificate-based signatures. If neither **ca_pem_file** nor **ca_path** is given, the Mozilla CA bundle provided by :py:mod:`certifi` will be loaded. :type ca_path: string :param cert_subject_name: Subject Common Name to check the signing X.509 certificate against. Implies **require_x509=True**. :type cert_subject_name: string :param hmac_key: If using HMAC, a string containing the shared secret. :type hmac_key: string :param validate_schema: Whether to validate **data** against the XML Signature schema. :type validate_schema: boolean :param parser: Custom XML parser instance to use when parsing **data**. :type parser: :py:class:`lxml.etree.XMLParser` compatible parser :param uri_resolver: Function to use to resolve reference URIs that don't start with "#". :type uri_resolver: callable :param id_attribute: Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID". :type id_attribute: string :param expect_references: Number of references to expect in the signature. If this is not 1, an array of VerifyResults is returned. If set to a non-integer, any number of references is accepted (otherwise a mismatch raises an error). :type expect_references: int or boolean :raises: :py:class:`cryptography.exceptions.InvalidSignature` :returns: VerifyResult object with the signed data, signed xml and signature xml :rtype: VerifyResult ] name[self].hmac_key assign[=] name[hmac_key] name[self].require_x509 assign[=] name[require_x509] name[self].x509_cert assign[=] name[x509_cert] name[self]._parser assign[=] name[parser] if name[x509_cert] begin[:] name[self].require_x509 assign[=] constant[True] if compare[name[id_attribute] is_not constant[None]] begin[:] name[self].id_attributes assign[=] tuple[[<ast.Name object at 0x7da1b157ea10>]] variable[root] assign[=] call[name[self].get_root, parameter[name[data]]] if compare[name[root].tag equal[==] call[name[ds_tag], parameter[constant[Signature]]]] begin[:] variable[signature_ref] assign[=] name[root] variable[signature] assign[=] call[name[fromstring], parameter[call[name[etree].tostring, parameter[name[signature_ref]]]]] if name[validate_schema] begin[:] call[call[name[self].schema, parameter[]].assertValid, parameter[name[signature]]] variable[signed_info] assign[=] call[name[self]._find, parameter[name[signature], constant[SignedInfo]]] variable[c14n_method] assign[=] call[name[self]._find, parameter[name[signed_info], constant[CanonicalizationMethod]]] variable[c14n_algorithm] assign[=] call[name[c14n_method].get, parameter[constant[Algorithm]]] variable[signature_method] assign[=] call[name[self]._find, parameter[name[signed_info], constant[SignatureMethod]]] variable[signature_value] assign[=] call[name[self]._find, parameter[name[signature], constant[SignatureValue]]] variable[signature_alg] assign[=] call[name[signature_method].get, parameter[constant[Algorithm]]] variable[raw_signature] assign[=] call[name[b64decode], parameter[name[signature_value].text]] variable[x509_data] assign[=] call[name[signature].find, parameter[constant[ds:KeyInfo/ds:X509Data]]] variable[signed_info_c14n] assign[=] call[name[self]._c14n, parameter[name[signed_info]]] if <ast.BoolOp object at 0x7da1b157dd50> begin[:] from relative_module[OpenSSL.crypto] import module[load_certificate], module[X509], module[FILETYPE_PEM], module[verify], module[Error] if compare[name[self].x509_cert is constant[None]] begin[:] if compare[name[x509_data] is constant[None]] begin[:] <ast.Raise object at 0x7da1b157f0d0> variable[certs] assign[=] <ast.ListComp object at 0x7da1b157c910> if <ast.UnaryOp object at 0x7da1b157c7f0> begin[:] variable[msg] assign[=] constant[Expected to find an X509Certificate element in the signature] <ast.AugAssign object at 0x7da1b15f7d60> <ast.Raise object at 0x7da1b15f6770> variable[cert_chain] assign[=] <ast.ListComp object at 0x7da1b15f6e30> variable[signing_cert] assign[=] call[name[verify_x509_cert_chain], parameter[name[cert_chain]]] if <ast.BoolOp object at 0x7da1b15f7dc0> begin[:] <ast.Raise object at 0x7da1b15f5ed0> variable[signature_digest_method] assign[=] call[name[self]._get_signature_digest_method, parameter[name[signature_alg]]].name <ast.Try object at 0x7da1b15f53c0> variable[verify_results] assign[=] list[[]] for taget[name[reference]] in starred[call[name[self]._findall, parameter[name[signed_info], constant[Reference]]]] begin[:] variable[transforms] assign[=] call[name[self]._find, parameter[name[reference], constant[Transforms]]] variable[digest_algorithm] assign[=] call[call[name[self]._find, parameter[name[reference], constant[DigestMethod]]].get, parameter[constant[Algorithm]]] variable[digest_value] assign[=] call[name[self]._find, parameter[name[reference], constant[DigestValue]]] variable[payload] assign[=] call[name[self]._resolve_reference, parameter[name[root], name[reference]]] variable[payload_c14n] assign[=] call[name[self]._apply_transforms, parameter[name[payload], name[transforms], name[signature_ref], name[c14n_algorithm]]] if compare[name[digest_value].text not_equal[!=] call[name[self]._get_digest, parameter[name[payload_c14n], call[name[self]._get_digest_method, parameter[name[digest_algorithm]]]]]] begin[:] <ast.Raise object at 0x7da1b15f5750> <ast.Try object at 0x7da1b1306cb0> call[name[verify_results].append, parameter[call[name[VerifyResult], parameter[name[payload_c14n], name[payload_c14n_xml], name[signature]]]]] if <ast.BoolOp object at 0x7da1b1304a30> begin[:] variable[msg] assign[=] constant[Expected to find {} references, but found {}] <ast.Raise object at 0x7da1b13074c0> return[<ast.IfExp object at 0x7da1b15498d0>]
keyword[def] identifier[verify] ( identifier[self] , identifier[data] , identifier[require_x509] = keyword[True] , identifier[x509_cert] = keyword[None] , identifier[cert_subject_name] = keyword[None] , identifier[ca_pem_file] = keyword[None] , identifier[ca_path] = keyword[None] , identifier[hmac_key] = keyword[None] , identifier[validate_schema] = keyword[True] , identifier[parser] = keyword[None] , identifier[uri_resolver] = keyword[None] , identifier[id_attribute] = keyword[None] , identifier[expect_references] = literal[int] ): literal[string] identifier[self] . identifier[hmac_key] = identifier[hmac_key] identifier[self] . identifier[require_x509] = identifier[require_x509] identifier[self] . identifier[x509_cert] = identifier[x509_cert] identifier[self] . identifier[_parser] = identifier[parser] keyword[if] identifier[x509_cert] : identifier[self] . identifier[require_x509] = keyword[True] keyword[if] identifier[id_attribute] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[id_attributes] =( identifier[id_attribute] ,) identifier[root] = identifier[self] . identifier[get_root] ( identifier[data] ) keyword[if] identifier[root] . identifier[tag] == identifier[ds_tag] ( literal[string] ): identifier[signature_ref] = identifier[root] keyword[else] : identifier[signature_ref] = identifier[self] . identifier[_find] ( identifier[root] , literal[string] , identifier[anywhere] = keyword[True] ) identifier[signature] = identifier[fromstring] ( identifier[etree] . identifier[tostring] ( identifier[signature_ref] ), identifier[parser] = identifier[parser] ) keyword[if] identifier[validate_schema] : identifier[self] . identifier[schema] (). identifier[assertValid] ( identifier[signature] ) identifier[signed_info] = identifier[self] . identifier[_find] ( identifier[signature] , literal[string] ) identifier[c14n_method] = identifier[self] . identifier[_find] ( identifier[signed_info] , literal[string] ) identifier[c14n_algorithm] = identifier[c14n_method] . identifier[get] ( literal[string] ) identifier[signature_method] = identifier[self] . identifier[_find] ( identifier[signed_info] , literal[string] ) identifier[signature_value] = identifier[self] . identifier[_find] ( identifier[signature] , literal[string] ) identifier[signature_alg] = identifier[signature_method] . identifier[get] ( literal[string] ) identifier[raw_signature] = identifier[b64decode] ( identifier[signature_value] . identifier[text] ) identifier[x509_data] = identifier[signature] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[namespaces] ) identifier[signed_info_c14n] = identifier[self] . identifier[_c14n] ( identifier[signed_info] , identifier[algorithm] = identifier[c14n_algorithm] ) keyword[if] identifier[x509_data] keyword[is] keyword[not] keyword[None] keyword[or] identifier[self] . identifier[require_x509] : keyword[from] identifier[OpenSSL] . identifier[crypto] keyword[import] identifier[load_certificate] , identifier[X509] , identifier[FILETYPE_PEM] , identifier[verify] , identifier[Error] keyword[as] identifier[OpenSSLCryptoError] keyword[if] identifier[self] . identifier[x509_cert] keyword[is] keyword[None] : keyword[if] identifier[x509_data] keyword[is] keyword[None] : keyword[raise] identifier[InvalidInput] ( literal[string] ) identifier[certs] =[ identifier[cert] . identifier[text] keyword[for] identifier[cert] keyword[in] identifier[self] . identifier[_findall] ( identifier[x509_data] , literal[string] )] keyword[if] keyword[not] identifier[certs] : identifier[msg] = literal[string] identifier[msg] += literal[string] keyword[raise] identifier[InvalidInput] ( identifier[msg] ) identifier[cert_chain] =[ identifier[load_certificate] ( identifier[FILETYPE_PEM] , identifier[add_pem_header] ( identifier[cert] )) keyword[for] identifier[cert] keyword[in] identifier[certs] ] identifier[signing_cert] = identifier[verify_x509_cert_chain] ( identifier[cert_chain] , identifier[ca_pem_file] = identifier[ca_pem_file] , identifier[ca_path] = identifier[ca_path] ) keyword[elif] identifier[isinstance] ( identifier[self] . identifier[x509_cert] , identifier[X509] ): identifier[signing_cert] = identifier[self] . identifier[x509_cert] keyword[else] : identifier[signing_cert] = identifier[load_certificate] ( identifier[FILETYPE_PEM] , identifier[add_pem_header] ( identifier[self] . identifier[x509_cert] )) keyword[if] identifier[cert_subject_name] keyword[and] identifier[signing_cert] . identifier[get_subject] (). identifier[commonName] != identifier[cert_subject_name] : keyword[raise] identifier[InvalidSignature] ( literal[string] ) identifier[signature_digest_method] = identifier[self] . identifier[_get_signature_digest_method] ( identifier[signature_alg] ). identifier[name] keyword[try] : identifier[verify] ( identifier[signing_cert] , identifier[raw_signature] , identifier[signed_info_c14n] , identifier[signature_digest_method] ) keyword[except] identifier[OpenSSLCryptoError] keyword[as] identifier[e] : keyword[try] : identifier[lib] , identifier[func] , identifier[reason] = identifier[e] . identifier[args] [ literal[int] ][ literal[int] ] keyword[except] identifier[Exception] : identifier[reason] = identifier[e] keyword[raise] identifier[InvalidSignature] ( literal[string] . identifier[format] ( identifier[reason] )) keyword[elif] literal[string] keyword[in] identifier[signature_alg] : keyword[if] identifier[self] . identifier[hmac_key] keyword[is] keyword[None] : keyword[raise] identifier[InvalidInput] ( literal[string] ) keyword[from] identifier[cryptography] . identifier[hazmat] . identifier[primitives] . identifier[hmac] keyword[import] identifier[HMAC] identifier[signer] = identifier[HMAC] ( identifier[key] = identifier[ensure_bytes] ( identifier[self] . identifier[hmac_key] ), identifier[algorithm] = identifier[self] . identifier[_get_hmac_digest_method] ( identifier[signature_alg] ), identifier[backend] = identifier[default_backend] ()) identifier[signer] . identifier[update] ( identifier[signed_info_c14n] ) keyword[if] identifier[raw_signature] != identifier[signer] . identifier[finalize] (): keyword[raise] identifier[InvalidSignature] ( literal[string] ) keyword[else] : identifier[key_value] = identifier[signature] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[namespaces] ) keyword[if] identifier[key_value] keyword[is] keyword[None] : keyword[raise] identifier[InvalidInput] ( literal[string] ) identifier[self] . identifier[_verify_signature_with_pubkey] ( identifier[signed_info_c14n] , identifier[raw_signature] , identifier[key_value] , identifier[signature_alg] ) identifier[verify_results] =[] keyword[for] identifier[reference] keyword[in] identifier[self] . identifier[_findall] ( identifier[signed_info] , literal[string] ): identifier[transforms] = identifier[self] . identifier[_find] ( identifier[reference] , literal[string] , identifier[require] = keyword[False] ) identifier[digest_algorithm] = identifier[self] . identifier[_find] ( identifier[reference] , literal[string] ). identifier[get] ( literal[string] ) identifier[digest_value] = identifier[self] . identifier[_find] ( identifier[reference] , literal[string] ) identifier[payload] = identifier[self] . identifier[_resolve_reference] ( identifier[root] , identifier[reference] , identifier[uri_resolver] = identifier[uri_resolver] ) identifier[payload_c14n] = identifier[self] . identifier[_apply_transforms] ( identifier[payload] , identifier[transforms] , identifier[signature_ref] , identifier[c14n_algorithm] ) keyword[if] identifier[digest_value] . identifier[text] != identifier[self] . identifier[_get_digest] ( identifier[payload_c14n] , identifier[self] . identifier[_get_digest_method] ( identifier[digest_algorithm] )): keyword[raise] identifier[InvalidDigest] ( literal[string] . identifier[format] ( identifier[len] ( identifier[verify_results] ))) keyword[try] : identifier[payload_c14n_xml] = identifier[fromstring] ( identifier[payload_c14n] ) keyword[except] identifier[etree] . identifier[XMLSyntaxError] : identifier[payload_c14n_xml] = keyword[None] identifier[verify_results] . identifier[append] ( identifier[VerifyResult] ( identifier[payload_c14n] , identifier[payload_c14n_xml] , identifier[signature] )) keyword[if] identifier[type] ( identifier[expect_references] ) keyword[is] identifier[int] keyword[and] identifier[len] ( identifier[verify_results] )!= identifier[expect_references] : identifier[msg] = literal[string] keyword[raise] identifier[InvalidSignature] ( identifier[msg] . identifier[format] ( identifier[expect_references] , identifier[len] ( identifier[verify_results] ))) keyword[return] identifier[verify_results] keyword[if] identifier[expect_references] > literal[int] keyword[else] identifier[verify_results] [ literal[int] ]
def verify(self, data, require_x509=True, x509_cert=None, cert_subject_name=None, ca_pem_file=None, ca_path=None, hmac_key=None, validate_schema=True, parser=None, uri_resolver=None, id_attribute=None, expect_references=1): """ Verify the XML signature supplied in the data and return the XML node signed by the signature, or raise an exception if the signature is not valid. By default, this requires the signature to be generated using a valid X.509 certificate. To enable other means of signature validation, set the **require_x509** argument to `False`. .. admonition:: See what is signed It is important to understand and follow the best practice rule of "See what is signed" when verifying XML signatures. The gist of this rule is: if your application neglects to verify that the information it trusts is what was actually signed, the attacker can supply a valid signature but point you to malicious data that wasn't signed by that signature. In SignXML, you can ensure that the information signed is what you expect to be signed by only trusting the data returned by the ``verify()`` method. The return value is the XML node or string that was signed. Also, depending on the signature settings used, comments in the XML data may not be subject to signing, so may need to be untrusted. **Recommended reading:** http://www.w3.org/TR/xmldsig-bestpractices/#practices-applications .. admonition:: Establish trust If you do not supply any keyword arguments to ``verify()``, the default behavior is to trust **any** valid XML signature generated using a valid X.509 certificate trusted by your system's CA store. This means anyone can get an SSL certificate and generate a signature that you will trust. To establish trust in the signer, use the ``x509_cert`` argument to specify a certificate that was pre-shared out-of-band (e.g. via SAML metadata, as shown in :ref:`Verifying SAML assertions <verifying-saml-assertions>`), or ``cert_subject_name`` to specify a subject name that must be in the signing X.509 certificate given by the signature (verified as if it were a domain name), or ``ca_pem_file``/``ca_path`` to give a custom CA. :param data: Signature data to verify :type data: String, file-like object, or XML ElementTree Element API compatible object :param require_x509: If ``True``, a valid X.509 certificate-based signature with an established chain of trust is required to pass validation. If ``False``, other types of valid signatures (e.g. HMAC or RSA public key) are accepted. :type require_x509: boolean :param x509_cert: A trusted external X.509 certificate, given as a PEM-formatted string or OpenSSL.crypto.X509 object, to use for verification. Overrides any X.509 certificate information supplied by the signature. If left set to ``None``, requires that the signature supply a valid X.509 certificate chain that validates against the known certificate authorities. Implies **require_x509=True**. :type x509_cert: string or OpenSSL.crypto.X509 :param ca_pem_file: Filename of a PEM file containing certificate authority information to use when verifying certificate-based signatures. :type ca_pem_file: string or bytes :param ca_path: Path to a directory containing PEM-formatted certificate authority files to use when verifying certificate-based signatures. If neither **ca_pem_file** nor **ca_path** is given, the Mozilla CA bundle provided by :py:mod:`certifi` will be loaded. :type ca_path: string :param cert_subject_name: Subject Common Name to check the signing X.509 certificate against. Implies **require_x509=True**. :type cert_subject_name: string :param hmac_key: If using HMAC, a string containing the shared secret. :type hmac_key: string :param validate_schema: Whether to validate **data** against the XML Signature schema. :type validate_schema: boolean :param parser: Custom XML parser instance to use when parsing **data**. :type parser: :py:class:`lxml.etree.XMLParser` compatible parser :param uri_resolver: Function to use to resolve reference URIs that don't start with "#". :type uri_resolver: callable :param id_attribute: Name of the attribute whose value ``URI`` refers to. By default, SignXML will search for "Id", then "ID". :type id_attribute: string :param expect_references: Number of references to expect in the signature. If this is not 1, an array of VerifyResults is returned. If set to a non-integer, any number of references is accepted (otherwise a mismatch raises an error). :type expect_references: int or boolean :raises: :py:class:`cryptography.exceptions.InvalidSignature` :returns: VerifyResult object with the signed data, signed xml and signature xml :rtype: VerifyResult """ self.hmac_key = hmac_key self.require_x509 = require_x509 self.x509_cert = x509_cert self._parser = parser if x509_cert: self.require_x509 = True # depends on [control=['if'], data=[]] if id_attribute is not None: self.id_attributes = (id_attribute,) # depends on [control=['if'], data=['id_attribute']] root = self.get_root(data) if root.tag == ds_tag('Signature'): signature_ref = root # depends on [control=['if'], data=[]] else: signature_ref = self._find(root, 'Signature', anywhere=True) # HACK: deep copy won't keep root's namespaces signature = fromstring(etree.tostring(signature_ref), parser=parser) if validate_schema: self.schema().assertValid(signature) # depends on [control=['if'], data=[]] signed_info = self._find(signature, 'SignedInfo') c14n_method = self._find(signed_info, 'CanonicalizationMethod') c14n_algorithm = c14n_method.get('Algorithm') signature_method = self._find(signed_info, 'SignatureMethod') signature_value = self._find(signature, 'SignatureValue') signature_alg = signature_method.get('Algorithm') raw_signature = b64decode(signature_value.text) x509_data = signature.find('ds:KeyInfo/ds:X509Data', namespaces=namespaces) signed_info_c14n = self._c14n(signed_info, algorithm=c14n_algorithm) if x509_data is not None or self.require_x509: from OpenSSL.crypto import load_certificate, X509, FILETYPE_PEM, verify, Error as OpenSSLCryptoError if self.x509_cert is None: if x509_data is None: raise InvalidInput('Expected a X.509 certificate based signature') # depends on [control=['if'], data=[]] certs = [cert.text for cert in self._findall(x509_data, 'X509Certificate')] if not certs: msg = 'Expected to find an X509Certificate element in the signature' msg += ' (X509SubjectName, X509SKI are not supported)' raise InvalidInput(msg) # depends on [control=['if'], data=[]] cert_chain = [load_certificate(FILETYPE_PEM, add_pem_header(cert)) for cert in certs] signing_cert = verify_x509_cert_chain(cert_chain, ca_pem_file=ca_pem_file, ca_path=ca_path) # depends on [control=['if'], data=[]] elif isinstance(self.x509_cert, X509): signing_cert = self.x509_cert # depends on [control=['if'], data=[]] else: signing_cert = load_certificate(FILETYPE_PEM, add_pem_header(self.x509_cert)) if cert_subject_name and signing_cert.get_subject().commonName != cert_subject_name: raise InvalidSignature('Certificate subject common name mismatch') # depends on [control=['if'], data=[]] signature_digest_method = self._get_signature_digest_method(signature_alg).name try: verify(signing_cert, raw_signature, signed_info_c14n, signature_digest_method) # depends on [control=['try'], data=[]] except OpenSSLCryptoError as e: try: (lib, func, reason) = e.args[0][0] # depends on [control=['try'], data=[]] except Exception: reason = e # depends on [control=['except'], data=[]] raise InvalidSignature('Signature verification failed: {}'.format(reason)) # depends on [control=['except'], data=['e']] # depends on [control=['if'], data=[]] # TODO: CN verification goes here # TODO: require one of the following to be set: either x509_cert or (ca_pem_file or ca_path) or common_name # Use ssl.match_hostname or code from it to perform match elif 'hmac-sha' in signature_alg: if self.hmac_key is None: raise InvalidInput('Parameter "hmac_key" is required when verifying a HMAC signature') # depends on [control=['if'], data=[]] from cryptography.hazmat.primitives.hmac import HMAC signer = HMAC(key=ensure_bytes(self.hmac_key), algorithm=self._get_hmac_digest_method(signature_alg), backend=default_backend()) signer.update(signed_info_c14n) if raw_signature != signer.finalize(): raise InvalidSignature('Signature mismatch (HMAC)') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['signature_alg']] else: key_value = signature.find('ds:KeyInfo/ds:KeyValue', namespaces=namespaces) if key_value is None: raise InvalidInput('Expected to find either KeyValue or X509Data XML element in KeyInfo') # depends on [control=['if'], data=[]] self._verify_signature_with_pubkey(signed_info_c14n, raw_signature, key_value, signature_alg) verify_results = [] for reference in self._findall(signed_info, 'Reference'): transforms = self._find(reference, 'Transforms', require=False) digest_algorithm = self._find(reference, 'DigestMethod').get('Algorithm') digest_value = self._find(reference, 'DigestValue') payload = self._resolve_reference(root, reference, uri_resolver=uri_resolver) payload_c14n = self._apply_transforms(payload, transforms, signature_ref, c14n_algorithm) if digest_value.text != self._get_digest(payload_c14n, self._get_digest_method(digest_algorithm)): raise InvalidDigest('Digest mismatch for reference {}'.format(len(verify_results))) # depends on [control=['if'], data=[]] # We return the signed XML (and only that) to ensure no access to unsigned data happens try: payload_c14n_xml = fromstring(payload_c14n) # depends on [control=['try'], data=[]] except etree.XMLSyntaxError: payload_c14n_xml = None # depends on [control=['except'], data=[]] verify_results.append(VerifyResult(payload_c14n, payload_c14n_xml, signature)) # depends on [control=['for'], data=['reference']] if type(expect_references) is int and len(verify_results) != expect_references: msg = 'Expected to find {} references, but found {}' raise InvalidSignature(msg.format(expect_references, len(verify_results))) # depends on [control=['if'], data=[]] return verify_results if expect_references > 1 else verify_results[0]
def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): '''Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits''' assert start_hit.qry_name == end_hit.qry_name if start_hit.ref_name == end_hit.ref_name: return False if ( (self._is_at_ref_end(start_hit) and start_hit.on_same_strand()) or (self._is_at_ref_start(start_hit) and not start_hit.on_same_strand()) ): start_hit_ok = True else: start_hit_ok = False if ( (self._is_at_ref_start(end_hit) and end_hit.on_same_strand()) or (self._is_at_ref_end(end_hit) and not end_hit.on_same_strand()) ): end_hit_ok = True else: end_hit_ok = False return start_hit_ok and end_hit_ok
def function[_orientation_ok_to_bridge_contigs, parameter[self, start_hit, end_hit]]: constant[Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits] assert[compare[name[start_hit].qry_name equal[==] name[end_hit].qry_name]] if compare[name[start_hit].ref_name equal[==] name[end_hit].ref_name] begin[:] return[constant[False]] if <ast.BoolOp object at 0x7da18f720730> begin[:] variable[start_hit_ok] assign[=] constant[True] if <ast.BoolOp object at 0x7da18f723610> begin[:] variable[end_hit_ok] assign[=] constant[True] return[<ast.BoolOp object at 0x7da18f7210c0>]
keyword[def] identifier[_orientation_ok_to_bridge_contigs] ( identifier[self] , identifier[start_hit] , identifier[end_hit] ): literal[string] keyword[assert] identifier[start_hit] . identifier[qry_name] == identifier[end_hit] . identifier[qry_name] keyword[if] identifier[start_hit] . identifier[ref_name] == identifier[end_hit] . identifier[ref_name] : keyword[return] keyword[False] keyword[if] ( ( identifier[self] . identifier[_is_at_ref_end] ( identifier[start_hit] ) keyword[and] identifier[start_hit] . identifier[on_same_strand] ()) keyword[or] ( identifier[self] . identifier[_is_at_ref_start] ( identifier[start_hit] ) keyword[and] keyword[not] identifier[start_hit] . identifier[on_same_strand] ()) ): identifier[start_hit_ok] = keyword[True] keyword[else] : identifier[start_hit_ok] = keyword[False] keyword[if] ( ( identifier[self] . identifier[_is_at_ref_start] ( identifier[end_hit] ) keyword[and] identifier[end_hit] . identifier[on_same_strand] ()) keyword[or] ( identifier[self] . identifier[_is_at_ref_end] ( identifier[end_hit] ) keyword[and] keyword[not] identifier[end_hit] . identifier[on_same_strand] ()) ): identifier[end_hit_ok] = keyword[True] keyword[else] : identifier[end_hit_ok] = keyword[False] keyword[return] identifier[start_hit_ok] keyword[and] identifier[end_hit_ok]
def _orientation_ok_to_bridge_contigs(self, start_hit, end_hit): """Returns True iff the orientation of the hits means that the query contig of both hits can bridge the reference contigs of the hits""" assert start_hit.qry_name == end_hit.qry_name if start_hit.ref_name == end_hit.ref_name: return False # depends on [control=['if'], data=[]] if self._is_at_ref_end(start_hit) and start_hit.on_same_strand() or (self._is_at_ref_start(start_hit) and (not start_hit.on_same_strand())): start_hit_ok = True # depends on [control=['if'], data=[]] else: start_hit_ok = False if self._is_at_ref_start(end_hit) and end_hit.on_same_strand() or (self._is_at_ref_end(end_hit) and (not end_hit.on_same_strand())): end_hit_ok = True # depends on [control=['if'], data=[]] else: end_hit_ok = False return start_hit_ok and end_hit_ok
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int` """ min_arc = asin(((ball_diam + min_gap) / 2) / rolling_radius) * 2 return int((2 * pi) / min_arc)
def function[get_max_ballcount, parameter[cls, ball_diam, rolling_radius, min_gap]]: constant[ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int` ] variable[min_arc] assign[=] binary_operation[call[name[asin], parameter[binary_operation[binary_operation[binary_operation[name[ball_diam] + name[min_gap]] / constant[2]] / name[rolling_radius]]]] * constant[2]] return[call[name[int], parameter[binary_operation[binary_operation[constant[2] * name[pi]] / name[min_arc]]]]]
keyword[def] identifier[get_max_ballcount] ( identifier[cls] , identifier[ball_diam] , identifier[rolling_radius] , identifier[min_gap] = literal[int] ): literal[string] identifier[min_arc] = identifier[asin] ((( identifier[ball_diam] + identifier[min_gap] )/ literal[int] )/ identifier[rolling_radius] )* literal[int] keyword[return] identifier[int] (( literal[int] * identifier[pi] )/ identifier[min_arc] )
def get_max_ballcount(cls, ball_diam, rolling_radius, min_gap=0.0): """ The maximum number of balls given ``rolling_radius`` and ``ball_diam`` :param min_gap: minimum gap between balls (measured along vector between spherical centers) :type min_gap: :class:`float` :return: maximum ball count :rtype: :class:`int` """ min_arc = asin((ball_diam + min_gap) / 2 / rolling_radius) * 2 return int(2 * pi / min_arc)
def ctype(self): """Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. """ if self.dtype == "logical": return "C_BOOL" elif self.dtype == "complex": #We don't actually know what the precision of the complex numbers is because #it is defined by the developer when they construct the number with CMPLX() #We just return double to be safe; it is a widening conversion, so there #shouldn't be any issues. return "C_DOUBLE_COMPLEX" elif self.dtype == "character": return "C_CHAR" elif self.dtype in ["integer", "real"]: if self.kind is None: if self.dtype == "integer": return "C_INT" else: return "C_FLOAT" if self._kind_module is None and self.kind is not None: self.dependency() if self._kind_module is None and self.kind is not None: raise ValueError("Can't find the c-type for {}".format(self.definition())) elif self._kind_module is not None: #We look up the parameter in the kind module to find out its #precision etc. import re default = self._kind_module.members[self.kind].default vals = default.split("(")[1].replace(")", "") ints = list(map(int, re.split(",\s*", vals))) if self.dtype == "integer" and len(ints) == 1: if ints[0] <= 15: return "C_SHORT" elif ints[0] <= 31: return "C_INT" elif ints[0] <= 63: return "C_LONG" elif self.dtype == "real" and len(ints) == 2: if ints[0] <= 24 and ints[1] < 127: return "C_FLOAT" elif ints[0] <= 53 and ints[1] < 1023: return "C_DOUBLE"
def function[ctype, parameter[self]]: constant[Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. ] if compare[name[self].dtype equal[==] constant[logical]] begin[:] return[constant[C_BOOL]]
keyword[def] identifier[ctype] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[dtype] == literal[string] : keyword[return] literal[string] keyword[elif] identifier[self] . identifier[dtype] == literal[string] : keyword[return] literal[string] keyword[elif] identifier[self] . identifier[dtype] == literal[string] : keyword[return] literal[string] keyword[elif] identifier[self] . identifier[dtype] keyword[in] [ literal[string] , literal[string] ]: keyword[if] identifier[self] . identifier[kind] keyword[is] keyword[None] : keyword[if] identifier[self] . identifier[dtype] == literal[string] : keyword[return] literal[string] keyword[else] : keyword[return] literal[string] keyword[if] identifier[self] . identifier[_kind_module] keyword[is] keyword[None] keyword[and] identifier[self] . identifier[kind] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[dependency] () keyword[if] identifier[self] . identifier[_kind_module] keyword[is] keyword[None] keyword[and] identifier[self] . identifier[kind] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( identifier[self] . identifier[definition] ())) keyword[elif] identifier[self] . identifier[_kind_module] keyword[is] keyword[not] keyword[None] : keyword[import] identifier[re] identifier[default] = identifier[self] . identifier[_kind_module] . identifier[members] [ identifier[self] . identifier[kind] ]. identifier[default] identifier[vals] = identifier[default] . identifier[split] ( literal[string] )[ literal[int] ]. identifier[replace] ( literal[string] , literal[string] ) identifier[ints] = identifier[list] ( identifier[map] ( identifier[int] , identifier[re] . identifier[split] ( literal[string] , identifier[vals] ))) keyword[if] identifier[self] . identifier[dtype] == literal[string] keyword[and] identifier[len] ( identifier[ints] )== literal[int] : keyword[if] identifier[ints] [ literal[int] ]<= literal[int] : keyword[return] literal[string] keyword[elif] identifier[ints] [ literal[int] ]<= literal[int] : keyword[return] literal[string] keyword[elif] identifier[ints] [ literal[int] ]<= literal[int] : keyword[return] literal[string] keyword[elif] identifier[self] . identifier[dtype] == literal[string] keyword[and] identifier[len] ( identifier[ints] )== literal[int] : keyword[if] identifier[ints] [ literal[int] ]<= literal[int] keyword[and] identifier[ints] [ literal[int] ]< literal[int] : keyword[return] literal[string] keyword[elif] identifier[ints] [ literal[int] ]<= literal[int] keyword[and] identifier[ints] [ literal[int] ]< literal[int] : keyword[return] literal[string]
def ctype(self): """Returns the name of the c_type from iso_c_binding to use when declaring the output parameter for interaction with python ctypes. """ if self.dtype == 'logical': return 'C_BOOL' # depends on [control=['if'], data=[]] elif self.dtype == 'complex': #We don't actually know what the precision of the complex numbers is because #it is defined by the developer when they construct the number with CMPLX() #We just return double to be safe; it is a widening conversion, so there #shouldn't be any issues. return 'C_DOUBLE_COMPLEX' # depends on [control=['if'], data=[]] elif self.dtype == 'character': return 'C_CHAR' # depends on [control=['if'], data=[]] elif self.dtype in ['integer', 'real']: if self.kind is None: if self.dtype == 'integer': return 'C_INT' # depends on [control=['if'], data=[]] else: return 'C_FLOAT' # depends on [control=['if'], data=[]] if self._kind_module is None and self.kind is not None: self.dependency() # depends on [control=['if'], data=[]] if self._kind_module is None and self.kind is not None: raise ValueError("Can't find the c-type for {}".format(self.definition())) # depends on [control=['if'], data=[]] elif self._kind_module is not None: #We look up the parameter in the kind module to find out its #precision etc. import re default = self._kind_module.members[self.kind].default vals = default.split('(')[1].replace(')', '') ints = list(map(int, re.split(',\\s*', vals))) if self.dtype == 'integer' and len(ints) == 1: if ints[0] <= 15: return 'C_SHORT' # depends on [control=['if'], data=[]] elif ints[0] <= 31: return 'C_INT' # depends on [control=['if'], data=[]] elif ints[0] <= 63: return 'C_LONG' # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] elif self.dtype == 'real' and len(ints) == 2: if ints[0] <= 24 and ints[1] < 127: return 'C_FLOAT' # depends on [control=['if'], data=[]] elif ints[0] <= 53 and ints[1] < 1023: return 'C_DOUBLE' # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
def log_to_logger(fn): """ Wrap a Bottle request so that a log line is emitted after it's handled. """ @wraps(fn) def _log_to_logger(*args, **kwargs): actual_response = fn(*args, **kwargs) # modify this to log exactly what you need: logger.info('%s %s %s %s' % (bottle.request.remote_addr, bottle.request.method, bottle.request.url, bottle.response.status)) return actual_response return _log_to_logger
def function[log_to_logger, parameter[fn]]: constant[ Wrap a Bottle request so that a log line is emitted after it's handled. ] def function[_log_to_logger, parameter[]]: variable[actual_response] assign[=] call[name[fn], parameter[<ast.Starred object at 0x7da20c76cf40>]] call[name[logger].info, parameter[binary_operation[constant[%s %s %s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da20c794670>, <ast.Attribute object at 0x7da20c795960>, <ast.Attribute object at 0x7da20c794100>, <ast.Attribute object at 0x7da20c796680>]]]]] return[name[actual_response]] return[name[_log_to_logger]]
keyword[def] identifier[log_to_logger] ( identifier[fn] ): literal[string] @ identifier[wraps] ( identifier[fn] ) keyword[def] identifier[_log_to_logger] (* identifier[args] ,** identifier[kwargs] ): identifier[actual_response] = identifier[fn] (* identifier[args] ,** identifier[kwargs] ) identifier[logger] . identifier[info] ( literal[string] %( identifier[bottle] . identifier[request] . identifier[remote_addr] , identifier[bottle] . identifier[request] . identifier[method] , identifier[bottle] . identifier[request] . identifier[url] , identifier[bottle] . identifier[response] . identifier[status] )) keyword[return] identifier[actual_response] keyword[return] identifier[_log_to_logger]
def log_to_logger(fn): """ Wrap a Bottle request so that a log line is emitted after it's handled. """ @wraps(fn) def _log_to_logger(*args, **kwargs): actual_response = fn(*args, **kwargs) # modify this to log exactly what you need: logger.info('%s %s %s %s' % (bottle.request.remote_addr, bottle.request.method, bottle.request.url, bottle.response.status)) return actual_response return _log_to_logger
def read_dir(input_dir,input_ext,func): '''reads all files with extension input_ext in a directory input_dir and apply function func to their contents''' import os for dirpath, dnames, fnames in os.walk(input_dir): for fname in fnames: if not dirpath.endswith(os.sep): dirpath = dirpath + os.sep if fname.endswith(input_ext): func(read_file(dirpath + fname))
def function[read_dir, parameter[input_dir, input_ext, func]]: constant[reads all files with extension input_ext in a directory input_dir and apply function func to their contents] import module[os] for taget[tuple[[<ast.Name object at 0x7da1b0ab88e0>, <ast.Name object at 0x7da1b0aba770>, <ast.Name object at 0x7da1b0aba020>]]] in starred[call[name[os].walk, parameter[name[input_dir]]]] begin[:] for taget[name[fname]] in starred[name[fnames]] begin[:] if <ast.UnaryOp object at 0x7da1b0abb1c0> begin[:] variable[dirpath] assign[=] binary_operation[name[dirpath] + name[os].sep] if call[name[fname].endswith, parameter[name[input_ext]]] begin[:] call[name[func], parameter[call[name[read_file], parameter[binary_operation[name[dirpath] + name[fname]]]]]]
keyword[def] identifier[read_dir] ( identifier[input_dir] , identifier[input_ext] , identifier[func] ): literal[string] keyword[import] identifier[os] keyword[for] identifier[dirpath] , identifier[dnames] , identifier[fnames] keyword[in] identifier[os] . identifier[walk] ( identifier[input_dir] ): keyword[for] identifier[fname] keyword[in] identifier[fnames] : keyword[if] keyword[not] identifier[dirpath] . identifier[endswith] ( identifier[os] . identifier[sep] ): identifier[dirpath] = identifier[dirpath] + identifier[os] . identifier[sep] keyword[if] identifier[fname] . identifier[endswith] ( identifier[input_ext] ): identifier[func] ( identifier[read_file] ( identifier[dirpath] + identifier[fname] ))
def read_dir(input_dir, input_ext, func): """reads all files with extension input_ext in a directory input_dir and apply function func to their contents""" import os for (dirpath, dnames, fnames) in os.walk(input_dir): for fname in fnames: if not dirpath.endswith(os.sep): dirpath = dirpath + os.sep # depends on [control=['if'], data=[]] if fname.endswith(input_ext): func(read_file(dirpath + fname)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['fname']] # depends on [control=['for'], data=[]]
def gateways_info(): """Returns gateways data. """ data = netifaces.gateways() results = {'default': {}} with suppress(KeyError): results['ipv4'] = data[netifaces.AF_INET] results['default']['ipv4'] = data['default'][netifaces.AF_INET] with suppress(KeyError): results['ipv6'] = data[netifaces.AF_INET6] results['default']['ipv6'] = data['default'][netifaces.AF_INET6] return results
def function[gateways_info, parameter[]]: constant[Returns gateways data. ] variable[data] assign[=] call[name[netifaces].gateways, parameter[]] variable[results] assign[=] dictionary[[<ast.Constant object at 0x7da20cabf190>], [<ast.Dict object at 0x7da20cabece0>]] with call[name[suppress], parameter[name[KeyError]]] begin[:] call[name[results]][constant[ipv4]] assign[=] call[name[data]][name[netifaces].AF_INET] call[call[name[results]][constant[default]]][constant[ipv4]] assign[=] call[call[name[data]][constant[default]]][name[netifaces].AF_INET] with call[name[suppress], parameter[name[KeyError]]] begin[:] call[name[results]][constant[ipv6]] assign[=] call[name[data]][name[netifaces].AF_INET6] call[call[name[results]][constant[default]]][constant[ipv6]] assign[=] call[call[name[data]][constant[default]]][name[netifaces].AF_INET6] return[name[results]]
keyword[def] identifier[gateways_info] (): literal[string] identifier[data] = identifier[netifaces] . identifier[gateways] () identifier[results] ={ literal[string] :{}} keyword[with] identifier[suppress] ( identifier[KeyError] ): identifier[results] [ literal[string] ]= identifier[data] [ identifier[netifaces] . identifier[AF_INET] ] identifier[results] [ literal[string] ][ literal[string] ]= identifier[data] [ literal[string] ][ identifier[netifaces] . identifier[AF_INET] ] keyword[with] identifier[suppress] ( identifier[KeyError] ): identifier[results] [ literal[string] ]= identifier[data] [ identifier[netifaces] . identifier[AF_INET6] ] identifier[results] [ literal[string] ][ literal[string] ]= identifier[data] [ literal[string] ][ identifier[netifaces] . identifier[AF_INET6] ] keyword[return] identifier[results]
def gateways_info(): """Returns gateways data. """ data = netifaces.gateways() results = {'default': {}} with suppress(KeyError): results['ipv4'] = data[netifaces.AF_INET] results['default']['ipv4'] = data['default'][netifaces.AF_INET] # depends on [control=['with'], data=[]] with suppress(KeyError): results['ipv6'] = data[netifaces.AF_INET6] results['default']['ipv6'] = data['default'][netifaces.AF_INET6] # depends on [control=['with'], data=[]] return results
def init_package(path=None, name='manage'): """Initialize (import) the submodules, and recursively the subpackages, of a "manage" package at ``path``. ``path`` may be specified as either a system directory path or a list of these. If ``path`` is unspecified, it is inferred from the already-imported "manage" top-level module. """ if path is None: manager = sys.modules[name] init_package(manager.__path__, name) return if isinstance(path, str): init_package([path], name) return for module_info in pkgutil.walk_packages(path, f'{name}.'): if not module_info.ispkg: importlib.import_module(module_info.name)
def function[init_package, parameter[path, name]]: constant[Initialize (import) the submodules, and recursively the subpackages, of a "manage" package at ``path``. ``path`` may be specified as either a system directory path or a list of these. If ``path`` is unspecified, it is inferred from the already-imported "manage" top-level module. ] if compare[name[path] is constant[None]] begin[:] variable[manager] assign[=] call[name[sys].modules][name[name]] call[name[init_package], parameter[name[manager].__path__, name[name]]] return[None] if call[name[isinstance], parameter[name[path], name[str]]] begin[:] call[name[init_package], parameter[list[[<ast.Name object at 0x7da18c4cea40>]], name[name]]] return[None] for taget[name[module_info]] in starred[call[name[pkgutil].walk_packages, parameter[name[path], <ast.JoinedStr object at 0x7da18c4ced70>]]] begin[:] if <ast.UnaryOp object at 0x7da18c4cf6a0> begin[:] call[name[importlib].import_module, parameter[name[module_info].name]]
keyword[def] identifier[init_package] ( identifier[path] = keyword[None] , identifier[name] = literal[string] ): literal[string] keyword[if] identifier[path] keyword[is] keyword[None] : identifier[manager] = identifier[sys] . identifier[modules] [ identifier[name] ] identifier[init_package] ( identifier[manager] . identifier[__path__] , identifier[name] ) keyword[return] keyword[if] identifier[isinstance] ( identifier[path] , identifier[str] ): identifier[init_package] ([ identifier[path] ], identifier[name] ) keyword[return] keyword[for] identifier[module_info] keyword[in] identifier[pkgutil] . identifier[walk_packages] ( identifier[path] , literal[string] ): keyword[if] keyword[not] identifier[module_info] . identifier[ispkg] : identifier[importlib] . identifier[import_module] ( identifier[module_info] . identifier[name] )
def init_package(path=None, name='manage'): """Initialize (import) the submodules, and recursively the subpackages, of a "manage" package at ``path``. ``path`` may be specified as either a system directory path or a list of these. If ``path`` is unspecified, it is inferred from the already-imported "manage" top-level module. """ if path is None: manager = sys.modules[name] init_package(manager.__path__, name) return # depends on [control=['if'], data=[]] if isinstance(path, str): init_package([path], name) return # depends on [control=['if'], data=[]] for module_info in pkgutil.walk_packages(path, f'{name}.'): if not module_info.ispkg: importlib.import_module(module_info.name) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['module_info']]
def run(job_ini, slowest=False, hc=None, param='', concurrent_tasks=None, exports='', loglevel='info', pdb=None): """ Run a calculation bypassing the database layer """ dbserver.ensure_on() if param: params = oqvalidation.OqParam.check( dict(p.split('=', 1) for p in param.split(','))) else: params = {} if slowest: prof = cProfile.Profile() stmt = ('_run(job_ini, concurrent_tasks, pdb, loglevel, hc, ' 'exports, params)') prof.runctx(stmt, globals(), locals()) pstat = calc_path + '.pstat' prof.dump_stats(pstat) print('Saved profiling info in %s' % pstat) print(get_pstats(pstat, slowest)) else: _run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params)
def function[run, parameter[job_ini, slowest, hc, param, concurrent_tasks, exports, loglevel, pdb]]: constant[ Run a calculation bypassing the database layer ] call[name[dbserver].ensure_on, parameter[]] if name[param] begin[:] variable[params] assign[=] call[name[oqvalidation].OqParam.check, parameter[call[name[dict], parameter[<ast.GeneratorExp object at 0x7da18f00c370>]]]] if name[slowest] begin[:] variable[prof] assign[=] call[name[cProfile].Profile, parameter[]] variable[stmt] assign[=] constant[_run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params)] call[name[prof].runctx, parameter[name[stmt], call[name[globals], parameter[]], call[name[locals], parameter[]]]] variable[pstat] assign[=] binary_operation[name[calc_path] + constant[.pstat]] call[name[prof].dump_stats, parameter[name[pstat]]] call[name[print], parameter[binary_operation[constant[Saved profiling info in %s] <ast.Mod object at 0x7da2590d6920> name[pstat]]]] call[name[print], parameter[call[name[get_pstats], parameter[name[pstat], name[slowest]]]]]
keyword[def] identifier[run] ( identifier[job_ini] , identifier[slowest] = keyword[False] , identifier[hc] = keyword[None] , identifier[param] = literal[string] , identifier[concurrent_tasks] = keyword[None] , identifier[exports] = literal[string] , identifier[loglevel] = literal[string] , identifier[pdb] = keyword[None] ): literal[string] identifier[dbserver] . identifier[ensure_on] () keyword[if] identifier[param] : identifier[params] = identifier[oqvalidation] . identifier[OqParam] . identifier[check] ( identifier[dict] ( identifier[p] . identifier[split] ( literal[string] , literal[int] ) keyword[for] identifier[p] keyword[in] identifier[param] . identifier[split] ( literal[string] ))) keyword[else] : identifier[params] ={} keyword[if] identifier[slowest] : identifier[prof] = identifier[cProfile] . identifier[Profile] () identifier[stmt] =( literal[string] literal[string] ) identifier[prof] . identifier[runctx] ( identifier[stmt] , identifier[globals] (), identifier[locals] ()) identifier[pstat] = identifier[calc_path] + literal[string] identifier[prof] . identifier[dump_stats] ( identifier[pstat] ) identifier[print] ( literal[string] % identifier[pstat] ) identifier[print] ( identifier[get_pstats] ( identifier[pstat] , identifier[slowest] )) keyword[else] : identifier[_run] ( identifier[job_ini] , identifier[concurrent_tasks] , identifier[pdb] , identifier[loglevel] , identifier[hc] , identifier[exports] , identifier[params] )
def run(job_ini, slowest=False, hc=None, param='', concurrent_tasks=None, exports='', loglevel='info', pdb=None): """ Run a calculation bypassing the database layer """ dbserver.ensure_on() if param: params = oqvalidation.OqParam.check(dict((p.split('=', 1) for p in param.split(',')))) # depends on [control=['if'], data=[]] else: params = {} if slowest: prof = cProfile.Profile() stmt = '_run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params)' prof.runctx(stmt, globals(), locals()) pstat = calc_path + '.pstat' prof.dump_stats(pstat) print('Saved profiling info in %s' % pstat) print(get_pstats(pstat, slowest)) # depends on [control=['if'], data=[]] else: _run(job_ini, concurrent_tasks, pdb, loglevel, hc, exports, params)
def update(self, job_id, sql_query): """ Updates the sql query of a specific job :param job_id: The id of the job to be updated :param sql_query: The new SQL query for the job :type job_id: str :type sql_query: str :return: Response data, either as json or as a regular response.content object :rtype: object :raise: CartoException """ header = {'content-type': 'application/json'} data = self.send(self.api_url + job_id, http_method="PUT", json_body={"query": sql_query}, http_header=header) return data
def function[update, parameter[self, job_id, sql_query]]: constant[ Updates the sql query of a specific job :param job_id: The id of the job to be updated :param sql_query: The new SQL query for the job :type job_id: str :type sql_query: str :return: Response data, either as json or as a regular response.content object :rtype: object :raise: CartoException ] variable[header] assign[=] dictionary[[<ast.Constant object at 0x7da1b0f18ee0>], [<ast.Constant object at 0x7da1b0f185e0>]] variable[data] assign[=] call[name[self].send, parameter[binary_operation[name[self].api_url + name[job_id]]]] return[name[data]]
keyword[def] identifier[update] ( identifier[self] , identifier[job_id] , identifier[sql_query] ): literal[string] identifier[header] ={ literal[string] : literal[string] } identifier[data] = identifier[self] . identifier[send] ( identifier[self] . identifier[api_url] + identifier[job_id] , identifier[http_method] = literal[string] , identifier[json_body] ={ literal[string] : identifier[sql_query] }, identifier[http_header] = identifier[header] ) keyword[return] identifier[data]
def update(self, job_id, sql_query): """ Updates the sql query of a specific job :param job_id: The id of the job to be updated :param sql_query: The new SQL query for the job :type job_id: str :type sql_query: str :return: Response data, either as json or as a regular response.content object :rtype: object :raise: CartoException """ header = {'content-type': 'application/json'} data = self.send(self.api_url + job_id, http_method='PUT', json_body={'query': sql_query}, http_header=header) return data
def clear(self) -> None: """ Clear the cache. """ LOGGER.debug('SchemaCache.clear >>>') self._schema_key2schema = {} self._seq_no2schema_key = {} LOGGER.debug('SchemaCache.clear <<<')
def function[clear, parameter[self]]: constant[ Clear the cache. ] call[name[LOGGER].debug, parameter[constant[SchemaCache.clear >>>]]] name[self]._schema_key2schema assign[=] dictionary[[], []] name[self]._seq_no2schema_key assign[=] dictionary[[], []] call[name[LOGGER].debug, parameter[constant[SchemaCache.clear <<<]]]
keyword[def] identifier[clear] ( identifier[self] )-> keyword[None] : literal[string] identifier[LOGGER] . identifier[debug] ( literal[string] ) identifier[self] . identifier[_schema_key2schema] ={} identifier[self] . identifier[_seq_no2schema_key] ={} identifier[LOGGER] . identifier[debug] ( literal[string] )
def clear(self) -> None: """ Clear the cache. """ LOGGER.debug('SchemaCache.clear >>>') self._schema_key2schema = {} self._seq_no2schema_key = {} LOGGER.debug('SchemaCache.clear <<<')
def generate(env): """Add Builders and construction variables for javah to an Environment.""" java_javah = SCons.Tool.CreateJavaHBuilder(env) java_javah.emitter = emit_java_headers env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator env['JAVAH'] = 'javah' env['JAVAHFLAGS'] = SCons.Util.CLVar('') env['_JAVAHCLASSPATH'] = getJavaHClassPath env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}' env['JAVACLASSSUFFIX'] = '.class'
def function[generate, parameter[env]]: constant[Add Builders and construction variables for javah to an Environment.] variable[java_javah] assign[=] call[name[SCons].Tool.CreateJavaHBuilder, parameter[name[env]]] name[java_javah].emitter assign[=] name[emit_java_headers] call[name[env]][constant[_JAVAHOUTFLAG]] assign[=] name[JavaHOutFlagGenerator] call[name[env]][constant[JAVAH]] assign[=] constant[javah] call[name[env]][constant[JAVAHFLAGS]] assign[=] call[name[SCons].Util.CLVar, parameter[constant[]]] call[name[env]][constant[_JAVAHCLASSPATH]] assign[=] name[getJavaHClassPath] call[name[env]][constant[JAVAHCOM]] assign[=] constant[$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}] call[name[env]][constant[JAVACLASSSUFFIX]] assign[=] constant[.class]
keyword[def] identifier[generate] ( identifier[env] ): literal[string] identifier[java_javah] = identifier[SCons] . identifier[Tool] . identifier[CreateJavaHBuilder] ( identifier[env] ) identifier[java_javah] . identifier[emitter] = identifier[emit_java_headers] identifier[env] [ literal[string] ]= identifier[JavaHOutFlagGenerator] identifier[env] [ literal[string] ]= literal[string] identifier[env] [ literal[string] ]= identifier[SCons] . identifier[Util] . identifier[CLVar] ( literal[string] ) identifier[env] [ literal[string] ]= identifier[getJavaHClassPath] identifier[env] [ literal[string] ]= literal[string] identifier[env] [ literal[string] ]= literal[string]
def generate(env): """Add Builders and construction variables for javah to an Environment.""" java_javah = SCons.Tool.CreateJavaHBuilder(env) java_javah.emitter = emit_java_headers env['_JAVAHOUTFLAG'] = JavaHOutFlagGenerator env['JAVAH'] = 'javah' env['JAVAHFLAGS'] = SCons.Util.CLVar('') env['_JAVAHCLASSPATH'] = getJavaHClassPath env['JAVAHCOM'] = '$JAVAH $JAVAHFLAGS $_JAVAHOUTFLAG $_JAVAHCLASSPATH ${SOURCES.attributes.java_classname}' env['JAVACLASSSUFFIX'] = '.class'
def start_site(name): ''' Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site' ''' ps_cmd = ['Start-WebSite', r"'{0}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return cmd_ret['retcode'] == 0
def function[start_site, parameter[name]]: constant[ Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site' ] variable[ps_cmd] assign[=] list[[<ast.Constant object at 0x7da1b2136a70>, <ast.Call object at 0x7da1b2135090>]] variable[cmd_ret] assign[=] call[name[_srvmgr], parameter[name[ps_cmd]]] return[compare[call[name[cmd_ret]][constant[retcode]] equal[==] constant[0]]]
keyword[def] identifier[start_site] ( identifier[name] ): literal[string] identifier[ps_cmd] =[ literal[string] , literal[string] . identifier[format] ( identifier[name] )] identifier[cmd_ret] = identifier[_srvmgr] ( identifier[ps_cmd] ) keyword[return] identifier[cmd_ret] [ literal[string] ]== literal[int]
def start_site(name): """ Start a Web Site in IIS. .. versionadded:: 2017.7.0 Args: name (str): The name of the website to start. Returns: bool: True if successful, otherwise False CLI Example: .. code-block:: bash salt '*' win_iis.start_site name='My Test Site' """ ps_cmd = ['Start-WebSite', "'{0}'".format(name)] cmd_ret = _srvmgr(ps_cmd) return cmd_ret['retcode'] == 0
def autorange(self, analyte='total_counts', gwin=5, swin=3, win=30, on_mult=[1., 1.], off_mult=[1., 1.5], ploterrs=True, transform='log', **kwargs): """ Automatically separates signal and background data regions. Automatically detect signal and background regions in the laser data, based on the behaviour of a single analyte. The analyte used should be abundant and homogenous in the sample. **Step 1: Thresholding.** The background signal is determined using a gaussian kernel density estimator (kde) of all the data. Under normal circumstances, this kde should find two distinct data distributions, corresponding to 'signal' and 'background'. The minima between these two distributions is taken as a rough threshold to identify signal and background regions. Any point where the trace crosses this thrshold is identified as a 'transition'. **Step 2: Transition Removal.** The width of the transition regions between signal and background are then determined, and the transitions are excluded from analysis. The width of the transitions is determined by fitting a gaussian to the smoothed first derivative of the analyte trace, and determining its width at a point where the gaussian intensity is at at `conf` time the gaussian maximum. These gaussians are fit to subsets of the data centered around the transitions regions determined in Step 1, +/- `win` data points. The peak is further isolated by finding the minima and maxima of a second derivative within this window, and the gaussian is fit to the isolated peak. Parameters ---------- analyte : str The analyte that autorange should consider. For best results, choose an analyte that is present homogeneously in high concentrations. gwin : int The smoothing window used for calculating the first derivative. Must be odd. win : int Determines the width (c +/- win) of the transition data subsets. on_mult and off_mult : tuple, len=2 Factors to control the width of the excluded transition regions. A region n times the full - width - half - maximum of the transition gradient will be removed either side of the transition center. `on_mult` and `off_mult` refer to the laser - on and laser - off transitions, respectively. See manual for full explanation. Defaults to (1.5, 1) and (1, 1.5). Returns ------- Outputs added as instance attributes. Returns None. bkg, sig, trn : iterable, bool Boolean arrays identifying background, signal and transision regions bkgrng, sigrng and trnrng : iterable (min, max) pairs identifying the boundaries of contiguous True regions in the boolean arrays. """ if analyte is None: # sig = self.focus[self.internal_standard] sig = self.data['total_counts'] elif analyte == 'total_counts': sig = self.data['total_counts'] elif analyte in self.analytes: sig = self.focus[analyte] else: raise ValueError('Invalid analyte.') (self.bkg, self.sig, self.trn, failed) = proc.autorange(self.Time, sig, gwin=gwin, swin=swin, win=win, on_mult=on_mult, off_mult=off_mult, transform=transform) self.mkrngs() errs_to_plot = False if len(failed) > 0: errs_to_plot = True plotlines = [] for f in failed: if f != self.Time[-1]: plotlines.append(f) # warnings.warn(("\n\nSample {:s}: ".format(self.sample) + # "Transition identification at " + # "{:.1f} failed.".format(f) + # "\n **This is not necessarily a problem**" # "\nBut please check the data plots and make sure " + # "everything is OK.\n")) if ploterrs and errs_to_plot and len(plotlines) > 0: f, ax = self.tplot(ranges=True) for pl in plotlines: ax.axvline(pl, c='r', alpha=0.6, lw=3, ls='dashed') return f, plotlines else: return
def function[autorange, parameter[self, analyte, gwin, swin, win, on_mult, off_mult, ploterrs, transform]]: constant[ Automatically separates signal and background data regions. Automatically detect signal and background regions in the laser data, based on the behaviour of a single analyte. The analyte used should be abundant and homogenous in the sample. **Step 1: Thresholding.** The background signal is determined using a gaussian kernel density estimator (kde) of all the data. Under normal circumstances, this kde should find two distinct data distributions, corresponding to 'signal' and 'background'. The minima between these two distributions is taken as a rough threshold to identify signal and background regions. Any point where the trace crosses this thrshold is identified as a 'transition'. **Step 2: Transition Removal.** The width of the transition regions between signal and background are then determined, and the transitions are excluded from analysis. The width of the transitions is determined by fitting a gaussian to the smoothed first derivative of the analyte trace, and determining its width at a point where the gaussian intensity is at at `conf` time the gaussian maximum. These gaussians are fit to subsets of the data centered around the transitions regions determined in Step 1, +/- `win` data points. The peak is further isolated by finding the minima and maxima of a second derivative within this window, and the gaussian is fit to the isolated peak. Parameters ---------- analyte : str The analyte that autorange should consider. For best results, choose an analyte that is present homogeneously in high concentrations. gwin : int The smoothing window used for calculating the first derivative. Must be odd. win : int Determines the width (c +/- win) of the transition data subsets. on_mult and off_mult : tuple, len=2 Factors to control the width of the excluded transition regions. A region n times the full - width - half - maximum of the transition gradient will be removed either side of the transition center. `on_mult` and `off_mult` refer to the laser - on and laser - off transitions, respectively. See manual for full explanation. Defaults to (1.5, 1) and (1, 1.5). Returns ------- Outputs added as instance attributes. Returns None. bkg, sig, trn : iterable, bool Boolean arrays identifying background, signal and transision regions bkgrng, sigrng and trnrng : iterable (min, max) pairs identifying the boundaries of contiguous True regions in the boolean arrays. ] if compare[name[analyte] is constant[None]] begin[:] variable[sig] assign[=] call[name[self].data][constant[total_counts]] <ast.Tuple object at 0x7da1b026d150> assign[=] call[name[proc].autorange, parameter[name[self].Time, name[sig]]] call[name[self].mkrngs, parameter[]] variable[errs_to_plot] assign[=] constant[False] if compare[call[name[len], parameter[name[failed]]] greater[>] constant[0]] begin[:] variable[errs_to_plot] assign[=] constant[True] variable[plotlines] assign[=] list[[]] for taget[name[f]] in starred[name[failed]] begin[:] if compare[name[f] not_equal[!=] call[name[self].Time][<ast.UnaryOp object at 0x7da1b026dc30>]] begin[:] call[name[plotlines].append, parameter[name[f]]] if <ast.BoolOp object at 0x7da1b026cac0> begin[:] <ast.Tuple object at 0x7da1b026e860> assign[=] call[name[self].tplot, parameter[]] for taget[name[pl]] in starred[name[plotlines]] begin[:] call[name[ax].axvline, parameter[name[pl]]] return[tuple[[<ast.Name object at 0x7da1b026eb30>, <ast.Name object at 0x7da1b026ea70>]]]
keyword[def] identifier[autorange] ( identifier[self] , identifier[analyte] = literal[string] , identifier[gwin] = literal[int] , identifier[swin] = literal[int] , identifier[win] = literal[int] , identifier[on_mult] =[ literal[int] , literal[int] ], identifier[off_mult] =[ literal[int] , literal[int] ], identifier[ploterrs] = keyword[True] , identifier[transform] = literal[string] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[analyte] keyword[is] keyword[None] : identifier[sig] = identifier[self] . identifier[data] [ literal[string] ] keyword[elif] identifier[analyte] == literal[string] : identifier[sig] = identifier[self] . identifier[data] [ literal[string] ] keyword[elif] identifier[analyte] keyword[in] identifier[self] . identifier[analytes] : identifier[sig] = identifier[self] . identifier[focus] [ identifier[analyte] ] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) ( identifier[self] . identifier[bkg] , identifier[self] . identifier[sig] , identifier[self] . identifier[trn] , identifier[failed] )= identifier[proc] . identifier[autorange] ( identifier[self] . identifier[Time] , identifier[sig] , identifier[gwin] = identifier[gwin] , identifier[swin] = identifier[swin] , identifier[win] = identifier[win] , identifier[on_mult] = identifier[on_mult] , identifier[off_mult] = identifier[off_mult] , identifier[transform] = identifier[transform] ) identifier[self] . identifier[mkrngs] () identifier[errs_to_plot] = keyword[False] keyword[if] identifier[len] ( identifier[failed] )> literal[int] : identifier[errs_to_plot] = keyword[True] identifier[plotlines] =[] keyword[for] identifier[f] keyword[in] identifier[failed] : keyword[if] identifier[f] != identifier[self] . identifier[Time] [- literal[int] ]: identifier[plotlines] . identifier[append] ( identifier[f] ) keyword[if] identifier[ploterrs] keyword[and] identifier[errs_to_plot] keyword[and] identifier[len] ( identifier[plotlines] )> literal[int] : identifier[f] , identifier[ax] = identifier[self] . identifier[tplot] ( identifier[ranges] = keyword[True] ) keyword[for] identifier[pl] keyword[in] identifier[plotlines] : identifier[ax] . identifier[axvline] ( identifier[pl] , identifier[c] = literal[string] , identifier[alpha] = literal[int] , identifier[lw] = literal[int] , identifier[ls] = literal[string] ) keyword[return] identifier[f] , identifier[plotlines] keyword[else] : keyword[return]
def autorange(self, analyte='total_counts', gwin=5, swin=3, win=30, on_mult=[1.0, 1.0], off_mult=[1.0, 1.5], ploterrs=True, transform='log', **kwargs): """ Automatically separates signal and background data regions. Automatically detect signal and background regions in the laser data, based on the behaviour of a single analyte. The analyte used should be abundant and homogenous in the sample. **Step 1: Thresholding.** The background signal is determined using a gaussian kernel density estimator (kde) of all the data. Under normal circumstances, this kde should find two distinct data distributions, corresponding to 'signal' and 'background'. The minima between these two distributions is taken as a rough threshold to identify signal and background regions. Any point where the trace crosses this thrshold is identified as a 'transition'. **Step 2: Transition Removal.** The width of the transition regions between signal and background are then determined, and the transitions are excluded from analysis. The width of the transitions is determined by fitting a gaussian to the smoothed first derivative of the analyte trace, and determining its width at a point where the gaussian intensity is at at `conf` time the gaussian maximum. These gaussians are fit to subsets of the data centered around the transitions regions determined in Step 1, +/- `win` data points. The peak is further isolated by finding the minima and maxima of a second derivative within this window, and the gaussian is fit to the isolated peak. Parameters ---------- analyte : str The analyte that autorange should consider. For best results, choose an analyte that is present homogeneously in high concentrations. gwin : int The smoothing window used for calculating the first derivative. Must be odd. win : int Determines the width (c +/- win) of the transition data subsets. on_mult and off_mult : tuple, len=2 Factors to control the width of the excluded transition regions. A region n times the full - width - half - maximum of the transition gradient will be removed either side of the transition center. `on_mult` and `off_mult` refer to the laser - on and laser - off transitions, respectively. See manual for full explanation. Defaults to (1.5, 1) and (1, 1.5). Returns ------- Outputs added as instance attributes. Returns None. bkg, sig, trn : iterable, bool Boolean arrays identifying background, signal and transision regions bkgrng, sigrng and trnrng : iterable (min, max) pairs identifying the boundaries of contiguous True regions in the boolean arrays. """ if analyte is None: # sig = self.focus[self.internal_standard] sig = self.data['total_counts'] # depends on [control=['if'], data=[]] elif analyte == 'total_counts': sig = self.data['total_counts'] # depends on [control=['if'], data=[]] elif analyte in self.analytes: sig = self.focus[analyte] # depends on [control=['if'], data=['analyte']] else: raise ValueError('Invalid analyte.') (self.bkg, self.sig, self.trn, failed) = proc.autorange(self.Time, sig, gwin=gwin, swin=swin, win=win, on_mult=on_mult, off_mult=off_mult, transform=transform) self.mkrngs() errs_to_plot = False if len(failed) > 0: errs_to_plot = True plotlines = [] for f in failed: if f != self.Time[-1]: plotlines.append(f) # depends on [control=['if'], data=['f']] # depends on [control=['for'], data=['f']] # depends on [control=['if'], data=[]] # warnings.warn(("\n\nSample {:s}: ".format(self.sample) + # "Transition identification at " + # "{:.1f} failed.".format(f) + # "\n **This is not necessarily a problem**" # "\nBut please check the data plots and make sure " + # "everything is OK.\n")) if ploterrs and errs_to_plot and (len(plotlines) > 0): (f, ax) = self.tplot(ranges=True) for pl in plotlines: ax.axvline(pl, c='r', alpha=0.6, lw=3, ls='dashed') # depends on [control=['for'], data=['pl']] return (f, plotlines) # depends on [control=['if'], data=[]] else: return
def f1Measure(self, label=None): """ Returns f1Measure or f1Measure for a given label (category) if specified. """ if label is None: return self.call("f1Measure") else: return self.call("f1Measure", float(label))
def function[f1Measure, parameter[self, label]]: constant[ Returns f1Measure or f1Measure for a given label (category) if specified. ] if compare[name[label] is constant[None]] begin[:] return[call[name[self].call, parameter[constant[f1Measure]]]]
keyword[def] identifier[f1Measure] ( identifier[self] , identifier[label] = keyword[None] ): literal[string] keyword[if] identifier[label] keyword[is] keyword[None] : keyword[return] identifier[self] . identifier[call] ( literal[string] ) keyword[else] : keyword[return] identifier[self] . identifier[call] ( literal[string] , identifier[float] ( identifier[label] ))
def f1Measure(self, label=None): """ Returns f1Measure or f1Measure for a given label (category) if specified. """ if label is None: return self.call('f1Measure') # depends on [control=['if'], data=[]] else: return self.call('f1Measure', float(label))
def _update_ctx(self, attrs): """ Update the state of the Styler. Collects a mapping of {index_label: ['<property>: <value>']}. attrs : Series or DataFrame should contain strings of '<property>: <value>;<prop2>: <val2>' Whitespace shouldn't matter and the final trailing ';' shouldn't matter. """ for row_label, v in attrs.iterrows(): for col_label, col in v.iteritems(): i = self.index.get_indexer([row_label])[0] j = self.columns.get_indexer([col_label])[0] for pair in col.rstrip(";").split(";"): self.ctx[(i, j)].append(pair)
def function[_update_ctx, parameter[self, attrs]]: constant[ Update the state of the Styler. Collects a mapping of {index_label: ['<property>: <value>']}. attrs : Series or DataFrame should contain strings of '<property>: <value>;<prop2>: <val2>' Whitespace shouldn't matter and the final trailing ';' shouldn't matter. ] for taget[tuple[[<ast.Name object at 0x7da18f00f490>, <ast.Name object at 0x7da18f00f610>]]] in starred[call[name[attrs].iterrows, parameter[]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da18f00c9d0>, <ast.Name object at 0x7da18f00c2b0>]]] in starred[call[name[v].iteritems, parameter[]]] begin[:] variable[i] assign[=] call[call[name[self].index.get_indexer, parameter[list[[<ast.Name object at 0x7da18f00c8e0>]]]]][constant[0]] variable[j] assign[=] call[call[name[self].columns.get_indexer, parameter[list[[<ast.Name object at 0x7da18f00dea0>]]]]][constant[0]] for taget[name[pair]] in starred[call[call[name[col].rstrip, parameter[constant[;]]].split, parameter[constant[;]]]] begin[:] call[call[name[self].ctx][tuple[[<ast.Name object at 0x7da1b2029240>, <ast.Name object at 0x7da1b2029c90>]]].append, parameter[name[pair]]]
keyword[def] identifier[_update_ctx] ( identifier[self] , identifier[attrs] ): literal[string] keyword[for] identifier[row_label] , identifier[v] keyword[in] identifier[attrs] . identifier[iterrows] (): keyword[for] identifier[col_label] , identifier[col] keyword[in] identifier[v] . identifier[iteritems] (): identifier[i] = identifier[self] . identifier[index] . identifier[get_indexer] ([ identifier[row_label] ])[ literal[int] ] identifier[j] = identifier[self] . identifier[columns] . identifier[get_indexer] ([ identifier[col_label] ])[ literal[int] ] keyword[for] identifier[pair] keyword[in] identifier[col] . identifier[rstrip] ( literal[string] ). identifier[split] ( literal[string] ): identifier[self] . identifier[ctx] [( identifier[i] , identifier[j] )]. identifier[append] ( identifier[pair] )
def _update_ctx(self, attrs): """ Update the state of the Styler. Collects a mapping of {index_label: ['<property>: <value>']}. attrs : Series or DataFrame should contain strings of '<property>: <value>;<prop2>: <val2>' Whitespace shouldn't matter and the final trailing ';' shouldn't matter. """ for (row_label, v) in attrs.iterrows(): for (col_label, col) in v.iteritems(): i = self.index.get_indexer([row_label])[0] j = self.columns.get_indexer([col_label])[0] for pair in col.rstrip(';').split(';'): self.ctx[i, j].append(pair) # depends on [control=['for'], data=['pair']] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]]
def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): """Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items :param enrich_backend: backend to access enriched items :param retention_time: maximum number of minutes wrt the current date to retain the data :param studies_args: list of studies to be executed """ for study in enrich_backend.studies: selected_studies = [(s['name'], s['params']) for s in studies_args if s['type'] == study.__name__] for (name, params) in selected_studies: logger.info("Starting study: %s, params %s", name, str(params)) try: study(ocean_backend, enrich_backend, **params) except Exception as e: logger.error("Problem executing study %s, %s", name, str(e)) raise e # identify studies which creates other indexes. If the study is onion, # it can be ignored since the index is recreated every week if name.startswith('enrich_onion'): continue index_params = [p for p in params if 'out_index' in p] for ip in index_params: index_name = params[ip] elastic = get_elastic(enrich_backend.elastic_url, index_name) elastic.delete_items(retention_time)
def function[do_studies, parameter[ocean_backend, enrich_backend, studies_args, retention_time]]: constant[Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items :param enrich_backend: backend to access enriched items :param retention_time: maximum number of minutes wrt the current date to retain the data :param studies_args: list of studies to be executed ] for taget[name[study]] in starred[name[enrich_backend].studies] begin[:] variable[selected_studies] assign[=] <ast.ListComp object at 0x7da1b0f18ac0> for taget[tuple[[<ast.Name object at 0x7da1b0f183a0>, <ast.Name object at 0x7da1b0f18790>]]] in starred[name[selected_studies]] begin[:] call[name[logger].info, parameter[constant[Starting study: %s, params %s], name[name], call[name[str], parameter[name[params]]]]] <ast.Try object at 0x7da1b0f18670> if call[name[name].startswith, parameter[constant[enrich_onion]]] begin[:] continue variable[index_params] assign[=] <ast.ListComp object at 0x7da1b0d180a0> for taget[name[ip]] in starred[name[index_params]] begin[:] variable[index_name] assign[=] call[name[params]][name[ip]] variable[elastic] assign[=] call[name[get_elastic], parameter[name[enrich_backend].elastic_url, name[index_name]]] call[name[elastic].delete_items, parameter[name[retention_time]]]
keyword[def] identifier[do_studies] ( identifier[ocean_backend] , identifier[enrich_backend] , identifier[studies_args] , identifier[retention_time] = keyword[None] ): literal[string] keyword[for] identifier[study] keyword[in] identifier[enrich_backend] . identifier[studies] : identifier[selected_studies] =[( identifier[s] [ literal[string] ], identifier[s] [ literal[string] ]) keyword[for] identifier[s] keyword[in] identifier[studies_args] keyword[if] identifier[s] [ literal[string] ]== identifier[study] . identifier[__name__] ] keyword[for] ( identifier[name] , identifier[params] ) keyword[in] identifier[selected_studies] : identifier[logger] . identifier[info] ( literal[string] , identifier[name] , identifier[str] ( identifier[params] )) keyword[try] : identifier[study] ( identifier[ocean_backend] , identifier[enrich_backend] ,** identifier[params] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[logger] . identifier[error] ( literal[string] , identifier[name] , identifier[str] ( identifier[e] )) keyword[raise] identifier[e] keyword[if] identifier[name] . identifier[startswith] ( literal[string] ): keyword[continue] identifier[index_params] =[ identifier[p] keyword[for] identifier[p] keyword[in] identifier[params] keyword[if] literal[string] keyword[in] identifier[p] ] keyword[for] identifier[ip] keyword[in] identifier[index_params] : identifier[index_name] = identifier[params] [ identifier[ip] ] identifier[elastic] = identifier[get_elastic] ( identifier[enrich_backend] . identifier[elastic_url] , identifier[index_name] ) identifier[elastic] . identifier[delete_items] ( identifier[retention_time] )
def do_studies(ocean_backend, enrich_backend, studies_args, retention_time=None): """Execute studies related to a given enrich backend. If `retention_time` is not None, the study data is deleted based on the number of minutes declared in `retention_time`. :param ocean_backend: backend to access raw items :param enrich_backend: backend to access enriched items :param retention_time: maximum number of minutes wrt the current date to retain the data :param studies_args: list of studies to be executed """ for study in enrich_backend.studies: selected_studies = [(s['name'], s['params']) for s in studies_args if s['type'] == study.__name__] for (name, params) in selected_studies: logger.info('Starting study: %s, params %s', name, str(params)) try: study(ocean_backend, enrich_backend, **params) # depends on [control=['try'], data=[]] except Exception as e: logger.error('Problem executing study %s, %s', name, str(e)) raise e # depends on [control=['except'], data=['e']] # identify studies which creates other indexes. If the study is onion, # it can be ignored since the index is recreated every week if name.startswith('enrich_onion'): continue # depends on [control=['if'], data=[]] index_params = [p for p in params if 'out_index' in p] for ip in index_params: index_name = params[ip] elastic = get_elastic(enrich_backend.elastic_url, index_name) elastic.delete_items(retention_time) # depends on [control=['for'], data=['ip']] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['study']]
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs): """ index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs """ fit = np.empty((len(boot_collection), dimensions)) if ISPY3: query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees] else: query_trees = [PhyloTree(tree, rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree, rooted) for tree in ref_collection.trees] for i, tree in enumerate(query_trees): distvec = np.array([task(tree, ref_tree, False) for ref_tree in ref_trees]) oos = OutOfSampleMDS(ref_distance_matrix) fit[i] = oos.fit(index, distvec, dimensions=dimensions, **kwargs) return fit
def function[run_out_of_sample_mds, parameter[boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task, rooted]]: constant[ index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs ] variable[fit] assign[=] call[name[np].empty, parameter[tuple[[<ast.Call object at 0x7da18f00faf0>, <ast.Name object at 0x7da20c7ca6b0>]]]] if name[ISPY3] begin[:] variable[query_trees] assign[=] <ast.ListComp object at 0x7da20c7c89a0> variable[ref_trees] assign[=] <ast.ListComp object at 0x7da18f00e410> for taget[tuple[[<ast.Name object at 0x7da18f00c160>, <ast.Name object at 0x7da18f00f0a0>]]] in starred[call[name[enumerate], parameter[name[query_trees]]]] begin[:] variable[distvec] assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da18f00f670>]] variable[oos] assign[=] call[name[OutOfSampleMDS], parameter[name[ref_distance_matrix]]] call[name[fit]][name[i]] assign[=] call[name[oos].fit, parameter[name[index], name[distvec]]] return[name[fit]]
keyword[def] identifier[run_out_of_sample_mds] ( identifier[boot_collection] , identifier[ref_collection] , identifier[ref_distance_matrix] , identifier[index] , identifier[dimensions] , identifier[task] = identifier[_fast_geo] , identifier[rooted] = keyword[False] ,** identifier[kwargs] ): literal[string] identifier[fit] = identifier[np] . identifier[empty] (( identifier[len] ( identifier[boot_collection] ), identifier[dimensions] )) keyword[if] identifier[ISPY3] : identifier[query_trees] =[ identifier[PhyloTree] ( identifier[tree] . identifier[encode] (), identifier[rooted] ) keyword[for] identifier[tree] keyword[in] identifier[boot_collection] . identifier[trees] ] identifier[ref_trees] =[ identifier[PhyloTree] ( identifier[tree] . identifier[encode] (), identifier[rooted] ) keyword[for] identifier[tree] keyword[in] identifier[ref_collection] . identifier[trees] ] keyword[else] : identifier[query_trees] =[ identifier[PhyloTree] ( identifier[tree] , identifier[rooted] ) keyword[for] identifier[tree] keyword[in] identifier[boot_collection] . identifier[trees] ] identifier[ref_trees] =[ identifier[PhyloTree] ( identifier[tree] , identifier[rooted] ) keyword[for] identifier[tree] keyword[in] identifier[ref_collection] . identifier[trees] ] keyword[for] identifier[i] , identifier[tree] keyword[in] identifier[enumerate] ( identifier[query_trees] ): identifier[distvec] = identifier[np] . identifier[array] ([ identifier[task] ( identifier[tree] , identifier[ref_tree] , keyword[False] ) keyword[for] identifier[ref_tree] keyword[in] identifier[ref_trees] ]) identifier[oos] = identifier[OutOfSampleMDS] ( identifier[ref_distance_matrix] ) identifier[fit] [ identifier[i] ]= identifier[oos] . identifier[fit] ( identifier[index] , identifier[distvec] , identifier[dimensions] = identifier[dimensions] ,** identifier[kwargs] ) keyword[return] identifier[fit]
def run_out_of_sample_mds(boot_collection, ref_collection, ref_distance_matrix, index, dimensions, task=_fast_geo, rooted=False, **kwargs): """ index = index of the locus the bootstrap sample corresponds to - only important if using recalc=True in kwargs """ fit = np.empty((len(boot_collection), dimensions)) if ISPY3: query_trees = [PhyloTree(tree.encode(), rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree.encode(), rooted) for tree in ref_collection.trees] # depends on [control=['if'], data=[]] else: query_trees = [PhyloTree(tree, rooted) for tree in boot_collection.trees] ref_trees = [PhyloTree(tree, rooted) for tree in ref_collection.trees] for (i, tree) in enumerate(query_trees): distvec = np.array([task(tree, ref_tree, False) for ref_tree in ref_trees]) oos = OutOfSampleMDS(ref_distance_matrix) fit[i] = oos.fit(index, distvec, dimensions=dimensions, **kwargs) # depends on [control=['for'], data=[]] return fit
def read(self, size=None): """ <Purpose> Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file. <Arguments> size: Number of bytes to be read. <Exceptions> securesystemslib.exceptions.FormatError: if 'size' is invalid. <Return> String of data. """ if size is None: self.temporary_file.seek(0) data = self.temporary_file.read() self.temporary_file.seek(0) return data else: if not (isinstance(size, int) and size > 0): raise securesystemslib.exceptions.FormatError return self.temporary_file.read(size)
def function[read, parameter[self, size]]: constant[ <Purpose> Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file. <Arguments> size: Number of bytes to be read. <Exceptions> securesystemslib.exceptions.FormatError: if 'size' is invalid. <Return> String of data. ] if compare[name[size] is constant[None]] begin[:] call[name[self].temporary_file.seek, parameter[constant[0]]] variable[data] assign[=] call[name[self].temporary_file.read, parameter[]] call[name[self].temporary_file.seek, parameter[constant[0]]] return[name[data]]
keyword[def] identifier[read] ( identifier[self] , identifier[size] = keyword[None] ): literal[string] keyword[if] identifier[size] keyword[is] keyword[None] : identifier[self] . identifier[temporary_file] . identifier[seek] ( literal[int] ) identifier[data] = identifier[self] . identifier[temporary_file] . identifier[read] () identifier[self] . identifier[temporary_file] . identifier[seek] ( literal[int] ) keyword[return] identifier[data] keyword[else] : keyword[if] keyword[not] ( identifier[isinstance] ( identifier[size] , identifier[int] ) keyword[and] identifier[size] > literal[int] ): keyword[raise] identifier[securesystemslib] . identifier[exceptions] . identifier[FormatError] keyword[return] identifier[self] . identifier[temporary_file] . identifier[read] ( identifier[size] )
def read(self, size=None): """ <Purpose> Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file. <Arguments> size: Number of bytes to be read. <Exceptions> securesystemslib.exceptions.FormatError: if 'size' is invalid. <Return> String of data. """ if size is None: self.temporary_file.seek(0) data = self.temporary_file.read() self.temporary_file.seek(0) return data # depends on [control=['if'], data=[]] else: if not (isinstance(size, int) and size > 0): raise securesystemslib.exceptions.FormatError # depends on [control=['if'], data=[]] return self.temporary_file.read(size)
def authenticate_by_password(cls, params): """ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). """ def verify_password(user, password): return crypt.check(user.password, password) success = False user = None login = params['login'].lower().strip() key = 'email' if '@' in login else 'username' try: user = cls.get_item(**{key: login}) except Exception as ex: log.error(str(ex)) if user: password = params.get('password', None) success = (password and verify_password(user, password)) return success, user
def function[authenticate_by_password, parameter[cls, params]]: constant[ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). ] def function[verify_password, parameter[user, password]]: return[call[name[crypt].check, parameter[name[user].password, name[password]]]] variable[success] assign[=] constant[False] variable[user] assign[=] constant[None] variable[login] assign[=] call[call[call[name[params]][constant[login]].lower, parameter[]].strip, parameter[]] variable[key] assign[=] <ast.IfExp object at 0x7da1b0e33730> <ast.Try object at 0x7da1b0e32410> if name[user] begin[:] variable[password] assign[=] call[name[params].get, parameter[constant[password], constant[None]]] variable[success] assign[=] <ast.BoolOp object at 0x7da1b0e325c0> return[tuple[[<ast.Name object at 0x7da1b0e30190>, <ast.Name object at 0x7da1b0e302e0>]]]
keyword[def] identifier[authenticate_by_password] ( identifier[cls] , identifier[params] ): literal[string] keyword[def] identifier[verify_password] ( identifier[user] , identifier[password] ): keyword[return] identifier[crypt] . identifier[check] ( identifier[user] . identifier[password] , identifier[password] ) identifier[success] = keyword[False] identifier[user] = keyword[None] identifier[login] = identifier[params] [ literal[string] ]. identifier[lower] (). identifier[strip] () identifier[key] = literal[string] keyword[if] literal[string] keyword[in] identifier[login] keyword[else] literal[string] keyword[try] : identifier[user] = identifier[cls] . identifier[get_item] (**{ identifier[key] : identifier[login] }) keyword[except] identifier[Exception] keyword[as] identifier[ex] : identifier[log] . identifier[error] ( identifier[str] ( identifier[ex] )) keyword[if] identifier[user] : identifier[password] = identifier[params] . identifier[get] ( literal[string] , keyword[None] ) identifier[success] =( identifier[password] keyword[and] identifier[verify_password] ( identifier[user] , identifier[password] )) keyword[return] identifier[success] , identifier[user]
def authenticate_by_password(cls, params): """ Authenticate user with login and password from :params: Used both by Token and Ticket-based auths (called from views). """ def verify_password(user, password): return crypt.check(user.password, password) success = False user = None login = params['login'].lower().strip() key = 'email' if '@' in login else 'username' try: user = cls.get_item(**{key: login}) # depends on [control=['try'], data=[]] except Exception as ex: log.error(str(ex)) # depends on [control=['except'], data=['ex']] if user: password = params.get('password', None) success = password and verify_password(user, password) # depends on [control=['if'], data=[]] return (success, user)
def rm_pawn(self, name, *args): """Remove the :class:`Pawn` by the given name.""" if name not in self.pawn: raise KeyError("No Pawn named {}".format(name)) # Currently there's no way to connect Pawns with Arrows but I # think there will be, so, insurance self.rm_arrows_to_and_from(name) pwn = self.pawn.pop(name) if pwn in self.selection_candidates: self.selection_candidates.remove(pwn) pwn.parent.remove_widget(pwn)
def function[rm_pawn, parameter[self, name]]: constant[Remove the :class:`Pawn` by the given name.] if compare[name[name] <ast.NotIn object at 0x7da2590d7190> name[self].pawn] begin[:] <ast.Raise object at 0x7da1b0babdc0> call[name[self].rm_arrows_to_and_from, parameter[name[name]]] variable[pwn] assign[=] call[name[self].pawn.pop, parameter[name[name]]] if compare[name[pwn] in name[self].selection_candidates] begin[:] call[name[self].selection_candidates.remove, parameter[name[pwn]]] call[name[pwn].parent.remove_widget, parameter[name[pwn]]]
keyword[def] identifier[rm_pawn] ( identifier[self] , identifier[name] ,* identifier[args] ): literal[string] keyword[if] identifier[name] keyword[not] keyword[in] identifier[self] . identifier[pawn] : keyword[raise] identifier[KeyError] ( literal[string] . identifier[format] ( identifier[name] )) identifier[self] . identifier[rm_arrows_to_and_from] ( identifier[name] ) identifier[pwn] = identifier[self] . identifier[pawn] . identifier[pop] ( identifier[name] ) keyword[if] identifier[pwn] keyword[in] identifier[self] . identifier[selection_candidates] : identifier[self] . identifier[selection_candidates] . identifier[remove] ( identifier[pwn] ) identifier[pwn] . identifier[parent] . identifier[remove_widget] ( identifier[pwn] )
def rm_pawn(self, name, *args): """Remove the :class:`Pawn` by the given name.""" if name not in self.pawn: raise KeyError('No Pawn named {}'.format(name)) # depends on [control=['if'], data=['name']] # Currently there's no way to connect Pawns with Arrows but I # think there will be, so, insurance self.rm_arrows_to_and_from(name) pwn = self.pawn.pop(name) if pwn in self.selection_candidates: self.selection_candidates.remove(pwn) # depends on [control=['if'], data=['pwn']] pwn.parent.remove_widget(pwn)
def get_unspent_outputs(self): """Get the utxoset. Returns: generator of unspent_outputs. """ cursor = backend.query.get_unspent_outputs(self.connection) return (record for record in cursor)
def function[get_unspent_outputs, parameter[self]]: constant[Get the utxoset. Returns: generator of unspent_outputs. ] variable[cursor] assign[=] call[name[backend].query.get_unspent_outputs, parameter[name[self].connection]] return[<ast.GeneratorExp object at 0x7da1b1b01fc0>]
keyword[def] identifier[get_unspent_outputs] ( identifier[self] ): literal[string] identifier[cursor] = identifier[backend] . identifier[query] . identifier[get_unspent_outputs] ( identifier[self] . identifier[connection] ) keyword[return] ( identifier[record] keyword[for] identifier[record] keyword[in] identifier[cursor] )
def get_unspent_outputs(self): """Get the utxoset. Returns: generator of unspent_outputs. """ cursor = backend.query.get_unspent_outputs(self.connection) return (record for record in cursor)
def wait_until_loaded(self, timeout=None): """Wait until page object is loaded Search all page elements configured with wait=True :param timeout: max time to wait :returns: this page object instance """ for element in self._get_page_elements(): if hasattr(element, 'wait') and element.wait: from toolium.pageelements.page_element import PageElement if isinstance(element, PageElement): # Pageelement and Group element.wait_until_visible(timeout) if isinstance(element, PageObject): # PageObject and Group element.wait_until_loaded(timeout) return self
def function[wait_until_loaded, parameter[self, timeout]]: constant[Wait until page object is loaded Search all page elements configured with wait=True :param timeout: max time to wait :returns: this page object instance ] for taget[name[element]] in starred[call[name[self]._get_page_elements, parameter[]]] begin[:] if <ast.BoolOp object at 0x7da1b1c388b0> begin[:] from relative_module[toolium.pageelements.page_element] import module[PageElement] if call[name[isinstance], parameter[name[element], name[PageElement]]] begin[:] call[name[element].wait_until_visible, parameter[name[timeout]]] if call[name[isinstance], parameter[name[element], name[PageObject]]] begin[:] call[name[element].wait_until_loaded, parameter[name[timeout]]] return[name[self]]
keyword[def] identifier[wait_until_loaded] ( identifier[self] , identifier[timeout] = keyword[None] ): literal[string] keyword[for] identifier[element] keyword[in] identifier[self] . identifier[_get_page_elements] (): keyword[if] identifier[hasattr] ( identifier[element] , literal[string] ) keyword[and] identifier[element] . identifier[wait] : keyword[from] identifier[toolium] . identifier[pageelements] . identifier[page_element] keyword[import] identifier[PageElement] keyword[if] identifier[isinstance] ( identifier[element] , identifier[PageElement] ): identifier[element] . identifier[wait_until_visible] ( identifier[timeout] ) keyword[if] identifier[isinstance] ( identifier[element] , identifier[PageObject] ): identifier[element] . identifier[wait_until_loaded] ( identifier[timeout] ) keyword[return] identifier[self]
def wait_until_loaded(self, timeout=None): """Wait until page object is loaded Search all page elements configured with wait=True :param timeout: max time to wait :returns: this page object instance """ for element in self._get_page_elements(): if hasattr(element, 'wait') and element.wait: from toolium.pageelements.page_element import PageElement if isinstance(element, PageElement): # Pageelement and Group element.wait_until_visible(timeout) # depends on [control=['if'], data=[]] if isinstance(element, PageObject): # PageObject and Group element.wait_until_loaded(timeout) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['element']] return self
def formatLij(Lij0,Ne): """This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.""" #We create Lij as a matrix of lists of laser indices global Lij Lij=[] for i in range(Ne): fila=[] for j in range(Ne): band=False for tri in Lij0: if [i+1,j+1] == tri[:2]: band=True break elif [j+1,i+1] == tri[:2]: band=True break if band: fila+=[tri[2]] else: fila+=[[]] Lij+=[fila] return Lij
def function[formatLij, parameter[Lij0, Ne]]: constant[This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.] <ast.Global object at 0x7da1b1957e20> variable[Lij] assign[=] list[[]] for taget[name[i]] in starred[call[name[range], parameter[name[Ne]]]] begin[:] variable[fila] assign[=] list[[]] for taget[name[j]] in starred[call[name[range], parameter[name[Ne]]]] begin[:] variable[band] assign[=] constant[False] for taget[name[tri]] in starred[name[Lij0]] begin[:] if compare[list[[<ast.BinOp object at 0x7da1b1957910>, <ast.BinOp object at 0x7da1b1957880>]] equal[==] call[name[tri]][<ast.Slice object at 0x7da1b1957790>]] begin[:] variable[band] assign[=] constant[True] break if name[band] begin[:] <ast.AugAssign object at 0x7da1b18026e0> <ast.AugAssign object at 0x7da1b1802890> return[name[Lij]]
keyword[def] identifier[formatLij] ( identifier[Lij0] , identifier[Ne] ): literal[string] keyword[global] identifier[Lij] identifier[Lij] =[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[Ne] ): identifier[fila] =[] keyword[for] identifier[j] keyword[in] identifier[range] ( identifier[Ne] ): identifier[band] = keyword[False] keyword[for] identifier[tri] keyword[in] identifier[Lij0] : keyword[if] [ identifier[i] + literal[int] , identifier[j] + literal[int] ]== identifier[tri] [: literal[int] ]: identifier[band] = keyword[True] keyword[break] keyword[elif] [ identifier[j] + literal[int] , identifier[i] + literal[int] ]== identifier[tri] [: literal[int] ]: identifier[band] = keyword[True] keyword[break] keyword[if] identifier[band] : identifier[fila] +=[ identifier[tri] [ literal[int] ]] keyword[else] : identifier[fila] +=[[]] identifier[Lij] +=[ identifier[fila] ] keyword[return] identifier[Lij]
def formatLij(Lij0, Ne): """This function transforms a list of laser conections of the form [i,j,[l1,l2,...]] between states i and j by lasers l1,l2,... into a Ne x Ne matrix whose elements are the lasers connecting the corresponding indices.""" #We create Lij as a matrix of lists of laser indices global Lij Lij = [] for i in range(Ne): fila = [] for j in range(Ne): band = False for tri in Lij0: if [i + 1, j + 1] == tri[:2]: band = True break # depends on [control=['if'], data=[]] elif [j + 1, i + 1] == tri[:2]: band = True break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['tri']] if band: fila += [tri[2]] # depends on [control=['if'], data=[]] else: fila += [[]] # depends on [control=['for'], data=['j']] Lij += [fila] # depends on [control=['for'], data=['i']] return Lij
def extract_arguments(arguments, long_keys, key_prefix='--'): """ :param arguments: dict of command line arguments """ long_arguments = extract(arguments, long_keys) return dict( [(key.replace(key_prefix, ''), value) for key, value in long_arguments.items()] )
def function[extract_arguments, parameter[arguments, long_keys, key_prefix]]: constant[ :param arguments: dict of command line arguments ] variable[long_arguments] assign[=] call[name[extract], parameter[name[arguments], name[long_keys]]] return[call[name[dict], parameter[<ast.ListComp object at 0x7da1b0693a60>]]]
keyword[def] identifier[extract_arguments] ( identifier[arguments] , identifier[long_keys] , identifier[key_prefix] = literal[string] ): literal[string] identifier[long_arguments] = identifier[extract] ( identifier[arguments] , identifier[long_keys] ) keyword[return] identifier[dict] ( [( identifier[key] . identifier[replace] ( identifier[key_prefix] , literal[string] ), identifier[value] ) keyword[for] identifier[key] , identifier[value] keyword[in] identifier[long_arguments] . identifier[items] ()] )
def extract_arguments(arguments, long_keys, key_prefix='--'): """ :param arguments: dict of command line arguments """ long_arguments = extract(arguments, long_keys) return dict([(key.replace(key_prefix, ''), value) for (key, value) in long_arguments.items()])
def set(args): """Set an Aegea configuration parameter to a given value""" from . import config, tweak class ConfigSaver(tweak.Config): @property def config_files(self): return [config.config_files[2]] config_saver = ConfigSaver(use_yaml=True, save_on_exit=False) c = config_saver for key in args.key.split(".")[:-1]: try: c = c[key] except KeyError: c[key] = {} c = c[key] c[args.key.split(".")[-1]] = json.loads(args.value) if args.json else args.value config_saver.save()
def function[set, parameter[args]]: constant[Set an Aegea configuration parameter to a given value] from relative_module[None] import module[config], module[tweak] class class[ConfigSaver, parameter[]] begin[:] def function[config_files, parameter[self]]: return[list[[<ast.Subscript object at 0x7da1b0f98040>]]] variable[config_saver] assign[=] call[name[ConfigSaver], parameter[]] variable[c] assign[=] name[config_saver] for taget[name[key]] in starred[call[call[name[args].key.split, parameter[constant[.]]]][<ast.Slice object at 0x7da1b0f98ac0>]] begin[:] <ast.Try object at 0x7da1b0f993f0> call[name[c]][call[call[name[args].key.split, parameter[constant[.]]]][<ast.UnaryOp object at 0x7da1b0f9a200>]] assign[=] <ast.IfExp object at 0x7da1b0f98c70> call[name[config_saver].save, parameter[]]
keyword[def] identifier[set] ( identifier[args] ): literal[string] keyword[from] . keyword[import] identifier[config] , identifier[tweak] keyword[class] identifier[ConfigSaver] ( identifier[tweak] . identifier[Config] ): @ identifier[property] keyword[def] identifier[config_files] ( identifier[self] ): keyword[return] [ identifier[config] . identifier[config_files] [ literal[int] ]] identifier[config_saver] = identifier[ConfigSaver] ( identifier[use_yaml] = keyword[True] , identifier[save_on_exit] = keyword[False] ) identifier[c] = identifier[config_saver] keyword[for] identifier[key] keyword[in] identifier[args] . identifier[key] . identifier[split] ( literal[string] )[:- literal[int] ]: keyword[try] : identifier[c] = identifier[c] [ identifier[key] ] keyword[except] identifier[KeyError] : identifier[c] [ identifier[key] ]={} identifier[c] = identifier[c] [ identifier[key] ] identifier[c] [ identifier[args] . identifier[key] . identifier[split] ( literal[string] )[- literal[int] ]]= identifier[json] . identifier[loads] ( identifier[args] . identifier[value] ) keyword[if] identifier[args] . identifier[json] keyword[else] identifier[args] . identifier[value] identifier[config_saver] . identifier[save] ()
def set(args): """Set an Aegea configuration parameter to a given value""" from . import config, tweak class ConfigSaver(tweak.Config): @property def config_files(self): return [config.config_files[2]] config_saver = ConfigSaver(use_yaml=True, save_on_exit=False) c = config_saver for key in args.key.split('.')[:-1]: try: c = c[key] # depends on [control=['try'], data=[]] except KeyError: c[key] = {} c = c[key] # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['key']] c[args.key.split('.')[-1]] = json.loads(args.value) if args.json else args.value config_saver.save()
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return "".join(chars) ordinal -= 1 index, ordinal = divmod(ordinal, weight) chars.append(_ALPHABET[index]) return "".join(chars)
def function[_ord_to_str, parameter[ordinal, weights]]: constant[Reverse function of _str_to_ord.] variable[chars] assign[=] list[[]] for taget[name[weight]] in starred[name[weights]] begin[:] if compare[name[ordinal] equal[==] constant[0]] begin[:] return[call[constant[].join, parameter[name[chars]]]] <ast.AugAssign object at 0x7da20c6c69b0> <ast.Tuple object at 0x7da20c6c7a00> assign[=] call[name[divmod], parameter[name[ordinal], name[weight]]] call[name[chars].append, parameter[call[name[_ALPHABET]][name[index]]]] return[call[constant[].join, parameter[name[chars]]]]
keyword[def] identifier[_ord_to_str] ( identifier[ordinal] , identifier[weights] ): literal[string] identifier[chars] =[] keyword[for] identifier[weight] keyword[in] identifier[weights] : keyword[if] identifier[ordinal] == literal[int] : keyword[return] literal[string] . identifier[join] ( identifier[chars] ) identifier[ordinal] -= literal[int] identifier[index] , identifier[ordinal] = identifier[divmod] ( identifier[ordinal] , identifier[weight] ) identifier[chars] . identifier[append] ( identifier[_ALPHABET] [ identifier[index] ]) keyword[return] literal[string] . identifier[join] ( identifier[chars] )
def _ord_to_str(ordinal, weights): """Reverse function of _str_to_ord.""" chars = [] for weight in weights: if ordinal == 0: return ''.join(chars) # depends on [control=['if'], data=[]] ordinal -= 1 (index, ordinal) = divmod(ordinal, weight) chars.append(_ALPHABET[index]) # depends on [control=['for'], data=['weight']] return ''.join(chars)
def escape(str): """Precede all special characters with a backslash.""" out = '' for char in str: if char in '\\ ': out += '\\' out += char return out
def function[escape, parameter[str]]: constant[Precede all special characters with a backslash.] variable[out] assign[=] constant[] for taget[name[char]] in starred[name[str]] begin[:] if compare[name[char] in constant[\ ]] begin[:] <ast.AugAssign object at 0x7da207f987c0> <ast.AugAssign object at 0x7da207f9ad70> return[name[out]]
keyword[def] identifier[escape] ( identifier[str] ): literal[string] identifier[out] = literal[string] keyword[for] identifier[char] keyword[in] identifier[str] : keyword[if] identifier[char] keyword[in] literal[string] : identifier[out] += literal[string] identifier[out] += identifier[char] keyword[return] identifier[out]
def escape(str): """Precede all special characters with a backslash.""" out = '' for char in str: if char in '\\ ': out += '\\' # depends on [control=['if'], data=[]] out += char # depends on [control=['for'], data=['char']] return out
def validate_wrap(self, value): ''' Checks that value is valid for `EnumField.item_type` and that value is one of the values specified when the EnumField was constructed ''' self.item_type.validate_wrap(value) if value not in self.values: self._fail_validation(value, 'Value was not in the enum values')
def function[validate_wrap, parameter[self, value]]: constant[ Checks that value is valid for `EnumField.item_type` and that value is one of the values specified when the EnumField was constructed ] call[name[self].item_type.validate_wrap, parameter[name[value]]] if compare[name[value] <ast.NotIn object at 0x7da2590d7190> name[self].values] begin[:] call[name[self]._fail_validation, parameter[name[value], constant[Value was not in the enum values]]]
keyword[def] identifier[validate_wrap] ( identifier[self] , identifier[value] ): literal[string] identifier[self] . identifier[item_type] . identifier[validate_wrap] ( identifier[value] ) keyword[if] identifier[value] keyword[not] keyword[in] identifier[self] . identifier[values] : identifier[self] . identifier[_fail_validation] ( identifier[value] , literal[string] )
def validate_wrap(self, value): """ Checks that value is valid for `EnumField.item_type` and that value is one of the values specified when the EnumField was constructed """ self.item_type.validate_wrap(value) if value not in self.values: self._fail_validation(value, 'Value was not in the enum values') # depends on [control=['if'], data=['value']]
def AddStopTimeObject(self, stoptime, schedule=None, problems=None): """Add a StopTime object to the end of this trip. Args: stoptime: A StopTime object. Should not be reused in multiple trips. schedule: Schedule object containing this trip which must be passed to Trip.__init__ or here problems: ProblemReporter object for validating the StopTime in its new home Returns: None """ if schedule is None: schedule = self._schedule if schedule is None: warnings.warn("No longer supported. _schedule attribute is used to get " "stop_times table", DeprecationWarning) if problems is None: problems = schedule.problem_reporter new_secs = stoptime.GetTimeSecs() cursor = schedule._connection.cursor() cursor.execute("SELECT max(stop_sequence), max(arrival_secs), " "max(departure_secs) FROM stop_times WHERE trip_id=?", (self.trip_id,)) row = cursor.fetchone() if row[0] is None: # This is the first stop_time of the trip stoptime.stop_sequence = 1 if new_secs == None: problems.OtherProblem( 'No time for first StopTime of trip_id "%s"' % (self.trip_id,)) else: stoptime.stop_sequence = row[0] + 1 prev_secs = max(row[1], row[2]) if new_secs != None and new_secs < prev_secs: problems.OtherProblem( 'out of order stop time for stop_id=%s trip_id=%s %s < %s' % (util.EncodeUnicode(stoptime.stop_id), util.EncodeUnicode(self.trip_id), util.FormatSecondsSinceMidnight(new_secs), util.FormatSecondsSinceMidnight(prev_secs))) self._AddStopTimeObjectUnordered(stoptime, schedule)
def function[AddStopTimeObject, parameter[self, stoptime, schedule, problems]]: constant[Add a StopTime object to the end of this trip. Args: stoptime: A StopTime object. Should not be reused in multiple trips. schedule: Schedule object containing this trip which must be passed to Trip.__init__ or here problems: ProblemReporter object for validating the StopTime in its new home Returns: None ] if compare[name[schedule] is constant[None]] begin[:] variable[schedule] assign[=] name[self]._schedule if compare[name[schedule] is constant[None]] begin[:] call[name[warnings].warn, parameter[constant[No longer supported. _schedule attribute is used to get stop_times table], name[DeprecationWarning]]] if compare[name[problems] is constant[None]] begin[:] variable[problems] assign[=] name[schedule].problem_reporter variable[new_secs] assign[=] call[name[stoptime].GetTimeSecs, parameter[]] variable[cursor] assign[=] call[name[schedule]._connection.cursor, parameter[]] call[name[cursor].execute, parameter[constant[SELECT max(stop_sequence), max(arrival_secs), max(departure_secs) FROM stop_times WHERE trip_id=?], tuple[[<ast.Attribute object at 0x7da1b17a8e20>]]]] variable[row] assign[=] call[name[cursor].fetchone, parameter[]] if compare[call[name[row]][constant[0]] is constant[None]] begin[:] name[stoptime].stop_sequence assign[=] constant[1] if compare[name[new_secs] equal[==] constant[None]] begin[:] call[name[problems].OtherProblem, parameter[binary_operation[constant[No time for first StopTime of trip_id "%s"] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b17a8490>]]]]] call[name[self]._AddStopTimeObjectUnordered, parameter[name[stoptime], name[schedule]]]
keyword[def] identifier[AddStopTimeObject] ( identifier[self] , identifier[stoptime] , identifier[schedule] = keyword[None] , identifier[problems] = keyword[None] ): literal[string] keyword[if] identifier[schedule] keyword[is] keyword[None] : identifier[schedule] = identifier[self] . identifier[_schedule] keyword[if] identifier[schedule] keyword[is] keyword[None] : identifier[warnings] . identifier[warn] ( literal[string] literal[string] , identifier[DeprecationWarning] ) keyword[if] identifier[problems] keyword[is] keyword[None] : identifier[problems] = identifier[schedule] . identifier[problem_reporter] identifier[new_secs] = identifier[stoptime] . identifier[GetTimeSecs] () identifier[cursor] = identifier[schedule] . identifier[_connection] . identifier[cursor] () identifier[cursor] . identifier[execute] ( literal[string] literal[string] , ( identifier[self] . identifier[trip_id] ,)) identifier[row] = identifier[cursor] . identifier[fetchone] () keyword[if] identifier[row] [ literal[int] ] keyword[is] keyword[None] : identifier[stoptime] . identifier[stop_sequence] = literal[int] keyword[if] identifier[new_secs] == keyword[None] : identifier[problems] . identifier[OtherProblem] ( literal[string] %( identifier[self] . identifier[trip_id] ,)) keyword[else] : identifier[stoptime] . identifier[stop_sequence] = identifier[row] [ literal[int] ]+ literal[int] identifier[prev_secs] = identifier[max] ( identifier[row] [ literal[int] ], identifier[row] [ literal[int] ]) keyword[if] identifier[new_secs] != keyword[None] keyword[and] identifier[new_secs] < identifier[prev_secs] : identifier[problems] . identifier[OtherProblem] ( literal[string] % ( identifier[util] . identifier[EncodeUnicode] ( identifier[stoptime] . identifier[stop_id] ), identifier[util] . identifier[EncodeUnicode] ( identifier[self] . identifier[trip_id] ), identifier[util] . identifier[FormatSecondsSinceMidnight] ( identifier[new_secs] ), identifier[util] . identifier[FormatSecondsSinceMidnight] ( identifier[prev_secs] ))) identifier[self] . identifier[_AddStopTimeObjectUnordered] ( identifier[stoptime] , identifier[schedule] )
def AddStopTimeObject(self, stoptime, schedule=None, problems=None): """Add a StopTime object to the end of this trip. Args: stoptime: A StopTime object. Should not be reused in multiple trips. schedule: Schedule object containing this trip which must be passed to Trip.__init__ or here problems: ProblemReporter object for validating the StopTime in its new home Returns: None """ if schedule is None: schedule = self._schedule # depends on [control=['if'], data=['schedule']] if schedule is None: warnings.warn('No longer supported. _schedule attribute is used to get stop_times table', DeprecationWarning) # depends on [control=['if'], data=[]] if problems is None: problems = schedule.problem_reporter # depends on [control=['if'], data=['problems']] new_secs = stoptime.GetTimeSecs() cursor = schedule._connection.cursor() cursor.execute('SELECT max(stop_sequence), max(arrival_secs), max(departure_secs) FROM stop_times WHERE trip_id=?', (self.trip_id,)) row = cursor.fetchone() if row[0] is None: # This is the first stop_time of the trip stoptime.stop_sequence = 1 if new_secs == None: problems.OtherProblem('No time for first StopTime of trip_id "%s"' % (self.trip_id,)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: stoptime.stop_sequence = row[0] + 1 prev_secs = max(row[1], row[2]) if new_secs != None and new_secs < prev_secs: problems.OtherProblem('out of order stop time for stop_id=%s trip_id=%s %s < %s' % (util.EncodeUnicode(stoptime.stop_id), util.EncodeUnicode(self.trip_id), util.FormatSecondsSinceMidnight(new_secs), util.FormatSecondsSinceMidnight(prev_secs))) # depends on [control=['if'], data=[]] self._AddStopTimeObjectUnordered(stoptime, schedule)
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.coroutine, for example) will handle that. to_yield = next(coroutine) while True: try: to_send = yield to_yield except Exception: to_yield = coroutine.throw(*sys.exc_info()) else: try: to_yield = coroutine.send(to_send) except StopIteration: break
def function[_handle_generator, parameter[self, fn]]: constant[Wraps a generator so that we're inside the cassette context for the duration of the generator. ] with name[self] begin[:] variable[coroutine] assign[=] call[name[fn], parameter[name[cassette]]] variable[to_yield] assign[=] call[name[next], parameter[name[coroutine]]] while constant[True] begin[:] <ast.Try object at 0x7da20e9558d0>
keyword[def] identifier[_handle_generator] ( identifier[self] , identifier[fn] ): literal[string] keyword[with] identifier[self] keyword[as] identifier[cassette] : identifier[coroutine] = identifier[fn] ( identifier[cassette] ) identifier[to_yield] = identifier[next] ( identifier[coroutine] ) keyword[while] keyword[True] : keyword[try] : identifier[to_send] = keyword[yield] identifier[to_yield] keyword[except] identifier[Exception] : identifier[to_yield] = identifier[coroutine] . identifier[throw] (* identifier[sys] . identifier[exc_info] ()) keyword[else] : keyword[try] : identifier[to_yield] = identifier[coroutine] . identifier[send] ( identifier[to_send] ) keyword[except] identifier[StopIteration] : keyword[break]
def _handle_generator(self, fn): """Wraps a generator so that we're inside the cassette context for the duration of the generator. """ with self as cassette: coroutine = fn(cassette) # We don't need to catch StopIteration. The caller (Tornado's # gen.coroutine, for example) will handle that. to_yield = next(coroutine) while True: try: to_send = (yield to_yield) # depends on [control=['try'], data=[]] except Exception: to_yield = coroutine.throw(*sys.exc_info()) # depends on [control=['except'], data=[]] else: try: to_yield = coroutine.send(to_send) # depends on [control=['try'], data=[]] except StopIteration: break # depends on [control=['except'], data=[]] # depends on [control=['while'], data=[]] # depends on [control=['with'], data=['cassette']]
def attr(obj, attr): """ Does the same thing as getattr. getattr(obj, attr, '') """ if not obj or not hasattr(obj, attr): return '' return getattr(obj, attr, '')
def function[attr, parameter[obj, attr]]: constant[ Does the same thing as getattr. getattr(obj, attr, '') ] if <ast.BoolOp object at 0x7da18bcc94e0> begin[:] return[constant[]] return[call[name[getattr], parameter[name[obj], name[attr], constant[]]]]
keyword[def] identifier[attr] ( identifier[obj] , identifier[attr] ): literal[string] keyword[if] keyword[not] identifier[obj] keyword[or] keyword[not] identifier[hasattr] ( identifier[obj] , identifier[attr] ): keyword[return] literal[string] keyword[return] identifier[getattr] ( identifier[obj] , identifier[attr] , literal[string] )
def attr(obj, attr): """ Does the same thing as getattr. getattr(obj, attr, '') """ if not obj or not hasattr(obj, attr): return '' # depends on [control=['if'], data=[]] return getattr(obj, attr, '')
def is_contradictory(self, other): """ Whether other and self can coexist """ other = IntervalCell.coerce(other) assert other.low <= other.high, "Low must be <= high" if max(other.low, self.low) <= min(other.high, self.high): return False else: return True
def function[is_contradictory, parameter[self, other]]: constant[ Whether other and self can coexist ] variable[other] assign[=] call[name[IntervalCell].coerce, parameter[name[other]]] assert[compare[name[other].low less_or_equal[<=] name[other].high]] if compare[call[name[max], parameter[name[other].low, name[self].low]] less_or_equal[<=] call[name[min], parameter[name[other].high, name[self].high]]] begin[:] return[constant[False]]
keyword[def] identifier[is_contradictory] ( identifier[self] , identifier[other] ): literal[string] identifier[other] = identifier[IntervalCell] . identifier[coerce] ( identifier[other] ) keyword[assert] identifier[other] . identifier[low] <= identifier[other] . identifier[high] , literal[string] keyword[if] identifier[max] ( identifier[other] . identifier[low] , identifier[self] . identifier[low] )<= identifier[min] ( identifier[other] . identifier[high] , identifier[self] . identifier[high] ): keyword[return] keyword[False] keyword[else] : keyword[return] keyword[True]
def is_contradictory(self, other): """ Whether other and self can coexist """ other = IntervalCell.coerce(other) assert other.low <= other.high, 'Low must be <= high' if max(other.low, self.low) <= min(other.high, self.high): return False # depends on [control=['if'], data=[]] else: return True
def ConfigureHostnames(config, external_hostname = None): """This configures the hostnames stored in the config.""" if not external_hostname: try: external_hostname = socket.gethostname() except (OSError, IOError): print("Sorry, we couldn't guess your hostname.\n") external_hostname = RetryQuestion( "Please enter your hostname e.g. " "grr.example.com", "^[\\.A-Za-z0-9-]+$", external_hostname) print("""\n\n-=Server URL=- The Server URL specifies the URL that the clients will connect to communicate with the server. For best results this should be publicly accessible. By default this will be port 8080 with the URL ending in /control. """) frontend_url = RetryQuestion("Frontend URL", "^http://.*/$", "http://%s:8080/" % external_hostname) config.Set("Client.server_urls", [frontend_url]) frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get( "Frontend.bind_port") config.Set("Frontend.bind_port", frontend_port) print("""\n\n-=AdminUI URL=-: The UI URL specifies where the Administrative Web Interface can be found. """) ui_url = RetryQuestion("AdminUI URL", "^http[s]*://.*$", "http://%s:8000" % external_hostname) config.Set("AdminUI.url", ui_url) ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get( "AdminUI.port") config.Set("AdminUI.port", ui_port)
def function[ConfigureHostnames, parameter[config, external_hostname]]: constant[This configures the hostnames stored in the config.] if <ast.UnaryOp object at 0x7da1b1b6b6a0> begin[:] <ast.Try object at 0x7da1b1b6ada0> variable[external_hostname] assign[=] call[name[RetryQuestion], parameter[constant[Please enter your hostname e.g. grr.example.com], constant[^[\.A-Za-z0-9-]+$], name[external_hostname]]] call[name[print], parameter[constant[ -=Server URL=- The Server URL specifies the URL that the clients will connect to communicate with the server. For best results this should be publicly accessible. By default this will be port 8080 with the URL ending in /control. ]]] variable[frontend_url] assign[=] call[name[RetryQuestion], parameter[constant[Frontend URL], constant[^http://.*/$], binary_operation[constant[http://%s:8080/] <ast.Mod object at 0x7da2590d6920> name[external_hostname]]]] call[name[config].Set, parameter[constant[Client.server_urls], list[[<ast.Name object at 0x7da1b1b6ace0>]]]] variable[frontend_port] assign[=] <ast.BoolOp object at 0x7da1b1b68c40> call[name[config].Set, parameter[constant[Frontend.bind_port], name[frontend_port]]] call[name[print], parameter[constant[ -=AdminUI URL=-: The UI URL specifies where the Administrative Web Interface can be found. ]]] variable[ui_url] assign[=] call[name[RetryQuestion], parameter[constant[AdminUI URL], constant[^http[s]*://.*$], binary_operation[constant[http://%s:8000] <ast.Mod object at 0x7da2590d6920> name[external_hostname]]]] call[name[config].Set, parameter[constant[AdminUI.url], name[ui_url]]] variable[ui_port] assign[=] <ast.BoolOp object at 0x7da1b1b6a860> call[name[config].Set, parameter[constant[AdminUI.port], name[ui_port]]]
keyword[def] identifier[ConfigureHostnames] ( identifier[config] , identifier[external_hostname] = keyword[None] ): literal[string] keyword[if] keyword[not] identifier[external_hostname] : keyword[try] : identifier[external_hostname] = identifier[socket] . identifier[gethostname] () keyword[except] ( identifier[OSError] , identifier[IOError] ): identifier[print] ( literal[string] ) identifier[external_hostname] = identifier[RetryQuestion] ( literal[string] literal[string] , literal[string] , identifier[external_hostname] ) identifier[print] ( literal[string] ) identifier[frontend_url] = identifier[RetryQuestion] ( literal[string] , literal[string] , literal[string] % identifier[external_hostname] ) identifier[config] . identifier[Set] ( literal[string] ,[ identifier[frontend_url] ]) identifier[frontend_port] = identifier[urlparse] . identifier[urlparse] ( identifier[frontend_url] ). identifier[port] keyword[or] identifier[grr_config] . identifier[CONFIG] . identifier[Get] ( literal[string] ) identifier[config] . identifier[Set] ( literal[string] , identifier[frontend_port] ) identifier[print] ( literal[string] ) identifier[ui_url] = identifier[RetryQuestion] ( literal[string] , literal[string] , literal[string] % identifier[external_hostname] ) identifier[config] . identifier[Set] ( literal[string] , identifier[ui_url] ) identifier[ui_port] = identifier[urlparse] . identifier[urlparse] ( identifier[ui_url] ). identifier[port] keyword[or] identifier[grr_config] . identifier[CONFIG] . identifier[Get] ( literal[string] ) identifier[config] . identifier[Set] ( literal[string] , identifier[ui_port] )
def ConfigureHostnames(config, external_hostname=None): """This configures the hostnames stored in the config.""" if not external_hostname: try: external_hostname = socket.gethostname() # depends on [control=['try'], data=[]] except (OSError, IOError): print("Sorry, we couldn't guess your hostname.\n") # depends on [control=['except'], data=[]] external_hostname = RetryQuestion('Please enter your hostname e.g. grr.example.com', '^[\\.A-Za-z0-9-]+$', external_hostname) # depends on [control=['if'], data=[]] print('\n\n-=Server URL=-\nThe Server URL specifies the URL that the clients will connect to\ncommunicate with the server. For best results this should be publicly\naccessible. By default this will be port 8080 with the URL ending in /control.\n') frontend_url = RetryQuestion('Frontend URL', '^http://.*/$', 'http://%s:8080/' % external_hostname) config.Set('Client.server_urls', [frontend_url]) frontend_port = urlparse.urlparse(frontend_url).port or grr_config.CONFIG.Get('Frontend.bind_port') config.Set('Frontend.bind_port', frontend_port) print('\n\n-=AdminUI URL=-:\nThe UI URL specifies where the Administrative Web Interface can be found.\n') ui_url = RetryQuestion('AdminUI URL', '^http[s]*://.*$', 'http://%s:8000' % external_hostname) config.Set('AdminUI.url', ui_url) ui_port = urlparse.urlparse(ui_url).port or grr_config.CONFIG.Get('AdminUI.port') config.Set('AdminUI.port', ui_port)
def copy(self, name=None): r""" Creates a deep copy of the current project A deep copy means that new, unique versions of all the objects are created but with identical data and properties. Parameters ---------- name : string The name to give to the new project. If not supplied, a name is automatically generated. Returns ------- A new Project object containing copies of all objects """ if name is None: name = ws._gen_name() proj = deepcopy(self) ws[name] = proj return proj
def function[copy, parameter[self, name]]: constant[ Creates a deep copy of the current project A deep copy means that new, unique versions of all the objects are created but with identical data and properties. Parameters ---------- name : string The name to give to the new project. If not supplied, a name is automatically generated. Returns ------- A new Project object containing copies of all objects ] if compare[name[name] is constant[None]] begin[:] variable[name] assign[=] call[name[ws]._gen_name, parameter[]] variable[proj] assign[=] call[name[deepcopy], parameter[name[self]]] call[name[ws]][name[name]] assign[=] name[proj] return[name[proj]]
keyword[def] identifier[copy] ( identifier[self] , identifier[name] = keyword[None] ): literal[string] keyword[if] identifier[name] keyword[is] keyword[None] : identifier[name] = identifier[ws] . identifier[_gen_name] () identifier[proj] = identifier[deepcopy] ( identifier[self] ) identifier[ws] [ identifier[name] ]= identifier[proj] keyword[return] identifier[proj]
def copy(self, name=None): """ Creates a deep copy of the current project A deep copy means that new, unique versions of all the objects are created but with identical data and properties. Parameters ---------- name : string The name to give to the new project. If not supplied, a name is automatically generated. Returns ------- A new Project object containing copies of all objects """ if name is None: name = ws._gen_name() # depends on [control=['if'], data=['name']] proj = deepcopy(self) ws[name] = proj return proj
def convertWCS(inwcs,drizwcs): """ Copy WCSObject WCS into Drizzle compatible array.""" drizwcs[0] = inwcs.crpix[0] drizwcs[1] = inwcs.crval[0] drizwcs[2] = inwcs.crpix[1] drizwcs[3] = inwcs.crval[1] drizwcs[4] = inwcs.cd[0][0] drizwcs[5] = inwcs.cd[1][0] drizwcs[6] = inwcs.cd[0][1] drizwcs[7] = inwcs.cd[1][1] return drizwcs
def function[convertWCS, parameter[inwcs, drizwcs]]: constant[ Copy WCSObject WCS into Drizzle compatible array.] call[name[drizwcs]][constant[0]] assign[=] call[name[inwcs].crpix][constant[0]] call[name[drizwcs]][constant[1]] assign[=] call[name[inwcs].crval][constant[0]] call[name[drizwcs]][constant[2]] assign[=] call[name[inwcs].crpix][constant[1]] call[name[drizwcs]][constant[3]] assign[=] call[name[inwcs].crval][constant[1]] call[name[drizwcs]][constant[4]] assign[=] call[call[name[inwcs].cd][constant[0]]][constant[0]] call[name[drizwcs]][constant[5]] assign[=] call[call[name[inwcs].cd][constant[1]]][constant[0]] call[name[drizwcs]][constant[6]] assign[=] call[call[name[inwcs].cd][constant[0]]][constant[1]] call[name[drizwcs]][constant[7]] assign[=] call[call[name[inwcs].cd][constant[1]]][constant[1]] return[name[drizwcs]]
keyword[def] identifier[convertWCS] ( identifier[inwcs] , identifier[drizwcs] ): literal[string] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[crpix] [ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[crval] [ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[crpix] [ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[crval] [ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[cd] [ literal[int] ][ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[cd] [ literal[int] ][ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[cd] [ literal[int] ][ literal[int] ] identifier[drizwcs] [ literal[int] ]= identifier[inwcs] . identifier[cd] [ literal[int] ][ literal[int] ] keyword[return] identifier[drizwcs]
def convertWCS(inwcs, drizwcs): """ Copy WCSObject WCS into Drizzle compatible array.""" drizwcs[0] = inwcs.crpix[0] drizwcs[1] = inwcs.crval[0] drizwcs[2] = inwcs.crpix[1] drizwcs[3] = inwcs.crval[1] drizwcs[4] = inwcs.cd[0][0] drizwcs[5] = inwcs.cd[1][0] drizwcs[6] = inwcs.cd[0][1] drizwcs[7] = inwcs.cd[1][1] return drizwcs
def zrange(self, key, start=0, stop=-1, with_scores=False): """Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. See :meth:`tredis.Client.zrevrange` when you need the elements ordered from highest to lowest score (and descending lexicographical order for elements with equal score). Both start and stop are zero-based indexes, where ``0`` is the first element, ``1`` is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with ``-1`` being the last element of the sorted set, ``-2`` the penultimate element and so on. ``start`` and ``stop`` are inclusive ranges, so for example ``ZRANGE myzset 0 1`` will return both the first and the second element of the sorted set. Out of range indexes will not produce an error. If start is larger than the largest index in the sorted set, or ``start > stop``, an empty list is returned. If stop is larger than the end of the sorted set Redis will treat it like it is the last element of the sorted set. It is possible to pass the ``WITHSCORES`` option in order to return the scores of the elements together with the elements. The returned list will contain ``value1,score1,...,valueN,scoreN`` instead of ``value1,...,valueN``. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples). .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number of elements in the sorted set and ``M`` the number of elements returned. :param key: The key of the sorted set :type key: :class:`str`, :class:`bytes` :param int start: The starting index of the sorted set :param int stop: The ending index of the sorted set :param bool with_scores: Return the scores with the elements :rtype: list :raises: :exc:`~tredis.exceptions.RedisError` """ command = [b'ZRANGE', key, start, stop] if with_scores: command += ['WITHSCORES'] return self._execute(command)
def function[zrange, parameter[self, key, start, stop, with_scores]]: constant[Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. See :meth:`tredis.Client.zrevrange` when you need the elements ordered from highest to lowest score (and descending lexicographical order for elements with equal score). Both start and stop are zero-based indexes, where ``0`` is the first element, ``1`` is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with ``-1`` being the last element of the sorted set, ``-2`` the penultimate element and so on. ``start`` and ``stop`` are inclusive ranges, so for example ``ZRANGE myzset 0 1`` will return both the first and the second element of the sorted set. Out of range indexes will not produce an error. If start is larger than the largest index in the sorted set, or ``start > stop``, an empty list is returned. If stop is larger than the end of the sorted set Redis will treat it like it is the last element of the sorted set. It is possible to pass the ``WITHSCORES`` option in order to return the scores of the elements together with the elements. The returned list will contain ``value1,score1,...,valueN,scoreN`` instead of ``value1,...,valueN``. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples). .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number of elements in the sorted set and ``M`` the number of elements returned. :param key: The key of the sorted set :type key: :class:`str`, :class:`bytes` :param int start: The starting index of the sorted set :param int stop: The ending index of the sorted set :param bool with_scores: Return the scores with the elements :rtype: list :raises: :exc:`~tredis.exceptions.RedisError` ] variable[command] assign[=] list[[<ast.Constant object at 0x7da20e956980>, <ast.Name object at 0x7da20e954a00>, <ast.Name object at 0x7da20e956560>, <ast.Name object at 0x7da20e955ab0>]] if name[with_scores] begin[:] <ast.AugAssign object at 0x7da20e955930> return[call[name[self]._execute, parameter[name[command]]]]
keyword[def] identifier[zrange] ( identifier[self] , identifier[key] , identifier[start] = literal[int] , identifier[stop] =- literal[int] , identifier[with_scores] = keyword[False] ): literal[string] identifier[command] =[ literal[string] , identifier[key] , identifier[start] , identifier[stop] ] keyword[if] identifier[with_scores] : identifier[command] +=[ literal[string] ] keyword[return] identifier[self] . identifier[_execute] ( identifier[command] )
def zrange(self, key, start=0, stop=-1, with_scores=False): """Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. See :meth:`tredis.Client.zrevrange` when you need the elements ordered from highest to lowest score (and descending lexicographical order for elements with equal score). Both start and stop are zero-based indexes, where ``0`` is the first element, ``1`` is the next element and so on. They can also be negative numbers indicating offsets from the end of the sorted set, with ``-1`` being the last element of the sorted set, ``-2`` the penultimate element and so on. ``start`` and ``stop`` are inclusive ranges, so for example ``ZRANGE myzset 0 1`` will return both the first and the second element of the sorted set. Out of range indexes will not produce an error. If start is larger than the largest index in the sorted set, or ``start > stop``, an empty list is returned. If stop is larger than the end of the sorted set Redis will treat it like it is the last element of the sorted set. It is possible to pass the ``WITHSCORES`` option in order to return the scores of the elements together with the elements. The returned list will contain ``value1,score1,...,valueN,scoreN`` instead of ``value1,...,valueN``. Client libraries are free to return a more appropriate data type (suggestion: an array with (value, score) arrays/tuples). .. note:: **Time complexity**: ``O(log(N)+M)`` with ``N`` being the number of elements in the sorted set and ``M`` the number of elements returned. :param key: The key of the sorted set :type key: :class:`str`, :class:`bytes` :param int start: The starting index of the sorted set :param int stop: The ending index of the sorted set :param bool with_scores: Return the scores with the elements :rtype: list :raises: :exc:`~tredis.exceptions.RedisError` """ command = [b'ZRANGE', key, start, stop] if with_scores: command += ['WITHSCORES'] # depends on [control=['if'], data=[]] return self._execute(command)
def _discover_sensitivity_seq(self, signals: List[RtlSignalBase], seen: set, ctx: SensitivityCtx)\ -> None: """ Discover sensitivity for list of signals """ casualSensitivity = set() for s in signals: s._walk_sensitivity(casualSensitivity, seen, ctx) if ctx.contains_ev_dependency: break # if event dependent sensitivity found do not add other sensitivity if not ctx.contains_ev_dependency: ctx.extend(casualSensitivity)
def function[_discover_sensitivity_seq, parameter[self, signals, seen, ctx]]: constant[ Discover sensitivity for list of signals ] variable[casualSensitivity] assign[=] call[name[set], parameter[]] for taget[name[s]] in starred[name[signals]] begin[:] call[name[s]._walk_sensitivity, parameter[name[casualSensitivity], name[seen], name[ctx]]] if name[ctx].contains_ev_dependency begin[:] break if <ast.UnaryOp object at 0x7da1b03e1210> begin[:] call[name[ctx].extend, parameter[name[casualSensitivity]]]
keyword[def] identifier[_discover_sensitivity_seq] ( identifier[self] , identifier[signals] : identifier[List] [ identifier[RtlSignalBase] ], identifier[seen] : identifier[set] , identifier[ctx] : identifier[SensitivityCtx] )-> keyword[None] : literal[string] identifier[casualSensitivity] = identifier[set] () keyword[for] identifier[s] keyword[in] identifier[signals] : identifier[s] . identifier[_walk_sensitivity] ( identifier[casualSensitivity] , identifier[seen] , identifier[ctx] ) keyword[if] identifier[ctx] . identifier[contains_ev_dependency] : keyword[break] keyword[if] keyword[not] identifier[ctx] . identifier[contains_ev_dependency] : identifier[ctx] . identifier[extend] ( identifier[casualSensitivity] )
def _discover_sensitivity_seq(self, signals: List[RtlSignalBase], seen: set, ctx: SensitivityCtx) -> None: """ Discover sensitivity for list of signals """ casualSensitivity = set() for s in signals: s._walk_sensitivity(casualSensitivity, seen, ctx) if ctx.contains_ev_dependency: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['s']] # if event dependent sensitivity found do not add other sensitivity if not ctx.contains_ev_dependency: ctx.extend(casualSensitivity) # depends on [control=['if'], data=[]]
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints: :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns ------- self """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) else: try: idx = self._dynamicNames.getPositionByName(name) except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) return self.setComponentByPosition( idx, value, verifyConstraints, matchTags, matchConstraints )
def function[setComponentByName, parameter[self, name, value, verifyConstraints, matchTags, matchConstraints]]: constant[Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints: :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns ------- self ] if name[self]._componentTypeLen begin[:] variable[idx] assign[=] call[name[self].componentType.getPositionByName, parameter[name[name]]] return[call[name[self].setComponentByPosition, parameter[name[idx], name[value], name[verifyConstraints], name[matchTags], name[matchConstraints]]]]
keyword[def] identifier[setComponentByName] ( identifier[self] , identifier[name] , identifier[value] = identifier[noValue] , identifier[verifyConstraints] = keyword[True] , identifier[matchTags] = keyword[True] , identifier[matchConstraints] = keyword[True] ): literal[string] keyword[if] identifier[self] . identifier[_componentTypeLen] : identifier[idx] = identifier[self] . identifier[componentType] . identifier[getPositionByName] ( identifier[name] ) keyword[else] : keyword[try] : identifier[idx] = identifier[self] . identifier[_dynamicNames] . identifier[getPositionByName] ( identifier[name] ) keyword[except] identifier[KeyError] : keyword[raise] identifier[error] . identifier[PyAsn1Error] ( literal[string] %( identifier[name] ,)) keyword[return] identifier[self] . identifier[setComponentByPosition] ( identifier[idx] , identifier[value] , identifier[verifyConstraints] , identifier[matchTags] , identifier[matchConstraints] )
def setComponentByName(self, name, value=noValue, verifyConstraints=True, matchTags=True, matchConstraints=True): """Assign |ASN.1| type component by name. Equivalent to Python :class:`dict` item assignment operation (e.g. `[]`). Parameters ---------- name: :class:`str` |ASN.1| type component name Keyword Args ------------ value: :class:`object` or :py:class:`~pyasn1.type.base.PyAsn1Item` derivative A Python value to initialize |ASN.1| component with (if *componentType* is set) or ASN.1 value object to assign to |ASN.1| component. verifyConstraints: :class:`bool` If `False`, skip constraints validation matchTags: :class:`bool` If `False`, skip component tags matching matchConstraints: :class:`bool` If `False`, skip component constraints matching Returns ------- self """ if self._componentTypeLen: idx = self.componentType.getPositionByName(name) # depends on [control=['if'], data=[]] else: try: idx = self._dynamicNames.getPositionByName(name) # depends on [control=['try'], data=[]] except KeyError: raise error.PyAsn1Error('Name %s not found' % (name,)) # depends on [control=['except'], data=[]] return self.setComponentByPosition(idx, value, verifyConstraints, matchTags, matchConstraints)
def _calc_concat_dim_coord(dim): """ Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension. """ from .dataarray import DataArray if isinstance(dim, str): coord = None elif not isinstance(dim, (DataArray, Variable)): dim_name = getattr(dim, 'name', None) if dim_name is None: dim_name = 'concat_dim' coord = IndexVariable(dim_name, dim) dim = dim_name elif not isinstance(dim, DataArray): coord = as_variable(dim).to_index_variable() dim, = coord.dims else: coord = dim dim, = coord.dims return dim, coord
def function[_calc_concat_dim_coord, parameter[dim]]: constant[ Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension. ] from relative_module[dataarray] import module[DataArray] if call[name[isinstance], parameter[name[dim], name[str]]] begin[:] variable[coord] assign[=] constant[None] return[tuple[[<ast.Name object at 0x7da18c4cca60>, <ast.Name object at 0x7da18c4cf910>]]]
keyword[def] identifier[_calc_concat_dim_coord] ( identifier[dim] ): literal[string] keyword[from] . identifier[dataarray] keyword[import] identifier[DataArray] keyword[if] identifier[isinstance] ( identifier[dim] , identifier[str] ): identifier[coord] = keyword[None] keyword[elif] keyword[not] identifier[isinstance] ( identifier[dim] ,( identifier[DataArray] , identifier[Variable] )): identifier[dim_name] = identifier[getattr] ( identifier[dim] , literal[string] , keyword[None] ) keyword[if] identifier[dim_name] keyword[is] keyword[None] : identifier[dim_name] = literal[string] identifier[coord] = identifier[IndexVariable] ( identifier[dim_name] , identifier[dim] ) identifier[dim] = identifier[dim_name] keyword[elif] keyword[not] identifier[isinstance] ( identifier[dim] , identifier[DataArray] ): identifier[coord] = identifier[as_variable] ( identifier[dim] ). identifier[to_index_variable] () identifier[dim] ,= identifier[coord] . identifier[dims] keyword[else] : identifier[coord] = identifier[dim] identifier[dim] ,= identifier[coord] . identifier[dims] keyword[return] identifier[dim] , identifier[coord]
def _calc_concat_dim_coord(dim): """ Infer the dimension name and 1d coordinate variable (if appropriate) for concatenating along the new dimension. """ from .dataarray import DataArray if isinstance(dim, str): coord = None # depends on [control=['if'], data=[]] elif not isinstance(dim, (DataArray, Variable)): dim_name = getattr(dim, 'name', None) if dim_name is None: dim_name = 'concat_dim' # depends on [control=['if'], data=['dim_name']] coord = IndexVariable(dim_name, dim) dim = dim_name # depends on [control=['if'], data=[]] elif not isinstance(dim, DataArray): coord = as_variable(dim).to_index_variable() (dim,) = coord.dims # depends on [control=['if'], data=[]] else: coord = dim (dim,) = coord.dims return (dim, coord)
def from_array(filename, data, iline=189, xline=193, format=SegySampleFormat.IBM_FLOAT_4_BYTE, dt=4000, delrt=0): """ Create a new SEGY file from an n-dimentional array. Create a structured SEGY file with defaulted headers from a 2-, 3- or 4-dimensional array. ilines, xlines, offsets and samples are inferred from the size of the array. Please refer to the documentation for functions from_array2D, from_array3D and from_array4D to see how the arrays are interpreted. Structure-defining fields in the binary header and in the traceheaders are set accordingly. Such fields include, but are not limited to iline, xline and offset. The file also contains a defaulted textual header. Parameters ---------- filename : string-like Path to new file data : 2-,3- or 4-dimensional array-like iline : int or segyio.TraceField Inline number field in the trace headers. Defaults to 189 as per the SEG-Y rev1 specification xline : int or segyio.TraceField Crossline number field in the trace headers. Defaults to 193 as per the SEG-Y rev1 specification format : int or segyio.SegySampleFormat Sample format field in the trace header. Defaults to IBM float 4 byte dt : int-like sample interval delrt : int-like Notes ----- .. versionadded:: 1.8 Examples -------- Create a file from a 3D array, open it and read an iline: >>> segyio.tools.from_array(path, array3d) >>> segyio.open(path, mode) as f: ... iline = f.iline[0] ... """ dt = int(dt) delrt = int(delrt) data = np.asarray(data) dimensions = len(data.shape) if dimensions not in range(2, 5): problem = "Expected 2, 3, or 4 dimensions, {} was given".format(dimensions) raise ValueError(problem) spec = segyio.spec() spec.iline = iline spec.xline = xline spec.format = format spec.sorting = TraceSortingFormat.INLINE_SORTING if dimensions == 2: spec.ilines = [1] spec.xlines = list(range(1, np.size(data,0) + 1)) spec.samples = list(range(np.size(data,1))) spec.tracecount = np.size(data, 1) if dimensions == 3: spec.ilines = list(range(1, np.size(data, 0) + 1)) spec.xlines = list(range(1, np.size(data, 1) + 1)) spec.samples = list(range(np.size(data, 2))) if dimensions == 4: spec.ilines = list(range(1, np.size(data, 0) + 1)) spec.xlines = list(range(1, np.size(data, 1) + 1)) spec.offsets = list(range(1, np.size(data, 2)+ 1)) spec.samples = list(range(np.size(data,3))) samplecount = len(spec.samples) with segyio.create(filename, spec) as f: tr = 0 for ilno, il in enumerate(spec.ilines): for xlno, xl in enumerate(spec.xlines): for offno, off in enumerate(spec.offsets): f.header[tr] = { segyio.su.tracf : tr, segyio.su.cdpt : tr, segyio.su.offset : off, segyio.su.ns : samplecount, segyio.su.dt : dt, segyio.su.delrt : delrt, segyio.su.iline : il, segyio.su.xline : xl } if dimensions == 2: f.trace[tr] = data[tr, :] if dimensions == 3: f.trace[tr] = data[ilno, xlno, :] if dimensions == 4: f.trace[tr] = data[ilno, xlno, offno, :] tr += 1 f.bin.update( tsort=TraceSortingFormat.INLINE_SORTING, hdt=dt, dto=dt )
def function[from_array, parameter[filename, data, iline, xline, format, dt, delrt]]: constant[ Create a new SEGY file from an n-dimentional array. Create a structured SEGY file with defaulted headers from a 2-, 3- or 4-dimensional array. ilines, xlines, offsets and samples are inferred from the size of the array. Please refer to the documentation for functions from_array2D, from_array3D and from_array4D to see how the arrays are interpreted. Structure-defining fields in the binary header and in the traceheaders are set accordingly. Such fields include, but are not limited to iline, xline and offset. The file also contains a defaulted textual header. Parameters ---------- filename : string-like Path to new file data : 2-,3- or 4-dimensional array-like iline : int or segyio.TraceField Inline number field in the trace headers. Defaults to 189 as per the SEG-Y rev1 specification xline : int or segyio.TraceField Crossline number field in the trace headers. Defaults to 193 as per the SEG-Y rev1 specification format : int or segyio.SegySampleFormat Sample format field in the trace header. Defaults to IBM float 4 byte dt : int-like sample interval delrt : int-like Notes ----- .. versionadded:: 1.8 Examples -------- Create a file from a 3D array, open it and read an iline: >>> segyio.tools.from_array(path, array3d) >>> segyio.open(path, mode) as f: ... iline = f.iline[0] ... ] variable[dt] assign[=] call[name[int], parameter[name[dt]]] variable[delrt] assign[=] call[name[int], parameter[name[delrt]]] variable[data] assign[=] call[name[np].asarray, parameter[name[data]]] variable[dimensions] assign[=] call[name[len], parameter[name[data].shape]] if compare[name[dimensions] <ast.NotIn object at 0x7da2590d7190> call[name[range], parameter[constant[2], constant[5]]]] begin[:] variable[problem] assign[=] call[constant[Expected 2, 3, or 4 dimensions, {} was given].format, parameter[name[dimensions]]] <ast.Raise object at 0x7da20c6e6140> variable[spec] assign[=] call[name[segyio].spec, parameter[]] name[spec].iline assign[=] name[iline] name[spec].xline assign[=] name[xline] name[spec].format assign[=] name[format] name[spec].sorting assign[=] name[TraceSortingFormat].INLINE_SORTING if compare[name[dimensions] equal[==] constant[2]] begin[:] name[spec].ilines assign[=] list[[<ast.Constant object at 0x7da20c6e68c0>]] name[spec].xlines assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[0]]] + constant[1]]]]]] name[spec].samples assign[=] call[name[list], parameter[call[name[range], parameter[call[name[np].size, parameter[name[data], constant[1]]]]]]] name[spec].tracecount assign[=] call[name[np].size, parameter[name[data], constant[1]]] if compare[name[dimensions] equal[==] constant[3]] begin[:] name[spec].ilines assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[0]]] + constant[1]]]]]] name[spec].xlines assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[1]]] + constant[1]]]]]] name[spec].samples assign[=] call[name[list], parameter[call[name[range], parameter[call[name[np].size, parameter[name[data], constant[2]]]]]]] if compare[name[dimensions] equal[==] constant[4]] begin[:] name[spec].ilines assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[0]]] + constant[1]]]]]] name[spec].xlines assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[1]]] + constant[1]]]]]] name[spec].offsets assign[=] call[name[list], parameter[call[name[range], parameter[constant[1], binary_operation[call[name[np].size, parameter[name[data], constant[2]]] + constant[1]]]]]] name[spec].samples assign[=] call[name[list], parameter[call[name[range], parameter[call[name[np].size, parameter[name[data], constant[3]]]]]]] variable[samplecount] assign[=] call[name[len], parameter[name[spec].samples]] with call[name[segyio].create, parameter[name[filename], name[spec]]] begin[:] variable[tr] assign[=] constant[0] for taget[tuple[[<ast.Name object at 0x7da1b17b69e0>, <ast.Name object at 0x7da1b17b64a0>]]] in starred[call[name[enumerate], parameter[name[spec].ilines]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da1b17b6b00>, <ast.Name object at 0x7da1b17b67a0>]]] in starred[call[name[enumerate], parameter[name[spec].xlines]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da1b17b6260>, <ast.Name object at 0x7da1b17b6c80>]]] in starred[call[name[enumerate], parameter[name[spec].offsets]]] begin[:] call[name[f].header][name[tr]] assign[=] dictionary[[<ast.Attribute object at 0x7da1b17b4100>, <ast.Attribute object at 0x7da1b17b6b30>, <ast.Attribute object at 0x7da1b17b6320>, <ast.Attribute object at 0x7da1b17b6800>, <ast.Attribute object at 0x7da1b17b45b0>, <ast.Attribute object at 0x7da1b17b5150>, <ast.Attribute object at 0x7da1b17b43a0>, <ast.Attribute object at 0x7da1b17b5ea0>], [<ast.Name object at 0x7da1b17b4940>, <ast.Name object at 0x7da1b17b5d80>, <ast.Name object at 0x7da1b17b7a30>, <ast.Name object at 0x7da1b17b5c00>, <ast.Name object at 0x7da1b17b7b80>, <ast.Name object at 0x7da1b17b6350>, <ast.Name object at 0x7da1b17b53f0>, <ast.Name object at 0x7da1b17b5030>]] if compare[name[dimensions] equal[==] constant[2]] begin[:] call[name[f].trace][name[tr]] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b17b4250>, <ast.Slice object at 0x7da1b17b68f0>]]] if compare[name[dimensions] equal[==] constant[3]] begin[:] call[name[f].trace][name[tr]] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b17b5ff0>, <ast.Name object at 0x7da1b17b42e0>, <ast.Slice object at 0x7da1b17b6980>]]] if compare[name[dimensions] equal[==] constant[4]] begin[:] call[name[f].trace][name[tr]] assign[=] call[name[data]][tuple[[<ast.Name object at 0x7da1b17b56f0>, <ast.Name object at 0x7da1b17b6f80>, <ast.Name object at 0x7da1b17b5ab0>, <ast.Slice object at 0x7da1b17b6b60>]]] <ast.AugAssign object at 0x7da1b17b7cd0> call[name[f].bin.update, parameter[]]
keyword[def] identifier[from_array] ( identifier[filename] , identifier[data] , identifier[iline] = literal[int] , identifier[xline] = literal[int] , identifier[format] = identifier[SegySampleFormat] . identifier[IBM_FLOAT_4_BYTE] , identifier[dt] = literal[int] , identifier[delrt] = literal[int] ): literal[string] identifier[dt] = identifier[int] ( identifier[dt] ) identifier[delrt] = identifier[int] ( identifier[delrt] ) identifier[data] = identifier[np] . identifier[asarray] ( identifier[data] ) identifier[dimensions] = identifier[len] ( identifier[data] . identifier[shape] ) keyword[if] identifier[dimensions] keyword[not] keyword[in] identifier[range] ( literal[int] , literal[int] ): identifier[problem] = literal[string] . identifier[format] ( identifier[dimensions] ) keyword[raise] identifier[ValueError] ( identifier[problem] ) identifier[spec] = identifier[segyio] . identifier[spec] () identifier[spec] . identifier[iline] = identifier[iline] identifier[spec] . identifier[xline] = identifier[xline] identifier[spec] . identifier[format] = identifier[format] identifier[spec] . identifier[sorting] = identifier[TraceSortingFormat] . identifier[INLINE_SORTING] keyword[if] identifier[dimensions] == literal[int] : identifier[spec] . identifier[ilines] =[ literal[int] ] identifier[spec] . identifier[xlines] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[samples] = identifier[list] ( identifier[range] ( identifier[np] . identifier[size] ( identifier[data] , literal[int] ))) identifier[spec] . identifier[tracecount] = identifier[np] . identifier[size] ( identifier[data] , literal[int] ) keyword[if] identifier[dimensions] == literal[int] : identifier[spec] . identifier[ilines] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[xlines] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[samples] = identifier[list] ( identifier[range] ( identifier[np] . identifier[size] ( identifier[data] , literal[int] ))) keyword[if] identifier[dimensions] == literal[int] : identifier[spec] . identifier[ilines] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[xlines] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[offsets] = identifier[list] ( identifier[range] ( literal[int] , identifier[np] . identifier[size] ( identifier[data] , literal[int] )+ literal[int] )) identifier[spec] . identifier[samples] = identifier[list] ( identifier[range] ( identifier[np] . identifier[size] ( identifier[data] , literal[int] ))) identifier[samplecount] = identifier[len] ( identifier[spec] . identifier[samples] ) keyword[with] identifier[segyio] . identifier[create] ( identifier[filename] , identifier[spec] ) keyword[as] identifier[f] : identifier[tr] = literal[int] keyword[for] identifier[ilno] , identifier[il] keyword[in] identifier[enumerate] ( identifier[spec] . identifier[ilines] ): keyword[for] identifier[xlno] , identifier[xl] keyword[in] identifier[enumerate] ( identifier[spec] . identifier[xlines] ): keyword[for] identifier[offno] , identifier[off] keyword[in] identifier[enumerate] ( identifier[spec] . identifier[offsets] ): identifier[f] . identifier[header] [ identifier[tr] ]={ identifier[segyio] . identifier[su] . identifier[tracf] : identifier[tr] , identifier[segyio] . identifier[su] . identifier[cdpt] : identifier[tr] , identifier[segyio] . identifier[su] . identifier[offset] : identifier[off] , identifier[segyio] . identifier[su] . identifier[ns] : identifier[samplecount] , identifier[segyio] . identifier[su] . identifier[dt] : identifier[dt] , identifier[segyio] . identifier[su] . identifier[delrt] : identifier[delrt] , identifier[segyio] . identifier[su] . identifier[iline] : identifier[il] , identifier[segyio] . identifier[su] . identifier[xline] : identifier[xl] } keyword[if] identifier[dimensions] == literal[int] : identifier[f] . identifier[trace] [ identifier[tr] ]= identifier[data] [ identifier[tr] ,:] keyword[if] identifier[dimensions] == literal[int] : identifier[f] . identifier[trace] [ identifier[tr] ]= identifier[data] [ identifier[ilno] , identifier[xlno] ,:] keyword[if] identifier[dimensions] == literal[int] : identifier[f] . identifier[trace] [ identifier[tr] ]= identifier[data] [ identifier[ilno] , identifier[xlno] , identifier[offno] ,:] identifier[tr] += literal[int] identifier[f] . identifier[bin] . identifier[update] ( identifier[tsort] = identifier[TraceSortingFormat] . identifier[INLINE_SORTING] , identifier[hdt] = identifier[dt] , identifier[dto] = identifier[dt] )
def from_array(filename, data, iline=189, xline=193, format=SegySampleFormat.IBM_FLOAT_4_BYTE, dt=4000, delrt=0): """ Create a new SEGY file from an n-dimentional array. Create a structured SEGY file with defaulted headers from a 2-, 3- or 4-dimensional array. ilines, xlines, offsets and samples are inferred from the size of the array. Please refer to the documentation for functions from_array2D, from_array3D and from_array4D to see how the arrays are interpreted. Structure-defining fields in the binary header and in the traceheaders are set accordingly. Such fields include, but are not limited to iline, xline and offset. The file also contains a defaulted textual header. Parameters ---------- filename : string-like Path to new file data : 2-,3- or 4-dimensional array-like iline : int or segyio.TraceField Inline number field in the trace headers. Defaults to 189 as per the SEG-Y rev1 specification xline : int or segyio.TraceField Crossline number field in the trace headers. Defaults to 193 as per the SEG-Y rev1 specification format : int or segyio.SegySampleFormat Sample format field in the trace header. Defaults to IBM float 4 byte dt : int-like sample interval delrt : int-like Notes ----- .. versionadded:: 1.8 Examples -------- Create a file from a 3D array, open it and read an iline: >>> segyio.tools.from_array(path, array3d) >>> segyio.open(path, mode) as f: ... iline = f.iline[0] ... """ dt = int(dt) delrt = int(delrt) data = np.asarray(data) dimensions = len(data.shape) if dimensions not in range(2, 5): problem = 'Expected 2, 3, or 4 dimensions, {} was given'.format(dimensions) raise ValueError(problem) # depends on [control=['if'], data=['dimensions']] spec = segyio.spec() spec.iline = iline spec.xline = xline spec.format = format spec.sorting = TraceSortingFormat.INLINE_SORTING if dimensions == 2: spec.ilines = [1] spec.xlines = list(range(1, np.size(data, 0) + 1)) spec.samples = list(range(np.size(data, 1))) spec.tracecount = np.size(data, 1) # depends on [control=['if'], data=[]] if dimensions == 3: spec.ilines = list(range(1, np.size(data, 0) + 1)) spec.xlines = list(range(1, np.size(data, 1) + 1)) spec.samples = list(range(np.size(data, 2))) # depends on [control=['if'], data=[]] if dimensions == 4: spec.ilines = list(range(1, np.size(data, 0) + 1)) spec.xlines = list(range(1, np.size(data, 1) + 1)) spec.offsets = list(range(1, np.size(data, 2) + 1)) spec.samples = list(range(np.size(data, 3))) # depends on [control=['if'], data=[]] samplecount = len(spec.samples) with segyio.create(filename, spec) as f: tr = 0 for (ilno, il) in enumerate(spec.ilines): for (xlno, xl) in enumerate(spec.xlines): for (offno, off) in enumerate(spec.offsets): f.header[tr] = {segyio.su.tracf: tr, segyio.su.cdpt: tr, segyio.su.offset: off, segyio.su.ns: samplecount, segyio.su.dt: dt, segyio.su.delrt: delrt, segyio.su.iline: il, segyio.su.xline: xl} if dimensions == 2: f.trace[tr] = data[tr, :] # depends on [control=['if'], data=[]] if dimensions == 3: f.trace[tr] = data[ilno, xlno, :] # depends on [control=['if'], data=[]] if dimensions == 4: f.trace[tr] = data[ilno, xlno, offno, :] # depends on [control=['if'], data=[]] tr += 1 # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] f.bin.update(tsort=TraceSortingFormat.INLINE_SORTING, hdt=dt, dto=dt) # depends on [control=['with'], data=['f']]
def _jnzero16(ins): """ Jumps if top of the stack (16bit) is != 0 to arg(1) """ value = ins.quad[1] if is_int(value): if int(value) != 0: return ['jp %s' % str(ins.quad[2])] # Always true else: return [] output = _16bit_oper(value) output.append('ld a, h') output.append('or l') output.append('jp nz, %s' % str(ins.quad[2])) return output
def function[_jnzero16, parameter[ins]]: constant[ Jumps if top of the stack (16bit) is != 0 to arg(1) ] variable[value] assign[=] call[name[ins].quad][constant[1]] if call[name[is_int], parameter[name[value]]] begin[:] if compare[call[name[int], parameter[name[value]]] not_equal[!=] constant[0]] begin[:] return[list[[<ast.BinOp object at 0x7da1b05419f0>]]] variable[output] assign[=] call[name[_16bit_oper], parameter[name[value]]] call[name[output].append, parameter[constant[ld a, h]]] call[name[output].append, parameter[constant[or l]]] call[name[output].append, parameter[binary_operation[constant[jp nz, %s] <ast.Mod object at 0x7da2590d6920> call[name[str], parameter[call[name[ins].quad][constant[2]]]]]]] return[name[output]]
keyword[def] identifier[_jnzero16] ( identifier[ins] ): literal[string] identifier[value] = identifier[ins] . identifier[quad] [ literal[int] ] keyword[if] identifier[is_int] ( identifier[value] ): keyword[if] identifier[int] ( identifier[value] )!= literal[int] : keyword[return] [ literal[string] % identifier[str] ( identifier[ins] . identifier[quad] [ literal[int] ])] keyword[else] : keyword[return] [] identifier[output] = identifier[_16bit_oper] ( identifier[value] ) identifier[output] . identifier[append] ( literal[string] ) identifier[output] . identifier[append] ( literal[string] ) identifier[output] . identifier[append] ( literal[string] % identifier[str] ( identifier[ins] . identifier[quad] [ literal[int] ])) keyword[return] identifier[output]
def _jnzero16(ins): """ Jumps if top of the stack (16bit) is != 0 to arg(1) """ value = ins.quad[1] if is_int(value): if int(value) != 0: return ['jp %s' % str(ins.quad[2])] # Always true # depends on [control=['if'], data=[]] else: return [] # depends on [control=['if'], data=[]] output = _16bit_oper(value) output.append('ld a, h') output.append('or l') output.append('jp nz, %s' % str(ins.quad[2])) return output
def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp") arp_entry = ET.SubElement(hide_arp_holder, "arp-entry") arp_ip_address_key = ET.SubElement(arp_entry, "arp-ip-address") arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, "interfacetype") HundredGigabitEthernet = ET.SubElement(interfacetype, "HundredGigabitEthernet") HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, "HundredGigabitEthernet") HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[hide_arp_holder] assign[=] call[name[ET].SubElement, parameter[name[config], constant[hide-arp-holder]]] variable[arp_entry] assign[=] call[name[ET].SubElement, parameter[name[hide_arp_holder], constant[arp-entry]]] variable[arp_ip_address_key] assign[=] call[name[ET].SubElement, parameter[name[arp_entry], constant[arp-ip-address]]] name[arp_ip_address_key].text assign[=] call[name[kwargs].pop, parameter[constant[arp_ip_address]]] variable[interfacetype] assign[=] call[name[ET].SubElement, parameter[name[arp_entry], constant[interfacetype]]] variable[HundredGigabitEthernet] assign[=] call[name[ET].SubElement, parameter[name[interfacetype], constant[HundredGigabitEthernet]]] variable[HundredGigabitEthernet] assign[=] call[name[ET].SubElement, parameter[name[HundredGigabitEthernet], constant[HundredGigabitEthernet]]] name[HundredGigabitEthernet].text assign[=] call[name[kwargs].pop, parameter[constant[HundredGigabitEthernet]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[hide_arp_holder] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifier[xmlns] = literal[string] ) identifier[arp_entry] = identifier[ET] . identifier[SubElement] ( identifier[hide_arp_holder] , literal[string] ) identifier[arp_ip_address_key] = identifier[ET] . identifier[SubElement] ( identifier[arp_entry] , literal[string] ) identifier[arp_ip_address_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[interfacetype] = identifier[ET] . identifier[SubElement] ( identifier[arp_entry] , literal[string] ) identifier[HundredGigabitEthernet] = identifier[ET] . identifier[SubElement] ( identifier[interfacetype] , literal[string] ) identifier[HundredGigabitEthernet] = identifier[ET] . identifier[SubElement] ( identifier[HundredGigabitEthernet] , literal[string] ) identifier[HundredGigabitEthernet] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] ) keyword[return] identifier[callback] ( identifier[config] )
def hide_arp_holder_arp_entry_interfacetype_HundredGigabitEthernet_HundredGigabitEthernet(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') hide_arp_holder = ET.SubElement(config, 'hide-arp-holder', xmlns='urn:brocade.com:mgmt:brocade-arp') arp_entry = ET.SubElement(hide_arp_holder, 'arp-entry') arp_ip_address_key = ET.SubElement(arp_entry, 'arp-ip-address') arp_ip_address_key.text = kwargs.pop('arp_ip_address') interfacetype = ET.SubElement(arp_entry, 'interfacetype') HundredGigabitEthernet = ET.SubElement(interfacetype, 'HundredGigabitEthernet') HundredGigabitEthernet = ET.SubElement(HundredGigabitEthernet, 'HundredGigabitEthernet') HundredGigabitEthernet.text = kwargs.pop('HundredGigabitEthernet') callback = kwargs.pop('callback', self._callback) return callback(config)
def layers(self): """ gets the layers for the feature service """ if self._layers is None: self.__init() self._getLayers() return self._layers
def function[layers, parameter[self]]: constant[ gets the layers for the feature service ] if compare[name[self]._layers is constant[None]] begin[:] call[name[self].__init, parameter[]] call[name[self]._getLayers, parameter[]] return[name[self]._layers]
keyword[def] identifier[layers] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_layers] keyword[is] keyword[None] : identifier[self] . identifier[__init] () identifier[self] . identifier[_getLayers] () keyword[return] identifier[self] . identifier[_layers]
def layers(self): """ gets the layers for the feature service """ if self._layers is None: self.__init() # depends on [control=['if'], data=[]] self._getLayers() return self._layers
def db_get_val(self, table, record, column): """ Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL """ command = ovs_vsctl.VSCtlCommand('get', (table, record, column)) self.run_command([command]) assert len(command.result) == 1 return command.result[0]
def function[db_get_val, parameter[self, table, record, column]]: constant[ Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL ] variable[command] assign[=] call[name[ovs_vsctl].VSCtlCommand, parameter[constant[get], tuple[[<ast.Name object at 0x7da1b1a36c80>, <ast.Name object at 0x7da1b1a36f50>, <ast.Name object at 0x7da1b1a35fc0>]]]] call[name[self].run_command, parameter[list[[<ast.Name object at 0x7da1b1a34970>]]]] assert[compare[call[name[len], parameter[name[command].result]] equal[==] constant[1]]] return[call[name[command].result][constant[0]]]
keyword[def] identifier[db_get_val] ( identifier[self] , identifier[table] , identifier[record] , identifier[column] ): literal[string] identifier[command] = identifier[ovs_vsctl] . identifier[VSCtlCommand] ( literal[string] ,( identifier[table] , identifier[record] , identifier[column] )) identifier[self] . identifier[run_command] ([ identifier[command] ]) keyword[assert] identifier[len] ( identifier[command] . identifier[result] )== literal[int] keyword[return] identifier[command] . identifier[result] [ literal[int] ]
def db_get_val(self, table, record, column): """ Gets values of 'column' in 'record' in 'table'. This method is corresponding to the following ovs-vsctl command:: $ ovs-vsctl get TBL REC COL """ command = ovs_vsctl.VSCtlCommand('get', (table, record, column)) self.run_command([command]) assert len(command.result) == 1 return command.result[0]
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. Baidu's API will always return at most one result. .. versionadded:: 1.14.0 :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = { 'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query), } url = self._construct_url(params) logger.debug("%s.reverse: %s", self.__class__.__name__, url) return self._parse_reverse_json( self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one )
def function[reverse, parameter[self, query, exactly_one, timeout]]: constant[ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. Baidu's API will always return at most one result. .. versionadded:: 1.14.0 :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. ] variable[params] assign[=] dictionary[[<ast.Constant object at 0x7da20c6c77f0>, <ast.Constant object at 0x7da20c6c4190>, <ast.Constant object at 0x7da20c6c4700>], [<ast.Attribute object at 0x7da20c6c62c0>, <ast.Constant object at 0x7da20c6c7a30>, <ast.Call object at 0x7da20c6c63e0>]] variable[url] assign[=] call[name[self]._construct_url, parameter[name[params]]] call[name[logger].debug, parameter[constant[%s.reverse: %s], name[self].__class__.__name__, name[url]]] return[call[name[self]._parse_reverse_json, parameter[call[name[self]._call_geocoder, parameter[name[url]]]]]]
keyword[def] identifier[reverse] ( identifier[self] , identifier[query] , identifier[exactly_one] = keyword[True] , identifier[timeout] = identifier[DEFAULT_SENTINEL] ): literal[string] identifier[params] ={ literal[string] : identifier[self] . identifier[api_key] , literal[string] : literal[string] , literal[string] : identifier[self] . identifier[_coerce_point_to_string] ( identifier[query] ), } identifier[url] = identifier[self] . identifier[_construct_url] ( identifier[params] ) identifier[logger] . identifier[debug] ( literal[string] , identifier[self] . identifier[__class__] . identifier[__name__] , identifier[url] ) keyword[return] identifier[self] . identifier[_parse_reverse_json] ( identifier[self] . identifier[_call_geocoder] ( identifier[url] , identifier[timeout] = identifier[timeout] ), identifier[exactly_one] = identifier[exactly_one] )
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitude, longitude)``, or string as ``"%(latitude)s, %(longitude)s"``. :param bool exactly_one: Return one result or a list of results, if available. Baidu's API will always return at most one result. .. versionadded:: 1.14.0 :param int timeout: Time, in seconds, to wait for the geocoding service to respond before raising a :class:`geopy.exc.GeocoderTimedOut` exception. Set this only if you wish to override, on this call only, the value set during the geocoder's initialization. :rtype: ``None``, :class:`geopy.location.Location` or a list of them, if ``exactly_one=False``. """ params = {'ak': self.api_key, 'output': 'json', 'location': self._coerce_point_to_string(query)} url = self._construct_url(params) logger.debug('%s.reverse: %s', self.__class__.__name__, url) return self._parse_reverse_json(self._call_geocoder(url, timeout=timeout), exactly_one=exactly_one)
def _evalDateStd(self, datetimeString, sourceTime): """ Evaluate text passed by L{_partialParseDateStd()} """ s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format 07/21/2006 return self.parseDate(s, sourceTime)
def function[_evalDateStd, parameter[self, datetimeString, sourceTime]]: constant[ Evaluate text passed by L{_partialParseDateStd()} ] variable[s] assign[=] call[name[datetimeString].strip, parameter[]] variable[sourceTime] assign[=] call[name[self]._evalDT, parameter[name[datetimeString], name[sourceTime]]] return[call[name[self].parseDate, parameter[name[s], name[sourceTime]]]]
keyword[def] identifier[_evalDateStd] ( identifier[self] , identifier[datetimeString] , identifier[sourceTime] ): literal[string] identifier[s] = identifier[datetimeString] . identifier[strip] () identifier[sourceTime] = identifier[self] . identifier[_evalDT] ( identifier[datetimeString] , identifier[sourceTime] ) keyword[return] identifier[self] . identifier[parseDate] ( identifier[s] , identifier[sourceTime] )
def _evalDateStd(self, datetimeString, sourceTime): """ Evaluate text passed by L{_partialParseDateStd()} """ s = datetimeString.strip() sourceTime = self._evalDT(datetimeString, sourceTime) # Given string is in the format 07/21/2006 return self.parseDate(s, sourceTime)
def formjoinin(self): ''' <+- * / <+- prop ''' self.ignore(whitespace) self.nextmust('<+-') self.ignore(whitespace) if self.nextchar() == '*': self.offs += 1 return s_ast.PivotIn(isjoin=True) prop = self.absprop() return s_ast.PivotInFrom(kids=(prop,), isjoin=True)
def function[formjoinin, parameter[self]]: constant[ <+- * / <+- prop ] call[name[self].ignore, parameter[name[whitespace]]] call[name[self].nextmust, parameter[constant[<+-]]] call[name[self].ignore, parameter[name[whitespace]]] if compare[call[name[self].nextchar, parameter[]] equal[==] constant[*]] begin[:] <ast.AugAssign object at 0x7da18eb56bc0> return[call[name[s_ast].PivotIn, parameter[]]] variable[prop] assign[=] call[name[self].absprop, parameter[]] return[call[name[s_ast].PivotInFrom, parameter[]]]
keyword[def] identifier[formjoinin] ( identifier[self] ): literal[string] identifier[self] . identifier[ignore] ( identifier[whitespace] ) identifier[self] . identifier[nextmust] ( literal[string] ) identifier[self] . identifier[ignore] ( identifier[whitespace] ) keyword[if] identifier[self] . identifier[nextchar] ()== literal[string] : identifier[self] . identifier[offs] += literal[int] keyword[return] identifier[s_ast] . identifier[PivotIn] ( identifier[isjoin] = keyword[True] ) identifier[prop] = identifier[self] . identifier[absprop] () keyword[return] identifier[s_ast] . identifier[PivotInFrom] ( identifier[kids] =( identifier[prop] ,), identifier[isjoin] = keyword[True] )
def formjoinin(self): """ <+- * / <+- prop """ self.ignore(whitespace) self.nextmust('<+-') self.ignore(whitespace) if self.nextchar() == '*': self.offs += 1 return s_ast.PivotIn(isjoin=True) # depends on [control=['if'], data=[]] prop = self.absprop() return s_ast.PivotInFrom(kids=(prop,), isjoin=True)
def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by( family=family, started_at=started_at, status=status, ) return query.first()
def function[find_analysis, parameter[self, family, started_at, status]]: constant[Find a single analysis.] variable[query] assign[=] call[name[self].Analysis.query.filter_by, parameter[]] return[call[name[query].first, parameter[]]]
keyword[def] identifier[find_analysis] ( identifier[self] , identifier[family] , identifier[started_at] , identifier[status] ): literal[string] identifier[query] = identifier[self] . identifier[Analysis] . identifier[query] . identifier[filter_by] ( identifier[family] = identifier[family] , identifier[started_at] = identifier[started_at] , identifier[status] = identifier[status] , ) keyword[return] identifier[query] . identifier[first] ()
def find_analysis(self, family, started_at, status): """Find a single analysis.""" query = self.Analysis.query.filter_by(family=family, started_at=started_at, status=status) return query.first()
def unique_rows(arr, return_index=False, return_inverse=False): """Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_index : bool, optional If True, the indices of the unique rows in the array will also be returned. I.e., unique = arr[idx]. Default is False (don't return indices). return_inverse: bool, optional If True, the indices in the unique array to reconstruct the original array will also be returned. I.e., arr = unique[inv]. Default is False (don't return inverse). Returns ------- unique : :py:class:`Array`, (`p`, `n`) where `p` <= `m` The array `arr` with duplicate rows removed. """ b = scipy.ascontiguousarray(arr).view( scipy.dtype((scipy.void, arr.dtype.itemsize * arr.shape[1])) ) try: out = scipy.unique(b, return_index=True, return_inverse=return_inverse) dum = out[0] idx = out[1] if return_inverse: inv = out[2] except TypeError: if return_inverse: raise RuntimeError( "Error in scipy.unique on older versions of numpy prevents " "return_inverse from working!" ) # Handle bug in numpy 1.6.2: rows = [_Row(row) for row in b] srt_idx = sorted(range(len(rows)), key=rows.__getitem__) rows = scipy.asarray(rows)[srt_idx] row_cmp = [-1] for k in xrange(1, len(srt_idx)): row_cmp.append(rows[k-1].__cmp__(rows[k])) row_cmp = scipy.asarray(row_cmp) transition_idxs = scipy.where(row_cmp != 0)[0] idx = scipy.asarray(srt_idx)[transition_idxs] out = arr[idx] if return_index: out = (out, idx) elif return_inverse: out = (out, inv) elif return_index and return_inverse: out = (out, idx, inv) return out
def function[unique_rows, parameter[arr, return_index, return_inverse]]: constant[Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_index : bool, optional If True, the indices of the unique rows in the array will also be returned. I.e., unique = arr[idx]. Default is False (don't return indices). return_inverse: bool, optional If True, the indices in the unique array to reconstruct the original array will also be returned. I.e., arr = unique[inv]. Default is False (don't return inverse). Returns ------- unique : :py:class:`Array`, (`p`, `n`) where `p` <= `m` The array `arr` with duplicate rows removed. ] variable[b] assign[=] call[call[name[scipy].ascontiguousarray, parameter[name[arr]]].view, parameter[call[name[scipy].dtype, parameter[tuple[[<ast.Attribute object at 0x7da20c7c9b70>, <ast.BinOp object at 0x7da20c7cb130>]]]]]] <ast.Try object at 0x7da20c7cb7f0> variable[out] assign[=] call[name[arr]][name[idx]] if name[return_index] begin[:] variable[out] assign[=] tuple[[<ast.Name object at 0x7da20c7cb790>, <ast.Name object at 0x7da20c7c9510>]] return[name[out]]
keyword[def] identifier[unique_rows] ( identifier[arr] , identifier[return_index] = keyword[False] , identifier[return_inverse] = keyword[False] ): literal[string] identifier[b] = identifier[scipy] . identifier[ascontiguousarray] ( identifier[arr] ). identifier[view] ( identifier[scipy] . identifier[dtype] (( identifier[scipy] . identifier[void] , identifier[arr] . identifier[dtype] . identifier[itemsize] * identifier[arr] . identifier[shape] [ literal[int] ])) ) keyword[try] : identifier[out] = identifier[scipy] . identifier[unique] ( identifier[b] , identifier[return_index] = keyword[True] , identifier[return_inverse] = identifier[return_inverse] ) identifier[dum] = identifier[out] [ literal[int] ] identifier[idx] = identifier[out] [ literal[int] ] keyword[if] identifier[return_inverse] : identifier[inv] = identifier[out] [ literal[int] ] keyword[except] identifier[TypeError] : keyword[if] identifier[return_inverse] : keyword[raise] identifier[RuntimeError] ( literal[string] literal[string] ) identifier[rows] =[ identifier[_Row] ( identifier[row] ) keyword[for] identifier[row] keyword[in] identifier[b] ] identifier[srt_idx] = identifier[sorted] ( identifier[range] ( identifier[len] ( identifier[rows] )), identifier[key] = identifier[rows] . identifier[__getitem__] ) identifier[rows] = identifier[scipy] . identifier[asarray] ( identifier[rows] )[ identifier[srt_idx] ] identifier[row_cmp] =[- literal[int] ] keyword[for] identifier[k] keyword[in] identifier[xrange] ( literal[int] , identifier[len] ( identifier[srt_idx] )): identifier[row_cmp] . identifier[append] ( identifier[rows] [ identifier[k] - literal[int] ]. identifier[__cmp__] ( identifier[rows] [ identifier[k] ])) identifier[row_cmp] = identifier[scipy] . identifier[asarray] ( identifier[row_cmp] ) identifier[transition_idxs] = identifier[scipy] . identifier[where] ( identifier[row_cmp] != literal[int] )[ literal[int] ] identifier[idx] = identifier[scipy] . identifier[asarray] ( identifier[srt_idx] )[ identifier[transition_idxs] ] identifier[out] = identifier[arr] [ identifier[idx] ] keyword[if] identifier[return_index] : identifier[out] =( identifier[out] , identifier[idx] ) keyword[elif] identifier[return_inverse] : identifier[out] =( identifier[out] , identifier[inv] ) keyword[elif] identifier[return_index] keyword[and] identifier[return_inverse] : identifier[out] =( identifier[out] , identifier[idx] , identifier[inv] ) keyword[return] identifier[out]
def unique_rows(arr, return_index=False, return_inverse=False): """Returns a copy of arr with duplicate rows removed. From Stackoverflow "Find unique rows in numpy.array." Parameters ---------- arr : :py:class:`Array`, (`m`, `n`) The array to find the unique rows of. return_index : bool, optional If True, the indices of the unique rows in the array will also be returned. I.e., unique = arr[idx]. Default is False (don't return indices). return_inverse: bool, optional If True, the indices in the unique array to reconstruct the original array will also be returned. I.e., arr = unique[inv]. Default is False (don't return inverse). Returns ------- unique : :py:class:`Array`, (`p`, `n`) where `p` <= `m` The array `arr` with duplicate rows removed. """ b = scipy.ascontiguousarray(arr).view(scipy.dtype((scipy.void, arr.dtype.itemsize * arr.shape[1]))) try: out = scipy.unique(b, return_index=True, return_inverse=return_inverse) dum = out[0] idx = out[1] if return_inverse: inv = out[2] # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except TypeError: if return_inverse: raise RuntimeError('Error in scipy.unique on older versions of numpy prevents return_inverse from working!') # depends on [control=['if'], data=[]] # Handle bug in numpy 1.6.2: rows = [_Row(row) for row in b] srt_idx = sorted(range(len(rows)), key=rows.__getitem__) rows = scipy.asarray(rows)[srt_idx] row_cmp = [-1] for k in xrange(1, len(srt_idx)): row_cmp.append(rows[k - 1].__cmp__(rows[k])) # depends on [control=['for'], data=['k']] row_cmp = scipy.asarray(row_cmp) transition_idxs = scipy.where(row_cmp != 0)[0] idx = scipy.asarray(srt_idx)[transition_idxs] # depends on [control=['except'], data=[]] out = arr[idx] if return_index: out = (out, idx) # depends on [control=['if'], data=[]] elif return_inverse: out = (out, inv) # depends on [control=['if'], data=[]] elif return_index and return_inverse: out = (out, idx, inv) # depends on [control=['if'], data=[]] return out
def _get_national_number_groups_without_pattern(numobj): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.""" # This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of # digits. rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966) # We remove the extension part from the formatted string before splitting # it into different groups. end_index = rfc3966_format.find(U_SEMICOLON) if end_index < 0: end_index = len(rfc3966_format) # The country-code will have a '-' following it. start_index = rfc3966_format.find(U_DASH) + 1 return rfc3966_format[start_index:end_index].split(U_DASH)
def function[_get_national_number_groups_without_pattern, parameter[numobj]]: constant[Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.] variable[rfc3966_format] assign[=] call[name[format_number], parameter[name[numobj], name[PhoneNumberFormat].RFC3966]] variable[end_index] assign[=] call[name[rfc3966_format].find, parameter[name[U_SEMICOLON]]] if compare[name[end_index] less[<] constant[0]] begin[:] variable[end_index] assign[=] call[name[len], parameter[name[rfc3966_format]]] variable[start_index] assign[=] binary_operation[call[name[rfc3966_format].find, parameter[name[U_DASH]]] + constant[1]] return[call[call[name[rfc3966_format]][<ast.Slice object at 0x7da1b188c580>].split, parameter[name[U_DASH]]]]
keyword[def] identifier[_get_national_number_groups_without_pattern] ( identifier[numobj] ): literal[string] identifier[rfc3966_format] = identifier[format_number] ( identifier[numobj] , identifier[PhoneNumberFormat] . identifier[RFC3966] ) identifier[end_index] = identifier[rfc3966_format] . identifier[find] ( identifier[U_SEMICOLON] ) keyword[if] identifier[end_index] < literal[int] : identifier[end_index] = identifier[len] ( identifier[rfc3966_format] ) identifier[start_index] = identifier[rfc3966_format] . identifier[find] ( identifier[U_DASH] )+ literal[int] keyword[return] identifier[rfc3966_format] [ identifier[start_index] : identifier[end_index] ]. identifier[split] ( identifier[U_DASH] )
def _get_national_number_groups_without_pattern(numobj): """Helper method to get the national-number part of a number, formatted without any national prefix, and return it as a set of digit blocks that would be formatted together following standard formatting rules.""" # This will be in the format +CC-DG1-DG2-DGX;ext=EXT where DG1..DGX represents groups of # digits. rfc3966_format = format_number(numobj, PhoneNumberFormat.RFC3966) # We remove the extension part from the formatted string before splitting # it into different groups. end_index = rfc3966_format.find(U_SEMICOLON) if end_index < 0: end_index = len(rfc3966_format) # depends on [control=['if'], data=['end_index']] # The country-code will have a '-' following it. start_index = rfc3966_format.find(U_DASH) + 1 return rfc3966_format[start_index:end_index].split(U_DASH)
def call(self, node, children): 'call = name "(" arguments ")"' name, _, arguments, _ = children return name(*arguments)
def function[call, parameter[self, node, children]]: constant[call = name "(" arguments ")"] <ast.Tuple object at 0x7da18fe90070> assign[=] name[children] return[call[name[name], parameter[<ast.Starred object at 0x7da18fe923e0>]]]
keyword[def] identifier[call] ( identifier[self] , identifier[node] , identifier[children] ): literal[string] identifier[name] , identifier[_] , identifier[arguments] , identifier[_] = identifier[children] keyword[return] identifier[name] (* identifier[arguments] )
def call(self, node, children): '''call = name "(" arguments ")"''' (name, _, arguments, _) = children return name(*arguments)
def get_zones(input_list): """Returns a list of zones based on any wildcard input. This function is intended to provide an easy method for producing a list of desired zones for a pipeline to run in. The Pipelines API default zone list is "any zone". The problem with "any zone" is that it can lead to incurring Cloud Storage egress charges if the GCE zone selected is in a different region than the GCS bucket. See https://cloud.google.com/storage/pricing#network-egress. A user with a multi-region US bucket would want to pipelines to run in a "us-*" zone. A user with a regional bucket in US would want to restrict pipelines to run in a zone in that region. Rarely does the specific zone matter for a pipeline. This function allows for a simple short-hand such as: [ "us-*" ] [ "us-central1-*" ] These examples will expand out to the full list of US and us-central1 zones respectively. Args: input_list: list of zone names/patterns Returns: A list of zones, with any wildcard zone specifications expanded. """ if not input_list: return [] output_list = [] for zone in input_list: if zone.endswith('*'): prefix = zone[:-1] output_list.extend([z for z in _ZONES if z.startswith(prefix)]) else: output_list.append(zone) return output_list
def function[get_zones, parameter[input_list]]: constant[Returns a list of zones based on any wildcard input. This function is intended to provide an easy method for producing a list of desired zones for a pipeline to run in. The Pipelines API default zone list is "any zone". The problem with "any zone" is that it can lead to incurring Cloud Storage egress charges if the GCE zone selected is in a different region than the GCS bucket. See https://cloud.google.com/storage/pricing#network-egress. A user with a multi-region US bucket would want to pipelines to run in a "us-*" zone. A user with a regional bucket in US would want to restrict pipelines to run in a zone in that region. Rarely does the specific zone matter for a pipeline. This function allows for a simple short-hand such as: [ "us-*" ] [ "us-central1-*" ] These examples will expand out to the full list of US and us-central1 zones respectively. Args: input_list: list of zone names/patterns Returns: A list of zones, with any wildcard zone specifications expanded. ] if <ast.UnaryOp object at 0x7da1b016cd30> begin[:] return[list[[]]] variable[output_list] assign[=] list[[]] for taget[name[zone]] in starred[name[input_list]] begin[:] if call[name[zone].endswith, parameter[constant[*]]] begin[:] variable[prefix] assign[=] call[name[zone]][<ast.Slice object at 0x7da1b0055900>] call[name[output_list].extend, parameter[<ast.ListComp object at 0x7da1b0055c90>]] return[name[output_list]]
keyword[def] identifier[get_zones] ( identifier[input_list] ): literal[string] keyword[if] keyword[not] identifier[input_list] : keyword[return] [] identifier[output_list] =[] keyword[for] identifier[zone] keyword[in] identifier[input_list] : keyword[if] identifier[zone] . identifier[endswith] ( literal[string] ): identifier[prefix] = identifier[zone] [:- literal[int] ] identifier[output_list] . identifier[extend] ([ identifier[z] keyword[for] identifier[z] keyword[in] identifier[_ZONES] keyword[if] identifier[z] . identifier[startswith] ( identifier[prefix] )]) keyword[else] : identifier[output_list] . identifier[append] ( identifier[zone] ) keyword[return] identifier[output_list]
def get_zones(input_list): """Returns a list of zones based on any wildcard input. This function is intended to provide an easy method for producing a list of desired zones for a pipeline to run in. The Pipelines API default zone list is "any zone". The problem with "any zone" is that it can lead to incurring Cloud Storage egress charges if the GCE zone selected is in a different region than the GCS bucket. See https://cloud.google.com/storage/pricing#network-egress. A user with a multi-region US bucket would want to pipelines to run in a "us-*" zone. A user with a regional bucket in US would want to restrict pipelines to run in a zone in that region. Rarely does the specific zone matter for a pipeline. This function allows for a simple short-hand such as: [ "us-*" ] [ "us-central1-*" ] These examples will expand out to the full list of US and us-central1 zones respectively. Args: input_list: list of zone names/patterns Returns: A list of zones, with any wildcard zone specifications expanded. """ if not input_list: return [] # depends on [control=['if'], data=[]] output_list = [] for zone in input_list: if zone.endswith('*'): prefix = zone[:-1] output_list.extend([z for z in _ZONES if z.startswith(prefix)]) # depends on [control=['if'], data=[]] else: output_list.append(zone) # depends on [control=['for'], data=['zone']] return output_list
def ckobj(ck, outCell=None): """ Find the set of ID codes of all objects in a specified CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html :param ck: Name of CK file. :type ck: str :param outCell: Optional user provided Spice Int cell. :type outCell: Optional spiceypy.utils.support_types.SpiceCell :return: Set of ID codes of objects in CK file. :rtype: spiceypy.utils.support_types.SpiceCell """ assert isinstance(ck, str) ck = stypes.stringToCharP(ck) if not outCell: outCell = stypes.SPICEINT_CELL(1000) assert isinstance(outCell, stypes.SpiceCell) assert outCell.dtype == 2 libspice.ckobj_c(ck, ctypes.byref(outCell)) return outCell
def function[ckobj, parameter[ck, outCell]]: constant[ Find the set of ID codes of all objects in a specified CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html :param ck: Name of CK file. :type ck: str :param outCell: Optional user provided Spice Int cell. :type outCell: Optional spiceypy.utils.support_types.SpiceCell :return: Set of ID codes of objects in CK file. :rtype: spiceypy.utils.support_types.SpiceCell ] assert[call[name[isinstance], parameter[name[ck], name[str]]]] variable[ck] assign[=] call[name[stypes].stringToCharP, parameter[name[ck]]] if <ast.UnaryOp object at 0x7da18bc724d0> begin[:] variable[outCell] assign[=] call[name[stypes].SPICEINT_CELL, parameter[constant[1000]]] assert[call[name[isinstance], parameter[name[outCell], name[stypes].SpiceCell]]] assert[compare[name[outCell].dtype equal[==] constant[2]]] call[name[libspice].ckobj_c, parameter[name[ck], call[name[ctypes].byref, parameter[name[outCell]]]]] return[name[outCell]]
keyword[def] identifier[ckobj] ( identifier[ck] , identifier[outCell] = keyword[None] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[ck] , identifier[str] ) identifier[ck] = identifier[stypes] . identifier[stringToCharP] ( identifier[ck] ) keyword[if] keyword[not] identifier[outCell] : identifier[outCell] = identifier[stypes] . identifier[SPICEINT_CELL] ( literal[int] ) keyword[assert] identifier[isinstance] ( identifier[outCell] , identifier[stypes] . identifier[SpiceCell] ) keyword[assert] identifier[outCell] . identifier[dtype] == literal[int] identifier[libspice] . identifier[ckobj_c] ( identifier[ck] , identifier[ctypes] . identifier[byref] ( identifier[outCell] )) keyword[return] identifier[outCell]
def ckobj(ck, outCell=None): """ Find the set of ID codes of all objects in a specified CK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ckobj_c.html :param ck: Name of CK file. :type ck: str :param outCell: Optional user provided Spice Int cell. :type outCell: Optional spiceypy.utils.support_types.SpiceCell :return: Set of ID codes of objects in CK file. :rtype: spiceypy.utils.support_types.SpiceCell """ assert isinstance(ck, str) ck = stypes.stringToCharP(ck) if not outCell: outCell = stypes.SPICEINT_CELL(1000) # depends on [control=['if'], data=[]] assert isinstance(outCell, stypes.SpiceCell) assert outCell.dtype == 2 libspice.ckobj_c(ck, ctypes.byref(outCell)) return outCell
def add_view(self, view): """ Add a ViewTrack object to this composite. :param view: A ViewTrack object. """ self.add_child(view) self.views.append(view)
def function[add_view, parameter[self, view]]: constant[ Add a ViewTrack object to this composite. :param view: A ViewTrack object. ] call[name[self].add_child, parameter[name[view]]] call[name[self].views.append, parameter[name[view]]]
keyword[def] identifier[add_view] ( identifier[self] , identifier[view] ): literal[string] identifier[self] . identifier[add_child] ( identifier[view] ) identifier[self] . identifier[views] . identifier[append] ( identifier[view] )
def add_view(self, view): """ Add a ViewTrack object to this composite. :param view: A ViewTrack object. """ self.add_child(view) self.views.append(view)
def tokenize_sent(mtokens, raw='', auto_strip=True): ''' Tokenize a text to multiple sentences ''' sents = [] bucket = [] cfrom = 0 cto = 0 token_cfrom = 0 logger = getLogger() logger.debug("raw text: {}".format(raw)) logger.debug("tokens: {}".format(mtokens)) for t in mtokens: if t.is_eos: continue token_cfrom = raw.find(t.surface, cto) cto = token_cfrom + len(t.surface) # also token_cto logger.debug("processing token {} <{}:{}>".format(t, token_cfrom, cto)) bucket.append(t) # sentence ending if t.pos == '記号' and t.sc1 == '句点': sent_text = raw[cfrom:cto] getLogger().debug("sent_text = {} | <{}:{}>".format(sent_text, cfrom, cto)) if auto_strip: sent_text = sent_text.strip() sents.append(MeCabSent(sent_text, bucket)) logger.debug("Found a sentence: {}".format(sent_text)) cfrom = cto bucket = [] if bucket: logger.debug("Bucket is not empty: {}".format(bucket)) sent_text = raw[cfrom:cto] logger.debug("remaining text: {} [{}:{}]".format(sent_text, cfrom, cto)) if auto_strip: sent_text = sent_text.strip() sents.append(MeCabSent(sent_text, bucket)) return sents
def function[tokenize_sent, parameter[mtokens, raw, auto_strip]]: constant[ Tokenize a text to multiple sentences ] variable[sents] assign[=] list[[]] variable[bucket] assign[=] list[[]] variable[cfrom] assign[=] constant[0] variable[cto] assign[=] constant[0] variable[token_cfrom] assign[=] constant[0] variable[logger] assign[=] call[name[getLogger], parameter[]] call[name[logger].debug, parameter[call[constant[raw text: {}].format, parameter[name[raw]]]]] call[name[logger].debug, parameter[call[constant[tokens: {}].format, parameter[name[mtokens]]]]] for taget[name[t]] in starred[name[mtokens]] begin[:] if name[t].is_eos begin[:] continue variable[token_cfrom] assign[=] call[name[raw].find, parameter[name[t].surface, name[cto]]] variable[cto] assign[=] binary_operation[name[token_cfrom] + call[name[len], parameter[name[t].surface]]] call[name[logger].debug, parameter[call[constant[processing token {} <{}:{}>].format, parameter[name[t], name[token_cfrom], name[cto]]]]] call[name[bucket].append, parameter[name[t]]] if <ast.BoolOp object at 0x7da1b1196860> begin[:] variable[sent_text] assign[=] call[name[raw]][<ast.Slice object at 0x7da1b1197880>] call[call[name[getLogger], parameter[]].debug, parameter[call[constant[sent_text = {} | <{}:{}>].format, parameter[name[sent_text], name[cfrom], name[cto]]]]] if name[auto_strip] begin[:] variable[sent_text] assign[=] call[name[sent_text].strip, parameter[]] call[name[sents].append, parameter[call[name[MeCabSent], parameter[name[sent_text], name[bucket]]]]] call[name[logger].debug, parameter[call[constant[Found a sentence: {}].format, parameter[name[sent_text]]]]] variable[cfrom] assign[=] name[cto] variable[bucket] assign[=] list[[]] if name[bucket] begin[:] call[name[logger].debug, parameter[call[constant[Bucket is not empty: {}].format, parameter[name[bucket]]]]] variable[sent_text] assign[=] call[name[raw]][<ast.Slice object at 0x7da1b1196c50>] call[name[logger].debug, parameter[call[constant[remaining text: {} [{}:{}]].format, parameter[name[sent_text], name[cfrom], name[cto]]]]] if name[auto_strip] begin[:] variable[sent_text] assign[=] call[name[sent_text].strip, parameter[]] call[name[sents].append, parameter[call[name[MeCabSent], parameter[name[sent_text], name[bucket]]]]] return[name[sents]]
keyword[def] identifier[tokenize_sent] ( identifier[mtokens] , identifier[raw] = literal[string] , identifier[auto_strip] = keyword[True] ): literal[string] identifier[sents] =[] identifier[bucket] =[] identifier[cfrom] = literal[int] identifier[cto] = literal[int] identifier[token_cfrom] = literal[int] identifier[logger] = identifier[getLogger] () identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[raw] )) identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[mtokens] )) keyword[for] identifier[t] keyword[in] identifier[mtokens] : keyword[if] identifier[t] . identifier[is_eos] : keyword[continue] identifier[token_cfrom] = identifier[raw] . identifier[find] ( identifier[t] . identifier[surface] , identifier[cto] ) identifier[cto] = identifier[token_cfrom] + identifier[len] ( identifier[t] . identifier[surface] ) identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[t] , identifier[token_cfrom] , identifier[cto] )) identifier[bucket] . identifier[append] ( identifier[t] ) keyword[if] identifier[t] . identifier[pos] == literal[string] keyword[and] identifier[t] . identifier[sc1] == literal[string] : identifier[sent_text] = identifier[raw] [ identifier[cfrom] : identifier[cto] ] identifier[getLogger] (). identifier[debug] ( literal[string] . identifier[format] ( identifier[sent_text] , identifier[cfrom] , identifier[cto] )) keyword[if] identifier[auto_strip] : identifier[sent_text] = identifier[sent_text] . identifier[strip] () identifier[sents] . identifier[append] ( identifier[MeCabSent] ( identifier[sent_text] , identifier[bucket] )) identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[sent_text] )) identifier[cfrom] = identifier[cto] identifier[bucket] =[] keyword[if] identifier[bucket] : identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[bucket] )) identifier[sent_text] = identifier[raw] [ identifier[cfrom] : identifier[cto] ] identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[sent_text] , identifier[cfrom] , identifier[cto] )) keyword[if] identifier[auto_strip] : identifier[sent_text] = identifier[sent_text] . identifier[strip] () identifier[sents] . identifier[append] ( identifier[MeCabSent] ( identifier[sent_text] , identifier[bucket] )) keyword[return] identifier[sents]
def tokenize_sent(mtokens, raw='', auto_strip=True): """ Tokenize a text to multiple sentences """ sents = [] bucket = [] cfrom = 0 cto = 0 token_cfrom = 0 logger = getLogger() logger.debug('raw text: {}'.format(raw)) logger.debug('tokens: {}'.format(mtokens)) for t in mtokens: if t.is_eos: continue # depends on [control=['if'], data=[]] token_cfrom = raw.find(t.surface, cto) cto = token_cfrom + len(t.surface) # also token_cto logger.debug('processing token {} <{}:{}>'.format(t, token_cfrom, cto)) bucket.append(t) # sentence ending if t.pos == '記号' and t.sc1 == '句点': sent_text = raw[cfrom:cto] getLogger().debug('sent_text = {} | <{}:{}>'.format(sent_text, cfrom, cto)) if auto_strip: sent_text = sent_text.strip() # depends on [control=['if'], data=[]] sents.append(MeCabSent(sent_text, bucket)) logger.debug('Found a sentence: {}'.format(sent_text)) cfrom = cto bucket = [] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['t']] if bucket: logger.debug('Bucket is not empty: {}'.format(bucket)) sent_text = raw[cfrom:cto] logger.debug('remaining text: {} [{}:{}]'.format(sent_text, cfrom, cto)) if auto_strip: sent_text = sent_text.strip() # depends on [control=['if'], data=[]] sents.append(MeCabSent(sent_text, bucket)) # depends on [control=['if'], data=[]] return sents
def compute_structure_environments(self, excluded_atoms=None, only_atoms=None, only_cations=True, only_indices=None, maximum_distance_factor=PRESETS['DEFAULT']['maximum_distance_factor'], minimum_angle_factor=PRESETS['DEFAULT']['minimum_angle_factor'], max_cn=None, min_cn=None, only_symbols=None, valences='undefined', additional_conditions=None, info=None, timelimit=None, initial_structure_environments=None, get_from_hints=False, voronoi_normalized_distance_tolerance=PRESETS['DEFAULT'] ['voronoi_normalized_distance_tolerance'], voronoi_normalized_angle_tolerance=PRESETS['DEFAULT'] ['voronoi_normalized_angle_tolerance'], recompute=None, optimization=PRESETS['DEFAULT']['optimization']): """ Computes and returns the StructureEnvironments object containing all the information about the coordination environments in the structure :param excluded_atoms: Atoms for which the coordination geometries does not have to be identified :param only_atoms: If not set to None, atoms for which the coordination geometries have to be identified :param only_cations: If set to True, will only compute environments for cations :param only_indices: If not set to None, will only compute environments the atoms of the given indices :param maximum_distance_factor: If not set to None, neighbors beyond maximum_distance_factor*closest_neighbor_distance are not considered :param minimum_angle_factor: If not set to None, neighbors for which the angle is lower than minimum_angle_factor*largest_angle_neighbor are not considered :param max_cn: maximum coordination number to be considered :param min_cn: minimum coordination number to be considered :param only_symbols: if not set to None, consider only coordination environments with the given symbols :param valences: valences of the atoms :param additional_conditions: additional conditions to be considered in the bonds (example : only bonds between cation and anion :param info: additional info about the calculation :param timelimit: time limit (in secs) after which the calculation of the StructureEnvironments object stops :param initial_structure_environments: initial StructureEnvironments object (most probably incomplete) :param get_from_hints: whether to add neighbors sets from "hints" (e.g. capped environment => test the neighbors without the cap) :param voronoi_normalized_distance_tolerance: tolerance for the normalized distance used to distinguish neighbors sets :param voronoi_normalized_angle_tolerance: tolerance for the normalized angle used to distinguish neighbors sets :param recompute: whether to recompute the sites already computed (when initial_structure_environments is not None) :param optimization: optimization algorithm :return: The StructureEnvironments object containing all the information about the coordination environments in the structure """ time_init = time.clock() if info is None: info = {} info.update({'local_geometry_finder': {'parameters': {'centering_type': self.centering_type, 'include_central_site_in_centroid': self.include_central_site_in_centroid, 'structure_refinement': self.structure_refinement, 'spg_analyzer_options': self.spg_analyzer_options } } }) if only_symbols is not None: self.allcg = AllCoordinationGeometries( permutations_safe_override=self.permutations_safe_override, only_symbols=only_symbols) self.valences = valences # Get a list of indices of unequivalent sites from the initial structure self.equivalent_sites = [[site] for site in self.structure] self.struct_sites_to_irreducible_site_list_map = list( range(len(self.structure))) self.sites_map = list(range(len(self.structure))) indices = list(range(len(self.structure))) # Get list of unequivalent sites with valence >= 0 if only_cations and self.valences != 'undefined': sites_indices = [isite for isite in indices if self.valences[isite] >= 0] else: sites_indices = [isite for isite in indices] # Include atoms that are in the list of "only_atoms" if it is provided if only_atoms is not None: sites_indices = [isite for isite in sites_indices if any([at in [sp.symbol for sp in self.structure[ isite].species] for at in only_atoms])] # Exclude atoms that are in the list of excluded atoms if excluded_atoms: sites_indices = [isite for isite in sites_indices if not any([at in [sp.symbol for sp in self.structure[ isite].species] for at in excluded_atoms])] if only_indices is not None: sites_indices = [isite for isite in indices if isite in only_indices] # Get the VoronoiContainer for the sites defined by their indices (sites_indices) logging.info('Getting DetailedVoronoiContainer') if voronoi_normalized_distance_tolerance is None: normalized_distance_tolerance = DetailedVoronoiContainer.default_normalized_distance_tolerance else: normalized_distance_tolerance = voronoi_normalized_distance_tolerance if voronoi_normalized_angle_tolerance is None: normalized_angle_tolerance = DetailedVoronoiContainer.default_normalized_angle_tolerance else: normalized_angle_tolerance = voronoi_normalized_angle_tolerance self.detailed_voronoi = DetailedVoronoiContainer(self.structure, isites=sites_indices, valences=self.valences, maximum_distance_factor=maximum_distance_factor, minimum_angle_factor=minimum_angle_factor, additional_conditions=additional_conditions, normalized_distance_tolerance=normalized_distance_tolerance, normalized_angle_tolerance=normalized_angle_tolerance) logging.info('DetailedVoronoiContainer has been set up') # Initialize the StructureEnvironments object (either from initial_structure_environments or from scratch) if initial_structure_environments is not None: se = initial_structure_environments if se.structure != self.structure: raise ValueError('Structure is not the same in initial_structure_environments') if se.voronoi != self.detailed_voronoi: if self.detailed_voronoi.is_close_to(se.voronoi): self.detailed_voronoi = se.voronoi else: raise ValueError('Detailed Voronoi is not the same in initial_structure_environments') se.info = info else: se = StructureEnvironments(voronoi=self.detailed_voronoi, valences=self.valences, sites_map=self.sites_map, equivalent_sites=self.equivalent_sites, ce_list=[None]*len(self.structure), structure=self.structure, info=info) # Set up the coordination numbers that have to be computed based on min_cn, max_cn and possibly the settings # for an update (argument "recompute") of an existing StructureEnvironments if min_cn is None: min_cn = 1 if max_cn is None: max_cn = 13 all_cns = range(min_cn, max_cn+1) do_recompute = False if recompute is not None: if 'cns' in recompute: cns_to_recompute = recompute['cns'] all_cns = list(set(all_cns).intersection(cns_to_recompute)) do_recompute = True # Variables used for checking timelimit max_time_one_site = 0.0 breakit = False if optimization > 0: self.detailed_voronoi.local_planes = [None]*len(self.structure) self.detailed_voronoi.separations = [None]*len(self.structure) # Loop on all the sites for isite in range(len(self.structure)): if isite not in sites_indices: logging.info(' ... in site #{:d}/{:d} ({}) : ' 'skipped'.format(isite, len(self.structure), self.structure[isite].species_string)) continue if breakit: logging.info(' ... in site #{:d}/{:d} ({}) : ' 'skipped (timelimit)'.format(isite, len(self.structure), self.structure[isite].species_string)) continue logging.info(' ... in site #{:d}/{:d} ({})'.format(isite, len(self.structure), self.structure[isite].species_string)) t1 = time.clock() if optimization > 0: self.detailed_voronoi.local_planes[isite] = OrderedDict() self.detailed_voronoi.separations[isite] = {} se.init_neighbors_sets(isite=isite, additional_conditions=additional_conditions, valences=valences) to_add_from_hints = [] nb_sets_info = {} for cn, nb_sets in se.neighbors_sets[isite].items(): if cn not in all_cns: continue for inb_set, nb_set in enumerate(nb_sets): logging.debug(' ... getting environments for nb_set ({:d}, {:d})'.format(cn, inb_set)) tnbset1 = time.clock() ce = self.update_nb_set_environments(se=se, isite=isite, cn=cn, inb_set=inb_set, nb_set=nb_set, recompute=do_recompute, optimization=optimization) tnbset2 = time.clock() if cn not in nb_sets_info: nb_sets_info[cn] = {} nb_sets_info[cn][inb_set] = {'time': tnbset2 - tnbset1} if get_from_hints: for cg_symbol, cg_dict in ce: cg = self.allcg[cg_symbol] # Get possibly missing neighbors sets if cg.neighbors_sets_hints is None: continue logging.debug(' ... getting hints from cg with mp_symbol "{}" ...'.format(cg_symbol)) hints_info = {'csm': cg_dict['symmetry_measure'], 'nb_set': nb_set, 'permutation': cg_dict['permutation']} for nb_sets_hints in cg.neighbors_sets_hints: suggested_nb_set_voronoi_indices = nb_sets_hints.hints(hints_info) for inew, new_nb_set_voronoi_indices in enumerate(suggested_nb_set_voronoi_indices): logging.debug(' hint # {:d}'.format(inew)) new_nb_set = se.NeighborsSet(structure=se.structure, isite=isite, detailed_voronoi=se.voronoi, site_voronoi_indices=new_nb_set_voronoi_indices, sources={'origin': 'nb_set_hints', 'hints_type': nb_sets_hints.hints_type, 'suggestion_index': inew, 'cn_map_source': [cn, inb_set], 'cg_source_symbol': cg_symbol}) cn_new_nb_set = len(new_nb_set) if max_cn is not None and cn_new_nb_set > max_cn: continue if min_cn is not None and cn_new_nb_set < min_cn: continue if new_nb_set in [ta['new_nb_set'] for ta in to_add_from_hints]: has_nb_set = True elif not cn_new_nb_set in se.neighbors_sets[isite]: has_nb_set = False else: has_nb_set = new_nb_set in se.neighbors_sets[isite][cn_new_nb_set] if not has_nb_set: to_add_from_hints.append({'isite': isite, 'new_nb_set': new_nb_set, 'cn_new_nb_set': cn_new_nb_set}) logging.debug(' => to be computed'.format(inew)) else: logging.debug(' => already present'.format(inew)) logging.debug(' ... getting environments for nb_sets added from hints') for missing_nb_set_to_add in to_add_from_hints: se.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add['new_nb_set']) for missing_nb_set_to_add in to_add_from_hints: isite_new_nb_set = missing_nb_set_to_add['isite'] cn_new_nb_set = missing_nb_set_to_add['cn_new_nb_set'] new_nb_set = missing_nb_set_to_add['new_nb_set'] inew_nb_set = se.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set) logging.debug(' ... getting environments for nb_set ({:d}, {:d}) - ' 'from hints'.format(cn_new_nb_set, inew_nb_set)) tnbset1 = time.clock() self.update_nb_set_environments(se=se, isite=isite_new_nb_set, cn=cn_new_nb_set, inb_set=inew_nb_set, nb_set=new_nb_set, optimization=optimization) tnbset2 = time.clock() if cn not in nb_sets_info: nb_sets_info[cn] = {} nb_sets_info[cn][inew_nb_set] = {'time': tnbset2 - tnbset1} t2 = time.clock() se.update_site_info(isite=isite, info_dict={'time': t2 - t1, 'nb_sets_info': nb_sets_info}) if timelimit is not None: time_elapsed = t2 - time_init time_left = timelimit - time_elapsed if time_left < 2.0 * max_time_one_site: breakit = True max_time_one_site = max(max_time_one_site, t2 - t1) logging.info(' ... computed in {:.2f} seconds'.format(t2 - t1)) time_end = time.clock() logging.info(' ... compute_structure_environments ended in {:.2f} seconds'.format(time_end-time_init)) return se
def function[compute_structure_environments, parameter[self, excluded_atoms, only_atoms, only_cations, only_indices, maximum_distance_factor, minimum_angle_factor, max_cn, min_cn, only_symbols, valences, additional_conditions, info, timelimit, initial_structure_environments, get_from_hints, voronoi_normalized_distance_tolerance, voronoi_normalized_angle_tolerance, recompute, optimization]]: constant[ Computes and returns the StructureEnvironments object containing all the information about the coordination environments in the structure :param excluded_atoms: Atoms for which the coordination geometries does not have to be identified :param only_atoms: If not set to None, atoms for which the coordination geometries have to be identified :param only_cations: If set to True, will only compute environments for cations :param only_indices: If not set to None, will only compute environments the atoms of the given indices :param maximum_distance_factor: If not set to None, neighbors beyond maximum_distance_factor*closest_neighbor_distance are not considered :param minimum_angle_factor: If not set to None, neighbors for which the angle is lower than minimum_angle_factor*largest_angle_neighbor are not considered :param max_cn: maximum coordination number to be considered :param min_cn: minimum coordination number to be considered :param only_symbols: if not set to None, consider only coordination environments with the given symbols :param valences: valences of the atoms :param additional_conditions: additional conditions to be considered in the bonds (example : only bonds between cation and anion :param info: additional info about the calculation :param timelimit: time limit (in secs) after which the calculation of the StructureEnvironments object stops :param initial_structure_environments: initial StructureEnvironments object (most probably incomplete) :param get_from_hints: whether to add neighbors sets from "hints" (e.g. capped environment => test the neighbors without the cap) :param voronoi_normalized_distance_tolerance: tolerance for the normalized distance used to distinguish neighbors sets :param voronoi_normalized_angle_tolerance: tolerance for the normalized angle used to distinguish neighbors sets :param recompute: whether to recompute the sites already computed (when initial_structure_environments is not None) :param optimization: optimization algorithm :return: The StructureEnvironments object containing all the information about the coordination environments in the structure ] variable[time_init] assign[=] call[name[time].clock, parameter[]] if compare[name[info] is constant[None]] begin[:] variable[info] assign[=] dictionary[[], []] call[name[info].update, parameter[dictionary[[<ast.Constant object at 0x7da20e9b26e0>], [<ast.Dict object at 0x7da20e9b2f80>]]]] if compare[name[only_symbols] is_not constant[None]] begin[:] name[self].allcg assign[=] call[name[AllCoordinationGeometries], parameter[]] name[self].valences assign[=] name[valences] name[self].equivalent_sites assign[=] <ast.ListComp object at 0x7da20e9b1d80> name[self].struct_sites_to_irreducible_site_list_map assign[=] call[name[list], parameter[call[name[range], parameter[call[name[len], parameter[name[self].structure]]]]]] name[self].sites_map assign[=] call[name[list], parameter[call[name[range], parameter[call[name[len], parameter[name[self].structure]]]]]] variable[indices] assign[=] call[name[list], parameter[call[name[range], parameter[call[name[len], parameter[name[self].structure]]]]]] if <ast.BoolOp object at 0x7da18eb57670> begin[:] variable[sites_indices] assign[=] <ast.ListComp object at 0x7da20e9b25c0> if compare[name[only_atoms] is_not constant[None]] begin[:] variable[sites_indices] assign[=] <ast.ListComp object at 0x7da20e9b2a40> if name[excluded_atoms] begin[:] variable[sites_indices] assign[=] <ast.ListComp object at 0x7da20e9b00a0> if compare[name[only_indices] is_not constant[None]] begin[:] variable[sites_indices] assign[=] <ast.ListComp object at 0x7da20e9b1cf0> call[name[logging].info, parameter[constant[Getting DetailedVoronoiContainer]]] if compare[name[voronoi_normalized_distance_tolerance] is constant[None]] begin[:] variable[normalized_distance_tolerance] assign[=] name[DetailedVoronoiContainer].default_normalized_distance_tolerance if compare[name[voronoi_normalized_angle_tolerance] is constant[None]] begin[:] variable[normalized_angle_tolerance] assign[=] name[DetailedVoronoiContainer].default_normalized_angle_tolerance name[self].detailed_voronoi assign[=] call[name[DetailedVoronoiContainer], parameter[name[self].structure]] call[name[logging].info, parameter[constant[DetailedVoronoiContainer has been set up]]] if compare[name[initial_structure_environments] is_not constant[None]] begin[:] variable[se] assign[=] name[initial_structure_environments] if compare[name[se].structure not_equal[!=] name[self].structure] begin[:] <ast.Raise object at 0x7da204621d50> if compare[name[se].voronoi not_equal[!=] name[self].detailed_voronoi] begin[:] if call[name[self].detailed_voronoi.is_close_to, parameter[name[se].voronoi]] begin[:] name[self].detailed_voronoi assign[=] name[se].voronoi name[se].info assign[=] name[info] if compare[name[min_cn] is constant[None]] begin[:] variable[min_cn] assign[=] constant[1] if compare[name[max_cn] is constant[None]] begin[:] variable[max_cn] assign[=] constant[13] variable[all_cns] assign[=] call[name[range], parameter[name[min_cn], binary_operation[name[max_cn] + constant[1]]]] variable[do_recompute] assign[=] constant[False] if compare[name[recompute] is_not constant[None]] begin[:] if compare[constant[cns] in name[recompute]] begin[:] variable[cns_to_recompute] assign[=] call[name[recompute]][constant[cns]] variable[all_cns] assign[=] call[name[list], parameter[call[call[name[set], parameter[name[all_cns]]].intersection, parameter[name[cns_to_recompute]]]]] variable[do_recompute] assign[=] constant[True] variable[max_time_one_site] assign[=] constant[0.0] variable[breakit] assign[=] constant[False] if compare[name[optimization] greater[>] constant[0]] begin[:] name[self].detailed_voronoi.local_planes assign[=] binary_operation[list[[<ast.Constant object at 0x7da204623a00>]] * call[name[len], parameter[name[self].structure]]] name[self].detailed_voronoi.separations assign[=] binary_operation[list[[<ast.Constant object at 0x7da204622500>]] * call[name[len], parameter[name[self].structure]]] for taget[name[isite]] in starred[call[name[range], parameter[call[name[len], parameter[name[self].structure]]]]] begin[:] if compare[name[isite] <ast.NotIn object at 0x7da2590d7190> name[sites_indices]] begin[:] call[name[logging].info, parameter[call[constant[ ... in site #{:d}/{:d} ({}) : skipped].format, parameter[name[isite], call[name[len], parameter[name[self].structure]], call[name[self].structure][name[isite]].species_string]]]] continue if name[breakit] begin[:] call[name[logging].info, parameter[call[constant[ ... in site #{:d}/{:d} ({}) : skipped (timelimit)].format, parameter[name[isite], call[name[len], parameter[name[self].structure]], call[name[self].structure][name[isite]].species_string]]]] continue call[name[logging].info, parameter[call[constant[ ... in site #{:d}/{:d} ({})].format, parameter[name[isite], call[name[len], parameter[name[self].structure]], call[name[self].structure][name[isite]].species_string]]]] variable[t1] assign[=] call[name[time].clock, parameter[]] if compare[name[optimization] greater[>] constant[0]] begin[:] call[name[self].detailed_voronoi.local_planes][name[isite]] assign[=] call[name[OrderedDict], parameter[]] call[name[self].detailed_voronoi.separations][name[isite]] assign[=] dictionary[[], []] call[name[se].init_neighbors_sets, parameter[]] variable[to_add_from_hints] assign[=] list[[]] variable[nb_sets_info] assign[=] dictionary[[], []] for taget[tuple[[<ast.Name object at 0x7da20c6e5810>, <ast.Name object at 0x7da20c6e4460>]]] in starred[call[call[name[se].neighbors_sets][name[isite]].items, parameter[]]] begin[:] if compare[name[cn] <ast.NotIn object at 0x7da2590d7190> name[all_cns]] begin[:] continue for taget[tuple[[<ast.Name object at 0x7da18eb576d0>, <ast.Name object at 0x7da18eb54940>]]] in starred[call[name[enumerate], parameter[name[nb_sets]]]] begin[:] call[name[logging].debug, parameter[call[constant[ ... getting environments for nb_set ({:d}, {:d})].format, parameter[name[cn], name[inb_set]]]]] variable[tnbset1] assign[=] call[name[time].clock, parameter[]] variable[ce] assign[=] call[name[self].update_nb_set_environments, parameter[]] variable[tnbset2] assign[=] call[name[time].clock, parameter[]] if compare[name[cn] <ast.NotIn object at 0x7da2590d7190> name[nb_sets_info]] begin[:] call[name[nb_sets_info]][name[cn]] assign[=] dictionary[[], []] call[call[name[nb_sets_info]][name[cn]]][name[inb_set]] assign[=] dictionary[[<ast.Constant object at 0x7da18eb557b0>], [<ast.BinOp object at 0x7da18eb540a0>]] if name[get_from_hints] begin[:] for taget[tuple[[<ast.Name object at 0x7da18ede7580>, <ast.Name object at 0x7da18ede5e40>]]] in starred[name[ce]] begin[:] variable[cg] assign[=] call[name[self].allcg][name[cg_symbol]] if compare[name[cg].neighbors_sets_hints is constant[None]] begin[:] continue call[name[logging].debug, parameter[call[constant[ ... getting hints from cg with mp_symbol "{}" ...].format, parameter[name[cg_symbol]]]]] variable[hints_info] assign[=] dictionary[[<ast.Constant object at 0x7da18ede56f0>, <ast.Constant object at 0x7da18ede7b80>, <ast.Constant object at 0x7da18ede6260>], [<ast.Subscript object at 0x7da18ede7b20>, <ast.Name object at 0x7da18ede6620>, <ast.Subscript object at 0x7da18ede7bb0>]] for taget[name[nb_sets_hints]] in starred[name[cg].neighbors_sets_hints] begin[:] variable[suggested_nb_set_voronoi_indices] assign[=] call[name[nb_sets_hints].hints, parameter[name[hints_info]]] for taget[tuple[[<ast.Name object at 0x7da18ede5330>, <ast.Name object at 0x7da18ede4730>]]] in starred[call[name[enumerate], parameter[name[suggested_nb_set_voronoi_indices]]]] begin[:] call[name[logging].debug, parameter[call[constant[ hint # {:d}].format, parameter[name[inew]]]]] variable[new_nb_set] assign[=] call[name[se].NeighborsSet, parameter[]] variable[cn_new_nb_set] assign[=] call[name[len], parameter[name[new_nb_set]]] if <ast.BoolOp object at 0x7da18c4cceb0> begin[:] continue if <ast.BoolOp object at 0x7da18c4cec20> begin[:] continue if compare[name[new_nb_set] in <ast.ListComp object at 0x7da18c4cf940>] begin[:] variable[has_nb_set] assign[=] constant[True] if <ast.UnaryOp object at 0x7da18c4cfcd0> begin[:] call[name[to_add_from_hints].append, parameter[dictionary[[<ast.Constant object at 0x7da18c4cde10>, <ast.Constant object at 0x7da18c4cf8b0>, <ast.Constant object at 0x7da18c4cc190>], [<ast.Name object at 0x7da18c4cdc00>, <ast.Name object at 0x7da18c4cc5e0>, <ast.Name object at 0x7da18c4cc070>]]]] call[name[logging].debug, parameter[call[constant[ => to be computed].format, parameter[name[inew]]]]] call[name[logging].debug, parameter[constant[ ... getting environments for nb_sets added from hints]]] for taget[name[missing_nb_set_to_add]] in starred[name[to_add_from_hints]] begin[:] call[name[se].add_neighbors_set, parameter[]] for taget[name[missing_nb_set_to_add]] in starred[name[to_add_from_hints]] begin[:] variable[isite_new_nb_set] assign[=] call[name[missing_nb_set_to_add]][constant[isite]] variable[cn_new_nb_set] assign[=] call[name[missing_nb_set_to_add]][constant[cn_new_nb_set]] variable[new_nb_set] assign[=] call[name[missing_nb_set_to_add]][constant[new_nb_set]] variable[inew_nb_set] assign[=] call[call[call[name[se].neighbors_sets][name[isite_new_nb_set]]][name[cn_new_nb_set]].index, parameter[name[new_nb_set]]] call[name[logging].debug, parameter[call[constant[ ... getting environments for nb_set ({:d}, {:d}) - from hints].format, parameter[name[cn_new_nb_set], name[inew_nb_set]]]]] variable[tnbset1] assign[=] call[name[time].clock, parameter[]] call[name[self].update_nb_set_environments, parameter[]] variable[tnbset2] assign[=] call[name[time].clock, parameter[]] if compare[name[cn] <ast.NotIn object at 0x7da2590d7190> name[nb_sets_info]] begin[:] call[name[nb_sets_info]][name[cn]] assign[=] dictionary[[], []] call[call[name[nb_sets_info]][name[cn]]][name[inew_nb_set]] assign[=] dictionary[[<ast.Constant object at 0x7da18dc9af20>], [<ast.BinOp object at 0x7da18dc9a770>]] variable[t2] assign[=] call[name[time].clock, parameter[]] call[name[se].update_site_info, parameter[]] if compare[name[timelimit] is_not constant[None]] begin[:] variable[time_elapsed] assign[=] binary_operation[name[t2] - name[time_init]] variable[time_left] assign[=] binary_operation[name[timelimit] - name[time_elapsed]] if compare[name[time_left] less[<] binary_operation[constant[2.0] * name[max_time_one_site]]] begin[:] variable[breakit] assign[=] constant[True] variable[max_time_one_site] assign[=] call[name[max], parameter[name[max_time_one_site], binary_operation[name[t2] - name[t1]]]] call[name[logging].info, parameter[call[constant[ ... computed in {:.2f} seconds].format, parameter[binary_operation[name[t2] - name[t1]]]]]] variable[time_end] assign[=] call[name[time].clock, parameter[]] call[name[logging].info, parameter[call[constant[ ... compute_structure_environments ended in {:.2f} seconds].format, parameter[binary_operation[name[time_end] - name[time_init]]]]]] return[name[se]]
keyword[def] identifier[compute_structure_environments] ( identifier[self] , identifier[excluded_atoms] = keyword[None] , identifier[only_atoms] = keyword[None] , identifier[only_cations] = keyword[True] , identifier[only_indices] = keyword[None] , identifier[maximum_distance_factor] = identifier[PRESETS] [ literal[string] ][ literal[string] ], identifier[minimum_angle_factor] = identifier[PRESETS] [ literal[string] ][ literal[string] ], identifier[max_cn] = keyword[None] , identifier[min_cn] = keyword[None] , identifier[only_symbols] = keyword[None] , identifier[valences] = literal[string] , identifier[additional_conditions] = keyword[None] , identifier[info] = keyword[None] , identifier[timelimit] = keyword[None] , identifier[initial_structure_environments] = keyword[None] , identifier[get_from_hints] = keyword[False] , identifier[voronoi_normalized_distance_tolerance] = identifier[PRESETS] [ literal[string] ] [ literal[string] ], identifier[voronoi_normalized_angle_tolerance] = identifier[PRESETS] [ literal[string] ] [ literal[string] ], identifier[recompute] = keyword[None] , identifier[optimization] = identifier[PRESETS] [ literal[string] ][ literal[string] ]): literal[string] identifier[time_init] = identifier[time] . identifier[clock] () keyword[if] identifier[info] keyword[is] keyword[None] : identifier[info] ={} identifier[info] . identifier[update] ({ literal[string] : { literal[string] : { literal[string] : identifier[self] . identifier[centering_type] , literal[string] : identifier[self] . identifier[include_central_site_in_centroid] , literal[string] : identifier[self] . identifier[structure_refinement] , literal[string] : identifier[self] . identifier[spg_analyzer_options] } } }) keyword[if] identifier[only_symbols] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[allcg] = identifier[AllCoordinationGeometries] ( identifier[permutations_safe_override] = identifier[self] . identifier[permutations_safe_override] , identifier[only_symbols] = identifier[only_symbols] ) identifier[self] . identifier[valences] = identifier[valences] identifier[self] . identifier[equivalent_sites] =[[ identifier[site] ] keyword[for] identifier[site] keyword[in] identifier[self] . identifier[structure] ] identifier[self] . identifier[struct_sites_to_irreducible_site_list_map] = identifier[list] ( identifier[range] ( identifier[len] ( identifier[self] . identifier[structure] ))) identifier[self] . identifier[sites_map] = identifier[list] ( identifier[range] ( identifier[len] ( identifier[self] . identifier[structure] ))) identifier[indices] = identifier[list] ( identifier[range] ( identifier[len] ( identifier[self] . identifier[structure] ))) keyword[if] identifier[only_cations] keyword[and] identifier[self] . identifier[valences] != literal[string] : identifier[sites_indices] =[ identifier[isite] keyword[for] identifier[isite] keyword[in] identifier[indices] keyword[if] identifier[self] . identifier[valences] [ identifier[isite] ]>= literal[int] ] keyword[else] : identifier[sites_indices] =[ identifier[isite] keyword[for] identifier[isite] keyword[in] identifier[indices] ] keyword[if] identifier[only_atoms] keyword[is] keyword[not] keyword[None] : identifier[sites_indices] =[ identifier[isite] keyword[for] identifier[isite] keyword[in] identifier[sites_indices] keyword[if] identifier[any] ([ identifier[at] keyword[in] [ identifier[sp] . identifier[symbol] keyword[for] identifier[sp] keyword[in] identifier[self] . identifier[structure] [ identifier[isite] ]. identifier[species] ] keyword[for] identifier[at] keyword[in] identifier[only_atoms] ])] keyword[if] identifier[excluded_atoms] : identifier[sites_indices] =[ identifier[isite] keyword[for] identifier[isite] keyword[in] identifier[sites_indices] keyword[if] keyword[not] identifier[any] ([ identifier[at] keyword[in] [ identifier[sp] . identifier[symbol] keyword[for] identifier[sp] keyword[in] identifier[self] . identifier[structure] [ identifier[isite] ]. identifier[species] ] keyword[for] identifier[at] keyword[in] identifier[excluded_atoms] ])] keyword[if] identifier[only_indices] keyword[is] keyword[not] keyword[None] : identifier[sites_indices] =[ identifier[isite] keyword[for] identifier[isite] keyword[in] identifier[indices] keyword[if] identifier[isite] keyword[in] identifier[only_indices] ] identifier[logging] . identifier[info] ( literal[string] ) keyword[if] identifier[voronoi_normalized_distance_tolerance] keyword[is] keyword[None] : identifier[normalized_distance_tolerance] = identifier[DetailedVoronoiContainer] . identifier[default_normalized_distance_tolerance] keyword[else] : identifier[normalized_distance_tolerance] = identifier[voronoi_normalized_distance_tolerance] keyword[if] identifier[voronoi_normalized_angle_tolerance] keyword[is] keyword[None] : identifier[normalized_angle_tolerance] = identifier[DetailedVoronoiContainer] . identifier[default_normalized_angle_tolerance] keyword[else] : identifier[normalized_angle_tolerance] = identifier[voronoi_normalized_angle_tolerance] identifier[self] . identifier[detailed_voronoi] = identifier[DetailedVoronoiContainer] ( identifier[self] . identifier[structure] , identifier[isites] = identifier[sites_indices] , identifier[valences] = identifier[self] . identifier[valences] , identifier[maximum_distance_factor] = identifier[maximum_distance_factor] , identifier[minimum_angle_factor] = identifier[minimum_angle_factor] , identifier[additional_conditions] = identifier[additional_conditions] , identifier[normalized_distance_tolerance] = identifier[normalized_distance_tolerance] , identifier[normalized_angle_tolerance] = identifier[normalized_angle_tolerance] ) identifier[logging] . identifier[info] ( literal[string] ) keyword[if] identifier[initial_structure_environments] keyword[is] keyword[not] keyword[None] : identifier[se] = identifier[initial_structure_environments] keyword[if] identifier[se] . identifier[structure] != identifier[self] . identifier[structure] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[se] . identifier[voronoi] != identifier[self] . identifier[detailed_voronoi] : keyword[if] identifier[self] . identifier[detailed_voronoi] . identifier[is_close_to] ( identifier[se] . identifier[voronoi] ): identifier[self] . identifier[detailed_voronoi] = identifier[se] . identifier[voronoi] keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[se] . identifier[info] = identifier[info] keyword[else] : identifier[se] = identifier[StructureEnvironments] ( identifier[voronoi] = identifier[self] . identifier[detailed_voronoi] , identifier[valences] = identifier[self] . identifier[valences] , identifier[sites_map] = identifier[self] . identifier[sites_map] , identifier[equivalent_sites] = identifier[self] . identifier[equivalent_sites] , identifier[ce_list] =[ keyword[None] ]* identifier[len] ( identifier[self] . identifier[structure] ), identifier[structure] = identifier[self] . identifier[structure] , identifier[info] = identifier[info] ) keyword[if] identifier[min_cn] keyword[is] keyword[None] : identifier[min_cn] = literal[int] keyword[if] identifier[max_cn] keyword[is] keyword[None] : identifier[max_cn] = literal[int] identifier[all_cns] = identifier[range] ( identifier[min_cn] , identifier[max_cn] + literal[int] ) identifier[do_recompute] = keyword[False] keyword[if] identifier[recompute] keyword[is] keyword[not] keyword[None] : keyword[if] literal[string] keyword[in] identifier[recompute] : identifier[cns_to_recompute] = identifier[recompute] [ literal[string] ] identifier[all_cns] = identifier[list] ( identifier[set] ( identifier[all_cns] ). identifier[intersection] ( identifier[cns_to_recompute] )) identifier[do_recompute] = keyword[True] identifier[max_time_one_site] = literal[int] identifier[breakit] = keyword[False] keyword[if] identifier[optimization] > literal[int] : identifier[self] . identifier[detailed_voronoi] . identifier[local_planes] =[ keyword[None] ]* identifier[len] ( identifier[self] . identifier[structure] ) identifier[self] . identifier[detailed_voronoi] . identifier[separations] =[ keyword[None] ]* identifier[len] ( identifier[self] . identifier[structure] ) keyword[for] identifier[isite] keyword[in] identifier[range] ( identifier[len] ( identifier[self] . identifier[structure] )): keyword[if] identifier[isite] keyword[not] keyword[in] identifier[sites_indices] : identifier[logging] . identifier[info] ( literal[string] literal[string] . identifier[format] ( identifier[isite] , identifier[len] ( identifier[self] . identifier[structure] ), identifier[self] . identifier[structure] [ identifier[isite] ]. identifier[species_string] )) keyword[continue] keyword[if] identifier[breakit] : identifier[logging] . identifier[info] ( literal[string] literal[string] . identifier[format] ( identifier[isite] , identifier[len] ( identifier[self] . identifier[structure] ), identifier[self] . identifier[structure] [ identifier[isite] ]. identifier[species_string] )) keyword[continue] identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[isite] , identifier[len] ( identifier[self] . identifier[structure] ), identifier[self] . identifier[structure] [ identifier[isite] ]. identifier[species_string] )) identifier[t1] = identifier[time] . identifier[clock] () keyword[if] identifier[optimization] > literal[int] : identifier[self] . identifier[detailed_voronoi] . identifier[local_planes] [ identifier[isite] ]= identifier[OrderedDict] () identifier[self] . identifier[detailed_voronoi] . identifier[separations] [ identifier[isite] ]={} identifier[se] . identifier[init_neighbors_sets] ( identifier[isite] = identifier[isite] , identifier[additional_conditions] = identifier[additional_conditions] , identifier[valences] = identifier[valences] ) identifier[to_add_from_hints] =[] identifier[nb_sets_info] ={} keyword[for] identifier[cn] , identifier[nb_sets] keyword[in] identifier[se] . identifier[neighbors_sets] [ identifier[isite] ]. identifier[items] (): keyword[if] identifier[cn] keyword[not] keyword[in] identifier[all_cns] : keyword[continue] keyword[for] identifier[inb_set] , identifier[nb_set] keyword[in] identifier[enumerate] ( identifier[nb_sets] ): identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[cn] , identifier[inb_set] )) identifier[tnbset1] = identifier[time] . identifier[clock] () identifier[ce] = identifier[self] . identifier[update_nb_set_environments] ( identifier[se] = identifier[se] , identifier[isite] = identifier[isite] , identifier[cn] = identifier[cn] , identifier[inb_set] = identifier[inb_set] , identifier[nb_set] = identifier[nb_set] , identifier[recompute] = identifier[do_recompute] , identifier[optimization] = identifier[optimization] ) identifier[tnbset2] = identifier[time] . identifier[clock] () keyword[if] identifier[cn] keyword[not] keyword[in] identifier[nb_sets_info] : identifier[nb_sets_info] [ identifier[cn] ]={} identifier[nb_sets_info] [ identifier[cn] ][ identifier[inb_set] ]={ literal[string] : identifier[tnbset2] - identifier[tnbset1] } keyword[if] identifier[get_from_hints] : keyword[for] identifier[cg_symbol] , identifier[cg_dict] keyword[in] identifier[ce] : identifier[cg] = identifier[self] . identifier[allcg] [ identifier[cg_symbol] ] keyword[if] identifier[cg] . identifier[neighbors_sets_hints] keyword[is] keyword[None] : keyword[continue] identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[cg_symbol] )) identifier[hints_info] ={ literal[string] : identifier[cg_dict] [ literal[string] ], literal[string] : identifier[nb_set] , literal[string] : identifier[cg_dict] [ literal[string] ]} keyword[for] identifier[nb_sets_hints] keyword[in] identifier[cg] . identifier[neighbors_sets_hints] : identifier[suggested_nb_set_voronoi_indices] = identifier[nb_sets_hints] . identifier[hints] ( identifier[hints_info] ) keyword[for] identifier[inew] , identifier[new_nb_set_voronoi_indices] keyword[in] identifier[enumerate] ( identifier[suggested_nb_set_voronoi_indices] ): identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[inew] )) identifier[new_nb_set] = identifier[se] . identifier[NeighborsSet] ( identifier[structure] = identifier[se] . identifier[structure] , identifier[isite] = identifier[isite] , identifier[detailed_voronoi] = identifier[se] . identifier[voronoi] , identifier[site_voronoi_indices] = identifier[new_nb_set_voronoi_indices] , identifier[sources] ={ literal[string] : literal[string] , literal[string] : identifier[nb_sets_hints] . identifier[hints_type] , literal[string] : identifier[inew] , literal[string] :[ identifier[cn] , identifier[inb_set] ], literal[string] : identifier[cg_symbol] }) identifier[cn_new_nb_set] = identifier[len] ( identifier[new_nb_set] ) keyword[if] identifier[max_cn] keyword[is] keyword[not] keyword[None] keyword[and] identifier[cn_new_nb_set] > identifier[max_cn] : keyword[continue] keyword[if] identifier[min_cn] keyword[is] keyword[not] keyword[None] keyword[and] identifier[cn_new_nb_set] < identifier[min_cn] : keyword[continue] keyword[if] identifier[new_nb_set] keyword[in] [ identifier[ta] [ literal[string] ] keyword[for] identifier[ta] keyword[in] identifier[to_add_from_hints] ]: identifier[has_nb_set] = keyword[True] keyword[elif] keyword[not] identifier[cn_new_nb_set] keyword[in] identifier[se] . identifier[neighbors_sets] [ identifier[isite] ]: identifier[has_nb_set] = keyword[False] keyword[else] : identifier[has_nb_set] = identifier[new_nb_set] keyword[in] identifier[se] . identifier[neighbors_sets] [ identifier[isite] ][ identifier[cn_new_nb_set] ] keyword[if] keyword[not] identifier[has_nb_set] : identifier[to_add_from_hints] . identifier[append] ({ literal[string] : identifier[isite] , literal[string] : identifier[new_nb_set] , literal[string] : identifier[cn_new_nb_set] }) identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[inew] )) keyword[else] : identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[inew] )) identifier[logging] . identifier[debug] ( literal[string] ) keyword[for] identifier[missing_nb_set_to_add] keyword[in] identifier[to_add_from_hints] : identifier[se] . identifier[add_neighbors_set] ( identifier[isite] = identifier[isite] , identifier[nb_set] = identifier[missing_nb_set_to_add] [ literal[string] ]) keyword[for] identifier[missing_nb_set_to_add] keyword[in] identifier[to_add_from_hints] : identifier[isite_new_nb_set] = identifier[missing_nb_set_to_add] [ literal[string] ] identifier[cn_new_nb_set] = identifier[missing_nb_set_to_add] [ literal[string] ] identifier[new_nb_set] = identifier[missing_nb_set_to_add] [ literal[string] ] identifier[inew_nb_set] = identifier[se] . identifier[neighbors_sets] [ identifier[isite_new_nb_set] ][ identifier[cn_new_nb_set] ]. identifier[index] ( identifier[new_nb_set] ) identifier[logging] . identifier[debug] ( literal[string] literal[string] . identifier[format] ( identifier[cn_new_nb_set] , identifier[inew_nb_set] )) identifier[tnbset1] = identifier[time] . identifier[clock] () identifier[self] . identifier[update_nb_set_environments] ( identifier[se] = identifier[se] , identifier[isite] = identifier[isite_new_nb_set] , identifier[cn] = identifier[cn_new_nb_set] , identifier[inb_set] = identifier[inew_nb_set] , identifier[nb_set] = identifier[new_nb_set] , identifier[optimization] = identifier[optimization] ) identifier[tnbset2] = identifier[time] . identifier[clock] () keyword[if] identifier[cn] keyword[not] keyword[in] identifier[nb_sets_info] : identifier[nb_sets_info] [ identifier[cn] ]={} identifier[nb_sets_info] [ identifier[cn] ][ identifier[inew_nb_set] ]={ literal[string] : identifier[tnbset2] - identifier[tnbset1] } identifier[t2] = identifier[time] . identifier[clock] () identifier[se] . identifier[update_site_info] ( identifier[isite] = identifier[isite] , identifier[info_dict] ={ literal[string] : identifier[t2] - identifier[t1] , literal[string] : identifier[nb_sets_info] }) keyword[if] identifier[timelimit] keyword[is] keyword[not] keyword[None] : identifier[time_elapsed] = identifier[t2] - identifier[time_init] identifier[time_left] = identifier[timelimit] - identifier[time_elapsed] keyword[if] identifier[time_left] < literal[int] * identifier[max_time_one_site] : identifier[breakit] = keyword[True] identifier[max_time_one_site] = identifier[max] ( identifier[max_time_one_site] , identifier[t2] - identifier[t1] ) identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[t2] - identifier[t1] )) identifier[time_end] = identifier[time] . identifier[clock] () identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[time_end] - identifier[time_init] )) keyword[return] identifier[se]
def compute_structure_environments(self, excluded_atoms=None, only_atoms=None, only_cations=True, only_indices=None, maximum_distance_factor=PRESETS['DEFAULT']['maximum_distance_factor'], minimum_angle_factor=PRESETS['DEFAULT']['minimum_angle_factor'], max_cn=None, min_cn=None, only_symbols=None, valences='undefined', additional_conditions=None, info=None, timelimit=None, initial_structure_environments=None, get_from_hints=False, voronoi_normalized_distance_tolerance=PRESETS['DEFAULT']['voronoi_normalized_distance_tolerance'], voronoi_normalized_angle_tolerance=PRESETS['DEFAULT']['voronoi_normalized_angle_tolerance'], recompute=None, optimization=PRESETS['DEFAULT']['optimization']): """ Computes and returns the StructureEnvironments object containing all the information about the coordination environments in the structure :param excluded_atoms: Atoms for which the coordination geometries does not have to be identified :param only_atoms: If not set to None, atoms for which the coordination geometries have to be identified :param only_cations: If set to True, will only compute environments for cations :param only_indices: If not set to None, will only compute environments the atoms of the given indices :param maximum_distance_factor: If not set to None, neighbors beyond maximum_distance_factor*closest_neighbor_distance are not considered :param minimum_angle_factor: If not set to None, neighbors for which the angle is lower than minimum_angle_factor*largest_angle_neighbor are not considered :param max_cn: maximum coordination number to be considered :param min_cn: minimum coordination number to be considered :param only_symbols: if not set to None, consider only coordination environments with the given symbols :param valences: valences of the atoms :param additional_conditions: additional conditions to be considered in the bonds (example : only bonds between cation and anion :param info: additional info about the calculation :param timelimit: time limit (in secs) after which the calculation of the StructureEnvironments object stops :param initial_structure_environments: initial StructureEnvironments object (most probably incomplete) :param get_from_hints: whether to add neighbors sets from "hints" (e.g. capped environment => test the neighbors without the cap) :param voronoi_normalized_distance_tolerance: tolerance for the normalized distance used to distinguish neighbors sets :param voronoi_normalized_angle_tolerance: tolerance for the normalized angle used to distinguish neighbors sets :param recompute: whether to recompute the sites already computed (when initial_structure_environments is not None) :param optimization: optimization algorithm :return: The StructureEnvironments object containing all the information about the coordination environments in the structure """ time_init = time.clock() if info is None: info = {} # depends on [control=['if'], data=['info']] info.update({'local_geometry_finder': {'parameters': {'centering_type': self.centering_type, 'include_central_site_in_centroid': self.include_central_site_in_centroid, 'structure_refinement': self.structure_refinement, 'spg_analyzer_options': self.spg_analyzer_options}}}) if only_symbols is not None: self.allcg = AllCoordinationGeometries(permutations_safe_override=self.permutations_safe_override, only_symbols=only_symbols) # depends on [control=['if'], data=['only_symbols']] self.valences = valences # Get a list of indices of unequivalent sites from the initial structure self.equivalent_sites = [[site] for site in self.structure] self.struct_sites_to_irreducible_site_list_map = list(range(len(self.structure))) self.sites_map = list(range(len(self.structure))) indices = list(range(len(self.structure))) # Get list of unequivalent sites with valence >= 0 if only_cations and self.valences != 'undefined': sites_indices = [isite for isite in indices if self.valences[isite] >= 0] # depends on [control=['if'], data=[]] else: sites_indices = [isite for isite in indices] # Include atoms that are in the list of "only_atoms" if it is provided if only_atoms is not None: sites_indices = [isite for isite in sites_indices if any([at in [sp.symbol for sp in self.structure[isite].species] for at in only_atoms])] # depends on [control=['if'], data=['only_atoms']] # Exclude atoms that are in the list of excluded atoms if excluded_atoms: sites_indices = [isite for isite in sites_indices if not any([at in [sp.symbol for sp in self.structure[isite].species] for at in excluded_atoms])] # depends on [control=['if'], data=[]] if only_indices is not None: sites_indices = [isite for isite in indices if isite in only_indices] # depends on [control=['if'], data=['only_indices']] # Get the VoronoiContainer for the sites defined by their indices (sites_indices) logging.info('Getting DetailedVoronoiContainer') if voronoi_normalized_distance_tolerance is None: normalized_distance_tolerance = DetailedVoronoiContainer.default_normalized_distance_tolerance # depends on [control=['if'], data=[]] else: normalized_distance_tolerance = voronoi_normalized_distance_tolerance if voronoi_normalized_angle_tolerance is None: normalized_angle_tolerance = DetailedVoronoiContainer.default_normalized_angle_tolerance # depends on [control=['if'], data=[]] else: normalized_angle_tolerance = voronoi_normalized_angle_tolerance self.detailed_voronoi = DetailedVoronoiContainer(self.structure, isites=sites_indices, valences=self.valences, maximum_distance_factor=maximum_distance_factor, minimum_angle_factor=minimum_angle_factor, additional_conditions=additional_conditions, normalized_distance_tolerance=normalized_distance_tolerance, normalized_angle_tolerance=normalized_angle_tolerance) logging.info('DetailedVoronoiContainer has been set up') # Initialize the StructureEnvironments object (either from initial_structure_environments or from scratch) if initial_structure_environments is not None: se = initial_structure_environments if se.structure != self.structure: raise ValueError('Structure is not the same in initial_structure_environments') # depends on [control=['if'], data=[]] if se.voronoi != self.detailed_voronoi: if self.detailed_voronoi.is_close_to(se.voronoi): self.detailed_voronoi = se.voronoi # depends on [control=['if'], data=[]] else: raise ValueError('Detailed Voronoi is not the same in initial_structure_environments') # depends on [control=['if'], data=[]] se.info = info # depends on [control=['if'], data=['initial_structure_environments']] else: se = StructureEnvironments(voronoi=self.detailed_voronoi, valences=self.valences, sites_map=self.sites_map, equivalent_sites=self.equivalent_sites, ce_list=[None] * len(self.structure), structure=self.structure, info=info) # Set up the coordination numbers that have to be computed based on min_cn, max_cn and possibly the settings # for an update (argument "recompute") of an existing StructureEnvironments if min_cn is None: min_cn = 1 # depends on [control=['if'], data=['min_cn']] if max_cn is None: max_cn = 13 # depends on [control=['if'], data=['max_cn']] all_cns = range(min_cn, max_cn + 1) do_recompute = False if recompute is not None: if 'cns' in recompute: cns_to_recompute = recompute['cns'] all_cns = list(set(all_cns).intersection(cns_to_recompute)) # depends on [control=['if'], data=['recompute']] do_recompute = True # depends on [control=['if'], data=['recompute']] # Variables used for checking timelimit max_time_one_site = 0.0 breakit = False if optimization > 0: self.detailed_voronoi.local_planes = [None] * len(self.structure) self.detailed_voronoi.separations = [None] * len(self.structure) # depends on [control=['if'], data=[]] # Loop on all the sites for isite in range(len(self.structure)): if isite not in sites_indices: logging.info(' ... in site #{:d}/{:d} ({}) : skipped'.format(isite, len(self.structure), self.structure[isite].species_string)) continue # depends on [control=['if'], data=['isite']] if breakit: logging.info(' ... in site #{:d}/{:d} ({}) : skipped (timelimit)'.format(isite, len(self.structure), self.structure[isite].species_string)) continue # depends on [control=['if'], data=[]] logging.info(' ... in site #{:d}/{:d} ({})'.format(isite, len(self.structure), self.structure[isite].species_string)) t1 = time.clock() if optimization > 0: self.detailed_voronoi.local_planes[isite] = OrderedDict() self.detailed_voronoi.separations[isite] = {} # depends on [control=['if'], data=[]] se.init_neighbors_sets(isite=isite, additional_conditions=additional_conditions, valences=valences) to_add_from_hints = [] nb_sets_info = {} for (cn, nb_sets) in se.neighbors_sets[isite].items(): if cn not in all_cns: continue # depends on [control=['if'], data=[]] for (inb_set, nb_set) in enumerate(nb_sets): logging.debug(' ... getting environments for nb_set ({:d}, {:d})'.format(cn, inb_set)) tnbset1 = time.clock() ce = self.update_nb_set_environments(se=se, isite=isite, cn=cn, inb_set=inb_set, nb_set=nb_set, recompute=do_recompute, optimization=optimization) tnbset2 = time.clock() if cn not in nb_sets_info: nb_sets_info[cn] = {} # depends on [control=['if'], data=['cn', 'nb_sets_info']] nb_sets_info[cn][inb_set] = {'time': tnbset2 - tnbset1} if get_from_hints: for (cg_symbol, cg_dict) in ce: cg = self.allcg[cg_symbol] # Get possibly missing neighbors sets if cg.neighbors_sets_hints is None: continue # depends on [control=['if'], data=[]] logging.debug(' ... getting hints from cg with mp_symbol "{}" ...'.format(cg_symbol)) hints_info = {'csm': cg_dict['symmetry_measure'], 'nb_set': nb_set, 'permutation': cg_dict['permutation']} for nb_sets_hints in cg.neighbors_sets_hints: suggested_nb_set_voronoi_indices = nb_sets_hints.hints(hints_info) for (inew, new_nb_set_voronoi_indices) in enumerate(suggested_nb_set_voronoi_indices): logging.debug(' hint # {:d}'.format(inew)) new_nb_set = se.NeighborsSet(structure=se.structure, isite=isite, detailed_voronoi=se.voronoi, site_voronoi_indices=new_nb_set_voronoi_indices, sources={'origin': 'nb_set_hints', 'hints_type': nb_sets_hints.hints_type, 'suggestion_index': inew, 'cn_map_source': [cn, inb_set], 'cg_source_symbol': cg_symbol}) cn_new_nb_set = len(new_nb_set) if max_cn is not None and cn_new_nb_set > max_cn: continue # depends on [control=['if'], data=[]] if min_cn is not None and cn_new_nb_set < min_cn: continue # depends on [control=['if'], data=[]] if new_nb_set in [ta['new_nb_set'] for ta in to_add_from_hints]: has_nb_set = True # depends on [control=['if'], data=[]] elif not cn_new_nb_set in se.neighbors_sets[isite]: has_nb_set = False # depends on [control=['if'], data=[]] else: has_nb_set = new_nb_set in se.neighbors_sets[isite][cn_new_nb_set] if not has_nb_set: to_add_from_hints.append({'isite': isite, 'new_nb_set': new_nb_set, 'cn_new_nb_set': cn_new_nb_set}) logging.debug(' => to be computed'.format(inew)) # depends on [control=['if'], data=[]] else: logging.debug(' => already present'.format(inew)) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['nb_sets_hints']] # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['for'], data=[]] logging.debug(' ... getting environments for nb_sets added from hints') for missing_nb_set_to_add in to_add_from_hints: se.add_neighbors_set(isite=isite, nb_set=missing_nb_set_to_add['new_nb_set']) # depends on [control=['for'], data=['missing_nb_set_to_add']] for missing_nb_set_to_add in to_add_from_hints: isite_new_nb_set = missing_nb_set_to_add['isite'] cn_new_nb_set = missing_nb_set_to_add['cn_new_nb_set'] new_nb_set = missing_nb_set_to_add['new_nb_set'] inew_nb_set = se.neighbors_sets[isite_new_nb_set][cn_new_nb_set].index(new_nb_set) logging.debug(' ... getting environments for nb_set ({:d}, {:d}) - from hints'.format(cn_new_nb_set, inew_nb_set)) tnbset1 = time.clock() self.update_nb_set_environments(se=se, isite=isite_new_nb_set, cn=cn_new_nb_set, inb_set=inew_nb_set, nb_set=new_nb_set, optimization=optimization) tnbset2 = time.clock() if cn not in nb_sets_info: nb_sets_info[cn] = {} # depends on [control=['if'], data=['cn', 'nb_sets_info']] nb_sets_info[cn][inew_nb_set] = {'time': tnbset2 - tnbset1} # depends on [control=['for'], data=['missing_nb_set_to_add']] t2 = time.clock() se.update_site_info(isite=isite, info_dict={'time': t2 - t1, 'nb_sets_info': nb_sets_info}) if timelimit is not None: time_elapsed = t2 - time_init time_left = timelimit - time_elapsed if time_left < 2.0 * max_time_one_site: breakit = True # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['timelimit']] max_time_one_site = max(max_time_one_site, t2 - t1) logging.info(' ... computed in {:.2f} seconds'.format(t2 - t1)) # depends on [control=['for'], data=['isite']] time_end = time.clock() logging.info(' ... compute_structure_environments ended in {:.2f} seconds'.format(time_end - time_init)) return se
def construct(generator, subtopic): '''Method constructor of Item-derived classes. Given a subtopic tuple, this method attempts to construct an Item-derived class, currently either ItemText or ItemImage, from the subtopic's type, found in its 4th element. :param generator: Reference to the owning ReportGenerator instance :param subtopic: Tuple containing content_id, meta_url, subtopic_id, type and type-specific data. :returns An instantiated Item-derived class. ''' type = subtopic[3] if type not in Item.constructors: raise LookupError(type) # perhaps customise this exception? return Item.constructors[type](generator, subtopic)
def function[construct, parameter[generator, subtopic]]: constant[Method constructor of Item-derived classes. Given a subtopic tuple, this method attempts to construct an Item-derived class, currently either ItemText or ItemImage, from the subtopic's type, found in its 4th element. :param generator: Reference to the owning ReportGenerator instance :param subtopic: Tuple containing content_id, meta_url, subtopic_id, type and type-specific data. :returns An instantiated Item-derived class. ] variable[type] assign[=] call[name[subtopic]][constant[3]] if compare[name[type] <ast.NotIn object at 0x7da2590d7190> name[Item].constructors] begin[:] <ast.Raise object at 0x7da1b13002b0> return[call[call[name[Item].constructors][name[type]], parameter[name[generator], name[subtopic]]]]
keyword[def] identifier[construct] ( identifier[generator] , identifier[subtopic] ): literal[string] identifier[type] = identifier[subtopic] [ literal[int] ] keyword[if] identifier[type] keyword[not] keyword[in] identifier[Item] . identifier[constructors] : keyword[raise] identifier[LookupError] ( identifier[type] ) keyword[return] identifier[Item] . identifier[constructors] [ identifier[type] ]( identifier[generator] , identifier[subtopic] )
def construct(generator, subtopic): """Method constructor of Item-derived classes. Given a subtopic tuple, this method attempts to construct an Item-derived class, currently either ItemText or ItemImage, from the subtopic's type, found in its 4th element. :param generator: Reference to the owning ReportGenerator instance :param subtopic: Tuple containing content_id, meta_url, subtopic_id, type and type-specific data. :returns An instantiated Item-derived class. """ type = subtopic[3] if type not in Item.constructors: raise LookupError(type) # perhaps customise this exception? # depends on [control=['if'], data=['type']] return Item.constructors[type](generator, subtopic)
def format_event_time(date_time): """ Accepts either an ISO 8601 string, a dict with a time and tzid OR a datetime object. Must be in UTC format: 2016-01-31T12:33:00Z 2016-01-31T12:33:00UTC 2016-01-31T12:33:00+00:00 https://en.wikipedia.org/wiki/ISO_8601 :param datetime.datetime date_time: ``datetime.datetime``, ``dict`` or ``string``. :return: ISO 8601 formatted datetime string. :rtype: ``string`` or ``dict`` """ if not date_time: # Return None if passed None return date_time date_time_type = type(date_time) if date_time_type in (type(''), type(u'')): # If passed a string, return the string. return date_time elif date_time_type == datetime.date: # If passed a date, return an iso8601 formatted date string. return date_time.strftime(ISO_8601_DATE_FORMAT) elif date_time_type is dict: if date_time.get('time'): date_time['time'] = format_event_time(date_time['time']) return date_time elif date_time_type != datetime.datetime: # If passed anything other than a datetime, date, string, dict, or None, raise an Exception. error_message = 'Unsupported type: ``%s``.\nSupported types: ``<datetime.datetime>``, ``<datetime.date>``, ``<dict>``, or ``<str>``.' raise PyCronofyDateTimeError( error_message % (repr(type(date_time))), date_time) if date_time.tzinfo and date_time.tzinfo != pytz.utc: date_time = date_time.astimezone(pytz.utc) return date_time.strftime(ISO_8601_DATETIME_FORMAT)
def function[format_event_time, parameter[date_time]]: constant[ Accepts either an ISO 8601 string, a dict with a time and tzid OR a datetime object. Must be in UTC format: 2016-01-31T12:33:00Z 2016-01-31T12:33:00UTC 2016-01-31T12:33:00+00:00 https://en.wikipedia.org/wiki/ISO_8601 :param datetime.datetime date_time: ``datetime.datetime``, ``dict`` or ``string``. :return: ISO 8601 formatted datetime string. :rtype: ``string`` or ``dict`` ] if <ast.UnaryOp object at 0x7da20c6ab9d0> begin[:] return[name[date_time]] variable[date_time_type] assign[=] call[name[type], parameter[name[date_time]]] if compare[name[date_time_type] in tuple[[<ast.Call object at 0x7da20c6a8eb0>, <ast.Call object at 0x7da20c6a9510>]]] begin[:] return[name[date_time]] if <ast.BoolOp object at 0x7da1b0ebf9d0> begin[:] variable[date_time] assign[=] call[name[date_time].astimezone, parameter[name[pytz].utc]] return[call[name[date_time].strftime, parameter[name[ISO_8601_DATETIME_FORMAT]]]]
keyword[def] identifier[format_event_time] ( identifier[date_time] ): literal[string] keyword[if] keyword[not] identifier[date_time] : keyword[return] identifier[date_time] identifier[date_time_type] = identifier[type] ( identifier[date_time] ) keyword[if] identifier[date_time_type] keyword[in] ( identifier[type] ( literal[string] ), identifier[type] ( literal[string] )): keyword[return] identifier[date_time] keyword[elif] identifier[date_time_type] == identifier[datetime] . identifier[date] : keyword[return] identifier[date_time] . identifier[strftime] ( identifier[ISO_8601_DATE_FORMAT] ) keyword[elif] identifier[date_time_type] keyword[is] identifier[dict] : keyword[if] identifier[date_time] . identifier[get] ( literal[string] ): identifier[date_time] [ literal[string] ]= identifier[format_event_time] ( identifier[date_time] [ literal[string] ]) keyword[return] identifier[date_time] keyword[elif] identifier[date_time_type] != identifier[datetime] . identifier[datetime] : identifier[error_message] = literal[string] keyword[raise] identifier[PyCronofyDateTimeError] ( identifier[error_message] %( identifier[repr] ( identifier[type] ( identifier[date_time] ))), identifier[date_time] ) keyword[if] identifier[date_time] . identifier[tzinfo] keyword[and] identifier[date_time] . identifier[tzinfo] != identifier[pytz] . identifier[utc] : identifier[date_time] = identifier[date_time] . identifier[astimezone] ( identifier[pytz] . identifier[utc] ) keyword[return] identifier[date_time] . identifier[strftime] ( identifier[ISO_8601_DATETIME_FORMAT] )
def format_event_time(date_time): """ Accepts either an ISO 8601 string, a dict with a time and tzid OR a datetime object. Must be in UTC format: 2016-01-31T12:33:00Z 2016-01-31T12:33:00UTC 2016-01-31T12:33:00+00:00 https://en.wikipedia.org/wiki/ISO_8601 :param datetime.datetime date_time: ``datetime.datetime``, ``dict`` or ``string``. :return: ISO 8601 formatted datetime string. :rtype: ``string`` or ``dict`` """ if not date_time: # Return None if passed None return date_time # depends on [control=['if'], data=[]] date_time_type = type(date_time) if date_time_type in (type(''), type(u'')): # If passed a string, return the string. return date_time # depends on [control=['if'], data=[]] elif date_time_type == datetime.date: # If passed a date, return an iso8601 formatted date string. return date_time.strftime(ISO_8601_DATE_FORMAT) # depends on [control=['if'], data=[]] elif date_time_type is dict: if date_time.get('time'): date_time['time'] = format_event_time(date_time['time']) # depends on [control=['if'], data=[]] return date_time # depends on [control=['if'], data=[]] elif date_time_type != datetime.datetime: # If passed anything other than a datetime, date, string, dict, or None, raise an Exception. error_message = 'Unsupported type: ``%s``.\nSupported types: ``<datetime.datetime>``, ``<datetime.date>``, ``<dict>``, or ``<str>``.' raise PyCronofyDateTimeError(error_message % repr(type(date_time)), date_time) # depends on [control=['if'], data=[]] if date_time.tzinfo and date_time.tzinfo != pytz.utc: date_time = date_time.astimezone(pytz.utc) # depends on [control=['if'], data=[]] return date_time.strftime(ISO_8601_DATETIME_FORMAT)
def skip_log_prefix(func): """Skips reporting the prefix of a given function or name by ABSLLogger. This is a convenience wrapper function / decorator for `ABSLLogger.register_frame_to_skip`. If a callable function is provided, only that function will be skipped. If a function name is provided, all functions with the same name in the file that this is called in will be skipped. This can be used as a decorator of the intended function to be skipped. Args: func: Callable function or its name as a string. Returns: func (the input, unchanged). Raises: ValueError: The input is callable but does not have a function code object. TypeError: The input is neither callable nor a string. """ if callable(func): func_code = getattr(func, '__code__', None) if func_code is None: raise ValueError('Input callable does not have a function code object.') file_name = func_code.co_filename func_name = func_code.co_name func_lineno = func_code.co_firstlineno elif isinstance(func, six.string_types): file_name = get_absl_logger().findCaller()[0] func_name = func func_lineno = None else: raise TypeError('Input is neither callable nor a string.') ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno) return func
def function[skip_log_prefix, parameter[func]]: constant[Skips reporting the prefix of a given function or name by ABSLLogger. This is a convenience wrapper function / decorator for `ABSLLogger.register_frame_to_skip`. If a callable function is provided, only that function will be skipped. If a function name is provided, all functions with the same name in the file that this is called in will be skipped. This can be used as a decorator of the intended function to be skipped. Args: func: Callable function or its name as a string. Returns: func (the input, unchanged). Raises: ValueError: The input is callable but does not have a function code object. TypeError: The input is neither callable nor a string. ] if call[name[callable], parameter[name[func]]] begin[:] variable[func_code] assign[=] call[name[getattr], parameter[name[func], constant[__code__], constant[None]]] if compare[name[func_code] is constant[None]] begin[:] <ast.Raise object at 0x7da1b18bd630> variable[file_name] assign[=] name[func_code].co_filename variable[func_name] assign[=] name[func_code].co_name variable[func_lineno] assign[=] name[func_code].co_firstlineno call[name[ABSLLogger].register_frame_to_skip, parameter[name[file_name], name[func_name], name[func_lineno]]] return[name[func]]
keyword[def] identifier[skip_log_prefix] ( identifier[func] ): literal[string] keyword[if] identifier[callable] ( identifier[func] ): identifier[func_code] = identifier[getattr] ( identifier[func] , literal[string] , keyword[None] ) keyword[if] identifier[func_code] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[file_name] = identifier[func_code] . identifier[co_filename] identifier[func_name] = identifier[func_code] . identifier[co_name] identifier[func_lineno] = identifier[func_code] . identifier[co_firstlineno] keyword[elif] identifier[isinstance] ( identifier[func] , identifier[six] . identifier[string_types] ): identifier[file_name] = identifier[get_absl_logger] (). identifier[findCaller] ()[ literal[int] ] identifier[func_name] = identifier[func] identifier[func_lineno] = keyword[None] keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] ) identifier[ABSLLogger] . identifier[register_frame_to_skip] ( identifier[file_name] , identifier[func_name] , identifier[func_lineno] ) keyword[return] identifier[func]
def skip_log_prefix(func): """Skips reporting the prefix of a given function or name by ABSLLogger. This is a convenience wrapper function / decorator for `ABSLLogger.register_frame_to_skip`. If a callable function is provided, only that function will be skipped. If a function name is provided, all functions with the same name in the file that this is called in will be skipped. This can be used as a decorator of the intended function to be skipped. Args: func: Callable function or its name as a string. Returns: func (the input, unchanged). Raises: ValueError: The input is callable but does not have a function code object. TypeError: The input is neither callable nor a string. """ if callable(func): func_code = getattr(func, '__code__', None) if func_code is None: raise ValueError('Input callable does not have a function code object.') # depends on [control=['if'], data=[]] file_name = func_code.co_filename func_name = func_code.co_name func_lineno = func_code.co_firstlineno # depends on [control=['if'], data=[]] elif isinstance(func, six.string_types): file_name = get_absl_logger().findCaller()[0] func_name = func func_lineno = None # depends on [control=['if'], data=[]] else: raise TypeError('Input is neither callable nor a string.') ABSLLogger.register_frame_to_skip(file_name, func_name, func_lineno) return func
def _clear_inspect(self): """Clears inspect attributes when re-executing a pipeline""" self.trace_info = defaultdict(list) self.process_tags = {} self.process_stats = {} self.samples = [] self.stored_ids = [] self.stored_log_ids = [] self.time_start = None self.time_stop = None self.execution_command = None self.nextflow_version = None self.abort_cause = None self._c = 0 # Clean up of tag running status for p in self.processes.values(): p["barrier"] = "W" for i in ["submitted", "finished", "failed", "retry"]: p[i] = set()
def function[_clear_inspect, parameter[self]]: constant[Clears inspect attributes when re-executing a pipeline] name[self].trace_info assign[=] call[name[defaultdict], parameter[name[list]]] name[self].process_tags assign[=] dictionary[[], []] name[self].process_stats assign[=] dictionary[[], []] name[self].samples assign[=] list[[]] name[self].stored_ids assign[=] list[[]] name[self].stored_log_ids assign[=] list[[]] name[self].time_start assign[=] constant[None] name[self].time_stop assign[=] constant[None] name[self].execution_command assign[=] constant[None] name[self].nextflow_version assign[=] constant[None] name[self].abort_cause assign[=] constant[None] name[self]._c assign[=] constant[0] for taget[name[p]] in starred[call[name[self].processes.values, parameter[]]] begin[:] call[name[p]][constant[barrier]] assign[=] constant[W] for taget[name[i]] in starred[list[[<ast.Constant object at 0x7da1b02db130>, <ast.Constant object at 0x7da1b02dbac0>, <ast.Constant object at 0x7da1b02d9750>, <ast.Constant object at 0x7da1b02d8340>]]] begin[:] call[name[p]][name[i]] assign[=] call[name[set], parameter[]]
keyword[def] identifier[_clear_inspect] ( identifier[self] ): literal[string] identifier[self] . identifier[trace_info] = identifier[defaultdict] ( identifier[list] ) identifier[self] . identifier[process_tags] ={} identifier[self] . identifier[process_stats] ={} identifier[self] . identifier[samples] =[] identifier[self] . identifier[stored_ids] =[] identifier[self] . identifier[stored_log_ids] =[] identifier[self] . identifier[time_start] = keyword[None] identifier[self] . identifier[time_stop] = keyword[None] identifier[self] . identifier[execution_command] = keyword[None] identifier[self] . identifier[nextflow_version] = keyword[None] identifier[self] . identifier[abort_cause] = keyword[None] identifier[self] . identifier[_c] = literal[int] keyword[for] identifier[p] keyword[in] identifier[self] . identifier[processes] . identifier[values] (): identifier[p] [ literal[string] ]= literal[string] keyword[for] identifier[i] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] ]: identifier[p] [ identifier[i] ]= identifier[set] ()
def _clear_inspect(self): """Clears inspect attributes when re-executing a pipeline""" self.trace_info = defaultdict(list) self.process_tags = {} self.process_stats = {} self.samples = [] self.stored_ids = [] self.stored_log_ids = [] self.time_start = None self.time_stop = None self.execution_command = None self.nextflow_version = None self.abort_cause = None self._c = 0 # Clean up of tag running status for p in self.processes.values(): p['barrier'] = 'W' for i in ['submitted', 'finished', 'failed', 'retry']: p[i] = set() # depends on [control=['for'], data=['i']] # depends on [control=['for'], data=['p']]
def _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles lists of dicts. """ if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) fields = get_field_list(fields, schema) gen = source[first_row:first_row + count] if count >= 0 else source rows = [{'c': [{'v': row[c]} if c in row else {} for c in fields]} for row in gen] return {'cols': _get_cols(fields, schema), 'rows': rows}, len(source)
def function[_get_data_from_list_of_dicts, parameter[source, fields, first_row, count, schema]]: constant[ Helper function for _get_data that handles lists of dicts. ] if compare[name[schema] is constant[None]] begin[:] variable[schema] assign[=] call[name[google].datalab.bigquery.Schema.from_data, parameter[name[source]]] variable[fields] assign[=] call[name[get_field_list], parameter[name[fields], name[schema]]] variable[gen] assign[=] <ast.IfExp object at 0x7da20e956e60> variable[rows] assign[=] <ast.ListComp object at 0x7da20e9563e0> return[tuple[[<ast.Dict object at 0x7da20e9572e0>, <ast.Call object at 0x7da20e954b50>]]]
keyword[def] identifier[_get_data_from_list_of_dicts] ( identifier[source] , identifier[fields] = literal[string] , identifier[first_row] = literal[int] , identifier[count] =- literal[int] , identifier[schema] = keyword[None] ): literal[string] keyword[if] identifier[schema] keyword[is] keyword[None] : identifier[schema] = identifier[google] . identifier[datalab] . identifier[bigquery] . identifier[Schema] . identifier[from_data] ( identifier[source] ) identifier[fields] = identifier[get_field_list] ( identifier[fields] , identifier[schema] ) identifier[gen] = identifier[source] [ identifier[first_row] : identifier[first_row] + identifier[count] ] keyword[if] identifier[count] >= literal[int] keyword[else] identifier[source] identifier[rows] =[{ literal[string] :[{ literal[string] : identifier[row] [ identifier[c] ]} keyword[if] identifier[c] keyword[in] identifier[row] keyword[else] {} keyword[for] identifier[c] keyword[in] identifier[fields] ]} keyword[for] identifier[row] keyword[in] identifier[gen] ] keyword[return] { literal[string] : identifier[_get_cols] ( identifier[fields] , identifier[schema] ), literal[string] : identifier[rows] }, identifier[len] ( identifier[source] )
def _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles lists of dicts. """ if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) # depends on [control=['if'], data=['schema']] fields = get_field_list(fields, schema) gen = source[first_row:first_row + count] if count >= 0 else source rows = [{'c': [{'v': row[c]} if c in row else {} for c in fields]} for row in gen] return ({'cols': _get_cols(fields, schema), 'rows': rows}, len(source))
def removeforkrelation(self, project_id): """ Remove an existing fork relation. this DO NOT remove the fork,only the relation between them :param project_id: project id :return: true if success """ request = requests.delete( '{0}/{1}/fork'.format(self.projects_url, project_id), headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 200: return True else: return False
def function[removeforkrelation, parameter[self, project_id]]: constant[ Remove an existing fork relation. this DO NOT remove the fork,only the relation between them :param project_id: project id :return: true if success ] variable[request] assign[=] call[name[requests].delete, parameter[call[constant[{0}/{1}/fork].format, parameter[name[self].projects_url, name[project_id]]]]] if compare[name[request].status_code equal[==] constant[200]] begin[:] return[constant[True]]
keyword[def] identifier[removeforkrelation] ( identifier[self] , identifier[project_id] ): literal[string] identifier[request] = identifier[requests] . identifier[delete] ( literal[string] . identifier[format] ( identifier[self] . identifier[projects_url] , identifier[project_id] ), identifier[headers] = identifier[self] . identifier[headers] , identifier[verify] = identifier[self] . identifier[verify_ssl] , identifier[auth] = identifier[self] . identifier[auth] , identifier[timeout] = identifier[self] . identifier[timeout] ) keyword[if] identifier[request] . identifier[status_code] == literal[int] : keyword[return] keyword[True] keyword[else] : keyword[return] keyword[False]
def removeforkrelation(self, project_id): """ Remove an existing fork relation. this DO NOT remove the fork,only the relation between them :param project_id: project id :return: true if success """ request = requests.delete('{0}/{1}/fork'.format(self.projects_url, project_id), headers=self.headers, verify=self.verify_ssl, auth=self.auth, timeout=self.timeout) if request.status_code == 200: return True # depends on [control=['if'], data=[]] else: return False
def main(args=None): """ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. """ _parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx')) if srp is not None: srv = srp.parsed_version location = srp.location spkg = 'package' else: srv = streamsx._streams._version.__version__ location = os.path.dirname(streamsx._streams._version.__file__) location = os.path.dirname(location) location = os.path.dirname(location) tk_path = (os.path.join('com.ibm.streamsx.topology', 'opt', 'python', 'packages')) spkg = 'toolkit' if location.endswith(tk_path) else 'unknown' print('streamsx==' + str(srv) + ' (' + spkg + ')') print(' location: ' + str(location)) print('Python version:' + str(sys.version)) print('PYTHONHOME=' + str(os.environ.get('PYTHONHOME', 'unset'))) print('PYTHONPATH=' + str(os.environ.get('PYTHONPATH', 'unset'))) print('PYTHONWARNINGS=' + str(os.environ.get('PYTHONWARNINGS', 'unset'))) print('STREAMS_INSTALL=' + str(os.environ.get('STREAMS_INSTALL', 'unset'))) print('JAVA_HOME=' + str(os.environ.get('JAVA_HOME', 'unset'))) return 0
def function[main, parameter[args]]: constant[ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. ] call[name[_parse_args], parameter[name[args]]] call[name[streamsx]._streams._version._mismatch_check, parameter[constant[streamsx.topology.context]]] variable[srp] assign[=] call[name[pkg_resources].working_set.find, parameter[call[name[pkg_resources].Requirement.parse, parameter[constant[streamsx]]]]] if compare[name[srp] is_not constant[None]] begin[:] variable[srv] assign[=] name[srp].parsed_version variable[location] assign[=] name[srp].location variable[spkg] assign[=] constant[package] call[name[print], parameter[binary_operation[binary_operation[binary_operation[binary_operation[constant[streamsx==] + call[name[str], parameter[name[srv]]]] + constant[ (]] + name[spkg]] + constant[)]]]] call[name[print], parameter[binary_operation[constant[ location: ] + call[name[str], parameter[name[location]]]]]] call[name[print], parameter[binary_operation[constant[Python version:] + call[name[str], parameter[name[sys].version]]]]] call[name[print], parameter[binary_operation[constant[PYTHONHOME=] + call[name[str], parameter[call[name[os].environ.get, parameter[constant[PYTHONHOME], constant[unset]]]]]]]] call[name[print], parameter[binary_operation[constant[PYTHONPATH=] + call[name[str], parameter[call[name[os].environ.get, parameter[constant[PYTHONPATH], constant[unset]]]]]]]] call[name[print], parameter[binary_operation[constant[PYTHONWARNINGS=] + call[name[str], parameter[call[name[os].environ.get, parameter[constant[PYTHONWARNINGS], constant[unset]]]]]]]] call[name[print], parameter[binary_operation[constant[STREAMS_INSTALL=] + call[name[str], parameter[call[name[os].environ.get, parameter[constant[STREAMS_INSTALL], constant[unset]]]]]]]] call[name[print], parameter[binary_operation[constant[JAVA_HOME=] + call[name[str], parameter[call[name[os].environ.get, parameter[constant[JAVA_HOME], constant[unset]]]]]]]] return[constant[0]]
keyword[def] identifier[main] ( identifier[args] = keyword[None] ): literal[string] identifier[_parse_args] ( identifier[args] ) identifier[streamsx] . identifier[_streams] . identifier[_version] . identifier[_mismatch_check] ( literal[string] ) identifier[srp] = identifier[pkg_resources] . identifier[working_set] . identifier[find] ( identifier[pkg_resources] . identifier[Requirement] . identifier[parse] ( literal[string] )) keyword[if] identifier[srp] keyword[is] keyword[not] keyword[None] : identifier[srv] = identifier[srp] . identifier[parsed_version] identifier[location] = identifier[srp] . identifier[location] identifier[spkg] = literal[string] keyword[else] : identifier[srv] = identifier[streamsx] . identifier[_streams] . identifier[_version] . identifier[__version__] identifier[location] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[streamsx] . identifier[_streams] . identifier[_version] . identifier[__file__] ) identifier[location] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[location] ) identifier[location] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[location] ) identifier[tk_path] =( identifier[os] . identifier[path] . identifier[join] ( literal[string] , literal[string] , literal[string] , literal[string] )) identifier[spkg] = literal[string] keyword[if] identifier[location] . identifier[endswith] ( identifier[tk_path] ) keyword[else] literal[string] identifier[print] ( literal[string] + identifier[str] ( identifier[srv] )+ literal[string] + identifier[spkg] + literal[string] ) identifier[print] ( literal[string] + identifier[str] ( identifier[location] )) identifier[print] ( literal[string] + identifier[str] ( identifier[sys] . identifier[version] )) identifier[print] ( literal[string] + identifier[str] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ))) identifier[print] ( literal[string] + identifier[str] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ))) identifier[print] ( literal[string] + identifier[str] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ))) identifier[print] ( literal[string] + identifier[str] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ))) identifier[print] ( literal[string] + identifier[str] ( identifier[os] . identifier[environ] . identifier[get] ( literal[string] , literal[string] ))) keyword[return] literal[int]
def main(args=None): """ Output information about `streamsx` and the environment. Useful for support to get key information for use of `streamsx` and Python in IBM Streams. """ _parse_args(args) streamsx._streams._version._mismatch_check('streamsx.topology.context') srp = pkg_resources.working_set.find(pkg_resources.Requirement.parse('streamsx')) if srp is not None: srv = srp.parsed_version location = srp.location spkg = 'package' # depends on [control=['if'], data=['srp']] else: srv = streamsx._streams._version.__version__ location = os.path.dirname(streamsx._streams._version.__file__) location = os.path.dirname(location) location = os.path.dirname(location) tk_path = os.path.join('com.ibm.streamsx.topology', 'opt', 'python', 'packages') spkg = 'toolkit' if location.endswith(tk_path) else 'unknown' print('streamsx==' + str(srv) + ' (' + spkg + ')') print(' location: ' + str(location)) print('Python version:' + str(sys.version)) print('PYTHONHOME=' + str(os.environ.get('PYTHONHOME', 'unset'))) print('PYTHONPATH=' + str(os.environ.get('PYTHONPATH', 'unset'))) print('PYTHONWARNINGS=' + str(os.environ.get('PYTHONWARNINGS', 'unset'))) print('STREAMS_INSTALL=' + str(os.environ.get('STREAMS_INSTALL', 'unset'))) print('JAVA_HOME=' + str(os.environ.get('JAVA_HOME', 'unset'))) return 0
def install_user_command_legacy(command, **substitutions): '''Install command executable file into users bin dir. If a custom executable exists it would be installed instead of the "normal" one. The executable also could exist as a <command>.template file. ''' path = flo('~/bin/{command}') install_file_legacy(path, **substitutions) run(flo('chmod 755 {path}'))
def function[install_user_command_legacy, parameter[command]]: constant[Install command executable file into users bin dir. If a custom executable exists it would be installed instead of the "normal" one. The executable also could exist as a <command>.template file. ] variable[path] assign[=] call[name[flo], parameter[constant[~/bin/{command}]]] call[name[install_file_legacy], parameter[name[path]]] call[name[run], parameter[call[name[flo], parameter[constant[chmod 755 {path}]]]]]
keyword[def] identifier[install_user_command_legacy] ( identifier[command] ,** identifier[substitutions] ): literal[string] identifier[path] = identifier[flo] ( literal[string] ) identifier[install_file_legacy] ( identifier[path] ,** identifier[substitutions] ) identifier[run] ( identifier[flo] ( literal[string] ))
def install_user_command_legacy(command, **substitutions): """Install command executable file into users bin dir. If a custom executable exists it would be installed instead of the "normal" one. The executable also could exist as a <command>.template file. """ path = flo('~/bin/{command}') install_file_legacy(path, **substitutions) run(flo('chmod 755 {path}'))
def quants_(self, inf, sup, chart_type="point", color="green"): """ Draw a chart to visualize quantiles """ try: return self._bokeh_quants(inf, sup, chart_type, color) except Exception as e: self.err(e, self.quants_, "Can not draw quantile chart")
def function[quants_, parameter[self, inf, sup, chart_type, color]]: constant[ Draw a chart to visualize quantiles ] <ast.Try object at 0x7da204620f10>
keyword[def] identifier[quants_] ( identifier[self] , identifier[inf] , identifier[sup] , identifier[chart_type] = literal[string] , identifier[color] = literal[string] ): literal[string] keyword[try] : keyword[return] identifier[self] . identifier[_bokeh_quants] ( identifier[inf] , identifier[sup] , identifier[chart_type] , identifier[color] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[self] . identifier[err] ( identifier[e] , identifier[self] . identifier[quants_] , literal[string] )
def quants_(self, inf, sup, chart_type='point', color='green'): """ Draw a chart to visualize quantiles """ try: return self._bokeh_quants(inf, sup, chart_type, color) # depends on [control=['try'], data=[]] except Exception as e: self.err(e, self.quants_, 'Can not draw quantile chart') # depends on [control=['except'], data=['e']]
def load_from_file(swag_path, swag_type='yml', root_path=None): """ Load specs from YAML file """ if swag_type not in ('yaml', 'yml'): raise AttributeError("Currently only yaml or yml supported") # TODO: support JSON try: enc = detect_by_bom(swag_path) with codecs.open(swag_path, encoding=enc) as yaml_file: return yaml_file.read() except IOError: # not in the same dir, add dirname swag_path = os.path.join( root_path or os.path.dirname(__file__), swag_path ) try: enc = detect_by_bom(swag_path) with codecs.open(swag_path, encoding=enc) as yaml_file: return yaml_file.read() except IOError: # pragma: no cover # if package dir # see https://github.com/rochacbruno/flasgger/pull/104 # Still not able to reproduce this case # test are in examples/package_example # need more detail on how to reproduce IOError here swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep) path = swag_path.replace( (root_path or os.path.dirname(__file__)), '' ).split(os.sep)[1:] site_package = imp.find_module(path[0])[1] swag_path = os.path.join(site_package, os.sep.join(path[1:])) with open(swag_path) as yaml_file: return yaml_file.read()
def function[load_from_file, parameter[swag_path, swag_type, root_path]]: constant[ Load specs from YAML file ] if compare[name[swag_type] <ast.NotIn object at 0x7da2590d7190> tuple[[<ast.Constant object at 0x7da1b1bc8b20>, <ast.Constant object at 0x7da1b1bc9780>]]] begin[:] <ast.Raise object at 0x7da1b1bc8430> <ast.Try object at 0x7da1b1bc84c0>
keyword[def] identifier[load_from_file] ( identifier[swag_path] , identifier[swag_type] = literal[string] , identifier[root_path] = keyword[None] ): literal[string] keyword[if] identifier[swag_type] keyword[not] keyword[in] ( literal[string] , literal[string] ): keyword[raise] identifier[AttributeError] ( literal[string] ) keyword[try] : identifier[enc] = identifier[detect_by_bom] ( identifier[swag_path] ) keyword[with] identifier[codecs] . identifier[open] ( identifier[swag_path] , identifier[encoding] = identifier[enc] ) keyword[as] identifier[yaml_file] : keyword[return] identifier[yaml_file] . identifier[read] () keyword[except] identifier[IOError] : identifier[swag_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[root_path] keyword[or] identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), identifier[swag_path] ) keyword[try] : identifier[enc] = identifier[detect_by_bom] ( identifier[swag_path] ) keyword[with] identifier[codecs] . identifier[open] ( identifier[swag_path] , identifier[encoding] = identifier[enc] ) keyword[as] identifier[yaml_file] : keyword[return] identifier[yaml_file] . identifier[read] () keyword[except] identifier[IOError] : identifier[swag_path] = identifier[swag_path] . identifier[replace] ( literal[string] , identifier[os] . identifier[sep] ). identifier[replace] ( literal[string] , identifier[os] . identifier[sep] ) identifier[path] = identifier[swag_path] . identifier[replace] ( ( identifier[root_path] keyword[or] identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] )), literal[string] ). identifier[split] ( identifier[os] . identifier[sep] )[ literal[int] :] identifier[site_package] = identifier[imp] . identifier[find_module] ( identifier[path] [ literal[int] ])[ literal[int] ] identifier[swag_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[site_package] , identifier[os] . identifier[sep] . identifier[join] ( identifier[path] [ literal[int] :])) keyword[with] identifier[open] ( identifier[swag_path] ) keyword[as] identifier[yaml_file] : keyword[return] identifier[yaml_file] . identifier[read] ()
def load_from_file(swag_path, swag_type='yml', root_path=None): """ Load specs from YAML file """ if swag_type not in ('yaml', 'yml'): raise AttributeError('Currently only yaml or yml supported') # depends on [control=['if'], data=[]] # TODO: support JSON try: enc = detect_by_bom(swag_path) with codecs.open(swag_path, encoding=enc) as yaml_file: return yaml_file.read() # depends on [control=['with'], data=['yaml_file']] # depends on [control=['try'], data=[]] except IOError: # not in the same dir, add dirname swag_path = os.path.join(root_path or os.path.dirname(__file__), swag_path) try: enc = detect_by_bom(swag_path) with codecs.open(swag_path, encoding=enc) as yaml_file: return yaml_file.read() # depends on [control=['with'], data=['yaml_file']] # depends on [control=['try'], data=[]] except IOError: # pragma: no cover # if package dir # see https://github.com/rochacbruno/flasgger/pull/104 # Still not able to reproduce this case # test are in examples/package_example # need more detail on how to reproduce IOError here swag_path = swag_path.replace('/', os.sep).replace('\\', os.sep) path = swag_path.replace(root_path or os.path.dirname(__file__), '').split(os.sep)[1:] site_package = imp.find_module(path[0])[1] swag_path = os.path.join(site_package, os.sep.join(path[1:])) with open(swag_path) as yaml_file: return yaml_file.read() # depends on [control=['with'], data=['yaml_file']] # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]]
def relaxNGNewDocParserCtxt(self): """Create an XML RelaxNGs parser context for that document. Note: since the process of compiling a RelaxNG schemas modifies the document, the @doc parameter is duplicated internally. """ ret = libxml2mod.xmlRelaxNGNewDocParserCtxt(self._o) if ret is None:raise parserError('xmlRelaxNGNewDocParserCtxt() failed') __tmp = relaxNgParserCtxt(_obj=ret) return __tmp
def function[relaxNGNewDocParserCtxt, parameter[self]]: constant[Create an XML RelaxNGs parser context for that document. Note: since the process of compiling a RelaxNG schemas modifies the document, the @doc parameter is duplicated internally. ] variable[ret] assign[=] call[name[libxml2mod].xmlRelaxNGNewDocParserCtxt, parameter[name[self]._o]] if compare[name[ret] is constant[None]] begin[:] <ast.Raise object at 0x7da1b1f63220> variable[__tmp] assign[=] call[name[relaxNgParserCtxt], parameter[]] return[name[__tmp]]
keyword[def] identifier[relaxNGNewDocParserCtxt] ( identifier[self] ): literal[string] identifier[ret] = identifier[libxml2mod] . identifier[xmlRelaxNGNewDocParserCtxt] ( identifier[self] . identifier[_o] ) keyword[if] identifier[ret] keyword[is] keyword[None] : keyword[raise] identifier[parserError] ( literal[string] ) identifier[__tmp] = identifier[relaxNgParserCtxt] ( identifier[_obj] = identifier[ret] ) keyword[return] identifier[__tmp]
def relaxNGNewDocParserCtxt(self): """Create an XML RelaxNGs parser context for that document. Note: since the process of compiling a RelaxNG schemas modifies the document, the @doc parameter is duplicated internally. """ ret = libxml2mod.xmlRelaxNGNewDocParserCtxt(self._o) if ret is None: raise parserError('xmlRelaxNGNewDocParserCtxt() failed') # depends on [control=['if'], data=[]] __tmp = relaxNgParserCtxt(_obj=ret) return __tmp
def green(fn=None, consume_green_mode=True): """Make a function green. Can be used as a decorator.""" def decorator(fn): @wraps(fn) def greener(obj, *args, **kwargs): args = (obj,) + args wait = kwargs.pop('wait', None) timeout = kwargs.pop('timeout', None) access = kwargs.pop if consume_green_mode else kwargs.get green_mode = access('green_mode', None) executor = get_object_executor(obj, green_mode) return executor.run(fn, args, kwargs, wait=wait, timeout=timeout) return greener if fn is None: return decorator return decorator(fn)
def function[green, parameter[fn, consume_green_mode]]: constant[Make a function green. Can be used as a decorator.] def function[decorator, parameter[fn]]: def function[greener, parameter[obj]]: variable[args] assign[=] binary_operation[tuple[[<ast.Name object at 0x7da18dc06c50>]] + name[args]] variable[wait] assign[=] call[name[kwargs].pop, parameter[constant[wait], constant[None]]] variable[timeout] assign[=] call[name[kwargs].pop, parameter[constant[timeout], constant[None]]] variable[access] assign[=] <ast.IfExp object at 0x7da18dc04ca0> variable[green_mode] assign[=] call[name[access], parameter[constant[green_mode], constant[None]]] variable[executor] assign[=] call[name[get_object_executor], parameter[name[obj], name[green_mode]]] return[call[name[executor].run, parameter[name[fn], name[args], name[kwargs]]]] return[name[greener]] if compare[name[fn] is constant[None]] begin[:] return[name[decorator]] return[call[name[decorator], parameter[name[fn]]]]
keyword[def] identifier[green] ( identifier[fn] = keyword[None] , identifier[consume_green_mode] = keyword[True] ): literal[string] keyword[def] identifier[decorator] ( identifier[fn] ): @ identifier[wraps] ( identifier[fn] ) keyword[def] identifier[greener] ( identifier[obj] ,* identifier[args] ,** identifier[kwargs] ): identifier[args] =( identifier[obj] ,)+ identifier[args] identifier[wait] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) identifier[timeout] = identifier[kwargs] . identifier[pop] ( literal[string] , keyword[None] ) identifier[access] = identifier[kwargs] . identifier[pop] keyword[if] identifier[consume_green_mode] keyword[else] identifier[kwargs] . identifier[get] identifier[green_mode] = identifier[access] ( literal[string] , keyword[None] ) identifier[executor] = identifier[get_object_executor] ( identifier[obj] , identifier[green_mode] ) keyword[return] identifier[executor] . identifier[run] ( identifier[fn] , identifier[args] , identifier[kwargs] , identifier[wait] = identifier[wait] , identifier[timeout] = identifier[timeout] ) keyword[return] identifier[greener] keyword[if] identifier[fn] keyword[is] keyword[None] : keyword[return] identifier[decorator] keyword[return] identifier[decorator] ( identifier[fn] )
def green(fn=None, consume_green_mode=True): """Make a function green. Can be used as a decorator.""" def decorator(fn): @wraps(fn) def greener(obj, *args, **kwargs): args = (obj,) + args wait = kwargs.pop('wait', None) timeout = kwargs.pop('timeout', None) access = kwargs.pop if consume_green_mode else kwargs.get green_mode = access('green_mode', None) executor = get_object_executor(obj, green_mode) return executor.run(fn, args, kwargs, wait=wait, timeout=timeout) return greener if fn is None: return decorator # depends on [control=['if'], data=[]] return decorator(fn)
def pnl_upsert(self, asset_manager_id, pnls): """ Upsert a list of pnls. Note: this performs a full update of existing records with matching keys, so the passed in pnl objects should be complete. Args: asset_manager_id (int): the id of the asset manager owning the pnl pnls (list): list of pnl objects to upsert """ self.logger.info('Upsert PnL for - Asset Manager: %s', asset_manager_id) pnls = [pnls] if not isinstance(pnls, list) else pnls json_pnls = [pnl.to_interface() for pnl in pnls] url = '%s/pnls/%s' % (self.endpoint, asset_manager_id) response = self.session.put(url, json=json_pnls) if response.ok: results = [] for pnl_result in response.json(): results.append(json_to_pnl(pnl_result)) self.logger.info('Upserted %s PnL records', len(results)) return results else: self.logger.error(response.text) response.raise_for_status()
def function[pnl_upsert, parameter[self, asset_manager_id, pnls]]: constant[ Upsert a list of pnls. Note: this performs a full update of existing records with matching keys, so the passed in pnl objects should be complete. Args: asset_manager_id (int): the id of the asset manager owning the pnl pnls (list): list of pnl objects to upsert ] call[name[self].logger.info, parameter[constant[Upsert PnL for - Asset Manager: %s], name[asset_manager_id]]] variable[pnls] assign[=] <ast.IfExp object at 0x7da1b09ed630> variable[json_pnls] assign[=] <ast.ListComp object at 0x7da1b09ec0d0> variable[url] assign[=] binary_operation[constant[%s/pnls/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b09ec1f0>, <ast.Name object at 0x7da1b09ee590>]]] variable[response] assign[=] call[name[self].session.put, parameter[name[url]]] if name[response].ok begin[:] variable[results] assign[=] list[[]] for taget[name[pnl_result]] in starred[call[name[response].json, parameter[]]] begin[:] call[name[results].append, parameter[call[name[json_to_pnl], parameter[name[pnl_result]]]]] call[name[self].logger.info, parameter[constant[Upserted %s PnL records], call[name[len], parameter[name[results]]]]] return[name[results]]
keyword[def] identifier[pnl_upsert] ( identifier[self] , identifier[asset_manager_id] , identifier[pnls] ): literal[string] identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[asset_manager_id] ) identifier[pnls] =[ identifier[pnls] ] keyword[if] keyword[not] identifier[isinstance] ( identifier[pnls] , identifier[list] ) keyword[else] identifier[pnls] identifier[json_pnls] =[ identifier[pnl] . identifier[to_interface] () keyword[for] identifier[pnl] keyword[in] identifier[pnls] ] identifier[url] = literal[string] %( identifier[self] . identifier[endpoint] , identifier[asset_manager_id] ) identifier[response] = identifier[self] . identifier[session] . identifier[put] ( identifier[url] , identifier[json] = identifier[json_pnls] ) keyword[if] identifier[response] . identifier[ok] : identifier[results] =[] keyword[for] identifier[pnl_result] keyword[in] identifier[response] . identifier[json] (): identifier[results] . identifier[append] ( identifier[json_to_pnl] ( identifier[pnl_result] )) identifier[self] . identifier[logger] . identifier[info] ( literal[string] , identifier[len] ( identifier[results] )) keyword[return] identifier[results] keyword[else] : identifier[self] . identifier[logger] . identifier[error] ( identifier[response] . identifier[text] ) identifier[response] . identifier[raise_for_status] ()
def pnl_upsert(self, asset_manager_id, pnls): """ Upsert a list of pnls. Note: this performs a full update of existing records with matching keys, so the passed in pnl objects should be complete. Args: asset_manager_id (int): the id of the asset manager owning the pnl pnls (list): list of pnl objects to upsert """ self.logger.info('Upsert PnL for - Asset Manager: %s', asset_manager_id) pnls = [pnls] if not isinstance(pnls, list) else pnls json_pnls = [pnl.to_interface() for pnl in pnls] url = '%s/pnls/%s' % (self.endpoint, asset_manager_id) response = self.session.put(url, json=json_pnls) if response.ok: results = [] for pnl_result in response.json(): results.append(json_to_pnl(pnl_result)) # depends on [control=['for'], data=['pnl_result']] self.logger.info('Upserted %s PnL records', len(results)) return results # depends on [control=['if'], data=[]] else: self.logger.error(response.text) response.raise_for_status()
def _pipeline_needs_fastq(config, data): """Determine if the pipeline can proceed with a BAM file, or needs fastq conversion. """ aligner = config["algorithm"].get("aligner") support_bam = aligner in alignment.metadata.get("support_bam", []) return aligner and not support_bam
def function[_pipeline_needs_fastq, parameter[config, data]]: constant[Determine if the pipeline can proceed with a BAM file, or needs fastq conversion. ] variable[aligner] assign[=] call[call[name[config]][constant[algorithm]].get, parameter[constant[aligner]]] variable[support_bam] assign[=] compare[name[aligner] in call[name[alignment].metadata.get, parameter[constant[support_bam], list[[]]]]] return[<ast.BoolOp object at 0x7da1b1844520>]
keyword[def] identifier[_pipeline_needs_fastq] ( identifier[config] , identifier[data] ): literal[string] identifier[aligner] = identifier[config] [ literal[string] ]. identifier[get] ( literal[string] ) identifier[support_bam] = identifier[aligner] keyword[in] identifier[alignment] . identifier[metadata] . identifier[get] ( literal[string] ,[]) keyword[return] identifier[aligner] keyword[and] keyword[not] identifier[support_bam]
def _pipeline_needs_fastq(config, data): """Determine if the pipeline can proceed with a BAM file, or needs fastq conversion. """ aligner = config['algorithm'].get('aligner') support_bam = aligner in alignment.metadata.get('support_bam', []) return aligner and (not support_bam)
def cli_ping(context, prefix): """ Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping """ if not prefix: prefix = 'swiftly-ping' ping_ring_object_puts = collections.defaultdict(lambda: []) ping_ring_object_gets = collections.defaultdict(lambda: []) ping_ring_object_deletes = collections.defaultdict(lambda: []) context.ping_begin = context.ping_begin_last = time.time() container = prefix + '-' + uuid.uuid4().hex objects = [uuid.uuid4().hex for x in moves.range(context.ping_count)] conc = Concurrency(context.concurrency) with context.client_manager.with_client() as client: client.auth() _cli_ping_status(context, 'auth', '-', None, None, None, None) _cli_ping_status(context, 'account head', '-', *client.head_account()) _cli_ping_status( context, 'container put', '-', *client.put_container(container)) if _cli_ping_objects( context, 'put', conc, container, objects, _cli_ping_object_put, ping_ring_object_puts): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR put objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'get', conc, container, objects, _cli_ping_object_get, ping_ring_object_gets): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR get objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'delete', conc, container, objects, _cli_ping_object_delete, ping_ring_object_deletes): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR delete objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() for attempt in moves.range(5): if attempt: sleep(2**attempt) with context.client_manager.with_client() as client: try: _cli_ping_status( context, 'container delete', '-', *client.delete_container(container)) break except ReturnCode as err: with context.io_manager.with_stderr() as fp: fp.write(str(err)) fp.write('\n') fp.flush() else: with context.io_manager.with_stderr() as fp: fp.write( 'ERROR could not confirm deletion of container due to ' 'previous error; but continuing\n') fp.flush() end = time.time() with context.io_manager.with_stdout() as fp: if context.graphite: fp.write( '%s.ping_overall %.02f %d\n' % ( context.graphite, end - context.ping_begin, time.time())) if context.ping_verbose: fp.write('% 6.02fs total\n' % (end - context.ping_begin)) elif not context.graphite: fp.write('%.02fs\n' % (end - context.ping_begin)) fp.flush() ping_ring_overall = collections.defaultdict(lambda: []) _cli_ping_ring_report(context, ping_ring_object_puts, 'PUT') for ip, timings in six.iteritems(ping_ring_object_puts): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_gets, 'GET') for ip, timings in six.iteritems(ping_ring_object_gets): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_deletes, 'DELETE') for ip, timings in six.iteritems(ping_ring_object_deletes): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_overall, 'overall')
def function[cli_ping, parameter[context, prefix]]: constant[ Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping ] if <ast.UnaryOp object at 0x7da1b26aeb30> begin[:] variable[prefix] assign[=] constant[swiftly-ping] variable[ping_ring_object_puts] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b26adf60>]] variable[ping_ring_object_gets] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b26ad4e0>]] variable[ping_ring_object_deletes] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da1b26aff40>]] name[context].ping_begin assign[=] call[name[time].time, parameter[]] variable[container] assign[=] binary_operation[binary_operation[name[prefix] + constant[-]] + call[name[uuid].uuid4, parameter[]].hex] variable[objects] assign[=] <ast.ListComp object at 0x7da1b26aefe0> variable[conc] assign[=] call[name[Concurrency], parameter[name[context].concurrency]] with call[name[context].client_manager.with_client, parameter[]] begin[:] call[name[client].auth, parameter[]] call[name[_cli_ping_status], parameter[name[context], constant[auth], constant[-], constant[None], constant[None], constant[None], constant[None]]] call[name[_cli_ping_status], parameter[name[context], constant[account head], constant[-], <ast.Starred object at 0x7da1b26ae470>]] call[name[_cli_ping_status], parameter[name[context], constant[container put], constant[-], <ast.Starred object at 0x7da1b26ac6a0>]] if call[name[_cli_ping_objects], parameter[name[context], constant[put], name[conc], name[container], name[objects], name[_cli_ping_object_put], name[ping_ring_object_puts]]] begin[:] with call[name[context].io_manager.with_stderr, parameter[]] begin[:] call[name[fp].write, parameter[constant[ERROR put objects did not complete successfully due to previous error; but continuing ]]] call[name[fp].flush, parameter[]] if call[name[_cli_ping_objects], parameter[name[context], constant[get], name[conc], name[container], name[objects], name[_cli_ping_object_get], name[ping_ring_object_gets]]] begin[:] with call[name[context].io_manager.with_stderr, parameter[]] begin[:] call[name[fp].write, parameter[constant[ERROR get objects did not complete successfully due to previous error; but continuing ]]] call[name[fp].flush, parameter[]] if call[name[_cli_ping_objects], parameter[name[context], constant[delete], name[conc], name[container], name[objects], name[_cli_ping_object_delete], name[ping_ring_object_deletes]]] begin[:] with call[name[context].io_manager.with_stderr, parameter[]] begin[:] call[name[fp].write, parameter[constant[ERROR delete objects did not complete successfully due to previous error; but continuing ]]] call[name[fp].flush, parameter[]] for taget[name[attempt]] in starred[call[name[moves].range, parameter[constant[5]]]] begin[:] if name[attempt] begin[:] call[name[sleep], parameter[binary_operation[constant[2] ** name[attempt]]]] with call[name[context].client_manager.with_client, parameter[]] begin[:] <ast.Try object at 0x7da18f722aa0> variable[end] assign[=] call[name[time].time, parameter[]] with call[name[context].io_manager.with_stdout, parameter[]] begin[:] if name[context].graphite begin[:] call[name[fp].write, parameter[binary_operation[constant[%s.ping_overall %.02f %d ] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da18f7227d0>, <ast.BinOp object at 0x7da18f721300>, <ast.Call object at 0x7da18f721150>]]]]] if name[context].ping_verbose begin[:] call[name[fp].write, parameter[binary_operation[constant[% 6.02fs total ] <ast.Mod object at 0x7da2590d6920> binary_operation[name[end] - name[context].ping_begin]]]] call[name[fp].flush, parameter[]] variable[ping_ring_overall] assign[=] call[name[collections].defaultdict, parameter[<ast.Lambda object at 0x7da18f721000>]] call[name[_cli_ping_ring_report], parameter[name[context], name[ping_ring_object_puts], constant[PUT]]] for taget[tuple[[<ast.Name object at 0x7da18f720370>, <ast.Name object at 0x7da18f7212a0>]]] in starred[call[name[six].iteritems, parameter[name[ping_ring_object_puts]]]] begin[:] call[call[name[ping_ring_overall]][name[ip]].extend, parameter[name[timings]]] call[name[_cli_ping_ring_report], parameter[name[context], name[ping_ring_object_gets], constant[GET]]] for taget[tuple[[<ast.Name object at 0x7da18f00c4c0>, <ast.Name object at 0x7da18f00dc60>]]] in starred[call[name[six].iteritems, parameter[name[ping_ring_object_gets]]]] begin[:] call[call[name[ping_ring_overall]][name[ip]].extend, parameter[name[timings]]] call[name[_cli_ping_ring_report], parameter[name[context], name[ping_ring_object_deletes], constant[DELETE]]] for taget[tuple[[<ast.Name object at 0x7da18f00c310>, <ast.Name object at 0x7da18f00d900>]]] in starred[call[name[six].iteritems, parameter[name[ping_ring_object_deletes]]]] begin[:] call[call[name[ping_ring_overall]][name[ip]].extend, parameter[name[timings]]] call[name[_cli_ping_ring_report], parameter[name[context], name[ping_ring_overall], constant[overall]]]
keyword[def] identifier[cli_ping] ( identifier[context] , identifier[prefix] ): literal[string] keyword[if] keyword[not] identifier[prefix] : identifier[prefix] = literal[string] identifier[ping_ring_object_puts] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[]) identifier[ping_ring_object_gets] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[]) identifier[ping_ring_object_deletes] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[]) identifier[context] . identifier[ping_begin] = identifier[context] . identifier[ping_begin_last] = identifier[time] . identifier[time] () identifier[container] = identifier[prefix] + literal[string] + identifier[uuid] . identifier[uuid4] (). identifier[hex] identifier[objects] =[ identifier[uuid] . identifier[uuid4] (). identifier[hex] keyword[for] identifier[x] keyword[in] identifier[moves] . identifier[range] ( identifier[context] . identifier[ping_count] )] identifier[conc] = identifier[Concurrency] ( identifier[context] . identifier[concurrency] ) keyword[with] identifier[context] . identifier[client_manager] . identifier[with_client] () keyword[as] identifier[client] : identifier[client] . identifier[auth] () identifier[_cli_ping_status] ( identifier[context] , literal[string] , literal[string] , keyword[None] , keyword[None] , keyword[None] , keyword[None] ) identifier[_cli_ping_status] ( identifier[context] , literal[string] , literal[string] ,* identifier[client] . identifier[head_account] ()) identifier[_cli_ping_status] ( identifier[context] , literal[string] , literal[string] ,* identifier[client] . identifier[put_container] ( identifier[container] )) keyword[if] identifier[_cli_ping_objects] ( identifier[context] , literal[string] , identifier[conc] , identifier[container] , identifier[objects] , identifier[_cli_ping_object_put] , identifier[ping_ring_object_puts] ): keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stderr] () keyword[as] identifier[fp] : identifier[fp] . identifier[write] ( literal[string] literal[string] ) identifier[fp] . identifier[flush] () keyword[if] identifier[_cli_ping_objects] ( identifier[context] , literal[string] , identifier[conc] , identifier[container] , identifier[objects] , identifier[_cli_ping_object_get] , identifier[ping_ring_object_gets] ): keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stderr] () keyword[as] identifier[fp] : identifier[fp] . identifier[write] ( literal[string] literal[string] ) identifier[fp] . identifier[flush] () keyword[if] identifier[_cli_ping_objects] ( identifier[context] , literal[string] , identifier[conc] , identifier[container] , identifier[objects] , identifier[_cli_ping_object_delete] , identifier[ping_ring_object_deletes] ): keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stderr] () keyword[as] identifier[fp] : identifier[fp] . identifier[write] ( literal[string] literal[string] ) identifier[fp] . identifier[flush] () keyword[for] identifier[attempt] keyword[in] identifier[moves] . identifier[range] ( literal[int] ): keyword[if] identifier[attempt] : identifier[sleep] ( literal[int] ** identifier[attempt] ) keyword[with] identifier[context] . identifier[client_manager] . identifier[with_client] () keyword[as] identifier[client] : keyword[try] : identifier[_cli_ping_status] ( identifier[context] , literal[string] , literal[string] , * identifier[client] . identifier[delete_container] ( identifier[container] )) keyword[break] keyword[except] identifier[ReturnCode] keyword[as] identifier[err] : keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stderr] () keyword[as] identifier[fp] : identifier[fp] . identifier[write] ( identifier[str] ( identifier[err] )) identifier[fp] . identifier[write] ( literal[string] ) identifier[fp] . identifier[flush] () keyword[else] : keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stderr] () keyword[as] identifier[fp] : identifier[fp] . identifier[write] ( literal[string] literal[string] ) identifier[fp] . identifier[flush] () identifier[end] = identifier[time] . identifier[time] () keyword[with] identifier[context] . identifier[io_manager] . identifier[with_stdout] () keyword[as] identifier[fp] : keyword[if] identifier[context] . identifier[graphite] : identifier[fp] . identifier[write] ( literal[string] %( identifier[context] . identifier[graphite] , identifier[end] - identifier[context] . identifier[ping_begin] , identifier[time] . identifier[time] ())) keyword[if] identifier[context] . identifier[ping_verbose] : identifier[fp] . identifier[write] ( literal[string] %( identifier[end] - identifier[context] . identifier[ping_begin] )) keyword[elif] keyword[not] identifier[context] . identifier[graphite] : identifier[fp] . identifier[write] ( literal[string] %( identifier[end] - identifier[context] . identifier[ping_begin] )) identifier[fp] . identifier[flush] () identifier[ping_ring_overall] = identifier[collections] . identifier[defaultdict] ( keyword[lambda] :[]) identifier[_cli_ping_ring_report] ( identifier[context] , identifier[ping_ring_object_puts] , literal[string] ) keyword[for] identifier[ip] , identifier[timings] keyword[in] identifier[six] . identifier[iteritems] ( identifier[ping_ring_object_puts] ): identifier[ping_ring_overall] [ identifier[ip] ]. identifier[extend] ( identifier[timings] ) identifier[_cli_ping_ring_report] ( identifier[context] , identifier[ping_ring_object_gets] , literal[string] ) keyword[for] identifier[ip] , identifier[timings] keyword[in] identifier[six] . identifier[iteritems] ( identifier[ping_ring_object_gets] ): identifier[ping_ring_overall] [ identifier[ip] ]. identifier[extend] ( identifier[timings] ) identifier[_cli_ping_ring_report] ( identifier[context] , identifier[ping_ring_object_deletes] , literal[string] ) keyword[for] identifier[ip] , identifier[timings] keyword[in] identifier[six] . identifier[iteritems] ( identifier[ping_ring_object_deletes] ): identifier[ping_ring_overall] [ identifier[ip] ]. identifier[extend] ( identifier[timings] ) identifier[_cli_ping_ring_report] ( identifier[context] , identifier[ping_ring_overall] , literal[string] )
def cli_ping(context, prefix): """ Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping """ if not prefix: prefix = 'swiftly-ping' # depends on [control=['if'], data=[]] ping_ring_object_puts = collections.defaultdict(lambda : []) ping_ring_object_gets = collections.defaultdict(lambda : []) ping_ring_object_deletes = collections.defaultdict(lambda : []) context.ping_begin = context.ping_begin_last = time.time() container = prefix + '-' + uuid.uuid4().hex objects = [uuid.uuid4().hex for x in moves.range(context.ping_count)] conc = Concurrency(context.concurrency) with context.client_manager.with_client() as client: client.auth() _cli_ping_status(context, 'auth', '-', None, None, None, None) _cli_ping_status(context, 'account head', '-', *client.head_account()) _cli_ping_status(context, 'container put', '-', *client.put_container(container)) # depends on [control=['with'], data=['client']] if _cli_ping_objects(context, 'put', conc, container, objects, _cli_ping_object_put, ping_ring_object_puts): with context.io_manager.with_stderr() as fp: fp.write('ERROR put objects did not complete successfully due to previous error; but continuing\n') fp.flush() # depends on [control=['with'], data=['fp']] # depends on [control=['if'], data=[]] if _cli_ping_objects(context, 'get', conc, container, objects, _cli_ping_object_get, ping_ring_object_gets): with context.io_manager.with_stderr() as fp: fp.write('ERROR get objects did not complete successfully due to previous error; but continuing\n') fp.flush() # depends on [control=['with'], data=['fp']] # depends on [control=['if'], data=[]] if _cli_ping_objects(context, 'delete', conc, container, objects, _cli_ping_object_delete, ping_ring_object_deletes): with context.io_manager.with_stderr() as fp: fp.write('ERROR delete objects did not complete successfully due to previous error; but continuing\n') fp.flush() # depends on [control=['with'], data=['fp']] # depends on [control=['if'], data=[]] for attempt in moves.range(5): if attempt: sleep(2 ** attempt) # depends on [control=['if'], data=[]] with context.client_manager.with_client() as client: try: _cli_ping_status(context, 'container delete', '-', *client.delete_container(container)) break # depends on [control=['try'], data=[]] except ReturnCode as err: with context.io_manager.with_stderr() as fp: fp.write(str(err)) fp.write('\n') fp.flush() # depends on [control=['with'], data=['fp']] # depends on [control=['except'], data=['err']] # depends on [control=['with'], data=['client']] # depends on [control=['for'], data=['attempt']] else: with context.io_manager.with_stderr() as fp: fp.write('ERROR could not confirm deletion of container due to previous error; but continuing\n') fp.flush() # depends on [control=['with'], data=['fp']] end = time.time() with context.io_manager.with_stdout() as fp: if context.graphite: fp.write('%s.ping_overall %.02f %d\n' % (context.graphite, end - context.ping_begin, time.time())) # depends on [control=['if'], data=[]] if context.ping_verbose: fp.write('% 6.02fs total\n' % (end - context.ping_begin)) # depends on [control=['if'], data=[]] elif not context.graphite: fp.write('%.02fs\n' % (end - context.ping_begin)) # depends on [control=['if'], data=[]] fp.flush() # depends on [control=['with'], data=['fp']] ping_ring_overall = collections.defaultdict(lambda : []) _cli_ping_ring_report(context, ping_ring_object_puts, 'PUT') for (ip, timings) in six.iteritems(ping_ring_object_puts): ping_ring_overall[ip].extend(timings) # depends on [control=['for'], data=[]] _cli_ping_ring_report(context, ping_ring_object_gets, 'GET') for (ip, timings) in six.iteritems(ping_ring_object_gets): ping_ring_overall[ip].extend(timings) # depends on [control=['for'], data=[]] _cli_ping_ring_report(context, ping_ring_object_deletes, 'DELETE') for (ip, timings) in six.iteritems(ping_ring_object_deletes): ping_ring_overall[ip].extend(timings) # depends on [control=['for'], data=[]] _cli_ping_ring_report(context, ping_ring_overall, 'overall')
def update_current_state(self, value: str, force: bool = False) -> datetime: """Update the current state. Args: value (str): New value for sdp state force (bool): If true, ignore allowed transitions Returns: datetime, update timestamp Raises: ValueError: If the specified current state is not allowed. """ value = value.lower() if not force: current_state = self.current_state # IF the current state is unknown, it can be set to any of the # allowed states, otherwise only allow certain transitions. if current_state == 'unknown': allowed_transitions = self._allowed_states else: allowed_transitions = self._allowed_transitions[current_state] allowed_transitions.append(current_state) LOG.debug('Updating current state of %s to %s', self._id, value) if value not in allowed_transitions: raise ValueError("Invalid current state update: '{}'. '{}' " "can be transitioned to states: {}" .format(value, current_state, allowed_transitions)) return self._update_state('current', value)
def function[update_current_state, parameter[self, value, force]]: constant[Update the current state. Args: value (str): New value for sdp state force (bool): If true, ignore allowed transitions Returns: datetime, update timestamp Raises: ValueError: If the specified current state is not allowed. ] variable[value] assign[=] call[name[value].lower, parameter[]] if <ast.UnaryOp object at 0x7da1b04fd750> begin[:] variable[current_state] assign[=] name[self].current_state if compare[name[current_state] equal[==] constant[unknown]] begin[:] variable[allowed_transitions] assign[=] name[self]._allowed_states call[name[LOG].debug, parameter[constant[Updating current state of %s to %s], name[self]._id, name[value]]] if compare[name[value] <ast.NotIn object at 0x7da2590d7190> name[allowed_transitions]] begin[:] <ast.Raise object at 0x7da1b04fc910> return[call[name[self]._update_state, parameter[constant[current], name[value]]]]
keyword[def] identifier[update_current_state] ( identifier[self] , identifier[value] : identifier[str] , identifier[force] : identifier[bool] = keyword[False] )-> identifier[datetime] : literal[string] identifier[value] = identifier[value] . identifier[lower] () keyword[if] keyword[not] identifier[force] : identifier[current_state] = identifier[self] . identifier[current_state] keyword[if] identifier[current_state] == literal[string] : identifier[allowed_transitions] = identifier[self] . identifier[_allowed_states] keyword[else] : identifier[allowed_transitions] = identifier[self] . identifier[_allowed_transitions] [ identifier[current_state] ] identifier[allowed_transitions] . identifier[append] ( identifier[current_state] ) identifier[LOG] . identifier[debug] ( literal[string] , identifier[self] . identifier[_id] , identifier[value] ) keyword[if] identifier[value] keyword[not] keyword[in] identifier[allowed_transitions] : keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[value] , identifier[current_state] , identifier[allowed_transitions] )) keyword[return] identifier[self] . identifier[_update_state] ( literal[string] , identifier[value] )
def update_current_state(self, value: str, force: bool=False) -> datetime: """Update the current state. Args: value (str): New value for sdp state force (bool): If true, ignore allowed transitions Returns: datetime, update timestamp Raises: ValueError: If the specified current state is not allowed. """ value = value.lower() if not force: current_state = self.current_state # IF the current state is unknown, it can be set to any of the # allowed states, otherwise only allow certain transitions. if current_state == 'unknown': allowed_transitions = self._allowed_states # depends on [control=['if'], data=[]] else: allowed_transitions = self._allowed_transitions[current_state] allowed_transitions.append(current_state) LOG.debug('Updating current state of %s to %s', self._id, value) if value not in allowed_transitions: raise ValueError("Invalid current state update: '{}'. '{}' can be transitioned to states: {}".format(value, current_state, allowed_transitions)) # depends on [control=['if'], data=['value', 'allowed_transitions']] # depends on [control=['if'], data=[]] return self._update_state('current', value)
def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)
def function[parameters_to_datetime, parameter[self, p]]: constant[ Given a dictionary of parameters, will extract the ranged task parameter value ] variable[dt] assign[=] call[name[p]][name[self]._param_name] return[call[name[datetime], parameter[name[dt].year, name[dt].month, name[dt].day]]]
keyword[def] identifier[parameters_to_datetime] ( identifier[self] , identifier[p] ): literal[string] identifier[dt] = identifier[p] [ identifier[self] . identifier[_param_name] ] keyword[return] identifier[datetime] ( identifier[dt] . identifier[year] , identifier[dt] . identifier[month] , identifier[dt] . identifier[day] )
def parameters_to_datetime(self, p): """ Given a dictionary of parameters, will extract the ranged task parameter value """ dt = p[self._param_name] return datetime(dt.year, dt.month, dt.day)