text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def collect(coro, index, results, preserve_order=False, return_exceptions=False): """ Collect is used internally to execute coroutines and collect the returned value. This function is intended to be used internally. """ result = yield from safe_run(coro, return_exceptions=ret...
[ "def", "collect", "(", "coro", ",", "index", ",", "results", ",", "preserve_order", "=", "False", ",", "return_exceptions", "=", "False", ")", ":", "result", "=", "yield", "from", "safe_run", "(", "coro", ",", "return_exceptions", "=", "return_exceptions", "...
32.307692
0.002315
def dasrfr(handle, lenout=_default_len_out): """ Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :type lenout: ...
[ "def", "dasrfr", "(", "handle", ",", "lenout", "=", "_default_len_out", ")", ":", "handle", "=", "ctypes", ".", "c_int", "(", "handle", ")", "idwlen", "=", "ctypes", ".", "c_int", "(", "lenout", ")", "# intentional", "ifnlen", "=", "ctypes", ".", "c_int"...
42.678571
0.008183
def a2s_info(server_addr, timeout=2, force_goldsrc=False): """Get information from a server .. note:: All ``GoldSrc`` games have been updated to reply in ``Source`` format. ``GoldSrc`` format is essentially DEPRECATED. By default the function will prefer to return ``Source`` format, and...
[ "def", "a2s_info", "(", "server_addr", ",", "timeout", "=", "2", ",", "force_goldsrc", "=", "False", ")", ":", "ss", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "ss", ".", "connect", "(", "server_...
29.84507
0.000913
def get_colorscheme(self, scheme_file): """Return a string object with the colorscheme that is to be inserted.""" scheme = get_yaml_dict(scheme_file) scheme_slug = builder.slugify(scheme_file) builder.format_scheme(scheme, scheme_slug) try: temp_base, temp_su...
[ "def", "get_colorscheme", "(", "self", ",", "scheme_file", ")", ":", "scheme", "=", "get_yaml_dict", "(", "scheme_file", ")", "scheme_slug", "=", "builder", ".", "slugify", "(", "scheme_file", ")", "builder", ".", "format_scheme", "(", "scheme", ",", "scheme_s...
37.913043
0.002237
def batch_get_archive(self, archive_names, default_versions=None): ''' Batch version of :py:meth:`~DataAPI.get_archive` Parameters ---------- archive_names: list Iterable of archive names to retrieve default_versions: str, object, or dict Defa...
[ "def", "batch_get_archive", "(", "self", ",", "archive_names", ",", "default_versions", "=", "None", ")", ":", "# toss prefixes and normalize names", "archive_names", "=", "map", "(", "lambda", "arch", ":", "self", ".", "_normalize_archive_name", "(", "arch", ")", ...
30.691176
0.000929
def find_descriptor(desc, find_all=False, custom_match=None, **args): r"""Find an inner descriptor. find_descriptor works in the same way as the core.find() function does, but it acts on general descriptor objects. For example, suppose you have a Device object called dev and want a Configuration of thi...
[ "def", "find_descriptor", "(", "desc", ",", "find_all", "=", "False", ",", "custom_match", "=", "None", ",", "*", "*", "args", ")", ":", "def", "desc_iter", "(", "*", "*", "kwargs", ")", ":", "for", "d", "in", "desc", ":", "tests", "=", "(", "val",...
38.793103
0.001735
def analyzeParameters(expName, suite): """ Analyze the impact of each list parameter in this experiment """ print("\n================",expName,"=====================") try: expParams = suite.get_params(expName) pprint.pprint(expParams) for p in ["boost_strength", "k", "learning_rate", "weight_spa...
[ "def", "analyzeParameters", "(", "expName", ",", "suite", ")", ":", "print", "(", "\"\\n================\"", ",", "expName", ",", "\"=====================\"", ")", "try", ":", "expParams", "=", "suite", ".", "get_params", "(", "expName", ")", "pprint", ".", "p...
37.125
0.017227
def get_metadata(doi): """Returns the metadata of an article given its DOI from CrossRef as a JSON dict""" url = crossref_url + 'works/' + doi res = requests.get(url) if res.status_code != 200: logger.info('Could not get CrossRef metadata for DOI %s, code %d' % (doi, res....
[ "def", "get_metadata", "(", "doi", ")", ":", "url", "=", "crossref_url", "+", "'works/'", "+", "doi", "res", "=", "requests", ".", "get", "(", "url", ")", "if", "res", ".", "status_code", "!=", "200", ":", "logger", ".", "info", "(", "'Could not get Cr...
36.083333
0.002252
def Ping(self, request, context): """ Invoke the Server health endpoint :param request: Empty :param context: the request context :return: Status message 'alive' """ status = processor_pb2.Status() status.message='alive' return status
[ "def", "Ping", "(", "self", ",", "request", ",", "context", ")", ":", "status", "=", "processor_pb2", ".", "Status", "(", ")", "status", ".", "message", "=", "'alive'", "return", "status" ]
29.8
0.013029
def check_angle_sampling(nvecs, angles): """ Returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n. Parameters ---------- nvecs ...
[ "def", "check_angle_sampling", "(", "nvecs", ",", "angles", ")", ":", "failed_nvecs", "=", "[", "]", "failures", "=", "[", "]", "for", "i", ",", "vec", "in", "enumerate", "(", "nvecs", ")", ":", "# N = np.linalg.norm(vec)", "# X = np.dot(angles,vec)", "X", "...
32.085106
0.000644
def merge_figures(figures): """ Generates a single Figure from a list of figures Parameters: ----------- figures : list(Figures) List of figures to be merged. """ figure={} data=[] for fig in figures: for trace in fig['data']: data.append(trace) layout=get_base_layout(figures) figure['data']=data ...
[ "def", "merge_figures", "(", "figures", ")", ":", "figure", "=", "{", "}", "data", "=", "[", "]", "for", "fig", "in", "figures", ":", "for", "trace", "in", "fig", "[", "'data'", "]", ":", "data", ".", "append", "(", "trace", ")", "layout", "=", "...
18.944444
0.061453
def connect(host, username, password, port=443, verify=False, debug=False): ''' Connect to a vCenter via the API :param host: Hostname or IP of the vCenter :type host: str or unicode :param username: Username :type user: str or unicode :param password: Password :type user: str or unicode...
[ "def", "connect", "(", "host", ",", "username", ",", "password", ",", "port", "=", "443", ",", "verify", "=", "False", ",", "debug", "=", "False", ")", ":", "context", "=", "ssl", ".", "SSLContext", "(", "ssl", ".", "PROTOCOL_TLSv1_2", ")", "if", "no...
34.5625
0.000586
def format_repo_status(repo): """ Return a dictionary representing the repository status It returns ``None`` for things we do not support or are not relevant. :param str repo_name: The name of the repository. :returns: dict """ commit = repo.commit() return { 'name...
[ "def", "format_repo_status", "(", "repo", ")", ":", "commit", "=", "repo", ".", "commit", "(", ")", "return", "{", "'name'", ":", "os", ".", "path", ".", "basename", "(", "repo", ".", "working_dir", ")", ",", "'commit'", ":", "commit", ".", "hexsha", ...
24.842105
0.002041
def set_mac_addr(self, mac_addr): """ Sets the MAC address. :param mac_addr: a MAC address (hexadecimal format: hh:hh:hh:hh:hh:hh) """ yield from self._hypervisor.send('{platform} set_mac_addr "{name}" {mac_addr}'.format(platform=self._platform, ...
[ "def", "set_mac_addr", "(", "self", ",", "mac_addr", ")", ":", "yield", "from", "self", ".", "_hypervisor", ".", "send", "(", "'{platform} set_mac_addr \"{name}\" {mac_addr}'", ".", "format", "(", "platform", "=", "self", ".", "_platform", ",", "name", "=", "s...
62.3125
0.008893
def _validate(self, request): """Validate an L{HTTPRequest} before executing it. The following conditions are checked: - The request contains all the generic parameters. - The action specified in the request is a supported one. - The signature mechanism is a supported one. ...
[ "def", "_validate", "(", "self", ",", "request", ")", ":", "call_arguments", "=", "self", ".", "get_call_arguments", "(", "request", ")", "args", "=", "call_arguments", "[", "\"transport_args\"", "]", "rest", "=", "call_arguments", "[", "\"handler_args\"", "]", ...
40.088235
0.001433
def get_board(self, id, name=None): ''' Get a board Returns: Board: The board with the given `id` ''' return self.create_board(dict(id=id, name=name))
[ "def", "get_board", "(", "self", ",", "id", ",", "name", "=", "None", ")", ":", "return", "self", ".", "create_board", "(", "dict", "(", "id", "=", "id", ",", "name", "=", "name", ")", ")" ]
24.5
0.009852
def delete_attr(self, name: str, axis: int = 0) -> None: """ **DEPRECATED** - Use `del ds.ra.key` or `del ds.ca.key` instead, where `key` is replaced with the attribute name """ deprecated("'delete_attr' is deprecated. Use 'del ds.ra.key' or 'del ds.ca.key' instead") if axis == 0: del self.ra[name] else:...
[ "def", "delete_attr", "(", "self", ",", "name", ":", "str", ",", "axis", ":", "int", "=", "0", ")", "->", "None", ":", "deprecated", "(", "\"'delete_attr' is deprecated. Use 'del ds.ra.key' or 'del ds.ca.key' instead\"", ")", "if", "axis", "==", "0", ":", "del",...
37
0.035191
def recv_connect(self, version=None, support=None, session=None): """DDP connect handler.""" del session # Meteor doesn't even use this! if self.connection is not None: raise MeteorError( 400, 'Session already established.', self.connection.connection...
[ "def", "recv_connect", "(", "self", ",", "version", "=", "None", ",", "support", "=", "None", ",", "session", "=", "None", ")", ":", "del", "session", "# Meteor doesn't even use this!", "if", "self", ".", "connection", "is", "not", "None", ":", "raise", "M...
43.8
0.001489
def index_tuple(self,tables_dict,index,is_set): "helper for rowget/rowset" if not self.aonly_resolved: raise RuntimeError('resolve_aonly() before querying nix') with tables_dict.tempkeys(): tables_dict.update(self.aonly) # todo: find spec support for aliases overwriting existing tables. (more likely, ...
[ "def", "index_tuple", "(", "self", ",", "tables_dict", ",", "index", ",", "is_set", ")", ":", "if", "not", "self", ".", "aonly_resolved", ":", "raise", "RuntimeError", "(", "'resolve_aonly() before querying nix'", ")", "with", "tables_dict", ".", "tempkeys", "("...
67.142857
0.027273
def throttle(self, wait): """ Returns a function, that, when invoked, will only be triggered at most once during a given window of time. """ ns = self.Namespace() ns.timeout = None ns.throttling = None ns.more = None ns.result = None def d...
[ "def", "throttle", "(", "self", ",", "wait", ")", ":", "ns", "=", "self", ".", "Namespace", "(", ")", "ns", ".", "timeout", "=", "None", "ns", ".", "throttling", "=", "None", "ns", ".", "more", "=", "None", "ns", ".", "result", "=", "None", "def"...
27.694444
0.001938
def add_links(self, parent, children): """Create dependency links from parent to child. Any sensors not in the tree are added. After all dependency links have been created, the parent is recalculated and the tree attaches to any sensors it was not yet attached to. Links that already exi...
[ "def", "add_links", "(", "self", ",", "parent", ",", "children", ")", ":", "new_sensors", "=", "[", "]", "if", "parent", "not", "in", "self", ":", "self", ".", "_add_sensor", "(", "parent", ")", "new_sensors", ".", "append", "(", "parent", ")", "for", ...
35.5
0.001828
def parse_duration(string): """ Parse human readable duration. >>> parse_duration('1m') 60 >>> parse_duration('7 days') == 7 * 24 * 60 * 60 True """ if string.isdigit(): return int(string) try: return float(string) except ValueError: pass string = st...
[ "def", "parse_duration", "(", "string", ")", ":", "if", "string", ".", "isdigit", "(", ")", ":", "return", "int", "(", "string", ")", "try", ":", "return", "float", "(", "string", ")", "except", "ValueError", ":", "pass", "string", "=", "string", ".", ...
23.782609
0.001757
def insert_entity(self, entity): ''' Adds an insert entity operation to the batch. See :func:`~azure.storage.table.tableservice.TableService.insert_entity` for more information on inserts. The operation will not be executed until the batch is committed. :param...
[ "def", "insert_entity", "(", "self", ",", "entity", ")", ":", "request", "=", "_insert_entity", "(", "entity", ")", "self", ".", "_add_to_batch", "(", "entity", "[", "'PartitionKey'", "]", ",", "entity", "[", "'RowKey'", "]", ",", "request", ")" ]
43.066667
0.010606
def _get_backend(): """ Returns the actual django cache object johnny is configured to use. This relies on the settings only; the actual active cache can theoretically be changed at runtime. """ enabled = [n for n, c in sorted(CACHES.items()) if c.get('JOHNNY_CACHE', False)] ...
[ "def", "_get_backend", "(", ")", ":", "enabled", "=", "[", "n", "for", "n", ",", "c", "in", "sorted", "(", "CACHES", ".", "items", "(", ")", ")", "if", "c", ".", "get", "(", "'JOHNNY_CACHE'", ",", "False", ")", "]", "if", "len", "(", "enabled", ...
39.833333
0.001021
def namedb_get_num_blockstack_ops_at( db, block_id ): """ Get the number of name/namespace/token operations that occurred at a particular block. """ cur = db.cursor() # preorders at this block preorder_count_rows_query = "SELECT COUNT(*) FROM preorders WHERE block_number = ?;" preorder_coun...
[ "def", "namedb_get_num_blockstack_ops_at", "(", "db", ",", "block_id", ")", ":", "cur", "=", "db", ".", "cursor", "(", ")", "# preorders at this block", "preorder_count_rows_query", "=", "\"SELECT COUNT(*) FROM preorders WHERE block_number = ?;\"", "preorder_count_rows_args", ...
33.04
0.009412
def solute_defect_density(structure, e0, vac_defs, antisite_defs, solute_defs, solute_concen=0.01, T=800, trial_chem_pot=None, ...
[ "def", "solute_defect_density", "(", "structure", ",", "e0", ",", "vac_defs", ",", "antisite_defs", ",", "solute_defs", ",", "solute_concen", "=", "0.01", ",", "T", "=", "800", ",", "trial_chem_pot", "=", "None", ",", "plot_style", "=", "\"highchargs\"", ")", ...
40.79
0.000718
def find_match_command(self, rule): """Return a matching (possibly munged) command, if found in rule.""" command_string = rule['command'] command_list = command_string.split() self.logdebug('comparing "%s" to "%s"\n' % (command_list, self.original_command_list)) ...
[ "def", "find_match_command", "(", "self", ",", "rule", ")", ":", "command_string", "=", "rule", "[", "'command'", "]", "command_list", "=", "command_string", ".", "split", "(", ")", "self", ".", "logdebug", "(", "'comparing \"%s\" to \"%s\"\\n'", "%", "(", "co...
43.44
0.001802
def IPS(copy_namespaces=True, overwrite_globals=False): """Starts IPython embedded shell. This is similar to IPython.embed() but with some additional features: 1. Print a list of the calling frames before entering the prompt 2. (optionally) copy local name space to global one to prevent certain IPython...
[ "def", "IPS", "(", "copy_namespaces", "=", "True", ",", "overwrite_globals", "=", "False", ")", ":", "# let the user know, where this shell is 'waking up'", "# construct frame list", "# this will be printed in the header", "frame_info_list", "=", "[", "]", "frame_list", "=", ...
35.669643
0.002192
def process_killed_run(self, dir_name): """ Process a killed vasp run. """ fullpath = os.path.abspath(dir_name) logger.info("Processing Killed run " + fullpath) d = {"dir_name": fullpath, "state": "killed", "oszicar": {}} for f in os.listdir(dir_name): ...
[ "def", "process_killed_run", "(", "self", ",", "dir_name", ")", ":", "fullpath", "=", "os", ".", "path", ".", "abspath", "(", "dir_name", ")", "logger", ".", "info", "(", "\"Processing Killed run \"", "+", "fullpath", ")", "d", "=", "{", "\"dir_name\"", ":...
46.891566
0.002265
def run_has_samplesheet(fc_dir, config, require_single=True): """Checks if there's a suitable SampleSheet.csv present for the run """ fc_name, _ = flowcell.parse_dirname(fc_dir) sheet_dirs = config.get("samplesheet_directories", []) fcid_sheet = {} for ss_dir in (s for s in sheet_dirs if os.path...
[ "def", "run_has_samplesheet", "(", "fc_dir", ",", "config", ",", "require_single", "=", "True", ")", ":", "fc_name", ",", "_", "=", "flowcell", ".", "parse_dirname", "(", "fc_dir", ")", "sheet_dirs", "=", "config", ".", "get", "(", "\"samplesheet_directories\"...
45.545455
0.001955
def bind(mod_path, with_path=None): """ bind user variable to `_wrapped` .. note:: you don't need call this method by yourself. program will call it in `cliez.parser.parse` .. expection:: if path is not correct,will cause an `ImportError` ...
[ "def", "bind", "(", "mod_path", ",", "with_path", "=", "None", ")", ":", "if", "with_path", ":", "if", "os", ".", "path", ".", "isdir", "(", "with_path", ")", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "with_path", ")", "else", ":", "...
25.568182
0.001712
def train(self): """ This method generates the classifier. This method assumes that the training data has been loaded """ if not self.training_data: self.import_training_data() training_feature_set = [(self.extract_features(line), label) ...
[ "def", "train", "(", "self", ")", ":", "if", "not", "self", ".", "training_data", ":", "self", ".", "import_training_data", "(", ")", "training_feature_set", "=", "[", "(", "self", ".", "extract_features", "(", "line", ")", ",", "label", ")", "for", "(",...
44.8
0.013129
def ensure_dir (self, mode=0o777, parents=False): """Ensure that this path exists as a directory. This function calls :meth:`mkdir` on this path, but does not raise an exception if it already exists. It does raise an exception if this path exists but is not a directory. If the directory...
[ "def", "ensure_dir", "(", "self", ",", "mode", "=", "0o777", ",", "parents", "=", "False", ")", ":", "if", "parents", ":", "p", "=", "self", ".", "parent", "if", "p", "==", "self", ":", "return", "False", "# can never create root; avoids loop when parents=Tr...
34.583333
0.009375
def offer(self, item, timeout=0): """ Transactional implementation of :func:`Queue.offer(item, timeout) <hazelcast.proxy.queue.Queue.offer>` :param item: (object), the item to be added. :param timeout: (long), maximum time in seconds to wait for addition (optional). :return: (bo...
[ "def", "offer", "(", "self", ",", "item", ",", "timeout", "=", "0", ")", ":", "check_not_none", "(", "item", ",", "\"item can't be none\"", ")", "return", "self", ".", "_encode_invoke", "(", "transactional_queue_offer_codec", ",", "item", "=", "self", ".", "...
54.909091
0.009772
def create_results_dirs(base_path): """Create base path dir and subdirectories Parameters ---------- base_path : str The base path has subdirectories for raw and processed results """ if not os.path.exists(base_path): print("Creating directory {} for results data.".format(base_...
[ "def", "create_results_dirs", "(", "base_path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "base_path", ")", ":", "print", "(", "\"Creating directory {} for results data.\"", ".", "format", "(", "base_path", ")", ")", "os", ".", "mkdir", "...
39.05
0.00125
def logistic(x: Union[float, np.ndarray], k: float, theta: float) -> Optional[float]: r""" Standard logistic function. .. math:: y = \frac {1} {1 + e^{-k (x - \theta)}} Args: x: :math:`x` k: :math:`k` theta: :math:`\theta` Returns: ...
[ "def", "logistic", "(", "x", ":", "Union", "[", "float", ",", "np", ".", "ndarray", "]", ",", "k", ":", "float", ",", "theta", ":", "float", ")", "->", "Optional", "[", "float", "]", ":", "# https://www.sharelatex.com/learn/List_of_Greek_letters_and_math_symbo...
22.958333
0.001742
def make_script(self): """Make the script and return a FilePath object pointing to the script above.""" self.script_path.write(self.script) self.script_path.permissions.make_executable() return self.script_path
[ "def", "make_script", "(", "self", ")", ":", "self", ".", "script_path", ".", "write", "(", "self", ".", "script", ")", "self", ".", "script_path", ".", "permissions", ".", "make_executable", "(", ")", "return", "self", ".", "script_path" ]
47.6
0.012397
def query_tissue_in_reference(): """ Returns list of tissues linked to references by query parameters --- tags: - Query functions parameters: - name: tissue in: query type: string required: false description: Tissue default: brain - name:...
[ "def", "query_tissue_in_reference", "(", ")", ":", "args", "=", "get_args", "(", "request_args", "=", "request", ".", "args", ",", "allowed_str_args", "=", "[", "'tissue'", ",", "'entry_name'", "]", ",", "allowed_int_args", "=", "[", "'limit'", "]", ")", "re...
20.631579
0.001218
def calculate(self): """ calculates the estimated happiness of a person living in a world self._update_pref(self.person.prefs['tax_min'], self.person.prefs['tax_max'], self.world.tax_rate) self._update_pref(self.person.prefs['tradition'], self.person.prefs['tradition'], self.worl...
[ "def", "calculate", "(", "self", ")", ":", "self", ".", "rating", "=", "0", "for", "f", "in", "self", ".", "factors", ":", "self", ".", "_update_pref", "(", "f", ".", "min", ",", "f", ".", "max", ",", "self", ".", "world", ".", "tax_rate", ")" ]
50.636364
0.008818
def get_border_widths(self): """Return border width for each side top, left, bottom, right.""" if type(self.border_widths) is int: # uniform size return [self.border_widths] * 4 return self.border_widths
[ "def", "get_border_widths", "(", "self", ")", ":", "if", "type", "(", "self", ".", "border_widths", ")", "is", "int", ":", "# uniform size", "return", "[", "self", ".", "border_widths", "]", "*", "4", "return", "self", ".", "border_widths" ]
47.4
0.008299
def new_filename(original_filename, new_locale): """Returns a filename derived from original_filename, using new_locale as the locale""" orig_file = Path(original_filename) new_file = orig_file.parent.parent.parent / new_locale / orig_file.parent.name / orig_file.name return new_file.abspath()
[ "def", "new_filename", "(", "original_filename", ",", "new_locale", ")", ":", "orig_file", "=", "Path", "(", "original_filename", ")", "new_file", "=", "orig_file", ".", "parent", ".", "parent", ".", "parent", "/", "new_locale", "/", "orig_file", ".", "parent"...
61.2
0.009677
def remove_masked_labels(self, mask, partial_overlap=True, relabel=False): """ Remove labeled segments located within a masked region. Parameters ---------- mask : array_like (bool) A boolean mask, with the same shape as the segmentation ...
[ "def", "remove_masked_labels", "(", "self", ",", "mask", ",", "partial_overlap", "=", "True", ",", "relabel", "=", "False", ")", ":", "if", "mask", ".", "shape", "!=", "self", ".", "shape", ":", "raise", "ValueError", "(", "'mask must have the same shape as th...
41.181818
0.001078
def swapWH(self): """! \~english Swap width and height of rectangles \~chinese 交换矩形高宽边数据 """ width = self.width self.width = self.height self.height = width
[ "def", "swapWH", "(", "self", ")", ":", "width", "=", "self", ".", "width", "self", ".", "width", "=", "self", ".", "height", "self", ".", "height", "=", "width" ]
25.625
0.018868
def delta(self,local=False): """ Returns the number of days of difference """ (s,e) = self.get(local) return e-s
[ "def", "delta", "(", "self", ",", "local", "=", "False", ")", ":", "(", "s", ",", "e", ")", "=", "self", ".", "get", "(", "local", ")", "return", "e", "-", "s" ]
28
0.027778
def getAdministrator(self, email, returned_properties=None): """Get the :class:`rtcclient.models.Administrator` object by the email address :param email: the email address (e.g. somebody@gmail.com) :param returned_properties: the returned properties that you want. Refer to :...
[ "def", "getAdministrator", "(", "self", ",", "email", ",", "returned_properties", "=", "None", ")", ":", "if", "not", "isinstance", "(", "email", ",", "six", ".", "string_types", ")", "or", "\"@\"", "not", "in", "email", ":", "excp_msg", "=", "\"Please spe...
45.870968
0.001377
def unpack_from(self, buff, offset=0): """Unpack the next bytes from a file object.""" return self._create(super(DictStruct, self).unpack_from(buff, offset))
[ "def", "unpack_from", "(", "self", ",", "buff", ",", "offset", "=", "0", ")", ":", "return", "self", ".", "_create", "(", "super", "(", "DictStruct", ",", "self", ")", ".", "unpack_from", "(", "buff", ",", "offset", ")", ")" ]
57
0.011561
def information(self, message, *args, **kwargs): """alias to message at information level""" self.log("info", message, *args, **kwargs)
[ "def", "information", "(", "self", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log", "(", "\"info\"", ",", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
49.666667
0.013245
def _submit_topology(cmd_args, app): """Submit a Python topology to the service. This includes an SPL main composite wrapped in a Python topology. """ cfg = app.cfg if cmd_args.create_bundle: ctxtype = ctx.ContextTypes.BUNDLE elif cmd_args.service_name: cfg[ctx.ConfigParams.FORCE...
[ "def", "_submit_topology", "(", "cmd_args", ",", "app", ")", ":", "cfg", "=", "app", ".", "cfg", "if", "cmd_args", ".", "create_bundle", ":", "ctxtype", "=", "ctx", ".", "ContextTypes", ".", "BUNDLE", "elif", "cmd_args", ".", "service_name", ":", "cfg", ...
39.692308
0.001894
def walk(self, relpath, topdown=True): """Walk the file tree rooted at `path`. Works like os.walk but returned root value is relative path. Ignored paths will not be returned. """ for root, dirs, files in self._walk_raw(relpath, topdown): matched_dirs = self.ignore.match_files([os.path.join(r...
[ "def", "walk", "(", "self", ",", "relpath", ",", "topdown", "=", "True", ")", ":", "for", "root", ",", "dirs", ",", "files", "in", "self", ".", "_walk_raw", "(", "relpath", ",", "topdown", ")", ":", "matched_dirs", "=", "self", ".", "ignore", ".", ...
41.25
0.011852
def set_properties(self, pathobj, props, recursive): """ Set artifact properties """ url = '/'.join([pathobj.drive, 'api/storage', str(pathobj.relative_to(pathobj.drive)).strip('/')]) params = {'properties': encode_properties(props...
[ "def", "set_properties", "(", "self", ",", "pathobj", ",", "props", ",", "recursive", ")", ":", "url", "=", "'/'", ".", "join", "(", "[", "pathobj", ".", "drive", ",", "'api/storage'", ",", "str", "(", "pathobj", ".", "relative_to", "(", "pathobj", "."...
35.304348
0.002398
def assign_params(func, namespace): """ Assign parameters from namespace where func solicits. >>> def func(x, y=3): ... print(x, y) >>> assigned = assign_params(func, dict(x=2, z=4)) >>> assigned() 2 3 The usual errors are raised if a function doesn't receive its required parameters: >>> assigned = ass...
[ "def", "assign_params", "(", "func", ",", "namespace", ")", ":", "try", ":", "sig", "=", "inspect", ".", "signature", "(", "func", ")", "params", "=", "sig", ".", "parameters", ".", "keys", "(", ")", "except", "AttributeError", ":", "spec", "=", "inspe...
22.473684
0.037037
def getUserByNumber(self, base, uidNumber): """ search for a user in LDAP and return its DN and uid """ res = self.query(base, "uidNumber="+str(uidNumber), ['uid']) if len(res) > 1: raise InputError(uidNumber, "Multiple users found. Expecting one.") return res[0][0], res[0][1]['uid'][0]
[ "def", "getUserByNumber", "(", "self", ",", "base", ",", "uidNumber", ")", ":", "res", "=", "self", ".", "query", "(", "base", ",", "\"uidNumber=\"", "+", "str", "(", "uidNumber", ")", ",", "[", "'uid'", "]", ")", "if", "len", "(", "res", ")", ">",...
48.833333
0.02349
def get_area_def(area_name): """Get the definition of *area_name* from file. The file is defined to use is to be placed in the $PPP_CONFIG_DIR directory, and its name is defined in satpy's configuration file. """ try: from pyresample import parse_area_file except ImportError: fr...
[ "def", "get_area_def", "(", "area_name", ")", ":", "try", ":", "from", "pyresample", "import", "parse_area_file", "except", "ImportError", ":", "from", "pyresample", ".", "utils", "import", "parse_area_file", "return", "parse_area_file", "(", "get_area_file", "(", ...
37.272727
0.002381
def print_tools(self, buf=sys.stdout, verbose=False, context_name=None): """Print table of tools available in the suite. Args: context_name (str): If provided, only print the tools from this context. """ def _get_row(entry): context_name_ = entry[...
[ "def", "print_tools", "(", "self", ",", "buf", "=", "sys", ".", "stdout", ",", "verbose", "=", "False", ",", "context_name", "=", "None", ")", ":", "def", "_get_row", "(", "entry", ")", ":", "context_name_", "=", "entry", "[", "\"context_name\"", "]", ...
35.829787
0.001156
def get_record_rdd_from_json_files(self, json_files: List[str], data_processor: DataProcessor = SimpleJsonDataProcessor(), spark_session: Optional['SparkSession'] = None) -> 'RDD': """ Re...
[ "def", "get_record_rdd_from_json_files", "(", "self", ",", "json_files", ":", "List", "[", "str", "]", ",", "data_processor", ":", "DataProcessor", "=", "SimpleJsonDataProcessor", "(", ")", ",", "spark_session", ":", "Optional", "[", "'SparkSession'", "]", "=", ...
61.857143
0.010614
def get_path_info(self, path): """ Get information about ``path`` as a dict of properties. The return value, based upon ``fs.FileStatus`` from the Java API, has the following fields: * ``block_size``: HDFS block size of ``path`` * ``group``: group associated with ``path...
[ "def", "get_path_info", "(", "self", ",", "path", ")", ":", "_complain_ifclosed", "(", "self", ".", "closed", ")", "return", "self", ".", "fs", ".", "get_path_info", "(", "path", ")" ]
38.153846
0.001967
def open(self, session, resource_name, access_mode=constants.AccessModes.no_lock, open_timeout=constants.VI_TMO_IMMEDIATE): """Opens a session to the specified resource. Corresponds to viOpen function of the VISA library. :param session: Resource Manager session (should always be ...
[ "def", "open", "(", "self", ",", "session", ",", "resource_name", ",", "access_mode", "=", "constants", ".", "AccessModes", ".", "no_lock", ",", "open_timeout", "=", "constants", ".", "VI_TMO_IMMEDIATE", ")", ":", "raise", "NotImplementedError" ]
59.5625
0.008264
def highlightNextMatch(self): """ Select and highlight the next match in the set of matches. """ # If this method was called on an empty input field (ie. # if the user hit <ctrl>+s again) then pick the default # selection. if self.qteText.toPlainText() == '': ...
[ "def", "highlightNextMatch", "(", "self", ")", ":", "# If this method was called on an empty input field (ie.", "# if the user hit <ctrl>+s again) then pick the default", "# selection.", "if", "self", ".", "qteText", ".", "toPlainText", "(", ")", "==", "''", ":", "self", "....
37.947368
0.001352
def addScalarBar(self, c=None, title="", horizontal=False, vmin=None, vmax=None): """ Add a 2D scalar bar to actor. .. hint:: |mesh_bands| |mesh_bands.py|_ """ # book it, it will be created by Plotter.show() later self.scalarbar = [c, title, horizontal, vmin, vmax] ...
[ "def", "addScalarBar", "(", "self", ",", "c", "=", "None", ",", "title", "=", "\"\"", ",", "horizontal", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "# book it, it will be created by Plotter.show() later", "self", ".", "scalar...
36.222222
0.008982
def show_kernel_error(self, error): """Show kernel initialization errors in infowidget.""" # Replace end of line chars with <br> eol = sourcecode.get_eol_chars(error) if eol: error = error.replace(eol, '<br>') # Don't break lines in hyphens # From htt...
[ "def", "show_kernel_error", "(", "self", ",", "error", ")", ":", "# Replace end of line chars with <br>\r", "eol", "=", "sourcecode", ".", "get_eol_chars", "(", "error", ")", "if", "eol", ":", "error", "=", "error", ".", "replace", "(", "eol", ",", "'<br>'", ...
34.269231
0.002183
def make_filename_hash(key): """Convert the given key (a simple Python object) to a unique-ish hash suitable for a filename. """ key_repr = repr(key).replace(BASE_DIR, '').encode('utf8') # This is really stupid but necessary for making the repr()s be the same on # Python 2 and 3 and thus allowin...
[ "def", "make_filename_hash", "(", "key", ")", ":", "key_repr", "=", "repr", "(", "key", ")", ".", "replace", "(", "BASE_DIR", ",", "''", ")", ".", "encode", "(", "'utf8'", ")", "# This is really stupid but necessary for making the repr()s be the same on", "# Python ...
51.8
0.001264
def query(self): """Runs an fstat for this file and repopulates the data""" self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0] self._head = HeadRevision(self._p4dict) self._filename = self.depotFile
[ "def", "query", "(", "self", ")", ":", "self", ".", "_p4dict", "=", "self", ".", "_connection", ".", "run", "(", "[", "'fstat'", ",", "'-m'", ",", "'1'", ",", "self", ".", "_p4dict", "[", "'depotFile'", "]", "]", ")", "[", "0", "]", "self", ".", ...
37.571429
0.011152
def ScrollIntoView(self, alignTop: bool = True, waitTime: float = OPERATION_WAIT_TIME) -> bool: """ Call IUIAutomationTextRange::ScrollIntoView. Cause the text control to scroll until the text range is visible in the viewport. alignTop: bool, True if the text control should be scrolled s...
[ "def", "ScrollIntoView", "(", "self", ",", "alignTop", ":", "bool", "=", "True", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "bool", ":", "ret", "=", "self", ".", "textRange", ".", "ScrollIntoView", "(", "int", "(", "alignTop", ...
61.923077
0.008568
def add_resources(self, resources): """ Add faked child resources to this resource, from the provided resource definitions. Duplicate resource names in the same scope are not permitted. Although this method is typically used to initially load the faked HMC with resource...
[ "def", "add_resources", "(", "self", ",", "resources", ")", ":", "for", "child_attr", "in", "resources", ":", "child_list", "=", "resources", "[", "child_attr", "]", "self", ".", "_process_child_list", "(", "self", ",", "child_attr", ",", "child_list", ")" ]
42.553398
0.000446
def get_releasenotes(repo_path, from_commit=None, bugtracker_url=''): """ Given a repo and optionally a base revision to start from, will return a text suitable for the relase notes announcement, grouping the bugs, the features and the api-breaking changes. Args: repo_path(str): Path to the...
[ "def", "get_releasenotes", "(", "repo_path", ",", "from_commit", "=", "None", ",", "bugtracker_url", "=", "''", ")", ":", "repo", "=", "dulwich", ".", "repo", ".", "Repo", "(", "repo_path", ")", "tags", "=", "get_tags", "(", "repo", ")", "refs", "=", "...
30.223077
0.000246
def not_found(self, *args, **kwargs): """Defines the handler that should handle not found requests against this API""" kwargs['api'] = self.api return not_found(*args, **kwargs)
[ "def", "not_found", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'api'", "]", "=", "self", ".", "api", "return", "not_found", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
49.5
0.014925
def in_cache(self, zenpy_object): """ Determine whether or not this object is in the cache """ object_type = get_object_type(zenpy_object) cache_key_attr = self._cache_key_attribute(object_type) return self.get(object_type, getattr(zenpy_object, cache_key_attr)) is not None
[ "def", "in_cache", "(", "self", ",", "zenpy_object", ")", ":", "object_type", "=", "get_object_type", "(", "zenpy_object", ")", "cache_key_attr", "=", "self", ".", "_cache_key_attribute", "(", "object_type", ")", "return", "self", ".", "get", "(", "object_type",...
60.4
0.009804
def _simUnitVcd(simModel, stimulFunctions, outputFile, until): """ :param unit: interface level unit to simulate :param stimulFunctions: iterable of function(env) (simpy environment) which are driving the simulation :param outputFile: file where vcd will be dumped :param time: endtime of sim...
[ "def", "_simUnitVcd", "(", "simModel", ",", "stimulFunctions", ",", "outputFile", ",", "until", ")", ":", "sim", "=", "HdlSimulator", "(", ")", "# configure simulator to log in vcd", "sim", ".", "config", "=", "VcdHdlSimConfig", "(", "outputFile", ")", "# run simu...
37.611111
0.001441
def main(): """ NAME pt_rot.py DESCRIPTION rotates pt according to specified age and plate SYNTAX pt_rot.py [command line options] OPTIONS -h prints help and quits -f file with lon lat plate age Dplate as space delimited input Dplate is the de...
[ "def", "main", "(", ")", ":", "dir_path", "=", "'.'", "PTS", "=", "[", "]", "ResRecs", "=", "[", "]", "ofile", "=", "\"\"", "data_model", "=", "3", "Dplates", "=", "[", "'nwaf'", ",", "'neaf'", ",", "'saf'", ",", "'aus'", ",", "'eur'", ",", "'ind...
37.325926
0.02919
def _convert_to_spans(self, tree, start, set, parent = None): "Convert a tree into spans (X, i, j) and add to a set." if len(tree) == 3: # Binary rule. # Remove unary collapsing. current = self._remove_vertical_markovization(tree[0]).split("+") split = s...
[ "def", "_convert_to_spans", "(", "self", ",", "tree", ",", "start", ",", "set", ",", "parent", "=", "None", ")", ":", "if", "len", "(", "tree", ")", "==", "3", ":", "# Binary rule.", "# Remove unary collapsing.", "current", "=", "self", ".", "_remove_verti...
40.625
0.01002
def mavlink_packet(self, m): '''handle an incoming mavlink packet''' if m.get_type() == 'PPP' and self.ppp_fd != -1: print("got ppp mavlink pkt len=%u" % m.length) os.write(self.ppp_fd, m.data[:m.length])
[ "def", "mavlink_packet", "(", "self", ",", "m", ")", ":", "if", "m", ".", "get_type", "(", ")", "==", "'PPP'", "and", "self", ".", "ppp_fd", "!=", "-", "1", ":", "print", "(", "\"got ppp mavlink pkt len=%u\"", "%", "m", ".", "length", ")", "os", ".",...
48
0.008197
def process_mavlink_packet(self, m): '''handle an incoming mavlink packet''' mtype = m.get_type() # if you add processing for an mtype here, remember to add it # to mavlink_packet, above if mtype in ['WAYPOINT_COUNT','MISSION_COUNT']: if (self.num_wps_expected == 0):...
[ "def", "process_mavlink_packet", "(", "self", ",", "m", ")", ":", "mtype", "=", "m", ".", "get_type", "(", ")", "# if you add processing for an mtype here, remember to add it", "# to mavlink_packet, above", "if", "mtype", "in", "[", "'WAYPOINT_COUNT'", ",", "'MISSION_CO...
51.15
0.009592
def inner(self, x1, x2): """Return the inner product of ``x1`` and ``x2``. Parameters ---------- x1, x2 : `LinearSpaceElement` Elements whose inner product to compute. Returns ------- inner : `LinearSpace.field` element Inner product of `...
[ "def", "inner", "(", "self", ",", "x1", ",", "x2", ")", ":", "if", "x1", "not", "in", "self", ":", "raise", "LinearSpaceTypeError", "(", "'`x1` {!r} is not an element of '", "'{!r}'", ".", "format", "(", "x1", ",", "self", ")", ")", "if", "x2", "not", ...
34.125
0.002375
def i_from_v(resistance_shunt, resistance_series, nNsVth, voltage, saturation_current, photocurrent, method='lambertw'): ''' Device current at the given device voltage for the single diode model. Uses the single diode model (SDM) as described in, e.g., Jain and Kapoor 2004 [1]. The so...
[ "def", "i_from_v", "(", "resistance_shunt", ",", "resistance_series", ",", "nNsVth", ",", "voltage", ",", "saturation_current", ",", "photocurrent", ",", "method", "=", "'lambertw'", ")", ":", "if", "method", ".", "lower", "(", ")", "==", "'lambertw'", ":", ...
39.918605
0.001421
def get_auth_token(self, user): """ Returns the user's authentication token. """ data = [str(user.id), self.security.hashing_context.hash(encode_string(user._password))] return self.security.remember_token_serializer.dumps(data)
[ "def", "get_auth_token", "(", "self", ",", "user", ")", ":", "data", "=", "[", "str", "(", "user", ".", "id", ")", ",", "self", ".", "security", ".", "hashing_context", ".", "hash", "(", "encode_string", "(", "user", ".", "_password", ")", ")", "]", ...
39.714286
0.010563
def get_total_time(cls): """Returns the total time taken across all results. :rtype: float """ cur = cls.get_cursor() q = "SELECT SUM(elapsed) FROM {}" cur.execute(q.format(cls.meta['table'])) result = cur.fetchone()['SUM(elapsed)'] return result ...
[ "def", "get_total_time", "(", "cls", ")", ":", "cur", "=", "cls", ".", "get_cursor", "(", ")", "q", "=", "\"SELECT SUM(elapsed) FROM {}\"", "cur", ".", "execute", "(", "q", ".", "format", "(", "cls", ".", "meta", "[", "'table'", "]", ")", ")", "result"...
32.9
0.008876
def anycast_mac(self, **kwargs): """Configure an anycast MAC address. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). mac (str): MAC address to configure (example: '0011.2233.4455'). delete (bool)...
[ "def", "anycast_mac", "(", "self", ",", "*", "*", "kwargs", ")", ":", "callback", "=", "kwargs", ".", "pop", "(", "'callback'", ",", "self", ".", "_callback", ")", "anycast_mac", "=", "getattr", "(", "self", ".", "_rbridge", ",", "'rbridge_id_ip_static_ag_...
47.898305
0.000693
def convert_pre(self, markup): """ Substitutes <pre> to Wikipedia markup by adding a space at the start of a line. """ for m in re.findall(self.re["preformatted"], markup): markup = markup.replace(m, m.replace("\n", "\n ")) markup = re.sub("<pre.*?>\n{0,...
[ "def", "convert_pre", "(", "self", ",", "markup", ")", ":", "for", "m", "in", "re", ".", "findall", "(", "self", ".", "re", "[", "\"preformatted\"", "]", ",", "markup", ")", ":", "markup", "=", "markup", ".", "replace", "(", "m", ",", "m", ".", "...
37.454545
0.016588
def validate(self, fixerrors=True): """ Validates that the feature is correctly formatted. Parameters: - **fixerrors** (optional): Attempts to fix minor errors without raising exceptions (defaults to True) Returns: - True if the feature is valid. Rais...
[ "def", "validate", "(", "self", ",", "fixerrors", "=", "True", ")", ":", "if", "not", "\"type\"", "in", "self", ".", "_data", "or", "self", ".", "_data", "[", "\"type\"", "]", "!=", "\"Feature\"", ":", "if", "fixerrors", ":", "self", ".", "_data", "[...
37.212121
0.011111
def create(self, xml): """ I take libvirt XML and start a new VM """ res = yield queue.executeInThread(self.connection.createXML, xml, 0) return self.DomainClass(self, res)
[ "def", "create", "(", "self", ",", "xml", ")", ":", "res", "=", "yield", "queue", ".", "executeInThread", "(", "self", ".", "connection", ".", "createXML", ",", "xml", ",", "0", ")", "return", "self", ".", "DomainClass", "(", "self", ",", "res", ")" ...
48.25
0.010204
def share_with_link(self, share_type='view', share_scope='anonymous'): """ Creates or returns a link you can share with others :param str share_type: 'view' to allow only view access, 'edit' to allow editions, and 'embed' to allow the DriveItem to be embedded :param str share_...
[ "def", "share_with_link", "(", "self", ",", "share_type", "=", "'view'", ",", "share_scope", "=", "'anonymous'", ")", ":", "if", "not", "self", ".", "object_id", ":", "return", "None", "url", "=", "self", ".", "build_url", "(", "self", ".", "_endpoints", ...
32.225806
0.001944
def run1(self): """Run one item (a callback or an RPC wait_any) or sleep. Returns: True if something happened; False if all queues are empty. """ delay = self.run0() if delay is None: return False if delay > 0: self.clock.sleep(delay) return True
[ "def", "run1", "(", "self", ")", ":", "delay", "=", "self", ".", "run0", "(", ")", "if", "delay", "is", "None", ":", "return", "False", "if", "delay", ">", "0", ":", "self", ".", "clock", ".", "sleep", "(", "delay", ")", "return", "True" ]
23.5
0.010239
def url_spec(transmute_path, handler, *args, **kwargs): """ convert the transmute_path to a tornado compatible regex, and return a tornado url object. """ p = _to_tornado_pattern(transmute_path) for m in METHODS: method = getattr(handler, m) if hasattr(method, "transmute_func...
[ "def", "url_spec", "(", "transmute_path", ",", "handler", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "p", "=", "_to_tornado_pattern", "(", "transmute_path", ")", "for", "m", "in", "METHODS", ":", "method", "=", "getattr", "(", "handler", ",", ...
30.066667
0.002151
def _create_topple_graph(cvh_mesh, com): """ Constructs a toppling digraph for the given convex hull mesh and center of mass. Each node n_i in the digraph corresponds to a face f_i of the mesh and is labelled with the probability that the mesh will land on f_i if dropped randomly. Not all faces...
[ "def", "_create_topple_graph", "(", "cvh_mesh", ",", "com", ")", ":", "adj_graph", "=", "nx", ".", "Graph", "(", ")", "topple_graph", "=", "nx", ".", "DiGraph", "(", ")", "# Create face adjacency graph", "face_pairs", "=", "cvh_mesh", ".", "face_adjacency", "e...
34.675676
0.000379
def data(self): """ Get the content for the response (lazily decoded). """ if self._data is None: self._data = self.response.content.decode("utf-8") return self._data
[ "def", "data", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_data", "=", "self", ".", "response", ".", "content", ".", "decode", "(", "\"utf-8\"", ")", "return", "self", ".", "_data" ]
30.285714
0.009174
def login(self): """ Logs the user in. The log in information is saved in the client - userid - username - cookies :return: The raw response from the request """ if self.options['token']: self.client.token = self.options['token'] result = self.users.get_user('me') else: response = self...
[ "def", "login", "(", "self", ")", ":", "if", "self", ".", "options", "[", "'token'", "]", ":", "self", ".", "client", ".", "token", "=", "self", ".", "options", "[", "'token'", "]", "result", "=", "self", ".", "users", ".", "get_user", "(", "'me'",...
23.945946
0.035792
def numeric_params(self): """Return a dict containing all (key, values) stored in '/parameters' """ nparams = dict() for p in self.h5file.root.parameters: nparams[p.name] = p.read() return nparams
[ "def", "numeric_params", "(", "self", ")", ":", "nparams", "=", "dict", "(", ")", "for", "p", "in", "self", ".", "h5file", ".", "root", ".", "parameters", ":", "nparams", "[", "p", ".", "name", "]", "=", "p", ".", "read", "(", ")", "return", "npa...
34.571429
0.008065
def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices ...
[ "def", "start_file", "(", "filename", ")", ":", "from", "qtpy", ".", "QtCore", "import", "QUrl", "from", "qtpy", ".", "QtGui", "import", "QDesktopServices", "# We need to use setUrl instead of setPath because this is the only\r", "# cross-platform way to open external files. se...
33.944444
0.001592
def check_response(response): """ checks the response if the server returned an error raises an exception. """ if response.status_code < 200 or response.status_code > 300: raise ServerError('API requests returned with error: %s' % response.status_code) try: ...
[ "def", "check_response", "(", "response", ")", ":", "if", "response", ".", "status_code", "<", "200", "or", "response", ".", "status_code", ">", "300", ":", "raise", "ServerError", "(", "'API requests returned with error: %s'", "%", "response", ".", "status_code",...
35.681818
0.001241
def on_epoch_end(self, epoch:int, **kwargs:Any)->None: "Compare the value monitored to its best score and maybe save the model." if self.every=="epoch": self.learn.save(f'{self.name}_{epoch}') else: #every="improvement" current = self.get_monitor_value() if current is not...
[ "def", "on_epoch_end", "(", "self", ",", "epoch", ":", "int", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "self", ".", "every", "==", "\"epoch\"", ":", "self", ".", "learn", ".", "save", "(", "f'{self.name}_{epoch}'", ")", "els...
60
0.020073
def gradient(self): """The gradient operator.""" return (ScalingOperator(self.domain, 1 / self.sigma) - (1 / self.sigma) * self.functional.proximal(self.sigma))
[ "def", "gradient", "(", "self", ")", ":", "return", "(", "ScalingOperator", "(", "self", ".", "domain", ",", "1", "/", "self", ".", "sigma", ")", "-", "(", "1", "/", "self", ".", "sigma", ")", "*", "self", ".", "functional", ".", "proximal", "(", ...
47.25
0.010417
def user_picklist(i_info, command): """Display list of instances matching args and ask user to select target. Instance list displayed and user asked to enter the number corresponding to the desired target instance, or '0' to abort. Args: i_info (dict): information on instances and details. ...
[ "def", "user_picklist", "(", "i_info", ",", "command", ")", ":", "valid_entry", "=", "False", "awsc", ".", "get_all_aminames", "(", "i_info", ")", "list_instances", "(", "i_info", ",", "\"\"", ",", "True", ")", "msg_txt", "=", "(", "\"Enter {0}#{1} of instance...
37.814815
0.000955
def lmx_base(): """Transformer on languagemodel_lm1b32k_packed. 50M Params.""" hparams = transformer.transformer_tpu() # sharing is counterproductive when underparameterized hparams.shared_embedding_and_softmax_weights = False # we judge by log-ppl, so label smoothing hurts. hparams.label_smoothing = 0.0 ...
[ "def", "lmx_base", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_tpu", "(", ")", "# sharing is counterproductive when underparameterized", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "# we judge by log-ppl, so label smoothing hurts.", ...
42.6875
0.022923
def sendfrom(self, account, address, amount): """send outgoing tx from specified account to a given address""" return self.req("sendfrom", [account, address, amount])
[ "def", "sendfrom", "(", "self", ",", "account", ",", "address", ",", "amount", ")", ":", "return", "self", ".", "req", "(", "\"sendfrom\"", ",", "[", "account", ",", "address", ",", "amount", "]", ")" ]
60
0.010989
def fetch_access_token(self, url, verifier=None, **request_kwargs): """Fetch an access token. This is the final step in the OAuth 1 workflow. An access token is obtained using all previously obtained credentials, including the verifier from the authorization step. Note that a p...
[ "def", "fetch_access_token", "(", "self", ",", "url", ",", "verifier", "=", "None", ",", "*", "*", "request_kwargs", ")", ":", "if", "verifier", ":", "self", ".", "_client", ".", "client", ".", "verifier", "=", "verifier", "if", "not", "getattr", "(", ...
46.147059
0.001873
def predict(self, features, verbose=False): """ Probability estimates of each feature See sklearn's SGDClassifier predict and predict_proba methods. Args: features (:obj:`list` of :obj:`list` of :obj:`float`) verbose: Boolean, optional. If true returns an array where ea...
[ "def", "predict", "(", "self", ",", "features", ",", "verbose", "=", "False", ")", ":", "probs", "=", "self", ".", "clf", ".", "predict_proba", "(", "features", ")", "if", "verbose", ":", "labels", "=", "self", ".", "labels", ".", "classes_", "res", ...
35.888889
0.00201
def crypto_box_beforenm(pk, sk): """ Computes and returns the shared key for the public key ``pk`` and the secret key ``sk``. This can be used to speed up operations where the same set of keys is going to be used multiple times. :param pk: bytes :param sk: bytes :rtype: bytes """ if...
[ "def", "crypto_box_beforenm", "(", "pk", ",", "sk", ")", ":", "if", "len", "(", "pk", ")", "!=", "crypto_box_PUBLICKEYBYTES", ":", "raise", "exc", ".", "ValueError", "(", "\"Invalid public key\"", ")", "if", "len", "(", "sk", ")", "!=", "crypto_box_SECRETKEY...
30.875
0.001309
def beacon(config): ''' Poll vmadm for changes ''' ret = [] # NOTE: lookup current images current_vms = __salt__['vmadm.list']( keyed=True, order='uuid,state,alias,hostname,dns_domain', ) # NOTE: apply configuration if VMADM_STATE['first_run']: log.info('App...
[ "def", "beacon", "(", "config", ")", ":", "ret", "=", "[", "]", "# NOTE: lookup current images", "current_vms", "=", "__salt__", "[", "'vmadm.list'", "]", "(", "keyed", "=", "True", ",", "order", "=", "'uuid,state,alias,hostname,dns_domain'", ",", ")", "# NOTE: ...
28.816901
0.00189
def set_image(self, text): """ Save image resource at `text` (path or url) to storage, then return the replacement string and the necessary exercicse image file object. Args: - text (str): path or url to parse as an exercise image resource Returns: (new_text, files) ...
[ "def", "set_image", "(", "self", ",", "text", ")", ":", "# Make sure `text` hasn't already been processed", "if", "exercises", ".", "CONTENT_STORAGE_PLACEHOLDER", "in", "text", ":", "return", "text", ",", "[", "]", "# Strip `text` of whitespace", "stripped_text", "=", ...
52.947368
0.001952
def _init(frame, log_level=ERROR): ''' Enables explicit relative import in sub-modules when ran as __main__ :param log_level: module's inner logger level (equivalent to logging pkg) ''' global _log_level _log_level = log_level # now we have access to the module globals main_globals = fra...
[ "def", "_init", "(", "frame", ",", "log_level", "=", "ERROR", ")", ":", "global", "_log_level", "_log_level", "=", "log_level", "# now we have access to the module globals", "main_globals", "=", "frame", ".", "f_globals", "# If __package__ set or it isn't the __main__, stop...
38.666667
0.001052