text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _get_content_range(start: Optional[int], end: Optional[int], total: int) -> str: """Returns a suitable Content-Range header: >>> print(_get_content_range(None, 1, 4)) bytes 0-0/4 >>> print(_get_content_range(1, 3, 4)) bytes 1-2/4 >>> print(_get_content_range(None, None, 4)) bytes 0-3/4 ...
[ "def", "_get_content_range", "(", "start", ":", "Optional", "[", "int", "]", ",", "end", ":", "Optional", "[", "int", "]", ",", "total", ":", "int", ")", "->", "str", ":", "start", "=", "start", "or", "0", "end", "=", "(", "end", "or", "total", "...
32.076923
16.384615
def zone_absent(domain, profile): ''' Ensures a record is absent. :param domain: Zone name, i.e. the domain name :type domain: ``str`` :param profile: The profile key :type profile: ``str`` ''' zones = __salt__['libcloud_dns.list_zones'](profile) matching_zone = [z for z in zones...
[ "def", "zone_absent", "(", "domain", ",", "profile", ")", ":", "zones", "=", "__salt__", "[", "'libcloud_dns.list_zones'", "]", "(", "profile", ")", "matching_zone", "=", "[", "z", "for", "z", "in", "zones", "if", "z", "[", "'domain'", "]", "==", "domain...
34
22.235294
def dt_dayofyear(x): """The ordinal day of the year. :returns: an expression containing the ordinal day of the year. Example: >>> import vaex >>> import numpy as np >>> date = np.array(['2009-10-12T03:31:00', '2016-02-11T10:17:34', '2015-11-12T11:34:22'], dtype=np.datetime64) >>> df = vae...
[ "def", "dt_dayofyear", "(", "x", ")", ":", "import", "pandas", "as", "pd", "return", "pd", ".", "Series", "(", "x", ")", ".", "dt", ".", "dayofyear", ".", "values" ]
25.37037
21
def jtag_configure(self, instr_regs=0, data_bits=0): """Configures the JTAG scan chain to determine which CPU to address. Must be called if the J-Link is connected to a JTAG scan chain with multiple devices. Args: self (JLink): the ``JLink`` instance instr_regs (int...
[ "def", "jtag_configure", "(", "self", ",", "instr_regs", "=", "0", ",", "data_bits", "=", "0", ")", ":", "if", "not", "util", ".", "is_natural", "(", "instr_regs", ")", ":", "raise", "ValueError", "(", "'IR value is not a natural number.'", ")", "if", "not",...
34.962963
23.518519
def inject_coordinates(self, x_coords, y_coords, rescale_x=None, rescale_y=None, original_x=None, original_y=None): ''' Inject custom x and y ...
[ "def", "inject_coordinates", "(", "self", ",", "x_coords", ",", "y_coords", ",", "rescale_x", "=", "None", ",", "rescale_y", "=", "None", ",", "original_x", "=", "None", ",", "original_y", "=", "None", ")", ":", "self", ".", "_verify_coordinates", "(", "x_...
37.351351
14.432432
def register(self): """ Register via the method configured :return: """ if self.register_method == "twine": self.register_by_twine() if self.register_method == "setup": self.register_by_setup() if self.register_method == "upload": ...
[ "def", "register", "(", "self", ")", ":", "if", "self", ".", "register_method", "==", "\"twine\"", ":", "self", ".", "register_by_twine", "(", ")", "if", "self", ".", "register_method", "==", "\"setup\"", ":", "self", ".", "register_by_setup", "(", ")", "i...
29.636364
7.272727
def group_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/core/groups#show-group" api_path = "/api/v2/groups/{id}.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "group_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/groups/{id}.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", ",", ...
48.2
10.2
def info(endpoint): """Show metric info from a Prometheus endpoint. \b Example: $ ddev meta prom info :8080/_status/vars """ endpoint = sanitize_endpoint(endpoint) metrics = parse_metrics(endpoint) num_metrics = len(metrics) num_gauge = 0 num_counter = 0 num_histogram = 0 ...
[ "def", "info", "(", "endpoint", ")", ":", "endpoint", "=", "sanitize_endpoint", "(", "endpoint", ")", "metrics", "=", "parse_metrics", "(", "endpoint", ")", "num_metrics", "=", "len", "(", "metrics", ")", "num_gauge", "=", "0", "num_counter", "=", "0", "nu...
24.384615
19.564103
def arg(*args, **kwargs): """ Declares an argument for given function. Does not register the function anywhere, nor does it modify the function in any way. The signature of the decorator matches that of :meth:`argparse.ArgumentParser.add_argument`, only some keywords are not required if they ca...
[ "def", "arg", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "wrapper", "(", "func", ")", ":", "declared_args", "=", "getattr", "(", "func", ",", "ATTR_ARGS", ",", "[", "]", ")", "# The innermost decorator is called first but appears last in the c...
40.22807
23.982456
def load_allconfig(kconf, filename): """ Helper for all*config. Loads (merges) the configuration file specified by KCONFIG_ALLCONFIG, if any. See Documentation/kbuild/kconfig.txt in the Linux kernel. Disables warnings for duplicated assignments within configuration files for the duration of the...
[ "def", "load_allconfig", "(", "kconf", ",", "filename", ")", ":", "def", "std_msg", "(", "e", ")", ":", "# \"Upcasts\" a _KconfigIOError to an IOError, removing the custom", "# __str__() message. The standard message is better here.", "return", "IOError", "(", "e", ".", "er...
39.222222
22.185185
def extract_frames(self, bpf_buffer): """Extract all frames from the buffer and stored them in the received list.""" # noqa: E501 # Ensure that the BPF buffer contains at least the header len_bb = len(bpf_buffer) if len_bb < 20: # Note: 20 == sizeof(struct bfp_hdr) return ...
[ "def", "extract_frames", "(", "self", ",", "bpf_buffer", ")", ":", "# noqa: E501", "# Ensure that the BPF buffer contains at least the header", "len_bb", "=", "len", "(", "bpf_buffer", ")", "if", "len_bb", "<", "20", ":", "# Note: 20 == sizeof(struct bfp_hdr)", "return", ...
37.974359
19.051282
def post_collect(self, obj): """ We want to manage the side-effect of not collecting other items of the same type as root model. If for example, you run the collect on a specific user that is linked to a model "A" linked (ForeignKey) to ANOTHER user. Then the collect won't collec...
[ "def", "post_collect", "(", "self", ",", "obj", ")", ":", "if", "not", "self", ".", "ALLOWS_SAME_TYPE_AS_ROOT_COLLECT", ":", "for", "field", "in", "self", ".", "get_local_fields", "(", "obj", ")", ":", "if", "isinstance", "(", "field", ",", "ForeignKey", "...
53.111111
28.518519
def processFlat(self): """Main process. Returns ------- est_idxs : np.array(N) Estimated indeces the segment boundaries in frame indeces. est_labels : np.array(N-1) Estimated labels for the segments. """ # Preprocess to obtain features (arr...
[ "def", "processFlat", "(", "self", ")", ":", "# Preprocess to obtain features (array(n_frames, n_features))", "F", "=", "self", ".", "_preprocess", "(", ")", "F", "=", "librosa", ".", "util", ".", "normalize", "(", "F", ",", "axis", "=", "0", ")", "F", "=", ...
33.75
19.708333
def union(inputtiles, parsenames): """ Returns the unioned shape of a steeam of [<x>, <y>, <z>] tiles in GeoJSON. """ try: inputtiles = click.open_file(inputtiles).readlines() except IOError: inputtiles = [inputtiles] unioned = uniontiles.union(inputtiles, parsenames) for u i...
[ "def", "union", "(", "inputtiles", ",", "parsenames", ")", ":", "try", ":", "inputtiles", "=", "click", ".", "open_file", "(", "inputtiles", ")", ".", "readlines", "(", ")", "except", "IOError", ":", "inputtiles", "=", "[", "inputtiles", "]", "unioned", ...
32.181818
14.909091
def pitch_hz_to_contour(annotation): '''Convert a pitch_hz annotation to a contour''' annotation.namespace = 'pitch_contour' data = annotation.pop_data() for obs in data: annotation.append(time=obs.time, duration=obs.duration, confidence=obs.confidence, ...
[ "def", "pitch_hz_to_contour", "(", "annotation", ")", ":", "annotation", ".", "namespace", "=", "'pitch_contour'", "data", "=", "annotation", ".", "pop_data", "(", ")", "for", "obs", "in", "data", ":", "annotation", ".", "append", "(", "time", "=", "obs", ...
40.583333
15.75
def kalman_transition(filtered_mean, filtered_cov, transition_matrix, transition_noise): """Propagate a filtered distribution through a transition model.""" predicted_mean = _propagate_mean(filtered_mean, transition_matrix, ...
[ "def", "kalman_transition", "(", "filtered_mean", ",", "filtered_cov", ",", "transition_matrix", ",", "transition_noise", ")", ":", "predicted_mean", "=", "_propagate_mean", "(", "filtered_mean", ",", "transition_matrix", ",", "transition_noise", ")", "predicted_cov", "...
47
12
def ensure_started(self): """Idempotent channel start""" if self.active: return self self._observer = self._observer_class(**self._observer_params) self.start() self._active = True return self
[ "def", "ensure_started", "(", "self", ")", ":", "if", "self", ".", "active", ":", "return", "self", "self", ".", "_observer", "=", "self", ".", "_observer_class", "(", "*", "*", "self", ".", "_observer_params", ")", "self", ".", "start", "(", ")", "sel...
30.625
16.625
def mkhead(repo, path): """:return: New branch/head instance""" return git.Head(repo, git.Head.to_full_path(path))
[ "def", "mkhead", "(", "repo", ",", "path", ")", ":", "return", "git", ".", "Head", "(", "repo", ",", "git", ".", "Head", ".", "to_full_path", "(", "path", ")", ")" ]
40
10.333333
def validate(self, val): """ A unicode string of the correct length and pattern will pass validation. In PY2, we enforce that a str type must be valid utf-8, and a unicode string will be returned. """ if not isinstance(val, six.string_types): raise ValidationE...
[ "def", "validate", "(", "self", ",", "val", ")", ":", "if", "not", "isinstance", "(", "val", ",", "six", ".", "string_types", ")", ":", "raise", "ValidationError", "(", "\"'%s' expected to be a string, got %s\"", "%", "(", "val", ",", "generic_type_name", "(",...
48.653846
22.576923
async def _query( self, path, method="GET", *, params=None, data=None, headers=None, timeout=None, chunked=None ): """ Get the response object by performing the HTTP request. The caller is responsible to finalize the res...
[ "async", "def", "_query", "(", "self", ",", "path", ",", "method", "=", "\"GET\"", ",", "*", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "timeout", "=", "None", ",", "chunked", "=", "None", ")", ":", "u...
32.102564
17.692308
def list_deep_types(list_): """ Returns all types in a deep list """ type_list = [] for item in list_: if util_type.is_listlike(item): type_list.extend(list_deep_types(item)) else: type_list.append(type(item)) return type_list
[ "def", "list_deep_types", "(", "list_", ")", ":", "type_list", "=", "[", "]", "for", "item", "in", "list_", ":", "if", "util_type", ".", "is_listlike", "(", "item", ")", ":", "type_list", ".", "extend", "(", "list_deep_types", "(", "item", ")", ")", "e...
25.454545
10.545455
def timeout_per_mb(seconds_per_mb, size_bytes): """ Scales timeouts which are size-specific """ result = seconds_per_mb * (size_bytes / 1e6) if result < DEFAULT_TIMEOUT: return DEFAULT_TIMEOUT return result
[ "def", "timeout_per_mb", "(", "seconds_per_mb", ",", "size_bytes", ")", ":", "result", "=", "seconds_per_mb", "*", "(", "size_bytes", "/", "1e6", ")", "if", "result", "<", "DEFAULT_TIMEOUT", ":", "return", "DEFAULT_TIMEOUT", "return", "result" ]
37.5
9.333333
def move_window(self, window, x, y): """ Move a window to a specific location. The top left corner of the window will be moved to the x,y coordinate. :param wid: the window to move :param x: the X coordinate to move to. :param y: the Y coordinate to move to. """...
[ "def", "move_window", "(", "self", ",", "window", ",", "x", ",", "y", ")", ":", "_libxdo", ".", "xdo_move_window", "(", "self", ".", "_xdo", ",", "window", ",", "x", ",", "y", ")" ]
33.363636
14.272727
def entry_assemble(entry_fields, ecc_params, header_size, filepath, fileheader=None): '''From an entry with its parameters (filename, filesize), assemble a list of each block from the original file along with the relative hash and ecc for easy processing later.''' # Extract the header from the file if fileh...
[ "def", "entry_assemble", "(", "entry_fields", ",", "ecc_params", ",", "header_size", ",", "filepath", ",", "fileheader", "=", "None", ")", ":", "# Extract the header from the file", "if", "fileheader", "is", "None", ":", "with", "open", "(", "filepath", ",", "'r...
72.681818
47.318182
def broadcast_transaction(hex_tx, blockchain_client): """ Dispatches a raw hex transaction to the network. """ if isinstance(blockchain_client, BlockcypherClient): return blockcypher.broadcast_transaction(hex_tx, blockchain_client) elif isinstance(blockchain_client, BlockchainInfoClient): ...
[ "def", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", ":", "if", "isinstance", "(", "blockchain_client", ",", "BlockcypherClient", ")", ":", "return", "blockcypher", ".", "broadcast_transaction", "(", "hex_tx", ",", "blockchain_client", ")", ...
58.058824
22.705882
def prop_modifier(self, cls: ClassDefinition, slot: SlotDefinition) -> str: """ Return the modifiers for the slot: (i) - inherited (m) - inherited through mixin (a) - injected (pk) - primary ckey @param cls: @param slot: @return: "...
[ "def", "prop_modifier", "(", "self", ",", "cls", ":", "ClassDefinition", ",", "slot", ":", "SlotDefinition", ")", "->", "str", ":", "pk", "=", "'(pk)'", "if", "slot", ".", "primary_key", "else", "''", "inherited", "=", "slot", ".", "name", "not", "in", ...
45.105263
21.157895
def _clean_xml(self, path_to_xml): """Clean MARCXML harvested from OAI. Allows the xml to be used with BibUpload or BibRecord. :param xml: either XML as a string or path to an XML file :return: ElementTree of clean data """ try: if os.path.isfile(path_to_xm...
[ "def", "_clean_xml", "(", "self", ",", "path_to_xml", ")", ":", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "path_to_xml", ")", ":", "tree", "=", "ET", ".", "parse", "(", "path_to_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")...
31.6
16.95
def _next_with_retry(self): """Return the next chunk and retry once on CursorNotFound. We retry on CursorNotFound to maintain backwards compatibility in cases where two calls to read occur more than 10 minutes apart (the server's default cursor timeout). """ if self._cur...
[ "def", "_next_with_retry", "(", "self", ")", ":", "if", "self", ".", "_cursor", "is", "None", ":", "self", ".", "_create_cursor", "(", ")", "try", ":", "return", "self", ".", "_cursor", ".", "next", "(", ")", "except", "CursorNotFound", ":", "self", "....
33.8125
14.625
def LogoOverlay(sites, overlayfile, overlay, nperline, sitewidth, rmargin, logoheight, barheight, barspacing, fix_limits={}, fixlongname=False, overlay_cmap=None, underlay=False, scalebar=False): """Makes overlay for *LogoPlot*. This function creates colored bars overlay bars showing up to two properties. ...
[ "def", "LogoOverlay", "(", "sites", ",", "overlayfile", ",", "overlay", ",", "nperline", ",", "sitewidth", ",", "rmargin", ",", "logoheight", ",", "barheight", ",", "barspacing", ",", "fix_limits", "=", "{", "}", ",", "fixlongname", "=", "False", ",", "ove...
50.287611
24.495575
def eigen_decomposition(G, n_components=8, eigen_solver='auto', random_state=None, drop_first=True, largest=True, solver_kwds=None): """ Function to compute the eigendecomposition of a square matrix. Parameters ---------- G : array_like or sparse matr...
[ "def", "eigen_decomposition", "(", "G", ",", "n_components", "=", "8", ",", "eigen_solver", "=", "'auto'", ",", "random_state", "=", "None", ",", "drop_first", "=", "True", ",", "largest", "=", "True", ",", "solver_kwds", "=", "None", ")", ":", "n_nodes", ...
42.867133
18.769231
def process_args(): """ Parse command-line arguments. """ parser = argparse.ArgumentParser( description=("A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!")) parser.add_argument('prefix', ...
[ "def", "process_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "\"A script which can be run to tune a NeuroML 2 model against a number of target properties. Work in progress!\"", ")", ")", "parser", ".", "add_argument", "...
42.85443
13.594937
def uniform(low:Number, high:Number=None, size:Optional[List[int]]=None)->FloatOrTensor: "Draw 1 or shape=`size` random floats from uniform dist: min=`low`, max=`high`." if high is None: high=low return random.uniform(low,high) if size is None else torch.FloatTensor(*listify(size)).uniform_(low,high)
[ "def", "uniform", "(", "low", ":", "Number", ",", "high", ":", "Number", "=", "None", ",", "size", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "FloatOrTensor", ":", "if", "high", "is", "None", ":", "high", "=", "lo...
77.5
43
def _is_small_molecule(pe): """Return True if the element is a small molecule""" val = isinstance(pe, _bp('SmallMolecule')) or \ isinstance(pe, _bpimpl('SmallMolecule')) or \ isinstance(pe, _bp('SmallMoleculeReference')) or \ isinstance(pe, _bpimpl('SmallMoleculeReference')) ...
[ "def", "_is_small_molecule", "(", "pe", ")", ":", "val", "=", "isinstance", "(", "pe", ",", "_bp", "(", "'SmallMolecule'", ")", ")", "or", "isinstance", "(", "pe", ",", "_bpimpl", "(", "'SmallMolecule'", ")", ")", "or", "isinstance", "(", "pe", ",", "_...
46.857143
15.714286
def get_lattice_vector_equivalence(point_symmetry): """Return (b==c, c==a, a==b)""" # primitive_vectors: column vectors equivalence = [False, False, False] for r in point_symmetry: if (np.abs(r[:, 0]) == [0, 1, 0]).all(): equivalence[2] = True if (np.abs(r[:, 0]) == [0, 0, 1...
[ "def", "get_lattice_vector_equivalence", "(", "point_symmetry", ")", ":", "# primitive_vectors: column vectors", "equivalence", "=", "[", "False", ",", "False", ",", "False", "]", "for", "r", "in", "point_symmetry", ":", "if", "(", "np", ".", "abs", "(", "r", ...
35
10.65
def _set_af_ipv4_unicast(self, v, load=False): """ Setter method for af_ipv4_unicast, mapped from YANG variable /routing_system/router/isis/router_isis_cmds_holder/address_family/ipv4/af_ipv4_unicast (container) If this variable is read-only (config: false) in the source YANG file, then _set_af_ipv4_uni...
[ "def", "_set_af_ipv4_unicast", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
93.818182
45.409091
def compute_partial_energy(self, removed_indices): """ Gives total ewald energy for certain sites being removed, i.e. zeroed out. """ total_energy_matrix = self.total_energy_matrix.copy() for i in removed_indices: total_energy_matrix[i, :] = 0 tota...
[ "def", "compute_partial_energy", "(", "self", ",", "removed_indices", ")", ":", "total_energy_matrix", "=", "self", ".", "total_energy_matrix", ".", "copy", "(", ")", "for", "i", "in", "removed_indices", ":", "total_energy_matrix", "[", "i", ",", ":", "]", "="...
38.1
10.9
def get_bin_hierarchy_design_session(self): """Gets the bin hierarchy design session. return: (osid.resource.BinHierarchyDesignSession) - a ``BinHierarchyDesignSession`` raise: OperationFailed - unable to complete request raise: Unimplemented - ``supports_bin_hierarchy...
[ "def", "get_bin_hierarchy_design_session", "(", "self", ")", ":", "if", "not", "self", ".", "supports_bin_hierarchy_design", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", ".", "BinHierarchyDesign...
42.9375
16.6875
def server_chan_push(title, content, key=None): """使用server酱推送消息到微信,关于server酱, 请参考:http://sc.ftqq.com/3.version :param title: str 消息标题 :param content: str 消息内容,最长64Kb,可空,支持MarkDown :param key: str 从[Server酱](https://sc.ftqq.com/3.version)获取的key :return: None """ ...
[ "def", "server_chan_push", "(", "title", ",", "content", ",", "key", "=", "None", ")", ":", "if", "not", "key", ":", "raise", "ValueError", "(", "\"请配置key,如果还没有key,\"", "\"可以到这里申请一个:http://sc.ftqq.com/3.version\")", "", "url", "=", "'https://sc.ftqq.com/%s.send'", "...
31.411765
15.352941
def copy_config_from_repo(namespace, workspace, from_cnamespace, from_config, from_snapshot_id, to_cnamespace, to_config): """Copy a method config from the methods repository to a workspace. Args: namespace (str): project to which workspace belongs ...
[ "def", "copy_config_from_repo", "(", "namespace", ",", "workspace", ",", "from_cnamespace", ",", "from_config", ",", "from_snapshot_id", ",", "to_cnamespace", ",", "to_config", ")", ":", "body", "=", "{", "\"configurationNamespace\"", ":", "from_cnamespace", ",", "\...
43.551724
21.068966
def save(self, dbfile=None, password=None, keyfile=None): """ Save the database to specified file/stream with password and/or keyfile. :param dbfile: The path to the file we wish to save. :type dbfile: The path to the database file or a file-like object. :param...
[ "def", "save", "(", "self", ",", "dbfile", "=", "None", ",", "password", "=", "None", ",", "keyfile", "=", "None", ")", ":", "if", "self", ".", "readonly", ":", "# We might wish to make this more sophisticated. E.g. if a new path is specified", "# as a parameter, the...
44.535714
21.892857
def make_api_call(self, method, url, json_params=None): """ Accesses the branch API :param method: The HTTP method :param url: The URL :param json_params: JSON parameters :return: The parsed response """ url = self.BRANCH_BASE_URI+url if self.ver...
[ "def", "make_api_call", "(", "self", ",", "method", ",", "url", ",", "json_params", "=", "None", ")", ":", "url", "=", "self", ".", "BRANCH_BASE_URI", "+", "url", "if", "self", ".", "verbose", "is", "True", ":", "print", "(", "\"Making web request: {}\"", ...
32.714286
15.714286
def save_load(jid, load, minions=None): ''' Save the load to the specified jid ''' serv = _get_serv(ret=None) serv.set(jid, salt.utils.json.dumps(load)) _append_list(serv, 'jids', jid)
[ "def", "save_load", "(", "jid", ",", "load", ",", "minions", "=", "None", ")", ":", "serv", "=", "_get_serv", "(", "ret", "=", "None", ")", "serv", ".", "set", "(", "jid", ",", "salt", ".", "utils", ".", "json", ".", "dumps", "(", "load", ")", ...
28.857143
12.857143
def dict_diff(d1: Dict[Any, Any], d2: Dict[Any, Any], deleted_value: Any = None) -> Dict[Any, Any]: """ Returns a representation of the changes that need to be made to ``d1`` to create ``d2``. Args: d1: a dictionary d2: another dictionary deleted_value: value to us...
[ "def", "dict_diff", "(", "d1", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "d2", ":", "Dict", "[", "Any", ",", "Any", "]", ",", "deleted_value", ":", "Any", "=", "None", ")", "->", "Dict", "[", "Any", ",", "Any", "]", ":", "changes", "=", ...
37.4
22.84
def NewFromCmyk(c, m, y, k, alpha=1.0, wref=_DEFAULT_WREF): '''Create a new instance based on the specifed CMYK values. Parameters: :c: The Cyan component value [0...1] :m: The Magenta component value [0...1] :y: The Yellow component value [0...1] :k: The...
[ "def", "NewFromCmyk", "(", "c", ",", "m", ",", "y", ",", "k", ",", "alpha", "=", "1.0", ",", "wref", "=", "_DEFAULT_WREF", ")", ":", "return", "Color", "(", "Color", ".", "CmyToRgb", "(", "*", "Color", ".", "CmykToCmy", "(", "c", ",", "m", ",", ...
27.962963
22.259259
def run_tutorial(plot=False, process_len=3600, num_cores=cpu_count()): """Main function to run the tutorial dataset.""" # First we want to load our templates template_names = glob.glob('tutorial_template_*.ms') if len(template_names) == 0: raise IOError('Template files not found, have you run t...
[ "def", "run_tutorial", "(", "plot", "=", "False", ",", "process_len", "=", "3600", ",", "num_cores", "=", "cpu_count", "(", ")", ")", ":", "# First we want to load our templates", "template_names", "=", "glob", ".", "glob", "(", "'tutorial_template_*.ms'", ")", ...
44.936937
20.378378
def compute_ngrams(word_list, S=3, T=3): """Compute NGrams in the word_list from [S-T) Args: word_list (list): A list of words to compute ngram set from S (int): The smallest NGram (default=3) T (int): The biggest NGram (default=3) """ _ngrams = [] if isinstan...
[ "def", "compute_ngrams", "(", "word_list", ",", "S", "=", "3", ",", "T", "=", "3", ")", ":", "_ngrams", "=", "[", "]", "if", "isinstance", "(", "word_list", ",", "str", ")", ":", "word_list", "=", "[", "word_list", "]", "for", "word", "in", "word_l...
37.571429
12
def concat(cls, variables, dim='concat_dim', positions=None, shortcut=False): """Concatenate variables along a new or existing dimension. Parameters ---------- variables : iterable of Array Arrays to stack together. Each variable is expected to have ...
[ "def", "concat", "(", "cls", ",", "variables", ",", "dim", "=", "'concat_dim'", ",", "positions", "=", "None", ",", "shortcut", "=", "False", ")", ":", "if", "not", "isinstance", "(", "dim", ",", "str", ")", ":", "dim", ",", "=", "dim", ".", "dims"...
41.861538
19.8
def getSpec(cls): """ Return the Spec for ApicalTMSequenceRegion. """ spec = { "description": ApicalTMSequenceRegion.__doc__, "singleNodeOnly": True, "inputs": { "activeColumns": { "description": ("An array of 0's and 1's representing the active " ...
[ "def", "getSpec", "(", "cls", ")", ":", "spec", "=", "{", "\"description\"", ":", "ApicalTMSequenceRegion", ".", "__doc__", ",", "\"singleNodeOnly\"", ":", "True", ",", "\"inputs\"", ":", "{", "\"activeColumns\"", ":", "{", "\"description\"", ":", "(", "\"An a...
34.186722
18.751037
def from_file (self, file, file_location, project): """ Creates a virtual target with appropriate name and type from 'file'. If a target with that name in that project was already created, returns that already created target. TODO: more correct way would be to compute path to...
[ "def", "from_file", "(", "self", ",", "file", ",", "file_location", ",", "project", ")", ":", "if", "__debug__", ":", "from", ".", "targets", "import", "ProjectTarget", "assert", "isinstance", "(", "file", ",", "basestring", ")", "assert", "isinstance", "(",...
44.740741
21.444444
def clear(self): """ Clears the context. """ self._objects.clear() self._class_aliases = {} self._unicodes = {} self.extra = {}
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_objects", ".", "clear", "(", ")", "self", ".", "_class_aliases", "=", "{", "}", "self", ".", "_unicodes", "=", "{", "}", "self", ".", "extra", "=", "{", "}" ]
22
10.75
def entries(self): """A list of :class:`PasswordEntry` objects.""" passwords = [] for store in self.stores: passwords.extend(store.entries) return natsort(passwords, key=lambda e: e.name)
[ "def", "entries", "(", "self", ")", ":", "passwords", "=", "[", "]", "for", "store", "in", "self", ".", "stores", ":", "passwords", ".", "extend", "(", "store", ".", "entries", ")", "return", "natsort", "(", "passwords", ",", "key", "=", "lambda", "e...
37.666667
10.833333
def confirm_login(): ''' This sets the current session as fresh. Sessions become stale when they are reloaded from a cookie. ''' session['_fresh'] = True session['_id'] = current_app.login_manager._session_identifier_generator() user_login_confirmed.send(current_app._get_current_object())
[ "def", "confirm_login", "(", ")", ":", "session", "[", "'_fresh'", "]", "=", "True", "session", "[", "'_id'", "]", "=", "current_app", ".", "login_manager", ".", "_session_identifier_generator", "(", ")", "user_login_confirmed", ".", "send", "(", "current_app", ...
38.75
25.5
def _save_pys(self, filepath): """Saves file as pys file and returns True if save success Parameters ---------- filepath: String \tTarget file path for xls file """ try: with Bz2AOpen(filepath, "wb", main_window=self.main_...
[ "def", "_save_pys", "(", "self", ",", "filepath", ")", ":", "try", ":", "with", "Bz2AOpen", "(", "filepath", ",", "\"wb\"", ",", "main_window", "=", "self", ".", "main_window", ")", "as", "outfile", ":", "interface", "=", "Pys", "(", "self", ".", "grid...
28.37037
19.444444
def scale_0to1(image_in, exclude_outliers_below=False, exclude_outliers_above=False): """Scale the two images to [0, 1] based on min/max from both. Parameters ----------- image_in : ndarray Input image exclude_outliers_{below,above} : float Lower/upper...
[ "def", "scale_0to1", "(", "image_in", ",", "exclude_outliers_below", "=", "False", ",", "exclude_outliers_above", "=", "False", ")", ":", "min_value", "=", "image_in", ".", "min", "(", ")", "max_value", "=", "image_in", ".", "max", "(", ")", "# making a copy t...
25.666667
20.333333
def floats(self, n: int = 2) -> List[float]: """Generate a list of random float numbers. :param n: Raise 10 to the 'n' power. :return: The list of floating-point numbers. """ nums = [self.random.random() for _ in range(10 ** int(n))] return nums
[ "def", "floats", "(", "self", ",", "n", ":", "int", "=", "2", ")", "->", "List", "[", "float", "]", ":", "nums", "=", "[", "self", ".", "random", ".", "random", "(", ")", "for", "_", "in", "range", "(", "10", "**", "int", "(", "n", ")", ")"...
33.555556
10
def register(cls, name, type_): """ Register a new type for an entry-type. The 2nd argument has to be a subclass of structures.Entry. """ if not issubclass(type_, Entry): raise exceptions.InvalidEntryType("%s is not a subclass of Entry" % str(type_)) cls._reg...
[ "def", "register", "(", "cls", ",", "name", ",", "type_", ")", ":", "if", "not", "issubclass", "(", "type_", ",", "Entry", ")", ":", "raise", "exceptions", ".", "InvalidEntryType", "(", "\"%s is not a subclass of Entry\"", "%", "str", "(", "type_", ")", ")...
37.666667
15.666667
def acquire(self, waitflag=None): """Dummy implementation of acquire(). For blocking calls, self.locked_status is automatically set to True and returned appropriately based on value of ``waitflag``. If it is non-blocking, then the value is actually checked and not set if it is ...
[ "def", "acquire", "(", "self", ",", "waitflag", "=", "None", ")", ":", "if", "waitflag", "is", "None", "or", "waitflag", ":", "self", ".", "locked_status", "=", "True", "return", "True", "else", ":", "if", "not", "self", ".", "locked_status", ":", "sel...
36.35
15.95
def print_diff(self, summary1=None, summary2=None): """Compute diff between to summaries and print it. If no summary is provided, the diff from the last to the current summary is used. If summary1 is provided the diff from summary1 to the current summary is used. If summary1 and summary...
[ "def", "print_diff", "(", "self", ",", "summary1", "=", "None", ",", "summary2", "=", "None", ")", ":", "summary", ".", "print_", "(", "self", ".", "diff", "(", "summary1", "=", "summary1", ",", "summary2", "=", "summary2", ")", ")" ]
50.555556
20.666667
def searchResults(self, REQUEST=None, used=None, **kw): """Search the catalog Search terms can be passed in the REQUEST or as keyword arguments. The used argument is now deprecated and ignored """ if REQUEST and REQUEST.get('getRequestUID') \ and self.id == CATALOG_ANALYSIS_LISTING...
[ "def", "searchResults", "(", "self", ",", "REQUEST", "=", "None", ",", "used", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "REQUEST", "and", "REQUEST", ".", "get", "(", "'getRequestUID'", ")", "and", "self", ".", "id", "==", "CATALOG_ANALYSIS_LIS...
38.487805
21.804878
def table_width(outer_widths, outer_border, inner_border): """Determine the width of the entire table including borders and padding. :param iter outer_widths: List of widths (with padding) for each column. :param int outer_border: Sum of left and right outer border visible widths. :param int inner_bord...
[ "def", "table_width", "(", "outer_widths", ",", "outer_border", ",", "inner_border", ")", ":", "column_count", "=", "len", "(", "outer_widths", ")", "# Count how much space outer and inner borders take up.", "non_data_space", "=", "outer_border", "if", "column_count", ":"...
37.25
19.85
def RemoveBackground(EPIC, campaign=None): ''' Returns :py:obj:`True` or :py:obj:`False`, indicating whether or not to remove the background flux for the target. If ``campaign < 3``, returns :py:obj:`True`, otherwise returns :py:obj:`False`. ''' if campaign is None: campaign = Campaign...
[ "def", "RemoveBackground", "(", "EPIC", ",", "campaign", "=", "None", ")", ":", "if", "campaign", "is", "None", ":", "campaign", "=", "Campaign", "(", "EPIC", ")", "if", "hasattr", "(", "campaign", ",", "'__len__'", ")", ":", "raise", "AttributeError", "...
31.058824
23.529412
def usearch61_fast_cluster(intermediate_fasta, percent_id=0.97, minlen=64, output_dir=".", remove_usearch_logs=False, wordlength=8, usearch61_maxrejects=8, ...
[ "def", "usearch61_fast_cluster", "(", "intermediate_fasta", ",", "percent_id", "=", "0.97", ",", "minlen", "=", "64", ",", "output_dir", "=", "\".\"", ",", "remove_usearch_logs", "=", "False", ",", "wordlength", "=", "8", ",", "usearch61_maxrejects", "=", "8", ...
39.727273
17.2
def select_by_visible_text(self, text): """Select all options that display text matching the argument. That is, when given "Bar" this would select an option like: <option value="foo">Bar</option> :Args: - text - The visible text to match against throw...
[ "def", "select_by_visible_text", "(", "self", ",", "text", ")", ":", "xpath", "=", "\".//option[normalize-space(.) = %s]\"", "%", "self", ".", "_escapeString", "(", "text", ")", "opts", "=", "self", ".", "_el", ".", "find_elements", "(", "By", ".", "XPATH", ...
39.666667
18.472222
def BeginEdit(self, row, col, grid): """ Fetch the value from the table and prepare the edit control to begin editing. Set the focus to the edit control. *Must Override* """ # Disable if cell is locked, enable if cell is not locked grid = self.main_window.grid ...
[ "def", "BeginEdit", "(", "self", ",", "row", ",", "col", ",", "grid", ")", ":", "# Disable if cell is locked, enable if cell is not locked", "grid", "=", "self", ".", "main_window", ".", "grid", "key", "=", "grid", ".", "actions", ".", "cursor", "locked", "=",...
34.954545
21.924242
def _make_auth(self, method, date, nonce, path, query={}, ctype='application/json'): ''' Create the request signature to authenticate Args: - method (str): HTTP method - date (str): HTTP date header string - nonce (str): Cryptographic nonce - path...
[ "def", "_make_auth", "(", "self", ",", "method", ",", "date", ",", "nonce", ",", "path", ",", "query", "=", "{", "}", ",", "ctype", "=", "'application/json'", ")", ":", "query", "=", "urlencode", "(", "query", ")", "hmac_str", "=", "(", "method", "+"...
36.566667
25.9
def load_dynamic_config(config_file=DEFAULT_DYNAMIC_CONFIG_FILE): """Load and parse dynamic config""" dynamic_configurations = {} # Insert config path so we can import it sys.path.insert(0, path.dirname(path.abspath(config_file))) try: config_module = __import__('config') dynamic_c...
[ "def", "load_dynamic_config", "(", "config_file", "=", "DEFAULT_DYNAMIC_CONFIG_FILE", ")", ":", "dynamic_configurations", "=", "{", "}", "# Insert config path so we can import it", "sys", ".", "path", ".", "insert", "(", "0", ",", "path", ".", "dirname", "(", "path"...
36.266667
21
def show_rendered_files(results_dict): """ Parses a nested dictionary returned from :meth:`Hub.render` and just prints the resulting files. """ for k, v in results_dict.items(): if isinstance(v, string_types): print("rendered file: %s (created by: %s)" % (v, k)) else: ...
[ "def", "show_rendered_files", "(", "results_dict", ")", ":", "for", "k", ",", "v", "in", "results_dict", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "string_types", ")", ":", "print", "(", "\"rendered file: %s (created by: %s)\"", "%", "(...
32
13.454545
def validate_query(self, using=None, **kwargs): """ Validate a potentially expensive query without executing it. Any additional keyword arguments will be passed to ``Elasticsearch.indices.validate_query`` unchanged. """ return self._get_connection(using).indices.validate...
[ "def", "validate_query", "(", "self", ",", "using", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_get_connection", "(", "using", ")", ".", "indices", ".", "validate_query", "(", "index", "=", "self", ".", "_name", ",", "*", ...
43.375
20.625
def get_sigma_tables(self, imt, rctx, stddev_types): """ Returns modification factors for the standard deviations, given the rupture and intensity measure type. :returns: List of standard deviation modification tables, each as an array of [Number Distances, Numbe...
[ "def", "get_sigma_tables", "(", "self", ",", "imt", ",", "rctx", ",", "stddev_types", ")", ":", "output_tables", "=", "[", "]", "for", "stddev_type", "in", "stddev_types", ":", "# For PGA and PGV only needs to apply magnitude interpolation", "if", "imt", ".", "name"...
45.030303
19.030303
def batch_size(self): """int: The number of results to fetch per batch. Clamped to limit if limit is set and is smaller than the given batch size. """ batch_size = self.get("batch_size", DEFAULT_BATCH_SIZE) if self.limit is not None: return min(self.limit, ba...
[ "def", "batch_size", "(", "self", ")", ":", "batch_size", "=", "self", ".", "get", "(", "\"batch_size\"", ",", "DEFAULT_BATCH_SIZE", ")", "if", "self", ".", "limit", "is", "not", "None", ":", "return", "min", "(", "self", ".", "limit", ",", "batch_size",...
38.555556
13.444444
def process_index(self, url, page): """Process the contents of a PyPI page""" def scan(link): # Process a URL to see if it's for a package page if link.startswith(self.index_url): parts = list(map( urllib.parse.unquote, link[len(self.index_url...
[ "def", "process_index", "(", "self", ",", "url", ",", "page", ")", ":", "def", "scan", "(", "link", ")", ":", "# Process a URL to see if it's for a package page", "if", "link", ".", "startswith", "(", "self", ".", "index_url", ")", ":", "parts", "=", "list",...
39.595238
19.047619
def argmax(attrs, inputs, proto_obj): """Returns indices of the maximum values along an axis""" axis = attrs.get('axis', 0) keepdims = attrs.get('keepdims', 1) argmax_op = symbol.argmax(inputs[0], axis=axis, keepdims=keepdims) # onnx argmax operator always expects int64 as output type cast_attrs...
[ "def", "argmax", "(", "attrs", ",", "inputs", ",", "proto_obj", ")", ":", "axis", "=", "attrs", ".", "get", "(", "'axis'", ",", "0", ")", "keepdims", "=", "attrs", ".", "get", "(", "'keepdims'", ",", "1", ")", "argmax_op", "=", "symbol", ".", "argm...
46.875
8.75
def compile_create(self, blueprint, command, _): """ Compile a create table command. """ columns = ', '.join(self._get_columns(blueprint)) sql = 'CREATE TABLE %s (%s' % (self.wrap_table(blueprint), columns) sql += self._add_foreign_keys(blueprint) sql += self._...
[ "def", "compile_create", "(", "self", ",", "blueprint", ",", "command", ",", "_", ")", ":", "columns", "=", "', '", ".", "join", "(", "self", ".", "_get_columns", "(", "blueprint", ")", ")", "sql", "=", "'CREATE TABLE %s (%s'", "%", "(", "self", ".", "...
27.769231
19.461538
def exvp(x, y, x0, y0, c2, c4, theta0, ff): """Convert virtual pixel(s) to real pixel(s). This function makes use of exvp_scalar(), which performs the conversion for a single point (x, y), over an array of X and Y values. Parameters ---------- x : array-like X coordinate (pixel). ...
[ "def", "exvp", "(", "x", ",", "y", ",", "x0", ",", "y0", ",", "c2", ",", "c4", ",", "theta0", ",", "ff", ")", ":", "if", "all", "(", "[", "np", ".", "isscalar", "(", "x", ")", ",", "np", ".", "isscalar", "(", "y", ")", "]", ")", ":", "x...
30.66
20.14
def custom_getter_scope(custom_getter): """ Args: custom_getter: the same as in :func:`tf.get_variable` Returns: The current variable scope with a custom_getter. """ scope = tf.get_variable_scope() if get_tf_version_tuple() >= (1, 5): with tf.variable_scope( ...
[ "def", "custom_getter_scope", "(", "custom_getter", ")", ":", "scope", "=", "tf", ".", "get_variable_scope", "(", ")", "if", "get_tf_version_tuple", "(", ")", ">=", "(", "1", ",", "5", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "cu...
31.45
14.35
def get_player_img(player_id): """ Returns the image of the player from stats.nba.com as a numpy array and saves the image as PNG file in the current directory. Parameters ---------- player_id: int The player ID used to find the image. Returns ------- player_img: ndarray ...
[ "def", "get_player_img", "(", "player_id", ")", ":", "url", "=", "\"http://stats.nba.com/media/players/230x185/\"", "+", "str", "(", "player_id", ")", "+", "\".png\"", "img_file", "=", "str", "(", "player_id", ")", "+", "\".png\"", "pic", "=", "urlretrieve", "("...
29.238095
20.190476
def add_to(self, parent, **kwargs): # type: (Part, **Any) -> Part """Add a new instance of this model to a part. This works if the current part is a model and an instance of this model is to be added to a part instances in the tree. In order to prevent the backend from updating...
[ "def", "add_to", "(", "self", ",", "parent", ",", "*", "*", "kwargs", ")", ":", "# type: (Part, **Any) -> Part", "if", "self", ".", "category", "!=", "Category", ".", "MODEL", ":", "raise", "APIError", "(", "\"Part should be of category MODEL\"", ")", "return", ...
42.84375
25
async def findTask(self, *args, **kwargs): """ Find Indexed Task Find a task by index path, returning the highest-rank task with that path. If no task exists for the given path, this API end-point will respond with a 404 status. This method gives output: ``v1/indexed-task-respo...
[ "async", "def", "findTask", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"findTask\"", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
34.615385
27.076923
def calculateLocalElasticitySegments(self, bp, span=2, frameGap=None, helical=False, unit='kT', err_type='block', tool='gmx analyze', outFile=None): """Calculate local elastic properties of consecutive overlapped DNA segments Calculate local elastic properties o...
[ "def", "calculateLocalElasticitySegments", "(", "self", ",", "bp", ",", "span", "=", "2", ",", "frameGap", "=", "None", ",", "helical", "=", "False", ",", "unit", "=", "'kT'", ",", "err_type", "=", "'block'", ",", "tool", "=", "'gmx analyze'", ",", "outF...
42.047059
28.176471
def put(self,specimen,coordinate_system,new_pars): """ Given a coordinate system and a new parameters dictionary that follows pmagpy convention given by the pmag.py/domean function it alters this fit's bounds and parameters such that it matches the new data. @param: specimen -> N...
[ "def", "put", "(", "self", ",", "specimen", ",", "coordinate_system", ",", "new_pars", ")", ":", "if", "specimen", "!=", "None", ":", "if", "type", "(", "new_pars", ")", "==", "dict", ":", "if", "'er_specimen_name'", "not", "in", "list", "(", "new_pars",...
55.894737
26.350877
async def update_watermark(self, update_watermark_request): """Update the watermark (read timestamp) of a conversation.""" response = hangouts_pb2.UpdateWatermarkResponse() await self._pb_request('conversations/updatewatermark', update_watermark_request, response) ...
[ "async", "def", "update_watermark", "(", "self", ",", "update_watermark_request", ")", ":", "response", "=", "hangouts_pb2", ".", "UpdateWatermarkResponse", "(", ")", "await", "self", ".", "_pb_request", "(", "'conversations/updatewatermark'", ",", "update_watermark_req...
56.333333
17
def p_annotation_spdx_id_1(self, p): """annotation_spdx_id : ANNOTATION_SPDX_ID LINE""" try: if six.PY2: value = p[2].decode(encoding='utf-8') else: value = p[2] self.builder.set_annotation_spdx_id(self.document, value) except C...
[ "def", "p_annotation_spdx_id_1", "(", "self", ",", "p", ")", ":", "try", ":", "if", "six", ".", "PY2", ":", "value", "=", "p", "[", "2", "]", ".", "decode", "(", "encoding", "=", "'utf-8'", ")", "else", ":", "value", "=", "p", "[", "2", "]", "s...
39.916667
16.083333
def indices_to_points(indices, pitch, origin): """ Convert indices of an (n,m,p) matrix into a set of voxel center points. Parameters ---------- indices: (q, 3) int, index of voxel matrix (n,m,p) pitch: float, what pitch was the voxel matrix computed with origin: (3,) float, what is the ori...
[ "def", "indices_to_points", "(", "indices", ",", "pitch", ",", "origin", ")", ":", "indices", "=", "np", ".", "asanyarray", "(", "indices", ",", "dtype", "=", "np", ".", "float64", ")", "origin", "=", "np", ".", "asanyarray", "(", "origin", ",", "dtype...
29.571429
20
def nl_send_simple(sk, type_, flags, buf=None, size=0): """Construct and transmit a Netlink message. https://github.com/thom311/libnl/blob/libnl3_2_25/lib/nl.c#L549 Allocates a new Netlink message based on `type_` and `flags`. If `buf` points to payload of length `size` that payload will be appended t...
[ "def", "nl_send_simple", "(", "sk", ",", "type_", ",", "flags", ",", "buf", "=", "None", ",", "size", "=", "0", ")", ":", "msg", "=", "nlmsg_alloc_simple", "(", "type_", ",", "flags", ")", "if", "buf", "is", "not", "None", "and", "size", ":", "err"...
32.607143
20.285714
def _flatten_models(tasklist): " Create 1d-array containing all disctinct models from ``tasklist``. " ans = gvar.BufferDict() for task, mlist in tasklist: if task != 'fit': continue for m in mlist: id_m = id(m) if id_m not i...
[ "def", "_flatten_models", "(", "tasklist", ")", ":", "ans", "=", "gvar", ".", "BufferDict", "(", ")", "for", "task", ",", "mlist", "in", "tasklist", ":", "if", "task", "!=", "'fit'", ":", "continue", "for", "m", "in", "mlist", ":", "id_m", "=", "id",...
34.727273
12.181818
def page(self, course): """ Get all data and display the page """ data = list(self.database.user_tasks.aggregate( [ { "$match": { "courseid": course.get_id(), "username": {"$in...
[ "def", "page", "(", "self", ",", "course", ")", ":", "data", "=", "list", "(", "self", ".", "database", ".", "user_tasks", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"userna...
44.875
23.6875
def impute(X, value=None, train=None, dropna=True, inplace=True): """ Performs mean imputation on a pandas dataframe. Args: train: an optional training mask with which to compute the mean value: instead of computing the mean, use this as the value argument to fillna dropna: whether t...
[ "def", "impute", "(", "X", ",", "value", "=", "None", ",", "train", "=", "None", ",", "dropna", "=", "True", ",", "inplace", "=", "True", ")", ":", "if", "value", "is", "None", ":", "Xfit", "=", "X", "[", "train", "]", "if", "train", "is", "not...
34.6875
21
def _param(self): """ Get/Set a parameter. """ class Parameters(object): def __getitem__(_self, name): return self.getParameter(name) def __setitem__(_self, name, value): if isinstance(value, (float, int, basestring)): ...
[ "def", "_param", "(", "self", ")", ":", "class", "Parameters", "(", "object", ")", ":", "def", "__getitem__", "(", "_self", ",", "name", ")", ":", "return", "self", ".", "getParameter", "(", "name", ")", "def", "__setitem__", "(", "_self", ",", "name",...
29.722222
15.388889
def error_buckets(gold, pred, X=None): """Group items by error buckets Args: gold: an array-like of gold labels (ints) pred: an array-like of predictions (ints) X: an iterable of items Returns: buckets: A dict of items where buckets[i,j] is a list of items with p...
[ "def", "error_buckets", "(", "gold", ",", "pred", ",", "X", "=", "None", ")", ":", "buckets", "=", "defaultdict", "(", "list", ")", "gold", "=", "arraylike_to_numpy", "(", "gold", ")", "pred", "=", "arraylike_to_numpy", "(", "pred", ")", "for", "i", ",...
34.625
14.625
def create_line_generator(self): """ Creates a generator function yielding lines in the file Should only yield non-empty lines """ if self.file_name.endswith(".gz"): if sys.version_info.major == 3: gz = gzip.open(self.file_name, mode='rt', encoding=se...
[ "def", "create_line_generator", "(", "self", ")", ":", "if", "self", ".", "file_name", ".", "endswith", "(", "\".gz\"", ")", ":", "if", "sys", ".", "version_info", ".", "major", "==", "3", ":", "gz", "=", "gzip", ".", "open", "(", "self", ".", "file_...
33.071429
20.5
def validateElement(self, ctxt, elem): """Try to validate the subtree under an element """ if ctxt is None: ctxt__o = None else: ctxt__o = ctxt._o if elem is None: elem__o = None else: elem__o = elem._o ret = libxml2mod.xmlValidateElement(ctxt__o, self._o, elem__o) ...
[ "def", "validateElement", "(", "self", ",", "ctxt", ",", "elem", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "if", "elem", "is", "None", ":", "elem__o", "=", "None", "else", ":"...
40.625
9.25
def find_share_ring(self, tree_map, parent_map, r): """ get a ring structure that tends to share nodes with the tree return a list starting from r """ nset = set(tree_map[r]) cset = nset - set([parent_map[r]]) if len(cset) == 0: return [r] rlst...
[ "def", "find_share_ring", "(", "self", ",", "tree_map", ",", "parent_map", ",", "r", ")", ":", "nset", "=", "set", "(", "tree_map", "[", "r", "]", ")", "cset", "=", "nset", "-", "set", "(", "[", "parent_map", "[", "r", "]", "]", ")", "if", "len",...
30.166667
13.833333
def read_response(self, response=None): '''Read the response's HTTP status line and header fields. Coroutine. ''' _logger.debug('Reading header.') if response is None: response = Response() header_lines = [] bytes_read = 0 while True: ...
[ "def", "read_response", "(", "self", ",", "response", "=", "None", ")", ":", "_logger", ".", "debug", "(", "'Reading header.'", ")", "if", "response", "is", "None", ":", "response", "=", "Response", "(", ")", "header_lines", "=", "[", "]", "bytes_read", ...
26.487805
20.487805
def classify_regions(dataset, masks, method='ERF', threshold=0.08, remove_overlap=True, regularization='scale', output='summary', studies=None, features=None, class_weight='auto', classifier=None, cross_val='4-Fold', param_grid=None, sc...
[ "def", "classify_regions", "(", "dataset", ",", "masks", ",", "method", "=", "'ERF'", ",", "threshold", "=", "0.08", ",", "remove_overlap", "=", "True", ",", "regularization", "=", "'scale'", ",", "output", "=", "'summary'", ",", "studies", "=", "None", ",...
53.45
25.116667
def _prepare_client(client_or_address): """ :param client_or_address: one of: * None * verbatim: 'local' * string address * a Client instance :return: a tuple: (Client instance, shutdown callback function). :raises: ValueError if no valid client input was prov...
[ "def", "_prepare_client", "(", "client_or_address", ")", ":", "if", "client_or_address", "is", "None", "or", "str", "(", "client_or_address", ")", ".", "lower", "(", ")", "==", "'local'", ":", "local_cluster", "=", "LocalCluster", "(", "diagnostics_port", "=", ...
29.851064
21.978723
def search_ap(self, mode, query): """搜索接入点 查看指定接入点的所有配置信息,包括所有监听端口的配置。 Args: - mode: 搜索模式,可以是domain、ip、host - query: 搜索文本 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回搜索结果,失败返回{"error": "<errMsg string...
[ "def", "search_ap", "(", "self", ",", "mode", ",", "query", ")", ":", "url", "=", "'{0}/v3/aps/search?{1}={2}'", ".", "format", "(", "self", ".", "host", ",", "mode", ",", "query", ")", "return", "self", ".", "__get", "(", "url", ")" ]
29.25
18.1875
def get_store_credit_by_id(cls, store_credit_id, **kwargs): """Find StoreCredit Return single instance of StoreCredit by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_store_credi...
[ "def", "get_store_credit_by_id", "(", "cls", ",", "store_credit_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_get_store_credi...
43.47619
21.380952
def namedAny(name): """ Retrieve a Python object by its fully qualified name from the global Python module namespace. The first part of the name, that describes a module, will be discovered and imported. Each subsequent part of the name is treated as the name of an attribute of the object specifie...
[ "def", "namedAny", "(", "name", ")", ":", "if", "not", "name", ":", "raise", "InvalidName", "(", "'Empty module name'", ")", "names", "=", "name", ".", "split", "(", "'.'", ")", "# if the name starts or ends with a '.' or contains '..', the __import__", "# will raise ...
36.344262
24.540984
def can_create_log_with_record_types(self, log_record_types): """Tests if this user can create a single ``Log`` using the desired record types. While ``LoggingManager.getLogRecordTypes()`` can be used to examine which records are supported, this method tests which record(s) are required...
[ "def", "can_create_log_with_record_types", "(", "self", ",", "log_record_types", ")", ":", "# Implemented from template for", "# osid.resource.BinAdminSession.can_create_bin_with_record_types", "# NOTE: It is expected that real authentication hints will be", "# handled in a service adapter abo...
50.44
25.4
def opticalModel(sim, ver: xarray.DataArray, obsAlt_km: float, zenithang: float): """ ver: Nalt x Nwavelength """ assert isinstance(ver, xarray.DataArray) # %% get system optical transmission T optT = getSystemT(ver.wavelength_nm, sim.bg3fn, sim.windowfn, sim.qefn, obsAlt_km, zenithang) # %% first ...
[ "def", "opticalModel", "(", "sim", ",", "ver", ":", "xarray", ".", "DataArray", ",", "obsAlt_km", ":", "float", ",", "zenithang", ":", "float", ")", ":", "assert", "isinstance", "(", "ver", ",", "xarray", ".", "DataArray", ")", "# %% get system optical trans...
43.421053
23.421053