text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_mean(self, col, row, mean): """ Sets the mean at this location (if valid location). :param col: the 0-based column index :type col: int :param row: the 0-based row index :type row: int :param mean: the mean to set :type mean: float """ ...
[ "def", "set_mean", "(", "self", ",", "col", ",", "row", ",", "mean", ")", ":", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"setMean\"", ",", "\"(IID)V\"", ",", "col", ",", "row", ",", "mean", ")" ]
31.666667
0.005115
def update_show_function(self, show_name, show_func): """ Modifies/overwrites an existing show function in the locally cached DesignDocument shows dictionary. :param show_name: Name used to identify the show function. :param show_func: Javascript show function. """ ...
[ "def", "update_show_function", "(", "self", ",", "show_name", ",", "show_func", ")", ":", "if", "self", ".", "get_show_function", "(", "show_name", ")", "is", "None", ":", "raise", "CloudantArgumentError", "(", "114", ",", "show_name", ")", "self", ".", "sho...
38.916667
0.004184
def securitycli(): """ Entry point for the runner defined in setup.py. """ parser = argparse.ArgumentParser(description="Runner for security test suite") parser.add_argument("-l", "--list-test-groups", action="store_true", help="List all logical test groups") parser.add_...
[ "def", "securitycli", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Runner for security test suite\"", ")", "parser", ".", "add_argument", "(", "\"-l\"", ",", "\"--list-test-groups\"", ",", "action", "=", "\"store_true\...
43.539683
0.002139
def send_with_template(message, api_key=None, secure=None, test=None, **request_args): '''Send a message. :param message: Message to send. :type message: `dict` or :class:`Message` :param api_key: Your Postmark ...
[ "def", "send_with_template", "(", "message", ",", "api_key", "=", "None", ",", "secure", "=", "None", ",", "test", "=", "None", ",", "*", "*", "request_args", ")", ":", "return", "_default_pyst_template_sender", ".", "send", "(", "message", "=", "message", ...
42.545455
0.003135
def mac(self, algorithm, key, data): """ Generate message authentication code. Args: algorithm(CryptographicAlgorithm): An enumeration specifying the algorithm for which the MAC operation will use. key(bytes): secret key used in the MAC operation ...
[ "def", "mac", "(", "self", ",", "algorithm", ",", "key", ",", "data", ")", ":", "mac_data", "=", "None", "if", "algorithm", "in", "self", ".", "_hash_algorithms", ".", "keys", "(", ")", ":", "self", ".", "logger", ".", "info", "(", "\"Generating a hash...
39.283582
0.000741
def adam7_generate(width, height): """ Generate the coordinates for the reduced scanlines of an Adam7 interlaced image of size `width` by `height` pixels. Yields a generator for each pass, and each pass generator yields a series of (x, y, xstep) triples, each one identifying a reduced scanl...
[ "def", "adam7_generate", "(", "width", ",", "height", ")", ":", "for", "xstart", ",", "ystart", ",", "xstep", ",", "ystep", "in", "adam7", ":", "if", "xstart", ">=", "width", ":", "continue", "yield", "(", "(", "xstart", ",", "y", ",", "xstep", ")", ...
35.8125
0.001701
def apply_network_settings(**settings): ''' Apply global network configuration. CLI Example: .. code-block:: bash salt '*' ip.apply_network_settings ''' if __grains__['lsb_distrib_id'] == 'nilrt': raise salt.exceptions.CommandExecutionError('Not supported in this version.') ...
[ "def", "apply_network_settings", "(", "*", "*", "settings", ")", ":", "if", "__grains__", "[", "'lsb_distrib_id'", "]", "==", "'nilrt'", ":", "raise", "salt", ".", "exceptions", ".", "CommandExecutionError", "(", "'Not supported in this version.'", ")", "if", "'re...
30.190476
0.002292
def to_find(self): ''' Todo: the name should be changed. list the infors. ''' kwd = {'pager': ''} self.render('user/info_list/most.html', topmenu='', userinfo=self.userinfo, kwd=kwd)
[ "def", "to_find", "(", "self", ")", ":", "kwd", "=", "{", "'pager'", ":", "''", "}", "self", ".", "render", "(", "'user/info_list/most.html'", ",", "topmenu", "=", "''", ",", "userinfo", "=", "self", ".", "userinfo", ",", "kwd", "=", "kwd", ")" ]
28.1
0.006897
def associate(self, eip_or_aid, instance_id='', network_interface_id='', private_ip=''): """Associate an EIP with a given instance or network interface. If the EIP was allocated for a VPC instance, an AllocationId(aid) must be provided instead of a PublicIp. """ ...
[ "def", "associate", "(", "self", ",", "eip_or_aid", ",", "instance_id", "=", "''", ",", "network_interface_id", "=", "''", ",", "private_ip", "=", "''", ")", ":", "if", "\".\"", "in", "eip_or_aid", ":", "# If an IP is given (Classic)", "return", "self", ".", ...
55.777778
0.002938
def popone(self, key, *default): """Remove first of given key and return corresponding value. If key is not found, default is returned if given. >>> m = MutableMultiMap([('a', 1), ('b', 2), ('b', 3), ('c', 4)]) >>> m.popone('b') 2 >>> m.items() [...
[ "def", "popone", "(", "self", ",", "key", ",", "*", "default", ")", ":", "try", ":", "value", "=", "self", "[", "key", "]", "except", "KeyError", ":", "if", "default", ":", "return", "default", "[", "0", "]", "raise", "# Delete this one.", "self", "....
26.419355
0.008245
def to_string(type): """ Converts a TypeCode into its string name. :param type: the TypeCode to convert into a string. :return: the name of the TypeCode passed as a string value. """ if type == None: return "unknown" elif type == TypeCode.Unknown: ...
[ "def", "to_string", "(", "type", ")", ":", "if", "type", "==", "None", ":", "return", "\"unknown\"", "elif", "type", "==", "TypeCode", ".", "Unknown", ":", "return", "\"unknown\"", "elif", "type", "==", "TypeCode", ".", "String", ":", "return", "\"string\"...
29.777778
0.00271
def applymap(self, func, subset=None, **kwargs): """ Apply a function elementwise, updating the HTML representation with the result. Parameters ---------- func : function ``func`` should take a scalar and return a scalar subset : IndexSlice ...
[ "def", "applymap", "(", "self", ",", "func", ",", "subset", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_todo", ".", "append", "(", "(", "lambda", "instance", ":", "getattr", "(", "instance", ",", "'_applymap'", ")", ",", "(", "fu...
28.461538
0.002614
def add_get(self, path, controller, template, raw=False): """ Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON respon...
[ "def", "add_get", "(", "self", ",", "path", ",", "controller", ",", "template", ",", "raw", "=", "False", ")", ":", "if", "raw", ":", "fn", "=", "controller", "else", ":", "fn", "=", "self", ".", "_prepare_controller", "(", "controller", ",", "template...
35.6875
0.006826
def save_data(self, *, data_filter=None, redownload=False, max_threads=None, raise_download_errors=False): """ Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers. :param data_filter: Used to specify which items will be returned by the method a...
[ "def", "save_data", "(", "self", ",", "*", ",", "data_filter", "=", "None", ",", "redownload", "=", "False", ",", "max_threads", "=", "None", ",", "raise_download_errors", "=", "False", ")", ":", "self", ".", "_preprocess_request", "(", "True", ",", "False...
67.944444
0.008871
def get_paginated_response(data, request): """ Update pagination links in course catalog data and return DRF Response. Arguments: data (dict): Dictionary containing catalog courses. request (HttpRequest): Current request object. Returns: (Response): DRF response object containi...
[ "def", "get_paginated_response", "(", "data", ",", "request", ")", ":", "url", "=", "urlparse", "(", "request", ".", "build_absolute_uri", "(", ")", ")", ".", "_replace", "(", "query", "=", "None", ")", ".", "geturl", "(", ")", "next_page", "=", "None", ...
30.942857
0.000895
def get_sdb_secret_version_paths(self, sdb_id): """ Get SDB secret version paths. This function takes the sdb_id """ sdb_resp = get_with_retry(str.join('', [self.cerberus_url, '/v1/sdb-secret-version-paths/', sdb_id]), headers=self.HEADERS) throw_if_bad_response...
[ "def", "get_sdb_secret_version_paths", "(", "self", ",", "sdb_id", ")", ":", "sdb_resp", "=", "get_with_retry", "(", "str", ".", "join", "(", "''", ",", "[", "self", ".", "cerberus_url", ",", "'/v1/sdb-secret-version-paths/'", ",", "sdb_id", "]", ")", ",", "...
44.375
0.01105
def js(request): """Returns the javascript needed to run persona""" userid = authenticated_userid(request) user = markupsafe.Markup("'%s'")%userid if userid else "null" redirect_paramater = request.registry['persona.redirect_url_parameter'] came_from = '%s%s' % (request.host_url, ...
[ "def", "js", "(", "request", ")", ":", "userid", "=", "authenticated_userid", "(", "request", ")", "user", "=", "markupsafe", ".", "Markup", "(", "\"'%s'\"", ")", "%", "userid", "if", "userid", "else", "\"null\"", "redirect_paramater", "=", "request", ".", ...
51.941176
0.004449
def sanitize_command_options(options): """ Sanitizes command options. """ multiples = [ 'badges', 'exclude_badges', ] for option in multiples: if options.get(option): value = options[option] if value: options[option] = [v for v in ...
[ "def", "sanitize_command_options", "(", "options", ")", ":", "multiples", "=", "[", "'badges'", ",", "'exclude_badges'", ",", "]", "for", "option", "in", "multiples", ":", "if", "options", ".", "get", "(", "option", ")", ":", "value", "=", "options", "[", ...
21.6875
0.002762
def _child_list(element, child_tagname): """ Return list containing the direct children of *element* having *child_tagname*. """ xpath = './%s' % child_tagname return element.xpath(xpath, namespaces=nsmap)
[ "def", "_child_list", "(", "element", ",", "child_tagname", ")", ":", "xpath", "=", "'./%s'", "%", "child_tagname", "return", "element", ".", "xpath", "(", "xpath", ",", "namespaces", "=", "nsmap", ")" ]
31.857143
0.004367
def transform(self, trans): """ Compute a transformation in place using a 4x4 transform. Parameters ---------- trans : vtk.vtkMatrix4x4, vtk.vtkTransform, or np.ndarray Accepts a vtk transformation object or a 4x4 transformation matrix. """ if isinst...
[ "def", "transform", "(", "self", ",", "trans", ")", ":", "if", "isinstance", "(", "trans", ",", "vtk", ".", "vtkMatrix4x4", ")", ":", "t", "=", "vtki", ".", "trans_from_matrix", "(", "trans", ")", "elif", "isinstance", "(", "trans", ",", "vtk", ".", ...
36.875
0.001652
def average(arr): """average of the values, must have more than 0 entries. :param arr: list of numbers :type arr: number[] a number array :return: average :rtype: float """ if len(arr) == 0: sys.stderr.write("ERROR: no content in array to take average\n") sys.exit() if len(arr) == 1: return a...
[ "def", "average", "(", "arr", ")", ":", "if", "len", "(", "arr", ")", "==", "0", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: no content in array to take average\\n\"", ")", "sys", ".", "exit", "(", ")", "if", "len", "(", "arr", ")", "==", ...
25.214286
0.019126
def TYPEDEF(self, _cursor_type): """ Handles TYPEDEF statement. """ _decl = _cursor_type.get_declaration() name = self.get_unique_name(_decl) if self.is_registered(name): obj = self.get_registered(name) else: log.debug('Was in TYPEDEF but h...
[ "def", "TYPEDEF", "(", "self", ",", "_cursor_type", ")", ":", "_decl", "=", "_cursor_type", ".", "get_declaration", "(", ")", "name", "=", "self", ".", "get_unique_name", "(", "_decl", ")", "if", "self", ".", "is_registered", "(", "name", ")", ":", "obj"...
34.666667
0.007026
def download_attachments(self): """ Downloads this message attachments into memory. Need a call to 'attachment.save' to save them on disk. :return: Success / Failure :rtype: bool """ if not self._parent.has_attachments: log.debug( 'Parent {} h...
[ "def", "download_attachments", "(", "self", ")", ":", "if", "not", "self", ".", "_parent", ".", "has_attachments", ":", "log", ".", "debug", "(", "'Parent {} has no attachments, skipping out early.'", ".", "format", "(", "self", ".", "_parent", ".", "__class__", ...
35.621622
0.001477
def _bfill(arr, n=None, axis=-1): '''inverse of ffill''' import bottleneck as bn arr = np.flip(arr, axis=axis) # fill arr = bn.push(arr, axis=axis, n=n) # reverse back to original return np.flip(arr, axis=axis)
[ "def", "_bfill", "(", "arr", ",", "n", "=", "None", ",", "axis", "=", "-", "1", ")", ":", "import", "bottleneck", "as", "bn", "arr", "=", "np", ".", "flip", "(", "arr", ",", "axis", "=", "axis", ")", "# fill", "arr", "=", "bn", ".", "push", "...
21
0.004149
def is_ternary(self, keyword): """return true if the given keyword is a ternary keyword for this ControlLine""" return keyword in { 'if':set(['else', 'elif']), 'try':set(['except', 'finally']), 'for':set(['else']) }.get(self.keyword, [])
[ "def", "is_ternary", "(", "self", ",", "keyword", ")", ":", "return", "keyword", "in", "{", "'if'", ":", "set", "(", "[", "'else'", ",", "'elif'", "]", ")", ",", "'try'", ":", "set", "(", "[", "'except'", ",", "'finally'", "]", ")", ",", "'for'", ...
33.111111
0.01634
def compress(self, setup): """ Returns the compressed graph according to the given experimental setup Parameters ---------- setup : :class:`caspo.core.setup.Setup` Experimental setup used to compress the graph Returns ------- caspo.core.graph...
[ "def", "compress", "(", "self", ",", "setup", ")", ":", "designated", "=", "set", "(", "setup", ".", "nodes", ")", "zipped", "=", "self", ".", "copy", "(", ")", "marked", "=", "[", "(", "n", ",", "d", ")", "for", "n", ",", "d", "in", "self", ...
37.305556
0.00508
def disable(self, msgid, scope="package", line=None, ignore_unknown=False): """don't output message of the given id""" self._set_msg_status( msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown ) self._register_by_id_managed_msg(msgid, line)
[ "def", "disable", "(", "self", ",", "msgid", ",", "scope", "=", "\"package\"", ",", "line", "=", "None", ",", "ignore_unknown", "=", "False", ")", ":", "self", ".", "_set_msg_status", "(", "msgid", ",", "enable", "=", "False", ",", "scope", "=", "scope...
50.333333
0.009772
def get_groups_from_category(self, category) -> typing.Iterator['Group']: """ Args: category: group category Returns: generator over all groups from a specific category in this coalition """ Mission.validator_group_category.validate(category, 'get_groups_from_categor...
[ "def", "get_groups_from_category", "(", "self", ",", "category", ")", "->", "typing", ".", "Iterator", "[", "'Group'", "]", ":", "Mission", ".", "validator_group_category", ".", "validate", "(", "category", ",", "'get_groups_from_category'", ")", "for", "group", ...
35.333333
0.009195
def in_nested_list(nested_list, obj): """return true if the object is an element of <nested_list> or of a nested list """ for elmt in nested_list: if isinstance(elmt, (list, tuple)): if in_nested_list(elmt, obj): return True elif elmt == obj: retur...
[ "def", "in_nested_list", "(", "nested_list", ",", "obj", ")", ":", "for", "elmt", "in", "nested_list", ":", "if", "isinstance", "(", "elmt", ",", "(", "list", ",", "tuple", ")", ")", ":", "if", "in_nested_list", "(", "elmt", ",", "obj", ")", ":", "re...
30.272727
0.002915
def ack(self, msg): """Processes the received message. I don't need to generate an ack message. """ self.log.info("senderID:%s Received: %s " % (self.senderID, msg['body'])) return stomper.NO_REPONSE_NEEDED
[ "def", "ack", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "info", "(", "\"senderID:%s Received: %s \"", "%", "(", "self", ".", "senderID", ",", "msg", "[", "'body'", "]", ")", ")", "return", "stomper", ".", "NO_REPONSE_NEEDED" ]
35.714286
0.019531
def t_IDENTIFIER(t): r"[A-Z_a-z][0-9A-Z_a-z]*" if t.value in keywords: t.type = t.value return t
[ "def", "t_IDENTIFIER", "(", "t", ")", ":", "if", "t", ".", "value", "in", "keywords", ":", "t", ".", "type", "=", "t", ".", "value", "return", "t" ]
20.4
0.037736
def passthrough_proc(self, inputstring, **kwargs): """Process python passthroughs.""" out = [] found = None # store of characters that might be the start of a passthrough hold = None # the contents of the passthrough so far count = None # current parenthetical level (num close...
[ "def", "passthrough_proc", "(", "self", ",", "inputstring", ",", "*", "*", "kwargs", ")", ":", "out", "=", "[", "]", "found", "=", "None", "# store of characters that might be the start of a passthrough", "hold", "=", "None", "# the contents of the passthrough so far", ...
38.638298
0.003222
def converge(self, playbook=None, **kwargs): """ Executes ``ansible-playbook`` against the converge playbook unless specified otherwise and returns a string. :param playbook: An optional string containing an absolute path to a playbook. :param kwargs: An optional keywor...
[ "def", "converge", "(", "self", ",", "playbook", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "playbook", "is", "None", ":", "pb", "=", "self", ".", "_get_ansible_playbook", "(", "self", ".", "playbooks", ".", "converge", ",", "*", "*", "kwa...
35.3125
0.003448
def add_options(parser): """ Add optional arguments to the parser """ partial_action = common.partial_append_action file_mods = parser.add_argument_group("Sequence File Modification") file_mods.add_argument('--line-wrap', dest='line_wrap', metavar='N', type=int, help='Adjust line wrap fo...
[ "def", "add_options", "(", "parser", ")", ":", "partial_action", "=", "common", ".", "partial_append_action", "file_mods", "=", "parser", ".", "add_argument_group", "(", "\"Sequence File Modification\"", ")", "file_mods", ".", "add_argument", "(", "'--line-wrap'", ","...
60.8
0.008133
def download_supplementary_files(self, directory='series', download_sra=True, email=None, sra_kwargs=None, nproc=1): """Download supplementary data. .. warning:: Do not use parallel option (nproc > 1) in the interact...
[ "def", "download_supplementary_files", "(", "self", ",", "directory", "=", "'series'", ",", "download_sra", "=", "True", ",", "email", "=", "None", ",", "sra_kwargs", "=", "None", ",", "nproc", "=", "1", ")", ":", "if", "sra_kwargs", "is", "None", ":", "...
44.772727
0.001987
def x509_rsa_load(txt): """ So I get the same output format as loads produces :param txt: :return: """ pub_key = import_rsa_key(txt) if isinstance(pub_key, rsa.RSAPublicKey): return [("rsa", pub_key)]
[ "def", "x509_rsa_load", "(", "txt", ")", ":", "pub_key", "=", "import_rsa_key", "(", "txt", ")", "if", "isinstance", "(", "pub_key", ",", "rsa", ".", "RSAPublicKey", ")", ":", "return", "[", "(", "\"rsa\"", ",", "pub_key", ")", "]" ]
28.125
0.00431
def add_feature_values(self, features): """ Adds feature values of feature 'feature' to all fixations in the calling fixmat. For fixations out of the image boundaries, NaNs are returned. The function generates a new attribute field named with the string in featu...
[ "def", "add_feature_values", "(", "self", ",", "features", ")", ":", "if", "not", "'x'", "in", "self", ".", "fieldnames", "(", ")", ":", "raise", "RuntimeError", "(", "\"\"\"add_feature_values expects to find\n (x,y) locations in self.x and self.y. But self.x does no...
47.047619
0.008924
def _find_pair(self, protocol, remote_candidate): """ Find a candidate pair in the check list. """ for pair in self._check_list: if (pair.protocol == protocol and pair.remote_candidate == remote_candidate): return pair return None
[ "def", "_find_pair", "(", "self", ",", "protocol", ",", "remote_candidate", ")", ":", "for", "pair", "in", "self", ".", "_check_list", ":", "if", "(", "pair", ".", "protocol", "==", "protocol", "and", "pair", ".", "remote_candidate", "==", "remote_candidate"...
36.375
0.010067
def named_config(self, func): """ Decorator to turn a function into a named configuration. See :ref:`named_configurations`. """ config_scope = ConfigScope(func) self._add_named_config(func.__name__, config_scope) return config_scope
[ "def", "named_config", "(", "self", ",", "func", ")", ":", "config_scope", "=", "ConfigScope", "(", "func", ")", "self", ".", "_add_named_config", "(", "func", ".", "__name__", ",", "config_scope", ")", "return", "config_scope" ]
31.222222
0.00692
def get_membership_cache(self, group_ids=None, is_active=True): """ Build a dict cache with the group membership info. Keyed off the group id and the values are a 2 element list of entity id and entity kind id (same values as the membership model). If no group ids are passed, then all gr...
[ "def", "get_membership_cache", "(", "self", ",", "group_ids", "=", "None", ",", "is_active", "=", "True", ")", ":", "membership_queryset", "=", "EntityGroupMembership", ".", "objects", ".", "filter", "(", "Q", "(", "entity__isnull", "=", "True", ")", "|", "(...
48.925926
0.007424
def demonstrate_colored_logging(): """Interactively demonstrate the :mod:`coloredlogs` package.""" # Determine the available logging levels and order them by numeric value. decorated_levels = [] defined_levels = coloredlogs.find_defined_levels() normalizer = coloredlogs.NameNormalizer() for name...
[ "def", "demonstrate_colored_logging", "(", ")", ":", "# Determine the available logging levels and order them by numeric value.", "decorated_levels", "=", "[", "]", "defined_levels", "=", "coloredlogs", ".", "find_defined_levels", "(", ")", "normalizer", "=", "coloredlogs", "...
50.142857
0.001864
def _filter_dicts(self): '''Filters out all the report_dicts that do not pass the cutoffs. If any ref sequence loses all of its report_dicts, then it is completely removed.''' keys_to_remove = set() for ref_name in self.report: for ctg_name in self.report[ref_name]: ...
[ "def", "_filter_dicts", "(", "self", ")", ":", "keys_to_remove", "=", "set", "(", ")", "for", "ref_name", "in", "self", ".", "report", ":", "for", "ctg_name", "in", "self", ".", "report", "[", "ref_name", "]", ":", "self", ".", "report", "[", "ref_name...
41.55
0.004706
def segment_radii(neurites, neurite_type=NeuriteType.all): '''arithmetic mean of the radii of the points in segments in a collection of neurites''' def _seg_radii(sec): '''vectorized mean radii''' pts = sec.points[:, COLS.R] return np.divide(np.add(pts[:-1], pts[1:]), 2.0) return ma...
[ "def", "segment_radii", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_radii", "(", "sec", ")", ":", "'''vectorized mean radii'''", "pts", "=", "sec", ".", "points", "[", ":", ",", "COLS", ".", "R", "]", "ret...
44.875
0.005464
def load_cache(): """ Load cache from the disk. Return: set: Deserialized data from disk. """ if not os.path.exists(settings.DUP_FILTER_FILE): return set() with open(settings.DUP_FILTER_FILE) as f: return set( json.loads(f.read()) )
[ "def", "load_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "settings", ".", "DUP_FILTER_FILE", ")", ":", "return", "set", "(", ")", "with", "open", "(", "settings", ".", "DUP_FILTER_FILE", ")", "as", "f", ":", "return", "...
20.642857
0.003311
def _clean_xml(self, path_to_xml): """Clean MARCXML harvested from OAI. Allows the xml to be used with BibUpload or BibRecord. :param xml: either XML as a string or path to an XML file :return: ElementTree of clean data """ try: if os.path.isfile(path_to_xm...
[ "def", "_clean_xml", "(", "self", ",", "path_to_xml", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "path_to_xml", ")", ":", "tree", "=", "ET", ".", "parse", "(", "path_to_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")...
31.6
0.003072
def create_enum_option(self, custom_field, params={}, **options): """Creates an enum option and adds it to this custom field's list of enum options. A custom field can have at most 50 enum options (including disabled options). By default new enum options are inserted at the end of a custom field's list. ...
[ "def", "create_enum_option", "(", "self", ",", "custom_field", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/custom_fields/%s/enum_options\"", "%", "(", "custom_field", ")", "return", "self", ".", "client", ".", "post", ...
74.0625
0.006667
def dmol_neg_log_perplexity(predictions, labels, weights_fn=None): """Average log-perplexity excluding padding 0s. No smoothing.""" del weights_fn # Unused num, den = common_layers.dml_loss( predictions, labels, reduce_sum=False) return (-num, den)
[ "def", "dmol_neg_log_perplexity", "(", "predictions", ",", "labels", ",", "weights_fn", "=", "None", ")", ":", "del", "weights_fn", "# Unused", "num", ",", "den", "=", "common_layers", ".", "dml_loss", "(", "predictions", ",", "labels", ",", "reduce_sum", "=",...
39
0.015674
def listDatasetArray(self): """ API to list datasets in DBS. To be called by datasetlist url with post call. :param dataset: list of datasets [dataset1,dataset2,..,dataset n] (must have either a list of dataset or dataset_id), Max length 1000. :type dataset: list :param dataset_id: lis...
[ "def", "listDatasetArray", "(", "self", ")", ":", "ret", "=", "[", "]", "try", ":", "body", "=", "request", ".", "body", ".", "read", "(", ")", "if", "body", ":", "data", "=", "cjson", ".", "decode", "(", "body", ")", "data", "=", "validateJSONInpu...
65.27907
0.010179
def validate_crc(msg): """ Validate CRC of message. :param msg: Byte array with message with CRC. :raise: CRCError. """ if not struct.unpack('<H', get_crc(msg[:-2])) ==\ struct.unpack('<H', msg[-2:]): raise CRCError('CRC validation failed.')
[ "def", "validate_crc", "(", "msg", ")", ":", "if", "not", "struct", ".", "unpack", "(", "'<H'", ",", "get_crc", "(", "msg", "[", ":", "-", "2", "]", ")", ")", "==", "struct", ".", "unpack", "(", "'<H'", ",", "msg", "[", "-", "2", ":", "]", ")...
30.444444
0.003546
def generate_colours(n): """Return a list of `n` distinct colours, each represented as an RGB string suitable for use in CSS. Based on the code at http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/ :param n: number of colours to generate :type n: `int` :rtype...
[ "def", "generate_colours", "(", "n", ")", ":", "colours", "=", "[", "]", "golden_ratio_conjugate", "=", "0.618033988749895", "h", "=", "0.8", "# Initial hue", "s", "=", "0.7", "# Fixed saturation", "v", "=", "0.95", "# Fixed value", "for", "i", "in", "range", ...
27.863636
0.001577
def _find_classes_param(self): """ Searches the wrapped model for the classes_ parameter. """ for attr in ["classes_"]: try: return getattr(self.estimator, attr) except AttributeError: continue raise YellowbrickTypeError( ...
[ "def", "_find_classes_param", "(", "self", ")", ":", "for", "attr", "in", "[", "\"classes_\"", "]", ":", "try", ":", "return", "getattr", "(", "self", ".", "estimator", ",", "attr", ")", "except", "AttributeError", ":", "continue", "raise", "YellowbrickTypeE...
29.066667
0.004444
def addnot(self, action=None, subject=None, **conditions): """ Defines an ability which cannot be done. """ self.add_rule(Rule(False, action, subject, **conditions))
[ "def", "addnot", "(", "self", ",", "action", "=", "None", ",", "subject", "=", "None", ",", "*", "*", "conditions", ")", ":", "self", ".", "add_rule", "(", "Rule", "(", "False", ",", "action", ",", "subject", ",", "*", "*", "conditions", ")", ")" ]
38.6
0.010152
def main(unused_argv): """Freeze a model to a GraphDef proto.""" if FLAGS.use_tpu: dual_net.freeze_graph_tpu(FLAGS.model_path) else: dual_net.freeze_graph(FLAGS.model_path)
[ "def", "main", "(", "unused_argv", ")", ":", "if", "FLAGS", ".", "use_tpu", ":", "dual_net", ".", "freeze_graph_tpu", "(", "FLAGS", ".", "model_path", ")", "else", ":", "dual_net", ".", "freeze_graph", "(", "FLAGS", ".", "model_path", ")" ]
32.5
0.005
def loadWallet(self, fpath): """Load wallet from specified localtion. Returns loaded wallet. Error cases: - ``fpath`` is not inside the keyrings base dir - ValueError raised - ``fpath`` exists and it's a directory - IsADirectoryError raised :param fpath: wallet...
[ "def", "loadWallet", "(", "self", ",", "fpath", ")", ":", "if", "not", "fpath", ":", "raise", "ValueError", "(", "\"empty path\"", ")", "_fpath", "=", "self", ".", "_normalize", "(", "fpath", ")", "_dpath", "=", "_fpath", ".", "parent", "try", ":", "_d...
29.068966
0.002296
def retry_connect(self): """Will be called when new channels in the token network are detected. If the minimum number of channels was not yet established, it will try to open new channels. If the connection manager has no funds, this is a noop. """ with self.lock: ...
[ "def", "retry_connect", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "_funds_remaining", ">", "0", "and", "not", "self", ".", "_leaving_state", ":", "self", ".", "_open_channels", "(", ")" ]
41.2
0.004751
def get_loco_name(self): """ Returns the Provider, Product and Engine name. :return list """ ret_str = self.dll.GetLocoName().decode() if not ret_str: return return ret_str.split('.:.')
[ "def", "get_loco_name", "(", "self", ")", ":", "ret_str", "=", "self", ".", "dll", ".", "GetLocoName", "(", ")", ".", "decode", "(", ")", "if", "not", "ret_str", ":", "return", "return", "ret_str", ".", "split", "(", "'.:.'", ")" ]
24.5
0.007874
def check_cmake_exists(cmake_command): """ Check whether CMake is installed. If not, print informative error message and quits. """ from subprocess import Popen, PIPE p = Popen( '{0} --version'.format(cmake_command), shell=True, stdin=PIPE, stdout=PIPE) if no...
[ "def", "check_cmake_exists", "(", "cmake_command", ")", ":", "from", "subprocess", "import", "Popen", ",", "PIPE", "p", "=", "Popen", "(", "'{0} --version'", ".", "format", "(", "cmake_command", ")", ",", "shell", "=", "True", ",", "stdin", "=", "PIPE", ",...
37.55
0.001299
def update_fmt_with_notebook_options(self, metadata): """Update format options with the values in the notebook metadata, and record those options in the notebook metadata""" # format options in notebook have precedence over that in fmt for opt in _VALID_FORMAT_OPTIONS: if opt...
[ "def", "update_fmt_with_notebook_options", "(", "self", ",", "metadata", ")", ":", "# format options in notebook have precedence over that in fmt", "for", "opt", "in", "_VALID_FORMAT_OPTIONS", ":", "if", "opt", "in", "metadata", ".", "get", "(", "'jupytext'", ",", "{", ...
53.384615
0.005666
def _decode_agents_data(self, block): """ decode agents jsons, count diffs """ collect = [] if block: for chunk in block.split('\n'): try: if chunk: prepared_results = {} jsn = json.lo...
[ "def", "_decode_agents_data", "(", "self", ",", "block", ")", ":", "collect", "=", "[", "]", "if", "block", ":", "for", "chunk", "in", "block", ".", "split", "(", "'\\n'", ")", ":", "try", ":", "if", "chunk", ":", "prepared_results", "=", "{", "}", ...
53
0.00314
def _check_input_directory_listing(base_directory, listing): """ Raises an DirectoryError if files or directories, given in the listing, could not be found in the local filesystem. :param base_directory: The path to the directory to check :param listing: A listing given as dictionary :raise Directo...
[ "def", "_check_input_directory_listing", "(", "base_directory", ",", "listing", ")", ":", "for", "sub", "in", "listing", ":", "path", "=", "os", ".", "path", ".", "join", "(", "base_directory", ",", "sub", "[", "'basename'", "]", ")", "if", "sub", "[", "...
48.238095
0.00484
def set_ownership(self): """Recursivelt set the parent, section and doc for a children""" assert self.section is not None for t in self.children: t.parent = self t._section = self.section t.doc = self.doc t.set_ownership()
[ "def", "set_ownership", "(", "self", ")", ":", "assert", "self", ".", "section", "is", "not", "None", "for", "t", "in", "self", ".", "children", ":", "t", ".", "parent", "=", "self", "t", ".", "_section", "=", "self", ".", "section", "t", ".", "doc...
31.888889
0.00678
def extend_extents(extents, factor=1.1): """Extend a given bounding box The bounding box (x1, y1, x2, y2) is centrally stretched by the given factor. :param extents: The bound box extents :param factor: The factor for stretching :return: (x1, y1, x2, y2) of the extended bounding box """ wi...
[ "def", "extend_extents", "(", "extents", ",", "factor", "=", "1.1", ")", ":", "width", "=", "extents", "[", "2", "]", "-", "extents", "[", "0", "]", "height", "=", "extents", "[", "3", "]", "-", "extents", "[", "1", "]", "add_width", "=", "(", "f...
34.277778
0.003155
def csv_to_map(fields, delimiter=','): """ Convert csv to dict :param delimiter: :param fields: :return: """ def _csv_to_list(csv_input): """ Util function to overcome the use of files by in-memory io buffer :param csv_input: :return: """ io...
[ "def", "csv_to_map", "(", "fields", ",", "delimiter", "=", "','", ")", ":", "def", "_csv_to_list", "(", "csv_input", ")", ":", "\"\"\"\n Util function to overcome the use of files by in-memory io buffer\n\n :param csv_input:\n :return:\n \"\"\"", "io_fil...
31.8
0.003052
def on_change_plot_cursor(self,event): """ If mouse is over data point making it selectable change the shape of the cursor @param: event -> the wx Mouseevent for that click """ if not self.xdata or not self.ydata: return pos=event.GetPosition() width, height = sel...
[ "def", "on_change_plot_cursor", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "xdata", "or", "not", "self", ".", "ydata", ":", "return", "pos", "=", "event", ".", "GetPosition", "(", ")", "width", ",", "height", "=", "self", ".", "ca...
40.037037
0.01355
def get_relationship_search_session(self, proxy=None): """Gets the ``OsidSession`` associated with the relationship search service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.relationship.RelationshipSearchSession) - a ``RelationshipSearchSession`` raise: N...
[ "def", "get_relationship_search_session", "(", "self", ",", "proxy", "=", "None", ")", ":", "if", "not", "self", ".", "supports_relationship_search", "(", ")", ":", "raise", "Unimplemented", "(", ")", "try", ":", "from", ".", "import", "sessions", "except", ...
42.730769
0.003521
def old_streamer(main_method): """Open a stream for the first file in arguments, or stdin""" if not arguments: return [sys.stdin] elif arguments[0] == '-c': return [StringIO(get_clipboard_data())] for argument in arguments: if os.path.isfile(argument): return file(arg...
[ "def", "old_streamer", "(", "main_method", ")", ":", "if", "not", "arguments", ":", "return", "[", "sys", ".", "stdin", "]", "elif", "arguments", "[", "0", "]", "==", "'-c'", ":", "return", "[", "StringIO", "(", "get_clipboard_data", "(", ")", ")", "]"...
34
0.002865
def fetch(self, tickers, fields=None, date=None, date_from=None, date_to=None, freq='D', only_data=True, static=False): """Fetch data from TR DWE. tickers - ticker or list of tickers fields - list of fields. date - date for a single-date query date_...
[ "def", "fetch", "(", "self", ",", "tickers", ",", "fields", "=", "None", ",", "date", "=", "None", ",", "date_from", "=", "None", ",", "date_to", "=", "None", ",", "freq", "=", "'D'", ",", "only_data", "=", "True", ",", "static", "=", "False", ")",...
38.032787
0.002941
def storage(self, sf=None, args=None): """Common storage interface with :class:`~flask_pluginkit.LocalStorage` or :class:`~flask_pluginkit.RedisStorage`, sf is a custom storage interface classes, args is its parameters, highest priority. :param sf: class based :class:`~flask_pluginkit.BaseStora...
[ "def", "storage", "(", "self", ",", "sf", "=", "None", ",", "args", "=", "None", ")", ":", "from", ".", "utils", "import", "BaseStorage", ",", "LocalStorage", ",", "RedisStorage", "if", "sf", "and", "isinstance", "(", "sf", ",", "BaseStorage", ")", ":"...
40.941176
0.005618
def get_dict_for_class(self, class_name, state=None, base_name='View'): """The style dict for a given class and state. This collects the style attributes from parent classes and the class of the given object and gives precedence to values thereof to the children. The state attr...
[ "def", "get_dict_for_class", "(", "self", ",", "class_name", ",", "state", "=", "None", ",", "base_name", "=", "'View'", ")", ":", "classes", "=", "[", "]", "klass", "=", "class_name", "while", "True", ":", "classes", ".", "append", "(", "klass", ")", ...
30.490196
0.001246
def exists(path, **kwargs): """Check if file or directory exists""" import os.path return os.path.exists(path, **kwargs)
[ "def", "exists", "(", "path", ",", "*", "*", "kwargs", ")", ":", "import", "os", ".", "path", "return", "os", ".", "path", ".", "exists", "(", "path", ",", "*", "*", "kwargs", ")" ]
32.25
0.007576
def _env_is_exposed(env): ''' Check if an environment is exposed by comparing it against a whitelist and blacklist. ''' if __opts__['svnfs_env_whitelist']: salt.utils.versions.warn_until( 'Neon', 'The svnfs_env_whitelist config option has been renamed to ' ...
[ "def", "_env_is_exposed", "(", "env", ")", ":", "if", "__opts__", "[", "'svnfs_env_whitelist'", "]", ":", "salt", ".", "utils", ".", "versions", ".", "warn_until", "(", "'Neon'", ",", "'The svnfs_env_whitelist config option has been renamed to '", "'svnfs_saltenv_whitel...
33.133333
0.000978
def finish(self): """ Restore the original SIGINT handler after finishing. This should happen regardless of whether the progress display finishes normally, or gets interrupted. """ super(InterruptibleMixin, self).finish() signal(SIGINT, self.original_handler)
[ "def", "finish", "(", "self", ")", ":", "super", "(", "InterruptibleMixin", ",", "self", ")", ".", "finish", "(", ")", "signal", "(", "SIGINT", ",", "self", ".", "original_handler", ")" ]
34.222222
0.006329
def type_object_attrgetter(obj, attr, *defargs): """ This implements an improved attrgetter for type objects (i.e. classes) that can handle class attributes that are implemented as properties on a metaclass. Normally `getattr` on a class with a `property` (say, "foo"), would return the `propert...
[ "def", "type_object_attrgetter", "(", "obj", ",", "attr", ",", "*", "defargs", ")", ":", "for", "base", "in", "obj", ".", "__mro__", ":", "if", "attr", "in", "base", ".", "__dict__", ":", "if", "isinstance", "(", "base", ".", "__dict__", "[", "attr", ...
37.361702
0.000555
def doubleMouseButtonLeftWithMods(self, coord, modifiers): """Click the left mouse button with modifiers pressed. Parameters: coordinates to click; modifiers (list) Returns: None """ modFlags = self._pressModifiers(modifiers) self._queueMouseButton(coord, Quartz.kCGMouse...
[ "def", "doubleMouseButtonLeftWithMods", "(", "self", ",", "coord", ",", "modifiers", ")", ":", "modFlags", "=", "self", ".", "_pressModifiers", "(", "modifiers", ")", "self", ".", "_queueMouseButton", "(", "coord", ",", "Quartz", ".", "kCGMouseButtonLeft", ",", ...
43.75
0.003731
def collate_data(in_dir, extension='.csv', out_dir=None): """ Copy all csvs in nested directroy to single directory. Function to copy all csvs from a directory, and place them in a new directory. Parameters ---------- in_dir : str Input directory containing csv files in subfolders ...
[ "def", "collate_data", "(", "in_dir", ",", "extension", "=", "'.csv'", ",", "out_dir", "=", "None", ")", ":", "if", "out_dir", "is", "None", ":", "out_dir", "=", "'./'", "+", "re", ".", "search", "(", "'^\\.(.*)'", ",", "extension", ")", ".", "groups",...
24.9375
0.002413
def setContentLen(self, content, len): """Replace the content of a node. NOTE: @content is supposed to be a piece of XML CDATA, so it allows entity references, but XML special chars need to be escaped first by using xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). """ ...
[ "def", "setContentLen", "(", "self", ",", "content", ",", "len", ")", ":", "libxml2mod", ".", "xmlNodeSetContentLen", "(", "self", ".", "_o", ",", "content", ",", "len", ")" ]
62.666667
0.005249
def _serialize( self, array_parent, # type: ET.Element value, # type: List state # type: _ProcessorState ): # type: (...) -> None """Serialize the array value and add it to the array parent element.""" if not value: # Nothing to ...
[ "def", "_serialize", "(", "self", ",", "array_parent", ",", "# type: ET.Element", "value", ",", "# type: List", "state", "# type: _ProcessorState", ")", ":", "# type: (...) -> None", "if", "not", "value", ":", "# Nothing to do. Avoid attempting to iterate over a possibly", ...
37.166667
0.005831
def statement_prep(link): ''' Prepare a statement into a triple ready for rdflib ''' from rdflib import URIRef, Literal from rdflib import BNode s, p, o = link[:3] if not isinstance(s, BNode): s = URIRef(s) p = URIRef(p) if not isinstance(o, BNode): o = URIRef(o) if isinstance(o, I) ...
[ "def", "statement_prep", "(", "link", ")", ":", "from", "rdflib", "import", "URIRef", ",", "Literal", "from", "rdflib", "import", "BNode", "s", ",", "p", ",", "o", "=", "link", "[", ":", "3", "]", "if", "not", "isinstance", "(", "s", ",", "BNode", ...
31.272727
0.011299
def _get_all(self, *args, **kwargs): """If 'force' is in the headers, retrieve the list of keys from S3. Otherwise, use the list() function to retrieve the keys from MimicDB. """ headers = kwargs.get('headers', args[2] if len(args) > 2 else None) or dict() if 'force' in headers:...
[ "def", "_get_all", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "kwargs", ".", "get", "(", "'headers'", ",", "args", "[", "2", "]", "if", "len", "(", "args", ")", ">", "2", "else", "None", ")", "or", "dict",...
36.8
0.005298
def build_additional_match(self, ident, node_set): """ handle additional matches supplied by 'has()' calls """ source_ident = ident for key, value in node_set.must_match.items(): if isinstance(value, dict): label = ':' + value['node_class'].__labe...
[ "def", "build_additional_match", "(", "self", ",", "ident", ",", "node_set", ")", ":", "source_ident", "=", "ident", "for", "key", ",", "value", "in", "node_set", ".", "must_match", ".", "items", "(", ")", ":", "if", "isinstance", "(", "value", ",", "dic...
42.761905
0.004357
def _insert_data(con, data): """ insert line for each cluster """ with con: cur = con.cursor() cur.execute("DROP TABLE IF EXISTS clusters;") cur.execute("CREATE TABLE clusters(Id INT, Description TEXT, Locus TEXT, Annotation TEXT, Sequences TEXT, Profile TXT, Precursor TXT)") ...
[ "def", "_insert_data", "(", "con", ",", "data", ")", ":", "with", "con", ":", "cur", "=", "con", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"DROP TABLE IF EXISTS clusters;\"", ")", "cur", ".", "execute", "(", "\"CREATE TABLE clusters(Id INT, Descri...
52.368421
0.002962
def cns_vwl_pstr_long(self): """ Return a new IPAString, containing only: 1. the consonants, 2. the vowels, and 3. the primary stress diacritics, and 4. the long suprasegmental in the current string. :rtype: IPAString """ return ...
[ "def", "cns_vwl_pstr_long", "(", "self", ")", ":", "return", "IPAString", "(", "ipa_chars", "=", "[", "c", "for", "c", "in", "self", ".", "ipa_chars", "if", "(", "c", ".", "is_letter", ")", "or", "(", "c", ".", "is_suprasegmental", "and", "(", "c", "...
31.142857
0.008909
def file_find(self, load): ''' Convenience function for calls made using the LocalClient ''' path = load.get('path') if not path: return {'path': '', 'rel': ''} tgt_env = load.get('saltenv', 'base') return self.find_file(path, tgt_e...
[ "def", "file_find", "(", "self", ",", "load", ")", ":", "path", "=", "load", ".", "get", "(", "'path'", ")", "if", "not", "path", ":", "return", "{", "'path'", ":", "''", ",", "'rel'", ":", "''", "}", "tgt_env", "=", "load", ".", "get", "(", "'...
31.4
0.006192
def add(config, username, filename): """Add user's SSH public key to their LDAP entry.""" try: client = Client() client.prepare_connection() user_api = UserApi(client) key_api = API(client) key_api.add(username, user_api, filename) exce...
[ "def", "add", "(", "config", ",", "username", ",", "filename", ")", ":", "try", ":", "client", "=", "Client", "(", ")", "client", ".", "prepare_connection", "(", ")", "user_api", "=", "UserApi", "(", "client", ")", "key_api", "=", "API", "(", "client",...
44.8
0.002915
def delete_operation(self, name, options=None): """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operation result. It does not cancel the operation. If the server doesn't support this method, it returns ``google.rpc.Code.U...
[ "def", "delete_operation", "(", "self", ",", "name", ",", "options", "=", "None", ")", ":", "# Create the request object.", "request", "=", "operations_pb2", ".", "DeleteOperationRequest", "(", "name", "=", "name", ")", "self", ".", "_delete_operation", "(", "re...
42.24
0.002778
def _bfd_rx(self, **kwargs): """Return the BFD minimum receive interval XML. You should not use this method. You probably want `BGP.bfd`. Args: min_rx (str): BFD receive interval in milliseconds (300, 500, etc) delete (bool): Remove the configuration if ``True``...
[ "def", "_bfd_rx", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", "[", "'int_type'", "]", "method_name", "=", "'interface_%s_bfd_interval_min_rx'", "%", "int_type", "bfd_rx", "=", "getattr", "(", "self", ".", "_interface", ",", "me...
30.48
0.002545
def _get_meta(model): """Return metadata of a model. Model could be a real model or evaluated metadata.""" if isinstance(model, Model): w = model.meta else: w = model # Already metadata return w
[ "def", "_get_meta", "(", "model", ")", ":", "if", "isinstance", "(", "model", ",", "Model", ")", ":", "w", "=", "model", ".", "meta", "else", ":", "w", "=", "model", "# Already metadata", "return", "w" ]
28
0.004329
def _maybe_validate_distributions(distributions, dtype_override, validate_args): """Checks that `distributions` satisfies all assumptions.""" assertions = [] if not _is_iterable(distributions) or not distributions: raise ValueError('`distributions` must be a list of one or more ' 'distri...
[ "def", "_maybe_validate_distributions", "(", "distributions", ",", "dtype_override", ",", "validate_args", ")", ":", "assertions", "=", "[", "]", "if", "not", "_is_iterable", "(", "distributions", ")", "or", "not", "distributions", ":", "raise", "ValueError", "(",...
40.591837
0.008346
def create(filename, spec): """Create a new segy file. Create a new segy file with the geometry and properties given by `spec`. This enables creating SEGY files from your data. The created file supports all segyio modes, but has an emphasis on writing. The spec must be complete, otherwise an except...
[ "def", "create", "(", "filename", ",", "spec", ")", ":", "from", ".", "import", "_segyio", "if", "not", "structured", "(", "spec", ")", ":", "tracecount", "=", "spec", ".", "tracecount", "else", ":", "tracecount", "=", "len", "(", "spec", ".", "ilines"...
29.368421
0.008194
def set_metadata(self, obj, metadata, clear=False, prefix=None): """ Accepts a dictionary of metadata key/value pairs and updates the specified object metadata with them. If 'clear' is True, any existing metadata is deleted and only the passed metadata is retained. Otherwise, th...
[ "def", "set_metadata", "(", "self", ",", "obj", ",", "metadata", ",", "clear", "=", "False", ",", "prefix", "=", "None", ")", ":", "# Add the metadata prefix, if needed.", "if", "prefix", "is", "None", ":", "prefix", "=", "OBJECT_META_PREFIX", "massaged", "=",...
44.578947
0.001155
def encoder(f, blocksize, seed=None, c=sampler.DEFAULT_C, delta=sampler.DEFAULT_DELTA): """Generates an infinite sequence of blocks to transmit to the receiver """ # Generate seed if not provided if seed is None: seed = randint(0, 1 << 31 - 1) # get file blocks filesize, blocks = _...
[ "def", "encoder", "(", "f", ",", "blocksize", ",", "seed", "=", "None", ",", "c", "=", "sampler", ".", "DEFAULT_C", ",", "delta", "=", "sampler", ".", "DEFAULT_DELTA", ")", ":", "# Generate seed if not provided", "if", "seed", "is", "None", ":", "seed", ...
30.962963
0.00464
def from_api_repr(cls, resource, client): """Factory: construct a metric given its API representation :type resource: dict :param resource: metric resource representation returned from the API :type client: :class:`google.cloud.logging.client.Client` :param client: Client whic...
[ "def", "from_api_repr", "(", "cls", ",", "resource", ",", "client", ")", ":", "metric_name", "=", "resource", "[", "\"name\"", "]", "filter_", "=", "resource", "[", "\"filter\"", "]", "description", "=", "resource", ".", "get", "(", "\"description\"", ",", ...
42.529412
0.00406
def write_str(data, sidx, pnames): """ Write STRUCTURE format for all SNPs and unlinked SNPs """ ## grab snp and bis data from tmparr start = time.time() tmparrs = os.path.join(data.dirs.outfiles, "tmp-{}.h5".format(data.name)) with h5py.File(tmparrs, 'r') as io5: snparr = io5["snparr"] ...
[ "def", "write_str", "(", "data", ",", "sidx", ",", "pnames", ")", ":", "## grab snp and bis data from tmparr", "start", "=", "time", ".", "time", "(", ")", "tmparrs", "=", "os", ".", "path", ".", "join", "(", "data", ".", "dirs", ".", "outfiles", ",", ...
41.54717
0.015084
def get(self, key, default) -> Union[Uniform, UniformBlock, Subroutine, Attribute, Varying]: ''' Returns a Uniform, UniformBlock, Subroutine, Attribute or Varying. Args: default: This is the value to be returned in case key does not exist. Returns: ...
[ "def", "get", "(", "self", ",", "key", ",", "default", ")", "->", "Union", "[", "Uniform", ",", "UniformBlock", ",", "Subroutine", ",", "Attribute", ",", "Varying", "]", ":", "return", "self", ".", "_members", ".", "get", "(", "key", ",", "default", ...
38.923077
0.009653
def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio): """ Creates an UDP connection in uBridge. :param bridge_name: bridge name in uBridge :param source_nio: source NIO instance :param destination_nio: destination NIO instance """ yield...
[ "def", "add_ubridge_udp_connection", "(", "self", ",", "bridge_name", ",", "source_nio", ",", "destination_nio", ")", ":", "yield", "from", "self", ".", "_ubridge_send", "(", "\"bridge create {name}\"", ".", "format", "(", "name", "=", "bridge_name", ")", ")", "...
63.666667
0.007736
def add_veth(name, interface_name, bridge=None, path=None): ''' Add a veth to a container. Note : this function doesn't update the container config, just add the interface at runtime name Name of the container interface_name Name of the interface in the container bridge ...
[ "def", "add_veth", "(", "name", ",", "interface_name", ",", "bridge", "=", "None", ",", "path", "=", "None", ")", ":", "# Get container init PID", "pid", "=", "get_pid", "(", "name", ",", "path", "=", "path", ")", "# Generate a ramdom string for veth and ensure ...
38.975
0.004692
def check(self): """ Checks the values of the window quads. If any problems are found it flags the offending window by changing the background colour. Returns: status : bool """ status = synced = True xbin = self.xbin.value() ybin = self.ybin...
[ "def", "check", "(", "self", ")", ":", "status", "=", "synced", "=", "True", "xbin", "=", "self", ".", "xbin", ".", "value", "(", ")", "ybin", "=", "self", ".", "ybin", ".", "value", "(", ")", "nquad", "=", "self", ".", "nquad", ".", "value", "...
39.37931
0.001281
def value_type(type_): """returns reference to `boost::shared_ptr` \ or `std::shared_ptr` value type""" if not smart_pointer_traits.is_smart_pointer(type_): raise TypeError( 'Type "%s" is not an instantiation of \ boost::shared_ptr or std::shared_ptr' ...
[ "def", "value_type", "(", "type_", ")", ":", "if", "not", "smart_pointer_traits", ".", "is_smart_pointer", "(", "type_", ")", ":", "raise", "TypeError", "(", "'Type \"%s\" is not an instantiation of \\\n boost::shared_ptr or std::shared_ptr'", "%", "type_", "...
44.25
0.00369
def _create_fig( *, x_sc=bq.LinearScale, y_sc=bq.LinearScale, x_ax=bq.Axis, y_ax=bq.Axis, fig=bq.Figure, options={}, params={} ): """ Initializes scales and axes for a bqplot figure and returns the resulting blank figure. Each plot component is passed in as a class. The plot ...
[ "def", "_create_fig", "(", "*", ",", "x_sc", "=", "bq", ".", "LinearScale", ",", "y_sc", "=", "bq", ".", "LinearScale", ",", "x_ax", "=", "bq", ".", "Axis", ",", "y_ax", "=", "bq", ".", "Axis", ",", "fig", "=", "bq", ".", "Figure", ",", "options"...
34.368421
0.000745
def add_member(self, member, dn=False): """Add a member to the bound group Arguments: member -- the CSHMember object (or distinguished name) of the member Keyword arguments: dn -- whether or not member is a distinguished name """ if dn: if self.chec...
[ "def", "add_member", "(", "self", ",", "member", ",", "dn", "=", "False", ")", ":", "if", "dn", ":", "if", "self", ".", "check_member", "(", "member", ",", "dn", "=", "True", ")", ":", "return", "mod", "=", "(", "ldap", ".", "MOD_ADD", ",", "'mem...
33.846154
0.00221