text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def main(): """Read configuration and execute test runs.""" parser = argparse.ArgumentParser(description='Stress test applications.') parser.add_argument('config_path', help='Path to configuration file.') args = parser.parse_args() try: configuration = load_configuration(args.config_path) ...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Stress test applications.'", ")", "parser", ".", "add_argument", "(", "'config_path'", ",", "help", "=", "'Path to configuration file.'", ")", "args", "=", ...
41.65
19.7
def pop(self, key, default=__marker): '''od.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised. ''' if key in self: result = self[key] del self[key] retur...
[ "def", "pop", "(", "self", ",", "key", ",", "default", "=", "__marker", ")", ":", "if", "key", "in", "self", ":", "result", "=", "self", "[", "key", "]", "del", "self", "[", "key", "]", "return", "result", "if", "default", "is", "self", ".", "__m...
34.083333
20.75
def read_namespaced_deployment_scale(self, name, namespace, **kwargs): """ read scale of the specified Deployment This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_namespaced_deployment_...
[ "def", "read_namespaced_deployment_scale", "(", "self", ",", "name", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self",...
49.545455
23.363636
def _potential_wins(self): '''Generates all the combinations of board positions that need to be checked for a win.''' yield from self.board yield from zip(*self.board) yield self.board[0][0], self.board[1][1], self.board[2][2] yield self.board[0][2], self.board[1][1], sel...
[ "def", "_potential_wins", "(", "self", ")", ":", "yield", "from", "self", ".", "board", "yield", "from", "zip", "(", "*", "self", ".", "board", ")", "yield", "self", ".", "board", "[", "0", "]", "[", "0", "]", ",", "self", ".", "board", "[", "1",...
46.714286
16.714286
def clear_cache(self, items=None, topic=EVENT_TOPIC): """ expects event object to be in the format of a session-stop or session-expire event, whose results attribute is a namedtuple(identifiers, session_key) """ try: for realm in self.realms: i...
[ "def", "clear_cache", "(", "self", ",", "items", "=", "None", ",", "topic", "=", "EVENT_TOPIC", ")", ":", "try", ":", "for", "realm", "in", "self", ".", "realms", ":", "identifier", "=", "items", ".", "identifiers", ".", "from_source", "(", "realm", "....
41.866667
14.133333
def set_attribute(self, attribute, attribute_state): """Get an attribute from the session. :param attribute: :return: attribute value, status code :rtype: object, constants.StatusCode """ # Check that the attribute exists. try: attr = attributes.Attr...
[ "def", "set_attribute", "(", "self", ",", "attribute", ",", "attribute_state", ")", ":", "# Check that the attribute exists.", "try", ":", "attr", "=", "attributes", ".", "AttributesByID", "[", "attribute", "]", "except", "KeyError", ":", "return", "constants", "....
34
20.214286
def import_module_from_fpath(module_fpath): r""" imports module from a file path Args: module_fpath (str): Returns: module: module CommandLine: python -m utool.util_import --test-import_module_from_fpath Example: >>> # DISABLE_DOCTEST >>> from utool.util_i...
[ "def", "import_module_from_fpath", "(", "module_fpath", ")", ":", "from", "os", ".", "path", "import", "basename", ",", "splitext", ",", "isdir", ",", "join", ",", "exists", ",", "dirname", ",", "split", "import", "platform", "if", "isdir", "(", "module_fpat...
35.191489
21.524823
def get_affiliation_details(self, value, affiliation_id, institute_literal): """ This method is used to map the Affiliation between an author and Institution. Parameters ---------- value - The author name affiliation_id - Primary key of the affiliation table inst...
[ "def", "get_affiliation_details", "(", "self", ",", "value", ",", "affiliation_id", ",", "institute_literal", ")", ":", "tokens", "=", "tuple", "(", "[", "t", ".", "upper", "(", ")", ".", "strip", "(", ")", "for", "t", "in", "value", ".", "split", "(",...
32
19.025641
def __random_density_bures(N, rank=None, seed=None): """ Generate a random density matrix from the Bures metric. Args: N (int): the length of the density matrix. rank (int or None): the rank of the density matrix. The default value is full-rank. seed (int): Optional. To ...
[ "def", "__random_density_bures", "(", "N", ",", "rank", "=", "None", ",", "seed", "=", "None", ")", ":", "P", "=", "np", ".", "eye", "(", "N", ")", "+", "random_unitary", "(", "N", ")", ".", "data", "G", "=", "P", ".", "dot", "(", "__ginibre_matr...
33.25
14.5
def _computeforce(self,R,z,phi=0,t=0): """ NAME: _computeforce PURPOSE: Evaluate the first derivative of Phi with respect to R, z and phi INPUT: R - Cylindrical Galactocentric radius z - vertical height phi - azimuth t - t...
[ "def", "_computeforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0", ",", "t", "=", "0", ")", ":", "Acos", ",", "Asin", "=", "self", ".", "_Acos", ",", "self", ".", "_Asin", "N", ",", "L", ",", "M", "=", "Acos", ".", "shape", "r",...
38.244444
15.844444
def bna_config_cmd_status_input_session_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") bna_config_cmd_status = ET.Element("bna_config_cmd_status") config = bna_config_cmd_status input = ET.SubElement(bna_config_cmd_status, "input") se...
[ "def", "bna_config_cmd_status_input_session_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "bna_config_cmd_status", "=", "ET", ".", "Element", "(", "\"bna_config_cmd_status\"", ")", "config", "="...
41.333333
13.583333
def add_to_subset(self, id, s): """ Adds a node to a subset """ n = self.node(id) if 'meta' not in n: n['meta'] = {} meta = n['meta'] if 'subsets' not in meta: meta['subsets'] = [] meta['subsets'].append(s)
[ "def", "add_to_subset", "(", "self", ",", "id", ",", "s", ")", ":", "n", "=", "self", ".", "node", "(", "id", ")", "if", "'meta'", "not", "in", "n", ":", "n", "[", "'meta'", "]", "=", "{", "}", "meta", "=", "n", "[", "'meta'", "]", "if", "'...
25.818182
8.909091
def verify(self, authenticators): """Verify this OMAPI message. >>> a1 = OmapiHMACMD5Authenticator(b"egg", b"spam") >>> a2 = OmapiHMACMD5Authenticator(b"egg", b"tomatoes") >>> a1.authid = a2.authid = 5 >>> m = OmapiMessage.open(b"host") >>> m.verify({a1.authid: a1}) False >>> m.sign(a1) >>> m.verify(...
[ "def", "verify", "(", "self", ",", "authenticators", ")", ":", "try", ":", "return", "authenticators", "[", "self", ".", "authid", "]", ".", "sign", "(", "self", ".", "as_string", "(", "forsigning", "=", "True", ")", ")", "==", "self", ".", "signature"...
25.695652
20.826087
def verify(self, connection_type=None): """ Verifies and update the remote system settings. :param connection_type: same as the one in `create` method. """ req_body = self._cli.make_body(connectionType=connection_type) resp = self.action('verify', **req_body) re...
[ "def", "verify", "(", "self", ",", "connection_type", "=", "None", ")", ":", "req_body", "=", "self", ".", "_cli", ".", "make_body", "(", "connectionType", "=", "connection_type", ")", "resp", "=", "self", ".", "action", "(", "'verify'", ",", "*", "*", ...
31.545455
17.727273
def tie_weights(self): """ Run this to be sure output and input (adaptive) softmax weights are tied """ # sampled softmax if self.sample_softmax > 0: if self.config.tie_weight: self.out_layer.weight = self.transformer.word_emb.weight # adaptive softmax (includ...
[ "def", "tie_weights", "(", "self", ")", ":", "# sampled softmax", "if", "self", ".", "sample_softmax", ">", "0", ":", "if", "self", ".", "config", ".", "tie_weight", ":", "self", ".", "out_layer", ".", "weight", "=", "self", ".", "transformer", ".", "wor...
58.411765
24.058824
def getaddresses(fieldvalues): """Return a list of (REALNAME, EMAIL) for each fieldvalue.""" all = COMMASPACE.join(fieldvalues) a = _AddressList(all) return a.addresslist
[ "def", "getaddresses", "(", "fieldvalues", ")", ":", "all", "=", "COMMASPACE", ".", "join", "(", "fieldvalues", ")", "a", "=", "_AddressList", "(", "all", ")", "return", "a", ".", "addresslist" ]
36.4
8.6
def authenticate(self, req, resp, resource): """ Extract basic auth token from request `authorization` header, deocode the token, verifies the username/password and return either a ``user`` object if successful else raise an `falcon.HTTPUnauthoried exception` """ usernam...
[ "def", "authenticate", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "username", ",", "password", "=", "self", ".", "_extract_credentials", "(", "req", ")", "user", "=", "self", ".", "user_loader", "(", "username", ",", "password", ")"...
42
18.923077
def resolve_parameters(value, parameters, date_time=datetime.datetime.now(), macros=False): """ Resolve a format modifier with the corresponding value. Args: value: The string (path, table, or any other artifact in a cell_body) which may have format modifiers. E.g. a table name could be <projec...
[ "def", "resolve_parameters", "(", "value", ",", "parameters", ",", "date_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "macros", "=", "False", ")", ":", "merged_parameters", "=", "Query", ".", "merge_parameters", "(", "parameters", ",",...
63.904762
39.238095
def scale_dataset(self, dsid, variable, info): """Scale the data set, applying the attributes from the netCDF file""" variable = remove_empties(variable) scale = variable.attrs.get('scale_factor', np.array(1)) offset = variable.attrs.get('add_offset', np.array(0)) if np.issubdty...
[ "def", "scale_dataset", "(", "self", ",", "dsid", ",", "variable", ",", "info", ")", ":", "variable", "=", "remove_empties", "(", "variable", ")", "scale", "=", "variable", ".", "attrs", ".", "get", "(", "'scale_factor'", ",", "np", ".", "array", "(", ...
49.288136
23.220339
def _append_hdu_info(self, ext): """ internal routine append info for indiciated extension """ # raised IOError if not found hdu_type = self._FITS.movabs_hdu(ext+1) if hdu_type == IMAGE_HDU: hdu = ImageHDU(self._FITS, ext, **self.keys) elif ...
[ "def", "_append_hdu_info", "(", "self", ",", "ext", ")", ":", "# raised IOError if not found", "hdu_type", "=", "self", ".", "_FITS", ".", "movabs_hdu", "(", "ext", "+", "1", ")", "if", "hdu_type", "==", "IMAGE_HDU", ":", "hdu", "=", "ImageHDU", "(", "self...
32.052632
13.947368
def get_dimension_type(self, dim): """Get the type of the requested dimension. Type is determined by Dimension.type attribute or common type of the dimension values, otherwise None. Args: dimension: Dimension to look up by name or by index Returns: Decl...
[ "def", "get_dimension_type", "(", "self", ",", "dim", ")", ":", "dim", "=", "self", ".", "get_dimension", "(", "dim", ")", "if", "dim", "is", "None", ":", "return", "None", "elif", "dim", ".", "type", "is", "not", "None", ":", "return", "dim", ".", ...
30.95
17.15
def where(self, column_or_label, value_or_predicate=None, other=None): """ Return a new ``Table`` containing rows where ``value_or_predicate`` returns True for values in ``column_or_label``. Args: ``column_or_label``: A column of the ``Table`` either as a label (...
[ "def", "where", "(", "self", ",", "column_or_label", ",", "value_or_predicate", "=", "None", ",", "other", "=", "None", ")", ":", "column", "=", "self", ".", "_get_column", "(", "column_or_label", ")", "if", "other", "is", "not", "None", ":", "assert", "...
42.789474
20.894737
def equal_to_be(self, be_record): # type: (PathTableRecord) -> bool ''' A method to compare a little-endian path table record to its big-endian counterpart. This is used to ensure that the ISO is sane. Parameters: be_record - The big-endian object to compare with the l...
[ "def", "equal_to_be", "(", "self", ",", "be_record", ")", ":", "# type: (PathTableRecord) -> bool", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'This Path Table Record is not yet initialized'", ")", "if", ...
43.956522
26.652174
def upload_video(self, media, media_type, media_category=None, size=None, check_progress=False): """Uploads video file to Twitter servers in chunks. The file will be available to be attached to a status for 60 minutes. To attach to a update, pass a list of returned media ids to the :meth:`update...
[ "def", "upload_video", "(", "self", ",", "media", ",", "media_type", ",", "media_category", "=", "None", ",", "size", "=", "None", ",", "check_progress", "=", "False", ")", ":", "upload_url", "=", "'https://upload.twitter.com/1.1/media/upload.json'", "if", "not", ...
37.965909
23.306818
def centerdc_2_twosided(data): """Convert a center-dc PSD to a twosided PSD""" N = len(data) newpsd = np.concatenate((data[N//2:], (cshift(data[0:N//2], -1)))) return newpsd
[ "def", "centerdc_2_twosided", "(", "data", ")", ":", "N", "=", "len", "(", "data", ")", "newpsd", "=", "np", ".", "concatenate", "(", "(", "data", "[", "N", "//", "2", ":", "]", ",", "(", "cshift", "(", "data", "[", "0", ":", "N", "//", "2", ...
37
17.2
def measurements_to_bf(measurements: np.ndarray) -> float: """ Convert measurements into gradient binary fraction. :param measurements: Output measurements of gradient program. :return: Binary fraction representation of gradient estimate. """ try: measurements.sum(axis=0) except Att...
[ "def", "measurements_to_bf", "(", "measurements", ":", "np", ".", "ndarray", ")", "->", "float", ":", "try", ":", "measurements", ".", "sum", "(", "axis", "=", "0", ")", "except", "AttributeError", ":", "measurements", "=", "np", ".", "asarray", "(", "me...
30.473684
20.157895
def save(self, filename, clobber=True, **kwargs): """ Save the `Spectrum1D` object to the specified filename. :param filename: The filename to save the Spectrum1D object to. :type filename: str :param clobber: [optional] Whether to o...
[ "def", "save", "(", "self", ",", "filename", ",", "clobber", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", "and", "not", "clobber", ":", "raise", "IOError", "(", "\"filename '{0}' exists a...
35.982456
20.684211
def getclusters(self, count): """ Generates *count* clusters. :param count: The amount of clusters that should be generated. count must be greater than ``1``. :raises ClusteringError: if *count* is out of bounds. """ # only proceed if we got sensible input ...
[ "def", "getclusters", "(", "self", ",", "count", ")", ":", "# only proceed if we got sensible input", "if", "count", "<=", "1", ":", "raise", "ClusteringError", "(", "\"When clustering, you need to ask for at \"", "\"least two clusters! \"", "\"You asked for %d\"", "%", "co...
39.95122
18.926829
def warning(lineno, msg): """ Generic warning error routine """ msg = "%s:%i: warning: %s" % (global_.FILENAME, lineno, msg) msg_output(msg) global_.has_warnings += 1
[ "def", "warning", "(", "lineno", ",", "msg", ")", ":", "msg", "=", "\"%s:%i: warning: %s\"", "%", "(", "global_", ".", "FILENAME", ",", "lineno", ",", "msg", ")", "msg_output", "(", "msg", ")", "global_", ".", "has_warnings", "+=", "1" ]
30.166667
11.833333
def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,None)], [4,5], ...
[ "def", "flatten", "(", "x", ")", ":", "for", "el", "in", "x", ":", "if", "hasattr", "(", "el", ",", "\"__iter__\"", ")", "and", "not", "isinstance", "(", "el", ",", "(", "binary", ",", "unicode", ")", ")", ":", "for", "els", "in", "flatten", "(",...
28.7
22.05
def ratio(value, decimal_places=0, failure_string='N/A'): """ Converts a floating point value a X:1 ratio. Number of decimal places set by the `precision` kwarg. Default is one. """ try: f = float(value) except ValueError: return failure_string return _saferound(f, decim...
[ "def", "ratio", "(", "value", ",", "decimal_places", "=", "0", ",", "failure_string", "=", "'N/A'", ")", ":", "try", ":", "f", "=", "float", "(", "value", ")", "except", "ValueError", ":", "return", "failure_string", "return", "_saferound", "(", "f", ","...
29.727273
16.272727
def _generateFirstOrder0(): """ Generate the initial, first order, and second order transition probabilities for 'probability0'. For this model, we generate the following set of sequences: .1 .75 0----1-----2 \ \ \ \ .25 \ \-----3 \ \ .9 .5 \--- 4-----...
[ "def", "_generateFirstOrder0", "(", ")", ":", "# --------------------------------------------------------------------", "# Initial probabilities, 'a' and 'e' equally likely", "numCategories", "=", "5", "initProb", "=", "numpy", ".", "zeros", "(", "numCategories", ")", "initProb",...
37.876543
22.209877
def main(): """Simply merge all trajectories in the working directory""" folder = os.getcwd() print('Merging all files') merge_all_in_folder(folder, delete_other_files=True, # We will only keep one trajectory dynamic_imports=FunctionParameter, ...
[ "def", "main", "(", ")", ":", "folder", "=", "os", ".", "getcwd", "(", ")", "print", "(", "'Merging all files'", ")", "merge_all_in_folder", "(", "folder", ",", "delete_other_files", "=", "True", ",", "# We will only keep one trajectory", "dynamic_imports", "=", ...
39.555556
16.888889
def _citation_sort_key(t: EdgeTuple) -> str: """Make a confusing 4 tuple sortable by citation.""" return '"{}", "{}"'.format(t[3][CITATION][CITATION_TYPE], t[3][CITATION][CITATION_REFERENCE])
[ "def", "_citation_sort_key", "(", "t", ":", "EdgeTuple", ")", "->", "str", ":", "return", "'\"{}\", \"{}\"'", ".", "format", "(", "t", "[", "3", "]", "[", "CITATION", "]", "[", "CITATION_TYPE", "]", ",", "t", "[", "3", "]", "[", "CITATION", "]", "[",...
65.666667
20.333333
def get_tau_at_quantile(mean, stddev, quantile): """ Returns the value of tau at a given quantile in the form of a dictionary organised by intensity measure """ tau_model = {} for imt in mean: tau_model[imt] = {} for key in mean[imt]: if quantile is None: ...
[ "def", "get_tau_at_quantile", "(", "mean", ",", "stddev", ",", "quantile", ")", ":", "tau_model", "=", "{", "}", "for", "imt", "in", "mean", ":", "tau_model", "[", "imt", "]", "=", "{", "}", "for", "key", "in", "mean", "[", "imt", "]", ":", "if", ...
36.6875
16.1875
def split(x, split_dim, num_or_size_splits, name=None): """Like tf.split. Args: x: a Tensor split_dim: a Dimension in x.shape.dims num_or_size_splits: either an integer dividing split_dim.size or a list of integers adding up to split_dim.size name: an optional string Returns: a list of...
[ "def", "split", "(", "x", ",", "split_dim", ",", "num_or_size_splits", ",", "name", "=", "None", ")", ":", "return", "SplitOperation", "(", "x", ",", "split_dim", ",", "num_or_size_splits", ",", "name", "=", "name", ")", ".", "outputs" ]
30.769231
19.384615
def p_mp_createClass(p): """mp_createClass : classDeclaration """ # pylint: disable=too-many-branches,too-many-statements,too-many-locals ns = p.parser.handle.default_namespace cc = p[1] try: fixedNS = fixedRefs = fixedSuper = False while not fixedNS or not fix...
[ "def", "p_mp_createClass", "(", "p", ")", ":", "# pylint: disable=too-many-branches,too-many-statements,too-many-locals", "ns", "=", "p", ".", "parser", ".", "handle", ".", "default_namespace", "cc", "=", "p", "[", "1", "]", "try", ":", "fixedNS", "=", "fixedRefs"...
46.4
17.208
def check_distance_funciton_input(distance_func_name, netinfo): """ Funciton checks distance_func_name, if it is specified as 'default'. Then given the type of the network selects a default distance function. Parameters ---------- distance_func_name : str distance function name. netin...
[ "def", "check_distance_funciton_input", "(", "distance_func_name", ",", "netinfo", ")", ":", "if", "distance_func_name", "==", "'default'", "and", "netinfo", "[", "'nettype'", "]", "[", "0", "]", "==", "'b'", ":", "print", "(", "'Default distance funciton specified....
30.3
25.366667
def _find_any(self, task_spec): """ Returns any descendants that have the given task spec assigned. :type task_spec: TaskSpec :param task_spec: The wanted task spec. :rtype: list(Task) :returns: The tasks objects that are attached to the given task spec. """ ...
[ "def", "_find_any", "(", "self", ",", "task_spec", ")", ":", "tasks", "=", "[", "]", "if", "self", ".", "task_spec", "==", "task_spec", ":", "tasks", ".", "append", "(", "self", ")", "for", "child", "in", "self", ":", "if", "child", ".", "task_spec",...
31.823529
14.058824
def generate_map(map, name='url_map'): """ Generates a JavaScript function containing the rules defined in this map, to be used with a MapAdapter's generate_javascript method. If you don't pass a name the returned JavaScript code is an expression that returns a function. Otherwise it's a standalon...
[ "def", "generate_map", "(", "map", ",", "name", "=", "'url_map'", ")", ":", "from", "warnings", "import", "warn", "warn", "(", "DeprecationWarning", "(", "'This module is deprecated'", ")", ")", "map", ".", "update", "(", ")", "rules", "=", "[", "]", "conv...
38.955556
15.622222
def get_section_by_sis_id(self, sis_section_id, params={}): """ Return section resource for given sis id. """ return self.get_section( self._sis_id(sis_section_id, sis_field="section"), params)
[ "def", "get_section_by_sis_id", "(", "self", ",", "sis_section_id", ",", "params", "=", "{", "}", ")", ":", "return", "self", ".", "get_section", "(", "self", ".", "_sis_id", "(", "sis_section_id", ",", "sis_field", "=", "\"section\"", ")", ",", "params", ...
38.666667
11
def _summary_sim(sim, pars, probs): """Summarize chains together and separately REF: rstan/rstan/R/misc.R Parameters are unraveled in *column-major order*. Parameters ---------- sim : dict dict from from a stanfit fit object, i.e., fit['sim'] pars : Iterable of str paramet...
[ "def", "_summary_sim", "(", "sim", ",", "pars", ",", "probs", ")", ":", "# NOTE: this follows RStan rather closely. Some of the calculations here", "probs_len", "=", "len", "(", "probs", ")", "n_chains", "=", "len", "(", "sim", "[", "'samples'", "]", ")", "# tidx ...
42.635135
21.013514
def get_series_first_release(self, series_id): """ Get first-release data for a Fred series id. This ignores any revision to the data series. For instance, The US GDP for Q1 2014 was first released to be 17149.6, and then later revised to 17101.3, and 17016.0. This will ignore revisions ...
[ "def", "get_series_first_release", "(", "self", ",", "series_id", ")", ":", "df", "=", "self", ".", "get_series_all_releases", "(", "series_id", ")", "first_release", "=", "df", ".", "groupby", "(", "'date'", ")", ".", "head", "(", "1", ")", "data", "=", ...
39.2
25.2
def auth_tls(self, mount_point='cert', use_token=True): """POST /auth/<mount point>/login :param mount_point: :type mount_point: :param use_token: :type use_token: :return: :rtype: """ return self.login('/v1/auth/{0}/login'.format(mount_point), us...
[ "def", "auth_tls", "(", "self", ",", "mount_point", "=", "'cert'", ",", "use_token", "=", "True", ")", ":", "return", "self", ".", "login", "(", "'/v1/auth/{0}/login'", ".", "format", "(", "mount_point", ")", ",", "use_token", "=", "use_token", ")" ]
29.818182
19.090909
def function_exists(FunctionName, region=None, key=None, keyid=None, profile=None): ''' Given a function name, check to see if the given function name exists. Returns True if the given function exists and returns False if the given function does not exist. CLI Example: .. ...
[ "def", "function_exists", "(", "FunctionName", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "func", "=", "_find_function", "(", "FunctionName", ",", "region", "=", "r...
29.545455
26.363636
def three_cornered_hat_phase(phasedata_ab, phasedata_bc, phasedata_ca, rate, taus, function): """ Three Cornered Hat Method Given three clocks A, B, C, we seek to find their variances :math:`\\sigma^2_A`, :math:`\\sigma^2_B`, :math:`\\sigma^2_C`. We measure three phase ...
[ "def", "three_cornered_hat_phase", "(", "phasedata_ab", ",", "phasedata_bc", ",", "phasedata_ca", ",", "rate", ",", "taus", ",", "function", ")", ":", "(", "tau_ab", ",", "dev_ab", ",", "err_ab", ",", "ns_ab", ")", "=", "function", "(", "phasedata_ab", ",", ...
33.289474
22.236842
def get_aspect(self, xspan, yspan): """ Computes the aspect ratio of the plot """ if self.data_aspect: return (yspan/xspan)*self.data_aspect elif self.aspect == 'equal': return xspan/yspan elif self.aspect == 'square': return 1 ...
[ "def", "get_aspect", "(", "self", ",", "xspan", ",", "yspan", ")", ":", "if", "self", ".", "data_aspect", ":", "return", "(", "yspan", "/", "xspan", ")", "*", "self", ".", "data_aspect", "elif", "self", ".", "aspect", "==", "'equal'", ":", "return", ...
31.6875
9.5625
def formfield(self, *args, **kwargs): """ Returns proper formfield, according to empty_values setting (only for ``forms.CharField`` subclasses). There are 3 different formfields: - CharField that stores all empty values as empty strings; - NullCharField that stores all e...
[ "def", "formfield", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "formfield", "=", "super", "(", "TranslationField", ",", "self", ")", ".", "formfield", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "...
53.375
25.775
def get_schema_input_format(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_schema = ET.Element("get_schema") config = get_schema input = ET.SubElement(get_schema, "input") format = ET.SubElement(input, "format") format.text =...
[ "def", "get_schema_input_format", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_schema", "=", "ET", ".", "Element", "(", "\"get_schema\"", ")", "config", "=", "get_schema", "input", "=", ...
35.083333
9.166667
def makeCertHokTokenLoginMethod(stsUrl, stsCert=None): '''Return a function that will call the vim.SessionManager.LoginByToken() after obtaining a HoK SAML token from the STS. The result of this function can be passed as the "loginMethod" to a SessionOrientedStub constructor. @param stsUrl: URL...
[ "def", "makeCertHokTokenLoginMethod", "(", "stsUrl", ",", "stsCert", "=", "None", ")", ":", "assert", "(", "stsUrl", ")", "def", "_doLogin", "(", "soapStub", ")", ":", "from", ".", "import", "sso", "cert", "=", "soapStub", ".", "schemeArgs", "[", "'cert_fi...
38.617647
23.382353
def drop_retention_policy(self, name, database=None): """Drop an existing retention policy for a database. :param name: the name of the retention policy to drop :type name: str :param database: the database for which the retention policy is dropped. Defaults to current clien...
[ "def", "drop_retention_policy", "(", "self", ",", "name", ",", "database", "=", "None", ")", ":", "query_string", "=", "(", "\"DROP RETENTION POLICY {0} ON {1}\"", ")", ".", "format", "(", "quote_ident", "(", "name", ")", ",", "quote_ident", "(", "database", "...
42.846154
16.769231
def message(blockers): """Create a sequence of key messages based on what is blocking.""" if not blockers: encoding = getattr(sys.stdout, 'encoding', '') if encoding: encoding = encoding.lower() if encoding == 'utf-8': # party hat flair = "\U0001F389 ...
[ "def", "message", "(", "blockers", ")", ":", "if", "not", "blockers", ":", "encoding", "=", "getattr", "(", "sys", ".", "stdout", ",", "'encoding'", ",", "''", ")", "if", "encoding", ":", "encoding", "=", "encoding", ".", "lower", "(", ")", "if", "en...
42.166667
13.566667
async def set_presence(self, status: str = "online", ignore_cache: bool = False): """ Set the online status of the user. See also: `API reference`_ Args: status: The online status of the user. Allowed values: "online", "offline", "unavailable". ignore_cache: Whether or n...
[ "async", "def", "set_presence", "(", "self", ",", "status", ":", "str", "=", "\"online\"", ",", "ignore_cache", ":", "bool", "=", "False", ")", ":", "await", "self", ".", "ensure_registered", "(", ")", "if", "not", "ignore_cache", "and", "self", ".", "st...
42.809524
29.095238
def calcMzFromMass(mass, charge): """Calculate the mz value of a peptide from its mass and charge. :param mass: float, exact non protonated mass :param charge: int, charge state :returns: mass to charge ratio of the specified charge state """ mz = (mass + (maspy.constants.atomicMassProton * ch...
[ "def", "calcMzFromMass", "(", "mass", ",", "charge", ")", ":", "mz", "=", "(", "mass", "+", "(", "maspy", ".", "constants", ".", "atomicMassProton", "*", "charge", ")", ")", "/", "charge", "return", "mz" ]
34
18.1
def _partialParseDateStd(self, s, sourceTime): """ test if giving C{s} matched CRE_DATE, used by L{parse()} @type s: string @param s: date/time text to evaluate @type sourceTime: struct_time @param sourceTime: C{struct_time} value to use as the base ...
[ "def", "_partialParseDateStd", "(", "self", ",", "s", ",", "sourceTime", ")", ":", "parseStr", "=", "None", "chunk1", "=", "chunk2", "=", "''", "# Standard date format", "m", "=", "self", ".", "ptc", ".", "CRE_DATE", ".", "search", "(", "s", ")", "if", ...
31.675676
17.297297
def search_databases(self, search_term, location=None, markets_only=False, databases_to_search=None, allow_internal=False): """ Search external databases linked to your lcopt model. To restrict the search to particular databases (e.g. technosphere or biosphere only) use a list of database name...
[ "def", "search_databases", "(", "self", ",", "search_term", ",", "location", "=", "None", ",", "markets_only", "=", "False", ",", "databases_to_search", "=", "None", ",", "allow_internal", "=", "False", ")", ":", "dict_list", "=", "[", "]", "if", "allow_inte...
40.068182
29.795455
def pass_q_v1(self): """Update the outlet link sequence.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.q[0] += flu.qa
[ "def", "pass_q_v1", "(", "self", ")", ":", "flu", "=", "self", ".", "sequences", ".", "fluxes", ".", "fastaccess", "out", "=", "self", ".", "sequences", ".", "outlets", ".", "fastaccess", "out", ".", "q", "[", "0", "]", "+=", "flu", ".", "qa" ]
33.8
8.6
def lookup_package(self, definition_name): """Determines the package name for any definition. Determine the package that any definition name belongs to. May check parent for package name and will resolve missing descriptors if provided descriptor loader. Args: definit...
[ "def", "lookup_package", "(", "self", ",", "definition_name", ")", ":", "while", "True", ":", "descriptor", "=", "self", ".", "lookup_descriptor", "(", "definition_name", ")", "if", "isinstance", "(", "descriptor", ",", "FileDescriptor", ")", ":", "return", "d...
36.55
18.2
def auto_cleaned_path_stripped_uuid4(instance, filename: str) -> str: """ Gets upload path in this format: {MODEL_NAME}/{UUID4}{SUFFIX}. Same as `upload_path_uuid4` but deletes the original file name from the user. :param instance: Instance of model or model class. :param filename: Uploaded file na...
[ "def", "auto_cleaned_path_stripped_uuid4", "(", "instance", ",", "filename", ":", "str", ")", "->", "str", ":", "_", ",", "suffix", "=", "parse_filename", "(", "filename", ")", "base_dir", "=", "get_base_dir_from_object", "(", "instance", ")", "rand_uuid", "=", ...
42.266667
20
def get_item_attribute(self, item, name): """ Method called by item when an attribute is not found. """ if name in self.__item_attributes: return self.__item_attributes[name](item) elif self.section: return self.section.get_item_attribute(item, name) ...
[ "def", "get_item_attribute", "(", "self", ",", "item", ",", "name", ")", ":", "if", "name", "in", "self", ".", "__item_attributes", ":", "return", "self", ".", "__item_attributes", "[", "name", "]", "(", "item", ")", "elif", "self", ".", "section", ":", ...
35.8
10.2
def create_vector_input(self, name='vector_observation'): """ Creates ops for vector observation input. :param name: Name of the placeholder op. :param vec_obs_size: Size of stacked vector observation. :return: """ self.vector_in = tf.placeholder(shape=[None, self...
[ "def", "create_vector_input", "(", "self", ",", "name", "=", "'vector_observation'", ")", ":", "self", ".", "vector_in", "=", "tf", ".", "placeholder", "(", "shape", "=", "[", "None", ",", "self", ".", "vec_obs_size", "]", ",", "dtype", "=", "tf", ".", ...
57.56
28.84
def _emiss_ep(self, Eph): """ Electron-proton bremsstrahlung emissivity per unit photon energy """ if self.weight_ep == 0.0: return np.zeros_like(Eph) gam = np.vstack(self._gam) eps = (Eph / mec2).decompose().value # compute integral with electron dis...
[ "def", "_emiss_ep", "(", "self", ",", "Eph", ")", ":", "if", "self", ".", "weight_ep", "==", "0.0", ":", "return", "np", ".", "zeros_like", "(", "Eph", ")", "gam", "=", "np", ".", "vstack", "(", "self", ".", "_gam", ")", "eps", "=", "(", "Eph", ...
32.125
13.125
def XKX(self): """ compute self covariance for rest """ cov_beta = np.zeros((self.dof,self.dof)) start_row = 0 #This is trivially parallelizable: for term1 in range(self.len): stop_row = start_row + self.A[term1].shape[0] * self.F[term1].shape[1] ...
[ "def", "XKX", "(", "self", ")", ":", "cov_beta", "=", "np", ".", "zeros", "(", "(", "self", ".", "dof", ",", "self", ".", "dof", ")", ")", "start_row", "=", "0", "#This is trivially parallelizable:", "for", "term1", "in", "range", "(", "self", ".", "...
50.421053
23.157895
def phymem_usage(): """Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory(). """ mem = virtual_memory() return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent)
[ "def", "phymem_usage", "(", ")", ":", "mem", "=", "virtual_memory", "(", ")", "return", "_nt_sysmeminfo", "(", "mem", ".", "total", ",", "mem", ".", "used", ",", "mem", ".", "free", ",", "mem", ".", "percent", ")" ]
40
11.285714
def process(self, request, response, environ): """ Create a new access token. :param request: The incoming :class:`oauth2.web.Request`. :param response: The :class:`oauth2.web.Response` that will be returned to the client. :param environ: A ``dict`` cont...
[ "def", "process", "(", "self", ",", "request", ",", "response", ",", "environ", ")", ":", "token_data", "=", "self", ".", "token_generator", ".", "create_access_token_data", "(", "self", ".", "refresh_grant_type", ")", "expires_at", "=", "int", "(", "time", ...
42.972222
25.25
def get_devices_from_response_dict(response_dict, device_type): """ :rtype: list of WinkDevice """ items = response_dict.get('data') devices = [] api_interface = WinkApiInterface() check_list = isinstance(device_type, (list,)) for item in items: if (check_list and get_object_t...
[ "def", "get_devices_from_response_dict", "(", "response_dict", ",", "device_type", ")", ":", "items", "=", "response_dict", ".", "get", "(", "'data'", ")", "devices", "=", "[", "]", "api_interface", "=", "WinkApiInterface", "(", ")", "check_list", "=", "isinstan...
29.421053
18.789474
def _request(self, method, path, params=None): """Make the actual request and returns the parsed response.""" url = self._base_url + path try: if method == 'GET': response = requests.get(url, timeout=TIMEOUT) elif method == "POST": respons...
[ "def", "_request", "(", "self", ",", "method", ",", "path", ",", "params", "=", "None", ")", ":", "url", "=", "self", ".", "_base_url", "+", "path", "try", ":", "if", "method", "==", "'GET'", ":", "response", "=", "requests", ".", "get", "(", "url"...
39.166667
13.083333
def present(name, running=None, source=None, profiles=None, config=None, devices=None, architecture='x86_64', ephemeral=False, restart_on_change=False, remote_addr=None, cert=None, key=Non...
[ "def", "present", "(", "name", ",", "running", "=", "None", ",", "source", "=", "None", ",", "profiles", "=", "None", ",", "config", "=", "None", ",", "devices", "=", "None", ",", "architecture", "=", "'x86_64'", ",", "ephemeral", "=", "False", ",", ...
28.072368
19.230263
def parse_args(self): """Parse CLI args.""" Args(self.tcex.parser) self.args = self.tcex.args
[ "def", "parse_args", "(", "self", ")", ":", "Args", "(", "self", ".", "tcex", ".", "parser", ")", "self", ".", "args", "=", "self", ".", "tcex", ".", "args" ]
28.5
8.75
def keras_dropout(layer, rate): '''keras dropout layer. ''' from keras import layers input_dim = len(layer.input.shape) if input_dim == 2: return layers.SpatialDropout1D(rate) elif input_dim == 3: return layers.SpatialDropout2D(rate) elif input_dim == 4: return laye...
[ "def", "keras_dropout", "(", "layer", ",", "rate", ")", ":", "from", "keras", "import", "layers", "input_dim", "=", "len", "(", "layer", ".", "input", ".", "shape", ")", "if", "input_dim", "==", "2", ":", "return", "layers", ".", "SpatialDropout1D", "(",...
25.133333
16.466667
def pca( data: Union[AnnData, np.ndarray, spmatrix], n_comps: int = N_PCS, zero_center: Optional[bool] = True, svd_solver: str = 'auto', random_state: int = 0, return_info: bool = False, use_highly_variable: Optional[bool] = None, dtype: str = 'float32', copy: bool = False, chunk...
[ "def", "pca", "(", "data", ":", "Union", "[", "AnnData", ",", "np", ".", "ndarray", ",", "spmatrix", "]", ",", "n_comps", ":", "int", "=", "N_PCS", ",", "zero_center", ":", "Optional", "[", "bool", "]", "=", "True", ",", "svd_solver", ":", "str", "...
41.773481
24.314917
def procrustes(source, target, scaling=True, reflection=True, reduction=False, oblique=False, oblique_rcond=-1, format_data=True): """ Function to project from one space to another using Procrustean transformation (shift + scaling + rotation + reflection). The implementation of this func...
[ "def", "procrustes", "(", "source", ",", "target", ",", "scaling", "=", "True", ",", "reflection", "=", "True", ",", "reduction", "=", "False", ",", "oblique", "=", "False", ",", "oblique_rcond", "=", "-", "1", ",", "format_data", "=", "True", ")", ":"...
32.966887
22.874172
def fetch(weeks, force): """Fetch newest PageViews and Downloads.""" weeks = get_last_weeks(weeks) print(weeks) recommender = RecordRecommender(config) recommender.fetch_weeks(weeks, overwrite=force)
[ "def", "fetch", "(", "weeks", ",", "force", ")", ":", "weeks", "=", "get_last_weeks", "(", "weeks", ")", "print", "(", "weeks", ")", "recommender", "=", "RecordRecommender", "(", "config", ")", "recommender", ".", "fetch_weeks", "(", "weeks", ",", "overwri...
35.666667
10.166667
def create_constants(self, rdbms): """ Factory for creating a Constants objects (i.e. objects for creating constants based on column widths, and auto increment columns and labels). :param str rdbms: The target RDBMS (i.e. mysql, mssql or pgsql). :rtype: pystratum.Constants.Cons...
[ "def", "create_constants", "(", "self", ",", "rdbms", ")", ":", "# Note: We load modules and classes dynamically such that on the end user's system only the required modules", "# and other dependencies for the targeted RDBMS must be installed (and required modules and other", "# depe...
42.807692
26.884615
def load_from_module(self, module): '''Load all benchmarks from a given module''' benchmarks = [] for name in dir(module): obj = getattr(module, name) if (inspect.isclass(obj) and issubclass(obj, Benchmark) and obj != Benchmark): benchm...
[ "def", "load_from_module", "(", "self", ",", "module", ")", ":", "benchmarks", "=", "[", "]", "for", "name", "in", "dir", "(", "module", ")", ":", "obj", "=", "getattr", "(", "module", ",", "name", ")", "if", "(", "inspect", ".", "isclass", "(", "o...
39.333333
10
def evaluate_all(ctx, model): """Evaluate POS taggers on WSJ and GENIA.""" click.echo('chemdataextractor.pos.evaluate_all') click.echo('Model: %s' % model) ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle' % model, corpus='wsj', clusters=False) ctx.invoke(evaluate, model='%s_wsj_nocluster.pickle'...
[ "def", "evaluate_all", "(", "ctx", ",", "model", ")", ":", "click", ".", "echo", "(", "'chemdataextractor.pos.evaluate_all'", ")", "click", ".", "echo", "(", "'Model: %s'", "%", "model", ")", "ctx", ".", "invoke", "(", "evaluate", ",", "model", "=", "'%s_w...
80.125
41.625
def enable(self, timeout=0): """ Enable the plugin. Args: timeout (int): Timeout in seconds. Default: 0 Raises: :py:class:`docker.errors.APIError` If the server returns an error. """ self.client.api.enable_...
[ "def", "enable", "(", "self", ",", "timeout", "=", "0", ")", ":", "self", ".", "client", ".", "api", ".", "enable_plugin", "(", "self", ".", "name", ",", "timeout", ")", "self", ".", "reload", "(", ")" ]
27.384615
17.230769
def _property_table(): """Download the PDB -> resolution table directly from the RCSB PDB REST service. See the other fields that you can get here: http://www.rcsb.org/pdb/results/reportField.do Returns: Pandas DataFrame: table of structureId as the index, resolution and experimentalTechnique as t...
[ "def", "_property_table", "(", ")", ":", "url", "=", "'http://www.rcsb.org/pdb/rest/customReport.csv?pdbids=*&customReportColumns=structureId,resolution,experimentalTechnique,releaseDate&service=wsfile&format=csv'", "r", "=", "requests", ".", "get", "(", "url", ")", "p", "=", "pd...
46.076923
37.384615
def apply(self, styles=None, verbose=False): """ Applies the specified style to the selected views and returns the SUIDs of the affected views. :param styles (string): Name of Style to be applied to the selected views. = ['Directed', 'BioPAX_SIF', 'Bridging Reads Histogram:u...
[ "def", "apply", "(", "self", ",", "styles", "=", "None", ",", "verbose", "=", "False", ")", ":", "PARAMS", "=", "set_param", "(", "[", "\"styles\"", "]", ",", "[", "styles", "]", ")", "response", "=", "api", "(", "url", "=", "self", ".", "__url", ...
55.962963
29.148148
def replace(s, pattern, replacement): """Replaces occurrences of a match string in a given string and returns the new string. The match string can be a regex expression. Args: s (str): the string to modify pattern (str): the search expression replacement (str): the...
[ "def", "replace", "(", "s", ",", "pattern", ",", "replacement", ")", ":", "# the replacement string may contain invalid backreferences (like \\1 or \\g)", "# which will cause python's regex to blow up. Since this should emulate", "# the jam version exactly and the jam version didn't support"...
45.7
17.25
def clear(self, rows=None): """Reset episodes in the memory. Internally, this only sets their lengths to zero. The memory entries will be overridden by future calls to append() or replace(). Args: rows: Episodes to clear, defaults to all. Returns: Operation. """ rows = tf.rang...
[ "def", "clear", "(", "self", ",", "rows", "=", "None", ")", ":", "rows", "=", "tf", ".", "range", "(", "self", ".", "_capacity", ")", "if", "rows", "is", "None", "else", "rows", "assert", "rows", ".", "shape", ".", "ndims", "==", "1", "return", "...
30.133333
22.466667
def _create_decoration(self, selection_start, selection_end): """ Creates the text occurences decoration """ deco = TextDecoration(self.editor.document(), selection_start, selection_end) deco.set_background(QtGui.QBrush(self.background)) deco.set_outline(sel...
[ "def", "_create_decoration", "(", "self", ",", "selection_start", ",", "selection_end", ")", ":", "deco", "=", "TextDecoration", "(", "self", ".", "editor", ".", "document", "(", ")", ",", "selection_start", ",", "selection_end", ")", "deco", ".", "set_backgro...
46.222222
12.444444
def get_rev_id(localRepoPath): """returns the current full git revision id of the specified local repository. Expected method of execution: python subroutine call Parameters ---------- localRepoPath: string Local repository path. Returns ======= full git revision ID of the spec...
[ "def", "get_rev_id", "(", "localRepoPath", ")", ":", "start_path", "=", "os", ".", "getcwd", "(", ")", "try", ":", "os", ".", "chdir", "(", "localRepoPath", ")", "instream", "=", "os", ".", "popen", "(", "\"git --no-pager log --max-count=1 | head -1\"", ")", ...
28.419355
22.16129
def filter(self, func, axis=(0,)): """ Filter array along an axis. Applies a function which should evaluate to boolean, along a single axis or multiple axes. Array will be aligned so that the desired set of axes are in the keys, which may require a transpose/reshape. ...
[ "def", "filter", "(", "self", ",", "func", ",", "axis", "=", "(", "0", ",", ")", ")", ":", "axes", "=", "sorted", "(", "tupleize", "(", "axis", ")", ")", "reshaped", "=", "self", ".", "_align", "(", "axes", ")", "filtered", "=", "asarray", "(", ...
27.962963
18.777778
def _delLocalOwnerRole(self, username): """Remove local owner role from parent object """ parent = self.getParent() if parent.portal_type == "Client": parent.manage_delLocalRoles([username]) # reindex object security self._recursive_reindex_object_secu...
[ "def", "_delLocalOwnerRole", "(", "self", ",", "username", ")", ":", "parent", "=", "self", ".", "getParent", "(", ")", "if", "parent", ".", "portal_type", "==", "\"Client\"", ":", "parent", ".", "manage_delLocalRoles", "(", "[", "username", "]", ")", "# r...
40.625
5.375
def helper_parallel_lines(start0, end0, start1, end1, filename): """Image for :func:`.parallel_lines_parameters` docstring.""" if NO_IMAGES: return figure = plt.figure() ax = figure.gca() points = stack1d(start0, end0, start1, end1) ax.plot(points[0, :2], points[1, :2], marker="o") ...
[ "def", "helper_parallel_lines", "(", "start0", ",", "end0", ",", "start1", ",", "end1", ",", "filename", ")", ":", "if", "NO_IMAGES", ":", "return", "figure", "=", "plt", ".", "figure", "(", ")", "ax", "=", "figure", ".", "gca", "(", ")", "points", "...
34.769231
16.076923
async def metrics(self, offs, size=None): ''' Yield metrics rows starting at offset. Args: offs (int): The index offset. size (int): The maximum number of records to yield. Yields: ((int, dict)): An index offset, info tuple for metrics. ''' ...
[ "async", "def", "metrics", "(", "self", ",", "offs", ",", "size", "=", "None", ")", ":", "for", "i", ",", "(", "indx", ",", "item", ")", "in", "enumerate", "(", "self", ".", "_metrics", ".", "iter", "(", "offs", ")", ")", ":", "if", "size", "is...
27.705882
23
def finished(self): """ Mark the activity as finished """ self.data_service.update_activity(self.id, self.name, self.desc, started_on=self.started, ended_on=self._current_timestamp_str())
[ "def", "finished", "(", "self", ")", ":", "self", ".", "data_service", ".", "update_activity", "(", "self", ".", "id", ",", "self", ".", "name", ",", "self", ".", "desc", ",", "started_on", "=", "self", ".", "started", ",", "ended_on", "=", "self", "...
42.428571
17.571429
def print_http_nfc_lease_info(info): """ Prints information about the lease, such as the entity covered by the lease, and HTTP URLs for up/downloading file backings. :param info: :type info: vim.HttpNfcLease.Info :return: """ print 'Lease timeout: {0.leaseTimeout}\n' \ 'Disk Ca...
[ "def", "print_http_nfc_lease_info", "(", "info", ")", ":", "print", "'Lease timeout: {0.leaseTimeout}\\n'", "'Disk Capacity KB: {0.totalDiskCapacityInKB}'", ".", "format", "(", "info", ")", "device_number", "=", "1", "if", "info", ".", "deviceUrl", ":", "for", "device_u...
42.107143
16.035714
def vcpu_pin(vm_, vcpu, cpus): ''' Set which CPUs a VCPU can use. CLI Example: .. code-block:: bash salt 'foo' virt.vcpu_pin domU-id 2 1 salt 'foo' virt.vcpu_pin domU-id 2 2-6 ''' with _get_xapi_session() as xapi: vm_uuid = _get_label_uuid(xapi, 'VM', vm_) if ...
[ "def", "vcpu_pin", "(", "vm_", ",", "vcpu", ",", "cpus", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ")", "if", "vm_uuid", "is", "False", ":", "return", ...
32.886792
18.207547
def to_tuple(self): """Cast to tuple. Returns ------- tuple The confusion table as a 4-tuple (tp, tn, fp, fn) Example ------- >>> ct = ConfusionTable(120, 60, 20, 30) >>> ct.to_tuple() (120, 60, 20, 30) """ return sel...
[ "def", "to_tuple", "(", "self", ")", ":", "return", "self", ".", "_tp", ",", "self", ".", "_tn", ",", "self", ".", "_fp", ",", "self", ".", "_fn" ]
21.25
21.25
def setPrefilter(self, edfsignal, prefilter): """ Sets the prefilter of signal edfsignal ("HP:0.1Hz", "LP:75Hz N:50Hz", etc.) :param edfsignal: int :param prefilter: str Notes ----- This function is optional for every signal and can be called only after opening ...
[ "def", "setPrefilter", "(", "self", ",", "edfsignal", ",", "prefilter", ")", ":", "if", "edfsignal", "<", "0", "or", "edfsignal", ">", "self", ".", "n_channels", ":", "raise", "ChannelDoesNotExist", "(", "edfsignal", ")", "self", ".", "channels", "[", "edf...
38.133333
24.4
def getAdditionalImages(self): ''' The same as calling ``client.getAdditionalImages(build.setID)``. :returns: A list of URL strings. :rtype: list ''' self._additionalImages = self._client.getAdditionalImages(self.setID) return self._additionalImages
[ "def", "getAdditionalImages", "(", "self", ")", ":", "self", ".", "_additionalImages", "=", "self", ".", "_client", ".", "getAdditionalImages", "(", "self", ".", "setID", ")", "return", "self", ".", "_additionalImages" ]
29.8
24
def wnfltd(small, window): """ Filter (remove) small intervals from a double precision window. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/wnfltd_c.html :param small: Limiting measure of small intervals. :type small: float :param window: Window to be filtered. :type window: s...
[ "def", "wnfltd", "(", "small", ",", "window", ")", ":", "assert", "isinstance", "(", "window", ",", "stypes", ".", "SpiceCell", ")", "assert", "window", ".", "dtype", "==", "1", "small", "=", "ctypes", ".", "c_double", "(", "small", ")", "libspice", "....
33.888889
15.777778
def _check_file(parameters): """Return list of errors.""" (filename, args) = parameters if filename == '-': contents = sys.stdin.read() else: with contextlib.closing( docutils.io.FileInput(source_path=filename) ) as input_file: contents = input_file.read(...
[ "def", "_check_file", "(", "parameters", ")", ":", "(", "filename", ",", "args", ")", "=", "parameters", "if", "filename", "==", "'-'", ":", "contents", "=", "sys", ".", "stdin", ".", "read", "(", ")", "else", ":", "with", "contextlib", ".", "closing",...
30.9375
16.4375
async def _handle_bad_notification(self, message): """ Adjusts the current state to be correct based on the received bad message notification whenever possible: bad_msg_notification#a7eff811 bad_msg_id:long bad_msg_seqno:int error_code:int = BadMsgNotification; "...
[ "async", "def", "_handle_bad_notification", "(", "self", ",", "message", ")", ":", "bad_msg", "=", "message", ".", "obj", "states", "=", "self", ".", "_pop_states", "(", "bad_msg", ".", "bad_msg_id", ")", "self", ".", "_log", ".", "debug", "(", "'Handling ...
44.657143
17.685714
def Colebrook(Re, eD, tol=None): r'''Calculates Darcy friction factor using the Colebrook equation originally published in [1]_. Normally, this function uses an exact solution to the Colebrook equation, derived with a CAS. A numerical can also be used. .. math:: \frac{1}{\sqrt{f}}=-2\log_...
[ "def", "Colebrook", "(", "Re", ",", "eD", ",", "tol", "=", "None", ")", ":", "if", "tol", "==", "-", "1", ":", "if", "Re", ">", "10.0", ":", "return", "Clamond", "(", "Re", ",", "eD", ")", "else", ":", "tol", "=", "None", "elif", "tol", "==",...
38.724138
24.42069
def set_hash_value(self, key, field, value, pipeline=False): """Set the value of field in a hash stored at key. Args: key (str): key (name) of the hash field (str): Field within the hash to set value: Value to set pipeline (bool): True, start a transactio...
[ "def", "set_hash_value", "(", "self", ",", "key", ",", "field", ",", "value", ",", "pipeline", "=", "False", ")", ":", "# FIXME(BMo): new name for this function -> save_dict_value ?", "if", "pipeline", ":", "self", ".", "_pipeline", ".", "hset", "(", "key", ",",...
36.866667
19.333333
def receive(host, timeout): """ Print all messages in queue. Args: host (str): Specified --host. timeout (int): How log should script wait for message. """ parameters = settings.get_amqp_settings()[host] queues = parameters["queues"] queues = dict(map(lambda (x, y): (y, x),...
[ "def", "receive", "(", "host", ",", "timeout", ")", ":", "parameters", "=", "settings", ".", "get_amqp_settings", "(", ")", "[", "host", "]", "queues", "=", "parameters", "[", "\"queues\"", "]", "queues", "=", "dict", "(", "map", "(", "lambda", "(", "x...
29
17.8
def readMyEC2Tag(tagName, connection=None): """ Load an EC2 tag for the running instance & print it. :param str tagName: Name of the tag to read :param connection: Optional boto connection """ assert isinstance(tagName, basestring), ("tagName must be a string but is %r" % tagName) # Load metadata. if ==...
[ "def", "readMyEC2Tag", "(", "tagName", ",", "connection", "=", "None", ")", ":", "assert", "isinstance", "(", "tagName", ",", "basestring", ")", ",", "(", "\"tagName must be a string but is %r\"", "%", "tagName", ")", "# Load metadata. if == {} we are on localhost", "...
38
20.631579