text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background...
[ "def", "check_background_commands_complete", "(", "self", ")", ":", "unstarted_command_exists", "=", "False", "self", ".", "shutit_obj", ".", "log", "(", "'In check_background_commands_complete: all background objects: '", "+", "str", "(", "self", ".", "background_objects",...
57.604167
0.025605
def sigmoidal_difference_membership(bin_center, bin_width, smoothness): r"""Create the difference of two sigmoids as membership function for a fuzzy histogram bin. Parameters ---------- bin_center : number The center of the bin of which to compute the membership function. bin_width : nu...
[ "def", "sigmoidal_difference_membership", "(", "bin_center", ",", "bin_width", ",", "smoothness", ")", ":", "if", "smoothness", ">", "10", "or", "smoothness", "<", "1.", "/", "10", ":", "raise", "AttributeError", "(", "'the sigmoidal membership function supports only ...
43.84507
0.012253
def RunInstaller(): """Run all registered installers. Run all the current installers and then exit the process. """ try: os.makedirs(os.path.dirname(config.CONFIG["Installer.logfile"])) except OSError: pass # Always log to the installer logfile at debug level. This way if our # installer fails ...
[ "def", "RunInstaller", "(", ")", ":", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "config", ".", "CONFIG", "[", "\"Installer.logfile\"", "]", ")", ")", "except", "OSError", ":", "pass", "# Always log to the installer logfi...
33.604651
0.015467
def make_idd_index(extract_func, fname, debug): """generate the iddindex""" astr = _readfname(fname) # fname is exhausted by the above read # reconstitute fname as a StringIO fname = StringIO(astr) # glist = iddgroups.iddtxt2grouplist(astr.decode('ISO-8859-2')) blocklst, commlst,...
[ "def", "make_idd_index", "(", "extract_func", ",", "fname", ",", "debug", ")", ":", "astr", "=", "_readfname", "(", "fname", ")", "# fname is exhausted by the above read", "# reconstitute fname as a StringIO", "fname", "=", "StringIO", "(", "astr", ")", "# glist = idd...
33
0.009302
def run_autoapi(app): """ Load AutoAPI data from the filesystem. """ if not app.config.autoapi_dirs: raise ExtensionError("You must configure an autoapi_dirs setting") # Make sure the paths are full normalized_dirs = [] autoapi_dirs = app.config.autoapi_dirs if isinstance(autoa...
[ "def", "run_autoapi", "(", "app", ")", ":", "if", "not", "app", ".", "config", ".", "autoapi_dirs", ":", "raise", "ExtensionError", "(", "\"You must configure an autoapi_dirs setting\"", ")", "# Make sure the paths are full", "normalized_dirs", "=", "[", "]", "autoapi...
34.492537
0.001683
def dbsExceptionHandler(eCode='', message='', logger=None , serverError=''): """ This utility function handles all dbs exceptions. It will log , raise exception based on input condition. It loggs the traceback on the server log. Send HTTPError 400 for invalid client input and HTTPError 404 for NOT FOUN...
[ "def", "dbsExceptionHandler", "(", "eCode", "=", "''", ",", "message", "=", "''", ",", "logger", "=", "None", ",", "serverError", "=", "''", ")", ":", "if", "logger", ":", "#HTTP Error", "if", "eCode", "==", "\"dbsException-invalid-input\"", ":", "#logger(eC...
50.628571
0.022702
def to_table(result): ''' normalize raw result to table ''' max_count = 20 table, count = [], 0 for role, envs_topos in result.items(): for env, topos in envs_topos.items(): for topo in topos: count += 1 if count > max_count: continue else: table.append([rol...
[ "def", "to_table", "(", "result", ")", ":", "max_count", "=", "20", "table", ",", "count", "=", "[", "]", ",", "0", "for", "role", ",", "envs_topos", "in", "result", ".", "items", "(", ")", ":", "for", "env", ",", "topos", "in", "envs_topos", ".", ...
30.4
0.023404
def _make_request( self, method, url, data=None, content_type=None, headers=None, target_object=None, ): """A low level method to send a request to the API. Typically, you shouldn't need to use this method. :type method: str :...
[ "def", "_make_request", "(", "self", ",", "method", ",", "url", ",", "data", "=", "None", ",", "content_type", "=", "None", ",", "headers", "=", "None", ",", "target_object", "=", "None", ",", ")", ":", "headers", "=", "headers", "or", "{", "}", "hea...
31.102041
0.001908
def remove_aliases(self_or_cls, aliases): """ Remove a list of aliases. """ for k,v in self_or_cls.aliases.items(): if v in aliases: self_or_cls.aliases.pop(k)
[ "def", "remove_aliases", "(", "self_or_cls", ",", "aliases", ")", ":", "for", "k", ",", "v", "in", "self_or_cls", ".", "aliases", ".", "items", "(", ")", ":", "if", "v", "in", "aliases", ":", "self_or_cls", ".", "aliases", ".", "pop", "(", "k", ")" ]
30.428571
0.013699
def save_metadata(self, data_dir, feature_name=None): """See base class for details.""" # Recursively save all child features for feature_key, feature in six.iteritems(self._feature_dict): if feature_name: feature_key = '-'.join((feature_name, feature_key)) feature.save_metadata(data_dir...
[ "def", "save_metadata", "(", "self", ",", "data_dir", ",", "feature_name", "=", "None", ")", ":", "# Recursively save all child features", "for", "feature_key", ",", "feature", "in", "six", ".", "iteritems", "(", "self", ".", "_feature_dict", ")", ":", "if", "...
48.714286
0.008646
async def update_bikes(delta: Optional[timedelta] = None): """ A background task that retrieves bike data. :param delta: The amount of time to wait between checks. """ async def update(delta: timedelta): logger.info("Fetching bike data.") if await should_update_bikes(delta): ...
[ "async", "def", "update_bikes", "(", "delta", ":", "Optional", "[", "timedelta", "]", "=", "None", ")", ":", "async", "def", "update", "(", "delta", ":", "timedelta", ")", ":", "logger", ".", "info", "(", "\"Fetching bike data.\"", ")", "if", "await", "s...
37
0.002079
def generate_pagination(total_page_num, current_page_num): """ >>> PAGE_SIZE = 10 >>> generate_pagination(total_page_num=9, current_page_num=1) {'start': 1, 'end': 9, 'current': 1} >>> generate_pagination(total_page_num=20, current_page_num=12) {'start': 8, 'end': 17, 'current': 12} >>> gene...
[ "def", "generate_pagination", "(", "total_page_num", ",", "current_page_num", ")", ":", "pagination", "=", "{", "'start'", ":", "1", ",", "'end'", ":", "PAGE_SIZE", ",", "'current'", ":", "current_page_num", "}", "if", "total_page_num", "<=", "PAGE_SIZE", ":", ...
36.733333
0.000884
def start_simple_webserver(domain=None, port=5832): r""" simple webserver that echos its arguments Args: domain (None): (default = None) port (int): (default = 5832) CommandLine: python -m utool.util_web --exec-start_simple_webserver:0 python -m utool.util_web --exec-st...
[ "def", "start_simple_webserver", "(", "domain", "=", "None", ",", "port", "=", "5832", ")", ":", "import", "tornado", ".", "ioloop", "import", "tornado", ".", "web", "import", "tornado", ".", "httpserver", "import", "tornado", ".", "wsgi", "import", "flask",...
32.933333
0.001311
def __doQuery(self, query, format, convert): """ Inner method that does the actual query """ self.__getFormat(format) self.sparql.setQuery(query) if convert: results = self.sparql.query().convert() else: results = self.sparql.query() return results
[ "def", "__doQuery", "(", "self", ",", "query", ",", "format", ",", "convert", ")", ":", "self", ".", "__getFormat", "(", "format", ")", "self", ".", "sparql", ".", "setQuery", "(", "query", ")", "if", "convert", ":", "results", "=", "self", ".", "spa...
21.666667
0.04428
def _fix_keys(key_mapping, inibin, string_table=None): """ Return a human-readable dictionary from the inibin. Arguments: key_mapping -- Dictionary used for conversion. Supports nesting. Every other value should be a numeric inibin key, or a tuple of the key and a function to apply to t...
[ "def", "_fix_keys", "(", "key_mapping", ",", "inibin", ",", "string_table", "=", "None", ")", ":", "if", "string_table", "is", "None", ":", "string_table", "=", "{", "}", "def", "walk", "(", "node", ",", "out_node", ")", ":", "# Walk the nodes of the key map...
33.33871
0.00188
def create_volume(self, project_id, plan, size, facility, label=""): """Creates a new volume. """ try: return self.manager.create_volume(project_id, label, plan, size, facility) except packet.baseapi.Error as msg: raise PacketManagerException(msg)
[ "def", "create_volume", "(", "self", ",", "project_id", ",", "plan", ",", "size", ",", "facility", ",", "label", "=", "\"\"", ")", ":", "try", ":", "return", "self", ".", "manager", ".", "create_volume", "(", "project_id", ",", "label", ",", "plan", ",...
42.428571
0.009901
def _normalize_index_columns_in_place(equities, equity_supplementary_mappings, futures, exchanges, root_symbols): """ Update dataframes in place to set indentif...
[ "def", "_normalize_index_columns_in_place", "(", "equities", ",", "equity_supplementary_mappings", ",", "futures", ",", "exchanges", ",", "root_symbols", ")", ":", "for", "frame", ",", "column_name", "in", "(", "(", "equities", ",", "'sid'", ")", ",", "(", "equi...
44.636364
0.000997
def print_data_to_file(data, file_name): """Prints data to file. :param data: the data to print. :param file_name: the name of the output file. :type data: numpy.recarray :type file_name: str """ try: with open(file_name, 'w') as output_file: print >>output_file, "\t"....
[ "def", "print_data_to_file", "(", "data", ",", "file_name", ")", ":", "try", ":", "with", "open", "(", "file_name", ",", "'w'", ")", "as", "output_file", ":", "print", ">>", "output_file", ",", "\"\\t\"", ".", "join", "(", "data", ".", "dtype", ".", "n...
29.055556
0.001852
def antiscia(self): """ Returns antiscia object. """ obj = self.copy() obj.type = const.OBJ_GENERIC obj.relocate(360 - obj.lon + 180) return obj
[ "def", "antiscia", "(", "self", ")", ":", "obj", "=", "self", ".", "copy", "(", ")", "obj", ".", "type", "=", "const", ".", "OBJ_GENERIC", "obj", ".", "relocate", "(", "360", "-", "obj", ".", "lon", "+", "180", ")", "return", "obj" ]
29.833333
0.01087
def class_balance(y_train, y_test=None, ax=None, labels=None, **kwargs): """Quick method: One of the biggest challenges for classification models is an imbalance of classes in the training data. This function vizualizes the relationship of the support for each class in both the training and test data b...
[ "def", "class_balance", "(", "y_train", ",", "y_test", "=", "None", ",", "ax", "=", "None", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Instantiate the visualizer", "visualizer", "=", "ClassBalance", "(", "ax", "=", "ax", ",", "labe...
37.481481
0.000963
def assert_regex(text, regex, msg_fmt="{msg}"): """Fail if text does not match the regular expression. regex can be either a regular expression string or a compiled regular expression object. >>> assert_regex("Hello World!", r"llo.*rld!$") >>> assert_regex("Hello World!", r"\\d") Traceback (mo...
[ "def", "assert_regex", "(", "text", ",", "regex", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "compiled", "=", "re", ".", "compile", "(", "regex", ")", "if", "not", "compiled", ".", "search", "(", "text", ")", ":", "msg", "=", "\"{!r} does not match {!r}...
35.909091
0.001233
async def get(self): """ Returns (batch, data) if one or more items could be retrieved. If the cancellation occurs or only invalid items were in the queue, (None, None) will be returned instead. """ if not self._deque: self._ready.clear() await se...
[ "async", "def", "get", "(", "self", ")", ":", "if", "not", "self", ".", "_deque", ":", "self", ".", "_ready", ".", "clear", "(", ")", "await", "self", ".", "_ready", ".", "wait", "(", ")", "buffer", "=", "io", ".", "BytesIO", "(", ")", "batch", ...
38.630137
0.000692
def set_env(self, arguments): """ Setup the environment variables for the process. """ return lib.zproc_set_env(self._as_parameter_, byref(zhash_p.from_param(arguments)))
[ "def", "set_env", "(", "self", ",", "arguments", ")", ":", "return", "lib", ".", "zproc_set_env", "(", "self", ".", "_as_parameter_", ",", "byref", "(", "zhash_p", ".", "from_param", "(", "arguments", ")", ")", ")" ]
39.6
0.014851
def is_clique(self, nodes): """ Check if the given nodes form a clique. Parameters ---------- nodes: list, array-like List of nodes to check if they are a part of any clique. Examples -------- >>> from pgmpy.base import UndirectedGraph ...
[ "def", "is_clique", "(", "self", ",", "nodes", ")", ":", "for", "node1", ",", "node2", "in", "itertools", ".", "combinations", "(", "nodes", ",", "2", ")", ":", "if", "not", "self", ".", "has_edge", "(", "node1", ",", "node2", ")", ":", "return", "...
32.965517
0.002033
def get_tree_size(path): """Return total size of all files in directory tree at path.""" size = 0 try: for entry in scandir.scandir(path): if entry.is_symlink(): pass elif entry.is_dir(): size += get_tree_size(os.path.join(path, entry.name)) ...
[ "def", "get_tree_size", "(", "path", ")", ":", "size", "=", "0", "try", ":", "for", "entry", "in", "scandir", ".", "scandir", "(", "path", ")", ":", "if", "entry", ".", "is_symlink", "(", ")", ":", "pass", "elif", "entry", ".", "is_dir", "(", ")", ...
29.714286
0.002331
def _do_retrieve_scopes(self, http, token): """Retrieves the list of authorized scopes from the OAuth2 provider. Args: http: an object to be used to make HTTP requests. token: A string used as the token to identify the credentials to the provider. Rai...
[ "def", "_do_retrieve_scopes", "(", "self", ",", "http", ",", "token", ")", ":", "logger", ".", "info", "(", "'Refreshing scopes'", ")", "query_params", "=", "{", "'access_token'", ":", "token", ",", "'fields'", ":", "'scope'", "}", "token_info_uri", "=", "_h...
40.8
0.001596
def _run_pre_command(self, pre_cmd): ''' Run a pre command to get external args for a command ''' logger.debug('Executing pre-command: %s', pre_cmd) try: pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True) except OSError as err: if er...
[ "def", "_run_pre_command", "(", "self", ",", "pre_cmd", ")", ":", "logger", ".", "debug", "(", "'Executing pre-command: %s'", ",", "pre_cmd", ")", "try", ":", "pre_proc", "=", "Popen", "(", "pre_cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT...
38
0.002334
def _decorate(self): """Draw all decorations""" self._set_view() self._make_graph() self._axes() self._legend() self._make_title() self._make_x_title() self._make_y_title()
[ "def", "_decorate", "(", "self", ")", ":", "self", ".", "_set_view", "(", ")", "self", ".", "_make_graph", "(", ")", "self", ".", "_axes", "(", ")", "self", ".", "_legend", "(", ")", "self", ".", "_make_title", "(", ")", "self", ".", "_make_x_title",...
25.333333
0.008475
def ProcessHuntFlowError(flow_obj, error_message=None, backtrace=None, status_msg=None): """Processes error and status message for a given hunt-induced flow.""" if not hunt.IsLegacyHunt(flow_obj.parent_hunt_id): hunt.StopHuntIfCPUOrNetw...
[ "def", "ProcessHuntFlowError", "(", "flow_obj", ",", "error_message", "=", "None", ",", "backtrace", "=", "None", ",", "status_msg", "=", "None", ")", ":", "if", "not", "hunt", ".", "IsLegacyHunt", "(", "flow_obj", ".", "parent_hunt_id", ")", ":", "hunt", ...
43.703704
0.010779
def message(self): 'the standard message which can be transfer' return { 'source': 'account', 'frequence': self.frequence, 'account_cookie': self.account_cookie, 'portfolio_cookie': self.portfolio_cookie, ...
[ "def", "message", "(", "self", ")", ":", "return", "{", "'source'", ":", "'account'", ",", "'frequence'", ":", "self", ".", "frequence", ",", "'account_cookie'", ":", "self", ".", "account_cookie", ",", "'portfolio_cookie'", ":", "self", ".", "portfolio_cookie...
28.245902
0.001122
def mangle(data_point): """mangle data into expected format.""" temp_dict = {} temp_dict.update(data_point) temp_dict['utc_datetime'] = \ datetime.datetime.utcfromtimestamp(temp_dict['time']) if 'solar' in data_point: temp_dict['GHI (W/m^2)'] = data_point['solar']['ghi'] temp...
[ "def", "mangle", "(", "data_point", ")", ":", "temp_dict", "=", "{", "}", "temp_dict", ".", "update", "(", "data_point", ")", "temp_dict", "[", "'utc_datetime'", "]", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "temp_dict", "[", "'time'",...
38.555556
0.001406
def source(self, value): """The source property. Args: value (string). the property value. """ if value == self._defaults['source'] and 'source' in self._values: del self._values['source'] else: self._values['source'] = value
[ "def", "source", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'source'", "]", "and", "'source'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'source'", "]", "else", ":", "self",...
30.1
0.009677
def get_nfc_chars(self): """ Returns the set of IPA symbols that are precomposed (decomposable) chars. These should not be decomposed during string normalisation, because they will not be recognised otherwise. In IPA 2015 there is only one precomposed character: ç, the voiceless palatal fricative. """ ...
[ "def", "get_nfc_chars", "(", "self", ")", ":", "ex", "=", "[", "]", "for", "char", "in", "self", ".", "ipa", ".", "keys", "(", ")", ":", "if", "len", "(", "char", ")", "==", "1", ":", "decomp", "=", "unicodedata", ".", "normalize", "(", "'NFD'", ...
26.444444
0.032454
def to_json(self, minimal=True): """Encode an object as a JSON string. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: str """ if minimal: return json.dumps(self.json_repr(minimal=True), cls=Marathon...
[ "def", "to_json", "(", "self", ",", "minimal", "=", "True", ")", ":", "if", "minimal", ":", "return", "json", ".", "dumps", "(", "self", ".", "json_repr", "(", "minimal", "=", "True", ")", ",", "cls", "=", "MarathonMinimalJsonEncoder", ",", "sort_keys", ...
40.727273
0.010917
def password(message: Text, default: Text = "", validate: Union[Type[Validator], Callable[[Text], bool], None] = None, # noqa qmark: Text = DEFAULT_QUESTION_PREFIX, style: Optional[Style] = None, ...
[ "def", "password", "(", "message", ":", "Text", ",", "default", ":", "Text", "=", "\"\"", ",", "validate", ":", "Union", "[", "Type", "[", "Validator", "]", ",", "Callable", "[", "[", "Text", "]", ",", "bool", "]", ",", "None", "]", "=", "None", ...
40.65
0.001201
def take_using_weights(items, weights): """ Generator that keeps yielding items from the items list, in proportion to their weight. For instance:: # Getting the first 70 items from this generator should have yielded 10 # times A, 20 times B and 40 times C, all distributed equally.. ...
[ "def", "take_using_weights", "(", "items", ",", "weights", ")", ":", "assert", "isinstance", "(", "items", ",", "list", ")", "assert", "isinstance", "(", "weights", ",", "list", ")", "assert", "all", "(", "isinstance", "(", "i", ",", "int", ")", "for", ...
34
0.001546
def save(self): """Save the alarm to the Sonos system. Raises: ~soco.exceptions.SoCoUPnPException: if the alarm cannot be created because there is already an alarm for this room at the specified time. """ # pylint: disable=bad-continuation ...
[ "def", "save", "(", "self", ")", ":", "# pylint: disable=bad-continuation", "args", "=", "[", "(", "'StartLocalTime'", ",", "self", ".", "start_time", ".", "strftime", "(", "TIME_FORMAT", ")", ")", ",", "(", "'Duration'", ",", "''", "if", "self", ".", "dur...
43.516129
0.00145
def get(self, a, b=None): """Return a link distance or a dict of {node: distance} entries. .get(a,b) returns the distance or None; .get(a) returns a dict of {node: distance} entries, possibly {}.""" links = self.dict.setdefault(a, {}) if b is None: return links else: retu...
[ "def", "get", "(", "self", ",", "a", ",", "b", "=", "None", ")", ":", "links", "=", "self", ".", "dict", ".", "setdefault", "(", "a", ",", "{", "}", ")", "if", "b", "is", "None", ":", "return", "links", "else", ":", "return", "links", ".", "g...
47
0.01194
def forward(self, ploc, plabel, gloc, glabel): """ ploc, plabel: Nx4x8732, Nxlabel_numx8732 predicted location and labels gloc, glabel: Nx4x8732, Nx8732 ground truth location and labels """ mask = glabel > 0 pos_num = mask.sum(dim...
[ "def", "forward", "(", "self", ",", "ploc", ",", "plabel", ",", "gloc", ",", "glabel", ")", ":", "mask", "=", "glabel", ">", "0", "pos_num", "=", "mask", ".", "sum", "(", "dim", "=", "1", ")", "vec_gd", "=", "self", ".", "_loc_vec", "(", "gloc", ...
30.15
0.001606
def parse_buffer_to_jpeg(data): """ Parse JPEG file bytes to Pillow Image """ return [ Image.open(BytesIO(image_data + b'\xff\xd9')) for image_data in data.split(b'\xff\xd9')[:-1] # Last element is obviously empty ]
[ "def", "parse_buffer_to_jpeg", "(", "data", ")", ":", "return", "[", "Image", ".", "open", "(", "BytesIO", "(", "image_data", "+", "b'\\xff\\xd9'", ")", ")", "for", "image_data", "in", "data", ".", "split", "(", "b'\\xff\\xd9'", ")", "[", ":", "-", "1", ...
27.555556
0.011719
def export(zone, path=None): ''' Export the configuration from memory to stable storage. zone : string name of zone path : string path of file to export to CLI Example: .. code-block:: bash salt '*' zonecfg.export epyon salt '*' zonecfg.export epyon /zones/epy...
[ "def", "export", "(", "zone", ",", "path", "=", "None", ")", ":", "ret", "=", "{", "'status'", ":", "True", "}", "# export zone", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "'zonecfg -z {zone} export{path}'", ".", "format", "(", "zone", "=", ...
24.290323
0.001277
def is_senior_subclass(obj, cls, testcls): """Determines whether the cls is the senior subclass of basecls for obj. The most senior subclass is the first class in the mro which is a subclass of testcls. Use for inheritance schemes where a method should only be called once by the most senior subcla...
[ "def", "is_senior_subclass", "(", "obj", ",", "cls", ",", "testcls", ")", ":", "for", "base", "in", "obj", ".", "__class__", ".", "mro", "(", ")", ":", "if", "base", "is", "cls", ":", "return", "True", "else", ":", "if", "issubclass", "(", "base", ...
35.75
0.00227
def explode_azure_storage_url(url): # type: (str) -> Tuple[str, str, str, str, str] """Explode Azure Storage URL into parts :param url str: storage url :rtype: tuple :return: (sa, mode, ep, rpath, sas) """ tmp = url.split('/') host = tmp[2].split('.') sa = host[0] mode = host[1]....
[ "def", "explode_azure_storage_url", "(", "url", ")", ":", "# type: (str) -> Tuple[str, str, str, str, str]", "tmp", "=", "url", ".", "split", "(", "'/'", ")", "host", "=", "tmp", "[", "2", "]", ".", "split", "(", "'.'", ")", "sa", "=", "host", "[", "0", ...
26.421053
0.001923
def intern(cls_): """Transforms the provided class into an interned class. That is, initializing the class multiple times with the same arguments (even if in a different order if using keyword arguments) should always produce the same object, and __init__ should only be called...
[ "def", "intern", "(", "cls_", ")", ":", "cls_", ".", "__pool", "=", "{", "}", "__init__", "=", "cls_", ".", "__init__", "try", ":", "__init__", ".", "__func__", ".", "__hash_function", "except", "AttributeError", ":", "try", ":", "__init__", ".", "__func...
41.07874
0.00992
def find_similar( self, face_id, face_list_id=None, large_face_list_id=None, face_ids=None, max_num_of_candidates_returned=20, mode="matchPerson", custom_headers=None, raw=False, **operation_config): """Given query face's faceId, to search the similar-looking faces from a faceId array, a fac...
[ "def", "find_similar", "(", "self", ",", "face_id", ",", "face_list_id", "=", "None", ",", "large_face_list_id", "=", "None", ",", "face_ids", "=", "None", ",", "max_num_of_candidates_returned", "=", "20", ",", "mode", "=", "\"matchPerson\"", ",", "custom_header...
54.009346
0.001189
def eidos_process_text(): """Process text with EIDOS and return INDRA Statements.""" if request.method == 'OPTIONS': return {} req = request.body.read().decode('utf-8') body = json.loads(req) text = body.get('text') webservice = body.get('webservice') if not webservice: respo...
[ "def", "eidos_process_text", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "req", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ".", "loads", ...
38.285714
0.001821
def list_endpoints(self): """Lists the known object storage endpoints.""" _filter = { 'hubNetworkStorage': {'vendorName': {'operation': 'Swift'}}, } endpoints = [] network_storage = self.client.call('Account', 'getHubNetworkS...
[ "def", "list_endpoints", "(", "self", ")", ":", "_filter", "=", "{", "'hubNetworkStorage'", ":", "{", "'vendorName'", ":", "{", "'operation'", ":", "'Swift'", "}", "}", ",", "}", "endpoints", "=", "[", "]", "network_storage", "=", "self", ".", "client", ...
40.8
0.002395
def increase_last(self, k): """ Increase the last result by k. """ idx = self._last_idx if idx is not None: self.results[idx] += k
[ "def", "increase_last", "(", "self", ",", "k", ")", ":", "idx", "=", "self", ".", "_last_idx", "if", "idx", "is", "not", "None", ":", "self", ".", "results", "[", "idx", "]", "+=", "k" ]
26
0.010638
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
[ "def", "geometric_progression_for_stepsize", "(", "x", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", ":", "epsilon", "=", "dist", "/", "np", ".", "sqrt", "(", "current_iteration", ")", "while", "True", ":", "updated", "="...
31.3125
0.013566
def _chosen_css(self): """Read the minified CSS file including STATIC_URL in the references to the sprite images.""" css = render_to_string(self.css_template, {}) for sprite in self.chosen_sprites: # rewrite path to sprites in the css css = css.replace(sprite, settings.STATI...
[ "def", "_chosen_css", "(", "self", ")", ":", "css", "=", "render_to_string", "(", "self", ".", "css_template", ",", "{", "}", ")", "for", "sprite", "in", "self", ".", "chosen_sprites", ":", "# rewrite path to sprites in the css", "css", "=", "css", ".", "rep...
51
0.008264
def ekffld(handle, segno, rcptrs): """ Complete a fast write operation on a new E-kernel segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekffld_c.html :param handle: File handle. :type handle: int :param segno: Segment number. :type segno: int :param rcptrs: Record poi...
[ "def", "ekffld", "(", "handle", ",", "segno", ",", "rcptrs", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "segno", "=", "ctypes", ".", "c_int", "(", "segno", ")", "rcptrs", "=", "stypes", ".", "toIntVector", "(", "rcptrs", ")"...
31.388889
0.001718
def write_short_bytes(b): """ Encode a Kafka short string which contains arbitrary bytes. A short string is limited to 32767 bytes in length by the signed 16-bit length prefix. A length prefix of -1 indicates ``null``, represented as ``None`` in Python. :param bytes b: No more than 3276...
[ "def", "write_short_bytes", "(", "b", ")", ":", "if", "b", "is", "None", ":", "return", "_NULL_SHORT_STRING", "if", "not", "isinstance", "(", "b", ",", "bytes", ")", ":", "raise", "TypeError", "(", "'{!r} is not bytes'", ".", "format", "(", "b", ")", ")"...
34.285714
0.001351
def try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: string - URI of the request :param method: string - HTTP Verb :param request: request object describing the HTTP request :p...
[ "def", "try_handle_route", "(", "self", ",", "route_uri", ",", "method", ",", "request", ",", "uri", ",", "headers", ")", ":", "uri_path", "=", "route_uri", "if", "'?'", "in", "uri", ":", "logger", ".", "debug", "(", "'StackInABoxService ({0}:{1}): Found query...
49.744186
0.000917
def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str: """Equivalent to ``function_signature_for_name_and_inputs('', components)``.""" ts = [] for c in components: t: str = c['type'] if t.startswith('tuple'): assert len(t) == 5...
[ "def", "tuple_signature_for_components", "(", "components", ":", "Sequence", "[", "Mapping", "[", "str", ",", "Any", "]", "]", ")", "->", "str", ":", "ts", "=", "[", "]", "for", "c", "in", "components", ":", "t", ":", "str", "=", "c", "[", "'type'", ...
47.9
0.010246
def db_exists(name, user=None, password=None, host=None, port=None): ''' Checks if a database exists in Influxdb name Database name to create user The user to connect as password The password of the user host The host to connect to port The port t...
[ "def", "db_exists", "(", "name", ",", "user", "=", "None", ",", "password", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "dbs", "=", "db_list", "(", "user", ",", "password", ",", "host", ",", "port", ")", "if", "not"...
20.833333
0.001529
def load(self, name): """[DEPRECATED] Load the polynomial series for `name` and return it.""" s = self.sets.get(name) if s is None: self.sets[name] = s = np.load(self.path('jpl-%s.npy' % name)) return s
[ "def", "load", "(", "self", ",", "name", ")", ":", "s", "=", "self", ".", "sets", ".", "get", "(", "name", ")", "if", "s", "is", "None", ":", "self", ".", "sets", "[", "name", "]", "=", "s", "=", "np", ".", "load", "(", "self", ".", "path",...
40.166667
0.00813
def get_formset(self, request, obj=None, **kwargs): """ Return the formset, and provide the language information to the formset. """ FormSet = super(TranslatableInlineModelAdmin, self).get_formset(request, obj, **kwargs) # Existing objects already got the language code from the q...
[ "def", "get_formset", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "FormSet", "=", "super", "(", "TranslatableInlineModelAdmin", ",", "self", ")", ".", "get_formset", "(", "request", ",", "obj", ",", "*", "*"...
59.875
0.008222
def register_blueprints(app): """Register blueprints to application. Currently, Rio registered: * /api/1 * /dashboard """ from .blueprints.event import bp as event_bp app.register_blueprint(event_bp, url_prefix='/event') from .blueprints.api_1 import bp as api_1_bp app.register_b...
[ "def", "register_blueprints", "(", "app", ")", ":", "from", ".", "blueprints", ".", "event", "import", "bp", "as", "event_bp", "app", ".", "register_blueprint", "(", "event_bp", ",", "url_prefix", "=", "'/event'", ")", "from", ".", "blueprints", ".", "api_1"...
28.8
0.001681
def run_args(args): """ call the lib entry function with CLI args """ return main(filename = args.get('MDFILE') ,theme = args.get('-t', 'random') ,cols = args.get('-c') ,from_txt = args.get('-f') ,c_theme = args.get('-T...
[ "def", "run_args", "(", "args", ")", ":", "return", "main", "(", "filename", "=", "args", ".", "get", "(", "'MDFILE'", ")", ",", "theme", "=", "args", ".", "get", "(", "'-t'", ",", "'random'", ")", ",", "cols", "=", "args", ".", "get", "(", "'-c'...
45.545455
0.099804
def clear(self): "Removes all entries from the config map" self._pb.IntMap.clear() self._pb.StringMap.clear() self._pb.FloatMap.clear() self._pb.BoolMap.clear()
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_pb", ".", "IntMap", ".", "clear", "(", ")", "self", ".", "_pb", ".", "StringMap", ".", "clear", "(", ")", "self", ".", "_pb", ".", "FloatMap", ".", "clear", "(", ")", "self", ".", "_pb", "."...
32.5
0.01
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the CreateKeyPair request payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "CreateKeyPairRequestPayload", ",", "self", ")", ".", "read", "(", "input_buffer", ",", "kmip_version", "=", "kmi...
39.677083
0.000512
def _get_url_node(parser, bits): """ Parses the expression as if it was a normal url tag. Was copied from the original function django.template.defaulttags.url, but unnecessary pieces were removed. """ viewname = parser.compile_filter(bits[1]) args = [] kwargs = {} bits = bits[2:] ...
[ "def", "_get_url_node", "(", "parser", ",", "bits", ")", ":", "viewname", "=", "parser", ".", "compile_filter", "(", "bits", "[", "1", "]", ")", "args", "=", "[", "]", "kwargs", "=", "{", "}", "bits", "=", "bits", "[", "2", ":", "]", "if", "len",...
32.666667
0.001239
def _parse_error(self, error): """ Parses a single GLSL error and extracts the linenr and description Other GLIR implementations may omit this. """ error = str(error) # Nvidia # 0(7): error C1008: undefined variable "MV" m = re.match(r'(\d+)\((\d+)\)\s*:\s(.*)', e...
[ "def", "_parse_error", "(", "self", ",", "error", ")", ":", "error", "=", "str", "(", "error", ")", "# Nvidia", "# 0(7): error C1008: undefined variable \"MV\"", "m", "=", "re", ".", "match", "(", "r'(\\d+)\\((\\d+)\\)\\s*:\\s(.*)'", ",", "error", ")", "if", "m"...
37.227273
0.002381
def unwrap_state_dict(self, obj: Dict[str, Any]) -> Union[Tuple[str, Any], Tuple[None, None]]: """Unwraps a marshalled state previously wrapped using :meth:`wrap_state_dict`.""" if len(obj) == 2: typename = obj.get(self.type_key) state = obj.get(self.state_key) if typ...
[ "def", "unwrap_state_dict", "(", "self", ",", "obj", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Union", "[", "Tuple", "[", "str", ",", "Any", "]", ",", "Tuple", "[", "None", ",", "None", "]", "]", ":", "if", "len", "(", "obj", ")", ...
44
0.009901
def validate_netmask(s): """Validate that a dotted-quad ip address is a valid netmask. >>> validate_netmask('0.0.0.0') True >>> validate_netmask('128.0.0.0') True >>> validate_netmask('255.0.0.0') True >>> validate_netmask('255.255.255.255') True >>> validate_netmask(BROADCAST)...
[ "def", "validate_netmask", "(", "s", ")", ":", "if", "validate_ip", "(", "s", ")", ":", "# Convert to binary string, strip '0b' prefix, 0 pad to 32 bits", "mask", "=", "bin", "(", "ip2network", "(", "s", ")", ")", "[", "2", ":", "]", ".", "zfill", "(", "32",...
25.707317
0.000914
def _list_groups(args, _): """Lists the groups in the project.""" project_id = args['project'] pattern = args['name'] or '*' groups = gcm.Groups(project_id=project_id) dataframe = groups.as_dataframe(pattern=pattern) return _render_dataframe(dataframe)
[ "def", "_list_groups", "(", "args", ",", "_", ")", ":", "project_id", "=", "args", "[", "'project'", "]", "pattern", "=", "args", "[", "'name'", "]", "or", "'*'", "groups", "=", "gcm", ".", "Groups", "(", "project_id", "=", "project_id", ")", "datafram...
36.857143
0.026515
def with_fork_context(self, func): """See the rustdocs for `scheduler_fork_context` for more information.""" res = self._native.lib.scheduler_fork_context(self._scheduler, Function(self._to_key(func))) return self._raise_or_return(res)
[ "def", "with_fork_context", "(", "self", ",", "func", ")", ":", "res", "=", "self", ".", "_native", ".", "lib", ".", "scheduler_fork_context", "(", "self", ".", "_scheduler", ",", "Function", "(", "self", ".", "_to_key", "(", "func", ")", ")", ")", "re...
61
0.008097
def winsorize(self, min_percentile, max_percentile, mask=NotSpecified, groupby=NotSpecified): """ Construct a new factor that winsorizes the result of this factor. Winsorizing changes values ranked less than the minimum per...
[ "def", "winsorize", "(", "self", ",", "min_percentile", ",", "max_percentile", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "if", "not", "0.0", "<=", "min_percentile", "<", "max_percentile", "<=", "1.0", ":", "raise", "Bad...
36.5
0.001667
def ifadd(self, iff, addr): """ Add an interface 'iff' with provided address into routing table. Ex: ifadd('eth0', '2001:bd8:cafe:1::1/64') will add following entry into # noqa: E501 Scapy6 internal routing table: Destination Next Hop iface Def src @ ...
[ "def", "ifadd", "(", "self", ",", "iff", ",", "addr", ")", ":", "addr", ",", "plen", "=", "(", "addr", ".", "split", "(", "\"/\"", ")", "+", "[", "\"128\"", "]", ")", "[", ":", "2", "]", "addr", "=", "in6_ptop", "(", "addr", ")", "plen", "=",...
40.761905
0.002283
def send_dm_sos(self, message: str) -> None: """ Send DM to owner if something happens. :param message: message to send to owner. :returns: None. """ if self.owner_handle: try: # twitter changed the DM API and tweepy (as of 2019-03-08) ...
[ "def", "send_dm_sos", "(", "self", ",", "message", ":", "str", ")", "->", "None", ":", "if", "self", ".", "owner_handle", ":", "try", ":", "# twitter changed the DM API and tweepy (as of 2019-03-08)", "# has not adapted.", "# fixing with", "# https://github.com/tweepy/twe...
35.285714
0.001576
def mix_hash(self, data: bytes): """ Sets h = HASH(h + data). :param data: bytes sequence """ self.h = self.noise_protocol.hash_fn.hash(self.h + data)
[ "def", "mix_hash", "(", "self", ",", "data", ":", "bytes", ")", ":", "self", ".", "h", "=", "self", ".", "noise_protocol", ".", "hash_fn", ".", "hash", "(", "self", ".", "h", "+", "data", ")" ]
27.285714
0.010152
def aggregation_postprocessors_extractor(impact_report, component_metadata): """Extracting aggregate result of demographic. :param impact_report: the impact report that acts as a proxy to fetch all the data that extractor needed :type impact_report: safe.report.impact_report.ImpactReport :para...
[ "def", "aggregation_postprocessors_extractor", "(", "impact_report", ",", "component_metadata", ")", ":", "context", "=", "{", "'sections'", ":", "OrderedDict", "(", ")", "}", "\"\"\"Initializations.\"\"\"", "extra_args", "=", "component_metadata", ".", "extra_args", "#...
35.238434
0.000098
def write (self, s): """Process text, writing it to the virtual screen while handling ANSI escape codes. """ if isinstance(s, bytes): s = self._decode(s) for c in s: self.process(c)
[ "def", "write", "(", "self", ",", "s", ")", ":", "if", "isinstance", "(", "s", ",", "bytes", ")", ":", "s", "=", "self", ".", "_decode", "(", "s", ")", "for", "c", "in", "s", ":", "self", ".", "process", "(", "c", ")" ]
29.75
0.012245
def record_sets(self): """Instance depends on the API version: * 2016-04-01: :class:`RecordSetsOperations<azure.mgmt.dns.v2016_04_01.operations.RecordSetsOperations>` * 2018-03-01-preview: :class:`RecordSetsOperations<azure.mgmt.dns.v2018_03_01_preview.operations.RecordSetsOperations>` ...
[ "def", "record_sets", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'record_sets'", ")", "if", "api_version", "==", "'2016-04-01'", ":", "from", ".", "v2016_04_01", ".", "operations", "import", "RecordSetsOperations", "as", "O...
67.117647
0.008643
def create(lr, betas=(0.9, 0.999), weight_decay=0, epsilon=1e-8, layer_groups=False): """ Vel factory function """ return AdamFactory(lr=lr, betas=betas, weight_decay=weight_decay, eps=epsilon, layer_groups=layer_groups)
[ "def", "create", "(", "lr", ",", "betas", "=", "(", "0.9", ",", "0.999", ")", ",", "weight_decay", "=", "0", ",", "epsilon", "=", "1e-8", ",", "layer_groups", "=", "False", ")", ":", "return", "AdamFactory", "(", "lr", "=", "lr", ",", "betas", "=",...
75.333333
0.013158
def submit_snl(self, snl): """ Submits a list of StructureNL to the Materials Project site. .. note:: As of now, this MP REST feature is open only to a select group of users. Opening up submissions to all users is being planned for the future. Args:...
[ "def", "submit_snl", "(", "self", ",", "snl", ")", ":", "try", ":", "snl", "=", "snl", "if", "isinstance", "(", "snl", ",", "list", ")", "else", "[", "snl", "]", "jsondata", "=", "[", "s", ".", "as_dict", "(", ")", "for", "s", "in", "snl", "]",...
36.125
0.001348
def dovandamme(vgp_df): """ determine the S_b value for VGPs using the Vandamme (1994) method for determining cutoff value for "outliers". Parameters ___________ vgp_df : pandas DataFrame with required column "vgp_lat" This should be in the desired coordinate system and assumes one ...
[ "def", "dovandamme", "(", "vgp_df", ")", ":", "vgp_df", "[", "'delta'", "]", "=", "90.", "-", "vgp_df", "[", "'vgp_lat'", "]", ".", "values", "ASD", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "vgp_df", ".", "delta", "**", "2", ")", "/", ...
34.269231
0.002183
def hist(data, cmap='hot', alpha=220, colorscale='sqrt', binsize=16, show_tooltip=False, scalemin=0, scalemax=None, f_group=None, show_colorbar=True): """Create a 2D histogram :param data: data access object :param cmap: colormap name :param alpha: color alpha :param colorscale: scaling [l...
[ "def", "hist", "(", "data", ",", "cmap", "=", "'hot'", ",", "alpha", "=", "220", ",", "colorscale", "=", "'sqrt'", ",", "binsize", "=", "16", ",", "show_tooltip", "=", "False", ",", "scalemin", "=", "0", ",", "scalemax", "=", "None", ",", "f_group", ...
53.263158
0.008738
def equalizeImage(img, save_path=None, name_additive='_eqHist'): ''' Equalize the histogram (contrast) of an image works with RGB/multi-channel images and flat-arrays @param img - image_path or np.array @param save_path if given output images will be saved there @param name_additiv...
[ "def", "equalizeImage", "(", "img", ",", "save_path", "=", "None", ",", "name_additive", "=", "'_eqHist'", ")", ":", "if", "isinstance", "(", "img", ",", "string_types", ")", ":", "img", "=", "PathStr", "(", "img", ")", "if", "not", "img", ".", "exists...
35.243243
0.002239
def parse_geo_box(geo_box_str): """ parses [-90,-180 TO 90,180] to a shapely.geometry.box :param geo_box_str: :return: """ from_point_str, to_point_str = parse_solr_geo_range_as_pair(geo_box_str) from_point = parse_lat_lon(from_point_str) to_point = parse_lat_lon(to_point_str) recta...
[ "def", "parse_geo_box", "(", "geo_box_str", ")", ":", "from_point_str", ",", "to_point_str", "=", "parse_solr_geo_range_as_pair", "(", "geo_box_str", ")", "from_point", "=", "parse_lat_lon", "(", "from_point_str", ")", "to_point", "=", "parse_lat_lon", "(", "to_point_...
33
0.002457
def parse_email(data, strip_attachment_payloads=False): """ A simplified email parser Args: data: The RFC 822 message string, or MSG binary strip_attachment_payloads (bool): Remove attachment payloads Returns (dict): Parsed email data """ if type(data) == bytes: if is_...
[ "def", "parse_email", "(", "data", ",", "strip_attachment_payloads", "=", "False", ")", ":", "if", "type", "(", "data", ")", "==", "bytes", ":", "if", "is_outlook_msg", "(", "data", ")", ":", "data", "=", "convert_outlook_msg", "(", "data", ")", "data", ...
35.759615
0.000262
def Mu(i, j, s, N, excluded_mu=[]): """This function calculates the global index mu for the element i, j. It returns the index for the real part if s=0 and the one for the imaginary part if s=1. """ if i == j: if s == -1: if i == 1: return 0 else: ...
[ "def", "Mu", "(", "i", ",", "j", ",", "s", ",", "N", ",", "excluded_mu", "=", "[", "]", ")", ":", "if", "i", "==", "j", ":", "if", "s", "==", "-", "1", ":", "if", "i", "==", "1", ":", "return", "0", "else", ":", "mes", "=", "'There is no ...
32.384615
0.001153
def gradients_X(self, dL_dK, X, X2, target): """Derivative of the covariance matrix with respect to X.""" if X2==None or X2 is X: dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1] self.dKdiag_dX(dL_dKdiag, X, target)
[ "def", "gradients_X", "(", "self", ",", "dL_dK", ",", "X", ",", "X2", ",", "target", ")", ":", "if", "X2", "==", "None", "or", "X2", "is", "X", ":", "dL_dKdiag", "=", "dL_dK", ".", "flat", "[", ":", ":", "dL_dK", ".", "shape", "[", "0", "]", ...
49
0.016064
def hessian(self, x, y, center_x = 0, center_y = 0, **kwargs): """ returns Hessian matrix of function d^2f/dx^2, d^f/dy^2, d^2/dxdy (un-normalized!!!) interpolated from the numerical deflection table """ diff = 1e-6 alpha_ra, alpha_dec = self.derivatives(x, y, center_x =...
[ "def", "hessian", "(", "self", ",", "x", ",", "y", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ",", "*", "*", "kwargs", ")", ":", "diff", "=", "1e-6", "alpha_ra", ",", "alpha_dec", "=", "self", ".", "derivatives", "(", "x", ",", "y", ...
41.75
0.022439
def generateSummaryHTMLTable(self, extraLapse = TYPICAL_LAPSE): '''Generates a summary in HTML of the status of the expected scripts broken based on the log. This summary is returned as a list of strings. ''' scriptsRun = self.scriptsRun html = [] html.append("<table style='text-align:center;border:1px...
[ "def", "generateSummaryHTMLTable", "(", "self", ",", "extraLapse", "=", "TYPICAL_LAPSE", ")", ":", "scriptsRun", "=", "self", ".", "scriptsRun", "html", "=", "[", "]", "html", ".", "append", "(", "\"<table style='text-align:center;border:1px solid black;margin-left: aut...
40.569444
0.032754
def _to_bstr(l): """Convert to byte string.""" if isinstance(l, str): l = l.encode('ascii', 'backslashreplace') elif not isinstance(l, bytes): l = str(l).encode('ascii', 'backslashreplace') return l
[ "def", "_to_bstr", "(", "l", ")", ":", "if", "isinstance", "(", "l", ",", "str", ")", ":", "l", "=", "l", ".", "encode", "(", "'ascii'", ",", "'backslashreplace'", ")", "elif", "not", "isinstance", "(", "l", ",", "bytes", ")", ":", "l", "=", "str...
28
0.017316
def getSets(self): """ Get all the sets declared. """ sets = lock_and_call( lambda: self._impl.getSets(), self._lock ) return EntityMap(sets, Set)
[ "def", "getSets", "(", "self", ")", ":", "sets", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getSets", "(", ")", ",", "self", ".", "_lock", ")", "return", "EntityMap", "(", "sets", ",", "Set", ")" ]
23.333333
0.009174
def abfProtocol(fname): """Determine the protocol used to record an ABF file""" f=open(fname,'rb') raw=f.read(30*1000) #it should be in the first 30k of the file f.close() raw=raw.decode("utf-8","ignore") raw=raw.split("Clampex")[1].split(".pro")[0] protocol = os.path.basename(raw) # the who...
[ "def", "abfProtocol", "(", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "'rb'", ")", "raw", "=", "f", ".", "read", "(", "30", "*", "1000", ")", "#it should be in the first 30k of the file", "f", ".", "close", "(", ")", "raw", "=", "raw", "...
41.7
0.025822
def missing_revisions(self, doc_id, *revisions): """ Returns a list of document revision values that do not exist in the current remote database for the specified document id and specified list of revision values. :param str doc_id: Document id to check for missing revisions aga...
[ "def", "missing_revisions", "(", "self", ",", "doc_id", ",", "*", "revisions", ")", ":", "url", "=", "'/'", ".", "join", "(", "(", "self", ".", "database_url", ",", "'_missing_revs'", ")", ")", "data", "=", "{", "doc_id", ":", "list", "(", "revisions",...
35.071429
0.001982
def stop(self): """Stops the context. This terminates all PIDs and closes all connections.""" log.info('Stopping %s' % self) pids = list(self._processes) # Clean up the context for pid in pids: self.terminate(pid) while self._connections: pid = next(iter(self._connections)) ...
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping %s'", "%", "self", ")", "pids", "=", "list", "(", "self", ".", "_processes", ")", "# Clean up the context", "for", "pid", "in", "pids", ":", "self", ".", "terminate", "(", "pid",...
22.444444
0.014252
def get(self, uri, query=None, **kwargs): """make a GET request""" return self.fetch('get', uri, query, **kwargs)
[ "def", "get", "(", "self", ",", "uri", ",", "query", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "fetch", "(", "'get'", ",", "uri", ",", "query", ",", "*", "*", "kwargs", ")" ]
42.333333
0.015504
def _lookup_attributes(glyph_name, data): """Look up glyph attributes in data by glyph name, alternative name or production name in order or return empty dictionary. Look up by alternative and production names for legacy projects and because of issue #232. """ attributes = ( data.names....
[ "def", "_lookup_attributes", "(", "glyph_name", ",", "data", ")", ":", "attributes", "=", "(", "data", ".", "names", ".", "get", "(", "glyph_name", ")", "or", "data", ".", "alternative_names", ".", "get", "(", "glyph_name", ")", "or", "data", ".", "produ...
33.071429
0.002101
def loader(schema, validator=CerberusValidator, update=None): """Create a load function based on schema dict and Validator class. :param schema: a Cerberus schema dict. :param validator: the validator class which must be a subclass of more.cerberus.CerberusValidator which is the default. :param...
[ "def", "loader", "(", "schema", ",", "validator", "=", "CerberusValidator", ",", "update", "=", "None", ")", ":", "if", "not", "issubclass", "(", "validator", ",", "CerberusValidator", ")", ":", "raise", "TypeError", "(", "\"Validator must be a subclass of more.ce...
46.409091
0.00096
def add_point_light(self, position, radius): """Add point light""" self.point_lights.append(PointLight(position, radius))
[ "def", "add_point_light", "(", "self", ",", "position", ",", "radius", ")", ":", "self", ".", "point_lights", ".", "append", "(", "PointLight", "(", "position", ",", "radius", ")", ")" ]
45
0.014599
def _maybe_check_valid_shape(shape, validate_args): """Check that a shape Tensor is int-type and otherwise sane.""" if not dtype_util.is_integer(shape.dtype): raise TypeError('{} dtype ({}) should be `int`-like.'.format( shape, dtype_util.name(shape.dtype))) assertions = [] message = '`{}` rank sh...
[ "def", "_maybe_check_valid_shape", "(", "shape", ",", "validate_args", ")", ":", "if", "not", "dtype_util", ".", "is_integer", "(", "shape", ".", "dtype", ")", ":", "raise", "TypeError", "(", "'{} dtype ({}) should be `int`-like.'", ".", "format", "(", "shape", ...
34.567568
0.013688
def addFileAnnot(self, point, buffer, filename, ufilename=None, desc=None): """Add a 'FileAttachment' annotation at location 'point'.""" CheckParent(self) val = _fitz.Page_addFileAnnot(self, point, buffer, filename, ufilename, desc) if not val: return val.thisown = True ...
[ "def", "addFileAnnot", "(", "self", ",", "point", ",", "buffer", ",", "filename", ",", "ufilename", "=", "None", ",", "desc", "=", "None", ")", ":", "CheckParent", "(", "self", ")", "val", "=", "_fitz", ".", "Page_addFileAnnot", "(", "self", ",", "poin...
33.5
0.009685
def generate_automodsumm_docs(lines, srcfn, suffix='.rst', warn=None, info=None, base_path=None, builder=None, template_dir=None): """ This function is adapted from `sphinx.ext.autosummary.generate.generate_autosummmary_docs` to generate source...
[ "def", "generate_automodsumm_docs", "(", "lines", ",", "srcfn", ",", "suffix", "=", "'.rst'", ",", "warn", "=", "None", ",", "info", "=", "None", ",", "base_path", "=", "None", ",", "builder", "=", "None", ",", "template_dir", "=", "None", ")", ":", "f...
40.809955
0.001191
def sessionless_data(self, data, sockaddr): """Examines unsolocited packet and decides appropriate action. For a listening IpmiServer, a packet without an active session comes here for examination. If it is something that is utterly sessionless (e.g. get channel authentication), send t...
[ "def", "sessionless_data", "(", "self", ",", "data", ",", "sockaddr", ")", ":", "if", "len", "(", "data", ")", "<", "22", ":", "return", "data", "=", "bytearray", "(", "data", ")", "if", "not", "(", "data", "[", "0", "]", "==", "6", "and", "data"...
47.111111
0.000924
def create_remoteckan(cls, site_url, user_agent=None, user_agent_config_yaml=None, user_agent_lookup=None, session=None, **kwargs): # type: (str, Optional[str], Optional[str], Optional[str], requests.Session, Any) -> ckanapi.RemoteCKAN """ Create remote CKAN instance fr...
[ "def", "create_remoteckan", "(", "cls", ",", "site_url", ",", "user_agent", "=", "None", ",", "user_agent_config_yaml", "=", "None", ",", "user_agent_lookup", "=", "None", ",", "session", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# type: (str, Optional[...
58.107143
0.008464
def status(name, *args, **kwargs): ''' Return the status for a service. If the name contains globbing, a dict mapping service name to True/False values is returned. .. versionchanged:: 2018.3.0 The service name can now be a glob (e.g. ``salt*``) Args: name (str): The name of th...
[ "def", "status", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "results", "=", "{", "}", "all_services", "=", "get_all", "(", ")", "contains_globbing", "=", "bool", "(", "re", ".", "search", "(", "r'\\*|\\?|\\[.+\\]'", ",", "name", ...
26.971429
0.002045