text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.""" # Override for avoid using sys.excepthook PY-12600 type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and typ...
[ "def", "showsyntaxerror", "(", "self", ",", "filename", "=", "None", ")", ":", "# Override for avoid using sys.excepthook PY-12600", "type", ",", "value", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "sys", ".", "last_type", "=", "type", "sys", ".", "la...
43.4
0.002255
def order_target_percent(self, asset, target, limit_price=None, stop_price=None, style=None): """Place an order to adjust a position to a target percent of the current portfolio value. If the position doesn't already exist, this is equivalent to placing a new order. ...
[ "def", "order_target_percent", "(", "self", ",", "asset", ",", "target", ",", "limit_price", "=", "None", ",", "stop_price", "=", "None", ",", "style", "=", "None", ")", ":", "if", "not", "self", ".", "_can_order_asset", "(", "asset", ")", ":", "return",...
36.766667
0.001325
def decodekey(self, key): """ splits a key in a tuple, one of: ( [ 'N', 'n', '$' ], 0, bignameid ) ( [ 'N', 'n', '$' ], name ) ( '-', id ) ( '.', id ) ( '.', id, tag ) ( '.', id, tag, value ) ( '.', id, 'H...
[ "def", "decodekey", "(", "self", ",", "key", ")", ":", "if", "key", "[", ":", "1", "]", "in", "(", "b'n'", ",", "b'N'", ",", "b'$'", ")", ":", "if", "key", "[", "1", ":", "2", "]", "==", "b\"\\x00\"", "and", "len", "(", "key", ")", "==", "2...
41.928571
0.001665
def plot(self,*args,**kwargs): """ NAME: plot PURPOSE: plot the snapshot INPUT: OUTPUT: HISTORY: 2011-08-15 - Started - Bovy (NYU) """ labeldict= {'t':r'$t$','R':r'$R$','vR':r'$v_R$','vT':r'$v_T$', ...
[ "def", "plot", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "labeldict", "=", "{", "'t'", ":", "r'$t$'", ",", "'R'", ":", "r'$R$'", ",", "'vR'", ":", "r'$v_R$'", ",", "'vT'", ":", "r'$v_T$'", ",", "'z'", ":", "r'$z$'", ",", ...
29.790698
0.032502
def _run_queued_callbacks(self): ''' run the init/quued calback when the trasnfer is initiated on apsera ''' for callback in self._queued_callbacks: try: callback() except Exception as ex: logger.error("Exception: %s" % str(ex))
[ "def", "_run_queued_callbacks", "(", "self", ")", ":", "for", "callback", "in", "self", ".", "_queued_callbacks", ":", "try", ":", "callback", "(", ")", "except", "Exception", "as", "ex", ":", "logger", ".", "error", "(", "\"Exception: %s\"", "%", "str", "...
42
0.01
def file_md5(self, file_name): """Compute MD5 hash of file.""" file_contents = self._read_file(file_name) file_contents = file_contents + "\n" # Cisco IOS automatically adds this file_contents = file_contents.encode("UTF-8") return hashlib.md5(file_contents).hexdigest()
[ "def", "file_md5", "(", "self", ",", "file_name", ")", ":", "file_contents", "=", "self", ".", "_read_file", "(", "file_name", ")", "file_contents", "=", "file_contents", "+", "\"\\n\"", "# Cisco IOS automatically adds this", "file_contents", "=", "file_contents", "...
51
0.009646
async def begin(request: web.Request) -> web.Response: """ Begin a session """ if None is not session_from_request(request): LOG.warning("begin: requested with active session") return web.json_response( data={'message': 'An update session is already active on th...
[ "async", "def", "begin", "(", "request", ":", "web", ".", "Request", ")", "->", "web", ".", "Response", ":", "if", "None", "is", "not", "session_from_request", "(", "request", ")", ":", "LOG", ".", "warning", "(", "\"begin: requested with active session\"", ...
38.470588
0.001493
def dict_union3(dict1, dict2, combine_op=op.add): r""" Args: dict1 (dict): dict2 (dict): combine_op (func): (default=op.add) Returns: dict: mergedict_ CommandLine: python -m utool.util_dict --exec-dict_union3 Example: >>> # ENABLE_DOCTEST >>...
[ "def", "dict_union3", "(", "dict1", ",", "dict2", ",", "combine_op", "=", "op", ".", "add", ")", ":", "keys1", "=", "set", "(", "dict1", ".", "keys", "(", ")", ")", "keys2", "=", "set", "(", "dict2", ".", "keys", "(", ")", ")", "# Combine common ke...
33.236842
0.001538
def adjustUncertToExposureTime(facExpTime, uncertMap, evtLenMap): ''' Adjust image uncertainty (measured at exposure time t0) to new exposure time facExpTime --> new exp.time / reference exp.time =(t/t0) uncertMap --> 2d array mapping image uncertainty evtLen --> 2d array mappi...
[ "def", "adjustUncertToExposureTime", "(", "facExpTime", ",", "uncertMap", ",", "evtLenMap", ")", ":", "#fit parameters, obtained from ####[simulateUncertDependencyOnExpTime]\r", "params", "=", "np", ".", "array", "(", "#a facExpTime f_0 f_inf ...
48.02
0.013878
def set_time(filename, mod_time): """ Set the modified time of a file """ log.debug('Setting modified time to %s', mod_time) mtime = calendar.timegm(mod_time.utctimetuple()) # utctimetuple discards microseconds, so restore it (for consistency) mtime += mod_time.microsecond / 1000000 atime = os.stat(file...
[ "def", "set_time", "(", "filename", ",", "mod_time", ")", ":", "log", ".", "debug", "(", "'Setting modified time to %s'", ",", "mod_time", ")", "mtime", "=", "calendar", ".", "timegm", "(", "mod_time", ".", "utctimetuple", "(", ")", ")", "# utctimetuple discar...
36.2
0.026954
def parse_limits_file(path): """Parse a file as a list of reaction flux limits The file format is detected and the file is parsed accordingly. Path can be given as a string or a context. """ context = FilePathContext(path) format = resolve_format(None, context.filepath) if format == 'tsv'...
[ "def", "parse_limits_file", "(", "path", ")", ":", "context", "=", "FilePathContext", "(", "path", ")", "format", "=", "resolve_format", "(", "None", ",", "context", ".", "filepath", ")", "if", "format", "==", "'tsv'", ":", "logger", ".", "debug", "(", "...
34.84
0.001117
def _R2deriv(self,R,z,phi=0.,t=0.): """ NAME: _Rforce PURPOSE: evaluate the second radial derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time ...
[ "def", "_R2deriv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_denom", "(", "R", ",", "z", ")", "**", "-", "1.5", "-", "3.", "*", "R", "**", "2", "*", "self", ".", "_deno...
29.411765
0.013566
def ensure_dict_key_title(dict_obj): """Set the dict key as key.title(); keys should be str. Always be used to headers. >>> from torequests.utils import ensure_dict_key_title >>> ensure_dict_key_title({'hello-world':1, 'HELLOWORLD':2}) {'Hello-World': 1, 'Helloworld': 2} """ if ...
[ "def", "ensure_dict_key_title", "(", "dict_obj", ")", ":", "if", "not", "all", "(", "(", "isinstance", "(", "i", ",", "unicode", ")", "for", "i", "in", "dict_obj", ".", "keys", "(", ")", ")", ")", ":", "return", "dict_obj", "return", "{", "key", ".",...
41.818182
0.002128
def get_ports(port, like=False): """ This function creates the SQL query depending on the specified port and the --like option. :param port: the specified port :param like: the --like option :return: all ports matching the given ``port`` :rtype: list """ where_field = "port" if port...
[ "def", "get_ports", "(", "port", ",", "like", "=", "False", ")", ":", "where_field", "=", "\"port\"", "if", "port", ".", "isdigit", "(", ")", "else", "\"name\"", "if", "like", ":", "ports", "=", "__DB__", ".", "search", "(", "where", "(", "where_field"...
30.294118
0.001883
def _set_class_parser(self, init_parser, methods_to_parse, cls): """Creates the complete argument parser for the decorated class. Args: init_parser: argument parser for the __init__ method or None methods_to_parse: dict of method name pointing to their associated arg...
[ "def", "_set_class_parser", "(", "self", ",", "init_parser", ",", "methods_to_parse", ",", "cls", ")", ":", "top_level_parents", "=", "[", "init_parser", "]", "if", "init_parser", "else", "[", "]", "description", "=", "self", ".", "_description", "or", "cls", ...
52
0.001302
def get_firmware(self): """ Gets the installed firmware for a logical interconnect. Returns: dict: LIFirmware. """ firmware_uri = self._helper.build_subresource_uri(self.data["uri"], subresource_path=self.FIRMWARE_PATH) return self._helper.do_get(firmware_uri...
[ "def", "get_firmware", "(", "self", ")", ":", "firmware_uri", "=", "self", ".", "_helper", ".", "build_subresource_uri", "(", "self", ".", "data", "[", "\"uri\"", "]", ",", "subresource_path", "=", "self", ".", "FIRMWARE_PATH", ")", "return", "self", ".", ...
34.777778
0.009346
def _sieve(self, multiple_records): """Return json object without multiple returns per resolved name.\ Names with multiple records are reduced by finding the name in the clade of\ interest, have the highest score, have the lowest taxonomic rank (if lowrank is true) and/or are the first item returned.""" ...
[ "def", "_sieve", "(", "self", ",", "multiple_records", ")", ":", "# TODO: Break up, too complex", "GnrStore", "=", "self", ".", "_store", "def", "writeAsJson", "(", "term", ",", "results", ")", ":", "record", "=", "{", "'supplied_name_string'", ":", "term", "}...
46
0.001663
def has_rotational(self): """Return true if any of the drive is HDD""" for member in self._drives_list(): if member.media_type == constants.MEDIA_TYPE_HDD: return True return False
[ "def", "has_rotational", "(", "self", ")", ":", "for", "member", "in", "self", ".", "_drives_list", "(", ")", ":", "if", "member", ".", "media_type", "==", "constants", ".", "MEDIA_TYPE_HDD", ":", "return", "True", "return", "False" ]
37.833333
0.008621
def FlowAccumFromProps( props, weights = None, in_place = False ): """Calculates flow accumulation from flow proportions. Args: props (rdarray): An elevation model weights (rdarray): Flow accumulation weights to use. This is the amount of flow generated ...
[ "def", "FlowAccumFromProps", "(", "props", ",", "weights", "=", "None", ",", "in_place", "=", "False", ")", ":", "if", "type", "(", "props", ")", "is", "not", "rd3array", ":", "raise", "Exception", "(", "\"A richdem.rd3array or numpy.ndarray is required!\"", ")"...
35.857143
0.017729
def delete(context, resource, id, **kwargs): """Delete a specific resource""" etag = kwargs.pop('etag', None) id = id subresource = kwargs.pop('subresource', None) subresource_id = kwargs.pop('subresource_id', None) uri = '%s/%s/%s' % (context.dci_cs_api, resource, id) if subresource: ...
[ "def", "delete", "(", "context", ",", "resource", ",", "id", ",", "*", "*", "kwargs", ")", ":", "etag", "=", "kwargs", ".", "pop", "(", "'etag'", ",", "None", ")", "id", "=", "id", "subresource", "=", "kwargs", ".", "pop", "(", "'subresource'", ","...
32.933333
0.001969
def _getIndexCascade(self): """ Find out if this signal is something indexed """ try: # now I am result of the index xxx[xx] <= source # get index op d = self.singleDriver() try: op = d.operator except Attribute...
[ "def", "_getIndexCascade", "(", "self", ")", ":", "try", ":", "# now I am result of the index xxx[xx] <= source", "# get index op", "d", "=", "self", ".", "singleDriver", "(", ")", "try", ":", "op", "=", "d", ".", "operator", "except", "AttributeError", ":", "r...
32.8
0.00237
def move_examples(root, lib_dir): """find examples not under lib dir, and move into ``examples``""" all_pde = files_multi_pattern(root, INO_PATTERNS) lib_pde = files_multi_pattern(lib_dir, INO_PATTERNS) stray_pde = all_pde.difference(lib_pde) if len(stray_pde) and not len(lib_pde): log.debug...
[ "def", "move_examples", "(", "root", ",", "lib_dir", ")", ":", "all_pde", "=", "files_multi_pattern", "(", "root", ",", "INO_PATTERNS", ")", "lib_pde", "=", "files_multi_pattern", "(", "lib_dir", ",", "INO_PATTERNS", ")", "stray_pde", "=", "all_pde", ".", "dif...
40.071429
0.001742
def query(self): """Group the self.special_coverages queries and memoize them.""" if not self._query: self._query.update({ "excluded_ids": [], "included_ids": [], "pinned_ids": [], "groups": [], }) for sp...
[ "def", "query", "(", "self", ")", ":", "if", "not", "self", ".", "_query", ":", "self", ".", "_query", ".", "update", "(", "{", "\"excluded_ids\"", ":", "[", "]", ",", "\"included_ids\"", ":", "[", "]", ",", "\"pinned_ids\"", ":", "[", "]", ",", "\...
45.157895
0.002283
def show_dscp_marking_rule(self, rule, policy, body=None): """Shows information of a certain DSCP marking rule.""" return self.get(self.qos_dscp_marking_rule_path % (policy, rule), body=body)
[ "def", "show_dscp_marking_rule", "(", "self", ",", "rule", ",", "policy", ",", "body", "=", "None", ")", ":", "return", "self", ".", "get", "(", "self", ".", "qos_dscp_marking_rule_path", "%", "(", "policy", ",", "rule", ")", ",", "body", "=", "body", ...
57
0.008658
def history_mean(self, nb=5): """Return the mean on the <nb> values in the history. """ _, v = zip(*self._history) return sum(v[-nb:]) / float(v[-1] - v[-nb])
[ "def", "history_mean", "(", "self", ",", "nb", "=", "5", ")", ":", "_", ",", "v", "=", "zip", "(", "*", "self", ".", "_history", ")", "return", "sum", "(", "v", "[", "-", "nb", ":", "]", ")", "/", "float", "(", "v", "[", "-", "1", "]", "-...
37.2
0.010526
def classical_risk(riskinputs, riskmodel, param, monitor): """ Compute and return the average losses for each asset. :param riskinputs: :class:`openquake.risklib.riskinput.RiskInput` objects :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param ...
[ "def", "classical_risk", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "result", "=", "dict", "(", "loss_curves", "=", "[", "]", ",", "stat_curves", "=", "[", "]", ")", "weights", "=", "[", "w", "[", "'default'", "]", "...
43.638298
0.001431
def list_namespaced_network_policy(self, namespace, **kwargs): # noqa: E501 """list_namespaced_network_policy # noqa: E501 list or watch objects of kind NetworkPolicy # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pa...
[ "def", "list_namespaced_network_policy", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ...
163.666667
0.000405
def create_logger(name, format='%(levelname)s: %(message)s', datefmt=None, stream=None, level=logging.INFO, filename=None, filemode='w', filelevel=None, propagate=True): """ Do basic configuration for the logging system. Similar to logging.basicConfig but the logger ``nam...
[ "def", "create_logger", "(", "name", ",", "format", "=", "'%(levelname)s: %(message)s'", ",", "datefmt", "=", "None", ",", "stream", "=", "None", ",", "level", "=", "logging", ".", "INFO", ",", "filename", "=", "None", ",", "filemode", "=", "'w'", ",", "...
37.711864
0.000438
def impute_and_confidence(self, M_c, X_L, X_D, Y, Q, seed, n): """Impute values and confidence of the value from the predictive distribution of the given latent state. :param Y: A list of constraints to apply when sampling. Each constraint is a triplet of (r, d, v): r is the row in...
[ "def", "impute_and_confidence", "(", "self", ",", "M_c", ",", "X_L", ",", "X_D", ",", "Y", ",", "Q", ",", "seed", ",", "n", ")", ":", "get_next_seed", "=", "make_get_next_seed", "(", "seed", ")", "if", "isinstance", "(", "X_L", ",", "(", "list", ",",...
47.137931
0.002151
def rotate_vector(evecs, old_vector, rescale_factor, index): """ Function to find the position of the system(s) in one of the xi_i or mu_i directions. Parameters ----------- evecs : numpy.matrix Matrix of the eigenvectors of the metric in lambda_i coordinates. Used to rotate to ...
[ "def", "rotate_vector", "(", "evecs", ",", "old_vector", ",", "rescale_factor", ",", "index", ")", ":", "temp", "=", "0", "for", "i", "in", "range", "(", "len", "(", "evecs", ")", ")", ":", "temp", "+=", "(", "evecs", "[", "i", ",", "index", "]", ...
34.666667
0.002079
def from_conll(this_class, text): """Construct a Token from a line in CoNLL-X format.""" fields = text.split('\t') fields[0] = int(fields[0]) # index fields[6] = int(fields[6]) # head index if fields[5] != '_': # feats fields[5] = tuple(fields[5].split('|')) f...
[ "def", "from_conll", "(", "this_class", ",", "text", ")", ":", "fields", "=", "text", ".", "split", "(", "'\\t'", ")", "fields", "[", "0", "]", "=", "int", "(", "fields", "[", "0", "]", ")", "# index", "fields", "[", "6", "]", "=", "int", "(", ...
47.7
0.012346
def vq_discrete_bottleneck(x, hparams): """Simple vector quantized discrete bottleneck.""" tf.logging.info("Using EMA with beta = {}".format(hparams.beta)) bottleneck_size = 2**hparams.bottleneck_bits x_shape = common_layers.shape_list(x) x = tf.reshape(x, [-1, hparams.hidden_size]) x_means_hot, e_loss = vq...
[ "def", "vq_discrete_bottleneck", "(", "x", ",", "hparams", ")", ":", "tf", ".", "logging", ".", "info", "(", "\"Using EMA with beta = {}\"", ".", "format", "(", "hparams", ".", "beta", ")", ")", "bottleneck_size", "=", "2", "**", "hparams", ".", "bottleneck_...
40.25
0.014151
def smooth_cuboid(space, min_pt=None, max_pt=None, axis=0): """Cuboid with smooth variations. Parameters ---------- space : `DiscreteLp` Discretized space in which the phantom is supposed to be created. min_pt : array-like of shape ``(space.ndim,)``, optional Lower left corner of th...
[ "def", "smooth_cuboid", "(", "space", ",", "min_pt", "=", "None", ",", "max_pt", "=", "None", ",", "axis", "=", "0", ")", ":", "dom_min_pt", "=", "space", ".", "domain", ".", "min", "(", ")", "dom_max_pt", "=", "space", ".", "domain", ".", "max", "...
34.20339
0.000482
def id_unique(dict_id, name, lineno): """Returns True if dict_id not already used. Otherwise, invokes error""" if dict_id in name_dict: global error_occurred error_occurred = True print( "ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}" .format(...
[ "def", "id_unique", "(", "dict_id", ",", "name", ",", "lineno", ")", ":", "if", "dict_id", "in", "name_dict", ":", "global", "error_occurred", "error_occurred", "=", "True", "print", "(", "\"ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}\"", ".", "f...
36.727273
0.002415
def input_dim(self): """ Extracts the input dimension of the domain. """ n_cont = len(self.get_continuous_dims()) n_disc = len(self.get_discrete_dims()) return n_cont + n_disc
[ "def", "input_dim", "(", "self", ")", ":", "n_cont", "=", "len", "(", "self", ".", "get_continuous_dims", "(", ")", ")", "n_disc", "=", "len", "(", "self", ".", "get_discrete_dims", "(", ")", ")", "return", "n_cont", "+", "n_disc" ]
31
0.008969
def is_transition_allowed(constraint_type: str, from_tag: str, from_entity: str, to_tag: str, to_entity: str): """ Given a constraint type and strings ``from_tag`` and ``to_tag`` that represent the origin...
[ "def", "is_transition_allowed", "(", "constraint_type", ":", "str", ",", "from_tag", ":", "str", ",", "from_entity", ":", "str", ",", "to_tag", ":", "str", ",", "to_entity", ":", "str", ")", ":", "# pylint: disable=too-many-return-statements", "if", "to_tag", "=...
42.065217
0.001515
def convert_nonParametricSeismicSource(self, node): """ Convert the given node into a non parametric source object. :param node: a node with tag areaGeometry :returns: a :class:`openquake.hazardlib.source.NonParametricSeismicSource` instance "...
[ "def", "convert_nonParametricSeismicSource", "(", "self", ",", "node", ")", ":", "trt", "=", "node", ".", "attrib", ".", "get", "(", "'tectonicRegion'", ")", "rup_pmf_data", "=", "[", "]", "rups_weights", "=", "None", "if", "'rup_weights'", "in", "node", "."...
41.423077
0.001815
def to_bb(YY, y="deprecated"): """Convert mask YY to a bounding box, assumes 0 as background nonzero object""" cols,rows = np.nonzero(YY) if len(cols)==0: return np.zeros(4, dtype=np.float32) top_row = np.min(rows) left_col = np.min(cols) bottom_row = np.max(rows) right_col = np.max(cols) ...
[ "def", "to_bb", "(", "YY", ",", "y", "=", "\"deprecated\"", ")", ":", "cols", ",", "rows", "=", "np", ".", "nonzero", "(", "YY", ")", "if", "len", "(", "cols", ")", "==", "0", ":", "return", "np", ".", "zeros", "(", "4", ",", "dtype", "=", "n...
43.444444
0.015038
def create_message( json_meta, data, data_type=0, version=b'\x00\x01@\x00'): """Create message, containing meta and data in df-envelope format. @json_meta - metadata @data - binary data @data_type - data type code for binary data @version - version of machine header @return - message as...
[ "def", "create_message", "(", "json_meta", ",", "data", ",", "data_type", "=", "0", ",", "version", "=", "b'\\x00\\x01@\\x00'", ")", ":", "__check_data", "(", "data", ")", "meta", "=", "__prepare_meta", "(", "json_meta", ")", "data", "=", "__compress", "(", ...
29.833333
0.001805
def folderitems(self): """TODO: Refactor to non-classic mode """ items = super(ServicesView, self).folderitems() self.categories.sort() return items
[ "def", "folderitems", "(", "self", ")", ":", "items", "=", "super", "(", "ServicesView", ",", "self", ")", ".", "folderitems", "(", ")", "self", ".", "categories", ".", "sort", "(", ")", "return", "items" ]
30.5
0.010638
def send_from_directory(directory, filename, **options): """Send a file from a given directory with :func:`send_file`. This is a secure way to quickly expose static files from an upload folder or something similar. Example usage:: @app.route('/uploads/<path:filename>') def download_fi...
[ "def", "send_from_directory", "(", "directory", ",", "filename", ",", "*", "*", "options", ")", ":", "filename", "=", "safe_join", "(", "directory", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "filename", ")", ":", "raise", ...
40.0625
0.000762
def application_version_set(version): """Charm authors may trigger this command from any hook to output what version of the application is running. This could be a package version, for instance postgres version 9.5. It could also be a build number or version control revision identifier, for instance git...
[ "def", "application_version_set", "(", "version", ")", ":", "cmd", "=", "[", "'application-version-set'", "]", "cmd", ".", "append", "(", "version", ")", "try", ":", "subprocess", ".", "check_call", "(", "cmd", ")", "except", "OSError", ":", "log", "(", "\...
42.416667
0.001923
def decode(image, timeout=None, gap_size=None, shrink=1, shape=None, deviation=None, threshold=None, min_edge=None, max_edge=None, corrections=None, max_count=None): """Decodes datamatrix barcodes in `image`. Args: image: `numpy.ndarray`, `PIL.Image` or tuple (pixels, width, heigh...
[ "def", "decode", "(", "image", ",", "timeout", "=", "None", ",", "gap_size", "=", "None", ",", "shrink", "=", "1", ",", "shape", "=", "None", ",", "deviation", "=", "None", ",", "threshold", "=", "None", ",", "min_edge", "=", "None", ",", "max_edge",...
35.319444
0.000765
def debug_info(self): """The debug info mapping.""" return [tuple(map(int, x.split('='))) for x in self._debug_info.split('&')]
[ "def", "debug_info", "(", "self", ")", ":", "return", "[", "tuple", "(", "map", "(", "int", ",", "x", ".", "split", "(", "'='", ")", ")", ")", "for", "x", "in", "self", ".", "_debug_info", ".", "split", "(", "'&'", ")", "]" ]
39
0.012579
def fit(self, x, y=None): """Compute the header. """ x = iter2array(x, dtype=(MoleculeContainer, CGRContainer)) if self.__head_less: warn(f'{self.__class__.__name__} configured to head less mode. fit unusable') return self self._reset() self.__pr...
[ "def", "fit", "(", "self", ",", "x", ",", "y", "=", "None", ")", ":", "x", "=", "iter2array", "(", "x", ",", "dtype", "=", "(", "MoleculeContainer", ",", "CGRContainer", ")", ")", "if", "self", ".", "__head_less", ":", "warn", "(", "f'{self.__class__...
28.083333
0.008621
def describeTable(TableName): """ INPUT PARAMETERS: TableName: name of the table to describe OUTPUT PARAMETERS: none --- DESCRIPTION: Print information about table, including parameter names, formats and wavenumber range. --- EXAMPLE OF USAGE: descr...
[ "def", "describeTable", "(", "TableName", ")", ":", "print", "(", "'-----------------------------------------'", ")", "print", "(", "TableName", "+", "' summary:'", ")", "try", ":", "print", "(", "'-----------------------------------------'", ")", "print", "(", "'Comm...
36.741935
0.00941
def auto_str_ignore(ignore_list): """ Use this decorator to suppress any fields that should not be part of the dynamically created `__str__` or `__repr__` function of `auto_str`. Args: ignore_list: List or item of the fields to suppress by `auto_str`. Returns: Returns a decorator. ...
[ "def", "auto_str_ignore", "(", "ignore_list", ")", ":", "def", "_decorator", "(", "cls", ")", ":", "ignored", "=", "make_list", "(", "ignore_list", ")", "cls", ".", "__auto_str_ignore__", "=", "ignored", "return", "cls", "return", "_decorator" ]
28.7
0.002247
def inMicrolensRegion_main(args=None): """Exposes K2visible to the command line.""" import argparse parser = argparse.ArgumentParser( description="Check if a celestial coordinate is " "inside the K2C9 microlensing superstamp.") parser.add_argument('ra'...
[ "def", "inMicrolensRegion_main", "(", "args", "=", "None", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Check if a celestial coordinate is \"", "\"inside the K2C9 microlensing superstamp.\"", ")", "parser", ...
51.066667
0.001282
def _permute_one_sample_iscs(iscs, group_parameters, i, pairwise=False, summary_statistic='median', group_matrix=None, exact_permutations=None, prng=None): """Applies one-sample permutations to ISC data Input ISCs should be n_subjects (leave-one-out ap...
[ "def", "_permute_one_sample_iscs", "(", "iscs", ",", "group_parameters", ",", "i", ",", "pairwise", "=", "False", ",", "summary_statistic", "=", "'median'", ",", "group_matrix", "=", "None", ",", "exact_permutations", "=", "None", ",", "prng", "=", "None", ")"...
31.575758
0.000465
def namedb_select_where_unexpired_names(current_block, only_registered=True): """ Generate part of a WHERE clause that selects from name records joined with namespaces (or projections of them) that are not expired. Also limit to names that are registered at this block, if only_registered=True. If o...
[ "def", "namedb_select_where_unexpired_names", "(", "current_block", ",", "only_registered", "=", "True", ")", ":", "ns_lifetime_multiplier", "=", "get_epoch_namespace_lifetime_multiplier", "(", "current_block", ",", "'*'", ")", "ns_grace_period", "=", "get_epoch_namespace_lif...
58.222222
0.008447
def with_details(self, key, value): """ Sets a parameter for additional error details. This details can be used to restore error description in other languages. This method returns reference to this exception to implement Builder pattern to chain additional calls. :param key: a...
[ "def", "with_details", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "details", "=", "self", ".", "details", "if", "self", ".", "details", "!=", "None", "else", "{", "}", "self", ".", "details", "[", "key", "]", "=", "value", "retur...
34.375
0.00885
def _get_value(context, key): """ Retrieve a key's value from a context item. Returns _NOT_FOUND if the key does not exist. The ContextStack.get() docstring documents this function's intended behavior. """ if isinstance(context, dict): # Then we consider the argument a "hash" for the ...
[ "def", "_get_value", "(", "context", ",", "key", ")", ":", "if", "isinstance", "(", "context", ",", "dict", ")", ":", "# Then we consider the argument a \"hash\" for the purposes of the spec.", "#", "# We do a membership test to avoid using exceptions for flow control", "# (e.g...
38.1
0.00128
def _do_taxons(self, taxon_str): """Taxon""" taxons = self._get_list(taxon_str) taxons_str = [v.split(':')[1] for v in taxons] # strip "taxon:" taxons_int = [int(s) for s in taxons_str if s] return taxons_int
[ "def", "_do_taxons", "(", "self", ",", "taxon_str", ")", ":", "taxons", "=", "self", ".", "_get_list", "(", "taxon_str", ")", "taxons_str", "=", "[", "v", ".", "split", "(", "':'", ")", "[", "1", "]", "for", "v", "in", "taxons", "]", "# strip \"taxon...
40.5
0.012097
def calculate_total_amt(self, items={}): """Returns the total amount/cost of items in the current invoice""" _items = items.items() or self.items.items() return sum(float(x[1].total_price) for x in _items)
[ "def", "calculate_total_amt", "(", "self", ",", "items", "=", "{", "}", ")", ":", "_items", "=", "items", ".", "items", "(", ")", "or", "self", ".", "items", ".", "items", "(", ")", "return", "sum", "(", "float", "(", "x", "[", "1", "]", ".", "...
56.5
0.008734
def config_unset(key, value_regex=None, cwd=None, user=None, password=None, ignore_retcode=False, output_encoding=None, **kwargs): ''' .. versionadded:: 2015.8.0 Unset a key in the git con...
[ "def", "config_unset", "(", "key", ",", "value_regex", "=", "None", ",", "cwd", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "ignore_retcode", "=", "False", ",", "output_encoding", "=", "None", ",", "*", "*", "kwargs", ")",...
32.267717
0.000237
def are_same_file_types(objs): """ Are given (maybe) file objs same type (extension) ? :param objs: A list of file path or file(-like) objects >>> are_same_file_types([]) False >>> are_same_file_types(["a.conf"]) True >>> are_same_file_types(["a.conf", "b.conf"]) True >>> are_s...
[ "def", "are_same_file_types", "(", "objs", ")", ":", "if", "not", "objs", ":", "return", "False", "ext", "=", "_try_to_get_extension", "(", "objs", "[", "0", "]", ")", "if", "ext", "is", "None", ":", "return", "False", "return", "all", "(", "_try_to_get_...
24.928571
0.001379
def thin_samples_for_writing(fp, samples, parameters, last_iteration): """Thins samples for writing to disk. The thinning interval to use is determined by the given file handler's ``thinned_by`` attribute. If that attribute is 1, just returns the samples. Parameters ---------- fp : MCMCMetadat...
[ "def", "thin_samples_for_writing", "(", "fp", ",", "samples", ",", "parameters", ",", "last_iteration", ")", ":", "if", "fp", ".", "thinned_by", ">", "1", ":", "if", "last_iteration", "is", "None", ":", "raise", "ValueError", "(", "\"File's thinned_by attribute ...
44.68
0.000438
def _cast(self, value): """ Try to cast value to int or float if possible :param value: value to cast :return: casted value """ if value.isdigit(): value = int(value) elif re.compile("^\d+\.\d+").match(value): value = float(value) r...
[ "def", "_cast", "(", "self", ",", "value", ")", ":", "if", "value", ".", "isdigit", "(", ")", ":", "value", "=", "int", "(", "value", ")", "elif", "re", ".", "compile", "(", "\"^\\d+\\.\\d+\"", ")", ".", "match", "(", "value", ")", ":", "value", ...
29.181818
0.015106
def K80(mu=1., kappa=0.1, **kwargs): """ Kimura 1980 model. Assumes equal concentrations across nucleotides, but allows different rates between transitions and transversions. The ratio of the transversion/transition rates is given by kappa parameter. For more info, see Kimura (1980), J. Mol. Ev...
[ "def", "K80", "(", "mu", "=", "1.", ",", "kappa", "=", "0.1", ",", "*", "*", "kwargs", ")", ":", "num_chars", "=", "len", "(", "alphabets", "[", "'nuc_nogap'", "]", ")", "pi", "=", "np", ".", "ones", "(", "len", "(", "alphabets", "[", "'nuc_nogap...
32.769231
0.002281
def create_zone(domain, profile, type='master', ttl=None): ''' Create a new zone. :param domain: Zone domain name (e.g. example.com) :type domain: ``str`` :param profile: The profile key :type profile: ``str`` :param type: Zone type (master / slave). :type type: ``str`` :param ...
[ "def", "create_zone", "(", "domain", ",", "profile", ",", "type", "=", "'master'", ",", "ttl", "=", "None", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "zone", "=", "conn", ".", "create_record", "(", "domain", ",", "type"...
24.16
0.001592
def expect(obj, caller_args=[]): """Primary method for test assertions in Specter :param obj: The evaluated target object :param caller_args: Is only used when using expecting a raised Exception """ line, module = get_module_and_line('__spec__') src_params = ExpectParams(line, module) expe...
[ "def", "expect", "(", "obj", ",", "caller_args", "=", "[", "]", ")", ":", "line", ",", "module", "=", "get_module_and_line", "(", "'__spec__'", ")", "src_params", "=", "ExpectParams", "(", "line", ",", "module", ")", "expect_obj", "=", "ExpectAssert", "(",...
29.375
0.002062
def element(self, inp=None, data_ptr=None, order=None): """Create a new element. Parameters ---------- inp : `array-like`, optional Input used to initialize the new element. If ``inp`` is `None`, an empty element is created with no guarantee of its s...
[ "def", "element", "(", "self", ",", "inp", "=", "None", ",", "data_ptr", "=", "None", ",", "order", "=", "None", ")", ":", "if", "order", "is", "not", "None", "and", "str", "(", "order", ")", ".", "upper", "(", ")", "not", "in", "(", "'C'", ","...
38.845528
0.000408
def dist_location(dist): """ Get the site-packages location of this distribution. Generally this is dist.location, except in the case of develop-installed packages, where dist.location is the source code location, and we want to know where the egg-link file is. """ egg_link = egg_link_path(...
[ "def", "dist_location", "(", "dist", ")", ":", "egg_link", "=", "egg_link_path", "(", "dist", ")", "if", "os", ".", "path", ".", "exists", "(", "egg_link", ")", ":", "return", "egg_link", "return", "dist", ".", "location" ]
33
0.002457
def cropped(self, T0, T1): """returns a cropped copy of the path.""" assert 0 <= T0 <= 1 and 0 <= T1<= 1 assert T0 != T1 assert not (T0 == 1 and T1 == 0) if T0 == 1 and 0 < T1 < 1 and self.isclosed(): return self.cropped(0, T1) if T1 == 1: seg1 =...
[ "def", "cropped", "(", "self", ",", "T0", ",", "T1", ")", ":", "assert", "0", "<=", "T0", "<=", "1", "and", "0", "<=", "T1", "<=", "1", "assert", "T0", "!=", "T1", "assert", "not", "(", "T0", "==", "1", "and", "T1", "==", "0", ")", "if", "T...
31.7
0.00153
def get_declared_fields(mcs, klass, *args, **kwargs): """Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Meta option. """ declared_fields = kwargs.get('dict_class', dict)() # Generate the fields provided through inheritance ...
[ "def", "get_declared_fields", "(", "mcs", ",", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "declared_fields", "=", "kwargs", ".", "get", "(", "'dict_class'", ",", "dict", ")", "(", ")", "# Generate the fields provided through inheritance", "o...
47.35
0.001552
def create_anchor_from_header(header, existing_anchors=None): """ Creates GitHub style auto-generated anchor tags from header line strings :param header: The portion of the line that should be converted :param existing_anchors: A dictionary of AnchorHub tags to auto-generated anchors :retur...
[ "def", "create_anchor_from_header", "(", "header", ",", "existing_anchors", "=", "None", ")", ":", "# Strip white space on the left/right and make lower case", "out", "=", "header", ".", "strip", "(", ")", ".", "lower", "(", ")", "# Replace groups of white space with hyph...
38.291667
0.001062
def preview(src_path): ''' Generates a preview of src_path in the requested format. :returns: A list of preview paths, one for each page. Blank list if unsupported. ''' preview = embedded_preview(src_path) if not is_valid_preview(preview): preview = generator_preview(src_path) if not is_valid_preview(...
[ "def", "preview", "(", "src_path", ")", ":", "preview", "=", "embedded_preview", "(", "src_path", ")", "if", "not", "is_valid_preview", "(", "preview", ")", ":", "preview", "=", "generator_preview", "(", "src_path", ")", "if", "not", "is_valid_preview", "(", ...
28.857143
0.017572
def getMaskArray(self, signature): """ Returns the appropriate StaticMask array for the image. """ if signature in self.masklist: mask = self.masklist[signature] else: mask = None return mask
[ "def", "getMaskArray", "(", "self", ",", "signature", ")", ":", "if", "signature", "in", "self", ".", "masklist", ":", "mask", "=", "self", ".", "masklist", "[", "signature", "]", "else", ":", "mask", "=", "None", "return", "mask" ]
34.571429
0.012097
def hybrid_tty_create_child(args): """ Like :func:`tty_create_child`, except attach stdin/stdout to a socketpair like :func:`create_child`, but leave stderr and the controlling TTY attached to a TTY. :param list args: :py:func:`os.execl` argument list. :returns: `(pid, socketpa...
[ "def", "hybrid_tty_create_child", "(", "args", ")", ":", "master_fd", ",", "slave_fd", "=", "openpty", "(", ")", "try", ":", "disable_echo", "(", "master_fd", ")", "disable_echo", "(", "slave_fd", ")", "mitogen", ".", "core", ".", "set_block", "(", "slave_fd...
27.958333
0.00072
def switch_to_window(driver, window, timeout=settings.SMALL_TIMEOUT): """ Wait for a window to appear, and switch to it. This should be usable as a drop-in replacement for driver.switch_to.window(). @Params driver - the webdriver object (required) window - the window index or window handle t...
[ "def", "switch_to_window", "(", "driver", ",", "window", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "start_ms", "=", "time", ".", "time", "(", ")", "*", "1000.0", "stop_ms", "=", "start_ms", "+", "(", "timeout", "*", "1000.0", ")", ...
37.75
0.000717
def parse_requirements_alt(fname='requirements.txt'): """ pip install requirements-parser fname='requirements.txt' """ import requirements from os.path import dirname, join, exists require_fpath = join(dirname(__file__), fname) if exists(require_fpath): # Dont use until this hand...
[ "def", "parse_requirements_alt", "(", "fname", "=", "'requirements.txt'", ")", ":", "import", "requirements", "from", "os", ".", "path", "import", "dirname", ",", "join", ",", "exists", "require_fpath", "=", "join", "(", "dirname", "(", "__file__", ")", ",", ...
35
0.001855
def configKeyButtons( self, enableButtons = [], bounceTime = DEF_BOUNCE_TIME_NORMAL, pullUpDown = GPIO.PUD_UP, event = GPIO.BOTH ): """! \~english Config multi key buttons IO and event on same time @param enableButtons: an array of key button configs. eg. <br> [{ "id":BU...
[ "def", "configKeyButtons", "(", "self", ",", "enableButtons", "=", "[", "]", ",", "bounceTime", "=", "DEF_BOUNCE_TIME_NORMAL", ",", "pullUpDown", "=", "GPIO", ".", "PUD_UP", ",", "event", "=", "GPIO", ".", "BOTH", ")", ":", "for", "key", "in", "enableButto...
42.586207
0.016627
def _get_search_path(main_file_dir, sys_path): ''' Find the parent python path that contains the __main__'s file directory :param main_file_dir: __main__'s file directory :param sys_path: paths list to match directory against (like sys.path) ''' # List to gather candidate parent paths paths...
[ "def", "_get_search_path", "(", "main_file_dir", ",", "sys_path", ")", ":", "# List to gather candidate parent paths", "paths", "=", "[", "]", "# look for paths containing the directory", "for", "pth", "in", "sys_path", ":", "# convert relative path to absolute", "pth", "="...
38.434783
0.001104
def latlon(self): '''return (lat,lon) for the grid coordinates''' from MAVProxy.modules.lib.ANUGA import lat_long_UTM_conversion (lat, lon) = lat_long_UTM_conversion.UTMtoLL(self.northing, self.easting, self.zone, isSouthernHemisphere=(self.hemisphere=='S')) return (lat, lon)
[ "def", "latlon", "(", "self", ")", ":", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "ANUGA", "import", "lat_long_UTM_conversion", "(", "lat", ",", "lon", ")", "=", "lat_long_UTM_conversion", ".", "UTMtoLL", "(", "self", ".", "northing", ",", "self...
60.8
0.012987
def add_legend(self, labels=None, **kwargs): """Specify legend for a plot. Adds labels and basic legend specifications for specific plot. For the optional Args, refer to https://matplotlib.org/api/_as_gen/matplotlib.pyplot.legend.html for more information. # TODO: Add ...
[ "def", "add_legend", "(", "self", ",", "labels", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "'size'", "in", "kwargs", ":", "if", "'prop'", "not", "in", "kwargs", ":", "kwargs", "[", "'prop'", "]", "=", "{", "'size'", ":", "kwargs", "[", ...
43.113636
0.001031
def _setup_source_and_destination(self): """use the base class to setup the source and destinations but add to that setup the instantiation of the "new_crash_source" """ super(FetchTransformSaveWithSeparateNewCrashSourceApp, self) \ ._setup_source_and_destination() if self.co...
[ "def", "_setup_source_and_destination", "(", "self", ")", ":", "super", "(", "FetchTransformSaveWithSeparateNewCrashSourceApp", ",", "self", ")", ".", "_setup_source_and_destination", "(", ")", "if", "self", ".", "config", ".", "new_crash_source", ".", "new_crash_source...
52.3125
0.002347
def read(self, cmd_args): """ Execute Vagrant read command. :param list cmd_args: Command argument list. """ args = [ "vagrant", "--machine-readable" ] args.extend(cmd_args) proc = subprocess.Popen(args, stdout=subprocess.PIPE) for line in proc.stdout.readlines(): if len(line) ==...
[ "def", "read", "(", "self", ",", "cmd_args", ")", ":", "args", "=", "[", "\"vagrant\"", ",", "\"--machine-readable\"", "]", "args", ".", "extend", "(", "cmd_args", ")", "proc", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdout", "=", "subprocess...
18.5
0.064267
def progress(msg, *args): '''Show current progress message to stderr. This function will remember the previous message so that next time, it will clear the previous message before showing next one. ''' # Don't show any progress if the output is directed to a file. if not (sys.stdout.isatty() and sys.s...
[ "def", "progress", "(", "msg", ",", "*", "args", ")", ":", "# Don't show any progress if the output is directed to a file.", "if", "not", "(", "sys", ".", "stdout", ".", "isatty", "(", ")", "and", "sys", ".", "stderr", ".", "isatty", "(", ")", ")", ":", "r...
36.428571
0.015296
def first_name(languages=None, genders=None): """ return a random first name :return: >>> from mock import patch >>> with patch('%s._get_firstnamess' % __name__, lambda *args: ['aaa']): ... first_name() 'Aaa' """ choices = [] languages = languages or ['en'] genders =...
[ "def", "first_name", "(", "languages", "=", "None", ",", "genders", "=", "None", ")", ":", "choices", "=", "[", "]", "languages", "=", "languages", "or", "[", "'en'", "]", "genders", "=", "genders", "or", "[", "GENDER_MALE", ",", "GENDER_FEMALE", "]", ...
29.5
0.001825
def get_shipment(self, resource_id): """Retrieve a single shipment by a shipment's ID.""" return Shipments(self.client).on(self).get(resource_id)
[ "def", "get_shipment", "(", "self", ",", "resource_id", ")", ":", "return", "Shipments", "(", "self", ".", "client", ")", ".", "on", "(", "self", ")", ".", "get", "(", "resource_id", ")" ]
53
0.012422
def ls(url='http://localhost:8080/manager', timeout=180): ''' list all the deployed webapps url : http://localhost:8080/manager the URL of the server manager webapp timeout : 180 timeout for HTTP request CLI Examples: .. code-block:: bash salt '*' tomcat.ls sa...
[ "def", "ls", "(", "url", "=", "'http://localhost:8080/manager'", ",", "timeout", "=", "180", ")", ":", "ret", "=", "{", "}", "data", "=", "_wget", "(", "'list'", ",", "''", ",", "url", ",", "timeout", "=", "timeout", ")", "if", "data", "[", "'res'", ...
23.257143
0.001179
def run_cmd(*cmd: Optional[str], out: Optional[Union[TeeCapture, IO[str]]] = sys.stdout, err: Optional[Union[TeeCapture, IO[str]]] = sys.stderr, raise_on_fail: bool = True, log_run_to_stderr: bool = True, abbreviate_non_option_arguments: bool = False, ...
[ "def", "run_cmd", "(", "*", "cmd", ":", "Optional", "[", "str", "]", ",", "out", ":", "Optional", "[", "Union", "[", "TeeCapture", ",", "IO", "[", "str", "]", "]", "]", "=", "sys", ".", "stdout", ",", "err", ":", "Optional", "[", "Union", "[", ...
47.66129
0.000332
def _parse_header(line): """Parse a Content-type like header. Return the main content-type and a dictionary of options. """ parts = _parseparam(';' + line) key = parts.next() pdict = {} for p in parts: i = p.find('=') if i >= 0: name = p[:i].strip().lower() ...
[ "def", "_parse_header", "(", "line", ")", ":", "parts", "=", "_parseparam", "(", "';'", "+", "line", ")", "key", "=", "parts", ".", "next", "(", ")", "pdict", "=", "{", "}", "for", "p", "in", "parts", ":", "i", "=", "p", ".", "find", "(", "'='"...
29.473684
0.00173
def headerLink( self, headerText, text=False): """*generate a link to a MMD header* **Key Arguments:** - ``headerText`` -- the header text (or anchor tag) - ``text`` -- the doc text to link. Default *False* **Return:** - `...
[ "def", "headerLink", "(", "self", ",", "headerText", ",", "text", "=", "False", ")", ":", "headerText", "=", "headerText", ".", "strip", "(", ")", "if", "text", ":", "return", "self", ".", "_surround", "(", "text", ",", "\"[\"", ",", "\"][%(headerText)s]...
26.0625
0.002312
def _get_or_create_stack(name): """Returns a thread local stack uniquified by the given name.""" stack = getattr(_LOCAL_STACKS, name, None) if stack is None: stack = [] setattr(_LOCAL_STACKS, name, stack) return stack
[ "def", "_get_or_create_stack", "(", "name", ")", ":", "stack", "=", "getattr", "(", "_LOCAL_STACKS", ",", "name", ",", "None", ")", "if", "stack", "is", "None", ":", "stack", "=", "[", "]", "setattr", "(", "_LOCAL_STACKS", ",", "name", ",", "stack", ")...
32.428571
0.021459
def events_for_secretreveal( transfers_pair: List[MediationPairState], secret: Secret, pseudo_random_generator: random.Random, ) -> List[Event]: """ Reveal the secret off-chain. The secret is revealed off-chain even if there is a pending transaction to reveal it on-chain, this allow...
[ "def", "events_for_secretreveal", "(", "transfers_pair", ":", "List", "[", "MediationPairState", "]", ",", "secret", ":", "Secret", ",", "pseudo_random_generator", ":", "random", ".", "Random", ",", ")", "->", "List", "[", "Event", "]", ":", "events", ":", "...
39.388889
0.000917
def shape(self) -> Tuple[int, ...]: """Shape of histogram's data. Returns ------- One-element tuple with the number of bins along each axis. """ return tuple(bins.bin_count for bins in self._binnings)
[ "def", "shape", "(", "self", ")", "->", "Tuple", "[", "int", ",", "...", "]", ":", "return", "tuple", "(", "bins", ".", "bin_count", "for", "bins", "in", "self", ".", "_binnings", ")" ]
30.25
0.008032
def _array_handler(self, _cursor_type): """ Handles all array types. Resolves it's element type and makes a Array typedesc. """ # The element type has been previously declared # we need to get the canonical typedef, in some cases _type = _cursor_type.get_canonical...
[ "def", "_array_handler", "(", "self", ",", "_cursor_type", ")", ":", "# The element type has been previously declared", "# we need to get the canonical typedef, in some cases", "_type", "=", "_cursor_type", ".", "get_canonical", "(", ")", "size", "=", "_type", ".", "get_arr...
46.882353
0.002459
def me(self): """Similar to :attr:`Client.user` except an instance of :class:`Member`. This is essentially used to get the member version of yourself. """ self_id = self._state.user.id return self.get_member(self_id)
[ "def", "me", "(", "self", ")", ":", "self_id", "=", "self", ".", "_state", ".", "user", ".", "id", "return", "self", ".", "get_member", "(", "self_id", ")" ]
41.833333
0.011719
def bicluster_similarity(self, reference_model): """ Calculates the similarity between the current model of biclusters and the reference model of biclusters :param reference_model: The reference model of biclusters :return: Returns the consensus score(Hochreiter et. al., 2010), i.e. the...
[ "def", "bicluster_similarity", "(", "self", ",", "reference_model", ")", ":", "similarity_score", "=", "consensus_score", "(", "self", ".", "model", ".", "biclusters_", ",", "reference_model", ".", "biclusters_", ")", "return", "similarity_score" ]
54.444444
0.01004
def inputhook_wx3(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sl...
[ "def", "inputhook_wx3", "(", ")", ":", "# We need to protect against a user pressing Control-C when IPython is", "# idle and this is running. We trap KeyboardInterrupt and pass.", "try", ":", "app", "=", "wx", ".", "GetApp", "(", ")", "# @UndefinedVariable", "if", "app", "is", ...
44.12963
0.001232
def get_unique_schema_id(schema): # type: (GraphQLSchema) -> str """Get a unique id given a GraphQLSchema""" assert isinstance(schema, GraphQLSchema), ( "Must receive a GraphQLSchema as schema. Received {}" ).format(repr(schema)) if schema not in _cached_schemas: _cached_schemas[sch...
[ "def", "get_unique_schema_id", "(", "schema", ")", ":", "# type: (GraphQLSchema) -> str", "assert", "isinstance", "(", "schema", ",", "GraphQLSchema", ")", ",", "(", "\"Must receive a GraphQLSchema as schema. Received {}\"", ")", ".", "format", "(", "repr", "(", "schema...
39.8
0.002457
def read_row(self,rownumber,reverse=True): """ Read a block of data. The number of samples per row is set in self.channels If reverse=True the x axis is flipped. """ raise NotImplementedError('To be implemented') # go to start of the row self.filfile.seek(int(self.da...
[ "def", "read_row", "(", "self", ",", "rownumber", ",", "reverse", "=", "True", ")", ":", "raise", "NotImplementedError", "(", "'To be implemented'", ")", "# go to start of the row", "self", ".", "filfile", ".", "seek", "(", "int", "(", "self", ".", "datastart"...
44.307692
0.018707
def dre_dm(self, pars): r""" :math:Add formula """ self._set_parameters(pars) terms = self.num / self.denom result = - self.sigmai * terms return result
[ "def", "dre_dm", "(", "self", ",", "pars", ")", ":", "self", ".", "_set_parameters", "(", "pars", ")", "terms", "=", "self", ".", "num", "/", "self", ".", "denom", "result", "=", "-", "self", ".", "sigmai", "*", "terms", "return", "result" ]
22.333333
0.009569
def strip(self, text): '''Return string with markup tags removed.''' tags, results = [], [] return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text)
[ "def", "strip", "(", "self", ",", "text", ")", ":", "tags", ",", "results", "=", "[", "]", ",", "[", "]", "return", "self", ".", "re_tag", ".", "sub", "(", "lambda", "m", ":", "self", ".", "clear_tag", "(", "m", ",", "tags", ",", "results", ")"...
46.25
0.015957
def _body(self): """ Generate the information required to create an ISBN-10 or ISBN-13. """ ean = self.random_element(RULES.keys()) reg_group = self.random_element(RULES[ean].keys()) # Given the chosen ean/group, decide how long the # registrant/publication str...
[ "def", "_body", "(", "self", ")", ":", "ean", "=", "self", ".", "random_element", "(", "RULES", ".", "keys", "(", ")", ")", "reg_group", "=", "self", ".", "random_element", "(", "RULES", "[", "ean", "]", ".", "keys", "(", ")", ")", "# Given the chose...
40.9
0.002389
def q_if(self, *qregs): """Add controls to all instructions.""" for gate in self.instructions: gate.q_if(*qregs) return self
[ "def", "q_if", "(", "self", ",", "*", "qregs", ")", ":", "for", "gate", "in", "self", ".", "instructions", ":", "gate", ".", "q_if", "(", "*", "qregs", ")", "return", "self" ]
31.2
0.0125
def notify( self, force_notify=None, use_email=None, use_sms=None, email_body_template=None, **kwargs, ): """Notify / send an email and/or SMS. Main entry point. This notification class (me) knows from whom and to whom the notificatio...
[ "def", "notify", "(", "self", ",", "force_notify", "=", "None", ",", "use_email", "=", "None", ",", "use_sms", "=", "None", ",", "email_body_template", "=", "None", ",", "*", "*", "kwargs", ",", ")", ":", "email_sent", "=", "None", "sms_sent", "=", "No...
33
0.002324
def _get_alt_labels(self, titles): """ From a string of delimited titles, make an array. This assumes that the titles are double-semicolon (';;') delimited. This will additionally pass each through the _cleanup_label method to convert the screaming ALL CAPS to something more plea...
[ "def", "_get_alt_labels", "(", "self", ",", "titles", ")", ":", "labels", "=", "[", "]", "# \"alternativeTitles\": \"", "# ACROCEPHALOSYNDACTYLY, TYPE V; ACS5;;\\nACS V;;\\nNOACK SYNDROME\",", "# \"includedTitles\":", "# \"CRANIOFACIAL-SKELETAL-DERMATOLOGIC DYSPLASIA, INCLUDED\"", ...
38.695652
0.002193
def resolve_structure(self, fc, ct): """ Resolve structure specifications. """ if self.debug: print("++++++++ Resolving structure of (%s) with %s"%(fc, ct)) for w in ct.structure.withs: try: if w.instance == 'parent' or w.instance == 'this': ...
[ "def", "resolve_structure", "(", "self", ",", "fc", ",", "ct", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "\"++++++++ Resolving structure of (%s) with %s\"", "%", "(", "fc", ",", "ct", ")", ")", "for", "w", "in", "ct", ".", "structure", "."...
50.434783
0.012118