code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def construct_graph(sakefile, settings): """ Takes the sakefile dictionary and builds a NetworkX graph Args: A dictionary that is the parsed Sakefile (from sake.py) The settings dictionary Returns: A NetworkX graph """ verbose = settings["verbose"] sprint = settings["sprint"] G = nx.DiGraph() sprint("Going to construct Graph", level="verbose") for target in sakefile: if target == "all": # we don't want this node continue if "formula" not in sakefile[target]: # that means this is a meta target for atomtarget in sakefile[target]: if atomtarget == "help": continue sprint("Adding '{}'".format(atomtarget), level="verbose") data_dict = sakefile[target][atomtarget] data_dict["parent"] = target G.add_node(atomtarget, **data_dict) else: sprint("Adding '{}'".format(target), level="verbose") G.add_node(target, **sakefile[target]) sprint("Nodes are built\nBuilding connections", level="verbose") for node in G.nodes(data=True): sprint("checking node {} for dependencies".format(node[0]), level="verbose") # normalize all paths in output for k, v in node[1].items(): if v is None: node[1][k] = [] if "output" in node[1]: for index, out in enumerate(node[1]['output']): node[1]['output'][index] = clean_path(node[1]['output'][index]) if "dependencies" not in node[1]: continue sprint("it has dependencies", level="verbose") connects = [] # normalize all paths in dependencies for index, dep in enumerate(node[1]['dependencies']): dep = os.path.normpath(dep) shrt = "dependencies" node[1]['dependencies'][index] = clean_path(node[1][shrt][index]) for node in G.nodes(data=True): connects = [] if "dependencies" not in node[1]: continue for dep in node[1]['dependencies']: matches = check_for_dep_in_outputs(dep, verbose, G) if not matches: continue for match in matches: sprint("Appending {} to matches".format(match), level="verbose") connects.append(match) if connects: for connect in connects: G.add_edge(connect, node[0]) return G
def function[construct_graph, parameter[sakefile, settings]]: constant[ Takes the sakefile dictionary and builds a NetworkX graph Args: A dictionary that is the parsed Sakefile (from sake.py) The settings dictionary Returns: A NetworkX graph ] variable[verbose] assign[=] call[name[settings]][constant[verbose]] variable[sprint] assign[=] call[name[settings]][constant[sprint]] variable[G] assign[=] call[name[nx].DiGraph, parameter[]] call[name[sprint], parameter[constant[Going to construct Graph]]] for taget[name[target]] in starred[name[sakefile]] begin[:] if compare[name[target] equal[==] constant[all]] begin[:] continue if compare[constant[formula] <ast.NotIn object at 0x7da2590d7190> call[name[sakefile]][name[target]]] begin[:] for taget[name[atomtarget]] in starred[call[name[sakefile]][name[target]]] begin[:] if compare[name[atomtarget] equal[==] constant[help]] begin[:] continue call[name[sprint], parameter[call[constant[Adding '{}'].format, parameter[name[atomtarget]]]]] variable[data_dict] assign[=] call[call[name[sakefile]][name[target]]][name[atomtarget]] call[name[data_dict]][constant[parent]] assign[=] name[target] call[name[G].add_node, parameter[name[atomtarget]]] call[name[sprint], parameter[constant[Nodes are built Building connections]]] for taget[name[node]] in starred[call[name[G].nodes, parameter[]]] begin[:] call[name[sprint], parameter[call[constant[checking node {} for dependencies].format, parameter[call[name[node]][constant[0]]]]]] for taget[tuple[[<ast.Name object at 0x7da1afe60fa0>, <ast.Name object at 0x7da1afe60fd0>]]] in starred[call[call[name[node]][constant[1]].items, parameter[]]] begin[:] if compare[name[v] is constant[None]] begin[:] call[call[name[node]][constant[1]]][name[k]] assign[=] list[[]] if compare[constant[output] in call[name[node]][constant[1]]] begin[:] for taget[tuple[[<ast.Name object at 0x7da1afe61480>, <ast.Name object at 0x7da1afe614b0>]]] in starred[call[name[enumerate], parameter[call[call[name[node]][constant[1]]][constant[output]]]]] begin[:] call[call[call[name[node]][constant[1]]][constant[output]]][name[index]] assign[=] call[name[clean_path], parameter[call[call[call[name[node]][constant[1]]][constant[output]]][name[index]]]] if compare[constant[dependencies] <ast.NotIn object at 0x7da2590d7190> call[name[node]][constant[1]]] begin[:] continue call[name[sprint], parameter[constant[it has dependencies]]] variable[connects] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1afe61d20>, <ast.Name object at 0x7da1afe61d50>]]] in starred[call[name[enumerate], parameter[call[call[name[node]][constant[1]]][constant[dependencies]]]]] begin[:] variable[dep] assign[=] call[name[os].path.normpath, parameter[name[dep]]] variable[shrt] assign[=] constant[dependencies] call[call[call[name[node]][constant[1]]][constant[dependencies]]][name[index]] assign[=] call[name[clean_path], parameter[call[call[call[name[node]][constant[1]]][name[shrt]]][name[index]]]] for taget[name[node]] in starred[call[name[G].nodes, parameter[]]] begin[:] variable[connects] assign[=] list[[]] if compare[constant[dependencies] <ast.NotIn object at 0x7da2590d7190> call[name[node]][constant[1]]] begin[:] continue for taget[name[dep]] in starred[call[call[name[node]][constant[1]]][constant[dependencies]]] begin[:] variable[matches] assign[=] call[name[check_for_dep_in_outputs], parameter[name[dep], name[verbose], name[G]]] if <ast.UnaryOp object at 0x7da1aff1f640> begin[:] continue for taget[name[match]] in starred[name[matches]] begin[:] call[name[sprint], parameter[call[constant[Appending {} to matches].format, parameter[name[match]]]]] call[name[connects].append, parameter[name[match]]] if name[connects] begin[:] for taget[name[connect]] in starred[name[connects]] begin[:] call[name[G].add_edge, parameter[name[connect], call[name[node]][constant[0]]]] return[name[G]]
keyword[def] identifier[construct_graph] ( identifier[sakefile] , identifier[settings] ): literal[string] identifier[verbose] = identifier[settings] [ literal[string] ] identifier[sprint] = identifier[settings] [ literal[string] ] identifier[G] = identifier[nx] . identifier[DiGraph] () identifier[sprint] ( literal[string] , identifier[level] = literal[string] ) keyword[for] identifier[target] keyword[in] identifier[sakefile] : keyword[if] identifier[target] == literal[string] : keyword[continue] keyword[if] literal[string] keyword[not] keyword[in] identifier[sakefile] [ identifier[target] ]: keyword[for] identifier[atomtarget] keyword[in] identifier[sakefile] [ identifier[target] ]: keyword[if] identifier[atomtarget] == literal[string] : keyword[continue] identifier[sprint] ( literal[string] . identifier[format] ( identifier[atomtarget] ), identifier[level] = literal[string] ) identifier[data_dict] = identifier[sakefile] [ identifier[target] ][ identifier[atomtarget] ] identifier[data_dict] [ literal[string] ]= identifier[target] identifier[G] . identifier[add_node] ( identifier[atomtarget] ,** identifier[data_dict] ) keyword[else] : identifier[sprint] ( literal[string] . identifier[format] ( identifier[target] ), identifier[level] = literal[string] ) identifier[G] . identifier[add_node] ( identifier[target] ,** identifier[sakefile] [ identifier[target] ]) identifier[sprint] ( literal[string] , identifier[level] = literal[string] ) keyword[for] identifier[node] keyword[in] identifier[G] . identifier[nodes] ( identifier[data] = keyword[True] ): identifier[sprint] ( literal[string] . identifier[format] ( identifier[node] [ literal[int] ]), identifier[level] = literal[string] ) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[node] [ literal[int] ]. identifier[items] (): keyword[if] identifier[v] keyword[is] keyword[None] : identifier[node] [ literal[int] ][ identifier[k] ]=[] keyword[if] literal[string] keyword[in] identifier[node] [ literal[int] ]: keyword[for] identifier[index] , identifier[out] keyword[in] identifier[enumerate] ( identifier[node] [ literal[int] ][ literal[string] ]): identifier[node] [ literal[int] ][ literal[string] ][ identifier[index] ]= identifier[clean_path] ( identifier[node] [ literal[int] ][ literal[string] ][ identifier[index] ]) keyword[if] literal[string] keyword[not] keyword[in] identifier[node] [ literal[int] ]: keyword[continue] identifier[sprint] ( literal[string] , identifier[level] = literal[string] ) identifier[connects] =[] keyword[for] identifier[index] , identifier[dep] keyword[in] identifier[enumerate] ( identifier[node] [ literal[int] ][ literal[string] ]): identifier[dep] = identifier[os] . identifier[path] . identifier[normpath] ( identifier[dep] ) identifier[shrt] = literal[string] identifier[node] [ literal[int] ][ literal[string] ][ identifier[index] ]= identifier[clean_path] ( identifier[node] [ literal[int] ][ identifier[shrt] ][ identifier[index] ]) keyword[for] identifier[node] keyword[in] identifier[G] . identifier[nodes] ( identifier[data] = keyword[True] ): identifier[connects] =[] keyword[if] literal[string] keyword[not] keyword[in] identifier[node] [ literal[int] ]: keyword[continue] keyword[for] identifier[dep] keyword[in] identifier[node] [ literal[int] ][ literal[string] ]: identifier[matches] = identifier[check_for_dep_in_outputs] ( identifier[dep] , identifier[verbose] , identifier[G] ) keyword[if] keyword[not] identifier[matches] : keyword[continue] keyword[for] identifier[match] keyword[in] identifier[matches] : identifier[sprint] ( literal[string] . identifier[format] ( identifier[match] ), identifier[level] = literal[string] ) identifier[connects] . identifier[append] ( identifier[match] ) keyword[if] identifier[connects] : keyword[for] identifier[connect] keyword[in] identifier[connects] : identifier[G] . identifier[add_edge] ( identifier[connect] , identifier[node] [ literal[int] ]) keyword[return] identifier[G]
def construct_graph(sakefile, settings): """ Takes the sakefile dictionary and builds a NetworkX graph Args: A dictionary that is the parsed Sakefile (from sake.py) The settings dictionary Returns: A NetworkX graph """ verbose = settings['verbose'] sprint = settings['sprint'] G = nx.DiGraph() sprint('Going to construct Graph', level='verbose') for target in sakefile: if target == 'all': # we don't want this node continue # depends on [control=['if'], data=[]] if 'formula' not in sakefile[target]: # that means this is a meta target for atomtarget in sakefile[target]: if atomtarget == 'help': continue # depends on [control=['if'], data=[]] sprint("Adding '{}'".format(atomtarget), level='verbose') data_dict = sakefile[target][atomtarget] data_dict['parent'] = target G.add_node(atomtarget, **data_dict) # depends on [control=['for'], data=['atomtarget']] # depends on [control=['if'], data=[]] else: sprint("Adding '{}'".format(target), level='verbose') G.add_node(target, **sakefile[target]) # depends on [control=['for'], data=['target']] sprint('Nodes are built\nBuilding connections', level='verbose') for node in G.nodes(data=True): sprint('checking node {} for dependencies'.format(node[0]), level='verbose') # normalize all paths in output for (k, v) in node[1].items(): if v is None: node[1][k] = [] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] if 'output' in node[1]: for (index, out) in enumerate(node[1]['output']): node[1]['output'][index] = clean_path(node[1]['output'][index]) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]] if 'dependencies' not in node[1]: continue # depends on [control=['if'], data=[]] sprint('it has dependencies', level='verbose') connects = [] # normalize all paths in dependencies for (index, dep) in enumerate(node[1]['dependencies']): dep = os.path.normpath(dep) shrt = 'dependencies' node[1]['dependencies'][index] = clean_path(node[1][shrt][index]) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['node']] for node in G.nodes(data=True): connects = [] if 'dependencies' not in node[1]: continue # depends on [control=['if'], data=[]] for dep in node[1]['dependencies']: matches = check_for_dep_in_outputs(dep, verbose, G) if not matches: continue # depends on [control=['if'], data=[]] for match in matches: sprint('Appending {} to matches'.format(match), level='verbose') connects.append(match) # depends on [control=['for'], data=['match']] # depends on [control=['for'], data=['dep']] if connects: for connect in connects: G.add_edge(connect, node[0]) # depends on [control=['for'], data=['connect']] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['node']] return G
def update_token(self, token, secret): """Update token with new values. :param token: The token value. :param secret: The secret key. """ if self.access_token != token or self.secret != secret: with db.session.begin_nested(): self.access_token = token self.secret = secret db.session.add(self)
def function[update_token, parameter[self, token, secret]]: constant[Update token with new values. :param token: The token value. :param secret: The secret key. ] if <ast.BoolOp object at 0x7da20c6ab070> begin[:] with call[name[db].session.begin_nested, parameter[]] begin[:] name[self].access_token assign[=] name[token] name[self].secret assign[=] name[secret] call[name[db].session.add, parameter[name[self]]]
keyword[def] identifier[update_token] ( identifier[self] , identifier[token] , identifier[secret] ): literal[string] keyword[if] identifier[self] . identifier[access_token] != identifier[token] keyword[or] identifier[self] . identifier[secret] != identifier[secret] : keyword[with] identifier[db] . identifier[session] . identifier[begin_nested] (): identifier[self] . identifier[access_token] = identifier[token] identifier[self] . identifier[secret] = identifier[secret] identifier[db] . identifier[session] . identifier[add] ( identifier[self] )
def update_token(self, token, secret): """Update token with new values. :param token: The token value. :param secret: The secret key. """ if self.access_token != token or self.secret != secret: with db.session.begin_nested(): self.access_token = token self.secret = secret db.session.add(self) # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]]
def future_raise(self, tp, value=None, tb=None): """raise_ implementation from future.utils""" if value is not None and isinstance(tp, Exception): raise TypeError("instance exception may not have a separate value") if value is not None: exc = tp(value) else: exc = tp if exc.__traceback__ is not tb: raise exc.with_traceback(tb) raise exc
def function[future_raise, parameter[self, tp, value, tb]]: constant[raise_ implementation from future.utils] if <ast.BoolOp object at 0x7da207f9b940> begin[:] <ast.Raise object at 0x7da207f9b9a0> if compare[name[value] is_not constant[None]] begin[:] variable[exc] assign[=] call[name[tp], parameter[name[value]]] if compare[name[exc].__traceback__ is_not name[tb]] begin[:] <ast.Raise object at 0x7da207f98d90> <ast.Raise object at 0x7da207f99f30>
keyword[def] identifier[future_raise] ( identifier[self] , identifier[tp] , identifier[value] = keyword[None] , identifier[tb] = keyword[None] ): literal[string] keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] keyword[and] identifier[isinstance] ( identifier[tp] , identifier[Exception] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] : identifier[exc] = identifier[tp] ( identifier[value] ) keyword[else] : identifier[exc] = identifier[tp] keyword[if] identifier[exc] . identifier[__traceback__] keyword[is] keyword[not] identifier[tb] : keyword[raise] identifier[exc] . identifier[with_traceback] ( identifier[tb] ) keyword[raise] identifier[exc]
def future_raise(self, tp, value=None, tb=None): """raise_ implementation from future.utils""" if value is not None and isinstance(tp, Exception): raise TypeError('instance exception may not have a separate value') # depends on [control=['if'], data=[]] if value is not None: exc = tp(value) # depends on [control=['if'], data=['value']] else: exc = tp if exc.__traceback__ is not tb: raise exc.with_traceback(tb) # depends on [control=['if'], data=['tb']] raise exc
def fetch_and_register_remote_function(self, key): """Import a remote function.""" (driver_id_str, function_id_str, function_name, serialized_function, num_return_vals, module, resources, max_calls) = self._worker.redis_client.hmget(key, [ "driver_id", "function_id", "name", "function", "num_return_vals", "module", "resources", "max_calls" ]) function_id = ray.FunctionID(function_id_str) driver_id = ray.DriverID(driver_id_str) function_name = decode(function_name) max_calls = int(max_calls) module = decode(module) # This is a placeholder in case the function can't be unpickled. This # will be overwritten if the function is successfully registered. def f(): raise Exception("This function was not imported properly.") # This function is called by ImportThread. This operation needs to be # atomic. Otherwise, there is race condition. Another thread may use # the temporary function above before the real function is ready. with self.lock: self._function_execution_info[driver_id][function_id] = ( FunctionExecutionInfo( function=f, function_name=function_name, max_calls=max_calls)) self._num_task_executions[driver_id][function_id] = 0 try: function = pickle.loads(serialized_function) except Exception: # If an exception was thrown when the remote function was # imported, we record the traceback and notify the scheduler # of the failure. traceback_str = format_error_message(traceback.format_exc()) # Log the error message. push_error_to_driver( self._worker, ray_constants.REGISTER_REMOTE_FUNCTION_PUSH_ERROR, "Failed to unpickle the remote function '{}' with " "function ID {}. Traceback:\n{}".format( function_name, function_id.hex(), traceback_str), driver_id=driver_id) else: # The below line is necessary. Because in the driver process, # if the function is defined in the file where the python # script was started from, its module is `__main__`. # However in the worker process, the `__main__` module is a # different module, which is `default_worker.py` function.__module__ = module self._function_execution_info[driver_id][function_id] = ( FunctionExecutionInfo( function=function, function_name=function_name, max_calls=max_calls)) # Add the function to the function table. self._worker.redis_client.rpush( b"FunctionTable:" + function_id.binary(), self._worker.worker_id)
def function[fetch_and_register_remote_function, parameter[self, key]]: constant[Import a remote function.] <ast.Tuple object at 0x7da20e9b0c40> assign[=] call[name[self]._worker.redis_client.hmget, parameter[name[key], list[[<ast.Constant object at 0x7da18eb555a0>, <ast.Constant object at 0x7da18eb57a90>, <ast.Constant object at 0x7da18eb559f0>, <ast.Constant object at 0x7da18eb56e00>, <ast.Constant object at 0x7da18eb54160>, <ast.Constant object at 0x7da18eb56f50>, <ast.Constant object at 0x7da18eb56a70>, <ast.Constant object at 0x7da18eb55c30>]]]] variable[function_id] assign[=] call[name[ray].FunctionID, parameter[name[function_id_str]]] variable[driver_id] assign[=] call[name[ray].DriverID, parameter[name[driver_id_str]]] variable[function_name] assign[=] call[name[decode], parameter[name[function_name]]] variable[max_calls] assign[=] call[name[int], parameter[name[max_calls]]] variable[module] assign[=] call[name[decode], parameter[name[module]]] def function[f, parameter[]]: <ast.Raise object at 0x7da18eb55840> with name[self].lock begin[:] call[call[name[self]._function_execution_info][name[driver_id]]][name[function_id]] assign[=] call[name[FunctionExecutionInfo], parameter[]] call[call[name[self]._num_task_executions][name[driver_id]]][name[function_id]] assign[=] constant[0] <ast.Try object at 0x7da18eb563b0>
keyword[def] identifier[fetch_and_register_remote_function] ( identifier[self] , identifier[key] ): literal[string] ( identifier[driver_id_str] , identifier[function_id_str] , identifier[function_name] , identifier[serialized_function] , identifier[num_return_vals] , identifier[module] , identifier[resources] , identifier[max_calls] )= identifier[self] . identifier[_worker] . identifier[redis_client] . identifier[hmget] ( identifier[key] ,[ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]) identifier[function_id] = identifier[ray] . identifier[FunctionID] ( identifier[function_id_str] ) identifier[driver_id] = identifier[ray] . identifier[DriverID] ( identifier[driver_id_str] ) identifier[function_name] = identifier[decode] ( identifier[function_name] ) identifier[max_calls] = identifier[int] ( identifier[max_calls] ) identifier[module] = identifier[decode] ( identifier[module] ) keyword[def] identifier[f] (): keyword[raise] identifier[Exception] ( literal[string] ) keyword[with] identifier[self] . identifier[lock] : identifier[self] . identifier[_function_execution_info] [ identifier[driver_id] ][ identifier[function_id] ]=( identifier[FunctionExecutionInfo] ( identifier[function] = identifier[f] , identifier[function_name] = identifier[function_name] , identifier[max_calls] = identifier[max_calls] )) identifier[self] . identifier[_num_task_executions] [ identifier[driver_id] ][ identifier[function_id] ]= literal[int] keyword[try] : identifier[function] = identifier[pickle] . identifier[loads] ( identifier[serialized_function] ) keyword[except] identifier[Exception] : identifier[traceback_str] = identifier[format_error_message] ( identifier[traceback] . identifier[format_exc] ()) identifier[push_error_to_driver] ( identifier[self] . identifier[_worker] , identifier[ray_constants] . identifier[REGISTER_REMOTE_FUNCTION_PUSH_ERROR] , literal[string] literal[string] . identifier[format] ( identifier[function_name] , identifier[function_id] . identifier[hex] (), identifier[traceback_str] ), identifier[driver_id] = identifier[driver_id] ) keyword[else] : identifier[function] . identifier[__module__] = identifier[module] identifier[self] . identifier[_function_execution_info] [ identifier[driver_id] ][ identifier[function_id] ]=( identifier[FunctionExecutionInfo] ( identifier[function] = identifier[function] , identifier[function_name] = identifier[function_name] , identifier[max_calls] = identifier[max_calls] )) identifier[self] . identifier[_worker] . identifier[redis_client] . identifier[rpush] ( literal[string] + identifier[function_id] . identifier[binary] (), identifier[self] . identifier[_worker] . identifier[worker_id] )
def fetch_and_register_remote_function(self, key): """Import a remote function.""" (driver_id_str, function_id_str, function_name, serialized_function, num_return_vals, module, resources, max_calls) = self._worker.redis_client.hmget(key, ['driver_id', 'function_id', 'name', 'function', 'num_return_vals', 'module', 'resources', 'max_calls']) function_id = ray.FunctionID(function_id_str) driver_id = ray.DriverID(driver_id_str) function_name = decode(function_name) max_calls = int(max_calls) module = decode(module) # This is a placeholder in case the function can't be unpickled. This # will be overwritten if the function is successfully registered. def f(): raise Exception('This function was not imported properly.') # This function is called by ImportThread. This operation needs to be # atomic. Otherwise, there is race condition. Another thread may use # the temporary function above before the real function is ready. with self.lock: self._function_execution_info[driver_id][function_id] = FunctionExecutionInfo(function=f, function_name=function_name, max_calls=max_calls) self._num_task_executions[driver_id][function_id] = 0 try: function = pickle.loads(serialized_function) # depends on [control=['try'], data=[]] except Exception: # If an exception was thrown when the remote function was # imported, we record the traceback and notify the scheduler # of the failure. traceback_str = format_error_message(traceback.format_exc()) # Log the error message. push_error_to_driver(self._worker, ray_constants.REGISTER_REMOTE_FUNCTION_PUSH_ERROR, "Failed to unpickle the remote function '{}' with function ID {}. Traceback:\n{}".format(function_name, function_id.hex(), traceback_str), driver_id=driver_id) # depends on [control=['except'], data=[]] else: # The below line is necessary. Because in the driver process, # if the function is defined in the file where the python # script was started from, its module is `__main__`. # However in the worker process, the `__main__` module is a # different module, which is `default_worker.py` function.__module__ = module self._function_execution_info[driver_id][function_id] = FunctionExecutionInfo(function=function, function_name=function_name, max_calls=max_calls) # Add the function to the function table. self._worker.redis_client.rpush(b'FunctionTable:' + function_id.binary(), self._worker.worker_id) # depends on [control=['with'], data=[]]
def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_read() self.set_base_prompt() self.disable_paging() self.set_terminal_width(command="terminal width 511") # Clear the read buffer time.sleep(0.3 * self.global_delay_factor) self.clear_buffer()
def function[session_preparation, parameter[self]]: constant[Prepare the session after the connection has been established.] name[self].ansi_escape_codes assign[=] constant[True] call[name[self]._test_channel_read, parameter[]] call[name[self].set_base_prompt, parameter[]] call[name[self].disable_paging, parameter[]] call[name[self].set_terminal_width, parameter[]] call[name[time].sleep, parameter[binary_operation[constant[0.3] * name[self].global_delay_factor]]] call[name[self].clear_buffer, parameter[]]
keyword[def] identifier[session_preparation] ( identifier[self] ): literal[string] identifier[self] . identifier[ansi_escape_codes] = keyword[True] identifier[self] . identifier[_test_channel_read] () identifier[self] . identifier[set_base_prompt] () identifier[self] . identifier[disable_paging] () identifier[self] . identifier[set_terminal_width] ( identifier[command] = literal[string] ) identifier[time] . identifier[sleep] ( literal[int] * identifier[self] . identifier[global_delay_factor] ) identifier[self] . identifier[clear_buffer] ()
def session_preparation(self): """Prepare the session after the connection has been established.""" self.ansi_escape_codes = True self._test_channel_read() self.set_base_prompt() self.disable_paging() self.set_terminal_width(command='terminal width 511') # Clear the read buffer time.sleep(0.3 * self.global_delay_factor) self.clear_buffer()
def profiler_handler(uri): """Profiler handler.""" # HTTP method should be GET. if uri == 'main': runner.run(show_guestbook, 'cmhp') # In this case HTTP method should be POST singe add_entry uses POST elif uri == 'add': runner.run(add_entry, 'cmhp') return flask.redirect('/')
def function[profiler_handler, parameter[uri]]: constant[Profiler handler.] if compare[name[uri] equal[==] constant[main]] begin[:] call[name[runner].run, parameter[name[show_guestbook], constant[cmhp]]] return[call[name[flask].redirect, parameter[constant[/]]]]
keyword[def] identifier[profiler_handler] ( identifier[uri] ): literal[string] keyword[if] identifier[uri] == literal[string] : identifier[runner] . identifier[run] ( identifier[show_guestbook] , literal[string] ) keyword[elif] identifier[uri] == literal[string] : identifier[runner] . identifier[run] ( identifier[add_entry] , literal[string] ) keyword[return] identifier[flask] . identifier[redirect] ( literal[string] )
def profiler_handler(uri): """Profiler handler.""" # HTTP method should be GET. if uri == 'main': runner.run(show_guestbook, 'cmhp') # depends on [control=['if'], data=[]] # In this case HTTP method should be POST singe add_entry uses POST elif uri == 'add': runner.run(add_entry, 'cmhp') # depends on [control=['if'], data=[]] return flask.redirect('/')
def element_id_by_label(browser, label): """ The ID of an element referenced by a `label`s ``for`` attribute. The label must be visible. :param browser: ``world.browser`` :param label: label text to return the referenced element for Returns: ``for`` attribute value """ label = ElementSelector(browser, str('//label[contains(., %s)]' % string_literal(label))) if not label: return False return label.get_attribute('for')
def function[element_id_by_label, parameter[browser, label]]: constant[ The ID of an element referenced by a `label`s ``for`` attribute. The label must be visible. :param browser: ``world.browser`` :param label: label text to return the referenced element for Returns: ``for`` attribute value ] variable[label] assign[=] call[name[ElementSelector], parameter[name[browser], call[name[str], parameter[binary_operation[constant[//label[contains(., %s)]] <ast.Mod object at 0x7da2590d6920> call[name[string_literal], parameter[name[label]]]]]]]] if <ast.UnaryOp object at 0x7da18f09c4f0> begin[:] return[constant[False]] return[call[name[label].get_attribute, parameter[constant[for]]]]
keyword[def] identifier[element_id_by_label] ( identifier[browser] , identifier[label] ): literal[string] identifier[label] = identifier[ElementSelector] ( identifier[browser] , identifier[str] ( literal[string] % identifier[string_literal] ( identifier[label] ))) keyword[if] keyword[not] identifier[label] : keyword[return] keyword[False] keyword[return] identifier[label] . identifier[get_attribute] ( literal[string] )
def element_id_by_label(browser, label): """ The ID of an element referenced by a `label`s ``for`` attribute. The label must be visible. :param browser: ``world.browser`` :param label: label text to return the referenced element for Returns: ``for`` attribute value """ label = ElementSelector(browser, str('//label[contains(., %s)]' % string_literal(label))) if not label: return False # depends on [control=['if'], data=[]] return label.get_attribute('for')
def get_domain_resolver(self, domain_name, cur=None): """ Get the last-knwon resolver entry for a domain name Returns None if not found. """ get_cmd = "SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;".format(self.subdomain_table) cursor = None if cur is None: cursor = self.conn.cursor() else: cursor = cur db_query_execute(cursor, get_cmd, (domain_name,)) rowdata = cursor.fetchone() if not rowdata: return None return rowdata['resolver']
def function[get_domain_resolver, parameter[self, domain_name, cur]]: constant[ Get the last-knwon resolver entry for a domain name Returns None if not found. ] variable[get_cmd] assign[=] call[constant[SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;].format, parameter[name[self].subdomain_table]] variable[cursor] assign[=] constant[None] if compare[name[cur] is constant[None]] begin[:] variable[cursor] assign[=] call[name[self].conn.cursor, parameter[]] call[name[db_query_execute], parameter[name[cursor], name[get_cmd], tuple[[<ast.Name object at 0x7da1b180f490>]]]] variable[rowdata] assign[=] call[name[cursor].fetchone, parameter[]] if <ast.UnaryOp object at 0x7da1b180e080> begin[:] return[constant[None]] return[call[name[rowdata]][constant[resolver]]]
keyword[def] identifier[get_domain_resolver] ( identifier[self] , identifier[domain_name] , identifier[cur] = keyword[None] ): literal[string] identifier[get_cmd] = literal[string] . identifier[format] ( identifier[self] . identifier[subdomain_table] ) identifier[cursor] = keyword[None] keyword[if] identifier[cur] keyword[is] keyword[None] : identifier[cursor] = identifier[self] . identifier[conn] . identifier[cursor] () keyword[else] : identifier[cursor] = identifier[cur] identifier[db_query_execute] ( identifier[cursor] , identifier[get_cmd] ,( identifier[domain_name] ,)) identifier[rowdata] = identifier[cursor] . identifier[fetchone] () keyword[if] keyword[not] identifier[rowdata] : keyword[return] keyword[None] keyword[return] identifier[rowdata] [ literal[string] ]
def get_domain_resolver(self, domain_name, cur=None): """ Get the last-knwon resolver entry for a domain name Returns None if not found. """ get_cmd = "SELECT resolver FROM {} WHERE domain=? AND resolver != '' AND accepted=1 ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;".format(self.subdomain_table) cursor = None if cur is None: cursor = self.conn.cursor() # depends on [control=['if'], data=[]] else: cursor = cur db_query_execute(cursor, get_cmd, (domain_name,)) rowdata = cursor.fetchone() if not rowdata: return None # depends on [control=['if'], data=[]] return rowdata['resolver']
def execute(self, name): """Orchestrate the work of the generator plugin. It is split into multiple phases: * initializing * prompting * configuring * writing :param gen: the generator you want to run :return: """ generator = self._get_generator(name) generator.initializing() answers = generator.prompting(create_store_prompt(name)) # TODO # app.insight.track('yoyo', 'help', answers) generator.configuring(answers) generator.writing(answers)
def function[execute, parameter[self, name]]: constant[Orchestrate the work of the generator plugin. It is split into multiple phases: * initializing * prompting * configuring * writing :param gen: the generator you want to run :return: ] variable[generator] assign[=] call[name[self]._get_generator, parameter[name[name]]] call[name[generator].initializing, parameter[]] variable[answers] assign[=] call[name[generator].prompting, parameter[call[name[create_store_prompt], parameter[name[name]]]]] call[name[generator].configuring, parameter[name[answers]]] call[name[generator].writing, parameter[name[answers]]]
keyword[def] identifier[execute] ( identifier[self] , identifier[name] ): literal[string] identifier[generator] = identifier[self] . identifier[_get_generator] ( identifier[name] ) identifier[generator] . identifier[initializing] () identifier[answers] = identifier[generator] . identifier[prompting] ( identifier[create_store_prompt] ( identifier[name] )) identifier[generator] . identifier[configuring] ( identifier[answers] ) identifier[generator] . identifier[writing] ( identifier[answers] )
def execute(self, name): """Orchestrate the work of the generator plugin. It is split into multiple phases: * initializing * prompting * configuring * writing :param gen: the generator you want to run :return: """ generator = self._get_generator(name) generator.initializing() answers = generator.prompting(create_store_prompt(name)) # TODO # app.insight.track('yoyo', 'help', answers) generator.configuring(answers) generator.writing(answers)
def profile_file(self): """Return the full path to write the cProfile data :return: str """ if 'profile' in self._kwargs and self._kwargs['profile']: profile_path = path.normpath(self._kwargs['profile']) if os.path.exists(profile_path) and os.path.isdir(profile_path): return path.join( profile_path, '{}-{}.prof'.format( os.getpid(), self._kwargs['consumer_name']))
def function[profile_file, parameter[self]]: constant[Return the full path to write the cProfile data :return: str ] if <ast.BoolOp object at 0x7da20e954fd0> begin[:] variable[profile_path] assign[=] call[name[path].normpath, parameter[call[name[self]._kwargs][constant[profile]]]] if <ast.BoolOp object at 0x7da18dc05ed0> begin[:] return[call[name[path].join, parameter[name[profile_path], call[constant[{}-{}.prof].format, parameter[call[name[os].getpid, parameter[]], call[name[self]._kwargs][constant[consumer_name]]]]]]]
keyword[def] identifier[profile_file] ( identifier[self] ): literal[string] keyword[if] literal[string] keyword[in] identifier[self] . identifier[_kwargs] keyword[and] identifier[self] . identifier[_kwargs] [ literal[string] ]: identifier[profile_path] = identifier[path] . identifier[normpath] ( identifier[self] . identifier[_kwargs] [ literal[string] ]) keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[profile_path] ) keyword[and] identifier[os] . identifier[path] . identifier[isdir] ( identifier[profile_path] ): keyword[return] identifier[path] . identifier[join] ( identifier[profile_path] , literal[string] . identifier[format] ( identifier[os] . identifier[getpid] (), identifier[self] . identifier[_kwargs] [ literal[string] ]))
def profile_file(self): """Return the full path to write the cProfile data :return: str """ if 'profile' in self._kwargs and self._kwargs['profile']: profile_path = path.normpath(self._kwargs['profile']) if os.path.exists(profile_path) and os.path.isdir(profile_path): return path.join(profile_path, '{}-{}.prof'.format(os.getpid(), self._kwargs['consumer_name'])) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
def allsplit(self, x, mesh_axis, split_axis, which=None): """Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTensor. mesh_axis: int, the mesh axis along which to split. split_axis: int, the Tensor axis along which to split. which: an optional LaidOutTensor of integer scalars. Selects the slice to to keep, instead of the coordinate. Returns: LaidOutTensor. """ if which is None: which = self.laid_out_pcoord(mesh_axis) num_splits = self.shape[mesh_axis].size def my_fn(x, which): slice_begin = [ dimsize // num_splits * which if i == split_axis else 0 for i, dimsize in enumerate(x.shape.as_list())] slice_size = [ dimsize // num_splits if i == split_axis else dimsize for i, dimsize in enumerate(x.shape.as_list())] return tf.slice(x, slice_begin, slice_size) return self.slicewise(my_fn, x, which)
def function[allsplit, parameter[self, x, mesh_axis, split_axis, which]]: constant[Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTensor. mesh_axis: int, the mesh axis along which to split. split_axis: int, the Tensor axis along which to split. which: an optional LaidOutTensor of integer scalars. Selects the slice to to keep, instead of the coordinate. Returns: LaidOutTensor. ] if compare[name[which] is constant[None]] begin[:] variable[which] assign[=] call[name[self].laid_out_pcoord, parameter[name[mesh_axis]]] variable[num_splits] assign[=] call[name[self].shape][name[mesh_axis]].size def function[my_fn, parameter[x, which]]: variable[slice_begin] assign[=] <ast.ListComp object at 0x7da2044c0b80> variable[slice_size] assign[=] <ast.ListComp object at 0x7da2044c11b0> return[call[name[tf].slice, parameter[name[x], name[slice_begin], name[slice_size]]]] return[call[name[self].slicewise, parameter[name[my_fn], name[x], name[which]]]]
keyword[def] identifier[allsplit] ( identifier[self] , identifier[x] , identifier[mesh_axis] , identifier[split_axis] , identifier[which] = keyword[None] ): literal[string] keyword[if] identifier[which] keyword[is] keyword[None] : identifier[which] = identifier[self] . identifier[laid_out_pcoord] ( identifier[mesh_axis] ) identifier[num_splits] = identifier[self] . identifier[shape] [ identifier[mesh_axis] ]. identifier[size] keyword[def] identifier[my_fn] ( identifier[x] , identifier[which] ): identifier[slice_begin] =[ identifier[dimsize] // identifier[num_splits] * identifier[which] keyword[if] identifier[i] == identifier[split_axis] keyword[else] literal[int] keyword[for] identifier[i] , identifier[dimsize] keyword[in] identifier[enumerate] ( identifier[x] . identifier[shape] . identifier[as_list] ())] identifier[slice_size] =[ identifier[dimsize] // identifier[num_splits] keyword[if] identifier[i] == identifier[split_axis] keyword[else] identifier[dimsize] keyword[for] identifier[i] , identifier[dimsize] keyword[in] identifier[enumerate] ( identifier[x] . identifier[shape] . identifier[as_list] ())] keyword[return] identifier[tf] . identifier[slice] ( identifier[x] , identifier[slice_begin] , identifier[slice_size] ) keyword[return] identifier[self] . identifier[slicewise] ( identifier[my_fn] , identifier[x] , identifier[which] )
def allsplit(self, x, mesh_axis, split_axis, which=None): """Inverse of allconcat - split each slice and keep only one piece of it. The number of ways to split is the number of processors in the group. The part that is kept corresponds to the processor's index in the group. Args: x: LaidOutTensor. mesh_axis: int, the mesh axis along which to split. split_axis: int, the Tensor axis along which to split. which: an optional LaidOutTensor of integer scalars. Selects the slice to to keep, instead of the coordinate. Returns: LaidOutTensor. """ if which is None: which = self.laid_out_pcoord(mesh_axis) # depends on [control=['if'], data=['which']] num_splits = self.shape[mesh_axis].size def my_fn(x, which): slice_begin = [dimsize // num_splits * which if i == split_axis else 0 for (i, dimsize) in enumerate(x.shape.as_list())] slice_size = [dimsize // num_splits if i == split_axis else dimsize for (i, dimsize) in enumerate(x.shape.as_list())] return tf.slice(x, slice_begin, slice_size) return self.slicewise(my_fn, x, which)
def statistic_recommend(classes, P): """ Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list """ if imbalance_check(P): return IMBALANCED_RECOMMEND if binary_check(classes): return BINARY_RECOMMEND return MULTICLASS_RECOMMEND
def function[statistic_recommend, parameter[classes, P]]: constant[ Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list ] if call[name[imbalance_check], parameter[name[P]]] begin[:] return[name[IMBALANCED_RECOMMEND]] if call[name[binary_check], parameter[name[classes]]] begin[:] return[name[BINARY_RECOMMEND]] return[name[MULTICLASS_RECOMMEND]]
keyword[def] identifier[statistic_recommend] ( identifier[classes] , identifier[P] ): literal[string] keyword[if] identifier[imbalance_check] ( identifier[P] ): keyword[return] identifier[IMBALANCED_RECOMMEND] keyword[if] identifier[binary_check] ( identifier[classes] ): keyword[return] identifier[BINARY_RECOMMEND] keyword[return] identifier[MULTICLASS_RECOMMEND]
def statistic_recommend(classes, P): """ Return recommend parameters which are more suitable due to the input dataset characteristics. :param classes: all classes name :type classes : list :param P: condition positive :type P : dict :return: recommendation_list as list """ if imbalance_check(P): return IMBALANCED_RECOMMEND # depends on [control=['if'], data=[]] if binary_check(classes): return BINARY_RECOMMEND # depends on [control=['if'], data=[]] return MULTICLASS_RECOMMEND
def for_type_by_name(self, type_module, type_name, func): """Add a format function for a type specified by the full dotted module and name of the type, rather than the type of the object. Parameters ---------- type_module : str The full dotted name of the module the type is defined in, like ``numpy``. type_name : str The name of the type (the class name), like ``dtype`` func : callable The callable that will be called to compute the format data. The call signature of this function is simple, it must take the object to be formatted and return the raw data for the given format. Subclasses may use a different call signature for the `func` argument. """ key = (type_module, type_name) oldfunc = self.deferred_printers.get(key, None) if func is not None: # To support easy restoration of old printers, we need to ignore # Nones. self.deferred_printers[key] = func return oldfunc
def function[for_type_by_name, parameter[self, type_module, type_name, func]]: constant[Add a format function for a type specified by the full dotted module and name of the type, rather than the type of the object. Parameters ---------- type_module : str The full dotted name of the module the type is defined in, like ``numpy``. type_name : str The name of the type (the class name), like ``dtype`` func : callable The callable that will be called to compute the format data. The call signature of this function is simple, it must take the object to be formatted and return the raw data for the given format. Subclasses may use a different call signature for the `func` argument. ] variable[key] assign[=] tuple[[<ast.Name object at 0x7da20eb2ae60>, <ast.Name object at 0x7da20eb29de0>]] variable[oldfunc] assign[=] call[name[self].deferred_printers.get, parameter[name[key], constant[None]]] if compare[name[func] is_not constant[None]] begin[:] call[name[self].deferred_printers][name[key]] assign[=] name[func] return[name[oldfunc]]
keyword[def] identifier[for_type_by_name] ( identifier[self] , identifier[type_module] , identifier[type_name] , identifier[func] ): literal[string] identifier[key] =( identifier[type_module] , identifier[type_name] ) identifier[oldfunc] = identifier[self] . identifier[deferred_printers] . identifier[get] ( identifier[key] , keyword[None] ) keyword[if] identifier[func] keyword[is] keyword[not] keyword[None] : identifier[self] . identifier[deferred_printers] [ identifier[key] ]= identifier[func] keyword[return] identifier[oldfunc]
def for_type_by_name(self, type_module, type_name, func): """Add a format function for a type specified by the full dotted module and name of the type, rather than the type of the object. Parameters ---------- type_module : str The full dotted name of the module the type is defined in, like ``numpy``. type_name : str The name of the type (the class name), like ``dtype`` func : callable The callable that will be called to compute the format data. The call signature of this function is simple, it must take the object to be formatted and return the raw data for the given format. Subclasses may use a different call signature for the `func` argument. """ key = (type_module, type_name) oldfunc = self.deferred_printers.get(key, None) if func is not None: # To support easy restoration of old printers, we need to ignore # Nones. self.deferred_printers[key] = func # depends on [control=['if'], data=['func']] return oldfunc
def complete_experiment(self, status): """Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints. """ self.log("Bot player completing experiment. Status: {}".format(status)) while True: url = "{host}/{status}?participant_id={participant_id}".format( host=self.host, participant_id=self.participant_id, status=status ) try: result = requests.get(url) result.raise_for_status() except RequestException: self.stochastic_sleep() continue return result
def function[complete_experiment, parameter[self, status]]: constant[Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints. ] call[name[self].log, parameter[call[constant[Bot player completing experiment. Status: {}].format, parameter[name[status]]]]] while constant[True] begin[:] variable[url] assign[=] call[constant[{host}/{status}?participant_id={participant_id}].format, parameter[]] <ast.Try object at 0x7da1b0308100> return[name[result]]
keyword[def] identifier[complete_experiment] ( identifier[self] , identifier[status] ): literal[string] identifier[self] . identifier[log] ( literal[string] . identifier[format] ( identifier[status] )) keyword[while] keyword[True] : identifier[url] = literal[string] . identifier[format] ( identifier[host] = identifier[self] . identifier[host] , identifier[participant_id] = identifier[self] . identifier[participant_id] , identifier[status] = identifier[status] ) keyword[try] : identifier[result] = identifier[requests] . identifier[get] ( identifier[url] ) identifier[result] . identifier[raise_for_status] () keyword[except] identifier[RequestException] : identifier[self] . identifier[stochastic_sleep] () keyword[continue] keyword[return] identifier[result]
def complete_experiment(self, status): """Record worker completion status to the experiment server. This is done using a GET request to the /worker_complete or /worker_failed endpoints. """ self.log('Bot player completing experiment. Status: {}'.format(status)) while True: url = '{host}/{status}?participant_id={participant_id}'.format(host=self.host, participant_id=self.participant_id, status=status) try: result = requests.get(url) result.raise_for_status() # depends on [control=['try'], data=[]] except RequestException: self.stochastic_sleep() continue # depends on [control=['except'], data=[]] return result # depends on [control=['while'], data=[]]
def show_page_groups(self, url, group_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} params = {} # REQUIRED - PATH - group_id """ID""" path["group_id"] = group_id # REQUIRED - PATH - url """ID""" path["url"] = url self.logger.debug("GET /api/v1/groups/{group_id}/pages/{url} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/groups/{group_id}/pages/{url}".format(**path), data=data, params=params, single_item=True)
def function[show_page_groups, parameter[self, url, group_id]]: constant[ Show page. Retrieve the content of a wiki page ] variable[path] assign[=] dictionary[[], []] variable[data] assign[=] dictionary[[], []] variable[params] assign[=] dictionary[[], []] constant[ID] call[name[path]][constant[group_id]] assign[=] name[group_id] constant[ID] call[name[path]][constant[url]] assign[=] name[url] call[name[self].logger.debug, parameter[call[constant[GET /api/v1/groups/{group_id}/pages/{url} with query params: {params} and form data: {data}].format, parameter[]]]] return[call[name[self].generic_request, parameter[constant[GET], call[constant[/api/v1/groups/{group_id}/pages/{url}].format, parameter[]]]]]
keyword[def] identifier[show_page_groups] ( identifier[self] , identifier[url] , identifier[group_id] ): literal[string] identifier[path] ={} identifier[data] ={} identifier[params] ={} literal[string] identifier[path] [ literal[string] ]= identifier[group_id] literal[string] identifier[path] [ literal[string] ]= identifier[url] identifier[self] . identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[params] = identifier[params] , identifier[data] = identifier[data] ,** identifier[path] )) keyword[return] identifier[self] . identifier[generic_request] ( literal[string] , literal[string] . identifier[format] (** identifier[path] ), identifier[data] = identifier[data] , identifier[params] = identifier[params] , identifier[single_item] = keyword[True] )
def show_page_groups(self, url, group_id): """ Show page. Retrieve the content of a wiki page """ path = {} data = {} params = {} # REQUIRED - PATH - group_id 'ID' path['group_id'] = group_id # REQUIRED - PATH - url 'ID' path['url'] = url self.logger.debug('GET /api/v1/groups/{group_id}/pages/{url} with query params: {params} and form data: {data}'.format(params=params, data=data, **path)) return self.generic_request('GET', '/api/v1/groups/{group_id}/pages/{url}'.format(**path), data=data, params=params, single_item=True)
def get_config(self): """ Return a formatted text with main configuration parameters. """ # Create a dummy report object if necessary channels = [sect.rsplit('_')[0] for sect in self.config.sections(suffix='_channel')] channels.sort() disabled_apps = [app for app in self._config_apps.keys() if app not in self._apps] return u''.join([ u"\n--- %s configuration ---" % __package__, u"\nConfiguration file: %s" % self.config.cfgfile, u"\nConfiguration directory: %s" % self.confdir, u"\nConfigured applications: %s" % ', '.join(self._config_apps.keys()), u"\nDisabled applications: %s" % ', '.join(disabled_apps) if disabled_apps else '', u"\nFilter fields: %s" % ', '.join(self.config.options('fields')), u"\nOutput channels: %s" % ', '.join(channels) if channels else u'No channels defined', u"\nReports: %s\n" % ', '.join( [section[:-7] for section in self.config.sections(suffix='_report')] ), '' ])
def function[get_config, parameter[self]]: constant[ Return a formatted text with main configuration parameters. ] variable[channels] assign[=] <ast.ListComp object at 0x7da2044c2b90> call[name[channels].sort, parameter[]] variable[disabled_apps] assign[=] <ast.ListComp object at 0x7da2044c3400> return[call[constant[].join, parameter[list[[<ast.BinOp object at 0x7da2044c0be0>, <ast.BinOp object at 0x7da2044c2a40>, <ast.BinOp object at 0x7da2044c04f0>, <ast.BinOp object at 0x7da2044c3fa0>, <ast.IfExp object at 0x7da2044c29b0>, <ast.BinOp object at 0x7da2044c2500>, <ast.IfExp object at 0x7da2044c0d90>, <ast.BinOp object at 0x7da2044c2d70>, <ast.Constant object at 0x7da20c6aa920>]]]]]
keyword[def] identifier[get_config] ( identifier[self] ): literal[string] identifier[channels] =[ identifier[sect] . identifier[rsplit] ( literal[string] )[ literal[int] ] keyword[for] identifier[sect] keyword[in] identifier[self] . identifier[config] . identifier[sections] ( identifier[suffix] = literal[string] )] identifier[channels] . identifier[sort] () identifier[disabled_apps] =[ identifier[app] keyword[for] identifier[app] keyword[in] identifier[self] . identifier[_config_apps] . identifier[keys] () keyword[if] identifier[app] keyword[not] keyword[in] identifier[self] . identifier[_apps] ] keyword[return] literal[string] . identifier[join] ([ literal[string] % identifier[__package__] , literal[string] % identifier[self] . identifier[config] . identifier[cfgfile] , literal[string] % identifier[self] . identifier[confdir] , literal[string] % literal[string] . identifier[join] ( identifier[self] . identifier[_config_apps] . identifier[keys] ()), literal[string] % literal[string] . identifier[join] ( identifier[disabled_apps] ) keyword[if] identifier[disabled_apps] keyword[else] literal[string] , literal[string] % literal[string] . identifier[join] ( identifier[self] . identifier[config] . identifier[options] ( literal[string] )), literal[string] % literal[string] . identifier[join] ( identifier[channels] ) keyword[if] identifier[channels] keyword[else] literal[string] , literal[string] % literal[string] . identifier[join] ( [ identifier[section] [:- literal[int] ] keyword[for] identifier[section] keyword[in] identifier[self] . identifier[config] . identifier[sections] ( identifier[suffix] = literal[string] )] ), literal[string] ])
def get_config(self): """ Return a formatted text with main configuration parameters. """ # Create a dummy report object if necessary channels = [sect.rsplit('_')[0] for sect in self.config.sections(suffix='_channel')] channels.sort() disabled_apps = [app for app in self._config_apps.keys() if app not in self._apps] return u''.join([u'\n--- %s configuration ---' % __package__, u'\nConfiguration file: %s' % self.config.cfgfile, u'\nConfiguration directory: %s' % self.confdir, u'\nConfigured applications: %s' % ', '.join(self._config_apps.keys()), u'\nDisabled applications: %s' % ', '.join(disabled_apps) if disabled_apps else '', u'\nFilter fields: %s' % ', '.join(self.config.options('fields')), u'\nOutput channels: %s' % ', '.join(channels) if channels else u'No channels defined', u'\nReports: %s\n' % ', '.join([section[:-7] for section in self.config.sections(suffix='_report')]), ''])
def set_maxrad(self,maxrad, distribution_skip=True): """ Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should always have units. :param maxrad: The maximum angular value of Rsky. :type maxrad: :class:`astropy.units.Quantity` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* """ self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky,maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip)
def function[set_maxrad, parameter[self, maxrad, distribution_skip]]: constant[ Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should always have units. :param maxrad: The maximum angular value of Rsky. :type maxrad: :class:`astropy.units.Quantity` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* ] name[self].maxrad assign[=] name[maxrad] call[name[self].apply_constraint, parameter[call[name[UpperLimit], parameter[name[self].Rsky, name[maxrad]]]]]
keyword[def] identifier[set_maxrad] ( identifier[self] , identifier[maxrad] , identifier[distribution_skip] = keyword[True] ): literal[string] identifier[self] . identifier[maxrad] = identifier[maxrad] identifier[self] . identifier[apply_constraint] ( identifier[UpperLimit] ( identifier[self] . identifier[Rsky] , identifier[maxrad] , identifier[name] = literal[string] ), identifier[overwrite] = keyword[True] , identifier[distribution_skip] = identifier[distribution_skip] )
def set_maxrad(self, maxrad, distribution_skip=True): """ Adds a constraint that rejects everything with Rsky > maxrad Requires ``Rsky`` attribute, which should always have units. :param maxrad: The maximum angular value of Rsky. :type maxrad: :class:`astropy.units.Quantity` :param distribution_skip: This is by default ``True``. *To be honest, I'm not exactly sure why. Might be important, might not (don't remember).* """ self.maxrad = maxrad self.apply_constraint(UpperLimit(self.Rsky, maxrad, name='Max Rsky'), overwrite=True, distribution_skip=distribution_skip)
def create(cls, name, user_group=None, activation_date=None, expiration_date=None, comment=None): """ Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser """ json = { 'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} limits = {'activation_date': activation_date, 'expiration_date': expiration_date} for attr, value in limits.items(): json[attr] = datetime_to_ms(value) if value else None if user_group: json.update(user_group=element_resolver(user_group)) return ElementCreator(cls, json)
def function[create, parameter[cls, name, user_group, activation_date, expiration_date, comment]]: constant[ Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser ] variable[json] assign[=] dictionary[[<ast.Constant object at 0x7da1b1a28e80>, <ast.Constant object at 0x7da1b1a2a860>, <ast.Constant object at 0x7da1b1a2a5f0>], [<ast.Name object at 0x7da1b1a2b700>, <ast.Call object at 0x7da1b1a28cd0>, <ast.Name object at 0x7da1b1a28610>]] variable[limits] assign[=] dictionary[[<ast.Constant object at 0x7da1b1a2a0e0>, <ast.Constant object at 0x7da1b1a28520>], [<ast.Name object at 0x7da1b1a2b880>, <ast.Name object at 0x7da1b1a28b50>]] for taget[tuple[[<ast.Name object at 0x7da1b1a291e0>, <ast.Name object at 0x7da1b1a2bc70>]]] in starred[call[name[limits].items, parameter[]]] begin[:] call[name[json]][name[attr]] assign[=] <ast.IfExp object at 0x7da1b1a2b760> if name[user_group] begin[:] call[name[json].update, parameter[]] return[call[name[ElementCreator], parameter[name[cls], name[json]]]]
keyword[def] identifier[create] ( identifier[cls] , identifier[name] , identifier[user_group] = keyword[None] , identifier[activation_date] = keyword[None] , identifier[expiration_date] = keyword[None] , identifier[comment] = keyword[None] ): literal[string] identifier[json] ={ literal[string] : identifier[name] , literal[string] : literal[string] . identifier[format] ( identifier[name] , identifier[InternalUserDomain] . identifier[user_dn] ), literal[string] : identifier[comment] } identifier[limits] ={ literal[string] : identifier[activation_date] , literal[string] : identifier[expiration_date] } keyword[for] identifier[attr] , identifier[value] keyword[in] identifier[limits] . identifier[items] (): identifier[json] [ identifier[attr] ]= identifier[datetime_to_ms] ( identifier[value] ) keyword[if] identifier[value] keyword[else] keyword[None] keyword[if] identifier[user_group] : identifier[json] . identifier[update] ( identifier[user_group] = identifier[element_resolver] ( identifier[user_group] )) keyword[return] identifier[ElementCreator] ( identifier[cls] , identifier[json] )
def create(cls, name, user_group=None, activation_date=None, expiration_date=None, comment=None): """ Create an internal user. Add a user example:: InternalUser.create(name='goog', comment='my comment') :param str name: name of user that is displayed in SMC :param list(str,InternalUserGroup) user_group: internal user groups which to add this user to. :param datetime activation_date: activation date as datetime object. Activation date only supports year and month/day :param datetime expiration_date: expiration date as datetime object. Expiration date only supports year and month/day :param str comment: optional comment :raises ElementNotFound: thrown if group specified does not exist :rtype: InternalUser """ json = {'name': name, 'unique_id': 'cn={},{}'.format(name, InternalUserDomain.user_dn), 'comment': comment} limits = {'activation_date': activation_date, 'expiration_date': expiration_date} for (attr, value) in limits.items(): json[attr] = datetime_to_ms(value) if value else None # depends on [control=['for'], data=[]] if user_group: json.update(user_group=element_resolver(user_group)) # depends on [control=['if'], data=[]] return ElementCreator(cls, json)
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=None, compressed=True, custom_pushdata=False): """ sanitize_tx_data() fee is in satoshis per byte. """ outputs = outputs.copy() for i, output in enumerate(outputs): dest, amount, currency = output # LEGACYADDRESSDEPRECATION # FIXME: Will be removed in an upcoming release, breaking compatibility with legacy addresses. dest = cashaddress.to_cash_address(dest) outputs[i] = (dest, currency_to_satoshi_cached(amount, currency)) if not unspents: raise ValueError('Transactions must have at least one unspent.') # Temporary storage so all outputs precede messages. messages = [] total_op_return_size = 0 if message and (custom_pushdata is False): try: message = message.encode('utf-8') except AttributeError: pass # assume message is already a bytes-like object message_chunks = chunk_data(message, MESSAGE_LIMIT) for message in message_chunks: messages.append((message, 0)) total_op_return_size += get_op_return_size(message, custom_pushdata=False) elif message and (custom_pushdata is True): if (len(message) >= 220): # FIXME add capability for >220 bytes for custom pushdata elements raise ValueError("Currently cannot exceed 220 bytes with custom_pushdata.") else: messages.append((message, 0)) total_op_return_size += get_op_return_size(message, custom_pushdata=True) # Include return address in fee estimate. total_in = 0 num_outputs = len(outputs) + 1 sum_outputs = sum(out[1] for out in outputs) if combine: # calculated_fee is in total satoshis. calculated_fee = estimate_tx_fee(len(unspents), num_outputs, fee, compressed, total_op_return_size) total_out = sum_outputs + calculated_fee unspents = unspents.copy() total_in += sum(unspent.amount for unspent in unspents) else: unspents = sorted(unspents, key=lambda x: x.amount) index = 0 for index, unspent in enumerate(unspents): total_in += unspent.amount calculated_fee = estimate_tx_fee(len(unspents[:index + 1]), num_outputs, fee, compressed, total_op_return_size) total_out = sum_outputs + calculated_fee if total_in >= total_out: break unspents[:] = unspents[:index + 1] remaining = total_in - total_out if remaining > 0: outputs.append((leftover, remaining)) elif remaining < 0: raise InsufficientFunds('Balance {} is less than {} (including ' 'fee).'.format(total_in, total_out)) outputs.extend(messages) return unspents, outputs
def function[sanitize_tx_data, parameter[unspents, outputs, fee, leftover, combine, message, compressed, custom_pushdata]]: constant[ sanitize_tx_data() fee is in satoshis per byte. ] variable[outputs] assign[=] call[name[outputs].copy, parameter[]] for taget[tuple[[<ast.Name object at 0x7da207f00ca0>, <ast.Name object at 0x7da207f010f0>]]] in starred[call[name[enumerate], parameter[name[outputs]]]] begin[:] <ast.Tuple object at 0x7da207f01360> assign[=] name[output] variable[dest] assign[=] call[name[cashaddress].to_cash_address, parameter[name[dest]]] call[name[outputs]][name[i]] assign[=] tuple[[<ast.Name object at 0x7da207f02ec0>, <ast.Call object at 0x7da207f007c0>]] if <ast.UnaryOp object at 0x7da207f03580> begin[:] <ast.Raise object at 0x7da207f00ee0> variable[messages] assign[=] list[[]] variable[total_op_return_size] assign[=] constant[0] if <ast.BoolOp object at 0x7da207f035b0> begin[:] <ast.Try object at 0x7da207f03b50> variable[message_chunks] assign[=] call[name[chunk_data], parameter[name[message], name[MESSAGE_LIMIT]]] for taget[name[message]] in starred[name[message_chunks]] begin[:] call[name[messages].append, parameter[tuple[[<ast.Name object at 0x7da207f028c0>, <ast.Constant object at 0x7da207f02110>]]]] <ast.AugAssign object at 0x7da207f01cf0> variable[total_in] assign[=] constant[0] variable[num_outputs] assign[=] binary_operation[call[name[len], parameter[name[outputs]]] + constant[1]] variable[sum_outputs] assign[=] call[name[sum], parameter[<ast.GeneratorExp object at 0x7da207f01d50>]] if name[combine] begin[:] variable[calculated_fee] assign[=] call[name[estimate_tx_fee], parameter[call[name[len], parameter[name[unspents]]], name[num_outputs], name[fee], name[compressed], name[total_op_return_size]]] variable[total_out] assign[=] binary_operation[name[sum_outputs] + name[calculated_fee]] variable[unspents] assign[=] call[name[unspents].copy, parameter[]] <ast.AugAssign object at 0x7da207f033a0> variable[remaining] assign[=] binary_operation[name[total_in] - name[total_out]] if compare[name[remaining] greater[>] constant[0]] begin[:] call[name[outputs].append, parameter[tuple[[<ast.Name object at 0x7da207f9ba60>, <ast.Name object at 0x7da207f9a7a0>]]]] call[name[outputs].extend, parameter[name[messages]]] return[tuple[[<ast.Name object at 0x7da207f9a9b0>, <ast.Name object at 0x7da207f9a680>]]]
keyword[def] identifier[sanitize_tx_data] ( identifier[unspents] , identifier[outputs] , identifier[fee] , identifier[leftover] , identifier[combine] = keyword[True] , identifier[message] = keyword[None] , identifier[compressed] = keyword[True] , identifier[custom_pushdata] = keyword[False] ): literal[string] identifier[outputs] = identifier[outputs] . identifier[copy] () keyword[for] identifier[i] , identifier[output] keyword[in] identifier[enumerate] ( identifier[outputs] ): identifier[dest] , identifier[amount] , identifier[currency] = identifier[output] identifier[dest] = identifier[cashaddress] . identifier[to_cash_address] ( identifier[dest] ) identifier[outputs] [ identifier[i] ]=( identifier[dest] , identifier[currency_to_satoshi_cached] ( identifier[amount] , identifier[currency] )) keyword[if] keyword[not] identifier[unspents] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[messages] =[] identifier[total_op_return_size] = literal[int] keyword[if] identifier[message] keyword[and] ( identifier[custom_pushdata] keyword[is] keyword[False] ): keyword[try] : identifier[message] = identifier[message] . identifier[encode] ( literal[string] ) keyword[except] identifier[AttributeError] : keyword[pass] identifier[message_chunks] = identifier[chunk_data] ( identifier[message] , identifier[MESSAGE_LIMIT] ) keyword[for] identifier[message] keyword[in] identifier[message_chunks] : identifier[messages] . identifier[append] (( identifier[message] , literal[int] )) identifier[total_op_return_size] += identifier[get_op_return_size] ( identifier[message] , identifier[custom_pushdata] = keyword[False] ) keyword[elif] identifier[message] keyword[and] ( identifier[custom_pushdata] keyword[is] keyword[True] ): keyword[if] ( identifier[len] ( identifier[message] )>= literal[int] ): keyword[raise] identifier[ValueError] ( literal[string] ) keyword[else] : identifier[messages] . identifier[append] (( identifier[message] , literal[int] )) identifier[total_op_return_size] += identifier[get_op_return_size] ( identifier[message] , identifier[custom_pushdata] = keyword[True] ) identifier[total_in] = literal[int] identifier[num_outputs] = identifier[len] ( identifier[outputs] )+ literal[int] identifier[sum_outputs] = identifier[sum] ( identifier[out] [ literal[int] ] keyword[for] identifier[out] keyword[in] identifier[outputs] ) keyword[if] identifier[combine] : identifier[calculated_fee] = identifier[estimate_tx_fee] ( identifier[len] ( identifier[unspents] ), identifier[num_outputs] , identifier[fee] , identifier[compressed] , identifier[total_op_return_size] ) identifier[total_out] = identifier[sum_outputs] + identifier[calculated_fee] identifier[unspents] = identifier[unspents] . identifier[copy] () identifier[total_in] += identifier[sum] ( identifier[unspent] . identifier[amount] keyword[for] identifier[unspent] keyword[in] identifier[unspents] ) keyword[else] : identifier[unspents] = identifier[sorted] ( identifier[unspents] , identifier[key] = keyword[lambda] identifier[x] : identifier[x] . identifier[amount] ) identifier[index] = literal[int] keyword[for] identifier[index] , identifier[unspent] keyword[in] identifier[enumerate] ( identifier[unspents] ): identifier[total_in] += identifier[unspent] . identifier[amount] identifier[calculated_fee] = identifier[estimate_tx_fee] ( identifier[len] ( identifier[unspents] [: identifier[index] + literal[int] ]), identifier[num_outputs] , identifier[fee] , identifier[compressed] , identifier[total_op_return_size] ) identifier[total_out] = identifier[sum_outputs] + identifier[calculated_fee] keyword[if] identifier[total_in] >= identifier[total_out] : keyword[break] identifier[unspents] [:]= identifier[unspents] [: identifier[index] + literal[int] ] identifier[remaining] = identifier[total_in] - identifier[total_out] keyword[if] identifier[remaining] > literal[int] : identifier[outputs] . identifier[append] (( identifier[leftover] , identifier[remaining] )) keyword[elif] identifier[remaining] < literal[int] : keyword[raise] identifier[InsufficientFunds] ( literal[string] literal[string] . identifier[format] ( identifier[total_in] , identifier[total_out] )) identifier[outputs] . identifier[extend] ( identifier[messages] ) keyword[return] identifier[unspents] , identifier[outputs]
def sanitize_tx_data(unspents, outputs, fee, leftover, combine=True, message=None, compressed=True, custom_pushdata=False): """ sanitize_tx_data() fee is in satoshis per byte. """ outputs = outputs.copy() for (i, output) in enumerate(outputs): (dest, amount, currency) = output # LEGACYADDRESSDEPRECATION # FIXME: Will be removed in an upcoming release, breaking compatibility with legacy addresses. dest = cashaddress.to_cash_address(dest) outputs[i] = (dest, currency_to_satoshi_cached(amount, currency)) # depends on [control=['for'], data=[]] if not unspents: raise ValueError('Transactions must have at least one unspent.') # depends on [control=['if'], data=[]] # Temporary storage so all outputs precede messages. messages = [] total_op_return_size = 0 if message and custom_pushdata is False: try: message = message.encode('utf-8') # depends on [control=['try'], data=[]] except AttributeError: pass # assume message is already a bytes-like object # depends on [control=['except'], data=[]] message_chunks = chunk_data(message, MESSAGE_LIMIT) for message in message_chunks: messages.append((message, 0)) total_op_return_size += get_op_return_size(message, custom_pushdata=False) # depends on [control=['for'], data=['message']] # depends on [control=['if'], data=[]] elif message and custom_pushdata is True: if len(message) >= 220: # FIXME add capability for >220 bytes for custom pushdata elements raise ValueError('Currently cannot exceed 220 bytes with custom_pushdata.') # depends on [control=['if'], data=[]] else: messages.append((message, 0)) total_op_return_size += get_op_return_size(message, custom_pushdata=True) # depends on [control=['if'], data=[]] # Include return address in fee estimate. total_in = 0 num_outputs = len(outputs) + 1 sum_outputs = sum((out[1] for out in outputs)) if combine: # calculated_fee is in total satoshis. calculated_fee = estimate_tx_fee(len(unspents), num_outputs, fee, compressed, total_op_return_size) total_out = sum_outputs + calculated_fee unspents = unspents.copy() total_in += sum((unspent.amount for unspent in unspents)) # depends on [control=['if'], data=[]] else: unspents = sorted(unspents, key=lambda x: x.amount) index = 0 for (index, unspent) in enumerate(unspents): total_in += unspent.amount calculated_fee = estimate_tx_fee(len(unspents[:index + 1]), num_outputs, fee, compressed, total_op_return_size) total_out = sum_outputs + calculated_fee if total_in >= total_out: break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] unspents[:] = unspents[:index + 1] remaining = total_in - total_out if remaining > 0: outputs.append((leftover, remaining)) # depends on [control=['if'], data=['remaining']] elif remaining < 0: raise InsufficientFunds('Balance {} is less than {} (including fee).'.format(total_in, total_out)) # depends on [control=['if'], data=[]] outputs.extend(messages) return (unspents, outputs)
def get_provider_id(self): """Gets the ``Id`` of the provider. return: (osid.id.Id) - the provider ``Id`` *compliance: mandatory -- This method must be implemented.* """ if 'providerId' not in self._my_map or not self._my_map['providerId']: raise errors.IllegalState('this sourceable object has no provider set') return Id(self._my_map['providerId'])
def function[get_provider_id, parameter[self]]: constant[Gets the ``Id`` of the provider. return: (osid.id.Id) - the provider ``Id`` *compliance: mandatory -- This method must be implemented.* ] if <ast.BoolOp object at 0x7da1b0a65fc0> begin[:] <ast.Raise object at 0x7da1b0a66a70> return[call[name[Id], parameter[call[name[self]._my_map][constant[providerId]]]]]
keyword[def] identifier[get_provider_id] ( identifier[self] ): literal[string] keyword[if] literal[string] keyword[not] keyword[in] identifier[self] . identifier[_my_map] keyword[or] keyword[not] identifier[self] . identifier[_my_map] [ literal[string] ]: keyword[raise] identifier[errors] . identifier[IllegalState] ( literal[string] ) keyword[return] identifier[Id] ( identifier[self] . identifier[_my_map] [ literal[string] ])
def get_provider_id(self): """Gets the ``Id`` of the provider. return: (osid.id.Id) - the provider ``Id`` *compliance: mandatory -- This method must be implemented.* """ if 'providerId' not in self._my_map or not self._my_map['providerId']: raise errors.IllegalState('this sourceable object has no provider set') # depends on [control=['if'], data=[]] return Id(self._my_map['providerId'])
def run(self): """ Iterate passed read group ids, or go through all available read groups """ if not self._readGroupIds: for referenceGroupId in self.getAllReadGroups(): self._run(referenceGroupId) else: for referenceGroupId in self._readGroupIds: self._run(referenceGroupId)
def function[run, parameter[self]]: constant[ Iterate passed read group ids, or go through all available read groups ] if <ast.UnaryOp object at 0x7da18c4cc760> begin[:] for taget[name[referenceGroupId]] in starred[call[name[self].getAllReadGroups, parameter[]]] begin[:] call[name[self]._run, parameter[name[referenceGroupId]]]
keyword[def] identifier[run] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[_readGroupIds] : keyword[for] identifier[referenceGroupId] keyword[in] identifier[self] . identifier[getAllReadGroups] (): identifier[self] . identifier[_run] ( identifier[referenceGroupId] ) keyword[else] : keyword[for] identifier[referenceGroupId] keyword[in] identifier[self] . identifier[_readGroupIds] : identifier[self] . identifier[_run] ( identifier[referenceGroupId] )
def run(self): """ Iterate passed read group ids, or go through all available read groups """ if not self._readGroupIds: for referenceGroupId in self.getAllReadGroups(): self._run(referenceGroupId) # depends on [control=['for'], data=['referenceGroupId']] # depends on [control=['if'], data=[]] else: for referenceGroupId in self._readGroupIds: self._run(referenceGroupId) # depends on [control=['for'], data=['referenceGroupId']]
def get_validated_type(object_type: Type[Any], name: str, enforce_not_joker: bool = True) -> Type[Any]: """ Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or accepted 'as is' :param object_type: the type to validate :param name: a name used in exceptions if any :param enforce_not_joker: a boolean, set to False to tolerate JOKER types :return: the fixed type """ if object_type is object or object_type is Any or object_type is AnyObject: return AnyObject else: # -- !! Do not check TypeVar or Union : this is already handled at higher levels -- if object_type is JOKER: # optionally check if JOKER is allowed if enforce_not_joker: raise ValueError('JOKER is not allowed for object_type') else: # note: we dont check var earlier, since 'typing.Any' is not a subclass of type anymore check_var(object_type, var_types=type, var_name=name) return object_type
def function[get_validated_type, parameter[object_type, name, enforce_not_joker]]: constant[ Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or accepted 'as is' :param object_type: the type to validate :param name: a name used in exceptions if any :param enforce_not_joker: a boolean, set to False to tolerate JOKER types :return: the fixed type ] if <ast.BoolOp object at 0x7da18ede5120> begin[:] return[name[AnyObject]]
keyword[def] identifier[get_validated_type] ( identifier[object_type] : identifier[Type] [ identifier[Any] ], identifier[name] : identifier[str] , identifier[enforce_not_joker] : identifier[bool] = keyword[True] )-> identifier[Type] [ identifier[Any] ]: literal[string] keyword[if] identifier[object_type] keyword[is] identifier[object] keyword[or] identifier[object_type] keyword[is] identifier[Any] keyword[or] identifier[object_type] keyword[is] identifier[AnyObject] : keyword[return] identifier[AnyObject] keyword[else] : keyword[if] identifier[object_type] keyword[is] identifier[JOKER] : keyword[if] identifier[enforce_not_joker] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[else] : identifier[check_var] ( identifier[object_type] , identifier[var_types] = identifier[type] , identifier[var_name] = identifier[name] ) keyword[return] identifier[object_type]
def get_validated_type(object_type: Type[Any], name: str, enforce_not_joker: bool=True) -> Type[Any]: """ Utility to validate a type : * None is not allowed, * 'object', 'AnyObject' and 'Any' lead to the same 'AnyObject' type * JOKER is either rejected (if enforce_not_joker is True, default) or accepted 'as is' :param object_type: the type to validate :param name: a name used in exceptions if any :param enforce_not_joker: a boolean, set to False to tolerate JOKER types :return: the fixed type """ if object_type is object or object_type is Any or object_type is AnyObject: return AnyObject # depends on [control=['if'], data=[]] else: # -- !! Do not check TypeVar or Union : this is already handled at higher levels -- if object_type is JOKER: # optionally check if JOKER is allowed if enforce_not_joker: raise ValueError('JOKER is not allowed for object_type') # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] else: # note: we dont check var earlier, since 'typing.Any' is not a subclass of type anymore check_var(object_type, var_types=type, var_name=name) return object_type
def mmGetPlotConnectionsPerColumn(self, title=None): """ Returns plot of # connections per column. @return (Plot) plot """ plot = Plot(self, title) plot.addGraph(sorted(self._connectedCounts.tolist(), reverse=True), position=211, xlabel="column", ylabel="# connections") plot.addHistogram(self._connectedCounts.tolist(), position=212, bins=len(self._connectedCounts) / 10, xlabel="# connections", ylabel="# columns") return plot
def function[mmGetPlotConnectionsPerColumn, parameter[self, title]]: constant[ Returns plot of # connections per column. @return (Plot) plot ] variable[plot] assign[=] call[name[Plot], parameter[name[self], name[title]]] call[name[plot].addGraph, parameter[call[name[sorted], parameter[call[name[self]._connectedCounts.tolist, parameter[]]]]]] call[name[plot].addHistogram, parameter[call[name[self]._connectedCounts.tolist, parameter[]]]] return[name[plot]]
keyword[def] identifier[mmGetPlotConnectionsPerColumn] ( identifier[self] , identifier[title] = keyword[None] ): literal[string] identifier[plot] = identifier[Plot] ( identifier[self] , identifier[title] ) identifier[plot] . identifier[addGraph] ( identifier[sorted] ( identifier[self] . identifier[_connectedCounts] . identifier[tolist] (), identifier[reverse] = keyword[True] ), identifier[position] = literal[int] , identifier[xlabel] = literal[string] , identifier[ylabel] = literal[string] ) identifier[plot] . identifier[addHistogram] ( identifier[self] . identifier[_connectedCounts] . identifier[tolist] (), identifier[position] = literal[int] , identifier[bins] = identifier[len] ( identifier[self] . identifier[_connectedCounts] )/ literal[int] , identifier[xlabel] = literal[string] , identifier[ylabel] = literal[string] ) keyword[return] identifier[plot]
def mmGetPlotConnectionsPerColumn(self, title=None): """ Returns plot of # connections per column. @return (Plot) plot """ plot = Plot(self, title) plot.addGraph(sorted(self._connectedCounts.tolist(), reverse=True), position=211, xlabel='column', ylabel='# connections') plot.addHistogram(self._connectedCounts.tolist(), position=212, bins=len(self._connectedCounts) / 10, xlabel='# connections', ylabel='# columns') return plot
def getPiLambert(n): """Returns a list containing first n digits of Pi """ mypi = piGenLambert() result = [] if n > 0: result += [next(mypi) for i in range(n)] mypi.close() return result
def function[getPiLambert, parameter[n]]: constant[Returns a list containing first n digits of Pi ] variable[mypi] assign[=] call[name[piGenLambert], parameter[]] variable[result] assign[=] list[[]] if compare[name[n] greater[>] constant[0]] begin[:] <ast.AugAssign object at 0x7da18f00ebc0> call[name[mypi].close, parameter[]] return[name[result]]
keyword[def] identifier[getPiLambert] ( identifier[n] ): literal[string] identifier[mypi] = identifier[piGenLambert] () identifier[result] =[] keyword[if] identifier[n] > literal[int] : identifier[result] +=[ identifier[next] ( identifier[mypi] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[n] )] identifier[mypi] . identifier[close] () keyword[return] identifier[result]
def getPiLambert(n): """Returns a list containing first n digits of Pi """ mypi = piGenLambert() result = [] if n > 0: result += [next(mypi) for i in range(n)] # depends on [control=['if'], data=['n']] mypi.close() return result
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, defer=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3 :param int defer: Defer connection delay, seconds. Default: 5. """ super(RouterFast, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'defer'])) self._set_aliased('max-retries', retry_max) self._set_aliased('defer-connect-timeout', defer) return self
def function[set_connections_params, parameter[self, harakiri, timeout_socket, retry_delay, retry_max, defer]]: constant[Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3 :param int defer: Defer connection delay, seconds. Default: 5. ] call[call[name[super], parameter[name[RouterFast], name[self]]].set_connections_params, parameter[]] call[name[self]._set_aliased, parameter[constant[max-retries], name[retry_max]]] call[name[self]._set_aliased, parameter[constant[defer-connect-timeout], name[defer]]] return[name[self]]
keyword[def] identifier[set_connections_params] ( identifier[self] , identifier[harakiri] = keyword[None] , identifier[timeout_socket] = keyword[None] , identifier[retry_delay] = keyword[None] , identifier[retry_max] = keyword[None] , identifier[defer] = keyword[None] ): literal[string] identifier[super] ( identifier[RouterFast] , identifier[self] ). identifier[set_connections_params] (** identifier[filter_locals] ( identifier[locals] (),[ literal[string] , literal[string] ])) identifier[self] . identifier[_set_aliased] ( literal[string] , identifier[retry_max] ) identifier[self] . identifier[_set_aliased] ( literal[string] , identifier[defer] ) keyword[return] identifier[self]
def set_connections_params(self, harakiri=None, timeout_socket=None, retry_delay=None, retry_max=None, defer=None): """Sets connection-related parameters. :param int harakiri: Set gateway harakiri timeout (seconds). :param int timeout_socket: Node socket timeout (seconds). Default: 60. :param int retry_delay: Retry connections to dead static nodes after the specified amount of seconds. Default: 30. :param int retry_max: Maximum number of retries/fallbacks to other nodes. Default: 3 :param int defer: Defer connection delay, seconds. Default: 5. """ super(RouterFast, self).set_connections_params(**filter_locals(locals(), ['retry_max', 'defer'])) self._set_aliased('max-retries', retry_max) self._set_aliased('defer-connect-timeout', defer) return self
def remove(self, cls, originalMemberNameList, classNamingConvention): """ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention """ self._memberDelegate.remove(cls = cls, originalMemberNameList = originalMemberNameList, memberName = self._memberName, classNamingConvention = classNamingConvention)
def function[remove, parameter[self, cls, originalMemberNameList, classNamingConvention]]: constant[ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention ] call[name[self]._memberDelegate.remove, parameter[]]
keyword[def] identifier[remove] ( identifier[self] , identifier[cls] , identifier[originalMemberNameList] , identifier[classNamingConvention] ): literal[string] identifier[self] . identifier[_memberDelegate] . identifier[remove] ( identifier[cls] = identifier[cls] , identifier[originalMemberNameList] = identifier[originalMemberNameList] , identifier[memberName] = identifier[self] . identifier[_memberName] , identifier[classNamingConvention] = identifier[classNamingConvention] )
def remove(self, cls, originalMemberNameList, classNamingConvention): """ :type cls: type :type originalMemberNameList: list(str) :type classNamingConvention: INamingConvention """ self._memberDelegate.remove(cls=cls, originalMemberNameList=originalMemberNameList, memberName=self._memberName, classNamingConvention=classNamingConvention)
def cell_strings(term): """Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. """ num_colors = term.number_of_colors if num_colors >= 16: funcs = term.on_bright_red, term.on_bright_green, term.on_bright_cyan elif num_colors >= 8: funcs = term.on_red, term.on_green, term.on_blue else: # For black and white, use the checkerboard cursor from the vt100 # alternate charset: return (term.reverse(' '), term.smacs + term.reverse('a') + term.rmacs, term.smacs + 'a' + term.rmacs) # Wrap spaces in whatever pretty colors we chose: return [f(' ') for f in funcs]
def function[cell_strings, parameter[term]]: constant[Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. ] variable[num_colors] assign[=] name[term].number_of_colors if compare[name[num_colors] greater_or_equal[>=] constant[16]] begin[:] variable[funcs] assign[=] tuple[[<ast.Attribute object at 0x7da1b0b6c0a0>, <ast.Attribute object at 0x7da1b0b6f880>, <ast.Attribute object at 0x7da1b0b6c5e0>]] return[<ast.ListComp object at 0x7da1b0b1b8e0>]
keyword[def] identifier[cell_strings] ( identifier[term] ): literal[string] identifier[num_colors] = identifier[term] . identifier[number_of_colors] keyword[if] identifier[num_colors] >= literal[int] : identifier[funcs] = identifier[term] . identifier[on_bright_red] , identifier[term] . identifier[on_bright_green] , identifier[term] . identifier[on_bright_cyan] keyword[elif] identifier[num_colors] >= literal[int] : identifier[funcs] = identifier[term] . identifier[on_red] , identifier[term] . identifier[on_green] , identifier[term] . identifier[on_blue] keyword[else] : keyword[return] ( identifier[term] . identifier[reverse] ( literal[string] ), identifier[term] . identifier[smacs] + identifier[term] . identifier[reverse] ( literal[string] )+ identifier[term] . identifier[rmacs] , identifier[term] . identifier[smacs] + literal[string] + identifier[term] . identifier[rmacs] ) keyword[return] [ identifier[f] ( literal[string] ) keyword[for] identifier[f] keyword[in] identifier[funcs] ]
def cell_strings(term): """Return the strings that represent each possible living cell state. Return the most colorful ones the terminal supports. """ num_colors = term.number_of_colors if num_colors >= 16: funcs = (term.on_bright_red, term.on_bright_green, term.on_bright_cyan) # depends on [control=['if'], data=[]] elif num_colors >= 8: funcs = (term.on_red, term.on_green, term.on_blue) # depends on [control=['if'], data=[]] else: # For black and white, use the checkerboard cursor from the vt100 # alternate charset: return (term.reverse(' '), term.smacs + term.reverse('a') + term.rmacs, term.smacs + 'a' + term.rmacs) # Wrap spaces in whatever pretty colors we chose: return [f(' ') for f in funcs]
def windowed_sum(arrays, span, t=None, indices=None, tpowers=0, period=None, subtract_mid=False): """Compute the windowed sum of the given arrays. Parameters ---------- arrays : tuple of arrays arrays to window span : int or array of ints The span to use for the sum at each point. If array is provided, it must be broadcastable with ``indices`` indices : array the indices of the center of the desired windows. If ``None``, the indices are assumed to be ``range(len(arrays[0]))`` though these are not actually instantiated. t : array (optional) Times associated with the arrays tpowers : list (optional) Powers of t for each array sum period : float (optional) Period to use, if times are periodic. If supplied, input times must be arranged such that (t % period) is sorted! subtract_mid : boolean If true, then subtract the middle value from each sum Returns ------- arrays : tuple of ndarrays arrays containing the windowed sum of each input array """ span = np.asarray(span, dtype=int) if not np.all(span > 0): raise ValueError("span values must be positive") arrays = tuple(map(np.asarray, arrays)) N = arrays[0].size if not all(a.shape == (N,) for a in arrays): raise ValueError("sizes of provided arrays must match") t_input = t if t is not None: t = np.asarray(t) if t.shape != (N,): raise ValueError("shape of t must match shape of arrays " "t -> {0} arr -> {1}".format(t.shape, arrays[0].shape)) else: # XXX: special-case no t? t = np.ones(N) tpowers = np.asarray(tpowers) + np.zeros(len(arrays)) if indices is not None: span, indices = np.broadcast_arrays(span, indices) # For the periodic case, re-call the function with padded arrays if period: if t_input is None: raise ValueError("periodic requires t to be provided") t = t % period t, arrays, sl = _pad_arrays(t, arrays, indices, span, period) if len(t) > N: # arrays are padded. Recursively call windowed_sum() and return. if span.ndim == 0 and indices is None: # fixed-span/no index case is done faster this way arrs = windowed_sum(arrays, span, t=t, indices=indices, tpowers=tpowers, period=None, subtract_mid=subtract_mid) return tuple([a[sl] for a in arrs]) else: # this works for variable span and general indices if indices is None: indices = np.arange(N) indices = indices + sl.start return windowed_sum(arrays, span, t=t, indices=indices, tpowers=tpowers, period=None, subtract_mid=subtract_mid) else: # No padding needed! We can carry-on as if it's a non-periodic case period = None # The rest of the algorithm now proceeds without reference to the period # just as a sanity check... assert not period if span.ndim == 0: # fixed-span case. Because of the checks & manipulations above # we know here that indices=None assert indices is None window = np.ones(span) def convolve_same(a, window): if len(window) <= len(a): res = np.convolve(a, window, mode='same') else: res = np.convolve(a, window, mode='full') start = (len(window) - 1) // 2 res = res[start:start + len(a)] return res results = [convolve_same(a * t ** tp, window) for a, tp in zip(arrays, tpowers)] indices = slice(None) else: # variable-span case. Use reduceat() in a clever way for speed. if indices is None: indices = np.arange(len(span)) # we checked this above, but just as a sanity check assert it here... assert span.shape == indices.shape mins = np.asarray(indices) - span // 2 results = [] for a, tp in zip(arrays, tpowers): ranges = np.vstack([np.maximum(0, mins), np.minimum(len(a), mins+span)]).ravel('F') results.append(np.add.reduceat(np.append(a * t ** tp, 0), ranges)[::2]) # Subtract the midpoint if required: this is used in cross-validation if subtract_mid: results = [r - a[indices] * t[indices] ** tp for r, a, tp in zip(results, arrays, tpowers)] return tuple(results)
def function[windowed_sum, parameter[arrays, span, t, indices, tpowers, period, subtract_mid]]: constant[Compute the windowed sum of the given arrays. Parameters ---------- arrays : tuple of arrays arrays to window span : int or array of ints The span to use for the sum at each point. If array is provided, it must be broadcastable with ``indices`` indices : array the indices of the center of the desired windows. If ``None``, the indices are assumed to be ``range(len(arrays[0]))`` though these are not actually instantiated. t : array (optional) Times associated with the arrays tpowers : list (optional) Powers of t for each array sum period : float (optional) Period to use, if times are periodic. If supplied, input times must be arranged such that (t % period) is sorted! subtract_mid : boolean If true, then subtract the middle value from each sum Returns ------- arrays : tuple of ndarrays arrays containing the windowed sum of each input array ] variable[span] assign[=] call[name[np].asarray, parameter[name[span]]] if <ast.UnaryOp object at 0x7da207f9ad70> begin[:] <ast.Raise object at 0x7da207f9ac20> variable[arrays] assign[=] call[name[tuple], parameter[call[name[map], parameter[name[np].asarray, name[arrays]]]]] variable[N] assign[=] call[name[arrays]][constant[0]].size if <ast.UnaryOp object at 0x7da207f9ab00> begin[:] <ast.Raise object at 0x7da207f9ae60> variable[t_input] assign[=] name[t] if compare[name[t] is_not constant[None]] begin[:] variable[t] assign[=] call[name[np].asarray, parameter[name[t]]] if compare[name[t].shape not_equal[!=] tuple[[<ast.Name object at 0x7da18eb579a0>]]] begin[:] <ast.Raise object at 0x7da18eb57a00> variable[tpowers] assign[=] binary_operation[call[name[np].asarray, parameter[name[tpowers]]] + call[name[np].zeros, parameter[call[name[len], parameter[name[arrays]]]]]] if compare[name[indices] is_not constant[None]] begin[:] <ast.Tuple object at 0x7da18eb56da0> assign[=] call[name[np].broadcast_arrays, parameter[name[span], name[indices]]] if name[period] begin[:] if compare[name[t_input] is constant[None]] begin[:] <ast.Raise object at 0x7da18eb55a50> variable[t] assign[=] binary_operation[name[t] <ast.Mod object at 0x7da2590d6920> name[period]] <ast.Tuple object at 0x7da18eb541f0> assign[=] call[name[_pad_arrays], parameter[name[t], name[arrays], name[indices], name[span], name[period]]] if compare[call[name[len], parameter[name[t]]] greater[>] name[N]] begin[:] if <ast.BoolOp object at 0x7da18eb57730> begin[:] variable[arrs] assign[=] call[name[windowed_sum], parameter[name[arrays], name[span]]] return[call[name[tuple], parameter[<ast.ListComp object at 0x7da20c6c5930>]]] assert[<ast.UnaryOp object at 0x7da20c6c65c0>] if compare[name[span].ndim equal[==] constant[0]] begin[:] assert[compare[name[indices] is constant[None]]] variable[window] assign[=] call[name[np].ones, parameter[name[span]]] def function[convolve_same, parameter[a, window]]: if compare[call[name[len], parameter[name[window]]] less_or_equal[<=] call[name[len], parameter[name[a]]]] begin[:] variable[res] assign[=] call[name[np].convolve, parameter[name[a], name[window]]] return[name[res]] variable[results] assign[=] <ast.ListComp object at 0x7da20c6c7850> variable[indices] assign[=] call[name[slice], parameter[constant[None]]] if name[subtract_mid] begin[:] variable[results] assign[=] <ast.ListComp object at 0x7da20c6c5570> return[call[name[tuple], parameter[name[results]]]]
keyword[def] identifier[windowed_sum] ( identifier[arrays] , identifier[span] , identifier[t] = keyword[None] , identifier[indices] = keyword[None] , identifier[tpowers] = literal[int] , identifier[period] = keyword[None] , identifier[subtract_mid] = keyword[False] ): literal[string] identifier[span] = identifier[np] . identifier[asarray] ( identifier[span] , identifier[dtype] = identifier[int] ) keyword[if] keyword[not] identifier[np] . identifier[all] ( identifier[span] > literal[int] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[arrays] = identifier[tuple] ( identifier[map] ( identifier[np] . identifier[asarray] , identifier[arrays] )) identifier[N] = identifier[arrays] [ literal[int] ]. identifier[size] keyword[if] keyword[not] identifier[all] ( identifier[a] . identifier[shape] ==( identifier[N] ,) keyword[for] identifier[a] keyword[in] identifier[arrays] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[t_input] = identifier[t] keyword[if] identifier[t] keyword[is] keyword[not] keyword[None] : identifier[t] = identifier[np] . identifier[asarray] ( identifier[t] ) keyword[if] identifier[t] . identifier[shape] !=( identifier[N] ,): keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[t] . identifier[shape] , identifier[arrays] [ literal[int] ]. identifier[shape] )) keyword[else] : identifier[t] = identifier[np] . identifier[ones] ( identifier[N] ) identifier[tpowers] = identifier[np] . identifier[asarray] ( identifier[tpowers] )+ identifier[np] . identifier[zeros] ( identifier[len] ( identifier[arrays] )) keyword[if] identifier[indices] keyword[is] keyword[not] keyword[None] : identifier[span] , identifier[indices] = identifier[np] . identifier[broadcast_arrays] ( identifier[span] , identifier[indices] ) keyword[if] identifier[period] : keyword[if] identifier[t_input] keyword[is] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) identifier[t] = identifier[t] % identifier[period] identifier[t] , identifier[arrays] , identifier[sl] = identifier[_pad_arrays] ( identifier[t] , identifier[arrays] , identifier[indices] , identifier[span] , identifier[period] ) keyword[if] identifier[len] ( identifier[t] )> identifier[N] : keyword[if] identifier[span] . identifier[ndim] == literal[int] keyword[and] identifier[indices] keyword[is] keyword[None] : identifier[arrs] = identifier[windowed_sum] ( identifier[arrays] , identifier[span] , identifier[t] = identifier[t] , identifier[indices] = identifier[indices] , identifier[tpowers] = identifier[tpowers] , identifier[period] = keyword[None] , identifier[subtract_mid] = identifier[subtract_mid] ) keyword[return] identifier[tuple] ([ identifier[a] [ identifier[sl] ] keyword[for] identifier[a] keyword[in] identifier[arrs] ]) keyword[else] : keyword[if] identifier[indices] keyword[is] keyword[None] : identifier[indices] = identifier[np] . identifier[arange] ( identifier[N] ) identifier[indices] = identifier[indices] + identifier[sl] . identifier[start] keyword[return] identifier[windowed_sum] ( identifier[arrays] , identifier[span] , identifier[t] = identifier[t] , identifier[indices] = identifier[indices] , identifier[tpowers] = identifier[tpowers] , identifier[period] = keyword[None] , identifier[subtract_mid] = identifier[subtract_mid] ) keyword[else] : identifier[period] = keyword[None] keyword[assert] keyword[not] identifier[period] keyword[if] identifier[span] . identifier[ndim] == literal[int] : keyword[assert] identifier[indices] keyword[is] keyword[None] identifier[window] = identifier[np] . identifier[ones] ( identifier[span] ) keyword[def] identifier[convolve_same] ( identifier[a] , identifier[window] ): keyword[if] identifier[len] ( identifier[window] )<= identifier[len] ( identifier[a] ): identifier[res] = identifier[np] . identifier[convolve] ( identifier[a] , identifier[window] , identifier[mode] = literal[string] ) keyword[else] : identifier[res] = identifier[np] . identifier[convolve] ( identifier[a] , identifier[window] , identifier[mode] = literal[string] ) identifier[start] =( identifier[len] ( identifier[window] )- literal[int] )// literal[int] identifier[res] = identifier[res] [ identifier[start] : identifier[start] + identifier[len] ( identifier[a] )] keyword[return] identifier[res] identifier[results] =[ identifier[convolve_same] ( identifier[a] * identifier[t] ** identifier[tp] , identifier[window] ) keyword[for] identifier[a] , identifier[tp] keyword[in] identifier[zip] ( identifier[arrays] , identifier[tpowers] )] identifier[indices] = identifier[slice] ( keyword[None] ) keyword[else] : keyword[if] identifier[indices] keyword[is] keyword[None] : identifier[indices] = identifier[np] . identifier[arange] ( identifier[len] ( identifier[span] )) keyword[assert] identifier[span] . identifier[shape] == identifier[indices] . identifier[shape] identifier[mins] = identifier[np] . identifier[asarray] ( identifier[indices] )- identifier[span] // literal[int] identifier[results] =[] keyword[for] identifier[a] , identifier[tp] keyword[in] identifier[zip] ( identifier[arrays] , identifier[tpowers] ): identifier[ranges] = identifier[np] . identifier[vstack] ([ identifier[np] . identifier[maximum] ( literal[int] , identifier[mins] ), identifier[np] . identifier[minimum] ( identifier[len] ( identifier[a] ), identifier[mins] + identifier[span] )]). identifier[ravel] ( literal[string] ) identifier[results] . identifier[append] ( identifier[np] . identifier[add] . identifier[reduceat] ( identifier[np] . identifier[append] ( identifier[a] * identifier[t] ** identifier[tp] , literal[int] ), identifier[ranges] )[:: literal[int] ]) keyword[if] identifier[subtract_mid] : identifier[results] =[ identifier[r] - identifier[a] [ identifier[indices] ]* identifier[t] [ identifier[indices] ]** identifier[tp] keyword[for] identifier[r] , identifier[a] , identifier[tp] keyword[in] identifier[zip] ( identifier[results] , identifier[arrays] , identifier[tpowers] )] keyword[return] identifier[tuple] ( identifier[results] )
def windowed_sum(arrays, span, t=None, indices=None, tpowers=0, period=None, subtract_mid=False): """Compute the windowed sum of the given arrays. Parameters ---------- arrays : tuple of arrays arrays to window span : int or array of ints The span to use for the sum at each point. If array is provided, it must be broadcastable with ``indices`` indices : array the indices of the center of the desired windows. If ``None``, the indices are assumed to be ``range(len(arrays[0]))`` though these are not actually instantiated. t : array (optional) Times associated with the arrays tpowers : list (optional) Powers of t for each array sum period : float (optional) Period to use, if times are periodic. If supplied, input times must be arranged such that (t % period) is sorted! subtract_mid : boolean If true, then subtract the middle value from each sum Returns ------- arrays : tuple of ndarrays arrays containing the windowed sum of each input array """ span = np.asarray(span, dtype=int) if not np.all(span > 0): raise ValueError('span values must be positive') # depends on [control=['if'], data=[]] arrays = tuple(map(np.asarray, arrays)) N = arrays[0].size if not all((a.shape == (N,) for a in arrays)): raise ValueError('sizes of provided arrays must match') # depends on [control=['if'], data=[]] t_input = t if t is not None: t = np.asarray(t) if t.shape != (N,): raise ValueError('shape of t must match shape of arrays t -> {0} arr -> {1}'.format(t.shape, arrays[0].shape)) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['t']] else: # XXX: special-case no t? t = np.ones(N) tpowers = np.asarray(tpowers) + np.zeros(len(arrays)) if indices is not None: (span, indices) = np.broadcast_arrays(span, indices) # depends on [control=['if'], data=['indices']] # For the periodic case, re-call the function with padded arrays if period: if t_input is None: raise ValueError('periodic requires t to be provided') # depends on [control=['if'], data=[]] t = t % period (t, arrays, sl) = _pad_arrays(t, arrays, indices, span, period) if len(t) > N: # arrays are padded. Recursively call windowed_sum() and return. if span.ndim == 0 and indices is None: # fixed-span/no index case is done faster this way arrs = windowed_sum(arrays, span, t=t, indices=indices, tpowers=tpowers, period=None, subtract_mid=subtract_mid) return tuple([a[sl] for a in arrs]) # depends on [control=['if'], data=[]] else: # this works for variable span and general indices if indices is None: indices = np.arange(N) # depends on [control=['if'], data=['indices']] indices = indices + sl.start return windowed_sum(arrays, span, t=t, indices=indices, tpowers=tpowers, period=None, subtract_mid=subtract_mid) # depends on [control=['if'], data=['N']] else: # No padding needed! We can carry-on as if it's a non-periodic case period = None # depends on [control=['if'], data=[]] # The rest of the algorithm now proceeds without reference to the period # just as a sanity check... assert not period if span.ndim == 0: # fixed-span case. Because of the checks & manipulations above # we know here that indices=None assert indices is None window = np.ones(span) def convolve_same(a, window): if len(window) <= len(a): res = np.convolve(a, window, mode='same') # depends on [control=['if'], data=[]] else: res = np.convolve(a, window, mode='full') start = (len(window) - 1) // 2 res = res[start:start + len(a)] return res results = [convolve_same(a * t ** tp, window) for (a, tp) in zip(arrays, tpowers)] indices = slice(None) # depends on [control=['if'], data=[]] else: # variable-span case. Use reduceat() in a clever way for speed. if indices is None: indices = np.arange(len(span)) # depends on [control=['if'], data=['indices']] # we checked this above, but just as a sanity check assert it here... assert span.shape == indices.shape mins = np.asarray(indices) - span // 2 results = [] for (a, tp) in zip(arrays, tpowers): ranges = np.vstack([np.maximum(0, mins), np.minimum(len(a), mins + span)]).ravel('F') results.append(np.add.reduceat(np.append(a * t ** tp, 0), ranges)[::2]) # depends on [control=['for'], data=[]] # Subtract the midpoint if required: this is used in cross-validation if subtract_mid: results = [r - a[indices] * t[indices] ** tp for (r, a, tp) in zip(results, arrays, tpowers)] # depends on [control=['if'], data=[]] return tuple(results)
def _parse_interfaces(interface_files=None): ''' Parse /etc/network/interfaces and return current configured interfaces ''' if interface_files is None: interface_files = [] # Add this later. if os.path.exists(_DEB_NETWORK_DIR): interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)] if os.path.isfile(_DEB_NETWORK_FILE): interface_files.insert(0, _DEB_NETWORK_FILE) adapters = salt.utils.odict.OrderedDict() method = -1 for interface_file in interface_files: with salt.utils.files.fopen(interface_file) as interfaces: # This ensures iface_dict exists, but does not ensure we're not reading a new interface. iface_dict = {} for line in interfaces: line = salt.utils.stringutils.to_unicode(line) # Identify the clauses by the first word of each line. # Go to the next line if the current line is a comment # or all spaces. if line.lstrip().startswith('#') or line.isspace(): continue # Parse the iface clause if line.startswith('iface'): sline = line.split() if len(sline) != 4: msg = 'Interface file malformed: {0}.' msg = msg.format(sline) log.error(msg) raise AttributeError(msg) iface_name = sline[1] addrfam = sline[2] method = sline[3] # Create item in dict, if not already there if iface_name not in adapters: adapters[iface_name] = salt.utils.odict.OrderedDict() # Create item in dict, if not already there if 'data' not in adapters[iface_name]: adapters[iface_name]['data'] = salt.utils.odict.OrderedDict() if addrfam not in adapters[iface_name]['data']: adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict() iface_dict = adapters[iface_name]['data'][addrfam] iface_dict['addrfam'] = addrfam iface_dict['proto'] = method iface_dict['filename'] = interface_file # Parse the detail clauses. elif line[0].isspace(): sline = line.split() # conf file attr: dns-nameservers # salt states.network attr: dns attr, valuestr = line.rstrip().split(None, 1) if _attrmaps_contain_attr(attr): if '-' in attr: attrname = attr.replace('-', '_') else: attrname = attr (valid, value, errmsg) = _validate_interface_option( attr, valuestr, addrfam) if attrname == 'address' and 'address' in iface_dict: if 'addresses' not in iface_dict: iface_dict['addresses'] = [] iface_dict['addresses'].append(value) else: iface_dict[attrname] = value elif attr in _REV_ETHTOOL_CONFIG_OPTS: if 'ethtool' not in iface_dict: iface_dict['ethtool'] = salt.utils.odict.OrderedDict() iface_dict['ethtool'][attr] = valuestr elif attr.startswith('bond'): opt = re.split(r'[_-]', attr, maxsplit=1)[1] if 'bonding' not in iface_dict: iface_dict['bonding'] = salt.utils.odict.OrderedDict() iface_dict['bonding'][opt] = valuestr elif attr.startswith('bridge'): opt = re.split(r'[_-]', attr, maxsplit=1)[1] if 'bridging' not in iface_dict: iface_dict['bridging'] = salt.utils.odict.OrderedDict() iface_dict['bridging'][opt] = valuestr elif attr in ['up', 'pre-up', 'post-up', 'down', 'pre-down', 'post-down']: cmd = valuestr cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr)) if cmd_key not in iface_dict: iface_dict[cmd_key] = [] iface_dict[cmd_key].append(cmd) elif line.startswith('auto'): for word in line.split()[1:]: if word not in adapters: adapters[word] = salt.utils.odict.OrderedDict() adapters[word]['enabled'] = True elif line.startswith('allow-hotplug'): for word in line.split()[1:]: if word not in adapters: adapters[word] = salt.utils.odict.OrderedDict() adapters[word]['hotplug'] = True elif line.startswith('source'): if 'source' not in adapters: adapters['source'] = salt.utils.odict.OrderedDict() # Create item in dict, if not already there if 'data' not in adapters['source']: adapters['source']['data'] = salt.utils.odict.OrderedDict() adapters['source']['data']['sources'] = [] adapters['source']['data']['sources'].append(line.split()[1]) # Return a sorted list of the keys for bond, bridge and ethtool options to # ensure a consistent order for iface_name in adapters: if iface_name == 'source': continue if 'data' not in adapters[iface_name]: msg = 'Interface file malformed for interface: {0}.'.format(iface_name) log.error(msg) adapters.pop(iface_name) continue for opt in ['ethtool', 'bonding', 'bridging']: for inet in ['inet', 'inet6']: if inet in adapters[iface_name]['data']: if opt in adapters[iface_name]['data'][inet]: opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys()) adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys return adapters
def function[_parse_interfaces, parameter[interface_files]]: constant[ Parse /etc/network/interfaces and return current configured interfaces ] if compare[name[interface_files] is constant[None]] begin[:] variable[interface_files] assign[=] list[[]] if call[name[os].path.exists, parameter[name[_DEB_NETWORK_DIR]]] begin[:] <ast.AugAssign object at 0x7da1b1f2fbe0> if call[name[os].path.isfile, parameter[name[_DEB_NETWORK_FILE]]] begin[:] call[name[interface_files].insert, parameter[constant[0], name[_DEB_NETWORK_FILE]]] variable[adapters] assign[=] call[name[salt].utils.odict.OrderedDict, parameter[]] variable[method] assign[=] <ast.UnaryOp object at 0x7da1b1f2f4f0> for taget[name[interface_file]] in starred[name[interface_files]] begin[:] with call[name[salt].utils.files.fopen, parameter[name[interface_file]]] begin[:] variable[iface_dict] assign[=] dictionary[[], []] for taget[name[line]] in starred[name[interfaces]] begin[:] variable[line] assign[=] call[name[salt].utils.stringutils.to_unicode, parameter[name[line]]] if <ast.BoolOp object at 0x7da1b1f2ef50> begin[:] continue if call[name[line].startswith, parameter[constant[iface]]] begin[:] variable[sline] assign[=] call[name[line].split, parameter[]] if compare[call[name[len], parameter[name[sline]]] not_equal[!=] constant[4]] begin[:] variable[msg] assign[=] constant[Interface file malformed: {0}.] variable[msg] assign[=] call[name[msg].format, parameter[name[sline]]] call[name[log].error, parameter[name[msg]]] <ast.Raise object at 0x7da1b1f2ca60> variable[iface_name] assign[=] call[name[sline]][constant[1]] variable[addrfam] assign[=] call[name[sline]][constant[2]] variable[method] assign[=] call[name[sline]][constant[3]] if compare[name[iface_name] <ast.NotIn object at 0x7da2590d7190> name[adapters]] begin[:] call[name[adapters]][name[iface_name]] assign[=] call[name[salt].utils.odict.OrderedDict, parameter[]] if compare[constant[data] <ast.NotIn object at 0x7da2590d7190> call[name[adapters]][name[iface_name]]] begin[:] call[call[name[adapters]][name[iface_name]]][constant[data]] assign[=] call[name[salt].utils.odict.OrderedDict, parameter[]] if compare[name[addrfam] <ast.NotIn object at 0x7da2590d7190> call[call[name[adapters]][name[iface_name]]][constant[data]]] begin[:] call[call[call[name[adapters]][name[iface_name]]][constant[data]]][name[addrfam]] assign[=] call[name[salt].utils.odict.OrderedDict, parameter[]] variable[iface_dict] assign[=] call[call[call[name[adapters]][name[iface_name]]][constant[data]]][name[addrfam]] call[name[iface_dict]][constant[addrfam]] assign[=] name[addrfam] call[name[iface_dict]][constant[proto]] assign[=] name[method] call[name[iface_dict]][constant[filename]] assign[=] name[interface_file] for taget[name[iface_name]] in starred[name[adapters]] begin[:] if compare[name[iface_name] equal[==] constant[source]] begin[:] continue if compare[constant[data] <ast.NotIn object at 0x7da2590d7190> call[name[adapters]][name[iface_name]]] begin[:] variable[msg] assign[=] call[constant[Interface file malformed for interface: {0}.].format, parameter[name[iface_name]]] call[name[log].error, parameter[name[msg]]] call[name[adapters].pop, parameter[name[iface_name]]] continue for taget[name[opt]] in starred[list[[<ast.Constant object at 0x7da1b1f3fd00>, <ast.Constant object at 0x7da1b1f3ffa0>, <ast.Constant object at 0x7da1b1f3fa90>]]] begin[:] for taget[name[inet]] in starred[list[[<ast.Constant object at 0x7da1b1f3fb50>, <ast.Constant object at 0x7da1b1f3fc70>]]] begin[:] if compare[name[inet] in call[call[name[adapters]][name[iface_name]]][constant[data]]] begin[:] if compare[name[opt] in call[call[call[name[adapters]][name[iface_name]]][constant[data]]][name[inet]]] begin[:] variable[opt_keys] assign[=] call[name[sorted], parameter[call[call[call[call[call[name[adapters]][name[iface_name]]][constant[data]]][name[inet]]][name[opt]].keys, parameter[]]]] call[call[call[call[name[adapters]][name[iface_name]]][constant[data]]][name[inet]]][binary_operation[name[opt] + constant[_keys]]] assign[=] name[opt_keys] return[name[adapters]]
keyword[def] identifier[_parse_interfaces] ( identifier[interface_files] = keyword[None] ): literal[string] keyword[if] identifier[interface_files] keyword[is] keyword[None] : identifier[interface_files] =[] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[_DEB_NETWORK_DIR] ): identifier[interface_files] +=[ literal[string] . identifier[format] ( identifier[_DEB_NETWORK_DIR] , identifier[dir] ) keyword[for] identifier[dir] keyword[in] identifier[os] . identifier[listdir] ( identifier[_DEB_NETWORK_DIR] )] keyword[if] identifier[os] . identifier[path] . identifier[isfile] ( identifier[_DEB_NETWORK_FILE] ): identifier[interface_files] . identifier[insert] ( literal[int] , identifier[_DEB_NETWORK_FILE] ) identifier[adapters] = identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[method] =- literal[int] keyword[for] identifier[interface_file] keyword[in] identifier[interface_files] : keyword[with] identifier[salt] . identifier[utils] . identifier[files] . identifier[fopen] ( identifier[interface_file] ) keyword[as] identifier[interfaces] : identifier[iface_dict] ={} keyword[for] identifier[line] keyword[in] identifier[interfaces] : identifier[line] = identifier[salt] . identifier[utils] . identifier[stringutils] . identifier[to_unicode] ( identifier[line] ) keyword[if] identifier[line] . identifier[lstrip] (). identifier[startswith] ( literal[string] ) keyword[or] identifier[line] . identifier[isspace] (): keyword[continue] keyword[if] identifier[line] . identifier[startswith] ( literal[string] ): identifier[sline] = identifier[line] . identifier[split] () keyword[if] identifier[len] ( identifier[sline] )!= literal[int] : identifier[msg] = literal[string] identifier[msg] = identifier[msg] . identifier[format] ( identifier[sline] ) identifier[log] . identifier[error] ( identifier[msg] ) keyword[raise] identifier[AttributeError] ( identifier[msg] ) identifier[iface_name] = identifier[sline] [ literal[int] ] identifier[addrfam] = identifier[sline] [ literal[int] ] identifier[method] = identifier[sline] [ literal[int] ] keyword[if] identifier[iface_name] keyword[not] keyword[in] identifier[adapters] : identifier[adapters] [ identifier[iface_name] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () keyword[if] literal[string] keyword[not] keyword[in] identifier[adapters] [ identifier[iface_name] ]: identifier[adapters] [ identifier[iface_name] ][ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () keyword[if] identifier[addrfam] keyword[not] keyword[in] identifier[adapters] [ identifier[iface_name] ][ literal[string] ]: identifier[adapters] [ identifier[iface_name] ][ literal[string] ][ identifier[addrfam] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[iface_dict] = identifier[adapters] [ identifier[iface_name] ][ literal[string] ][ identifier[addrfam] ] identifier[iface_dict] [ literal[string] ]= identifier[addrfam] identifier[iface_dict] [ literal[string] ]= identifier[method] identifier[iface_dict] [ literal[string] ]= identifier[interface_file] keyword[elif] identifier[line] [ literal[int] ]. identifier[isspace] (): identifier[sline] = identifier[line] . identifier[split] () identifier[attr] , identifier[valuestr] = identifier[line] . identifier[rstrip] (). identifier[split] ( keyword[None] , literal[int] ) keyword[if] identifier[_attrmaps_contain_attr] ( identifier[attr] ): keyword[if] literal[string] keyword[in] identifier[attr] : identifier[attrname] = identifier[attr] . identifier[replace] ( literal[string] , literal[string] ) keyword[else] : identifier[attrname] = identifier[attr] ( identifier[valid] , identifier[value] , identifier[errmsg] )= identifier[_validate_interface_option] ( identifier[attr] , identifier[valuestr] , identifier[addrfam] ) keyword[if] identifier[attrname] == literal[string] keyword[and] literal[string] keyword[in] identifier[iface_dict] : keyword[if] literal[string] keyword[not] keyword[in] identifier[iface_dict] : identifier[iface_dict] [ literal[string] ]=[] identifier[iface_dict] [ literal[string] ]. identifier[append] ( identifier[value] ) keyword[else] : identifier[iface_dict] [ identifier[attrname] ]= identifier[value] keyword[elif] identifier[attr] keyword[in] identifier[_REV_ETHTOOL_CONFIG_OPTS] : keyword[if] literal[string] keyword[not] keyword[in] identifier[iface_dict] : identifier[iface_dict] [ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[iface_dict] [ literal[string] ][ identifier[attr] ]= identifier[valuestr] keyword[elif] identifier[attr] . identifier[startswith] ( literal[string] ): identifier[opt] = identifier[re] . identifier[split] ( literal[string] , identifier[attr] , identifier[maxsplit] = literal[int] )[ literal[int] ] keyword[if] literal[string] keyword[not] keyword[in] identifier[iface_dict] : identifier[iface_dict] [ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[iface_dict] [ literal[string] ][ identifier[opt] ]= identifier[valuestr] keyword[elif] identifier[attr] . identifier[startswith] ( literal[string] ): identifier[opt] = identifier[re] . identifier[split] ( literal[string] , identifier[attr] , identifier[maxsplit] = literal[int] )[ literal[int] ] keyword[if] literal[string] keyword[not] keyword[in] identifier[iface_dict] : identifier[iface_dict] [ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[iface_dict] [ literal[string] ][ identifier[opt] ]= identifier[valuestr] keyword[elif] identifier[attr] keyword[in] [ literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ]: identifier[cmd] = identifier[valuestr] identifier[cmd_key] = literal[string] . identifier[format] ( identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[attr] )) keyword[if] identifier[cmd_key] keyword[not] keyword[in] identifier[iface_dict] : identifier[iface_dict] [ identifier[cmd_key] ]=[] identifier[iface_dict] [ identifier[cmd_key] ]. identifier[append] ( identifier[cmd] ) keyword[elif] identifier[line] . identifier[startswith] ( literal[string] ): keyword[for] identifier[word] keyword[in] identifier[line] . identifier[split] ()[ literal[int] :]: keyword[if] identifier[word] keyword[not] keyword[in] identifier[adapters] : identifier[adapters] [ identifier[word] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[adapters] [ identifier[word] ][ literal[string] ]= keyword[True] keyword[elif] identifier[line] . identifier[startswith] ( literal[string] ): keyword[for] identifier[word] keyword[in] identifier[line] . identifier[split] ()[ literal[int] :]: keyword[if] identifier[word] keyword[not] keyword[in] identifier[adapters] : identifier[adapters] [ identifier[word] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[adapters] [ identifier[word] ][ literal[string] ]= keyword[True] keyword[elif] identifier[line] . identifier[startswith] ( literal[string] ): keyword[if] literal[string] keyword[not] keyword[in] identifier[adapters] : identifier[adapters] [ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () keyword[if] literal[string] keyword[not] keyword[in] identifier[adapters] [ literal[string] ]: identifier[adapters] [ literal[string] ][ literal[string] ]= identifier[salt] . identifier[utils] . identifier[odict] . identifier[OrderedDict] () identifier[adapters] [ literal[string] ][ literal[string] ][ literal[string] ]=[] identifier[adapters] [ literal[string] ][ literal[string] ][ literal[string] ]. identifier[append] ( identifier[line] . identifier[split] ()[ literal[int] ]) keyword[for] identifier[iface_name] keyword[in] identifier[adapters] : keyword[if] identifier[iface_name] == literal[string] : keyword[continue] keyword[if] literal[string] keyword[not] keyword[in] identifier[adapters] [ identifier[iface_name] ]: identifier[msg] = literal[string] . identifier[format] ( identifier[iface_name] ) identifier[log] . identifier[error] ( identifier[msg] ) identifier[adapters] . identifier[pop] ( identifier[iface_name] ) keyword[continue] keyword[for] identifier[opt] keyword[in] [ literal[string] , literal[string] , literal[string] ]: keyword[for] identifier[inet] keyword[in] [ literal[string] , literal[string] ]: keyword[if] identifier[inet] keyword[in] identifier[adapters] [ identifier[iface_name] ][ literal[string] ]: keyword[if] identifier[opt] keyword[in] identifier[adapters] [ identifier[iface_name] ][ literal[string] ][ identifier[inet] ]: identifier[opt_keys] = identifier[sorted] ( identifier[adapters] [ identifier[iface_name] ][ literal[string] ][ identifier[inet] ][ identifier[opt] ]. identifier[keys] ()) identifier[adapters] [ identifier[iface_name] ][ literal[string] ][ identifier[inet] ][ identifier[opt] + literal[string] ]= identifier[opt_keys] keyword[return] identifier[adapters]
def _parse_interfaces(interface_files=None): """ Parse /etc/network/interfaces and return current configured interfaces """ if interface_files is None: interface_files = [] # Add this later. if os.path.exists(_DEB_NETWORK_DIR): interface_files += ['{0}/{1}'.format(_DEB_NETWORK_DIR, dir) for dir in os.listdir(_DEB_NETWORK_DIR)] # depends on [control=['if'], data=[]] if os.path.isfile(_DEB_NETWORK_FILE): interface_files.insert(0, _DEB_NETWORK_FILE) # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['interface_files']] adapters = salt.utils.odict.OrderedDict() method = -1 for interface_file in interface_files: with salt.utils.files.fopen(interface_file) as interfaces: # This ensures iface_dict exists, but does not ensure we're not reading a new interface. iface_dict = {} for line in interfaces: line = salt.utils.stringutils.to_unicode(line) # Identify the clauses by the first word of each line. # Go to the next line if the current line is a comment # or all spaces. if line.lstrip().startswith('#') or line.isspace(): continue # depends on [control=['if'], data=[]] # Parse the iface clause if line.startswith('iface'): sline = line.split() if len(sline) != 4: msg = 'Interface file malformed: {0}.' msg = msg.format(sline) log.error(msg) raise AttributeError(msg) # depends on [control=['if'], data=[]] iface_name = sline[1] addrfam = sline[2] method = sline[3] # Create item in dict, if not already there if iface_name not in adapters: adapters[iface_name] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['iface_name', 'adapters']] # Create item in dict, if not already there if 'data' not in adapters[iface_name]: adapters[iface_name]['data'] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=[]] if addrfam not in adapters[iface_name]['data']: adapters[iface_name]['data'][addrfam] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['addrfam']] iface_dict = adapters[iface_name]['data'][addrfam] iface_dict['addrfam'] = addrfam iface_dict['proto'] = method iface_dict['filename'] = interface_file # depends on [control=['if'], data=[]] # Parse the detail clauses. elif line[0].isspace(): sline = line.split() # conf file attr: dns-nameservers # salt states.network attr: dns (attr, valuestr) = line.rstrip().split(None, 1) if _attrmaps_contain_attr(attr): if '-' in attr: attrname = attr.replace('-', '_') # depends on [control=['if'], data=['attr']] else: attrname = attr (valid, value, errmsg) = _validate_interface_option(attr, valuestr, addrfam) if attrname == 'address' and 'address' in iface_dict: if 'addresses' not in iface_dict: iface_dict['addresses'] = [] # depends on [control=['if'], data=['iface_dict']] iface_dict['addresses'].append(value) # depends on [control=['if'], data=[]] else: iface_dict[attrname] = value # depends on [control=['if'], data=[]] elif attr in _REV_ETHTOOL_CONFIG_OPTS: if 'ethtool' not in iface_dict: iface_dict['ethtool'] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['iface_dict']] iface_dict['ethtool'][attr] = valuestr # depends on [control=['if'], data=['attr']] elif attr.startswith('bond'): opt = re.split('[_-]', attr, maxsplit=1)[1] if 'bonding' not in iface_dict: iface_dict['bonding'] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['iface_dict']] iface_dict['bonding'][opt] = valuestr # depends on [control=['if'], data=[]] elif attr.startswith('bridge'): opt = re.split('[_-]', attr, maxsplit=1)[1] if 'bridging' not in iface_dict: iface_dict['bridging'] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['iface_dict']] iface_dict['bridging'][opt] = valuestr # depends on [control=['if'], data=[]] elif attr in ['up', 'pre-up', 'post-up', 'down', 'pre-down', 'post-down']: cmd = valuestr cmd_key = '{0}_cmds'.format(re.sub('-', '_', attr)) if cmd_key not in iface_dict: iface_dict[cmd_key] = [] # depends on [control=['if'], data=['cmd_key', 'iface_dict']] iface_dict[cmd_key].append(cmd) # depends on [control=['if'], data=['attr']] # depends on [control=['if'], data=[]] elif line.startswith('auto'): for word in line.split()[1:]: if word not in adapters: adapters[word] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['word', 'adapters']] adapters[word]['enabled'] = True # depends on [control=['for'], data=['word']] # depends on [control=['if'], data=[]] elif line.startswith('allow-hotplug'): for word in line.split()[1:]: if word not in adapters: adapters[word] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['word', 'adapters']] adapters[word]['hotplug'] = True # depends on [control=['for'], data=['word']] # depends on [control=['if'], data=[]] elif line.startswith('source'): if 'source' not in adapters: adapters['source'] = salt.utils.odict.OrderedDict() # depends on [control=['if'], data=['adapters']] # Create item in dict, if not already there if 'data' not in adapters['source']: adapters['source']['data'] = salt.utils.odict.OrderedDict() adapters['source']['data']['sources'] = [] # depends on [control=['if'], data=[]] adapters['source']['data']['sources'].append(line.split()[1]) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] # depends on [control=['with'], data=['interfaces']] # depends on [control=['for'], data=['interface_file']] # Return a sorted list of the keys for bond, bridge and ethtool options to # ensure a consistent order for iface_name in adapters: if iface_name == 'source': continue # depends on [control=['if'], data=[]] if 'data' not in adapters[iface_name]: msg = 'Interface file malformed for interface: {0}.'.format(iface_name) log.error(msg) adapters.pop(iface_name) continue # depends on [control=['if'], data=[]] for opt in ['ethtool', 'bonding', 'bridging']: for inet in ['inet', 'inet6']: if inet in adapters[iface_name]['data']: if opt in adapters[iface_name]['data'][inet]: opt_keys = sorted(adapters[iface_name]['data'][inet][opt].keys()) adapters[iface_name]['data'][inet][opt + '_keys'] = opt_keys # depends on [control=['if'], data=['opt']] # depends on [control=['if'], data=['inet']] # depends on [control=['for'], data=['inet']] # depends on [control=['for'], data=['opt']] # depends on [control=['for'], data=['iface_name']] return adapters
def _fill_instance_child(xmldoc, element_name, return_type): '''Converts a child of the current dom element to the specified type. ''' element = xmldoc.find(_get_serialization_name(element_name)) if element is None: return None return_obj = return_type() _ETreeXmlToObject._fill_data_to_return_object(element, return_obj) return return_obj
def function[_fill_instance_child, parameter[xmldoc, element_name, return_type]]: constant[Converts a child of the current dom element to the specified type. ] variable[element] assign[=] call[name[xmldoc].find, parameter[call[name[_get_serialization_name], parameter[name[element_name]]]]] if compare[name[element] is constant[None]] begin[:] return[constant[None]] variable[return_obj] assign[=] call[name[return_type], parameter[]] call[name[_ETreeXmlToObject]._fill_data_to_return_object, parameter[name[element], name[return_obj]]] return[name[return_obj]]
keyword[def] identifier[_fill_instance_child] ( identifier[xmldoc] , identifier[element_name] , identifier[return_type] ): literal[string] identifier[element] = identifier[xmldoc] . identifier[find] ( identifier[_get_serialization_name] ( identifier[element_name] )) keyword[if] identifier[element] keyword[is] keyword[None] : keyword[return] keyword[None] identifier[return_obj] = identifier[return_type] () identifier[_ETreeXmlToObject] . identifier[_fill_data_to_return_object] ( identifier[element] , identifier[return_obj] ) keyword[return] identifier[return_obj]
def _fill_instance_child(xmldoc, element_name, return_type): """Converts a child of the current dom element to the specified type. """ element = xmldoc.find(_get_serialization_name(element_name)) if element is None: return None # depends on [control=['if'], data=[]] return_obj = return_type() _ETreeXmlToObject._fill_data_to_return_object(element, return_obj) return return_obj
def scheme_specification(cls): """ :meth:`.WSchemeHandler.scheme_specification` method implementation """ return WSchemeSpecification( cls.scheme_name(), WURIComponentVerifier(WURI.Component.username, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.password, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.hostname, WURIComponentVerifier.Requirement.required), WURIComponentVerifier(WURI.Component.port, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.path, WURIComponentVerifier.Requirement.optional), WURIQueryVerifier( WURIComponentVerifier.Requirement.optional, WStrictURIQuery.ParameterSpecification( 'remote_path', nullable=False, multiple=False, optional=False ), extra_parameters=False ) )
def function[scheme_specification, parameter[cls]]: constant[ :meth:`.WSchemeHandler.scheme_specification` method implementation ] return[call[name[WSchemeSpecification], parameter[call[name[cls].scheme_name, parameter[]], call[name[WURIComponentVerifier], parameter[name[WURI].Component.username, name[WURIComponentVerifier].Requirement.optional]], call[name[WURIComponentVerifier], parameter[name[WURI].Component.password, name[WURIComponentVerifier].Requirement.optional]], call[name[WURIComponentVerifier], parameter[name[WURI].Component.hostname, name[WURIComponentVerifier].Requirement.required]], call[name[WURIComponentVerifier], parameter[name[WURI].Component.port, name[WURIComponentVerifier].Requirement.optional]], call[name[WURIComponentVerifier], parameter[name[WURI].Component.path, name[WURIComponentVerifier].Requirement.optional]], call[name[WURIQueryVerifier], parameter[name[WURIComponentVerifier].Requirement.optional, call[name[WStrictURIQuery].ParameterSpecification, parameter[constant[remote_path]]]]]]]]
keyword[def] identifier[scheme_specification] ( identifier[cls] ): literal[string] keyword[return] identifier[WSchemeSpecification] ( identifier[cls] . identifier[scheme_name] (), identifier[WURIComponentVerifier] ( identifier[WURI] . identifier[Component] . identifier[username] , identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[optional] ), identifier[WURIComponentVerifier] ( identifier[WURI] . identifier[Component] . identifier[password] , identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[optional] ), identifier[WURIComponentVerifier] ( identifier[WURI] . identifier[Component] . identifier[hostname] , identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[required] ), identifier[WURIComponentVerifier] ( identifier[WURI] . identifier[Component] . identifier[port] , identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[optional] ), identifier[WURIComponentVerifier] ( identifier[WURI] . identifier[Component] . identifier[path] , identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[optional] ), identifier[WURIQueryVerifier] ( identifier[WURIComponentVerifier] . identifier[Requirement] . identifier[optional] , identifier[WStrictURIQuery] . identifier[ParameterSpecification] ( literal[string] , identifier[nullable] = keyword[False] , identifier[multiple] = keyword[False] , identifier[optional] = keyword[False] ), identifier[extra_parameters] = keyword[False] ) )
def scheme_specification(cls): """ :meth:`.WSchemeHandler.scheme_specification` method implementation """ return WSchemeSpecification(cls.scheme_name(), WURIComponentVerifier(WURI.Component.username, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.password, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.hostname, WURIComponentVerifier.Requirement.required), WURIComponentVerifier(WURI.Component.port, WURIComponentVerifier.Requirement.optional), WURIComponentVerifier(WURI.Component.path, WURIComponentVerifier.Requirement.optional), WURIQueryVerifier(WURIComponentVerifier.Requirement.optional, WStrictURIQuery.ParameterSpecification('remote_path', nullable=False, multiple=False, optional=False), extra_parameters=False))
def intersperse(e, iterable, n=1): """Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [1, 2, None, 3, 4, None, 5] """ if n == 0: raise ValueError('n must be > 0') elif n == 1: # interleave(repeat(e), iterable) -> e, x_0, e, e, x_1, e, x_2... # islice(..., 1, None) -> x_0, e, e, x_1, e, x_2... return islice(interleave(repeat(e), iterable), 1, None) else: # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]... # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]... # flatten(...) -> x_0, x_1, e, x_2, x_3... filler = repeat([e]) chunks = chunked(iterable, n) return flatten(islice(interleave(filler, chunks), 1, None))
def function[intersperse, parameter[e, iterable, n]]: constant[Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [1, 2, None, 3, 4, None, 5] ] if compare[name[n] equal[==] constant[0]] begin[:] <ast.Raise object at 0x7da2054a7a90>
keyword[def] identifier[intersperse] ( identifier[e] , identifier[iterable] , identifier[n] = literal[int] ): literal[string] keyword[if] identifier[n] == literal[int] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[elif] identifier[n] == literal[int] : keyword[return] identifier[islice] ( identifier[interleave] ( identifier[repeat] ( identifier[e] ), identifier[iterable] ), literal[int] , keyword[None] ) keyword[else] : identifier[filler] = identifier[repeat] ([ identifier[e] ]) identifier[chunks] = identifier[chunked] ( identifier[iterable] , identifier[n] ) keyword[return] identifier[flatten] ( identifier[islice] ( identifier[interleave] ( identifier[filler] , identifier[chunks] ), literal[int] , keyword[None] ))
def intersperse(e, iterable, n=1): """Intersperse filler element *e* among the items in *iterable*, leaving *n* items between each filler element. >>> list(intersperse('!', [1, 2, 3, 4, 5])) [1, '!', 2, '!', 3, '!', 4, '!', 5] >>> list(intersperse(None, [1, 2, 3, 4, 5], n=2)) [1, 2, None, 3, 4, None, 5] """ if n == 0: raise ValueError('n must be > 0') # depends on [control=['if'], data=[]] elif n == 1: # interleave(repeat(e), iterable) -> e, x_0, e, e, x_1, e, x_2... # islice(..., 1, None) -> x_0, e, e, x_1, e, x_2... return islice(interleave(repeat(e), iterable), 1, None) # depends on [control=['if'], data=[]] else: # interleave(filler, chunks) -> [e], [x_0, x_1], [e], [x_2, x_3]... # islice(..., 1, None) -> [x_0, x_1], [e], [x_2, x_3]... # flatten(...) -> x_0, x_1, e, x_2, x_3... filler = repeat([e]) chunks = chunked(iterable, n) return flatten(islice(interleave(filler, chunks), 1, None))
def link_for_image(self, base_dir: str, conf: Config) -> int: """Link all artifacts required for a Docker image under `base_dir` and return the number of linked artifacts.""" return self.link_types( base_dir, [ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py], conf)
def function[link_for_image, parameter[self, base_dir, conf]]: constant[Link all artifacts required for a Docker image under `base_dir` and return the number of linked artifacts.] return[call[name[self].link_types, parameter[name[base_dir], list[[<ast.Attribute object at 0x7da20e955300>, <ast.Attribute object at 0x7da20e9546d0>, <ast.Attribute object at 0x7da20e954910>]], name[conf]]]]
keyword[def] identifier[link_for_image] ( identifier[self] , identifier[base_dir] : identifier[str] , identifier[conf] : identifier[Config] )-> identifier[int] : literal[string] keyword[return] identifier[self] . identifier[link_types] ( identifier[base_dir] , [ identifier[ArtifactType] . identifier[app] , identifier[ArtifactType] . identifier[binary] , identifier[ArtifactType] . identifier[gen_py] ], identifier[conf] )
def link_for_image(self, base_dir: str, conf: Config) -> int: """Link all artifacts required for a Docker image under `base_dir` and return the number of linked artifacts.""" return self.link_types(base_dir, [ArtifactType.app, ArtifactType.binary, ArtifactType.gen_py], conf)
def at_time(cls, at, target): """ Construct a DelayedCommand to come due at `at`, where `at` may be a datetime or timestamp. """ at = cls._from_timestamp(at) cmd = cls.from_datetime(at) cmd.delay = at - now() cmd.target = target return cmd
def function[at_time, parameter[cls, at, target]]: constant[ Construct a DelayedCommand to come due at `at`, where `at` may be a datetime or timestamp. ] variable[at] assign[=] call[name[cls]._from_timestamp, parameter[name[at]]] variable[cmd] assign[=] call[name[cls].from_datetime, parameter[name[at]]] name[cmd].delay assign[=] binary_operation[name[at] - call[name[now], parameter[]]] name[cmd].target assign[=] name[target] return[name[cmd]]
keyword[def] identifier[at_time] ( identifier[cls] , identifier[at] , identifier[target] ): literal[string] identifier[at] = identifier[cls] . identifier[_from_timestamp] ( identifier[at] ) identifier[cmd] = identifier[cls] . identifier[from_datetime] ( identifier[at] ) identifier[cmd] . identifier[delay] = identifier[at] - identifier[now] () identifier[cmd] . identifier[target] = identifier[target] keyword[return] identifier[cmd]
def at_time(cls, at, target): """ Construct a DelayedCommand to come due at `at`, where `at` may be a datetime or timestamp. """ at = cls._from_timestamp(at) cmd = cls.from_datetime(at) cmd.delay = at - now() cmd.target = target return cmd
def isStochastic(matrix): """Check that ``matrix`` is row stochastic. Returns ======= is_stochastic : bool ``True`` if ``matrix`` is row stochastic, ``False`` otherwise. """ try: absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0]))) except AttributeError: matrix = _np.array(matrix) absdiff = (_np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0]))) return (absdiff.max() <= 10*_np.spacing(_np.float64(1)))
def function[isStochastic, parameter[matrix]]: constant[Check that ``matrix`` is row stochastic. Returns ======= is_stochastic : bool ``True`` if ``matrix`` is row stochastic, ``False`` otherwise. ] <ast.Try object at 0x7da2044c1fc0> return[compare[call[name[absdiff].max, parameter[]] less_or_equal[<=] binary_operation[constant[10] * call[name[_np].spacing, parameter[call[name[_np].float64, parameter[constant[1]]]]]]]]
keyword[def] identifier[isStochastic] ( identifier[matrix] ): literal[string] keyword[try] : identifier[absdiff] =( identifier[_np] . identifier[abs] ( identifier[matrix] . identifier[sum] ( identifier[axis] = literal[int] )- identifier[_np] . identifier[ones] ( identifier[matrix] . identifier[shape] [ literal[int] ]))) keyword[except] identifier[AttributeError] : identifier[matrix] = identifier[_np] . identifier[array] ( identifier[matrix] ) identifier[absdiff] =( identifier[_np] . identifier[abs] ( identifier[matrix] . identifier[sum] ( identifier[axis] = literal[int] )- identifier[_np] . identifier[ones] ( identifier[matrix] . identifier[shape] [ literal[int] ]))) keyword[return] ( identifier[absdiff] . identifier[max] ()<= literal[int] * identifier[_np] . identifier[spacing] ( identifier[_np] . identifier[float64] ( literal[int] )))
def isStochastic(matrix): """Check that ``matrix`` is row stochastic. Returns ======= is_stochastic : bool ``True`` if ``matrix`` is row stochastic, ``False`` otherwise. """ try: absdiff = _np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])) # depends on [control=['try'], data=[]] except AttributeError: matrix = _np.array(matrix) absdiff = _np.abs(matrix.sum(axis=1) - _np.ones(matrix.shape[0])) # depends on [control=['except'], data=[]] return absdiff.max() <= 10 * _np.spacing(_np.float64(1))
def _compile_int(self): """Time Domain Simulation routine execution""" string = '"""\n' # evaluate the algebraic equations g string += 'system.dae.init_fg(resetz=False)\n' for gcall, call in zip(self.gcall, self.gcalls): if gcall: string += call string += '\n' string += 'system.dae.reset_small_g()\n' # handle islands string += self.gisland # evaluate differential equations f for fcall, call in zip(self.fcall, self.fcalls): if fcall: string += call string += 'system.dae.reset_small_f()\n' string += '\n' fg_string = string + '"""' self.int_fg = compile(eval(fg_string), '', 'exec') # rebuild constant Jacobian elements if needed string += 'if system.dae.factorize:\n' string += ' system.dae.init_jac0()\n' for jac0, call in zip(self.jac0, self.jac0s): if jac0: string += ' ' + call string += ' system.dae.temp_to_spmatrix(\'jac0\')\n' # evaluate Jacobians Gy and Fx string += 'system.dae.setup_FxGy()\n' for gycall, call in zip(self.gycall, self.gycalls): if gycall: string += call string += '\n' for fxcall, call in zip(self.fxcall, self.fxcalls): if fxcall: string += call string += self.gyisland string += 'system.dae.temp_to_spmatrix(\'jac\')\n' string += '"""' if SHOW_INT_CALL: logger.debug(string) self.int = compile(eval(string), '', 'exec')
def function[_compile_int, parameter[self]]: constant[Time Domain Simulation routine execution] variable[string] assign[=] constant[""" ] <ast.AugAssign object at 0x7da18f09cf70> for taget[tuple[[<ast.Name object at 0x7da18f09d930>, <ast.Name object at 0x7da18f09d330>]]] in starred[call[name[zip], parameter[name[self].gcall, name[self].gcalls]]] begin[:] if name[gcall] begin[:] <ast.AugAssign object at 0x7da18f09c760> <ast.AugAssign object at 0x7da18f09f970> <ast.AugAssign object at 0x7da18f09f160> <ast.AugAssign object at 0x7da18f09d450> for taget[tuple[[<ast.Name object at 0x7da18f09c8e0>, <ast.Name object at 0x7da18f09c9d0>]]] in starred[call[name[zip], parameter[name[self].fcall, name[self].fcalls]]] begin[:] if name[fcall] begin[:] <ast.AugAssign object at 0x7da18f09cc70> <ast.AugAssign object at 0x7da18f09f340> <ast.AugAssign object at 0x7da18f09c4f0> variable[fg_string] assign[=] binary_operation[name[string] + constant["""]] name[self].int_fg assign[=] call[name[compile], parameter[call[name[eval], parameter[name[fg_string]]], constant[], constant[exec]]] <ast.AugAssign object at 0x7da18f00eef0> <ast.AugAssign object at 0x7da18f00c580> for taget[tuple[[<ast.Name object at 0x7da18f00ec80>, <ast.Name object at 0x7da18f00e6b0>]]] in starred[call[name[zip], parameter[name[self].jac0, name[self].jac0s]]] begin[:] if name[jac0] begin[:] <ast.AugAssign object at 0x7da18f09fe80> <ast.AugAssign object at 0x7da18f09cb80> <ast.AugAssign object at 0x7da18f09ee60> for taget[tuple[[<ast.Name object at 0x7da18f09f850>, <ast.Name object at 0x7da18f09e560>]]] in starred[call[name[zip], parameter[name[self].gycall, name[self].gycalls]]] begin[:] if name[gycall] begin[:] <ast.AugAssign object at 0x7da18f09c9a0> <ast.AugAssign object at 0x7da18f09cc10> for taget[tuple[[<ast.Name object at 0x7da18f09dd80>, <ast.Name object at 0x7da18f09d300>]]] in starred[call[name[zip], parameter[name[self].fxcall, name[self].fxcalls]]] begin[:] if name[fxcall] begin[:] <ast.AugAssign object at 0x7da18f09d210> <ast.AugAssign object at 0x7da18f09ce50> <ast.AugAssign object at 0x7da18f09c100> <ast.AugAssign object at 0x7da18f09f580> if name[SHOW_INT_CALL] begin[:] call[name[logger].debug, parameter[name[string]]] name[self].int assign[=] call[name[compile], parameter[call[name[eval], parameter[name[string]]], constant[], constant[exec]]]
keyword[def] identifier[_compile_int] ( identifier[self] ): literal[string] identifier[string] = literal[string] identifier[string] += literal[string] keyword[for] identifier[gcall] , identifier[call] keyword[in] identifier[zip] ( identifier[self] . identifier[gcall] , identifier[self] . identifier[gcalls] ): keyword[if] identifier[gcall] : identifier[string] += identifier[call] identifier[string] += literal[string] identifier[string] += literal[string] identifier[string] += identifier[self] . identifier[gisland] keyword[for] identifier[fcall] , identifier[call] keyword[in] identifier[zip] ( identifier[self] . identifier[fcall] , identifier[self] . identifier[fcalls] ): keyword[if] identifier[fcall] : identifier[string] += identifier[call] identifier[string] += literal[string] identifier[string] += literal[string] identifier[fg_string] = identifier[string] + literal[string] identifier[self] . identifier[int_fg] = identifier[compile] ( identifier[eval] ( identifier[fg_string] ), literal[string] , literal[string] ) identifier[string] += literal[string] identifier[string] += literal[string] keyword[for] identifier[jac0] , identifier[call] keyword[in] identifier[zip] ( identifier[self] . identifier[jac0] , identifier[self] . identifier[jac0s] ): keyword[if] identifier[jac0] : identifier[string] += literal[string] + identifier[call] identifier[string] += literal[string] identifier[string] += literal[string] keyword[for] identifier[gycall] , identifier[call] keyword[in] identifier[zip] ( identifier[self] . identifier[gycall] , identifier[self] . identifier[gycalls] ): keyword[if] identifier[gycall] : identifier[string] += identifier[call] identifier[string] += literal[string] keyword[for] identifier[fxcall] , identifier[call] keyword[in] identifier[zip] ( identifier[self] . identifier[fxcall] , identifier[self] . identifier[fxcalls] ): keyword[if] identifier[fxcall] : identifier[string] += identifier[call] identifier[string] += identifier[self] . identifier[gyisland] identifier[string] += literal[string] identifier[string] += literal[string] keyword[if] identifier[SHOW_INT_CALL] : identifier[logger] . identifier[debug] ( identifier[string] ) identifier[self] . identifier[int] = identifier[compile] ( identifier[eval] ( identifier[string] ), literal[string] , literal[string] )
def _compile_int(self): """Time Domain Simulation routine execution""" string = '"""\n' # evaluate the algebraic equations g string += 'system.dae.init_fg(resetz=False)\n' for (gcall, call) in zip(self.gcall, self.gcalls): if gcall: string += call # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] string += '\n' string += 'system.dae.reset_small_g()\n' # handle islands string += self.gisland # evaluate differential equations f for (fcall, call) in zip(self.fcall, self.fcalls): if fcall: string += call # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] string += 'system.dae.reset_small_f()\n' string += '\n' fg_string = string + '"""' self.int_fg = compile(eval(fg_string), '', 'exec') # rebuild constant Jacobian elements if needed string += 'if system.dae.factorize:\n' string += ' system.dae.init_jac0()\n' for (jac0, call) in zip(self.jac0, self.jac0s): if jac0: string += ' ' + call # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] string += " system.dae.temp_to_spmatrix('jac0')\n" # evaluate Jacobians Gy and Fx string += 'system.dae.setup_FxGy()\n' for (gycall, call) in zip(self.gycall, self.gycalls): if gycall: string += call # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] string += '\n' for (fxcall, call) in zip(self.fxcall, self.fxcalls): if fxcall: string += call # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] string += self.gyisland string += "system.dae.temp_to_spmatrix('jac')\n" string += '"""' if SHOW_INT_CALL: logger.debug(string) # depends on [control=['if'], data=[]] self.int = compile(eval(string), '', 'exec')
def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.""" return BipartiteGraph(((n1, n2), v) for (n1, n2), v in self._edges.items() if n1 != edge[0] and n2 != edge[1])
def function[without_nodes, parameter[self, edge]]: constant[Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.] return[call[name[BipartiteGraph], parameter[<ast.GeneratorExp object at 0x7da1b2344070>]]]
keyword[def] identifier[without_nodes] ( identifier[self] , identifier[edge] : identifier[Edge] )-> literal[string] : literal[string] keyword[return] identifier[BipartiteGraph] ((( identifier[n1] , identifier[n2] ), identifier[v] ) keyword[for] ( identifier[n1] , identifier[n2] ), identifier[v] keyword[in] identifier[self] . identifier[_edges] . identifier[items] () keyword[if] identifier[n1] != identifier[edge] [ literal[int] ] keyword[and] identifier[n2] != identifier[edge] [ literal[int] ])
def without_nodes(self, edge: Edge) -> 'BipartiteGraph[TLeft, TRight, TEdgeValue]': """Returns a copy of this bipartite graph with the given edge and its adjacent nodes removed.""" return BipartiteGraph((((n1, n2), v) for ((n1, n2), v) in self._edges.items() if n1 != edge[0] and n2 != edge[1]))
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='\"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): """ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line """ # Pandas argument compatibility if "sep" in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] if "quotechar" in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] if "doublequote" in kwargs: double_quote = kwargs['doublequote'] del kwargs['doublequote'] if "lineterminator" in kwargs: line_terminator = kwargs['lineterminator'] del kwargs['lineterminator'] if len(kwargs) > 0: raise TypeError("Unexpected keyword arguments " + str(list(kwargs.keys()))) write_csv_options = {} write_csv_options['delimiter'] = delimiter write_csv_options['escape_char'] = escape_char write_csv_options['double_quote'] = double_quote write_csv_options['quote_char'] = quote_char if quote_level == csv.QUOTE_MINIMAL: write_csv_options['quote_level'] = 0 elif quote_level == csv.QUOTE_ALL: write_csv_options['quote_level'] = 1 elif quote_level == csv.QUOTE_NONNUMERIC: write_csv_options['quote_level'] = 2 elif quote_level == csv.QUOTE_NONE: write_csv_options['quote_level'] = 3 write_csv_options['header'] = header write_csv_options['line_terminator'] = line_terminator write_csv_options['na_value'] = na_rep write_csv_options['file_header'] = file_header write_csv_options['file_footer'] = file_footer write_csv_options['line_prefix'] = line_prefix # undocumented option. Disables line prefix on the first value line write_csv_options['_no_prefix_on_first_value'] = _no_prefix_on_first_value url = _make_internal_url(filename) self.__proxy__.save_as_csv(url, write_csv_options)
def function[export_csv, parameter[self, filename, delimiter, line_terminator, header, quote_level, double_quote, escape_char, quote_char, na_rep, file_header, file_footer, line_prefix, _no_prefix_on_first_value]]: constant[ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line ] if compare[constant[sep] in name[kwargs]] begin[:] variable[delimiter] assign[=] call[name[kwargs]][constant[sep]] <ast.Delete object at 0x7da1b2048e80> if compare[constant[quotechar] in name[kwargs]] begin[:] variable[quote_char] assign[=] call[name[kwargs]][constant[quotechar]] <ast.Delete object at 0x7da1b2049810> if compare[constant[doublequote] in name[kwargs]] begin[:] variable[double_quote] assign[=] call[name[kwargs]][constant[doublequote]] <ast.Delete object at 0x7da1b204a800> if compare[constant[lineterminator] in name[kwargs]] begin[:] variable[line_terminator] assign[=] call[name[kwargs]][constant[lineterminator]] <ast.Delete object at 0x7da1b204b0a0> if compare[call[name[len], parameter[name[kwargs]]] greater[>] constant[0]] begin[:] <ast.Raise object at 0x7da1b204ab60> variable[write_csv_options] assign[=] dictionary[[], []] call[name[write_csv_options]][constant[delimiter]] assign[=] name[delimiter] call[name[write_csv_options]][constant[escape_char]] assign[=] name[escape_char] call[name[write_csv_options]][constant[double_quote]] assign[=] name[double_quote] call[name[write_csv_options]][constant[quote_char]] assign[=] name[quote_char] if compare[name[quote_level] equal[==] name[csv].QUOTE_MINIMAL] begin[:] call[name[write_csv_options]][constant[quote_level]] assign[=] constant[0] call[name[write_csv_options]][constant[header]] assign[=] name[header] call[name[write_csv_options]][constant[line_terminator]] assign[=] name[line_terminator] call[name[write_csv_options]][constant[na_value]] assign[=] name[na_rep] call[name[write_csv_options]][constant[file_header]] assign[=] name[file_header] call[name[write_csv_options]][constant[file_footer]] assign[=] name[file_footer] call[name[write_csv_options]][constant[line_prefix]] assign[=] name[line_prefix] call[name[write_csv_options]][constant[_no_prefix_on_first_value]] assign[=] name[_no_prefix_on_first_value] variable[url] assign[=] call[name[_make_internal_url], parameter[name[filename]]] call[name[self].__proxy__.save_as_csv, parameter[name[url], name[write_csv_options]]]
keyword[def] identifier[export_csv] ( identifier[self] , identifier[filename] , identifier[delimiter] = literal[string] , identifier[line_terminator] = literal[string] , identifier[header] = keyword[True] , identifier[quote_level] = identifier[csv] . identifier[QUOTE_NONNUMERIC] , identifier[double_quote] = keyword[True] , identifier[escape_char] = literal[string] , identifier[quote_char] = literal[string] , identifier[na_rep] = literal[string] , identifier[file_header] = literal[string] , identifier[file_footer] = literal[string] , identifier[line_prefix] = literal[string] , identifier[_no_prefix_on_first_value] = keyword[False] ,** identifier[kwargs] ): literal[string] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[delimiter] = identifier[kwargs] [ literal[string] ] keyword[del] identifier[kwargs] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[quote_char] = identifier[kwargs] [ literal[string] ] keyword[del] identifier[kwargs] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[double_quote] = identifier[kwargs] [ literal[string] ] keyword[del] identifier[kwargs] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[kwargs] : identifier[line_terminator] = identifier[kwargs] [ literal[string] ] keyword[del] identifier[kwargs] [ literal[string] ] keyword[if] identifier[len] ( identifier[kwargs] )> literal[int] : keyword[raise] identifier[TypeError] ( literal[string] + identifier[str] ( identifier[list] ( identifier[kwargs] . identifier[keys] ()))) identifier[write_csv_options] ={} identifier[write_csv_options] [ literal[string] ]= identifier[delimiter] identifier[write_csv_options] [ literal[string] ]= identifier[escape_char] identifier[write_csv_options] [ literal[string] ]= identifier[double_quote] identifier[write_csv_options] [ literal[string] ]= identifier[quote_char] keyword[if] identifier[quote_level] == identifier[csv] . identifier[QUOTE_MINIMAL] : identifier[write_csv_options] [ literal[string] ]= literal[int] keyword[elif] identifier[quote_level] == identifier[csv] . identifier[QUOTE_ALL] : identifier[write_csv_options] [ literal[string] ]= literal[int] keyword[elif] identifier[quote_level] == identifier[csv] . identifier[QUOTE_NONNUMERIC] : identifier[write_csv_options] [ literal[string] ]= literal[int] keyword[elif] identifier[quote_level] == identifier[csv] . identifier[QUOTE_NONE] : identifier[write_csv_options] [ literal[string] ]= literal[int] identifier[write_csv_options] [ literal[string] ]= identifier[header] identifier[write_csv_options] [ literal[string] ]= identifier[line_terminator] identifier[write_csv_options] [ literal[string] ]= identifier[na_rep] identifier[write_csv_options] [ literal[string] ]= identifier[file_header] identifier[write_csv_options] [ literal[string] ]= identifier[file_footer] identifier[write_csv_options] [ literal[string] ]= identifier[line_prefix] identifier[write_csv_options] [ literal[string] ]= identifier[_no_prefix_on_first_value] identifier[url] = identifier[_make_internal_url] ( identifier[filename] ) identifier[self] . identifier[__proxy__] . identifier[save_as_csv] ( identifier[url] , identifier[write_csv_options] )
def export_csv(self, filename, delimiter=',', line_terminator='\n', header=True, quote_level=csv.QUOTE_NONNUMERIC, double_quote=True, escape_char='\\', quote_char='"', na_rep='', file_header='', file_footer='', line_prefix='', _no_prefix_on_first_value=False, **kwargs): """ Writes an SFrame to a CSV file. Parameters ---------- filename : string The location to save the CSV. delimiter : string, optional This describes the delimiter used for writing csv files. line_terminator: string, optional The newline character header : bool, optional If true, the column names are emitted as a header. quote_level: csv.QUOTE_ALL | csv.QUOTE_NONE | csv.QUOTE_NONNUMERIC, optional The quoting level. If csv.QUOTE_ALL, every field is quoted. if csv.quote_NONE, no field is quoted. If csv.QUOTE_NONNUMERIC, only non-numeric fileds are quoted. csv.QUOTE_MINIMAL is interpreted as csv.QUOTE_NONNUMERIC. double_quote : bool, optional If True, quotes are escaped as two consecutive quotes escape_char : string, optional Character which begins a C escape sequence quote_char: string, optional Character used to quote fields na_rep: string, optional The value used to denote a missing value. file_header: string, optional A string printed to the start of the file file_footer: string, optional A string printed to the end of the file line_prefix: string, optional A string printed at the start of each value line """ # Pandas argument compatibility if 'sep' in kwargs: delimiter = kwargs['sep'] del kwargs['sep'] # depends on [control=['if'], data=['kwargs']] if 'quotechar' in kwargs: quote_char = kwargs['quotechar'] del kwargs['quotechar'] # depends on [control=['if'], data=['kwargs']] if 'doublequote' in kwargs: double_quote = kwargs['doublequote'] del kwargs['doublequote'] # depends on [control=['if'], data=['kwargs']] if 'lineterminator' in kwargs: line_terminator = kwargs['lineterminator'] del kwargs['lineterminator'] # depends on [control=['if'], data=['kwargs']] if len(kwargs) > 0: raise TypeError('Unexpected keyword arguments ' + str(list(kwargs.keys()))) # depends on [control=['if'], data=[]] write_csv_options = {} write_csv_options['delimiter'] = delimiter write_csv_options['escape_char'] = escape_char write_csv_options['double_quote'] = double_quote write_csv_options['quote_char'] = quote_char if quote_level == csv.QUOTE_MINIMAL: write_csv_options['quote_level'] = 0 # depends on [control=['if'], data=[]] elif quote_level == csv.QUOTE_ALL: write_csv_options['quote_level'] = 1 # depends on [control=['if'], data=[]] elif quote_level == csv.QUOTE_NONNUMERIC: write_csv_options['quote_level'] = 2 # depends on [control=['if'], data=[]] elif quote_level == csv.QUOTE_NONE: write_csv_options['quote_level'] = 3 # depends on [control=['if'], data=[]] write_csv_options['header'] = header write_csv_options['line_terminator'] = line_terminator write_csv_options['na_value'] = na_rep write_csv_options['file_header'] = file_header write_csv_options['file_footer'] = file_footer write_csv_options['line_prefix'] = line_prefix # undocumented option. Disables line prefix on the first value line write_csv_options['_no_prefix_on_first_value'] = _no_prefix_on_first_value url = _make_internal_url(filename) self.__proxy__.save_as_csv(url, write_csv_options)
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_fcoe_port_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list") fcoe_intf_fcoe_port_id = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id") fcoe_intf_fcoe_port_id.text = kwargs.pop('fcoe_intf_fcoe_port_id') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_fcoe_port_id, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[fcoe_get_interface] assign[=] call[name[ET].Element, parameter[constant[fcoe_get_interface]]] variable[config] assign[=] name[fcoe_get_interface] variable[output] assign[=] call[name[ET].SubElement, parameter[name[fcoe_get_interface], constant[output]]] variable[fcoe_intf_list] assign[=] call[name[ET].SubElement, parameter[name[output], constant[fcoe-intf-list]]] variable[fcoe_intf_fcoe_port_id] assign[=] call[name[ET].SubElement, parameter[name[fcoe_intf_list], constant[fcoe-intf-fcoe-port-id]]] name[fcoe_intf_fcoe_port_id].text assign[=] call[name[kwargs].pop, parameter[constant[fcoe_intf_fcoe_port_id]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_fcoe_port_id] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[fcoe_get_interface] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[config] = identifier[fcoe_get_interface] identifier[output] = identifier[ET] . identifier[SubElement] ( identifier[fcoe_get_interface] , literal[string] ) identifier[fcoe_intf_list] = identifier[ET] . identifier[SubElement] ( identifier[output] , literal[string] ) identifier[fcoe_intf_fcoe_port_id] = identifier[ET] . identifier[SubElement] ( identifier[fcoe_intf_list] , literal[string] ) identifier[fcoe_intf_fcoe_port_id] . 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 fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_fcoe_port_id(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') fcoe_get_interface = ET.Element('fcoe_get_interface') config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, 'output') fcoe_intf_list = ET.SubElement(output, 'fcoe-intf-list') fcoe_intf_fcoe_port_id = ET.SubElement(fcoe_intf_list, 'fcoe-intf-fcoe-port-id') fcoe_intf_fcoe_port_id.text = kwargs.pop('fcoe_intf_fcoe_port_id') callback = kwargs.pop('callback', self._callback) return callback(config)
def create_embeded_pkcs7_signature(data, cert, key): """ Creates an embeded ("nodetached") pkcs7 signature. This is equivalent to the output of:: openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data :type data: bytes :type cert: str :type key: str """ # noqa: E501 assert isinstance(data, bytes) assert isinstance(cert, str) try: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) except crypto.Error as e: raise exceptions.CorruptCertificate from e bio_in = crypto._new_mem_buf(data) pkcs7 = crypto._lib.PKCS7_sign( signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS ) bio_out = crypto._new_mem_buf() crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7) signed_data = crypto._bio_to_string(bio_out) return signed_data
def function[create_embeded_pkcs7_signature, parameter[data, cert, key]]: constant[ Creates an embeded ("nodetached") pkcs7 signature. This is equivalent to the output of:: openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data :type data: bytes :type cert: str :type key: str ] assert[call[name[isinstance], parameter[name[data], name[bytes]]]] assert[call[name[isinstance], parameter[name[cert], name[str]]]] <ast.Try object at 0x7da1b1a1c6a0> variable[bio_in] assign[=] call[name[crypto]._new_mem_buf, parameter[name[data]]] variable[pkcs7] assign[=] call[name[crypto]._lib.PKCS7_sign, parameter[name[signcert]._x509, name[pkey]._pkey, name[crypto]._ffi.NULL, name[bio_in], name[PKCS7_NOSIGS]]] variable[bio_out] assign[=] call[name[crypto]._new_mem_buf, parameter[]] call[name[crypto]._lib.i2d_PKCS7_bio, parameter[name[bio_out], name[pkcs7]]] variable[signed_data] assign[=] call[name[crypto]._bio_to_string, parameter[name[bio_out]]] return[name[signed_data]]
keyword[def] identifier[create_embeded_pkcs7_signature] ( identifier[data] , identifier[cert] , identifier[key] ): literal[string] keyword[assert] identifier[isinstance] ( identifier[data] , identifier[bytes] ) keyword[assert] identifier[isinstance] ( identifier[cert] , identifier[str] ) keyword[try] : identifier[pkey] = identifier[crypto] . identifier[load_privatekey] ( identifier[crypto] . identifier[FILETYPE_PEM] , identifier[key] ) identifier[signcert] = identifier[crypto] . identifier[load_certificate] ( identifier[crypto] . identifier[FILETYPE_PEM] , identifier[cert] ) keyword[except] identifier[crypto] . identifier[Error] keyword[as] identifier[e] : keyword[raise] identifier[exceptions] . identifier[CorruptCertificate] keyword[from] identifier[e] identifier[bio_in] = identifier[crypto] . identifier[_new_mem_buf] ( identifier[data] ) identifier[pkcs7] = identifier[crypto] . identifier[_lib] . identifier[PKCS7_sign] ( identifier[signcert] . identifier[_x509] , identifier[pkey] . identifier[_pkey] , identifier[crypto] . identifier[_ffi] . identifier[NULL] , identifier[bio_in] , identifier[PKCS7_NOSIGS] ) identifier[bio_out] = identifier[crypto] . identifier[_new_mem_buf] () identifier[crypto] . identifier[_lib] . identifier[i2d_PKCS7_bio] ( identifier[bio_out] , identifier[pkcs7] ) identifier[signed_data] = identifier[crypto] . identifier[_bio_to_string] ( identifier[bio_out] ) keyword[return] identifier[signed_data]
def create_embeded_pkcs7_signature(data, cert, key): """ Creates an embeded ("nodetached") pkcs7 signature. This is equivalent to the output of:: openssl smime -sign -signer cert -inkey key -outform DER -nodetach < data :type data: bytes :type cert: str :type key: str """ # noqa: E501 assert isinstance(data, bytes) assert isinstance(cert, str) try: pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key) signcert = crypto.load_certificate(crypto.FILETYPE_PEM, cert) # depends on [control=['try'], data=[]] except crypto.Error as e: raise exceptions.CorruptCertificate from e # depends on [control=['except'], data=['e']] bio_in = crypto._new_mem_buf(data) pkcs7 = crypto._lib.PKCS7_sign(signcert._x509, pkey._pkey, crypto._ffi.NULL, bio_in, PKCS7_NOSIGS) bio_out = crypto._new_mem_buf() crypto._lib.i2d_PKCS7_bio(bio_out, pkcs7) signed_data = crypto._bio_to_string(bio_out) return signed_data
def send_file(self, filename, status=200): """ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) """ if isinstance(filename, Path) and sys.version_info >= (3, 5): self.message = filename.read_bytes() else: with io.FileIO(str(filename)) as f: self.message = f.read() self.status_code = status self.send_headers() self.write() self.write_eof()
def function[send_file, parameter[self, filename, status]]: constant[ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) ] if <ast.BoolOp object at 0x7da18bcc9ae0> begin[:] name[self].message assign[=] call[name[filename].read_bytes, parameter[]] name[self].status_code assign[=] name[status] call[name[self].send_headers, parameter[]] call[name[self].write, parameter[]] call[name[self].write_eof, parameter[]]
keyword[def] identifier[send_file] ( identifier[self] , identifier[filename] , identifier[status] = literal[int] ): literal[string] keyword[if] identifier[isinstance] ( identifier[filename] , identifier[Path] ) keyword[and] identifier[sys] . identifier[version_info] >=( literal[int] , literal[int] ): identifier[self] . identifier[message] = identifier[filename] . identifier[read_bytes] () keyword[else] : keyword[with] identifier[io] . identifier[FileIO] ( identifier[str] ( identifier[filename] )) keyword[as] identifier[f] : identifier[self] . identifier[message] = identifier[f] . identifier[read] () identifier[self] . identifier[status_code] = identifier[status] identifier[self] . identifier[send_headers] () identifier[self] . identifier[write] () identifier[self] . identifier[write_eof] ()
def send_file(self, filename, status=200): """ Reads in the file 'filename' and sends bytes to client Parameters ---------- filename : str Filename of the file to read status : int, optional The HTTP status code, defaults to 200 (OK) """ if isinstance(filename, Path) and sys.version_info >= (3, 5): self.message = filename.read_bytes() # depends on [control=['if'], data=[]] else: with io.FileIO(str(filename)) as f: self.message = f.read() # depends on [control=['with'], data=['f']] self.status_code = status self.send_headers() self.write() self.write_eof()
def extent_location(self): # type: () -> int ''' A method to get the extent location of this UDF NSR Volume Structure. Parameters: None. Returns: Integer extent location of this UDF NSR Volume Structure. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF NSR Volume Structure not yet initialized') if self.new_extent_loc < 0: return self.orig_extent_loc return self.new_extent_loc
def function[extent_location, parameter[self]]: constant[ A method to get the extent location of this UDF NSR Volume Structure. Parameters: None. Returns: Integer extent location of this UDF NSR Volume Structure. ] if <ast.UnaryOp object at 0x7da20e956ad0> begin[:] <ast.Raise object at 0x7da20e955720> if compare[name[self].new_extent_loc less[<] constant[0]] begin[:] return[name[self].orig_extent_loc] return[name[self].new_extent_loc]
keyword[def] identifier[extent_location] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[_initialized] : keyword[raise] identifier[pycdlibexception] . identifier[PyCdlibInternalError] ( literal[string] ) keyword[if] identifier[self] . identifier[new_extent_loc] < literal[int] : keyword[return] identifier[self] . identifier[orig_extent_loc] keyword[return] identifier[self] . identifier[new_extent_loc]
def extent_location(self): # type: () -> int '\n A method to get the extent location of this UDF NSR Volume Structure.\n\n Parameters:\n None.\n Returns:\n Integer extent location of this UDF NSR Volume Structure.\n ' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('UDF NSR Volume Structure not yet initialized') # depends on [control=['if'], data=[]] if self.new_extent_loc < 0: return self.orig_extent_loc # depends on [control=['if'], data=[]] return self.new_extent_loc
def constraint_stats(self,primarylist=None): """Returns information about effect of constraints on population. :param primarylist: List of constraint names that you want specific information on (i.e., not blended within "multiple constraints".) :return: ``dict`` of what percentage of population is ruled out by each constraint, including a "multiple constraints" entry. """ if primarylist is None: primarylist = [] n = len(self.stars) primaryOK = np.ones(n).astype(bool) tot_reject = np.zeros(n) for name in self.constraints: if name in self.selectfrac_skip: continue c = self.constraints[name] if name in primarylist: primaryOK &= c.ok tot_reject += ~c.ok primary_rejected = ~primaryOK secondary_rejected = tot_reject - primary_rejected lone_reject = {} for name in self.constraints: if name in primarylist or name in self.selectfrac_skip: continue c = self.constraints[name] lone_reject[name] = ((secondary_rejected==1) & (~primary_rejected) & (~c.ok)).sum()/float(n) mult_rejected = (secondary_rejected > 1) & (~primary_rejected) not_rejected = ~(tot_reject.astype(bool)) primary_reject_pct = primary_rejected.sum()/float(n) mult_reject_pct = mult_rejected.sum()/float(n) not_reject_pct = not_rejected.sum()/float(n) tot = 0 results = {} results['pri'] = primary_reject_pct tot += primary_reject_pct for name in lone_reject: results[name] = lone_reject[name] tot += lone_reject[name] results['multiple constraints'] = mult_reject_pct tot += mult_reject_pct results['remaining'] = not_reject_pct tot += not_reject_pct if tot != 1: logging.warning('total adds up to: %.2f (%s)' % (tot,self.model)) return results
def function[constraint_stats, parameter[self, primarylist]]: constant[Returns information about effect of constraints on population. :param primarylist: List of constraint names that you want specific information on (i.e., not blended within "multiple constraints".) :return: ``dict`` of what percentage of population is ruled out by each constraint, including a "multiple constraints" entry. ] if compare[name[primarylist] is constant[None]] begin[:] variable[primarylist] assign[=] list[[]] variable[n] assign[=] call[name[len], parameter[name[self].stars]] variable[primaryOK] assign[=] call[call[name[np].ones, parameter[name[n]]].astype, parameter[name[bool]]] variable[tot_reject] assign[=] call[name[np].zeros, parameter[name[n]]] for taget[name[name]] in starred[name[self].constraints] begin[:] if compare[name[name] in name[self].selectfrac_skip] begin[:] continue variable[c] assign[=] call[name[self].constraints][name[name]] if compare[name[name] in name[primarylist]] begin[:] <ast.AugAssign object at 0x7da1b265ad40> <ast.AugAssign object at 0x7da1b265b7f0> variable[primary_rejected] assign[=] <ast.UnaryOp object at 0x7da1b265b520> variable[secondary_rejected] assign[=] binary_operation[name[tot_reject] - name[primary_rejected]] variable[lone_reject] assign[=] dictionary[[], []] for taget[name[name]] in starred[name[self].constraints] begin[:] if <ast.BoolOp object at 0x7da1b28f3220> begin[:] continue variable[c] assign[=] call[name[self].constraints][name[name]] call[name[lone_reject]][name[name]] assign[=] binary_operation[call[binary_operation[binary_operation[compare[name[secondary_rejected] equal[==] constant[1]] <ast.BitAnd object at 0x7da2590d6b60> <ast.UnaryOp object at 0x7da1b26597e0>] <ast.BitAnd object at 0x7da2590d6b60> <ast.UnaryOp object at 0x7da1b265a800>].sum, parameter[]] / call[name[float], parameter[name[n]]]] variable[mult_rejected] assign[=] binary_operation[compare[name[secondary_rejected] greater[>] constant[1]] <ast.BitAnd object at 0x7da2590d6b60> <ast.UnaryOp object at 0x7da1b2658d90>] variable[not_rejected] assign[=] <ast.UnaryOp object at 0x7da1b265b010> variable[primary_reject_pct] assign[=] binary_operation[call[name[primary_rejected].sum, parameter[]] / call[name[float], parameter[name[n]]]] variable[mult_reject_pct] assign[=] binary_operation[call[name[mult_rejected].sum, parameter[]] / call[name[float], parameter[name[n]]]] variable[not_reject_pct] assign[=] binary_operation[call[name[not_rejected].sum, parameter[]] / call[name[float], parameter[name[n]]]] variable[tot] assign[=] constant[0] variable[results] assign[=] dictionary[[], []] call[name[results]][constant[pri]] assign[=] name[primary_reject_pct] <ast.AugAssign object at 0x7da1b265bfa0> for taget[name[name]] in starred[name[lone_reject]] begin[:] call[name[results]][name[name]] assign[=] call[name[lone_reject]][name[name]] <ast.AugAssign object at 0x7da1b26d49a0> call[name[results]][constant[multiple constraints]] assign[=] name[mult_reject_pct] <ast.AugAssign object at 0x7da1b26d40d0> call[name[results]][constant[remaining]] assign[=] name[not_reject_pct] <ast.AugAssign object at 0x7da1b26d5ab0> if compare[name[tot] not_equal[!=] constant[1]] begin[:] call[name[logging].warning, parameter[binary_operation[constant[total adds up to: %.2f (%s)] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b26d75b0>, <ast.Attribute object at 0x7da1b26d50f0>]]]]] return[name[results]]
keyword[def] identifier[constraint_stats] ( identifier[self] , identifier[primarylist] = keyword[None] ): literal[string] keyword[if] identifier[primarylist] keyword[is] keyword[None] : identifier[primarylist] =[] identifier[n] = identifier[len] ( identifier[self] . identifier[stars] ) identifier[primaryOK] = identifier[np] . identifier[ones] ( identifier[n] ). identifier[astype] ( identifier[bool] ) identifier[tot_reject] = identifier[np] . identifier[zeros] ( identifier[n] ) keyword[for] identifier[name] keyword[in] identifier[self] . identifier[constraints] : keyword[if] identifier[name] keyword[in] identifier[self] . identifier[selectfrac_skip] : keyword[continue] identifier[c] = identifier[self] . identifier[constraints] [ identifier[name] ] keyword[if] identifier[name] keyword[in] identifier[primarylist] : identifier[primaryOK] &= identifier[c] . identifier[ok] identifier[tot_reject] +=~ identifier[c] . identifier[ok] identifier[primary_rejected] =~ identifier[primaryOK] identifier[secondary_rejected] = identifier[tot_reject] - identifier[primary_rejected] identifier[lone_reject] ={} keyword[for] identifier[name] keyword[in] identifier[self] . identifier[constraints] : keyword[if] identifier[name] keyword[in] identifier[primarylist] keyword[or] identifier[name] keyword[in] identifier[self] . identifier[selectfrac_skip] : keyword[continue] identifier[c] = identifier[self] . identifier[constraints] [ identifier[name] ] identifier[lone_reject] [ identifier[name] ]=(( identifier[secondary_rejected] == literal[int] )&(~ identifier[primary_rejected] )&(~ identifier[c] . identifier[ok] )). identifier[sum] ()/ identifier[float] ( identifier[n] ) identifier[mult_rejected] =( identifier[secondary_rejected] > literal[int] )&(~ identifier[primary_rejected] ) identifier[not_rejected] =~( identifier[tot_reject] . identifier[astype] ( identifier[bool] )) identifier[primary_reject_pct] = identifier[primary_rejected] . identifier[sum] ()/ identifier[float] ( identifier[n] ) identifier[mult_reject_pct] = identifier[mult_rejected] . identifier[sum] ()/ identifier[float] ( identifier[n] ) identifier[not_reject_pct] = identifier[not_rejected] . identifier[sum] ()/ identifier[float] ( identifier[n] ) identifier[tot] = literal[int] identifier[results] ={} identifier[results] [ literal[string] ]= identifier[primary_reject_pct] identifier[tot] += identifier[primary_reject_pct] keyword[for] identifier[name] keyword[in] identifier[lone_reject] : identifier[results] [ identifier[name] ]= identifier[lone_reject] [ identifier[name] ] identifier[tot] += identifier[lone_reject] [ identifier[name] ] identifier[results] [ literal[string] ]= identifier[mult_reject_pct] identifier[tot] += identifier[mult_reject_pct] identifier[results] [ literal[string] ]= identifier[not_reject_pct] identifier[tot] += identifier[not_reject_pct] keyword[if] identifier[tot] != literal[int] : identifier[logging] . identifier[warning] ( literal[string] %( identifier[tot] , identifier[self] . identifier[model] )) keyword[return] identifier[results]
def constraint_stats(self, primarylist=None): """Returns information about effect of constraints on population. :param primarylist: List of constraint names that you want specific information on (i.e., not blended within "multiple constraints".) :return: ``dict`` of what percentage of population is ruled out by each constraint, including a "multiple constraints" entry. """ if primarylist is None: primarylist = [] # depends on [control=['if'], data=['primarylist']] n = len(self.stars) primaryOK = np.ones(n).astype(bool) tot_reject = np.zeros(n) for name in self.constraints: if name in self.selectfrac_skip: continue # depends on [control=['if'], data=[]] c = self.constraints[name] if name in primarylist: primaryOK &= c.ok # depends on [control=['if'], data=[]] tot_reject += ~c.ok # depends on [control=['for'], data=['name']] primary_rejected = ~primaryOK secondary_rejected = tot_reject - primary_rejected lone_reject = {} for name in self.constraints: if name in primarylist or name in self.selectfrac_skip: continue # depends on [control=['if'], data=[]] c = self.constraints[name] lone_reject[name] = ((secondary_rejected == 1) & ~primary_rejected & ~c.ok).sum() / float(n) # depends on [control=['for'], data=['name']] mult_rejected = (secondary_rejected > 1) & ~primary_rejected not_rejected = ~tot_reject.astype(bool) primary_reject_pct = primary_rejected.sum() / float(n) mult_reject_pct = mult_rejected.sum() / float(n) not_reject_pct = not_rejected.sum() / float(n) tot = 0 results = {} results['pri'] = primary_reject_pct tot += primary_reject_pct for name in lone_reject: results[name] = lone_reject[name] tot += lone_reject[name] # depends on [control=['for'], data=['name']] results['multiple constraints'] = mult_reject_pct tot += mult_reject_pct results['remaining'] = not_reject_pct tot += not_reject_pct if tot != 1: logging.warning('total adds up to: %.2f (%s)' % (tot, self.model)) # depends on [control=['if'], data=['tot']] return results
def _is_non_public_numeric_address(host): """ returns True if 'host' is not public """ # for numeric hostnames, skip RFC1918 addresses, since no Tor exit # node will be able to reach those. Likewise ignore IPv6 addresses. try: a = ipaddress.ip_address(six.text_type(host)) except ValueError: return False # non-numeric, let Tor try it if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved \ or a.is_unspecified: return True # too weird, don't connect return False
def function[_is_non_public_numeric_address, parameter[host]]: constant[ returns True if 'host' is not public ] <ast.Try object at 0x7da1b07f72b0> if <ast.BoolOp object at 0x7da1b07f63b0> begin[:] return[constant[True]] return[constant[False]]
keyword[def] identifier[_is_non_public_numeric_address] ( identifier[host] ): literal[string] keyword[try] : identifier[a] = identifier[ipaddress] . identifier[ip_address] ( identifier[six] . identifier[text_type] ( identifier[host] )) keyword[except] identifier[ValueError] : keyword[return] keyword[False] keyword[if] identifier[a] . identifier[is_loopback] keyword[or] identifier[a] . identifier[is_multicast] keyword[or] identifier[a] . identifier[is_private] keyword[or] identifier[a] . identifier[is_reserved] keyword[or] identifier[a] . identifier[is_unspecified] : keyword[return] keyword[True] keyword[return] keyword[False]
def _is_non_public_numeric_address(host): """ returns True if 'host' is not public """ # for numeric hostnames, skip RFC1918 addresses, since no Tor exit # node will be able to reach those. Likewise ignore IPv6 addresses. try: a = ipaddress.ip_address(six.text_type(host)) # depends on [control=['try'], data=[]] except ValueError: return False # non-numeric, let Tor try it # depends on [control=['except'], data=[]] if a.is_loopback or a.is_multicast or a.is_private or a.is_reserved or a.is_unspecified: return True # too weird, don't connect # depends on [control=['if'], data=[]] return False
def convert_to_shape(self, origin_x=0, origin_y=0): """Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. Note that this method may be called more than once to add multiple shapes of the same geometry in different locations on the slide. """ sp = self._add_freeform_sp(origin_x, origin_y) path = self._start_path(sp) for drawing_operation in self: drawing_operation.apply_operation_to(path) return self._shapes._shape_factory(sp)
def function[convert_to_shape, parameter[self, origin_x, origin_y]]: constant[Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. Note that this method may be called more than once to add multiple shapes of the same geometry in different locations on the slide. ] variable[sp] assign[=] call[name[self]._add_freeform_sp, parameter[name[origin_x], name[origin_y]]] variable[path] assign[=] call[name[self]._start_path, parameter[name[sp]]] for taget[name[drawing_operation]] in starred[name[self]] begin[:] call[name[drawing_operation].apply_operation_to, parameter[name[path]]] return[call[name[self]._shapes._shape_factory, parameter[name[sp]]]]
keyword[def] identifier[convert_to_shape] ( identifier[self] , identifier[origin_x] = literal[int] , identifier[origin_y] = literal[int] ): literal[string] identifier[sp] = identifier[self] . identifier[_add_freeform_sp] ( identifier[origin_x] , identifier[origin_y] ) identifier[path] = identifier[self] . identifier[_start_path] ( identifier[sp] ) keyword[for] identifier[drawing_operation] keyword[in] identifier[self] : identifier[drawing_operation] . identifier[apply_operation_to] ( identifier[path] ) keyword[return] identifier[self] . identifier[_shapes] . identifier[_shape_factory] ( identifier[sp] )
def convert_to_shape(self, origin_x=0, origin_y=0): """Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. Note that this method may be called more than once to add multiple shapes of the same geometry in different locations on the slide. """ sp = self._add_freeform_sp(origin_x, origin_y) path = self._start_path(sp) for drawing_operation in self: drawing_operation.apply_operation_to(path) # depends on [control=['for'], data=['drawing_operation']] return self._shapes._shape_factory(sp)
def init ( self, parent ): """ Finishes initialising the editor by creating the underlying toolkit widget. """ self._graph = graph = Graph() ui = graph.edit_traits(parent=parent, kind="panel") self.control = ui.control
def function[init, parameter[self, parent]]: constant[ Finishes initialising the editor by creating the underlying toolkit widget. ] name[self]._graph assign[=] call[name[Graph], parameter[]] variable[ui] assign[=] call[name[graph].edit_traits, parameter[]] name[self].control assign[=] name[ui].control
keyword[def] identifier[init] ( identifier[self] , identifier[parent] ): literal[string] identifier[self] . identifier[_graph] = identifier[graph] = identifier[Graph] () identifier[ui] = identifier[graph] . identifier[edit_traits] ( identifier[parent] = identifier[parent] , identifier[kind] = literal[string] ) identifier[self] . identifier[control] = identifier[ui] . identifier[control]
def init(self, parent): """ Finishes initialising the editor by creating the underlying toolkit widget. """ self._graph = graph = Graph() ui = graph.edit_traits(parent=parent, kind='panel') self.control = ui.control
def get_tile_locations_by_gid(self, gid): """ Search map for tile locations by the GID Return (int, int, int) tuples, where the layer is index of the visible tile layers. Note: Not a fast operation. Cache results if used often. :param gid: GID to be searched for :rtype: generator of tile locations """ for l in self.visible_tile_layers: for x, y, _gid in [i for i in self.layers[l].iter_data() if i[2] == gid]: yield x, y, l
def function[get_tile_locations_by_gid, parameter[self, gid]]: constant[ Search map for tile locations by the GID Return (int, int, int) tuples, where the layer is index of the visible tile layers. Note: Not a fast operation. Cache results if used often. :param gid: GID to be searched for :rtype: generator of tile locations ] for taget[name[l]] in starred[name[self].visible_tile_layers] begin[:] for taget[tuple[[<ast.Name object at 0x7da1b088ef80>, <ast.Name object at 0x7da1b088c850>, <ast.Name object at 0x7da1b088eb00>]]] in starred[<ast.ListComp object at 0x7da1b088f100>] begin[:] <ast.Yield object at 0x7da1b088f970>
keyword[def] identifier[get_tile_locations_by_gid] ( identifier[self] , identifier[gid] ): literal[string] keyword[for] identifier[l] keyword[in] identifier[self] . identifier[visible_tile_layers] : keyword[for] identifier[x] , identifier[y] , identifier[_gid] keyword[in] [ identifier[i] keyword[for] identifier[i] keyword[in] identifier[self] . identifier[layers] [ identifier[l] ]. identifier[iter_data] () keyword[if] identifier[i] [ literal[int] ]== identifier[gid] ]: keyword[yield] identifier[x] , identifier[y] , identifier[l]
def get_tile_locations_by_gid(self, gid): """ Search map for tile locations by the GID Return (int, int, int) tuples, where the layer is index of the visible tile layers. Note: Not a fast operation. Cache results if used often. :param gid: GID to be searched for :rtype: generator of tile locations """ for l in self.visible_tile_layers: for (x, y, _gid) in [i for i in self.layers[l].iter_data() if i[2] == gid]: yield (x, y, l) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['l']]
def find_occurrences(project, resource, offset, unsure=False, resources=None, in_hierarchy=False, task_handle=taskhandle.NullTaskHandle()): """Return a list of `Location`\s If `unsure` is `True`, possible matches are returned, too. You can use `Location.unsure` to see which are unsure occurrences. `resources` can be a list of `rope.base.resource.File`\s that should be searched for occurrences; if `None` all python files in the project are searched. """ name = worder.get_name_at(resource, offset) this_pymodule = project.get_pymodule(resource) primary, pyname = rope.base.evaluate.eval_location2( this_pymodule, offset) def is_match(occurrence): return unsure finder = occurrences.create_finder( project, name, pyname, unsure=is_match, in_hierarchy=in_hierarchy, instance=primary) if resources is None: resources = project.get_python_files() job_set = task_handle.create_jobset('Finding Occurrences', count=len(resources)) return _find_locations(finder, resources, job_set)
def function[find_occurrences, parameter[project, resource, offset, unsure, resources, in_hierarchy, task_handle]]: constant[Return a list of `Location`\s If `unsure` is `True`, possible matches are returned, too. You can use `Location.unsure` to see which are unsure occurrences. `resources` can be a list of `rope.base.resource.File`\s that should be searched for occurrences; if `None` all python files in the project are searched. ] variable[name] assign[=] call[name[worder].get_name_at, parameter[name[resource], name[offset]]] variable[this_pymodule] assign[=] call[name[project].get_pymodule, parameter[name[resource]]] <ast.Tuple object at 0x7da1b0860eb0> assign[=] call[name[rope].base.evaluate.eval_location2, parameter[name[this_pymodule], name[offset]]] def function[is_match, parameter[occurrence]]: return[name[unsure]] variable[finder] assign[=] call[name[occurrences].create_finder, parameter[name[project], name[name], name[pyname]]] if compare[name[resources] is constant[None]] begin[:] variable[resources] assign[=] call[name[project].get_python_files, parameter[]] variable[job_set] assign[=] call[name[task_handle].create_jobset, parameter[constant[Finding Occurrences]]] return[call[name[_find_locations], parameter[name[finder], name[resources], name[job_set]]]]
keyword[def] identifier[find_occurrences] ( identifier[project] , identifier[resource] , identifier[offset] , identifier[unsure] = keyword[False] , identifier[resources] = keyword[None] , identifier[in_hierarchy] = keyword[False] , identifier[task_handle] = identifier[taskhandle] . identifier[NullTaskHandle] ()): literal[string] identifier[name] = identifier[worder] . identifier[get_name_at] ( identifier[resource] , identifier[offset] ) identifier[this_pymodule] = identifier[project] . identifier[get_pymodule] ( identifier[resource] ) identifier[primary] , identifier[pyname] = identifier[rope] . identifier[base] . identifier[evaluate] . identifier[eval_location2] ( identifier[this_pymodule] , identifier[offset] ) keyword[def] identifier[is_match] ( identifier[occurrence] ): keyword[return] identifier[unsure] identifier[finder] = identifier[occurrences] . identifier[create_finder] ( identifier[project] , identifier[name] , identifier[pyname] , identifier[unsure] = identifier[is_match] , identifier[in_hierarchy] = identifier[in_hierarchy] , identifier[instance] = identifier[primary] ) keyword[if] identifier[resources] keyword[is] keyword[None] : identifier[resources] = identifier[project] . identifier[get_python_files] () identifier[job_set] = identifier[task_handle] . identifier[create_jobset] ( literal[string] , identifier[count] = identifier[len] ( identifier[resources] )) keyword[return] identifier[_find_locations] ( identifier[finder] , identifier[resources] , identifier[job_set] )
def find_occurrences(project, resource, offset, unsure=False, resources=None, in_hierarchy=False, task_handle=taskhandle.NullTaskHandle()): """Return a list of `Location`\\s If `unsure` is `True`, possible matches are returned, too. You can use `Location.unsure` to see which are unsure occurrences. `resources` can be a list of `rope.base.resource.File`\\s that should be searched for occurrences; if `None` all python files in the project are searched. """ name = worder.get_name_at(resource, offset) this_pymodule = project.get_pymodule(resource) (primary, pyname) = rope.base.evaluate.eval_location2(this_pymodule, offset) def is_match(occurrence): return unsure finder = occurrences.create_finder(project, name, pyname, unsure=is_match, in_hierarchy=in_hierarchy, instance=primary) if resources is None: resources = project.get_python_files() # depends on [control=['if'], data=['resources']] job_set = task_handle.create_jobset('Finding Occurrences', count=len(resources)) return _find_locations(finder, resources, job_set)
def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None): """ Bulk link users by email. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance request (django.http.request.HttpRequest): HTTP Request instance email_list (iterable): A list of pre-processed email addresses to handle using the form """ errors = [] emails = set() already_linked_emails = [] duplicate_emails = [] csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD] if email_list: parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list] else: parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL}) try: for index, row in enumerate(parsed_csv): email = row[ManageLearnersForm.CsvColumns.EMAIL] try: already_linked = validate_email_to_link(email, ignore_existing=True) except ValidationError as exc: message = _("Error at line {line}: {message}\n").format(line=index + 1, message=exc) errors.append(message) else: if already_linked: already_linked_emails.append((email, already_linked.enterprise_customer)) elif email in emails: duplicate_emails.append(email) else: emails.add(email) except ValidationError as exc: errors.append(exc) if errors: manage_learners_form.add_error( ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED ) for error in errors: manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error) return # There were no errors. Now do the actual linking: for email in emails: EnterpriseCustomerUser.objects.link_user(enterprise_customer, email) # Report what happened: count = len(emails) messages.success(request, ungettext( "{count} new learner was added to {enterprise_customer_name}.", "{count} new learners were added to {enterprise_customer_name}.", count ).format(count=count, enterprise_customer_name=enterprise_customer.name)) this_customer_linked_emails = [ email for email, customer in already_linked_emails if customer == enterprise_customer ] other_customer_linked_emails = [ email for email, __ in already_linked_emails if email not in this_customer_linked_emails ] if this_customer_linked_emails: messages.warning( request, _( "The following learners were already associated with this Enterprise " "Customer: {list_of_emails}" ).format( list_of_emails=", ".join(this_customer_linked_emails) ) ) if other_customer_linked_emails: messages.warning( request, _( "The following learners are already associated with " "another Enterprise Customer. These learners were not " "added to {enterprise_customer_name}: {list_of_emails}" ).format( enterprise_customer_name=enterprise_customer.name, list_of_emails=", ".join(other_customer_linked_emails), ) ) if duplicate_emails: messages.warning( request, _( "The following duplicate email addresses were not added: " "{list_of_emails}" ).format( list_of_emails=", ".join(duplicate_emails) ) ) # Build a list of all the emails that we can act on further; that is, # emails that we either linked to this customer, or that were linked already. all_processable_emails = list(emails) + this_customer_linked_emails return all_processable_emails
def function[_handle_bulk_upload, parameter[cls, enterprise_customer, manage_learners_form, request, email_list]]: constant[ Bulk link users by email. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance request (django.http.request.HttpRequest): HTTP Request instance email_list (iterable): A list of pre-processed email addresses to handle using the form ] variable[errors] assign[=] list[[]] variable[emails] assign[=] call[name[set], parameter[]] variable[already_linked_emails] assign[=] list[[]] variable[duplicate_emails] assign[=] list[[]] variable[csv_file] assign[=] call[name[manage_learners_form].cleaned_data][name[ManageLearnersForm].Fields.BULK_UPLOAD] if name[email_list] begin[:] variable[parsed_csv] assign[=] <ast.ListComp object at 0x7da1b013d390> <ast.Try object at 0x7da1b013e140> if name[errors] begin[:] call[name[manage_learners_form].add_error, parameter[name[ManageLearnersForm].Fields.GENERAL_ERRORS, name[ValidationMessages].BULK_LINK_FAILED]] for taget[name[error]] in starred[name[errors]] begin[:] call[name[manage_learners_form].add_error, parameter[name[ManageLearnersForm].Fields.BULK_UPLOAD, name[error]]] return[None] for taget[name[email]] in starred[name[emails]] begin[:] call[name[EnterpriseCustomerUser].objects.link_user, parameter[name[enterprise_customer], name[email]]] variable[count] assign[=] call[name[len], parameter[name[emails]]] call[name[messages].success, parameter[name[request], call[call[name[ungettext], parameter[constant[{count} new learner was added to {enterprise_customer_name}.], constant[{count} new learners were added to {enterprise_customer_name}.], name[count]]].format, parameter[]]]] variable[this_customer_linked_emails] assign[=] <ast.ListComp object at 0x7da18f09f9a0> variable[other_customer_linked_emails] assign[=] <ast.ListComp object at 0x7da18f09e860> if name[this_customer_linked_emails] begin[:] call[name[messages].warning, parameter[name[request], call[call[name[_], parameter[constant[The following learners were already associated with this Enterprise Customer: {list_of_emails}]]].format, parameter[]]]] if name[other_customer_linked_emails] begin[:] call[name[messages].warning, parameter[name[request], call[call[name[_], parameter[constant[The following learners are already associated with another Enterprise Customer. These learners were not added to {enterprise_customer_name}: {list_of_emails}]]].format, parameter[]]]] if name[duplicate_emails] begin[:] call[name[messages].warning, parameter[name[request], call[call[name[_], parameter[constant[The following duplicate email addresses were not added: {list_of_emails}]]].format, parameter[]]]] variable[all_processable_emails] assign[=] binary_operation[call[name[list], parameter[name[emails]]] + name[this_customer_linked_emails]] return[name[all_processable_emails]]
keyword[def] identifier[_handle_bulk_upload] ( identifier[cls] , identifier[enterprise_customer] , identifier[manage_learners_form] , identifier[request] , identifier[email_list] = keyword[None] ): literal[string] identifier[errors] =[] identifier[emails] = identifier[set] () identifier[already_linked_emails] =[] identifier[duplicate_emails] =[] identifier[csv_file] = identifier[manage_learners_form] . identifier[cleaned_data] [ identifier[ManageLearnersForm] . identifier[Fields] . identifier[BULK_UPLOAD] ] keyword[if] identifier[email_list] : identifier[parsed_csv] =[{ identifier[ManageLearnersForm] . identifier[CsvColumns] . identifier[EMAIL] : identifier[email] } keyword[for] identifier[email] keyword[in] identifier[email_list] ] keyword[else] : identifier[parsed_csv] = identifier[parse_csv] ( identifier[csv_file] , identifier[expected_columns] ={ identifier[ManageLearnersForm] . identifier[CsvColumns] . identifier[EMAIL] }) keyword[try] : keyword[for] identifier[index] , identifier[row] keyword[in] identifier[enumerate] ( identifier[parsed_csv] ): identifier[email] = identifier[row] [ identifier[ManageLearnersForm] . identifier[CsvColumns] . identifier[EMAIL] ] keyword[try] : identifier[already_linked] = identifier[validate_email_to_link] ( identifier[email] , identifier[ignore_existing] = keyword[True] ) keyword[except] identifier[ValidationError] keyword[as] identifier[exc] : identifier[message] = identifier[_] ( literal[string] ). identifier[format] ( identifier[line] = identifier[index] + literal[int] , identifier[message] = identifier[exc] ) identifier[errors] . identifier[append] ( identifier[message] ) keyword[else] : keyword[if] identifier[already_linked] : identifier[already_linked_emails] . identifier[append] (( identifier[email] , identifier[already_linked] . identifier[enterprise_customer] )) keyword[elif] identifier[email] keyword[in] identifier[emails] : identifier[duplicate_emails] . identifier[append] ( identifier[email] ) keyword[else] : identifier[emails] . identifier[add] ( identifier[email] ) keyword[except] identifier[ValidationError] keyword[as] identifier[exc] : identifier[errors] . identifier[append] ( identifier[exc] ) keyword[if] identifier[errors] : identifier[manage_learners_form] . identifier[add_error] ( identifier[ManageLearnersForm] . identifier[Fields] . identifier[GENERAL_ERRORS] , identifier[ValidationMessages] . identifier[BULK_LINK_FAILED] ) keyword[for] identifier[error] keyword[in] identifier[errors] : identifier[manage_learners_form] . identifier[add_error] ( identifier[ManageLearnersForm] . identifier[Fields] . identifier[BULK_UPLOAD] , identifier[error] ) keyword[return] keyword[for] identifier[email] keyword[in] identifier[emails] : identifier[EnterpriseCustomerUser] . identifier[objects] . identifier[link_user] ( identifier[enterprise_customer] , identifier[email] ) identifier[count] = identifier[len] ( identifier[emails] ) identifier[messages] . identifier[success] ( identifier[request] , identifier[ungettext] ( literal[string] , literal[string] , identifier[count] ). identifier[format] ( identifier[count] = identifier[count] , identifier[enterprise_customer_name] = identifier[enterprise_customer] . identifier[name] )) identifier[this_customer_linked_emails] =[ identifier[email] keyword[for] identifier[email] , identifier[customer] keyword[in] identifier[already_linked_emails] keyword[if] identifier[customer] == identifier[enterprise_customer] ] identifier[other_customer_linked_emails] =[ identifier[email] keyword[for] identifier[email] , identifier[__] keyword[in] identifier[already_linked_emails] keyword[if] identifier[email] keyword[not] keyword[in] identifier[this_customer_linked_emails] ] keyword[if] identifier[this_customer_linked_emails] : identifier[messages] . identifier[warning] ( identifier[request] , identifier[_] ( literal[string] literal[string] ). identifier[format] ( identifier[list_of_emails] = literal[string] . identifier[join] ( identifier[this_customer_linked_emails] ) ) ) keyword[if] identifier[other_customer_linked_emails] : identifier[messages] . identifier[warning] ( identifier[request] , identifier[_] ( literal[string] literal[string] literal[string] ). identifier[format] ( identifier[enterprise_customer_name] = identifier[enterprise_customer] . identifier[name] , identifier[list_of_emails] = literal[string] . identifier[join] ( identifier[other_customer_linked_emails] ), ) ) keyword[if] identifier[duplicate_emails] : identifier[messages] . identifier[warning] ( identifier[request] , identifier[_] ( literal[string] literal[string] ). identifier[format] ( identifier[list_of_emails] = literal[string] . identifier[join] ( identifier[duplicate_emails] ) ) ) identifier[all_processable_emails] = identifier[list] ( identifier[emails] )+ identifier[this_customer_linked_emails] keyword[return] identifier[all_processable_emails]
def _handle_bulk_upload(cls, enterprise_customer, manage_learners_form, request, email_list=None): """ Bulk link users by email. Arguments: enterprise_customer (EnterpriseCustomer): learners will be linked to this Enterprise Customer instance manage_learners_form (ManageLearnersForm): bound ManageLearners form instance request (django.http.request.HttpRequest): HTTP Request instance email_list (iterable): A list of pre-processed email addresses to handle using the form """ errors = [] emails = set() already_linked_emails = [] duplicate_emails = [] csv_file = manage_learners_form.cleaned_data[ManageLearnersForm.Fields.BULK_UPLOAD] if email_list: parsed_csv = [{ManageLearnersForm.CsvColumns.EMAIL: email} for email in email_list] # depends on [control=['if'], data=[]] else: parsed_csv = parse_csv(csv_file, expected_columns={ManageLearnersForm.CsvColumns.EMAIL}) try: for (index, row) in enumerate(parsed_csv): email = row[ManageLearnersForm.CsvColumns.EMAIL] try: already_linked = validate_email_to_link(email, ignore_existing=True) # depends on [control=['try'], data=[]] except ValidationError as exc: message = _('Error at line {line}: {message}\n').format(line=index + 1, message=exc) errors.append(message) # depends on [control=['except'], data=['exc']] else: if already_linked: already_linked_emails.append((email, already_linked.enterprise_customer)) # depends on [control=['if'], data=[]] elif email in emails: duplicate_emails.append(email) # depends on [control=['if'], data=['email']] else: emails.add(email) # depends on [control=['for'], data=[]] # depends on [control=['try'], data=[]] except ValidationError as exc: errors.append(exc) # depends on [control=['except'], data=['exc']] if errors: manage_learners_form.add_error(ManageLearnersForm.Fields.GENERAL_ERRORS, ValidationMessages.BULK_LINK_FAILED) for error in errors: manage_learners_form.add_error(ManageLearnersForm.Fields.BULK_UPLOAD, error) # depends on [control=['for'], data=['error']] return # depends on [control=['if'], data=[]] # There were no errors. Now do the actual linking: for email in emails: EnterpriseCustomerUser.objects.link_user(enterprise_customer, email) # depends on [control=['for'], data=['email']] # Report what happened: count = len(emails) messages.success(request, ungettext('{count} new learner was added to {enterprise_customer_name}.', '{count} new learners were added to {enterprise_customer_name}.', count).format(count=count, enterprise_customer_name=enterprise_customer.name)) this_customer_linked_emails = [email for (email, customer) in already_linked_emails if customer == enterprise_customer] other_customer_linked_emails = [email for (email, __) in already_linked_emails if email not in this_customer_linked_emails] if this_customer_linked_emails: messages.warning(request, _('The following learners were already associated with this Enterprise Customer: {list_of_emails}').format(list_of_emails=', '.join(this_customer_linked_emails))) # depends on [control=['if'], data=[]] if other_customer_linked_emails: messages.warning(request, _('The following learners are already associated with another Enterprise Customer. These learners were not added to {enterprise_customer_name}: {list_of_emails}').format(enterprise_customer_name=enterprise_customer.name, list_of_emails=', '.join(other_customer_linked_emails))) # depends on [control=['if'], data=[]] if duplicate_emails: messages.warning(request, _('The following duplicate email addresses were not added: {list_of_emails}').format(list_of_emails=', '.join(duplicate_emails))) # depends on [control=['if'], data=[]] # Build a list of all the emails that we can act on further; that is, # emails that we either linked to this customer, or that were linked already. all_processable_emails = list(emails) + this_customer_linked_emails return all_processable_emails
def xrb_address_to_public_key(address): """ Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i'\ '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :type address: bytes :return: public key in bytes :rtype: bytes :raises ValueError: """ address = bytearray(address, 'ascii') if not address.startswith(b'xrb_'): raise ValueError('address does not start with xrb_: %s' % address) if len(address) != 64: raise ValueError('address must be 64 chars long: %s' % address) address = bytes(address) key_b32xrb = b'1111' + address[4:56] key_bytes = b32xrb_decode(key_b32xrb)[3:] checksum = address[56:] if b32xrb_encode(address_checksum(key_bytes)) != checksum: raise ValueError('invalid address, invalid checksum: %s' % address) return key_bytes
def function[xrb_address_to_public_key, parameter[address]]: constant[ Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i' '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :type address: bytes :return: public key in bytes :rtype: bytes :raises ValueError: ] variable[address] assign[=] call[name[bytearray], parameter[name[address], constant[ascii]]] if <ast.UnaryOp object at 0x7da1b2535cc0> begin[:] <ast.Raise object at 0x7da1b2535d80> if compare[call[name[len], parameter[name[address]]] not_equal[!=] constant[64]] begin[:] <ast.Raise object at 0x7da1b2537c10> variable[address] assign[=] call[name[bytes], parameter[name[address]]] variable[key_b32xrb] assign[=] binary_operation[constant[b'1111'] + call[name[address]][<ast.Slice object at 0x7da1b2537a90>]] variable[key_bytes] assign[=] call[call[name[b32xrb_decode], parameter[name[key_b32xrb]]]][<ast.Slice object at 0x7da1b2537340>] variable[checksum] assign[=] call[name[address]][<ast.Slice object at 0x7da1b2535990>] if compare[call[name[b32xrb_encode], parameter[call[name[address_checksum], parameter[name[key_bytes]]]]] not_equal[!=] name[checksum]] begin[:] <ast.Raise object at 0x7da1b2534a60> return[name[key_bytes]]
keyword[def] identifier[xrb_address_to_public_key] ( identifier[address] ): literal[string] identifier[address] = identifier[bytearray] ( identifier[address] , literal[string] ) keyword[if] keyword[not] identifier[address] . identifier[startswith] ( literal[string] ): keyword[raise] identifier[ValueError] ( literal[string] % identifier[address] ) keyword[if] identifier[len] ( identifier[address] )!= literal[int] : keyword[raise] identifier[ValueError] ( literal[string] % identifier[address] ) identifier[address] = identifier[bytes] ( identifier[address] ) identifier[key_b32xrb] = literal[string] + identifier[address] [ literal[int] : literal[int] ] identifier[key_bytes] = identifier[b32xrb_decode] ( identifier[key_b32xrb] )[ literal[int] :] identifier[checksum] = identifier[address] [ literal[int] :] keyword[if] identifier[b32xrb_encode] ( identifier[address_checksum] ( identifier[key_bytes] ))!= identifier[checksum] : keyword[raise] identifier[ValueError] ( literal[string] % identifier[address] ) keyword[return] identifier[key_bytes]
def xrb_address_to_public_key(address): """ Convert an xrb address to public key in bytes >>> xrb_address_to_public_key('xrb_1e3i81r51e3i81r51e3i81r51e3i' '81r51e3i81r51e3i81r51e3imxssakuq') b'00000000000000000000000000000000' :param address: xrb address :type address: bytes :return: public key in bytes :rtype: bytes :raises ValueError: """ address = bytearray(address, 'ascii') if not address.startswith(b'xrb_'): raise ValueError('address does not start with xrb_: %s' % address) # depends on [control=['if'], data=[]] if len(address) != 64: raise ValueError('address must be 64 chars long: %s' % address) # depends on [control=['if'], data=[]] address = bytes(address) key_b32xrb = b'1111' + address[4:56] key_bytes = b32xrb_decode(key_b32xrb)[3:] checksum = address[56:] if b32xrb_encode(address_checksum(key_bytes)) != checksum: raise ValueError('invalid address, invalid checksum: %s' % address) # depends on [control=['if'], data=[]] return key_bytes
def add_prefix(self, errors, prefix): """Add form prefix to errors""" if not prefix: prefix = self.get_prefix() if prefix: return {"%s-%s" % (prefix, k): v for k, v in errors.items()} return errors
def function[add_prefix, parameter[self, errors, prefix]]: constant[Add form prefix to errors] if <ast.UnaryOp object at 0x7da18f58f9d0> begin[:] variable[prefix] assign[=] call[name[self].get_prefix, parameter[]] if name[prefix] begin[:] return[<ast.DictComp object at 0x7da1b24d4520>] return[name[errors]]
keyword[def] identifier[add_prefix] ( identifier[self] , identifier[errors] , identifier[prefix] ): literal[string] keyword[if] keyword[not] identifier[prefix] : identifier[prefix] = identifier[self] . identifier[get_prefix] () keyword[if] identifier[prefix] : keyword[return] { literal[string] %( identifier[prefix] , identifier[k] ): identifier[v] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[errors] . identifier[items] ()} keyword[return] identifier[errors]
def add_prefix(self, errors, prefix): """Add form prefix to errors""" if not prefix: prefix = self.get_prefix() # depends on [control=['if'], data=[]] if prefix: return {'%s-%s' % (prefix, k): v for (k, v) in errors.items()} # depends on [control=['if'], data=[]] return errors
def _get_user(self, username, attrs=ALL_ATTRS): """Get a user from the ldap""" username = ldap.filter.escape_filter_chars(username) user_filter = self.user_filter_tmpl % { 'username': self._uni(username) } r = self._search(self._byte_p2(user_filter), attrs, self.userdn) if len(r) == 0: return None # if NO_ATTR, only return the DN if attrs == NO_ATTR: dn_entry = r[0][0] # in other cases, return everything (dn + attributes) else: dn_entry = r[0] return dn_entry
def function[_get_user, parameter[self, username, attrs]]: constant[Get a user from the ldap] variable[username] assign[=] call[name[ldap].filter.escape_filter_chars, parameter[name[username]]] variable[user_filter] assign[=] binary_operation[name[self].user_filter_tmpl <ast.Mod object at 0x7da2590d6920> dictionary[[<ast.Constant object at 0x7da20c6c7a30>], [<ast.Call object at 0x7da20c6c53f0>]]] variable[r] assign[=] call[name[self]._search, parameter[call[name[self]._byte_p2, parameter[name[user_filter]]], name[attrs], name[self].userdn]] if compare[call[name[len], parameter[name[r]]] equal[==] constant[0]] begin[:] return[constant[None]] if compare[name[attrs] equal[==] name[NO_ATTR]] begin[:] variable[dn_entry] assign[=] call[call[name[r]][constant[0]]][constant[0]] return[name[dn_entry]]
keyword[def] identifier[_get_user] ( identifier[self] , identifier[username] , identifier[attrs] = identifier[ALL_ATTRS] ): literal[string] identifier[username] = identifier[ldap] . identifier[filter] . identifier[escape_filter_chars] ( identifier[username] ) identifier[user_filter] = identifier[self] . identifier[user_filter_tmpl] %{ literal[string] : identifier[self] . identifier[_uni] ( identifier[username] ) } identifier[r] = identifier[self] . identifier[_search] ( identifier[self] . identifier[_byte_p2] ( identifier[user_filter] ), identifier[attrs] , identifier[self] . identifier[userdn] ) keyword[if] identifier[len] ( identifier[r] )== literal[int] : keyword[return] keyword[None] keyword[if] identifier[attrs] == identifier[NO_ATTR] : identifier[dn_entry] = identifier[r] [ literal[int] ][ literal[int] ] keyword[else] : identifier[dn_entry] = identifier[r] [ literal[int] ] keyword[return] identifier[dn_entry]
def _get_user(self, username, attrs=ALL_ATTRS): """Get a user from the ldap""" username = ldap.filter.escape_filter_chars(username) user_filter = self.user_filter_tmpl % {'username': self._uni(username)} r = self._search(self._byte_p2(user_filter), attrs, self.userdn) if len(r) == 0: return None # depends on [control=['if'], data=[]] # if NO_ATTR, only return the DN if attrs == NO_ATTR: dn_entry = r[0][0] # depends on [control=['if'], data=[]] else: # in other cases, return everything (dn + attributes) dn_entry = r[0] return dn_entry
def make_sshable(c): """ Set up passwordless SSH keypair & authorized_hosts access to localhost. """ user = c.travis.sudo.user home = "~{0}".format(user) # Run sudo() as the new sudo user; means less chown'ing, etc. c.config.sudo.user = user ssh_dir = "{0}/.ssh".format(home) # TODO: worth wrapping in 'sh -c' and using '&&' instead of doing this? for cmd in ("mkdir {0}", "chmod 0700 {0}"): c.sudo(cmd.format(ssh_dir, user)) c.sudo('ssh-keygen -f {0}/id_rsa -N ""'.format(ssh_dir)) c.sudo("cp {0}/{{id_rsa.pub,authorized_keys}}".format(ssh_dir))
def function[make_sshable, parameter[c]]: constant[ Set up passwordless SSH keypair & authorized_hosts access to localhost. ] variable[user] assign[=] name[c].travis.sudo.user variable[home] assign[=] call[constant[~{0}].format, parameter[name[user]]] name[c].config.sudo.user assign[=] name[user] variable[ssh_dir] assign[=] call[constant[{0}/.ssh].format, parameter[name[home]]] for taget[name[cmd]] in starred[tuple[[<ast.Constant object at 0x7da207f9a530>, <ast.Constant object at 0x7da207f98370>]]] begin[:] call[name[c].sudo, parameter[call[name[cmd].format, parameter[name[ssh_dir], name[user]]]]] call[name[c].sudo, parameter[call[constant[ssh-keygen -f {0}/id_rsa -N ""].format, parameter[name[ssh_dir]]]]] call[name[c].sudo, parameter[call[constant[cp {0}/{{id_rsa.pub,authorized_keys}}].format, parameter[name[ssh_dir]]]]]
keyword[def] identifier[make_sshable] ( identifier[c] ): literal[string] identifier[user] = identifier[c] . identifier[travis] . identifier[sudo] . identifier[user] identifier[home] = literal[string] . identifier[format] ( identifier[user] ) identifier[c] . identifier[config] . identifier[sudo] . identifier[user] = identifier[user] identifier[ssh_dir] = literal[string] . identifier[format] ( identifier[home] ) keyword[for] identifier[cmd] keyword[in] ( literal[string] , literal[string] ): identifier[c] . identifier[sudo] ( identifier[cmd] . identifier[format] ( identifier[ssh_dir] , identifier[user] )) identifier[c] . identifier[sudo] ( literal[string] . identifier[format] ( identifier[ssh_dir] )) identifier[c] . identifier[sudo] ( literal[string] . identifier[format] ( identifier[ssh_dir] ))
def make_sshable(c): """ Set up passwordless SSH keypair & authorized_hosts access to localhost. """ user = c.travis.sudo.user home = '~{0}'.format(user) # Run sudo() as the new sudo user; means less chown'ing, etc. c.config.sudo.user = user ssh_dir = '{0}/.ssh'.format(home) # TODO: worth wrapping in 'sh -c' and using '&&' instead of doing this? for cmd in ('mkdir {0}', 'chmod 0700 {0}'): c.sudo(cmd.format(ssh_dir, user)) # depends on [control=['for'], data=['cmd']] c.sudo('ssh-keygen -f {0}/id_rsa -N ""'.format(ssh_dir)) c.sudo('cp {0}/{{id_rsa.pub,authorized_keys}}'.format(ssh_dir))
def get_xrefs_list_from_element(cls, element): """Helper for get_xrefs_list element is a ClassDefItem or MethodDefItem At the end of the function, we lost if we worked on a class or method but we do not care for now. """ xref_items = element.XREFfrom.items log.debug("%d XREFs found" % len(xref_items)) xrefs = [] for xref_item in xref_items: class_ = xref_item[0].get_class_name() method_ = xref_item[0].get_name() descriptor_ = xref_item[0].get_descriptor() xrefs.append(classmethod2display(class_, method_, descriptor_)) return xrefs
def function[get_xrefs_list_from_element, parameter[cls, element]]: constant[Helper for get_xrefs_list element is a ClassDefItem or MethodDefItem At the end of the function, we lost if we worked on a class or method but we do not care for now. ] variable[xref_items] assign[=] name[element].XREFfrom.items call[name[log].debug, parameter[binary_operation[constant[%d XREFs found] <ast.Mod object at 0x7da2590d6920> call[name[len], parameter[name[xref_items]]]]]] variable[xrefs] assign[=] list[[]] for taget[name[xref_item]] in starred[name[xref_items]] begin[:] variable[class_] assign[=] call[call[name[xref_item]][constant[0]].get_class_name, parameter[]] variable[method_] assign[=] call[call[name[xref_item]][constant[0]].get_name, parameter[]] variable[descriptor_] assign[=] call[call[name[xref_item]][constant[0]].get_descriptor, parameter[]] call[name[xrefs].append, parameter[call[name[classmethod2display], parameter[name[class_], name[method_], name[descriptor_]]]]] return[name[xrefs]]
keyword[def] identifier[get_xrefs_list_from_element] ( identifier[cls] , identifier[element] ): literal[string] identifier[xref_items] = identifier[element] . identifier[XREFfrom] . identifier[items] identifier[log] . identifier[debug] ( literal[string] % identifier[len] ( identifier[xref_items] )) identifier[xrefs] =[] keyword[for] identifier[xref_item] keyword[in] identifier[xref_items] : identifier[class_] = identifier[xref_item] [ literal[int] ]. identifier[get_class_name] () identifier[method_] = identifier[xref_item] [ literal[int] ]. identifier[get_name] () identifier[descriptor_] = identifier[xref_item] [ literal[int] ]. identifier[get_descriptor] () identifier[xrefs] . identifier[append] ( identifier[classmethod2display] ( identifier[class_] , identifier[method_] , identifier[descriptor_] )) keyword[return] identifier[xrefs]
def get_xrefs_list_from_element(cls, element): """Helper for get_xrefs_list element is a ClassDefItem or MethodDefItem At the end of the function, we lost if we worked on a class or method but we do not care for now. """ xref_items = element.XREFfrom.items log.debug('%d XREFs found' % len(xref_items)) xrefs = [] for xref_item in xref_items: class_ = xref_item[0].get_class_name() method_ = xref_item[0].get_name() descriptor_ = xref_item[0].get_descriptor() xrefs.append(classmethod2display(class_, method_, descriptor_)) # depends on [control=['for'], data=['xref_item']] return xrefs
def spec_filled(self, pos_args, kw_args): """Check if we have enough arguments to call this function. Args: pos_args (list): A list of all the positional values we have. kw_args (dict): A dict of all of the keyword args we have. Returns: bool: True if we have a filled spec, False otherwise. """ req_names = self.arg_names if len(self.arg_defaults) > 0: req_names = req_names[:-len(self.arg_defaults)] req = [x for x in req_names if x not in kw_args] return len(req) <= len(pos_args)
def function[spec_filled, parameter[self, pos_args, kw_args]]: constant[Check if we have enough arguments to call this function. Args: pos_args (list): A list of all the positional values we have. kw_args (dict): A dict of all of the keyword args we have. Returns: bool: True if we have a filled spec, False otherwise. ] variable[req_names] assign[=] name[self].arg_names if compare[call[name[len], parameter[name[self].arg_defaults]] greater[>] constant[0]] begin[:] variable[req_names] assign[=] call[name[req_names]][<ast.Slice object at 0x7da1b026fc40>] variable[req] assign[=] <ast.ListComp object at 0x7da1b026ca30> return[compare[call[name[len], parameter[name[req]]] less_or_equal[<=] call[name[len], parameter[name[pos_args]]]]]
keyword[def] identifier[spec_filled] ( identifier[self] , identifier[pos_args] , identifier[kw_args] ): literal[string] identifier[req_names] = identifier[self] . identifier[arg_names] keyword[if] identifier[len] ( identifier[self] . identifier[arg_defaults] )> literal[int] : identifier[req_names] = identifier[req_names] [:- identifier[len] ( identifier[self] . identifier[arg_defaults] )] identifier[req] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[req_names] keyword[if] identifier[x] keyword[not] keyword[in] identifier[kw_args] ] keyword[return] identifier[len] ( identifier[req] )<= identifier[len] ( identifier[pos_args] )
def spec_filled(self, pos_args, kw_args): """Check if we have enough arguments to call this function. Args: pos_args (list): A list of all the positional values we have. kw_args (dict): A dict of all of the keyword args we have. Returns: bool: True if we have a filled spec, False otherwise. """ req_names = self.arg_names if len(self.arg_defaults) > 0: req_names = req_names[:-len(self.arg_defaults)] # depends on [control=['if'], data=[]] req = [x for x in req_names if x not in kw_args] return len(req) <= len(pos_args)
def get_context_data(self, **kwargs): """ push data from settings and from the current object, in the current context :param kwargs: :return: """ context = super(UserServiceUpdateView, self).get_context_data(**kwargs) context['service_name_alone'] = self.object.name.name.rsplit('Service')[1] context['service_name'] = self.object.name.name context['SERVICES_AUTH'] = settings.SERVICES_AUTH context['SERVICES_HOSTED_WITH_AUTH'] = settings.SERVICES_HOSTED_WITH_AUTH context['SERVICES_NEUTRAL'] = settings.SERVICES_NEUTRAL context['action'] = 'edit' return context
def function[get_context_data, parameter[self]]: constant[ push data from settings and from the current object, in the current context :param kwargs: :return: ] variable[context] assign[=] call[call[name[super], parameter[name[UserServiceUpdateView], name[self]]].get_context_data, parameter[]] call[name[context]][constant[service_name_alone]] assign[=] call[call[name[self].object.name.name.rsplit, parameter[constant[Service]]]][constant[1]] call[name[context]][constant[service_name]] assign[=] name[self].object.name.name call[name[context]][constant[SERVICES_AUTH]] assign[=] name[settings].SERVICES_AUTH call[name[context]][constant[SERVICES_HOSTED_WITH_AUTH]] assign[=] name[settings].SERVICES_HOSTED_WITH_AUTH call[name[context]][constant[SERVICES_NEUTRAL]] assign[=] name[settings].SERVICES_NEUTRAL call[name[context]][constant[action]] assign[=] constant[edit] return[name[context]]
keyword[def] identifier[get_context_data] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[context] = identifier[super] ( identifier[UserServiceUpdateView] , identifier[self] ). identifier[get_context_data] (** identifier[kwargs] ) identifier[context] [ literal[string] ]= identifier[self] . identifier[object] . identifier[name] . identifier[name] . identifier[rsplit] ( literal[string] )[ literal[int] ] identifier[context] [ literal[string] ]= identifier[self] . identifier[object] . identifier[name] . identifier[name] identifier[context] [ literal[string] ]= identifier[settings] . identifier[SERVICES_AUTH] identifier[context] [ literal[string] ]= identifier[settings] . identifier[SERVICES_HOSTED_WITH_AUTH] identifier[context] [ literal[string] ]= identifier[settings] . identifier[SERVICES_NEUTRAL] identifier[context] [ literal[string] ]= literal[string] keyword[return] identifier[context]
def get_context_data(self, **kwargs): """ push data from settings and from the current object, in the current context :param kwargs: :return: """ context = super(UserServiceUpdateView, self).get_context_data(**kwargs) context['service_name_alone'] = self.object.name.name.rsplit('Service')[1] context['service_name'] = self.object.name.name context['SERVICES_AUTH'] = settings.SERVICES_AUTH context['SERVICES_HOSTED_WITH_AUTH'] = settings.SERVICES_HOSTED_WITH_AUTH context['SERVICES_NEUTRAL'] = settings.SERVICES_NEUTRAL context['action'] = 'edit' return context
def severity_list(self, severity_list): """Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str] """ allowed_values = ["INFO", "SMOKE", "WARN", "SEVERE"] # noqa: E501 if not set(severity_list).issubset(set(allowed_values)): raise ValueError( "Invalid values for `severity_list` [{0}], must be a subset of [{1}]" # noqa: E501 .format(", ".join(map(str, set(severity_list) - set(allowed_values))), # noqa: E501 ", ".join(map(str, allowed_values))) ) self._severity_list = severity_list
def function[severity_list, parameter[self, severity_list]]: constant[Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str] ] variable[allowed_values] assign[=] list[[<ast.Constant object at 0x7da18bc71c90>, <ast.Constant object at 0x7da18bc73520>, <ast.Constant object at 0x7da18bc72e00>, <ast.Constant object at 0x7da18bc72260>]] if <ast.UnaryOp object at 0x7da18bc70040> begin[:] <ast.Raise object at 0x7da18bc73130> name[self]._severity_list assign[=] name[severity_list]
keyword[def] identifier[severity_list] ( identifier[self] , identifier[severity_list] ): literal[string] identifier[allowed_values] =[ literal[string] , literal[string] , literal[string] , literal[string] ] keyword[if] keyword[not] identifier[set] ( identifier[severity_list] ). identifier[issubset] ( identifier[set] ( identifier[allowed_values] )): keyword[raise] identifier[ValueError] ( literal[string] . identifier[format] ( literal[string] . identifier[join] ( identifier[map] ( identifier[str] , identifier[set] ( identifier[severity_list] )- identifier[set] ( identifier[allowed_values] ))), literal[string] . identifier[join] ( identifier[map] ( identifier[str] , identifier[allowed_values] ))) ) identifier[self] . identifier[_severity_list] = identifier[severity_list]
def severity_list(self, severity_list): """Sets the severity_list of this Alert. Alert severity list for multi-threshold type. # noqa: E501 :param severity_list: The severity_list of this Alert. # noqa: E501 :type: list[str] """ allowed_values = ['INFO', 'SMOKE', 'WARN', 'SEVERE'] # noqa: E501 if not set(severity_list).issubset(set(allowed_values)): # noqa: E501 # noqa: E501 raise ValueError('Invalid values for `severity_list` [{0}], must be a subset of [{1}]'.format(', '.join(map(str, set(severity_list) - set(allowed_values))), ', '.join(map(str, allowed_values)))) # depends on [control=['if'], data=[]] self._severity_list = severity_list
def read(cls, data): """Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dataset populated with data. """ if isinstance(data, pd.DataFrame): return cls((json.loads( to_json_stat(data, output='dict', version='2.0'), object_pairs_hook=OrderedDict))) elif isinstance(data, OrderedDict): return cls(data) elif (isinstance(data, basestring) and data.startswith(("http://", "https://", "ftp://", "ftps://"))): # requests will do the rest... return cls(request(data)) elif isinstance(data, basestring): try: json_dict = json.loads(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise else: try: json_dict = json.load(data, object_pairs_hook=OrderedDict) return cls(json_dict) except ValueError: raise
def function[read, parameter[cls, data]]: constant[Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dataset populated with data. ] if call[name[isinstance], parameter[name[data], name[pd].DataFrame]] begin[:] return[call[name[cls], parameter[call[name[json].loads, parameter[call[name[to_json_stat], parameter[name[data]]]]]]]]
keyword[def] identifier[read] ( identifier[cls] , identifier[data] ): literal[string] keyword[if] identifier[isinstance] ( identifier[data] , identifier[pd] . identifier[DataFrame] ): keyword[return] identifier[cls] (( identifier[json] . identifier[loads] ( identifier[to_json_stat] ( identifier[data] , identifier[output] = literal[string] , identifier[version] = literal[string] ), identifier[object_pairs_hook] = identifier[OrderedDict] ))) keyword[elif] identifier[isinstance] ( identifier[data] , identifier[OrderedDict] ): keyword[return] identifier[cls] ( identifier[data] ) keyword[elif] ( identifier[isinstance] ( identifier[data] , identifier[basestring] ) keyword[and] identifier[data] . identifier[startswith] (( literal[string] , literal[string] , literal[string] , literal[string] ))): keyword[return] identifier[cls] ( identifier[request] ( identifier[data] )) keyword[elif] identifier[isinstance] ( identifier[data] , identifier[basestring] ): keyword[try] : identifier[json_dict] = identifier[json] . identifier[loads] ( identifier[data] , identifier[object_pairs_hook] = identifier[OrderedDict] ) keyword[return] identifier[cls] ( identifier[json_dict] ) keyword[except] identifier[ValueError] : keyword[raise] keyword[else] : keyword[try] : identifier[json_dict] = identifier[json] . identifier[load] ( identifier[data] , identifier[object_pairs_hook] = identifier[OrderedDict] ) keyword[return] identifier[cls] ( identifier[json_dict] ) keyword[except] identifier[ValueError] : keyword[raise]
def read(cls, data): """Reads data from URL, Dataframe, JSON string, JSON file or OrderedDict. Args: data: can be a Pandas Dataframe, a JSON file, a JSON string, an OrderedDict or a URL pointing to a JSONstat file. Returns: An object of class Dataset populated with data. """ if isinstance(data, pd.DataFrame): return cls(json.loads(to_json_stat(data, output='dict', version='2.0'), object_pairs_hook=OrderedDict)) # depends on [control=['if'], data=[]] elif isinstance(data, OrderedDict): return cls(data) # depends on [control=['if'], data=[]] elif isinstance(data, basestring) and data.startswith(('http://', 'https://', 'ftp://', 'ftps://')): # requests will do the rest... return cls(request(data)) # depends on [control=['if'], data=[]] elif isinstance(data, basestring): try: json_dict = json.loads(data, object_pairs_hook=OrderedDict) return cls(json_dict) # depends on [control=['try'], data=[]] except ValueError: raise # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] else: try: json_dict = json.load(data, object_pairs_hook=OrderedDict) return cls(json_dict) # depends on [control=['try'], data=[]] except ValueError: raise # depends on [control=['except'], data=[]]
def floordiv(self, other, axis="columns", level=None, fill_value=None): """Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to apply divide over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Divide applied. """ return self._binary_op( "floordiv", other, axis=axis, level=level, fill_value=fill_value )
def function[floordiv, parameter[self, other, axis, level, fill_value]]: constant[Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to apply divide over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Divide applied. ] return[call[name[self]._binary_op, parameter[constant[floordiv], name[other]]]]
keyword[def] identifier[floordiv] ( identifier[self] , identifier[other] , identifier[axis] = literal[string] , identifier[level] = keyword[None] , identifier[fill_value] = keyword[None] ): literal[string] keyword[return] identifier[self] . identifier[_binary_op] ( literal[string] , identifier[other] , identifier[axis] = identifier[axis] , identifier[level] = identifier[level] , identifier[fill_value] = identifier[fill_value] )
def floordiv(self, other, axis='columns', level=None, fill_value=None): """Divides this DataFrame against another DataFrame/Series/scalar. Args: other: The object to use to apply the divide against this. axis: The axis to divide over. level: The Multilevel index level to apply divide over. fill_value: The value to fill NaNs with. Returns: A new DataFrame with the Divide applied. """ return self._binary_op('floordiv', other, axis=axis, level=level, fill_value=fill_value)
def manually_disable_aa_profile(self): """ Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart. """ profile_path = '/etc/apparmor.d' disable_path = '/etc/apparmor.d/disable' if not os.path.lexists(os.path.join(disable_path, self.aa_profile)): os.symlink(os.path.join(profile_path, self.aa_profile), os.path.join(disable_path, self.aa_profile))
def function[manually_disable_aa_profile, parameter[self]]: constant[ Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart. ] variable[profile_path] assign[=] constant[/etc/apparmor.d] variable[disable_path] assign[=] constant[/etc/apparmor.d/disable] if <ast.UnaryOp object at 0x7da1b1249420> begin[:] call[name[os].symlink, parameter[call[name[os].path.join, parameter[name[profile_path], name[self].aa_profile]], call[name[os].path.join, parameter[name[disable_path], name[self].aa_profile]]]]
keyword[def] identifier[manually_disable_aa_profile] ( identifier[self] ): literal[string] identifier[profile_path] = literal[string] identifier[disable_path] = literal[string] keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[lexists] ( identifier[os] . identifier[path] . identifier[join] ( identifier[disable_path] , identifier[self] . identifier[aa_profile] )): identifier[os] . identifier[symlink] ( identifier[os] . identifier[path] . identifier[join] ( identifier[profile_path] , identifier[self] . identifier[aa_profile] ), identifier[os] . identifier[path] . identifier[join] ( identifier[disable_path] , identifier[self] . identifier[aa_profile] ))
def manually_disable_aa_profile(self): """ Manually disable an apparmor profile. If aa-profile-mode is set to disabled (default) this is required as the template has been written but apparmor is yet unaware of the profile and aa-disable aa-profile fails. Without this the profile would kick into enforce mode on the next service restart. """ profile_path = '/etc/apparmor.d' disable_path = '/etc/apparmor.d/disable' if not os.path.lexists(os.path.join(disable_path, self.aa_profile)): os.symlink(os.path.join(profile_path, self.aa_profile), os.path.join(disable_path, self.aa_profile)) # depends on [control=['if'], data=[]]
def parse_report(self, lines, table_names): """ Parse a GATK report https://software.broadinstitute.org/gatk/documentation/article.php?id=1244 Only GATTable entries are parsed. Tables are returned as a dict of tables. Each table is a dict of arrays, where names correspond to column names, and arrays correspond to column values. Args: lines (file handle): an iterable over the lines of a GATK report. table_names (dict): a dict with keys that are GATK report table names (e.g. "#:GATKTable:Quantized:Quality quantization map"), and values that are the keys in the returned dict. Returns: { table_1: { col_1: [ val_1, val_2, ... ] col_2: [ val_1, val_2, ... ] ... } table_2: ... } """ report = dict() lines = (l for l in lines) for line in lines: line = line.rstrip() if line in table_names.keys(): report[table_names[line]] = self.parse_gatk_report_table(lines) return report
def function[parse_report, parameter[self, lines, table_names]]: constant[ Parse a GATK report https://software.broadinstitute.org/gatk/documentation/article.php?id=1244 Only GATTable entries are parsed. Tables are returned as a dict of tables. Each table is a dict of arrays, where names correspond to column names, and arrays correspond to column values. Args: lines (file handle): an iterable over the lines of a GATK report. table_names (dict): a dict with keys that are GATK report table names (e.g. "#:GATKTable:Quantized:Quality quantization map"), and values that are the keys in the returned dict. Returns: { table_1: { col_1: [ val_1, val_2, ... ] col_2: [ val_1, val_2, ... ] ... } table_2: ... } ] variable[report] assign[=] call[name[dict], parameter[]] variable[lines] assign[=] <ast.GeneratorExp object at 0x7da207f9a1a0> for taget[name[line]] in starred[name[lines]] begin[:] variable[line] assign[=] call[name[line].rstrip, parameter[]] if compare[name[line] in call[name[table_names].keys, parameter[]]] begin[:] call[name[report]][call[name[table_names]][name[line]]] assign[=] call[name[self].parse_gatk_report_table, parameter[name[lines]]] return[name[report]]
keyword[def] identifier[parse_report] ( identifier[self] , identifier[lines] , identifier[table_names] ): literal[string] identifier[report] = identifier[dict] () identifier[lines] =( identifier[l] keyword[for] identifier[l] keyword[in] identifier[lines] ) keyword[for] identifier[line] keyword[in] identifier[lines] : identifier[line] = identifier[line] . identifier[rstrip] () keyword[if] identifier[line] keyword[in] identifier[table_names] . identifier[keys] (): identifier[report] [ identifier[table_names] [ identifier[line] ]]= identifier[self] . identifier[parse_gatk_report_table] ( identifier[lines] ) keyword[return] identifier[report]
def parse_report(self, lines, table_names): """ Parse a GATK report https://software.broadinstitute.org/gatk/documentation/article.php?id=1244 Only GATTable entries are parsed. Tables are returned as a dict of tables. Each table is a dict of arrays, where names correspond to column names, and arrays correspond to column values. Args: lines (file handle): an iterable over the lines of a GATK report. table_names (dict): a dict with keys that are GATK report table names (e.g. "#:GATKTable:Quantized:Quality quantization map"), and values that are the keys in the returned dict. Returns: { table_1: { col_1: [ val_1, val_2, ... ] col_2: [ val_1, val_2, ... ] ... } table_2: ... } """ report = dict() lines = (l for l in lines) for line in lines: line = line.rstrip() if line in table_names.keys(): report[table_names[line]] = self.parse_gatk_report_table(lines) # depends on [control=['if'], data=['line']] # depends on [control=['for'], data=['line']] return report
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\\\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\\\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there """ model_structure_grammar = _include_common_grammar(r""" model = (entry / section)+ sketch? entry = element "~" element "~" element ("~" element)? "|" section = element "~" element "|" sketch = ~r".*" #anything # Either an escape group, or a character that is not tilde or pipe element = (escape_group / ~r"[^~|]")* """) parser = parsimonious.Grammar(model_structure_grammar) tree = parser.parse(model_str) class ModelParser(parsimonious.NodeVisitor): def __init__(self, ast): self.entries = [] self.visit(ast) def visit_entry(self, n, vc): units, lims = parse_units(vc[2].strip()) self.entries.append({'eqn': vc[0].strip(), 'unit': units, 'lims': str(lims), 'doc': vc[4].strip(), 'kind': 'entry'}) def visit_section(self, n, vc): if vc[2].strip() != "Simulation Control Parameters": self.entries.append({'eqn': '', 'unit': '', 'lims': '', 'doc': vc[2].strip(), 'kind': 'section'}) def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text or '' return ModelParser(tree).entries
def function[get_model_elements, parameter[model_str]]: constant[ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there ] variable[model_structure_grammar] assign[=] call[name[_include_common_grammar], parameter[constant[ model = (entry / section)+ sketch? entry = element "~" element "~" element ("~" element)? "|" section = element "~" element "|" sketch = ~r".*" #anything # Either an escape group, or a character that is not tilde or pipe element = (escape_group / ~r"[^~|]")* ]]] variable[parser] assign[=] call[name[parsimonious].Grammar, parameter[name[model_structure_grammar]]] variable[tree] assign[=] call[name[parser].parse, parameter[name[model_str]]] class class[ModelParser, parameter[]] begin[:] def function[__init__, parameter[self, ast]]: name[self].entries assign[=] list[[]] call[name[self].visit, parameter[name[ast]]] def function[visit_entry, parameter[self, n, vc]]: <ast.Tuple object at 0x7da2043449a0> assign[=] call[name[parse_units], parameter[call[call[name[vc]][constant[2]].strip, parameter[]]]] call[name[self].entries.append, parameter[dictionary[[<ast.Constant object at 0x7da204346920>, <ast.Constant object at 0x7da204346ce0>, <ast.Constant object at 0x7da2043470d0>, <ast.Constant object at 0x7da204345930>, <ast.Constant object at 0x7da204345540>], [<ast.Call object at 0x7da204345510>, <ast.Name object at 0x7da204345690>, <ast.Call object at 0x7da204347ca0>, <ast.Call object at 0x7da204345120>, <ast.Constant object at 0x7da204346950>]]]] def function[visit_section, parameter[self, n, vc]]: if compare[call[call[name[vc]][constant[2]].strip, parameter[]] not_equal[!=] constant[Simulation Control Parameters]] begin[:] call[name[self].entries.append, parameter[dictionary[[<ast.Constant object at 0x7da204347b50>, <ast.Constant object at 0x7da204347250>, <ast.Constant object at 0x7da2043446a0>, <ast.Constant object at 0x7da204344820>, <ast.Constant object at 0x7da2043451e0>], [<ast.Constant object at 0x7da2043470a0>, <ast.Constant object at 0x7da204344670>, <ast.Constant object at 0x7da204344130>, <ast.Call object at 0x7da204347520>, <ast.Constant object at 0x7da204345150>]]]] def function[generic_visit, parameter[self, n, vc]]: return[<ast.BoolOp object at 0x7da2043479d0>] return[call[name[ModelParser], parameter[name[tree]]].entries]
keyword[def] identifier[get_model_elements] ( identifier[model_str] ): literal[string] identifier[model_structure_grammar] = identifier[_include_common_grammar] ( literal[string] ) identifier[parser] = identifier[parsimonious] . identifier[Grammar] ( identifier[model_structure_grammar] ) identifier[tree] = identifier[parser] . identifier[parse] ( identifier[model_str] ) keyword[class] identifier[ModelParser] ( identifier[parsimonious] . identifier[NodeVisitor] ): keyword[def] identifier[__init__] ( identifier[self] , identifier[ast] ): identifier[self] . identifier[entries] =[] identifier[self] . identifier[visit] ( identifier[ast] ) keyword[def] identifier[visit_entry] ( identifier[self] , identifier[n] , identifier[vc] ): identifier[units] , identifier[lims] = identifier[parse_units] ( identifier[vc] [ literal[int] ]. identifier[strip] ()) identifier[self] . identifier[entries] . identifier[append] ({ literal[string] : identifier[vc] [ literal[int] ]. identifier[strip] (), literal[string] : identifier[units] , literal[string] : identifier[str] ( identifier[lims] ), literal[string] : identifier[vc] [ literal[int] ]. identifier[strip] (), literal[string] : literal[string] }) keyword[def] identifier[visit_section] ( identifier[self] , identifier[n] , identifier[vc] ): keyword[if] identifier[vc] [ literal[int] ]. identifier[strip] ()!= literal[string] : identifier[self] . identifier[entries] . identifier[append] ({ literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : literal[string] , literal[string] : identifier[vc] [ literal[int] ]. identifier[strip] (), literal[string] : literal[string] }) keyword[def] identifier[generic_visit] ( identifier[self] , identifier[n] , identifier[vc] ): keyword[return] literal[string] . identifier[join] ( identifier[filter] ( keyword[None] , identifier[vc] )) keyword[or] identifier[n] . identifier[text] keyword[or] literal[string] keyword[return] identifier[ModelParser] ( identifier[tree] ). identifier[entries]
def get_model_elements(model_str): """ Takes in a string representing model text and splits it into elements I think we're making the assumption that all newline characters are removed... Parameters ---------- model_str : string Returns ------- entries : array of dictionaries Each dictionary contains the components of a different model element, separated into the equation, units, and docstring. Examples -------- # Basic Parsing: >>> get_model_elements(r'a~b~c| d~e~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Special characters are escaped within double-quotes: >>> get_model_elements(r'a~b~c| d~e"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Double-quotes within escape groups are themselves escaped with backslashes: >>> get_model_elements(r'a~b~c| d~e"\\"~"~f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"\\\\"~"', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e~"\\"|"f| g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': '"\\\\"|"f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] >>> get_model_elements(r'a~b~c| d~e"x\\nx"~f| g~h~|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e"x\\\\nx"', 'eqn': 'd'}, {'doc': '', 'unit': 'h', 'eqn': 'g'}] # Todo: Handle model-level or section-level documentation >>> get_model_elements(r'*** .model doc ***~ Docstring!| d~e~f| g~h~i|') [{'doc': 'Docstring!', 'unit': '', 'eqn': ''}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle control sections, returning appropriate docstring pieces >>> get_model_elements(r'a~b~c| ****.Control***~ Simulation Control Parameters | g~h~i|') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'i', 'unit': 'h', 'eqn': 'g'}] # Handle the model display elements (ignore them) >>> get_model_elements(r'a~b~c| d~e~f| \\\\---///junk|junk~junk') [{'doc': 'c', 'unit': 'b', 'eqn': 'a'}, {'doc': 'f', 'unit': 'e', 'eqn': 'd'}] Notes ----- - Tildes and pipes are not allowed in element docstrings, but we should still handle them there """ model_structure_grammar = _include_common_grammar('\n model = (entry / section)+ sketch?\n entry = element "~" element "~" element ("~" element)? "|"\n section = element "~" element "|"\n sketch = ~r".*" #anything\n\n # Either an escape group, or a character that is not tilde or pipe\n element = (escape_group / ~r"[^~|]")*\n ') parser = parsimonious.Grammar(model_structure_grammar) tree = parser.parse(model_str) class ModelParser(parsimonious.NodeVisitor): def __init__(self, ast): self.entries = [] self.visit(ast) def visit_entry(self, n, vc): (units, lims) = parse_units(vc[2].strip()) self.entries.append({'eqn': vc[0].strip(), 'unit': units, 'lims': str(lims), 'doc': vc[4].strip(), 'kind': 'entry'}) def visit_section(self, n, vc): if vc[2].strip() != 'Simulation Control Parameters': self.entries.append({'eqn': '', 'unit': '', 'lims': '', 'doc': vc[2].strip(), 'kind': 'section'}) # depends on [control=['if'], data=[]] def generic_visit(self, n, vc): return ''.join(filter(None, vc)) or n.text or '' return ModelParser(tree).entries
def publish(ctx, test=False): """Publish to the cheeseshop.""" clean(ctx) if test: run('python setup.py register -r test sdist bdist_wheel', echo=True) run('twine upload dist/* -r test', echo=True) else: run('python setup.py register sdist bdist_wheel', echo=True) run('twine upload dist/*', echo=True)
def function[publish, parameter[ctx, test]]: constant[Publish to the cheeseshop.] call[name[clean], parameter[name[ctx]]] if name[test] begin[:] call[name[run], parameter[constant[python setup.py register -r test sdist bdist_wheel]]] call[name[run], parameter[constant[twine upload dist/* -r test]]]
keyword[def] identifier[publish] ( identifier[ctx] , identifier[test] = keyword[False] ): literal[string] identifier[clean] ( identifier[ctx] ) keyword[if] identifier[test] : identifier[run] ( literal[string] , identifier[echo] = keyword[True] ) identifier[run] ( literal[string] , identifier[echo] = keyword[True] ) keyword[else] : identifier[run] ( literal[string] , identifier[echo] = keyword[True] ) identifier[run] ( literal[string] , identifier[echo] = keyword[True] )
def publish(ctx, test=False): """Publish to the cheeseshop.""" clean(ctx) if test: run('python setup.py register -r test sdist bdist_wheel', echo=True) run('twine upload dist/* -r test', echo=True) # depends on [control=['if'], data=[]] else: run('python setup.py register sdist bdist_wheel', echo=True) run('twine upload dist/*', echo=True)
def compile_truncate(self, query): """ Compile a truncate statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled truncate statement :rtype: str """ sql = { "DELETE FROM sqlite_sequence WHERE name = %s" % self.get_marker(): [query.from__] } sql["DELETE FROM %s" % self.wrap_table(query.from__)] = [] return sql
def function[compile_truncate, parameter[self, query]]: constant[ Compile a truncate statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled truncate statement :rtype: str ] variable[sql] assign[=] dictionary[[<ast.BinOp object at 0x7da20c7c9c90>], [<ast.List object at 0x7da20c7ca080>]] call[name[sql]][binary_operation[constant[DELETE FROM %s] <ast.Mod object at 0x7da2590d6920> call[name[self].wrap_table, parameter[name[query].from__]]]] assign[=] list[[]] return[name[sql]]
keyword[def] identifier[compile_truncate] ( identifier[self] , identifier[query] ): literal[string] identifier[sql] ={ literal[string] % identifier[self] . identifier[get_marker] ():[ identifier[query] . identifier[from__] ] } identifier[sql] [ literal[string] % identifier[self] . identifier[wrap_table] ( identifier[query] . identifier[from__] )]=[] keyword[return] identifier[sql]
def compile_truncate(self, query): """ Compile a truncate statement into SQL :param query: A QueryBuilder instance :type query: QueryBuilder :return: The compiled truncate statement :rtype: str """ sql = {'DELETE FROM sqlite_sequence WHERE name = %s' % self.get_marker(): [query.from__]} sql['DELETE FROM %s' % self.wrap_table(query.from__)] = [] return sql
def write_compacted(g): """Write a graph in our own compacted format. Returns: str. """ d_nodes = {} d_edges = {} def conv(value): if isinstance(value, basestring): return value.strip('"') else: return value for node in g.nodes(): label = None attrs = [] for k, v in sorted(g.node_attributes(node)): v_ = conv(v) if k == "label": label = v_ else: attrs.append((k, v_)) value = (node, label) if label else node d_nodes.setdefault(tuple(attrs), []).append(value) for edge in g.edges(): attrs = [(k, conv(v)) for k, v in sorted(g.edge_attributes(edge))] label = str(g.edge_label(edge)) value = tuple(list(edge) + [label]) if label else edge d_edges.setdefault(tuple(attrs), []).append(tuple(value)) doc = dict(nodes=d_nodes.items(), edges=d_edges.items()) contents = str(doc) return contents
def function[write_compacted, parameter[g]]: constant[Write a graph in our own compacted format. Returns: str. ] variable[d_nodes] assign[=] dictionary[[], []] variable[d_edges] assign[=] dictionary[[], []] def function[conv, parameter[value]]: if call[name[isinstance], parameter[name[value], name[basestring]]] begin[:] return[call[name[value].strip, parameter[constant["]]]] for taget[name[node]] in starred[call[name[g].nodes, parameter[]]] begin[:] variable[label] assign[=] constant[None] variable[attrs] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b175e5f0>, <ast.Name object at 0x7da1b175e200>]]] in starred[call[name[sorted], parameter[call[name[g].node_attributes, parameter[name[node]]]]]] begin[:] variable[v_] assign[=] call[name[conv], parameter[name[v]]] if compare[name[k] equal[==] constant[label]] begin[:] variable[label] assign[=] name[v_] variable[value] assign[=] <ast.IfExp object at 0x7da1b175ebf0> call[call[name[d_nodes].setdefault, parameter[call[name[tuple], parameter[name[attrs]]], list[[]]]].append, parameter[name[value]]] for taget[name[edge]] in starred[call[name[g].edges, parameter[]]] begin[:] variable[attrs] assign[=] <ast.ListComp object at 0x7da1b175f670> variable[label] assign[=] call[name[str], parameter[call[name[g].edge_label, parameter[name[edge]]]]] variable[value] assign[=] <ast.IfExp object at 0x7da1b17bb5b0> call[call[name[d_edges].setdefault, parameter[call[name[tuple], parameter[name[attrs]]], list[[]]]].append, parameter[call[name[tuple], parameter[name[value]]]]] variable[doc] assign[=] call[name[dict], parameter[]] variable[contents] assign[=] call[name[str], parameter[name[doc]]] return[name[contents]]
keyword[def] identifier[write_compacted] ( identifier[g] ): literal[string] identifier[d_nodes] ={} identifier[d_edges] ={} keyword[def] identifier[conv] ( identifier[value] ): keyword[if] identifier[isinstance] ( identifier[value] , identifier[basestring] ): keyword[return] identifier[value] . identifier[strip] ( literal[string] ) keyword[else] : keyword[return] identifier[value] keyword[for] identifier[node] keyword[in] identifier[g] . identifier[nodes] (): identifier[label] = keyword[None] identifier[attrs] =[] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[sorted] ( identifier[g] . identifier[node_attributes] ( identifier[node] )): identifier[v_] = identifier[conv] ( identifier[v] ) keyword[if] identifier[k] == literal[string] : identifier[label] = identifier[v_] keyword[else] : identifier[attrs] . identifier[append] (( identifier[k] , identifier[v_] )) identifier[value] =( identifier[node] , identifier[label] ) keyword[if] identifier[label] keyword[else] identifier[node] identifier[d_nodes] . identifier[setdefault] ( identifier[tuple] ( identifier[attrs] ),[]). identifier[append] ( identifier[value] ) keyword[for] identifier[edge] keyword[in] identifier[g] . identifier[edges] (): identifier[attrs] =[( identifier[k] , identifier[conv] ( identifier[v] )) keyword[for] identifier[k] , identifier[v] keyword[in] identifier[sorted] ( identifier[g] . identifier[edge_attributes] ( identifier[edge] ))] identifier[label] = identifier[str] ( identifier[g] . identifier[edge_label] ( identifier[edge] )) identifier[value] = identifier[tuple] ( identifier[list] ( identifier[edge] )+[ identifier[label] ]) keyword[if] identifier[label] keyword[else] identifier[edge] identifier[d_edges] . identifier[setdefault] ( identifier[tuple] ( identifier[attrs] ),[]). identifier[append] ( identifier[tuple] ( identifier[value] )) identifier[doc] = identifier[dict] ( identifier[nodes] = identifier[d_nodes] . identifier[items] (), identifier[edges] = identifier[d_edges] . identifier[items] ()) identifier[contents] = identifier[str] ( identifier[doc] ) keyword[return] identifier[contents]
def write_compacted(g): """Write a graph in our own compacted format. Returns: str. """ d_nodes = {} d_edges = {} def conv(value): if isinstance(value, basestring): return value.strip('"') # depends on [control=['if'], data=[]] else: return value for node in g.nodes(): label = None attrs = [] for (k, v) in sorted(g.node_attributes(node)): v_ = conv(v) if k == 'label': label = v_ # depends on [control=['if'], data=[]] else: attrs.append((k, v_)) # depends on [control=['for'], data=[]] value = (node, label) if label else node d_nodes.setdefault(tuple(attrs), []).append(value) # depends on [control=['for'], data=['node']] for edge in g.edges(): attrs = [(k, conv(v)) for (k, v) in sorted(g.edge_attributes(edge))] label = str(g.edge_label(edge)) value = tuple(list(edge) + [label]) if label else edge d_edges.setdefault(tuple(attrs), []).append(tuple(value)) # depends on [control=['for'], data=['edge']] doc = dict(nodes=d_nodes.items(), edges=d_edges.items()) contents = str(doc) return contents
def set_outgoing(self, value): """ Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. """ if not isinstance(value, list): raise TypeError("OutgoingList new value must be a list") for element in value: if not isinstance(element, str): raise TypeError("OutgoingList elements in variable must be of String class") self.__outgoing_list = value
def function[set_outgoing, parameter[self, value]]: constant[ Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. ] if <ast.UnaryOp object at 0x7da18ede4fa0> begin[:] <ast.Raise object at 0x7da18ede7d30> for taget[name[element]] in starred[name[value]] begin[:] if <ast.UnaryOp object at 0x7da18ede7130> begin[:] <ast.Raise object at 0x7da18ede5bd0> name[self].__outgoing_list assign[=] name[value]
keyword[def] identifier[set_outgoing] ( identifier[self] , identifier[value] ): literal[string] keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[list] ): keyword[raise] identifier[TypeError] ( literal[string] ) keyword[for] identifier[element] keyword[in] identifier[value] : keyword[if] keyword[not] identifier[isinstance] ( identifier[element] , identifier[str] ): keyword[raise] identifier[TypeError] ( literal[string] ) identifier[self] . identifier[__outgoing_list] = identifier[value]
def set_outgoing(self, value): """ Setter for 'outgoing' field. :param value - a new value of 'outgoing' field. Must be a list of IDs (String type) of outgoing flows. """ if not isinstance(value, list): raise TypeError('OutgoingList new value must be a list') # depends on [control=['if'], data=[]] for element in value: if not isinstance(element, str): raise TypeError('OutgoingList elements in variable must be of String class') # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['element']] self.__outgoing_list = value
def validate_range_value(value): """ Validates given value against `Schema.TYPE_RANGE` data type. Raises TypeError or ValueError if something is wrong. Returns None if everything is OK. """ if value == (None, None): return if not hasattr(value, '__iter__'): raise TypeError('Range value must be an iterable, got "%s".' % value) if not 2 == len(value): raise ValueError('Range value must consist of two elements, got %d.' % len(value)) if not all(isinstance(x, (int,float)) for x in value): raise TypeError('Range value must consist of two numbers, got "%s" ' 'and "%s" instead.' % value) if not value[0] <= value[1]: raise ValueError('Range must consist of min and max values (min <= ' 'max) but got "%s" and "%s" instead.' % value) return
def function[validate_range_value, parameter[value]]: constant[ Validates given value against `Schema.TYPE_RANGE` data type. Raises TypeError or ValueError if something is wrong. Returns None if everything is OK. ] if compare[name[value] equal[==] tuple[[<ast.Constant object at 0x7da1b246bdc0>, <ast.Constant object at 0x7da1b246a800>]]] begin[:] return[None] if <ast.UnaryOp object at 0x7da1b246be20> begin[:] <ast.Raise object at 0x7da1b2468b20> if <ast.UnaryOp object at 0x7da1b2468190> begin[:] <ast.Raise object at 0x7da1b246ad40> if <ast.UnaryOp object at 0x7da1b2468ee0> begin[:] <ast.Raise object at 0x7da1b2469540> if <ast.UnaryOp object at 0x7da1b246bbe0> begin[:] <ast.Raise object at 0x7da1b246a320> return[None]
keyword[def] identifier[validate_range_value] ( identifier[value] ): literal[string] keyword[if] identifier[value] ==( keyword[None] , keyword[None] ): keyword[return] keyword[if] keyword[not] identifier[hasattr] ( identifier[value] , literal[string] ): keyword[raise] identifier[TypeError] ( literal[string] % identifier[value] ) keyword[if] keyword[not] literal[int] == identifier[len] ( identifier[value] ): keyword[raise] identifier[ValueError] ( literal[string] % identifier[len] ( identifier[value] )) keyword[if] keyword[not] identifier[all] ( identifier[isinstance] ( identifier[x] ,( identifier[int] , identifier[float] )) keyword[for] identifier[x] keyword[in] identifier[value] ): keyword[raise] identifier[TypeError] ( literal[string] literal[string] % identifier[value] ) keyword[if] keyword[not] identifier[value] [ literal[int] ]<= identifier[value] [ literal[int] ]: keyword[raise] identifier[ValueError] ( literal[string] literal[string] % identifier[value] ) keyword[return]
def validate_range_value(value): """ Validates given value against `Schema.TYPE_RANGE` data type. Raises TypeError or ValueError if something is wrong. Returns None if everything is OK. """ if value == (None, None): return # depends on [control=['if'], data=[]] if not hasattr(value, '__iter__'): raise TypeError('Range value must be an iterable, got "%s".' % value) # depends on [control=['if'], data=[]] if not 2 == len(value): raise ValueError('Range value must consist of two elements, got %d.' % len(value)) # depends on [control=['if'], data=[]] if not all((isinstance(x, (int, float)) for x in value)): raise TypeError('Range value must consist of two numbers, got "%s" and "%s" instead.' % value) # depends on [control=['if'], data=[]] if not value[0] <= value[1]: raise ValueError('Range must consist of min and max values (min <= max) but got "%s" and "%s" instead.' % value) # depends on [control=['if'], data=[]] return
def requires(self, requirements, **overrides): """Adds additional requirements to the specified route""" return self.where(requires=tuple(self.route.get('requires', ())) + tuple(requirements), **overrides)
def function[requires, parameter[self, requirements]]: constant[Adds additional requirements to the specified route] return[call[name[self].where, parameter[]]]
keyword[def] identifier[requires] ( identifier[self] , identifier[requirements] ,** identifier[overrides] ): literal[string] keyword[return] identifier[self] . identifier[where] ( identifier[requires] = identifier[tuple] ( identifier[self] . identifier[route] . identifier[get] ( literal[string] ,()))+ identifier[tuple] ( identifier[requirements] ),** identifier[overrides] )
def requires(self, requirements, **overrides): """Adds additional requirements to the specified route""" return self.where(requires=tuple(self.route.get('requires', ())) + tuple(requirements), **overrides)
def search_channels(self, query, limit=25, offset=0): """Search for channels and return them :param query: the query string :type query: :class:`str` :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of channels :rtype: :class:`list` of :class:`models.Channel` instances :raises: None """ r = self.kraken_request('GET', 'search/channels', params={'query': query, 'limit': limit, 'offset': offset}) return models.Channel.wrap_search(r)
def function[search_channels, parameter[self, query, limit, offset]]: constant[Search for channels and return them :param query: the query string :type query: :class:`str` :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of channels :rtype: :class:`list` of :class:`models.Channel` instances :raises: None ] variable[r] assign[=] call[name[self].kraken_request, parameter[constant[GET], constant[search/channels]]] return[call[name[models].Channel.wrap_search, parameter[name[r]]]]
keyword[def] identifier[search_channels] ( identifier[self] , identifier[query] , identifier[limit] = literal[int] , identifier[offset] = literal[int] ): literal[string] identifier[r] = identifier[self] . identifier[kraken_request] ( literal[string] , literal[string] , identifier[params] ={ literal[string] : identifier[query] , literal[string] : identifier[limit] , literal[string] : identifier[offset] }) keyword[return] identifier[models] . identifier[Channel] . identifier[wrap_search] ( identifier[r] )
def search_channels(self, query, limit=25, offset=0): """Search for channels and return them :param query: the query string :type query: :class:`str` :param limit: maximum number of results :type limit: :class:`int` :param offset: offset for pagination :type offset: :class:`int` :returns: A list of channels :rtype: :class:`list` of :class:`models.Channel` instances :raises: None """ r = self.kraken_request('GET', 'search/channels', params={'query': query, 'limit': limit, 'offset': offset}) return models.Channel.wrap_search(r)
async def is_object_synced_to_cn(self, client, pid): """Check if object with {pid} has successfully synced to the CN. CNRead.describe() is used as it's a light-weight HTTP HEAD request. This assumes that the call is being made over a connection that has been authenticated and has read or better access on the given object if it exists. """ try: await client.describe(pid) except d1_common.types.exceptions.DataONEException: return False return True
<ast.AsyncFunctionDef object at 0x7da1b1af3340>
keyword[async] keyword[def] identifier[is_object_synced_to_cn] ( identifier[self] , identifier[client] , identifier[pid] ): literal[string] keyword[try] : keyword[await] identifier[client] . identifier[describe] ( identifier[pid] ) keyword[except] identifier[d1_common] . identifier[types] . identifier[exceptions] . identifier[DataONEException] : keyword[return] keyword[False] keyword[return] keyword[True]
async def is_object_synced_to_cn(self, client, pid): """Check if object with {pid} has successfully synced to the CN. CNRead.describe() is used as it's a light-weight HTTP HEAD request. This assumes that the call is being made over a connection that has been authenticated and has read or better access on the given object if it exists. """ try: await client.describe(pid) # depends on [control=['try'], data=[]] except d1_common.types.exceptions.DataONEException: return False # depends on [control=['except'], data=[]] return True
def find_existing(self): """ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """ instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instances.pop(0) server_id = i[A.server.ID] if self.namespace.add_if_unique(server_id): log.info('Found existing server, %s' % server_id) self.server_attrs = i break if len(self.namespace.names) >= maxnames: break instances.append(i)
def function[find_existing, parameter[self]]: constant[ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". ] variable[instances] assign[=] call[name[self].consul.find_servers, parameter[name[self].tags]] variable[maxnames] assign[=] call[name[len], parameter[name[instances]]] while name[instances] begin[:] variable[i] assign[=] call[name[instances].pop, parameter[constant[0]]] variable[server_id] assign[=] call[name[i]][name[A].server.ID] if call[name[self].namespace.add_if_unique, parameter[name[server_id]]] begin[:] call[name[log].info, parameter[binary_operation[constant[Found existing server, %s] <ast.Mod object at 0x7da2590d6920> name[server_id]]]] name[self].server_attrs assign[=] name[i] break if compare[call[name[len], parameter[name[self].namespace.names]] greater_or_equal[>=] name[maxnames]] begin[:] break call[name[instances].append, parameter[name[i]]]
keyword[def] identifier[find_existing] ( identifier[self] ): literal[string] identifier[instances] = identifier[self] . identifier[consul] . identifier[find_servers] ( identifier[self] . identifier[tags] ) identifier[maxnames] = identifier[len] ( identifier[instances] ) keyword[while] identifier[instances] : identifier[i] = identifier[instances] . identifier[pop] ( literal[int] ) identifier[server_id] = identifier[i] [ identifier[A] . identifier[server] . identifier[ID] ] keyword[if] identifier[self] . identifier[namespace] . identifier[add_if_unique] ( identifier[server_id] ): identifier[log] . identifier[info] ( literal[string] % identifier[server_id] ) identifier[self] . identifier[server_attrs] = identifier[i] keyword[break] keyword[if] identifier[len] ( identifier[self] . identifier[namespace] . identifier[names] )>= identifier[maxnames] : keyword[break] identifier[instances] . identifier[append] ( identifier[i] )
def find_existing(self): """ Searches for existing server instances with matching tags. To match, the existing instances must also be "running". """ instances = self.consul.find_servers(self.tags) maxnames = len(instances) while instances: i = instances.pop(0) server_id = i[A.server.ID] if self.namespace.add_if_unique(server_id): log.info('Found existing server, %s' % server_id) self.server_attrs = i break # depends on [control=['if'], data=[]] if len(self.namespace.names) >= maxnames: break # depends on [control=['if'], data=[]] instances.append(i) # depends on [control=['while'], data=[]]
def is_number(num, if_bool=False): """ :return: True if num is either an actual number, or an object that converts to one """ if isinstance(num, bool): return if_bool elif isinstance(num, int): return True try: number = float(num) return not (isnan(number) or isinf(number)) except (TypeError, ValueError): return False
def function[is_number, parameter[num, if_bool]]: constant[ :return: True if num is either an actual number, or an object that converts to one ] if call[name[isinstance], parameter[name[num], name[bool]]] begin[:] return[name[if_bool]] <ast.Try object at 0x7da1b28fc040>
keyword[def] identifier[is_number] ( identifier[num] , identifier[if_bool] = keyword[False] ): literal[string] keyword[if] identifier[isinstance] ( identifier[num] , identifier[bool] ): keyword[return] identifier[if_bool] keyword[elif] identifier[isinstance] ( identifier[num] , identifier[int] ): keyword[return] keyword[True] keyword[try] : identifier[number] = identifier[float] ( identifier[num] ) keyword[return] keyword[not] ( identifier[isnan] ( identifier[number] ) keyword[or] identifier[isinf] ( identifier[number] )) keyword[except] ( identifier[TypeError] , identifier[ValueError] ): keyword[return] keyword[False]
def is_number(num, if_bool=False): """ :return: True if num is either an actual number, or an object that converts to one """ if isinstance(num, bool): return if_bool # depends on [control=['if'], data=[]] elif isinstance(num, int): return True # depends on [control=['if'], data=[]] try: number = float(num) return not (isnan(number) or isinf(number)) # depends on [control=['try'], data=[]] except (TypeError, ValueError): return False # depends on [control=['except'], data=[]]
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig except AttributeError: pass contents = self.get_contents() self.get_ninfo().csig = contents return contents
def function[get_csig, parameter[self, calc]]: constant[Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.] <ast.Try object at 0x7da207f9a6b0> variable[contents] assign[=] call[name[self].get_contents, parameter[]] call[name[self].get_ninfo, parameter[]].csig assign[=] name[contents] return[name[contents]]
keyword[def] identifier[get_csig] ( identifier[self] , identifier[calc] = keyword[None] ): literal[string] keyword[try] : keyword[return] identifier[self] . identifier[ninfo] . identifier[csig] keyword[except] identifier[AttributeError] : keyword[pass] identifier[contents] = identifier[self] . identifier[get_contents] () identifier[self] . identifier[get_ninfo] (). identifier[csig] = identifier[contents] keyword[return] identifier[contents]
def get_csig(self, calc=None): """Because we're a Python value node and don't have a real timestamp, we get to ignore the calculator and just use the value contents.""" try: return self.ninfo.csig # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] contents = self.get_contents() self.get_ninfo().csig = contents return contents
def translate_docs_compact(self, ds, field_mapping=None, slim=None, map_identifiers=None, invert_subject_object=False, **kwargs): """ Translate golr association documents to a compact representation """ amap = {} logging.info("Translating docs to compact form. Slim={}".format(slim)) for d in ds: self.map_doc(d, field_mapping, invert_subject_object=invert_subject_object) subject = d[M.SUBJECT] subject_label = d[M.SUBJECT_LABEL] # TODO: use a more robust method; we need equivalence as separate field in solr if map_identifiers is not None: if M.SUBJECT_CLOSURE in d: subject = self.map_id(subject, map_identifiers, d[M.SUBJECT_CLOSURE]) else: logging.debug("NO SUBJECT CLOSURE IN: "+str(d)) rel = d.get(M.RELATION) skip = False # TODO if rel == 'not' or rel == 'NOT': skip = True # this is a list in GO if isinstance(rel,list): if 'not' in rel or 'NOT' in rel: skip = True if len(rel) > 1: logging.warn(">1 relation: {}".format(rel)) rel = ";".join(rel) if skip: logging.debug("Skipping: {}".format(d)) continue subject = self.make_canonical_identifier(subject) #if subject.startswith('MGI:MGI:'): # subject = subject.replace('MGI:MGI:','MGI:') k = (subject,rel) if k not in amap: amap[k] = {'subject':subject, 'subject_label':subject_label, 'relation':rel, 'objects': []} if slim is not None and len(slim)>0: mapped_objects = [x for x in d[M.OBJECT_CLOSURE] if x in slim] logging.debug("Mapped objects: {}".format(mapped_objects)) amap[k]['objects'] += mapped_objects else: amap[k]['objects'].append(d[M.OBJECT]) for k in amap.keys(): amap[k]['objects'] = list(set(amap[k]['objects'])) return list(amap.values())
def function[translate_docs_compact, parameter[self, ds, field_mapping, slim, map_identifiers, invert_subject_object]]: constant[ Translate golr association documents to a compact representation ] variable[amap] assign[=] dictionary[[], []] call[name[logging].info, parameter[call[constant[Translating docs to compact form. Slim={}].format, parameter[name[slim]]]]] for taget[name[d]] in starred[name[ds]] begin[:] call[name[self].map_doc, parameter[name[d], name[field_mapping]]] variable[subject] assign[=] call[name[d]][name[M].SUBJECT] variable[subject_label] assign[=] call[name[d]][name[M].SUBJECT_LABEL] if compare[name[map_identifiers] is_not constant[None]] begin[:] if compare[name[M].SUBJECT_CLOSURE in name[d]] begin[:] variable[subject] assign[=] call[name[self].map_id, parameter[name[subject], name[map_identifiers], call[name[d]][name[M].SUBJECT_CLOSURE]]] variable[rel] assign[=] call[name[d].get, parameter[name[M].RELATION]] variable[skip] assign[=] constant[False] if <ast.BoolOp object at 0x7da1b086a7d0> begin[:] variable[skip] assign[=] constant[True] if call[name[isinstance], parameter[name[rel], name[list]]] begin[:] if <ast.BoolOp object at 0x7da1b086b7c0> begin[:] variable[skip] assign[=] constant[True] if compare[call[name[len], parameter[name[rel]]] greater[>] constant[1]] begin[:] call[name[logging].warn, parameter[call[constant[>1 relation: {}].format, parameter[name[rel]]]]] variable[rel] assign[=] call[constant[;].join, parameter[name[rel]]] if name[skip] begin[:] call[name[logging].debug, parameter[call[constant[Skipping: {}].format, parameter[name[d]]]]] continue variable[subject] assign[=] call[name[self].make_canonical_identifier, parameter[name[subject]]] variable[k] assign[=] tuple[[<ast.Name object at 0x7da1b0869c60>, <ast.Name object at 0x7da1b086a410>]] if compare[name[k] <ast.NotIn object at 0x7da2590d7190> name[amap]] begin[:] call[name[amap]][name[k]] assign[=] dictionary[[<ast.Constant object at 0x7da1b086a560>, <ast.Constant object at 0x7da1b086a530>, <ast.Constant object at 0x7da1b086a200>, <ast.Constant object at 0x7da1b0869fc0>], [<ast.Name object at 0x7da1b086a1d0>, <ast.Name object at 0x7da1b086a230>, <ast.Name object at 0x7da1b086a260>, <ast.List object at 0x7da1b086a1a0>]] if <ast.BoolOp object at 0x7da1b086a290> begin[:] variable[mapped_objects] assign[=] <ast.ListComp object at 0x7da1b086ad70> call[name[logging].debug, parameter[call[constant[Mapped objects: {}].format, parameter[name[mapped_objects]]]]] <ast.AugAssign object at 0x7da1b086ad10> for taget[name[k]] in starred[call[name[amap].keys, parameter[]]] begin[:] call[call[name[amap]][name[k]]][constant[objects]] assign[=] call[name[list], parameter[call[name[set], parameter[call[call[name[amap]][name[k]]][constant[objects]]]]]] return[call[name[list], parameter[call[name[amap].values, parameter[]]]]]
keyword[def] identifier[translate_docs_compact] ( identifier[self] , identifier[ds] , identifier[field_mapping] = keyword[None] , identifier[slim] = keyword[None] , identifier[map_identifiers] = keyword[None] , identifier[invert_subject_object] = keyword[False] ,** identifier[kwargs] ): literal[string] identifier[amap] ={} identifier[logging] . identifier[info] ( literal[string] . identifier[format] ( identifier[slim] )) keyword[for] identifier[d] keyword[in] identifier[ds] : identifier[self] . identifier[map_doc] ( identifier[d] , identifier[field_mapping] , identifier[invert_subject_object] = identifier[invert_subject_object] ) identifier[subject] = identifier[d] [ identifier[M] . identifier[SUBJECT] ] identifier[subject_label] = identifier[d] [ identifier[M] . identifier[SUBJECT_LABEL] ] keyword[if] identifier[map_identifiers] keyword[is] keyword[not] keyword[None] : keyword[if] identifier[M] . identifier[SUBJECT_CLOSURE] keyword[in] identifier[d] : identifier[subject] = identifier[self] . identifier[map_id] ( identifier[subject] , identifier[map_identifiers] , identifier[d] [ identifier[M] . identifier[SUBJECT_CLOSURE] ]) keyword[else] : identifier[logging] . identifier[debug] ( literal[string] + identifier[str] ( identifier[d] )) identifier[rel] = identifier[d] . identifier[get] ( identifier[M] . identifier[RELATION] ) identifier[skip] = keyword[False] keyword[if] identifier[rel] == literal[string] keyword[or] identifier[rel] == literal[string] : identifier[skip] = keyword[True] keyword[if] identifier[isinstance] ( identifier[rel] , identifier[list] ): keyword[if] literal[string] keyword[in] identifier[rel] keyword[or] literal[string] keyword[in] identifier[rel] : identifier[skip] = keyword[True] keyword[if] identifier[len] ( identifier[rel] )> literal[int] : identifier[logging] . identifier[warn] ( literal[string] . identifier[format] ( identifier[rel] )) identifier[rel] = literal[string] . identifier[join] ( identifier[rel] ) keyword[if] identifier[skip] : identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[d] )) keyword[continue] identifier[subject] = identifier[self] . identifier[make_canonical_identifier] ( identifier[subject] ) identifier[k] =( identifier[subject] , identifier[rel] ) keyword[if] identifier[k] keyword[not] keyword[in] identifier[amap] : identifier[amap] [ identifier[k] ]={ literal[string] : identifier[subject] , literal[string] : identifier[subject_label] , literal[string] : identifier[rel] , literal[string] :[]} keyword[if] identifier[slim] keyword[is] keyword[not] keyword[None] keyword[and] identifier[len] ( identifier[slim] )> literal[int] : identifier[mapped_objects] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[d] [ identifier[M] . identifier[OBJECT_CLOSURE] ] keyword[if] identifier[x] keyword[in] identifier[slim] ] identifier[logging] . identifier[debug] ( literal[string] . identifier[format] ( identifier[mapped_objects] )) identifier[amap] [ identifier[k] ][ literal[string] ]+= identifier[mapped_objects] keyword[else] : identifier[amap] [ identifier[k] ][ literal[string] ]. identifier[append] ( identifier[d] [ identifier[M] . identifier[OBJECT] ]) keyword[for] identifier[k] keyword[in] identifier[amap] . identifier[keys] (): identifier[amap] [ identifier[k] ][ literal[string] ]= identifier[list] ( identifier[set] ( identifier[amap] [ identifier[k] ][ literal[string] ])) keyword[return] identifier[list] ( identifier[amap] . identifier[values] ())
def translate_docs_compact(self, ds, field_mapping=None, slim=None, map_identifiers=None, invert_subject_object=False, **kwargs): """ Translate golr association documents to a compact representation """ amap = {} logging.info('Translating docs to compact form. Slim={}'.format(slim)) for d in ds: self.map_doc(d, field_mapping, invert_subject_object=invert_subject_object) subject = d[M.SUBJECT] subject_label = d[M.SUBJECT_LABEL] # TODO: use a more robust method; we need equivalence as separate field in solr if map_identifiers is not None: if M.SUBJECT_CLOSURE in d: subject = self.map_id(subject, map_identifiers, d[M.SUBJECT_CLOSURE]) # depends on [control=['if'], data=['d']] else: logging.debug('NO SUBJECT CLOSURE IN: ' + str(d)) # depends on [control=['if'], data=['map_identifiers']] rel = d.get(M.RELATION) skip = False # TODO if rel == 'not' or rel == 'NOT': skip = True # depends on [control=['if'], data=[]] # this is a list in GO if isinstance(rel, list): if 'not' in rel or 'NOT' in rel: skip = True # depends on [control=['if'], data=[]] if len(rel) > 1: logging.warn('>1 relation: {}'.format(rel)) # depends on [control=['if'], data=[]] rel = ';'.join(rel) # depends on [control=['if'], data=[]] if skip: logging.debug('Skipping: {}'.format(d)) continue # depends on [control=['if'], data=[]] subject = self.make_canonical_identifier(subject) #if subject.startswith('MGI:MGI:'): # subject = subject.replace('MGI:MGI:','MGI:') k = (subject, rel) if k not in amap: amap[k] = {'subject': subject, 'subject_label': subject_label, 'relation': rel, 'objects': []} # depends on [control=['if'], data=['k', 'amap']] if slim is not None and len(slim) > 0: mapped_objects = [x for x in d[M.OBJECT_CLOSURE] if x in slim] logging.debug('Mapped objects: {}'.format(mapped_objects)) amap[k]['objects'] += mapped_objects # depends on [control=['if'], data=[]] else: amap[k]['objects'].append(d[M.OBJECT]) # depends on [control=['for'], data=['d']] for k in amap.keys(): amap[k]['objects'] = list(set(amap[k]['objects'])) # depends on [control=['for'], data=['k']] return list(amap.values())
def new() -> ulid.ULID: """ Create a new :class:`~ulid.ulid.ULID` instance. The timestamp is created from :func:`~time.time`. The randomness is created from :func:`~os.urandom`. :return: ULID from current timestamp :rtype: :class:`~ulid.ulid.ULID` """ timestamp = int(time.time() * 1000).to_bytes(6, byteorder='big') randomness = os.urandom(10) return ulid.ULID(timestamp + randomness)
def function[new, parameter[]]: constant[ Create a new :class:`~ulid.ulid.ULID` instance. The timestamp is created from :func:`~time.time`. The randomness is created from :func:`~os.urandom`. :return: ULID from current timestamp :rtype: :class:`~ulid.ulid.ULID` ] variable[timestamp] assign[=] call[call[name[int], parameter[binary_operation[call[name[time].time, parameter[]] * constant[1000]]]].to_bytes, parameter[constant[6]]] variable[randomness] assign[=] call[name[os].urandom, parameter[constant[10]]] return[call[name[ulid].ULID, parameter[binary_operation[name[timestamp] + name[randomness]]]]]
keyword[def] identifier[new] ()-> identifier[ulid] . identifier[ULID] : literal[string] identifier[timestamp] = identifier[int] ( identifier[time] . identifier[time] ()* literal[int] ). identifier[to_bytes] ( literal[int] , identifier[byteorder] = literal[string] ) identifier[randomness] = identifier[os] . identifier[urandom] ( literal[int] ) keyword[return] identifier[ulid] . identifier[ULID] ( identifier[timestamp] + identifier[randomness] )
def new() -> ulid.ULID: """ Create a new :class:`~ulid.ulid.ULID` instance. The timestamp is created from :func:`~time.time`. The randomness is created from :func:`~os.urandom`. :return: ULID from current timestamp :rtype: :class:`~ulid.ulid.ULID` """ timestamp = int(time.time() * 1000).to_bytes(6, byteorder='big') randomness = os.urandom(10) return ulid.ULID(timestamp + randomness)
def to_dict(self, files=None): """ Converts the CodeBaseDoc into a dictionary containing the to_dict() representations of each contained file. The optional `files` list lets you restrict the dict to include only specific files. >>> CodeBaseDoc(['examples']).to_dict(['class.js']).get('module.js') >>> CodeBaseDoc(['examples']).to_dict(['class.js'])['class.js'][0]['name'] 'MyClass' """ keys = files or list(self.keys()) return dict((key, self[key].to_dict()) for key in keys)
def function[to_dict, parameter[self, files]]: constant[ Converts the CodeBaseDoc into a dictionary containing the to_dict() representations of each contained file. The optional `files` list lets you restrict the dict to include only specific files. >>> CodeBaseDoc(['examples']).to_dict(['class.js']).get('module.js') >>> CodeBaseDoc(['examples']).to_dict(['class.js'])['class.js'][0]['name'] 'MyClass' ] variable[keys] assign[=] <ast.BoolOp object at 0x7da20c6e78e0> return[call[name[dict], parameter[<ast.GeneratorExp object at 0x7da20c6e5510>]]]
keyword[def] identifier[to_dict] ( identifier[self] , identifier[files] = keyword[None] ): literal[string] identifier[keys] = identifier[files] keyword[or] identifier[list] ( identifier[self] . identifier[keys] ()) keyword[return] identifier[dict] (( identifier[key] , identifier[self] [ identifier[key] ]. identifier[to_dict] ()) keyword[for] identifier[key] keyword[in] identifier[keys] )
def to_dict(self, files=None): """ Converts the CodeBaseDoc into a dictionary containing the to_dict() representations of each contained file. The optional `files` list lets you restrict the dict to include only specific files. >>> CodeBaseDoc(['examples']).to_dict(['class.js']).get('module.js') >>> CodeBaseDoc(['examples']).to_dict(['class.js'])['class.js'][0]['name'] 'MyClass' """ keys = files or list(self.keys()) return dict(((key, self[key].to_dict()) for key in keys))
def getParent(self, returned_properties=None): """Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :class:`rtcclient.workitem.Workitem` object :rtype: rtcclient.workitem.Workitem """ parent_tag = ("rtc_cm:com.ibm.team.workitem.linktype." "parentworkitem.parent") rp = returned_properties parent = (self.rtc_obj ._get_paged_resources("Parent", workitem_id=self.identifier, customized_attr=parent_tag, page_size="5", returned_properties=rp)) # No more than one parent if parent: # only one element return parent[0] return None
def function[getParent, parameter[self, returned_properties]]: constant[Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :class:`rtcclient.workitem.Workitem` object :rtype: rtcclient.workitem.Workitem ] variable[parent_tag] assign[=] constant[rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent] variable[rp] assign[=] name[returned_properties] variable[parent] assign[=] call[name[self].rtc_obj._get_paged_resources, parameter[constant[Parent]]] if name[parent] begin[:] return[call[name[parent]][constant[0]]] return[constant[None]]
keyword[def] identifier[getParent] ( identifier[self] , identifier[returned_properties] = keyword[None] ): literal[string] identifier[parent_tag] =( literal[string] literal[string] ) identifier[rp] = identifier[returned_properties] identifier[parent] =( identifier[self] . identifier[rtc_obj] . identifier[_get_paged_resources] ( literal[string] , identifier[workitem_id] = identifier[self] . identifier[identifier] , identifier[customized_attr] = identifier[parent_tag] , identifier[page_size] = literal[string] , identifier[returned_properties] = identifier[rp] )) keyword[if] identifier[parent] : keyword[return] identifier[parent] [ literal[int] ] keyword[return] keyword[None]
def getParent(self, returned_properties=None): """Get the parent workitem of this workitem If no parent, None will be returned. :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return: a :class:`rtcclient.workitem.Workitem` object :rtype: rtcclient.workitem.Workitem """ parent_tag = 'rtc_cm:com.ibm.team.workitem.linktype.parentworkitem.parent' rp = returned_properties parent = self.rtc_obj._get_paged_resources('Parent', workitem_id=self.identifier, customized_attr=parent_tag, page_size='5', returned_properties=rp) # No more than one parent if parent: # only one element return parent[0] # depends on [control=['if'], data=[]] return None
def remove_user(name, profile='github'): ''' Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ''' client = _get_client(profile) organization = client.get_organization( _get_config_value(profile, 'org_name') ) try: git_user = client.get_user(name) except UnknownObjectException: log.exception("Resource not found") return False if organization.has_in_members(git_user): organization.remove_from_members(git_user) return not organization.has_in_members(git_user)
def function[remove_user, parameter[name, profile]]: constant[ Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle ] variable[client] assign[=] call[name[_get_client], parameter[name[profile]]] variable[organization] assign[=] call[name[client].get_organization, parameter[call[name[_get_config_value], parameter[name[profile], constant[org_name]]]]] <ast.Try object at 0x7da1b1c63190> if call[name[organization].has_in_members, parameter[name[git_user]]] begin[:] call[name[organization].remove_from_members, parameter[name[git_user]]] return[<ast.UnaryOp object at 0x7da1b1c605e0>]
keyword[def] identifier[remove_user] ( identifier[name] , identifier[profile] = literal[string] ): literal[string] identifier[client] = identifier[_get_client] ( identifier[profile] ) identifier[organization] = identifier[client] . identifier[get_organization] ( identifier[_get_config_value] ( identifier[profile] , literal[string] ) ) keyword[try] : identifier[git_user] = identifier[client] . identifier[get_user] ( identifier[name] ) keyword[except] identifier[UnknownObjectException] : identifier[log] . identifier[exception] ( literal[string] ) keyword[return] keyword[False] keyword[if] identifier[organization] . identifier[has_in_members] ( identifier[git_user] ): identifier[organization] . identifier[remove_from_members] ( identifier[git_user] ) keyword[return] keyword[not] identifier[organization] . identifier[has_in_members] ( identifier[git_user] )
def remove_user(name, profile='github'): """ Remove a Github user by name. name The user for which to obtain information. profile The name of the profile configuration to use. Defaults to ``github``. CLI Example: .. code-block:: bash salt myminion github.remove_user github-handle """ client = _get_client(profile) organization = client.get_organization(_get_config_value(profile, 'org_name')) try: git_user = client.get_user(name) # depends on [control=['try'], data=[]] except UnknownObjectException: log.exception('Resource not found') return False # depends on [control=['except'], data=[]] if organization.has_in_members(git_user): organization.remove_from_members(git_user) # depends on [control=['if'], data=[]] return not organization.has_in_members(git_user)
def expand_repertoire(self, direction, repertoire, new_purview=None): """Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. """ if repertoire is None: return None purview = distribution.purview(repertoire) if new_purview is None: new_purview = self.node_indices # full subsystem if not set(purview).issubset(new_purview): raise ValueError("Expanded purview must contain original purview.") # Get the unconstrained repertoire over the other nodes in the network. non_purview_indices = tuple(set(new_purview) - set(purview)) uc = self.unconstrained_repertoire(direction, non_purview_indices) # Multiply the given repertoire by the unconstrained one to get a # distribution over all the nodes in the network. expanded_repertoire = repertoire * uc return distribution.normalize(expanded_repertoire)
def function[expand_repertoire, parameter[self, direction, repertoire, new_purview]]: constant[Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. ] if compare[name[repertoire] is constant[None]] begin[:] return[constant[None]] variable[purview] assign[=] call[name[distribution].purview, parameter[name[repertoire]]] if compare[name[new_purview] is constant[None]] begin[:] variable[new_purview] assign[=] name[self].node_indices if <ast.UnaryOp object at 0x7da1b2345150> begin[:] <ast.Raise object at 0x7da1b2344550> variable[non_purview_indices] assign[=] call[name[tuple], parameter[binary_operation[call[name[set], parameter[name[new_purview]]] - call[name[set], parameter[name[purview]]]]]] variable[uc] assign[=] call[name[self].unconstrained_repertoire, parameter[name[direction], name[non_purview_indices]]] variable[expanded_repertoire] assign[=] binary_operation[name[repertoire] * name[uc]] return[call[name[distribution].normalize, parameter[name[expanded_repertoire]]]]
keyword[def] identifier[expand_repertoire] ( identifier[self] , identifier[direction] , identifier[repertoire] , identifier[new_purview] = keyword[None] ): literal[string] keyword[if] identifier[repertoire] keyword[is] keyword[None] : keyword[return] keyword[None] identifier[purview] = identifier[distribution] . identifier[purview] ( identifier[repertoire] ) keyword[if] identifier[new_purview] keyword[is] keyword[None] : identifier[new_purview] = identifier[self] . identifier[node_indices] keyword[if] keyword[not] identifier[set] ( identifier[purview] ). identifier[issubset] ( identifier[new_purview] ): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[non_purview_indices] = identifier[tuple] ( identifier[set] ( identifier[new_purview] )- identifier[set] ( identifier[purview] )) identifier[uc] = identifier[self] . identifier[unconstrained_repertoire] ( identifier[direction] , identifier[non_purview_indices] ) identifier[expanded_repertoire] = identifier[repertoire] * identifier[uc] keyword[return] identifier[distribution] . identifier[normalize] ( identifier[expanded_repertoire] )
def expand_repertoire(self, direction, repertoire, new_purview=None): """Distribute an effect repertoire over a larger purview. Args: direction (Direction): |CAUSE| or |EFFECT|. repertoire (np.ndarray): The repertoire to expand. Keyword Args: new_purview (tuple[int]): The new purview to expand the repertoire over. If ``None`` (the default), the new purview is the entire network. Returns: np.ndarray: A distribution over the new purview, where probability is spread out over the new nodes. Raises: ValueError: If the expanded purview doesn't contain the original purview. """ if repertoire is None: return None # depends on [control=['if'], data=[]] purview = distribution.purview(repertoire) if new_purview is None: new_purview = self.node_indices # full subsystem # depends on [control=['if'], data=['new_purview']] if not set(purview).issubset(new_purview): raise ValueError('Expanded purview must contain original purview.') # depends on [control=['if'], data=[]] # Get the unconstrained repertoire over the other nodes in the network. non_purview_indices = tuple(set(new_purview) - set(purview)) uc = self.unconstrained_repertoire(direction, non_purview_indices) # Multiply the given repertoire by the unconstrained one to get a # distribution over all the nodes in the network. expanded_repertoire = repertoire * uc return distribution.normalize(expanded_repertoire)
def match_file(self, file, separators=None): """ Matches the file to this path-spec. *file* (:class:`str`) is the file path to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`) optionally contains the path separators to normalize. See :func:`~pathspec.util.normalize_file` for more information. Returns :data:`True` if *file* matched; otherwise, :data:`False`. """ norm_file = util.normalize_file(file, separators=separators) return util.match_file(self.patterns, norm_file)
def function[match_file, parameter[self, file, separators]]: constant[ Matches the file to this path-spec. *file* (:class:`str`) is the file path to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`) optionally contains the path separators to normalize. See :func:`~pathspec.util.normalize_file` for more information. Returns :data:`True` if *file* matched; otherwise, :data:`False`. ] variable[norm_file] assign[=] call[name[util].normalize_file, parameter[name[file]]] return[call[name[util].match_file, parameter[name[self].patterns, name[norm_file]]]]
keyword[def] identifier[match_file] ( identifier[self] , identifier[file] , identifier[separators] = keyword[None] ): literal[string] identifier[norm_file] = identifier[util] . identifier[normalize_file] ( identifier[file] , identifier[separators] = identifier[separators] ) keyword[return] identifier[util] . identifier[match_file] ( identifier[self] . identifier[patterns] , identifier[norm_file] )
def match_file(self, file, separators=None): """ Matches the file to this path-spec. *file* (:class:`str`) is the file path to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`) optionally contains the path separators to normalize. See :func:`~pathspec.util.normalize_file` for more information. Returns :data:`True` if *file* matched; otherwise, :data:`False`. """ norm_file = util.normalize_file(file, separators=separators) return util.match_file(self.patterns, norm_file)
def set_attrs(self, **attrs): """Set model attributes, e.g. input resistance of a cell.""" self.attrs.update(attrs) self._backend.set_attrs(**attrs)
def function[set_attrs, parameter[self]]: constant[Set model attributes, e.g. input resistance of a cell.] call[name[self].attrs.update, parameter[name[attrs]]] call[name[self]._backend.set_attrs, parameter[]]
keyword[def] identifier[set_attrs] ( identifier[self] ,** identifier[attrs] ): literal[string] identifier[self] . identifier[attrs] . identifier[update] ( identifier[attrs] ) identifier[self] . identifier[_backend] . identifier[set_attrs] (** identifier[attrs] )
def set_attrs(self, **attrs): """Set model attributes, e.g. input resistance of a cell.""" self.attrs.update(attrs) self._backend.set_attrs(**attrs)
def find_types(self, site=None, match=r'^(?!lastfile|spectro|\.).*'): """Return the list of known data types. This is just the basename of each FFL file found in the FFL directory (minus the ``.ffl`` extension) """ self._find_paths() types = [tag for (site_, tag) in self.paths if site in (None, site_)] if match is not None: match = re.compile(match) return list(filter(match.search, types)) return types
def function[find_types, parameter[self, site, match]]: constant[Return the list of known data types. This is just the basename of each FFL file found in the FFL directory (minus the ``.ffl`` extension) ] call[name[self]._find_paths, parameter[]] variable[types] assign[=] <ast.ListComp object at 0x7da18ede71f0> if compare[name[match] is_not constant[None]] begin[:] variable[match] assign[=] call[name[re].compile, parameter[name[match]]] return[call[name[list], parameter[call[name[filter], parameter[name[match].search, name[types]]]]]] return[name[types]]
keyword[def] identifier[find_types] ( identifier[self] , identifier[site] = keyword[None] , identifier[match] = literal[string] ): literal[string] identifier[self] . identifier[_find_paths] () identifier[types] =[ identifier[tag] keyword[for] ( identifier[site_] , identifier[tag] ) keyword[in] identifier[self] . identifier[paths] keyword[if] identifier[site] keyword[in] ( keyword[None] , identifier[site_] )] keyword[if] identifier[match] keyword[is] keyword[not] keyword[None] : identifier[match] = identifier[re] . identifier[compile] ( identifier[match] ) keyword[return] identifier[list] ( identifier[filter] ( identifier[match] . identifier[search] , identifier[types] )) keyword[return] identifier[types]
def find_types(self, site=None, match='^(?!lastfile|spectro|\\.).*'): """Return the list of known data types. This is just the basename of each FFL file found in the FFL directory (minus the ``.ffl`` extension) """ self._find_paths() types = [tag for (site_, tag) in self.paths if site in (None, site_)] if match is not None: match = re.compile(match) return list(filter(match.search, types)) # depends on [control=['if'], data=['match']] return types
def do_save(self, fp=None): """Save to file. Parameters ---------- fp : `file` or `str`, optional Output file (default: stdout). """ if fp is None: fp = sys.stdout data = { 'settings': self.settings, 'nodes': self.nodes, 'backward': self.backward } json.dump(data, fp, ensure_ascii=False)
def function[do_save, parameter[self, fp]]: constant[Save to file. Parameters ---------- fp : `file` or `str`, optional Output file (default: stdout). ] if compare[name[fp] is constant[None]] begin[:] variable[fp] assign[=] name[sys].stdout variable[data] assign[=] dictionary[[<ast.Constant object at 0x7da20e9b30a0>, <ast.Constant object at 0x7da20e9b05b0>, <ast.Constant object at 0x7da20e9b2ec0>], [<ast.Attribute object at 0x7da20e9b1360>, <ast.Attribute object at 0x7da20e9b0c10>, <ast.Attribute object at 0x7da20e9b3eb0>]] call[name[json].dump, parameter[name[data], name[fp]]]
keyword[def] identifier[do_save] ( identifier[self] , identifier[fp] = keyword[None] ): literal[string] keyword[if] identifier[fp] keyword[is] keyword[None] : identifier[fp] = identifier[sys] . identifier[stdout] identifier[data] ={ literal[string] : identifier[self] . identifier[settings] , literal[string] : identifier[self] . identifier[nodes] , literal[string] : identifier[self] . identifier[backward] } identifier[json] . identifier[dump] ( identifier[data] , identifier[fp] , identifier[ensure_ascii] = keyword[False] )
def do_save(self, fp=None): """Save to file. Parameters ---------- fp : `file` or `str`, optional Output file (default: stdout). """ if fp is None: fp = sys.stdout # depends on [control=['if'], data=['fp']] data = {'settings': self.settings, 'nodes': self.nodes, 'backward': self.backward} json.dump(data, fp, ensure_ascii=False)
def search_channels(self, **kwargs): """ Search for all channels by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = "/notification/v1/channel?{}".format( urlencode(params, doseq=True)) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) data = json.loads(response.data) channels = [] for datum in data.get("Channels", []): channels.append(self._channel_from_json(datum)) return channels
def function[search_channels, parameter[self]]: constant[ Search for all channels by parameters ] variable[params] assign[=] <ast.ListComp object at 0x7da18f810b20> variable[url] assign[=] call[constant[/notification/v1/channel?{}].format, parameter[call[name[urlencode], parameter[name[params]]]]] variable[response] assign[=] call[call[name[NWS_DAO], parameter[]].getURL, parameter[name[url], name[self]._read_headers]] if compare[name[response].status not_equal[!=] constant[200]] begin[:] <ast.Raise object at 0x7da18f812bc0> variable[data] assign[=] call[name[json].loads, parameter[name[response].data]] variable[channels] assign[=] list[[]] for taget[name[datum]] in starred[call[name[data].get, parameter[constant[Channels], list[[]]]]] begin[:] call[name[channels].append, parameter[call[name[self]._channel_from_json, parameter[name[datum]]]]] return[name[channels]]
keyword[def] identifier[search_channels] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[params] =[( identifier[key] , identifier[kwargs] [ identifier[key] ]) keyword[for] identifier[key] keyword[in] identifier[sorted] ( identifier[kwargs] . identifier[keys] ())] identifier[url] = literal[string] . identifier[format] ( identifier[urlencode] ( identifier[params] , identifier[doseq] = keyword[True] )) identifier[response] = identifier[NWS_DAO] (). identifier[getURL] ( identifier[url] , identifier[self] . identifier[_read_headers] ) keyword[if] identifier[response] . identifier[status] != literal[int] : keyword[raise] identifier[DataFailureException] ( identifier[url] , identifier[response] . identifier[status] , identifier[response] . identifier[data] ) identifier[data] = identifier[json] . identifier[loads] ( identifier[response] . identifier[data] ) identifier[channels] =[] keyword[for] identifier[datum] keyword[in] identifier[data] . identifier[get] ( literal[string] ,[]): identifier[channels] . identifier[append] ( identifier[self] . identifier[_channel_from_json] ( identifier[datum] )) keyword[return] identifier[channels]
def search_channels(self, **kwargs): """ Search for all channels by parameters """ params = [(key, kwargs[key]) for key in sorted(kwargs.keys())] url = '/notification/v1/channel?{}'.format(urlencode(params, doseq=True)) response = NWS_DAO().getURL(url, self._read_headers) if response.status != 200: raise DataFailureException(url, response.status, response.data) # depends on [control=['if'], data=[]] data = json.loads(response.data) channels = [] for datum in data.get('Channels', []): channels.append(self._channel_from_json(datum)) # depends on [control=['for'], data=['datum']] return channels
def nvmlDeviceSetPowerManagementLimit(handle, limit): r""" /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. * * \note Limit is not persistent across reboots or driver unloads. * Enable persistent mode to prevent driver from unloading when no application is using the device. * * @param device The identifier of the target device * @param limit Power management limit in milliwatts to set * * @return * - \ref NVML_SUCCESS if \a limit has been set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a defaultLimit is out of range * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPowerManagementLimitConstraints * @see nvmlDeviceGetPowerManagementDefaultLimit */ nvmlReturn_t DECLDIR nvmlDeviceSetPowerManagementLimit """ fn = _nvmlGetFunctionPointer("nvmlDeviceSetPowerManagementLimit") ret = fn(handle, c_uint(limit)) _nvmlCheckReturn(ret) return None
def function[nvmlDeviceSetPowerManagementLimit, parameter[handle, limit]]: constant[ /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. * * \note Limit is not persistent across reboots or driver unloads. * Enable persistent mode to prevent driver from unloading when no application is using the device. * * @param device The identifier of the target device * @param limit Power management limit in milliwatts to set * * @return * - \ref NVML_SUCCESS if \a limit has been set * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a defaultLimit is out of range * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPowerManagementLimitConstraints * @see nvmlDeviceGetPowerManagementDefaultLimit */ nvmlReturn_t DECLDIR nvmlDeviceSetPowerManagementLimit ] variable[fn] assign[=] call[name[_nvmlGetFunctionPointer], parameter[constant[nvmlDeviceSetPowerManagementLimit]]] variable[ret] assign[=] call[name[fn], parameter[name[handle], call[name[c_uint], parameter[name[limit]]]]] call[name[_nvmlCheckReturn], parameter[name[ret]]] return[constant[None]]
keyword[def] identifier[nvmlDeviceSetPowerManagementLimit] ( identifier[handle] , identifier[limit] ): literal[string] identifier[fn] = identifier[_nvmlGetFunctionPointer] ( literal[string] ) identifier[ret] = identifier[fn] ( identifier[handle] , identifier[c_uint] ( identifier[limit] )) identifier[_nvmlCheckReturn] ( identifier[ret] ) keyword[return] keyword[None]
def nvmlDeviceSetPowerManagementLimit(handle, limit): """ /** * Set new power limit of this device. * * For Kepler &tm; or newer fully supported devices. * Requires root/admin permissions. * * See \\ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. * * \\note Limit is not persistent across reboots or driver unloads. * Enable persistent mode to prevent driver from unloading when no application is using the device. * * @param device The identifier of the target device * @param limit Power management limit in milliwatts to set * * @return * - \\ref NVML_SUCCESS if \\a limit has been set * - \\ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized * - \\ref NVML_ERROR_INVALID_ARGUMENT if \\a device is invalid or \\a defaultLimit is out of range * - \\ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature * - \\ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible * - \\ref NVML_ERROR_UNKNOWN on any unexpected error * * @see nvmlDeviceGetPowerManagementLimitConstraints * @see nvmlDeviceGetPowerManagementDefaultLimit */ nvmlReturn_t DECLDIR nvmlDeviceSetPowerManagementLimit """ fn = _nvmlGetFunctionPointer('nvmlDeviceSetPowerManagementLimit') ret = fn(handle, c_uint(limit)) _nvmlCheckReturn(ret) return None
def _adjust_anchors(anchor_data, ufo, component): """Adjust anchors to which a mark component may have been attached.""" glyph = ufo[component.baseGlyph] t = Transform(*component.transformation) for anchor in glyph.anchors: # only adjust if this anchor has data and the component also contains # the associated mark anchor (e.g. "_top" for "top") if anchor.name in anchor_data and any( a.name == "_" + anchor.name for a in glyph.anchors ): anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y))
def function[_adjust_anchors, parameter[anchor_data, ufo, component]]: constant[Adjust anchors to which a mark component may have been attached.] variable[glyph] assign[=] call[name[ufo]][name[component].baseGlyph] variable[t] assign[=] call[name[Transform], parameter[<ast.Starred object at 0x7da1b0338490>]] for taget[name[anchor]] in starred[name[glyph].anchors] begin[:] if <ast.BoolOp object at 0x7da1b0338610> begin[:] call[name[anchor_data]][name[anchor].name] assign[=] call[name[t].transformPoint, parameter[tuple[[<ast.Attribute object at 0x7da1b0339540>, <ast.Attribute object at 0x7da1b03395a0>]]]]
keyword[def] identifier[_adjust_anchors] ( identifier[anchor_data] , identifier[ufo] , identifier[component] ): literal[string] identifier[glyph] = identifier[ufo] [ identifier[component] . identifier[baseGlyph] ] identifier[t] = identifier[Transform] (* identifier[component] . identifier[transformation] ) keyword[for] identifier[anchor] keyword[in] identifier[glyph] . identifier[anchors] : keyword[if] identifier[anchor] . identifier[name] keyword[in] identifier[anchor_data] keyword[and] identifier[any] ( identifier[a] . identifier[name] == literal[string] + identifier[anchor] . identifier[name] keyword[for] identifier[a] keyword[in] identifier[glyph] . identifier[anchors] ): identifier[anchor_data] [ identifier[anchor] . identifier[name] ]= identifier[t] . identifier[transformPoint] (( identifier[anchor] . identifier[x] , identifier[anchor] . identifier[y] ))
def _adjust_anchors(anchor_data, ufo, component): """Adjust anchors to which a mark component may have been attached.""" glyph = ufo[component.baseGlyph] t = Transform(*component.transformation) for anchor in glyph.anchors: # only adjust if this anchor has data and the component also contains # the associated mark anchor (e.g. "_top" for "top") if anchor.name in anchor_data and any((a.name == '_' + anchor.name for a in glyph.anchors)): anchor_data[anchor.name] = t.transformPoint((anchor.x, anchor.y)) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['anchor']]
def sample(program: Union[circuits.Circuit, schedules.Schedule], *, noise: devices.NoiseModel = devices.NO_NOISE, param_resolver: Optional[study.ParamResolver] = None, repetitions: int = 1, dtype: Type[np.number] = np.complex64) -> study.TrialResult: """Simulates sampling from the given circuit or schedule. Args: program: The circuit or schedule to sample from. noise: Noise model to use while running the simulation. param_resolver: Parameters to run with the program. repetitions: The number of samples to take. dtype: The `numpy.dtype` used by the simulation. Typically one of `numpy.complex64` or `numpy.complex128`. Favors speed over precision by default, i.e. uses `numpy.complex64`. """ # State vector simulation is much faster, but only works if no randomness. if noise == devices.NO_NOISE and protocols.has_unitary(program): return sparse_simulator.Simulator(dtype=dtype).run( program=program, param_resolver=param_resolver, repetitions=repetitions) return density_matrix_simulator.DensityMatrixSimulator( dtype=dtype, noise=noise).run(program=program, param_resolver=param_resolver, repetitions=repetitions)
def function[sample, parameter[program]]: constant[Simulates sampling from the given circuit or schedule. Args: program: The circuit or schedule to sample from. noise: Noise model to use while running the simulation. param_resolver: Parameters to run with the program. repetitions: The number of samples to take. dtype: The `numpy.dtype` used by the simulation. Typically one of `numpy.complex64` or `numpy.complex128`. Favors speed over precision by default, i.e. uses `numpy.complex64`. ] if <ast.BoolOp object at 0x7da1b1c3e5f0> begin[:] return[call[call[name[sparse_simulator].Simulator, parameter[]].run, parameter[]]] return[call[call[name[density_matrix_simulator].DensityMatrixSimulator, parameter[]].run, parameter[]]]
keyword[def] identifier[sample] ( identifier[program] : identifier[Union] [ identifier[circuits] . identifier[Circuit] , identifier[schedules] . identifier[Schedule] ], *, identifier[noise] : identifier[devices] . identifier[NoiseModel] = identifier[devices] . identifier[NO_NOISE] , identifier[param_resolver] : identifier[Optional] [ identifier[study] . identifier[ParamResolver] ]= keyword[None] , identifier[repetitions] : identifier[int] = literal[int] , identifier[dtype] : identifier[Type] [ identifier[np] . identifier[number] ]= identifier[np] . identifier[complex64] )-> identifier[study] . identifier[TrialResult] : literal[string] keyword[if] identifier[noise] == identifier[devices] . identifier[NO_NOISE] keyword[and] identifier[protocols] . identifier[has_unitary] ( identifier[program] ): keyword[return] identifier[sparse_simulator] . identifier[Simulator] ( identifier[dtype] = identifier[dtype] ). identifier[run] ( identifier[program] = identifier[program] , identifier[param_resolver] = identifier[param_resolver] , identifier[repetitions] = identifier[repetitions] ) keyword[return] identifier[density_matrix_simulator] . identifier[DensityMatrixSimulator] ( identifier[dtype] = identifier[dtype] , identifier[noise] = identifier[noise] ). identifier[run] ( identifier[program] = identifier[program] , identifier[param_resolver] = identifier[param_resolver] , identifier[repetitions] = identifier[repetitions] )
def sample(program: Union[circuits.Circuit, schedules.Schedule], *, noise: devices.NoiseModel=devices.NO_NOISE, param_resolver: Optional[study.ParamResolver]=None, repetitions: int=1, dtype: Type[np.number]=np.complex64) -> study.TrialResult: """Simulates sampling from the given circuit or schedule. Args: program: The circuit or schedule to sample from. noise: Noise model to use while running the simulation. param_resolver: Parameters to run with the program. repetitions: The number of samples to take. dtype: The `numpy.dtype` used by the simulation. Typically one of `numpy.complex64` or `numpy.complex128`. Favors speed over precision by default, i.e. uses `numpy.complex64`. """ # State vector simulation is much faster, but only works if no randomness. if noise == devices.NO_NOISE and protocols.has_unitary(program): return sparse_simulator.Simulator(dtype=dtype).run(program=program, param_resolver=param_resolver, repetitions=repetitions) # depends on [control=['if'], data=[]] return density_matrix_simulator.DensityMatrixSimulator(dtype=dtype, noise=noise).run(program=program, param_resolver=param_resolver, repetitions=repetitions)
async def _call_handle(self, func, *args): """ call and check result of handle_query/read/insert/update """ await async_call(func, *args) if self.is_finished: raise FinishQuitException()
<ast.AsyncFunctionDef object at 0x7da20e957fd0>
keyword[async] keyword[def] identifier[_call_handle] ( identifier[self] , identifier[func] ,* identifier[args] ): literal[string] keyword[await] identifier[async_call] ( identifier[func] ,* identifier[args] ) keyword[if] identifier[self] . identifier[is_finished] : keyword[raise] identifier[FinishQuitException] ()
async def _call_handle(self, func, *args): """ call and check result of handle_query/read/insert/update """ await async_call(func, *args) if self.is_finished: raise FinishQuitException() # depends on [control=['if'], data=[]]
def schema_to_index(schema, index_names=None): """Get index/doc_type given a schema URL. :param schema: The schema name :param index_names: A list of index name. :returns: A tuple containing (index, doc_type). """ parts = schema.split('/') doc_type = os.path.splitext(parts[-1]) if doc_type[1] not in {'.json', }: return (None, None) if index_names is None: return (build_index_name(current_app, *parts), doc_type[0]) for start in range(len(parts)): index_name = build_index_name(current_app, *parts[start:]) if index_name in index_names: return (index_name, doc_type[0]) return (None, None)
def function[schema_to_index, parameter[schema, index_names]]: constant[Get index/doc_type given a schema URL. :param schema: The schema name :param index_names: A list of index name. :returns: A tuple containing (index, doc_type). ] variable[parts] assign[=] call[name[schema].split, parameter[constant[/]]] variable[doc_type] assign[=] call[name[os].path.splitext, parameter[call[name[parts]][<ast.UnaryOp object at 0x7da18eb57490>]]] if compare[call[name[doc_type]][constant[1]] <ast.NotIn object at 0x7da2590d7190> <ast.Set object at 0x7da18eb56380>] begin[:] return[tuple[[<ast.Constant object at 0x7da18eb57a30>, <ast.Constant object at 0x7da18eb57460>]]] if compare[name[index_names] is constant[None]] begin[:] return[tuple[[<ast.Call object at 0x7da18eb543d0>, <ast.Subscript object at 0x7da18eb55240>]]] for taget[name[start]] in starred[call[name[range], parameter[call[name[len], parameter[name[parts]]]]]] begin[:] variable[index_name] assign[=] call[name[build_index_name], parameter[name[current_app], <ast.Starred object at 0x7da18eb54820>]] if compare[name[index_name] in name[index_names]] begin[:] return[tuple[[<ast.Name object at 0x7da18eb56410>, <ast.Subscript object at 0x7da18eb55780>]]] return[tuple[[<ast.Constant object at 0x7da18eb54d00>, <ast.Constant object at 0x7da18eb55fc0>]]]
keyword[def] identifier[schema_to_index] ( identifier[schema] , identifier[index_names] = keyword[None] ): literal[string] identifier[parts] = identifier[schema] . identifier[split] ( literal[string] ) identifier[doc_type] = identifier[os] . identifier[path] . identifier[splitext] ( identifier[parts] [- literal[int] ]) keyword[if] identifier[doc_type] [ literal[int] ] keyword[not] keyword[in] { literal[string] ,}: keyword[return] ( keyword[None] , keyword[None] ) keyword[if] identifier[index_names] keyword[is] keyword[None] : keyword[return] ( identifier[build_index_name] ( identifier[current_app] ,* identifier[parts] ), identifier[doc_type] [ literal[int] ]) keyword[for] identifier[start] keyword[in] identifier[range] ( identifier[len] ( identifier[parts] )): identifier[index_name] = identifier[build_index_name] ( identifier[current_app] ,* identifier[parts] [ identifier[start] :]) keyword[if] identifier[index_name] keyword[in] identifier[index_names] : keyword[return] ( identifier[index_name] , identifier[doc_type] [ literal[int] ]) keyword[return] ( keyword[None] , keyword[None] )
def schema_to_index(schema, index_names=None): """Get index/doc_type given a schema URL. :param schema: The schema name :param index_names: A list of index name. :returns: A tuple containing (index, doc_type). """ parts = schema.split('/') doc_type = os.path.splitext(parts[-1]) if doc_type[1] not in {'.json'}: return (None, None) # depends on [control=['if'], data=[]] if index_names is None: return (build_index_name(current_app, *parts), doc_type[0]) # depends on [control=['if'], data=[]] for start in range(len(parts)): index_name = build_index_name(current_app, *parts[start:]) if index_name in index_names: return (index_name, doc_type[0]) # depends on [control=['if'], data=['index_name']] # depends on [control=['for'], data=['start']] return (None, None)
def _get_batches(self, items): """given a list yield list at most self.max_batch_size in size""" for i in xrange(0, len(items), self.max_batch_size): yield items[i:i + self.max_batch_size]
def function[_get_batches, parameter[self, items]]: constant[given a list yield list at most self.max_batch_size in size] for taget[name[i]] in starred[call[name[xrange], parameter[constant[0], call[name[len], parameter[name[items]]], name[self].max_batch_size]]] begin[:] <ast.Yield object at 0x7da18dc98940>
keyword[def] identifier[_get_batches] ( identifier[self] , identifier[items] ): literal[string] keyword[for] identifier[i] keyword[in] identifier[xrange] ( literal[int] , identifier[len] ( identifier[items] ), identifier[self] . identifier[max_batch_size] ): keyword[yield] identifier[items] [ identifier[i] : identifier[i] + identifier[self] . identifier[max_batch_size] ]
def _get_batches(self, items): """given a list yield list at most self.max_batch_size in size""" for i in xrange(0, len(items), self.max_batch_size): yield items[i:i + self.max_batch_size] # depends on [control=['for'], data=['i']]
def write_parent (self, url_data): """Write url_data.parent_url.""" self.write(self.part('parenturl') + self.spaces("parenturl")) txt = url_data.parent_url if url_data.line > 0: txt += _(", line %d") % url_data.line if url_data.column > 0: txt += _(", col %d") % url_data.column if url_data.page > 0: txt += _(", page %d") % url_data.page self.writeln(txt, color=self.colorparent)
def function[write_parent, parameter[self, url_data]]: constant[Write url_data.parent_url.] call[name[self].write, parameter[binary_operation[call[name[self].part, parameter[constant[parenturl]]] + call[name[self].spaces, parameter[constant[parenturl]]]]]] variable[txt] assign[=] name[url_data].parent_url if compare[name[url_data].line greater[>] constant[0]] begin[:] <ast.AugAssign object at 0x7da1b0911ea0> if compare[name[url_data].column greater[>] constant[0]] begin[:] <ast.AugAssign object at 0x7da1b0910910> if compare[name[url_data].page greater[>] constant[0]] begin[:] <ast.AugAssign object at 0x7da1b09eb070> call[name[self].writeln, parameter[name[txt]]]
keyword[def] identifier[write_parent] ( identifier[self] , identifier[url_data] ): literal[string] identifier[self] . identifier[write] ( identifier[self] . identifier[part] ( literal[string] )+ identifier[self] . identifier[spaces] ( literal[string] )) identifier[txt] = identifier[url_data] . identifier[parent_url] keyword[if] identifier[url_data] . identifier[line] > literal[int] : identifier[txt] += identifier[_] ( literal[string] )% identifier[url_data] . identifier[line] keyword[if] identifier[url_data] . identifier[column] > literal[int] : identifier[txt] += identifier[_] ( literal[string] )% identifier[url_data] . identifier[column] keyword[if] identifier[url_data] . identifier[page] > literal[int] : identifier[txt] += identifier[_] ( literal[string] )% identifier[url_data] . identifier[page] identifier[self] . identifier[writeln] ( identifier[txt] , identifier[color] = identifier[self] . identifier[colorparent] )
def write_parent(self, url_data): """Write url_data.parent_url.""" self.write(self.part('parenturl') + self.spaces('parenturl')) txt = url_data.parent_url if url_data.line > 0: txt += _(', line %d') % url_data.line # depends on [control=['if'], data=[]] if url_data.column > 0: txt += _(', col %d') % url_data.column # depends on [control=['if'], data=[]] if url_data.page > 0: txt += _(', page %d') % url_data.page # depends on [control=['if'], data=[]] self.writeln(txt, color=self.colorparent)
def has_description(self, param): """ if a parameter has a description """ return param in self.param_description.keys() and \ not self.param_description[param].isspace()
def function[has_description, parameter[self, param]]: constant[ if a parameter has a description ] return[<ast.BoolOp object at 0x7da18dc9beb0>]
keyword[def] identifier[has_description] ( identifier[self] , identifier[param] ): literal[string] keyword[return] identifier[param] keyword[in] identifier[self] . identifier[param_description] . identifier[keys] () keyword[and] keyword[not] identifier[self] . identifier[param_description] [ identifier[param] ]. identifier[isspace] ()
def has_description(self, param): """ if a parameter has a description """ return param in self.param_description.keys() and (not self.param_description[param].isspace())
def _sig(self, name, dtype=BIT, defVal=None): """ Create signal in this unit """ if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() container = dtype.fromPy(None) for f in dtype.fields: if f.name is not None: r = self._sig("%s_%s" % (name, f.name), f.dtype) setattr(container, f.name, r) return container return self._ctx.sig(name, dtype=dtype, defVal=defVal)
def function[_sig, parameter[self, name, dtype, defVal]]: constant[ Create signal in this unit ] if call[name[isinstance], parameter[name[dtype], name[HStruct]]] begin[:] if compare[name[defVal] is_not constant[None]] begin[:] <ast.Raise object at 0x7da1b03e3640> variable[container] assign[=] call[name[dtype].fromPy, parameter[constant[None]]] for taget[name[f]] in starred[name[dtype].fields] begin[:] if compare[name[f].name is_not constant[None]] begin[:] variable[r] assign[=] call[name[self]._sig, parameter[binary_operation[constant[%s_%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b03e07f0>, <ast.Attribute object at 0x7da1b03e0c70>]]], name[f].dtype]] call[name[setattr], parameter[name[container], name[f].name, name[r]]] return[name[container]] return[call[name[self]._ctx.sig, parameter[name[name]]]]
keyword[def] identifier[_sig] ( identifier[self] , identifier[name] , identifier[dtype] = identifier[BIT] , identifier[defVal] = keyword[None] ): literal[string] keyword[if] identifier[isinstance] ( identifier[dtype] , identifier[HStruct] ): keyword[if] identifier[defVal] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[NotImplementedError] () identifier[container] = identifier[dtype] . identifier[fromPy] ( keyword[None] ) keyword[for] identifier[f] keyword[in] identifier[dtype] . identifier[fields] : keyword[if] identifier[f] . identifier[name] keyword[is] keyword[not] keyword[None] : identifier[r] = identifier[self] . identifier[_sig] ( literal[string] %( identifier[name] , identifier[f] . identifier[name] ), identifier[f] . identifier[dtype] ) identifier[setattr] ( identifier[container] , identifier[f] . identifier[name] , identifier[r] ) keyword[return] identifier[container] keyword[return] identifier[self] . identifier[_ctx] . identifier[sig] ( identifier[name] , identifier[dtype] = identifier[dtype] , identifier[defVal] = identifier[defVal] )
def _sig(self, name, dtype=BIT, defVal=None): """ Create signal in this unit """ if isinstance(dtype, HStruct): if defVal is not None: raise NotImplementedError() # depends on [control=['if'], data=[]] container = dtype.fromPy(None) for f in dtype.fields: if f.name is not None: r = self._sig('%s_%s' % (name, f.name), f.dtype) setattr(container, f.name, r) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']] return container # depends on [control=['if'], data=[]] return self._ctx.sig(name, dtype=dtype, defVal=defVal)
def assertTraceDoesNotContain(response, message): """ Raise TestStepFail if response.verify_trace finds message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns True. """ if not hasattr(response, "verify_trace"): raise AttributeError("Response object does not contain verify_trace method!") if response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message)
def function[assertTraceDoesNotContain, parameter[response, message]]: constant[ Raise TestStepFail if response.verify_trace finds message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns True. ] if <ast.UnaryOp object at 0x7da1b0e253c0> begin[:] <ast.Raise object at 0x7da1b0e25630> if call[name[response].verify_trace, parameter[name[message], constant[False]]] begin[:] <ast.Raise object at 0x7da1b0e25b70>
keyword[def] identifier[assertTraceDoesNotContain] ( identifier[response] , identifier[message] ): literal[string] keyword[if] keyword[not] identifier[hasattr] ( identifier[response] , literal[string] ): keyword[raise] identifier[AttributeError] ( literal[string] ) keyword[if] identifier[response] . identifier[verify_trace] ( identifier[message] , keyword[False] ): keyword[raise] identifier[TestStepFail] ( literal[string] % identifier[message] )
def assertTraceDoesNotContain(response, message): """ Raise TestStepFail if response.verify_trace finds message from response traces. :param response: Response. Must contain method verify_trace :param message: Message to look for :return: Nothing :raises: AttributeError if response does not contain verify_trace method. TestStepFail if verify_trace returns True. """ if not hasattr(response, 'verify_trace'): raise AttributeError('Response object does not contain verify_trace method!') # depends on [control=['if'], data=[]] if response.verify_trace(message, False): raise TestStepFail('Assert: Message(s) "%s" in response' % message) # depends on [control=['if'], data=[]]
def advertise(self, routers=None, name=None, timeout=None, router_file=None, jitter=None): """Advertise with Hyperbahn. After a successful advertisement, Hyperbahn will establish long-lived connections with your application. These connections are used to load balance inbound and outbound requests to other applications on the Hyperbahn network. Re-advertisement happens periodically after calling this method (every minute). Hyperbahn will eject us from the network if it doesn't get a re-advertise from us after 5 minutes. This function may be called multiple times if it fails. If it succeeds, all consecutive calls are ignored. :param list routers: A seed list of known Hyperbahn addresses to attempt contact with. Entries should be of the form ``"host:port"``. :param string name: The name your application identifies itself as. This is usually unneeded because in the common case it will match the ``name`` you initialized the ``TChannel`` instance with. This is the identifier other services will use to make contact with you. :param timeout: The timeout (in sec) for the initial advertise attempt. Defaults to 30 seconds. :param jitter: Variance allowed in the interval per request. Defaults to 5 seconds. The jitter applies to the initial advertise request as well. :param router_file: The host file that contains the routers information. The file should contain a JSON stringified format of the routers parameter. Either routers or router_file should be provided. If both provided, a ValueError will be raised. :returns: A future that resolves to the remote server's response after the first advertise finishes. :raises TimeoutError: When unable to make our first advertise request to Hyperbahn. Subsequent requests may fail but will be ignored. """ if routers is not None and router_file is not None: raise ValueError( 'Only one of routers and router_file can be provided.') if routers is None and router_file is not None: # should just let the exceptions fly try: with open(router_file, 'r') as json_data: routers = json.load(json_data) except (IOError, OSError, ValueError): log.exception('Failed to read seed routers list.') raise @gen.coroutine def _advertise(): result = yield self._dep_tchannel.advertise( routers=routers, name=name, timeout=timeout, ) body = yield result.get_body() headers = yield result.get_header() response = Response(json.loads(body), headers or {}) raise gen.Return(response) def _on_advertise(future): if not future.exception(): return # If the request failed, clear the response so that we can try # again. with self._advertise_lock: # `is` comparison to ensure we're not deleting another Future. if self._advertise_response is future: self._advertise_response = None with self._advertise_lock: if self._advertise_response is not None: return self._advertise_response future = self._advertise_response = _advertise() # We call add_done_callback here rather than when we call _advertise() # because if the future has already resolved by the time we call # add_done_callback, the callback will immediately be executed. The # callback will try to acquire the advertise_lock which we already # hold and end up in a deadlock. future.add_done_callback(_on_advertise) return future
def function[advertise, parameter[self, routers, name, timeout, router_file, jitter]]: constant[Advertise with Hyperbahn. After a successful advertisement, Hyperbahn will establish long-lived connections with your application. These connections are used to load balance inbound and outbound requests to other applications on the Hyperbahn network. Re-advertisement happens periodically after calling this method (every minute). Hyperbahn will eject us from the network if it doesn't get a re-advertise from us after 5 minutes. This function may be called multiple times if it fails. If it succeeds, all consecutive calls are ignored. :param list routers: A seed list of known Hyperbahn addresses to attempt contact with. Entries should be of the form ``"host:port"``. :param string name: The name your application identifies itself as. This is usually unneeded because in the common case it will match the ``name`` you initialized the ``TChannel`` instance with. This is the identifier other services will use to make contact with you. :param timeout: The timeout (in sec) for the initial advertise attempt. Defaults to 30 seconds. :param jitter: Variance allowed in the interval per request. Defaults to 5 seconds. The jitter applies to the initial advertise request as well. :param router_file: The host file that contains the routers information. The file should contain a JSON stringified format of the routers parameter. Either routers or router_file should be provided. If both provided, a ValueError will be raised. :returns: A future that resolves to the remote server's response after the first advertise finishes. :raises TimeoutError: When unable to make our first advertise request to Hyperbahn. Subsequent requests may fail but will be ignored. ] if <ast.BoolOp object at 0x7da18dc9a470> begin[:] <ast.Raise object at 0x7da18dc99660> if <ast.BoolOp object at 0x7da18dc98370> begin[:] <ast.Try object at 0x7da18dc9a0e0> def function[_advertise, parameter[]]: variable[result] assign[=] <ast.Yield object at 0x7da18dc98d60> variable[body] assign[=] <ast.Yield object at 0x7da18dc9b310> variable[headers] assign[=] <ast.Yield object at 0x7da18dc994e0> variable[response] assign[=] call[name[Response], parameter[call[name[json].loads, parameter[name[body]]], <ast.BoolOp object at 0x7da20c7cbb50>]] <ast.Raise object at 0x7da20c7cbe20> def function[_on_advertise, parameter[future]]: if <ast.UnaryOp object at 0x7da20c7c8070> begin[:] return[None] with name[self]._advertise_lock begin[:] if compare[name[self]._advertise_response is name[future]] begin[:] name[self]._advertise_response assign[=] constant[None] with name[self]._advertise_lock begin[:] if compare[name[self]._advertise_response is_not constant[None]] begin[:] return[name[self]._advertise_response] variable[future] assign[=] call[name[_advertise], parameter[]] call[name[future].add_done_callback, parameter[name[_on_advertise]]] return[name[future]]
keyword[def] identifier[advertise] ( identifier[self] , identifier[routers] = keyword[None] , identifier[name] = keyword[None] , identifier[timeout] = keyword[None] , identifier[router_file] = keyword[None] , identifier[jitter] = keyword[None] ): literal[string] keyword[if] identifier[routers] keyword[is] keyword[not] keyword[None] keyword[and] identifier[router_file] keyword[is] keyword[not] keyword[None] : keyword[raise] identifier[ValueError] ( literal[string] ) keyword[if] identifier[routers] keyword[is] keyword[None] keyword[and] identifier[router_file] keyword[is] keyword[not] keyword[None] : keyword[try] : keyword[with] identifier[open] ( identifier[router_file] , literal[string] ) keyword[as] identifier[json_data] : identifier[routers] = identifier[json] . identifier[load] ( identifier[json_data] ) keyword[except] ( identifier[IOError] , identifier[OSError] , identifier[ValueError] ): identifier[log] . identifier[exception] ( literal[string] ) keyword[raise] @ identifier[gen] . identifier[coroutine] keyword[def] identifier[_advertise] (): identifier[result] = keyword[yield] identifier[self] . identifier[_dep_tchannel] . identifier[advertise] ( identifier[routers] = identifier[routers] , identifier[name] = identifier[name] , identifier[timeout] = identifier[timeout] , ) identifier[body] = keyword[yield] identifier[result] . identifier[get_body] () identifier[headers] = keyword[yield] identifier[result] . identifier[get_header] () identifier[response] = identifier[Response] ( identifier[json] . identifier[loads] ( identifier[body] ), identifier[headers] keyword[or] {}) keyword[raise] identifier[gen] . identifier[Return] ( identifier[response] ) keyword[def] identifier[_on_advertise] ( identifier[future] ): keyword[if] keyword[not] identifier[future] . identifier[exception] (): keyword[return] keyword[with] identifier[self] . identifier[_advertise_lock] : keyword[if] identifier[self] . identifier[_advertise_response] keyword[is] identifier[future] : identifier[self] . identifier[_advertise_response] = keyword[None] keyword[with] identifier[self] . identifier[_advertise_lock] : keyword[if] identifier[self] . identifier[_advertise_response] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[self] . identifier[_advertise_response] identifier[future] = identifier[self] . identifier[_advertise_response] = identifier[_advertise] () identifier[future] . identifier[add_done_callback] ( identifier[_on_advertise] ) keyword[return] identifier[future]
def advertise(self, routers=None, name=None, timeout=None, router_file=None, jitter=None): """Advertise with Hyperbahn. After a successful advertisement, Hyperbahn will establish long-lived connections with your application. These connections are used to load balance inbound and outbound requests to other applications on the Hyperbahn network. Re-advertisement happens periodically after calling this method (every minute). Hyperbahn will eject us from the network if it doesn't get a re-advertise from us after 5 minutes. This function may be called multiple times if it fails. If it succeeds, all consecutive calls are ignored. :param list routers: A seed list of known Hyperbahn addresses to attempt contact with. Entries should be of the form ``"host:port"``. :param string name: The name your application identifies itself as. This is usually unneeded because in the common case it will match the ``name`` you initialized the ``TChannel`` instance with. This is the identifier other services will use to make contact with you. :param timeout: The timeout (in sec) for the initial advertise attempt. Defaults to 30 seconds. :param jitter: Variance allowed in the interval per request. Defaults to 5 seconds. The jitter applies to the initial advertise request as well. :param router_file: The host file that contains the routers information. The file should contain a JSON stringified format of the routers parameter. Either routers or router_file should be provided. If both provided, a ValueError will be raised. :returns: A future that resolves to the remote server's response after the first advertise finishes. :raises TimeoutError: When unable to make our first advertise request to Hyperbahn. Subsequent requests may fail but will be ignored. """ if routers is not None and router_file is not None: raise ValueError('Only one of routers and router_file can be provided.') # depends on [control=['if'], data=[]] if routers is None and router_file is not None: # should just let the exceptions fly try: with open(router_file, 'r') as json_data: routers = json.load(json_data) # depends on [control=['with'], data=['json_data']] # depends on [control=['try'], data=[]] except (IOError, OSError, ValueError): log.exception('Failed to read seed routers list.') raise # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] @gen.coroutine def _advertise(): result = (yield self._dep_tchannel.advertise(routers=routers, name=name, timeout=timeout)) body = (yield result.get_body()) headers = (yield result.get_header()) response = Response(json.loads(body), headers or {}) raise gen.Return(response) def _on_advertise(future): if not future.exception(): return # depends on [control=['if'], data=[]] # If the request failed, clear the response so that we can try # again. with self._advertise_lock: # `is` comparison to ensure we're not deleting another Future. if self._advertise_response is future: self._advertise_response = None # depends on [control=['if'], data=[]] # depends on [control=['with'], data=[]] with self._advertise_lock: if self._advertise_response is not None: return self._advertise_response # depends on [control=['if'], data=[]] future = self._advertise_response = _advertise() # depends on [control=['with'], data=[]] # We call add_done_callback here rather than when we call _advertise() # because if the future has already resolved by the time we call # add_done_callback, the callback will immediately be executed. The # callback will try to acquire the advertise_lock which we already # hold and end up in a deadlock. future.add_done_callback(_on_advertise) return future
def save(self, filename, format_='fasta'): """ Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. @raise ValueError: if C{format_} is 'fastq' and a read with no quality is present, or if an unknown format is requested. @return: An C{int} giving the number of reads in C{self}. """ format_ = format_.lower() count = 0 if isinstance(filename, str): try: with open(filename, 'w') as fp: for read in self: fp.write(read.toString(format_)) count += 1 except ValueError: unlink(filename) raise else: # We have a file-like object. for read in self: filename.write(read.toString(format_)) count += 1 return count
def function[save, parameter[self, filename, format_]]: constant[ Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. @raise ValueError: if C{format_} is 'fastq' and a read with no quality is present, or if an unknown format is requested. @return: An C{int} giving the number of reads in C{self}. ] variable[format_] assign[=] call[name[format_].lower, parameter[]] variable[count] assign[=] constant[0] if call[name[isinstance], parameter[name[filename], name[str]]] begin[:] <ast.Try object at 0x7da1b0cfd4b0> return[name[count]]
keyword[def] identifier[save] ( identifier[self] , identifier[filename] , identifier[format_] = literal[string] ): literal[string] identifier[format_] = identifier[format_] . identifier[lower] () identifier[count] = literal[int] keyword[if] identifier[isinstance] ( identifier[filename] , identifier[str] ): keyword[try] : keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[fp] : keyword[for] identifier[read] keyword[in] identifier[self] : identifier[fp] . identifier[write] ( identifier[read] . identifier[toString] ( identifier[format_] )) identifier[count] += literal[int] keyword[except] identifier[ValueError] : identifier[unlink] ( identifier[filename] ) keyword[raise] keyword[else] : keyword[for] identifier[read] keyword[in] identifier[self] : identifier[filename] . identifier[write] ( identifier[read] . identifier[toString] ( identifier[format_] )) identifier[count] += literal[int] keyword[return] identifier[count]
def save(self, filename, format_='fasta'): """ Write the reads to C{filename} in the requested format. @param filename: Either a C{str} file name to save into (the file will be overwritten) or an open file descriptor (e.g., sys.stdout). @param format_: A C{str} format to save as, either 'fasta', 'fastq' or 'fasta-ss'. @raise ValueError: if C{format_} is 'fastq' and a read with no quality is present, or if an unknown format is requested. @return: An C{int} giving the number of reads in C{self}. """ format_ = format_.lower() count = 0 if isinstance(filename, str): try: with open(filename, 'w') as fp: for read in self: fp.write(read.toString(format_)) count += 1 # depends on [control=['for'], data=['read']] # depends on [control=['with'], data=['fp']] # depends on [control=['try'], data=[]] except ValueError: unlink(filename) raise # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] else: # We have a file-like object. for read in self: filename.write(read.toString(format_)) count += 1 # depends on [control=['for'], data=['read']] return count
def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False): ''' :param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy). :param is_pause: If this is a pause to suspend all threads, any thread can be considered as the 'main' thread paused. ''' self._threads_suspended_single_notification.increment_suspend_time() if is_pause: self._threads_suspended_single_notification.on_pause() info = self._mark_suspend(thread, stop_reason) if is_pause: # Must set tracing after setting the state to suspend. frame = info.get_topmost_frame(thread) if frame is not None: try: self.set_trace_for_frame_and_parents(frame) finally: frame = None # If conditional breakpoint raises any exception during evaluation send the details to the client. if stop_reason == CMD_SET_BREAK and info.conditional_breakpoint_exception is not None: conditional_breakpoint_exception_tuple = info.conditional_breakpoint_exception info.conditional_breakpoint_exception = None self._send_breakpoint_condition_exception(thread, conditional_breakpoint_exception_tuple) if not suspend_other_threads and self.multi_threads_single_notification: # In the mode which gives a single notification when all threads are # stopped, stop all threads whenever a set_suspend is issued. suspend_other_threads = True if suspend_other_threads: # Suspend all other threads. all_threads = pydevd_utils.get_non_pydevd_threads() for t in all_threads: if getattr(t, 'pydev_do_not_trace', None): pass # skip some other threads, i.e. ipython history saving thread from debug console else: if t is thread: continue info = self._mark_suspend(t, CMD_THREAD_SUSPEND) frame = info.get_topmost_frame(t) # Reset the time as in this case this was not the main thread suspended. if frame is not None: try: self.set_trace_for_frame_and_parents(frame) finally: frame = None
def function[set_suspend, parameter[self, thread, stop_reason, suspend_other_threads, is_pause]]: constant[ :param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy). :param is_pause: If this is a pause to suspend all threads, any thread can be considered as the 'main' thread paused. ] call[name[self]._threads_suspended_single_notification.increment_suspend_time, parameter[]] if name[is_pause] begin[:] call[name[self]._threads_suspended_single_notification.on_pause, parameter[]] variable[info] assign[=] call[name[self]._mark_suspend, parameter[name[thread], name[stop_reason]]] if name[is_pause] begin[:] variable[frame] assign[=] call[name[info].get_topmost_frame, parameter[name[thread]]] if compare[name[frame] is_not constant[None]] begin[:] <ast.Try object at 0x7da20e957130> if <ast.BoolOp object at 0x7da20e9572e0> begin[:] variable[conditional_breakpoint_exception_tuple] assign[=] name[info].conditional_breakpoint_exception name[info].conditional_breakpoint_exception assign[=] constant[None] call[name[self]._send_breakpoint_condition_exception, parameter[name[thread], name[conditional_breakpoint_exception_tuple]]] if <ast.BoolOp object at 0x7da20e956f50> begin[:] variable[suspend_other_threads] assign[=] constant[True] if name[suspend_other_threads] begin[:] variable[all_threads] assign[=] call[name[pydevd_utils].get_non_pydevd_threads, parameter[]] for taget[name[t]] in starred[name[all_threads]] begin[:] if call[name[getattr], parameter[name[t], constant[pydev_do_not_trace], constant[None]]] begin[:] pass
keyword[def] identifier[set_suspend] ( identifier[self] , identifier[thread] , identifier[stop_reason] , identifier[suspend_other_threads] = keyword[False] , identifier[is_pause] = keyword[False] ): literal[string] identifier[self] . identifier[_threads_suspended_single_notification] . identifier[increment_suspend_time] () keyword[if] identifier[is_pause] : identifier[self] . identifier[_threads_suspended_single_notification] . identifier[on_pause] () identifier[info] = identifier[self] . identifier[_mark_suspend] ( identifier[thread] , identifier[stop_reason] ) keyword[if] identifier[is_pause] : identifier[frame] = identifier[info] . identifier[get_topmost_frame] ( identifier[thread] ) keyword[if] identifier[frame] keyword[is] keyword[not] keyword[None] : keyword[try] : identifier[self] . identifier[set_trace_for_frame_and_parents] ( identifier[frame] ) keyword[finally] : identifier[frame] = keyword[None] keyword[if] identifier[stop_reason] == identifier[CMD_SET_BREAK] keyword[and] identifier[info] . identifier[conditional_breakpoint_exception] keyword[is] keyword[not] keyword[None] : identifier[conditional_breakpoint_exception_tuple] = identifier[info] . identifier[conditional_breakpoint_exception] identifier[info] . identifier[conditional_breakpoint_exception] = keyword[None] identifier[self] . identifier[_send_breakpoint_condition_exception] ( identifier[thread] , identifier[conditional_breakpoint_exception_tuple] ) keyword[if] keyword[not] identifier[suspend_other_threads] keyword[and] identifier[self] . identifier[multi_threads_single_notification] : identifier[suspend_other_threads] = keyword[True] keyword[if] identifier[suspend_other_threads] : identifier[all_threads] = identifier[pydevd_utils] . identifier[get_non_pydevd_threads] () keyword[for] identifier[t] keyword[in] identifier[all_threads] : keyword[if] identifier[getattr] ( identifier[t] , literal[string] , keyword[None] ): keyword[pass] keyword[else] : keyword[if] identifier[t] keyword[is] identifier[thread] : keyword[continue] identifier[info] = identifier[self] . identifier[_mark_suspend] ( identifier[t] , identifier[CMD_THREAD_SUSPEND] ) identifier[frame] = identifier[info] . identifier[get_topmost_frame] ( identifier[t] ) keyword[if] identifier[frame] keyword[is] keyword[not] keyword[None] : keyword[try] : identifier[self] . identifier[set_trace_for_frame_and_parents] ( identifier[frame] ) keyword[finally] : identifier[frame] = keyword[None]
def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False): """ :param thread: The thread which should be suspended. :param stop_reason: Reason why the thread was suspended. :param suspend_other_threads: Whether to force other threads to be suspended (i.e.: when hitting a breakpoint with a suspend all threads policy). :param is_pause: If this is a pause to suspend all threads, any thread can be considered as the 'main' thread paused. """ self._threads_suspended_single_notification.increment_suspend_time() if is_pause: self._threads_suspended_single_notification.on_pause() # depends on [control=['if'], data=[]] info = self._mark_suspend(thread, stop_reason) if is_pause: # Must set tracing after setting the state to suspend. frame = info.get_topmost_frame(thread) if frame is not None: try: self.set_trace_for_frame_and_parents(frame) # depends on [control=['try'], data=[]] finally: frame = None # depends on [control=['if'], data=['frame']] # depends on [control=['if'], data=[]] # If conditional breakpoint raises any exception during evaluation send the details to the client. if stop_reason == CMD_SET_BREAK and info.conditional_breakpoint_exception is not None: conditional_breakpoint_exception_tuple = info.conditional_breakpoint_exception info.conditional_breakpoint_exception = None self._send_breakpoint_condition_exception(thread, conditional_breakpoint_exception_tuple) # depends on [control=['if'], data=[]] if not suspend_other_threads and self.multi_threads_single_notification: # In the mode which gives a single notification when all threads are # stopped, stop all threads whenever a set_suspend is issued. suspend_other_threads = True # depends on [control=['if'], data=[]] if suspend_other_threads: # Suspend all other threads. all_threads = pydevd_utils.get_non_pydevd_threads() for t in all_threads: if getattr(t, 'pydev_do_not_trace', None): pass # skip some other threads, i.e. ipython history saving thread from debug console # depends on [control=['if'], data=[]] else: if t is thread: continue # depends on [control=['if'], data=[]] info = self._mark_suspend(t, CMD_THREAD_SUSPEND) frame = info.get_topmost_frame(t) # Reset the time as in this case this was not the main thread suspended. if frame is not None: try: self.set_trace_for_frame_and_parents(frame) # depends on [control=['try'], data=[]] finally: frame = None # depends on [control=['if'], data=['frame']] # depends on [control=['for'], data=['t']] # depends on [control=['if'], data=[]]
def draw(self): """Draws the checkbox.""" if not self.visible: return # Blit the current checkbox's image. if self.isEnabled: if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton: if self.value: self.window.blit(self.surfaceOnDown, self.loc) else: self.window.blit(self.surfaceOffDown, self.loc) else: if self.value: self.window.blit(self.surfaceOn, self.loc) else: self.window.blit(self.surfaceOff, self.loc) else: if self.value: self.window.blit(self.surfaceOnDisabled, self.loc) else: self.window.blit(self.surfaceOffDisabled, self.loc)
def function[draw, parameter[self]]: constant[Draws the checkbox.] if <ast.UnaryOp object at 0x7da18ede5b10> begin[:] return[None] if name[self].isEnabled begin[:] if <ast.BoolOp object at 0x7da18ede71c0> begin[:] if name[self].value begin[:] call[name[self].window.blit, parameter[name[self].surfaceOnDown, name[self].loc]]
keyword[def] identifier[draw] ( identifier[self] ): literal[string] keyword[if] keyword[not] identifier[self] . identifier[visible] : keyword[return] keyword[if] identifier[self] . identifier[isEnabled] : keyword[if] identifier[self] . identifier[mouseIsDown] keyword[and] identifier[self] . identifier[lastMouseDownOverButton] keyword[and] identifier[self] . identifier[mouseOverButton] : keyword[if] identifier[self] . identifier[value] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOnDown] , identifier[self] . identifier[loc] ) keyword[else] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOffDown] , identifier[self] . identifier[loc] ) keyword[else] : keyword[if] identifier[self] . identifier[value] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOn] , identifier[self] . identifier[loc] ) keyword[else] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOff] , identifier[self] . identifier[loc] ) keyword[else] : keyword[if] identifier[self] . identifier[value] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOnDisabled] , identifier[self] . identifier[loc] ) keyword[else] : identifier[self] . identifier[window] . identifier[blit] ( identifier[self] . identifier[surfaceOffDisabled] , identifier[self] . identifier[loc] )
def draw(self): """Draws the checkbox.""" if not self.visible: return # depends on [control=['if'], data=[]] # Blit the current checkbox's image. if self.isEnabled: if self.mouseIsDown and self.lastMouseDownOverButton and self.mouseOverButton: if self.value: self.window.blit(self.surfaceOnDown, self.loc) # depends on [control=['if'], data=[]] else: self.window.blit(self.surfaceOffDown, self.loc) # depends on [control=['if'], data=[]] elif self.value: self.window.blit(self.surfaceOn, self.loc) # depends on [control=['if'], data=[]] else: self.window.blit(self.surfaceOff, self.loc) # depends on [control=['if'], data=[]] elif self.value: self.window.blit(self.surfaceOnDisabled, self.loc) # depends on [control=['if'], data=[]] else: self.window.blit(self.surfaceOffDisabled, self.loc)
def wns_send_message( uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs ): """ Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more information: https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx There are multiple ways to input notification data: 1. The simplest and least custom notification to send is to just pass a string to `message`. This will create a toast notification with one text element. e.g.: "This is my notification title" 2. You can also pass a dictionary to `message`: it can only contain one or both keys: ["text", "image"]. The value of each key must be a list with the text and src respectively. e.g.: { "text": ["text1", "text2"], "image": ["src1", "src2"], } 3. Passing a dictionary to `xml_data` will create one of three types of notifications depending on the dictionary data (toast, tile, badge). See `dict_to_xml_schema` docs for more information on dictionary formatting. 4. Passing a value to `raw_data` will create a `raw` notification and send the input data as is. :param uri: str: The device's unique notification uri. :param message: str|dict: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification. """ # Create a simple toast notification if message: wns_type = "wns/toast" if isinstance(message, str): message = { "text": [message, ], } prepared_data = _wns_prepare_toast(data=message, **kwargs) # Create a toast/tile/badge notification from a dictionary elif xml_data: xml = dict_to_xml_schema(xml_data) wns_type = "wns/%s" % xml.tag prepared_data = ET.tostring(xml) # Create a raw notification elif raw_data: wns_type = "wns/raw" prepared_data = raw_data else: raise TypeError( "At least one of the following parameters must be set:" "`message`, `xml_data`, `raw_data`" ) return _wns_send( uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id )
def function[wns_send_message, parameter[uri, message, xml_data, raw_data, application_id]]: constant[ Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more information: https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx There are multiple ways to input notification data: 1. The simplest and least custom notification to send is to just pass a string to `message`. This will create a toast notification with one text element. e.g.: "This is my notification title" 2. You can also pass a dictionary to `message`: it can only contain one or both keys: ["text", "image"]. The value of each key must be a list with the text and src respectively. e.g.: { "text": ["text1", "text2"], "image": ["src1", "src2"], } 3. Passing a dictionary to `xml_data` will create one of three types of notifications depending on the dictionary data (toast, tile, badge). See `dict_to_xml_schema` docs for more information on dictionary formatting. 4. Passing a value to `raw_data` will create a `raw` notification and send the input data as is. :param uri: str: The device's unique notification uri. :param message: str|dict: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification. ] if name[message] begin[:] variable[wns_type] assign[=] constant[wns/toast] if call[name[isinstance], parameter[name[message], name[str]]] begin[:] variable[message] assign[=] dictionary[[<ast.Constant object at 0x7da20e956fe0>], [<ast.List object at 0x7da20e956740>]] variable[prepared_data] assign[=] call[name[_wns_prepare_toast], parameter[]] return[call[name[_wns_send], parameter[]]]
keyword[def] identifier[wns_send_message] ( identifier[uri] , identifier[message] = keyword[None] , identifier[xml_data] = keyword[None] , identifier[raw_data] = keyword[None] , identifier[application_id] = keyword[None] ,** identifier[kwargs] ): literal[string] keyword[if] identifier[message] : identifier[wns_type] = literal[string] keyword[if] identifier[isinstance] ( identifier[message] , identifier[str] ): identifier[message] ={ literal[string] :[ identifier[message] ,], } identifier[prepared_data] = identifier[_wns_prepare_toast] ( identifier[data] = identifier[message] ,** identifier[kwargs] ) keyword[elif] identifier[xml_data] : identifier[xml] = identifier[dict_to_xml_schema] ( identifier[xml_data] ) identifier[wns_type] = literal[string] % identifier[xml] . identifier[tag] identifier[prepared_data] = identifier[ET] . identifier[tostring] ( identifier[xml] ) keyword[elif] identifier[raw_data] : identifier[wns_type] = literal[string] identifier[prepared_data] = identifier[raw_data] keyword[else] : keyword[raise] identifier[TypeError] ( literal[string] literal[string] ) keyword[return] identifier[_wns_send] ( identifier[uri] = identifier[uri] , identifier[data] = identifier[prepared_data] , identifier[wns_type] = identifier[wns_type] , identifier[application_id] = identifier[application_id] )
def wns_send_message(uri, message=None, xml_data=None, raw_data=None, application_id=None, **kwargs): """ Sends a notification request to WNS. There are four notification types that WNS can send: toast, tile, badge and raw. Toast, tile, and badge can all be customized to use different templates/icons/sounds/launch params/etc. See docs for more information: https://msdn.microsoft.com/en-us/library/windows/apps/br212853.aspx There are multiple ways to input notification data: 1. The simplest and least custom notification to send is to just pass a string to `message`. This will create a toast notification with one text element. e.g.: "This is my notification title" 2. You can also pass a dictionary to `message`: it can only contain one or both keys: ["text", "image"]. The value of each key must be a list with the text and src respectively. e.g.: { "text": ["text1", "text2"], "image": ["src1", "src2"], } 3. Passing a dictionary to `xml_data` will create one of three types of notifications depending on the dictionary data (toast, tile, badge). See `dict_to_xml_schema` docs for more information on dictionary formatting. 4. Passing a value to `raw_data` will create a `raw` notification and send the input data as is. :param uri: str: The device's unique notification uri. :param message: str|dict: The notification data to be sent. :param xml_data: dict: A dictionary containing data to be converted to an xml tree. :param raw_data: str: Data to be sent via a `raw` notification. """ # Create a simple toast notification if message: wns_type = 'wns/toast' if isinstance(message, str): message = {'text': [message]} # depends on [control=['if'], data=[]] prepared_data = _wns_prepare_toast(data=message, **kwargs) # depends on [control=['if'], data=[]] # Create a toast/tile/badge notification from a dictionary elif xml_data: xml = dict_to_xml_schema(xml_data) wns_type = 'wns/%s' % xml.tag prepared_data = ET.tostring(xml) # depends on [control=['if'], data=[]] # Create a raw notification elif raw_data: wns_type = 'wns/raw' prepared_data = raw_data # depends on [control=['if'], data=[]] else: raise TypeError('At least one of the following parameters must be set:`message`, `xml_data`, `raw_data`') return _wns_send(uri=uri, data=prepared_data, wns_type=wns_type, application_id=application_id)
def setup_path(): """Sets up the python include paths to include src""" import os.path; import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, "src")] + sys.path pass return
def function[setup_path, parameter[]]: constant[Sets up the python include paths to include src] import module[os.path] import module[sys] if call[name[sys].argv][constant[0]] begin[:] variable[top_dir] assign[=] call[name[os].path.dirname, parameter[call[name[os].path.abspath, parameter[call[name[sys].argv][constant[0]]]]]] name[sys].path assign[=] binary_operation[list[[<ast.Call object at 0x7da1b141d720>]] + name[sys].path] pass return[None]
keyword[def] identifier[setup_path] (): literal[string] keyword[import] identifier[os] . identifier[path] ; keyword[import] identifier[sys] keyword[if] identifier[sys] . identifier[argv] [ literal[int] ]: identifier[top_dir] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . identifier[path] . identifier[abspath] ( identifier[sys] . identifier[argv] [ literal[int] ])) identifier[sys] . identifier[path] =[ identifier[os] . identifier[path] . identifier[join] ( identifier[top_dir] , literal[string] )]+ identifier[sys] . identifier[path] keyword[pass] keyword[return]
def setup_path(): """Sets up the python include paths to include src""" import os.path import sys if sys.argv[0]: top_dir = os.path.dirname(os.path.abspath(sys.argv[0])) sys.path = [os.path.join(top_dir, 'src')] + sys.path pass # depends on [control=['if'], data=[]] return