text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def try_add_variable(self, variable_name: str, replacement: VariableReplacement) -> None: """Try to add the variable with its replacement to the substitution. This considers an existing replacement and will only succeed if the new replacement can be merged with the old replacement. Merging can ...
[ "def", "try_add_variable", "(", "self", ",", "variable_name", ":", "str", ",", "replacement", ":", "VariableReplacement", ")", "->", "None", ":", "if", "variable_name", "not", "in", "self", ":", "self", "[", "variable_name", "]", "=", "replacement", ".", "co...
45.043478
22.673913
def setInstrumentParameters(self, instrpars): """ This method overrides the superclass to set default values into the parameter dictionary, in case empty entries are provided. """ pri_header = self._image[0].header if self._isNotValid (instrpars['gain'], instrpars['gnkeyword...
[ "def", "setInstrumentParameters", "(", "self", ",", "instrpars", ")", ":", "pri_header", "=", "self", ".", "_image", "[", "0", "]", ".", "header", "if", "self", ".", "_isNotValid", "(", "instrpars", "[", "'gain'", "]", ",", "instrpars", "[", "'gnkeyword'",...
49.6
26.6
def _update_criteria_with_filters(self, query, section_name): """ This method updates the 'query' dictionary with the criteria stored in dashboard cookie. :param query: A dictionary with search criteria. :param section_name: The dashboard section name :return: The 'query...
[ "def", "_update_criteria_with_filters", "(", "self", ",", "query", ",", "section_name", ")", ":", "if", "self", ".", "dashboard_cookie", "is", "None", ":", "return", "query", "cookie_criteria", "=", "self", ".", "dashboard_cookie", ".", "get", "(", "section_name...
38.2
14.733333
def isentropic_interpolation(theta_levels, pressure, temperature, *args, **kwargs): r"""Interpolate data in isobaric coordinates to isentropic coordinates. Parameters ---------- theta_levels : array One-dimensional array of desired theta surfaces pressure : array One-dimensional arr...
[ "def", "isentropic_interpolation", "(", "theta_levels", ",", "pressure", ",", "temperature", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# iteration function to be used later", "# Calculates theta from linearly interpolated temperature and solves for pressure", "def",...
37.720779
24.422078
def init_celery(project_name): """ init celery app without the need of redundant code """ os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % project_name) app = Celery(project_name) app.config_from_object('django.conf:settings') app.autodiscover_tasks(settings.INSTALLED_APPS, related_na...
[ "def", "init_celery", "(", "project_name", ")", ":", "os", ".", "environ", ".", "setdefault", "(", "'DJANGO_SETTINGS_MODULE'", ",", "'%s.settings'", "%", "project_name", ")", "app", "=", "Celery", "(", "project_name", ")", "app", ".", "config_from_object", "(", ...
48.571429
18.571429
def system_call(cmd, **kwargs): """Call cmd and return (stdout, stderr, return_value). Parameters ---------- cmd: str Can be either a string containing the command to be run, or a sequence of strings that are the tokens of the command. kwargs : dict, optional Ignored. Availa...
[ "def", "system_call", "(", "cmd", ",", "*", "*", "kwargs", ")", ":", "proc", "=", "Popen", "(", "cmd", ",", "universal_newlines", "=", "True", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "# communicate pulls ...
34.205882
20.294118
def list_articles(self, project, articleset, page=1, **filters): """List the articles in a set""" url = URL.article.format(**locals()) return self.get_pages(url, page=page, **filters)
[ "def", "list_articles", "(", "self", ",", "project", ",", "articleset", ",", "page", "=", "1", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "article", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "g...
51
11
def conv2d_trans(ni:int, nf:int, ks:int=2, stride:int=2, padding:int=0, bias=False) -> nn.ConvTranspose2d: "Create `nn.ConvTranspose2d` layer." return nn.ConvTranspose2d(ni, nf, kernel_size=ks, stride=stride, padding=padding, bias=bias)
[ "def", "conv2d_trans", "(", "ni", ":", "int", ",", "nf", ":", "int", ",", "ks", ":", "int", "=", "2", ",", "stride", ":", "int", "=", "2", ",", "padding", ":", "int", "=", "0", ",", "bias", "=", "False", ")", "->", "nn", ".", "ConvTranspose2d",...
80.666667
40.666667
def fullversion(): ''' Return server version (``apachectl -V``) CLI Example: .. code-block:: bash salt '*' apache.fullversion ''' cmd = '{0} -V'.format(_detect_os()) ret = {} ret['compiled_with'] = [] out = __salt__['cmd.run'](cmd).splitlines() # Example # -D APR_...
[ "def", "fullversion", "(", ")", ":", "cmd", "=", "'{0} -V'", ".", "format", "(", "_detect_os", "(", ")", ")", "ret", "=", "{", "}", "ret", "[", "'compiled_with'", "]", "=", "[", "]", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ...
25.555556
18.740741
def compute_hr(sig_len, qrs_inds, fs): """ Compute instantaneous heart rate from peak indices. Parameters ---------- sig_len : int The length of the corresponding signal qrs_inds : numpy array The qrs index locations fs : int, or float The corresponding signal's samp...
[ "def", "compute_hr", "(", "sig_len", ",", "qrs_inds", ",", "fs", ")", ":", "heart_rate", "=", "np", ".", "full", "(", "sig_len", ",", "np", ".", "nan", ",", "dtype", "=", "'float32'", ")", "if", "len", "(", "qrs_inds", ")", "<", "2", ":", "return",...
25.405405
19.945946
def build_on_entry(self, runnable, regime, on_entry): """ Build OnEntry start handler code. @param on_entry: OnEntry start handler object @type on_entry: lems.model.dynamics.OnEntry @return: Generated OnEntry code @rtype: list(string) """ on_entry_code ...
[ "def", "build_on_entry", "(", "self", ",", "runnable", ",", "regime", ",", "on_entry", ")", ":", "on_entry_code", "=", "[", "]", "on_entry_code", "+=", "[", "'if self.current_regime != self.last_regime:'", "]", "on_entry_code", "+=", "[", "' self.last_regime = self...
30.090909
19.181818
def list(self, **kwargs): """Retrieve a list of objects. Args: all (bool): If True, return all the items, without pagination per_page (int): Number of items to retrieve per request page (int): ID of the page to return (starts with page 1) as_list (bool): ...
[ "def", "list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Duplicate data to avoid messing with what the user sent us", "data", "=", "kwargs", ".", "copy", "(", ")", "if", "self", ".", "gitlab", ".", "per_page", ":", "data", ".", "setdefault", "(", "'...
40.025
23.2
def validate_ports_string(ports): """ Validate that provided string has proper port numbers: 1. port number < 65535 2. range start < range end """ pattern = re.compile('^\\d+(-\\d+)?(,\\d+(-\\d+)?)*$') if pattern.match(ports) is None: return False ...
[ "def", "validate_ports_string", "(", "ports", ")", ":", "pattern", "=", "re", ".", "compile", "(", "'^\\\\d+(-\\\\d+)?(,\\\\d+(-\\\\d+)?)*$'", ")", "if", "pattern", ".", "match", "(", "ports", ")", "is", "None", ":", "return", "False", "ranges", "=", "PortsRan...
36.428571
13.785714
def print(self, txt: str, hold: bool=False) -> None: """ Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return: "...
[ "def", "print", "(", "self", ",", "txt", ":", "str", ",", "hold", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "hold", ":", "self", ".", "held_prints", "[", "self", ".", "trace_depth", "]", "=", "txt", "elif", "self", ".", "held_prints"...
40
18
def _nucmer_command(self, ref, qry, outprefix): '''Construct the nucmer command''' if self.use_promer: command = 'promer' else: command = 'nucmer' command += ' -p ' + outprefix if self.breaklen is not None: command += ' -b ' + str(self.breakl...
[ "def", "_nucmer_command", "(", "self", ",", "ref", ",", "qry", ",", "outprefix", ")", ":", "if", "self", ".", "use_promer", ":", "command", "=", "'promer'", "else", ":", "command", "=", "'nucmer'", "command", "+=", "' -p '", "+", "outprefix", "if", "self...
27.741935
18.774194
def fibonacci(n): """A recursive Fibonacci to exercise task switching.""" if n <= 1: raise ndb.Return(n) a, b = yield fibonacci(n - 1), fibonacci(n - 2) raise ndb.Return(a + b)
[ "def", "fibonacci", "(", "n", ")", ":", "if", "n", "<=", "1", ":", "raise", "ndb", ".", "Return", "(", "n", ")", "a", ",", "b", "=", "yield", "fibonacci", "(", "n", "-", "1", ")", ",", "fibonacci", "(", "n", "-", "2", ")", "raise", "ndb", "...
30.5
15.333333
def push_func(self, cuin, callback): """Push a function for dfp. :param cuin: str,unicode: Callback Unique Identifier Name. :param callback: callable: Corresponding to the cuin to perform a function. :raises: DFPError,NotCallableError: raises an exception .. versionadded:: 2....
[ "def", "push_func", "(", "self", ",", "cuin", ",", "callback", ")", ":", "if", "cuin", "and", "isinstance", "(", "cuin", ",", "string_types", ")", "and", "callable", "(", "callback", ")", ":", "if", "cuin", "in", "self", ".", "_dfp_funcs", ":", "raise"...
37
21.3
def increment_failed_logins(self): """ Increment failed logins counter""" if not self.failed_logins: self.failed_logins = 1 elif not self.failed_login_limit_reached(): self.failed_logins += 1 else: self.reset_login_counter() self.lock_accou...
[ "def", "increment_failed_logins", "(", "self", ")", ":", "if", "not", "self", ".", "failed_logins", ":", "self", ".", "failed_logins", "=", "1", "elif", "not", "self", ".", "failed_login_limit_reached", "(", ")", ":", "self", ".", "failed_logins", "+=", "1",...
35.333333
7.777778
def open_mask_rle(mask_rle:str, shape:Tuple[int, int])->ImageSegment: "Return `ImageSegment` object create from run-length encoded string in `mask_lre` with size in `shape`." x = FloatTensor(rle_decode(str(mask_rle), shape).astype(np.uint8)) x = x.view(shape[1], shape[0], -1) return ImageSegment(x.permu...
[ "def", "open_mask_rle", "(", "mask_rle", ":", "str", ",", "shape", ":", "Tuple", "[", "int", ",", "int", "]", ")", "->", "ImageSegment", ":", "x", "=", "FloatTensor", "(", "rle_decode", "(", "str", "(", "mask_rle", ")", ",", "shape", ")", ".", "astyp...
65.2
26
def match(self, node): """Returns match for a given parse tree node. Should return a true or false object (not necessarily a bool). It may return a non-empty dict of matching sub-nodes as returned by a matching pattern. Subclass may override. """ results = {"nod...
[ "def", "match", "(", "self", ",", "node", ")", ":", "results", "=", "{", "\"node\"", ":", "node", "}", "return", "self", ".", "pattern", ".", "match", "(", "node", ",", "results", ")", "and", "results" ]
34.545455
17.272727
def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): """Read pixels from the currently selected buffer. Under most circumstances, this function reads from the front buffer. Unlike all other functions in vispy.gloo, this function directly executes an OpenGL command. Parameters...
[ "def", "read_pixels", "(", "viewport", "=", "None", ",", "alpha", "=", "True", ",", "out_type", "=", "'unsigned_byte'", ")", ":", "# Check whether the GL context is direct or remote", "context", "=", "get_current_canvas", "(", ")", ".", "context", "if", "context", ...
41.810345
18.293103
def _cnvkit_fix(cnns, background_cnn, items, ckouts): """Normalize samples, correcting sources of bias. """ return [_cnvkit_fix_base(cnns, background_cnn, items, ckouts)]
[ "def", "_cnvkit_fix", "(", "cnns", ",", "background_cnn", ",", "items", ",", "ckouts", ")", ":", "return", "[", "_cnvkit_fix_base", "(", "cnns", ",", "background_cnn", ",", "items", ",", "ckouts", ")", "]" ]
44.75
9.75
def equate_initial(name1, name2): """ Evaluates whether names match, or one name is the initial of the other """ if len(name1) == 0 or len(name2) == 0: return False if len(name1) == 1 or len(name2) == 1: return name1[0] == name2[0] return name1 == name2
[ "def", "equate_initial", "(", "name1", ",", "name2", ")", ":", "if", "len", "(", "name1", ")", "==", "0", "or", "len", "(", "name2", ")", "==", "0", ":", "return", "False", "if", "len", "(", "name1", ")", "==", "1", "or", "len", "(", "name2", "...
25.909091
15
def get_path(self, api_info): """Get the path portion of the URL to the method (for RESTful methods). Request path can be specified in the method, and it could have a base path prepended to it. Args: api_info: API information for this API, possibly including a base path. This is the api_...
[ "def", "get_path", "(", "self", ",", "api_info", ")", ":", "path", "=", "self", ".", "__path", "or", "''", "if", "path", "and", "path", "[", "0", "]", "==", "'/'", ":", "# Absolute path, ignoring any prefixes. Just strip off the leading /.", "path", "=", "pat...
34.111111
23.111111
def load_agency_profile(cls, source): ''' Classmethod loading metadata on a data provider. ``source`` must be a json-formated string or file-like object describing one or more data providers (URL of the SDMX web API, resource types etc. The dict ``Request._agencies`` is updated w...
[ "def", "load_agency_profile", "(", "cls", ",", "source", ")", ":", "if", "not", "isinstance", "(", "source", ",", "str_type", ")", ":", "# so it must be a text file", "source", "=", "source", ".", "read", "(", ")", "new_agencies", "=", "json", ".", "loads", ...
39.066667
19.466667
def _draw_fold_indicator(self, top, mouse_over, collapsed, painter): """ Draw the fold indicator/trigger (arrow). :param top: Top position :param mouse_over: Whether the mouse is over the indicator :param collapsed: Whether the trigger is collapsed or not. :param painter...
[ "def", "_draw_fold_indicator", "(", "self", ",", "top", ",", "mouse_over", ",", "collapsed", ",", "painter", ")", ":", "rect", "=", "QtCore", ".", "QRect", "(", "0", ",", "top", ",", "self", ".", "sizeHint", "(", ")", ".", "width", "(", ")", ",", "...
43.605263
17.552632
def get_getter(cls, prop_name, # @NoSelf user_getter=None, getter_takes_name=False): """This implementation returns the PROP_NAME value if there exists such property. Otherwise there must exist a logical getter (user_getter) which the value is taken from. If no ...
[ "def", "get_getter", "(", "cls", ",", "prop_name", ",", "# @NoSelf", "user_getter", "=", "None", ",", "getter_takes_name", "=", "False", ")", ":", "has_prop_variable", "=", "cls", ".", "has_prop_attribute", "(", "prop_name", ")", "# WARNING! Deprecated", "has_spec...
44.805556
21.125
def _loadConfiguration(self): """ Load module configuration files. :return: <void> """ configPath = os.path.join(self.path, "config") if not os.path.isdir(configPath): return config = Config(configPath) Config.mergeDictionaries(config.getDat...
[ "def", "_loadConfiguration", "(", "self", ")", ":", "configPath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "\"config\"", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "configPath", ")", ":", "return", "config", "=...
25.923077
17.307692
def read_file(filename): """Read a file.""" logging.debug(_('Reading file: %s'), filename) try: with open(filename) as readable: return readable.read() except OSError: logging.error(_('Error reading file: %s'), filename) return ''
[ "def", "read_file", "(", "filename", ")", ":", "logging", ".", "debug", "(", "_", "(", "'Reading file: %s'", ")", ",", "filename", ")", "try", ":", "with", "open", "(", "filename", ")", "as", "readable", ":", "return", "readable", ".", "read", "(", ")"...
30.444444
14.222222
def unlock_repo(self, repo_name): """ :calls: `DELETE /user/migrations/:migration_id/repos/:repo_name/lock`_ :param repo_name: str :rtype: None """ assert isinstance(repo_name, (str, unicode)), repo_name headers, data = self._requester.requestJsonAndCheck( ...
[ "def", "unlock_repo", "(", "self", ",", "repo_name", ")", ":", "assert", "isinstance", "(", "repo_name", ",", "(", "str", ",", "unicode", ")", ")", ",", "repo_name", "headers", ",", "data", "=", "self", ".", "_requester", ".", "requestJsonAndCheck", "(", ...
34.428571
17.714286
def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE): """Axis function decorator. An axis function will take a node as an argument and return a sequence over the nodes along an XPath axis. Axis functions have two extra attributes indicating the axis direction and principal node typ...
[ "def", "axisfn", "(", "reverse", "=", "False", ",", "principal_node_type", "=", "xml", ".", "dom", ".", "Node", ".", "ELEMENT_NODE", ")", ":", "def", "decorate", "(", "f", ")", ":", "f", ".", "__name__", "=", "f", ".", "__name__", ".", "replace", "("...
38.923077
20.307692
def write_file_list_cache(opts, data, list_cache, w_lock): ''' Checks the cache file to see if there is a new enough file list cache, and returns the match (if found, along with booleans used by the fileserver backend to determine if the cache needs to be refreshed/written). ''' serial = salt.pa...
[ "def", "write_file_list_cache", "(", "opts", ",", "data", ",", "list_cache", ",", "w_lock", ")", ":", "serial", "=", "salt", ".", "payload", ".", "Serial", "(", "opts", ")", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "list_cache", "...
45.818182
20.727273
def view_history(name, gitref): """Serve a page name from git repo (an old version of a page). .. note:: this is a bottle view * this is a GET only method : you can not change a committed page Keyword Arguments: :name: (str) -- name of the rest file (without the .rst extension) :gitre...
[ "def", "view_history", "(", "name", ",", "gitref", ")", ":", "response", ".", "set_header", "(", "'Cache-control'", ",", "'no-cache'", ")", "response", ".", "set_header", "(", "'Pragma'", ",", "'no-cache'", ")", "content", "=", "read_committed_file", "(", "git...
36.575758
15.515152
def arg_scope(list_ops_or_scope, **kwargs): """Stores the default arguments for the given set of list_ops. For usage, please see examples at top of the file. Args: list_ops_or_scope: List or tuple of operations to set argument scope for or a dictionary containg the current scope. When list_ops_or_scop...
[ "def", "arg_scope", "(", "list_ops_or_scope", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "list_ops_or_scope", ",", "dict", ")", ":", "# Assumes that list_ops_or_scope is a scope that is being reused.", "if", "kwargs", ":", "raise", "ValueError", "(", ...
41.254902
20.843137
def prefix_keys(self, prefix, strip_prefix=False): """Get all keys that begin with ``prefix``. :param prefix: Lexical prefix for keys to search. :type prefix: bytes :param strip_prefix: True to strip the prefix from yielded items. :type strip_prefix: bool :yields: All ...
[ "def", "prefix_keys", "(", "self", ",", "prefix", ",", "strip_prefix", "=", "False", ")", ":", "keys", "=", "self", ".", "keys", "(", "key_from", "=", "prefix", ")", "start", "=", "0", "if", "strip_prefix", ":", "start", "=", "len", "(", "prefix", ")...
27.090909
20.181818
def main(): '''Entry point''' if len(sys.argv) == 1: print("Usage: tyler [filename]") sys.exit(0) filename = sys.argv[1] if not os.path.isfile(filename): print("Specified file does not exists") sys.exit(8) my_tyler = Tyler(filename=filename) while True: ...
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "==", "1", ":", "print", "(", "\"Usage: tyler [filename]\"", ")", "sys", ".", "exit", "(", "0", ")", "filename", "=", "sys", ".", "argv", "[", "1", "]", "if", "not", "os", ...
24.65
16.15
def _get_contents_between(string, opener, closer): """ Get the contents of a string between two characters """ opener_location = string.index(opener) closer_location = string.index(closer) content = string[opener_location + 1:closer_location] return content
[ "def", "_get_contents_between", "(", "string", ",", "opener", ",", "closer", ")", ":", "opener_location", "=", "string", ".", "index", "(", "opener", ")", "closer_location", "=", "string", ".", "index", "(", "closer", ")", "content", "=", "string", "[", "o...
34.75
8.5
def loadFeatures(self, path_to_fc): """ loads a feature class features to the object """ from ..common.spatial import featureclass_to_json v = json.loads(featureclass_to_json(path_to_fc)) self.value = v
[ "def", "loadFeatures", "(", "self", ",", "path_to_fc", ")", ":", "from", ".", ".", "common", ".", "spatial", "import", "featureclass_to_json", "v", "=", "json", ".", "loads", "(", "featureclass_to_json", "(", "path_to_fc", ")", ")", "self", ".", "value", "...
34.857143
9.714286
def _next_numId(self): """ The first ``numId`` unused by a ``<w:num>`` element, starting at 1 and filling any gaps in numbering between existing ``<w:num>`` elements. """ numId_strs = self.xpath('./w:num/@w:numId') num_ids = [int(numId_str) for numId_str in numId_...
[ "def", "_next_numId", "(", "self", ")", ":", "numId_strs", "=", "self", ".", "xpath", "(", "'./w:num/@w:numId'", ")", "num_ids", "=", "[", "int", "(", "numId_str", ")", "for", "numId_str", "in", "numId_strs", "]", "for", "num", "in", "range", "(", "1", ...
36.25
15.75
def set_tmp_folder(): """ Create a temporary folder using the current time in which the zip can be extracted and which should be destroyed afterward. """ output = "%s" % datetime.datetime.now() for char in [' ', ':', '.', '-']: output = output.replace(char, '') output.strip() tmp_fol...
[ "def", "set_tmp_folder", "(", ")", ":", "output", "=", "\"%s\"", "%", "datetime", ".", "datetime", ".", "now", "(", ")", "for", "char", "in", "[", "' '", ",", "':'", ",", "'.'", ",", "'-'", "]", ":", "output", "=", "output", ".", "replace", "(", ...
38.2
11.6
def _parse_info(line): """ The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] """ re_info = re.compile( r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1fre...
[ "def", "_parse_info", "(", "line", ")", ":", "re_info", "=", "re", ".", "compile", "(", "r'\\[(?P<name>\\w+).(?P<ver>.*) '", "+", "r'\\((?P<rfm1name>\\w+) (\\w+):(?P<rfm1freq>\\d+) '", "+", "r'(?P<rfm1mode>.*)\\)\\]'", ")", "info", "=", "{", "'name'", ":", "None", ","...
34.342857
13.257143
def create(type_dict, *type_parameters): """ EnumFactory.create(*type_parameters) expects: enumeration name, (enumeration values) """ name, values = type_parameters assert isinstance(values, (list, tuple)) for value in values: assert isinstance(value, Compatibility.stringy) r...
[ "def", "create", "(", "type_dict", ",", "*", "type_parameters", ")", ":", "name", ",", "values", "=", "type_parameters", "assert", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", "for", "value", "in", "values", ":", "assert", "isin...
38.1
9.1
def finish_and_die(self): """ If there is a request pending, let it finish and be handled, then disconnect and die. If not, cancel any pending queue requests and just die. """ self.logstate('finish_and_die') self.stop_working_on_queue() if self.jobphase !=...
[ "def", "finish_and_die", "(", "self", ")", ":", "self", ".", "logstate", "(", "'finish_and_die'", ")", "self", ".", "stop_working_on_queue", "(", ")", "if", "self", ".", "jobphase", "!=", "'pending_request'", ":", "self", ".", "stopFactory", "(", ")" ]
36.1
12.5
def available_actions(self, obs): """Return the list of available action ids.""" available_actions = set() hide_specific_actions = self._agent_interface_format.hide_specific_actions for i, func in six.iteritems(actions.FUNCTIONS_AVAILABLE): if func.avail_fn(obs): available_actions.add(i) ...
[ "def", "available_actions", "(", "self", ",", "obs", ")", ":", "available_actions", "=", "set", "(", ")", "hide_specific_actions", "=", "self", ".", "_agent_interface_format", ".", "hide_specific_actions", "for", "i", ",", "func", "in", "six", ".", "iteritems", ...
51.173913
19.434783
def render_category(slug): """Template tag to render a category with all it's entries.""" try: category = EntryCategory.objects.get(slug=slug) except EntryCategory.DoesNotExist: pass else: return {'category': category} return {}
[ "def", "render_category", "(", "slug", ")", ":", "try", ":", "category", "=", "EntryCategory", ".", "objects", ".", "get", "(", "slug", "=", "slug", ")", "except", "EntryCategory", ".", "DoesNotExist", ":", "pass", "else", ":", "return", "{", "'category'",...
29.333333
16.888889
def match(self, item): """ Return True if filter matches item. """ if getattr(item, self._name) is None: # Never match "N/A" items, except when "-0" was specified return False if self._value else self._cmp(-1, 0) else: return super(DurationFilter, self...
[ "def", "match", "(", "self", ",", "item", ")", ":", "if", "getattr", "(", "item", ",", "self", ".", "_name", ")", "is", "None", ":", "# Never match \"N/A\" items, except when \"-0\" was specified", "return", "False", "if", "self", ".", "_value", "else", "self"...
40.75
14.75
def check_rest(module, names, dots=True): """ Check reStructuredText formatting of docstrings Returns: [(name, success_flag, output), ...] """ try: skip_types = (dict, str, unicode, float, int) except NameError: # python 3 skip_types = (dict, str, float, int) resul...
[ "def", "check_rest", "(", "module", ",", "names", ",", "dots", "=", "True", ")", ":", "try", ":", "skip_types", "=", "(", "dict", ",", "str", ",", "unicode", ",", "float", ",", "int", ")", "except", "NameError", ":", "# python 3", "skip_types", "=", ...
29.761905
20.460317
def new(self, bootstrap_with=None, use_timer=False): """ Actual constructor of the solver. """ if not self.minicard: self.minicard = pysolvers.minicard_new() if bootstrap_with: for clause in bootstrap_with: self.add_clause...
[ "def", "new", "(", "self", ",", "bootstrap_with", "=", "None", ",", "use_timer", "=", "False", ")", ":", "if", "not", "self", ".", "minicard", ":", "self", ".", "minicard", "=", "pysolvers", ".", "minicard_new", "(", ")", "if", "bootstrap_with", ":", "...
30.8
14.8
def runUncertainLocations(missingLoc=None, profile=False): """ Runs the same experiment as above, with missing locations at some timesteps during inference (if it was not successfully computed by the rest of the network for example). @param missingLoc (dict) A dictionary mapping indices in the o...
[ "def", "runUncertainLocations", "(", "missingLoc", "=", "None", ",", "profile", "=", "False", ")", ":", "if", "missingLoc", "is", "None", ":", "missingLoc", "=", "{", "}", "exp", "=", "L4L2Experiment", "(", "\"uncertain_location\"", ",", "enableLateralSP", "="...
24.741379
22.224138
def cancel_notification(cls, notification_or_id, tag=None): """ Cancel the notification. Parameters ---------- notification_or_id: Notification.Builder or int The notification or id of a notification to clear tag: String The tag of the notificati...
[ "def", "cancel_notification", "(", "cls", ",", "notification_or_id", ",", "tag", "=", "None", ")", ":", "def", "on_ready", "(", "mgr", ")", ":", "if", "isinstance", "(", "notification_or_id", ",", "JavaBridgeObject", ")", ":", "nid", "=", "notification_or_id",...
32.380952
15
def wkt_rewind(x, digits = None): ''' reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. :return: a string Usage:: from py...
[ "def", "wkt_rewind", "(", "x", ",", "digits", "=", "None", ")", ":", "z", "=", "wkt", ".", "loads", "(", "x", ")", "if", "digits", "is", "None", ":", "coords", "=", "z", "[", "'coordinates'", "]", "nums", "=", "__flatten", "(", "coords", ")", "de...
30.709677
20.709677
def marshmallow_loader(schema_class): """Marshmallow loader for JSON requests.""" def json_loader(): request_json = request.get_json() context = {} pid_data = request.view_args.get('pid_value') if pid_data: pid, _ = pid_data.data context['pid'] = pid ...
[ "def", "marshmallow_loader", "(", "schema_class", ")", ":", "def", "json_loader", "(", ")", ":", "request_json", "=", "request", ".", "get_json", "(", ")", "context", "=", "{", "}", "pid_data", "=", "request", ".", "view_args", ".", "get", "(", "'pid_value...
29.058824
17.117647
def get_edge_annotation_layers(docgraph): """ WARNING: this is higly inefficient! Fix this via Issue #36. Returns ------- all_layers : set or dict the set of all annotation layers used for annotating edges in the given graph """ all_layers = set() for source_id, targ...
[ "def", "get_edge_annotation_layers", "(", "docgraph", ")", ":", "all_layers", "=", "set", "(", ")", "for", "source_id", ",", "target_id", ",", "edge_attribs", "in", "docgraph", ".", "edges_iter", "(", "data", "=", "True", ")", ":", "for", "layer", "in", "e...
28.75
17.25
def transform_future(transformation, future): """Returns a new future that will resolve with a transformed value Takes the resolution value of `future` and applies transformation(*future.result()) to it before setting the result of the new future with the transformed value. If future() resolves with an...
[ "def", "transform_future", "(", "transformation", ",", "future", ")", ":", "new_future", "=", "tornado_Future", "(", ")", "def", "_transform", "(", "f", ")", ":", "assert", "f", "is", "future", "if", "f", ".", "exc_info", "(", ")", "is", "not", "None", ...
37.625
21.416667
def _process_dataset(name, directory, num_shards, synset_to_human, image_to_bboxes): """Process a complete data set and save it as a TFRecord. Args: name: string, unique identifier specifying the data set. directory: string, root path to the data set. num_shards: integer number of ...
[ "def", "_process_dataset", "(", "name", ",", "directory", ",", "num_shards", ",", "synset_to_human", ",", "image_to_bboxes", ")", ":", "filenames", ",", "synsets", ",", "labels", "=", "_find_image_files", "(", "directory", ",", "FLAGS", ".", "labels_file", ")", ...
49.333333
18.555556
def write_file(self, *args, **kwargs): """Write a file into this directory This method takes the same arguments as :meth:`.FileDataAPI.write_file` with the exception of the ``path`` argument which is not needed here. """ return self._fdapi.write_file(self.get_path(), *args, **k...
[ "def", "write_file", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_fdapi", ".", "write_file", "(", "self", ".", "get_path", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
39.875
23.625
def _read_byte(self): """Read a byte from input.""" to_return = "" if (self._mode == PROP_MODE_SERIAL): to_return = self._serial.read(1) elif (self._mode == PROP_MODE_TCP): to_return = self._socket.recv(1) elif (self._mode == PROP_MODE_FILE): ...
[ "def", "_read_byte", "(", "self", ")", ":", "to_return", "=", "\"\"", "if", "(", "self", ".", "_mode", "==", "PROP_MODE_SERIAL", ")", ":", "to_return", "=", "self", ".", "_serial", ".", "read", "(", "1", ")", "elif", "(", "self", ".", "_mode", "==", ...
36.421053
19
def copy(self, dest): """ Copy file to destination """ if isinstance(dest, File): dest_dir = dest.get_directory() dest_dir.create() dest = dest.filename elif isinstance(dest, Directory): dest = dest.dirname shutil.copy2(self.filename, dest...
[ "def", "copy", "(", "self", ",", "dest", ")", ":", "if", "isinstance", "(", "dest", ",", "File", ")", ":", "dest_dir", "=", "dest", ".", "get_directory", "(", ")", "dest_dir", ".", "create", "(", ")", "dest", "=", "dest", ".", "filename", "elif", "...
31.2
9.8
def reparse(self): '''Reparse all children of this directory. This effectively rebuilds the tree below this node. This operation takes an unbounded time to complete; if there are a lot of objects registered below this directory's context, they will all need to be parsed. ...
[ "def", "reparse", "(", "self", ")", ":", "self", ".", "_remove_all_children", "(", ")", "self", ".", "_parse_context", "(", "self", ".", "_context", ",", "self", ".", "orb", ")" ]
33.666667
25.333333
def run(self): """ run the plugin """ try: self.hide_files = get_hide_files(self.workflow) except KeyError: self.log.info("Skipping hide files: no files to hide") return self._populate_start_file_lines() self._populate_end_file...
[ "def", "run", "(", "self", ")", ":", "try", ":", "self", ".", "hide_files", "=", "get_hide_files", "(", "self", ".", "workflow", ")", "except", "KeyError", ":", "self", ".", "log", ".", "info", "(", "\"Skipping hide files: no files to hide\"", ")", "return",...
30.35
16.95
def delay( self, identifier: typing.Any, until: typing.Union[int, float]=-1, ) -> bool: """Delay a deferred function until the given time. Args: identifier (typing.Any): The identifier returned from a call to defer or defer_for. ...
[ "def", "delay", "(", "self", ",", "identifier", ":", "typing", ".", "Any", ",", "until", ":", "typing", ".", "Union", "[", "int", ",", "float", "]", "=", "-", "1", ",", ")", "->", "bool", ":", "raise", "NotImplementedError", "(", ")" ]
39.95
22.7
def named_value_float_send(self, time_boot_ms, name, value, force_mavlink1=False): ''' Send a key-value pair as float. The use of this message is discouraged for normal packets, but a quite efficient way for testing new messages and getting experimental de...
[ "def", "named_value_float_send", "(", "self", ",", "time_boot_ms", ",", "name", ",", "value", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "named_value_float_encode", "(", "time_boot_ms", ",", "name", ",", "...
56
37.384615
async def items(self, name=None, *, watch=None): """Lists the most recent events an agent has seen Parameters: name (str): Filter events by name. watch (Blocking): Do a blocking query Returns: CollectionMeta: where value is a list of events It return...
[ "async", "def", "items", "(", "self", ",", "name", "=", "None", ",", "*", ",", "watch", "=", "None", ")", ":", "path", "=", "\"/v1/event/list\"", "params", "=", "{", "\"name\"", ":", "name", "}", "response", "=", "await", "self", ".", "_api", ".", ...
34.533333
16.666667
def list_(bank): ''' Lists entries stored in the specified bank. ''' redis_server = _get_redis_server() bank_redis_key = _get_bank_redis_key(bank) try: banks = redis_server.smembers(bank_redis_key) except (RedisConnectionError, RedisResponseError) as rerr: mesg = 'Cannot list...
[ "def", "list_", "(", "bank", ")", ":", "redis_server", "=", "_get_redis_server", "(", ")", "bank_redis_key", "=", "_get_bank_redis_key", "(", "bank", ")", "try", ":", "banks", "=", "redis_server", ".", "smembers", "(", "bank_redis_key", ")", "except", "(", "...
35.5625
21.9375
def _signature(self, *parts): """ Creates signature for the session. """ signature = hmac.new(six.b(self.secret), digestmod=hashlib.sha1) signature.update(six.b('|'.join(parts))) return signature.hexdigest()
[ "def", "_signature", "(", "self", ",", "*", "parts", ")", ":", "signature", "=", "hmac", ".", "new", "(", "six", ".", "b", "(", "self", ".", "secret", ")", ",", "digestmod", "=", "hashlib", ".", "sha1", ")", "signature", ".", "update", "(", "six", ...
35.571429
8.142857
def _toolkit_serialize_summary_struct(model, sections, section_titles): """ Serialize model summary into a dict with ordered lists of sections and section titles Parameters ---------- model : Model object sections : Ordered list of lists (sections) of tuples (field,value) [ [(fi...
[ "def", "_toolkit_serialize_summary_struct", "(", "model", ",", "sections", ",", "section_titles", ")", ":", "output_dict", "=", "dict", "(", ")", "output_dict", "[", "'sections'", "]", "=", "[", "[", "(", "field", "[", "0", "]", ",", "__extract_model_summary_v...
37.964286
27.892857
async def get_input_entity(self, peer): """ Turns the given peer into its input entity version. Most requests use this kind of :tl:`InputPeer`, so this is the most suitable call to make for those cases. **Generally you should let the library do its job** and don't worry about get...
[ "async", "def", "get_input_entity", "(", "self", ",", "peer", ")", ":", "# Short-circuit if the input parameter directly maps to an InputPeer", "try", ":", "return", "utils", ".", "get_input_peer", "(", "peer", ")", "except", "TypeError", ":", "pass", "# Next in priorit...
45.467213
24.598361
def scalar_inc_dec(word, valence, is_cap_diff): """ Check if the preceding words increase, decrease, or negate/nullify the valence """ scalar = 0.0 word_lower = word.lower() if word_lower in BOOSTER_DICT: scalar = BOOSTER_DICT[word_lower] if valence < 0: scalar *=...
[ "def", "scalar_inc_dec", "(", "word", ",", "valence", ",", "is_cap_diff", ")", ":", "scalar", "=", "0.0", "word_lower", "=", "word", ".", "lower", "(", ")", "if", "word_lower", "in", "BOOSTER_DICT", ":", "scalar", "=", "BOOSTER_DICT", "[", "word_lower", "]...
30.888889
14.333333
def calculeToday(self): """Calcule the intervals from the last date.""" self.__logger.debug("Add today") last = datetime.datetime.strptime(self.__lastDay, "%Y-%m-%d") today = datetime.datetime.now().date() self.__validInterval(last, today)
[ "def", "calculeToday", "(", "self", ")", ":", "self", ".", "__logger", ".", "debug", "(", "\"Add today\"", ")", "last", "=", "datetime", ".", "datetime", ".", "strptime", "(", "self", ".", "__lastDay", ",", "\"%Y-%m-%d\"", ")", "today", "=", "datetime", ...
45.666667
8.833333
def do_dissect_payload(self, s): """ Perform the dissection of the layer's payload :param str s: the raw layer """ if s: cls = self.guess_payload_class(s) try: p = cls(s, _internal=1, _underlayer=self) except KeyboardInterrupt:...
[ "def", "do_dissect_payload", "(", "self", ",", "s", ")", ":", "if", "s", ":", "cls", "=", "self", ".", "guess_payload_class", "(", "s", ")", "try", ":", "p", "=", "cls", "(", "s", ",", "_internal", "=", "1", ",", "_underlayer", "=", "self", ")", ...
38.772727
17.136364
def lazy_load_modules(*modules): """ Decorator to load module to perform related operation for specific function and delete the module from imports once the task is done. GC frees the memory related to module during clean-up. """ def decorator(function): def wrapper(*args, **kwargs): ...
[ "def", "lazy_load_modules", "(", "*", "modules", ")", ":", "def", "decorator", "(", "function", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "module_dict", "=", "{", "}", "for", "module_string", "in", "modules", ":",...
36.933333
18.466667
def summarize(self, rows): """Return summary rows for `rows`. Parameters ---------- rows : list of dicts Normalized rows to summarize. Returns ------- A list of summary rows. Each row is a tuple where the first item is the data and the secon...
[ "def", "summarize", "(", "self", ",", "rows", ")", ":", "columns", "=", "list", "(", "rows", "[", "0", "]", ".", "keys", "(", ")", ")", "agg_styles", "=", "{", "c", ":", "self", ".", "style", "[", "c", "]", "[", "\"aggregate\"", "]", "for", "c"...
38.5
17.44
def from_raw_message(cls, rawmessage): """Create message from raw byte stream.""" return ManageAllLinkRecord(rawmessage[2:3], rawmessage[3:4], rawmessage[4:7], rawmessage[7:8], ...
[ "def", "from_raw_message", "(", "cls", ",", "rawmessage", ")", ":", "return", "ManageAllLinkRecord", "(", "rawmessage", "[", "2", ":", "3", "]", ",", "rawmessage", "[", "3", ":", "4", "]", ",", "rawmessage", "[", "4", ":", "7", "]", ",", "rawmessage", ...
49.777778
9.111111
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the f...
[ "def", "_proc_builtin", "(", "self", ",", "tarfile", ")", ":", "self", ".", "offset_data", "=", "tarfile", ".", "fileobj", ".", "tell", "(", ")", "offset", "=", "self", ".", "offset_data", "if", "self", ".", "isreg", "(", ")", "or", "self", ".", "typ...
37
14.5625
def unique_list_dicts(dlist, key): """Return a list of dictionaries which are sorted for only unique entries. :param dlist: :param key: :return list: """ return list(dict((val[key], val) for val in dlist).values())
[ "def", "unique_list_dicts", "(", "dlist", ",", "key", ")", ":", "return", "list", "(", "dict", "(", "(", "val", "[", "key", "]", ",", "val", ")", "for", "val", "in", "dlist", ")", ".", "values", "(", ")", ")" ]
25.777778
20.111111
def find_by_url(self, space_url, id_only=True): """ Returns a space ID given the URL of the space. :param space_url: URL of the Space :param id_only: ? :return: space_id: Space url :rtype: str """ resp = self.transport.GET(url='/space/url?%s' % urlencode(...
[ "def", "find_by_url", "(", "self", ",", "space_url", ",", "id_only", "=", "True", ")", ":", "resp", "=", "self", ".", "transport", ".", "GET", "(", "url", "=", "'/space/url?%s'", "%", "urlencode", "(", "{", "'url'", ":", "space_url", "}", ")", ")", "...
31.076923
15.076923
def colored(text, color=None, on_color=None, attrs=None): """Colorize text using a reimplementation of the colorizer from https://github.com/pavdmyt/yaspin so that it works on windows. Available text colors: red, green, yellow, blue, magenta, cyan, white. Available text highlights: on_...
[ "def", "colored", "(", "text", ",", "color", "=", "None", ",", "on_color", "=", "None", ",", "attrs", "=", "None", ")", ":", "return", "colorize", "(", "text", ",", "fg", "=", "color", ",", "bg", "=", "on_color", ",", "attrs", "=", "attrs", ")" ]
36.055556
21.611111
def send(self, payloads, logger, num_tries=5): """ Enqueue payloads to the SQS queue, retrying failed messages with exponential backoff. """ from time import sleep backoff_interval = 1 backoff_factor = 2 for try_counter in xrange(0, num_tries): ...
[ "def", "send", "(", "self", ",", "payloads", ",", "logger", ",", "num_tries", "=", "5", ")", ":", "from", "time", "import", "sleep", "backoff_interval", "=", "1", "backoff_factor", "=", "2", "for", "try_counter", "in", "xrange", "(", "0", ",", "num_tries...
37.181818
19.909091
def register(name): """Return a decorator that registers the decorated class as a resolver with the given *name*.""" def decorator(class_): if name in known_resolvers: raise ValueError('duplicate resolver name "%s"' % name) known_resolvers[name] = class_ return decorator
[ "def", "register", "(", "name", ")", ":", "def", "decorator", "(", "class_", ")", ":", "if", "name", "in", "known_resolvers", ":", "raise", "ValueError", "(", "'duplicate resolver name \"%s\"'", "%", "name", ")", "known_resolvers", "[", "name", "]", "=", "cl...
38.5
11.125
def report_all_label(self): """ Return the best label of the asked entry. Parameters ---------- Returns ------- labels: list of object, shape=(m) The best label of all samples. """ labels = np.empty(len(self.dataset), dtype=int) ...
[ "def", "report_all_label", "(", "self", ")", ":", "labels", "=", "np", ".", "empty", "(", "len", "(", "self", ".", "dataset", ")", ",", "dtype", "=", "int", ")", "for", "pruning", "in", "self", ".", "prunings", ":", "best_label", "=", "self", ".", ...
26.105263
15.473684
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if (selector.startswith('/') or selector.startswith('./') or ( selector.startswith('('))): return True return False
[ "def", "is_xpath_selector", "(", "selector", ")", ":", "if", "(", "selector", ".", "startswith", "(", "'/'", ")", "or", "selector", ".", "startswith", "(", "'./'", ")", "or", "(", "selector", ".", "startswith", "(", "'('", ")", ")", ")", ":", "return",...
31.625
13.375
def _eval_kwargs(self): """Evaluates any parameterized methods in the kwargs""" evaled_kwargs = {} for k, v in self.p.kwargs.items(): if util.is_param_method(v): v = v() evaled_kwargs[k] = v return evaled_kwargs
[ "def", "_eval_kwargs", "(", "self", ")", ":", "evaled_kwargs", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "p", ".", "kwargs", ".", "items", "(", ")", ":", "if", "util", ".", "is_param_method", "(", "v", ")", ":", "v", "=", "v", "("...
34.5
8.875
def logout(self): """ 登出会话 :return: self """ self.req(API_ACCOUNT_LOGOUT % self.ck()) self.cookies = {} self.user_alias = None self.persist()
[ "def", "logout", "(", "self", ")", ":", "self", ".", "req", "(", "API_ACCOUNT_LOGOUT", "%", "self", ".", "ck", "(", ")", ")", "self", ".", "cookies", "=", "{", "}", "self", ".", "user_alias", "=", "None", "self", ".", "persist", "(", ")" ]
20.5
15.3
def force_clean(self, remove_rw=False, allow_lazy=False, retries=5, sleep_interval=0.5): """Attempts to call the clean method, but will retry automatically if an error is raised. When the attempts run out, it will raise the last error. Note that the method will only catch :class:`ImageMounterEr...
[ "def", "force_clean", "(", "self", ",", "remove_rw", "=", "False", ",", "allow_lazy", "=", "False", ",", "retries", "=", "5", ",", "sleep_interval", "=", "0.5", ")", ":", "while", "True", ":", "try", ":", "self", ".", "clean", "(", "remove_rw", "=", ...
46.458333
24.875
def regex(self): """ RFC822 Email Address Regex Originally written by Cal Henderson c.f. http://iamcal.com/publish/articles/php/parsing_email/ Translated to Python by Tim Fletcher with changes suggested by Dan Kubb http://tfletcher.com/lib/rfc822.py Licensed under...
[ "def", "regex", "(", "self", ")", ":", "qtext", "=", "'[^\\\\x0d\\\\x22\\\\x5c\\\\x80-\\\\xff]'", "dtext", "=", "'[^\\\\x0d\\\\x5b-\\\\x5d\\\\x80-\\\\xff]'", "atom", "=", "'[^\\\\x00-\\\\x20\\\\x22\\\\x28\\\\x29\\\\x2c\\\\x2e\\\\x3a-\\\\x3c\\\\x3e\\\\x40'", "atom", "+=", "'\\\\x5b-...
41
19
def _edge_group_substitution( self, ndid, nsplit, idxs, sr_tab, ndoffset, ed_remove, into_or_from ): """ Reconnect edges. :param ndid: id of low resolution edges :param nsplit: number of split :param idxs: indexes of low resolution :param sr_tab: :para...
[ "def", "_edge_group_substitution", "(", "self", ",", "ndid", ",", "nsplit", ",", "idxs", ",", "sr_tab", ",", "ndoffset", ",", "ed_remove", ",", "into_or_from", ")", ":", "# this is useful for type(idxs) == np.ndarray", "eidxs", "=", "idxs", "[", "nm", ".", "wher...
48.241379
19.586207
def periodicity(self) -> str: """Get a random periodicity string. :return: Periodicity. """ periodicity = self._data['periodicity'] return self.random.choice(periodicity)
[ "def", "periodicity", "(", "self", ")", "->", "str", ":", "periodicity", "=", "self", ".", "_data", "[", "'periodicity'", "]", "return", "self", ".", "random", ".", "choice", "(", "periodicity", ")" ]
29.285714
10.714286
def constants_pyx(): """generate CONST = ZMQ_CONST and __all__ for constants.pxi""" all_lines = [] assign_lines = [] for name in all_names: if name == "NULL": # avoid conflict with NULL in Cython assign_lines.append("globals()['NULL'] = ZMQ_NULL") else: ...
[ "def", "constants_pyx", "(", ")", ":", "all_lines", "=", "[", "]", "assign_lines", "=", "[", "]", "for", "name", "in", "all_names", ":", "if", "name", "==", "\"NULL\"", ":", "# avoid conflict with NULL in Cython", "assign_lines", ".", "append", "(", "\"globals...
40.75
17.916667
def _upcoming_datetime_from(self): """ The datetime this event next starts in the local time zone, or None if it is finished. """ nextDt = self.__localAfter(timezone.localtime(), dt.time.max, excludeCancellations=True, ...
[ "def", "_upcoming_datetime_from", "(", "self", ")", ":", "nextDt", "=", "self", ".", "__localAfter", "(", "timezone", ".", "localtime", "(", ")", ",", "dt", ".", "time", ".", "max", ",", "excludeCancellations", "=", "True", ",", "excludeExtraInfo", "=", "T...
40.555556
16.333333
def get_next_slug(self, slug, **kwargs): """Gets the next available slug. :param slug: the slug to slugify :param kwargs: additional filter criteria to check for when looking for a unique slug. Example: if the value "my-slug" is already taken, this method will appe...
[ "def", "get_next_slug", "(", "self", ",", "slug", ",", "*", "*", "kwargs", ")", ":", "original_slug", "=", "slug", "=", "slugify", "(", "slug", ")", "count", "=", "0", "while", "not", "self", ".", "is_slug_available", "(", "slug", "=", "slug", ",", "...
29.52381
23.285714
def send(self, commands): """Ship commands to the daemon Arguments: commands: e.g., '?WATCH={{'enable':true,'json':true}}'|'?VERSION;'|'?DEVICES;'|'?DEVICE;'|'?POLL;' """ try: self.streamSock.send(bytes(commands, encoding='utf-8')) except TypeError: ...
[ "def", "send", "(", "self", ",", "commands", ")", ":", "try", ":", "self", ".", "streamSock", ".", "send", "(", "bytes", "(", "commands", ",", "encoding", "=", "'utf-8'", ")", ")", "except", "TypeError", ":", "self", ".", "streamSock", ".", "send", "...
49.363636
26.727273
def assign_license(license_key, license_name, entity, entity_display_name, safety_checks=True, service_instance=None): ''' Assigns a license to an entity license_key Key of the license to assign See ``_get_entity`` docstrings for format. license_name Display ...
[ "def", "assign_license", "(", "license_key", ",", "license_name", ",", "entity", ",", "entity_display_name", ",", "safety_checks", "=", "True", ",", "service_instance", "=", "None", ")", ":", "log", ".", "trace", "(", "'Assigning license %s to entity %s'", ",", "l...
33.5
23.909091
def invalidate(self): """Invalidate cached data for this page.""" cache.delete(self.PAGE_LANGUAGES_KEY % (self.pk)) cache.delete('PAGE_FIRST_ROOT_ID') cache.delete(self.CHILDREN_KEY % self.pk) cache.delete(self.PUB_CHILDREN_KEY % self.pk) # XXX: Should this have a depth ...
[ "def", "invalidate", "(", "self", ")", ":", "cache", ".", "delete", "(", "self", ".", "PAGE_LANGUAGES_KEY", "%", "(", "self", ".", "pk", ")", ")", "cache", ".", "delete", "(", "'PAGE_FIRST_ROOT_ID'", ")", "cache", ".", "delete", "(", "self", ".", "CHIL...
32.358974
13.820513
def gap_proportion(sequences, gap_chars='-'): """ Generates a list with the proportion of gaps by index in a set of sequences. """ aln_len = None gaps = [] for i, sequence in enumerate(sequences): if aln_len is None: aln_len = len(sequence) gaps = [0] * aln_le...
[ "def", "gap_proportion", "(", "sequences", ",", "gap_chars", "=", "'-'", ")", ":", "aln_len", "=", "None", "gaps", "=", "[", "]", "for", "i", ",", "sequence", "in", "enumerate", "(", "sequences", ")", ":", "if", "aln_len", "is", "None", ":", "aln_len",...
32.25
16.166667
def getHostsFromFile(filename): """Parse a file to return a list of hosts.""" valid_hostname = r"^[^ /\t=\n]+" workers = r"\d+" hostname_re = re.compile(valid_hostname) worker_re = re.compile(workers) hosts = [] with open(filename) as f: for line in f: # check to see if i...
[ "def", "getHostsFromFile", "(", "filename", ")", ":", "valid_hostname", "=", "r\"^[^ /\\t=\\n]+\"", "workers", "=", "r\"\\d+\"", "hostname_re", "=", "re", ".", "compile", "(", "valid_hostname", ")", "worker_re", "=", "re", ".", "compile", "(", "workers", ")", ...
36.96
13
def train_on_replay_memory(self, batch_info): """ Train agent on a memory gotten from replay buffer """ self.model.train() # Algo will aggregate data into this list: batch_info['sub_batch_data'] = [] for i in range(self.settings.training_rounds): sampled_rollout = s...
[ "def", "train_on_replay_memory", "(", "self", ",", "batch_info", ")", ":", "self", ".", "model", ".", "train", "(", ")", "# Algo will aggregate data into this list:", "batch_info", "[", "'sub_batch_data'", "]", "=", "[", "]", "for", "i", "in", "range", "(", "s...
37.045455
22.727273
def handle_gateway_ready_20(msg): """Process an internal gateway ready message.""" _LOGGER.info( 'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type, msg.sub_type, msg.payload) msg.gateway.alert(msg) return msg.copy( node_id=255, ack=0, sub_type=msg.gateway.co...
[ "def", "handle_gateway_ready_20", "(", "msg", ")", ":", "_LOGGER", ".", "info", "(", "'n:%s c:%s t:%s s:%s p:%s'", ",", "msg", ".", "node_id", ",", "msg", ".", "child_id", ",", "msg", ".", "type", ",", "msg", ".", "sub_type", ",", "msg", ".", "payload", ...
38.666667
15.777778
def supports_heading_type(self, heading_type=None): """Tests if the given heading type is supported. arg: heading_type (osid.type.Type): a heading Type return: (boolean) - ``true`` if the type is supported, ``false`` otherwise raise: IllegalState - syntax is not a ``...
[ "def", "supports_heading_type", "(", "self", ",", "heading_type", "=", "None", ")", ":", "# Implemented from template for osid.Metadata.supports_coordinate_type", "from", ".", "osid_errors", "import", "IllegalState", ",", "NullArgument", "if", "not", "heading_type", ":", ...
47.555556
20.166667
def split_levels(fields): """ Convert dot-notation such as ['a', 'a.b', 'a.d', 'c'] into current-level fields ['a', 'c'] and next-level fields {'a': ['b', 'd']}. """ first_level_fields = [] next_level_fields = {} if not fields: return first_level_fields, next_level_f...
[ "def", "split_levels", "(", "fields", ")", ":", "first_level_fields", "=", "[", "]", "next_level_fields", "=", "{", "}", "if", "not", "fields", ":", "return", "first_level_fields", ",", "next_level_fields", "if", "not", "isinstance", "(", "fields", ",", "list"...
33.041667
18.208333
def ori(ip, rc=None, r=None, iq=None, ico=None, pl=None, fl=None, fs=None, ot=None, coe=None, moc=None): # pylint: disable=too-many-arguments, redefined-outer-name, invalid-name """ This function is a wrapper for :meth:`~pywbem.WBEMConnection.OpenReferenceInstances`. Open an enumeration ses...
[ "def", "ori", "(", "ip", ",", "rc", "=", "None", ",", "r", "=", "None", ",", "iq", "=", "None", ",", "ico", "=", "None", ",", "pl", "=", "None", ",", "fl", "=", "None", ",", "fs", "=", "None", ",", "ot", "=", "None", ",", "coe", "=", "Non...
38.161017
25.991525