text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def help_center_article_show(self, locale, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/articles#show-article" api_path = "/api/v2/help_center/{locale}/articles/{id}.json" api_path = api_path.format(locale=locale, id=id) return self.call(api_path, **kwargs)
[ "def", "help_center_article_show", "(", "self", ",", "locale", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/{locale}/articles/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "locale", "=", "locale", ",", "i...
62.4
22.4
def debug_callback(event, *args, **kwds): '''Example callback, useful for debugging. ''' l = ['event %s' % (event.type,)] if args: l.extend(map(str, args)) if kwds: l.extend(sorted('%s=%s' % t for t in kwds.items())) print('Debug callback (%s)' % ', '.join(l))
[ "def", "debug_callback", "(", "event", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "l", "=", "[", "'event %s'", "%", "(", "event", ".", "type", ",", ")", "]", "if", "args", ":", "l", ".", "extend", "(", "map", "(", "str", ",", "args", ...
32.444444
14.888889
def get_kind(self): """ Return the 'kind' argument of the instruction :rtype: int """ if self.OP > 0xff: if self.OP >= 0xf2ff: return DALVIK_OPCODES_OPTIMIZED[self.OP][1][1] return DALVIK_OPCODES_EXTENDED_WIDTH[self.OP][1][1] retur...
[ "def", "get_kind", "(", "self", ")", ":", "if", "self", ".", "OP", ">", "0xff", ":", "if", "self", ".", "OP", ">=", "0xf2ff", ":", "return", "DALVIK_OPCODES_OPTIMIZED", "[", "self", ".", "OP", "]", "[", "1", "]", "[", "1", "]", "return", "DALVIK_OP...
31.636364
15.636364
def process_literal_param(self, value: Optional[List[int]], dialect: Dialect) -> str: """Convert things on the way from Python to the database.""" retval = self._intlist_to_dbstr(value) return retval
[ "def", "process_literal_param", "(", "self", ",", "value", ":", "Optional", "[", "List", "[", "int", "]", "]", ",", "dialect", ":", "Dialect", ")", "->", "str", ":", "retval", "=", "self", ".", "_intlist_to_dbstr", "(", "value", ")", "return", "retval" ]
49.8
11.8
def ssh_key_info_from_key_data(key_id, priv_key=None): """Get/load SSH key info necessary for signing. @param key_id {str} Either a private ssh key fingerprint, e.g. 'b3:f0:a1:6c:18:3b:42:63:fd:6e:57:42:74:17:d4:bc', or the path to an ssh private key file (like ssh's IdentityFile config option)...
[ "def", "ssh_key_info_from_key_data", "(", "key_id", ",", "priv_key", "=", "None", ")", ":", "if", "FINGERPRINT_RE", ".", "match", "(", "key_id", ")", "and", "priv_key", ":", "key_info", "=", "{", "\"fingerprint\"", ":", "key_id", ",", "\"priv_key\"", ":", "p...
38.569231
17.430769
def valid_loc(self,F=None): """returns the indices of individuals with valid fitness.""" if F is not None: return [i for i,f in enumerate(F) if np.all(f < self.max_fit) and np.all(f >= 0)] else: return [i for i,f in enumerate(self.F) if np.all(f < self.max_fit) and np.all...
[ "def", "valid_loc", "(", "self", ",", "F", "=", "None", ")", ":", "if", "F", "is", "not", "None", ":", "return", "[", "i", "for", "i", ",", "f", "in", "enumerate", "(", "F", ")", "if", "np", ".", "all", "(", "f", "<", "self", ".", "max_fit", ...
54
27.666667
def __deserialize_primitive(self, data, klass): """ Deserializes string to primitive type. :param data: str. :param klass: class literal. :return: int, long, float, str, bool. """ try: return klass(data) except UnicodeEncodeError: ...
[ "def", "__deserialize_primitive", "(", "self", ",", "data", ",", "klass", ")", ":", "try", ":", "return", "klass", "(", "data", ")", "except", "UnicodeEncodeError", ":", "return", "text", "(", "data", ")", "except", "TypeError", ":", "return", "data" ]
24.933333
13.6
def union(*sets, **kwargs): """all unique items which occur in any one of the sets Parameters ---------- sets : tuple of indexable objects Returns ------- union of all items in all sets """ sets = _set_preprocess(sets, **kwargs) return as_index( _set_concatenate(sets), axis=0, ...
[ "def", "union", "(", "*", "sets", ",", "*", "*", "kwargs", ")", ":", "sets", "=", "_set_preprocess", "(", "sets", ",", "*", "*", "kwargs", ")", "return", "as_index", "(", "_set_concatenate", "(", "sets", ")", ",", "axis", "=", "0", ",", "base", "="...
25
18.769231
def bh_fdr(pval): """A python implementation of the Benjamani-Hochberg FDR method. This code should always give precisely the same answer as using p.adjust(pval, method="BH") in R. Parameters ---------- pval : list or array list/array of p-values Returns ------- pval_adj :...
[ "def", "bh_fdr", "(", "pval", ")", ":", "pval_array", "=", "np", ".", "array", "(", "pval", ")", "sorted_order", "=", "np", ".", "argsort", "(", "pval_array", ")", "original_order", "=", "np", ".", "argsort", "(", "sorted_order", ")", "pval_array", "=", ...
29.851852
18.62963
def find_regex(self, name_regex: str) -> Dict[str, Optional[ConnectedConsulLockInformation]]: """ Finds the locks with key names that match the given regex. :param name_regex: key name regex :return: keys that match """ # Gets prefix directory (must not include regex!) ...
[ "def", "find_regex", "(", "self", ",", "name_regex", ":", "str", ")", "->", "Dict", "[", "str", ",", "Optional", "[", "ConnectedConsulLockInformation", "]", "]", ":", "# Gets prefix directory (must not include regex!)", "escaped_name_regex", "=", "re", ".", "escape"...
48.37037
23.851852
def get_class_attributes(cls): """Return a generator for class attributes' names and value. This method strict relies on the PEP 520 (Preserving Class Attribute Definition Order), implemented on Python 3.6. So, if this behaviour changes this whole lib can loose its functionality (since ...
[ "def", "get_class_attributes", "(", "cls", ")", ":", "#: see this method docstring for a important notice about the use of", "#: cls.__dict__", "for", "name", ",", "value", "in", "cls", ".", "__dict__", ".", "items", "(", ")", ":", "# gets only our (kytos) attributes. this ...
43.538462
23.961538
def mask_missing(arr, values_to_mask): """ Return a masking array of same size/shape as arr with entries equaling any member of values_to_mask set to True """ dtype, values_to_mask = infer_dtype_from_array(values_to_mask) try: values_to_mask = np.array(values_to_mask, dtype=dtype) ...
[ "def", "mask_missing", "(", "arr", ",", "values_to_mask", ")", ":", "dtype", ",", "values_to_mask", "=", "infer_dtype_from_array", "(", "values_to_mask", ")", "try", ":", "values_to_mask", "=", "np", ".", "array", "(", "values_to_mask", ",", "dtype", "=", "dty...
26.510204
20.632653
def drop_columns(cr, column_spec): """ Drop columns but perform an additional check if a column exists. This covers the case of function fields that may or may not be stored. Consider that this may not be obvious: an additional module can govern a function fields' store properties. :param colum...
[ "def", "drop_columns", "(", "cr", ",", "column_spec", ")", ":", "for", "(", "table", ",", "column", ")", "in", "column_spec", ":", "logger", ".", "info", "(", "\"table %s: drop column %s\"", ",", "table", ",", "column", ")", "if", "column_exists", "(", "cr...
40.777778
13.666667
def message_about_scripts_not_on_PATH(scripts): # type: (Sequence[str]) -> Optional[str] """Determine if any scripts are not on PATH and format a warning. Returns a warning message if one or more scripts are not on PATH, otherwise None. """ if not scripts: return None # Group scrip...
[ "def", "message_about_scripts_not_on_PATH", "(", "scripts", ")", ":", "# type: (Sequence[str]) -> Optional[str]", "if", "not", "scripts", ":", "return", "None", "# Group scripts by the path they were installed in", "grouped_by_dir", "=", "collections", ".", "defaultdict", "(", ...
35.783333
21.65
def untldict_normalizer(untl_dict, normalizations): """Normalize UNTL elements by their qualifier. Takes a UNTL descriptive metadata dictionary and a dictionary of the elements and the qualifiers for normalization: {'element1': ['qualifier1', 'qualifier2'], 'element2': ['qualifier3']} and norm...
[ "def", "untldict_normalizer", "(", "untl_dict", ",", "normalizations", ")", ":", "# Loop through the element types in the UNTL metadata.", "for", "element_type", ",", "element_list", "in", "untl_dict", ".", "items", "(", ")", ":", "# A normalization is required for that eleme...
53.484848
18.30303
def get_transcript_ids_for_ensembl_gene_ids(self, gene_ids, hgnc_symbols): """ fetch the ensembl transcript IDs for a given ensembl gene ID. Args: gene_ids: list of Ensembl gene IDs for the gene hgnc_symbols: list of possible HGNC symbols for gene """ ...
[ "def", "get_transcript_ids_for_ensembl_gene_ids", "(", "self", ",", "gene_ids", ",", "hgnc_symbols", ")", ":", "chroms", "=", "{", "\"1\"", ",", "\"2\"", ",", "\"3\"", ",", "\"4\"", ",", "\"5\"", ",", "\"6\"", ",", "\"7\"", ",", "\"8\"", ",", "\"9\"", ",",...
42.8
21.714286
def _build_name_attribute(self, name=None): ''' Build a name attribute, returned in a list for ease of use in the caller ''' name_list = [] if name: name_list.append(self.attribute_factory.create_attribute( enums.AttributeType.NAME, ...
[ "def", "_build_name_attribute", "(", "self", ",", "name", "=", "None", ")", ":", "name_list", "=", "[", "]", "if", "name", ":", "name_list", ".", "append", "(", "self", ".", "attribute_factory", ".", "create_attribute", "(", "enums", ".", "AttributeType", ...
29.833333
18.833333
def make_example_docstr(funcname=None, modname=None, argname_list=None, defaults=None, return_type=None, return_name=None, ismethod=False): """ Creates skeleton code to build an example doctest Args: funcname (str): function name modname (str...
[ "def", "make_example_docstr", "(", "funcname", "=", "None", ",", "modname", "=", "None", ",", "argname_list", "=", "None", ",", "defaults", "=", "None", ",", "return_type", "=", "None", ",", "return_name", "=", "None", ",", "ismethod", "=", "False", ")", ...
38.890052
15.732984
def add_to_writer(self, writer: PdfFileWriter, start_recto: bool = True) -> None: """ Add the PDF described by this class to a PDF writer. Args: writer: a :class:`PyPDF2.PdfFileWriter` start_recto: start a new right-hand page? ...
[ "def", "add_to_writer", "(", "self", ",", "writer", ":", "PdfFileWriter", ",", "start_recto", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "self", ".", "is_html", ":", "pdf", "=", "get_pdf_from_html", "(", "html", "=", "self", ".", "html", "...
38.730769
15.807692
def filter_data(self, data, values=None, args=None): """Return entries containing specified patterns (single log)""" if args: if not args.pattern: return data if not values: values = args.pattern newdata = {} if 'parser' in data.keys(): new...
[ "def", "filter_data", "(", "self", ",", "data", ",", "values", "=", "None", ",", "args", "=", "None", ")", ":", "if", "args", ":", "if", "not", "args", ".", "pattern", ":", "return", "data", "if", "not", "values", ":", "values", "=", "args", ".", ...
37.384615
16.961538
def item_controller(self): """Method to control a task.""" return StartActionItemController( self, self.raw, self.state, self.path, self.devices_dict)
[ "def", "item_controller", "(", "self", ")", ":", "return", "StartActionItemController", "(", "self", ",", "self", ".", "raw", ",", "self", ".", "state", ",", "self", ".", "path", ",", "self", ".", "devices_dict", ")" ]
27.375
12.75
async def status(self, switch=None): """Get current relay status.""" if switch is not None: if self.waiters or self.in_transaction: fut = self.loop.create_future() self.status_waiters.append(fut) states = await fut state = state...
[ "async", "def", "status", "(", "self", ",", "switch", "=", "None", ")", ":", "if", "switch", "is", "not", "None", ":", "if", "self", ".", "waiters", "or", "self", ".", "in_transaction", ":", "fut", "=", "self", ".", "loop", ".", "create_future", "(",...
39.238095
11.095238
def visit_Call(self, node): # type: (ast.Call) -> None """python3.7+ breakpoint()""" if isinstance(node.func, ast.Name) and node.func.id == 'breakpoint': st = Debug(node.lineno, node.col_offset, node.func.id, 'called') self.breakpoints.append(st) self.generic_visit(node)
[ "def", "visit_Call", "(", "self", ",", "node", ")", ":", "# type: (ast.Call) -> None", "if", "isinstance", "(", "node", ".", "func", ",", "ast", ".", "Name", ")", "and", "node", ".", "func", ".", "id", "==", "'breakpoint'", ":", "st", "=", "Debug", "("...
52.5
16
def abi_to_fasta(input, output): ''' Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files ''' direcs = [input, ]...
[ "def", "abi_to_fasta", "(", "input", ",", "output", ")", ":", "direcs", "=", "[", "input", ",", "]", "# unzip any zip archives", "zip_files", "=", "list_files", "(", "input", ",", "[", "'zip'", "]", ")", "if", "zip_files", ":", "direcs", ".", "extend", "...
34.68
20.2
def from_dict(cls, word2index, unk, counts=None): """Create Vocab from an existing string to integer dictionary. All counts are set to 0. :param word2index: a dictionary representing a bijection from N words to the integers 0 through N-1. UNK must be assigned the 0 index. ...
[ "def", "from_dict", "(", "cls", ",", "word2index", ",", "unk", ",", "counts", "=", "None", ")", ":", "try", ":", "if", "word2index", "[", "unk", "]", "!=", "0", ":", "raise", "ValueError", "(", "'unk must be assigned index 0'", ")", "except", "KeyError", ...
35.880952
25.333333
def report_idle_after(seconds): """Report_idle_after after certain number of seconds.""" def decorator(func): def wrapper(*args, **kwargs): def _handle_timeout(signum, frame): config = get_config() if not config.ready: config.load() ...
[ "def", "report_idle_after", "(", "seconds", ")", ":", "def", "decorator", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "_handle_timeout", "(", "signum", ",", "frame", ")", ":", "config", "=", "g...
32.827586
16.689655
def asyncPipeRegex(context=None, _INPUT=None, conf=None, **kwargs): """An operator that asynchronously replaces text in items using regexes. Each has the general format: "In [field] replace [match] with [replace]". Not loopable. Parameters ---------- context : pipe2py.Context object _INPUT ...
[ "def", "asyncPipeRegex", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "splits", "=", "yield", "asyncGetSplits", "(", "_INPUT", ",", "conf", "[", "'RULE'", "]", ",", "*", "*", ...
36.69697
20.727273
def map(self, func): """ Apply a function on each subarray. Parameters ---------- func : function This is applied to each value in the intermediate RDD. Returns ------- StackedArray """ vshape = self.shape[self.split:] ...
[ "def", "map", "(", "self", ",", "func", ")", ":", "vshape", "=", "self", ".", "shape", "[", "self", ".", "split", ":", "]", "x", "=", "self", ".", "_rdd", ".", "values", "(", ")", ".", "first", "(", ")", "if", "x", ".", "shape", "==", "vshape...
34.722222
21.092593
def send(self, data): """Send data to socket.""" # send message _LOGGER.debug("send: " + data) self.socket.send(data.encode('ascii')) # sleep needed to prevent flooding the GC100 with sends sleep(.01)
[ "def", "send", "(", "self", ",", "data", ")", ":", "# send message\r", "_LOGGER", ".", "debug", "(", "\"send: \"", "+", "data", ")", "self", ".", "socket", ".", "send", "(", "data", ".", "encode", "(", "'ascii'", ")", ")", "# sleep needed to prevent floodi...
35.428571
12.714286
def emit_metadata_for_region_py(self, region, region_filename, module_prefix): """Emit Python code generating the metadata for the given region""" terrobj = self.territory[region] with open(region_filename, "w") as outfile: prnt(_REGION_METADATA_PROLOG % {'region': terrobj.identifier...
[ "def", "emit_metadata_for_region_py", "(", "self", ",", "region", ",", "region_filename", ",", "module_prefix", ")", ":", "terrobj", "=", "self", ".", "territory", "[", "region", "]", "with", "open", "(", "region_filename", ",", "\"w\"", ")", "as", "outfile", ...
74.833333
29
def remap_args(input_args, remap): """ Generate a new argument list by remapping keys. The 'remap' dict maps from destination key -> priority list of source keys """ out_args = input_args for dest_key, src_keys in remap.items(): remap_value = None if isinstance(src_keys, str): ...
[ "def", "remap_args", "(", "input_args", ",", "remap", ")", ":", "out_args", "=", "input_args", "for", "dest_key", ",", "src_keys", "in", "remap", ".", "items", "(", ")", ":", "remap_value", "=", "None", "if", "isinstance", "(", "src_keys", ",", "str", ")...
30.619048
12.904762
def for_application(self, id, secret_key, api_version=None): """ Initialize GraphAPI with an OAuth access token for an application. :param id: An integer describing a Facebook application. :param secret_key: A String describing the Facebook application's secret key. """ ...
[ "def", "for_application", "(", "self", ",", "id", ",", "secret_key", ",", "api_version", "=", "None", ")", ":", "from", "facepy", ".", "utils", "import", "get_application_access_token", "access_token", "=", "get_application_access_token", "(", "id", ",", "secret_k...
46.909091
26.727273
def add_to_graph(self, nodes, edges, nesting): """ Adds nodes and edges to the graph as long as the maximum number of nodes is not exceeded. All edges are expected to have a reference to an entry in nodes. If the list of nodes is not added in the first hop due to graph si...
[ "def", "add_to_graph", "(", "self", ",", "nodes", ",", "edges", ",", "nesting", ")", ":", "if", "(", "len", "(", "nodes", ")", "+", "len", "(", "self", ".", "added", ")", ")", ">", "self", ".", "max_nodes", ":", "if", "nesting", "<", "2", ":", ...
41.464286
14.892857
async def delete_invite(self, invite): """|coro| Revokes an :class:`.Invite`, URL, or ID to an invite. You must have the :attr:`~.Permissions.manage_channels` permission in the associated guild to do this. Parameters ---------- invite: Union[:class:`.Invite`, :...
[ "async", "def", "delete_invite", "(", "self", ",", "invite", ")", ":", "invite_id", "=", "utils", ".", "resolve_invite", "(", "invite", ")", "await", "self", ".", "http", ".", "delete_invite", "(", "invite_id", ")" ]
27.48
19.24
def get_config(self, budget): """ Function to sample a new configuration This function is called inside Hyperband to query a new configuration Parameters: ----------- budget: float the budget for which this configuration is scheduled returns: config should return a valid configuration ...
[ "def", "get_config", "(", "self", ",", "budget", ")", ":", "self", ".", "logger", ".", "debug", "(", "'start sampling a new configuration.'", ")", "sample", "=", "None", "info_dict", "=", "{", "}", "# If no model is available, sample from prior", "# also mix in a frac...
33.551471
24.889706
def wait(button=LEFT, target_types=(UP, DOWN, DOUBLE)): """ Blocks program execution until the given button performs an event. """ from threading import Lock lock = Lock() lock.acquire() handler = on_button(lock.release, (), [button], target_types) lock.acquire() _listener.remove_han...
[ "def", "wait", "(", "button", "=", "LEFT", ",", "target_types", "=", "(", "UP", ",", "DOWN", ",", "DOUBLE", ")", ")", ":", "from", "threading", "import", "Lock", "lock", "=", "Lock", "(", ")", "lock", ".", "acquire", "(", ")", "handler", "=", "on_b...
32.4
15
def excluded_length(self): """Surveyed length which does not count toward the included total""" return sum([shot.length for shot in self.shots if Exclude.LENGTH in shot.flags or Exclude.TOTAL in shot.flags])
[ "def", "excluded_length", "(", "self", ")", ":", "return", "sum", "(", "[", "shot", ".", "length", "for", "shot", "in", "self", ".", "shots", "if", "Exclude", ".", "LENGTH", "in", "shot", ".", "flags", "or", "Exclude", ".", "TOTAL", "in", "shot", "."...
73.666667
31
def _as_log_entry(self, name, now): """Makes a `LogEntry` from this instance for the given log_name. Args: rules (:class:`ReportingRules`): determines what labels, metrics and logs to include in the report request. now (:class:`datetime.DateTime`): the current time ...
[ "def", "_as_log_entry", "(", "self", ",", "name", ",", "now", ")", ":", "# initialize the struct with fields that are always present", "d", "=", "{", "u'http_response_code'", ":", "self", ".", "response_code", ",", "u'timestamp'", ":", "time", ".", "mktime", "(", ...
34.7
18.68
def first(self): """ Generate query parameters for the first page """ if self.total and self.limit < self.total: return {'page[offset]': 0, 'page[limit]': self.limit} else: return None
[ "def", "first", "(", "self", ")", ":", "if", "self", ".", "total", "and", "self", ".", "limit", "<", "self", ".", "total", ":", "return", "{", "'page[offset]'", ":", "0", ",", "'page[limit]'", ":", "self", ".", "limit", "}", "else", ":", "return", ...
32.428571
20.428571
def format_assistants_lines(cls, assistants): '''Return formatted assistants from the given list in human readable form.''' lines = cls._format_files(assistants, 'assistants') # Assistant help if assistants: lines.append('') assistant = strip_prefix(random.choice...
[ "def", "format_assistants_lines", "(", "cls", ",", "assistants", ")", ":", "lines", "=", "cls", ".", "_format_files", "(", "assistants", ",", "'assistants'", ")", "# Assistant help", "if", "assistants", ":", "lines", ".", "append", "(", "''", ")", "assistant",...
48.823529
29.176471
def _call(self, x, out=None): """Evaluate all operators in ``x`` and broadcast.""" wrapped_x = self.prod_op.domain.element([x], cast=False) return self.prod_op(wrapped_x, out=out)
[ "def", "_call", "(", "self", ",", "x", ",", "out", "=", "None", ")", ":", "wrapped_x", "=", "self", ".", "prod_op", ".", "domain", ".", "element", "(", "[", "x", "]", ",", "cast", "=", "False", ")", "return", "self", ".", "prod_op", "(", "wrapped...
50
10.5
def geth_commands(ctx, geth_hosts, datadir): """This is helpful to setup a private cluster of geth nodes that won't need discovery (because they can use the content of `static_nodes` as `static-nodes.json`). """ pretty = ctx.obj['pretty'] nodes = [] # pylint: disable=redefined-outer-name for i...
[ "def", "geth_commands", "(", "ctx", ",", "geth_hosts", ",", "datadir", ")", ":", "pretty", "=", "ctx", ".", "obj", "[", "'pretty'", "]", "nodes", "=", "[", "]", "# pylint: disable=redefined-outer-name", "for", "i", ",", "host", "in", "enumerate", "(", "get...
30.68
23.8
def set_headers(context): """ Parameters: +--------------+---------------+ | header_name | header_value | +==============+===============+ | header1 | value1 | +--------------+---------------+ | header2 | value2 | +--------------...
[ "def", "set_headers", "(", "context", ")", ":", "safe_add_http_request_context_to_behave_context", "(", "context", ")", "headers", "=", "dict", "(", ")", "for", "row", "in", "context", ".", "table", ":", "headers", "[", "row", "[", "\"header_name\"", "]", "]",...
32.588235
9.529412
def _load_build(self): """See `pickle.py` in Python's source code.""" # if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2], Ref): # Ref.__setstate__ will know it's a remote ref if the state is a tuple self.stack[-1] = (self...
[ "def", "_load_build", "(", "self", ")", ":", "# if the ctor. function (penultimate on the stack) is the `Ref` class...", "if", "isinstance", "(", "self", ".", "stack", "[", "-", "2", "]", ",", "Ref", ")", ":", "# Ref.__setstate__ will know it's a remote ref if the state is ...
47.333333
20.888889
def set_widgets(self): """Set widgets on the extra keywords tab.""" self.clear() self.description_label.setText( 'In this step you can set some extra keywords for the layer. This ' 'keywords can be used for creating richer reporting or map.') subcategory = self.pa...
[ "def", "set_widgets", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "self", ".", "description_label", ".", "setText", "(", "'In this step you can set some extra keywords for the layer. This '", "'keywords can be used for creating richer reporting or map.'", ")", "sub...
41.541667
21.041667
def set_state(self, state): """ :param state: a boolean of true (on) or false ('off') :return: nothing """ if self.index() == 0: values = {"outlets": [{"desired_state": {"powered": state}}, {}]} else: values = {"outlets": [{}, {"desired_s...
[ "def", "set_state", "(", "self", ",", "state", ")", ":", "if", "self", ".", "index", "(", ")", "==", "0", ":", "values", "=", "{", "\"outlets\"", ":", "[", "{", "\"desired_state\"", ":", "{", "\"powered\"", ":", "state", "}", "}", ",", "{", "}", ...
44.153846
24.153846
def set_text(self, text): """Set the filter text.""" text = text.strip() new_text = self.text() + text self.setText(new_text)
[ "def", "set_text", "(", "self", ",", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "new_text", "=", "self", ".", "text", "(", ")", "+", "text", "self", ".", "setText", "(", "new_text", ")" ]
31.4
7.6
def get_y(self, var, coords=None): """ Get the y-coordinate of a variable This method searches for the y-coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'Y', otherwise it looks whether there is an intersection ...
[ "def", "get_y", "(", "self", ",", "var", ",", "coords", "=", "None", ")", ":", "coords", "=", "coords", "or", "self", ".", "ds", ".", "coords", "coord", "=", "self", ".", "get_variable_by_axis", "(", "var", ",", "'y'", ",", "coords", ")", "if", "co...
40.25
20.428571
def write_PROM_HOTB_progenitor(self,name,description): """ Write a progenitor file for the PROMETHEUS/HBOT supernova code. Parameters ---------- name : string File name for the progenitor file description : string Information to be written into th...
[ "def", "write_PROM_HOTB_progenitor", "(", "self", ",", "name", ",", "description", ")", ":", "try", ":", "from", "ProgenitorHotb_new", "import", "ProgenitorHotb_new", "except", "ImportError", ":", "print", "(", "'Module ProgenitorHotb_new not found.'", ")", "return", ...
35.181818
17.909091
def set_rules(self, rules): """ Sets the rules to be run or ignored for the audit. Args: rules: a dictionary of the format `{"ignore": [], "apply": []}`. See https://github.com/GoogleChrome/accessibility-developer-tools/tree/master/src/audits Passing `{"apply": []...
[ "def", "set_rules", "(", "self", ",", "rules", ")", ":", "self", ".", "rules_to_ignore", "=", "rules", ".", "get", "(", "\"ignore\"", ",", "[", "]", ")", "self", ".", "rules_to_run", "=", "rules", ".", "get", "(", "\"apply\"", ",", "[", "]", ")" ]
32.911765
27.205882
def _resolve_by_callback(request, url, urlconf=None): """ Finds a view function by urlconf. If the function has attribute 'navigation', it is used as breadcrumb title. Such title can be either a callable or an object with `__unicode__` attribute. If it is callable, it must follow the views API (i.e....
[ "def", "_resolve_by_callback", "(", "request", ",", "url", ",", "urlconf", "=", "None", ")", ":", "try", ":", "callback", ",", "args", ",", "kwargs", "=", "_resolve_url", "(", "url", ",", "request", ",", "urlconf", "=", "urlconf", ")", "except", "urlreso...
38.257143
20.942857
def _initialize(self, chain, length): """Create an array of zeros with shape (length, shape(obj)), where obj is the internal PyMC Stochastic or Deterministic. """ # If this db was loaded from the disk, it may not have its # tallied step methods' getfuncs yet. if self._get...
[ "def", "_initialize", "(", "self", ",", "chain", ",", "length", ")", ":", "# If this db was loaded from the disk, it may not have its", "# tallied step methods' getfuncs yet.", "if", "self", ".", "_getfunc", "is", "None", ":", "self", ".", "_getfunc", "=", "self", "."...
39.419355
20.032258
def _get_vm_status(self): """ Returns this VM suspend status. Status are extracted from: https://github.com/qemu/qemu/blob/master/qapi-schema.json#L152 :returns: status (string) """ result = yield from self._control_vm("info status", [ b"debug", b...
[ "def", "_get_vm_status", "(", "self", ")", ":", "result", "=", "yield", "from", "self", ".", "_control_vm", "(", "\"info status\"", ",", "[", "b\"debug\"", ",", "b\"inmigrate\"", ",", "b\"internal-error\"", ",", "b\"io-error\"", ",", "b\"paused\"", ",", "b\"post...
34.538462
16.076923
def pythag(a, b): """Computer c = (a^2 + b^2)^0.5 without destructive underflow or overflow It solves the Pythagorean theorem a^2 + b^2 = c^2 """ absA = abs(a) absB = abs(b) if absA > absB: return absA * sqrt(1.0 + (absB / float(absA)) ** 2) elif absB == 0.0: return 0.0 ...
[ "def", "pythag", "(", "a", ",", "b", ")", ":", "absA", "=", "abs", "(", "a", ")", "absB", "=", "abs", "(", "b", ")", "if", "absA", ">", "absB", ":", "return", "absA", "*", "sqrt", "(", "1.0", "+", "(", "absB", "/", "float", "(", "absA", ")"...
28.692308
19.461538
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Passw...
[ "def", "xml", "(", "self", ")", ":", "root", "=", "Element", "(", "'UsernameToken'", ",", "ns", "=", "wssens", ")", "u", "=", "Element", "(", "'Username'", ",", "ns", "=", "wssens", ")", "u", ".", "setText", "(", "self", ".", "username", ")", "root...
31.409091
9.227273
def fit( self, durations, event_observed=None, timeline=None, entry=None, label="KM_estimate", left_censorship=False, alpha=None, ci_labels=None, weights=None, ): # pylint: disable=too-many-arguments,too-many-locals """ ...
[ "def", "fit", "(", "self", ",", "durations", ",", "event_observed", "=", "None", ",", "timeline", "=", "None", ",", "entry", "=", "None", ",", "label", "=", "\"KM_estimate\"", ",", "left_censorship", "=", "False", ",", "alpha", "=", "None", ",", "ci_labe...
48.113208
30.037736
def smudge(newtype, target): """ Smudge magic bytes with a known type """ db = smudge_db.get() magic_bytes = db[newtype]['magic'] magic_offset = db[newtype]['offset'] _backup_bytes(target, magic_offset, len(magic_bytes)) _smudge_bytes(target, magic_offset, magic_bytes)
[ "def", "smudge", "(", "newtype", ",", "target", ")", ":", "db", "=", "smudge_db", ".", "get", "(", ")", "magic_bytes", "=", "db", "[", "newtype", "]", "[", "'magic'", "]", "magic_offset", "=", "db", "[", "newtype", "]", "[", "'offset'", "]", "_backup...
24.75
15.25
def use_plenary_vault_view(self): """A complete view of the ``Authorization`` and ``Vault`` returns is desired. Methods will return what is requested or result in an error. This view is used when greater precision is desired at the expense of interoperability. *compliance: mand...
[ "def", "use_plenary_vault_view", "(", "self", ")", ":", "# Implemented from template for", "# osid.resource.BinLookupSession.use_plenary_bin_view", "self", ".", "_catalog_view", "=", "PLENARY", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "self", ".", ...
40.666667
17.733333
def prefix(self, imod: YangIdentifier, mid: ModuleId) -> YangIdentifier: """Return the prefix corresponding to an implemented module. Args: imod: Name of an implemented module. mid: Identifier of the context module. Raises: ModuleNotImplemented: If `imod` is...
[ "def", "prefix", "(", "self", ",", "imod", ":", "YangIdentifier", ",", "mid", ":", "ModuleId", ")", "->", "YangIdentifier", ":", "try", ":", "did", "=", "(", "imod", ",", "self", ".", "implement", "[", "imod", "]", ")", "except", "KeyError", ":", "ra...
36.333333
18.375
def drop_constraints(quiet=True, stdout=None): """ Discover and drop all constraints. :type: bool :return: None """ results, meta = db.cypher_query("CALL db.constraints()") pattern = re.compile(':(.*) \).*\.(\w*)') for constraint in results: db.cypher_query('DROP ' + constraint...
[ "def", "drop_constraints", "(", "quiet", "=", "True", ",", "stdout", "=", "None", ")", ":", "results", ",", "meta", "=", "db", ".", "cypher_query", "(", "\"CALL db.constraints()\"", ")", "pattern", "=", "re", ".", "compile", "(", "':(.*) \\).*\\.(\\w*)'", ")...
33.1875
17.0625
def smart_query(cls, filters=None, sort_attrs=None, schema=None): """ Does magic Django-ish joins like post___user___name__startswith='Bob' (see https://goo.gl/jAgCyM) Does filtering, sorting and eager loading at the same time. And if, say, filters and sorting need the same join...
[ "def", "smart_query", "(", "cls", ",", "filters", "=", "None", ",", "sort_attrs", "=", "None", ",", "schema", "=", "None", ")", ":", "return", "smart_query", "(", "cls", ".", "query", ",", "filters", ",", "sort_attrs", ",", "schema", ")" ]
44.923077
18.615385
def get_file_hash(self, *algorithms: str): ''' get lower case hash of file. return value is a tuple, you may need to unpack it. for example: `get_file_hash('md5', 'sha1')` return `('XXXX1', 'XXXX2')` ''' from .hashs import hashfile_hexdigest return hashfile_hexd...
[ "def", "get_file_hash", "(", "self", ",", "*", "algorithms", ":", "str", ")", ":", "from", ".", "hashs", "import", "hashfile_hexdigest", "return", "hashfile_hexdigest", "(", "self", ".", "_path", ",", "algorithms", ")" ]
34
22.4
def match_preferences(self, pcr=None, issuer=None): """ Match the clients preferences against what the provider can do. This is to prepare for later client registration and or what functionality the client actually will use. In the client configuration the client preferences are ...
[ "def", "match_preferences", "(", "self", ",", "pcr", "=", "None", ",", "issuer", "=", "None", ")", ":", "if", "not", "pcr", ":", "pcr", "=", "self", ".", "service_context", ".", "provider_info", "regreq", "=", "oidc", ".", "RegistrationRequest", "for", "...
39.209302
18.116279
def make_symmetric_matrix_from_upper_tri(val): """ Given a symmetric matrix in upper triangular matrix form as flat array indexes as: [A_xx,A_yy,A_zz,A_xy,A_xz,A_yz] This will generate the full matrix: [[A_xx,A_xy,A_xz],[A_xy,A_yy,A_yz],[A_xz,A_yz,A_zz] """ idx = [0,3,4,1,5,2] val = np.a...
[ "def", "make_symmetric_matrix_from_upper_tri", "(", "val", ")", ":", "idx", "=", "[", "0", ",", "3", ",", "4", ",", "1", ",", "5", ",", "2", "]", "val", "=", "np", ".", "array", "(", "val", ")", "[", "idx", "]", "mask", "=", "~", "np", ".", "...
32.714286
12.285714
def from_dict(cls, enclave): """ Create a enclave object from a dictionary. :param enclave: The dictionary. :return: The enclave object. """ return Enclave(id=enclave.get('id'), name=enclave.get('name'), type=EnclaveType.fro...
[ "def", "from_dict", "(", "cls", ",", "enclave", ")", ":", "return", "Enclave", "(", "id", "=", "enclave", ".", "get", "(", "'id'", ")", ",", "name", "=", "enclave", ".", "get", "(", "'name'", ")", ",", "type", "=", "EnclaveType", ".", "from_string", ...
30.909091
13.818182
def shutdown(self, skip_hooks=False): """ Shuts down the process. `skip_hooks` Set to ``True`` to skip running task end event plugins. """ if not self._exited: self._exited = True if not skip_hooks: self._run_events(shutd...
[ "def", "shutdown", "(", "self", ",", "skip_hooks", "=", "False", ")", ":", "if", "not", "self", ".", "_exited", ":", "self", ".", "_exited", "=", "True", "if", "not", "skip_hooks", ":", "self", ".", "_run_events", "(", "shutdown", "=", "True", ")", "...
25.8125
17.0625
def _parse_list(cls, value, separator=','): """Represents value as a list. Value is split either by separator (defaults to comma) or by lines. :param value: :param separator: List items separator character. :rtype: list """ if isinstance(value, list): # _get_pa...
[ "def", "_parse_list", "(", "cls", ",", "value", ",", "separator", "=", "','", ")", ":", "if", "isinstance", "(", "value", ",", "list", ")", ":", "# _get_parser_compound case", "return", "value", "if", "'\\n'", "in", "value", ":", "value", "=", "value", "...
29.833333
20.333333
def get_params(): """Get params to execute the micro-mordred""" parser = get_params_parser() args = parser.parse_args() if not args.raw and not args.enrich and not args.identities and not args.panels: print("No tasks enabled") sys.exit(1) return args
[ "def", "get_params", "(", ")", ":", "parser", "=", "get_params_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "not", "args", ".", "raw", "and", "not", "args", ".", "enrich", "and", "not", "args", ".", "identities", "and", ...
25.363636
23.454545
def transpose(self): """Return the transpose of the QuantumChannel.""" din, dout = self.dim dtr = self._data[0].shape[0] // dout stine = [None, None] for i, mat in enumerate(self._data): if mat is not None: stine[i] = np.reshape( np...
[ "def", "transpose", "(", "self", ")", ":", "din", ",", "dout", "=", "self", ".", "dim", "dtr", "=", "self", ".", "_data", "[", "0", "]", ".", "shape", "[", "0", "]", "//", "dout", "stine", "=", "[", "None", ",", "None", "]", "for", "i", ",", ...
38.785714
9.714286
def _add_compounds(self, variant_obj, info_dict): """Check if there are any compounds and add them to the variant The compounds that are added should be sorted on rank score """ compound_list = [] compound_entry = info_dict.get('Compounds') if compound_entry:...
[ "def", "_add_compounds", "(", "self", ",", "variant_obj", ",", "info_dict", ")", ":", "compound_list", "=", "[", "]", "compound_entry", "=", "info_dict", ".", "get", "(", "'Compounds'", ")", "if", "compound_entry", ":", "for", "family_annotation", "in", "compo...
41.793103
16.896552
def retrieve_agent_profile_ids(self, agent, since=None): """Retrieve agent profile id(s) with the specified parameters :param agent: Agent object of desired agent profiles :type agent: :class:`tincan.agent.Agent` :param since: Retrieve agent profile id's since this time :type si...
[ "def", "retrieve_agent_profile_ids", "(", "self", ",", "agent", ",", "since", "=", "None", ")", ":", "if", "not", "isinstance", "(", "agent", ",", "Agent", ")", ":", "agent", "=", "Agent", "(", "agent", ")", "request", "=", "HTTPRequest", "(", "method", ...
34.964286
19.607143
def eval_objfn(self): """Compute components of regularisation function as well as total contribution to objective function. """ g0v = self.obfn_g0(self.obfn_g0var()) g1v = self.obfn_g1(self.obfn_g1var()) rgr = sl.rfl2norm2(np.sqrt(self.GHGf * np.conj(self.Xf) * self.Xf),...
[ "def", "eval_objfn", "(", "self", ")", ":", "g0v", "=", "self", ".", "obfn_g0", "(", "self", ".", "obfn_g0var", "(", ")", ")", "g1v", "=", "self", ".", "obfn_g1", "(", "self", ".", "obfn_g1var", "(", ")", ")", "rgr", "=", "sl", ".", "rfl2norm2", ...
41.363636
12.636364
def from_dict(data, ctx): """ Instantiate a new Order from a dict (generally from loading a JSON response). The data used to instantiate the Order is a shallow copy of the dict passed in, with any complex child types instantiated appropriately. """ type = data.ge...
[ "def", "from_dict", "(", "data", ",", "ctx", ")", ":", "type", "=", "data", ".", "get", "(", "\"type\"", ")", "if", "type", "==", "\"TAKE_PROFIT\"", ":", "return", "TakeProfitOrder", ".", "from_dict", "(", "data", ",", "ctx", ")", "if", "type", "==", ...
35.638889
16.916667
def make_msg_id(): """ Create a semi random message id, by using 12 char random hex string and a timestamp. @return: string consisting of timestamp, -, random value """ random_string = get_rand_string(12) timestamp = time.strftime("%Y%m%d%I%M%S") msg_id = timestamp + "-" + random_string ...
[ "def", "make_msg_id", "(", ")", ":", "random_string", "=", "get_rand_string", "(", "12", ")", "timestamp", "=", "time", ".", "strftime", "(", "\"%Y%m%d%I%M%S\"", ")", "msg_id", "=", "timestamp", "+", "\"-\"", "+", "random_string", "return", "msg_id" ]
32.8
13.4
def request_with_retries_on_post_search(self, session, url, query, json_input, stream, headers): """ Submit a request and retry POST search requests specifically. We don't currently retry on POST requests, and this is intended as a temporary fix until the swagger is updated and changes ...
[ "def", "request_with_retries_on_post_search", "(", "self", ",", "session", ",", "url", ",", "query", ",", "json_input", ",", "stream", ",", "headers", ")", ":", "# TODO: Revert this PR as soon as the appropriate swagger definitions have percolated up", "# to prod and merged; se...
46.625
22.5625
def report_errors(audit, url): """ Args: audit: results of `AxsAudit.do_audit()`. url: the url of the page being audited. Raises: `AccessibilityError` """ errors = AxsAudit.get_errors(audit) if errors: msg = u"URL '{}' has {} errors:\...
[ "def", "report_errors", "(", "audit", ",", "url", ")", ":", "errors", "=", "AxsAudit", ".", "get_errors", "(", "audit", ")", "if", "errors", ":", "msg", "=", "u\"URL '{}' has {} errors:\\n{}\"", ".", "format", "(", "url", ",", "len", "(", "errors", ")", ...
26.823529
14.823529
def lstm_attention_base(): """Base attention params.""" hparams = lstm_seq2seq() hparams.add_hparam("attention_layer_size", hparams.hidden_size) hparams.add_hparam("output_attention", True) hparams.add_hparam("num_heads", 1) return hparams
[ "def", "lstm_attention_base", "(", ")", ":", "hparams", "=", "lstm_seq2seq", "(", ")", "hparams", ".", "add_hparam", "(", "\"attention_layer_size\"", ",", "hparams", ".", "hidden_size", ")", "hparams", ".", "add_hparam", "(", "\"output_attention\"", ",", "True", ...
35
12.428571
def BitmathType(bmstring): """An 'argument type' for integrations with the argparse module. For more information, see https://docs.python.org/2/library/argparse.html#type Of particular interest to us is this bit: ``type=`` can take any callable that takes a single string argument and returns the converted v...
[ "def", "BitmathType", "(", "bmstring", ")", ":", "try", ":", "argvalue", "=", "bitmath", ".", "parse_string", "(", "bmstring", ")", "except", "ValueError", ":", "raise", "argparse", ".", "ArgumentTypeError", "(", "\"'%s' can not be parsed into a valid bitmath object\"...
36.229167
22.916667
def _combine_regions(all_regions, ref_regions): """Combine multiple BEDtools regions of regions into sorted final BEDtool. """ chrom_order = {} for i, x in enumerate(ref_regions): chrom_order[x.chrom] = i def wchrom_key(x): chrom, start, end = x return (chrom_order[chrom], st...
[ "def", "_combine_regions", "(", "all_regions", ",", "ref_regions", ")", ":", "chrom_order", "=", "{", "}", "for", "i", ",", "x", "in", "enumerate", "(", "ref_regions", ")", ":", "chrom_order", "[", "x", ".", "chrom", "]", "=", "i", "def", "wchrom_key", ...
42.4375
13
def plan_first_phase(N1, N2): """ Create a plan for the first stage of the pruned FFT operation. (Alex to provide a write up with more details.) Parameters ----------- N1 : int Number of rows. N2 : int Number of columns. Returns -------- plan : FFTWF plan ...
[ "def", "plan_first_phase", "(", "N1", ",", "N2", ")", ":", "N", "=", "N1", "*", "N2", "vin", "=", "pycbc", ".", "types", ".", "zeros", "(", "N", ",", "dtype", "=", "numpy", ".", "complex64", ")", "vout", "=", "pycbc", ".", "types", ".", "zeros", ...
32.064516
16.774194
def Decrypt(self, encrypted_data): """Decrypts the encrypted data. Args: encrypted_data (bytes): encrypted data. Returns: tuple[bytes,bytes]: decrypted data and remaining encrypted data. """ index_split = -(len(encrypted_data) % Blowfish.block_size) if index_split: remaining_...
[ "def", "Decrypt", "(", "self", ",", "encrypted_data", ")", ":", "index_split", "=", "-", "(", "len", "(", "encrypted_data", ")", "%", "Blowfish", ".", "block_size", ")", "if", "index_split", ":", "remaining_encrypted_data", "=", "encrypted_data", "[", "index_s...
29.842105
21.421053
def remove_tar_files(file_list): """Public function that removes temporary tar archive files in a local directory""" for f in file_list: if file_exists(f) and f.endswith('.tar'): os.remove(f)
[ "def", "remove_tar_files", "(", "file_list", ")", ":", "for", "f", "in", "file_list", ":", "if", "file_exists", "(", "f", ")", "and", "f", ".", "endswith", "(", "'.tar'", ")", ":", "os", ".", "remove", "(", "f", ")" ]
43
10
def _find_descendents(self, url): """Return properties document for url and all children.""" # Ad-hoc query for URL starting with a prefix map_fun = """function(doc) { var url = doc.url + "/"; if(doc.type === 'properties' && url.indexOf('%s') === 0) { ...
[ "def", "_find_descendents", "(", "self", ",", "url", ")", ":", "# Ad-hoc query for URL starting with a prefix", "map_fun", "=", "\"\"\"function(doc) {\n var url = doc.url + \"/\";\n if(doc.type === 'properties' && url.indexOf('%s') === 0) {\n em...
36.866667
15.266667
def del_var(self, varname, by_name=False): """Delete a variable from the various namespaces, so that, as far as possible, we're not keeping any hidden references to it. Parameters ---------- varname : str The name of the variable to delete. by_name : bool ...
[ "def", "del_var", "(", "self", ",", "varname", ",", "by_name", "=", "False", ")", ":", "if", "varname", "in", "(", "'__builtin__'", ",", "'__builtins__'", ")", ":", "raise", "ValueError", "(", "\"Refusing to delete %s\"", "%", "varname", ")", "ns_refs", "=",...
39.425
17.125
def require(self, perm_name, **kwargs): """Use as a decorator on a view to require a permission. Optional args: - ``field`` The name of the model field to use for lookup (this is only relevant when requiring a permission that was registered with ``model=SomeMode...
[ "def", "require", "(", "self", ",", "perm_name", ",", "*", "*", "kwargs", ")", ":", "view_decorator", "=", "self", ".", "_get_entry", "(", "perm_name", ")", ".", "view_decorator", "return", "view_decorator", "(", "*", "*", "kwargs", ")", "if", "kwargs", ...
32.590909
23.090909
def update(self, **kwargs): """ Overrides Django's update method to emit a post_bulk_operation signal when it completes. """ ret_val = super(ManagerUtilsQuerySet, self).update(**kwargs) post_bulk_operation.send(sender=self.model, model=self.model) return ret_val
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "ret_val", "=", "super", "(", "ManagerUtilsQuerySet", ",", "self", ")", ".", "update", "(", "*", "*", "kwargs", ")", "post_bulk_operation", ".", "send", "(", "sender", "=", "self", ".", ...
43.428571
20.571429
def extract_storm_objects(label_grid, data, x_grid, y_grid, times, dx=1, dt=1, obj_buffer=0): """ After storms are labeled, this method extracts the storm objects from the grid and places them into STObjects. The STObjects contain intensity, location, and shape information about each storm at each timestep....
[ "def", "extract_storm_objects", "(", "label_grid", ",", "data", ",", "x_grid", ",", "y_grid", ",", "times", ",", "dx", "=", "1", ",", "dt", "=", "1", ",", "obj_buffer", "=", "0", ")", ":", "storm_objects", "=", "[", "]", "if", "len", "(", "label_grid...
58.75
28.044118
def strip_prompt(self, *args, **kwargs): """Strip the trailing router prompt from the output.""" a_string = super(JuniperBase, self).strip_prompt(*args, **kwargs) return self.strip_context_items(a_string)
[ "def", "strip_prompt", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "a_string", "=", "super", "(", "JuniperBase", ",", "self", ")", ".", "strip_prompt", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "self", ".", "st...
56.25
10.5
def mappable(obj): """return whether an object is mappable or not.""" if isinstance(obj, (tuple,list)): return True for m in arrayModules: if isinstance(obj,m['type']): return True return False
[ "def", "mappable", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "tuple", ",", "list", ")", ")", ":", "return", "True", "for", "m", "in", "arrayModules", ":", "if", "isinstance", "(", "obj", ",", "m", "[", "'type'", "]", ")", ":...
28.75
13
def updateD_G(self, x): """ Compute Gradient for update of D See [2] for derivation of Gradient """ self.precompute(x) g = zeros(len(x)) Ai = zeros(self.A.shape[0]) for i in range(len(g)): Ai = self.A[:, i] g[i] = (self.E * (dot(se...
[ "def", "updateD_G", "(", "self", ",", "x", ")", ":", "self", ".", "precompute", "(", "x", ")", "g", "=", "zeros", "(", "len", "(", "x", ")", ")", "Ai", "=", "zeros", "(", "self", ".", "A", ".", "shape", "[", "0", "]", ")", "for", "i", "in",...
30.642857
13.357143
def to_ut1unix(time: Union[str, datetime, float, np.ndarray]) -> np.ndarray: """ converts time inputs to UT1 seconds since Unix epoch """ # keep this order time = totime(time) if isinstance(time, (float, int)): return time if isinstance(time, (tuple, list, np.ndarray)): ass...
[ "def", "to_ut1unix", "(", "time", ":", "Union", "[", "str", ",", "datetime", ",", "float", ",", "np", ".", "ndarray", "]", ")", "->", "np", ".", "ndarray", ":", "# keep this order", "time", "=", "totime", "(", "time", ")", "if", "isinstance", "(", "t...
31.875
18.875
def apply_trans_rot(ampal, translation, angle, axis, point, radians=False): """Applies a translation and rotation to an AMPAL object.""" if not numpy.isclose(angle, 0.0): ampal.rotate(angle=angle, axis=axis, point=point, radians=radians) ampal.translate(vector=translation) return
[ "def", "apply_trans_rot", "(", "ampal", ",", "translation", ",", "angle", ",", "axis", ",", "point", ",", "radians", "=", "False", ")", ":", "if", "not", "numpy", ".", "isclose", "(", "angle", ",", "0.0", ")", ":", "ampal", ".", "rotate", "(", "angle...
49.833333
17.166667
def close(self): """ Close the tunnel. If the tunnel is already closed or never opened, do nothing. """ if self.fd is None: return logger.debug("Closing tunnel '%s'..." % (self.name or "", )) # Close tun.ko file os.close(...
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "fd", "is", "None", ":", "return", "logger", ".", "debug", "(", "\"Closing tunnel '%s'...\"", "%", "(", "self", ".", "name", "or", "\"\"", ",", ")", ")", "# Close tun.ko file", "os", ".", "close...
25.125
21.375
def __assert_param_consistency(args, argx_list_): """ debugging function for accepts_scalar_input2 checks to make sure all the iterable inputs are of the same length """ if util_arg.NO_ASSERTS: return if len(argx_list_) == 0: return True argx_flags = [util_iter.isiterable(arg...
[ "def", "__assert_param_consistency", "(", "args", ",", "argx_list_", ")", ":", "if", "util_arg", ".", "NO_ASSERTS", ":", "return", "if", "len", "(", "argx_list_", ")", "==", "0", ":", "return", "True", "argx_flags", "=", "[", "util_iter", ".", "isiterable", ...
37.777778
17.555556
def other_dependencies(ctx, server, environment): """Install things that need to be in place before installing the main package.""" if 'extra_packages' in ctx.releaser: server = server.lower() extra_pkgs = [] if server in ["local"]: if 'local' in ctx.releaser.extra_packages: ...
[ "def", "other_dependencies", "(", "ctx", ",", "server", ",", "environment", ")", ":", "if", "'extra_packages'", "in", "ctx", ".", "releaser", ":", "server", "=", "server", ".", "lower", "(", ")", "extra_pkgs", "=", "[", "]", "if", "server", "in", "[", ...
49.138889
20.833333
def skip_if(condition, reason=None): """The skip_if decorator allows for you to bypass a test on conditions :param condition: Expects a boolean :param reason: Expects a string """ if condition: return skip(reason) def wrapper(func): return func return wrapper
[ "def", "skip_if", "(", "condition", ",", "reason", "=", "None", ")", ":", "if", "condition", ":", "return", "skip", "(", "reason", ")", "def", "wrapper", "(", "func", ")", ":", "return", "func", "return", "wrapper" ]
24.5
15.583333
def _get_spill_dir(self, n): """ Choose one directory for spill by number n """ return os.path.join(self.localdirs[n % len(self.localdirs)], str(n))
[ "def", "_get_spill_dir", "(", "self", ",", "n", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "localdirs", "[", "n", "%", "len", "(", "self", ".", "localdirs", ")", "]", ",", "str", "(", "n", ")", ")" ]
54
16
def chunks(l: List[Any], n: int) -> Iterable[List[Any]]: """ Yield successive ``n``-sized chunks from ``l``. Args: l: input list n: chunk size Yields: successive chunks of size ``n`` """ for i in range(0, len(l), n): yield l[i:i + n]
[ "def", "chunks", "(", "l", ":", "List", "[", "Any", "]", ",", "n", ":", "int", ")", "->", "Iterable", "[", "List", "[", "Any", "]", "]", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "l", ")", ",", "n", ")", ":", "yield", "l"...
19.928571
19.214286
def manage_subscription(): """Shows how to interact with a parameter subscription.""" subscription = processor.create_parameter_subscription([ '/YSS/SIMULATOR/BatteryVoltage1' ]) sleep(5) print('Adding extra items to the existing subscription...') subscription.add([ '/YSS/SIMUL...
[ "def", "manage_subscription", "(", ")", ":", "subscription", "=", "processor", ".", "create_parameter_subscription", "(", "[", "'/YSS/SIMULATOR/BatteryVoltage1'", "]", ")", "sleep", "(", "5", ")", "print", "(", "'Adding extra items to the existing subscription...'", ")", ...
31.607143
21.25
def create_deploy_branch(deploy_branch, push=True): """ If there is no remote branch with name specified in ``deploy_branch``, create one. Note that default ``deploy_branch`` is ``gh-pages`` for regular repos and ``master`` for ``github.io`` repos. Return True if ``deploy_branch`` was created,...
[ "def", "create_deploy_branch", "(", "deploy_branch", ",", "push", "=", "True", ")", ":", "if", "not", "deploy_branch_exists", "(", "deploy_branch", ")", ":", "print", "(", "\"Creating {} branch on doctr_remote\"", ".", "format", "(", "deploy_branch", ")", ")", "cl...
45.34375
22.40625