text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def __add_variables(self, *args, **kwargs): """ Adds given variables to __variables attribute. :param \*args: Variables. :type \*args: \* :param \*\*kwargs: Variables : Values. :type \*\*kwargs: \* """ for variable in args: self.__variables[v...
[ "def", "__add_variables", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "variable", "in", "args", ":", "self", ".", "__variables", "[", "variable", "]", "=", "None", "self", ".", "__variables", ".", "update", "(", "kwargs", ...
27.923077
11.923077
def raw_cmd(self, *args): '''adb command. return the subprocess.Popen object.''' cmd_line = [self.adb()] + self.adb_host_port_options + list(args) if os.name != "nt": cmd_line = [" ".join(cmd_line)] return subprocess.Popen(cmd_line, shell=True, stdout=subprocess.PIPE, stderr=...
[ "def", "raw_cmd", "(", "self", ",", "*", "args", ")", ":", "cmd_line", "=", "[", "self", ".", "adb", "(", ")", "]", "+", "self", ".", "adb_host_port_options", "+", "list", "(", "args", ")", "if", "os", ".", "name", "!=", "\"nt\"", ":", "cmd_line", ...
55.166667
24.5
def shh_newFilter(self, to=None, *, topics): """https://github.com/ethereum/wiki/wiki/JSON-RPC#shh_newfilter DEPRECATED """ obj = { 'to': to, 'topics': topics, } warnings.warn('deprecated', DeprecationWarning) return (yield from self.rpc_c...
[ "def", "shh_newFilter", "(", "self", ",", "to", "=", "None", ",", "*", ",", "topics", ")", ":", "obj", "=", "{", "'to'", ":", "to", ",", "'topics'", ":", "topics", ",", "}", "warnings", ".", "warn", "(", "'deprecated'", ",", "DeprecationWarning", ")"...
30.727273
17.454545
def connect(self, access_key_id=None, secret_access_key=None, **kwargs): """ Opens a connection to appropriate provider, depending on provider portion of URI. Requires Credentials defined in boto config file (see boto/pyami/config.py). @type storage_uri: StorageUri @param...
[ "def", "connect", "(", "self", ",", "access_key_id", "=", "None", ",", "secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "connection_args", "=", "dict", "(", "self", ".", "connection_args", "or", "(", ")", ")", "# Use OrdinaryCallingFormat...
55.333333
19.208333
def decode_params_utf8(params): """Ensures that all parameters in a list of 2-element tuples are decoded to unicode using UTF-8. """ decoded = [] for k, v in params: decoded.append(( k.decode('utf-8') if isinstance(k, bytes) else k, v.decode('utf-8') if isinstance(v, ...
[ "def", "decode_params_utf8", "(", "params", ")", ":", "decoded", "=", "[", "]", "for", "k", ",", "v", "in", "params", ":", "decoded", ".", "append", "(", "(", "k", ".", "decode", "(", "'utf-8'", ")", "if", "isinstance", "(", "k", ",", "bytes", ")",...
34.5
14.7
def check_docker_command_works(): """ Verify that dockerd and docker binary works fine. This is performed by calling `docker version`, which also checks server API version. :return: bool, True if all is good, otherwise ConuException or CommandDoesNotExistException is thrown """ tr...
[ "def", "check_docker_command_works", "(", ")", ":", "try", ":", "out", "=", "subprocess", ".", "check_output", "(", "[", "\"docker\"", ",", "\"version\"", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "universal_newlines", "=", "True", ")", "exc...
41.821429
21.821429
def version(): ''' Return imgadm version CLI Example: .. code-block:: bash salt '*' imgadm.version ''' ret = {} cmd = 'imgadm --version' res = __salt__['cmd.run'](cmd).splitlines() ret = res[0].split() return ret[-1]
[ "def", "version", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'imgadm --version'", "res", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "ret", "=", "res", "[", "0", "]", ".", "split", "(", ")", "retur...
16.866667
24.066667
def instantiate_labels(instructions): """ Takes an iterable of instructions which may contain label placeholders and assigns them all defined values. :return: list of instructions with all label placeholders assigned to real labels. """ label_i = 1 result = [] label_mapping = dict() ...
[ "def", "instantiate_labels", "(", "instructions", ")", ":", "label_i", "=", "1", "result", "=", "[", "]", "label_mapping", "=", "dict", "(", ")", "for", "instr", "in", "instructions", ":", "if", "isinstance", "(", "instr", ",", "Jump", ")", "and", "isins...
46.64
27.44
def _setup_kafka(self): """ Sets up kafka connections """ # close older connections if self.consumer is not None: self.logger.debug("Closing existing kafka consumer") self.consumer.close() self.consumer = None if self.producer is not No...
[ "def", "_setup_kafka", "(", "self", ")", ":", "# close older connections", "if", "self", ".", "consumer", "is", "not", "None", ":", "self", ".", "logger", ".", "debug", "(", "\"Closing existing kafka consumer\"", ")", "self", ".", "consumer", ".", "close", "("...
35.931034
11.655172
def restore_original_method(self): """Replaces the proxy method on the target object with its original value.""" if self._target.is_class_or_module(): setattr(self._target.obj, self._method_name, self._original_method) if self._method_name == '__new__' and sys.version_info >= (3...
[ "def", "restore_original_method", "(", "self", ")", ":", "if", "self", ".", "_target", ".", "is_class_or_module", "(", ")", ":", "setattr", "(", "self", ".", "_target", ".", "obj", ",", "self", ".", "_method_name", ",", "self", ".", "_original_method", ")"...
55.3
26.65
def getRvaFromOffset(self, offset): """ Converts a RVA to an offset. @type offset: int @param offset: The offset value to be converted to RVA. @rtype: int @return: The RVA obtained from the given offset. """ rva = -1 s = self.getS...
[ "def", "getRvaFromOffset", "(", "self", ",", "offset", ")", ":", "rva", "=", "-", "1", "s", "=", "self", ".", "getSectionByOffset", "(", "offset", ")", "if", "s", ":", "rva", "=", "(", "offset", "-", "self", ".", "sectionHeaders", "[", "s", "]", "....
29.529412
21.411765
def timeit_compare(stmt_list, setup='', iterations=100000, verbose=True, strict=False, assertsame=True): """ Compares several statments by timing them and also checks that they have the same return value Args: stmt_list (list) : list of statments to compare setup (str...
[ "def", "timeit_compare", "(", "stmt_list", ",", "setup", "=", "''", ",", "iterations", "=", "100000", ",", "verbose", "=", "True", ",", "strict", "=", "False", ",", "assertsame", "=", "True", ")", ":", "import", "timeit", "import", "utool", "as", "ut", ...
37.2
17.4
def _time_delta_from_info(info): """Format the elapsed time for the given TensorBoardInfo. Args: info: A TensorBoardInfo value. Returns: A human-readable string describing the time since the server described by `info` started: e.g., "2 days, 0:48:58". """ delta_seconds = int(time.time()) - info....
[ "def", "_time_delta_from_info", "(", "info", ")", ":", "delta_seconds", "=", "int", "(", "time", ".", "time", "(", ")", ")", "-", "info", ".", "start_time", "return", "str", "(", "datetime", ".", "timedelta", "(", "seconds", "=", "delta_seconds", ")", ")...
31.25
18.75
def decode_embedded_strs(src): ''' Convert enbedded bytes to strings if possible. This is necessary because Python 3 makes a distinction between these types. This wouldn't be needed if we used "use_bin_type=True" when encoding and "encoding='utf-8'" when decoding. Unfortunately, this would brea...
[ "def", "decode_embedded_strs", "(", "src", ")", ":", "if", "not", "six", ".", "PY3", ":", "return", "src", "if", "isinstance", "(", "src", ",", "dict", ")", ":", "return", "_decode_embedded_dict", "(", "src", ")", "elif", "isinstance", "(", "src", ",", ...
32.36
20.68
def align_chunk_with_ner(tmp_ner_path, i_chunk, tmp_done_path): ''' iterate through the i_chunk and tmp_ner_path to generate a new Chunk with body.ner ''' o_chunk = Chunk() input_iter = i_chunk.__iter__() ner = '' stream_id = None all_ner = xml.dom.minidom.parse(open(tmp_ner_path)) ...
[ "def", "align_chunk_with_ner", "(", "tmp_ner_path", ",", "i_chunk", ",", "tmp_done_path", ")", ":", "o_chunk", "=", "Chunk", "(", ")", "input_iter", "=", "i_chunk", ".", "__iter__", "(", ")", "ner", "=", "''", "stream_id", "=", "None", "all_ner", "=", "xml...
36.776119
18.656716
def add_review_date(self, doc, reviewed): """Sets the review date. Raises CardinalityError if already set. OrderError if no reviewer defined before. Raises SPDXValueError if invalid reviewed value. """ if len(doc.reviews) != 0: if not self.review_date_set: ...
[ "def", "add_review_date", "(", "self", ",", "doc", ",", "reviewed", ")", ":", "if", "len", "(", "doc", ".", "reviews", ")", "!=", "0", ":", "if", "not", "self", ".", "review_date_set", ":", "self", ".", "review_date_set", "=", "True", "date", "=", "u...
41.777778
12.222222
def modify_service(self, service_id, type): ''' modify_service(self, service_id, type) | Modifies a service type (action, container, etc.) :Parameters: * *service_id* (`string`) -- Identifier of an existing service * *type* (`string`) -- service type :return: S...
[ "def", "modify_service", "(", "self", ",", "service_id", ",", "type", ")", ":", "request_data", "=", "{", "'id'", ":", "service_id", ",", "'type'", ":", "type", "}", "return", "self", ".", "_call_rest_api", "(", "'post'", ",", "'/services'", ",", "data", ...
39.272727
31.181818
def getIRData(self): ''' Returns last LaserData. @return last JdeRobotTypes LaserData saved ''' if self.hasproxy(): self.lock.acquire() ir = self.ir self.lock.release() return ir return None
[ "def", "getIRData", "(", "self", ")", ":", "if", "self", ".", "hasproxy", "(", ")", ":", "self", ".", "lock", ".", "acquire", "(", ")", "ir", "=", "self", ".", "ir", "self", ".", "lock", ".", "release", "(", ")", "return", "ir", "return", "None" ...
20.142857
21.285714
def list_(return_yaml=True, include_pillar=True, include_opts=True, **kwargs): ''' List the beacons currently configured on the minion. Args: return_yaml (bool): Whether to return YAML formatted output, default ``True``. include_pillar (bool): ...
[ "def", "list_", "(", "return_yaml", "=", "True", ",", "include_pillar", "=", "True", ",", "include_opts", "=", "True", ",", "*", "*", "kwargs", ")", ":", "beacons", "=", "None", "try", ":", "eventer", "=", "salt", ".", "utils", ".", "event", ".", "ge...
29.85
23.883333
def _fix_sitk_bug(self, path, metadata): """ There is a bug in simple ITK for Z axis in 3D images. This is a fix :param path: :param metadata: :return: """ ds = dicom.read_file(path) ds.SpacingBetweenSlices = str(metadata["voxelsize_mm"][0])[:16] d...
[ "def", "_fix_sitk_bug", "(", "self", ",", "path", ",", "metadata", ")", ":", "ds", "=", "dicom", ".", "read_file", "(", "path", ")", "ds", ".", "SpacingBetweenSlices", "=", "str", "(", "metadata", "[", "\"voxelsize_mm\"", "]", "[", "0", "]", ")", "[", ...
33.6
13.8
def dobingham(di_block): """ Calculates the Bingham mean and associated statistical parameters from directions that are input as a di_block Parameters ---------- di_block : a nested list of [dec,inc] or [dec,inc,intensity] Returns ------- bpars : dictionary containing the Bingham m...
[ "def", "dobingham", "(", "di_block", ")", ":", "control", ",", "X", ",", "bpars", "=", "[", "]", ",", "[", "]", ",", "{", "}", "N", "=", "len", "(", "di_block", ")", "if", "N", "<", "2", ":", "return", "bpars", "#", "# get cartesian coordinates", ...
26.774194
19.193548
def push(self, line, frame, buffer_output=True): """Change built-in stdout and stderr methods by the new custom StdMessage. execute the InteractiveConsole.push. Change the stdout and stderr back be the original built-ins :param buffer_output: if False won't redirect the output. ...
[ "def", "push", "(", "self", ",", "line", ",", "frame", ",", "buffer_output", "=", "True", ")", ":", "self", ".", "__buffer_output", "=", "buffer_output", "more", "=", "False", "if", "buffer_output", ":", "original_stdout", "=", "sys", ".", "stdout", "origi...
35.219512
14.146341
def get_metadata_desc(self): """ See super class satosa.backends.backend_base.BackendModule#get_metadata_desc :rtype: satosa.metadata_creation.description.MetadataDescription """ entity_descriptions = [] idp_entities = self.sp.metadata.with_descriptor("idpsso") f...
[ "def", "get_metadata_desc", "(", "self", ")", ":", "entity_descriptions", "=", "[", "]", "idp_entities", "=", "self", ".", "sp", ".", "metadata", ".", "with_descriptor", "(", "\"idpsso\"", ")", "for", "entity_id", ",", "entity", "in", "idp_entities", ".", "i...
48.237288
25.084746
def set_export(args): '''Return a list of lines in TSV form that would suffice to reconstitute a container (set) entity, if passed to entity_import. The first line in the list is the header, and subsequent lines are the container members. ''' r = fapi.get_entity(args.project, args.workspace,...
[ "def", "set_export", "(", "args", ")", ":", "r", "=", "fapi", ".", "get_entity", "(", "args", ".", "project", ",", "args", ".", "workspace", ",", "args", ".", "entity_type", ",", "args", ".", "entity", ")", "fapi", ".", "_check_response_code", "(", "r"...
43.75
26.375
def rm_rf(path): """ Recursively (if needed) delete path. """ if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) elif os.path.lexists(path): os.remove(path)
[ "def", "rm_rf", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "elif", "os", ".", "path", ".", ...
25.875
9.875
def p_list_or(self, p): 'list : list OR list' p[0] = pd.concat( [p[1], p[3]], axis=1).fillna(0.0).apply(self.func, axis=1)
[ "def", "p_list_or", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "pd", ".", "concat", "(", "[", "p", "[", "1", "]", ",", "p", "[", "3", "]", "]", ",", "axis", "=", "1", ")", ".", "fillna", "(", "0.0", ")", ".", "apply", "("...
36.75
18.25
def do_transition_for(brain_or_object, transition): """Performs a workflow transition for the passed in object. :param brain_or_object: A single catalog brain or content object :type brain_or_object: ATContentType/DexterityContentType/CatalogBrain :returns: The object where the transtion was performed ...
[ "def", "do_transition_for", "(", "brain_or_object", ",", "transition", ")", ":", "if", "not", "isinstance", "(", "transition", ",", "basestring", ")", ":", "fail", "(", "\"Transition type needs to be string, got '%s'\"", "%", "type", "(", "transition", ")", ")", "...
44.5
18
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags): """ This method for run some function at subprocess. Very useful when you have a problem with memory leaks. """ if use_subprocess is False: return foo(*args, **kwrags) child_pid = os.fork() ...
[ "def", "run_at_subprocess", "(", "self", ",", "use_subprocess", ",", "foo", ",", "*", "args", ",", "*", "*", "kwrags", ")", ":", "if", "use_subprocess", "is", "False", ":", "return", "foo", "(", "*", "args", ",", "*", "*", "kwrags", ")", "child_pid", ...
33.615385
12.846154
def search(i): """ Input: { (repo_uoa) - repo UOA (module_uoa) - module UOA (data_uoa) - data UOA (repo_uoa_list) - list of repos to search (module_uoa_list) - list of module to search (data...
[ "def", "search", "(", "i", ")", ":", "o", "=", "i", ".", "get", "(", "'out'", ",", "''", ")", "ss", "=", "i", ".", "get", "(", "'search_string'", ",", "''", ")", "ls", "=", "i", ".", "get", "(", "'limit_size'", ",", "'5000'", ")", "rr", "=", ...
28.191729
20.349624
def get_layer(self): """ retrieve layer from DB """ if self.layer: return try: self.layer = Layer.objects.get(slug=self.kwargs['slug']) except Layer.DoesNotExist: raise Http404(_('Layer not found'))
[ "def", "get_layer", "(", "self", ")", ":", "if", "self", ".", "layer", ":", "return", "try", ":", "self", ".", "layer", "=", "Layer", ".", "objects", ".", "get", "(", "slug", "=", "self", ".", "kwargs", "[", "'slug'", "]", ")", "except", "Layer", ...
32.375
16.125
def create_or_update_secret(self, path, secret, cas=None, mount_point=DEFAULT_MOUNT_POINT): """Create a new version of a secret at the specified location. If the value does not yet exist, the calling token must have an ACL policy granting the create capability. If the value already exists, the ...
[ "def", "create_or_update_secret", "(", "self", ",", "path", ",", "secret", ",", "cas", "=", "None", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'options'", ":", "{", "}", ",", "'data'", ":", "secret", ",", "}", "if", ...
44
29.25
def importPreflibFile(self, fileName): """ Imports a preflib format file that contains all the information of a Profile. This function will completely override all members of the current Profile object. Currently, we assume that in an election where incomplete ordering are allowed, if a...
[ "def", "importPreflibFile", "(", "self", ",", "fileName", ")", ":", "# Use the functionality found in io to read the file.", "elecFileObj", "=", "open", "(", "fileName", ",", "'r'", ")", "self", ".", "candMap", ",", "rankMaps", ",", "wmgMapsCounts", ",", "self", "...
50.875
29.791667
def species_string(self): """ String representation of species on the site. """ if self.is_ordered: return list(self.species.keys())[0].__str__() else: sorted_species = sorted(self.species.keys()) return ", ".join(["{}:{:.3f}".format(sp, self.s...
[ "def", "species_string", "(", "self", ")", ":", "if", "self", ".", "is_ordered", ":", "return", "list", "(", "self", ".", "species", ".", "keys", "(", ")", ")", "[", "0", "]", ".", "__str__", "(", ")", "else", ":", "sorted_species", "=", "sorted", ...
37.9
14.7
def parse_experiment_params(name_exp): '''Parse experiment parameters from the data directory name Args ---- name_exp: str Name of data directory with experiment parameters Returns ------- tag_params: dict of str Dictionary of parsed experiment parameters ''' if ('/...
[ "def", "parse_experiment_params", "(", "name_exp", ")", ":", "if", "(", "'/'", "in", "name_exp", ")", "or", "(", "'\\\\'", "in", "name_exp", ")", ":", "raise", "ValueError", "(", "\"The path {} appears to be a path. Please pass \"", "\"only the data directory's name (i....
32.5
22.5
def clone(self): """Create a complete copy of the stream. :returns: A new MaterialStream object.""" result = copy.copy(self) result._compound_mfrs = copy.deepcopy(self._compound_mfrs) return result
[ "def", "clone", "(", "self", ")", ":", "result", "=", "copy", ".", "copy", "(", "self", ")", "result", ".", "_compound_mfrs", "=", "copy", ".", "deepcopy", "(", "self", ".", "_compound_mfrs", ")", "return", "result" ]
29
19.625
def get_last_name_first_name(self): """ :rtype: str """ last_names = [] if self._get_last_names(): last_names += self._get_last_names() first_and_additional_names = [] if self._get_first_names(): first_and_additional_names += self._get_firs...
[ "def", "get_last_name_first_name", "(", "self", ")", ":", "last_names", "=", "[", "]", "if", "self", ".", "_get_last_names", "(", ")", ":", "last_names", "+=", "self", ".", "_get_last_names", "(", ")", "first_and_additional_names", "=", "[", "]", "if", "self...
40.636364
12.727273
def new_post(blog_id, username, password, post, publish): """ metaWeblog.newPost(blog_id, username, password, post, publish) => post_id """ user = authenticate(username, password, 'zinnia.add_entry') if post.get('dateCreated'): creation_date = datetime.strptime( post['dateCre...
[ "def", "new_post", "(", "blog_id", ",", "username", ",", "password", ",", "post", ",", "publish", ")", ":", "user", "=", "authenticate", "(", "username", ",", "password", ",", "'zinnia.add_entry'", ")", "if", "post", ".", "get", "(", "'dateCreated'", ")", ...
41.395833
17.770833
def _IOC(cls, dir, op, structure=None): """ Encode an ioctl id. """ control = cls(dir, op, structure) def do(dev, **args): return control(dev, **args) return do
[ "def", "_IOC", "(", "cls", ",", "dir", ",", "op", ",", "structure", "=", "None", ")", ":", "control", "=", "cls", "(", "dir", ",", "op", ",", "structure", ")", "def", "do", "(", "dev", ",", "*", "*", "args", ")", ":", "return", "control", "(", ...
28.428571
11.142857
def nonblock_read(stream, limit=None, forceMode=None): ''' nonblock_read - Read any data available on the given stream (file, socket, etc) without blocking and regardless of newlines. @param stream <object> - A stream (like a file object or a socket) @param limit <None/int> - Max nu...
[ "def", "nonblock_read", "(", "stream", ",", "limit", "=", "None", ",", "forceMode", "=", "None", ")", ":", "bytesRead", "=", "0", "ret", "=", "[", "]", "if", "forceMode", ":", "if", "'b'", "in", "forceMode", ":", "streamMode", "=", "bytes", "elif", "...
36.839286
31.267857
def n_members(self): """ Returns the number of members in the domain if it `is_finite`, otherwise, returns `np.inf`. :type: ``int`` or ``np.inf`` """ if self.is_finite: return reduce(mul, [domain.n_members for domain in self._domains], 1) else: ...
[ "def", "n_members", "(", "self", ")", ":", "if", "self", ".", "is_finite", ":", "return", "reduce", "(", "mul", ",", "[", "domain", ".", "n_members", "for", "domain", "in", "self", ".", "_domains", "]", ",", "1", ")", "else", ":", "return", "np", "...
29.909091
17
def sample( self, n=None, frac=None, replace=False, weights=None, random_state=None, axis=None, ): """Returns a random sample of items from an axis of object. Args: n: Number of items from axis to return. Cannot be used...
[ "def", "sample", "(", "self", ",", "n", "=", "None", ",", "frac", "=", "None", ",", "replace", "=", "False", ",", "weights", "=", "None", ",", "random_state", "=", "None", ",", "axis", "=", "None", ",", ")", ":", "axis", "=", "self", ".", "_get_a...
46.391608
21.048951
def make_config(self, instance_relative=False): """Used to create the config attribute by the Flask constructor. The `instance_relative` parameter is passed in from the constructor of Flask (there named `instance_relative_config`) and indicates if the config should be relative to the ins...
[ "def", "make_config", "(", "self", ",", "instance_relative", "=", "False", ")", ":", "root_path", "=", "self", ".", "root_path", "if", "instance_relative", ":", "root_path", "=", "self", ".", "instance_path", "return", "Config", "(", "root_path", ",", "self", ...
43.692308
15.923077
def parse_mark_duplicate_metrics(fn): """ Parse the output from Picard's MarkDuplicates and return as pandas Series. Parameters ---------- filename : str of filename or file handle Filename of the Picard output you want to parse. Returns ------- metrics : pandas.Series ...
[ "def", "parse_mark_duplicate_metrics", "(", "fn", ")", ":", "with", "open", "(", "fn", ")", "as", "f", ":", "lines", "=", "[", "x", ".", "strip", "(", ")", ".", "split", "(", "'\\t'", ")", "for", "x", "in", "f", ".", "readlines", "(", ")", "]", ...
26.137931
19.862069
def transformToNative(obj): """ Convert comma separated periods into tuples. """ if obj.isNative: return obj obj.isNative = True if obj.value == '': obj.value = [] return obj tzinfo = getTzid(getattr(obj, 'tzid_param', None)) ...
[ "def", "transformToNative", "(", "obj", ")", ":", "if", "obj", ".", "isNative", ":", "return", "obj", "obj", ".", "isNative", "=", "True", "if", "obj", ".", "value", "==", "''", ":", "obj", ".", "value", "=", "[", "]", "return", "obj", "tzinfo", "=...
30.923077
14.923077
def morlet(freq, s_freq, ratio=5, sigma_f=None, dur_in_sd=4, dur_in_s=None, normalization='peak', zero_mean=False): """Create a Morlet wavelet. Parameters ---------- freq : float central frequency of the wavelet s_freq : int sampling frequency ratio : float ra...
[ "def", "morlet", "(", "freq", ",", "s_freq", ",", "ratio", "=", "5", ",", "sigma_f", "=", "None", ",", "dur_in_sd", "=", "4", ",", "dur_in_s", "=", "None", ",", "normalization", "=", "'peak'", ",", "zero_mean", "=", "False", ")", ":", "if", "sigma_f"...
35.564103
23.820513
def delete_genelist(list_id, case_id=None): """Delete a whole gene list with links to cases or a link.""" if case_id: # unlink a case from a gene list case_obj = app.db.case(case_id) app.db.remove_genelist(list_id, case_obj=case_obj) return redirect(request.referrer) else: ...
[ "def", "delete_genelist", "(", "list_id", ",", "case_id", "=", "None", ")", ":", "if", "case_id", ":", "# unlink a case from a gene list", "case_obj", "=", "app", ".", "db", ".", "case", "(", "case_id", ")", "app", ".", "db", ".", "remove_genelist", "(", "...
38.818182
7.818182
def get_all_items_of_confirmation(self, confirmation_id): """ Get all items of confirmation This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param confirmation_id: the confirmation id ...
[ "def", "get_all_items_of_confirmation", "(", "self", ",", "confirmation_id", ")", ":", "return", "self", ".", "_iterate_through_pages", "(", "get_function", "=", "self", ".", "get_items_of_confirmation_per_page", ",", "resource", "=", "CONFIRMATION_ITEMS", ",", "*", "...
39.428571
16.857143
def draw(self): """ Renders the class balance chart on the specified axes from support. """ # Number of colors is either number of classes or 2 colors = resolve_colors(len(self.support_)) if self._mode == BALANCE: self.ax.bar( np.arange(len(se...
[ "def", "draw", "(", "self", ")", ":", "# Number of colors is either number of classes or 2", "colors", "=", "resolve_colors", "(", "len", "(", "self", ".", "support_", ")", ")", "if", "self", ".", "_mode", "==", "BALANCE", ":", "self", ".", "ax", ".", "bar",...
29.655172
19.241379
def get_subwords(self, word, on_unicode_error='strict'): """ Given a word, get the subwords and their indicies. """ pair = self.f.getSubwords(word, on_unicode_error) return pair[0], np.array(pair[1])
[ "def", "get_subwords", "(", "self", ",", "word", ",", "on_unicode_error", "=", "'strict'", ")", ":", "pair", "=", "self", ".", "f", ".", "getSubwords", "(", "word", ",", "on_unicode_error", ")", "return", "pair", "[", "0", "]", ",", "np", ".", "array",...
39
8.666667
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by...
[ "def", "folderitem", "(", "self", ",", "obj", ",", "item", ",", "index", ")", ":", "item", "=", "super", "(", "ReferenceSamplesView", ",", "self", ")", ".", "folderitem", "(", "obj", ",", "item", ",", "index", ")", "# ensure we have an object and not a brain...
35.8
21.9
def process(self, filename, encoding, **kwargs): """Process ``filename`` and encode byte-string with ``encoding``. This method is called by :func:`textract.parsers.process` and wraps the :meth:`.BaseParser.extract` method in `a delicious unicode sandwich <http://nedbatchelder.com/text/un...
[ "def", "process", "(", "self", ",", "filename", ",", "encoding", ",", "*", "*", "kwargs", ")", ":", "# make a \"unicode sandwich\" to handle dealing with unknown", "# input byte strings and converting them to a predictable", "# output encoding", "# http://nedbatchelder.com/text/uni...
51.071429
18.285714
def reconstitute_path(drive, folders): """Reverts a tuple from `get_path_components` into a path. :param drive: A drive (eg 'c:'). Only applicable for NT systems :param folders: A list of folder names :return: A path comprising the drive and list of folder names. The path terminate with a ...
[ "def", "reconstitute_path", "(", "drive", ",", "folders", ")", ":", "reconstituted", "=", "os", ".", "path", ".", "join", "(", "drive", ",", "os", ".", "path", ".", "sep", ",", "*", "folders", ")", "return", "reconstituted" ]
45.3
18
def lookup(id=None, artist_amg_id=None, upc=None, country='US', media='all', entity=None, attribute=None, limit=50): """ Returns the result of the lookup of the specified id, artist_amg_id or upc in an array of result_item(s) :param id: String. iTunes ID of the artist, album, track, ebook or software :p...
[ "def", "lookup", "(", "id", "=", "None", ",", "artist_amg_id", "=", "None", ",", "upc", "=", "None", ",", "country", "=", "'US'", ",", "media", "=", "'all'", ",", "entity", "=", "None", ",", "attribute", "=", "None", ",", "limit", "=", "50", ")", ...
53.09375
31.84375
def check_surface_validity(cls, edges): """ Check validity of the surface. Project edge points to vertical plane anchored to surface upper left edge and with strike equal to top edge strike. Check that resulting polygon is valid. This method doesn't have to be called by...
[ "def", "check_surface_validity", "(", "cls", ",", "edges", ")", ":", "# extract coordinates of surface boundary (as defined from edges)", "full_boundary", "=", "[", "]", "left_boundary", "=", "[", "]", "right_boundary", "=", "[", "]", "for", "i", "in", "range", "(",...
40.22449
19.612245
def learn(self, initial_state_key, limit=1000, game_n=1): ''' Multi-Agent Learning. Override. Args: initial_state_key: Initial state. limit: Limit of the number of learning. game_n: The number of games. ...
[ "def", "learn", "(", "self", ",", "initial_state_key", ",", "limit", "=", "1000", ",", "game_n", "=", "1", ")", ":", "end_flag_list", "=", "[", "False", "]", "*", "len", "(", "self", ".", "q_learning_list", ")", "for", "game", "in", "range", "(", "ga...
44.079365
22.269841
def render(self, name, value, attrs=None, renderer=None): """ Returns this Widget rendered as HTML, as a Unicode string. The 'value' given is not guaranteed to be valid input, so subclass implementations should program defensively. """ html = '' html += '%s' % va...
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ",", "renderer", "=", "None", ")", ":", "html", "=", "''", "html", "+=", "'%s'", "%", "value", "html", "+=", "'<input type=\"hidden\" name=\"%s\" value=\"%s\">'", "%", "(",...
39.727273
20.454545
def apply_filter(objs, selector, mode): '''Apply selector to transform each object in objs. This operates in-place on objs. Empty objects are removed from the list. Args: mode: either KEEP (to keep selected items & their ancestors) or DELETE (to delete selected items and their childr...
[ "def", "apply_filter", "(", "objs", ",", "selector", ",", "mode", ")", ":", "indices_to_delete", "=", "[", "]", "presumption", "=", "DELETE", "if", "mode", "==", "KEEP", "else", "KEEP", "for", "i", ",", "obj", "in", "enumerate", "(", "objs", ")", ":", ...
37.565217
18.869565
def from_flag(cls, flag): """ Find relation implementation in the current charm, based on the name of an active flag. You should not use this method directly. Use :func:`endpoint_from_flag` instead. """ value = _get_flag_value(flag) if value is None: ...
[ "def", "from_flag", "(", "cls", ",", "flag", ")", ":", "value", "=", "_get_flag_value", "(", "flag", ")", "if", "value", "is", "None", ":", "return", "None", "relation_name", "=", "value", "[", "'relation'", "]", "conversations", "=", "Conversation", ".", ...
35.214286
13.5
def query(self): """ Returns the full query for this widget. This will reflect the complete combined query for all containers within this widget. :return <orb.Query> """ if self._loadQuery is not None: return self._loadQuery ...
[ "def", "query", "(", "self", ")", ":", "if", "self", ".", "_loadQuery", "is", "not", "None", ":", "return", "self", ".", "_loadQuery", "container", "=", "self", ".", "widget", "(", "0", ")", "if", "container", ":", "query", "=", "container", ".", "qu...
27.882353
16.117647
def bind_socket(self, config): """ :meth:`.WNetworkNativeTransportProto.bind_socket` method implementation """ address = config[self.__bind_socket_config.section][self.__bind_socket_config.address_option] port = config.getint(self.__bind_socket_config.section, self.__bind_socket_config.port_option) return WIP...
[ "def", "bind_socket", "(", "self", ",", "config", ")", ":", "address", "=", "config", "[", "self", ".", "__bind_socket_config", ".", "section", "]", "[", "self", ".", "__bind_socket_config", ".", "address_option", "]", "port", "=", "config", ".", "getint", ...
57
20.333333
def fcsp_sa_fcsp_auth_proto_auth_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcsp_sa = ET.SubElement(config, "fcsp-sa", xmlns="urn:brocade.com:mgmt:brocade-fc-auth") fcsp = ET.SubElement(fcsp_sa, "fcsp") auth = ET.SubElement(fcsp, "auth"...
[ "def", "fcsp_sa_fcsp_auth_proto_auth_type", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "fcsp_sa", "=", "ET", ".", "SubElement", "(", "config", ",", "\"fcsp-sa\"", ",", "xmlns", "=", "\"urn:b...
42.153846
13.153846
def f(self): """ Time, in 12-hour hours and minutes, with minutes left off if they're zero. Examples: '1', '1:30', '2:05', '2' Proprietary extension. """ if self.data.minute == 0: return self.g() return u'%s:%s' % (self.g(), self.i())
[ "def", "f", "(", "self", ")", ":", "if", "self", ".", "data", ".", "minute", "==", "0", ":", "return", "self", ".", "g", "(", ")", "return", "u'%s:%s'", "%", "(", "self", ".", "g", "(", ")", ",", "self", ".", "i", "(", ")", ")" ]
30.1
12.9
def parse_options(cls, options): """Extracts subdomain and endpoint values from the options dict and returns them along with a new dict without those values. """ options = options.copy() subdomain = options.pop('subdomain', None) endpoint = options.pop('endpoint', None...
[ "def", "parse_options", "(", "cls", ",", "options", ")", ":", "options", "=", "options", ".", "copy", "(", ")", "subdomain", "=", "options", ".", "pop", "(", "'subdomain'", ",", "None", ")", "endpoint", "=", "options", ".", "pop", "(", "'endpoint'", ",...
44.875
7.125
def _add_initial_value(self, data_id, value, initial_dist=0.0, fringe=None, check_cutoff=None, no_call=None): """ Add initial values updating workflow, seen, and fringe. :param fringe: Heapq of closest available nodes. :type fringe: list[(float | i...
[ "def", "_add_initial_value", "(", "self", ",", "data_id", ",", "value", ",", "initial_dist", "=", "0.0", ",", "fringe", "=", "None", ",", "check_cutoff", "=", "None", ",", "no_call", "=", "None", ")", ":", "# Namespace shortcuts for speed.", "nodes", ",", "s...
34.307692
25.557692
def should_try_kafka_again(error): """Determine if the error means to retry or fail, True to retry.""" msg = 'Unable to retrieve' return isinstance(error, KafkaException) and str(error).startswith(msg)
[ "def", "should_try_kafka_again", "(", "error", ")", ":", "msg", "=", "'Unable to retrieve'", "return", "isinstance", "(", "error", ",", "KafkaException", ")", "and", "str", "(", "error", ")", ".", "startswith", "(", "msg", ")" ]
52.5
12.75
def update_grade(self, grade_form): """Updates an existing grade. arg: grade_form (osid.grading.GradeForm): the form containing the elements to be updated raise: IllegalState - ``grade_form`` already used in an update transaction raise: InvalidArgume...
[ "def", "update_grade", "(", "self", ",", "grade_form", ")", ":", "# Implemented from template for", "# osid.repository.AssetAdminSession.update_asset_content_template", "from", "dlkit", ".", "abstract_osid", ".", "grading", ".", "objects", "import", "GradeForm", "as", "ABCG...
48.180328
21.360656
def mtf_unitransformer_base(): """Hyperparameters for single-stack Transformer.""" hparams = mtf_transformer2_base() hparams.add_hparam("autoregressive", True) # HYPERPARAMETERS FOR THE SINGLE LAYER STACK hparams.add_hparam("layers", ["self_att", "drd"] * 6) # number of heads in multihead attention hparam...
[ "def", "mtf_unitransformer_base", "(", ")", ":", "hparams", "=", "mtf_transformer2_base", "(", ")", "hparams", ".", "add_hparam", "(", "\"autoregressive\"", ",", "True", ")", "# HYPERPARAMETERS FOR THE SINGLE LAYER STACK", "hparams", ".", "add_hparam", "(", "\"layers\""...
43.1875
8.5
def start(self): """ Start agents execute popen of agent.py on target and start output reader thread. """ [agent.start() for agent in self.agents] [agent.reader_thread.start() for agent in self.agents]
[ "def", "start", "(", "self", ")", ":", "[", "agent", ".", "start", "(", ")", "for", "agent", "in", "self", ".", "agents", "]", "[", "agent", ".", "reader_thread", ".", "start", "(", ")", "for", "agent", "in", "self", ".", "agents", "]" ]
33.714286
18.428571
def _to_dict(self): """Return a json dictionary representing this model.""" _dict = {} if hasattr(self, 'languages') and self.languages is not None: _dict['languages'] = [x._to_dict() for x in self.languages] return _dict
[ "def", "_to_dict", "(", "self", ")", ":", "_dict", "=", "{", "}", "if", "hasattr", "(", "self", ",", "'languages'", ")", "and", "self", ".", "languages", "is", "not", "None", ":", "_dict", "[", "'languages'", "]", "=", "[", "x", ".", "_to_dict", "(...
43.333333
20.5
def from_xml(cls, input_xml: str) -> 'NistBeaconValue': """ Convert a string of XML which represents a NIST Randomness Beacon value into a 'NistBeaconValue' object. :param input_xml: XML to build a 'NistBeaconValue' from :return: A 'NistBeaconValue' object, 'None' otherwise ...
[ "def", "from_xml", "(", "cls", ",", "input_xml", ":", "str", ")", "->", "'NistBeaconValue'", ":", "invalid_result", "=", "None", "understood_namespaces", "=", "{", "'nist-0.1'", ":", "'http://beacon.nist.gov/record/0.1/'", ",", "}", "# Our required values are \"must hav...
37.969231
19.723077
def get_data(latitude=52.091579, longitude=5.119734, usexml=False): """Get buienradar xml data and return results.""" if usexml: log.info("Getting buienradar XML data for latitude=%s, longitude=%s", latitude, longitude) return get_xml_data(latitude, longitude) else: ...
[ "def", "get_data", "(", "latitude", "=", "52.091579", ",", "longitude", "=", "5.119734", ",", "usexml", "=", "False", ")", ":", "if", "usexml", ":", "log", ".", "info", "(", "\"Getting buienradar XML data for latitude=%s, longitude=%s\"", ",", "latitude", ",", "...
46.9
18.2
def calculate_temperature_equivalent(temperatures): """ Calculates the temperature equivalent from a series of average daily temperatures according to the formula: 0.6 * tempDay0 + 0.3 * tempDay-1 + 0.1 * tempDay-2 Parameters ---------- series : Pandas Series Returns ------- Pandas...
[ "def", "calculate_temperature_equivalent", "(", "temperatures", ")", ":", "ret", "=", "0.6", "*", "temperatures", "+", "0.3", "*", "temperatures", ".", "shift", "(", "1", ")", "+", "0.1", "*", "temperatures", ".", "shift", "(", "2", ")", "ret", ".", "nam...
26.529412
25.823529
def _exec_nb(self, cmd, cwd=None, env=None, encoding='utf-8'): """Run a command with a non blocking call. Execute `cmd` command with a non blocking call. The command will be run in the directory set by `cwd`. Enviroment variables can be set using the `env` dictionary. The output data is...
[ "def", "_exec_nb", "(", "self", ",", "cmd", ",", "cwd", "=", "None", ",", "env", "=", "None", ",", "encoding", "=", "'utf-8'", ")", ":", "self", ".", "failed_message", "=", "None", "logger", ".", "debug", "(", "\"Running command %s (cwd: %s, env: %s)\"", "...
41.27907
20.27907
def _margtimedist_loglr(self, mf_snr, opt_snr): """Returns the log likelihood ratio marginalized over time and distance. """ logl = special.logsumexp(mf_snr, b=self._deltat) logl_marg = logl/self._dist_array opt_snr_marg = opt_snr/self._dist_array**2 return specia...
[ "def", "_margtimedist_loglr", "(", "self", ",", "mf_snr", ",", "opt_snr", ")", ":", "logl", "=", "special", ".", "logsumexp", "(", "mf_snr", ",", "b", "=", "self", ".", "_deltat", ")", "logl_marg", "=", "logl", "/", "self", ".", "_dist_array", "opt_snr_m...
46.444444
11.444444
def p_expression_unand(self, p): 'expression : NAND expression %prec UNAND' p[0] = Unand(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
[ "def", "p_expression_unand", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "Unand", "(", "p", "[", "2", "]", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")", "p", ".", "set_lineno", "(", "0", ",", "p", ".", "lineno", ...
41
7
def _generate_rsa_key(key_length): """Generate a new RSA private key. :param int key_length: Required key length in bits :returns: DER-encoded private key, private key identifier, and DER encoding identifier :rtype: tuple(bytes, :class:`EncryptionKeyType`, :class:`KeyEncodingType`) """ private_...
[ "def", "_generate_rsa_key", "(", "key_length", ")", ":", "private_key", "=", "rsa", ".", "generate_private_key", "(", "public_exponent", "=", "65537", ",", "key_size", "=", "key_length", ",", "backend", "=", "default_backend", "(", ")", ")", "key_bytes", "=", ...
48.571429
22.642857
def random(cls, engine_or_session, limit=5): """ Return random ORM instance. :type engine_or_session: Union[Engine, Session] :type limit: int :rtype: List[ExtendedBase] """ ses, auto_close = ensure_session(engine_or_session) result = ses.query(cls).order...
[ "def", "random", "(", "cls", ",", "engine_or_session", ",", "limit", "=", "5", ")", ":", "ses", ",", "auto_close", "=", "ensure_session", "(", "engine_or_session", ")", "result", "=", "ses", ".", "query", "(", "cls", ")", ".", "order_by", "(", "func", ...
30.928571
15.5
def get_gene2section2gos(gene2gos, sec2gos): """Get a list of section aliases for each gene product ID.""" gene2section2gos = {} for geneid, gos_gene in gene2gos.items(): section2gos = {} for section_name, gos_sec in sec2gos.items(): gos_secgene = gos_gene...
[ "def", "get_gene2section2gos", "(", "gene2gos", ",", "sec2gos", ")", ":", "gene2section2gos", "=", "{", "}", "for", "geneid", ",", "gos_gene", "in", "gene2gos", ".", "items", "(", ")", ":", "section2gos", "=", "{", "}", "for", "section_name", ",", "gos_sec...
46.090909
10.909091
def get_record(self, dns_type, name): """ Get a dns record :param dns_type: :param name: :return: """ try: record = [record for record in self.dns_records if record['type'] == dns_type and record['name'] == name][0] except...
[ "def", "get_record", "(", "self", ",", "dns_type", ",", "name", ")", ":", "try", ":", "record", "=", "[", "record", "for", "record", "in", "self", ".", "dns_records", "if", "record", "[", "'type'", "]", "==", "dns_type", "and", "record", "[", "'name'",...
32.4
16.266667
def set_geometry(self, im, geometry, options=None): """Rescale the image to the new geometry. """ if not geometry: return im options = options or {} width, height = geometry if not width and not height: return im imw, imh = self.get_size(...
[ "def", "set_geometry", "(", "self", ",", "im", ",", "geometry", ",", "options", "=", "None", ")", ":", "if", "not", "geometry", ":", "return", "im", "options", "=", "options", "or", "{", "}", "width", ",", "height", "=", "geometry", "if", "not", "wid...
30.919355
14.33871
def get_port_channel_detail_output_lacp_aggr_member_actor_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channe...
[ "def", "get_port_channel_detail_output_lacp_aggr_member_actor_port", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_port_channel_detail", "=", "ET", ".", "Element", "(", "\"get_port_channel_detail\"", ...
45.142857
15.357143
def select(self, *command_tokens, **command_env): """ Select suitable command, that matches the given tokens. Each new command to check is fetched with this object iterator (:meth:`.WCommandSelector.__iter__`) :param command_tokens: command :param command_env: command environment :return: WCommandProto """...
[ "def", "select", "(", "self", ",", "*", "command_tokens", ",", "*", "*", "command_env", ")", ":", "for", "command_obj", "in", "self", ":", "if", "command_obj", ".", "match", "(", "*", "command_tokens", ",", "*", "*", "command_env", ")", ":", "return", ...
37.909091
12.818182
def _entry_must_not_exist(df, k1, k2): """Evaluate key-subkey non-existence. Checks that the key-subkey combo does not exists in the configuration options. """ count = df[(df['k1'] == k1) & (df['k2'] == k2)].shape[0] if count > 0: raise AlreadyRegisteredError( ...
[ "def", "_entry_must_not_exist", "(", "df", ",", "k1", ",", "k2", ")", ":", "count", "=", "df", "[", "(", "df", "[", "'k1'", "]", "==", "k1", ")", "&", "(", "df", "[", "'k2'", "]", "==", "k2", ")", "]", ".", "shape", "[", "0", "]", "if", "co...
32.909091
12
def _create_environment(config): """Constructor for an instance of the environment. Args: config: Object providing configurations via attributes. Raises: NotImplementedError: For action spaces other than Box and Discrete. Returns: Wrapped OpenAI Gym environment. """ if isinstance(config.env, ...
[ "def", "_create_environment", "(", "config", ")", ":", "if", "isinstance", "(", "config", ".", "env", ",", "str", ")", ":", "env", "=", "gym", ".", "make", "(", "config", ".", "env", ")", "else", ":", "env", "=", "config", ".", "env", "(", ")", "...
31.806452
17.967742
def prod(): """Option to do something on the production server.""" common_conf() env.user = settings.LOGIN_USER_PROD env.machine = 'prod' env.host_string = settings.HOST_PROD env.hosts = [env.host_string, ]
[ "def", "prod", "(", ")", ":", "common_conf", "(", ")", "env", ".", "user", "=", "settings", ".", "LOGIN_USER_PROD", "env", ".", "machine", "=", "'prod'", "env", ".", "host_string", "=", "settings", ".", "HOST_PROD", "env", ".", "hosts", "=", "[", "env"...
32
10.571429
def route(self, url_rule, name=None, options=None): '''A decorator to add a route to a view. name is used to differentiate when there are multiple routes for a given view.''' # TODO: change options kwarg to defaults def decorator(f): view_name = name or f.__name__ ...
[ "def", "route", "(", "self", ",", "url_rule", ",", "name", "=", "None", ",", "options", "=", "None", ")", ":", "# TODO: change options kwarg to defaults", "def", "decorator", "(", "f", ")", ":", "view_name", "=", "name", "or", "f", ".", "__name__", "self",...
46.888889
18.222222
def _EncodeInt64Field(field, value): """Handle the special case of int64 as a string.""" capabilities = [ messages.Variant.INT64, messages.Variant.UINT64, ] if field.variant not in capabilities: return encoding.CodecResult(value=value, complete=False) if field.repeated: ...
[ "def", "_EncodeInt64Field", "(", "field", ",", "value", ")", ":", "capabilities", "=", "[", "messages", ".", "Variant", ".", "INT64", ",", "messages", ".", "Variant", ".", "UINT64", ",", "]", "if", "field", ".", "variant", "not", "in", "capabilities", ":...
31.571429
15.928571
def _get_vsan_eligible_disks(service_instance, host, host_names): ''' Helper function that returns a dictionary of host_name keys with either a list of eligible disks that can be added to VSAN or either an 'Error' message or a message saying no eligible disks were found. Possible keys/values look like: ...
[ "def", "_get_vsan_eligible_disks", "(", "service_instance", ",", "host", ",", "host_names", ")", ":", "ret", "=", "{", "}", "for", "host_name", "in", "host_names", ":", "# Get VSAN System Config Manager, if available.", "host_ref", "=", "_get_host_ref", "(", "service_...
43.037736
25.415094
async def handle_adapter_event(self, adapter_id, conn_string, conn_id, name, event): """Handle an event received from an adapter.""" if name == 'device_seen': self._track_device_seen(adapter_id, conn_string, event) event = self._translate_device_seen(adapter_id, conn_string, eve...
[ "async", "def", "handle_adapter_event", "(", "self", ",", "adapter_id", ",", "conn_string", ",", "conn_id", ",", "name", ",", "event", ")", ":", "if", "name", "==", "'device_seen'", ":", "self", ".", "_track_device_seen", "(", "adapter_id", ",", "conn_string",...
49.357143
30.285714
def download_to_shared_memory(self, slices, location=None): """ Download images to a shared memory array. https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory tip: If you want to use slice notation, np.s_[...] will help in a pinch. MEMORY LIFECYCLE WARNING: You are respon...
[ "def", "download_to_shared_memory", "(", "self", ",", "slices", ",", "location", "=", "None", ")", ":", "if", "self", ".", "path", ".", "protocol", "==", "'boss'", ":", "raise", "NotImplementedError", "(", "'BOSS protocol does not support shared memory download.'", ...
51.688889
34.088889
def unattach_issue(resource_id, issue_id, table): """Unattach an issue from a specific job.""" v1_utils.verify_existence_and_get(issue_id, _TABLE) if table.name == 'jobs': join_table = models.JOIN_JOBS_ISSUES where_clause = sql.and_(join_table.c.job_id == resource_id, ...
[ "def", "unattach_issue", "(", "resource_id", ",", "issue_id", ",", "table", ")", ":", "v1_utils", ".", "verify_existence_and_get", "(", "issue_id", ",", "_TABLE", ")", "if", "table", ".", "name", "==", "'jobs'", ":", "join_table", "=", "models", ".", "JOIN_J...
40.7
21.9
def compile_dmtf_schema(self, schema_version, schema_root_dir, class_names, use_experimental=False, namespace=None, verbose=False): """ Compile the classes defined by `class_names` and their dependent classes from the DMTF CIM schema versio...
[ "def", "compile_dmtf_schema", "(", "self", ",", "schema_version", ",", "schema_root_dir", ",", "class_names", ",", "use_experimental", "=", "False", ",", "namespace", "=", "None", ",", "verbose", "=", "False", ")", ":", "schema", "=", "DMTFCIMSchema", "(", "sc...
45.762887
26.381443
def getTokensEndLoc(): """Method to be called from within a parse action to determine the end location of the parsed tokens.""" import inspect fstack = inspect.stack() try: # search up the stack (through intervening argument normalizers) for correct calling routine for f in...
[ "def", "getTokensEndLoc", "(", ")", ":", "import", "inspect", "fstack", "=", "inspect", ".", "stack", "(", ")", "try", ":", "# search up the stack (through intervening argument normalizers) for correct calling routine\r", "for", "f", "in", "fstack", "[", "2", ":", "]"...
40.733333
21.8
def run_competition(builders=[], task=BalanceTask(), Optimizer=HillClimber, rounds=3, max_eval=20, N_hidden=3, verbosity=0): """ pybrain buildNetwork builds a subtly different network structhan build_ann... so compete them! Arguments: task (Task): task to compete at Optimizer (class): pybrain.O...
[ "def", "run_competition", "(", "builders", "=", "[", "]", ",", "task", "=", "BalanceTask", "(", ")", ",", "Optimizer", "=", "HillClimber", ",", "rounds", "=", "3", ",", "max_eval", "=", "20", ",", "N_hidden", "=", "3", ",", "verbosity", "=", "0", ")"...
42.774194
28.467742
def add_alias(self, alias, indices, **kwargs): """ Add an alias to point to a set of indices. (See :ref:`es-guide-reference-api-admin-indices-aliases`) :param alias: the name of an alias :param indices: a list of indices """ indices = self.conn._validate_indices...
[ "def", "add_alias", "(", "self", ",", "alias", ",", "indices", ",", "*", "*", "kwargs", ")", ":", "indices", "=", "self", ".", "conn", ".", "_validate_indices", "(", "indices", ")", "return", "self", ".", "change_aliases", "(", "[", "'add'", ",", "inde...
35.857143
17.142857
def get_cdd_hdd_candidate_models( data, minimum_non_zero_cdd, minimum_non_zero_hdd, minimum_total_cdd, minimum_total_hdd, beta_cdd_maximum_p_value, beta_hdd_maximum_p_value, weights_col, ): """ Return a list of candidate cdd_hdd models for a particular selection of cooling balanc...
[ "def", "get_cdd_hdd_candidate_models", "(", "data", ",", "minimum_non_zero_cdd", ",", "minimum_non_zero_hdd", ",", "minimum_total_cdd", ",", "minimum_total_hdd", ",", "beta_cdd_maximum_p_value", ",", "beta_hdd_maximum_p_value", ",", "weights_col", ",", ")", ":", "cooling_ba...
36.405797
19.376812
def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Sign a file with the current blockchain ID's host's public key. @config_path should be for the *client*, not blockstack-file Return {'status': True, 'sender_key_id': ..., 'sig': ...} on ...
[ "def", "file_sign", "(", "blockchain_id", ",", "hostname", ",", "input_path", ",", "passphrase", "=", "None", ",", "config_path", "=", "CONFIG_PATH", ",", "wallet_keys", "=", "None", ")", ":", "config_dir", "=", "os", ".", "path", ".", "dirname", "(", "con...
46.095238
28.095238
def hyperrectangle(lower, upper, bdy=True): '''Returns the indicator function of a hyperrectangle. :param lower: Vector-like numpy array, defining the lower boundary of the hyperrectangle.\n len(lower) fixes the dimension. :param upper: Vector-like numpy array, defining the upper...
[ "def", "hyperrectangle", "(", "lower", ",", "upper", ",", "bdy", "=", "True", ")", ":", "# copy input", "lower", "=", "_np", ".", "array", "(", "lower", ")", "upper", "=", "_np", ".", "array", "(", "upper", ")", "dim", "=", "len", "(", "lower", ")"...
33.021277
25.531915
def get_book_metadata(self, asin): """Returns a book's metadata. Args: asin: The ASIN of the book to be queried. Returns: A `KindleBook` instance corresponding to the book associated with `asin`. """ kbm = self._get_api_call('get_book_metadata', '"%s"' % asin) return KindleCl...
[ "def", "get_book_metadata", "(", "self", ",", "asin", ")", ":", "kbm", "=", "self", ".", "_get_api_call", "(", "'get_book_metadata'", ",", "'\"%s\"'", "%", "asin", ")", "return", "KindleCloudReaderAPI", ".", "_kbm_to_book", "(", "kbm", ")" ]
28.25
20.25
def hmget(key, *fields, **options): ''' Returns the values of all the given hash fields. .. versionadded:: 2017.7.0 CLI Example: .. code-block:: bash salt '*' redis.hmget foo_hash bar_field1 bar_field2 ''' host = options.get('host', None) port = options.get('port', None) ...
[ "def", "hmget", "(", "key", ",", "*", "fields", ",", "*", "*", "options", ")", ":", "host", "=", "options", ".", "get", "(", "'host'", ",", "None", ")", "port", "=", "options", ".", "get", "(", "'port'", ",", "None", ")", "database", "=", "option...
26.333333
19