text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def genargs() -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser() parser.add_argument("infile", help="Input JSG specification") parser.add_argument("-o", "--outfile", help="Output python file (Default: {infile}.py)") parser.add_argument("-e",...
[ "def", "genargs", "(", ")", "->", "ArgumentParser", ":", "parser", "=", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"infile\"", ",", "help", "=", "\"Input JSG specification\"", ")", "parser", ".", "add_argument", "(", "\"-o\"", ",", "\"--...
45.363636
24.272727
def get_train_err(htfa, data, F): """Calcuate training error Parameters ---------- htfa : HTFA An instance of HTFA, factor anaysis class in BrainIAK. data : 2D array Input data to HTFA. F : 2D array HTFA factor matrix. Returns ------- float ...
[ "def", "get_train_err", "(", "htfa", ",", "data", ",", "F", ")", ":", "W", "=", "htfa", ".", "get_weights", "(", "data", ",", "F", ")", "return", "recon_err", "(", "data", ",", "F", ",", "W", ")" ]
17.75
23.291667
def filter_pem(data): '''Processes the bytes for PEM certificates. Returns: ``set`` containing each certificate ''' assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data)) certs = set() new_list = [] in_pem_block = False for line in re.split(br'[\r\n]+', data...
[ "def", "filter_pem", "(", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", ",", "'Expect bytes. Got {}.'", ".", "format", "(", "type", "(", "data", ")", ")", "certs", "=", "set", "(", ")", "new_list", "=", "[", "]", "in_pem_blo...
27.903226
19
def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT): 'Encrypts a stream of bytes from in_stream to out_stream using mode.' encrypter = Encrypter(mode, padding = padding) _feed_stream(encrypter, in_stream, out_stream, block_size)
[ "def", "encrypt_stream", "(", "mode", ",", "in_stream", ",", "out_stream", ",", "block_size", "=", "BLOCK_SIZE", ",", "padding", "=", "PADDING_DEFAULT", ")", ":", "encrypter", "=", "Encrypter", "(", "mode", ",", "padding", "=", "padding", ")", "_feed_stream", ...
57
33
def _filter_commands(ctx, commands=None): """Return list of used commands.""" lookup = getattr(ctx.command, 'commands', {}) if not lookup and isinstance(ctx.command, click.MultiCommand): lookup = _get_lazyload_commands(ctx.command) if commands is None: return sorted(lookup.values(), key...
[ "def", "_filter_commands", "(", "ctx", ",", "commands", "=", "None", ")", ":", "lookup", "=", "getattr", "(", "ctx", ".", "command", ",", "'commands'", ",", "{", "}", ")", "if", "not", "lookup", "and", "isinstance", "(", "ctx", ".", "command", ",", "...
41.454545
19
def swap_environment_cnames(self, from_env_name, to_env_name): """ Swaps cnames for an environment """ self.ebs.swap_environment_cnames(source_environment_name=from_env_name, destination_environment_name=to_env_name)
[ "def", "swap_environment_cnames", "(", "self", ",", "from_env_name", ",", "to_env_name", ")", ":", "self", ".", "ebs", ".", "swap_environment_cnames", "(", "source_environment_name", "=", "from_env_name", ",", "destination_environment_name", "=", "to_env_name", ")" ]
47.333333
17.333333
def get_instance(self, payload): """ Build an instance of SessionInstance :param dict payload: Payload response from the API :returns: twilio.rest.proxy.v1.service.session.SessionInstance :rtype: twilio.rest.proxy.v1.service.session.SessionInstance """ return Se...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "SessionInstance", "(", "self", ".", "_version", ",", "payload", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", ")" ]
39.3
22.7
def users(self, user_base='active'): """Return dict of users""" if not getattr(self, '_%s_users' % user_base): self._get_users(user_base) return getattr(self, '_%s_users' % user_base)
[ "def", "users", "(", "self", ",", "user_base", "=", "'active'", ")", ":", "if", "not", "getattr", "(", "self", ",", "'_%s_users'", "%", "user_base", ")", ":", "self", ".", "_get_users", "(", "user_base", ")", "return", "getattr", "(", "self", ",", "'_%...
43
6.6
def list_streams(self, file_type, start=0, limit=100, filter_path=None, **kwargs): """以视频、音频、图片及文档四种类型的视图获取所创建应用程序下的 文件列表. :param file_type: 类型分为video、audio、image及doc四种。 :param start: 返回条目控制起始值,缺省值为0。 :param limit: 返回条目控制长度,缺省为1000,可配置。 :param filter...
[ "def", "list_streams", "(", "self", ",", "file_type", ",", "start", "=", "0", ",", "limit", "=", "100", ",", "filter_path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "'type'", ":", "file_type", ",", "'start'", ":", "start", ...
35.555556
15.333333
def delete(self, remote): """ Delete a file from server """ try: self.conn.delete(remote) except Exception: return False else: return True
[ "def", "delete", "(", "self", ",", "remote", ")", ":", "try", ":", "self", ".", "conn", ".", "delete", "(", "remote", ")", "except", "Exception", ":", "return", "False", "else", ":", "return", "True" ]
24.875
15.25
def zoom(image, factor, dimension, hdr = False, order = 3): """ Zooms the provided image by the supplied factor in the supplied dimension. The factor is an integer determining how many slices should be put between each existing pair. If an image header (hdr) is supplied, its voxel spacing gets updat...
[ "def", "zoom", "(", "image", ",", "factor", ",", "dimension", ",", "hdr", "=", "False", ",", "order", "=", "3", ")", ":", "# check if supplied dimension is valid", "if", "dimension", ">=", "image", ".", "ndim", ":", "raise", "argparse", ".", "ArgumentError",...
43.46875
28.09375
def __analizar_controles(self, ret): "Comprueba y extrae controles si existen en la respuesta XML" if 'arrayControles' in ret: controles = ret['arrayControles'] self.Controles = ["%(tipo)s: %(descripcion)s" % ctl['control'] for ctl in controles]
[ "def", "__analizar_controles", "(", "self", ",", "ret", ")", ":", "if", "'arrayControles'", "in", "ret", ":", "controles", "=", "ret", "[", "'arrayControles'", "]", "self", ".", "Controles", "=", "[", "\"%(tipo)s: %(descripcion)s\"", "%", "ctl", "[", "'control...
52.166667
15.166667
def match(self, ref): """ Get all concepts matching this ref. For a dimension, that is all its attributes, but not the dimension itself. """ try: concept = self[ref] if not isinstance(concept, Dimension): return [concept] return [a for a in con...
[ "def", "match", "(", "self", ",", "ref", ")", ":", "try", ":", "concept", "=", "self", "[", "ref", "]", "if", "not", "isinstance", "(", "concept", ",", "Dimension", ")", ":", "return", "[", "concept", "]", "return", "[", "a", "for", "a", "in", "c...
37.4
11.9
def _output_type_by_input_path(inpaths, itype, fmsg): """ :param inpaths: List of input file paths :param itype: Input type or None :param fmsg: message if it cannot detect otype by 'inpath' :return: Output type :: str """ msg = ("Specify inpath and/or outpath type[s] with -I/--itype " ...
[ "def", "_output_type_by_input_path", "(", "inpaths", ",", "itype", ",", "fmsg", ")", ":", "msg", "=", "(", "\"Specify inpath and/or outpath type[s] with -I/--itype \"", "\"or -O/--otype option explicitly\"", ")", "if", "itype", "is", "None", ":", "try", ":", "otype", ...
32.7
13.7
def get_single_submission_courses(self, user_id, course_id, assignment_id, include=None): """ Get a single submission. Get a single submission, based on user id. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""...
[ "def", "get_single_submission_courses", "(", "self", ",", "user_id", ",", "course_id", ",", "assignment_id", ",", "include", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\...
40.7
26.933333
def set_approvers(self, approver_ids=[], approver_group_ids=[], **kwargs): """Change MR-level allowed approvers and approver groups. Args: approver_ids (list): User IDs that can approve MRs approver_group_ids (list): Group IDs whose members can approve MRs Raises: ...
[ "def", "set_approvers", "(", "self", ",", "approver_ids", "=", "[", "]", ",", "approver_group_ids", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'%s/%s/approvers'", "%", "(", "self", ".", "_parent", ".", "manager", ".", "path", ",", ...
46.5625
23.3125
def _vel_disp_one(self, kwargs_profile, kwargs_aperture, kwargs_light, kwargs_anisotropy): """ computes one realisation of the velocity dispersion realized in the slit :param gamma: :param rho0_r0_gamma: :param r_eff: :param r_ani: :param R_slit: :param dR...
[ "def", "_vel_disp_one", "(", "self", ",", "kwargs_profile", ",", "kwargs_aperture", ",", "kwargs_light", ",", "kwargs_anisotropy", ")", ":", "while", "True", ":", "r", "=", "self", ".", "lightProfile", ".", "draw_light", "(", "kwargs_light", ")", "# draw r", "...
36.909091
22.818182
def expression_statement(self): """ expression_statement: assignment ';' """ node = self.assignment() self._process(Nature.SEMI) return node
[ "def", "expression_statement", "(", "self", ")", ":", "node", "=", "self", ".", "assignment", "(", ")", "self", ".", "_process", "(", "Nature", ".", "SEMI", ")", "return", "node" ]
26
6.857143
def transform_timeseries_data(timeseries, start, end=None): """Transforms a Go Metrics API metric result into a list of values for a given window period. start and end are expected to be Unix timestamps in microseconds. """ data = [] include = False for metric, points in timeseries.items():...
[ "def", "transform_timeseries_data", "(", "timeseries", ",", "start", ",", "end", "=", "None", ")", ":", "data", "=", "[", "]", "include", "=", "False", "for", "metric", ",", "points", "in", "timeseries", ".", "items", "(", ")", ":", "for", "point", "in...
33.058824
14.117647
def cmd_module(args): '''module commands''' usage = "usage: module <list|load|reload|unload>" if len(args) < 1: print(usage) return if args[0] == "list": for (m,pm) in mpstate.modules: print("%s: %s" % (m.name, m.description)) elif args[0] == "load": if le...
[ "def", "cmd_module", "(", "args", ")", ":", "usage", "=", "\"usage: module <list|load|reload|unload>\"", "if", "len", "(", "args", ")", "<", "1", ":", "print", "(", "usage", ")", "return", "if", "args", "[", "0", "]", "==", "\"list\"", ":", "for", "(", ...
32.692308
15
def prt_hier_down(self, goid, prt=sys.stdout): """Write hierarchy for all GO IDs below GO ID in arg, goid.""" wrhiercfg = self._get_wrhiercfg() obj = WrHierPrt(self.gosubdag.go2obj, self.gosubdag.go2nt, wrhiercfg, prt) obj.prt_hier_rec(goid) return obj.items_list
[ "def", "prt_hier_down", "(", "self", ",", "goid", ",", "prt", "=", "sys", ".", "stdout", ")", ":", "wrhiercfg", "=", "self", ".", "_get_wrhiercfg", "(", ")", "obj", "=", "WrHierPrt", "(", "self", ".", "gosubdag", ".", "go2obj", ",", "self", ".", "gos...
49.666667
11.666667
def get_language_tabs(self): """ Determine the language tabs to show. """ current_language = self.get_current_language() if self.object: available_languages = list(self.object.get_available_languages()) else: available_languages = [] retur...
[ "def", "get_language_tabs", "(", "self", ")", ":", "current_language", "=", "self", ".", "get_current_language", "(", ")", "if", "self", ".", "object", ":", "available_languages", "=", "list", "(", "self", ".", "object", ".", "get_available_languages", "(", ")...
34.727273
18.181818
def ensure_indirect_subclass(class_, of): """Check whether given is an indirect subclass of another, i.e. there exists at least intermediate base between ``of`` and ``class_``. :param class_: Class to check :param of: Superclass to check against :return: ``class_``, if the check succeeds :rais...
[ "def", "ensure_indirect_subclass", "(", "class_", ",", "of", ")", ":", "if", "not", "is_indirect_subclass", "(", "class_", ",", "of", ")", ":", "raise", "TypeError", "(", "\"expected an indirect subclass of %r, got %s instead\"", "%", "(", "of", ",", "class_", "."...
33.529412
15.588235
def get_stored_metadata(self, temp_ver): """ Retrieves the metadata for the given template version from the store Args: temp_ver (TemplateVersion): template version to retrieve the metadata for Returns: dict: the metadata of the given template ve...
[ "def", "get_stored_metadata", "(", "self", ",", "temp_ver", ")", ":", "with", "open", "(", "self", ".", "_prefixed", "(", "'%s.metadata'", "%", "temp_ver", ".", "name", ")", ")", "as", "f", ":", "return", "json", ".", "load", "(", "f", ")" ]
32.923077
20.769231
def load(self, service_name, api_version=None, cached=True): """ Loads the desired JSON for a service. (uncached) This will fall back through all the ``data_dirs`` provided to the constructor, returning the **first** one it finds. :param service_name: The name of the desired se...
[ "def", "load", "(", "self", ",", "service_name", ",", "api_version", "=", "None", ",", "cached", "=", "True", ")", ":", "# Fetch from the cache first if it's there.", "if", "cached", ":", "if", "service_name", "in", "self", ".", "_loaded_data", ":", "if", "api...
34.659091
20.840909
def recent(self, username, project, limit=1, offset=0, branch=None, status_filter=""): """Return status of recent builds for given project. Retrieves build statuses for given project and branch. If branch is None it retrieves most recent build. Args: username (str): Name o...
[ "def", "recent", "(", "self", ",", "username", ",", "project", ",", "limit", "=", "1", ",", "offset", "=", "0", ",", "branch", "=", "None", ",", "status_filter", "=", "\"\"", ")", ":", "method", "=", "'GET'", "if", "branch", "is", "not", "None", ":...
50.857143
25.514286
def locateChild(self, context, segments): """ Delegate dispatch to a sharing resource if the request is for a user subdomain, otherwise fall back to the wrapped resource's C{locateChild} implementation. """ request = IRequest(context) hostname = request.getHeader(...
[ "def", "locateChild", "(", "self", ",", "context", ",", "segments", ")", ":", "request", "=", "IRequest", "(", "context", ")", "hostname", "=", "request", ".", "getHeader", "(", "'host'", ")", "info", "=", "self", ".", "subdomain", "(", "hostname", ")", ...
40.235294
13.411765
def odt_to_ri(f, res, nm): r"""Convert the ODT object function to refractive index In :abbr:`ODT (Optical Diffraction Tomography)`, the object function is defined by the Helmholtz equation .. math:: f(\mathbf{r}) = k_\mathrm{m}^2 \left[ \left( \frac{n(\mathbf{r})}{n_\mathrm{m}} ...
[ "def", "odt_to_ri", "(", "f", ",", "res", ",", "nm", ")", ":", "km", "=", "(", "2", "*", "np", ".", "pi", "*", "nm", ")", "/", "res", "ri", "=", "nm", "*", "np", ".", "sqrt", "(", "f", "/", "km", "**", "2", "+", "1", ")", "# Always take t...
32.735849
22.056604
def SimpleRowColumn(field, *args, **kwargs): """ Shortcut for simple row with only a full column """ if isinstance(field, basestring): field = Field(field, *args, **kwargs) return Row( Column(field), )
[ "def", "SimpleRowColumn", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "field", ",", "basestring", ")", ":", "field", "=", "Field", "(", "field", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return...
25.888889
11.222222
def _other_pipeline_samples(summary_file, cur_samples): """Retrieve samples produced previously by another pipeline in the summary output. """ cur_descriptions = set([s[0]["description"] for s in cur_samples]) out = [] if utils.file_exists(summary_file): with open(summary_file) as in_handle:...
[ "def", "_other_pipeline_samples", "(", "summary_file", ",", "cur_samples", ")", ":", "cur_descriptions", "=", "set", "(", "[", "s", "[", "0", "]", "[", "\"description\"", "]", "for", "s", "in", "cur_samples", "]", ")", "out", "=", "[", "]", "if", "utils"...
44.272727
14.363636
def check_ensembl_api_version(self): """ check the ensembl api version matches a currently working version This function is included so when the api version changes, we notice the change, and we can manually check the responses for the new version. """ self.atte...
[ "def", "check_ensembl_api_version", "(", "self", ")", ":", "self", ".", "attempt", "=", "0", "headers", "=", "{", "\"content-type\"", ":", "\"application/json\"", "}", "ext", "=", "\"/info/rest\"", "r", "=", "self", ".", "ensembl_request", "(", "ext", ",", "...
39.214286
18.357143
def add_interim_values(module, input, output): """The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers """ try: del module.x except AttributeError: pass try: del module.y except AttributeError: pass modu...
[ "def", "add_interim_values", "(", "module", ",", "input", ",", "output", ")", ":", "try", ":", "del", "module", ".", "x", "except", "AttributeError", ":", "pass", "try", ":", "del", "module", ".", "y", "except", "AttributeError", ":", "pass", "module_type"...
42.405405
18.216216
def ancestors(obj, refattrs=(ALIGNMENT, SEGMENTATION)): """ >>> for anc in query.ancestors(igt.get_item('g1'), refattrs=(ALIGNMENT, SEGMENTATION)): ... print(anc) (<Tier object (id: g type: glosses) at ...>, 'alignment', <Tier object (id: m type: morphemes) at ...>, [<Item object (id: m1) at ...>]) ...
[ "def", "ancestors", "(", "obj", ",", "refattrs", "=", "(", "ALIGNMENT", ",", "SEGMENTATION", ")", ")", ":", "if", "hasattr", "(", "obj", ",", "'tier'", ")", ":", "tier", "=", "obj", ".", "tier", "items", "=", "[", "obj", "]", "else", ":", "tier", ...
44.617647
25.558824
def _parse_use(self, string): """Extracts use dependencies from the innertext of a module.""" result = {} for ruse in self.RE_USE.finditer(string): #We also handle comments for individual use cases, the "only" section #won't pick up any comments. name = ruse.g...
[ "def", "_parse_use", "(", "self", ",", "string", ")", ":", "result", "=", "{", "}", "for", "ruse", "in", "self", ".", "RE_USE", ".", "finditer", "(", "string", ")", ":", "#We also handle comments for individual use cases, the \"only\" section", "#won't pick up any c...
41.388889
14.333333
def import_data(target_zip): """ Import data from given zip-arc, this means database + __data__ :param target_zip: :param backup_zip_path: :return: """ from django_productline.context import PRODUCT_CONTEXT tasks.import_data_dir(target_zip) # product context is not reloaded if contex...
[ "def", "import_data", "(", "target_zip", ")", ":", "from", "django_productline", ".", "context", "import", "PRODUCT_CONTEXT", "tasks", ".", "import_data_dir", "(", "target_zip", ")", "# product context is not reloaded if context file is changed", "tasks", ".", "import_datab...
37.727273
17.181818
def construct(self, request=None, service=None, http_args=None, **kwargs): """ Constructing the Authorization header. The value of the Authorization header is "Bearer <access_token>". :param request: Request class instance :param service: Service :param...
[ "def", "construct", "(", "self", ",", "request", "=", "None", ",", "service", "=", "None", ",", "http_args", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "service", ".", "service_name", "==", "'refresh_token'", ":", "_acc_token", "=", "find_toke...
34.777778
20.777778
def get_all_anonymous_mappings(self, struct1, struct2, niggli=True, include_dist=False): """ Performs an anonymous fitting, which allows distinct species in one structure to map to another. Returns a dictionary of species substitutions that are within t...
[ "def", "get_all_anonymous_mappings", "(", "self", ",", "struct1", ",", "struct2", ",", "niggli", "=", "True", ",", "include_dist", "=", "False", ")", ":", "struct1", ",", "struct2", "=", "self", ".", "_process_species", "(", "[", "struct1", ",", "struct2", ...
44
22.962963
def _repr_mimebundle_(self, include=None, exclude=None): """Display the visualization in the Jupyter notebook.""" id = uuid.uuid4() return ( {'application/javascript': self._generate_js(id)}, {'jupyter-vega': '#{0}'.format(id)}, )
[ "def", "_repr_mimebundle_", "(", "self", ",", "include", "=", "None", ",", "exclude", "=", "None", ")", ":", "id", "=", "uuid", ".", "uuid4", "(", ")", "return", "(", "{", "'application/javascript'", ":", "self", ".", "_generate_js", "(", "id", ")", "}...
40
16.571429
def add_file_handler(logger, logFilename=None): """Adds file handler to logger. File is opened in "a" mode (append) """ assert isinstance(logger, logging.Logger) ch = logging.FileHandler(logFilename, "a") # ch.setFormatter(logging._defaultFormatter) # todo may change to have same formatt...
[ "def", "add_file_handler", "(", "logger", ",", "logFilename", "=", "None", ")", ":", "assert", "isinstance", "(", "logger", ",", "logging", ".", "Logger", ")", "ch", "=", "logging", ".", "FileHandler", "(", "logFilename", ",", "\"a\"", ")", "# ch.setFormatte...
39.4
16.4
def update_classroom(self, course, classroomid, new_data): """ Update classroom and returns a list of errored students""" student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid) # Check tutors new_data["tutors"] = [tutor for tutor in map(str.strip, new_dat...
[ "def", "update_classroom", "(", "self", ",", "course", ",", "classroomid", ",", "new_data", ")", ":", "student_list", ",", "tutor_list", ",", "other_students", ",", "_", "=", "self", ".", "get_user_lists", "(", "course", ",", "classroomid", ")", "# Check tutor...
50.156863
29.647059
def proveG1(x,tTilde,kw,y): """ Generate a zero-knowledge proof that DL(Q*kw) == DL(e(x,tTilde)^kw) where <Q> = G1. """ # Verify types assertType(x, G1Element) assertType(tTilde, G2Element) # Compute the proof. beta = pair(x,tTilde) Q = generatorG1() p = Q*kw v = randomZ...
[ "def", "proveG1", "(", "x", ",", "tTilde", ",", "kw", ",", "y", ")", ":", "# Verify types", "assertType", "(", "x", ",", "G1Element", ")", "assertType", "(", "tTilde", ",", "G2Element", ")", "# Compute the proof.", "beta", "=", "pair", "(", "x", ",", "...
20.136364
20.227273
def work_get(self, wallet, account): """ Retrieves work for **account** in **wallet** .. enable_control required .. version 8.0 required :param wallet: Wallet to get account work for :type wallet: str :param account: Account to get work for :type accoun...
[ "def", "work_get", "(", "self", ",", "wallet", ",", "account", ")", ":", "wallet", "=", "self", ".", "_process_value", "(", "wallet", ",", "'wallet'", ")", "account", "=", "self", ".", "_process_value", "(", "account", ",", "'account'", ")", "payload", "...
27.645161
22.870968
def remove_key(pki_dir, id_): ''' This method removes a specified key from the accepted keys dir ''' key = os.path.join(pki_dir, 'minions', id_) if os.path.isfile(key): os.remove(key) log.debug('Deleted \'%s\'', key)
[ "def", "remove_key", "(", "pki_dir", ",", "id_", ")", ":", "key", "=", "os", ".", "path", ".", "join", "(", "pki_dir", ",", "'minions'", ",", "id_", ")", "if", "os", ".", "path", ".", "isfile", "(", "key", ")", ":", "os", ".", "remove", "(", "k...
30.625
17.625
async def SetInstanceInfo(self, machines): ''' machines : typing.Sequence[~InstanceInfo] Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='Provisioner', request='SetInstanceInfo', ...
[ "async", "def", "SetInstanceInfo", "(", "self", ",", "machines", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'Provisioner'", ",", "request", "=", "'SetInstanceInfo'", ",", "version", "=", ...
32.857143
10.571429
def project_ecef_vector_onto_basis(x, y, z, xx, xy, xz, yx, yy, yz, zx, zy, zz): """Projects vector in ecef onto different basis, with components also expressed in ECEF Parameters ---------- x : float or array-like ECEF-X component of vector y : float or array-like ECEF-Y compon...
[ "def", "project_ecef_vector_onto_basis", "(", "x", ",", "y", ",", "z", ",", "xx", ",", "xy", ",", "xz", ",", "yx", ",", "yy", ",", "yz", ",", "zx", ",", "zy", ",", "zz", ")", ":", "out_x", "=", "x", "*", "xx", "+", "y", "*", "xy", "+", "z",...
31.44
17.04
def brain(self): """Catalog brain of the wrapped object """ if self._brain is None: logger.debug("SuperModel::brain: *Fetch catalog brain*") self._brain = self.get_brain_by_uid(self.uid) return self._brain
[ "def", "brain", "(", "self", ")", ":", "if", "self", ".", "_brain", "is", "None", ":", "logger", ".", "debug", "(", "\"SuperModel::brain: *Fetch catalog brain*\"", ")", "self", ".", "_brain", "=", "self", ".", "get_brain_by_uid", "(", "self", ".", "uid", "...
36.428571
13.142857
def partial_update(self, index, doc_type, id, doc=None, script=None, params=None, upsert=None, querystring_args=None): """ Partially update a document with a script """ if querystring_args is None: querystring_args = {} if doc is None and scrip...
[ "def", "partial_update", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "doc", "=", "None", ",", "script", "=", "None", ",", "params", "=", "None", ",", "upsert", "=", "None", ",", "querystring_args", "=", "None", ")", ":", "if", "querys...
33.590909
16.954545
def server_date_utc(self): """获取扇贝网服务器时间(UTC 时间)""" date_str = self.request('http://www.shanbay.com', 'head' ).headers['date'] date_utc = datetime.datetime.strptime(date_str, '%a, %d %b %Y %H:%M:%S GMT') return...
[ "def", "server_date_utc", "(", "self", ")", ":", "date_str", "=", "self", ".", "request", "(", "'http://www.shanbay.com'", ",", "'head'", ")", ".", "headers", "[", "'date'", "]", "date_utc", "=", "datetime", ".", "datetime", ".", "strptime", "(", "date_str",...
46.142857
16.142857
def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False return True
[ "def", "matches", "(", "self", ",", "client", ",", "event_data", ")", ":", "for", "f", "in", "self", ".", "filters", ":", "if", "not", "f", "(", "client", ",", "event_data", ")", ":", "return", "False", "return", "True" ]
25.375
15.75
def factor_for_space(self, spc): """Return a tuple of two products, where the first product contains the given Hilbert space, and the second product is disjunct from it.""" if spc == TrivialSpace: ops_on_spc = [ o for o in self.operands if o.space is TrivialSpace] ...
[ "def", "factor_for_space", "(", "self", ",", "spc", ")", ":", "if", "spc", "==", "TrivialSpace", ":", "ops_on_spc", "=", "[", "o", "for", "o", "in", "self", ".", "operands", "if", "o", ".", "space", "is", "TrivialSpace", "]", "ops_not_on_spc", "=", "["...
47.75
17.625
def _parse_members(self, contents, anexec, params, mode="insert"): """Parses the local variables for the contents of the specified executable.""" #First get the variables declared in the body of the executable, these can #be either locals or parameter declarations. members = self.vparser...
[ "def", "_parse_members", "(", "self", ",", "contents", ",", "anexec", ",", "params", ",", "mode", "=", "\"insert\"", ")", ":", "#First get the variables declared in the body of the executable, these can", "#be either locals or parameter declarations.", "members", "=", "self",...
49.818182
20.848485
def bedpe(args): """ %prog bedpe bedfile Convert to bedpe format. Use --span to write another bed file that contain the span of the read pairs. """ from jcvi.assembly.coverage import bed_to_bedpe p = OptionParser(bedpe.__doc__) p.add_option("--span", default=False, action="store_true",...
[ "def", "bedpe", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "coverage", "import", "bed_to_bedpe", "p", "=", "OptionParser", "(", "bedpe", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--span\"", ",", "default", "=", "False", ",", ...
35.142857
18.428571
def subsample(self, rate, random=False): """Returns a subsampled version of the PointCloud. Parameters ---------- rate : int Only every rate-th element of the PointCloud is returned. Returns ------- :obj:`PointCloud` A subsampled point cl...
[ "def", "subsample", "(", "self", ",", "rate", ",", "random", "=", "False", ")", ":", "if", "type", "(", "rate", ")", "!=", "int", "and", "rate", "<", "1", ":", "raise", "ValueError", "(", "'Can only subsample with strictly positive integer rate'", ")", "indi...
32.192308
19.461538
def glm(interactive=True, echo=True, testing=False): """GLM model demo.""" def demo_body(go): """ Demo of H2O's Generalized Linear Estimator. This demo uploads a dataset to h2o, parses it, and shows a description. Then it divides the dataset into training and test sets, builds ...
[ "def", "glm", "(", "interactive", "=", "True", ",", "echo", "=", "True", ",", "testing", "=", "False", ")", ":", "def", "demo_body", "(", "go", ")", ":", "\"\"\"\n Demo of H2O's Generalized Linear Estimator.\n\n This demo uploads a dataset to h2o, parses it,...
32.732143
24.25
async def get_data(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None, default: typing.Optional[typing.Dict] = None) -> typing.Dict: """ Get state-data for user in chat. Return `default` if no...
[ "async", "def", "get_data", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None",...
37.6875
23.9375
def head(self, msgid_article=None): """HEAD command. """ args = None if msgid_article is not None: args = utils.unparse_msgid_article(msgid_article) code, message = self.command("HEAD", args) if code != 221: raise NNTPReplyError(code, message) ...
[ "def", "head", "(", "self", ",", "msgid_article", "=", "None", ")", ":", "args", "=", "None", "if", "msgid_article", "is", "not", "None", ":", "args", "=", "utils", ".", "unparse_msgid_article", "(", "msgid_article", ")", "code", ",", "message", "=", "se...
30.916667
15.666667
def write_exports(self, exports): """ Write a dictionary of exports to a file in .ini format. :param exports: A dictionary of exports, mapping an export category to a list of :class:`ExportEntry` instances describing the individual export entries. ...
[ "def", "write_exports", "(", "self", ",", "exports", ")", ":", "rf", "=", "self", ".", "get_distinfo_file", "(", "EXPORTS_FILENAME", ")", "with", "open", "(", "rf", ",", "'w'", ")", "as", "f", ":", "write_exports", "(", "exports", ",", "f", ")" ]
44.7
14.1
def auth_get(user, computed=True): ''' List authorization for user user : string username computed : boolean merge results from `auths` command into data from user_attr CLI Example: .. code-block:: bash salt '*' rbac.auth_get leo ''' user_auths = [] ## re...
[ "def", "auth_get", "(", "user", ",", "computed", "=", "True", ")", ":", "user_auths", "=", "[", "]", "## read user_attr file (user:qualifier:res1:res2:attr)", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/etc/user_attr'", ",", "'r'", ")", "...
29.45283
20.509434
def correct_spectral_interference(self, target_analyte, source_analyte, f): """ Correct spectral interference. Subtract interference counts from target_analyte, based on the intensity of a source_analayte and a known fractional contribution (f). Correction takes the form: ...
[ "def", "correct_spectral_interference", "(", "self", ",", "target_analyte", ",", "source_analyte", ",", "f", ")", ":", "if", "target_analyte", "not", "in", "self", ".", "analytes", ":", "raise", "ValueError", "(", "'target_analyte: {:} not in available analytes ({:})'",...
35.693878
27
def deleteOverlapping(self, targetList): ''' Erase points from another list that overlap with points in this list ''' start = self.pointList[0][0] stop = self.pointList[-1][0] if self.netLeftShift < 0: start += self.netLeftShift i...
[ "def", "deleteOverlapping", "(", "self", ",", "targetList", ")", ":", "start", "=", "self", ".", "pointList", "[", "0", "]", "[", "0", "]", "stop", "=", "self", ".", "pointList", "[", "-", "1", "]", "[", "0", "]", "if", "self", ".", "netLeftShift",...
29.8125
17.0625
def rename(self, new_name, *args, **kwargs): """Rename this multireddit. This function is a handy shortcut to :meth:`rename_multireddit` of the reddit_session. """ new = self.reddit_session.rename_multireddit(self.name, new_name, ...
[ "def", "rename", "(", "self", ",", "new_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "new", "=", "self", ".", "reddit_session", ".", "rename_multireddit", "(", "self", ".", "name", ",", "new_name", ",", "*", "args", ",", "*", "*", "k...
37.545455
19
def plot_coherence(xdata, ydata, std_error, fit, fit_function, xunit, exp_str, qubit_label): """Plot coherence data. Args: xdata ydata std_error fit fit_function xunit exp_str qubit_label Raises: ImportError: If matp...
[ "def", "plot_coherence", "(", "xdata", ",", "ydata", ",", "std_error", ",", "fit", ",", "fit_function", ",", "xunit", ",", "exp_str", ",", "qubit_label", ")", ":", "if", "not", "HAS_MATPLOTLIB", ":", "raise", "ImportError", "(", "'The function plot_coherence nee...
33.612903
20.903226
def retrieve_data(self): """ retrieve data from an HTTP URL """ # shortcuts for readability url = self.config.get('url') timeout = float(self.config.get('timeout', 10)) # perform HTTP request and store content self.data = requests.get(url, verify=self.verify_ssl, timeout=...
[ "def", "retrieve_data", "(", "self", ")", ":", "# shortcuts for readability", "url", "=", "self", ".", "config", ".", "get", "(", "'url'", ")", "timeout", "=", "float", "(", "self", ".", "config", ".", "get", "(", "'timeout'", ",", "10", ")", ")", "# p...
47.142857
13.428571
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ pkg_resources.py31compat.makedirs(replacement, exist_ok=True) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir = saved
[ "def", "override_temp", "(", "replacement", ")", ":", "pkg_resources", ".", "py31compat", ".", "makedirs", "(", "replacement", ",", "exist_ok", "=", "True", ")", "saved", "=", "tempfile", ".", "tempdir", "tempfile", ".", "tempdir", "=", "replacement", "try", ...
21.928571
21.214286
def _filter_row_ranges(self): """ Helper for :meth:`build_updated_request`""" new_row_ranges = [] for row_range in self.message.rows.row_ranges: # if current end_key (open or closed) is set, return its value, # if not, set to empty string (''). # NOTE: Empty ...
[ "def", "_filter_row_ranges", "(", "self", ")", ":", "new_row_ranges", "=", "[", "]", "for", "row_range", "in", "self", ".", "message", ".", "rows", ".", "row_ranges", ":", "# if current end_key (open or closed) is set, return its value,", "# if not, set to empty string ('...
44.7
21
def get(self, action, params=None, headers=None): """Makes a GET request """ return self.request(make_url(self.endpoint, action), method='GET', data=params, headers=headers)
[ "def", "get", "(", "self", ",", "action", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "request", "(", "make_url", "(", "self", ".", "endpoint", ",", "action", ")", ",", "method", "=", "'GET'", ",", "dat...
44.2
12
def get_instance(self, payload): """ Build an instance of KeyInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.key.KeyInstance :rtype: twilio.rest.api.v2010.account.key.KeyInstance """ return KeyInstance(self._ve...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "KeyInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
37.1
20.5
def _calc_hypothesis_probability(hypothesis): """ Get the probability (or rather a score) of a hypothesis. Parameters ---------- hypothesis : dict with keys 'segmentation', 'symbols', ... Returns ------- float in [0.0, 1.0] """ prob = 0.0 for symbol, seg in ...
[ "def", "_calc_hypothesis_probability", "(", "hypothesis", ")", ":", "prob", "=", "0.0", "for", "symbol", ",", "seg", "in", "zip", "(", "hypothesis", "[", "'symbols'", "]", ",", "hypothesis", "[", "'segmentation'", "]", ")", ":", "# symbol_latex = symbol['symbol'...
34.464286
20.035714
def construct_txt_file(self): """Construct the header of the txt file""" textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftim...
[ "def", "construct_txt_file", "(", "self", ")", ":", "textlines", "=", "[", "'Prediction of noncovalent interactions for PDB structure %s'", "%", "self", ".", "mol", ".", "pymol_name", ".", "upper", "(", ")", ",", "]", "textlines", ".", "append", "(", "\"=\"", "*...
70.384615
36.076923
def get_video_image_storage(): """ Return the configured django storage backend. """ if hasattr(settings, 'VIDEO_IMAGE_SETTINGS'): return get_storage_class( settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_CLASS'), )(**settings.VIDEO_IMAGE_SETTINGS.get('STORAGE_KWARGS', {})) el...
[ "def", "get_video_image_storage", "(", ")", ":", "if", "hasattr", "(", "settings", ",", "'VIDEO_IMAGE_SETTINGS'", ")", ":", "return", "get_storage_class", "(", "settings", ".", "VIDEO_IMAGE_SETTINGS", ".", "get", "(", "'STORAGE_CLASS'", ")", ",", ")", "(", "*", ...
44.416667
18.583333
def _run_aws(cmd, region, opts, user, **kwargs): ''' Runs the given command against AWS. cmd Command to run region Region to execute cmd in opts Pass in from salt user Pass in from salt kwargs Key-value arguments to pass to the command ''' # Th...
[ "def", "_run_aws", "(", "cmd", ",", "region", ",", "opts", ",", "user", ",", "*", "*", "kwargs", ")", ":", "# These args need a specific key value that aren't", "# valid python parameter keys", "receipthandle", "=", "kwargs", ".", "pop", "(", "'receipthandle'", ",",...
27.657143
20.4
def link_to(self, model, idx, self_idx): """ Register (self.name, self.idx) in `model._from` Returns ------- """ if model in self.system.loaded_groups: # access group instance grp = self.system.__dict__[model] # doing it one by one ...
[ "def", "link_to", "(", "self", ",", "model", ",", "idx", ",", "self_idx", ")", ":", "if", "model", "in", "self", ".", "system", ".", "loaded_groups", ":", "# access group instance", "grp", "=", "self", ".", "system", ".", "__dict__", "[", "model", "]", ...
30.513514
17.540541
def analyse_hydrogen_bonds_topology(self,distance=3): """ MDAnalysis.analysis.hbonds module is used to analyse hydrogen bonds formed between protein and ligand for each submitted trajectory. The hydrogen bonds are then counted by total value per frame (count_by_time), as well as obtainin...
[ "def", "analyse_hydrogen_bonds_topology", "(", "self", ",", "distance", "=", "3", ")", ":", "h", "=", "MDAnalysis", ".", "analysis", ".", "hbonds", ".", "HydrogenBondAnalysis", "(", "self", ".", "topology_data", ".", "universe", ",", "'(segid '", "+", "str", ...
63.3
40.2
def get_interface_detail_input_request_type_get_request_interface_name(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_interface_detail = ET.Element("get_interface_detail") config = get_interface_detail input = ET.SubElement(get_interface_det...
[ "def", "get_interface_detail_input_request_type_get_request_interface_name", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_interface_detail", "=", "ET", ".", "Element", "(", "\"get_interface_detail\""...
47.5
18.142857
def objective(self, params): """Compute the negative penalized log-likelihood.""" val = self._penalty * np.sum(params**2) for win, los in self._data: val += np.logaddexp(0, -(params[win] - params[los])) return val
[ "def", "objective", "(", "self", ",", "params", ")", ":", "val", "=", "self", ".", "_penalty", "*", "np", ".", "sum", "(", "params", "**", "2", ")", "for", "win", ",", "los", "in", "self", ".", "_data", ":", "val", "+=", "np", ".", "logaddexp", ...
42
11.666667
def pool(self, host, port, db, pools={}, **options): ''' Fetch a redis conenction pool for the unique combination of host and port. Will create a new one if there isn't one already. ''' key = (host, port, db) rval = pools.get(key) if not isinstance(rval, Connectio...
[ "def", "pool", "(", "self", ",", "host", ",", "port", ",", "db", ",", "pools", "=", "{", "}", ",", "*", "*", "options", ")", ":", "key", "=", "(", "host", ",", "port", ",", "db", ")", "rval", "=", "pools", ".", "get", "(", "key", ")", "if",...
36.75
21.916667
async def send_script(self, conn_id, data): """Send a a script to a device. See :meth:`AbstractDeviceAdapter.send_script`. """ progress_callback = functools.partial(_on_progress, self, 'script', conn_id) resp = await self._execute(self._adapter.send_script_sync, conn_id, data,...
[ "async", "def", "send_script", "(", "self", ",", "conn_id", ",", "data", ")", ":", "progress_callback", "=", "functools", ".", "partial", "(", "_on_progress", ",", "self", ",", "'script'", ",", "conn_id", ")", "resp", "=", "await", "self", ".", "_execute",...
37.8
24.8
def get_changed_devices(self, timestamp): """Get data since last timestamp. This is done via a blocking call, pass NONE for initial state. """ if timestamp is None: payload = {} else: payload = { 'timeout': SUBSCRIPTION_WAIT, ...
[ "def", "get_changed_devices", "(", "self", ",", "timestamp", ")", ":", "if", "timestamp", "is", "None", ":", "payload", "=", "{", "}", "else", ":", "payload", "=", "{", "'timeout'", ":", "SUBSCRIPTION_WAIT", ",", "'minimumdelay'", ":", "SUBSCRIPTION_MIN_WAIT",...
39.857143
21.938776
def register_plugin(self): """Register plugin in Spyder's main window.""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) self.ipyconsole = self.main.ipyconsole self.create_new_client(give_focus=False) icon_path = os.path.jo...
[ "def", "register_plugin", "(", "self", ")", ":", "self", ".", "focus_changed", ".", "connect", "(", "self", ".", "main", ".", "plugin_focus_changed", ")", "self", ".", "main", ".", "add_dockwidget", "(", "self", ")", "self", ".", "ipyconsole", "=", "self",...
56.1
17.4
def get_bandstructure_by_material_id(self, material_id, line_mode=True): """ Get a BandStructure corresponding to a material_id. REST Endpoint: https://www.materialsproject.org/rest/v2/materials/<mp-id>/vasp/bandstructure or https://www.materialsproject.org/rest/v2/materials/<mp-id>/vas...
[ "def", "get_bandstructure_by_material_id", "(", "self", ",", "material_id", ",", "line_mode", "=", "True", ")", ":", "prop", "=", "\"bandstructure\"", "if", "line_mode", "else", "\"bandstructure_uniform\"", "data", "=", "self", ".", "get_data", "(", "material_id", ...
42.888889
27
def perform_oauth(email, master_token, android_id, service, app, client_sig, device_country='us', operatorCountry='us', lang='en', sdk_version=17): """ Use a master token from master_login to perform OAuth to a specific Google service. Return a dict, eg:: { ...
[ "def", "perform_oauth", "(", "email", ",", "master_token", ",", "android_id", ",", "service", ",", "app", ",", "client_sig", ",", "device_country", "=", "'us'", ",", "operatorCountry", "=", "'us'", ",", "lang", "=", "'en'", ",", "sdk_version", "=", "17", "...
28.342105
17.973684
def modified(self): """Union[datetime.datetime, None]: Datetime at which the dataset was last modified (:data:`None` until set from the server). """ modified_time = self._properties.get("lastModifiedTime") if modified_time is not None: # modified_time will be in milli...
[ "def", "modified", "(", "self", ")", ":", "modified_time", "=", "self", ".", "_properties", ".", "get", "(", "\"lastModifiedTime\"", ")", "if", "modified_time", "is", "not", "None", ":", "# modified_time will be in milliseconds.", "return", "google", ".", "cloud",...
44.9
14.4
def save(self, filepath): """ Saves the classifier to `filepath`. Because this classifier needs to save the dataset, it must be something that can be pickled and not something like an iterator. """ if not filepath or not isinstance(filepath, str): rai...
[ "def", "save", "(", "self", ",", "filepath", ")", ":", "if", "not", "filepath", "or", "not", "isinstance", "(", "filepath", ",", "str", ")", ":", "raise", "ValueError", "(", "\"Invalid filepath\"", ")", "with", "open", "(", "filepath", ",", "\"wb\"", ")"...
33.461538
16.076923
def tf_solve(self, fn_x, x_init, base_value, target_value, estimated_improvement=None): """ Iteratively optimizes $f(x)$ for $x$ on the line between $x'$ and $x_0$. Args: fn_x: A callable returning the value $f(x)$ at $x$. x_init: Initial solution guess $x_0$. ...
[ "def", "tf_solve", "(", "self", ",", "fn_x", ",", "x_init", ",", "base_value", ",", "target_value", ",", "estimated_improvement", "=", "None", ")", ":", "return", "super", "(", "LineSearch", ",", "self", ")", ".", "tf_solve", "(", "fn_x", ",", "x_init", ...
46.466667
27.8
def showInvLines(rh): """ Produce help output related to command synopsis Input: Request Handle """ if rh.subfunction != '': rh.printLn("N", "Usage:") rh.printLn("N", " python " + rh.cmdName + " GetHost " + "diskpoolnames") rh.printLn("N", " python " + rh.cmdName +...
[ "def", "showInvLines", "(", "rh", ")", ":", "if", "rh", ".", "subfunction", "!=", "''", ":", "rh", ".", "printLn", "(", "\"N\"", ",", "\"Usage:\"", ")", "rh", ".", "printLn", "(", "\"N\"", ",", "\" python \"", "+", "rh", ".", "cmdName", "+", "\" Get...
33.210526
19.631579
def dependency_sort(dependency_tree): """ Sorts items 'dependencies first' in a given dependency tree. A dependency tree is a dictionary mapping an object to a collection its dependency objects. Result is a properly sorted list of items, where each item is a 2-tuple containing an object and it...
[ "def", "dependency_sort", "(", "dependency_tree", ")", ":", "sorted", "=", "[", "]", "processed", "=", "set", "(", ")", "for", "key", ",", "deps", "in", "dependency_tree", ".", "iteritems", "(", ")", ":", "_sort_r", "(", "sorted", ",", "processed", ",", ...
35.516129
25.967742
def deregister(self, key): """ Deregisters an existing key. `key` String key to deregister. Returns boolean. """ if not key in self._actions: return False del self._actions[key] if key in self._cache: del se...
[ "def", "deregister", "(", "self", ",", "key", ")", ":", "if", "not", "key", "in", "self", ".", "_actions", ":", "return", "False", "del", "self", ".", "_actions", "[", "key", "]", "if", "key", "in", "self", ".", "_cache", ":", "del", "self", ".", ...
18.777778
19.944444
async def allPurgeRequests(self, *args, **kwargs): """ All Open Purge Requests This is useful mostly for administors to view the set of open purge requests. It should not be used by workers. They should use the purgeRequests endpoint that is specific to their workerType ...
[ "async", "def", "allPurgeRequests", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "await", "self", ".", "_makeApiCall", "(", "self", ".", "funcinfo", "[", "\"allPurgeRequests\"", "]", ",", "*", "args", ",", "*", "*", "kwar...
34.1875
22.0625
def _return_base_data(self, url, container, container_object=None, container_headers=None, object_headers=None): """Return headers and a parsed url. :param url: :param container: :param container_object: :param container_headers: :return: ``tupl...
[ "def", "_return_base_data", "(", "self", ",", "url", ",", "container", ",", "container_object", "=", "None", ",", "container_headers", "=", "None", ",", "object_headers", "=", "None", ")", ":", "headers", "=", "self", ".", "job_args", "[", "'base_headers'", ...
30.375
19.625
def modify_conf(cfgfile, service_name, outfn): """Modify config file neutron and keystone to include enabler options.""" if not cfgfile or not outfn: print('ERROR: There is no config file.') sys.exit(0) options = service_options[service_name] with open(cfgfile, 'r') as cf: line...
[ "def", "modify_conf", "(", "cfgfile", ",", "service_name", ",", "outfn", ")", ":", "if", "not", "cfgfile", "or", "not", "outfn", ":", "print", "(", "'ERROR: There is no config file.'", ")", "sys", ".", "exit", "(", "0", ")", "options", "=", "service_options"...
37.692308
17.442308
def off_policy_train_batch(self, batch_info: BatchInfo): """ Perform an 'off-policy' training step of sampling the replay buffer and gradient descent """ self.model.train() rollout = self.env_roller.sample(batch_info, self.model, self.settings.number_of_steps).to_device(self.device) ba...
[ "def", "off_policy_train_batch", "(", "self", ",", "batch_info", ":", "BatchInfo", ")", ":", "self", ".", "model", ".", "train", "(", ")", "rollout", "=", "self", ".", "env_roller", ".", "sample", "(", "batch_info", ",", "self", ".", "model", ",", "self"...
38.5
23.071429
def fetch_images(self, images, depth_level): """\ download the images to temp disk and set their dimensions - we're going to score the images in the order in which they appear so images higher up will have more importance, - we'll count the area of the 1st image as a score ...
[ "def", "fetch_images", "(", "self", ",", "images", ",", "depth_level", ")", ":", "image_results", "=", "{", "}", "initial_area", "=", "float", "(", "0.0", ")", "total_score", "=", "float", "(", "0.0", ")", "cnt", "=", "float", "(", "1.0", ")", "MIN_WID...
46.23913
17.478261
def lockFile(self, fileName, byteOffset, length, dokanFileInfo): """Lock a file. :param fileName: name of file to lock :type fileName: ctypes.c_wchar_p :param byteOffset: location to start lock :type byteOffset: ctypes.c_longlong :param length: number of bytes to lock ...
[ "def", "lockFile", "(", "self", ",", "fileName", ",", "byteOffset", ",", "length", ",", "dokanFileInfo", ")", ":", "return", "self", ".", "operations", "(", "'lockFile'", ",", "fileName", ",", "byteOffset", ",", "length", ")" ]
35.9375
12.0625
def remove_edge_from_heap(self, segment_ids): """Remove an edge from the heap.""" self._initialize_heap() key = normalize_edge(segment_ids) if key in self.edge_map: self.edge_map[key][0] = None self.num_valid_edges -= 1
[ "def", "remove_edge_from_heap", "(", "self", ",", "segment_ids", ")", ":", "self", ".", "_initialize_heap", "(", ")", "key", "=", "normalize_edge", "(", "segment_ids", ")", "if", "key", "in", "self", ".", "edge_map", ":", "self", ".", "edge_map", "[", "key...
38.428571
3.714286
def QA_fetch_get_hkfund_list(ip=None, port=None): """[summary] Keyword Arguments: ip {[type]} -- [description] (default: {None}) port {[type]} -- [description] (default: {None}) # 港股 HKMARKET 27 5 香港指数 FH 31 2 香港主板 KH 48 ...
[ "def", "QA_fetch_get_hkfund_list", "(", "ip", "=", "None", ",", "port", "=", "None", ")", ":", "global", "extension_market_list", "extension_market_list", "=", "QA_fetch_get_extensionmarket_list", "(", ")", "if", "extension_market_list", "is", "None", "else", "extensi...
30.333333
16.761905
def default_versions(self, default_versions): ''' Set archive default read versions Parameters ---------- default_versions: dict Dictionary of archive_name, version pairs. On read/download, archives in this dictionary will download the specified version ...
[ "def", "default_versions", "(", "self", ",", "default_versions", ")", ":", "default_versions", "=", "{", "self", ".", "_normalize_archive_name", "(", "arch", ")", "[", "1", "]", ":", "v", "for", "arch", ",", "v", "in", "default_versions", ".", "items", "("...
33.166667
22.166667
def set_sampling_strategy(self, sensor_name, strategy_and_params): """Set sampling strategy for the sensors of all the group's clients. Only sensors that match the specified filter are considered. See the `KATCPResource.set_sampling_strategies` docstring for parameter definitions and mo...
[ "def", "set_sampling_strategy", "(", "self", ",", "sensor_name", ",", "strategy_and_params", ")", ":", "futures_dict", "=", "{", "}", "for", "res_obj", "in", "self", ".", "clients", ":", "futures_dict", "[", "res_obj", ".", "name", "]", "=", "res_obj", ".", ...
45.7
20.85
def get_new_tag(self, api_tag): """ Instantiate a new Tag from api data. :param api_tag: the api data for the Tag :return: the new Tag """ return Tag(site_id=self.site_id, wp_id=api_tag["ID"], **self.api_object_data("tag", api_tag))
[ "def", "get_new_tag", "(", "self", ",", "api_tag", ")", ":", "return", "Tag", "(", "site_id", "=", "self", ".", "site_id", ",", "wp_id", "=", "api_tag", "[", "\"ID\"", "]", ",", "*", "*", "self", ".", "api_object_data", "(", "\"tag\"", ",", "api_tag", ...
31
9.2
def calculate_leaf_paths(self): """Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves. """ reverse_xref = {} leaves = set() for v in self.value.values(): if v.leaf: leaves.add(v) for xref in v.value_xref:...
[ "def", "calculate_leaf_paths", "(", "self", ")", ":", "reverse_xref", "=", "{", "}", "leaves", "=", "set", "(", ")", "for", "v", "in", "self", ".", "value", ".", "values", "(", ")", ":", "if", "v", ".", "leaf", ":", "leaves", ".", "add", "(", "v"...
38.333333
10.916667
def workflow_states_column(self, obj): """ Return text description of workflow states assigned to object """ workflow_states = models.WorkflowState.objects.filter( content_type=self._get_obj_ct(obj), object_id=obj.pk, ) return ', '.join([unicode(wfs) for wfs in wo...
[ "def", "workflow_states_column", "(", "self", ",", "obj", ")", ":", "workflow_states", "=", "models", ".", "WorkflowState", ".", "objects", ".", "filter", "(", "content_type", "=", "self", ".", "_get_obj_ct", "(", "obj", ")", ",", "object_id", "=", "obj", ...
47
14.285714