text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _update_disks(disks_old_new): ''' Changes the disk size and returns the config spec objects in a list. The controller property cannot be updated, because controller address identifies the disk by the unit and bus number properties. disks_diffs List of old and new disk properties, the pr...
[ "def", "_update_disks", "(", "disks_old_new", ")", ":", "disk_changes", "=", "[", "]", "if", "disks_old_new", ":", "devs", "=", "[", "disk", "[", "'old'", "]", "[", "'address'", "]", "for", "disk", "in", "disks_old_new", "]", "log", ".", "trace", "(", ...
45.375
0.000449
def plot_mask_cell(true_mask, predicted_mask, cell, suffix, ax1, ax2, ax3, padding=16): """Plots a single cell with a its true mask and predicuted mask""" for ax in [ax1, ax2, ax3...
[ "def", "plot_mask_cell", "(", "true_mask", ",", "predicted_mask", ",", "cell", ",", "suffix", ",", "ax1", ",", "ax2", ",", "ax3", ",", "padding", "=", "16", ")", ":", "for", "ax", "in", "[", "ax1", ",", "ax2", ",", "ax3", "]", ":", "ax", ".", "gr...
37.380952
0.001242
def print(self, indent=0): """Print a structural view of the registered extensions.""" LOG.info("%s:: %s", indent * " ", self.__class__) for ext in self.next_extensions: ext.print(indent=indent + 2)
[ "def", "print", "(", "self", ",", "indent", "=", "0", ")", ":", "LOG", ".", "info", "(", "\"%s:: %s\"", ",", "indent", "*", "\" \"", ",", "self", ".", "__class__", ")", "for", "ext", "in", "self", ".", "next_extensions", ":", "ext", ".", "print", "...
46
0.008547
def wherenotin(self, fieldname, value): """ Logical opposite of `wherein`. """ return self.wherein(fieldname, value, negate=True)
[ "def", "wherenotin", "(", "self", ",", "fieldname", ",", "value", ")", ":", "return", "self", ".", "wherein", "(", "fieldname", ",", "value", ",", "negate", "=", "True", ")" ]
31.4
0.012422
def dependents(self, on_predicate=None, from_predicate=None): """Returns a map from targets that satisfy the from_predicate to targets they depend on that satisfy the on_predicate. :API: public """ core = set(self.targets(on_predicate)) dependees = defaultdict(set) for target in self.tar...
[ "def", "dependents", "(", "self", ",", "on_predicate", "=", "None", ",", "from_predicate", "=", "None", ")", ":", "core", "=", "set", "(", "self", ".", "targets", "(", "on_predicate", ")", ")", "dependees", "=", "defaultdict", "(", "set", ")", "for", "...
36.153846
0.008299
def explode_host_groups_into_hosts(self, item, hosts, hostgroups): """ Get all hosts of hostgroups and add all in host_name container :param item: the item object :type item: alignak.objects.item.Item :param hosts: hosts object :type hosts: alignak.objects.host.Hosts ...
[ "def", "explode_host_groups_into_hosts", "(", "self", ",", "item", ",", "hosts", ",", "hostgroups", ")", ":", "hnames_list", "=", "[", "]", "# Gets item's hostgroup_name", "hgnames", "=", "getattr", "(", "item", ",", "\"hostgroup_name\"", ",", "''", ")", "or", ...
38.02
0.001538
def unparse(self): """Convert the parsed representation back into the source code.""" ut = Untokenizer(start_row=self._tokens[0].start_row) self._unparse(ut) return ut.result()
[ "def", "unparse", "(", "self", ")", ":", "ut", "=", "Untokenizer", "(", "start_row", "=", "self", ".", "_tokens", "[", "0", "]", ".", "start_row", ")", "self", ".", "_unparse", "(", "ut", ")", "return", "ut", ".", "result", "(", ")" ]
40.8
0.009615
def split_line(what, indent='', cols=79): """Split a line on the closest space, or break the last word with '-'. Args: what(str): text to spli one line of. indent(str): will prepend this indent to the split line, taking it into account in the column count. cols(int): maximum len...
[ "def", "split_line", "(", "what", ",", "indent", "=", "''", ",", "cols", "=", "79", ")", ":", "if", "len", "(", "indent", ")", ">", "cols", ":", "raise", "ValueError", "(", "\"The indent can't be longer than cols.\"", ")", "if", "cols", "<", "2", ":", ...
28.770833
0.0007
def ListDirectory(self, pathspec, depth=0): """A recursive generator of files.""" # Limit recursion depth if depth >= self.request.max_depth: return try: fd = vfs.VFSOpen(pathspec, progress_callback=self.Progress) files = fd.ListFiles(ext_attrs=self.request.collect_ext_attrs) exce...
[ "def", "ListDirectory", "(", "self", ",", "pathspec", ",", "depth", "=", "0", ")", ":", "# Limit recursion depth", "if", "depth", ">=", "self", ".", "request", ".", "max_depth", ":", "return", "try", ":", "fd", "=", "vfs", ".", "VFSOpen", "(", "pathspec"...
38.945946
0.008125
def _write_standard(self, message, extra): ''' Writes a standard log statement @param message: The message to write @param extra: The object to pull defaults from ''' level = extra['level'] if self.include_extra: del extra['timestamp'] del...
[ "def", "_write_standard", "(", "self", ",", "message", ",", "extra", ")", ":", "level", "=", "extra", "[", "'level'", "]", "if", "self", ".", "include_extra", ":", "del", "extra", "[", "'timestamp'", "]", "del", "extra", "[", "'level'", "]", "del", "ex...
30.592593
0.002347
def have_all_block_data(self): """ Have we received all block data? """ if not (self.num_blocks_received == self.num_blocks_requested): log.debug("num blocks received = %s, num requested = %s" % (self.num_blocks_received, self.num_blocks_requested)) return False ...
[ "def", "have_all_block_data", "(", "self", ")", ":", "if", "not", "(", "self", ".", "num_blocks_received", "==", "self", ".", "num_blocks_requested", ")", ":", "log", ".", "debug", "(", "\"num blocks received = %s, num requested = %s\"", "%", "(", "self", ".", "...
36.777778
0.00885
def enc_to_clear_filename(fname): """ Converts the filename of an encrypted file to cleartext :param fname: :return: filename of clear secret file if found, else None """ if not fname.lower().endswith('.json'): raise CredkeepException('Invalid filetype') if not fname.lower().endswi...
[ "def", "enc_to_clear_filename", "(", "fname", ")", ":", "if", "not", "fname", ".", "lower", "(", ")", ".", "endswith", "(", "'.json'", ")", ":", "raise", "CredkeepException", "(", "'Invalid filetype'", ")", "if", "not", "fname", ".", "lower", "(", ")", "...
30.588235
0.001866
def _expand_fcp_list(fcp_list): """Expand fcp list string into a python list object which contains each fcp devices in the list string. A fcp list is composed of fcp device addresses, range indicator '-', and split indicator ';'. For example, if fcp_list is "0011-0013;0015;0017-...
[ "def", "_expand_fcp_list", "(", "fcp_list", ")", ":", "LOG", ".", "debug", "(", "\"Expand FCP list %s\"", "%", "fcp_list", ")", "if", "not", "fcp_list", ":", "return", "set", "(", ")", "range_pattern", "=", "'[0-9a-fA-F]{1,4}(-[0-9a-fA-F]{1,4})?'", "match_pattern", ...
36.368421
0.001409
def flavor_create(name, # pylint: disable=C0103 flavor_id=0, # pylint: disable=C0103 ram=0, disk=0, vcpus=1, is_public=True, profile=None, **kwargs): ''' Add a flavor to nova (nova flavor-create...
[ "def", "flavor_create", "(", "name", ",", "# pylint: disable=C0103", "flavor_id", "=", "0", ",", "# pylint: disable=C0103", "ram", "=", "0", ",", "disk", "=", "0", ",", "vcpus", "=", "1", ",", "is_public", "=", "True", ",", "profile", "=", "None", ",", "...
23.333333
0.00211
def get_query_batch_request(self, batch_id, job_id=None): """ Fetch the request sent for the batch. Note should only used for query batches """ if not job_id: job_id = self.lookup_job_id(batch_id) url = self.endpoint + "/job/{}/batch/{}/request".format(job_id, batch_id) resp...
[ "def", "get_query_batch_request", "(", "self", ",", "batch_id", ",", "job_id", "=", "None", ")", ":", "if", "not", "job_id", ":", "job_id", "=", "self", ".", "lookup_job_id", "(", "batch_id", ")", "url", "=", "self", ".", "endpoint", "+", "\"/job/{}/batch/...
45.888889
0.009501
def create_url_rules(endpoint, list_route=None, item_route=None, pid_type=None, pid_minter=None, pid_fetcher=None, read_permission_factory_imp=None, create_permission_factory_imp=None, update_permission_factory_imp=None, ...
[ "def", "create_url_rules", "(", "endpoint", ",", "list_route", "=", "None", ",", "item_route", "=", "None", ",", "pid_type", "=", "None", ",", "pid_minter", "=", "None", ",", "pid_fetcher", "=", "None", ",", "read_permission_factory_imp", "=", "None", ",", "...
41.879397
0.000117
def log_response( self, response: Response, trim_log_values: bool = False, **kwargs: Any ) -> None: """ Log a response. Note this is different to log_request, in that it takes a Response object, not a string. Args: response: The Response object to log. N...
[ "def", "log_response", "(", "self", ",", "response", ":", "Response", ",", "trim_log_values", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "return", "log_", "(", "response", ".", "text", ",", "response_log", "...
36.933333
0.010563
def serialize(data): """Serialize a dict into a JSON formatted string. This function enforces rules like the separator and order of keys. This ensures that all dicts are serialized in the same way. This is specially important for hashing data. We need to make sure that everyone ser...
[ "def", "serialize", "(", "data", ")", ":", "return", "rapidjson", ".", "dumps", "(", "data", ",", "skipkeys", "=", "False", ",", "ensure_ascii", "=", "False", ",", "sort_keys", "=", "True", ")" ]
34.15
0.001425
def rescale_center(x): r""" Rescale and center data, e.g. embedding coordinates. Parameters ---------- x : ndarray Data to be rescaled. Returns ------- r : ndarray Rescaled data. Examples -------- >>> from pygsp import utils >>> x = np.array([[1, 6], [2...
[ "def", "rescale_center", "(", "x", ")", ":", "N", "=", "x", ".", "shape", "[", "1", "]", "y", "=", "x", "-", "np", ".", "kron", "(", "np", ".", "ones", "(", "(", "1", ",", "N", ")", ")", ",", "np", ".", "mean", "(", "x", ",", "axis", "=...
18.666667
0.001698
def encrypt(source_text, passphrase, debug_stmt=None): """ Returns *source_text* as a base64 AES encrypted string. The full encrypted text is special crafted to be compatible with openssl. It can be decrypted with: $ echo _full_encypted_ | openssl aes-256-cbc -d -a -k _passphrase_ -p s...
[ "def", "encrypt", "(", "source_text", ",", "passphrase", ",", "debug_stmt", "=", "None", ")", ":", "if", "debug_stmt", "is", "None", ":", "debug_stmt", "=", "\"encrypt\"", "prefix", "=", "b'Salted__'", "salt", "=", "os", ".", "urandom", "(", "IV_BLOCK_SIZE",...
34.105263
0.0015
def load(self): """Deferred loading""" path = self.find_scene(self.meta.path) if not path: raise ValueError("Scene '{}' not found".format(self.meta.path)) if path.suffix == '.bin': path = path.parent / path.stem data = pywavefront.Wavefront(str(path), c...
[ "def", "load", "(", "self", ")", ":", "path", "=", "self", ".", "find_scene", "(", "self", ".", "meta", ".", "path", ")", "if", "not", "path", ":", "raise", "ValueError", "(", "\"Scene '{}' not found\"", ".", "format", "(", "self", ".", "meta", ".", ...
32.914286
0.002107
def get_filetypes2wildcards(filetypes): """Returns OrderedDict of filetypes to wildcards The filetypes that are provided in the filetypes parameter are checked for availability. Only available filetypes are inluded in the return ODict. Parameters ---------- filetypes: Iterable of strings \...
[ "def", "get_filetypes2wildcards", "(", "filetypes", ")", ":", "def", "is_available", "(", "filetype", ")", ":", "return", "filetype", "not", "in", "FILETYPE_AVAILABILITY", "or", "FILETYPE_AVAILABILITY", "[", "filetype", "]", "available_filetypes", "=", "filter", "("...
29.809524
0.001548
def get_metric_by_day(self, unique_identifier, metric, from_date, limit=30, **kwargs): """ Returns the ``metric`` for ``unique_identifier`` segmented by day starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric...
[ "def", "get_metric_by_day", "(", "self", ",", "unique_identifier", ",", "metric", ",", "from_date", ",", "limit", "=", "30", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "kwargs", ".", "get", "(", "\"connection\"", ",", "None", ")", "date_generator", ...
50.137931
0.009447
def create_request_elements( cls, request_type, credentials, url, method='GET', params=None, headers=None, body='', secret=None, redirect_uri='', scope='', csrf='', user_state='' ): """ Creates |oauth2| request elements. """ headers = headers or {...
[ "def", "create_request_elements", "(", "cls", ",", "request_type", ",", "credentials", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "headers", "=", "None", ",", "body", "=", "''", ",", "secret", "=", "None", ",", "redirect_ur...
42.267327
0.000687
def calc_adev_phase(phase, rate, mj, stride): """ Main algorithm for adev() (stride=mj) and oadev() (stride=1) see http://www.leapsecond.com/tools/adev_lib.c stride = mj for nonoverlapping allan deviation Parameters ---------- phase: np.array Phase data in seconds. rate: f...
[ "def", "calc_adev_phase", "(", "phase", ",", "rate", ",", "mj", ",", "stride", ")", ":", "mj", "=", "int", "(", "mj", ")", "stride", "=", "int", "(", "stride", ")", "d2", "=", "phase", "[", "2", "*", "mj", ":", ":", "stride", "]", "d1", "=", ...
24.019231
0.001538
def FromString(self, string): """Parse a bool from a string.""" if string.lower() in ("false", "no", "n"): return False if string.lower() in ("true", "yes", "y"): return True raise TypeValueError("%s is not recognized as a boolean value." % string)
[ "def", "FromString", "(", "self", ",", "string", ")", ":", "if", "string", ".", "lower", "(", ")", "in", "(", "\"false\"", ",", "\"no\"", ",", "\"n\"", ")", ":", "return", "False", "if", "string", ".", "lower", "(", ")", "in", "(", "\"true\"", ",",...
30
0.010791
def _set_shape_on_tensor(tensor, shape): """Convenience to set a shape or check it.""" if shape is not None: try: tensor.set_shape(shape) except ValueError: raise ValueError("Requested shape does not match tensor's shape: %s vs %s" % (shape, tensor.get_shape())) elif ten...
[ "def", "_set_shape_on_tensor", "(", "tensor", ",", "shape", ")", ":", "if", "shape", "is", "not", "None", ":", "try", ":", "tensor", ".", "set_shape", "(", "shape", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Requested shape does not match...
40.2
0.017032
def set_user_timer(self, value, index): """Set the current value of a user timer.""" err = self.clock_manager.set_tick(index, value) return [err]
[ "def", "set_user_timer", "(", "self", ",", "value", ",", "index", ")", ":", "err", "=", "self", ".", "clock_manager", ".", "set_tick", "(", "index", ",", "value", ")", "return", "[", "err", "]" ]
33.2
0.011765
def _wrap_unary_errors(callable_): """Map errors for Unary-Unary and Stream-Unary gRPC callables.""" _patch_callable_name(callable_) @six.wraps(callable_) def error_remapped_callable(*args, **kwargs): try: return callable_(*args, **kwargs) except grpc.RpcError as exc: ...
[ "def", "_wrap_unary_errors", "(", "callable_", ")", ":", "_patch_callable_name", "(", "callable_", ")", "@", "six", ".", "wraps", "(", "callable_", ")", "def", "error_remapped_callable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "ret...
33.583333
0.002415
def run(juttle, deployment_name, program_name=None, persist=False, token_manager=None, app_url=defaults.APP_URL): """ run a juttle program through the juttle streaming API and return the various events that are part of running a Juttle program which include: ...
[ "def", "run", "(", "juttle", ",", "deployment_name", ",", "program_name", "=", "None", ",", "persist", "=", "False", ",", "token_manager", "=", "None", ",", "app_url", "=", "defaults", ".", "APP_URL", ")", ":", "headers", "=", "token_manager", ".", "get_ac...
32.230769
0.000232
def default_child_path(path): """Return the default child of the parent path ,if it exists, else path. As an example, if the path `parent` show show the page `parent/child` by default, this method will return `parent/child` given `parent`. If `parent/child` should show `parent/child/grandchild` by defa...
[ "def", "default_child_path", "(", "path", ")", ":", "try", ":", "# Recurse until we find a path with no default child", "child_path", "=", "default_child_path", "(", "current_app", ".", "config", "[", "'DEFAULT_CHILDREN'", "]", "[", "path", "]", ")", "except", "KeyErr...
41.736842
0.001233
def pytype_to_pretty_type(t): """ Python -> docstring type. """ if isinstance(t, List): return '{0} list'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Set): return '{0} set'.format(pytype_to_pretty_type(t.__args__[0])) elif isinstance(t, Dict): tkey, tvalue = t...
[ "def", "pytype_to_pretty_type", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "List", ")", ":", "return", "'{0} list'", ".", "format", "(", "pytype_to_pretty_type", "(", "t", ".", "__args__", "[", "0", "]", ")", ")", "elif", "isinstance", "(", ...
41.538462
0.000603
def hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, omega_laser, xi, RWA=True, RF=True): r"""Return symbolic Hamiltonian. >>> from sympy import zeros, pi, pprint, symbols >>> Ne = 3 >>> Nl = 2 >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonp = [polarizatio...
[ "def", "hamiltonian", "(", "Ep", ",", "epsilonp", ",", "detuning_knob", ",", "rm", ",", "omega_level", ",", "omega_laser", ",", "xi", ",", "RWA", "=", "True", ",", "RF", "=", "True", ")", ":", "# We check what RF is.", "if", "type", "(", "RF", ")", "==...
34.64
0.000561
def force_seek(fd, offset, chunk=CHUNK): """ Force adjustment of read cursort to specified offset This function takes a file descriptor ``fd`` and tries to seek to position specified by ``offset`` argument. If the descriptor does not support the ``seek()`` method, it will fall back to ``emulate_seek()`...
[ "def", "force_seek", "(", "fd", ",", "offset", ",", "chunk", "=", "CHUNK", ")", ":", "try", ":", "fd", ".", "seek", "(", "offset", ")", "except", "(", "AttributeError", ",", "io", ".", "UnsupportedOperation", ")", ":", "# This file handle probably has no see...
39.666667
0.001642
def sample_variants(self, variants, sample_name, category = 'snv'): """Given a list of variants get variant objects found in a specific patient Args: variants(list): a list of variant ids sample_name(str): a sample display name category(str): 'snv', 'sv' .. ...
[ "def", "sample_variants", "(", "self", ",", "variants", ",", "sample_name", ",", "category", "=", "'snv'", ")", ":", "LOG", ".", "info", "(", "'Retrieving variants for subject : {0}'", ".", "format", "(", "sample_name", ")", ")", "has_allele", "=", "re", ".", ...
35.5
0.018987
def getNbVariants(self, x1, x2 = -1) : """returns the nb of variants of sequences between x1 and x2""" if x2 == -1 : xx2 = len(self.defaultSequence) else : xx2 = x2 nbP = 1 for p in self.polymorphisms: if x1 <= p[0] and p[0] <= xx2 : nbP *= len(p[1]) return nbP
[ "def", "getNbVariants", "(", "self", ",", "x1", ",", "x2", "=", "-", "1", ")", ":", "if", "x2", "==", "-", "1", ":", "xx2", "=", "len", "(", "self", ".", "defaultSequence", ")", "else", ":", "xx2", "=", "x2", "nbP", "=", "1", "for", "p", "in"...
21.538462
0.075342
def generate_overcloud_passwords(output_file="tripleo-overcloud-passwords"): """Create the passwords needed for the overcloud This will create the set of passwords required by the overcloud, store them in the output file path and return a dictionary of passwords. If the file already exists the existing...
[ "def", "generate_overcloud_passwords", "(", "output_file", "=", "\"tripleo-overcloud-passwords\"", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "output_file", ")", ":", "with", "open", "(", "output_file", ")", "as", "f", ":", "return", "dict", "(", ...
35.142857
0.000791
def cluster_coincs(stat, time1, time2, timeslide_id, slide, window, argmax=numpy.argmax): """Cluster coincident events for each timeslide separately, across templates, based on the ranking statistic Parameters ---------- stat: numpy.ndarray vector of ranking values to maximize time1: nu...
[ "def", "cluster_coincs", "(", "stat", ",", "time1", ",", "time2", ",", "timeslide_id", ",", "slide", ",", "window", ",", "argmax", "=", "numpy", ".", "argmax", ")", ":", "logging", ".", "info", "(", "'clustering coinc triggers over %ss window'", "%", "window",...
32.555556
0.001988
def upload(cls, path, project=None, parent=None, file_name=None, overwrite=False, retry=5, timeout=10, part_size=PartSize.UPLOAD_MINIMUM_PART_SIZE, wait=True, api=None): """ Uploads a file using multipart upload and returns an upload handle if the wai...
[ "def", "upload", "(", "cls", ",", "path", ",", "project", "=", "None", ",", "parent", "=", "None", ",", "file_name", "=", "None", ",", "overwrite", "=", "False", ",", "retry", "=", "5", ",", "timeout", "=", "10", ",", "part_size", "=", "PartSize", ...
35.033898
0.002353
def problem_id(self, value): """The problem_id property. Args: value (string). the property value. """ if value == self._defaults['problemId'] and 'problemId' in self._values: del self._values['problemId'] else: self._values['problemId...
[ "def", "problem_id", "(", "self", ",", "value", ")", ":", "if", "value", "==", "self", ".", "_defaults", "[", "'problemId'", "]", "and", "'problemId'", "in", "self", ".", "_values", ":", "del", "self", ".", "_values", "[", "'problemId'", "]", "else", "...
32.1
0.012121
def hostname(state, host, hostname, hostname_file=None): ''' Set the system hostname. + hostname: the hostname that should be set + hostname_file: the file that permanently sets the hostname Hostname file: By default pyinfra will auto detect this by targetting ``/etc/hostname`` on ...
[ "def", "hostname", "(", "state", ",", "host", ",", "hostname", ",", "hostname_file", "=", "None", ")", ":", "if", "hostname_file", "is", "None", ":", "os", "=", "host", ".", "fact", ".", "os", "if", "os", "==", "'Linux'", ":", "hostname_file", "=", "...
26.588235
0.002134
def saveJSON(g, data, backup=False): """ Saves the current setup to disk. g : hcam_drivers.globals.Container Container with globals data : dict The current setup in JSON compatible dictionary format. backup : bool If we are saving a backup on close, don't prompt for filename """ ...
[ "def", "saveJSON", "(", "g", ",", "data", ",", "backup", "=", "False", ")", ":", "if", "not", "backup", ":", "fname", "=", "filedialog", ".", "asksaveasfilename", "(", "defaultextension", "=", "'.json'", ",", "filetypes", "=", "[", "(", "'json files'", "...
27.060606
0.001081
def get_reduced_bases(lattice, method='delaunay', tolerance=1e-5): """Search kinds of shortest basis vectors Parameters ---------- lattice : ndarray or list of list Basis vectors by row vectors, [a, b, c]^T shape=(3, 3) method : str ...
[ "def", "get_reduced_bases", "(", "lattice", ",", "method", "=", "'delaunay'", ",", "tolerance", "=", "1e-5", ")", ":", "if", "method", "==", "'niggli'", ":", "return", "spg", ".", "niggli_reduce", "(", "lattice", ",", "eps", "=", "tolerance", ")", "else", ...
25.344828
0.001311
def iter_attrs( idx_bytes ): ''' called when idx_chars is just past "<a " inside an HTML anchor tag generates tuple(end_idx, attr_name, attr_value) ''' ## read to the end of the "A" tag while 1: idx, attr_name, next_b = read_to(idx_bytes, ['=', '>']) attr_vals = [] ...
[ "def", "iter_attrs", "(", "idx_bytes", ")", ":", "## read to the end of the \"A\" tag", "while", "1", ":", "idx", ",", "attr_name", ",", "next_b", "=", "read_to", "(", "idx_bytes", ",", "[", "'='", ",", "'>'", "]", ")", "attr_vals", "=", "[", "]", "## stop...
35.071429
0.015857
def gen_colors(img): """Format the output from imagemagick into a list of hex colors.""" magick_command = has_im() for i in range(0, 20, 1): raw_colors = imagemagick(16 + i, img, magick_command) if len(raw_colors) > 16: break elif i == 19: logging.er...
[ "def", "gen_colors", "(", "img", ")", ":", "magick_command", "=", "has_im", "(", ")", "for", "i", "in", "range", "(", "0", ",", "20", ",", "1", ")", ":", "raw_colors", "=", "imagemagick", "(", "16", "+", "i", ",", "img", ",", "magick_command", ")",...
30.85
0.001572
def _summary(tag, hparams_plugin_data): """Returns a summary holding the given HParamsPluginData message. Helper function. Args: tag: string. The tag to use. hparams_plugin_data: The HParamsPluginData message to use. """ summary = tf.compat.v1.Summary() summary.value.add( tag=tag, meta...
[ "def", "_summary", "(", "tag", ",", "hparams_plugin_data", ")", ":", "summary", "=", "tf", ".", "compat", ".", "v1", ".", "Summary", "(", ")", "summary", ".", "value", ".", "add", "(", "tag", "=", "tag", ",", "metadata", "=", "metadata", ".", "create...
27.357143
0.012626
def event_cd(cls, event_tx, ab_des): """ Event Code for Retrosheet :param event_tx: Event text :param ab_des: at bat description :return: event_cd(int) """ _event_tx = event_tx.lower() _ab_des = ab_des.lower() # Generic out(event_cd:2) if _...
[ "def", "event_cd", "(", "cls", ",", "event_tx", ",", "ab_des", ")", ":", "_event_tx", "=", "event_tx", ".", "lower", "(", ")", "_ab_des", "=", "ab_des", ".", "lower", "(", ")", "# Generic out(event_cd:2)", "if", "_event_tx", "in", "cls", ".", "EVENT_02_GEN...
33.149254
0.000875
def capture(cls, eval_env=0, reference=0): """Capture an execution environment from the stack. If `eval_env` is already an :class:`EvalEnvironment`, it is returned unchanged. Otherwise, we walk up the stack by ``eval_env + reference`` steps and capture that function's evaluation environm...
[ "def", "capture", "(", "cls", ",", "eval_env", "=", "0", ",", "reference", "=", "0", ")", ":", "if", "isinstance", "(", "eval_env", ",", "cls", ")", ":", "return", "eval_env", "elif", "isinstance", "(", "eval_env", ",", "numbers", ".", "Integral", ")",...
50.175439
0.000686
def update_pop(self): """Assigns fitnesses to particles that are within bounds.""" valid_particles = [] invalid_particles = [] for part in self.population: if any(x > 1 or x < -1 for x in part): invalid_particles.append(part) else: ...
[ "def", "update_pop", "(", "self", ")", ":", "valid_particles", "=", "[", "]", "invalid_particles", "=", "[", "]", "for", "part", "in", "self", ".", "population", ":", "if", "any", "(", "x", ">", "1", "or", "x", "<", "-", "1", "for", "x", "in", "p...
42.47619
0.002193
def _num_samples(x): """Return number of samples in array-like x.""" if hasattr(x, 'fit'): # Don't get num_samples from an ensembles length! raise TypeError('Expected sequence or array-like, got ' 'estimator %s' % x) if not hasattr(x, '__len__') and not hasattr(x, 'sh...
[ "def", "_num_samples", "(", "x", ")", ":", "if", "hasattr", "(", "x", ",", "'fit'", ")", ":", "# Don't get num_samples from an ensembles length!", "raise", "TypeError", "(", "'Expected sequence or array-like, got '", "'estimator %s'", "%", "x", ")", "if", "not", "ha...
38.894737
0.001321
def check(self, *args): """ Checks the validity of the run parameters. Returns flag (True = OK), and a message which indicates the nature of the problem if the flag is False. """ ok = True msg = '' g = get_root(self).globals dtype = g.observe.rtyp...
[ "def", "check", "(", "self", ",", "*", "args", ")", ":", "ok", "=", "True", "msg", "=", "''", "g", "=", "get_root", "(", "self", ")", ".", "globals", "dtype", "=", "g", ".", "observe", ".", "rtype", "(", ")", "expert", "=", "g", ".", "cpars", ...
35.266667
0.00092
def qAx(mt, x, q): """ This function evaluates the APV of a geometrically increasing annual annuity-due """ q = float(q) j = (mt.i - q) / (1 + q) mtj = Actuarial(nt=mt.nt, i=j) return Ax(mtj, x)
[ "def", "qAx", "(", "mt", ",", "x", ",", "q", ")", ":", "q", "=", "float", "(", "q", ")", "j", "=", "(", "mt", ".", "i", "-", "q", ")", "/", "(", "1", "+", "q", ")", "mtj", "=", "Actuarial", "(", "nt", "=", "mt", ".", "nt", ",", "i", ...
34.833333
0.009346
def createOutputBuffer(file, encoding): """Create a libxml2 output buffer from a Python file """ ret = libxml2mod.xmlCreateOutputBuffer(file, encoding) if ret is None:raise treeError('xmlCreateOutputBuffer() failed') return outputBuffer(_obj=ret)
[ "def", "createOutputBuffer", "(", "file", ",", "encoding", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCreateOutputBuffer", "(", "file", ",", "encoding", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlCreateOutputBuffer() failed'", ")", ...
51.6
0.01145
def imagej_metadata(data, bytecounts, byteorder): """Return IJMetadata tag value as dict. The 'Info' string can have multiple formats, e.g. OIF or ScanImage, that might be parsed into dicts using the matlabstr2py or oiffile.SettingsFile functions. """ def _string(data, byteorder): retu...
[ "def", "imagej_metadata", "(", "data", ",", "bytecounts", ",", "byteorder", ")", ":", "def", "_string", "(", "data", ",", "byteorder", ")", ":", "return", "data", ".", "decode", "(", "'utf-16'", "+", "{", "'>'", ":", "'be'", ",", "'<'", ":", "'le'", ...
33.571429
0.000517
def weighted_sample_instance_from_weighted_samples(self, index): """Setup a model instance of a weighted sample, including its weight and likelihood. Parameters ----------- index : int The index of the weighted sample to return. """ model, weight, likelihood ...
[ "def", "weighted_sample_instance_from_weighted_samples", "(", "self", ",", "index", ")", ":", "model", ",", "weight", ",", "likelihood", "=", "self", ".", "weighted_sample_model_from_weighted_samples", "(", "index", ")", "self", ".", "_weighted_sample_model", "=", "mo...
38.230769
0.009823
def get_instance(self, payload): """ Build an instance of MobileInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.incoming_phone_number.mobile.MobileInstance :rtype: twilio.rest.api.v2010.account.incoming_phone_number.mobile.Mob...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "MobileInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
43.3
0.011312
async def get_box_ids_json(self) -> str: """ Return json object on lists of all unique box identifiers for credentials in wallet: schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g., :: { "schema_id": [ "R...
[ "async", "def", "get_box_ids_json", "(", "self", ")", "->", "str", ":", "LOGGER", ".", "debug", "(", "'HolderProver.get_box_ids_json >>>'", ")", "s_ids", "=", "set", "(", ")", "cd_ids", "=", "set", "(", ")", "rr_ids", "=", "set", "(", ")", "for", "cred",...
33.612245
0.00236
def encipher(self,message): """Encipher string using M209 cipher according to initialised key. Punctuation and whitespace are removed from the input. Example (continuing from the example above):: ciphertext = m.encipher(plaintext) :param string: The str...
[ "def", "encipher", "(", "self", ",", "message", ")", ":", "message", "=", "self", ".", "remove_punctuation", "(", "message", ")", "effective_ch", "=", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", "# these are the wheels ...
54.03125
0.020455
def avg_mutual_coverage(self,gpd): """get the coverage fraction of each transcript then return the geometric mean :param gpd: Another transcript :type gpd: Transcript :return: avg_coverage :rtype: float """ ov = self.overlap_size(gpd) if ov == 0: return 0 xfrac = float(ov) / float(s...
[ "def", "avg_mutual_coverage", "(", "self", ",", "gpd", ")", ":", "ov", "=", "self", ".", "overlap_size", "(", "gpd", ")", "if", "ov", "==", "0", ":", "return", "0", "xfrac", "=", "float", "(", "ov", ")", "/", "float", "(", "self", ".", "get_length"...
30.923077
0.009662
def search(query, num_results=10): """ searches google for :query and returns a list of tuples of the format (name, url) """ data = download(query, num_results) results = re.findall(r'\<h3.*?\>.*?\<\/h3\>', data, re.IGNORECASE) if results is None or len(results) == 0: print('No results where found. Did the rat...
[ "def", "search", "(", "query", ",", "num_results", "=", "10", ")", ":", "data", "=", "download", "(", "query", ",", "num_results", ")", "results", "=", "re", ".", "findall", "(", "r'\\<h3.*?\\>.*?\\<\\/h3\\>'", ",", "data", ",", "re", ".", "IGNORECASE", ...
35.333333
0.033058
def dropEvent( self, event ): """ Processes drop event. :param event | <QDropEvent> """ if event.mimeData().hasUrls(): url = event.mimeData().urls()[0] filepath = url.toLocalFile() if filepath: self....
[ "def", "dropEvent", "(", "self", ",", "event", ")", ":", "if", "event", ".", "mimeData", "(", ")", ".", "hasUrls", "(", ")", ":", "url", "=", "event", ".", "mimeData", "(", ")", ".", "urls", "(", ")", "[", "0", "]", "filepath", "=", "url", ".",...
30.090909
0.017595
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT): """Test if a matrix is positive semidefinite""" if atol is None: atol = ATOL_DEFAULT if rtol is None: rtol = RTOL_DEFAULT if not is_hermitian_matrix(mat, rtol=rtol, atol=atol): return False # Chec...
[ "def", "is_positive_semidefinite_matrix", "(", "mat", ",", "rtol", "=", "RTOL_DEFAULT", ",", "atol", "=", "ATOL_DEFAULT", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "ATOL_DEFAULT", "if", "rtol", "is", "None", ":", "rtol", "=", "RTOL_DEFAULT", ...
32.428571
0.002141
def init_default(self): """ Initializes object with its default values Tries to load self.default_filename from default data directory. For safety, filename is reset to None so that it doesn't point to the original file. """ import f311 if self.default_fi...
[ "def", "init_default", "(", "self", ")", ":", "import", "f311", "if", "self", ".", "default_filename", "is", "None", ":", "raise", "RuntimeError", "(", "\"Class '{}' has no default filename\"", ".", "format", "(", "self", ".", "__class__", ".", "__name__", ")", ...
40.857143
0.008547
def from_grpc(operation, operations_stub, result_type, **kwargs): """Create an operation future using a gRPC client. This interacts with the long-running operations `service`_ (specific to a given API) via gRPC. .. _service: https://github.com/googleapis/googleapis/blob/\ 050400df0fdb...
[ "def", "from_grpc", "(", "operation", ",", "operations_stub", ",", "result_type", ",", "*", "*", "kwargs", ")", ":", "refresh", "=", "functools", ".", "partial", "(", "_refresh_grpc", ",", "operations_stub", ",", "operation", ".", "name", ")", "cancel", "=",...
44.916667
0.000908
def as_json(obj: JsonObj, indent: Optional[str]=' ', **kwargs) -> str: """ Convert obj to json string representation. :param obj: pseudo 'self' :param indent: indent argument to dumps :param kwargs: other arguments for dumps :return: JSON formatted string """ return obj...
[ "def", "as_json", "(", "obj", ":", "JsonObj", ",", "indent", ":", "Optional", "[", "str", "]", "=", "' '", ",", "*", "*", "kwargs", ")", "->", "str", ":", "return", "obj", ".", "_as_json_dumps", "(", "indent", ",", "*", "*", "kwargs", ")" ]
38.333333
0.008499
def initialize_uninitialized_global_variables(sess): """ Only initializes the variables of a TensorFlow session that were not already initialized. :param sess: the TensorFlow session :return: """ # List all global variables global_vars = tf.global_variables() # Find initialized status for all variabl...
[ "def", "initialize_uninitialized_global_variables", "(", "sess", ")", ":", "# List all global variables", "global_vars", "=", "tf", ".", "global_variables", "(", ")", "# Find initialized status for all variables", "is_var_init", "=", "[", "tf", ".", "is_variable_initialized",...
35.666667
0.014304
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
[ "def", "maybe_load_model", "(", "savedir", ",", "container", ")", ":", "if", "savedir", "is", "None", ":", "return", "state_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "savedir", ",", "'training_state.pkl.zip'", ...
38.05
0.010256
def check_ordered(self): """ True if each chromosome is listed together as a chunk and if the range starts go from smallest to largest otherwise false :return: is it ordered? :rtype: bool """ sys.stderr.write("error unimplemented check_ordered\n") sys.exit() seen_chrs = set() curr_chr ...
[ "def", "check_ordered", "(", "self", ")", ":", "sys", ".", "stderr", ".", "write", "(", "\"error unimplemented check_ordered\\n\"", ")", "sys", ".", "exit", "(", ")", "seen_chrs", "=", "set", "(", ")", "curr_chr", "=", "None", "prevstart", "=", "0", "for",...
30.136364
0.017544
def _generateExtraMetricSpecs(options): """Generates the non-default metrics specified by the expGenerator params """ _metricSpecSchema = {'properties': {}} results = [] for metric in options['metrics']: for propertyName in _metricSpecSchema['properties'].keys(): _getPropertyValue(_metricSpecSchema,...
[ "def", "_generateExtraMetricSpecs", "(", "options", ")", ":", "_metricSpecSchema", "=", "{", "'properties'", ":", "{", "}", "}", "results", "=", "[", "]", "for", "metric", "in", "options", "[", "'metrics'", "]", ":", "for", "propertyName", "in", "_metricSpec...
37.166667
0.013115
def delete_where_user_id(cls, user_id): """ delete by email """ result = cls.where_user_id(user_id) if result is None: return None result.delete() return True
[ "def", "delete_where_user_id", "(", "cls", ",", "user_id", ")", ":", "result", "=", "cls", ".", "where_user_id", "(", "user_id", ")", "if", "result", "is", "None", ":", "return", "None", "result", ".", "delete", "(", ")", "return", "True" ]
30
0.009259
async def metadata_verify(config, args) -> int: """ Crawl all saved JSON metadata or online to check we have all packages if delete - generate a diff of unowned files """ all_package_files = [] # type: List[Path] loop = asyncio.get_event_loop() mirror_base = config.get("mirror", "directory") ...
[ "async", "def", "metadata_verify", "(", "config", ",", "args", ")", "->", "int", ":", "all_package_files", "=", "[", "]", "# type: List[Path]", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "mirror_base", "=", "config", ".", "get", "(", "\"mirror\...
41.766667
0.00234
def ndim(n, *args, **kwargs): """ Makes a multi-dimensional array of random floats. (Replaces RandomArray). """ thunk = kwargs.get("thunk", lambda: random.random()) if not args: return [thunk() for i in range(n)] A = [] for i in range(n): A.append( ndim(*args, thunk=thunk) ...
[ "def", "ndim", "(", "n", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "thunk", "=", "kwargs", ".", "get", "(", "\"thunk\"", ",", "lambda", ":", "random", ".", "random", "(", ")", ")", "if", "not", "args", ":", "return", "[", "thunk", "(...
29.545455
0.01791
def get_data(): """Returns combined list of tuples: [(table, column)]. List is built, based on retrieved tables, where column with name ``tenant_id`` exists. """ output = [] tables = get_tables() for table in tables: try: columns = get_columns(table) except sa.e...
[ "def", "get_data", "(", ")", ":", "output", "=", "[", "]", "tables", "=", "get_tables", "(", ")", "for", "table", "in", "tables", ":", "try", ":", "columns", "=", "get_columns", "(", "table", ")", "except", "sa", ".", "exc", ".", "NoSuchTableError", ...
24.3
0.00198
def bootstrap_plot(series, fig=None, size=50, samples=500, **kwds): """ Bootstrap plot on mean, median and mid-range statistics. The bootstrap plot is used to estimate the uncertainty of a statistic by relaying on random sampling with replacement [1]_. This function will generate bootstrapping plot...
[ "def", "bootstrap_plot", "(", "series", ",", "fig", "=", "None", ",", "size", "=", "50", ",", "samples", "=", "500", ",", "*", "*", "kwds", ")", ":", "import", "random", "import", "matplotlib", ".", "pyplot", "as", "plt", "# random.sample(ndarray, int) fai...
32.640449
0.000334
def load_nifti(filename, to='auto'): ''' load_nifti(filename) yields the Nifti1Image or Nifti2Image referened by the given filename by using the nibabel load function. The optional argument to may be used to coerce the resulting data to a particular format; the following arguments are underst...
[ "def", "load_nifti", "(", "filename", ",", "to", "=", "'auto'", ")", ":", "img", "=", "nib", ".", "load", "(", "filename", ")", "to", "=", "to", ".", "lower", "(", ")", "if", "to", "==", "'image'", ":", "return", "img", "elif", "to", "==", "'data...
46.135135
0.008606
def _normalize(arr, keep_ratio=False): """Normalize an array into [0, 1].""" (x_min, y_min), (x_max, y_max) = arr.min(axis=0), arr.max(axis=0) if keep_ratio: a = 1. / max(x_max - x_min, y_max - y_min) ax = ay = a bx = .5 - .5 * a * (x_max + x_min) by = .5 - .5 * a * (y_max +...
[ "def", "_normalize", "(", "arr", ",", "keep_ratio", "=", "False", ")", ":", "(", "x_min", ",", "y_min", ")", ",", "(", "x_max", ",", "y_max", ")", "=", "arr", ".", "min", "(", "axis", "=", "0", ")", ",", "arr", ".", "max", "(", "axis", "=", "...
26.818182
0.001637
def fuse_trees(to_tree, from_tree, lib_exts=('.so', '.dylib', '.a')): """ Fuse path `from_tree` into path `to_tree` For each file in `from_tree` - check for library file extension (in `lib_exts` - if present, check if there is a file with matching relative path in `to_tree`, if so, use :func:`delocate....
[ "def", "fuse_trees", "(", "to_tree", ",", "from_tree", ",", "lib_exts", "=", "(", "'.so'", ",", "'.dylib'", ",", "'.a'", ")", ")", ":", "for", "from_dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "from_tree", ")", ":", "to_d...
43.285714
0.000538
def init_model( lang, output_dir, freqs_loc=None, clusters_loc=None, jsonl_loc=None, vectors_loc=None, prune_vectors=-1, ): """ Create a new model from raw data, like word frequencies, Brown clusters and word vectors. If vectors are provided in Word2Vec format, they can be ei...
[ "def", "init_model", "(", "lang", ",", "output_dir", ",", "freqs_loc", "=", "None", ",", "clusters_loc", "=", "None", ",", "jsonl_loc", "=", "None", ",", "vectors_loc", "=", "None", ",", "prune_vectors", "=", "-", "1", ",", ")", ":", "if", "jsonl_loc", ...
36.698113
0.000501
def get_fieldsets(self, *args, **kwargs): """Re-order fields""" result = super(EventAdmin, self).get_fieldsets(*args, **kwargs) result = list(result) fields = list(result[0][1]['fields']) for name in ('content', 'start', 'end', 'repeat', 'repeat_until', \ 'external_li...
[ "def", "get_fieldsets", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "result", "=", "super", "(", "EventAdmin", ",", "self", ")", ".", "get_fieldsets", "(", "*", "args", ",", "*", "*", "kwargs", ")", "result", "=", "list", "(",...
42.545455
0.01046
def _minute_exclusion_tree(self): """ Build an interval tree keyed by the start and end of each range of positions should be dropped from windows. (These are the minutes between an early close and the minute which would be the close based on the regular period if there were no ea...
[ "def", "_minute_exclusion_tree", "(", "self", ")", ":", "itree", "=", "IntervalTree", "(", ")", "for", "market_open", ",", "early_close", "in", "self", ".", "_minutes_to_exclude", "(", ")", ":", "start_pos", "=", "self", ".", "_find_position_of_minute", "(", "...
39.3
0.001656
def handleResponse(self, response): """Handle the response string received by KafkaProtocol. Ok, we've received the response from the broker. Find the requestId in the message, lookup & fire the deferred with the response. """ requestId = KafkaCodec.get_response_correlation_id(r...
[ "def", "handleResponse", "(", "self", ",", "response", ")", ":", "requestId", "=", "KafkaCodec", ".", "get_response_correlation_id", "(", "response", ")", "# Protect against responses coming back we didn't expect", "tReq", "=", "self", ".", "requests", ".", "pop", "("...
49.5625
0.002475
def to_dict_list(df, use_ordered_dict=True): """Transform each row to dict, and put them into a list. **中文文档** 将 ``pandas.DataFrame`` 转换成一个字典的列表。列表的长度与行数相同, 其中 每一个字典相当于表中的一行, 相当于一个 ``pandas.Series`` 对象。 """ if use_ordered_dict: dict = OrderedDict columns = df.columns data = li...
[ "def", "to_dict_list", "(", "df", ",", "use_ordered_dict", "=", "True", ")", ":", "if", "use_ordered_dict", ":", "dict", "=", "OrderedDict", "columns", "=", "df", ".", "columns", "data", "=", "list", "(", ")", "for", "tp", "in", "itertuple", "(", "df", ...
24.875
0.002421
def deconstruct(self): # pragma: no cover """ As outlined in the Django 1.7 documentation, this method tells Django how to take an instance of a new field in order to reduce it to a serialized form. This can be used to configure what arguments need to be passed to the __init__() method ...
[ "def", "deconstruct", "(", "self", ")", ":", "# pragma: no cover", "name", ",", "import_path", ",", "args", ",", "kwargs", "=", "super", "(", ")", ".", "deconstruct", "(", ")", "kwargs", "[", "'no_rendered_field'", "]", "=", "True", "return", "name", ",", ...
62.272727
0.010072
def setup(self, filters=()): """Sets up a cache of python interpreters. :param filters: A sequence of strings that constrain the interpreter compatibility for this cache, using the Requirement-style format, e.g. ``'CPython>=3', or just ['>=2.7','<3']`` for requirements agnostic to interpreter class...
[ "def", "setup", "(", "self", ",", "filters", "=", "(", ")", ")", ":", "# We filter the interpreter cache itself (and not just the interpreters we pull from it)", "# because setting up some python versions (e.g., 3<=python<3.3) crashes, and this gives us", "# an escape hatch.", "filters",...
47.027027
0.009009
def _find_device(self, idVendor, idProduct): """Find a USB device by product and vendor id.""" for bus in usb.busses(): for device in bus.devices: if (device.idVendor == idVendor and device.idProduct == idProduct): return device ...
[ "def", "_find_device", "(", "self", ",", "idVendor", ",", "idProduct", ")", ":", "for", "bus", "in", "usb", ".", "busses", "(", ")", ":", "for", "device", "in", "bus", ".", "devices", ":", "if", "(", "device", ".", "idVendor", "==", "idVendor", "and"...
40.625
0.009036
def ULT(self, o): """ Unsigned less than. :param o: The other operand :return: TrueResult(), FalseResult(), or MaybeResult() """ unsigned_bounds_1 = self._unsigned_bounds() unsigned_bounds_2 = o._unsigned_bounds() ret = [] for lb_1, ub_1 in unsi...
[ "def", "ULT", "(", "self", ",", "o", ")", ":", "unsigned_bounds_1", "=", "self", ".", "_unsigned_bounds", "(", ")", "unsigned_bounds_2", "=", "o", ".", "_unsigned_bounds", "(", ")", "ret", "=", "[", "]", "for", "lb_1", ",", "ub_1", "in", "unsigned_bounds...
30.037037
0.002389
def _calc_eddy_time(self): """ estimate the eddy turn-over time in days """ ens = 0. for j in range(self.nz): ens = .5*self.Hi[j] * self.spec_var(self.wv2*self.ph[j]) return 2.*pi*np.sqrt( self.H / ens.sum() ) / 86400
[ "def", "_calc_eddy_time", "(", "self", ")", ":", "ens", "=", "0.", "for", "j", "in", "range", "(", "self", ".", "nz", ")", ":", "ens", "=", ".5", "*", "self", ".", "Hi", "[", "j", "]", "*", "self", ".", "spec_var", "(", "self", ".", "wv2", "*...
36.571429
0.015267
def get_license(self): """ :calls: `GET /repos/:owner/:repo/license <https://developer.github.com/v3/licenses>`_ :rtype: :class:`github.ContentFile.ContentFile` """ headers, data = self._requester.requestJsonAndCheck( "GET", self.url + "/license" ...
[ "def", "get_license", "(", "self", ")", ":", "headers", ",", "data", "=", "self", ".", "_requester", ".", "requestJsonAndCheck", "(", "\"GET\"", ",", "self", ".", "url", "+", "\"/license\"", ")", "return", "github", ".", "ContentFile", ".", "ContentFile", ...
36.818182
0.009639
def iraf_phot(f,x,y,zmag=26.5,apin=10,skyin=15,skywidth=10): """Compute the magnitude of the star at location x/y""" import pyfits import re infits=pyfits.open(f,'update') f=re.sub(r'.fits$','',f) ### Get my python routines from pyraf import iraf from pyraf.irafpar import IrafParLis...
[ "def", "iraf_phot", "(", "f", ",", "x", ",", "y", ",", "zmag", "=", "26.5", ",", "apin", "=", "10", ",", "skyin", "=", "15", ",", "skywidth", "=", "10", ")", ":", "import", "pyfits", "import", "re", "infits", "=", "pyfits", ".", "open", "(", "f...
28.45283
0.0314
def valid_kbreak_matchings(start_edges, result_edges): """ A staticmethod check implementation that makes sure that degrees of vertices, that are affected by current :class:`KBreak` By the notion of k-break, it shall keep the degree of vertices in :class:`bg.breakpoint_graph.BreakpointGraph` the same, ...
[ "def", "valid_kbreak_matchings", "(", "start_edges", ",", "result_edges", ")", ":", "start_stats", "=", "Counter", "(", "vertex", "for", "vertex_pair", "in", "start_edges", "for", "vertex", "in", "vertex_pair", ")", "result_stats", "=", "Counter", "(", "vertex", ...
76.6875
0.008052
def push(self): """Binds the app context to the current context.""" self._refcnt += 1 _app_ctx_stack.push(self) appcontext_pushed.send(self.app)
[ "def", "push", "(", "self", ")", ":", "self", ".", "_refcnt", "+=", "1", "_app_ctx_stack", ".", "push", "(", "self", ")", "appcontext_pushed", ".", "send", "(", "self", ".", "app", ")" ]
34.4
0.011364
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() ...
[ "def", "_handle_api", "(", "self", ",", "handler", ",", "handler_args", ",", "handler_kwargs", ")", ":", "try", ":", "status_code", ",", "return_value", "=", "handler", "(", "*", "handler_args", ",", "*", "*", "handler_kwargs", ")", "except", "APIError", "as...
45.666667
0.009547
def calculate_hash_of_dir(directory, file_list=None): """Calculate hash of directory.""" md5_hash = md5() if not os.path.exists(directory): return -1 try: for subdir, dirs, files in os.walk(directory): for _file in files: file_path = os.path.join(subdir, _fil...
[ "def", "calculate_hash_of_dir", "(", "directory", ",", "file_list", "=", "None", ")", ":", "md5_hash", "=", "md5", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "return", "-", "1", "try", ":", "for", "subdir", "...
38.258065
0.000822
def split(self, widget, orientation): """ Split the the current widget in new SplittableTabWidget. :param widget: widget to split :param orientation: orientation of the splitter :return: the new splitter """ if widget.original: base = widget.original ...
[ "def", "split", "(", "self", ",", "widget", ",", "orientation", ")", ":", "if", "widget", ".", "original", ":", "base", "=", "widget", ".", "original", "else", ":", "base", "=", "widget", "clone", "=", "base", ".", "split", "(", ")", "if", "not", "...
37.651163
0.001204
def page_size(self) -> int: """ A property that returns how large a page is, calculated from the paginator properties. If this exceeds `max_page_size`, an exception is raised upon instantiation. """ page_count = self.page_count return self.paginator.max_size + len(f'\nPa...
[ "def", "page_size", "(", "self", ")", "->", "int", ":", "page_count", "=", "self", ".", "page_count", "return", "self", ".", "paginator", ".", "max_size", "+", "len", "(", "f'\\nPage {page_count}/{page_count}'", ")" ]
42.875
0.014286
def verify(value, msg): """ C-style validator Keyword arguments: value -- dictionary to validate (required) msg -- the protobuf schema to validate against (required) Returns: True: If valid input False: If invalid input """ return bool(value) and \ converts_t...
[ "def", "verify", "(", "value", ",", "msg", ")", ":", "return", "bool", "(", "value", ")", "and", "converts_to_proto", "(", "value", ",", "msg", ")", "and", "successfuly_encodes", "(", "msg", ")", "and", "special_typechecking", "(", "value", ",", "msg", "...
26
0.009281
def _log_sum_sq(x, axis=None): """Computes log(sum(x**2)).""" return tf.reduce_logsumexp( input_tensor=2. * tf.math.log(tf.abs(x)), axis=axis)
[ "def", "_log_sum_sq", "(", "x", ",", "axis", "=", "None", ")", ":", "return", "tf", ".", "reduce_logsumexp", "(", "input_tensor", "=", "2.", "*", "tf", ".", "math", ".", "log", "(", "tf", ".", "abs", "(", "x", ")", ")", ",", "axis", "=", "axis", ...
37.25
0.019737
def iterCodons(self) : """iterates through the codons""" for i in range(len(self.cDNA)/3) : yield self.getCodon(i)
[ "def", "iterCodons", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "cDNA", ")", "/", "3", ")", ":", "yield", "self", ".", "getCodon", "(", "i", ")" ]
29.5
0.057851
def generate_contrast(problem): """Generates the raw sample from the problem file Arguments ========= problem : dict The problem definition """ num_vars = problem['num_vars'] # Find the smallest n, such that num_vars < k k = [2 ** n for n in range(16)] k_chosen = 2 ** find...
[ "def", "generate_contrast", "(", "problem", ")", ":", "num_vars", "=", "problem", "[", "'num_vars'", "]", "# Find the smallest n, such that num_vars < k", "k", "=", "[", "2", "**", "n", "for", "n", "in", "range", "(", "16", ")", "]", "k_chosen", "=", "2", ...
24.210526
0.002092
def check_and_order_id_inputs(rid, ridx, cid, cidx, row_meta_df, col_meta_df): """ Makes sure that (if entered) id inputs entered are of one type (string id or index) Input: - rid (list or None): if not None, a list of rids - ridx (list or None): if not None, a list of indexes - cid ...
[ "def", "check_and_order_id_inputs", "(", "rid", ",", "ridx", ",", "cid", ",", "cidx", ",", "row_meta_df", ",", "col_meta_df", ")", ":", "(", "row_type", ",", "row_ids", ")", "=", "check_id_idx_exclusivity", "(", "rid", ",", "ridx", ")", "(", "col_type", ",...
45.45
0.002155