text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def parse_tag (self, tag, attr, value, name, base): """Add given url data to url list.""" assert isinstance(tag, unicode), repr(tag) assert isinstance(attr, unicode), repr(attr) assert isinstance(name, unicode), repr(name) assert isinstance(base, unicode), repr(base) asse...
[ "def", "parse_tag", "(", "self", ",", "tag", ",", "attr", ",", "value", ",", "name", ",", "base", ")", ":", "assert", "isinstance", "(", "tag", ",", "unicode", ")", ",", "repr", "(", "tag", ")", "assert", "isinstance", "(", "attr", ",", "unicode", ...
44.111111
0.002465
def _fetch_app_role_token(vault_url, role_id, secret_id): """Get a Vault token, using the RoleID and SecretID""" url = _url_joiner(vault_url, 'v1/auth/approle/login') resp = requests.post(url, data={'role_id': role_id, 'secret_id': secret_id}) resp.raise_for_status() data = resp....
[ "def", "_fetch_app_role_token", "(", "vault_url", ",", "role_id", ",", "secret_id", ")", ":", "url", "=", "_url_joiner", "(", "vault_url", ",", "'v1/auth/approle/login'", ")", "resp", "=", "requests", ".", "post", "(", "url", ",", "data", "=", "{", "'role_id...
53.777778
0.00813
def pressision_try(orbitals, U, beta, step): """perform a better initial guess of lambda no improvement""" mu, lam = main(orbitals, U, beta, step) mu2, lam2 = linspace(0, U*orbitals, step), zeros(step) for i in range(99): lam2[i+1] = fsolve(restriction, lam2[i], (mu2[i+1], orbitals, U, be...
[ "def", "pressision_try", "(", "orbitals", ",", "U", ",", "beta", ",", "step", ")", ":", "mu", ",", "lam", "=", "main", "(", "orbitals", ",", "U", ",", "beta", ",", "step", ")", "mu2", ",", "lam2", "=", "linspace", "(", "0", ",", "U", "*", "orbi...
45.555556
0.002392
def fetch_order(self, order_id: str) -> Order: """Fetch an order by ID.""" return self._fetch(f'order id={order_id}', exc=OrderNotFound)(self._order)(order_id)
[ "def", "fetch_order", "(", "self", ",", "order_id", ":", "str", ")", "->", "Order", ":", "return", "self", ".", "_fetch", "(", "f'order id={order_id}'", ",", "exc", "=", "OrderNotFound", ")", "(", "self", ".", "_order", ")", "(", "order_id", ")" ]
57.666667
0.017143
def binary_operation_logical(self, rule, left, right, **kwargs): """ Implementation of :py:func:`pynspect.traversers.RuleTreeTraverser.binary_operation_logical` interface. """ return self.evaluate_binop_logical(rule.operation, left, right, **kwargs)
[ "def", "binary_operation_logical", "(", "self", ",", "rule", ",", "left", ",", "right", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "evaluate_binop_logical", "(", "rule", ".", "operation", ",", "left", ",", "right", ",", "*", "*", "kwargs",...
55.4
0.014235
def WriteFile(self, printer): """Write the messages file to out.""" self.Validate() extended_descriptor.WritePythonFile( self.__file_descriptor, self.__package, self.__client_info.version, printer)
[ "def", "WriteFile", "(", "self", ",", "printer", ")", ":", "self", ".", "Validate", "(", ")", "extended_descriptor", ".", "WritePythonFile", "(", "self", ".", "__file_descriptor", ",", "self", ".", "__package", ",", "self", ".", "__client_info", ".", "versio...
40
0.008163
def res_set_to_phenotype(res_set, full_list): """ Converts a set of strings indicating resources to a binary string where the positions of 1s indicate which resources are present. Inputs: res_set - a set of strings indicating which resources are present full_list - a list of strings indicat...
[ "def", "res_set_to_phenotype", "(", "res_set", ",", "full_list", ")", ":", "full_list", "=", "list", "(", "full_list", ")", "phenotype", "=", "len", "(", "full_list", ")", "*", "[", "\"0\"", "]", "for", "i", "in", "range", "(", "len", "(", "full_list", ...
33.730769
0.001109
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the ExtensionInformation object to a stream. Args: ostream (Stream): A data stream in which to encode object data, supporting a write method; usually a BytearrayStream obje...
[ "def", "write", "(", "self", ",", "ostream", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "tstream", "=", "BytearrayStream", "(", ")", "self", ".", "extension_name", ".", "write", "(", "tstream", ",", "kmip_version", "=...
39.692308
0.001892
def configure_sources(update=False, sources_var='install_sources', keys_var='install_keys'): """Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sourc...
[ "def", "configure_sources", "(", "update", "=", "False", ",", "sources_var", "=", "'install_sources'", ",", "keys_var", "=", "'install_keys'", ")", ":", "sources", "=", "safe_load", "(", "(", "config", "(", "sources_var", ")", "or", "''", ")", ".", "strip", ...
32.564103
0.000765
def inverseHistogram(hist, bin_range): """sample data from given histogram and min, max values within range Returns: np.array: data that would create the same histogram as given """ data = hist.astype(float) / np.min(hist[np.nonzero(hist)]) new_data = np.empty(shape=np.sum(data, dtype=int))...
[ "def", "inverseHistogram", "(", "hist", ",", "bin_range", ")", ":", "data", "=", "hist", ".", "astype", "(", "float", ")", "/", "np", ".", "min", "(", "hist", "[", "np", ".", "nonzero", "(", "hist", ")", "]", ")", "new_data", "=", "np", ".", "emp...
34.571429
0.002012
def next(self): """Returns the next line from this input reader as (lineinfo, line) tuple. Returns: The next input from this input reader, in the form of a 2-tuple. The first element of the tuple describes the source, it is itself a tuple (blobkey, filenumber, byteoffset). The second ...
[ "def", "next", "(", "self", ")", ":", "if", "not", "self", ".", "_filestream", ":", "if", "not", "self", ".", "_zip", ":", "self", ".", "_zip", "=", "zipfile", ".", "ZipFile", "(", "self", ".", "_reader", "(", "self", ".", "_blob_key", ")", ")", ...
37.815789
0.00882
def git_clone(sub_repo, branch, commit = None, cwd = None, no_submodules = False): ''' This clone mimicks the way Travis-CI clones a project's repo. So far Travis-CI is the most limiting in the sense of only fetching partial history of the repo. ''' if not cwd: ...
[ "def", "git_clone", "(", "sub_repo", ",", "branch", ",", "commit", "=", "None", ",", "cwd", "=", "None", ",", "no_submodules", "=", "False", ")", ":", "if", "not", "cwd", ":", "cwd", "=", "cwd", "=", "os", ".", "getcwd", "(", ")", "root_dir", "=", ...
43.911765
0.029489
def get_read_cache(self): """Returns the read cache for this setup, creating it if necessary. Returns None if no read cache is configured. """ if self._options.read_from and not self._read_cache: cache_spec = self._resolve(self._sanitize_cache_spec(self._options.read_from)) if cache_spec: ...
[ "def", "get_read_cache", "(", "self", ")", ":", "if", "self", ".", "_options", ".", "read_from", "and", "not", "self", ".", "_read_cache", ":", "cache_spec", "=", "self", ".", "_resolve", "(", "self", ".", "_sanitize_cache_spec", "(", "self", ".", "_option...
42.090909
0.012685
def fetch(backend_class, backend_args, category, filter_classified=False, manager=None): """Fetch items using the given backend. Generator to get items using the given backend class. When an archive manager is given, this function will store the fetched items in an `Archive`. If an exception ...
[ "def", "fetch", "(", "backend_class", ",", "backend_args", ",", "category", ",", "filter_classified", "=", "False", ",", "manager", "=", "None", ")", ":", "init_args", "=", "find_signature_parameters", "(", "backend_class", ".", "__init__", ",", "backend_args", ...
37.488889
0.000578
def combine_hla_fqs(hlas, out_file, data): """OptiType performs best on a combination of all extracted HLAs. """ if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") as out_handle: for hla_type, hla_fq in hl...
[ "def", "combine_hla_fqs", "(", "hlas", ",", "out_file", ",", "data", ")", ":", "if", "not", "utils", ".", "file_exists", "(", "out_file", ")", ":", "with", "file_transaction", "(", "data", ",", "out_file", ")", "as", "tx_out_file", ":", "with", "open", "...
46.272727
0.001927
def get_print_info(n_step, fill=None): """ Returns the max. number of digits in range(n_step) and the corresponding format string. Examples: >>> get_print_info(11) (2, '%2d') >>> get_print_info(8) (1, '%1d') >>> get_print_info(100) (2, '%2d') >>> get_print_info(101) (3,...
[ "def", "get_print_info", "(", "n_step", ",", "fill", "=", "None", ")", ":", "if", "n_step", ">", "1", ":", "n_digit", "=", "int", "(", "nm", ".", "log10", "(", "n_step", "-", "1", ")", "+", "1", ")", "if", "fill", "is", "None", ":", "format", "...
23.259259
0.001529
def list_registered(self, parent_path) : "lists all the object paths for which you have ObjectPathVTable handlers registered." child_entries = ct.POINTER(ct.c_char_p)() if not dbus.dbus_connection_list_registered(self._dbobj, parent_path.encode(), ct.byref(child_entries)) : raise Cal...
[ "def", "list_registered", "(", "self", ",", "parent_path", ")", ":", "child_entries", "=", "ct", ".", "POINTER", "(", "ct", ".", "c_char_p", ")", "(", ")", "if", "not", "dbus", ".", "dbus_connection_list_registered", "(", "self", ".", "_dbobj", ",", "paren...
37.388889
0.015942
def unlock(self): '''Unlock card with SCardEndTransaction.''' component = self.component while True: if isinstance( component, smartcard.pcsc.PCSCCardConnection.PCSCCardConnection): hresult = SCardEndTransaction(component.hcard,...
[ "def", "unlock", "(", "self", ")", ":", "component", "=", "self", ".", "component", "while", "True", ":", "if", "isinstance", "(", "component", ",", "smartcard", ".", "pcsc", ".", "PCSCCardConnection", ".", "PCSCCardConnection", ")", ":", "hresult", "=", "...
39.047619
0.002381
def stop_sync(self): """Synchronously stop this adapter and release all resources.""" if self._control_thread is not None and self._control_thread.is_alive(): self._control_thread.stop() self._control_thread.join() if self.jlink is not None: self.jlink.close...
[ "def", "stop_sync", "(", "self", ")", ":", "if", "self", ".", "_control_thread", "is", "not", "None", "and", "self", ".", "_control_thread", ".", "is_alive", "(", ")", ":", "self", ".", "_control_thread", ".", "stop", "(", ")", "self", ".", "_control_thr...
34.888889
0.009317
def delete_webhook(self, id, **data): """ DELETE /webhooks/:id/ Deletes the specified :format:`webhook` object. """ return self.delete("/webhooks/{0}/".format(id), data=data)
[ "def", "delete_webhook", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "delete", "(", "\"/webhooks/{0}/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
31
0.013453
def __is_noncopyable_single(class_, already_visited_cls_vars=None): """ Implementation detail. Checks if the class is non copyable, without considering the base classes. Args: class_ (declarations.class_t): the class to be checked already_visited_cls_vars (list): optional list of vars ...
[ "def", "__is_noncopyable_single", "(", "class_", ",", "already_visited_cls_vars", "=", "None", ")", ":", "# It is not enough to check base classes, we should also to check", "# member variables.", "logger", "=", "utils", ".", "loggers", ".", "cxx_parser", "if", "has_copy_cons...
34.954545
0.000633
def diff(self, periods=1, axis=0): """ First discrete difference of element. Calculates the difference of a DataFrame element compared with another element in the DataFrame (default is the element in the same column of the previous row). Parameters ---------- ...
[ "def", "diff", "(", "self", ",", "periods", "=", "1", ",", "axis", "=", "0", ")", ":", "bm_axis", "=", "self", ".", "_get_block_manager_axis", "(", "axis", ")", "new_data", "=", "self", ".", "_data", ".", "diff", "(", "n", "=", "periods", ",", "axi...
26.277778
0.000815
def mod_root(a, p): """ Return a root of `a' modulo p """ if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> ...
[ "def", "mod_root", "(", "a", ",", "p", ")", ":", "if", "a", "==", "0", ":", "return", "0", "if", "not", "mod_issquare", "(", "a", ",", "p", ")", ":", "raise", "ValueError", "n", "=", "2", "while", "mod_issquare", "(", "n", ",", "p", ")", ":", ...
19.848485
0.001456
def get_locations(self, url): """Get valid location header values from responses. :param url: a URL address. If a HEAD request sent to it fails because the address has invalid schema, times out or there is a connection error, the generator yields nothing. :returns: valid redirec...
[ "def", "get_locations", "(", "self", ",", "url", ")", ":", "if", "not", "is_valid_url", "(", "url", ")", ":", "raise", "InvalidURLError", "(", "'{} is not a valid URL'", ".", "format", "(", "url", ")", ")", "try", ":", "response", "=", "self", ".", "sess...
42.483871
0.001485
def callstop(*args, **kwargs): """Limits the number of times a function can be called. Can be used as a function decorator or as a function that accepts another function. If used as a function, it returns a new function that will be call limited. **Params**: - func (func) - Function to call. Only...
[ "def", "callstop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "limit", "=", "kwargs", ".", "get", "(", "'limit'", ",", "1", ")", "def", "decor", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
31.038462
0.002404
def to_valid_rgb(t, decorrelate=False, sigmoid=True): """Transform inner dimension of t to valid rgb colors. In practice this consistes of two parts: (1) If requested, transform the colors from a decorrelated color space to RGB. (2) Constrain the color channels to be in [0,1], either using a sigmoid f...
[ "def", "to_valid_rgb", "(", "t", ",", "decorrelate", "=", "False", ",", "sigmoid", "=", "True", ")", ":", "if", "decorrelate", ":", "t", "=", "_linear_decorelate_color", "(", "t", ")", "if", "decorrelate", "and", "not", "sigmoid", ":", "t", "+=", "color_...
33.703704
0.011752
def join(self, people): """ Join the local audience (a config message should be received on success) Validates that there are people to join and that each of them has a valid unique id :param people: Which people does this sensor have :type people: list[paps.pers...
[ "def", "join", "(", "self", ",", "people", ")", ":", "tries", "=", "0", "if", "not", "people", ":", "raise", "SensorJoinException", "(", "\"No people given\"", ")", "ids", "=", "set", "(", ")", "for", "person", "in", "people", ":", "if", "not", "person...
39.08
0.000999
def register_event(self, pattern, callback=None): """register an event. See :class:`~panoramisk.message.Message`: .. code-block:: python >>> def callback(manager, event): ... print(manager, event) >>> manager = Manager() >>> manager.register_event('M...
[ "def", "register_event", "(", "self", ",", "pattern", ",", "callback", "=", "None", ")", ":", "def", "_register_event", "(", "callback", ")", ":", "if", "not", "self", ".", "callbacks", "[", "pattern", "]", ":", "self", ".", "patterns", ".", "append", ...
34.666667
0.001871
def create(path, venv_bin=None, system_site_packages=False, distribute=False, clear=False, python=None, extra_search_dir=None, never_download=None, prompt=None, pip=False, symlinks=None, upgrade=None...
[ "def", "create", "(", "path", ",", "venv_bin", "=", "None", ",", "system_site_packages", "=", "False", ",", "distribute", "=", "False", ",", "clear", "=", "False", ",", "python", "=", "None", ",", "extra_search_dir", "=", "None", ",", "never_download", "="...
35.712687
0.000712
def paramnames(co): """ Get the parameter names from a pycode object. Returns a 4-tuple of (args, kwonlyargs, varargs, varkwargs). varargs and varkwargs will be None if the function doesn't take *args or **kwargs, respectively. """ flags = co.co_flags varnames = co.co_varnames argc...
[ "def", "paramnames", "(", "co", ")", ":", "flags", "=", "co", ".", "co_flags", "varnames", "=", "co", ".", "co_varnames", "argcount", ",", "kwonlyargcount", "=", "co", ".", "co_argcount", ",", "co", ".", "co_kwonlyargcount", "total", "=", "argcount", "+", ...
29.583333
0.001364
def distribute_ready(self): '''Distribute the ready state across all of the connections''' connections = [c for c in self.connections() if c.alive()] if len(connections) > self._max_in_flight: raise NotImplementedError( 'Max in flight must be greater than number of co...
[ "def", "distribute_ready", "(", "self", ")", ":", "connections", "=", "[", "c", "for", "c", "in", "self", ".", "connections", "(", ")", "if", "c", ".", "alive", "(", ")", "]", "if", "len", "(", "connections", ")", ">", "self", ".", "_max_in_flight", ...
53.411765
0.002165
def parse_params(self, eps=0.3, eps_iter=0.05, nb_iter=10, y=None, ord=np.inf, clip_min=None, clip_max=None, y_target=None, rand_init=None, ...
[ "def", "parse_params", "(", "self", ",", "eps", "=", "0.3", ",", "eps_iter", "=", "0.05", ",", "nb_iter", "=", "10", ",", "y", "=", "None", ",", "ord", "=", "np", ".", "inf", ",", "clip_min", "=", "None", ",", "clip_max", "=", "None", ",", "y_tar...
37.2
0.00823
def _verify_safe(self, this): """Make sure we are not trying to write an invalid character.""" context = self._context if context & contexts.FAIL_NEXT: return False if context & contexts.WIKILINK_TITLE: if this == "]" or this == "{": self._context ...
[ "def", "_verify_safe", "(", "self", ",", "this", ")", ":", "context", "=", "self", ".", "_context", "if", "context", "&", "contexts", ".", "FAIL_NEXT", ":", "return", "False", "if", "context", "&", "contexts", ".", "WIKILINK_TITLE", ":", "if", "this", "=...
42.435484
0.000743
def repository_exists(self): """ Determine if the repository exists. :rtype: bool """ schema = self.get_connection().get_schema_builder() return schema.has_table(self._table)
[ "def", "repository_exists", "(", "self", ")", ":", "schema", "=", "self", ".", "get_connection", "(", ")", ".", "get_schema_builder", "(", ")", "return", "schema", ".", "has_table", "(", "self", ".", "_table", ")" ]
24
0.008929
def range(self, chromosome, start, stop, exact=False): """ Shortcut to do range filters on genomic datasets. """ return self._clone( filters=[GenomicFilter(chromosome, start, stop, exact)])
[ "def", "range", "(", "self", ",", "chromosome", ",", "start", ",", "stop", ",", "exact", "=", "False", ")", ":", "return", "self", ".", "_clone", "(", "filters", "=", "[", "GenomicFilter", "(", "chromosome", ",", "start", ",", "stop", ",", "exact", "...
38
0.008584
def packages( state, host, packages=None, present=True, latest=False, update=False, clean=False, ): ''' Install/remove/update yum packages & updates. + packages: list of packages to ensure + present: whether the packages should be installed + latest: whether to upgrade packages without a sp...
[ "def", "packages", "(", "state", ",", "host", ",", "packages", "=", "None", ",", "present", "=", "True", ",", "latest", "=", "False", ",", "update", "=", "False", ",", "clean", "=", "False", ",", ")", ":", "if", "clean", ":", "yield", "'yum clean all...
26.096774
0.001192
def setup_cmd_parser(cls): """Returns the Groupsio argument parser.""" parser = BackendCommandArgumentParser(cls.BACKEND.CATEGORIES, from_date=True, token_auth=True) # Backend token is required ...
[ "def", "setup_cmd_parser", "(", "cls", ")", ":", "parser", "=", "BackendCommandArgumentParser", "(", "cls", ".", "BACKEND", ".", "CATEGORIES", ",", "from_date", "=", "True", ",", "token_auth", "=", "True", ")", "# Backend token is required", "action", "=", "pars...
40.791667
0.001996
def post_manager_view(model, view="PostManager", template_dir=None): """ :param PostStruct: """ PostStruct = model.PostStruct Pylot.context_(COMPONENT_POST_MANAGER=True) if not template_dir: template_dir = "Pylot/PostManager" template_page = template_dir + "/%s.html" class Po...
[ "def", "post_manager_view", "(", "model", ",", "view", "=", "\"PostManager\"", ",", "template_dir", "=", "None", ")", ":", "PostStruct", "=", "model", ".", "PostStruct", "Pylot", ".", "context_", "(", "COMPONENT_POST_MANAGER", "=", "True", ")", "if", "not", ...
38.763804
0.001466
def trace_generator(trace, start=0, stop=None, step=1): """Return a generator returning values from the object's trace. Ex: T = trace_generator(theta.trace) T.next() for t in T:... """ i = start stop = stop or np.inf size = min(trace.length(), stop) while i < size: index...
[ "def", "trace_generator", "(", "trace", ",", "start", "=", "0", ",", "stop", "=", "None", ",", "step", "=", "1", ")", ":", "i", "=", "start", "stop", "=", "stop", "or", "np", ".", "inf", "size", "=", "min", "(", "trace", ".", "length", "(", ")"...
25.933333
0.002481
def collect_compare_into(left, right, added, removed, altered, same): """ collect the results of compare into the given lists (or None if you do not wish to collect results of that type. Returns a tuple of (added, removed, altered, same) """ for event, filename in compare(left, right): ...
[ "def", "collect_compare_into", "(", "left", ",", "right", ",", "added", ",", "removed", ",", "altered", ",", "same", ")", ":", "for", "event", ",", "filename", "in", "compare", "(", "left", ",", "right", ")", ":", "if", "event", "==", "LEFT", ":", "g...
24.222222
0.001471
def api_orgas(request, key=None, hproPk=None): """Return the list of organizations pk""" if not check_api_key(request, key, hproPk): return HttpResponseForbidden list_orgas = [] if settings.PIAPI_STANDALONE: list_orgas = [{'id': -1, 'name': 'EBU', 'codops': 'ZZEBU'}, ...
[ "def", "api_orgas", "(", "request", ",", "key", "=", "None", ",", "hproPk", "=", "None", ")", ":", "if", "not", "check_api_key", "(", "request", ",", "key", ",", "hproPk", ")", ":", "return", "HttpResponseForbidden", "list_orgas", "=", "[", "]", "if", ...
35.172414
0.001908
def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Return RDS instance details. CLI example:: salt myminion boto_rds.describe myrds ''' res = __salt__['boto_rds.exists'](name, tags, region, key, keyid, pro...
[ "def", "describe", "(", "name", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "res", "=", "__salt__", "[", "'boto_rds.exists'", "]", "(", "name", ","...
39.583333
0.000514
def get_table(self): """ Get the table """ buffer_length = self.__get_table_size() returned_buffer_length = ctypes.wintypes.DWORD(buffer_length) buffer = ctypes.create_string_buffer(buffer_length) pointer_type = ctypes.POINTER(self.structure) table_p = ctypes.cast(buffer, pointer_type) res = self.meth...
[ "def", "get_table", "(", "self", ")", ":", "buffer_length", "=", "self", ".", "__get_table_size", "(", ")", "returned_buffer_length", "=", "ctypes", ".", "wintypes", ".", "DWORD", "(", "buffer_length", ")", "buffer", "=", "ctypes", ".", "create_string_buffer", ...
35.692308
0.029412
def download_and_parse_mnist_file(fname, target_dir=None, force=False): """Download the IDX file named fname from the URL specified in dataset_url and return it as a numpy array. Parameters ---------- fname : str File name to download and parse target_dir : str Directory where ...
[ "def", "download_and_parse_mnist_file", "(", "fname", ",", "target_dir", "=", "None", ",", "force", "=", "False", ")", ":", "fname", "=", "download_file", "(", "fname", ",", "target_dir", "=", "target_dir", ",", "force", "=", "force", ")", "fopen", "=", "g...
30
0.001346
def dict2namedtuple(*args, **kwargs): """ Helper function to create a :class:`namedtuple` from a dictionary. Example: >>> t = dict2namedtuple(foo=1, bar="hello") >>> assert t.foo == 1 and t.bar == "hello" >>> t = dict2namedtuple([("foo", 1), ("bar", "hello")]) >>> assert t...
[ "def", "dict2namedtuple", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "d", "=", "collections", ".", "OrderedDict", "(", "*", "args", ")", "d", ".", "update", "(", "*", "*", "kwargs", ")", "return", "collections", ".", "namedtuple", "(", "typ...
35.923077
0.002086
def render(self, rect, data): """Draws the cells in grid.""" size = self.get_minimum_size(data) # Find how much extra space we have. extra_width = rect.w - size.x extra_height = rect.h - size.y # Distribute the extra space into the correct rows and columns. if s...
[ "def", "render", "(", "self", ",", "rect", ",", "data", ")", ":", "size", "=", "self", ".", "get_minimum_size", "(", "data", ")", "# Find how much extra space we have.", "extra_width", "=", "rect", ".", "w", "-", "size", ".", "x", "extra_height", "=", "rec...
40.407895
0.000636
def IterIfaddrs(ifaddrs): """Iterates over contents of the intrusive linked list of `ifaddrs`. Args: ifaddrs: A pointer to the first node of `ifaddrs` linked list. Can be NULL. Yields: Instances of `Ifaddr`. """ precondition.AssertOptionalType(ifaddrs, ctypes.POINTER(Ifaddrs)) while ifaddrs: ...
[ "def", "IterIfaddrs", "(", "ifaddrs", ")", ":", "precondition", ".", "AssertOptionalType", "(", "ifaddrs", ",", "ctypes", ".", "POINTER", "(", "Ifaddrs", ")", ")", "while", "ifaddrs", ":", "yield", "ifaddrs", ".", "contents", "ifaddrs", "=", "ifaddrs", ".", ...
26.357143
0.010471
def _update_power_status(self, message=None, status=None): """ Uses the provided message to update the AC power state. :param message: message to use to update :type message: :py:class:`~alarmdecoder.messages.Message` :param status: power status, overrides message bits. ...
[ "def", "_update_power_status", "(", "self", ",", "message", "=", "None", ",", "status", "=", "None", ")", ":", "power_status", "=", "status", "if", "isinstance", "(", "message", ",", "Message", ")", ":", "power_status", "=", "message", ".", "ac_power", "if...
32.4
0.002398
def get_all(self, name, default=None): """make cookie python 3 version use this instead of getheaders""" if default is None: default = [] return self._headers.get_list(name) or default
[ "def", "get_all", "(", "self", ",", "name", ",", "default", "=", "None", ")", ":", "if", "default", "is", "None", ":", "default", "=", "[", "]", "return", "self", ".", "_headers", ".", "get_list", "(", "name", ")", "or", "default" ]
43.2
0.009091
def check_auth(): """ Check are we authorised :return: True if we authorised False if no auth provided exception if provided auth is wrong """ if get_oauth_token(): auth_info = get_auth_info() if not auth_info: raise MissingTokenInfoException("Could not ge...
[ "def", "check_auth", "(", ")", ":", "if", "get_oauth_token", "(", ")", ":", "auth_info", "=", "get_auth_info", "(", ")", "if", "not", "auth_info", ":", "raise", "MissingTokenInfoException", "(", "\"Could not get token info\"", ")", "if", "datetime", ".", "now", ...
29.913043
0.001408
def evalfunc(cls, func, *args, **kwargs): """Evaluate a function with error propagation. Inputs: ------- ``func``: callable this is the function to be evaluated. Should return either a number or a np.ndarray. ``*args``: other positional ar...
[ "def", "evalfunc", "(", "cls", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "do_random", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "cls", ")", ":", "return", "x", ".", "random", "(", ")", "else", ":", ...
41.590164
0.001925
def copy(self): """ Copies the current queue items. """ copy = self._queue.copy() result = list() while not copy.empty(): result.append(copy.get_nowait()) return result
[ "def", "copy", "(", "self", ")", ":", "copy", "=", "self", ".", "_queue", ".", "copy", "(", ")", "result", "=", "list", "(", ")", "while", "not", "copy", ".", "empty", "(", ")", ":", "result", ".", "append", "(", "copy", ".", "get_nowait", "(", ...
26.75
0.00905
def run(cmd_str,cwd='.',verbose=False): """ an OS agnostic function to execute command Parameters ---------- cmd_str : str the str to execute with os.system() cwd : str the directory to execute the command in verbose : bool flag to echo to stdout complete cmd str ...
[ "def", "run", "(", "cmd_str", ",", "cwd", "=", "'.'", ",", "verbose", "=", "False", ")", ":", "warnings", ".", "warn", "(", "\"run() has moved to pyemu.os_utils\"", ",", "PyemuWarning", ")", "pyemu", ".", "os_utils", ".", "run", "(", "cmd_str", "=", "cmd_s...
23.310345
0.008523
def _release_line(c): """ Examine current repo state to determine what type of release to prep. :returns: A two-tuple of ``(branch-name, line-type)`` where: - ``branch-name`` is the current branch name, e.g. ``1.1``, ``master``, ``gobbledygook`` (or, usually, ``HEAD`` if not on a...
[ "def", "_release_line", "(", "c", ")", ":", "# TODO: I don't _think_ this technically overlaps with Releases (because", "# that only ever deals with changelog contents, and therefore full release", "# version numbers) but in case it does, move it there sometime.", "# TODO: this and similar calls i...
46.028571
0.000608
def local(args: arg(container=list), cd=None, environ: arg(type=dict) = None, replace_env=False, paths=(), shell: arg(type=bool) = None, stdout: arg(type=StreamOptions) = None, stderr: arg(type=StreamOptions) = None, echo=False, r...
[ "def", "local", "(", "args", ":", "arg", "(", "container", "=", "list", ")", ",", "cd", "=", "None", ",", "environ", ":", "arg", "(", "type", "=", "dict", ")", "=", "None", ",", "replace_env", "=", "False", ",", "paths", "=", "(", ")", ",", "sh...
30.429907
0.000297
def try_to_create_directory(directory_path): """Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create. """ logger = logging.getLogger("ray") directory_path = os.path.expanduser(directory_path) if not os.path.exists(di...
[ "def", "try_to_create_directory", "(", "directory_path", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"ray\"", ")", "directory_path", "=", "os", ".", "path", ".", "expanduser", "(", "directory_path", ")", "if", "not", "os", ".", "path", ".", ...
40.064516
0.000786
def transformer_revnet_base(): """Base hparams for TransformerRevnet.""" hparams = transformer.transformer_big() # Use settings from transformer_n_da hparams.layer_preprocess_sequence = "n" hparams.layer_postprocess_sequence = "da" hparams.learning_rate = 0.4 return hparams
[ "def", "transformer_revnet_base", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_big", "(", ")", "# Use settings from transformer_n_da", "hparams", ".", "layer_preprocess_sequence", "=", "\"n\"", "hparams", ".", "layer_postprocess_sequence", "=", "\"da\""...
28.1
0.027586
def _qnwcheb1(n, a, b): """ Compute univariate Guass-Checbychev quadrature nodes and weights Parameters ---------- n : int The number of nodes a : int The lower endpoint b : int The upper endpoint Returns ------- nodes : np.ndarray(dtype=float) ...
[ "def", "_qnwcheb1", "(", "n", ",", "a", ",", "b", ")", ":", "nodes", "=", "(", "b", "+", "a", ")", "/", "2", "-", "(", "b", "-", "a", ")", "/", "2", "*", "np", ".", "cos", "(", "np", ".", "pi", "/", "n", "*", "np", ".", "linspace", "(...
23.586957
0.000885
def _get_cpu_info_from_kstat(): ''' Returns the CPU info gathered from isainfo and kstat. Returns {} if isainfo or kstat are not found. ''' try: # Just return {} if there is no isainfo or kstat if not DataSource.has_isainfo() or not DataSource.has_kstat(): return {} # If isainfo fails return {} returnc...
[ "def", "_get_cpu_info_from_kstat", "(", ")", ":", "try", ":", "# Just return {} if there is no isainfo or kstat", "if", "not", "DataSource", ".", "has_isainfo", "(", ")", "or", "not", "DataSource", ".", "has_kstat", "(", ")", ":", "return", "{", "}", "# If isainfo...
30.152542
0.039194
def get_token(self, user_id): """ Get user token Checks if a custom token implementation is registered and uses that. Otherwise falls back to default token implementation. Returns a string token on success. :param user_id: int, user id :return: str """ ...
[ "def", "get_token", "(", "self", ",", "user_id", ")", ":", "if", "not", "self", ".", "jwt_implementation", ":", "return", "self", ".", "default_token_implementation", "(", "user_id", ")", "try", ":", "implementation", "=", "import_string", "(", "self", ".", ...
35.681818
0.002481
def _getReportItem(itemName, results): """ Get a specific item by name out of the results dict. The format of itemName is a string of dictionary keys separated by colons, each key being one level deeper into the results dict. For example, 'key1:key2' would fetch results['key1']['key2']. If itemName is not...
[ "def", "_getReportItem", "(", "itemName", ",", "results", ")", ":", "subKeys", "=", "itemName", ".", "split", "(", "':'", ")", "subResults", "=", "results", "for", "subKey", "in", "subKeys", ":", "subResults", "=", "subResults", "[", "subKey", "]", "return...
27.111111
0.011881
def attach(self): """Attach strategy to its sensor and send initial update.""" s = self._sensor self.update(s, s.read()) self._sensor.attach(self)
[ "def", "attach", "(", "self", ")", ":", "s", "=", "self", ".", "_sensor", "self", ".", "update", "(", "s", ",", "s", ".", "read", "(", ")", ")", "self", ".", "_sensor", ".", "attach", "(", "self", ")" ]
34.8
0.011236
def sum(self, other): """sum(x, y) = x(t) + y(t).""" return TimeSeries.merge( [self, other], operation=operations.ignorant_sum )
[ "def", "sum", "(", "self", ",", "other", ")", ":", "return", "TimeSeries", ".", "merge", "(", "[", "self", ",", "other", "]", ",", "operation", "=", "operations", ".", "ignorant_sum", ")" ]
32
0.012195
def do_exec(config, config_dir): """ CLI action "process the feed from specified configuration". """ if not os.path.exists(config_dir): print "Configuration '{}' does not exist.".format(config) exit(1) print "The parser for '{}' config has been initialized.".format(config) conf...
[ "def", "do_exec", "(", "config", ",", "config_dir", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "config_dir", ")", ":", "print", "\"Configuration '{}' does not exist.\"", ".", "format", "(", "config", ")", "exit", "(", "1", ")", "print", ...
33.319149
0.001241
def flatten_dict(x): """Flatten a dict Flatten an arbitrarily nested dict as output by to_dict .. note:: Keys in the flattened dict may get very long. Args: x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values Retu...
[ "def", "flatten_dict", "(", "x", ")", ":", "out", "=", "{", "}", "for", "k", ",", "v", "in", "x", ".", "items", "(", ")", ":", "out", "=", "_recur_flatten", "(", "k", ",", "v", ",", "out", ")", "return", "out" ]
23.421053
0.021598
def lte(name, value): ''' Only succeed if the value in the given register location is less than or equal the given value USAGE: .. code-block:: yaml foo: check.lte: - value: 42 run_remote_ex: local.cmd: - tgt: '*' - func: te...
[ "def", "lte", "(", "name", ",", "value", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "if", "name", "not", "in", "__reg__", ":", "ret", "[", ...
22.096774
0.001399
def is_model_view_subclass_method_shouldnt_be_function(node): """Checks that node is get or post method of the View class.""" if node.name not in ('get', 'post'): return False parent = node.parent while parent and not isinstance(parent, ScopedClass): parent = parent.parent subclass...
[ "def", "is_model_view_subclass_method_shouldnt_be_function", "(", "node", ")", ":", "if", "node", ".", "name", "not", "in", "(", "'get'", ",", "'post'", ")", ":", "return", "False", "parent", "=", "node", ".", "parent", "while", "parent", "and", "not", "isin...
35.571429
0.001957
def _display_layers(circ: Circuit, qubits: Qubits) -> Circuit: """Separate a circuit into groups of gates that do not visually overlap""" N = len(qubits) qubit_idx = dict(zip(qubits, range(N))) gate_layers = DAGCircuit(circ).layers() layers = [] lcirc = Circuit() layers.append(lcirc) un...
[ "def", "_display_layers", "(", "circ", ":", "Circuit", ",", "qubits", ":", "Qubits", ")", "->", "Circuit", ":", "N", "=", "len", "(", "qubits", ")", "qubit_idx", "=", "dict", "(", "zip", "(", "qubits", ",", "range", "(", "N", ")", ")", ")", "gate_l...
30.518519
0.001176
def loop_check(self): """Check if we have a loop in the graph :return: Nodes in loop :rtype: list """ in_loop = [] # Add the tag for dfs check for node in list(self.nodes.values()): node['dfs_loop_status'] = 'DFS_UNCHECKED' # Now do the job ...
[ "def", "loop_check", "(", "self", ")", ":", "in_loop", "=", "[", "]", "# Add the tag for dfs check", "for", "node", "in", "list", "(", "self", ".", "nodes", ".", "values", "(", ")", ")", ":", "node", "[", "'dfs_loop_status'", "]", "=", "'DFS_UNCHECKED'", ...
32.2
0.002413
def split(orig, sep=None): ''' Generator function for iterating through large strings, particularly useful as a replacement for str.splitlines(). See http://stackoverflow.com/a/3865367 ''' exp = re.compile(r'\s+' if sep is None else re.escape(sep)) pos = 0 length = len(orig) while T...
[ "def", "split", "(", "orig", ",", "sep", "=", "None", ")", ":", "exp", "=", "re", ".", "compile", "(", "r'\\s+'", "if", "sep", "is", "None", "else", "re", ".", "escape", "(", "sep", ")", ")", "pos", "=", "0", "length", "=", "len", "(", "orig", ...
35.916667
0.00113
def post(self, url, postParameters=None, urlParameters=None): """ Convenience method for requesting to google with proper cookies/params. """ if urlParameters: url = url + "?" + self.getParameters(urlParameters) headers = {'Authorization':'GoogleLogin auth=%s' % self....
[ "def", "post", "(", "self", ",", "url", ",", "postParameters", "=", "None", ",", "urlParameters", "=", "None", ")", ":", "if", "urlParameters", ":", "url", "=", "url", "+", "\"?\"", "+", "self", ".", "getParameters", "(", "urlParameters", ")", "headers",...
46.833333
0.008726
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: CredentialListContext for this CredentialListInstance :rtype: twilio.rest.trunking.v1.trunk.crede...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "CredentialListContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ",", ...
40.466667
0.008052
def _load_diff(args, extra_opts): """ :param args: :class:`argparse.Namespace` object :param extra_opts: Map object given to API.load as extra options """ try: diff = API.load(args.inputs, args.itype, ac_ignore_missing=args.ignore_missing, ac_m...
[ "def", "_load_diff", "(", "args", ",", "extra_opts", ")", ":", "try", ":", "diff", "=", "API", ".", "load", "(", "args", ".", "inputs", ",", "args", ".", "itype", ",", "ac_ignore_missing", "=", "args", ".", "ignore_missing", ",", "ac_merge", "=", "args...
40.571429
0.001147
def preprocess_input(userinput): """ <Purpose> Preprocess the raw command line input string. <Arguments> The raw command line input string. We assume it is pre-stripped. <Side Effects> The string will be processed by each module that has a defined preprocessor. <Exceptions> None <Return...
[ "def", "preprocess_input", "(", "userinput", ")", ":", "for", "module", "in", "get_enabled_modules", "(", ")", ":", "# Not every module has a preprocessor...", "if", "'input_preprocessor'", "in", "module_data", "[", "module", "]", ":", "userinput", "=", "module_data",...
25.545455
0.010292
def dump_copy(self, path, relativePath, name=None, description=None, replace=False, verbose=False): """ Copy an exisitng system file to the repository. attribute in the Repository with utc timestamp. :Parameters: #. path (str):...
[ "def", "dump_copy", "(", "self", ",", "path", ",", "relativePath", ",", "name", "=", "None", ",", "description", "=", "None", ",", "replace", "=", "False", ",", "verbose", "=", "False", ")", ":", "relativePath", "=", "os", ".", "path", ".", "normpath",...
50.509091
0.008121
def top1(scores: mx.nd.NDArray, offset: mx.nd.NDArray) -> Tuple[mx.nd.NDArray, mx.nd.NDArray, mx.nd.NDArray]: """ Get the single lowest element per sentence from a `scores` matrix. Expects that beam size is 1, for greedy decoding. NOTE(mathmu): The current implementation of argmin in MXNet muc...
[ "def", "top1", "(", "scores", ":", "mx", ".", "nd", ".", "NDArray", ",", "offset", ":", "mx", ".", "nd", ".", "NDArray", ")", "->", "Tuple", "[", "mx", ".", "nd", ".", "NDArray", ",", "mx", ".", "nd", ".", "NDArray", ",", "mx", ".", "nd", "."...
48.3
0.008122
def cdf_distribution(a_cdf, a_partitions): """ ARGS a_cdf vector a vectors of values/observations a_partitions int the number of partitions DESC This function returns the indices of a passed cdf such that the the range of values across t...
[ "def", "cdf_distribution", "(", "a_cdf", ",", "a_partitions", ")", ":", "f_range", "=", "a_cdf", "[", "-", "1", "]", "-", "a_cdf", "[", "0", "]", "f_rangePart", "=", "f_range", "/", "a_partitions", "lowerBound", "=", "a_cdf", "[", "0", "]", "vl", "=", ...
38.432432
0.000686
def unitResponse(self,band): """This is used internally for :ref:`pysynphot-formula-effstim` calculations.""" #sum = asumr(band,nwave) total = band.throughput.sum() return 2.5*math.log10(total)
[ "def", "unitResponse", "(", "self", ",", "band", ")", ":", "#sum = asumr(band,nwave)", "total", "=", "band", ".", "throughput", ".", "sum", "(", ")", "return", "2.5", "*", "math", ".", "log10", "(", "total", ")" ]
38
0.017167
def parent(self): """ Get the parent category """ if self.path: return Category(os.path.dirname(self.path)) return None
[ "def", "parent", "(", "self", ")", ":", "if", "self", ".", "path", ":", "return", "Category", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "path", ")", ")", "return", "None" ]
30.2
0.012903
def mapLabelRefs(dataDict): """ Replace the label strings in dataDict with corresponding ints. @return (tuple) (ordered list of category names, dataDict with names replaced by array of category indices) """ labelRefs = [label for label in set( itertools.chain.from_iterable([x[1] for...
[ "def", "mapLabelRefs", "(", "dataDict", ")", ":", "labelRefs", "=", "[", "label", "for", "label", "in", "set", "(", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "x", "[", "1", "]", "for", "x", "in", "dataDict", ".", "values", "(", ")", ...
35.266667
0.009208
def _get_user_info(self, cmd, section, required=True, accept_just_who=False): """Parse a user section.""" line = self.next_line() if line.startswith(section + b' '): return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_wh...
[ "def", "_get_user_info", "(", "self", ",", "cmd", ",", "section", ",", "required", "=", "True", ",", "accept_just_who", "=", "False", ")", ":", "line", "=", "self", ".", "next_line", "(", ")", "if", "line", ".", "startswith", "(", "section", "+", "b' '...
38.75
0.008403
def parse_received(received): """ Parse a single received header. Return a dictionary of values by clause. Arguments: received {str} -- single received header Raises: MailParserReceivedParsingError -- Raised when a received header cannot be parsed Returns: ...
[ "def", "parse_received", "(", "received", ")", ":", "values_by_clause", "=", "{", "}", "for", "pattern", "in", "RECEIVED_COMPILED_LIST", ":", "matches", "=", "[", "match", "for", "match", "in", "pattern", ".", "finditer", "(", "received", ")", "]", "if", "...
34.86
0.000558
async def create( self, task_template: Mapping[str, Any], *, name: str = None, labels: List = None, mode: Mapping = None, update_config: Mapping = None, rollback_config: Mapping = None, networks: List = None, endpoint_spec: Mapping = None, ...
[ "async", "def", "create", "(", "self", ",", "task_template", ":", "Mapping", "[", "str", ",", "Any", "]", ",", "*", ",", "name", ":", "str", "=", "None", ",", "labels", ":", "List", "=", "None", ",", "mode", ":", "Mapping", "=", "None", ",", "upd...
34
0.001225
def UpdateSNMPObjsAsync(): """ Starts UpdateSNMPObjs() in a separate thread. """ # UpdateSNMPObjs() will be executed in a separate thread so that the main # thread can continue looping and processing SNMP requests while the data # update is still in progress. However we'll make sure only one update # thread is ru...
[ "def", "UpdateSNMPObjsAsync", "(", ")", ":", "# UpdateSNMPObjs() will be executed in a separate thread so that the main", "# thread can continue looping and processing SNMP requests while the data", "# update is still in progress. However we'll make sure only one update", "# thread is run at any tim...
42.866667
0.021309
def on_change_specimen_mouse_cursor(self, event): """ If mouse is over data point making it selectable change the shape of the cursor Parameters ---------- event : the wx Mouseevent for that click """ if not self.specimen_EA_xdata or not self.specimen_EA_...
[ "def", "on_change_specimen_mouse_cursor", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "specimen_EA_xdata", "or", "not", "self", ".", "specimen_EA_ydata", ":", "return", "pos", "=", "event", ".", "GetPosition", "(", ")", "width", ",", "heig...
37.272727
0.001585
def cleanup_virtualenv(bare=True): """Removes the virtualenv directory from the system.""" if not bare: click.echo(crayons.red("Environment creation aborted.")) try: # Delete the virtualenv. vistir.path.rmtree(project.virtualenv_location) except OSError as e: click.echo( ...
[ "def", "cleanup_virtualenv", "(", "bare", "=", "True", ")", ":", "if", "not", "bare", ":", "click", ".", "echo", "(", "crayons", ".", "red", "(", "\"Environment creation aborted.\"", ")", ")", "try", ":", "# Delete the virtualenv.", "vistir", ".", "path", "....
35.75
0.001704
def main( req_files, verbose=False, outdated=False, latest=False, verbatim=False, repo=None, path='requirements.txt', token=None, branch='master', url=None, delay=None, ): """Given a list of requirements files reports which requirements are out of date. Everythin...
[ "def", "main", "(", "req_files", ",", "verbose", "=", "False", ",", "outdated", "=", "False", ",", "latest", "=", "False", ",", "verbatim", "=", "False", ",", "repo", "=", "None", ",", "path", "=", "'requirements.txt'", ",", "token", "=", "None", ",", ...
37.403101
0.000808
def is_iterable(o: Any) -> bool: """Return whether `o` is iterable and not a :class:`str` or :class:`bytes`. Parameters ---------- o Any python object Returns ------- bool Examples -------- >>> is_iterable('1') False >>> is_iterable(b'1') False >>> is_i...
[ "def", "is_iterable", "(", "o", ":", "Any", ")", "->", "bool", ":", "return", "not", "isinstance", "(", "o", ",", "(", "str", ",", "bytes", ")", ")", "and", "isinstance", "(", "o", ",", "collections", ".", "abc", ".", "Iterable", ")" ]
17.516129
0.001745
def read_instruction(fio, start_pos): """ Reads a single instruction from `fio` and returns it, or ``None`` if the stream is empty. :param fio: Any file-like object providing ``read()``. :param start_pos: The current position in the stream. """ op = fio.read(1) if not op: retur...
[ "def", "read_instruction", "(", "fio", ",", "start_pos", ")", ":", "op", "=", "fio", ".", "read", "(", "1", ")", "if", "not", "op", ":", "return", "None", "op", "=", "ord", "(", "op", ")", "ins", "=", "opcode_table", "[", "op", "]", "operands", "...
31.113924
0.000394
def contextMenuEvent(self, event): """Slot automatically called by Qt on right click on the WebView. :param event: the event that caused the context menu to be called. """ context_menu = QMenu(self) # add select all action_select_all = self.page().action( Q...
[ "def", "contextMenuEvent", "(", "self", ",", "event", ")", ":", "context_menu", "=", "QMenu", "(", "self", ")", "# add select all", "action_select_all", "=", "self", ".", "page", "(", ")", ".", "action", "(", "QtWebKitWidgets", ".", "QWebPage", ".", "SelectA...
35.241379
0.000952
def set_attributes(self, **kwargs): """ Set a group of attributes (parameters and members). Calls `setp` directly, so kwargs can include more than just the parameter value (e.g., bounds, free, etc.). """ kwargs = dict(kwargs) for name,value in kwargs.items(): ...
[ "def", "set_attributes", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "kwargs", ")", "for", "name", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "# Raise AttributeError if param not found", "self", ".", "__getat...
39.5
0.017002
def log_power_spectrum(frames, fft_points=512, normalize=True): """Log power spectrum of each frame in frames. Args: frames (array): The frame array in which each row is a frame. fft_points (int): The length of FFT. If fft_length is greater than frame_len, the frames will be zero-pa...
[ "def", "log_power_spectrum", "(", "frames", ",", "fft_points", "=", "512", ",", "normalize", "=", "True", ")", ":", "power_spec", "=", "power_spectrum", "(", "frames", ",", "fft_points", ")", "power_spec", "[", "power_spec", "<=", "1e-20", "]", "=", "1e-20",...
38.045455
0.001166
def get_epoch_info(self, epoch_name): '''This function returns the start frame and end frame of the epoch in a dict. Parameters ---------- epoch_name: str The name of the epoch to be returned Returns ---------- epoch_info: dict A ...
[ "def", "get_epoch_info", "(", "self", ",", "epoch_name", ")", ":", "# Default (Can add more information into each epoch in subclass)", "if", "isinstance", "(", "epoch_name", ",", "str", ")", ":", "if", "epoch_name", "in", "list", "(", "self", ".", "_epochs", ".", ...
34.043478
0.002484
def _checkReturnTo(self, message, return_to): """Check an OpenID message and its openid.return_to value against a return_to URL from an application. Return True on success, False on failure. """ # Check the openid.return_to args against args in the original # message. ...
[ "def", "_checkReturnTo", "(", "self", ",", "message", ",", "return_to", ")", ":", "# Check the openid.return_to args against args in the original", "# message.", "try", ":", "self", ".", "_verifyReturnToArgs", "(", "message", ".", "toPostArgs", "(", ")", ")", "except"...
38.464286
0.001812
def debit(self, amount, credit_account, description, debit_memo="", credit_memo="", datetime=None): """ Post a debit of 'amount' and a credit of -amount against this account and credit_account respectively. note amount must be non-negative. """ assert amount >= 0 return self.po...
[ "def", "debit", "(", "self", ",", "amount", ",", "credit_account", ",", "description", ",", "debit_memo", "=", "\"\"", ",", "credit_memo", "=", "\"\"", ",", "datetime", "=", "None", ")", ":", "assert", "amount", ">=", "0", "return", "self", ".", "post", ...
52.125
0.011792
def get_extension(media): """Gets the corresponding extension for any Telegram media.""" # Photos are always compressed as .jpg by Telegram if isinstance(media, (types.UserProfilePhoto, types.ChatPhoto, types.MessageMediaPhoto)): return '.jpg' # Documents will come wi...
[ "def", "get_extension", "(", "media", ")", ":", "# Photos are always compressed as .jpg by Telegram", "if", "isinstance", "(", "media", ",", "(", "types", ".", "UserProfilePhoto", ",", "types", ".", "ChatPhoto", ",", "types", ".", "MessageMediaPhoto", ")", ")", ":...
37.2
0.001311
def predict_y(self, xq, sigma=None, k=None, **kwargs): """Provide an prediction of xq in the output space @param xq an array of float of length dim_x """ sigma = sigma or self.sigma k = k or self.k dists, index = self.dataset.nn_x(xq, k = k) w = self._weights(di...
[ "def", "predict_y", "(", "self", ",", "xq", ",", "sigma", "=", "None", ",", "k", "=", "None", ",", "*", "*", "kwargs", ")", ":", "sigma", "=", "sigma", "or", "self", ".", "sigma", "k", "=", "k", "or", "self", ".", "k", "dists", ",", "index", ...
41.9
0.016355
def click_link(self, link_text, timeout=settings.SMALL_TIMEOUT): """ Same as self.click_link_text() """ self.click_link_text(link_text, timeout=timeout)
[ "def", "click_link", "(", "self", ",", "link_text", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "self", ".", "click_link_text", "(", "link_text", ",", "timeout", "=", "timeout", ")" ]
55.333333
0.011905
def eval(self, expression, identify_errors=True, print_expression=True, on_new_output=sys.stdout.write): """ Evaluates a matlab expression synchronously. If identify_erros is true, and the last output line after evaluat...
[ "def", "eval", "(", "self", ",", "expression", ",", "identify_errors", "=", "True", ",", "print_expression", "=", "True", ",", "on_new_output", "=", "sys", ".", "stdout", ".", "write", ")", ":", "self", ".", "_check_open", "(", ")", "if", "print_expression...
43.692308
0.008613
def LargestComponent(self): """ Returns (i, val) where i is the component index (0 - 2) which has largest absolute value and val is the value of the component. """ if abs(self.x) > abs(self.y): if abs(self.x) > abs(self.z): return (0, self.x) else: return (2, self.z) ...
[ "def", "LargestComponent", "(", "self", ")", ":", "if", "abs", "(", "self", ".", "x", ")", ">", "abs", "(", "self", ".", "y", ")", ":", "if", "abs", "(", "self", ".", "x", ")", ">", "abs", "(", "self", ".", "z", ")", ":", "return", "(", "0"...
26
0.011601