text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def echo(root_resource, message): """Have the server echo our message back.""" params = dict(message=message) return root_resource.get(ECHO_PATH, params)
[ "def", "echo", "(", "root_resource", ",", "message", ")", ":", "params", "=", "dict", "(", "message", "=", "message", ")", "return", "root_resource", ".", "get", "(", "ECHO_PATH", ",", "params", ")" ]
39
0.025157
def to_astropy_column(llwcol, cls, copy=False, dtype=None, use_numpy_dtype=False, **kwargs): """Convert a :class:`~ligo.lw.table.Column` to `astropy.table.Column` Parameters ----------- llwcol : :class:`~ligo.lw.table.Column`, `numpy.ndarray`, iterable the LIGO_LW column t...
[ "def", "to_astropy_column", "(", "llwcol", ",", "cls", ",", "copy", "=", "False", ",", "dtype", "=", "None", ",", "use_numpy_dtype", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "dtype", "is", "None", ":", "# try and find dtype", "dtype", "=", ...
38.107143
0.000457
def minute(self): """ Extract the "minute" part from a date column. :returns: a single-column H2OFrame containing the "minute" part from the source frame. """ fr = H2OFrame._expr(expr=ExprNode("minute", self), cache=self._ex._cache) if fr._ex._cache.types_valid(): ...
[ "def", "minute", "(", "self", ")", ":", "fr", "=", "H2OFrame", ".", "_expr", "(", "expr", "=", "ExprNode", "(", "\"minute\"", ",", "self", ")", ",", "cache", "=", "self", ".", "_ex", ".", "_cache", ")", "if", "fr", ".", "_ex", ".", "_cache", ".",...
40.5
0.012077
def tell(self): "get the file descriptor's position relative to the file's beginning" with _fdopen(os.dup(self._fileno)) as fp: return fp.tell()
[ "def", "tell", "(", "self", ")", ":", "with", "_fdopen", "(", "os", ".", "dup", "(", "self", ".", "_fileno", ")", ")", "as", "fp", ":", "return", "fp", ".", "tell", "(", ")" ]
42.25
0.011628
def build_headermap(headers): """ Construct dictionary {header_file : set_of_included_files}. This function operates on "real" set of includes, in the sense that it parses each header file to check which files are included from there. """ # TODO: what happens if some headers are circularly depe...
[ "def", "build_headermap", "(", "headers", ")", ":", "# TODO: what happens if some headers are circularly dependent?", "headermap", "=", "{", "}", "for", "hfile", "in", "headers", ":", "headermap", "[", "hfile", "]", "=", "None", "for", "hfile", "in", "headers", ":...
37.956522
0.001117
def serialize(script_string): ''' str -> bytearray ''' string_tokens = script_string.split() serialized_script = bytearray() for token in string_tokens: if token == 'OP_CODESEPARATOR' or token == 'OP_PUSHDATA4': raise NotImplementedError('{} is a bad idea.'.format(token)) ...
[ "def", "serialize", "(", "script_string", ")", ":", "string_tokens", "=", "script_string", ".", "split", "(", ")", "serialized_script", "=", "bytearray", "(", ")", "for", "token", "in", "string_tokens", ":", "if", "token", "==", "'OP_CODESEPARATOR'", "or", "to...
35.636364
0.000621
def get_prebuilt_targets(build_context): """Return set of target names that are contained within cached base images These targets may be considered "pre-built", and skipped during build. """ logger.info('Scanning for cached base images') # deps that are part of cached based images contained_dep...
[ "def", "get_prebuilt_targets", "(", "build_context", ")", ":", "logger", ".", "info", "(", "'Scanning for cached base images'", ")", "# deps that are part of cached based images", "contained_deps", "=", "set", "(", ")", "# deps that are needed by images that are going to be built...
48.171429
0.000581
def normalize_name(name): ''' Strips the architecture from the specified package name, if necessary. Circumstances where this would be done include: * If the arch is 32 bit and the package name ends in a 32-bit arch. * If the arch matches the OS arch, or is ``noarch``. CLI Example: .. cod...
[ "def", "normalize_name", "(", "name", ")", ":", "try", ":", "arch", "=", "name", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "-", "1", "]", "if", "arch", "not", "in", "salt", ".", "utils", ".", "pkg", ".", "rpm", ".", "ARCHES", "+", "(", "...
30.416667
0.001328
def parse(trigger_word_file): """Parse the file for source and sink definitions. Returns: A definitions tuple with sources and sinks. """ with open(trigger_word_file) as fd: triggers_dict = json.load(fd) sources = [Source(s) for s in triggers_dict['sources']] sinks = [ Si...
[ "def", "parse", "(", "trigger_word_file", ")", ":", "with", "open", "(", "trigger_word_file", ")", "as", "fd", ":", "triggers_dict", "=", "json", ".", "load", "(", "fd", ")", "sources", "=", "[", "Source", "(", "s", ")", "for", "s", "in", "triggers_dic...
31.357143
0.002212
def scroll_by_key_down(self, dat, distance_togo): """ 模拟 page_up/down 方式来滚动 :param dat: :type dat: :param distance_togo: :type distance_togo: :return: :rtype: """ try: target = self.get_elements(dat) distance_done = 0 ...
[ "def", "scroll_by_key_down", "(", "self", ",", "dat", ",", "distance_togo", ")", ":", "try", ":", "target", "=", "self", ".", "get_elements", "(", "dat", ")", "distance_done", "=", "0", "while", "distance_done", "<", "distance_togo", ":", "chance", "=", "r...
33
0.002181
def __get_connection_SNS(): """ Ensure connection to SNS """ region = get_global_option('region') try: if (get_global_option('aws_access_key_id') and get_global_option('aws_secret_access_key')): logger.debug( 'Authenticating to SNS using ' ...
[ "def", "__get_connection_SNS", "(", ")", ":", "region", "=", "get_global_option", "(", "'region'", ")", "try", ":", "if", "(", "get_global_option", "(", "'aws_access_key_id'", ")", "and", "get_global_option", "(", "'aws_secret_access_key'", ")", ")", ":", "logger"...
36.166667
0.000898
def write_catalog(event_list, max_sep=8, min_link=8, debug=0): """ Generate a dt.ct for hypoDD for a series of events. Takes input event list from :func:`eqcorrscan.utils.catalog_to_dd.write_event` as a list of tuples of event id and sfile. It will read the pick information from the seisan for...
[ "def", "write_catalog", "(", "event_list", ",", "max_sep", "=", "8", ",", "min_link", "=", "8", ",", "debug", "=", "0", ")", ":", "# Cope with possibly being passed a zip in python 3.x", "event_list", "=", "list", "(", "event_list", ")", "f", "=", "open", "(",...
48.17931
0.00014
def get_access_token(self, code, client_id, client_secret): ''' Exchange a temporary code for an access token allowing access to a user's account See https://developer.wunderlist.com/documentation/concepts/authorization for more info ''' headers = { 'Content-Typ...
[ "def", "get_access_token", "(", "self", ",", "code", ",", "client_id", ",", "client_secret", ")", ":", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "data", "=", "{", "'client_id'", ":", "client_id", ",", "'client_secret'", ":", "clien...
41.35
0.01182
def _init_axis(self, fig, axis): """ Return an axis which may need to be initialized from a new figure. """ if not fig and self._create_fig: fig = plt.figure() l, b, r, t = self.fig_bounds inches = self.fig_inches fig.subplots_adjus...
[ "def", "_init_axis", "(", "self", ",", "fig", ",", "axis", ")", ":", "if", "not", "fig", "and", "self", ".", "_create_fig", ":", "fig", "=", "plt", ".", "figure", "(", ")", "l", ",", "b", ",", "r", ",", "t", "=", "self", ".", "fig_bounds", "inc...
38.347826
0.002212
def inspect_func(self, namesrc): """Take a function's (name, sourcecode) and return a triple of (name, sourcecode, signature)""" (name, src) = namesrc glbls = {} lcls = {} exec(src, glbls, lcls) assert name in lcls func = lcls[name] return name, src, signa...
[ "def", "inspect_func", "(", "self", ",", "namesrc", ")", ":", "(", "name", ",", "src", ")", "=", "namesrc", "glbls", "=", "{", "}", "lcls", "=", "{", "}", "exec", "(", "src", ",", "glbls", ",", "lcls", ")", "assert", "name", "in", "lcls", "func",...
35.777778
0.009091
def update_floatingip_statuses_cfg(self, context, router_id, fip_statuses): """Update operational status for one or several floating IPs. This is called by Cisco cfg agent to update the status of one or several floatingips. :param context: contains user information :param route...
[ "def", "update_floatingip_statuses_cfg", "(", "self", ",", "context", ",", "router_id", ",", "fip_statuses", ")", ":", "with", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "for", "(", "floatingip_id", ",", "status", ...
56.235294
0.001028
def tabulate_state_transitions(x, states, pos=None): """Construct a dataframe where each row provides information about a state transition. Parameters ---------- x : array_like, int 1-dimensional array of state values. states : set Set of states of interest. Any state value not in t...
[ "def", "tabulate_state_transitions", "(", "x", ",", "states", ",", "pos", "=", "None", ")", ":", "# check inputs", "x", "=", "asarray_ndim", "(", "x", ",", "1", ")", "check_integer_dtype", "(", "x", ")", "x", "=", "memoryview_safe", "(", "x", ")", "# fin...
30.72
0.001682
def _compute_closed_central_moments(self, central_from_raw_exprs, n_counter, k_counter): """ Computes parametric expressions (e.g. in terms of mean, variance, covariances) for all central moments up to max_order + 1 order. :param central_from_raw_exprs: :param n_counter: a list ...
[ "def", "_compute_closed_central_moments", "(", "self", ",", "central_from_raw_exprs", ",", "n_counter", ",", "k_counter", ")", ":", "n_species", "=", "len", "(", "[", "None", "for", "pm", "in", "k_counter", "if", "pm", ".", "order", "==", "1", "]", ")", "c...
64.823529
0.012522
def eval_callx(self, exp): "dispatch for CallX" # below: this isn't contains(exp,consumes_row) -- it's just checking the current expression return (self.eval_agg_call if consumes_rows(exp) else self.eval_nonagg_call)(exp)
[ "def", "eval_callx", "(", "self", ",", "exp", ")", ":", "# below: this isn't contains(exp,consumes_row) -- it's just checking the current expression", "return", "(", "self", ".", "eval_agg_call", "if", "consumes_rows", "(", "exp", ")", "else", "self", ".", "eval_nonagg_ca...
57.5
0.012876
def do_ctrlc(self, arg): ''' Ctrl-C sends a STOP command to the arm. ''' print('STOP') if self.arm.is_connected(): self.arm.write('STOP')
[ "def", "do_ctrlc", "(", "self", ",", "arg", ")", ":", "print", "(", "'STOP'", ")", "if", "self", ".", "arm", ".", "is_connected", "(", ")", ":", "self", ".", "arm", ".", "write", "(", "'STOP'", ")" ]
33.8
0.011561
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing.""" status = status_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if status is None: raise LookupError("Status code {0} not supported".format(error_status_cod...
[ "def", "handle_error", "(", "self", ",", "error", ",", "req", ",", "schema", ",", "error_status_code", ",", "error_headers", ")", ":", "status", "=", "status_map", ".", "get", "(", "error_status_code", "or", "self", ".", "DEFAULT_VALIDATION_STATUS", ")", "if",...
66
0.009975
def index_fields(self, index=Index(), **options): """ Indexes the `Pointer` field and the :attr:`data` object referenced by the `Pointer` field starting with the given *index* and returns the :class:`Index` after the `Pointer` field. :param Index index: :class:`Index` for the `Pointer` ...
[ "def", "index_fields", "(", "self", ",", "index", "=", "Index", "(", ")", ",", "*", "*", "options", ")", ":", "index", "=", "self", ".", "index_field", "(", "index", ")", "# Container", "if", "is_container", "(", "self", ".", "_data", ")", ":", "self...
46
0.001374
def _autoset_min_reps_consistency(self): """ Sets the program mode to 'weekly', 'daily' or 'exercise' by automatically iterating over all exercises. """ # ------------------------------------------- # Set automatically by investigating program # -----------------...
[ "def", "_autoset_min_reps_consistency", "(", "self", ")", ":", "# -------------------------------------------", "# Set automatically by investigating program", "# -------------------------------------------", "# Check whether the mode is WEEKLY", "min_reps", ",", "max_reps", "=", "[", ...
40.897959
0.001949
def application(environ, start_response): """ The main WSGI application. Dispatch the current request to the functions from above. If nothing matches, call the `not_found` function. :param environ: The HTTP application environment :param start_response: The application to run when the handling...
[ "def", "application", "(", "environ", ",", "start_response", ")", ":", "path", "=", "environ", ".", "get", "(", "\"PATH_INFO\"", ",", "\"\"", ")", ".", "lstrip", "(", "\"/\"", ")", "logger", ".", "debug", "(", "\"<application> PATH: '%s'\"", ",", "path", "...
37.534884
0.000604
def python(self): """Path to the environment python""" py = vistir.compat.Path(self.base_paths["scripts"]).joinpath("python").absolute().as_posix() if not py: return vistir.compat.Path(sys.executable).as_posix() return py
[ "def", "python", "(", "self", ")", ":", "py", "=", "vistir", ".", "compat", ".", "Path", "(", "self", ".", "base_paths", "[", "\"scripts\"", "]", ")", ".", "joinpath", "(", "\"python\"", ")", ".", "absolute", "(", ")", ".", "as_posix", "(", ")", "i...
43.333333
0.011321
def __deftype_method_recur_to_py_ast( ctx: GeneratorContext, node: Recur ) -> GeneratedPyAST: """Return a Python AST node for `recur` occurring inside a `deftype*` method.""" assert node.op == NodeOp.RECUR recur_nodes: List[ast.AST] = [] recur_deps: List[ast.AST] = [] for expr in node.exprs: ...
[ "def", "__deftype_method_recur_to_py_ast", "(", "ctx", ":", "GeneratorContext", ",", "node", ":", "Recur", ")", "->", "GeneratedPyAST", ":", "assert", "node", ".", "op", "==", "NodeOp", ".", "RECUR", "recur_nodes", ":", "List", "[", "ast", ".", "AST", "]", ...
32.935484
0.001903
def add_inverse_query(self, key_val={}): """ Add an es_dsl inverse query object to the es_dsl Search object :param key_val: a key-value pair(dict) containing the query to be added to the search object :returns: self, which allows the method to be chainable with the other methods ...
[ "def", "add_inverse_query", "(", "self", ",", "key_val", "=", "{", "}", ")", ":", "q", "=", "Q", "(", "\"match\"", ",", "*", "*", "key_val", ")", "self", ".", "search", "=", "self", ".", "search", ".", "query", "(", "~", "q", ")", "return", "self...
37.545455
0.009456
def _do_revoke(self, http, token): """Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests. token: A string used as the token to be revoked. Can be either an access_token or refresh_token. ...
[ "def", "_do_revoke", "(", "self", ",", "http", ",", "token", ")", ":", "logger", ".", "info", "(", "'Revoking token'", ")", "query_params", "=", "{", "'token'", ":", "token", "}", "token_revoke_uri", "=", "_helpers", ".", "update_query_params", "(", "self", ...
40.114286
0.001391
def list_adresposities_by_subadres_and_huisnummer(self, subadres, huisnummer): ''' List all `adresposities` for a subadres and a :class:`Huisnummer`. :param subadres: A string representing a certain subadres. :param huisnummer: The :class:`Huisnummer` for which the \ `adresp...
[ "def", "list_adresposities_by_subadres_and_huisnummer", "(", "self", ",", "subadres", ",", "huisnummer", ")", ":", "try", ":", "hid", "=", "huisnummer", ".", "id", "except", "AttributeError", ":", "hid", "=", "huisnummer", "def", "creator", "(", ")", ":", "res...
38.71875
0.002362
def unescape_newlines(s: str) -> str: """ Reverses :func:`escape_newlines`. """ # See also http://stackoverflow.com/questions/4020539 if not s: return s d = "" # the destination string in_escape = False for i in range(len(s)): c = s[i] # the character being processed ...
[ "def", "unescape_newlines", "(", "s", ":", "str", ")", "->", "str", ":", "# See also http://stackoverflow.com/questions/4020539", "if", "not", "s", ":", "return", "s", "d", "=", "\"\"", "# the destination string", "in_escape", "=", "False", "for", "i", "in", "ra...
24.68
0.00156
def show(self): """Update the display with the data from the LED buffer.""" resp = ws.ws2811_render(self._leds) if resp != 0: str_resp = ws.ws2811_get_return_t_str(resp) raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, str_resp))
[ "def", "show", "(", "self", ")", ":", "resp", "=", "ws", ".", "ws2811_render", "(", "self", ".", "_leds", ")", "if", "resp", "!=", "0", ":", "str_resp", "=", "ws", ".", "ws2811_get_return_t_str", "(", "resp", ")", "raise", "RuntimeError", "(", "'ws2811...
49.666667
0.009901
def validate_excel_sheet_name(sheet_name): """ :param str sheet_name: Excel sheet name to validate. :raises pathvalidate.NullNameError: If the ``sheet_name`` is empty. :raises pathvalidate.InvalidCharError: If the ``sheet_name`` includes invalid char(s): |invalid_excel_sheet_chars|. ...
[ "def", "validate_excel_sheet_name", "(", "sheet_name", ")", ":", "validate_null_string", "(", "sheet_name", ")", "if", "len", "(", "sheet_name", ")", ">", "__MAX_SHEET_NAME_LEN", ":", "raise", "InvalidLengthError", "(", "\"sheet name is too long: expected<={:d}, actual={:d}...
36.692308
0.002043
def extend_trafo_power(extendable_trafos, trafo_params): """ Extend power of first trafo in list of extendable trafos Parameters ---------- extendable_trafos : :any:`list` Trafos with rated power below maximum size available trafo trafo_params : :pandas:`pandas.DataFrame<dataframe>` ...
[ "def", "extend_trafo_power", "(", "extendable_trafos", ",", "trafo_params", ")", ":", "trafo", "=", "extendable_trafos", "[", "0", "]", "trafo_s_max_a_before", "=", "trafo", ".", "s_max_a", "trafo_nearest_larger", "=", "trafo_params", ".", "loc", "[", "trafo_params"...
31.782609
0.001328
def collection_location(obj): """ Get the URL for the collection of objects like ``obj``. :param obj: Either a type representing a Kubernetes object kind or an instance of such a type. :return tuple[unicode]: Some path segments to stick on to a base URL to construct the location of the...
[ "def", "collection_location", "(", "obj", ")", ":", "# TODO kind is not part of IObjectLoader and we should really be loading", "# apiVersion off of this object too.", "kind", "=", "obj", ".", "kind", "apiVersion", "=", "obj", ".", "apiVersion", "prefix", "=", "version_to_seg...
31.787879
0.000925
def add_file(self, file_grp, content=None, **kwargs): """ Add an output file. Creates an :class:`OcrdFile` to pass around and adds that to the OcrdMets OUTPUT section. """ log.debug( 'outputfile file_grp=%s local_filename=%s content=%s', file_grp, ...
[ "def", "add_file", "(", "self", ",", "file_grp", ",", "content", "=", "None", ",", "*", "*", "kwargs", ")", ":", "log", ".", "debug", "(", "'outputfile file_grp=%s local_filename=%s content=%s'", ",", "file_grp", ",", "kwargs", ".", "get", "(", "'local_filenam...
37.257143
0.002242
def get_components(self): """ Returns all the applications from the store """ components = [] for app_id in self.components: components.append(self.components[app_id]) return components
[ "def", "get_components", "(", "self", ")", ":", "components", "=", "[", "]", "for", "app_id", "in", "self", ".", "components", ":", "components", ".", "append", "(", "self", ".", "components", "[", "app_id", "]", ")", "return", "components" ]
37.333333
0.008734
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarin...
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMIT...
35.390244
0.015426
def parse_udiff(diff, patterns=None, parent='.'): """Return a dictionary of matching lines.""" # For each file of the diff, the entry key is the filename, # and the value is a set of row numbers to consider. rv = {} path = nrows = None for line in diff.splitlines(): if nrows: ...
[ "def", "parse_udiff", "(", "diff", ",", "patterns", "=", "None", ",", "parent", "=", "'.'", ")", ":", "# For each file of the diff, the entry key is the filename,", "# and the value is a set of row numbers to consider.", "rv", "=", "{", "}", "path", "=", "nrows", "=", ...
39.26087
0.001081
def predmean(self, xp): """ Expectation of X_t given X_{t-1}=xp """ out = np.empty_like(xp) for i in range(3): out[:, i] = xp[:, i] + self.delta * xp[:, i+3] # position out[:, i+3] = xp[:, i+3] # velocity return out
[ "def", "predmean", "(", "self", ",", "xp", ")", ":", "out", "=", "np", ".", "empty_like", "(", "xp", ")", "for", "i", "in", "range", "(", "3", ")", ":", "out", "[", ":", ",", "i", "]", "=", "xp", "[", ":", ",", "i", "]", "+", "self", ".",...
37
0.013201
def add(self, attachments): """ Add more attachments :param attachments: list of attachments :type attachments: list[str] or list[Path] or str or Path or dict """ if attachments: if isinstance(attachments, (str, Path)): attachments = [attachments] ...
[ "def", "add", "(", "self", ",", "attachments", ")", ":", "if", "attachments", ":", "if", "isinstance", "(", "attachments", ",", "(", "str", ",", "Path", ")", ")", ":", "attachments", "=", "[", "attachments", "]", "if", "isinstance", "(", "attachments", ...
45.933333
0.001421
def fold_list(input_list, max_width=None): """ Fold the entries in input_list. If max_width is not None, fold only if it is longer than max_width. Otherwise fold each entry. """ if not input_list: return "" if not isinstance(input_list[0], six.string_types): input_list = [str(ite...
[ "def", "fold_list", "(", "input_list", ",", "max_width", "=", "None", ")", ":", "if", "not", "input_list", ":", "return", "\"\"", "if", "not", "isinstance", "(", "input_list", "[", "0", "]", ",", "six", ".", "string_types", ")", ":", "input_list", "=", ...
31.2
0.002075
def set_value(self, value, validate=True, todefault=False): """ Set (and validate) the value in the plotter Parameters ---------- %(Formatoption.set_value.parameters)s Notes ----- - If the current value in the plotter is None, then it will be set with ...
[ "def", "set_value", "(", "self", ",", "value", ",", "validate", "=", "True", ",", "todefault", "=", "False", ")", ":", "value", "=", "value", "if", "not", "validate", "else", "self", ".", "validate", "(", "value", ")", "# if the key in the plotter is not alr...
37.793103
0.001779
def adjoint(self): """Adjoint of this operator. The adjoint of the operator scalar multiplication is the scalar multiplication of the operator adjoint: ``OperatorLeftScalarMult(op, s).adjoint == OperatorLeftScalarMult(op.adjoint, s)`` Raises ------ ...
[ "def", "adjoint", "(", "self", ")", ":", "if", "not", "self", ".", "is_linear", ":", "raise", "OpNotImplementedError", "(", "'nonlinear operators have no adjoint'", ")", "return", "self", ".", "scalar", ".", "conjugate", "(", ")", "*", "self", ".", "operator",...
30.37037
0.002364
def simple_fault_node(fault_trace, dip, upper_depth, lower_depth): """ :param fault_trace: an object with an attribute .points :param dip: dip parameter :param upper_depth: upper seismogenic depth :param lower_depth: lower seismogenic depth :returns: a Node of kind simpleFaultGeometry """ ...
[ "def", "simple_fault_node", "(", "fault_trace", ",", "dip", ",", "upper_depth", ",", "lower_depth", ")", ":", "node", "=", "Node", "(", "'simpleFaultGeometry'", ")", "line", "=", "[", "]", "for", "p", "in", "fault_trace", ".", "points", ":", "line", ".", ...
39
0.001391
def keep_params(self, base_key, *params): """ Method to keep only specific parameters from a parameter documentation. This method extracts the given `param` from the `base_key` item in the :attr:`params` dictionary and creates a new item with the original documentation with only...
[ "def", "keep_params", "(", "self", ",", "base_key", ",", "*", "params", ")", ":", "self", ".", "params", "[", "base_key", "+", "'.'", "+", "'|'", ".", "join", "(", "params", ")", "]", "=", "self", ".", "keep_params_s", "(", "self", ".", "params", "...
33.011494
0.000676
def update_item(self, tablename, key, updates, returns=NONE, return_capacity=None, expect_or=False, **kwargs): """ Update a single item in a table This uses the older version of the DynamoDB API. See also: :meth:`~.update_item2`. Parameters ---------...
[ "def", "update_item", "(", "self", ",", "tablename", ",", "key", ",", "updates", ",", "returns", "=", "NONE", ",", "return_capacity", "=", "None", ",", "expect_or", "=", "False", ",", "*", "*", "kwargs", ")", ":", "key", "=", "self", ".", "dynamizer", ...
41.764706
0.001376
def imagetransformer_base_10l_16h_big_uncond_dr01_imgnet(): """big 1d model for conditional image generation.""" hparams = imagetransformer_base_14l_8h_big_dr01() # num_hidden_layers hparams.num_decoder_layers = 10 hparams.num_heads = 16 hparams.hidden_size = 1024 hparams.filter_size = 4096 hparams.batc...
[ "def", "imagetransformer_base_10l_16h_big_uncond_dr01_imgnet", "(", ")", ":", "hparams", "=", "imagetransformer_base_14l_8h_big_dr01", "(", ")", "# num_hidden_layers", "hparams", ".", "num_decoder_layers", "=", "10", "hparams", ".", "num_heads", "=", "16", "hparams", ".",...
34.727273
0.028061
def partition(a:Collection, sz:int)->List[Collection]: "Split iterables `a` in equal parts of size `sz`" return [a[i:i+sz] for i in range(0, len(a), sz)]
[ "def", "partition", "(", "a", ":", "Collection", ",", "sz", ":", "int", ")", "->", "List", "[", "Collection", "]", ":", "return", "[", "a", "[", "i", ":", "i", "+", "sz", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "a", ")", ...
53
0.024845
def choice(self, message, choices=None, select=None, cancel=None, msg_position='above', choices_to_return=None): """ prompt user to make a choice. :param message: string to display before list of choices :type message: unicode :param choices: dict of possible choi...
[ "def", "choice", "(", "self", ",", "message", ",", "choices", "=", "None", ",", "select", "=", "None", ",", "cancel", "=", "None", ",", "msg_position", "=", "'above'", ",", "choices_to_return", "=", "None", ")", ":", "choices", "=", "choices", "or", "{...
41.757576
0.001418
def get_kwic(tokens, index, context_window=5): """ keyword in context Parameters ---------- tokens : list of str a text represented as a list of tokens index : int the index of the keyword in the token list context_window : int the number of preceding/succeding words...
[ "def", "get_kwic", "(", "tokens", ",", "index", ",", "context_window", "=", "5", ")", ":", "text_length", "=", "len", "(", "tokens", ")", "start_before", "=", "max", "(", "0", ",", "index", "-", "context_window", ")", "end_before", "=", "max", "(", "0"...
28.645161
0.001089
def write_magic_file(self, custom_name=None, dir_path=".", append=False, multi_type=False, df=None): """ Write self.df out to tab-delimited file. By default will use standard MagIC filenames (specimens.txt, etc.), or you can provide a custom_name to write to inst...
[ "def", "write_magic_file", "(", "self", ",", "custom_name", "=", "None", ",", "dir_path", "=", "\".\"", ",", "append", "=", "False", ",", "multi_type", "=", "False", ",", "df", "=", "None", ")", ":", "# don't let custom name start with \"./\"", "if", "custom_n...
36.686747
0.001599
def _manual_lookup(self, facebook_id, facebook_id_string): """ People who we have not communicated with in a long time will not appear in the look-ahead cache that Facebook keeps. We must manually resolve them. :param facebook_id: Profile ID of the user to lookup. :retur...
[ "def", "_manual_lookup", "(", "self", ",", "facebook_id", ",", "facebook_id_string", ")", ":", "resp", "=", "self", ".", "_session", ".", "get", "(", "'https://www.facebook.com/%s'", "%", "facebook_id", ",", "allow_redirects", "=", "True", ",", "timeout", "=", ...
36.954545
0.002398
def find(self): """Call the find function""" options = self.find_options.get_options() if options is None: return self.stop_and_reset_thread(ignore_results=True) self.search_thread = SearchThread(self) self.search_thread.sig_finished.connect(self.search...
[ "def", "find", "(", "self", ")", ":", "options", "=", "self", ".", "find_options", ".", "get_options", "(", ")", "if", "options", "is", "None", ":", "return", "self", ".", "stop_and_reset_thread", "(", "ignore_results", "=", "True", ")", "self", ".", "se...
41.571429
0.001679
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer): """ Convert a Batch Normalization layer. Parameters keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get input and output names i...
[ "def", "convert_batchnorm", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", "...
27.294118
0.014563
def has_implicit_access_to_catalog(user, obj): # pylint: disable=unused-argument """ Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role. Returns: boolean: whether the request user has access or not """ request = get_request_or_stub() decoded_...
[ "def", "has_implicit_access_to_catalog", "(", "user", ",", "obj", ")", ":", "# pylint: disable=unused-argument", "request", "=", "get_request_or_stub", "(", ")", "decoded_jwt", "=", "get_decoded_jwt_from_request", "(", "request", ")", "return", "request_user_has_implicit_ac...
45.5
0.008621
def temp(self, name, templates=None, n_indents=None, skipping=False): """ Get specific template of chosen programming language. Parameters ---------- :param param name : string The key name of the template. :param param templates : string, default: No...
[ "def", "temp", "(", "self", ",", "name", ",", "templates", "=", "None", ",", "n_indents", "=", "None", ",", "skipping", "=", "False", ")", ":", "if", "templates", "is", "None", ":", "templates", "=", "self", ".", "TEMPLATES", ".", "get", "(", "self",...
38.84
0.001005
def _check_data_port_name(self, data_port): """Checks the validity of a data port name Checks whether the name of the given data port is already used by anther data port within the state. Names must be unique with input data ports, output data ports and scoped variables. :param rafcon....
[ "def", "_check_data_port_name", "(", "self", ",", "data_port", ")", ":", "# First check inputs and outputs", "valid", ",", "message", "=", "super", "(", "ContainerState", ",", "self", ")", ".", "_check_data_port_name", "(", "data_port", ")", "if", "not", "valid", ...
52.380952
0.008036
def check_shutdown_flag(self): """Shutdown the server if the flag has been set""" if self.shutdown_requested: tornado.ioloop.IOLoop.instance().stop() print("web server stopped.")
[ "def", "check_shutdown_flag", "(", "self", ")", ":", "if", "self", ".", "shutdown_requested", ":", "tornado", ".", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "stop", "(", ")", "print", "(", "\"web server stopped.\"", ")" ]
42.8
0.009174
def delete_keypair(kwargs=None, call=None): ''' Delete an SSH keypair ''' if call != 'function': log.error( 'The delete_keypair function must be called with -f or --function.' ) return False if not kwargs: kwargs = {} if 'keyname' not in kwargs: ...
[ "def", "delete_keypair", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "!=", "'function'", ":", "log", ".", "error", "(", "'The delete_keypair function must be called with -f or --function.'", ")", "return", "False", "if", "not", ...
25.37037
0.001406
def status(name, sig=None): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of the servi...
[ "def", "status", "(", "name", ",", "sig", "=", "None", ")", ":", "contains_globbing", "=", "bool", "(", "re", ".", "search", "(", "r'\\*|\\?|\\[.+\\]'", ",", "name", ")", ")", "if", "contains_globbing", ":", "services", "=", "fnmatch", ".", "filter", "("...
28.388889
0.000946
def get_web3(): """Return the web3 instance to interact with the ethereum client.""" if Web3Provider._web3 is None: config = ConfigProvider.get_config() provider = ( config.web3_provider if config.web3_provider else CustomHTTPProvid...
[ "def", "get_web3", "(", ")", ":", "if", "Web3Provider", ".", "_web3", "is", "None", ":", "config", "=", "ConfigProvider", ".", "get_config", "(", ")", "provider", "=", "(", "config", ".", "web3_provider", "if", "config", ".", "web3_provider", "else", "Cust...
50.708333
0.002419
def match(self, path): '''Match a path and return ``None`` if no matching, otherwise a dictionary of matched variables with values. If there is more to be match in the path, the remaining string is placed in the ``__remaining__`` key of the dictionary.''' match = self._regex.sear...
[ "def", "match", "(", "self", ",", "path", ")", ":", "match", "=", "self", ".", "_regex", ".", "search", "(", "path", ")", "if", "match", "is", "not", "None", ":", "remaining", "=", "path", "[", "match", ".", "end", "(", ")", ":", "]", "groups", ...
41.421053
0.002484
def rms(self, stride=1): """Calculate the root-mean-square value of this `TimeSeries` once per stride. Parameters ---------- stride : `float` stride (seconds) between RMS calculations Returns ------- rms : `TimeSeries` a new `Time...
[ "def", "rms", "(", "self", ",", "stride", "=", "1", ")", ":", "stridesamp", "=", "int", "(", "stride", "*", "self", ".", "sample_rate", ".", "value", ")", "nsteps", "=", "int", "(", "self", ".", "size", "//", "stridesamp", ")", "# stride through TimeSe...
37.107143
0.001876
def clean_german_number(x): """Convert a string with a German number into a Decimal Parameters ---------- x : str, list, tuple, numpy.ndarray, pandas.DataFrame A string with a number with German formatting, or an array of these strings, e.g. list, ndarray, df. Returns ------- ...
[ "def", "clean_german_number", "(", "x", ")", ":", "import", "numpy", "as", "np", "import", "pandas", "as", "pd", "import", "re", "def", "proc_elem", "(", "e", ")", ":", "# abort if it is not a string", "if", "not", "isinstance", "(", "e", ",", "str", ")", ...
26.775
0.001801
def _expand_files(self, file_name, original_path, indent=""): """This recursive function accepts a file name, opens the file and then spools the contents of the file into a list, examining each line as it does so. If it detects a line beginning with "+include", it assumes the string imm...
[ "def", "_expand_files", "(", "self", ",", "file_name", ",", "original_path", ",", "indent", "=", "\"\"", ")", ":", "expanded_file_contents", "=", "[", "]", "with", "open", "(", "file_name", ")", "as", "f", ":", "for", "a_line", "in", "f", ":", "match", ...
48.192308
0.001565
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ get view name from routing args """ urlvars = environ.get('wsgiorg.routing_args', [(), {}])[1] return urlvars.get(self.action_var_name)
[ "def", "detect_view_name", "(", "self", ",", "environ", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "str", ":", "urlvars", "=", "environ", ".", "get", "(", "'wsgiorg.routing_args'", ",", "[", "(", ")", ",", "{", "}", "]", ")", "[", "1", ...
55
0.008969
def make_inst1(): """creates example data set 1""" I,d = multidict({1:80, 2:270, 3:250 , 4:160, 5:180}) # demand J,M = multidict({1:500, 2:500, 3:500}) # capacity c = {(1,1):4, (1,2):6, (1,3):9, # cost (2,1):5, (2,2):4, (2,3):7, (3,1):6, (3,2):3, (3,3):...
[ "def", "make_inst1", "(", ")", ":", "I", ",", "d", "=", "multidict", "(", "{", "1", ":", "80", ",", "2", ":", "270", ",", "3", ":", "250", ",", "4", ":", "160", ",", "5", ":", "180", "}", ")", "# demand", "J", ",", "M", "=", "multidict", ...
38.909091
0.107306
def _get_diff_dict(dict1, dict2): ''' Returns a dictionary with the diffs between two dictionaries It will ignore any key that doesn't exist in dict2 ''' ret_dict = {} for p in dict2.keys(): if p not in dict1: ret_dict.update({p: {'val1': None, 'val2': dict2[p]}}) el...
[ "def", "_get_diff_dict", "(", "dict1", ",", "dict2", ")", ":", "ret_dict", "=", "{", "}", "for", "p", "in", "dict2", ".", "keys", "(", ")", ":", "if", "p", "not", "in", "dict1", ":", "ret_dict", ".", "update", "(", "{", "p", ":", "{", "'val1'", ...
37.277778
0.001453
def currentVersion(self): """ returns the current version of the site """ if self._currentVersion is None: self.__init(self._url) return self._currentVersion
[ "def", "currentVersion", "(", "self", ")", ":", "if", "self", ".", "_currentVersion", "is", "None", ":", "self", ".", "__init", "(", "self", ".", "_url", ")", "return", "self", ".", "_currentVersion" ]
37.8
0.010363
def _recursively_apply_get_cassette_subclass(self, replacement_dict_or_obj): """One of the subtleties of this class is that it does not directly replace HTTPSConnection with `VCRRequestsHTTPSConnection`, but a subclass of the aforementioned class that has the `cassette` class attribute a...
[ "def", "_recursively_apply_get_cassette_subclass", "(", "self", ",", "replacement_dict_or_obj", ")", ":", "if", "isinstance", "(", "replacement_dict_or_obj", ",", "dict", ")", ":", "for", "key", ",", "replacement_obj", "in", "replacement_dict_or_obj", ".", "items", "(...
54.428571
0.001934
def solve(self, X, rank, max_iter=500, stopping_criterion=1e-5, lambda_reg=0.0, dtype=np.float32, rng=None): """Solve CPD Args: X (numpy.ndarray): Target tensor of CPD. rank (int): Rank of the approximate tensor. max_iter (int): Max iteration of the ALS...
[ "def", "solve", "(", "self", ",", "X", ",", "rank", ",", "max_iter", "=", "500", ",", "stopping_criterion", "=", "1e-5", ",", "lambda_reg", "=", "0.0", ",", "dtype", "=", "np", ".", "float32", ",", "rng", "=", "None", ")", ":", "N", "=", "X", "."...
34.876712
0.001146
def remove_last_entry(self): """Remove the last NoteContainer in the Bar.""" self.current_beat -= 1.0 / self.bar[-1][1] self.bar = self.bar[:-1] return self.current_beat
[ "def", "remove_last_entry", "(", "self", ")", ":", "self", ".", "current_beat", "-=", "1.0", "/", "self", ".", "bar", "[", "-", "1", "]", "[", "1", "]", "self", ".", "bar", "=", "self", ".", "bar", "[", ":", "-", "1", "]", "return", "self", "."...
39.4
0.00995
def after_epoch(self, epoch_data: EpochData, **kwargs) -> None: """ Compute the specified aggregations and save them to the given epoch data. :param epoch_data: epoch data to be processed """ self._save_stats(epoch_data) super().after_epoch(epoch_data=epoch_data, **kwarg...
[ "def", "after_epoch", "(", "self", ",", "epoch_data", ":", "EpochData", ",", "*", "*", "kwargs", ")", "->", "None", ":", "self", ".", "_save_stats", "(", "epoch_data", ")", "super", "(", ")", ".", "after_epoch", "(", "epoch_data", "=", "epoch_data", ",",...
39.375
0.009317
def reduce_list_size(li): """Return two lists - the last N items of li whose total size is less than MAX_SIZE - the rest of the original list li """ # sys.getsizeof is nearly useless. All our data is stringable so rather # use that as a measure of size. size = len(repr(li)) keep ...
[ "def", "reduce_list_size", "(", "li", ")", ":", "# sys.getsizeof is nearly useless. All our data is stringable so rather", "# use that as a measure of size.", "size", "=", "len", "(", "repr", "(", "li", ")", ")", "keep", "=", "li", "toss", "=", "[", "]", "n", "=", ...
29.944444
0.001799
def clear_cursor(self, body, params=None): """ `<Clear SQL cursor>`_ :arg body: Specify the cursor value in the `cursor` element to clean the cursor. """ if body in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument 'body'.") ...
[ "def", "clear_cursor", "(", "self", ",", "body", ",", "params", "=", "None", ")", ":", "if", "body", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'body'.\"", ")", "return", "self", ".", "transport", ".", "p...
35
0.009281
def run(self): """Will call self.launch() after performing some checks""" # Check already exists # if self.status == "READY": return self.launch() # Check name conflict # if self.status == "DUPLICATE": message = "Job with same name '%s' already in queue, but we lost the script."...
[ "def", "run", "(", "self", ")", ":", "# Check already exists #", "if", "self", ".", "status", "==", "\"READY\"", ":", "return", "self", ".", "launch", "(", ")", "# Check name conflict #", "if", "self", ".", "status", "==", "\"DUPLICATE\"", ":", "message", "=...
71.142857
0.014866
def button_state(self): """The button state of the event. For events not of type :attr:`~libinput.constant.EventType.TABLET_PAD_BUTTON`, this property raises :exc:`AttributeError`. Returns: ~libinput.constant.ButtonState: The button state triggering this event. Raises: AttributeError """ if ...
[ "def", "button_state", "(", "self", ")", ":", "if", "self", ".", "type", "!=", "EventType", ".", "TABLET_PAD_BUTTON", ":", "raise", "AttributeError", "(", "_wrong_prop", ".", "format", "(", "self", ".", "type", ")", ")", "return", "self", ".", "_libinput",...
26.888889
0.031936
def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]: """Get several graphs by their identifiers.""" return [ self.networks[network_id] for network_id in network_ids ]
[ "def", "get_graphs_by_ids", "(", "self", ",", "network_ids", ":", "Iterable", "[", "int", "]", ")", "->", "List", "[", "BELGraph", "]", ":", "return", "[", "self", ".", "networks", "[", "network_id", "]", "for", "network_id", "in", "network_ids", "]" ]
38.5
0.008475
def mark_sentence(s, args): """Insert markers around relation arguments in word sequence :param s: list of tokens in sentence. :type s: list :param args: list of triples (l, h, idx) as per @_mark(...) corresponding to relation arguments :type args: list :return: The marked senten...
[ "def", "mark_sentence", "(", "s", ",", "args", ")", ":", "marks", "=", "sorted", "(", "[", "y", "for", "m", "in", "args", "for", "y", "in", "mark", "(", "*", "m", ")", "]", ",", "reverse", "=", "True", ")", "x", "=", "list", "(", "s", ")", ...
29.3
0.001653
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', ...
[ "def", "lsb_release", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "# v the space is intentional, to avoid polluting bash history.", "shutit", "=", "self", ".", "shutit", "d", "=", "{", "}", "self", ".", "send", "(", "ShutItSendSp...
36.964286
0.035782
def get_dependants(self, run): """ Return a list of nodes that are control dependent on the given node in the control dependence graph """ if run in self._graph.nodes(): return list(self._graph.successors(run)) else: return []
[ "def", "get_dependants", "(", "self", ",", "run", ")", ":", "if", "run", "in", "self", ".", "_graph", ".", "nodes", "(", ")", ":", "return", "list", "(", "self", ".", "_graph", ".", "successors", "(", "run", ")", ")", "else", ":", "return", "[", ...
35.375
0.010345
def quoted(arg): """ Given a string, return a quoted string as per RFC 3501, section 9. Implementation copied from https://github.com/mjs/imapclient (imapclient/imapclient.py), 3-clause BSD license """ if isinstance(arg, str): arg = arg.replace('\\', '\\\\') arg = arg.replac...
[ "def", "quoted", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "str", ")", ":", "arg", "=", "arg", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "arg", "=", "arg", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "q", "=",...
31.133333
0.002079
def list(self, filter_title=None, filter_ids=None, page=None): """ :type filter_title: str :param filter_title: Filter by dashboard title :type filter_ids: list of ints :param filter_ids: Filter by dashboard ids :type page: int :param page: Pagination index ...
[ "def", "list", "(", "self", ",", "filter_title", "=", "None", ",", "filter_ids", "=", "None", ",", "page", "=", "None", ")", ":", "filters", "=", "[", "'filter[title]={0}'", ".", "format", "(", "filter_title", ")", "if", "filter_title", "else", "None", "...
35.474576
0.002325
def reset_ids_in_meta_df(meta_df): """ Meta_df is modified inplace. """ # Record original index name, and then change it so that the column that it # becomes will be appropriately named original_index_name = meta_df.index.name meta_df.index.name = "old_id" # Reset index meta_df.reset_index...
[ "def", "reset_ids_in_meta_df", "(", "meta_df", ")", ":", "# Record original index name, and then change it so that the column that it", "# becomes will be appropriately named", "original_index_name", "=", "meta_df", ".", "index", ".", "name", "meta_df", ".", "index", ".", "name...
32
0.002336
def compare(referenceOnto, somegraph): """ Desc """ spy1 = Ontology(referenceOnto) spy2 = Ontology(somegraph) class_comparison = {} for x in spy2.allclasses: if x not in spy1.allclasses: class_comparison[x] = False else: class_comparison[x] = True prop_comparison = {} for x in spy2.allinferredprop...
[ "def", "compare", "(", "referenceOnto", ",", "somegraph", ")", ":", "spy1", "=", "Ontology", "(", "referenceOnto", ")", "spy2", "=", "Ontology", "(", "somegraph", ")", "class_comparison", "=", "{", "}", "for", "x", "in", "spy2", ".", "allclasses", ":", "...
23.035714
0.052083
def gen_schlumberger(self, M, N, a=None): """generate one Schlumberger sounding configuration, that is, one set of configurations for one potential dipole MN. Parameters ---------- M: int electrode number for the first potential electrode N: int e...
[ "def", "gen_schlumberger", "(", "self", ",", "M", ",", "N", ",", "a", "=", "None", ")", ":", "if", "a", "is", "None", ":", "a", "=", "np", ".", "abs", "(", "M", "-", "N", ")", "nr_of_steps_left", "=", "int", "(", "min", "(", "M", ",", "N", ...
32.1
0.001512
def _build_graph(self, vocab, initial_embedding_dict): """Builds the computatation graph. Parameters ------------ vocab : Iterable initial_embedding_dict : dict """ # Constants self.ones = tf.ones([self.n_words, 1]) # Parameters: if initi...
[ "def", "_build_graph", "(", "self", ",", "vocab", ",", "initial_embedding_dict", ")", ":", "# Constants", "self", ".", "ones", "=", "tf", ".", "ones", "(", "[", "self", ".", "n_words", ",", "1", "]", ")", "# Parameters:", "if", "initial_embedding_dict", "i...
46.865385
0.001608
def parse_view_args(self, req, name, field): """Pull a value from the request's ``view_args``.""" return core.get_value(req.match_info, name, field)
[ "def", "parse_view_args", "(", "self", ",", "req", ",", "name", ",", "field", ")", ":", "return", "core", ".", "get_value", "(", "req", ".", "match_info", ",", "name", ",", "field", ")" ]
54
0.012195
def remove_vectored_io_slice_suffix_from_name(name, slice): # type: (str, int) -> str """Remove vectored io (stripe) slice suffix from a given name :param str name: entity name :param int slice: slice num :rtype: str :return: name without suffix """ suffix = '.bxslice-{}'.format(slice) ...
[ "def", "remove_vectored_io_slice_suffix_from_name", "(", "name", ",", "slice", ")", ":", "# type: (str, int) -> str", "suffix", "=", "'.bxslice-{}'", ".", "format", "(", "slice", ")", "if", "name", ".", "endswith", "(", "suffix", ")", ":", "return", "name", "[",...
30.846154
0.002421
def validate_nodes_count(namespace): """Validate that min_count and max_count is set to 1-100""" if namespace.min_count is not None: if namespace.min_count < 1 or namespace.min_count > 100: raise CLIError('--min-count must be in the range [1,100]') if namespace.max_count is not None: ...
[ "def", "validate_nodes_count", "(", "namespace", ")", ":", "if", "namespace", ".", "min_count", "is", "not", "None", ":", "if", "namespace", ".", "min_count", "<", "1", "or", "namespace", ".", "min_count", ">", "100", ":", "raise", "CLIError", "(", "'--min...
55.625
0.002212
def store(self, msg, stuff_to_store, *args, **kwargs): """Simply keeps a reference to the stored data """ trajectory_name = kwargs['trajectory_name'] if trajectory_name not in self.references: self.references[trajectory_name] = [] self.references[trajectory_name].append((msg,...
[ "def", "store", "(", "self", ",", "msg", ",", "stuff_to_store", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "trajectory_name", "=", "kwargs", "[", "'trajectory_name'", "]", "if", "trajectory_name", "not", "in", "self", ".", "references", ":", "s...
59.166667
0.008333
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) chunk = self.mfac.value() if v < self.imin or v > self.imax or (v % chunk != 0): return False else: return True ex...
[ "def", "ok", "(", "self", ")", ":", "try", ":", "v", "=", "int", "(", "self", ".", "_value", ")", "chunk", "=", "self", ".", "mfac", ".", "value", "(", ")", "if", "v", "<", "self", ".", "imin", "or", "v", ">", "self", ".", "imax", "or", "("...
26
0.008571
def register_or_check(klass, finish, mean, between, refresh_presision, configuration): """Return the active configurations.""" m, created = klass.objects.get_or_create(finish=finish, configuration=configuration) if created: m.mean=mean m.between=between m.refresh_presision=refresh_presision m.save() ...
[ "def", "register_or_check", "(", "klass", ",", "finish", ",", "mean", ",", "between", ",", "refresh_presision", ",", "configuration", ")", ":", "m", ",", "created", "=", "klass", ".", "objects", ".", "get_or_create", "(", "finish", "=", "finish", ",", "con...
42
0.037634
def resource_action(client, action='', log_format='item: %(key)s', **kwargs): """Call _action_ using boto3 _client_ with _kwargs_. This is meant for _action_ methods that will create or implicitely prove a given Resource exists. The _log_failure_ flag is available for methods that should always succeed...
[ "def", "resource_action", "(", "client", ",", "action", "=", "''", ",", "log_format", "=", "'item: %(key)s'", ",", "*", "*", "kwargs", ")", ":", "result", "=", "None", "try", ":", "result", "=", "getattr", "(", "client", ",", "action", ")", "(", "*", ...
34.972222
0.000773
def setHiddenColumns(self, hidden): """ Sets the columns that should be hidden based on the inputed list of \ names. :param columns | [<str>, ..] """ colnames = self.columns() for c, column in enumerate(colnames): self.setColumnH...
[ "def", "setHiddenColumns", "(", "self", ",", "hidden", ")", ":", "colnames", "=", "self", ".", "columns", "(", ")", "for", "c", ",", "column", "in", "enumerate", "(", "colnames", ")", ":", "self", ".", "setColumnHidden", "(", "c", ",", "column", "in", ...
33.7
0.011561
def create_lbaas_member(self, lbaas_pool, body=None): """Creates a lbaas_member.""" return self.post(self.lbaas_members_path % lbaas_pool, body=body)
[ "def", "create_lbaas_member", "(", "self", ",", "lbaas_pool", ",", "body", "=", "None", ")", ":", "return", "self", ".", "post", "(", "self", ".", "lbaas_members_path", "%", "lbaas_pool", ",", "body", "=", "body", ")" ]
54.333333
0.012121
def mlt2mlon(self, mlt, datetime, ssheight=50*6371): """Computes the magnetic longitude at the specified magnetic local time and UT. Parameters ========== mlt : array_like Magnetic local time datetime : :class:`datetime.datetime` Date and time ...
[ "def", "mlt2mlon", "(", "self", ",", "mlt", ",", "datetime", ",", "ssheight", "=", "50", "*", "6371", ")", ":", "ssglat", ",", "ssglon", "=", "helpers", ".", "subsol", "(", "datetime", ")", "ssalat", ",", "ssalon", "=", "self", ".", "geo2apex", "(", ...
38.6
0.001444
def clean_ids(feed: "Feed") -> "Feed": """ In the given "Feed", strip whitespace from all string IDs and then replace every remaining whitespace chunk with an underscore. Return the resulting "Feed". """ # Alter feed inputs only, and build a new feed from them. # The derived feed attributes,...
[ "def", "clean_ids", "(", "feed", ":", "\"Feed\"", ")", "->", "\"Feed\"", ":", "# Alter feed inputs only, and build a new feed from them.", "# The derived feed attributes, such as feed.trips_i,", "# will be automatically handled when creating the new feed.", "feed", "=", "feed", ".", ...
38.12
0.001024
def get_exe_path(cls): """ Return the full path to the executable. """ return os.path.abspath(os.path.join(ROOT, cls.bmds_version_dir, cls.exe + ".exe"))
[ "def", "get_exe_path", "(", "cls", ")", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "ROOT", ",", "cls", ".", "bmds_version_dir", ",", "cls", ".", "exe", "+", "\".exe\"", ")", ")" ]
36.2
0.016216
def ssa(n,h,K,f,T): """ssa -- multi-stage (serial) safety stock allocation model Parameters: - n: number of stages - h[i]: inventory cost on stage i - K: number of linear segments - f: (non-linear) cost function - T[i]: production lead time on stage i Returns the mode...
[ "def", "ssa", "(", "n", ",", "h", ",", "K", ",", "f", ",", "T", ")", ":", "model", "=", "Model", "(", "\"safety stock allocation\"", ")", "# calculate endpoints for linear segments", "a", ",", "b", "=", "{", "}", ",", "{", "}", "for", "i", "in", "ran...
32.65
0.020074