text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def kabsch(P, Q): """ Using the Kabsch algorithm with two sets of paired point P and Q, centered around the centroid. Each vector set is represented as an NxD matrix, where D is the the dimension of the space. The algorithm works in three steps: - a centroid translation of P and Q (assumed done...
[ "def", "kabsch", "(", "P", ",", "Q", ")", ":", "# Computation of the covariance matrix", "C", "=", "np", ".", "dot", "(", "np", ".", "transpose", "(", "P", ")", ",", "Q", ")", "# Computation of the optimal rotation matrix", "# This can be done using singular value d...
29.291667
22
def read_dependencies(filename): """Read in the dependencies from the virtualenv requirements file. """ dependencies = [] filepath = os.path.join('requirements', filename) with open(filepath, 'r') as stream: for line in stream: package = line.strip().split('#')[0].strip() ...
[ "def", "read_dependencies", "(", "filename", ")", ":", "dependencies", "=", "[", "]", "filepath", "=", "os", ".", "path", ".", "join", "(", "'requirements'", ",", "filename", ")", "with", "open", "(", "filepath", ",", "'r'", ")", "as", "stream", ":", "...
35.75
12.333333
def path_filter(extensions, exclude_paths=None): """ Returns a function that returns True if a filepath is acceptable. @param extensions An array of strings. Specifies what file extensions should be accepted by the filter. If None, we default to the U...
[ "def", "path_filter", "(", "extensions", ",", "exclude_paths", "=", "None", ")", ":", "exclude_paths", "=", "exclude_paths", "or", "[", "]", "def", "the_filter", "(", "path", ")", ":", "if", "not", "any", "(", "matches_extension", "(", "path", ",", "extens...
40.822222
17.577778
def read_word_data(self, addr, cmd): """Read a word (2 bytes) from the specified cmd register of the device. Note that this will interpret data using the endianness of the processor running Python (typically little endian)! """ assert self._device is not None, 'Bus must be opened...
[ "def", "read_word_data", "(", "self", ",", "addr", ",", "cmd", ")", ":", "assert", "self", ".", "_device", "is", "not", "None", ",", "'Bus must be opened before operations are made against it!'", "# Build ctypes values to marshall between ioctl and Python.", "reg", "=", "...
50.235294
19.764706
def optimize(request): """ Performs Holt Winters Parameter Optimization on the given post data. Expects the following values set in the post of the request: seasonLength - integer valuesToForecast - integer data - two dimensional array of [timestamp, value] """ #Parse argumen...
[ "def", "optimize", "(", "request", ")", ":", "#Parse arguments", "seasonLength", "=", "int", "(", "request", ".", "POST", ".", "get", "(", "'seasonLength'", ",", "6", ")", ")", "valuesToForecast", "=", "int", "(", "request", ".", "POST", ".", "get", "(",...
40.677419
19.064516
def set_chassis_name(name, host=None, admin_username=None, admin_password=None): ''' Set the name of the chassis. name The name to be set on the chassis. host The chassis host. admin_username The username used ...
[ "def", "set_chassis_name", "(", "name", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "return", "__execute_cmd", "(", "'setsysinfo -c chassisname {0}'", ".", "format", "(", "name", ")", ",", "host",...
25.2
23.866667
def pop(self,*args): ''' pop dimensions :parameter dimlist: list of dimensions :return: popped dimensions (tuple) .. note: overrides :func:`OrderedDict.pop` ''' nargs=len(args) dimlist=args[0] if isiterable(args[0]) else [args[0]] ...
[ "def", "pop", "(", "self", ",", "*", "args", ")", ":", "nargs", "=", "len", "(", "args", ")", "dimlist", "=", "args", "[", "0", "]", "if", "isiterable", "(", "args", "[", "0", "]", ")", "else", "[", "args", "[", "0", "]", "]", "missing", "=",...
32.705882
17.294118
def ControlFromPoint2(x: int, y: int) -> Control: """ Get a native handle from point x,y and call IUIAutomation.ElementFromHandle. Return `Control` subclass. """ return Control.CreateControlFromElement(_AutomationClient.instance().IUIAutomation.ElementFromHandle(WindowFromPoint(x, y)))
[ "def", "ControlFromPoint2", "(", "x", ":", "int", ",", "y", ":", "int", ")", "->", "Control", ":", "return", "Control", ".", "CreateControlFromElement", "(", "_AutomationClient", ".", "instance", "(", ")", ".", "IUIAutomation", ".", "ElementFromHandle", "(", ...
50.166667
24.5
def _ellipse_phantom_2d(space, ellipses): """Create a phantom of ellipses in 2d space. Parameters ---------- space : `DiscreteLp` Uniformly discretized space in which the phantom should be generated. If ``space.shape`` is 1 in an axis, a corresponding slice of the phantom is cre...
[ "def", "_ellipse_phantom_2d", "(", "space", ",", "ellipses", ")", ":", "# Blank image", "p", "=", "np", ".", "zeros", "(", "space", ".", "shape", ",", "dtype", "=", "space", ".", "dtype", ")", "minp", "=", "space", ".", "grid", ".", "min_pt", "maxp", ...
34.064815
20.907407
def uri_path(self, path): """ Set the Uri-Path of a request. :param path: the Uri-Path """ path = path.strip("/") tmp = path.split("?") path = tmp[0] paths = path.split("/") for p in paths: option = Option() option.number =...
[ "def", "uri_path", "(", "self", ",", "path", ")", ":", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "tmp", "=", "path", ".", "split", "(", "\"?\"", ")", "path", "=", "tmp", "[", "0", "]", "paths", "=", "path", ".", "split", "(", "\"/\"...
27.444444
12.222222
def specific_error(error): """Try to find the best error for humans to resolve The jsonschema.exceptions.best_match error is based purely on a mix of a strong match (ie. not anyOf, oneOf) and schema depth, this often yields odd results that are semantically confusing, instead we can use a bit of st...
[ "def", "specific_error", "(", "error", ")", ":", "if", "error", ".", "validator", "not", "in", "(", "'anyOf'", ",", "'oneOf'", ")", ":", "return", "error", "r", "=", "t", "=", "None", "if", "isinstance", "(", "error", ".", "instance", ",", "dict", ")...
34.962264
16.962264
def _opt_soft(eigvectors, rot_matrix, n_clusters): """ Optimizes the PCCA+ rotation matrix such that the memberships are exclusively nonnegative. Parameters ---------- eigenvectors : ndarray A matrix with the sorted eigenvectors in the columns. The stationary eigenvector should be f...
[ "def", "_opt_soft", "(", "eigvectors", ",", "rot_matrix", ",", "n_clusters", ")", ":", "# only consider first n_clusters eigenvectors", "eigvectors", "=", "eigvectors", "[", ":", ",", ":", "n_clusters", "]", "# crop first row and first column from rot_matrix", "# rot_crop_m...
32.258065
23.258065
def register_converter(self, converter: Converter[S, T]): """ Utility method to register any converter. Converters that support any type will be stored in the "generic" lists, and the others will be stored in front of the types they support :return: """ check_var(converte...
[ "def", "register_converter", "(", "self", ",", "converter", ":", "Converter", "[", "S", ",", "T", "]", ")", ":", "check_var", "(", "converter", ",", "var_types", "=", "Converter", ",", "var_name", "=", "'converter'", ")", "# (0) sanity check : check that parser ...
63.689655
36.034483
def from_dict(vpc_config, do_sanitize=False): """ Extracts subnets and security group ids as lists from a VpcConfig dict Args: vpc_config (dict): a VpcConfig dict containing 'Subnets' and 'SecurityGroupIds' do_sanitize (bool): whether to sanitize the VpcConfig dict before extracting values ...
[ "def", "from_dict", "(", "vpc_config", ",", "do_sanitize", "=", "False", ")", ":", "if", "do_sanitize", ":", "vpc_config", "=", "sanitize", "(", "vpc_config", ")", "if", "vpc_config", "is", "None", ":", "return", "None", ",", "None", "return", "vpc_config", ...
36.857143
24.571429
def post(self, url, entity): """ To make a POST request to Falkonry API server :param url: string :param entity: Instantiated class object """ try: if entity is None or entity == "": jsonData = "" else: jsonData = e...
[ "def", "post", "(", "self", ",", "url", ",", "entity", ")", ":", "try", ":", "if", "entity", "is", "None", "or", "entity", "==", "\"\"", ":", "jsonData", "=", "\"\"", "else", ":", "jsonData", "=", "entity", ".", "to_json", "(", ")", "except", "Exce...
34.5
14.763158
def _check_audience(payload_dict, audience): """Checks audience field from a JWT payload. Does nothing if the passed in ``audience`` is null. Args: payload_dict: dict, A dictionary containing a JWT payload. audience: string or NoneType, an audience to check for in the JWT...
[ "def", "_check_audience", "(", "payload_dict", ",", "audience", ")", ":", "if", "audience", "is", "None", ":", "return", "audience_in_payload", "=", "payload_dict", ".", "get", "(", "'aud'", ")", "if", "audience_in_payload", "is", "None", ":", "raise", "AppIde...
38.5
21.230769
def check_error_response(self, body, status): """Raise an exception if the response from the backend was an error. Args: body: A string containing the backend response body. status: A string containing the backend response status. Raises: BackendError if the response is an error. """...
[ "def", "check_error_response", "(", "self", ",", "body", ",", "status", ")", ":", "status_code", "=", "int", "(", "status", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", ")", "if", "status_code", ">=", "300", ":", "raise", "errors", ".", ...
32.923077
16.692308
def print_user(self, user): '''print a filesystem database user. A "database" folder that might end with the participant status (e.g. _finished) is extracted to print in format [folder] [identifier][studyid] /scif/data/expfactory/xxxx-xxxx xxxx-xxxx[studyid] ...
[ "def", "print_user", "(", "self", ",", "user", ")", ":", "status", "=", "\"active\"", "if", "user", ".", "endswith", "(", "'_finished'", ")", ":", "status", "=", "\"finished\"", "elif", "user", ".", "endswith", "(", "'_revoked'", ")", ":", "status", "=",...
28.521739
22.26087
def _get_y_scores(self, X): """ The ``roc_curve`` metric requires target scores that can either be the probability estimates of the positive class, confidence values or non- thresholded measure of decisions (as returned by "decision_function"). This method computes the scores by...
[ "def", "_get_y_scores", "(", "self", ",", "X", ")", ":", "# The resolution order of scoring functions", "attrs", "=", "(", "'predict_proba'", ",", "'decision_function'", ",", ")", "# Return the first resolved function", "for", "attr", "in", "attrs", ":", "try", ":", ...
37.571429
20.857143
def save_data(self, trigger_id, **data): """ let's save the data :param trigger_id: trigger ID from which to save data :param data: the data to check to be used and save :type trigger_id: int :type data: dict :return: the status of the save...
[ "def", "save_data", "(", "self", ",", "trigger_id", ",", "*", "*", "data", ")", ":", "from", "th_pelican", ".", "models", "import", "Pelican", "title", ",", "content", "=", "super", "(", "ServicePelican", ",", "self", ")", ".", "save_data", "(", "trigger...
31.028571
18.057143
def proto_0202(theABF): """protocol: MTIV.""" abf=ABF(theABF) abf.log.info("analyzing as MTIV") plot=ABFplot(abf) plot.figure_height,plot.figure_width=SQUARESIZE,SQUARESIZE plot.title="" plot.kwargs["alpha"]=.6 plot.figure_sweeps() # frame to uppwer/lower bounds, ignoring peaks from...
[ "def", "proto_0202", "(", "theABF", ")", ":", "abf", "=", "ABF", "(", "theABF", ")", "abf", ".", "log", ".", "info", "(", "\"analyzing as MTIV\"", ")", "plot", "=", "ABFplot", "(", "abf", ")", "plot", ".", "figure_height", ",", "plot", ".", "figure_wid...
27.9
19.65
def read_moc(self, filename): """Read a file into the current running MOC object. If the running MOC object has not yet been created, then it is created by reading the file, which will import the MOC metadata. Otherwise the metadata are not imported. """ if self.moc is...
[ "def", "read_moc", "(", "self", ",", "filename", ")", ":", "if", "self", ".", "moc", "is", "None", ":", "self", ".", "moc", "=", "MOC", "(", "filename", "=", "filename", ")", "else", ":", "self", ".", "moc", ".", "read", "(", "filename", ")" ]
31.615385
19.307692
def _post_create(atdepth, entry, result): """Finishes the entry logging if applicable. """ if not atdepth and entry is not None: if result is not None: #We need to get these results a UUID that will be saved so that any #instance methods applied to this object has a parent to...
[ "def", "_post_create", "(", "atdepth", ",", "entry", ",", "result", ")", ":", "if", "not", "atdepth", "and", "entry", "is", "not", "None", ":", "if", "result", "is", "not", "None", ":", "#We need to get these results a UUID that will be saved so that any", "#insta...
37.466667
12.6
def as_event_description(self): """ Get the event description. Returns a dictionary describing the event. """ description = { self.name: { 'timestamp': self.time, }, } if self.data is not None: description[self...
[ "def", "as_event_description", "(", "self", ")", ":", "description", "=", "{", "self", ".", "name", ":", "{", "'timestamp'", ":", "self", ".", "time", ",", "}", ",", "}", "if", "self", ".", "data", "is", "not", "None", ":", "description", "[", "self"...
22.4375
16.9375
def plot_coupling_matrix(self, lmax, nwin=None, weights=None, mode='full', axes_labelsize=None, tick_labelsize=None, show=True, ax=None, fname=None): """ Plot the multitaper coupling matrix. This matrix relates the global power spectrum ...
[ "def", "plot_coupling_matrix", "(", "self", ",", "lmax", ",", "nwin", "=", "None", ",", "weights", "=", "None", ",", "mode", "=", "'full'", ",", "axes_labelsize", "=", "None", ",", "tick_labelsize", "=", "None", ",", "show", "=", "True", ",", "ax", "="...
43.471429
20.671429
def asserts(input_value, rule, message=''): """ this function allows you to write asserts in generators since there are moments where you actually want the program to halt when certain values are seen. """ assert callable(rule) or type(rule)==bool, 'asserts needs rule to be a callable functi...
[ "def", "asserts", "(", "input_value", ",", "rule", ",", "message", "=", "''", ")", ":", "assert", "callable", "(", "rule", ")", "or", "type", "(", "rule", ")", "==", "bool", ",", "'asserts needs rule to be a callable function or a test boolean'", "assert", "isin...
47.75
21.65
def visitMultiElementGroup(self, ctx: ShExDocParser.MultiElementGroupContext): """ multiElementGroup: unaryShape (';' unaryShape)+ ';'? """ self.expression = EachOf(expressions=[]) for us in ctx.unaryShape(): parser = ShexOneOfShapeParser(self.context) parser.visit(us) ...
[ "def", "visitMultiElementGroup", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "MultiElementGroupContext", ")", ":", "self", ".", "expression", "=", "EachOf", "(", "expressions", "=", "[", "]", ")", "for", "us", "in", "ctx", ".", "unaryShape", "(", "...
53.857143
14.714286
def strip_ssh_from_git_uri(uri): # type: (S) -> S """Return git+ssh:// formatted URI to git+git@ format""" if isinstance(uri, six.string_types): if "git+ssh://" in uri: parsed = urlparse(uri) # split the path on the first separating / so we can put the first segment ...
[ "def", "strip_ssh_from_git_uri", "(", "uri", ")", ":", "# type: (S) -> S", "if", "isinstance", "(", "uri", ",", "six", ".", "string_types", ")", ":", "if", "\"git+ssh://\"", "in", "uri", ":", "parsed", "=", "urlparse", "(", "uri", ")", "# split the path on the...
45.333333
17.466667
def param_defs(self, method): """Get parameter definitions for document literal.""" pts = self.bodypart_types(method) if not method.soap.input.body.wrapped: return pts pt = pts[0][1].resolve() return [(c.name, c, a) for c, a in pt if not c.isattr()]
[ "def", "param_defs", "(", "self", ",", "method", ")", ":", "pts", "=", "self", ".", "bodypart_types", "(", "method", ")", "if", "not", "method", ".", "soap", ".", "input", ".", "body", ".", "wrapped", ":", "return", "pts", "pt", "=", "pts", "[", "0...
42.142857
9.714286
def compare_digest(a, b): """ PyJWT expects hmac.compare_digest to exist for all Python 3.x, however it was added in Python > 3.3 It has a fallback for Python 2.x but not for Pythons between 2.x and 3.3 Copied from: https://github.com/python/cpython/commit/6cea65555caf2716b4633827715004ab0291a282#diff-c...
[ "def", "compare_digest", "(", "a", ",", "b", ")", ":", "# Consistent timing matters more here than data type flexibility", "if", "not", "(", "isinstance", "(", "a", ",", "bytes", ")", "and", "isinstance", "(", "b", ",", "bytes", ")", ")", ":", "raise", "TypeEr...
43.72
27.8
def __humanname(self, line): """Return the IRQ name, alias or number (choose the best for human). IRQ line samples: 1: 44487 341 44 72 IO-APIC 1-edge i8042 LOC: 33549868 22394684 32474570 21855077 Local timer interrupts """ ...
[ "def", "__humanname", "(", "self", ",", "line", ")", ":", "splitted_line", "=", "line", ".", "split", "(", ")", "irq_line", "=", "splitted_line", "[", "0", "]", ".", "replace", "(", "':'", ",", "''", ")", "if", "irq_line", ".", "isdigit", "(", ")", ...
44.153846
18.692308
def add_attributes(attrs,**kwargs): """ Add a list of generic attributes, which can then be used in creating a resource attribute, and put into a type. .. code-block:: python (Attr){ id = 1020 name = "Test Attr" dimen = "very big" } """ #Ch...
[ "def", "add_attributes", "(", "attrs", ",", "*", "*", "kwargs", ")", ":", "#Check to see if any of the attributs being added are already there.", "#If they are there already, don't add a new one. If an attribute", "#with the same name is there already but with a different dimension,", "#ad...
31.245283
22.90566
def add_cli_summarize(main: click.Group) -> click.Group: # noqa: D202 """Add a ``summarize`` command to main :mod:`click` function.""" @main.command() @click.pass_obj def summarize(manager: AbstractManager): """Summarize the contents of the database.""" if not manager.is_populated(): ...
[ "def", "add_cli_summarize", "(", "main", ":", "click", ".", "Group", ")", "->", "click", ".", "Group", ":", "# noqa: D202", "@", "main", ".", "command", "(", ")", "@", "click", ".", "pass_obj", "def", "summarize", "(", "manager", ":", "AbstractManager", ...
36.6
21.333333
def _process_added_port_event(self, port_name): """Callback for added ports.""" LOG.info("Hyper-V VM vNIC added: %s", port_name) self._added_ports.add(port_name)
[ "def", "_process_added_port_event", "(", "self", ",", "port_name", ")", ":", "LOG", ".", "info", "(", "\"Hyper-V VM vNIC added: %s\"", ",", "port_name", ")", "self", ".", "_added_ports", ".", "add", "(", "port_name", ")" ]
45.5
5.75
def remove_handler(self, handler): """Remove a handler object. :Parameters: - `handler`: the object to remove """ with self.lock: if handler in self.handlers: self.handlers.remove(handler) self._update_handlers()
[ "def", "remove_handler", "(", "self", ",", "handler", ")", ":", "with", "self", ".", "lock", ":", "if", "handler", "in", "self", ".", "handlers", ":", "self", ".", "handlers", ".", "remove", "(", "handler", ")", "self", ".", "_update_handlers", "(", ")...
29.2
9.4
def get_pdu_length(self): """ Returns info about the PDU length. """ logger.info("getting PDU length") requested_ = c_uint16() negotiated_ = c_uint16() code = self.library.Cli_GetPduLength(self.pointer, byref(requested_), byref(negotiated_)) check_error(co...
[ "def", "get_pdu_length", "(", "self", ")", ":", "logger", ".", "info", "(", "\"getting PDU length\"", ")", "requested_", "=", "c_uint16", "(", ")", "negotiated_", "=", "c_uint16", "(", ")", "code", "=", "self", ".", "library", ".", "Cli_GetPduLength", "(", ...
31.545455
14.090909
def ChangeUserStatus(self, Status): """Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` ...
[ "def", "ChangeUserStatus", "(", "self", ",", "Status", ")", ":", "if", "self", ".", "CurrentUserStatus", ".", "upper", "(", ")", "==", "Status", ".", "upper", "(", ")", ":", "return", "self", ".", "_ChangeUserStatus_Event", "=", "threading", ".", "Event", ...
46.315789
21.315789
def datagramReceived(self, datagram, address): """ After receiving a datagram, generate the deferreds and add myself to it. """ def write(result): print "Writing %r" % result self.transport.write(result, address) d = self.d() #d.addCallbacks(write...
[ "def", "datagramReceived", "(", "self", ",", "datagram", ",", "address", ")", ":", "def", "write", "(", "result", ")", ":", "print", "\"Writing %r\"", "%", "result", "self", ".", "transport", ".", "write", "(", "result", ",", "address", ")", "d", "=", ...
34.083333
13.583333
def get_osarch(): ''' Get the os architecture using rpm --eval ''' if salt.utils.path.which('rpm'): ret = subprocess.Popen( 'rpm --eval "%{_host_cpu}"', shell=True, close_fds=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communi...
[ "def", "get_osarch", "(", ")", ":", "if", "salt", ".", "utils", ".", "path", ".", "which", "(", "'rpm'", ")", ":", "ret", "=", "subprocess", ".", "Popen", "(", "'rpm --eval \"%{_host_cpu}\"'", ",", "shell", "=", "True", ",", "close_fds", "=", "True", "...
30.733333
18.466667
def apply_network(network, x, chunksize=None): """ Apply a pytorch network, potentially in chunks """ network_is_cuda = next(network.parameters()).is_cuda x = torch.from_numpy(x) with torch.no_grad(): if network_is_cuda: x = x.cuda() if chunksize is None: ...
[ "def", "apply_network", "(", "network", ",", "x", ",", "chunksize", "=", "None", ")", ":", "network_is_cuda", "=", "next", "(", "network", ".", "parameters", "(", ")", ")", ".", "is_cuda", "x", "=", "torch", ".", "from_numpy", "(", "x", ")", "with", ...
26.055556
16.277778
def get_logging_level(debug): """Returns logging level based on boolean""" level = logging.INFO if debug: level = logging.DEBUG return level
[ "def", "get_logging_level", "(", "debug", ")", ":", "level", "=", "logging", ".", "INFO", "if", "debug", ":", "level", "=", "logging", ".", "DEBUG", "return", "level" ]
26.5
14.833333
def bqm_index_labelled_input(var_labels_arg_name, samples_arg_names): """Returns a decorator which ensures bqm variable labeling and all other specified sample-like inputs are index labeled and consistent. Args: var_labels_arg_name (str): The name of the argument that the user should us...
[ "def", "bqm_index_labelled_input", "(", "var_labels_arg_name", ",", "samples_arg_names", ")", ":", "def", "index_label_decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "_index_label", "(", "sampler", ",", "bqm", ",", "*", "*", "kwargs", ")...
39.112903
23.032258
def ipv6_hdr_len(ipv6): """Calculate length of headers before IPv6-Frag""" hdr_len = ipv6.__hdr_len__ for code in (0, 60, 43): ext_hdr = ipv6.extension_hdrs.get(code) if ext_hdr is not None: hdr_len += ext_hdr.length return hdr_len
[ "def", "ipv6_hdr_len", "(", "ipv6", ")", ":", "hdr_len", "=", "ipv6", ".", "__hdr_len__", "for", "code", "in", "(", "0", ",", "60", ",", "43", ")", ":", "ext_hdr", "=", "ipv6", ".", "extension_hdrs", ".", "get", "(", "code", ")", "if", "ext_hdr", "...
33.5
10
def get_flow_by_idx(self, idx, bus): """Return seriesflow based on the external idx on the `bus` side""" P, Q = [], [] if type(idx) is not list: idx = [idx] if type(bus) is not list: bus = [bus] for line_idx, bus_idx in zip(idx, bus): line_int...
[ "def", "get_flow_by_idx", "(", "self", ",", "idx", ",", "bus", ")", ":", "P", ",", "Q", "=", "[", "]", ",", "[", "]", "if", "type", "(", "idx", ")", "is", "not", "list", ":", "idx", "=", "[", "idx", "]", "if", "type", "(", "bus", ")", "is",...
37.235294
8.823529
def coherence(self, other, fftlength=None, overlap=None, window='hann', **kwargs): """Calculate the frequency-coherence between this `TimeSeries` and another. Parameters ---------- other : `TimeSeries` `TimeSeries` signal to calculate coherence with...
[ "def", "coherence", "(", "self", ",", "other", ",", "fftlength", "=", "None", ",", "overlap", "=", "None", ",", "window", "=", "'hann'", ",", "*", "*", "kwargs", ")", ":", "from", "matplotlib", "import", "mlab", "from", ".", ".", "frequencyseries", "im...
37.35443
20.278481
def abusecheck(self, send, nick, target, limit, cmd): """ Rate-limits commands. | If a nick uses commands with the limit attr set, record the time | at which they were used. | If the command is used more than `limit` times in a | minute, ignore the nick. """ if n...
[ "def", "abusecheck", "(", "self", ",", "send", ",", "nick", ",", "target", ",", "limit", ",", "cmd", ")", ":", "if", "nick", "not", "in", "self", ".", "abuselist", ":", "self", ".", "abuselist", "[", "nick", "]", "=", "{", "}", "if", "cmd", "not"...
41.12
14.24
def draw(self,obj): """ Actually draws the model of the given object to the render target. Note that if the batch used for this object already existed, drawing will be skipped as the batch should be drawn by the owner of it. """ self.ensureModelData(obj) ...
[ "def", "draw", "(", "self", ",", "obj", ")", ":", "self", ".", "ensureModelData", "(", "obj", ")", "data", "=", "obj", ".", "_modeldata", "if", "data", ".", "get", "(", "\"_manual_render\"", ",", "False", ")", ":", "obj", ".", "batch3d", ".", "draw",...
37.090909
22.909091
def select_regex_in(pl,regex): ''' regex = re.compile("^x.*x$") pl = ['bcd','xabcxx','xx','y'] select_regex_in(pl,'abc') ''' def cond_func(ele,index,regex): if(type(ele)==type([])): cond = regex_in(ele,regex) else: m = regex.search(ele) ...
[ "def", "select_regex_in", "(", "pl", ",", "regex", ")", ":", "def", "cond_func", "(", "ele", ",", "index", ",", "regex", ")", ":", "if", "(", "type", "(", "ele", ")", "==", "type", "(", "[", "]", ")", ")", ":", "cond", "=", "regex_in", "(", "el...
28.722222
15.944444
def render(self, namespace): '''Render a 'true' or (if available) 'false' block based on a boolean.''' if (self._isbool and namespace[self._evaluate]) or \ (not self._isbool and namespace[self._evaluate](*[namespace[arg] ...
[ "def", "render", "(", "self", ",", "namespace", ")", ":", "if", "(", "self", ".", "_isbool", "and", "namespace", "[", "self", ".", "_evaluate", "]", ")", "or", "(", "not", "self", ".", "_isbool", "and", "namespace", "[", "self", ".", "_evaluate", "]"...
42.333333
14.5
def set(self, dic, val=None, force=False): """set can assign versatile options from `CMAOptions.versatile_options()` with a new value, use `init()` for the others. Arguments --------- `dic` either a dictionary or a key. In the latter c...
[ "def", "set", "(", "self", ",", "dic", ",", "val", "=", "None", ",", "force", "=", "False", ")", ":", "if", "val", "is", "not", "None", ":", "# dic is a key in this case", "dic", "=", "{", "dic", ":", "val", "}", "# compose a dictionary", "for", "key_o...
38.774194
19
def _replace_pressure(arguments, dtype_in_vert): """Replace p and dp Vars with appropriate Var objects specific to the dtype_in_vert.""" arguments_out = [] for arg in arguments: if isinstance(arg, Var): if arg.name == 'p': arguments_out.append(_P_VARS[dtype_in_vert]) ...
[ "def", "_replace_pressure", "(", "arguments", ",", "dtype_in_vert", ")", ":", "arguments_out", "=", "[", "]", "for", "arg", "in", "arguments", ":", "if", "isinstance", "(", "arg", ",", "Var", ")", ":", "if", "arg", ".", "name", "==", "'p'", ":", "argum...
35.933333
11.666667
def _debug_log(self, msg): """Debug log messages if debug=True""" if not self.debug: return sys.stderr.write('{}\n'.format(msg))
[ "def", "_debug_log", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "debug", ":", "return", "sys", ".", "stderr", ".", "write", "(", "'{}\\n'", ".", "format", "(", "msg", ")", ")" ]
32
10.8
def trace(*predicates, **options): """ Starts tracing. Can be used as a context manager (with slightly incorrect semantics - it starts tracing before ``__enter__`` is called). Parameters: *predicates (callables): Runs actions if **all** of the given predicates match. Keyword Args: c...
[ "def", "trace", "(", "*", "predicates", ",", "*", "*", "options", ")", ":", "global", "_last_tracer", "predicates", ",", "options", "=", "load_config", "(", "predicates", ",", "options", ")", "clear_env_var", "=", "options", ".", "pop", "(", "\"clear_env_var...
38.510638
25.276596
def Nand(*xs, simplify=True): """Expression NAND (not AND) operator If *simplify* is ``True``, return a simplified expression. """ xs = [Expression.box(x).node for x in xs] y = exprnode.not_(exprnode.and_(*xs)) if simplify: y = y.simplify() return _expr(y)
[ "def", "Nand", "(", "*", "xs", ",", "simplify", "=", "True", ")", ":", "xs", "=", "[", "Expression", ".", "box", "(", "x", ")", ".", "node", "for", "x", "in", "xs", "]", "y", "=", "exprnode", ".", "not_", "(", "exprnode", ".", "and_", "(", "*...
28.4
14
def get_kbr_values(self, searchkey="", searchvalue="", searchtype='s'): """ Return dicts of 'key' and 'value' from a knowledge base. :param kb_name the name of the knowledge base :param searchkey search using this key :param searchvalue search using this value :param sea...
[ "def", "get_kbr_values", "(", "self", ",", "searchkey", "=", "\"\"", ",", "searchvalue", "=", "\"\"", ",", "searchtype", "=", "'s'", ")", ":", "import", "warnings", "warnings", ".", "warn", "(", "\"The function is deprecated. Please use the \"", "\"`KnwKBRVAL.query_...
45.2
15.8
def ekifld(handle, tabnam, ncols, nrows, cnmlen, cnames, declen, decls): """ Initialize a new E-kernel segment to allow fast writing. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekifld_c.html :param handle: File handle. :type handle: int :param tabnam: Table name. :type tabnam:...
[ "def", "ekifld", "(", "handle", ",", "tabnam", ",", "ncols", ",", "nrows", ",", "cnmlen", ",", "cnames", ",", "declen", ",", "decls", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "tabnam", "=", "stypes", ".", "stringToCharP", ...
36.368421
14.736842
def get_cdd_only_candidate_models( data, minimum_non_zero_cdd, minimum_total_cdd, beta_cdd_maximum_p_value, weights_col ): """ Return a list of all possible candidate cdd-only models. Parameters ---------- data : :any:`pandas.DataFrame` A DataFrame containing at least the column ``meter_val...
[ "def", "get_cdd_only_candidate_models", "(", "data", ",", "minimum_non_zero_cdd", ",", "minimum_total_cdd", ",", "beta_cdd_maximum_p_value", ",", "weights_col", ")", ":", "balance_points", "=", "[", "int", "(", "col", "[", "4", ":", "]", ")", "for", "col", "in",...
40.512195
21.170732
def sf(f, dirpath, jottapath): """Create and return a SyncFile tuple from filename. localpath will be a byte string with utf8 code points jottapath will be a unicode string""" log.debug('Create SyncFile from %s', repr(f)) log.debug('Got encoded filename %r, joining with dirpath %r',...
[ "def", "sf", "(", "f", ",", "dirpath", ",", "jottapath", ")", ":", "log", ".", "debug", "(", "'Create SyncFile from %s'", ",", "repr", "(", "f", ")", ")", "log", ".", "debug", "(", "'Got encoded filename %r, joining with dirpath %r'", ",", "_encode_filename_to_f...
62.222222
30.555556
def geodesic(self, start_vertex, end_vertex, inplace=False): """ Calculates the geodesic path betweeen two vertices using Dijkstra's algorithm. Parameters ---------- start_vertex : int Vertex index indicating the start point of the geodesic segment. ...
[ "def", "geodesic", "(", "self", ",", "start_vertex", ",", "end_vertex", ",", "inplace", "=", "False", ")", ":", "if", "start_vertex", "<", "0", "or", "end_vertex", ">", "self", ".", "n_points", "-", "1", ":", "raise", "IndexError", "(", "'Invalid indices.'...
28.857143
21.714286
async def items(self): """Lists all the active tokens Returns: ObjectMeta: where value is a list of tokens It returns a body like this:: [ { "CreateIndex": 3, "ModifyIndex": 3, "ID": "8f246b77-f3e1-ff88-5b48...
[ "async", "def", "items", "(", "self", ")", ":", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/acl/list\"", ")", "results", "=", "[", "decode_token", "(", "r", ")", "for", "r", "in", "response", ".", "body", "]", "return", "co...
29.555556
17.592593
def ensure(cond, *args, **kwds): """ Return if a condition is true, otherwise raise a caller-configurable :py:class:`Exception` :param bool cond: the condition to be checked :param sequence args: the arguments to be passed to the exception's constructor The only accepte...
[ "def", "ensure", "(", "cond", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "_CHK_UNEXP", "=", "'check_condition() got an unexpected keyword argument {0}'", "raising", "=", "kwds", ".", "pop", "(", "'raising'", ",", "AssertionError", ")", "if", "kwds", ":...
35.947368
20.052632
def get(self, bus_name, object_path=None, **kwargs): """Get a remote object. Parameters ---------- bus_name : string Name of the service that exposes this object. You may start with "." - then org.freedesktop will be automatically prepended. object_path : string, optional Path of the object. If not ...
[ "def", "get", "(", "self", ",", "bus_name", ",", "object_path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Python 2 sux", "for", "kwarg", "in", "kwargs", ":", "if", "kwarg", "not", "in", "(", "\"timeout\"", ",", ")", ":", "raise", "TypeError", ...
35.255319
26.021277
def _other_to_lon(func): """Wrapper for casting Longitude operator arguments to Longitude""" def func_other_to_lon(obj, other): return func(obj, _maybe_cast_to_lon(other)) return func_other_to_lon
[ "def", "_other_to_lon", "(", "func", ")", ":", "def", "func_other_to_lon", "(", "obj", ",", "other", ")", ":", "return", "func", "(", "obj", ",", "_maybe_cast_to_lon", "(", "other", ")", ")", "return", "func_other_to_lon" ]
42.4
8.2
def tf_demo_loss(self, states, actions, terminal, reward, internals, update, reference=None): """ Extends the q-model loss via the dqfd large-margin loss. """ embedding = self.network.apply(x=states, internals=internals, update=update) deltas = list() for name in sorted(...
[ "def", "tf_demo_loss", "(", "self", ",", "states", ",", "actions", ",", "terminal", ",", "reward", ",", "internals", ",", "update", ",", "reference", "=", "None", ")", ":", "embedding", "=", "self", ".", "network", ".", "apply", "(", "x", "=", "states"...
50.55
31.35
def classifierPredict(testVector, storedVectors): """ Return overlap of the testVector with stored representations for each object. """ numClasses = storedVectors.shape[0] output = np.zeros((numClasses,)) for i in range(numClasses): output[i] = np.sum(np.minimum(testVector, storedVectors[i, :])) retu...
[ "def", "classifierPredict", "(", "testVector", ",", "storedVectors", ")", ":", "numClasses", "=", "storedVectors", ".", "shape", "[", "0", "]", "output", "=", "np", ".", "zeros", "(", "(", "numClasses", ",", ")", ")", "for", "i", "in", "range", "(", "n...
32
16
def load_file(self, path, objtype=None, encoding='utf-8'): ''' Load the file specified by path This method will first try to load the file contents from cache and if there is a cache miss, it will load the contents from disk Args: path (string): The full or relative...
[ "def", "load_file", "(", "self", ",", "path", ",", "objtype", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "path", "=", "self", ".", "abspath", "(", "path", ")", "debug", "(", "'file path is %s'", "%", "path", ")", "if", "path", "in", "sel...
35.981132
23.754717
def fastgrad(a, win=11): """ Returns rolling - window gradient of a. Function to efficiently calculate the rolling gradient of a numpy array using 'stride_tricks' to split up a 1D array into an ndarray of sub - sections of the original array, of dimensions [len(a) - win, win]. Parameters -...
[ "def", "fastgrad", "(", "a", ",", "win", "=", "11", ")", ":", "# check to see if 'window' is odd (even does not work)", "if", "win", "%", "2", "==", "0", ":", "win", "+=", "1", "# subtract 1 from window if it is even.", "# trick for efficient 'rolling' computation in nump...
34.15625
21.03125
def _make_padding( self, members, padding_nb, offset, length, prev_member=None): """Make padding Fields for a specifed size.""" name = 'PADDING_%d' % padding_nb padding_nb += 1 log.debug("_make_padding: for %d bits", length) if (length % 8) != 0 or (prev_member is not...
[ "def", "_make_padding", "(", "self", ",", "members", ",", "padding_nb", ",", "offset", ",", "length", ",", "prev_member", "=", "None", ")", ":", "name", "=", "'PADDING_%d'", "%", "padding_nb", "padding_nb", "+=", "1", "log", ".", "debug", "(", "\"_make_pad...
50.317073
16.804878
def parse_ssh_config(lines): ''' Parses lines from the SSH config to create roster targets. :param lines: Individual lines from the ssh config file :return: Dictionary of targets in similar style to the flat roster ''' # transform the list of individual lines into a list of sublists where each ...
[ "def", "parse_ssh_config", "(", "lines", ")", ":", "# transform the list of individual lines into a list of sublists where each", "# sublist represents a single Host definition", "hosts", "=", "[", "]", "for", "line", "in", "lines", ":", "line", "=", "salt", ".", "utils", ...
36.48
15.92
def _version_find_existing(): """Returns set of existing versions in this repository. This information is backed by previously used version tags in git. Available tags are pulled from origin repository before. :return: available versions :rtype: set """ _tool_run('git fetch...
[ "def", "_version_find_existing", "(", ")", ":", "_tool_run", "(", "'git fetch origin -t'", ")", "git_tags", "=", "[", "x", "for", "x", "in", "(", "y", ".", "strip", "(", ")", "for", "y", "in", "(", "_tool_run", "(", "'git tag -l'", ")", ".", "stdout", ...
39.466667
20.666667
def rest_get(url, timeout): '''Call rest get method''' try: response = requests.get(url, timeout=timeout) return response except Exception as e: print('Get exception {0} when sending http get to url {1}'.format(str(e), url)) return None
[ "def", "rest_get", "(", "url", ",", "timeout", ")", ":", "try", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "timeout", "=", "timeout", ")", "return", "response", "except", "Exception", "as", "e", ":", "print", "(", "'Get exception {0} ...
34.125
20.875
def search(self, base_dn, search_filter, attributes=()): """Perform an AD search :param str base_dn: The base DN to search within :param str search_filter: The search filter to apply, such as: *objectClass=person* :param list attributes: Object attributes to populate, defaults...
[ "def", "search", "(", "self", ",", "base_dn", ",", "search_filter", ",", "attributes", "=", "(", ")", ")", ":", "results", "=", "[", "]", "page", "=", "0", "while", "page", "==", "0", "or", "self", ".", "sprc", ".", "cookie", ":", "page", "+=", "...
44
20.25
def unfederate(self, serverId): """ This operation unfederates an ArcGIS Server from Portal for ArcGIS """ url = self._url + "/servers/{serverid}/unfederate".format( serverid=serverId) params = {"f" : "json"} return self._get(url=url, ...
[ "def", "unfederate", "(", "self", ",", "serverId", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/servers/{serverid}/unfederate\"", ".", "format", "(", "serverid", "=", "serverId", ")", "params", "=", "{", "\"f\"", ":", "\"json\"", "}", "return", "sel...
39.363636
11
def add_features(host_name, client_name, client_pass, feature_names): """ Add a number of numerical features in the client. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass...
[ "def", "add_features", "(", "host_name", ",", "client_name", ",", "client_pass", ",", "feature_names", ")", ":", "init_feats", "=", "(", "\"&\"", ".", "join", "(", "[", "\"%s=0\"", "]", "*", "len", "(", "feature_names", ")", ")", ")", "%", "tuple", "(", ...
46.176471
17.470588
def decr(self, conn, key, decrement=1): """Command is used to change data for some item in-place, decrementing it. The data for the item is treated as decimal representation of a 64-bit unsigned integer. :param key: ``bytes``, is the key of the item the client wishes to change ...
[ "def", "decr", "(", "self", ",", "conn", ",", "key", ",", "decrement", "=", "1", ")", ":", "assert", "self", ".", "_validate_key", "(", "key", ")", "resp", "=", "yield", "from", "self", ".", "_incr_decr", "(", "conn", ",", "b'decr'", ",", "key", ",...
42.235294
14.235294
def list_container_objects(self, container, prefix=None, delimiter=None): """List container objects :param container: container name (Container is equivalent to Bucket term in Amazon). :param prefix: prefix query :param delimiter: string to delimit the queries ...
[ "def", "list_container_objects", "(", "self", ",", "container", ",", "prefix", "=", "None", ",", "delimiter", "=", "None", ")", ":", "LOG", ".", "debug", "(", "'list_container_objects() with %s is success.'", ",", "self", ".", "driver", ")", "return", "self", ...
48.4
21
def default_returns_func(symbol, start=None, end=None): """ Gets returns for a symbol. Queries Yahoo Finance. Attempts to cache SPY. Parameters ---------- symbol : str Ticker symbol, e.g. APPL. start : date, optional Earliest date to fetch data for. Defaults to earli...
[ "def", "default_returns_func", "(", "symbol", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "start", "is", "None", ":", "start", "=", "'1/1/1970'", "if", "end", "is", "None", ":", "end", "=", "_1_bday_ago", "(", ")", "start", "=...
28.181818
17.409091
def match(select, tag, namespaces=None, flags=0, **kwargs): """Match node.""" return compile(select, namespaces, flags, **kwargs).match(tag)
[ "def", "match", "(", "select", ",", "tag", ",", "namespaces", "=", "None", ",", "flags", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "compile", "(", "select", ",", "namespaces", ",", "flags", ",", "*", "*", "kwargs", ")", ".", "match", ...
36.5
21.25
def _load_enums(root): """Returns {name: Enum}""" out = collections.OrderedDict() for elem in root.findall('enums/enum'): name = elem.attrib['name'] value = elem.attrib['value'] comment = elem.get('comment') out[name] = Enum(name, value, comment) return out
[ "def", "_load_enums", "(", "root", ")", ":", "out", "=", "collections", ".", "OrderedDict", "(", ")", "for", "elem", "in", "root", ".", "findall", "(", "'enums/enum'", ")", ":", "name", "=", "elem", ".", "attrib", "[", "'name'", "]", "value", "=", "e...
33
7.888889
def remove_scope_ip(hostid, auth, url): """ Function to add remove IP address allocation :param hostid: Host id of the host to be deleted :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.au...
[ "def", "remove_scope_ip", "(", "hostid", ",", "auth", ",", "url", ")", ":", "f_url", "=", "url", "+", "'/imcrs/res/access/assignedIpScope/ip/'", "+", "str", "(", "hostid", ")", "response", "=", "requests", ".", "delete", "(", "f_url", ",", "auth", "=", "au...
34.727273
27.136364
def commonprefix(m): "Given a list of pathnames, returns the longest common leading component" if not m: return '' s1 = min(m) s2 = max(m) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return s1
[ "def", "commonprefix", "(", "m", ")", ":", "if", "not", "m", ":", "return", "''", "s1", "=", "min", "(", "m", ")", "s2", "=", "max", "(", "m", ")", "for", "i", ",", "c", "in", "enumerate", "(", "s1", ")", ":", "if", "c", "!=", "s2", "[", ...
26.666667
21.555556
def _create_environment(config, outdir): """Constructor for an instance of the environment. Args: config: Object providing configurations via attributes. outdir: Directory to store videos in. Raises: NotImplementedError: For action spaces other than Box and Discrete. Returns: Wrapped OpenAI G...
[ "def", "_create_environment", "(", "config", ",", "outdir", ")", ":", "if", "isinstance", "(", "config", ".", "env", ",", "str", ")", ":", "env", "=", "gym", ".", "make", "(", "config", ".", "env", ")", "else", ":", "env", "=", "config", ".", "env"...
34.444444
17.416667
def build_scope(resource, method): """Compute the name of the scope for oauth :param Resource resource: the resource manager :param str method: an http method :return str: the name of the scope """ if ResourceList in inspect.getmro(resource) and method == 'GET': ...
[ "def", "build_scope", "(", "resource", ",", "method", ")", ":", "if", "ResourceList", "in", "inspect", ".", "getmro", "(", "resource", ")", "and", "method", "==", "'GET'", ":", "prefix", "=", "'list'", "else", ":", "method_to_prefix", "=", "{", "'GET'", ...
38.4
15.95
def argument(self, argument_dest, arg_type=None, **kwargs): """ Register an argument for the given command scope using a knack.arguments.CLIArgumentType :param argument_dest: The destination argument to add this argument type to :type argument_dest: str :param arg_type: Predefined CLIAr...
[ "def", "argument", "(", "self", ",", "argument_dest", ",", "arg_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_stale", "(", ")", "if", "not", "self", ".", "_applicable", "(", ")", ":", "return", "deprecate_action", "=", "se...
58.142857
30.095238
def union(*argv): """Returns union of sets as a new set. basically it's Items are ordered by set1, set2, ... **中文文档** 求多个有序集合的并集, 按照第一个集合, 第二个, ..., 这样的顺序。 """ res = OrderedSet() for ods in argv: res = res | ods return res
[ "def", "union", "(", "*", "argv", ")", ":", "res", "=", "OrderedSet", "(", ")", "for", "ods", "in", "argv", ":", "res", "=", "res", "|", "ods", "return", "res" ]
25.416667
15.416667
def _validateListedSubdirsExist(self, component): ''' Return true if all the subdirectories which this component lists in its module.json file exist (although their validity is otherwise not checked). If they don't, warning messages are printed. ''' lib_subdi...
[ "def", "_validateListedSubdirsExist", "(", "self", ",", "component", ")", ":", "lib_subdirs", "=", "component", ".", "getLibs", "(", "explicit_only", "=", "True", ")", "bin_subdirs", "=", "component", ".", "getBinaries", "(", ")", "ok", "=", "True", "for", "...
38.538462
26.538462
def raw_cube_array(self): """Return read-only ndarray of measure values from cube-response. The shape of the ndarray mirrors the shape of the (raw) cube response. Specifically, it includes values for missing elements, any MR_CAT dimensions, and any prunable rows and columns. """...
[ "def", "raw_cube_array", "(", "self", ")", ":", "array", "=", "np", ".", "array", "(", "self", ".", "_flat_values", ")", ".", "reshape", "(", "self", ".", "_all_dimensions", ".", "shape", ")", "# ---must be read-only to avoid hard-to-find bugs---", "array", ".",...
46.363636
20.181818
def move_roles_to_base_role_config_group(resource_root, service_name, role_names, cluster_name="default"): """ Moves roles to the base role config group. The roles can be moved from any role config group belonging to the same service. The role type of the roles may vary. Each role will be moved to its c...
[ "def", "move_roles_to_base_role_config_group", "(", "resource_root", ",", "service_name", ",", "role_names", ",", "cluster_name", "=", "\"default\"", ")", ":", "return", "call", "(", "resource_root", ".", "put", ",", "_get_role_config_groups_path", "(", "cluster_name", ...
40.9375
19.3125
def log_scalar(self, metric_name, value, step=None): """ Add a new measurement. The measurement will be processed by the MongoDB observer during a heartbeat event. Other observers are not yet supported. :param metric_name: The name of the metric, e.g. training.loss ...
[ "def", "log_scalar", "(", "self", ",", "metric_name", ",", "value", ",", "step", "=", "None", ")", ":", "# Method added in change https://github.com/chovanecm/sacred/issues/4", "# The same as Experiment.log_scalar (if something changes,", "# update the docstring too!)", "return", ...
42.263158
20.157895
def leaveEvent( self, event ): """ Toggles the display for the tracker item. """ item = self.trackerItem() if ( item ): item.setVisible(False)
[ "def", "leaveEvent", "(", "self", ",", "event", ")", ":", "item", "=", "self", ".", "trackerItem", "(", ")", "if", "(", "item", ")", ":", "item", ".", "setVisible", "(", "False", ")" ]
27.714286
7.142857
def wire_names(self, with_initial_value=True): """ Returns a list of names for each wire. Args: with_initial_value (bool): Optional (Default: True). If true, adds the initial value to the name. Returns: List: The list of wir...
[ "def", "wire_names", "(", "self", ",", "with_initial_value", "=", "True", ")", ":", "qubit_labels", "=", "self", ".", "_get_qubit_labels", "(", ")", "clbit_labels", "=", "self", ".", "_get_clbit_labels", "(", ")", "if", "with_initial_value", ":", "qubit_labels",...
37.666667
20.238095
def get_pattern(self, structure, scaled=True, two_theta_range=(0, 90)): """ Calculates the powder neutron diffraction pattern for a structure. Args: structure (Structure): Input structure scaled (bool): Whether to return scaled intensities. The maximum pe...
[ "def", "get_pattern", "(", "self", ",", "structure", ",", "scaled", "=", "True", ",", "two_theta_range", "=", "(", "0", ",", "90", ")", ")", ":", "if", "self", ".", "symprec", ":", "finder", "=", "SpacegroupAnalyzer", "(", "structure", ",", "symprec", ...
40.451852
21.962963
def _cartesian_product(self, first_specs, second_specs): """ Takes the Cartesian product of the specifications. Result will contain N specifications where N = len(first_specs) * len(second_specs) and keys are merged. Example: [{'a':1},{'b':2}] * [{'c':3},{'d':4}] = [{'a':...
[ "def", "_cartesian_product", "(", "self", ",", "first_specs", ",", "second_specs", ")", ":", "return", "[", "dict", "(", "zip", "(", "list", "(", "s1", ".", "keys", "(", ")", ")", "+", "list", "(", "s2", ".", "keys", "(", ")", ")", ",", "list", "...
47.153846
16.076923
def live_capture(self, new_timeout=10): """ try live capture of events """ was_enabled = self.is_enabled users = self.get_users() self.cancel_capture() self.verify_user() if not self.is_enabled: self.enable_device() if self.verbose: pri...
[ "def", "live_capture", "(", "self", ",", "new_timeout", "=", "10", ")", ":", "was_enabled", "=", "self", ".", "is_enabled", "users", "=", "self", ".", "get_users", "(", ")", "self", ".", "cancel_capture", "(", ")", "self", ".", "verify_user", "(", ")", ...
43.867647
12.544118
def flush_events(self): """Flush events from the cloud node.""" response = self._send_data('DELETE', 'admin', 'flush-events', {}) if response['success']: msg = "Events flushed" else: msg = "Flushing of events failed" output = {'message': msg} ret...
[ "def", "flush_events", "(", "self", ")", ":", "response", "=", "self", ".", "_send_data", "(", "'DELETE'", ",", "'admin'", ",", "'flush-events'", ",", "{", "}", ")", "if", "response", "[", "'success'", "]", ":", "msg", "=", "\"Events flushed\"", "else", ...
29.090909
18.454545
def ins2dict(ins, kind=''): """Turn a SQLAlchemy Model instance to dict. :param ins: a SQLAlchemy instance. :param kind: specify which kind of dict tranformer should be called. :return: dict, instance data. If model has defined `to_xxx_dict`, then ins2dict(ins, 'xxx') will call `model.to_xxx_d...
[ "def", "ins2dict", "(", "ins", ",", "kind", "=", "''", ")", ":", "if", "kind", "and", "hasattr", "(", "ins", ",", "'to_%s_dict'", "%", "kind", ")", ":", "return", "getattr", "(", "ins", ",", "'to_%s_dict'", "%", "kind", ")", "(", ")", "elif", "hasa...
35.263158
16.789474
def lagrange(pairs): """ Waring-Lagrange interpolator function. Parameters ---------- pairs : Iterable with pairs (tuples with two values), corresponding to points ``(x, y)`` of the function. Returns ------- A function that returns the interpolator result for a given ``x``. """ prod = lam...
[ "def", "lagrange", "(", "pairs", ")", ":", "prod", "=", "lambda", "args", ":", "reduce", "(", "operator", ".", "mul", ",", "args", ")", "xv", ",", "yv", "=", "xzip", "(", "*", "pairs", ")", "return", "lambda", "k", ":", "sum", "(", "yv", "[", "...
26.9
21.9
def list_shoulds(options): """Construct the list of 'SHOULD' validators to be run by the validator. """ validator_list = [] # Default: enable all if not options.disabled and not options.enabled: validator_list.extend(CHECKS['all']) return validator_list # --disable # Add SH...
[ "def", "list_shoulds", "(", "options", ")", ":", "validator_list", "=", "[", "]", "# Default: enable all", "if", "not", "options", ".", "disabled", "and", "not", "options", ".", "enabled", ":", "validator_list", ".", "extend", "(", "CHECKS", "[", "'all'", "]...
55.103774
24.622642
def build_area_source_node(area_source): """ Parses an area source to a Node class :param area_source: Area source as instance of :class: `openquake.hazardlib.source.area.AreaSource` :returns: Instance of :class:`openquake.baselib.node.Node` """ # parse geometry sour...
[ "def", "build_area_source_node", "(", "area_source", ")", ":", "# parse geometry", "source_nodes", "=", "[", "build_area_source_geometry", "(", "area_source", ")", "]", "# parse common distributed attributes", "source_nodes", ".", "extend", "(", "get_distributed_seismicity_so...
35.75
15.875
def tearDown(self): """ Be careful if a subclass of BaseCase overrides setUp() You'll need to add the following line to the subclass's tearDown(): super(SubClassOfBaseCase, self).tearDown() """ has_exception = False if sys.version.startswith('3') and hasattr(self,...
[ "def", "tearDown", "(", "self", ")", ":", "has_exception", "=", "False", "if", "sys", ".", "version", ".", "startswith", "(", "'3'", ")", "and", "hasattr", "(", "self", ",", "'_outcome'", ")", ":", "if", "hasattr", "(", "self", ".", "_outcome", ",", ...
52.469697
17.686869