text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def expool(name): """ Confirm the existence of a kernel variable in the kernel pool. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/expool_c.html :param name: Name of the variable whose value is to be returned. :type name: str :return: True when the variable is in the pool. :rtype...
[ "def", "expool", "(", "name", ")", ":", "name", "=", "stypes", ".", "stringToCharP", "(", "name", ")", "found", "=", "ctypes", ".", "c_int", "(", ")", "libspice", ".", "expool_c", "(", "name", ",", "ctypes", ".", "byref", "(", "found", ")", ")", "r...
30.866667
0.002096
def make_grid_slot(self, n, m): """Create a n x m video grid, show it and add it to the list of video containers """ def slot_func(): cont = container.VideoContainerNxM(gpu_handler=self.gpu_handler, filterchain_group=self.filtercha...
[ "def", "make_grid_slot", "(", "self", ",", "n", ",", "m", ")", ":", "def", "slot_func", "(", ")", ":", "cont", "=", "container", ".", "VideoContainerNxM", "(", "gpu_handler", "=", "self", ".", "gpu_handler", ",", "filterchain_group", "=", "self", ".", "f...
55.545455
0.016103
def set_camera(self, camera_id): """ Set the camera view to the specified camera ID. """ self.viewer.cam.fixedcamid = camera_id self.viewer.cam.type = const.CAMERA_FIXED
[ "def", "set_camera", "(", "self", ",", "camera_id", ")", ":", "self", ".", "viewer", ".", "cam", ".", "fixedcamid", "=", "camera_id", "self", ".", "viewer", ".", "cam", ".", "type", "=", "const", ".", "CAMERA_FIXED" ]
34
0.009569
def _get_linear_lookup_table_and_weight(nbits, wp): """ Generate a linear lookup table. :param nbits: int Number of bits to represent a quantized weight value :param wp: numpy.array Weight blob to be quantized Returns ------- lookup_table: numpy.array Lookup table ...
[ "def", "_get_linear_lookup_table_and_weight", "(", "nbits", ",", "wp", ")", ":", "w", "=", "wp", ".", "reshape", "(", "1", ",", "-", "1", ")", "qw", ",", "scales", ",", "biases", "=", "_quantize_channelwise_linear", "(", "w", ",", "nbits", ",", "axis", ...
29.136364
0.001511
def listen_for_dweets_from(thing_name, timeout=900, key=None, session=None): """Create a real-time subscription to dweets """ url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name) session = session or requests.Session() if key is not None: params = {'key': key} else: ...
[ "def", "listen_for_dweets_from", "(", "thing_name", ",", "timeout", "=", "900", ",", "key", "=", "None", ",", "session", "=", "None", ")", ":", "url", "=", "BASE_URL", "+", "'/listen/for/dweets/from/{0}'", ".", "format", "(", "thing_name", ")", "session", "=...
39.619048
0.002347
def copy(self): """make a deep copy of self Returns ------- Ensemble : Ensemble """ df = super(Ensemble,self).copy() return type(self).from_dataframe(df=df)
[ "def", "copy", "(", "self", ")", ":", "df", "=", "super", "(", "Ensemble", ",", "self", ")", ".", "copy", "(", ")", "return", "type", "(", "self", ")", ".", "from_dataframe", "(", "df", "=", "df", ")" ]
20.5
0.014019
def length_longest_path(input): """ :type input: str :rtype: int """ curr_len, max_len = 0, 0 # running length and max length stack = [] # keep track of the name length for s in input.split('\n'): print("---------") print("<path>:", s) depth = s.count('\t') #...
[ "def", "length_longest_path", "(", "input", ")", ":", "curr_len", ",", "max_len", "=", "0", ",", "0", "# running length and max length", "stack", "=", "[", "]", "# keep track of the name length", "for", "s", "in", "input", ".", "split", "(", "'\\n'", ")", ":",...
38.652174
0.001098
def autoremove(list_only=False, purge=False): ''' .. versionadded:: 2015.5.0 Remove packages not required by another package using ``apt-get autoremove``. list_only : False Only retrieve the list of packages to be auto-removed, do not actually perform the auto-removal. purge :...
[ "def", "autoremove", "(", "list_only", "=", "False", ",", "purge", "=", "False", ")", ":", "cmd", "=", "[", "]", "if", "list_only", ":", "ret", "=", "[", "]", "cmd", ".", "extend", "(", "[", "'apt-get'", ",", "'--assume-no'", "]", ")", "if", "purge...
28.320755
0.000644
def _get_version(addon_dir, manifest, odoo_version_override=None, git_post_version=True): """ Get addon version information from an addon directory """ version = manifest.get('version') if not version: warn("No version in manifest in %s" % addon_dir) version = '0.0.0' if...
[ "def", "_get_version", "(", "addon_dir", ",", "manifest", ",", "odoo_version_override", "=", "None", ",", "git_post_version", "=", "True", ")", ":", "version", "=", "manifest", ".", "get", "(", "'version'", ")", "if", "not", "version", ":", "warn", "(", "\...
48.173913
0.000885
def clean_dataframe(df, is_slugify=True, threshold=50, rename_cols=None): """ This method is used to: - slugify the column names (if slugify is set to True) - convert columns to 'category' (if len(unique) < threshold) or 'int' - clean the dataframe and rename if necessary """ if is_slugify: ...
[ "def", "clean_dataframe", "(", "df", ",", "is_slugify", "=", "True", ",", "threshold", "=", "50", ",", "rename_cols", "=", "None", ")", ":", "if", "is_slugify", ":", "df", "=", "df", ".", "rename", "(", "columns", "=", "slugify", ")", "df", "=", "df"...
33.2
0.001464
def get_next(self, label): """Get the next section with the given label""" while self._get_current_label() != label: self._skip_section() return self._read_section()
[ "def", "get_next", "(", "self", ",", "label", ")", ":", "while", "self", ".", "_get_current_label", "(", ")", "!=", "label", ":", "self", ".", "_skip_section", "(", ")", "return", "self", ".", "_read_section", "(", ")" ]
39.4
0.00995
def account(self): """ In oder to obtain the actual :class:`account.Account` from this class, you can use the ``account`` attribute. """ account = self.account_class(self["owner"], blockchain_instance=self.blockchain) # account.refresh() return account
[ "def", "account", "(", "self", ")", ":", "account", "=", "self", ".", "account_class", "(", "self", "[", "\"owner\"", "]", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "# account.refresh()", "return", "account" ]
38.625
0.009494
def _process_err(self, err_msg): """ Processes the raw error message sent by the server and close connection with current server. """ if STALE_CONNECTION in err_msg: yield from self._process_op_err(ErrStaleConnection) return if AUTHORIZATION_VIOLA...
[ "def", "_process_err", "(", "self", ",", "err_msg", ")", ":", "if", "STALE_CONNECTION", "in", "err_msg", ":", "yield", "from", "self", ".", "_process_op_err", "(", "ErrStaleConnection", ")", "return", "if", "AUTHORIZATION_VIOLATION", "in", "err_msg", ":", "self"...
34.347826
0.002463
def load(self, filename): """ Loads checkpoint from filename. :param filename: path to the checkpoint file """ if os.path.isfile(filename): checkpoint = torch.load(filename, map_location={'cuda:0': 'cpu'}) if self.distributed: self.model.m...
[ "def", "load", "(", "self", ",", "filename", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "checkpoint", "=", "torch", ".", "load", "(", "filename", ",", "map_location", "=", "{", "'cuda:0'", ":", "'cpu'", "}", ")", "...
43.6
0.002245
def _split_markdown(text_url, tld_pos): """ Split markdown URL. There is an issue wen Markdown URL is found. Parsing of the URL does not stop on right place so wrongly found URL has to be split. :param str text_url: URL that we want to extract from enclosure :param int t...
[ "def", "_split_markdown", "(", "text_url", ",", "tld_pos", ")", ":", "# Markdown url can looks like:", "# [http://example.com/](http://example.com/status/210)", "left_bracket_pos", "=", "text_url", ".", "find", "(", "'['", ")", "# subtract 3 because URL is never shorter than 3 ch...
35.481481
0.002033
def iterSourceCode(paths): """ Iterate over all Python source files in C{paths}. @param paths: A list of paths. Directories will be recursed into and any .py files found will be yielded. Any non-directories will be yielded as-is. """ for path in paths: if os.path.isdir(pat...
[ "def", "iterSourceCode", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "path", ")", ":", ...
35.125
0.001733
def hot_questions(self): """获取话题下热门的问题 :return: 话题下的热门动态中的问题,按热门度顺序返回生成器 :rtype: Question.Iterable """ from .question import Question hot_questions_url = Topic_Hot_Questions_Url.format(self.id) params = {'start': 0, '_xsrf': self.xsrf} res = self._session...
[ "def", "hot_questions", "(", "self", ")", ":", "from", ".", "question", "import", "Question", "hot_questions_url", "=", "Topic_Hot_Questions_Url", ".", "format", "(", "self", ".", "id", ")", "params", "=", "{", "'start'", ":", "0", ",", "'_xsrf'", ":", "se...
40.735294
0.00141
def find(self, item): """ Return the smallest i such that i is the index of an element that wholly contains item. Raises ValueError if no such element exists. Does not require the segmentlist to be coalesced. """ for i, seg in enumerate(self): if item in seg: return i raise ValueError(item)
[ "def", "find", "(", "self", ",", "item", ")", ":", "for", "i", ",", "seg", "in", "enumerate", "(", "self", ")", ":", "if", "item", "in", "seg", ":", "return", "i", "raise", "ValueError", "(", "item", ")" ]
27.818182
0.037975
def _parse_east_asian(fname, properties=(u'W', u'F',)): """Parse unicode east-asian width tables.""" version, date, values = None, None, [] print("parsing {} ..".format(fname)) for line in open(fname, 'rb'): uline = line.decode('utf-8') if version is None: ...
[ "def", "_parse_east_asian", "(", "fname", ",", "properties", "=", "(", "u'W'", ",", "u'F'", ",", ")", ")", ":", "version", ",", "date", ",", "values", "=", "None", ",", "None", ",", "[", "]", "print", "(", "\"parsing {} ..\"", ".", "format", "(", "fn...
43.727273
0.002035
def cluster_meanshift(data, bandwidth=None, bin_seeding=False, **kwargs): """ Identify clusters using Meanshift algorithm. Parameters ---------- data : array_like array of size [n_samples, n_features]. bandwidth : float or None If None, bandwidth is estimated automatically using...
[ "def", "cluster_meanshift", "(", "data", ",", "bandwidth", "=", "None", ",", "bin_seeding", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "bandwidth", "is", "None", ":", "bandwidth", "=", "cl", ".", "estimate_bandwidth", "(", "data", ")", "ms", ...
27.413793
0.001215
def atomic_open(filename, mode='w'): ''' Works like a regular `open()` but writes updates into a temporary file instead of the given file and moves it over when the file is closed. The file returned behaves as if it was a regular Python ''' if mode in ('r', 'rb', 'r+', 'rb+', 'a', 'ab'): ...
[ "def", "atomic_open", "(", "filename", ",", "mode", "=", "'w'", ")", ":", "if", "mode", "in", "(", "'r'", ",", "'rb'", ",", "'r+'", ",", "'rb+'", ",", "'a'", ",", "'ab'", ")", ":", "raise", "TypeError", "(", "'Read or append modes don\\'t work with atomic_...
39.411765
0.001458
def parse(cls, fptr, offset, length): """Parse palette box. Parameters ---------- fptr : file Open file object. offset : int Start position of box in bytes. length : int Length of the box in bytes. Returns ------- ...
[ "def", "parse", "(", "cls", ",", "fptr", ",", "offset", ",", "length", ")", ":", "num_bytes", "=", "offset", "+", "length", "-", "fptr", ".", "tell", "(", ")", "read_buffer", "=", "fptr", ".", "read", "(", "num_bytes", ")", "nrows", ",", "ncols", "...
35.428571
0.001962
def get_model_string(model): """ This function returns the conventional action designator for a given model. """ name = model if isinstance(model, str) else model.__name__ return normalize_string(name)
[ "def", "get_model_string", "(", "model", ")", ":", "name", "=", "model", "if", "isinstance", "(", "model", ",", "str", ")", "else", "model", ".", "__name__", "return", "normalize_string", "(", "name", ")" ]
36.666667
0.008889
def iterator_from_slice(s): """ Constructs an iterator given a slice object s. .. note:: The function returns an infinite iterator if s.stop is None """ import numpy as np start = s.start if s.start is not None else 0 step = s.step if s.step is not None else 1 if s.stop is Non...
[ "def", "iterator_from_slice", "(", "s", ")", ":", "import", "numpy", "as", "np", "start", "=", "s", ".", "start", "if", "s", ".", "start", "is", "not", "None", "else", "0", "step", "=", "s", ".", "step", "if", "s", ".", "step", "is", "not", "None...
27.944444
0.001923
def resources(self): """Vault resources within context""" res = [] for resource in self._resources: res = res + resource.resources() return res
[ "def", "resources", "(", "self", ")", ":", "res", "=", "[", "]", "for", "resource", "in", "self", ".", "_resources", ":", "res", "=", "res", "+", "resource", ".", "resources", "(", ")", "return", "res" ]
26
0.010638
def exists(value): "Query to test if a value exists." if not isinstance(value, Token): raise TypeError('value must be a token') if not hasattr(value, 'identifier'): raise TypeError('value must support an identifier') if not value.identifier: value = value.__class__(**value.__di...
[ "def", "exists", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "Token", ")", ":", "raise", "TypeError", "(", "'value must be a token'", ")", "if", "not", "hasattr", "(", "value", ",", "'identifier'", ")", ":", "raise", "TypeError", ...
26.526316
0.001916
def macro_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/macros#show-macro" api_path = "/api/v2/macros/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "macro_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/macros/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ",", ...
48.2
0.008163
def deprecated(func): """ Mark functions as deprecated. It will result in a warning being emitted when the function is used. """ @functools.wraps(func) def new_func(*args, **kwargs): if sys.version_info < (3, 0): warnings.warn_explicit( "Call to deprecated fu...
[ "def", "deprecated", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "new_func", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "0", ")", ":", "warnings",...
35.291667
0.001149
def uninstall_all_visa_handlers(self, session): """Uninstalls all previously installed handlers for a particular session. :param session: Unique logical identifier to a session. If None, operates on all sessions. """ if session is not None: self.__uninstall_all_handlers_hel...
[ "def", "uninstall_all_visa_handlers", "(", "self", ",", "session", ")", ":", "if", "session", "is", "not", "None", ":", "self", ".", "__uninstall_all_handlers_helper", "(", "session", ")", "else", ":", "for", "session", "in", "list", "(", "self", ".", "handl...
40.545455
0.008772
def reverse(self): """ Returns a reversed copy of the list. """ colors = ColorList.copy(self) _list.reverse(colors) return colors
[ "def", "reverse", "(", "self", ")", ":", "colors", "=", "ColorList", ".", "copy", "(", "self", ")", "_list", ".", "reverse", "(", "colors", ")", "return", "colors" ]
24.428571
0.011299
def shared_volume_containers(self): """All the harpoon containers in volumes.share_with for this container""" for container in self.volumes.share_with: if not isinstance(container, six.string_types): yield container.name
[ "def", "shared_volume_containers", "(", "self", ")", ":", "for", "container", "in", "self", ".", "volumes", ".", "share_with", ":", "if", "not", "isinstance", "(", "container", ",", "six", ".", "string_types", ")", ":", "yield", "container", ".", "name" ]
52
0.011364
def map_metabolite2kegg(metabolite): """ Return a KEGG compound identifier for the metabolite if it exists. First see if there is an unambiguous mapping to a single KEGG compound ID provided with the model. If not, check if there is any KEGG compound ID in a list of mappings. KEGG IDs may map to co...
[ "def", "map_metabolite2kegg", "(", "metabolite", ")", ":", "logger", ".", "debug", "(", "\"Looking for KEGG compound identifier for %s.\"", ",", "metabolite", ".", "id", ")", "kegg_annotation", "=", "metabolite", ".", "annotation", ".", "get", "(", "\"kegg.compound\""...
39.366667
0.000413
def parse_docstring(doc): """Parse a docstring into ParameterInfo and ReturnInfo objects.""" doc = inspect.cleandoc(doc) lines = doc.split('\n') section = None section_indent = None params = {} returns = None for line in lines: line = line.rstrip() if len(line) == 0: ...
[ "def", "parse_docstring", "(", "doc", ")", ":", "doc", "=", "inspect", ".", "cleandoc", "(", "doc", ")", "lines", "=", "doc", ".", "split", "(", "'\\n'", ")", "section", "=", "None", "section_indent", "=", "None", "params", "=", "{", "}", "returns", ...
26.954545
0.000814
def parse_return(return_line, include_desc=False): """Parse a single return statement declaration. The valid types of return declarion are a Returns: section heading followed a line that looks like: type [format-as formatter]: description OR type [show-as (string | context)]: description sent...
[ "def", "parse_return", "(", "return_line", ",", "include_desc", "=", "False", ")", ":", "ret_def", ",", "_colon", ",", "desc", "=", "return_line", ".", "partition", "(", "':'", ")", "if", "_colon", "==", "\"\"", ":", "raise", "ValidationError", "(", "\"Inv...
32.425
0.002246
def main(): """ Command line interface. """ parser = argparse.ArgumentParser( description='monoseq: pretty-printing DNA and protein sequences', epilog='If INPUT is in FASTA format, each record is pretty-printed ' 'after printing its name and ANNOTATION (if supplied) is used by ' ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'monoseq: pretty-printing DNA and protein sequences'", ",", "epilog", "=", "'If INPUT is in FASTA format, each record is pretty-printed '", "'after printing its name and ANNO...
48.911765
0.00059
def run_step(context): """Executes dynamic python code. Context is a dictionary or dictionary-like. Context must contain key 'pycode' Will exec context['pycode'] as dynamically interpreted python statements. context is mandatory. When you execute the pipeline, it should look something like thi...
[ "def", "run_step", "(", "context", ")", ":", "logger", ".", "debug", "(", "\"started\"", ")", "context", ".", "assert_key_has_value", "(", "key", "=", "'pycode'", ",", "caller", "=", "__name__", ")", "logger", ".", "debug", "(", "f\"Executing python string: {c...
36.44
0.00107
def find_recursive_dependency(self): """Return a list of nodes that have a recursive dependency.""" nodes_on_path = [] def helper(nodes): for node in nodes: cycle = node in nodes_on_path nodes_on_path.append(node) if cycle or helper(self.deps.get(node, [])): return T...
[ "def", "find_recursive_dependency", "(", "self", ")", ":", "nodes_on_path", "=", "[", "]", "def", "helper", "(", "nodes", ")", ":", "for", "node", "in", "nodes", ":", "cycle", "=", "node", "in", "nodes_on_path", "nodes_on_path", ".", "append", "(", "node",...
27.266667
0.009456
def get_draft_url(url): """ Return the given URL with a draft mode HMAC in its querystring. """ if verify_draft_url(url): # Nothing to do. Already a valid draft URL. return url # Parse querystring and add draft mode HMAC. url = urlparse.urlparse(url) salt = get_random_string(...
[ "def", "get_draft_url", "(", "url", ")", ":", "if", "verify_draft_url", "(", "url", ")", ":", "# Nothing to do. Already a valid draft URL.", "return", "url", "# Parse querystring and add draft mode HMAC.", "url", "=", "urlparse", ".", "urlparse", "(", "url", ")", "sal...
36.588235
0.001567
def create(self, provider, names, **kwargs): ''' Create the named VMs, without using a profile Example: .. code-block:: python client.create(provider='my-ec2-config', names=['myinstance'], image='ami-1624987f', size='t1.micro', ssh_username='ec2-user', ...
[ "def", "create", "(", "self", ",", "provider", ",", "names", ",", "*", "*", "kwargs", ")", ":", "mapper", "=", "salt", ".", "cloud", ".", "Map", "(", "self", ".", "_opts_defaults", "(", ")", ")", "providers", "=", "self", ".", "opts", "[", "'provid...
38.684211
0.001991
def addkey(ctx, key): """ Add a private key to the wallet """ if not key: while True: key = click.prompt( "Private Key (wif) [Enter to quit]", hide_input=True, show_default=False, default="exit", ) if...
[ "def", "addkey", "(", "ctx", ",", "key", ")", ":", "if", "not", "key", ":", "while", "True", ":", "key", "=", "click", ".", "prompt", "(", "\"Private Key (wif) [Enter to quit]\"", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "d...
35.567568
0.00074
async def recv(self) -> Data: """ This coroutine receives the next message. It returns a :class:`str` for a text frame and :class:`bytes` for a binary frame. When the end of the message stream is reached, :meth:`recv` raises :exc:`~websockets.exceptions.ConnectionClosed...
[ "async", "def", "recv", "(", "self", ")", "->", "Data", ":", "if", "self", ".", "_pop_message_waiter", "is", "not", "None", ":", "raise", "RuntimeError", "(", "\"cannot call recv() while another coroutine \"", "\"is already waiting for the next message\"", ")", "# Don't...
39.626667
0.000985
def solve_unchecked(self, sense=None): """Solve problem and return result. The user must manually check the status of the result to determine whether an optimal solution was found. A :class:`SolverError` may still be raised if the underlying solver raises an exception. """ ...
[ "def", "solve_unchecked", "(", "self", ",", "sense", "=", "None", ")", ":", "if", "sense", "is", "not", "None", ":", "self", ".", "set_objective_sense", "(", "sense", ")", "parm", "=", "swiglpk", ".", "glp_smcp", "(", ")", "swiglpk", ".", "glp_init_smcp"...
36.478261
0.001161
def embed(self, name, data=None): """Attach an image file and prepare for HTML embedding. This method should only be used to embed images. :param name: Path to the image to embed if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the image to embed, or No...
[ "def", "embed", "(", "self", ",", "name", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "with", "open", "(", "name", ",", "'rb'", ")", "as", "fp", ":", "data", "=", "fp", ".", "read", "(", ")", "name", "=", "os", ".", ...
31.826087
0.030504
def unobserve_all_properties(self, handler): """Unregister a property observer from *all* observed properties.""" for name in self._property_handlers: self.unobserve_property(name, handler)
[ "def", "unobserve_all_properties", "(", "self", ",", "handler", ")", ":", "for", "name", "in", "self", ".", "_property_handlers", ":", "self", ".", "unobserve_property", "(", "name", ",", "handler", ")" ]
53.5
0.009217
def compose(self, other, qargs=None, front=False): """Return the composition channel self∘other. Args: other (QuantumChannel): a quantum channel. qargs (list): a list of subsystem positions to compose other on. front (bool): If False compose in standard order other(s...
[ "def", "compose", "(", "self", ",", "other", ",", "qargs", "=", "None", ",", "front", "=", "False", ")", ":", "# Convert other to SuperOp", "if", "not", "isinstance", "(", "other", ",", "SuperOp", ")", ":", "other", "=", "SuperOp", "(", "other", ")", "...
41.325581
0.0011
def save_dict(): """ Save the ignored java message dict stored in g_ok_java_messages into a pickle file for future use. :return: none """ global g_ok_java_messages global g_save_java_message_filename global g_dict_changed if g_dict_changed: with open(g_save_java_message_filenam...
[ "def", "save_dict", "(", ")", ":", "global", "g_ok_java_messages", "global", "g_save_java_message_filename", "global", "g_dict_changed", "if", "g_dict_changed", ":", "with", "open", "(", "g_save_java_message_filename", ",", "'wb'", ")", "as", "ofile", ":", "pickle", ...
28.846154
0.010336
def remove_usb_device_filter(self, position): """Removes a USB device filter from the specified position in the list of filters. Positions are numbered starting from @c 0. Specifying a position equal to or greater than the number of elements in the list will produce an e...
[ "def", "remove_usb_device_filter", "(", "self", ",", "position", ")", ":", "if", "not", "isinstance", "(", "position", ",", "baseinteger", ")", ":", "raise", "TypeError", "(", "\"position can only be an instance of type baseinteger\"", ")", "self", ".", "_call", "("...
36.384615
0.011329
def exists(self): """ :return: true if the associated schema exists on the server """ cur = self.connection.query("SHOW DATABASES LIKE '{database}'".format(database=self.database)) return cur.rowcount > 0
[ "def", "exists", "(", "self", ")", ":", "cur", "=", "self", ".", "connection", ".", "query", "(", "\"SHOW DATABASES LIKE '{database}'\"", ".", "format", "(", "database", "=", "self", ".", "database", ")", ")", "return", "cur", ".", "rowcount", ">", "0" ]
39.833333
0.012295
def voronoi(points, buffer_percent=100): """ Surrounds each point in an input list of xy tuples with a unique Voronoi polygon. Arguments: - **points**: A list of xy or xyz point tuples to triangulate. - **buffer_percent** (optional): Controls how much bigger than the original bbox...
[ "def", "voronoi", "(", "points", ",", "buffer_percent", "=", "100", ")", ":", "# Remove duplicate xy points bc that would make delauney fail, and must remember z (if any) for retrieving originals from index results", "seen", "=", "set", "(", ")", "uniqpoints", "=", "[", "p", ...
44.2
0.015808
def fourier_segments(self): """ Return a list of the FFT'd segments. Return the list of FrequencySeries. Additional properties are added that describe the strain segment. The property 'analyze' is a slice corresponding to the portion of the time domain equivelant of the segment t...
[ "def", "fourier_segments", "(", "self", ")", ":", "if", "not", "self", ".", "_fourier_segments", ":", "self", ".", "_fourier_segments", "=", "[", "]", "for", "seg_slice", ",", "ana", "in", "zip", "(", "self", ".", "segment_slices", ",", "self", ".", "ana...
55.37931
0.002448
def stats(self, **attrs): """ Method for `Data Stream Stats <https://m2x.att.com/developer/documentation/v2/device#Data-Stream-Stats>`_ endpoint. :param attrs: Query parameters passed as keyword arguments. View M2X API Docs for listing of available parameters. :return: The API response, see M2...
[ "def", "stats", "(", "self", ",", "*", "*", "attrs", ")", ":", "return", "self", ".", "api", ".", "get", "(", "self", ".", "subpath", "(", "'/stats'", ")", ",", "data", "=", "attrs", ")" ]
48.727273
0.009158
def make_camera(cam_type, *args, **kwargs): """ Factory function for creating new cameras using a string name. Parameters ---------- cam_type : str May be one of: * 'panzoom' : Creates :class:`PanZoomCamera` * 'turntable' : Creates :class:`TurntableCamera` *...
[ "def", "make_camera", "(", "cam_type", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cam_types", "=", "{", "None", ":", "BaseCamera", "}", "for", "camType", "in", "(", "BaseCamera", ",", "PanZoomCamera", ",", "PerspectiveCamera", ",", "TurntableCam...
32.407407
0.00111
def char_to_bytes(arr): """Convert numpy/dask arrays from characters to fixed width bytes.""" if arr.dtype != 'S1': raise ValueError("argument must have dtype='S1'") if not arr.ndim: # no dimension to concatenate along return arr size = arr.shape[-1] if not size: #...
[ "def", "char_to_bytes", "(", "arr", ")", ":", "if", "arr", ".", "dtype", "!=", "'S1'", ":", "raise", "ValueError", "(", "\"argument must have dtype='S1'\"", ")", "if", "not", "arr", ".", "ndim", ":", "# no dimension to concatenate along", "return", "arr", "size"...
32.6
0.000993
def convert_rgb_to_real(x): """Conversion of pixel values to real numbers.""" with tf.name_scope("rgb_to_real", values=[x]): x = to_float(x) x /= 255.0 return x
[ "def", "convert_rgb_to_real", "(", "x", ")", ":", "with", "tf", ".", "name_scope", "(", "\"rgb_to_real\"", ",", "values", "=", "[", "x", "]", ")", ":", "x", "=", "to_float", "(", "x", ")", "x", "/=", "255.0", "return", "x" ]
28.5
0.017045
def _validate_at_hash(claims, access_token, algorithm): """ Validates that the 'at_hash' parameter included in the claims matches with the access_token returned alongside the id token as part of the authorization_code flow. Args: claims (dict): The claims dictionary to validate. acc...
[ "def", "_validate_at_hash", "(", "claims", ",", "access_token", ",", "algorithm", ")", ":", "if", "'at_hash'", "not", "in", "claims", "and", "not", "access_token", ":", "return", "elif", "'at_hash'", "in", "claims", "and", "not", "access_token", ":", "msg", ...
41.566667
0.001567
def PathToComponents(path): """Converts a canonical path representation to a list of components. Args: path: A canonical MySQL path representation. Returns: A sequence of path components. """ precondition.AssertType(path, Text) if path and not path.startswith("/"): raise ValueError("Path '{}' ...
[ "def", "PathToComponents", "(", "path", ")", ":", "precondition", ".", "AssertType", "(", "path", ",", "Text", ")", "if", "path", "and", "not", "path", ".", "startswith", "(", "\"/\"", ")", ":", "raise", "ValueError", "(", "\"Path '{}' is not absolute\"", "....
23.882353
0.014218
def cnvlPwBoxCarFn(aryNrlTc, varNumVol, varTr, tplPngSize, varNumMtDrctn, switchHrfSet, lgcOldSchoolHrf, varPar,): """Create 2D Gaussian kernel. Parameters ---------- aryNrlTc : 5d numpy array, shape [n_x_pos, n_y_pos, n_sd, n_mtn_dir, n_vol] Description of input 1. varNu...
[ "def", "cnvlPwBoxCarFn", "(", "aryNrlTc", ",", "varNumVol", ",", "varTr", ",", "tplPngSize", ",", "varNumMtDrctn", ",", "switchHrfSet", ",", "lgcOldSchoolHrf", ",", "varPar", ",", ")", ":", "print", "(", "'------Convolve every pixel box car function with hrf function(s)...
32.113043
0.000263
def interpolate(self, date, method=None, order=None): """Interpolate data at a given date Args: date (Date): method (str): Method of interpolation to use order (int): In case of ``LAGRANGE`` method is used Return: Orbit: """ if no...
[ "def", "interpolate", "(", "self", ",", "date", ",", "method", "=", "None", ",", "order", "=", "None", ")", ":", "if", "not", "self", ".", "start", "<=", "date", "<=", "self", ".", "stop", ":", "raise", "ValueError", "(", "\"Date '%s' not in range\"", ...
30.921053
0.002474
def bow(self, tokens, remove_oov=False): """ Create a bow representation of a list of tokens. Parameters ---------- tokens : list. The list of items to change into a bag of words representation. remove_oov : bool. Whether to remove OOV items from ...
[ "def", "bow", "(", "self", ",", "tokens", ",", "remove_oov", "=", "False", ")", ":", "if", "remove_oov", ":", "tokens", "=", "[", "x", "for", "x", "in", "tokens", "if", "x", "in", "self", ".", "items", "]", "for", "t", "in", "tokens", ":", "try",...
36.909091
0.0016
def process_event(self, event, hover_focus): """ Process any input event. :param event: The event that was triggered. :param hover_focus: Whether to trigger focus change on mouse moves. :returns: None if the Effect processed the event, else the original event. """ ...
[ "def", "process_event", "(", "self", ",", "event", ",", "hover_focus", ")", ":", "# Check whether this Layout is read-only - i.e. has no active focus.", "if", "self", ".", "_live_col", "<", "0", "or", "self", ".", "_live_widget", "<", "0", ":", "# Might just be that w...
52.446809
0.000796
def link_or_copy(src, dst, verbosity=0): """Try to make a hard link from src to dst and if that fails copy the file. Hard links save some disk space and linking should fail fast since no copying is involved. """ if verbosity > 0: log_info("Copying %s -> %s" % (src, dst)) try: os....
[ "def", "link_or_copy", "(", "src", ",", "dst", ",", "verbosity", "=", "0", ")", ":", "if", "verbosity", ">", "0", ":", "log_info", "(", "\"Copying %s -> %s\"", "%", "(", "src", ",", "dst", ")", ")", "try", ":", "os", ".", "link", "(", "src", ",", ...
33.714286
0.002062
def read_config_multiline_options(obj: Any, parser: ConfigParser, section: str, options: Iterable[str]) -> None: """ This is to :func:`read_config_string_options` as :func:`get_config_multiline_option` is t...
[ "def", "read_config_multiline_options", "(", "obj", ":", "Any", ",", "parser", ":", "ConfigParser", ",", "section", ":", "str", ",", "options", ":", "Iterable", "[", "str", "]", ")", "->", "None", ":", "for", "o", "in", "options", ":", "setattr", "(", ...
44.9
0.002183
def all(self): """ Return own repositories.""" url = self.bitbucket.url('GET_USER', username=self.bitbucket.username) response = self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth) try: return (response[0], response[1]['repositories']) except TypeError: ...
[ "def", "all", "(", "self", ")", ":", "url", "=", "self", ".", "bitbucket", ".", "url", "(", "'GET_USER'", ",", "username", "=", "self", ".", "bitbucket", ".", "username", ")", "response", "=", "self", ".", "bitbucket", ".", "dispatch", "(", "'GET'", ...
38.666667
0.008427
def get_knowledge_base(project_id, knowledge_base_id): """Gets a specific Knowledge base. Args: project_id: The GCP project linked with the agent. knowledge_base_id: Id of the Knowledge base.""" import dialogflow_v2beta1 as dialogflow client = dialogflow.KnowledgeBasesClient() knowl...
[ "def", "get_knowledge_base", "(", "project_id", ",", "knowledge_base_id", ")", ":", "import", "dialogflow_v2beta1", "as", "dialogflow", "client", "=", "dialogflow", ".", "KnowledgeBasesClient", "(", ")", "knowledge_base_path", "=", "client", ".", "knowledge_base_path", ...
37.6875
0.001618
def root_and_children_to_graph(self,root): """Take a root node and its children and make them into graphs""" g = Graph() g.add_node(root) edges = [] edges += self.get_node_edges(root,"outgoing") for c in self.get_children(root): g.add_node(c) edges += self.get_node_ed...
[ "def", "root_and_children_to_graph", "(", "self", ",", "root", ")", ":", "g", "=", "Graph", "(", ")", "g", ".", "add_node", "(", "root", ")", "edges", "=", "[", "]", "edges", "+=", "self", ".", "get_node_edges", "(", "root", ",", "\"outgoing\"", ")", ...
34.181818
0.044041
def fail_connection(self, code: int = 1006, reason: str = "") -> None: """ 7.1.7. Fail the WebSocket Connection This requires: 1. Stopping all processing of incoming data, which means cancelling :attr:`transfer_data_task`. The close code will be 1006 unless a clos...
[ "def", "fail_connection", "(", "self", ",", "code", ":", "int", "=", "1006", ",", "reason", ":", "str", "=", "\"\"", ")", "->", "None", ":", "logger", ".", "debug", "(", "\"%s ! failing %s WebSocket connection with code %d\"", ",", "self", ".", "side", ",", ...
40.533333
0.001606
def remove_cte(part, as_string=False): """Interpret MIME-part according to it's Content-Transfer-Encodings. This returns the payload of `part` as string or bytestring for display, or to be passed to an external program. In the raw file the payload may be encoded, e.g. in base64, quoted-printable, 7bit,...
[ "def", "remove_cte", "(", "part", ",", "as_string", "=", "False", ")", ":", "enc", "=", "part", ".", "get_content_charset", "(", ")", "or", "'ascii'", "cte", "=", "str", "(", "part", ".", "get", "(", "'content-transfer-encoding'", ",", "'7bit'", ")", ")"...
41.402597
0.000306
def normalize(text, mode='NFKC', ignore=''): u"""Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana, Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII and DIGIT. Additionally, Full-width wave dash (〜) etc. are normalized Params: <unicode> text <u...
[ "def", "normalize", "(", "text", ",", "mode", "=", "'NFKC'", ",", "ignore", "=", "''", ")", ":", "text", "=", "text", ".", "replace", "(", "u'〜', ", "u", "ー').re", "p", "l", "ace(u'~", "'", ", u'ー'", ")", "", "", "text", "=", "text", ".", "replac...
37.625
0.001621
def serve(): """main entry point""" logging.getLogger().setLevel(logging.DEBUG) logging.info('Python Tornado Crossdock Server Starting ...') tracer = Tracer( service_name='python', reporter=NullReporter(), sampler=ConstSampler(decision=True)) opentracing.tracer = tracer ...
[ "def", "serve", "(", ")", ":", "logging", ".", "getLogger", "(", ")", ".", "setLevel", "(", "logging", ".", "DEBUG", ")", "logging", ".", "info", "(", "'Python Tornado Crossdock Server Starting ...'", ")", "tracer", "=", "Tracer", "(", "service_name", "=", "...
30.52381
0.001513
def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. Called when a field is added to the parent serializer instance. Taken from DRF and modified to support drf_haystack multiple index functionality. """ # In order ...
[ "def", "bind", "(", "self", ",", "field_name", ",", "parent", ")", ":", "# In order to enforce a consistent style, we error if a redundant", "# 'source' argument has been used. For example:", "# my_field = serializer.CharField(source='my_field')", "assert", "self", ".", "source", "...
42.428571
0.001317
def session_preparation(self): """ Prepare the session after the connection has been established. Procurve uses - 'Press any key to continue' """ delay_factor = self.select_delay_factor(delay_factor=0) output = "" count = 1 while count <= 30: o...
[ "def", "session_preparation", "(", "self", ")", ":", "delay_factor", "=", "self", ".", "select_delay_factor", "(", "delay_factor", "=", "0", ")", "output", "=", "\"\"", "count", "=", "1", "while", "count", "<=", "30", ":", "output", "+=", "self", ".", "r...
34.096774
0.00184
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: A predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry ...
[ "def", "add_to_manifest", "(", "self", ",", "manifest", ")", ":", "manifest", ".", "add_service", "(", "self", ".", "service", ".", "name", ")", "host", "=", "predix", ".", "config", ".", "get_env_key", "(", "self", ".", "use_class", ",", "'host'", ")", ...
39.333333
0.002364
def get_languages(self, target_language=None): """Get list of supported languages for translation. Response See https://cloud.google.com/translate/docs/discovering-supported-languages :type target_language: str :param target_language: (Optional) The language used to lo...
[ "def", "get_languages", "(", "self", ",", "target_language", "=", "None", ")", ":", "query_params", "=", "{", "}", "if", "target_language", "is", "None", ":", "target_language", "=", "self", ".", "target_language", "if", "target_language", "is", "not", "None",...
42.310345
0.001594
def qc_table_html(self, tests, alias=None): """ Makes a nice table out of ``qc_data()`` Returns: str. An HTML string. """ data = self.qc_data(tests, alias=alias) all_tests = [list(d.keys()) for d in data.values()] tests = list(set(utils.flatten_list(a...
[ "def", "qc_table_html", "(", "self", ",", "tests", ",", "alias", "=", "None", ")", ":", "data", "=", "self", ".", "qc_data", "(", "tests", ",", "alias", "=", "alias", ")", "all_tests", "=", "[", "list", "(", "d", ".", "keys", "(", ")", ")", "for"...
31.560976
0.002249
def get_term_and_background_counts(self): ''' Returns ------- A pd.DataFrame consisting of unigram term counts of words occurring in the TermDocumentMatrix and their corresponding background corpus counts. The dataframe has two columns, corpus and background. ...
[ "def", "get_term_and_background_counts", "(", "self", ")", ":", "background_df", "=", "self", ".", "_get_background_unigram_frequencies", "(", ")", "corpus_freq_df", "=", "self", ".", "get_term_count_df", "(", ")", "corpus_unigram_freq", "=", "self", ".", "_get_corpus...
41.952381
0.00222
def calc_filenames(self, is_correct: bool, actual_output: bool, threshold=0.5) -> list: """Find a list of files with the given classification""" return [ filename for output, target, filename in zip(self.outputs, self.targets, self.filenames) if ((output > threshold) ...
[ "def", "calc_filenames", "(", "self", ",", "is_correct", ":", "bool", ",", "actual_output", ":", "bool", ",", "threshold", "=", "0.5", ")", "->", "list", ":", "return", "[", "filename", "for", "output", ",", "target", ",", "filename", "in", "zip", "(", ...
57.142857
0.012315
def voicing(self, value): """ Set the voicing of the consonant. :param str value: the value to be set """ if (value is not None) and (not value in DG_C_VOICING): raise ValueError("Unrecognized value for voicing: '%s'" % value) self.__voicing = value
[ "def", "voicing", "(", "self", ",", "value", ")", ":", "if", "(", "value", "is", "not", "None", ")", "and", "(", "not", "value", "in", "DG_C_VOICING", ")", ":", "raise", "ValueError", "(", "\"Unrecognized value for voicing: '%s'\"", "%", "value", ")", "sel...
33.555556
0.009677
def _get_pidfile_path(self): """Return the normalized path for the pidfile, raising an exception if it can not written to. :return: str :raises: ValueError :raises: OSError """ if self.config.daemon.pidfile: pidfile = path.abspath(self.config.daemon....
[ "def", "_get_pidfile_path", "(", "self", ")", ":", "if", "self", ".", "config", ".", "daemon", ".", "pidfile", ":", "pidfile", "=", "path", ".", "abspath", "(", "self", ".", "config", ".", "daemon", ".", "pidfile", ")", "if", "not", "os", ".", "acces...
41.2
0.001898
def guess_base_branch(): # type: (str) -> Optional[str, None] """ Try to guess the base branch for the current branch. Do not trust this guess. git makes it pretty much impossible to guess the base branch reliably so this function implements few heuristics that will work on most common use cases bu...
[ "def", "guess_base_branch", "(", ")", ":", "# type: (str) -> Optional[str, None]", "my_branch", "=", "current_branch", "(", "refresh", "=", "True", ")", ".", "name", "curr", "=", "latest_commit", "(", ")", "if", "len", "(", "curr", ".", "branches", ")", ">", ...
33.092593
0.000543
def string_to_timestamp(value, second_digits=3, default_utc_offset=None, rounding_method=TimestampRoundingMethod.ceiling): """ Return the ISO 8601 date time that corresponds to the specified string representation. When the required precision is lower than microsecond, the functi...
[ "def", "string_to_timestamp", "(", "value", ",", "second_digits", "=", "3", ",", "default_utc_offset", "=", "None", ",", "rounding_method", "=", "TimestampRoundingMethod", ".", "ceiling", ")", ":", "if", "second_digits", "<", "0", "or", "second_digits", ">", "6"...
37.725
0.001937
def get_dtext(value): """ dtext = <printable ascii except \ [ ]> / obs-dtext obs-dtext = obs-NO-WS-CTL / quoted-pair We allow anything except the excluded characters, but if we find any ASCII other than the RFC defined printable ASCII an NonPrintableDefect is added to the token's defects list. ...
[ "def", "get_dtext", "(", "value", ")", ":", "ptext", ",", "value", ",", "had_qp", "=", "_get_ptext_to_endchars", "(", "value", ",", "'[]'", ")", "ptext", "=", "ValueTerminal", "(", "ptext", ",", "'ptext'", ")", "if", "had_qp", ":", "ptext", ".", "defects...
43.894737
0.002347
def __calculate_memory_order(self, pattern): """! @brief Calculates function of the memorized pattern without any pattern validation. @param[in] pattern (list): Pattern for recognition represented by list of features that are equal to [-1; 1]. @return (double) Order of ...
[ "def", "__calculate_memory_order", "(", "self", ",", "pattern", ")", ":", "memory_order", "=", "0.0", "for", "index", "in", "range", "(", "len", "(", "self", ")", ")", ":", "memory_order", "+=", "pattern", "[", "index", "]", "*", "cmath", ".", "exp", "...
37.8125
0.025806
def timesince(dt, default='just now'): ''' Returns string representing 'time since' e.g. 3 days ago, 5 hours ago etc. >>> now = datetime.datetime.now() >>> timesince(now) 'just now' >>> timesince(now - datetime.timedelta(seconds=1)) '1 second ago' >>> timesince(now - datetime.timede...
[ "def", "timesince", "(", "dt", ",", "default", "=", "'just now'", ")", ":", "if", "isinstance", "(", "dt", ",", "datetime", ".", "timedelta", ")", ":", "diff", "=", "dt", "else", ":", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "...
34.169014
0.000401
def _conditions(self, full_path, environ): """Return a tuple of etag, last_modified by mtime from stat.""" mtime = stat(full_path).st_mtime return str(mtime), rfc822.formatdate(mtime)
[ "def", "_conditions", "(", "self", ",", "full_path", ",", "environ", ")", ":", "mtime", "=", "stat", "(", "full_path", ")", ".", "st_mtime", "return", "str", "(", "mtime", ")", ",", "rfc822", ".", "formatdate", "(", "mtime", ")" ]
51
0.009662
def list_attached_team(context, id, sort, limit, where, verbose): """list_attached_team(context, id, sort, limit. where. verbose) List teams attached to a topic. >>> dcictl topic-list-team :param string id: ID of the topic to list teams for [required] :param string sort: Field to apply sort :...
[ "def", "list_attached_team", "(", "context", ",", "id", ",", "sort", ",", "limit", ",", "where", ",", "verbose", ")", ":", "result", "=", "topic", ".", "list_teams", "(", "context", ",", "id", "=", "id", ",", "sort", "=", "sort", ",", "limit", "=", ...
40.25
0.001517
def iter_cookie_browse_sorting(cookies): ''' Get sorting-cookie from cookies dictionary. :yields: tuple of path and sorting property :ytype: 2-tuple of strings ''' try: data = cookies.get('browse-sorting', 'e30=').encode('ascii') for path, prop in json.loads(base64.b64decode(dat...
[ "def", "iter_cookie_browse_sorting", "(", "cookies", ")", ":", "try", ":", "data", "=", "cookies", ".", "get", "(", "'browse-sorting'", ",", "'e30='", ")", ".", "encode", "(", "'ascii'", ")", "for", "path", ",", "prop", "in", "json", ".", "loads", "(", ...
33.538462
0.002232
def get_owned_destinations(self, server_id): """ Return the listener destinations in a WBEM server owned by this subscription manager. This function accesses only the local list of owned destinations; it does not contact the WBEM server. The local list of owned destinations ...
[ "def", "get_owned_destinations", "(", "self", ",", "server_id", ")", ":", "# Validate server_id", "self", ".", "_get_server", "(", "server_id", ")", "return", "list", "(", "self", ".", "_owned_destinations", "[", "server_id", "]", ")" ]
34.814815
0.00207
def cost(self, node): """ The cost of a eliminating a node is the product of weights, domain cardinality, of its neighbors. """ return np.prod([self.bayesian_model.get_cardinality(neig_node) for neig_node in self.moralized_model.neighbors(node)])
[ "def", "cost", "(", "self", ",", "node", ")", ":", "return", "np", ".", "prod", "(", "[", "self", ".", "bayesian_model", ".", "get_cardinality", "(", "neig_node", ")", "for", "neig_node", "in", "self", ".", "moralized_model", ".", "neighbors", "(", "node...
43.428571
0.012903
def create_fake_mirror(src, dst): """Copy all dir, files from ``src`` to ``dst``. But only create a empty file with same file name. Of course, the tree structure doesn't change. A recipe gadget to create some test data set. Make sure to use absolute path. ...
[ "def", "create_fake_mirror", "(", "src", ",", "dst", ")", ":", "src", "=", "os", ".", "path", ".", "abspath", "(", "src", ")", "if", "not", "(", "os", ".", "path", ".", "exists", "(", "src", ")", "and", "(", "not", "os", ".", "path", ".", "exis...
36.375
0.011715
def create(self, prog=None, format='ps', encoding=None): """Creates and returns a binary image for the graph. create will write the graph to a temporary dot file in the encoding specified by `encoding` and process it with the program given by 'prog' (which defaults to 'twopi'), reading ...
[ "def", "create", "(", "self", ",", "prog", "=", "None", ",", "format", "=", "'ps'", ",", "encoding", "=", "None", ")", ":", "if", "prog", "is", "None", ":", "prog", "=", "self", ".", "prog", "assert", "prog", "is", "not", "None", "if", "isinstance"...
30
0.000512
def show_variables_window(self): """ Show the variables window. """ if self.var_window is None and self.bot._vars: self.var_window = VarWindow(self, self.bot, '%s variables' % (self.title or 'Shoebot')) self.var_window.window.connect("destroy", self.var_window_clo...
[ "def", "show_variables_window", "(", "self", ")", ":", "if", "self", ".", "var_window", "is", "None", "and", "self", ".", "bot", ".", "_vars", ":", "self", ".", "var_window", "=", "VarWindow", "(", "self", ",", "self", ".", "bot", ",", "'%s variables'", ...
45.428571
0.009259
def _load_calib(self): """Load and compute intrinsic and extrinsic calibration parameters.""" # We'll build the calibration parameters as a dictionary, then # convert it to a namedtuple to prevent it from being modified later data = {} # Load the rigid transformation from IMU to...
[ "def", "_load_calib", "(", "self", ")", ":", "# We'll build the calibration parameters as a dictionary, then", "# convert it to a namedtuple to prevent it from being modified later", "data", "=", "{", "}", "# Load the rigid transformation from IMU to velodyne", "data", "[", "'T_velo_im...
49.55
0.00198
def get_own_ip(): """ Gets the IP from the inet interfaces. """ own_ip = None interfaces = psutil.net_if_addrs() for _, details in interfaces.items(): for detail in details: if detail.family == socket.AF_INET: ip_address = ipaddress.ip_address(detail.addre...
[ "def", "get_own_ip", "(", ")", ":", "own_ip", "=", "None", "interfaces", "=", "psutil", ".", "net_if_addrs", "(", ")", "for", "_", ",", "details", "in", "interfaces", ".", "items", "(", ")", ":", "for", "detail", "in", "details", ":", "if", "detail", ...
34
0.002045
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if m.get_type() == "ADSB_VEHICLE": id = 'ADSB-' + str(m.ICAO_address) if id not in self.threat_vehicles.keys(): # check to see if the vehicle is in the dict # if not then add it ...
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "if", "m", ".", "get_type", "(", ")", "==", "\"ADSB_VEHICLE\"", ":", "id", "=", "'ADSB-'", "+", "str", "(", "m", ".", "ICAO_address", ")", "if", "id", "not", "in", "self", ".", "threat_vehicle...
65.804878
0.0084
def parse_args(arguments, wrapper_kwargs={}): """ MMI Runner """ # make a socket that replies to message with the grid # if we are running mpi we want to know the rank args = {} positional = [ 'engine', 'configfile', ] for key in positional: args[key] = argum...
[ "def", "parse_args", "(", "arguments", ",", "wrapper_kwargs", "=", "{", "}", ")", ":", "# make a socket that replies to message with the grid", "# if we are running mpi we want to know the rank", "args", "=", "{", "}", "positional", "=", "[", "'engine'", ",", "'configfile...
26.482759
0.001256
def get_developer_certificate(self, developer_certificate_id, authorization, **kwargs): # noqa: E501 """Fetch an existing developer certificate to connect to the bootstrap server. # noqa: E501 This REST API is intended to be used by customers to fetch an existing developer certificate (a certificate ...
[ "def", "get_developer_certificate", "(", "self", ",", "developer_certificate_id", ",", "authorization", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'...
74.090909
0.001211
def aligned_indel_filter(clust, max_internal_indels): """ checks for too many internal indels in muscle aligned clusters """ ## make into list lclust = clust.split() ## paired or not try: seq1 = [i.split("nnnn")[0] for i in lclust[1::2]] seq2 = [i.split("nnnn")[1] for i in lclu...
[ "def", "aligned_indel_filter", "(", "clust", ",", "max_internal_indels", ")", ":", "## make into list", "lclust", "=", "clust", ".", "split", "(", ")", "## paired or not", "try", ":", "seq1", "=", "[", "i", ".", "split", "(", "\"nnnn\"", ")", "[", "0", "]"...
34.347826
0.008621
def to_dict(self): """ Returns a dictionary that represents this object, to be used for JSONification. :return: the object dictionary :rtype: dict """ result = super(OptionHandler, self).to_dict() result["type"] = "OptionHandler" result["options"] = join_...
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "super", "(", "OptionHandler", ",", "self", ")", ".", "to_dict", "(", ")", "result", "[", "\"type\"", "]", "=", "\"OptionHandler\"", "result", "[", "\"options\"", "]", "=", "join_options", "(", "sel...
32.090909
0.008264
def random_regions(base, n, size): """Generate n random regions of 'size' in the provided base spread. """ spread = size // 2 base_info = collections.defaultdict(list) for space, start, end in base: base_info[space].append(start + spread) base_info[space].append(end - spread) reg...
[ "def", "random_regions", "(", "base", ",", "n", ",", "size", ")", ":", "spread", "=", "size", "//", "2", "base_info", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "space", ",", "start", ",", "end", "in", "base", ":", "base_info", ...
38.357143
0.001818
def _openssl_key_iv(passphrase, salt): """ Returns a (key, iv) tuple that can be used in AES symmetric encryption from a *passphrase* (a byte or unicode string) and *salt* (a byte array). """ def _openssl_kdf(req): if hasattr(passphrase, 'encode'): passwd = passphrase.encode('asc...
[ "def", "_openssl_key_iv", "(", "passphrase", ",", "salt", ")", ":", "def", "_openssl_kdf", "(", "req", ")", ":", "if", "hasattr", "(", "passphrase", ",", "'encode'", ")", ":", "passwd", "=", "passphrase", ".", "encode", "(", "'ascii'", ",", "'ignore'", "...
37.772727
0.001174