text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _peek_table(self): # type: () -> Tuple[bool, str] """ Peeks ahead non-intrusively by cloning then restoring the initial state of the parser. Returns the name of the table about to be parsed, as well as whether it is part of an AoT. """ # we always want to re...
[ "def", "_peek_table", "(", "self", ")", ":", "# type: () -> Tuple[bool, str]", "# we always want to restore after exiting this scope", "with", "self", ".", "_state", "(", "save_marker", "=", "True", ",", "restore", "=", "True", ")", ":", "if", "self", ".", "_current...
31.482759
0.002125
def fetch_s3_package(self, config): """Make a remote S3 archive available for local use. Args: config (dict): git config dictionary """ extractor_map = {'.tar.gz': TarGzipExtractor, '.tar': TarExtractor, '.zip': ZipExtractor...
[ "def", "fetch_s3_package", "(", "self", ",", "config", ")", ":", "extractor_map", "=", "{", "'.tar.gz'", ":", "TarGzipExtractor", ",", "'.tar'", ":", "TarExtractor", ",", "'.zip'", ":", "ZipExtractor", "}", "extractor", "=", "None", "for", "suffix", ",", "kl...
45.113402
0.000447
def save_root(histogram: HistogramBase, path: str, name: Optional[str] = None): """Write histogram to a (new) ROOT file. Parameters ---------- histogram : Any histogram path: path for the output file (perhaps should not exist?) name : The name of the histogram inside the file """ if nam...
[ "def", "save_root", "(", "histogram", ":", "HistogramBase", ",", "path", ":", "str", ",", "name", ":", "Optional", "[", "str", "]", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "histogram", ".", "name", "if", "os", ".", "pat...
32.5
0.001661
def pathIndex(self, path): '''Return index of item with *path*.''' if path == self.root.path: return QModelIndex() if not path.startswith(self.root.path): return QModelIndex() parts = [] while True: if path == self.root.path: ...
[ "def", "pathIndex", "(", "self", ",", "path", ")", ":", "if", "path", "==", "self", ".", "root", ".", "path", ":", "return", "QModelIndex", "(", ")", "if", "not", "path", ".", "startswith", "(", "self", ".", "root", ".", "path", ")", ":", "return",...
24.627907
0.001817
def dbapi(conf=cfg.CONF): """Retrieves an instance of the configured database API. :param oslo_config.cfg.ConfigOpts conf: an instance of the configuration file :return: database API instance :rtype: :class:`~tvrenamer.cache.api.DatabaseAPI` """ globa...
[ "def", "dbapi", "(", "conf", "=", "cfg", ".", "CONF", ")", ":", "global", "_DBAPI", "if", "_DBAPI", "is", "None", ":", "_DBAPI", "=", "api", ".", "DatabaseAPI", "(", "conf", ")", "return", "_DBAPI" ]
30.538462
0.002445
def sample(self, sample_indices=None, num_samples=1): """ returns samples according to the KDE Parameters ---------- sample_inices: list of ints Indices into the training data used as centers for the samples num_samples: int if samples_indices is None, this specifies how many samples ...
[ "def", "sample", "(", "self", ",", "sample_indices", "=", "None", ",", "num_samples", "=", "1", ")", ":", "if", "sample_indices", "is", "None", ":", "sample_indices", "=", "np", ".", "random", ".", "choice", "(", "self", ".", "data", ".", "shape", "[",...
33.117647
0.035375
def kl_divergence(V_a, V_b): """ Calculate Kullback-Leibler distance. Uses the smoothing method described in `Bigi 2003 <http://lvk.cs.msu.su/~bruzz/articles/classification/Using%20Kullback-Leibler%20Distance%20for%20Text%20Categorization.pdf>`_ to facilitate better comparisons between vectors desc...
[ "def", "kl_divergence", "(", "V_a", ",", "V_b", ")", ":", "# Find shared features.", "Ndiff", "=", "_shared_features", "(", "V_a", ",", "V_b", ")", "# aprob and bprob should each sum to 1.0", "aprob", "=", "map", "(", "lambda", "v", ":", "float", "(", "v", ")"...
27.1
0.001188
def as_iso8601(self): """ example: 2016-08-13T00:38:05.210+00:00 """ if self.__date is None or self.__time is None: return None return "20%s-%s-%sT%s:%s:%s0Z" % \ (self.__date[4:], self.__date[2:4], self.__date[:2], self.__time[:2], self.__time[2:4], s...
[ "def", "as_iso8601", "(", "self", ")", ":", "if", "self", ".", "__date", "is", "None", "or", "self", ".", "__time", "is", "None", ":", "return", "None", "return", "\"20%s-%s-%sT%s:%s:%s0Z\"", "%", "(", "self", ".", "__date", "[", "4", ":", "]", ",", ...
36.333333
0.008955
def parsexml(Class, node, doc, **kwargs):#pylint: disable=bad-classmethod-argument """(Method for internal usage, see AbstractElement)""" if not kwargs: kwargs = {} if 'offset' in node.attrib: kwargs['offset'] = int(node.attrib['offset']) if 'ref' in node.attrib: ...
[ "def", "parsexml", "(", "Class", ",", "node", ",", "doc", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=bad-classmethod-argument", "if", "not", "kwargs", ":", "kwargs", "=", "{", "}", "if", "'offset'", "in", "node", ".", "attrib", ":", "kwargs", "...
52
0.018913
def find_variable_start_frequency(approximant, parameters, f_start, max_length, delta_f = 1): """ Find a frequency value above the starting frequency that results in a waveform shorter than max_length. """ l = max_length + 1 f = f_start - delta_f while l > max_l...
[ "def", "find_variable_start_frequency", "(", "approximant", ",", "parameters", ",", "f_start", ",", "max_length", ",", "delta_f", "=", "1", ")", ":", "l", "=", "max_length", "+", "1", "f", "=", "f_start", "-", "delta_f", "while", "l", ">", "max_length", ":...
41.75
0.011719
def get_data_frame(client, program, start, stop, resolution=None): """Executes the given program across the given time range (expressed in millisecond timestamps since Epoch), and returns a Pandas DataFrame containing the results, indexed by output timestamp. If the program contains multiple publish() ...
[ "def", "get_data_frame", "(", "client", ",", "program", ",", "start", ",", "stop", ",", "resolution", "=", "None", ")", ":", "data", "=", "{", "}", "metadata", "=", "{", "}", "c", "=", "client", ".", "execute", "(", "program", ",", "start", "=", "s...
41.173913
0.001032
def _get_system(model_folder): """Return the preprocessing description, the feature description and the model description.""" # Get model description model_description_file = os.path.join(model_folder, "info.yml") if not os.path.isfile(model_description_file): logging.error("You are prob...
[ "def", "_get_system", "(", "model_folder", ")", ":", "# Get model description", "model_description_file", "=", "os", ".", "path", ".", "join", "(", "model_folder", ",", "\"info.yml\"", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "model_description_f...
41.315789
0.001245
def perform_work( self): """perform_work Process handler function for processing messages found in the ``multiprocessing.Manager.queue`` Build the ``self.log_payload`` from the queued log messages and POST it to the Splunk endpoint """ self.debug_l...
[ "def", "perform_work", "(", "self", ")", ":", "self", ".", "debug_log", "(", "(", "'perform_work - start'", ")", ")", "self", ".", "tid", "=", "threading", ".", "current_thread", "(", ")", ".", "ident", "if", "self", ".", "sleep_interval", ">", "0", ":",...
34.48
0.000564
def connect(self, urls=None, **overrides): """Sets the acceptable HTTP method to CONNECT""" if urls is not None: overrides['urls'] = urls return self.where(accept='CONNECT', **overrides)
[ "def", "connect", "(", "self", ",", "urls", "=", "None", ",", "*", "*", "overrides", ")", ":", "if", "urls", "is", "not", "None", ":", "overrides", "[", "'urls'", "]", "=", "urls", "return", "self", ".", "where", "(", "accept", "=", "'CONNECT'", ",...
43.6
0.009009
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: bulk/install_content /api/hosts/:host_id/bulk/install_content errata /api/hosts/:host_id/errata power ...
[ "def", "path", "(", "self", ",", "which", "=", "None", ")", ":", "if", "which", "in", "(", "'enc'", ",", "'errata'", ",", "'errata/apply'", ",", "'errata/applicability'", ",", "'facts'", ",", "'packages'", ",", "'power'", ",", "'puppetclass_ids'", ",", "'s...
31.038462
0.001201
def bezier_by_line_intersections(bezier, line): """Returns tuples (t1,t2) such that bezier.point(t1) ~= line.point(t2).""" # The method here is to translate (shift) then rotate the complex plane so # that line starts at the origin and proceeds along the positive real axis. # After this transformation, t...
[ "def", "bezier_by_line_intersections", "(", "bezier", ",", "line", ")", ":", "# The method here is to translate (shift) then rotate the complex plane so", "# that line starts at the origin and proceeds along the positive real axis.", "# After this transformation, the intersection points are the ...
48.432432
0.000547
def get_prepare_by_id( self, prepare_id=None): """get_prepare_by_id :param prepare_id: MLJob.id in the database """ if not prepare_id: log.error("missing prepare_id for get_prepare_by_id") return self.build_response( statu...
[ "def", "get_prepare_by_id", "(", "self", ",", "prepare_id", "=", "None", ")", ":", "if", "not", "prepare_id", ":", "log", ".", "error", "(", "\"missing prepare_id for get_prepare_by_id\"", ")", "return", "self", ".", "build_response", "(", "status", "=", "ERROR"...
33.401961
0.00057
def bank_account_number(self): """Return the IBAN's Bank Account Number.""" start = get_iban_spec(self.country_code).bban_split_pos + 4 return self._id[start:]
[ "def", "bank_account_number", "(", "self", ")", ":", "start", "=", "get_iban_spec", "(", "self", ".", "country_code", ")", ".", "bban_split_pos", "+", "4", "return", "self", ".", "_id", "[", "start", ":", "]" ]
45
0.010929
def _send_invitation(self, enrollment, event): """Send an invitation mail to an open enrolment""" self.log('Sending enrollment status mail to user') self._send_mail(self.config.invitation_subject, self.config.invitation_mail, enrollment, event)
[ "def", "_send_invitation", "(", "self", ",", "enrollment", ",", "event", ")", ":", "self", ".", "log", "(", "'Sending enrollment status mail to user'", ")", "self", ".", "_send_mail", "(", "self", ".", "config", ".", "invitation_subject", ",", "self", ".", "co...
44.166667
0.011111
def parse_xml_jtl(self, granularity): """ Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second' :return: status...
[ "def", "parse_xml_jtl", "(", "self", ",", "granularity", ")", ":", "data", "=", "defaultdict", "(", "list", ")", "processed_data", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "list", ")", ")", ")", "for", ...
53.918919
0.009847
def cookiecutter( template, checkout=None, no_input=False, extra_context=None, replay=False, overwrite_if_exists=False, output_dir='.', config_file=None, default_config=False, password=None): """ Run Cookiecutter just as if using it from the command line. :param template: A director...
[ "def", "cookiecutter", "(", "template", ",", "checkout", "=", "None", ",", "no_input", "=", "False", ",", "extra_context", "=", "None", ",", "replay", "=", "False", ",", "overwrite_if_exists", "=", "False", ",", "output_dir", "=", "'.'", ",", "config_file", ...
35.727273
0.000354
def add_to_history(self, command): """Add command to history""" command = to_text_string(command) if command in ['', '\n'] or command.startswith('Traceback'): return if command.endswith('\n'): command = command[:-1] self.histidx = None if l...
[ "def", "add_to_history", "(", "self", ",", "command", ")", ":", "command", "=", "to_text_string", "(", "command", ")", "if", "command", "in", "[", "''", ",", "'\\n'", "]", "or", "command", ".", "startswith", "(", "'Traceback'", ")", ":", "return", "if", ...
41.269231
0.001821
def hysteresis_magic2(path_to_file='.', hyst_file="rmag_hysteresis.txt", save=False, save_folder='.', fmt="svg", plots=True): """ Calculates hysteresis parameters, saves them in rmag_hysteresis format file. If selected, this function also plots hysteresis loops, d...
[ "def", "hysteresis_magic2", "(", "path_to_file", "=", "'.'", ",", "hyst_file", "=", "\"rmag_hysteresis.txt\"", ",", "save", "=", "False", ",", "save_folder", "=", "'.'", ",", "fmt", "=", "\"svg\"", ",", "plots", "=", "True", ")", ":", "user", ",", "meas_fi...
45.827225
0.001006
def time(self, subname=None, class_=None): '''Returns a context manager to time execution of a block of code. :keyword subname: The subname to report data to :type subname: str :keyword class_: The :class:`~statsd.client.Client` subclass to use (e.g. :class:`~statsd.timer.Ti...
[ "def", "time", "(", "self", ",", "subname", "=", "None", ",", "class_", "=", "None", ")", ":", "if", "class_", "is", "None", ":", "class_", "=", "Timer", "timer", "=", "self", ".", "get_client", "(", "subname", ",", "class_", ")", "timer", ".", "st...
32.413793
0.002066
def create_hammersley_samples(order, dim=1, burnin=-1, primes=()): """ Create samples from the Hammersley set. For ``dim == 1`` the sequence falls back to Van Der Corput sequence. Args: order (int): The order of the Hammersley sequence. Defines the number of samples. dim (i...
[ "def", "create_hammersley_samples", "(", "order", ",", "dim", "=", "1", ",", "burnin", "=", "-", "1", ",", "primes", "=", "(", ")", ")", ":", "if", "dim", "==", "1", ":", "return", "create_halton_samples", "(", "order", "=", "order", ",", "dim", "=",...
36.633333
0.001773
def func_load(code, defaults=None, closure=None, globs=None): '''Deserialize user defined function.''' if isinstance(code, (tuple, list)): # unpack previous dump code, defaults, closure = code code = marshal.loads(code.encode('raw_unicode_escape')) if globs is None: globs = globals() ...
[ "def", "func_load", "(", "code", ",", "defaults", "=", "None", ",", "closure", "=", "None", ",", "globs", "=", "None", ")", ":", "if", "isinstance", "(", "code", ",", "(", "tuple", ",", "list", ")", ")", ":", "# unpack previous dump", "code", ",", "d...
47.454545
0.00188
def loxodrome_inverse(lat1: float, lon1: float, lat2: float, lon2: float, ell: Ellipsoid = None, deg: bool = True): """ computes the arc length and azimuth of the loxodrome between two points on the surface of the reference ellipsoid Parameters ---------- lat1 : float or ...
[ "def", "loxodrome_inverse", "(", "lat1", ":", "float", ",", "lon1", ":", "float", ",", "lat2", ":", "float", ",", "lon2", ":", "float", ",", "ell", ":", "Ellipsoid", "=", "None", ",", "deg", ":", "bool", "=", "True", ")", ":", "# set ellipsoid parame...
33.479452
0.001192
def set_level(self, command): """ Defines the logging level (from standard logging module) for log messages. :param command: The command object that holds all the necessary information from the remote process. """ if not command.console_only: self.log.setLevel(command...
[ "def", "set_level", "(", "self", ",", "command", ")", ":", "if", "not", "command", ".", "console_only", ":", "self", ".", "log", ".", "setLevel", "(", "command", ".", "level", ")", "self", ".", "console_level", "=", "command", ".", "level" ]
40.333333
0.010782
def zstack_proxy_iterator(self, s=0, c=0, t=0): """Return iterator of :class:`jicimagelib.image.ProxyImage` instances in the zstack. :param s: series :param c: channel :param t: timepoint :returns: zstack :class:`jicimagelib.image.ProxyImage` iterator """ ...
[ "def", "zstack_proxy_iterator", "(", "self", ",", "s", "=", "0", ",", "c", "=", "0", ",", "t", "=", "0", ")", ":", "for", "proxy_image", "in", "self", ":", "if", "proxy_image", ".", "in_zstack", "(", "s", "=", "s", ",", "c", "=", "c", ",", "t",...
38.363636
0.009259
def unmask(self, data, layers=None, output='array'): """ Reconstruct a masked vector into the original 3D volume. Args: data: The 1D vector to reconstruct. (Can also be a 2D vector where the second dimension is time, but then output will always be set to 'arra...
[ "def", "unmask", "(", "self", ",", "data", ",", "layers", "=", "None", ",", "output", "=", "'array'", ")", ":", "self", ".", "set_mask", "(", "layers", ")", "if", "data", ".", "ndim", "==", "2", ":", "n_volumes", "=", "data", ".", "shape", "[", "...
53.888889
0.00135
def readline(self, size = -1): """This reads and returns one entire line. A trailing newline is kept in the string, but may be absent when a file ends with an incomplete line. Note: This readline() looks for a \\r\\n pair even on UNIX because this is what the pseudo tty device returns. S...
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "==", "0", ":", "return", "self", ".", "_empty_buffer", "index", "=", "self", ".", "expect", "(", "[", "self", ".", "_pty_newline", ",", "self", ".", "delimiter", "...
54.875
0.008959
def first(self): """ Generate query parameters for the first page """ if self.total and self.limit < self.total: return {'page[offset]': 0, 'page[limit]': self.limit} else: return None
[ "def", "first", "(", "self", ")", ":", "if", "self", ".", "total", "and", "self", ".", "limit", "<", "self", ".", "total", ":", "return", "{", "'page[offset]'", ":", "0", ",", "'page[limit]'", ":", "self", ".", "limit", "}", "else", ":", "return", ...
32.428571
0.008584
def delete_item(self, tablename, key, expected=None, returns=NONE, return_capacity=None, expect_or=False, **kwargs): """ Delete an item This uses the older version of the DynamoDB API. See also: :meth:`~.delete_item2`. Parameters ---------- t...
[ "def", "delete_item", "(", "self", ",", "tablename", ",", "key", ",", "expected", "=", "None", ",", "returns", "=", "NONE", ",", "return_capacity", "=", "None", ",", "expect_or", "=", "False", ",", "*", "*", "kwargs", ")", ":", "key", "=", "self", "....
44.270833
0.001381
def generic_visit(self, node): """Surround node statement with a try/except block to catch errors. This method is called for every node of the parsed code, and only changes statement lines. Args: node (ast.AST): node statement to surround. """ if (isinstance...
[ "def", "generic_visit", "(", "self", ",", "node", ")", ":", "if", "(", "isinstance", "(", "node", ",", "ast", ".", "stmt", ")", "and", "not", "isinstance", "(", "node", ",", "ast", ".", "FunctionDef", ")", ")", ":", "new_node", "=", "self", ".", "w...
32.961538
0.002268
def getc(self, block=True): """Return one character from the input queue""" try: return self.cookedq.get(block) except gevent.queue.Empty: return ''
[ "def", "getc", "(", "self", ",", "block", "=", "True", ")", ":", "try", ":", "return", "self", ".", "cookedq", ".", "get", "(", "block", ")", "except", "gevent", ".", "queue", ".", "Empty", ":", "return", "''" ]
31.833333
0.010204
def import_all_modules(): """ <Purpose> Imports all modules within the modules folder. This should only be called once throughout the entire execution of seash. <Side Effects> Modules that don't have collisions will have their commanddicts and helptexts loaded and returned. <Excep...
[ "def", "import_all_modules", "(", ")", ":", "for", "module_folder", "in", "get_installed_modules", "(", ")", ":", "try", ":", "if", "module_folder", "in", "module_data", ":", "raise", "seash_exceptions", ".", "ModuleImportError", "(", "\"Module already imported\"", ...
32.72
0.017815
def cast_vdata(vdata=None, vtype='REG_SZ'): ''' Cast the ``vdata` value to the appropriate data type for the registry type specified in ``vtype`` Args: vdata (str, int, list, bytes): The data to cast vtype (str): The type of data to be written to the registry. Must be one ...
[ "def", "cast_vdata", "(", "vdata", "=", "None", ",", "vtype", "=", "'REG_SZ'", ")", ":", "# Check data type and cast to expected type", "# int will automatically become long on 64bit numbers", "# https://www.python.org/dev/peps/pep-0237/", "registry", "=", "Registry", "(", ")",...
31.5
0.0011
def sigmar(Pot,r,dens=None,beta=0.): """ NAME: sigmar PURPOSE: Compute the radial velocity dispersion using the spherical Jeans equation INPUT: Pot - potential or list of potentials (evaluated at R=r/sqrt(2),z=r/sqrt(2), sphericity not checked) r - Galactocentric radius...
[ "def", "sigmar", "(", "Pot", ",", "r", ",", "dens", "=", "None", ",", "beta", "=", "0.", ")", ":", "Pot", "=", "flatten_pot", "(", "Pot", ")", "if", "dens", "is", "None", ":", "dens", "=", "lambda", "r", ":", "evaluateDensities", "(", "Pot", ",",...
32.2
0.014735
def _compute_phi_ss(C, mag, c1_dists, log_phi_ss, mean_phi_ss): """ Returns the embeded logic tree for single station sigma as defined to be used in the Swiss Hazard Model 2014: the single station sigma branching levels combines with equal weights: the phi_ss reported as function of magnitude as...
[ "def", "_compute_phi_ss", "(", "C", ",", "mag", ",", "c1_dists", ",", "log_phi_ss", ",", "mean_phi_ss", ")", ":", "phi_ss", "=", "0", "if", "mag", "<", "C", "[", "'Mc1'", "]", ":", "phi_ss", "=", "c1_dists", "elif", "mag", ">=", "C", "[", "'Mc1'", ...
33.375
0.001214
def copy(self): """ Return a copy of self. """ cls = self.__class__ result = cls.__new__(cls) result._default_plugins = dict(self._default_plugins) # pylint:disable=protected-access return result
[ "def", "copy", "(", "self", ")", ":", "cls", "=", "self", ".", "__class__", "result", "=", "cls", ".", "__new__", "(", "cls", ")", "result", ".", "_default_plugins", "=", "dict", "(", "self", ".", "_default_plugins", ")", "# pylint:disable=protected-access",...
30.625
0.011905
def owners(self): '''Read-only list of object owners, separated by the configured :attr:`OWNER_ID_SEPARATOR`, with whitespace stripped.''' return [o.strip() for o in self.owner.split(self.OWNER_ID_SEPARATOR)]
[ "def", "owners", "(", "self", ")", ":", "return", "[", "o", ".", "strip", "(", ")", "for", "o", "in", "self", ".", "owner", ".", "split", "(", "self", ".", "OWNER_ID_SEPARATOR", ")", "]" ]
57.25
0.008621
def _resetID(self): """Reset all ID fields.""" # Dirty.. .=)) self._setID((None,) * len(self._sqlPrimary)) self._new = True
[ "def", "_resetID", "(", "self", ")", ":", "# Dirty.. .=))", "self", ".", "_setID", "(", "(", "None", ",", ")", "*", "len", "(", "self", ".", "_sqlPrimary", ")", ")", "self", ".", "_new", "=", "True" ]
30.2
0.012903
def read_vest_pickle(gname, score_dir): """Read in VEST scores for given gene. Parameters ---------- gname : str name of gene score_dir : str directory containing vest scores Returns ------- gene_vest : dict or None dict containing vest scores for gene. Returns ...
[ "def", "read_vest_pickle", "(", "gname", ",", "score_dir", ")", ":", "vest_path", "=", "os", ".", "path", ".", "join", "(", "score_dir", ",", "gname", "+", "\".vest.pickle\"", ")", "if", "os", ".", "path", ".", "exists", "(", "vest_path", ")", ":", "if...
28.153846
0.001321
def calc_bias_correction_abc(acceleration, total_curvature): """ Calculate the bias correction constant for the approximate bootstrap confidence (ABC) intervals. Parameters ---------- acceleration : 1D ndarray of scalars. Should contain the ABC intervals' estimated acceleration constant...
[ "def", "calc_bias_correction_abc", "(", "acceleration", ",", "total_curvature", ")", ":", "inner_arg", "=", "2", "*", "norm", ".", "cdf", "(", "acceleration", ")", "*", "norm", ".", "cdf", "(", "-", "1", "*", "total_curvature", ")", "bias_correction", "=", ...
35.961538
0.001042
def get_t(self, var, coords=None): """ Get the time coordinate of a variable This method searches for the time coordinate in the :attr:`ds`. It first checks whether there is one dimension that holds an ``'axis'`` attribute with 'T', otherwise it looks whether there is an interse...
[ "def", "get_t", "(", "self", ",", "var", ",", "coords", "=", "None", ")", ":", "coords", "=", "coords", "or", "self", ".", "ds", ".", "coords", "coord", "=", "self", ".", "get_variable_by_axis", "(", "var", ",", "'t'", ",", "coords", ")", "if", "co...
40.578947
0.001267
def run(self): """Fetch and write items. This method runs the backend to fetch the items from the given origin. Items are converted to JSON objects and written to the defined output. If `fetch-archive` parameter was given as an argument during the inizialization of the ...
[ "def", "run", "(", "self", ")", ":", "backend_args", "=", "vars", "(", "self", ".", "parsed_args", ")", "category", "=", "backend_args", ".", "pop", "(", "'category'", ",", "None", ")", "filter_classified", "=", "backend_args", ".", "pop", "(", "'filter_cl...
41.473684
0.00186
def generate_diff_subparser(subparsers): """Adds a sub-command parser to `subparsers` to make a diff query.""" parser = subparsers.add_parser( 'diff', description=constants.DIFF_DESCRIPTION, epilog=constants.DIFF_EPILOG, formatter_class=ParagraphFormatter, help=constants.DIFF_HELP) ...
[ "def", "generate_diff_subparser", "(", "subparsers", ")", ":", "parser", "=", "subparsers", ".", "add_parser", "(", "'diff'", ",", "description", "=", "constants", ".", "DIFF_DESCRIPTION", ",", "epilog", "=", "constants", ".", "DIFF_EPILOG", ",", "formatter_class"...
44.2
0.001477
def cartesian(shape): r"""Cartesian indexing. Returns a sequence of n-tuples indexing each element of a hypothetical matrix of the given shape. Args: shape (tuple): tuple of dimensions. Returns: array_like: indices. Example ------- .. doctest:: >>> from nump...
[ "def", "cartesian", "(", "shape", ")", ":", "n", "=", "len", "(", "shape", ")", "idx", "=", "[", "slice", "(", "0", ",", "s", ")", "for", "s", "in", "shape", "]", "g", "=", "rollaxis", "(", "mgrid", "[", "idx", "]", ",", "0", ",", "n", "+",...
18.941176
0.001477
def get(self, key_id=None): """ Get one of the ssh keys associated with your account. """ url = self.bitbucket.url('GET_SSH_KEY', key_id=key_id) return self.bitbucket.dispatch('GET', url, auth=self.bitbucket.auth)
[ "def", "get", "(", "self", ",", "key_id", "=", "None", ")", ":", "url", "=", "self", ".", "bitbucket", ".", "url", "(", "'GET_SSH_KEY'", ",", "key_id", "=", "key_id", ")", "return", "self", ".", "bitbucket", ".", "dispatch", "(", "'GET'", ",", "url",...
48.2
0.008163
def resources(self, start=1, num=10): """ Resources lists all file resources for the organization. The start and num paging parameters are supported. Inputs: start - the number of the first entry in the result set response ...
[ "def", "resources", "(", "self", ",", "start", "=", "1", ",", "num", "=", "10", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/resources\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"start\"", ":", "start", ",", "\"num\"", ":", "nu...
36.608696
0.012731
def run_expect_command(self, cmd, expect_end=None, timeout=3, wait_seconds=2): """ 执行 shell 命令并获取返回结果 :param timeout: :param wait_seconds: :param cmd: :param expect_end: :return: """ shell = self.ssh_session.invoke_shell() last_time = int(t...
[ "def", "run_expect_command", "(", "self", ",", "cmd", ",", "expect_end", "=", "None", ",", "timeout", "=", "3", ",", "wait_seconds", "=", "2", ")", ":", "shell", "=", "self", ".", "ssh_session", ".", "invoke_shell", "(", ")", "last_time", "=", "int", "...
26.666667
0.00201
def partition(a, sz): """splits iterables a in equal parts of size sz""" return [a[i:i+sz] for i in range(0, len(a), sz)]
[ "def", "partition", "(", "a", ",", "sz", ")", ":", "return", "[", "a", "[", "i", ":", "i", "+", "sz", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "a", ")", ",", "sz", ")", "]" ]
42.666667
0.015385
def draw_matplotlib_figure(self, figure): """Draws matplotlib figure to context""" class CustomRendererCairo(RendererCairo): """Workaround for older versins with limited draw path length""" if sys.byteorder == 'little': BYTE_FORMAT = 0 # BGRA else: ...
[ "def", "draw_matplotlib_figure", "(", "self", ",", "figure", ")", ":", "class", "CustomRendererCairo", "(", "RendererCairo", ")", ":", "\"\"\"Workaround for older versins with limited draw path length\"\"\"", "if", "sys", ".", "byteorder", "==", "'little'", ":", "BYTE_FOR...
34.271429
0.00081
def source_attr(attr_name): """ Creates a getter that will drop the current value and retrieve the source's attribute with specified name. @param attr_name: the name of an attribute belonging to the source. @type attr_name: str """ def source_attr(_value, context, **_params): value ...
[ "def", "source_attr", "(", "attr_name", ")", ":", "def", "source_attr", "(", "_value", ",", "context", ",", "*", "*", "_params", ")", ":", "value", "=", "getattr", "(", "context", "[", "\"model\"", "]", ".", "source", ",", "attr_name", ")", "return", "...
31.153846
0.002398
def parse_binary(self, data, display, rawdict = 0): """values, remdata = s.parse_binary(data, display, rawdict = 0) Convert a binary representation of the structure into Python values. DATA is a string or a buffer containing the binary data. DISPLAY should be a Xlib.protocol.display.D...
[ "def", "parse_binary", "(", "self", ",", "data", ",", "display", ",", "rawdict", "=", "0", ")", ":", "ret", "=", "{", "}", "val", "=", "struct", ".", "unpack", "(", "self", ".", "static_codes", ",", "data", "[", ":", "self", ".", "static_size", "]"...
35.276316
0.001814
def list_entries( self, projects, filter_="", order_by="", page_size=0, page_token=None ): """Return a page of log entry resources. :type projects: list of strings :param projects: project IDs to include. If not passed, defaults to the project bound to the A...
[ "def", "list_entries", "(", "self", ",", "projects", ",", "filter_", "=", "\"\"", ",", "order_by", "=", "\"\"", ",", "page_size", "=", "0", ",", "page_token", "=", "None", ")", ":", "page_iter", "=", "self", ".", "_gapic_api", ".", "list_log_entries", "(...
39.042553
0.002127
def onOffset(self, date): """Check if the given date is in the set of possible dates created using a length-one version of this offset class.""" return date.day == _days_in_month(date) and date.month == self.month
[ "def", "onOffset", "(", "self", ",", "date", ")", ":", "return", "date", ".", "day", "==", "_days_in_month", "(", "date", ")", "and", "date", ".", "month", "==", "self", ".", "month" ]
58.5
0.008439
def set_bot(self, bot): ''' Bot must be set before running ''' self.bot = bot self.sink.set_bot(bot)
[ "def", "set_bot", "(", "self", ",", "bot", ")", ":", "self", ".", "bot", "=", "bot", "self", ".", "sink", ".", "set_bot", "(", "bot", ")" ]
30.25
0.016129
def add_observer( self, callable_, entity_type=None, action=None, entity_id=None, predicate=None): """Register an "on-model-change" callback Once the model is connected, ``callable_`` will be called each time the model changes. ``callable_`` should be Awaitable a...
[ "def", "add_observer", "(", "self", ",", "callable_", ",", "entity_type", "=", "None", ",", "action", "=", "None", ",", "entity_id", "=", "None", ",", "predicate", "=", "None", ")", ":", "observer", "=", "_Observer", "(", "callable_", ",", "entity_type", ...
41.871795
0.001197
def shadow(self,new_root,visitor) : """ Runs through the query, creating a clone directory structure in the new_root. Then applies process""" for n in self.walk() : sn = n.clone(new_root) if n.isdir() : visitor.process_dir(n,sn) else : ...
[ "def", "shadow", "(", "self", ",", "new_root", ",", "visitor", ")", ":", "for", "n", "in", "self", ".", "walk", "(", ")", ":", "sn", "=", "n", ".", "clone", "(", "new_root", ")", "if", "n", ".", "isdir", "(", ")", ":", "visitor", ".", "process_...
42.375
0.031792
def transit_sunrise_sunset(dates, lat, lon, delta_t, numthreads): """ Calculate the sun transit, sunrise, and sunset for a set of dates at a given location. Parameters ---------- dates : array Numpy array of ints/floats corresponding to the Unix time for the dates of interest, m...
[ "def", "transit_sunrise_sunset", "(", "dates", ",", "lat", ",", "lon", ",", "delta_t", ",", "numthreads", ")", ":", "isnumpy", "=", "isinstance", "(", "dates", ",", "ndarray", ")", "if", "isnumpy", ":", "condition", "=", "(", "(", "dates", "%", "86400", ...
31.962406
0.002053
def update_forum_redirects_counter(sender, forum, user, request, response, **kwargs): """ Handles the update of the link redirects counter associated with link forums. """ if forum.is_link and forum.link_redirects: forum.link_redirects_count = F('link_redirects_count') + 1 forum.save()
[ "def", "update_forum_redirects_counter", "(", "sender", ",", "forum", ",", "user", ",", "request", ",", "response", ",", "*", "*", "kwargs", ")", ":", "if", "forum", ".", "is_link", "and", "forum", ".", "link_redirects", ":", "forum", ".", "link_redirects_co...
61.2
0.009677
def encode_ipmb_msg(header, data): """Encode an IPMB message. header: IPMB header object data: IPMI message data as bytestring Returns the message as bytestring. """ msg = array('B') msg.fromstring(header.encode()) if data is not None: a = array('B') a.fromstring(data)...
[ "def", "encode_ipmb_msg", "(", "header", ",", "data", ")", ":", "msg", "=", "array", "(", "'B'", ")", "msg", ".", "fromstring", "(", "header", ".", "encode", "(", ")", ")", "if", "data", "is", "not", "None", ":", "a", "=", "array", "(", "'B'", ")...
22.705882
0.002488
def get_oembed_data(url, max_width=None, max_height=None, **params): """ Fetch the OEmbed object, return the response as dictionary. """ if max_width: params['maxwidth'] = max_width if max_height: params['maxheight'] = max_height registry = get_oembed_providers() return registry.request(ur...
[ "def", "get_oembed_data", "(", "url", ",", "max_width", "=", "None", ",", "max_height", "=", "None", ",", "*", "*", "params", ")", ":", "if", "max_width", ":", "params", "[", "'maxwidth'", "]", "=", "max_width", "if", "max_height", ":", "params", "[", ...
36
0.009036
def multipublish(self, topic, messages, block=True, timeout=None, raise_error=True): """Publish an iterable of messages to the given topic. :param topic: the topic to publish to :param messages: iterable of bytestrings to publish :param block: wait for a connectio...
[ "def", "multipublish", "(", "self", ",", "topic", ",", "messages", ",", "block", "=", "True", ",", "timeout", "=", "None", ",", "raise_error", "=", "True", ")", ":", "result", "=", "AsyncResult", "(", ")", "conn", "=", "self", ".", "_get_connection", "...
37.060606
0.00239
def _parse_metadata_filename(self, metadata): """ Parse the header metadata to pull out the filename and then store it under the key 'filename' """ index = metadata['Content-Disposition'].index('=')+1 metadata['filename'] = metadata['Content-Disposition'][index:].replace('"', '')...
[ "def", "_parse_metadata_filename", "(", "self", ",", "metadata", ")", ":", "index", "=", "metadata", "[", "'Content-Disposition'", "]", ".", "index", "(", "'='", ")", "+", "1", "metadata", "[", "'filename'", "]", "=", "metadata", "[", "'Content-Disposition'", ...
48.285714
0.011628
def _get_cpu_info_from_sysinfo_v1(): ''' Returns the CPU info gathered from sysinfo. Returns {} if sysinfo is not found. ''' try: # Just return {} if there is no sysinfo if not DataSource.has_sysinfo(): return {} # If sysinfo fails return {} returncode, output = DataSource.sysinfo_cpu() if output == ...
[ "def", "_get_cpu_info_from_sysinfo_v1", "(", ")", ":", "try", ":", "# Just return {} if there is no sysinfo", "if", "not", "DataSource", ".", "has_sysinfo", "(", ")", ":", "return", "{", "}", "# If sysinfo fails return {}", "returncode", ",", "output", "=", "DataSourc...
29.385965
0.045061
def assert_boolean_true(expr, msg_fmt="{msg}"): """Fail the test unless the expression is the constant True. >>> assert_boolean_true(True) >>> assert_boolean_true("Hello World!") Traceback (most recent call last): ... AssertionError: 'Hello World!' is not True The following msg_fmt arg...
[ "def", "assert_boolean_true", "(", "expr", ",", "msg_fmt", "=", "\"{msg}\"", ")", ":", "if", "expr", "is", "not", "True", ":", "msg", "=", "\"{!r} is not True\"", ".", "format", "(", "expr", ")", "fail", "(", "msg_fmt", ".", "format", "(", "msg", "=", ...
30.764706
0.001855
def _process_notes(record, new_record): """ Populate the notes property using the provided new_record. If the new_record field was populated, assume that we want to replace the notes. If there are valid changes to be made, they will be added to the new_notes list. An empty list ...
[ "def", "_process_notes", "(", "record", ",", "new_record", ")", ":", "if", "\"notes\"", "not", "in", "new_record", "or", "not", "new_record", "[", "\"notes\"", "]", ":", "return", "False", "# This assumes any notes passed into the edit record are intended to", "# replac...
39.1
0.001871
def order(self, signal, symbol, quantity=0, **kwargs): """ Send an order for the selected instrument :Parameters: direction : string Order Type (BUY/SELL, EXIT/FLATTEN) symbol : string instrument symbol quantity : int ...
[ "def", "order", "(", "self", ",", "signal", ",", "symbol", ",", "quantity", "=", "0", ",", "*", "*", "kwargs", ")", ":", "self", ".", "log_algo", ".", "debug", "(", "'ORDER: %s %4d %s %s'", ",", "signal", ",", "quantity", ",", "symbol", ",", "kwargs", ...
34.056818
0.000649
def concat(self, other_datatable, inplace=False): """ Concatenates two DataTables together, as long as column names are identical (ignoring order). The resulting DataTable's columns are in the order of the table whose `concat` method was called. """ if not isinstance(othe...
[ "def", "concat", "(", "self", ",", "other_datatable", ",", "inplace", "=", "False", ")", ":", "if", "not", "isinstance", "(", "other_datatable", ",", "DataTable", ")", ":", "raise", "TypeError", "(", "\"`concat` requires a DataTable, not a %s\"", "%", "type", "(...
43.95122
0.001086
def decode_jsonld(jsonld_text): """Decode a JSON-LD dataset, including decoding datetime strings into `datetime.datetime` objects. Parameters ---------- encoded_dataset : `str` The JSON-LD dataset encoded as a string. Returns ------- jsonld_dataset : `dict` A JSON-LD da...
[ "def", "decode_jsonld", "(", "jsonld_text", ")", ":", "decoder", "=", "json", ".", "JSONDecoder", "(", "object_pairs_hook", "=", "_decode_object_pairs", ")", "return", "decoder", ".", "decode", "(", "jsonld_text", ")" ]
26.217391
0.0016
def scatter(input, devices, streams=None): """Scatters tensor across multiple GPUs. """ if streams is None: streams = [None] * len(devices) if isinstance(input, list): chunk_size = (len(input) - 1) // len(devices) + 1 outputs = [ scatter(input[i], [devices[i // chunk...
[ "def", "scatter", "(", "input", ",", "devices", ",", "streams", "=", "None", ")", ":", "if", "streams", "is", "None", ":", "streams", "=", "[", "None", "]", "*", "len", "(", "devices", ")", "if", "isinstance", "(", "input", ",", "list", ")", ":", ...
38.727273
0.001145
def generate_templates(self, exercise_questions=False): """ Create empty .csv files with the right headers and place them in the Will place files as siblings of directory `channeldir`. """ self.generate_template(channeldir=self.channeldir, filename=...
[ "def", "generate_templates", "(", "self", ",", "exercise_questions", "=", "False", ")", ":", "self", ".", "generate_template", "(", "channeldir", "=", "self", ".", "channeldir", ",", "filename", "=", "self", ".", "channelinfo", ",", "header", "=", "CHANNEL_INF...
54.333333
0.00201
def is_full(cm, nodes1, nodes2): """Test connectivity of one set of nodes to another. Args: cm (``np.ndarrray``): The connectivity matrix nodes1 (tuple[int]): The nodes whose outputs to ``nodes2`` will be tested. nodes2 (tuple[int]): The nodes whose inputs from ``nodes1`` wi...
[ "def", "is_full", "(", "cm", ",", "nodes1", ",", "nodes2", ")", ":", "if", "not", "nodes1", "or", "not", "nodes2", ":", "return", "True", "cm", "=", "cm", "[", "np", ".", "ix_", "(", "nodes1", ",", "nodes2", ")", "]", "# Do all nodes have at least one ...
33.956522
0.001245
def parse(cls, addr): """Parses a new `Uri` instance from a string representation of a URI. >>> u1 = Uri.parse('/foo/bar') >>> u1.node, u1.steps, u1.path, u1.name (None, ['', 'foo', 'bar'], '/foo/bar', 'bar') >>> u2 = Uri.parse('somenode:123/foo/bar') >>> u2.node, u1.ste...
[ "def", "parse", "(", "cls", ",", "addr", ")", ":", "if", "addr", ".", "endswith", "(", "'/'", ")", ":", "raise", "ValueError", "(", "\"Uris must not end in '/'\"", ")", "# pragma: no cover", "parts", "=", "addr", ".", "split", "(", "'/'", ")", "if", "':'...
37.703704
0.001916
def process_config(self, grab): """ Setup curl instance with values from ``self.config``. """ # Copy some config for future usage self.config_nobody = grab.config['nobody'] self.config_body_maxsize = grab.config['body_maxsize'] try: request_url = nor...
[ "def", "process_config", "(", "self", ",", "grab", ")", ":", "# Copy some config for future usage", "self", ".", "config_nobody", "=", "grab", ".", "config", "[", "'nobody'", "]", "self", ".", "config_body_maxsize", "=", "grab", ".", "config", "[", "'body_maxsiz...
43.546798
0.000442
def _delete_os_nwk(self, tenant_id, tenant_name, direc, is_fw_virt=False): """Delete the network created in Openstack. Function to delete Openstack network, It also releases the associated segmentation, VLAN and subnets. """ serv_obj = self.get_service_obj(tenant_id) fw_...
[ "def", "_delete_os_nwk", "(", "self", ",", "tenant_id", ",", "tenant_name", ",", "direc", ",", "is_fw_virt", "=", "False", ")", ":", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "fw_dict", "=", "serv_obj", ".", "get_fw_dict", "(", ...
42.023256
0.001082
def set_mtime(self, name, mtime, size): """Set modification time on file.""" self.check_write(name) os.utime(os.path.join(self.cur_dir, name), (-1, mtime))
[ "def", "set_mtime", "(", "self", ",", "name", ",", "mtime", ",", "size", ")", ":", "self", ".", "check_write", "(", "name", ")", "os", ".", "utime", "(", "os", ".", "path", ".", "join", "(", "self", ".", "cur_dir", ",", "name", ")", ",", "(", "...
44
0.011173
def get_migrations_dir(graph): """ Resolve the migrations directory path. Either take the directory from a component of the object graph or by using the metaata's path resolution facilities. """ try: migrations_dir = graph.migrations_dir except (LockedGraphError, NotBoundError): ...
[ "def", "get_migrations_dir", "(", "graph", ")", ":", "try", ":", "migrations_dir", "=", "graph", ".", "migrations_dir", "except", "(", "LockedGraphError", ",", "NotBoundError", ")", ":", "migrations_dir", "=", "graph", ".", "metadata", ".", "get_path", "(", "\...
31.625
0.001919
def set(self, key: str, value: Any) -> None: """ Stores a setting to the database of its object. The write to the database is performed immediately and the cache in the cache backend is flushed. The cache within this object will be updated correctly. """ wc = se...
[ "def", "set", "(", "self", ",", "key", ":", "str", ",", "value", ":", "Any", ")", "->", "None", ":", "wc", "=", "self", ".", "_write_cache", "(", ")", "if", "key", "in", "wc", ":", "s", "=", "wc", "[", "key", "]", "else", ":", "s", "=", "se...
34.529412
0.008292
def get_elements_attributes(parent_to_parse, element_path=None, attrib_name=None): """ :return: list of text representing an attribute of parent or each element at element path, or a list of dicts representing all the attributes parsed from each element """ attrs = _get_elements_property(p...
[ "def", "get_elements_attributes", "(", "parent_to_parse", ",", "element_path", "=", "None", ",", "attrib_name", "=", "None", ")", ":", "attrs", "=", "_get_elements_property", "(", "parent_to_parse", ",", "element_path", ",", "'attrib'", ")", "if", "not", "attrib_n...
38.916667
0.008368
def to_dict(self): """ extract the data of the content and return it as a dictionary """ # 1. extract the schema fields data = self.extract_fields() # 2. include custom key-value pairs listed in the mapping dictionary for key, attr in self.attributes.iteritems(): ...
[ "def", "to_dict", "(", "self", ")", ":", "# 1. extract the schema fields", "data", "=", "self", ".", "extract_fields", "(", ")", "# 2. include custom key-value pairs listed in the mapping dictionary", "for", "key", ",", "attr", "in", "self", ".", "attributes", ".", "i...
37.809524
0.002457
def ramping_values(period=360): """ Provides an infinite source of values representing a triangle wave (from 0 to 1 and back again) which repeats every *period* values. For example, to pulse an LED once a second:: from gpiozero import PWMLED from gpiozero.tools import ramping_values ...
[ "def", "ramping_values", "(", "period", "=", "360", ")", ":", "step", "=", "2", "/", "period", "value", "=", "0", "while", "True", ":", "yield", "value", "value", "+=", "step", "if", "isclose", "(", "value", ",", "1", ",", "abs_tol", "=", "1e-9", "...
26.30303
0.001111
def readPrefs(prefsfile, minpref=0, avgprefs=False, randprefs=False, seed=1, sites_as_strings=False): """Read preferences from file with some error checking. Args: `prefsfile` (string or readable file-like object) File holding amino-acid preferences. Can be comma-, space...
[ "def", "readPrefs", "(", "prefsfile", ",", "minpref", "=", "0", ",", "avgprefs", "=", "False", ",", "randprefs", "=", "False", ",", "seed", "=", "1", ",", "sites_as_strings", "=", "False", ")", ":", "assert", "minpref", ">=", "0", ",", "'minpref must be ...
41.421053
0.001861
def ExecutePackage(self,package_id,parameters={}): """Execute an existing Bluerprint package on the server. https://t3n.zendesk.com/entries/59727040-Execute-Package Requires package ID, currently only available by browsing control and browsing for the package itself. The UUID parameter is the package ID we n...
[ "def", "ExecutePackage", "(", "self", ",", "package_id", ",", "parameters", "=", "{", "}", ")", ":", "return", "(", "clc", ".", "v2", ".", "Requests", "(", "clc", ".", "v2", ".", "API", ".", "Call", "(", "'POST'", ",", "'operations/%s/servers/executePack...
41.9
0.03734
def callback(self, msg): """Accept a message that was published, process and forward Parameters ---------- msg : tuple, (str, str, str) The message sent over the line. The `tuple` is of the form: (message_type, channel, payload). Notes ----- ...
[ "def", "callback", "(", "self", ",", "msg", ")", ":", "message_type", ",", "channel", ",", "payload", "=", "msg", "if", "message_type", "!=", "'message'", ":", "return", "try", ":", "payload", "=", "self", ".", "_decode", "(", "payload", ")", "except", ...
27.868421
0.001825
def get_children( self, **kwargs ): ''' Recursively collects and returns all subtrees of given tree (if no arguments are given), or, alternatively, collects and returns subtrees satisfying some specific criteria (pre-specified in the arguments); Parameters ...
[ "def", "get_children", "(", "self", ",", "*", "*", "kwargs", ")", ":", "depth_limit", "=", "kwargs", ".", "get", "(", "'depth_limit'", ",", "922337203685477580", ")", "# Just a nice big number to", "# assure that by default, ", "# there is no depth limit ...", "include_...
51.72
0.012396
def _spawn_receiver_loop(self): """Spawns the reader loop. This is called internall by socketio_manage(). """ job = gevent.spawn(self._receiver_loop) self.jobs.append(job) return job
[ "def", "_spawn_receiver_loop", "(", "self", ")", ":", "job", "=", "gevent", ".", "spawn", "(", "self", ".", "_receiver_loop", ")", "self", ".", "jobs", ".", "append", "(", "job", ")", "return", "job" ]
32.142857
0.008658
def create(name, config=None, profile=None, network_profile=None, nic_opts=None, **kwargs): ''' Create a new container. name Name of the container config The config file to use for the container. Defaults to system-wide con...
[ "def", "create", "(", "name", ",", "config", "=", "None", ",", "profile", "=", "None", ",", "network_profile", "=", "None", ",", "nic_opts", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Required params for 'download' template", "download_template_deps", ...
32.938389
0.00014
async def refresh_token(self): """Refresh API token from KLF 200.""" json_response = await self.api_call('auth', 'login', {'password': self.config.password}, add_authorization_token=False) if 'token' not in json_response: raise PyVLXException('no element token found in response: {0}'...
[ "async", "def", "refresh_token", "(", "self", ")", ":", "json_response", "=", "await", "self", ".", "api_call", "(", "'auth'", ",", "'login'", ",", "{", "'password'", ":", "self", ".", "config", ".", "password", "}", ",", "add_authorization_token", "=", "F...
65.666667
0.010025
def buffer_read(self, frames=-1, dtype=None): """Read from the file and return data as buffer object. Reads the given number of `frames` in the given data format starting at the current read/write position. This advances the read/write position by the same number of frames. By ...
[ "def", "buffer_read", "(", "self", ",", "frames", "=", "-", "1", ",", "dtype", "=", "None", ")", ":", "frames", "=", "self", ".", "_check_frames", "(", "frames", ",", "fill_value", "=", "None", ")", "ctype", "=", "self", ".", "_check_dtype", "(", "dt...
36.647059
0.001564
def add_tagged_report_number(reading_line, len_reportnum, reportnum, startpos, true_replacement_index, extras): """In rebuilding the line, add an identified institutional ...
[ "def", "add_tagged_report_number", "(", "reading_line", ",", "len_reportnum", ",", "reportnum", ",", "startpos", ",", "true_replacement_index", ",", "extras", ")", ":", "rebuilt_line", "=", "u\"\"", "# The segment of the line that's being rebuilt to", "# include the tagged & ...
48.807692
0.000386
def get_files_from_github(user_and_repo, filedir, regex, prefer_tags): ''' Return dictionary of version:directory and directory has extracted files. ''' github_url = f'https://api.github.com/repos/{user_and_repo}' args = f'?per_page={N_RESULTS}' results = [] json_data = None # Determine the rig...
[ "def", "get_files_from_github", "(", "user_and_repo", ",", "filedir", ",", "regex", ",", "prefer_tags", ")", ":", "github_url", "=", "f'https://api.github.com/repos/{user_and_repo}'", "args", "=", "f'?per_page={N_RESULTS}'", "results", "=", "[", "]", "json_data", "=", ...
30.403846
0.001225
async def close(self): '''Stop listening for messages. ''' if self.push_connection: self._execute('PUNSUBSCRIBE') self._execute('UNSUBSCRIBE') await self.push_connection.close()
[ "async", "def", "close", "(", "self", ")", ":", "if", "self", ".", "push_connection", ":", "self", ".", "_execute", "(", "'PUNSUBSCRIBE'", ")", "self", ".", "_execute", "(", "'UNSUBSCRIBE'", ")", "await", "self", ".", "push_connection", ".", "close", "(", ...
33
0.008439
def get_participants_for_gradebook(gradebook_id, person=None): """ Returns a list of gradebook participants for the passed gradebook_id and person. """ if not valid_gradebook_id(gradebook_id): raise InvalidGradebookID(gradebook_id) url = "/rest/gradebook/v1/book/{}/participants".format(...
[ "def", "get_participants_for_gradebook", "(", "gradebook_id", ",", "person", "=", "None", ")", ":", "if", "not", "valid_gradebook_id", "(", "gradebook_id", ")", ":", "raise", "InvalidGradebookID", "(", "gradebook_id", ")", "url", "=", "\"/rest/gradebook/v1/book/{}/par...
27.857143
0.001653
def delete(self, path): """Send a delete request to the given path of the CRUD API. This deletes the object. Or at least tries to.""" return self.handleresult(self.r.delete(urljoin(self.url + CRUD_PATH, path)))
[ "def", "delete", "(", "self", ",", "path", ")", ":", "return", "self", ".", "handleresult", "(", "self", ".", "r", ".", "delete", "(", "urljoin", "(", "self", ".", "url", "+", "CRUD_PATH", ",", "path", ")", ")", ")" ]
69.5
0.010676
def validate_message(self, msg, *parameters): """Validates given message using template defined with `New Message` and field values given as optional arguments. Examples: | Validate message | ${msg} | | Validate message | ${msg} | status:0 | """ _, message_fields...
[ "def", "validate_message", "(", "self", ",", "msg", ",", "*", "parameters", ")", ":", "_", ",", "message_fields", ",", "header_fields", "=", "self", ".", "_get_parameters_with_defaults", "(", "parameters", ")", "self", ".", "_validate_message", "(", "msg", ","...
44.2
0.008869
def parsecounter(table, field, parsers=(('int', int), ('float', float))): """ Count the number of `str` or `unicode` values under the given fields that can be parsed as ints, floats or via custom parser functions. Return a pair of `Counter` objects, the first mapping parser names to the number of st...
[ "def", "parsecounter", "(", "table", ",", "field", ",", "parsers", "=", "(", "(", "'int'", ",", "int", ")", ",", "(", "'float'", ",", "float", ")", ")", ")", ":", "if", "isinstance", "(", "parsers", ",", "(", "list", ",", "tuple", ")", ")", ":", ...
34.714286
0.001334
def weighted_median(data, weights=None): """Calculate the weighted median of a list.""" if weights is None: return median(data) midpoint = 0.5 * sum(weights) if any([j > midpoint for j in weights]): return data[weights.index(max(weights))] if any([j > 0 for j in weights]): so...
[ "def", "weighted_median", "(", "data", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "return", "median", "(", "data", ")", "midpoint", "=", "0.5", "*", "sum", "(", "weights", ")", "if", "any", "(", "[", "j", ">", "midpo...
47.105263
0.001095