id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
231,200
mbj4668/pyang
pyang/translators/dsdl.py
HybridDSDLSchema.choice_type
def choice_type(self, tchain, p_elem): """Handle ``enumeration`` and ``union`` types.""" elem = SchemaNode.choice(p_elem, occur=2) self.handle_substmts(tchain[0], elem)
python
def choice_type(self, tchain, p_elem): """Handle ``enumeration`` and ``union`` types.""" elem = SchemaNode.choice(p_elem, occur=2) self.handle_substmts(tchain[0], elem)
[ "def", "choice_type", "(", "self", ",", "tchain", ",", "p_elem", ")", ":", "elem", "=", "SchemaNode", ".", "choice", "(", "p_elem", ",", "occur", "=", "2", ")", "self", ".", "handle_substmts", "(", "tchain", "[", "0", "]", ",", "elem", ")" ]
Handle ``enumeration`` and ``union`` types.
[ "Handle", "enumeration", "and", "union", "types", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/dsdl.py#L1223-L1226
231,201
mbj4668/pyang
pyang/translators/dsdl.py
HybridDSDLSchema.mapped_type
def mapped_type(self, tchain, p_elem): """Handle types that are simply mapped to RELAX NG.""" SchemaNode("data", p_elem).set_attr("type", self.datatype_map[tchain[0].arg])
python
def mapped_type(self, tchain, p_elem): """Handle types that are simply mapped to RELAX NG.""" SchemaNode("data", p_elem).set_attr("type", self.datatype_map[tchain[0].arg])
[ "def", "mapped_type", "(", "self", ",", "tchain", ",", "p_elem", ")", ":", "SchemaNode", "(", "\"data\"", ",", "p_elem", ")", ".", "set_attr", "(", "\"type\"", ",", "self", ".", "datatype_map", "[", "tchain", "[", "0", "]", ".", "arg", "]", ")" ]
Handle types that are simply mapped to RELAX NG.
[ "Handle", "types", "that", "are", "simply", "mapped", "to", "RELAX", "NG", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/dsdl.py#L1262-L1265
231,202
mbj4668/pyang
pyang/translators/dsdl.py
HybridDSDLSchema.numeric_type
def numeric_type(self, tchain, p_elem): """Handle numeric types.""" typ = tchain[0].arg def gen_data(): elem = SchemaNode("data").set_attr("type", self.datatype_map[typ]) if typ == "decimal64": fd = tchain[0].search_one("fraction-digits").arg SchemaNode("param",elem,"19").set_attr("name","totalDigits") SchemaNode("param",elem,fd).set_attr("name","fractionDigits") return elem self.type_with_ranges(tchain, p_elem, "range", gen_data)
python
def numeric_type(self, tchain, p_elem): """Handle numeric types.""" typ = tchain[0].arg def gen_data(): elem = SchemaNode("data").set_attr("type", self.datatype_map[typ]) if typ == "decimal64": fd = tchain[0].search_one("fraction-digits").arg SchemaNode("param",elem,"19").set_attr("name","totalDigits") SchemaNode("param",elem,fd).set_attr("name","fractionDigits") return elem self.type_with_ranges(tchain, p_elem, "range", gen_data)
[ "def", "numeric_type", "(", "self", ",", "tchain", ",", "p_elem", ")", ":", "typ", "=", "tchain", "[", "0", "]", ".", "arg", "def", "gen_data", "(", ")", ":", "elem", "=", "SchemaNode", "(", "\"data\"", ")", ".", "set_attr", "(", "\"type\"", ",", "self", ".", "datatype_map", "[", "typ", "]", ")", "if", "typ", "==", "\"decimal64\"", ":", "fd", "=", "tchain", "[", "0", "]", ".", "search_one", "(", "\"fraction-digits\"", ")", ".", "arg", "SchemaNode", "(", "\"param\"", ",", "elem", ",", "\"19\"", ")", ".", "set_attr", "(", "\"name\"", ",", "\"totalDigits\"", ")", "SchemaNode", "(", "\"param\"", ",", "elem", ",", "fd", ")", ".", "set_attr", "(", "\"name\"", ",", "\"fractionDigits\"", ")", "return", "elem", "self", ".", "type_with_ranges", "(", "tchain", ",", "p_elem", ",", "\"range\"", ",", "gen_data", ")" ]
Handle numeric types.
[ "Handle", "numeric", "types", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/dsdl.py#L1267-L1277
231,203
mbj4668/pyang
pyang/grammar.py
add_stmt
def add_stmt(stmt, arg_rules): """Use by plugins to add grammar for an extension statement.""" (arg, rules) = arg_rules stmt_map[stmt] = (arg, rules)
python
def add_stmt(stmt, arg_rules): """Use by plugins to add grammar for an extension statement.""" (arg, rules) = arg_rules stmt_map[stmt] = (arg, rules)
[ "def", "add_stmt", "(", "stmt", ",", "arg_rules", ")", ":", "(", "arg", ",", "rules", ")", "=", "arg_rules", "stmt_map", "[", "stmt", "]", "=", "(", "arg", ",", "rules", ")" ]
Use by plugins to add grammar for an extension statement.
[ "Use", "by", "plugins", "to", "add", "grammar", "for", "an", "extension", "statement", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L77-L80
231,204
mbj4668/pyang
pyang/grammar.py
add_to_stmts_rules
def add_to_stmts_rules(stmts, rules): """Use by plugins to add extra rules to the existing rules for a statement.""" def is_rule_less_than(ra, rb): rka = ra[0] rkb = rb[0] if not util.is_prefixed(rkb): # old rule is non-prefixed; append new rule after return False if not util.is_prefixed(rka): # old rule prefixed, but new rule is not, insert return True # both are prefixed, compare modulename return rka[0] < rkb[0] for s in stmts: (arg, rules0) = stmt_map[s] for r in rules: i = 0 while i < len(rules0): if is_rule_less_than(r, rules0[i]): rules0.insert(i, r) break i += 1 if i == len(rules0): rules0.insert(i, r)
python
def add_to_stmts_rules(stmts, rules): """Use by plugins to add extra rules to the existing rules for a statement.""" def is_rule_less_than(ra, rb): rka = ra[0] rkb = rb[0] if not util.is_prefixed(rkb): # old rule is non-prefixed; append new rule after return False if not util.is_prefixed(rka): # old rule prefixed, but new rule is not, insert return True # both are prefixed, compare modulename return rka[0] < rkb[0] for s in stmts: (arg, rules0) = stmt_map[s] for r in rules: i = 0 while i < len(rules0): if is_rule_less_than(r, rules0[i]): rules0.insert(i, r) break i += 1 if i == len(rules0): rules0.insert(i, r)
[ "def", "add_to_stmts_rules", "(", "stmts", ",", "rules", ")", ":", "def", "is_rule_less_than", "(", "ra", ",", "rb", ")", ":", "rka", "=", "ra", "[", "0", "]", "rkb", "=", "rb", "[", "0", "]", "if", "not", "util", ".", "is_prefixed", "(", "rkb", ")", ":", "# old rule is non-prefixed; append new rule after", "return", "False", "if", "not", "util", ".", "is_prefixed", "(", "rka", ")", ":", "# old rule prefixed, but new rule is not, insert", "return", "True", "# both are prefixed, compare modulename", "return", "rka", "[", "0", "]", "<", "rkb", "[", "0", "]", "for", "s", "in", "stmts", ":", "(", "arg", ",", "rules0", ")", "=", "stmt_map", "[", "s", "]", "for", "r", "in", "rules", ":", "i", "=", "0", "while", "i", "<", "len", "(", "rules0", ")", ":", "if", "is_rule_less_than", "(", "r", ",", "rules0", "[", "i", "]", ")", ":", "rules0", ".", "insert", "(", "i", ",", "r", ")", "break", "i", "+=", "1", "if", "i", "==", "len", "(", "rules0", ")", ":", "rules0", ".", "insert", "(", "i", ",", "r", ")" ]
Use by plugins to add extra rules to the existing rules for a statement.
[ "Use", "by", "plugins", "to", "add", "extra", "rules", "to", "the", "existing", "rules", "for", "a", "statement", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L82-L106
231,205
mbj4668/pyang
pyang/grammar.py
chk_module_statements
def chk_module_statements(ctx, module_stmt, canonical=False): """Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise. """ return chk_statement(ctx, module_stmt, top_stmts, canonical)
python
def chk_module_statements(ctx, module_stmt, canonical=False): """Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise. """ return chk_statement(ctx, module_stmt, top_stmts, canonical)
[ "def", "chk_module_statements", "(", "ctx", ",", "module_stmt", ",", "canonical", "=", "False", ")", ":", "return", "chk_statement", "(", "ctx", ",", "module_stmt", ",", "top_stmts", ",", "canonical", ")" ]
Validate the statement hierarchy according to the grammar. Return True if module is valid, False otherwise.
[ "Validate", "the", "statement", "hierarchy", "according", "to", "the", "grammar", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L570-L575
231,206
mbj4668/pyang
pyang/grammar.py
chk_statement
def chk_statement(ctx, stmt, grammar, canonical=False): """Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise. """ n = len(ctx.errors) if canonical == True: canspec = grammar else: canspec = [] _chk_stmts(ctx, stmt.pos, [stmt], None, (grammar, canspec), canonical) return n == len(ctx.errors)
python
def chk_statement(ctx, stmt, grammar, canonical=False): """Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise. """ n = len(ctx.errors) if canonical == True: canspec = grammar else: canspec = [] _chk_stmts(ctx, stmt.pos, [stmt], None, (grammar, canspec), canonical) return n == len(ctx.errors)
[ "def", "chk_statement", "(", "ctx", ",", "stmt", ",", "grammar", ",", "canonical", "=", "False", ")", ":", "n", "=", "len", "(", "ctx", ".", "errors", ")", "if", "canonical", "==", "True", ":", "canspec", "=", "grammar", "else", ":", "canspec", "=", "[", "]", "_chk_stmts", "(", "ctx", ",", "stmt", ".", "pos", ",", "[", "stmt", "]", ",", "None", ",", "(", "grammar", ",", "canspec", ")", ",", "canonical", ")", "return", "n", "==", "len", "(", "ctx", ".", "errors", ")" ]
Validate `stmt` according to `grammar`. Marks each statement in the hierearchy with stmt.is_grammatically_valid, which is a boolean. Return True if stmt is valid, False otherwise.
[ "Validate", "stmt", "according", "to", "grammar", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L577-L591
231,207
mbj4668/pyang
pyang/grammar.py
sort_canonical
def sort_canonical(keyword, stmts): """Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is. """ try: (_arg_type, subspec) = stmt_map[keyword] except KeyError: return stmts res = [] # keep the order of data definition statements and case keep = [s[0] for s in data_def_stmts] + ['case'] for (kw, _spec) in flatten_spec(subspec): # keep comments before a statement together with that statement comments = [] for s in stmts: if s.keyword == '_comment': comments.append(s) elif s.keyword == kw and kw not in keep: res.extend(comments) comments = [] res.append(s) else: comments = [] # then copy all other statements (extensions) res.extend([stmt for stmt in stmts if stmt not in res]) return res
python
def sort_canonical(keyword, stmts): """Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is. """ try: (_arg_type, subspec) = stmt_map[keyword] except KeyError: return stmts res = [] # keep the order of data definition statements and case keep = [s[0] for s in data_def_stmts] + ['case'] for (kw, _spec) in flatten_spec(subspec): # keep comments before a statement together with that statement comments = [] for s in stmts: if s.keyword == '_comment': comments.append(s) elif s.keyword == kw and kw not in keep: res.extend(comments) comments = [] res.append(s) else: comments = [] # then copy all other statements (extensions) res.extend([stmt for stmt in stmts if stmt not in res]) return res
[ "def", "sort_canonical", "(", "keyword", ",", "stmts", ")", ":", "try", ":", "(", "_arg_type", ",", "subspec", ")", "=", "stmt_map", "[", "keyword", "]", "except", "KeyError", ":", "return", "stmts", "res", "=", "[", "]", "# keep the order of data definition statements and case", "keep", "=", "[", "s", "[", "0", "]", "for", "s", "in", "data_def_stmts", "]", "+", "[", "'case'", "]", "for", "(", "kw", ",", "_spec", ")", "in", "flatten_spec", "(", "subspec", ")", ":", "# keep comments before a statement together with that statement", "comments", "=", "[", "]", "for", "s", "in", "stmts", ":", "if", "s", ".", "keyword", "==", "'_comment'", ":", "comments", ".", "append", "(", "s", ")", "elif", "s", ".", "keyword", "==", "kw", "and", "kw", "not", "in", "keep", ":", "res", ".", "extend", "(", "comments", ")", "comments", "=", "[", "]", "res", ".", "append", "(", "s", ")", "else", ":", "comments", "=", "[", "]", "# then copy all other statements (extensions)", "res", ".", "extend", "(", "[", "stmt", "for", "stmt", "in", "stmts", "if", "stmt", "not", "in", "res", "]", ")", "return", "res" ]
Sort all `stmts` in the canonical order defined by `keyword`. Return the sorted list. The `stmt` list is not modified. If `keyword` does not have a canonical order, the list is returned as is.
[ "Sort", "all", "stmts", "in", "the", "canonical", "order", "defined", "by", "keyword", ".", "Return", "the", "sorted", "list", ".", "The", "stmt", "list", "is", "not", "modified", ".", "If", "keyword", "does", "not", "have", "a", "canonical", "order", "the", "list", "is", "returned", "as", "is", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/grammar.py#L799-L828
231,208
mbj4668/pyang
pyang/xpath_lexer.py
scan
def scan(s): """Return a list of tokens, or throw SyntaxError on failure. """ line = 1 linepos = 1 pos = 0 toks = [] while pos < len(s): matched = False for (tokname, r) in patterns: m = r.match(s, pos) if m is not None: # found a matching token v = m.group(0) prec = _preceding_token(toks) if tokname == 'STAR' and prec is not None and _is_special(prec): # XPath 1.0 spec, 3.7 special rule 1a # interpret '*' as a wildcard tok = XPathTok('wildcard', v, line, linepos) elif (tokname == 'name' and prec is not None and not _is_special(prec) and v in operators): # XPath 1.0 spec, 3.7 special rule 1b # interpret the name as an operator tok = XPathTok(operators[v], v, line, linepos) elif tokname == 'name': # check if next token is '(' if re_open_para.match(s, pos + len(v)): # XPath 1.0 spec, 3.7 special rule 2 if v in node_types: # XPath 1.0 spec, 3.7 special rule 2a tok = XPathTok('node_type', v, line, linepos) else: # XPath 1.0 spec, 3.7 special rule 2b tok = XPathTok('function_name', v, line, linepos) # check if next token is '::' elif re_axis.match(s, pos + len(v)): # XPath 1.0 spec, 3.7 special rule 3 if v in axes: tok = XPathTok('axis', v, line, linepos) else: e = "unknown axis %s" % v raise XPathError(e, line, linepos) else: tok = XPathTok('name', v, line, linepos) else: tok = XPathTok(tokname, v, line, linepos) if tokname == '_whitespace': n = v.count('\n') if n > 0: line = line + n linepos = len(v) - v.rfind('\n') else: linepos += len(v) else: linepos += len(v) pos += len(v) toks.append(tok) matched = True break if matched == False: # no patterns matched raise XPathError('syntax error', line, linepos) return toks
python
def scan(s): """Return a list of tokens, or throw SyntaxError on failure. """ line = 1 linepos = 1 pos = 0 toks = [] while pos < len(s): matched = False for (tokname, r) in patterns: m = r.match(s, pos) if m is not None: # found a matching token v = m.group(0) prec = _preceding_token(toks) if tokname == 'STAR' and prec is not None and _is_special(prec): # XPath 1.0 spec, 3.7 special rule 1a # interpret '*' as a wildcard tok = XPathTok('wildcard', v, line, linepos) elif (tokname == 'name' and prec is not None and not _is_special(prec) and v in operators): # XPath 1.0 spec, 3.7 special rule 1b # interpret the name as an operator tok = XPathTok(operators[v], v, line, linepos) elif tokname == 'name': # check if next token is '(' if re_open_para.match(s, pos + len(v)): # XPath 1.0 spec, 3.7 special rule 2 if v in node_types: # XPath 1.0 spec, 3.7 special rule 2a tok = XPathTok('node_type', v, line, linepos) else: # XPath 1.0 spec, 3.7 special rule 2b tok = XPathTok('function_name', v, line, linepos) # check if next token is '::' elif re_axis.match(s, pos + len(v)): # XPath 1.0 spec, 3.7 special rule 3 if v in axes: tok = XPathTok('axis', v, line, linepos) else: e = "unknown axis %s" % v raise XPathError(e, line, linepos) else: tok = XPathTok('name', v, line, linepos) else: tok = XPathTok(tokname, v, line, linepos) if tokname == '_whitespace': n = v.count('\n') if n > 0: line = line + n linepos = len(v) - v.rfind('\n') else: linepos += len(v) else: linepos += len(v) pos += len(v) toks.append(tok) matched = True break if matched == False: # no patterns matched raise XPathError('syntax error', line, linepos) return toks
[ "def", "scan", "(", "s", ")", ":", "line", "=", "1", "linepos", "=", "1", "pos", "=", "0", "toks", "=", "[", "]", "while", "pos", "<", "len", "(", "s", ")", ":", "matched", "=", "False", "for", "(", "tokname", ",", "r", ")", "in", "patterns", ":", "m", "=", "r", ".", "match", "(", "s", ",", "pos", ")", "if", "m", "is", "not", "None", ":", "# found a matching token", "v", "=", "m", ".", "group", "(", "0", ")", "prec", "=", "_preceding_token", "(", "toks", ")", "if", "tokname", "==", "'STAR'", "and", "prec", "is", "not", "None", "and", "_is_special", "(", "prec", ")", ":", "# XPath 1.0 spec, 3.7 special rule 1a", "# interpret '*' as a wildcard", "tok", "=", "XPathTok", "(", "'wildcard'", ",", "v", ",", "line", ",", "linepos", ")", "elif", "(", "tokname", "==", "'name'", "and", "prec", "is", "not", "None", "and", "not", "_is_special", "(", "prec", ")", "and", "v", "in", "operators", ")", ":", "# XPath 1.0 spec, 3.7 special rule 1b", "# interpret the name as an operator", "tok", "=", "XPathTok", "(", "operators", "[", "v", "]", ",", "v", ",", "line", ",", "linepos", ")", "elif", "tokname", "==", "'name'", ":", "# check if next token is '('", "if", "re_open_para", ".", "match", "(", "s", ",", "pos", "+", "len", "(", "v", ")", ")", ":", "# XPath 1.0 spec, 3.7 special rule 2", "if", "v", "in", "node_types", ":", "# XPath 1.0 spec, 3.7 special rule 2a", "tok", "=", "XPathTok", "(", "'node_type'", ",", "v", ",", "line", ",", "linepos", ")", "else", ":", "# XPath 1.0 spec, 3.7 special rule 2b", "tok", "=", "XPathTok", "(", "'function_name'", ",", "v", ",", "line", ",", "linepos", ")", "# check if next token is '::'", "elif", "re_axis", ".", "match", "(", "s", ",", "pos", "+", "len", "(", "v", ")", ")", ":", "# XPath 1.0 spec, 3.7 special rule 3", "if", "v", "in", "axes", ":", "tok", "=", "XPathTok", "(", "'axis'", ",", "v", ",", "line", ",", "linepos", ")", "else", ":", "e", "=", "\"unknown axis %s\"", "%", "v", "raise", "XPathError", "(", "e", ",", "line", ",", "linepos", ")", "else", ":", "tok", "=", "XPathTok", "(", "'name'", ",", "v", ",", "line", ",", "linepos", ")", "else", ":", "tok", "=", "XPathTok", "(", "tokname", ",", "v", ",", "line", ",", "linepos", ")", "if", "tokname", "==", "'_whitespace'", ":", "n", "=", "v", ".", "count", "(", "'\\n'", ")", "if", "n", ">", "0", ":", "line", "=", "line", "+", "n", "linepos", "=", "len", "(", "v", ")", "-", "v", ".", "rfind", "(", "'\\n'", ")", "else", ":", "linepos", "+=", "len", "(", "v", ")", "else", ":", "linepos", "+=", "len", "(", "v", ")", "pos", "+=", "len", "(", "v", ")", "toks", ".", "append", "(", "tok", ")", "matched", "=", "True", "break", "if", "matched", "==", "False", ":", "# no patterns matched", "raise", "XPathError", "(", "'syntax error'", ",", "line", ",", "linepos", ")", "return", "toks" ]
Return a list of tokens, or throw SyntaxError on failure.
[ "Return", "a", "list", "of", "tokens", "or", "throw", "SyntaxError", "on", "failure", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/xpath_lexer.py#L112-L175
231,209
mbj4668/pyang
pyang/hello.py
HelloParser.yang_modules
def yang_modules(self): """ Return a list of advertised YANG module names with revisions. Avoid repeated modules. """ res = {} for c in self.capabilities: m = c.parameters.get("module") if m is None or m in res: continue res[m] = c.parameters.get("revision") return res.items()
python
def yang_modules(self): """ Return a list of advertised YANG module names with revisions. Avoid repeated modules. """ res = {} for c in self.capabilities: m = c.parameters.get("module") if m is None or m in res: continue res[m] = c.parameters.get("revision") return res.items()
[ "def", "yang_modules", "(", "self", ")", ":", "res", "=", "{", "}", "for", "c", "in", "self", ".", "capabilities", ":", "m", "=", "c", ".", "parameters", ".", "get", "(", "\"module\"", ")", "if", "m", "is", "None", "or", "m", "in", "res", ":", "continue", "res", "[", "m", "]", "=", "c", ".", "parameters", ".", "get", "(", "\"revision\"", ")", "return", "res", ".", "items", "(", ")" ]
Return a list of advertised YANG module names with revisions. Avoid repeated modules.
[ "Return", "a", "list", "of", "advertised", "YANG", "module", "names", "with", "revisions", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/hello.py#L75-L86
231,210
mbj4668/pyang
pyang/hello.py
HelloParser.get_features
def get_features(self, yam): """Return list of features declared for module `yam`.""" mcap = [ c for c in self.capabilities if c.parameters.get("module", None) == yam ][0] if not mcap.parameters.get("features"): return [] return mcap.parameters["features"].split(",")
python
def get_features(self, yam): """Return list of features declared for module `yam`.""" mcap = [ c for c in self.capabilities if c.parameters.get("module", None) == yam ][0] if not mcap.parameters.get("features"): return [] return mcap.parameters["features"].split(",")
[ "def", "get_features", "(", "self", ",", "yam", ")", ":", "mcap", "=", "[", "c", "for", "c", "in", "self", ".", "capabilities", "if", "c", ".", "parameters", ".", "get", "(", "\"module\"", ",", "None", ")", "==", "yam", "]", "[", "0", "]", "if", "not", "mcap", ".", "parameters", ".", "get", "(", "\"features\"", ")", ":", "return", "[", "]", "return", "mcap", ".", "parameters", "[", "\"features\"", "]", ".", "split", "(", "\",\"", ")" ]
Return list of features declared for module `yam`.
[ "Return", "list", "of", "features", "declared", "for", "module", "yam", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/hello.py#L88-L93
231,211
mbj4668/pyang
pyang/hello.py
HelloParser.registered_capabilities
def registered_capabilities(self): """Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account. """ return dict ([ (CAPABILITIES[c.id],c) for c in self.capabilities if c.id in CAPABILITIES ])
python
def registered_capabilities(self): """Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account. """ return dict ([ (CAPABILITIES[c.id],c) for c in self.capabilities if c.id in CAPABILITIES ])
[ "def", "registered_capabilities", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "CAPABILITIES", "[", "c", ".", "id", "]", ",", "c", ")", "for", "c", "in", "self", ".", "capabilities", "if", "c", ".", "id", "in", "CAPABILITIES", "]", ")" ]
Return dictionary of non-YANG capabilities. Only capabilities from the `CAPABILITIES` dictionary are taken into account.
[ "Return", "dictionary", "of", "non", "-", "YANG", "capabilities", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/hello.py#L95-L102
231,212
mbj4668/pyang
pyang/util.py
listsdelete
def listsdelete(x, xs): """Return a new list with x removed from xs""" i = xs.index(x) return xs[:i] + xs[(i+1):]
python
def listsdelete(x, xs): """Return a new list with x removed from xs""" i = xs.index(x) return xs[:i] + xs[(i+1):]
[ "def", "listsdelete", "(", "x", ",", "xs", ")", ":", "i", "=", "xs", ".", "index", "(", "x", ")", "return", "xs", "[", ":", "i", "]", "+", "xs", "[", "(", "i", "+", "1", ")", ":", "]" ]
Return a new list with x removed from xs
[ "Return", "a", "new", "list", "with", "x", "removed", "from", "xs" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/util.py#L76-L79
231,213
mbj4668/pyang
pyang/util.py
unique_prefixes
def unique_prefixes(context): """Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary. """ res = {} for m in context.modules.values(): if m.keyword == "submodule": continue prf = new = m.i_prefix suff = 0 while new in res.values(): suff += 1 new = "%s%x" % (prf, suff) res[m] = new return res
python
def unique_prefixes(context): """Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary. """ res = {} for m in context.modules.values(): if m.keyword == "submodule": continue prf = new = m.i_prefix suff = 0 while new in res.values(): suff += 1 new = "%s%x" % (prf, suff) res[m] = new return res
[ "def", "unique_prefixes", "(", "context", ")", ":", "res", "=", "{", "}", "for", "m", "in", "context", ".", "modules", ".", "values", "(", ")", ":", "if", "m", ".", "keyword", "==", "\"submodule\"", ":", "continue", "prf", "=", "new", "=", "m", ".", "i_prefix", "suff", "=", "0", "while", "new", "in", "res", ".", "values", "(", ")", ":", "suff", "+=", "1", "new", "=", "\"%s%x\"", "%", "(", "prf", ",", "suff", ")", "res", "[", "m", "]", "=", "new", "return", "res" ]
Return a dictionary with unique prefixes for modules in `context`. Keys are 'module' statements and values are prefixes, disambiguated where necessary.
[ "Return", "a", "dictionary", "with", "unique", "prefixes", "for", "modules", "in", "context", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/util.py#L120-L135
231,214
mbj4668/pyang
setup.py
PyangDist.preprocess_files
def preprocess_files(self, prefix): """Change the installation prefix where necessary. """ if prefix is None: return files = ("bin/yang2dsdl", "man/man1/yang2dsdl.1", "pyang/plugins/jsonxsl.py") regex = re.compile("^(.*)/usr/local(.*)$") for f in files: inf = open(f) cnt = inf.readlines() inf.close() ouf = open(f,"w") for line in cnt: mo = regex.search(line) if mo is None: ouf.write(line) else: ouf.write(mo.group(1) + prefix + mo.group(2) + "\n") ouf.close()
python
def preprocess_files(self, prefix): """Change the installation prefix where necessary. """ if prefix is None: return files = ("bin/yang2dsdl", "man/man1/yang2dsdl.1", "pyang/plugins/jsonxsl.py") regex = re.compile("^(.*)/usr/local(.*)$") for f in files: inf = open(f) cnt = inf.readlines() inf.close() ouf = open(f,"w") for line in cnt: mo = regex.search(line) if mo is None: ouf.write(line) else: ouf.write(mo.group(1) + prefix + mo.group(2) + "\n") ouf.close()
[ "def", "preprocess_files", "(", "self", ",", "prefix", ")", ":", "if", "prefix", "is", "None", ":", "return", "files", "=", "(", "\"bin/yang2dsdl\"", ",", "\"man/man1/yang2dsdl.1\"", ",", "\"pyang/plugins/jsonxsl.py\"", ")", "regex", "=", "re", ".", "compile", "(", "\"^(.*)/usr/local(.*)$\"", ")", "for", "f", "in", "files", ":", "inf", "=", "open", "(", "f", ")", "cnt", "=", "inf", ".", "readlines", "(", ")", "inf", ".", "close", "(", ")", "ouf", "=", "open", "(", "f", ",", "\"w\"", ")", "for", "line", "in", "cnt", ":", "mo", "=", "regex", ".", "search", "(", "line", ")", "if", "mo", "is", "None", ":", "ouf", ".", "write", "(", "line", ")", "else", ":", "ouf", ".", "write", "(", "mo", ".", "group", "(", "1", ")", "+", "prefix", "+", "mo", ".", "group", "(", "2", ")", "+", "\"\\n\"", ")", "ouf", ".", "close", "(", ")" ]
Change the installation prefix where necessary.
[ "Change", "the", "installation", "prefix", "where", "necessary", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/setup.py#L26-L45
231,215
mbj4668/pyang
pyang/__init__.py
Context.add_module
def add_module(self, ref, text, format=None, expect_modulename=None, expect_revision=None, expect_failure_error=True): """Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for the user. used in error messages `text` is the raw text data `format` is one of 'yang' or 'yin'. Returns the parsed and validated module on success, and None on error. """ if format == None: format = util.guess_format(text) if format == 'yin': p = yin_parser.YinParser() else: p = yang_parser.YangParser() module = p.parse(self, ref, text) if module is None: return None if expect_modulename is not None: if not re.match(syntax.re_identifier, expect_modulename): error.err_add(self.errors, module.pos, 'FILENAME_BAD_MODULE_NAME', (ref, expect_modulename, syntax.identifier)) elif expect_modulename != module.arg: if expect_failure_error: error.err_add(self.errors, module.pos, 'BAD_MODULE_NAME', (module.arg, ref, expect_modulename)) return None else: error.err_add(self.errors, module.pos, 'WBAD_MODULE_NAME', (module.arg, ref, expect_modulename)) latest_rev = util.get_latest_revision(module) if expect_revision is not None: if not re.match(syntax.re_date, expect_revision): error.err_add(self.errors, module.pos, 'FILENAME_BAD_REVISION', (ref, expect_revision, 'YYYY-MM-DD')) elif expect_revision != latest_rev: if expect_failure_error: error.err_add(self.errors, module.pos, 'BAD_REVISION', (latest_rev, ref, expect_revision)) return None else: error.err_add(self.errors, module.pos, 'WBAD_REVISION', (latest_rev, ref, expect_revision)) if module.arg not in self.revs: self.revs[module.arg] = [] revs = self.revs[module.arg] revs.append((latest_rev, None)) return self.add_parsed_module(module)
python
def add_module(self, ref, text, format=None, expect_modulename=None, expect_revision=None, expect_failure_error=True): """Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for the user. used in error messages `text` is the raw text data `format` is one of 'yang' or 'yin'. Returns the parsed and validated module on success, and None on error. """ if format == None: format = util.guess_format(text) if format == 'yin': p = yin_parser.YinParser() else: p = yang_parser.YangParser() module = p.parse(self, ref, text) if module is None: return None if expect_modulename is not None: if not re.match(syntax.re_identifier, expect_modulename): error.err_add(self.errors, module.pos, 'FILENAME_BAD_MODULE_NAME', (ref, expect_modulename, syntax.identifier)) elif expect_modulename != module.arg: if expect_failure_error: error.err_add(self.errors, module.pos, 'BAD_MODULE_NAME', (module.arg, ref, expect_modulename)) return None else: error.err_add(self.errors, module.pos, 'WBAD_MODULE_NAME', (module.arg, ref, expect_modulename)) latest_rev = util.get_latest_revision(module) if expect_revision is not None: if not re.match(syntax.re_date, expect_revision): error.err_add(self.errors, module.pos, 'FILENAME_BAD_REVISION', (ref, expect_revision, 'YYYY-MM-DD')) elif expect_revision != latest_rev: if expect_failure_error: error.err_add(self.errors, module.pos, 'BAD_REVISION', (latest_rev, ref, expect_revision)) return None else: error.err_add(self.errors, module.pos, 'WBAD_REVISION', (latest_rev, ref, expect_revision)) if module.arg not in self.revs: self.revs[module.arg] = [] revs = self.revs[module.arg] revs.append((latest_rev, None)) return self.add_parsed_module(module)
[ "def", "add_module", "(", "self", ",", "ref", ",", "text", ",", "format", "=", "None", ",", "expect_modulename", "=", "None", ",", "expect_revision", "=", "None", ",", "expect_failure_error", "=", "True", ")", ":", "if", "format", "==", "None", ":", "format", "=", "util", ".", "guess_format", "(", "text", ")", "if", "format", "==", "'yin'", ":", "p", "=", "yin_parser", ".", "YinParser", "(", ")", "else", ":", "p", "=", "yang_parser", ".", "YangParser", "(", ")", "module", "=", "p", ".", "parse", "(", "self", ",", "ref", ",", "text", ")", "if", "module", "is", "None", ":", "return", "None", "if", "expect_modulename", "is", "not", "None", ":", "if", "not", "re", ".", "match", "(", "syntax", ".", "re_identifier", ",", "expect_modulename", ")", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'FILENAME_BAD_MODULE_NAME'", ",", "(", "ref", ",", "expect_modulename", ",", "syntax", ".", "identifier", ")", ")", "elif", "expect_modulename", "!=", "module", ".", "arg", ":", "if", "expect_failure_error", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'BAD_MODULE_NAME'", ",", "(", "module", ".", "arg", ",", "ref", ",", "expect_modulename", ")", ")", "return", "None", "else", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'WBAD_MODULE_NAME'", ",", "(", "module", ".", "arg", ",", "ref", ",", "expect_modulename", ")", ")", "latest_rev", "=", "util", ".", "get_latest_revision", "(", "module", ")", "if", "expect_revision", "is", "not", "None", ":", "if", "not", "re", ".", "match", "(", "syntax", ".", "re_date", ",", "expect_revision", ")", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'FILENAME_BAD_REVISION'", ",", "(", "ref", ",", "expect_revision", ",", "'YYYY-MM-DD'", ")", ")", "elif", "expect_revision", "!=", "latest_rev", ":", "if", "expect_failure_error", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'BAD_REVISION'", ",", "(", "latest_rev", ",", "ref", ",", "expect_revision", ")", ")", "return", "None", "else", ":", "error", ".", "err_add", "(", "self", ".", "errors", ",", "module", ".", "pos", ",", "'WBAD_REVISION'", ",", "(", "latest_rev", ",", "ref", ",", "expect_revision", ")", ")", "if", "module", ".", "arg", "not", "in", "self", ".", "revs", ":", "self", ".", "revs", "[", "module", ".", "arg", "]", "=", "[", "]", "revs", "=", "self", ".", "revs", "[", "module", ".", "arg", "]", "revs", ".", "append", "(", "(", "latest_rev", ",", "None", ")", ")", "return", "self", ".", "add_parsed_module", "(", "module", ")" ]
Parse a module text and add the module data to the context `ref` is a string which is used to identify the source of the text for the user. used in error messages `text` is the raw text data `format` is one of 'yang' or 'yin'. Returns the parsed and validated module on success, and None on error.
[ "Parse", "a", "module", "text", "and", "add", "the", "module", "data", "to", "the", "context" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/__init__.py#L56-L113
231,216
mbj4668/pyang
pyang/__init__.py
Context.del_module
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
python
def del_module(self, module): """Remove a module from the context""" rev = util.get_latest_revision(module) del self.modules[(module.arg, rev)]
[ "def", "del_module", "(", "self", ",", "module", ")", ":", "rev", "=", "util", ".", "get_latest_revision", "(", "module", ")", "del", "self", ".", "modules", "[", "(", "module", ".", "arg", ",", "rev", ")", "]" ]
Remove a module from the context
[ "Remove", "a", "module", "from", "the", "context" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/__init__.py#L138-L141
231,217
mbj4668/pyang
pyang/__init__.py
Context.get_module
def get_module(self, modulename, revision=None): """Return the module if it exists in the context""" if revision is None and modulename in self.revs: (revision, _handle) = self._get_latest_rev(self.revs[modulename]) if revision is not None: if (modulename,revision) in self.modules: return self.modules[(modulename, revision)] else: return None
python
def get_module(self, modulename, revision=None): """Return the module if it exists in the context""" if revision is None and modulename in self.revs: (revision, _handle) = self._get_latest_rev(self.revs[modulename]) if revision is not None: if (modulename,revision) in self.modules: return self.modules[(modulename, revision)] else: return None
[ "def", "get_module", "(", "self", ",", "modulename", ",", "revision", "=", "None", ")", ":", "if", "revision", "is", "None", "and", "modulename", "in", "self", ".", "revs", ":", "(", "revision", ",", "_handle", ")", "=", "self", ".", "_get_latest_rev", "(", "self", ".", "revs", "[", "modulename", "]", ")", "if", "revision", "is", "not", "None", ":", "if", "(", "modulename", ",", "revision", ")", "in", "self", ".", "modules", ":", "return", "self", ".", "modules", "[", "(", "modulename", ",", "revision", ")", "]", "else", ":", "return", "None" ]
Return the module if it exists in the context
[ "Return", "the", "module", "if", "it", "exists", "in", "the", "context" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/__init__.py#L143-L151
231,218
mbj4668/pyang
pyang/plugin.py
init
def init(plugindirs=[]): """Initialize the plugin framework""" # initialize the builtin plugins from .translators import yang,yin,dsdl yang.pyang_plugin_init() yin.pyang_plugin_init() dsdl.pyang_plugin_init() # initialize installed plugins for ep in pkg_resources.iter_entry_points(group='pyang.plugin'): plugin_init = ep.load() plugin_init() # search for plugins in std directories (plugins directory first) basedir = os.path.split(sys.modules['pyang'].__file__)[0] plugindirs.insert(0, basedir + "/transforms") plugindirs.insert(0, basedir + "/plugins") # add paths from env pluginpath = os.getenv('PYANG_PLUGINPATH') if pluginpath is not None: plugindirs.extend(pluginpath.split(os.pathsep)) syspath = sys.path for plugindir in plugindirs: sys.path = [plugindir] + syspath try: fnames = os.listdir(plugindir) except OSError: continue modnames = [] for fname in fnames: if (fname.startswith(".#") or fname.startswith("__init__.py") or fname.endswith("_flymake.py") or fname.endswith("_flymake.pyc")): pass elif fname.endswith(".py"): modname = fname[:-3] if modname not in modnames: modnames.append(modname) elif fname.endswith(".pyc"): modname = fname[:-4] if modname not in modnames: modnames.append(modname) for modname in modnames: pluginmod = __import__(modname) try: pluginmod.pyang_plugin_init() except AttributeError as s: print(pluginmod.__dict__) raise AttributeError(pluginmod.__file__ + ': ' + str(s)) sys.path = syspath
python
def init(plugindirs=[]): """Initialize the plugin framework""" # initialize the builtin plugins from .translators import yang,yin,dsdl yang.pyang_plugin_init() yin.pyang_plugin_init() dsdl.pyang_plugin_init() # initialize installed plugins for ep in pkg_resources.iter_entry_points(group='pyang.plugin'): plugin_init = ep.load() plugin_init() # search for plugins in std directories (plugins directory first) basedir = os.path.split(sys.modules['pyang'].__file__)[0] plugindirs.insert(0, basedir + "/transforms") plugindirs.insert(0, basedir + "/plugins") # add paths from env pluginpath = os.getenv('PYANG_PLUGINPATH') if pluginpath is not None: plugindirs.extend(pluginpath.split(os.pathsep)) syspath = sys.path for plugindir in plugindirs: sys.path = [plugindir] + syspath try: fnames = os.listdir(plugindir) except OSError: continue modnames = [] for fname in fnames: if (fname.startswith(".#") or fname.startswith("__init__.py") or fname.endswith("_flymake.py") or fname.endswith("_flymake.pyc")): pass elif fname.endswith(".py"): modname = fname[:-3] if modname not in modnames: modnames.append(modname) elif fname.endswith(".pyc"): modname = fname[:-4] if modname not in modnames: modnames.append(modname) for modname in modnames: pluginmod = __import__(modname) try: pluginmod.pyang_plugin_init() except AttributeError as s: print(pluginmod.__dict__) raise AttributeError(pluginmod.__file__ + ': ' + str(s)) sys.path = syspath
[ "def", "init", "(", "plugindirs", "=", "[", "]", ")", ":", "# initialize the builtin plugins", "from", ".", "translators", "import", "yang", ",", "yin", ",", "dsdl", "yang", ".", "pyang_plugin_init", "(", ")", "yin", ".", "pyang_plugin_init", "(", ")", "dsdl", ".", "pyang_plugin_init", "(", ")", "# initialize installed plugins", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "group", "=", "'pyang.plugin'", ")", ":", "plugin_init", "=", "ep", ".", "load", "(", ")", "plugin_init", "(", ")", "# search for plugins in std directories (plugins directory first)", "basedir", "=", "os", ".", "path", ".", "split", "(", "sys", ".", "modules", "[", "'pyang'", "]", ".", "__file__", ")", "[", "0", "]", "plugindirs", ".", "insert", "(", "0", ",", "basedir", "+", "\"/transforms\"", ")", "plugindirs", ".", "insert", "(", "0", ",", "basedir", "+", "\"/plugins\"", ")", "# add paths from env", "pluginpath", "=", "os", ".", "getenv", "(", "'PYANG_PLUGINPATH'", ")", "if", "pluginpath", "is", "not", "None", ":", "plugindirs", ".", "extend", "(", "pluginpath", ".", "split", "(", "os", ".", "pathsep", ")", ")", "syspath", "=", "sys", ".", "path", "for", "plugindir", "in", "plugindirs", ":", "sys", ".", "path", "=", "[", "plugindir", "]", "+", "syspath", "try", ":", "fnames", "=", "os", ".", "listdir", "(", "plugindir", ")", "except", "OSError", ":", "continue", "modnames", "=", "[", "]", "for", "fname", "in", "fnames", ":", "if", "(", "fname", ".", "startswith", "(", "\".#\"", ")", "or", "fname", ".", "startswith", "(", "\"__init__.py\"", ")", "or", "fname", ".", "endswith", "(", "\"_flymake.py\"", ")", "or", "fname", ".", "endswith", "(", "\"_flymake.pyc\"", ")", ")", ":", "pass", "elif", "fname", ".", "endswith", "(", "\".py\"", ")", ":", "modname", "=", "fname", "[", ":", "-", "3", "]", "if", "modname", "not", "in", "modnames", ":", "modnames", ".", "append", "(", "modname", ")", "elif", "fname", ".", "endswith", "(", "\".pyc\"", ")", ":", "modname", "=", "fname", "[", ":", "-", "4", "]", "if", "modname", "not", "in", "modnames", ":", "modnames", ".", "append", "(", "modname", ")", "for", "modname", "in", "modnames", ":", "pluginmod", "=", "__import__", "(", "modname", ")", "try", ":", "pluginmod", ".", "pyang_plugin_init", "(", ")", "except", "AttributeError", "as", "s", ":", "print", "(", "pluginmod", ".", "__dict__", ")", "raise", "AttributeError", "(", "pluginmod", ".", "__file__", "+", "': '", "+", "str", "(", "s", ")", ")", "sys", ".", "path", "=", "syspath" ]
Initialize the plugin framework
[ "Initialize", "the", "plugin", "framework" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugin.py#L10-L63
231,219
mbj4668/pyang
pyang/yin_parser.py
YinParser.split_qname
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: return res
python
def split_qname(qname): """Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.""" res = qname.split(YinParser.ns_sep) if len(res) == 1: # no namespace return None, res[0] else: return res
[ "def", "split_qname", "(", "qname", ")", ":", "res", "=", "qname", ".", "split", "(", "YinParser", ".", "ns_sep", ")", "if", "len", "(", "res", ")", "==", "1", ":", "# no namespace", "return", "None", ",", "res", "[", "0", "]", "else", ":", "return", "res" ]
Split `qname` into namespace URI and local name Return namespace and local name as a tuple. This is a static method.
[ "Split", "qname", "into", "namespace", "URI", "and", "local", "name" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/yin_parser.py#L55-L64
231,220
mbj4668/pyang
pyang/yin_parser.py
YinParser.check_attr
def check_attr(self, pos, attrs): """Check for unknown attributes.""" for at in attrs: (ns, local_name) = self.split_qname(at) if ns is None: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', local_name) elif ns == yin_namespace: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', "{"+at)
python
def check_attr(self, pos, attrs): """Check for unknown attributes.""" for at in attrs: (ns, local_name) = self.split_qname(at) if ns is None: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', local_name) elif ns == yin_namespace: error.err_add(self.ctx.errors, pos, 'UNEXPECTED_ATTRIBUTE', "{"+at)
[ "def", "check_attr", "(", "self", ",", "pos", ",", "attrs", ")", ":", "for", "at", "in", "attrs", ":", "(", "ns", ",", "local_name", ")", "=", "self", ".", "split_qname", "(", "at", ")", "if", "ns", "is", "None", ":", "error", ".", "err_add", "(", "self", ".", "ctx", ".", "errors", ",", "pos", ",", "'UNEXPECTED_ATTRIBUTE'", ",", "local_name", ")", "elif", "ns", "==", "yin_namespace", ":", "error", ".", "err_add", "(", "self", ".", "ctx", ".", "errors", ",", "pos", ",", "'UNEXPECTED_ATTRIBUTE'", ",", "\"{\"", "+", "at", ")" ]
Check for unknown attributes.
[ "Check", "for", "unknown", "attributes", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/yin_parser.py#L220-L230
231,221
mbj4668/pyang
pyang/yin_parser.py
YinParser.search_definition
def search_definition(self, module, keyword, arg): """Search for a defintion with `keyword` `name` Search the module and its submodules.""" r = module.search_one(keyword, arg) if r is not None: return r for i in module.search('include'): modulename = i.arg m = self.ctx.search_module(i.pos, modulename) if m is not None: r = m.search_one(keyword, arg) if r is not None: return r return None
python
def search_definition(self, module, keyword, arg): """Search for a defintion with `keyword` `name` Search the module and its submodules.""" r = module.search_one(keyword, arg) if r is not None: return r for i in module.search('include'): modulename = i.arg m = self.ctx.search_module(i.pos, modulename) if m is not None: r = m.search_one(keyword, arg) if r is not None: return r return None
[ "def", "search_definition", "(", "self", ",", "module", ",", "keyword", ",", "arg", ")", ":", "r", "=", "module", ".", "search_one", "(", "keyword", ",", "arg", ")", "if", "r", "is", "not", "None", ":", "return", "r", "for", "i", "in", "module", ".", "search", "(", "'include'", ")", ":", "modulename", "=", "i", ".", "arg", "m", "=", "self", ".", "ctx", ".", "search_module", "(", "i", ".", "pos", ",", "modulename", ")", "if", "m", "is", "not", "None", ":", "r", "=", "m", ".", "search_one", "(", "keyword", ",", "arg", ")", "if", "r", "is", "not", "None", ":", "return", "r", "return", "None" ]
Search for a defintion with `keyword` `name` Search the module and its submodules.
[ "Search", "for", "a", "defintion", "with", "keyword", "name", "Search", "the", "module", "and", "its", "submodules", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/yin_parser.py#L377-L390
231,222
mbj4668/pyang
pyang/translators/yang.py
emit_path_arg
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol): """Heuristically pretty print a path argument""" quote = '"' arg = escape_str(arg) if not(need_new_line(max_line_len, line_len, arg)): fd.write(" " + quote + arg + quote) return False ## FIXME: we should split the path on '/' and '[]' into multiple lines ## and then print each line num_chars = max_line_len - line_len if num_chars <= 0: # really small max_line_len; we give up fd.write(" " + quote + arg + quote) return False while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum(): num_chars -= 1 fd.write(" " + quote + arg[:num_chars] + quote) arg = arg[num_chars:] keyword_cont = ((len(keywordstr) - 1) * ' ') + '+' while arg != '': line_len = len( "%s%s %s%s%s%s" % (indent, keyword_cont, quote, arg, quote, eol)) num_chars = len(arg) - (line_len - max_line_len) while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum(): num_chars -= 1 fd.write('\n' + indent + keyword_cont + " " + quote + arg[:num_chars] + quote) arg = arg[num_chars:]
python
def emit_path_arg(keywordstr, arg, fd, indent, max_line_len, line_len, eol): """Heuristically pretty print a path argument""" quote = '"' arg = escape_str(arg) if not(need_new_line(max_line_len, line_len, arg)): fd.write(" " + quote + arg + quote) return False ## FIXME: we should split the path on '/' and '[]' into multiple lines ## and then print each line num_chars = max_line_len - line_len if num_chars <= 0: # really small max_line_len; we give up fd.write(" " + quote + arg + quote) return False while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum(): num_chars -= 1 fd.write(" " + quote + arg[:num_chars] + quote) arg = arg[num_chars:] keyword_cont = ((len(keywordstr) - 1) * ' ') + '+' while arg != '': line_len = len( "%s%s %s%s%s%s" % (indent, keyword_cont, quote, arg, quote, eol)) num_chars = len(arg) - (line_len - max_line_len) while num_chars > 2 and arg[num_chars - 1:num_chars].isalnum(): num_chars -= 1 fd.write('\n' + indent + keyword_cont + " " + quote + arg[:num_chars] + quote) arg = arg[num_chars:]
[ "def", "emit_path_arg", "(", "keywordstr", ",", "arg", ",", "fd", ",", "indent", ",", "max_line_len", ",", "line_len", ",", "eol", ")", ":", "quote", "=", "'\"'", "arg", "=", "escape_str", "(", "arg", ")", "if", "not", "(", "need_new_line", "(", "max_line_len", ",", "line_len", ",", "arg", ")", ")", ":", "fd", ".", "write", "(", "\" \"", "+", "quote", "+", "arg", "+", "quote", ")", "return", "False", "## FIXME: we should split the path on '/' and '[]' into multiple lines", "## and then print each line", "num_chars", "=", "max_line_len", "-", "line_len", "if", "num_chars", "<=", "0", ":", "# really small max_line_len; we give up", "fd", ".", "write", "(", "\" \"", "+", "quote", "+", "arg", "+", "quote", ")", "return", "False", "while", "num_chars", ">", "2", "and", "arg", "[", "num_chars", "-", "1", ":", "num_chars", "]", ".", "isalnum", "(", ")", ":", "num_chars", "-=", "1", "fd", ".", "write", "(", "\" \"", "+", "quote", "+", "arg", "[", ":", "num_chars", "]", "+", "quote", ")", "arg", "=", "arg", "[", "num_chars", ":", "]", "keyword_cont", "=", "(", "(", "len", "(", "keywordstr", ")", "-", "1", ")", "*", "' '", ")", "+", "'+'", "while", "arg", "!=", "''", ":", "line_len", "=", "len", "(", "\"%s%s %s%s%s%s\"", "%", "(", "indent", ",", "keyword_cont", ",", "quote", ",", "arg", ",", "quote", ",", "eol", ")", ")", "num_chars", "=", "len", "(", "arg", ")", "-", "(", "line_len", "-", "max_line_len", ")", "while", "num_chars", ">", "2", "and", "arg", "[", "num_chars", "-", "1", ":", "num_chars", "]", ".", "isalnum", "(", ")", ":", "num_chars", "-=", "1", "fd", ".", "write", "(", "'\\n'", "+", "indent", "+", "keyword_cont", "+", "\" \"", "+", "quote", "+", "arg", "[", ":", "num_chars", "]", "+", "quote", ")", "arg", "=", "arg", "[", "num_chars", ":", "]" ]
Heuristically pretty print a path argument
[ "Heuristically", "pretty", "print", "a", "path", "argument" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/yang.py#L323-L356
231,223
mbj4668/pyang
pyang/translators/yang.py
emit_arg
def emit_arg(keywordstr, stmt, fd, indent, indentstep, max_line_len, line_len): """Heuristically pretty print the argument string with double quotes""" arg = escape_str(stmt.arg) lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'\n' if (stmt.keyword in _force_newline_arg or need_new_line(max_line_len, line_len, arg)): fd.write('\n' + indent + indentstep + '"' + arg + '"') return True else: fd.write(' "' + arg + '"') return False else: need_nl = False if stmt.keyword in _force_newline_arg: need_nl = True elif len(keywordstr) > 8: # Heuristics: multi-line after a "long" keyword looks better # than after a "short" keyword (compare 'when' and 'error-message') need_nl = True else: for line in lines: if need_new_line(max_line_len, line_len + 1, line): need_nl = True break if need_nl: fd.write('\n' + indent + indentstep) prefix = indent + indentstep else: fd.write(' ') prefix = indent + len(keywordstr) * ' ' + ' ' fd.write('"' + lines[0]) for line in lines[1:-1]: if line[0] == '\n': fd.write('\n') else: fd.write(prefix + ' ' + line) # write last line fd.write(prefix + ' ' + lines[-1]) if lines[-1][-1] == '\n': # last line ends with a newline, indent the ending quote fd.write(prefix + '"') else: fd.write('"') return True
python
def emit_arg(keywordstr, stmt, fd, indent, indentstep, max_line_len, line_len): """Heuristically pretty print the argument string with double quotes""" arg = escape_str(stmt.arg) lines = arg.splitlines(True) if len(lines) <= 1: if len(arg) > 0 and arg[-1] == '\n': arg = arg[:-1] + r'\n' if (stmt.keyword in _force_newline_arg or need_new_line(max_line_len, line_len, arg)): fd.write('\n' + indent + indentstep + '"' + arg + '"') return True else: fd.write(' "' + arg + '"') return False else: need_nl = False if stmt.keyword in _force_newline_arg: need_nl = True elif len(keywordstr) > 8: # Heuristics: multi-line after a "long" keyword looks better # than after a "short" keyword (compare 'when' and 'error-message') need_nl = True else: for line in lines: if need_new_line(max_line_len, line_len + 1, line): need_nl = True break if need_nl: fd.write('\n' + indent + indentstep) prefix = indent + indentstep else: fd.write(' ') prefix = indent + len(keywordstr) * ' ' + ' ' fd.write('"' + lines[0]) for line in lines[1:-1]: if line[0] == '\n': fd.write('\n') else: fd.write(prefix + ' ' + line) # write last line fd.write(prefix + ' ' + lines[-1]) if lines[-1][-1] == '\n': # last line ends with a newline, indent the ending quote fd.write(prefix + '"') else: fd.write('"') return True
[ "def", "emit_arg", "(", "keywordstr", ",", "stmt", ",", "fd", ",", "indent", ",", "indentstep", ",", "max_line_len", ",", "line_len", ")", ":", "arg", "=", "escape_str", "(", "stmt", ".", "arg", ")", "lines", "=", "arg", ".", "splitlines", "(", "True", ")", "if", "len", "(", "lines", ")", "<=", "1", ":", "if", "len", "(", "arg", ")", ">", "0", "and", "arg", "[", "-", "1", "]", "==", "'\\n'", ":", "arg", "=", "arg", "[", ":", "-", "1", "]", "+", "r'\\n'", "if", "(", "stmt", ".", "keyword", "in", "_force_newline_arg", "or", "need_new_line", "(", "max_line_len", ",", "line_len", ",", "arg", ")", ")", ":", "fd", ".", "write", "(", "'\\n'", "+", "indent", "+", "indentstep", "+", "'\"'", "+", "arg", "+", "'\"'", ")", "return", "True", "else", ":", "fd", ".", "write", "(", "' \"'", "+", "arg", "+", "'\"'", ")", "return", "False", "else", ":", "need_nl", "=", "False", "if", "stmt", ".", "keyword", "in", "_force_newline_arg", ":", "need_nl", "=", "True", "elif", "len", "(", "keywordstr", ")", ">", "8", ":", "# Heuristics: multi-line after a \"long\" keyword looks better", "# than after a \"short\" keyword (compare 'when' and 'error-message')", "need_nl", "=", "True", "else", ":", "for", "line", "in", "lines", ":", "if", "need_new_line", "(", "max_line_len", ",", "line_len", "+", "1", ",", "line", ")", ":", "need_nl", "=", "True", "break", "if", "need_nl", ":", "fd", ".", "write", "(", "'\\n'", "+", "indent", "+", "indentstep", ")", "prefix", "=", "indent", "+", "indentstep", "else", ":", "fd", ".", "write", "(", "' '", ")", "prefix", "=", "indent", "+", "len", "(", "keywordstr", ")", "*", "' '", "+", "' '", "fd", ".", "write", "(", "'\"'", "+", "lines", "[", "0", "]", ")", "for", "line", "in", "lines", "[", "1", ":", "-", "1", "]", ":", "if", "line", "[", "0", "]", "==", "'\\n'", ":", "fd", ".", "write", "(", "'\\n'", ")", "else", ":", "fd", ".", "write", "(", "prefix", "+", "' '", "+", "line", ")", "# write last line", "fd", ".", "write", "(", "prefix", "+", "' '", "+", "lines", "[", "-", "1", "]", ")", "if", "lines", "[", "-", "1", "]", "[", "-", "1", "]", "==", "'\\n'", ":", "# last line ends with a newline, indent the ending quote", "fd", ".", "write", "(", "prefix", "+", "'\"'", ")", "else", ":", "fd", ".", "write", "(", "'\"'", ")", "return", "True" ]
Heuristically pretty print the argument string with double quotes
[ "Heuristically", "pretty", "print", "the", "argument", "string", "with", "double", "quotes" ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/translators/yang.py#L358-L404
231,224
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.process_children
def process_children(self, node, elem, module, path, omit=[]): """Proceed with all children of `node`.""" for ch in node.i_children: if ch not in omit and (ch.i_config or self.doctype == "data"): self.node_handler.get(ch.keyword, self.ignore)( ch, elem, module, path)
python
def process_children(self, node, elem, module, path, omit=[]): """Proceed with all children of `node`.""" for ch in node.i_children: if ch not in omit and (ch.i_config or self.doctype == "data"): self.node_handler.get(ch.keyword, self.ignore)( ch, elem, module, path)
[ "def", "process_children", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ",", "omit", "=", "[", "]", ")", ":", "for", "ch", "in", "node", ".", "i_children", ":", "if", "ch", "not", "in", "omit", "and", "(", "ch", ".", "i_config", "or", "self", ".", "doctype", "==", "\"data\"", ")", ":", "self", ".", "node_handler", ".", "get", "(", "ch", ".", "keyword", ",", "self", ".", "ignore", ")", "(", "ch", ",", "elem", ",", "module", ",", "path", ")" ]
Proceed with all children of `node`.
[ "Proceed", "with", "all", "children", "of", "node", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L135-L140
231,225
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.container
def container(self, node, elem, module, path): """Create a sample container element and proceed with its children.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: pres = node.search_one("presence") if pres is not None: nel.append(etree.Comment(" presence: %s " % pres.arg)) self.process_children(node, nel, newm, path)
python
def container(self, node, elem, module, path): """Create a sample container element and proceed with its children.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: pres = node.search_one("presence") if pres is not None: nel.append(etree.Comment(" presence: %s " % pres.arg)) self.process_children(node, nel, newm, path)
[ "def", "container", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ")", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "if", "self", ".", "annots", ":", "pres", "=", "node", ".", "search_one", "(", "\"presence\"", ")", "if", "pres", "is", "not", "None", ":", "nel", ".", "append", "(", "etree", ".", "Comment", "(", "\" presence: %s \"", "%", "pres", ".", "arg", ")", ")", "self", ".", "process_children", "(", "node", ",", "nel", ",", "newm", ",", "path", ")" ]
Create a sample container element and proceed with its children.
[ "Create", "a", "sample", "container", "element", "and", "proceed", "with", "its", "children", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L142-L151
231,226
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.leaf
def leaf(self, node, elem, module, path): """Create a sample leaf element.""" if node.i_default is None: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment( " type: %s " % node.search_one("type").arg)) elif self.defaults: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return nel.text = str(node.i_default_str)
python
def leaf(self, node, elem, module, path): """Create a sample leaf element.""" if node.i_default is None: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment( " type: %s " % node.search_one("type").arg)) elif self.defaults: nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return nel.text = str(node.i_default_str)
[ "def", "leaf", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ")", ":", "if", "node", ".", "i_default", "is", "None", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "if", "self", ".", "annots", ":", "nel", ".", "append", "(", "etree", ".", "Comment", "(", "\" type: %s \"", "%", "node", ".", "search_one", "(", "\"type\"", ")", ".", "arg", ")", ")", "elif", "self", ".", "defaults", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "nel", ".", "text", "=", "str", "(", "node", ".", "i_default_str", ")" ]
Create a sample leaf element.
[ "Create", "a", "sample", "leaf", "element", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L153-L166
231,227
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.anyxml
def anyxml(self, node, elem, module, path): """Create a sample anyxml element.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment(" anyxml "))
python
def anyxml(self, node, elem, module, path): """Create a sample anyxml element.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return if self.annots: nel.append(etree.Comment(" anyxml "))
[ "def", "anyxml", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ")", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "if", "self", ".", "annots", ":", "nel", ".", "append", "(", "etree", ".", "Comment", "(", "\" anyxml \"", ")", ")" ]
Create a sample anyxml element.
[ "Create", "a", "sample", "anyxml", "element", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L168-L174
231,228
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.list
def list(self, node, elem, module, path): """Create sample entries of a list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return for kn in node.i_key: self.node_handler.get(kn.keyword, self.ignore)( kn, nel, newm, path) self.process_children(node, nel, newm, path, node.i_key) minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) if self.annots: self.list_comment(node, nel, minel)
python
def list(self, node, elem, module, path): """Create sample entries of a list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return for kn in node.i_key: self.node_handler.get(kn.keyword, self.ignore)( kn, nel, newm, path) self.process_children(node, nel, newm, path, node.i_key) minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) if self.annots: self.list_comment(node, nel, minel)
[ "def", "list", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ")", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "for", "kn", "in", "node", ".", "i_key", ":", "self", ".", "node_handler", ".", "get", "(", "kn", ".", "keyword", ",", "self", ".", "ignore", ")", "(", "kn", ",", "nel", ",", "newm", ",", "path", ")", "self", ".", "process_children", "(", "node", ",", "nel", ",", "newm", ",", "path", ",", "node", ".", "i_key", ")", "minel", "=", "node", ".", "search_one", "(", "\"min-elements\"", ")", "self", ".", "add_copies", "(", "node", ",", "elem", ",", "nel", ",", "minel", ")", "if", "self", ".", "annots", ":", "self", ".", "list_comment", "(", "node", ",", "nel", ",", "minel", ")" ]
Create sample entries of a list.
[ "Create", "sample", "entries", "of", "a", "list", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L176-L188
231,229
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.leaf_list
def leaf_list(self, node, elem, module, path): """Create sample entries of a leaf-list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) self.list_comment(node, nel, minel)
python
def leaf_list(self, node, elem, module, path): """Create sample entries of a leaf-list.""" nel, newm, path = self.sample_element(node, elem, module, path) if path is None: return minel = node.search_one("min-elements") self.add_copies(node, elem, nel, minel) self.list_comment(node, nel, minel)
[ "def", "leaf_list", "(", "self", ",", "node", ",", "elem", ",", "module", ",", "path", ")", ":", "nel", ",", "newm", ",", "path", "=", "self", ".", "sample_element", "(", "node", ",", "elem", ",", "module", ",", "path", ")", "if", "path", "is", "None", ":", "return", "minel", "=", "node", ".", "search_one", "(", "\"min-elements\"", ")", "self", ".", "add_copies", "(", "node", ",", "elem", ",", "nel", ",", "minel", ")", "self", ".", "list_comment", "(", "node", ",", "nel", ",", "minel", ")" ]
Create sample entries of a leaf-list.
[ "Create", "sample", "entries", "of", "a", "leaf", "-", "list", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L190-L197
231,230
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.sample_element
def sample_element(self, node, parent, module, path): """Create element under `parent`. Declare new namespace if necessary. """ if path is None: return parent, module, None elif path == []: # GO ON pass else: if node.arg == path[0]: path = path[1:] else: return parent, module, None res = etree.SubElement(parent, node.arg) mm = node.main_module() if mm != module: res.attrib["xmlns"] = self.ns_uri[mm] module = mm return res, module, path
python
def sample_element(self, node, parent, module, path): """Create element under `parent`. Declare new namespace if necessary. """ if path is None: return parent, module, None elif path == []: # GO ON pass else: if node.arg == path[0]: path = path[1:] else: return parent, module, None res = etree.SubElement(parent, node.arg) mm = node.main_module() if mm != module: res.attrib["xmlns"] = self.ns_uri[mm] module = mm return res, module, path
[ "def", "sample_element", "(", "self", ",", "node", ",", "parent", ",", "module", ",", "path", ")", ":", "if", "path", "is", "None", ":", "return", "parent", ",", "module", ",", "None", "elif", "path", "==", "[", "]", ":", "# GO ON", "pass", "else", ":", "if", "node", ".", "arg", "==", "path", "[", "0", "]", ":", "path", "=", "path", "[", "1", ":", "]", "else", ":", "return", "parent", ",", "module", ",", "None", "res", "=", "etree", ".", "SubElement", "(", "parent", ",", "node", ".", "arg", ")", "mm", "=", "node", ".", "main_module", "(", ")", "if", "mm", "!=", "module", ":", "res", ".", "attrib", "[", "\"xmlns\"", "]", "=", "self", ".", "ns_uri", "[", "mm", "]", "module", "=", "mm", "return", "res", ",", "module", ",", "path" ]
Create element under `parent`. Declare new namespace if necessary.
[ "Create", "element", "under", "parent", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L199-L220
231,231
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.add_copies
def add_copies(self, node, parent, elem, minel): """Add appropriate number of `elem` copies to `parent`.""" rep = 0 if minel is None else int(minel.arg) - 1 for i in range(rep): parent.append(copy.deepcopy(elem))
python
def add_copies(self, node, parent, elem, minel): """Add appropriate number of `elem` copies to `parent`.""" rep = 0 if minel is None else int(minel.arg) - 1 for i in range(rep): parent.append(copy.deepcopy(elem))
[ "def", "add_copies", "(", "self", ",", "node", ",", "parent", ",", "elem", ",", "minel", ")", ":", "rep", "=", "0", "if", "minel", "is", "None", "else", "int", "(", "minel", ".", "arg", ")", "-", "1", "for", "i", "in", "range", "(", "rep", ")", ":", "parent", ".", "append", "(", "copy", ".", "deepcopy", "(", "elem", ")", ")" ]
Add appropriate number of `elem` copies to `parent`.
[ "Add", "appropriate", "number", "of", "elem", "copies", "to", "parent", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L222-L226
231,232
mbj4668/pyang
pyang/plugins/sample-xml-skeleton.py
SampleXMLSkeletonPlugin.list_comment
def list_comment(self, node, elem, minel): """Add list annotation to `elem`.""" lo = "0" if minel is None else minel.arg maxel = node.search_one("max-elements") hi = "" if maxel is None else maxel.arg elem.insert(0, etree.Comment( " # entries: %s..%s " % (lo, hi))) if node.keyword == 'list': elem.insert(0, etree.Comment( " # keys: " + ",".join([k.arg for k in node.i_key])))
python
def list_comment(self, node, elem, minel): """Add list annotation to `elem`.""" lo = "0" if minel is None else minel.arg maxel = node.search_one("max-elements") hi = "" if maxel is None else maxel.arg elem.insert(0, etree.Comment( " # entries: %s..%s " % (lo, hi))) if node.keyword == 'list': elem.insert(0, etree.Comment( " # keys: " + ",".join([k.arg for k in node.i_key])))
[ "def", "list_comment", "(", "self", ",", "node", ",", "elem", ",", "minel", ")", ":", "lo", "=", "\"0\"", "if", "minel", "is", "None", "else", "minel", ".", "arg", "maxel", "=", "node", ".", "search_one", "(", "\"max-elements\"", ")", "hi", "=", "\"\"", "if", "maxel", "is", "None", "else", "maxel", ".", "arg", "elem", ".", "insert", "(", "0", ",", "etree", ".", "Comment", "(", "\" # entries: %s..%s \"", "%", "(", "lo", ",", "hi", ")", ")", ")", "if", "node", ".", "keyword", "==", "'list'", ":", "elem", ".", "insert", "(", "0", ",", "etree", ".", "Comment", "(", "\" # keys: \"", "+", "\",\"", ".", "join", "(", "[", "k", ".", "arg", "for", "k", "in", "node", ".", "i_key", "]", ")", ")", ")" ]
Add list annotation to `elem`.
[ "Add", "list", "annotation", "to", "elem", "." ]
f2a5cc3142162e5b9ee4e18d154568d939ff63dd
https://github.com/mbj4668/pyang/blob/f2a5cc3142162e5b9ee4e18d154568d939ff63dd/pyang/plugins/sample-xml-skeleton.py#L228-L237
231,233
quantmind/pulsar
pulsar/utils/slugify.py
slugify
def slugify(value, separator='-', max_length=0, word_boundary=False, entities=True, decimal=True, hexadecimal=True): '''Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character ''' value = normalize('NFKD', to_string(value, 'utf-8', 'ignore')) if unidecode: value = unidecode(value) # character entity reference if entities: value = CHAR_ENTITY_REXP.sub( lambda m: chr(name2codepoint[m.group(1)]), value) # decimal character reference if decimal: try: value = DECIMAL_REXP.sub(lambda m: chr(int(m.group(1))), value) except Exception: pass # hexadecimal character reference if hexadecimal: try: value = HEX_REXP.sub(lambda m: chr(int(m.group(1), 16)), value) except Exception: pass value = value.lower() value = REPLACE1_REXP.sub('', value) value = REPLACE2_REXP.sub('-', value) # remove redundant - value = REMOVE_REXP.sub('-', value).strip('-') # smart truncate if requested if max_length > 0: value = smart_truncate(value, max_length, word_boundary, '-') if separator != '-': value = value.replace('-', separator) return value
python
def slugify(value, separator='-', max_length=0, word_boundary=False, entities=True, decimal=True, hexadecimal=True): '''Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character ''' value = normalize('NFKD', to_string(value, 'utf-8', 'ignore')) if unidecode: value = unidecode(value) # character entity reference if entities: value = CHAR_ENTITY_REXP.sub( lambda m: chr(name2codepoint[m.group(1)]), value) # decimal character reference if decimal: try: value = DECIMAL_REXP.sub(lambda m: chr(int(m.group(1))), value) except Exception: pass # hexadecimal character reference if hexadecimal: try: value = HEX_REXP.sub(lambda m: chr(int(m.group(1), 16)), value) except Exception: pass value = value.lower() value = REPLACE1_REXP.sub('', value) value = REPLACE2_REXP.sub('-', value) # remove redundant - value = REMOVE_REXP.sub('-', value).strip('-') # smart truncate if requested if max_length > 0: value = smart_truncate(value, max_length, word_boundary, '-') if separator != '-': value = value.replace('-', separator) return value
[ "def", "slugify", "(", "value", ",", "separator", "=", "'-'", ",", "max_length", "=", "0", ",", "word_boundary", "=", "False", ",", "entities", "=", "True", ",", "decimal", "=", "True", ",", "hexadecimal", "=", "True", ")", ":", "value", "=", "normalize", "(", "'NFKD'", ",", "to_string", "(", "value", ",", "'utf-8'", ",", "'ignore'", ")", ")", "if", "unidecode", ":", "value", "=", "unidecode", "(", "value", ")", "# character entity reference", "if", "entities", ":", "value", "=", "CHAR_ENTITY_REXP", ".", "sub", "(", "lambda", "m", ":", "chr", "(", "name2codepoint", "[", "m", ".", "group", "(", "1", ")", "]", ")", ",", "value", ")", "# decimal character reference", "if", "decimal", ":", "try", ":", "value", "=", "DECIMAL_REXP", ".", "sub", "(", "lambda", "m", ":", "chr", "(", "int", "(", "m", ".", "group", "(", "1", ")", ")", ")", ",", "value", ")", "except", "Exception", ":", "pass", "# hexadecimal character reference", "if", "hexadecimal", ":", "try", ":", "value", "=", "HEX_REXP", ".", "sub", "(", "lambda", "m", ":", "chr", "(", "int", "(", "m", ".", "group", "(", "1", ")", ",", "16", ")", ")", ",", "value", ")", "except", "Exception", ":", "pass", "value", "=", "value", ".", "lower", "(", ")", "value", "=", "REPLACE1_REXP", ".", "sub", "(", "''", ",", "value", ")", "value", "=", "REPLACE2_REXP", ".", "sub", "(", "'-'", ",", "value", ")", "# remove redundant -", "value", "=", "REMOVE_REXP", ".", "sub", "(", "'-'", ",", "value", ")", ".", "strip", "(", "'-'", ")", "# smart truncate if requested", "if", "max_length", ">", "0", ":", "value", "=", "smart_truncate", "(", "value", ",", "max_length", ",", "word_boundary", ",", "'-'", ")", "if", "separator", "!=", "'-'", ":", "value", "=", "value", ".", "replace", "(", "'-'", ",", "separator", ")", "return", "value" ]
Normalizes string, removes non-alpha characters, and converts spaces to ``separator`` character
[ "Normalizes", "string", "removes", "non", "-", "alpha", "characters", "and", "converts", "spaces", "to", "separator", "character" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/slugify.py#L32-L75
231,234
quantmind/pulsar
pulsar/utils/slugify.py
smart_truncate
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separator) if separator not in value: return value[:max_length] truncated = '' for word in value.split(separator): if word: next_len = len(truncated) + len(word) + len(separator) if next_len <= max_length: truncated += '{0}{1}'.format(word, separator) if not truncated: truncated = value[:max_length] return truncated.strip(separator)
python
def smart_truncate(value, max_length=0, word_boundaries=False, separator=' '): """ Truncate a string """ value = value.strip(separator) if not max_length: return value if len(value) < max_length: return value if not word_boundaries: return value[:max_length].strip(separator) if separator not in value: return value[:max_length] truncated = '' for word in value.split(separator): if word: next_len = len(truncated) + len(word) + len(separator) if next_len <= max_length: truncated += '{0}{1}'.format(word, separator) if not truncated: truncated = value[:max_length] return truncated.strip(separator)
[ "def", "smart_truncate", "(", "value", ",", "max_length", "=", "0", ",", "word_boundaries", "=", "False", ",", "separator", "=", "' '", ")", ":", "value", "=", "value", ".", "strip", "(", "separator", ")", "if", "not", "max_length", ":", "return", "value", "if", "len", "(", "value", ")", "<", "max_length", ":", "return", "value", "if", "not", "word_boundaries", ":", "return", "value", "[", ":", "max_length", "]", ".", "strip", "(", "separator", ")", "if", "separator", "not", "in", "value", ":", "return", "value", "[", ":", "max_length", "]", "truncated", "=", "''", "for", "word", "in", "value", ".", "split", "(", "separator", ")", ":", "if", "word", ":", "next_len", "=", "len", "(", "truncated", ")", "+", "len", "(", "word", ")", "+", "len", "(", "separator", ")", "if", "next_len", "<=", "max_length", ":", "truncated", "+=", "'{0}{1}'", ".", "format", "(", "word", ",", "separator", ")", "if", "not", "truncated", ":", "truncated", "=", "value", "[", ":", "max_length", "]", "return", "truncated", ".", "strip", "(", "separator", ")" ]
Truncate a string
[ "Truncate", "a", "string" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/slugify.py#L78-L103
231,235
quantmind/pulsar
pulsar/utils/pylib/redisparser.py
RedisParser.get
def get(self): '''Called by the protocol consumer''' if self._current: return self._resume(self._current, False) else: return self._get(None)
python
def get(self): '''Called by the protocol consumer''' if self._current: return self._resume(self._current, False) else: return self._get(None)
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "_current", ":", "return", "self", ".", "_resume", "(", "self", ".", "_current", ",", "False", ")", "else", ":", "return", "self", ".", "_get", "(", "None", ")" ]
Called by the protocol consumer
[ "Called", "by", "the", "protocol", "consumer" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/redisparser.py#L86-L91
231,236
quantmind/pulsar
pulsar/utils/pylib/redisparser.py
RedisParser.pack_pipeline
def pack_pipeline(self, commands): '''Packs pipeline commands into bytes.''' return b''.join( starmap(lambda *args: b''.join(self._pack_command(args)), (a for a, _ in commands)))
python
def pack_pipeline(self, commands): '''Packs pipeline commands into bytes.''' return b''.join( starmap(lambda *args: b''.join(self._pack_command(args)), (a for a, _ in commands)))
[ "def", "pack_pipeline", "(", "self", ",", "commands", ")", ":", "return", "b''", ".", "join", "(", "starmap", "(", "lambda", "*", "args", ":", "b''", ".", "join", "(", "self", ".", "_pack_command", "(", "args", ")", ")", ",", "(", "a", "for", "a", ",", "_", "in", "commands", ")", ")", ")" ]
Packs pipeline commands into bytes.
[ "Packs", "pipeline", "commands", "into", "bytes", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/redisparser.py#L114-L118
231,237
quantmind/pulsar
pulsar/cmds/pypi_version.py
PyPi.pypi_release
def pypi_release(self): """Get the latest pypi release """ meta = self.distribution.metadata pypi = ServerProxy(self.pypi_index_url) releases = pypi.package_releases(meta.name) if releases: return next(iter(sorted(releases, reverse=True)))
python
def pypi_release(self): """Get the latest pypi release """ meta = self.distribution.metadata pypi = ServerProxy(self.pypi_index_url) releases = pypi.package_releases(meta.name) if releases: return next(iter(sorted(releases, reverse=True)))
[ "def", "pypi_release", "(", "self", ")", ":", "meta", "=", "self", ".", "distribution", ".", "metadata", "pypi", "=", "ServerProxy", "(", "self", ".", "pypi_index_url", ")", "releases", "=", "pypi", ".", "package_releases", "(", "meta", ".", "name", ")", "if", "releases", ":", "return", "next", "(", "iter", "(", "sorted", "(", "releases", ",", "reverse", "=", "True", ")", ")", ")" ]
Get the latest pypi release
[ "Get", "the", "latest", "pypi", "release" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/cmds/pypi_version.py#L48-L55
231,238
quantmind/pulsar
pulsar/async/access.py
is_mainthread
def is_mainthread(thread=None): '''Check if thread is the main thread. If ``thread`` is not supplied check the current thread ''' thread = thread if thread is not None else current_thread() return isinstance(thread, threading._MainThread)
python
def is_mainthread(thread=None): '''Check if thread is the main thread. If ``thread`` is not supplied check the current thread ''' thread = thread if thread is not None else current_thread() return isinstance(thread, threading._MainThread)
[ "def", "is_mainthread", "(", "thread", "=", "None", ")", ":", "thread", "=", "thread", "if", "thread", "is", "not", "None", "else", "current_thread", "(", ")", "return", "isinstance", "(", "thread", ",", "threading", ".", "_MainThread", ")" ]
Check if thread is the main thread. If ``thread`` is not supplied check the current thread
[ "Check", "if", "thread", "is", "the", "main", "thread", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/access.py#L113-L119
231,239
quantmind/pulsar
pulsar/async/access.py
process_data
def process_data(name=None): '''Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary ''' ct = current_process() if not hasattr(ct, '_pulsar_local'): ct._pulsar_local = {} loc = ct._pulsar_local return loc.get(name) if name else loc
python
def process_data(name=None): '''Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary ''' ct = current_process() if not hasattr(ct, '_pulsar_local'): ct._pulsar_local = {} loc = ct._pulsar_local return loc.get(name) if name else loc
[ "def", "process_data", "(", "name", "=", "None", ")", ":", "ct", "=", "current_process", "(", ")", "if", "not", "hasattr", "(", "ct", ",", "'_pulsar_local'", ")", ":", "ct", ".", "_pulsar_local", "=", "{", "}", "loc", "=", "ct", ".", "_pulsar_local", "return", "loc", ".", "get", "(", "name", ")", "if", "name", "else", "loc" ]
Fetch the current process local data dictionary. If ``name`` is not ``None`` it returns the value at``name``, otherwise it return the process data dictionary
[ "Fetch", "the", "current", "process", "local", "data", "dictionary", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/access.py#L126-L136
231,240
quantmind/pulsar
pulsar/async/access.py
thread_data
def thread_data(name, value=NOTHING, ct=None): '''Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value. ''' ct = ct or current_thread() if is_mainthread(ct): loc = process_data() elif not hasattr(ct, '_pulsar_local'): ct._pulsar_local = loc = {} else: loc = ct._pulsar_local if value is not NOTHING: if name in loc: if loc[name] is not value: raise RuntimeError( '%s is already available on this thread' % name) else: loc[name] = value return loc.get(name)
python
def thread_data(name, value=NOTHING, ct=None): '''Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value. ''' ct = ct or current_thread() if is_mainthread(ct): loc = process_data() elif not hasattr(ct, '_pulsar_local'): ct._pulsar_local = loc = {} else: loc = ct._pulsar_local if value is not NOTHING: if name in loc: if loc[name] is not value: raise RuntimeError( '%s is already available on this thread' % name) else: loc[name] = value return loc.get(name)
[ "def", "thread_data", "(", "name", ",", "value", "=", "NOTHING", ",", "ct", "=", "None", ")", ":", "ct", "=", "ct", "or", "current_thread", "(", ")", "if", "is_mainthread", "(", "ct", ")", ":", "loc", "=", "process_data", "(", ")", "elif", "not", "hasattr", "(", "ct", ",", "'_pulsar_local'", ")", ":", "ct", ".", "_pulsar_local", "=", "loc", "=", "{", "}", "else", ":", "loc", "=", "ct", ".", "_pulsar_local", "if", "value", "is", "not", "NOTHING", ":", "if", "name", "in", "loc", ":", "if", "loc", "[", "name", "]", "is", "not", "value", ":", "raise", "RuntimeError", "(", "'%s is already available on this thread'", "%", "name", ")", "else", ":", "loc", "[", "name", "]", "=", "value", "return", "loc", ".", "get", "(", "name", ")" ]
Set or retrieve an attribute ``name`` from thread ``ct``. If ``ct`` is not given used the current thread. If ``value`` is None, it will get the value otherwise it will set the value.
[ "Set", "or", "retrieve", "an", "attribute", "name", "from", "thread", "ct", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/access.py#L139-L159
231,241
quantmind/pulsar
pulsar/utils/internet.py
parse_address
def parse_address(netloc, default_port=8000): '''Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.''' if isinstance(netloc, tuple): if len(netloc) != 2: raise ValueError('Invalid address %s' % str(netloc)) return netloc # netloc = native_str(netloc) auth = None # Check if auth is available if '@' in netloc: auth, netloc = netloc.split('@') if netloc.startswith("unix:"): host = netloc.split("unix:")[1] return '%s@%s' % (auth, host) if auth else host # get host if '[' in netloc and ']' in netloc: host = netloc.split(']')[0][1:].lower() elif ':' in netloc: host = netloc.split(':')[0].lower() elif netloc == "": host = "0.0.0.0" else: host = netloc.lower() # get port netloc = netloc.split(']')[-1] if ":" in netloc: port = netloc.split(':', 1)[1] if not port.isdigit(): raise ValueError("%r is not a valid port number." % port) port = int(port) else: port = default_port return ('%s@%s' % (auth, host) if auth else host, port)
python
def parse_address(netloc, default_port=8000): '''Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.''' if isinstance(netloc, tuple): if len(netloc) != 2: raise ValueError('Invalid address %s' % str(netloc)) return netloc # netloc = native_str(netloc) auth = None # Check if auth is available if '@' in netloc: auth, netloc = netloc.split('@') if netloc.startswith("unix:"): host = netloc.split("unix:")[1] return '%s@%s' % (auth, host) if auth else host # get host if '[' in netloc and ']' in netloc: host = netloc.split(']')[0][1:].lower() elif ':' in netloc: host = netloc.split(':')[0].lower() elif netloc == "": host = "0.0.0.0" else: host = netloc.lower() # get port netloc = netloc.split(']')[-1] if ":" in netloc: port = netloc.split(':', 1)[1] if not port.isdigit(): raise ValueError("%r is not a valid port number." % port) port = int(port) else: port = default_port return ('%s@%s' % (auth, host) if auth else host, port)
[ "def", "parse_address", "(", "netloc", ",", "default_port", "=", "8000", ")", ":", "if", "isinstance", "(", "netloc", ",", "tuple", ")", ":", "if", "len", "(", "netloc", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Invalid address %s'", "%", "str", "(", "netloc", ")", ")", "return", "netloc", "#", "netloc", "=", "native_str", "(", "netloc", ")", "auth", "=", "None", "# Check if auth is available", "if", "'@'", "in", "netloc", ":", "auth", ",", "netloc", "=", "netloc", ".", "split", "(", "'@'", ")", "if", "netloc", ".", "startswith", "(", "\"unix:\"", ")", ":", "host", "=", "netloc", ".", "split", "(", "\"unix:\"", ")", "[", "1", "]", "return", "'%s@%s'", "%", "(", "auth", ",", "host", ")", "if", "auth", "else", "host", "# get host", "if", "'['", "in", "netloc", "and", "']'", "in", "netloc", ":", "host", "=", "netloc", ".", "split", "(", "']'", ")", "[", "0", "]", "[", "1", ":", "]", ".", "lower", "(", ")", "elif", "':'", "in", "netloc", ":", "host", "=", "netloc", ".", "split", "(", "':'", ")", "[", "0", "]", ".", "lower", "(", ")", "elif", "netloc", "==", "\"\"", ":", "host", "=", "\"0.0.0.0\"", "else", ":", "host", "=", "netloc", ".", "lower", "(", ")", "# get port", "netloc", "=", "netloc", ".", "split", "(", "']'", ")", "[", "-", "1", "]", "if", "\":\"", "in", "netloc", ":", "port", "=", "netloc", ".", "split", "(", "':'", ",", "1", ")", "[", "1", "]", "if", "not", "port", ".", "isdigit", "(", ")", ":", "raise", "ValueError", "(", "\"%r is not a valid port number.\"", "%", "port", ")", "port", "=", "int", "(", "port", ")", "else", ":", "port", "=", "default_port", "return", "(", "'%s@%s'", "%", "(", "auth", ",", "host", ")", "if", "auth", "else", "host", ",", "port", ")" ]
Parse an internet address ``netloc`` and return a tuple with ``host`` and ``port``.
[ "Parse", "an", "internet", "address", "netloc", "and", "return", "a", "tuple", "with", "host", "and", "port", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/internet.py#L17-L51
231,242
quantmind/pulsar
pulsar/utils/internet.py
is_socket_closed
def is_socket_closed(sock): # pragma nocover """Check if socket ``sock`` is closed.""" if not sock: return True try: if not poll: # pragma nocover if not select: return False try: return bool(select([sock], [], [], 0.0)[0]) except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True except Exception: return True
python
def is_socket_closed(sock): # pragma nocover """Check if socket ``sock`` is closed.""" if not sock: return True try: if not poll: # pragma nocover if not select: return False try: return bool(select([sock], [], [], 0.0)[0]) except socket.error: return True # This version is better on platforms that support it. p = poll() p.register(sock, POLLIN) for (fno, ev) in p.poll(0.0): if fno == sock.fileno(): # Either data is buffered (bad), or the connection is dropped. return True except Exception: return True
[ "def", "is_socket_closed", "(", "sock", ")", ":", "# pragma nocover", "if", "not", "sock", ":", "return", "True", "try", ":", "if", "not", "poll", ":", "# pragma nocover", "if", "not", "select", ":", "return", "False", "try", ":", "return", "bool", "(", "select", "(", "[", "sock", "]", ",", "[", "]", ",", "[", "]", ",", "0.0", ")", "[", "0", "]", ")", "except", "socket", ".", "error", ":", "return", "True", "# This version is better on platforms that support it.", "p", "=", "poll", "(", ")", "p", ".", "register", "(", "sock", ",", "POLLIN", ")", "for", "(", "fno", ",", "ev", ")", "in", "p", ".", "poll", "(", "0.0", ")", ":", "if", "fno", "==", "sock", ".", "fileno", "(", ")", ":", "# Either data is buffered (bad), or the connection is dropped.", "return", "True", "except", "Exception", ":", "return", "True" ]
Check if socket ``sock`` is closed.
[ "Check", "if", "socket", "sock", "is", "closed", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/internet.py#L101-L121
231,243
quantmind/pulsar
pulsar/utils/internet.py
close_socket
def close_socket(sock): '''Shutdown and close the socket.''' if sock: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass try: sock.close() except Exception: pass
python
def close_socket(sock): '''Shutdown and close the socket.''' if sock: try: sock.shutdown(socket.SHUT_RDWR) except Exception: pass try: sock.close() except Exception: pass
[ "def", "close_socket", "(", "sock", ")", ":", "if", "sock", ":", "try", ":", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", "Exception", ":", "pass", "try", ":", "sock", ".", "close", "(", ")", "except", "Exception", ":", "pass" ]
Shutdown and close the socket.
[ "Shutdown", "and", "close", "the", "socket", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/internet.py#L124-L134
231,244
quantmind/pulsar
pulsar/apps/rpc/mixins.py
PulsarServerCommands.rpc_server_info
async def rpc_server_info(self, request): '''Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information. ''' info = await send('arbiter', 'info') info = self.extra_server_info(request, info) try: info = await info except TypeError: pass return info
python
async def rpc_server_info(self, request): '''Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information. ''' info = await send('arbiter', 'info') info = self.extra_server_info(request, info) try: info = await info except TypeError: pass return info
[ "async", "def", "rpc_server_info", "(", "self", ",", "request", ")", ":", "info", "=", "await", "send", "(", "'arbiter'", ",", "'info'", ")", "info", "=", "self", ".", "extra_server_info", "(", "request", ",", "info", ")", "try", ":", "info", "=", "await", "info", "except", "TypeError", ":", "pass", "return", "info" ]
Return a dictionary of information regarding the server and workers. It invokes the :meth:`extra_server_info` for adding custom information.
[ "Return", "a", "dictionary", "of", "information", "regarding", "the", "server", "and", "workers", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/mixins.py#L18-L30
231,245
quantmind/pulsar
pulsar/utils/pylib/events.py
Event.bind
def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, cannot add callbacks' % self) if handlers is None: handlers = [] self._handlers = handlers handlers.append(callback)
python
def bind(self, callback): """Bind a ``callback`` to this event. """ handlers = self._handlers if self._self is None: raise RuntimeError('%s already fired, cannot add callbacks' % self) if handlers is None: handlers = [] self._handlers = handlers handlers.append(callback)
[ "def", "bind", "(", "self", ",", "callback", ")", ":", "handlers", "=", "self", ".", "_handlers", "if", "self", ".", "_self", "is", "None", ":", "raise", "RuntimeError", "(", "'%s already fired, cannot add callbacks'", "%", "self", ")", "if", "handlers", "is", "None", ":", "handlers", "=", "[", "]", "self", ".", "_handlers", "=", "handlers", "handlers", ".", "append", "(", "callback", ")" ]
Bind a ``callback`` to this event.
[ "Bind", "a", "callback", "to", "this", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L41-L50
231,246
quantmind/pulsar
pulsar/utils/pylib/events.py
Event.unbind
def unbind(self, callback): """Remove a callback from the list """ handlers = self._handlers if handlers: filtered_callbacks = [f for f in handlers if f != callback] removed_count = len(handlers) - len(filtered_callbacks) if removed_count: self._handlers = filtered_callbacks return removed_count return 0
python
def unbind(self, callback): """Remove a callback from the list """ handlers = self._handlers if handlers: filtered_callbacks = [f for f in handlers if f != callback] removed_count = len(handlers) - len(filtered_callbacks) if removed_count: self._handlers = filtered_callbacks return removed_count return 0
[ "def", "unbind", "(", "self", ",", "callback", ")", ":", "handlers", "=", "self", ".", "_handlers", "if", "handlers", ":", "filtered_callbacks", "=", "[", "f", "for", "f", "in", "handlers", "if", "f", "!=", "callback", "]", "removed_count", "=", "len", "(", "handlers", ")", "-", "len", "(", "filtered_callbacks", ")", "if", "removed_count", ":", "self", ".", "_handlers", "=", "filtered_callbacks", "return", "removed_count", "return", "0" ]
Remove a callback from the list
[ "Remove", "a", "callback", "from", "the", "list" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L56-L66
231,247
quantmind/pulsar
pulsar/utils/pylib/events.py
Event.fire
def fire(self, exc=None, data=None): """Fire the event :param exc: fire the event with an exception :param data: fire an event with data """ o = self._self if o is not None: handlers = self._handlers if self._onetime: self._handlers = None self._self = None if handlers: if exc is not None: for hnd in handlers: hnd(o, exc=exc) elif data is not None: for hnd in handlers: hnd(o, data=data) else: for hnd in handlers: hnd(o) if self._waiter: if exc: self._waiter.set_exception(exc) else: self._waiter.set_result(data if data is not None else o) self._waiter = None
python
def fire(self, exc=None, data=None): """Fire the event :param exc: fire the event with an exception :param data: fire an event with data """ o = self._self if o is not None: handlers = self._handlers if self._onetime: self._handlers = None self._self = None if handlers: if exc is not None: for hnd in handlers: hnd(o, exc=exc) elif data is not None: for hnd in handlers: hnd(o, data=data) else: for hnd in handlers: hnd(o) if self._waiter: if exc: self._waiter.set_exception(exc) else: self._waiter.set_result(data if data is not None else o) self._waiter = None
[ "def", "fire", "(", "self", ",", "exc", "=", "None", ",", "data", "=", "None", ")", ":", "o", "=", "self", ".", "_self", "if", "o", "is", "not", "None", ":", "handlers", "=", "self", ".", "_handlers", "if", "self", ".", "_onetime", ":", "self", ".", "_handlers", "=", "None", "self", ".", "_self", "=", "None", "if", "handlers", ":", "if", "exc", "is", "not", "None", ":", "for", "hnd", "in", "handlers", ":", "hnd", "(", "o", ",", "exc", "=", "exc", ")", "elif", "data", "is", "not", "None", ":", "for", "hnd", "in", "handlers", ":", "hnd", "(", "o", ",", "data", "=", "data", ")", "else", ":", "for", "hnd", "in", "handlers", ":", "hnd", "(", "o", ")", "if", "self", ".", "_waiter", ":", "if", "exc", ":", "self", ".", "_waiter", ".", "set_exception", "(", "exc", ")", "else", ":", "self", ".", "_waiter", ".", "set_result", "(", "data", "if", "data", "is", "not", "None", "else", "o", ")", "self", ".", "_waiter", "=", "None" ]
Fire the event :param exc: fire the event with an exception :param data: fire an event with data
[ "Fire", "the", "event" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L68-L98
231,248
quantmind/pulsar
pulsar/utils/pylib/events.py
EventHandler.fire_event
def fire_event(self, name, exc=None, data=None): """Fire event at ``name`` if it is registered """ if self._events and name in self._events: self._events[name].fire(exc=exc, data=data)
python
def fire_event(self, name, exc=None, data=None): """Fire event at ``name`` if it is registered """ if self._events and name in self._events: self._events[name].fire(exc=exc, data=data)
[ "def", "fire_event", "(", "self", ",", "name", ",", "exc", "=", "None", ",", "data", "=", "None", ")", ":", "if", "self", ".", "_events", "and", "name", "in", "self", ".", "_events", ":", "self", ".", "_events", "[", "name", "]", ".", "fire", "(", "exc", "=", "exc", ",", "data", "=", "data", ")" ]
Fire event at ``name`` if it is registered
[ "Fire", "event", "at", "name", "if", "it", "is", "registered" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L141-L145
231,249
quantmind/pulsar
pulsar/utils/pylib/events.py
EventHandler.bind_events
def bind_events(self, events): '''Register all known events found in ``events`` key-valued parameters. ''' evs = self._events if evs and events: for event in evs.values(): if event.name in events: event.bind(events[event.name])
python
def bind_events(self, events): '''Register all known events found in ``events`` key-valued parameters. ''' evs = self._events if evs and events: for event in evs.values(): if event.name in events: event.bind(events[event.name])
[ "def", "bind_events", "(", "self", ",", "events", ")", ":", "evs", "=", "self", ".", "_events", "if", "evs", "and", "events", ":", "for", "event", "in", "evs", ".", "values", "(", ")", ":", "if", "event", ".", "name", "in", "events", ":", "event", ".", "bind", "(", "events", "[", "event", ".", "name", "]", ")" ]
Register all known events found in ``events`` key-valued parameters.
[ "Register", "all", "known", "events", "found", "in", "events", "key", "-", "valued", "parameters", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/events.py#L147-L154
231,250
quantmind/pulsar
pulsar/utils/autoreload.py
_get_args_for_reloading
def _get_args_for_reloading(): """Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. """ rv = [sys.executable] py_script = sys.argv[0] if os.name == 'nt' and not os.path.exists(py_script) and \ os.path.exists(py_script + '.exe'): py_script += '.exe' rv.append(py_script) rv.extend(sys.argv[1:]) return rv
python
def _get_args_for_reloading(): """Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading. """ rv = [sys.executable] py_script = sys.argv[0] if os.name == 'nt' and not os.path.exists(py_script) and \ os.path.exists(py_script + '.exe'): py_script += '.exe' rv.append(py_script) rv.extend(sys.argv[1:]) return rv
[ "def", "_get_args_for_reloading", "(", ")", ":", "rv", "=", "[", "sys", ".", "executable", "]", "py_script", "=", "sys", ".", "argv", "[", "0", "]", "if", "os", ".", "name", "==", "'nt'", "and", "not", "os", ".", "path", ".", "exists", "(", "py_script", ")", "and", "os", ".", "path", ".", "exists", "(", "py_script", "+", "'.exe'", ")", ":", "py_script", "+=", "'.exe'", "rv", ".", "append", "(", "py_script", ")", "rv", ".", "extend", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "return", "rv" ]
Returns the executable. This contains a workaround for windows if the executable is incorrectly reported to not have the .exe extension which can cause bugs on reloading.
[ "Returns", "the", "executable", ".", "This", "contains", "a", "workaround", "for", "windows", "if", "the", "executable", "is", "incorrectly", "reported", "to", "not", "have", "the", ".", "exe", "extension", "which", "can", "cause", "bugs", "on", "reloading", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/autoreload.py#L103-L115
231,251
quantmind/pulsar
pulsar/utils/autoreload.py
Reloader.restart_with_reloader
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one """ while True: LOGGER.info('Restarting with %s reloader' % self.name) args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ[PULSAR_RUN_MAIN] = 'true' exit_code = subprocess.call(args, env=new_environ, close_fds=False) if exit_code != EXIT_CODE: return exit_code
python
def restart_with_reloader(self): """Spawn a new Python interpreter with the same arguments as this one """ while True: LOGGER.info('Restarting with %s reloader' % self.name) args = _get_args_for_reloading() new_environ = os.environ.copy() new_environ[PULSAR_RUN_MAIN] = 'true' exit_code = subprocess.call(args, env=new_environ, close_fds=False) if exit_code != EXIT_CODE: return exit_code
[ "def", "restart_with_reloader", "(", "self", ")", ":", "while", "True", ":", "LOGGER", ".", "info", "(", "'Restarting with %s reloader'", "%", "self", ".", "name", ")", "args", "=", "_get_args_for_reloading", "(", ")", "new_environ", "=", "os", ".", "environ", ".", "copy", "(", ")", "new_environ", "[", "PULSAR_RUN_MAIN", "]", "=", "'true'", "exit_code", "=", "subprocess", ".", "call", "(", "args", ",", "env", "=", "new_environ", ",", "close_fds", "=", "False", ")", "if", "exit_code", "!=", "EXIT_CODE", ":", "return", "exit_code" ]
Spawn a new Python interpreter with the same arguments as this one
[ "Spawn", "a", "new", "Python", "interpreter", "with", "the", "same", "arguments", "as", "this", "one" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/autoreload.py#L35-L45
231,252
quantmind/pulsar
pulsar/async/threads.py
Thread.kill
def kill(self, sig): '''Invoke the stop on the event loop method.''' if self.is_alive() and self._loop: self._loop.call_soon_threadsafe(self._loop.stop)
python
def kill(self, sig): '''Invoke the stop on the event loop method.''' if self.is_alive() and self._loop: self._loop.call_soon_threadsafe(self._loop.stop)
[ "def", "kill", "(", "self", ",", "sig", ")", ":", "if", "self", ".", "is_alive", "(", ")", "and", "self", ".", "_loop", ":", "self", ".", "_loop", ".", "call_soon_threadsafe", "(", "self", ".", "_loop", ".", "stop", ")" ]
Invoke the stop on the event loop method.
[ "Invoke", "the", "stop", "on", "the", "event", "loop", "method", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/threads.py#L12-L15
231,253
quantmind/pulsar
pulsar/apps/http/auth.py
HTTPDigestAuth.encode
def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = self.options qop = o.get('qop') realm = o.get('realm') nonce = o.get('nonce') entdig = None p_parsed = urlparse(uri) path = p_parsed.path if p_parsed.query: path += '?' + p_parsed.query ha1 = self.ha1(realm, self.password) ha2 = self.ha2(qop, method, path) if qop == 'auth': if nonce == self.last_nonce: self.nonce_count += 1 else: self.nonce_count = 1 ncvalue = '%08x' % self.nonce_count s = str(self.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = sha1(s).hexdigest()[:16] noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, ha2) respdig = self.KD(ha1, noncebit) elif qop is None: respdig = self.KD(ha1, "%s:%s" % (nonce, ha2)) else: # XXX handle auth-int. return base = ('username="%s", realm="%s", nonce="%s", uri="%s", ' 'response="%s"' % (self.username, realm, nonce, path, respdig)) opaque = o.get('opaque') if opaque: base += ', opaque="%s"' % opaque if entdig: base += ', digest="%s"' % entdig base += ', algorithm="%s"' % self.algorithm if qop: base += ', qop=%s, nc=%s, cnonce="%s"' % (qop, ncvalue, cnonce) return 'Digest %s' % base
python
def encode(self, method, uri): '''Called by the client to encode Authentication header.''' if not self.username or not self.password: return o = self.options qop = o.get('qop') realm = o.get('realm') nonce = o.get('nonce') entdig = None p_parsed = urlparse(uri) path = p_parsed.path if p_parsed.query: path += '?' + p_parsed.query ha1 = self.ha1(realm, self.password) ha2 = self.ha2(qop, method, path) if qop == 'auth': if nonce == self.last_nonce: self.nonce_count += 1 else: self.nonce_count = 1 ncvalue = '%08x' % self.nonce_count s = str(self.nonce_count).encode('utf-8') s += nonce.encode('utf-8') s += time.ctime().encode('utf-8') s += os.urandom(8) cnonce = sha1(s).hexdigest()[:16] noncebit = "%s:%s:%s:%s:%s" % (nonce, ncvalue, cnonce, qop, ha2) respdig = self.KD(ha1, noncebit) elif qop is None: respdig = self.KD(ha1, "%s:%s" % (nonce, ha2)) else: # XXX handle auth-int. return base = ('username="%s", realm="%s", nonce="%s", uri="%s", ' 'response="%s"' % (self.username, realm, nonce, path, respdig)) opaque = o.get('opaque') if opaque: base += ', opaque="%s"' % opaque if entdig: base += ', digest="%s"' % entdig base += ', algorithm="%s"' % self.algorithm if qop: base += ', qop=%s, nc=%s, cnonce="%s"' % (qop, ncvalue, cnonce) return 'Digest %s' % base
[ "def", "encode", "(", "self", ",", "method", ",", "uri", ")", ":", "if", "not", "self", ".", "username", "or", "not", "self", ".", "password", ":", "return", "o", "=", "self", ".", "options", "qop", "=", "o", ".", "get", "(", "'qop'", ")", "realm", "=", "o", ".", "get", "(", "'realm'", ")", "nonce", "=", "o", ".", "get", "(", "'nonce'", ")", "entdig", "=", "None", "p_parsed", "=", "urlparse", "(", "uri", ")", "path", "=", "p_parsed", ".", "path", "if", "p_parsed", ".", "query", ":", "path", "+=", "'?'", "+", "p_parsed", ".", "query", "ha1", "=", "self", ".", "ha1", "(", "realm", ",", "self", ".", "password", ")", "ha2", "=", "self", ".", "ha2", "(", "qop", ",", "method", ",", "path", ")", "if", "qop", "==", "'auth'", ":", "if", "nonce", "==", "self", ".", "last_nonce", ":", "self", ".", "nonce_count", "+=", "1", "else", ":", "self", ".", "nonce_count", "=", "1", "ncvalue", "=", "'%08x'", "%", "self", ".", "nonce_count", "s", "=", "str", "(", "self", ".", "nonce_count", ")", ".", "encode", "(", "'utf-8'", ")", "s", "+=", "nonce", ".", "encode", "(", "'utf-8'", ")", "s", "+=", "time", ".", "ctime", "(", ")", ".", "encode", "(", "'utf-8'", ")", "s", "+=", "os", ".", "urandom", "(", "8", ")", "cnonce", "=", "sha1", "(", "s", ")", ".", "hexdigest", "(", ")", "[", ":", "16", "]", "noncebit", "=", "\"%s:%s:%s:%s:%s\"", "%", "(", "nonce", ",", "ncvalue", ",", "cnonce", ",", "qop", ",", "ha2", ")", "respdig", "=", "self", ".", "KD", "(", "ha1", ",", "noncebit", ")", "elif", "qop", "is", "None", ":", "respdig", "=", "self", ".", "KD", "(", "ha1", ",", "\"%s:%s\"", "%", "(", "nonce", ",", "ha2", ")", ")", "else", ":", "# XXX handle auth-int.", "return", "base", "=", "(", "'username=\"%s\", realm=\"%s\", nonce=\"%s\", uri=\"%s\", '", "'response=\"%s\"'", "%", "(", "self", ".", "username", ",", "realm", ",", "nonce", ",", "path", ",", "respdig", ")", ")", "opaque", "=", "o", ".", "get", "(", "'opaque'", ")", "if", "opaque", ":", "base", "+=", "', opaque=\"%s\"'", "%", "opaque", "if", "entdig", ":", "base", "+=", "', digest=\"%s\"'", "%", "entdig", "base", "+=", "', algorithm=\"%s\"'", "%", "self", ".", "algorithm", "if", "qop", ":", "base", "+=", "', qop=%s, nc=%s, cnonce=\"%s\"'", "%", "(", "qop", ",", "ncvalue", ",", "cnonce", ")", "return", "'Digest %s'", "%", "base" ]
Called by the client to encode Authentication header.
[ "Called", "by", "the", "client", "to", "encode", "Authentication", "header", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/auth.py#L78-L121
231,254
quantmind/pulsar
pulsar/apps/wsgi/utils.py
handle_wsgi_error
def handle_wsgi_error(environ, exc): '''The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse` ''' if isinstance(exc, tuple): exc_info = exc exc = exc[1] else: exc_info = True request = wsgi_request(environ) request.cache.handle_wsgi_error = True old_response = request.cache.pop('response', None) response = request.response if old_response: response.content_type = old_response.content_type logger = request.logger # if isinstance(exc, HTTPError): response.status_code = exc.code or 500 else: response.status_code = getattr(exc, 'status', 500) response.headers.update(getattr(exc, 'headers', None) or ()) status = response.status_code if status >= 500: logger.critical('%s - @ %s.\n%s', exc, request.first_line, dump_environ(environ), exc_info=exc_info) else: log_wsgi_info(logger.warning, environ, response.status, exc) if has_empty_content(status, request.method) or status in REDIRECT_CODES: response.content_type = None response.content = None else: request.cache.pop('html_document', None) renderer = environ.get('error.handler') or render_error try: content = renderer(request, exc) except Exception: logger.critical('Error while rendering error', exc_info=True) response.content_type = 'text/plain' content = 'Critical server error' if content is not response: response.content = content return response
python
def handle_wsgi_error(environ, exc): '''The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse` ''' if isinstance(exc, tuple): exc_info = exc exc = exc[1] else: exc_info = True request = wsgi_request(environ) request.cache.handle_wsgi_error = True old_response = request.cache.pop('response', None) response = request.response if old_response: response.content_type = old_response.content_type logger = request.logger # if isinstance(exc, HTTPError): response.status_code = exc.code or 500 else: response.status_code = getattr(exc, 'status', 500) response.headers.update(getattr(exc, 'headers', None) or ()) status = response.status_code if status >= 500: logger.critical('%s - @ %s.\n%s', exc, request.first_line, dump_environ(environ), exc_info=exc_info) else: log_wsgi_info(logger.warning, environ, response.status, exc) if has_empty_content(status, request.method) or status in REDIRECT_CODES: response.content_type = None response.content = None else: request.cache.pop('html_document', None) renderer = environ.get('error.handler') or render_error try: content = renderer(request, exc) except Exception: logger.critical('Error while rendering error', exc_info=True) response.content_type = 'text/plain' content = 'Critical server error' if content is not response: response.content = content return response
[ "def", "handle_wsgi_error", "(", "environ", ",", "exc", ")", ":", "if", "isinstance", "(", "exc", ",", "tuple", ")", ":", "exc_info", "=", "exc", "exc", "=", "exc", "[", "1", "]", "else", ":", "exc_info", "=", "True", "request", "=", "wsgi_request", "(", "environ", ")", "request", ".", "cache", ".", "handle_wsgi_error", "=", "True", "old_response", "=", "request", ".", "cache", ".", "pop", "(", "'response'", ",", "None", ")", "response", "=", "request", ".", "response", "if", "old_response", ":", "response", ".", "content_type", "=", "old_response", ".", "content_type", "logger", "=", "request", ".", "logger", "#", "if", "isinstance", "(", "exc", ",", "HTTPError", ")", ":", "response", ".", "status_code", "=", "exc", ".", "code", "or", "500", "else", ":", "response", ".", "status_code", "=", "getattr", "(", "exc", ",", "'status'", ",", "500", ")", "response", ".", "headers", ".", "update", "(", "getattr", "(", "exc", ",", "'headers'", ",", "None", ")", "or", "(", ")", ")", "status", "=", "response", ".", "status_code", "if", "status", ">=", "500", ":", "logger", ".", "critical", "(", "'%s - @ %s.\\n%s'", ",", "exc", ",", "request", ".", "first_line", ",", "dump_environ", "(", "environ", ")", ",", "exc_info", "=", "exc_info", ")", "else", ":", "log_wsgi_info", "(", "logger", ".", "warning", ",", "environ", ",", "response", ".", "status", ",", "exc", ")", "if", "has_empty_content", "(", "status", ",", "request", ".", "method", ")", "or", "status", "in", "REDIRECT_CODES", ":", "response", ".", "content_type", "=", "None", "response", ".", "content", "=", "None", "else", ":", "request", ".", "cache", ".", "pop", "(", "'html_document'", ",", "None", ")", "renderer", "=", "environ", ".", "get", "(", "'error.handler'", ")", "or", "render_error", "try", ":", "content", "=", "renderer", "(", "request", ",", "exc", ")", "except", "Exception", ":", "logger", ".", "critical", "(", "'Error while rendering error'", ",", "exc_info", "=", "True", ")", "response", ".", "content_type", "=", "'text/plain'", "content", "=", "'Critical server error'", "if", "content", "is", "not", "response", ":", "response", ".", "content", "=", "content", "return", "response" ]
The default error handler while serving a WSGI request. :param environ: The WSGI environment. :param exc: the exception :return: a :class:`.WsgiResponse`
[ "The", "default", "error", "handler", "while", "serving", "a", "WSGI", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L155-L200
231,255
quantmind/pulsar
pulsar/apps/wsgi/utils.py
render_error
def render_error(request, exc): '''Default renderer for errors.''' cfg = request.get('pulsar.cfg') debug = cfg.debug if cfg else False response = request.response if not response.content_type: content_type = request.get('default.content_type') response.content_type = request.content_types.best_match( as_tuple(content_type or DEFAULT_RESPONSE_CONTENT_TYPES) ) content_type = None if response.content_type: content_type = response.content_type.split(';')[0] is_html = content_type == 'text/html' if debug: msg = render_error_debug(request, exc, is_html) else: msg = escape(error_messages.get(response.status_code) or exc) if is_html: msg = textwrap.dedent(""" <h1>{0[reason]}</h1> {0[msg]} <h3>{0[version]}</h3> """).format({"reason": response.status, "msg": msg, "version": request.environ['SERVER_SOFTWARE']}) # if content_type == 'text/html': doc = HtmlDocument(title=response.status) doc.head.embedded_css.append(error_css) doc.body.append(Html('div', msg, cn='pulsar-error')) return doc.to_bytes(request) elif content_type in JSON_CONTENT_TYPES: return json.dumps({'status': response.status_code, 'message': msg}) else: return '\n'.join(msg) if isinstance(msg, (list, tuple)) else msg
python
def render_error(request, exc): '''Default renderer for errors.''' cfg = request.get('pulsar.cfg') debug = cfg.debug if cfg else False response = request.response if not response.content_type: content_type = request.get('default.content_type') response.content_type = request.content_types.best_match( as_tuple(content_type or DEFAULT_RESPONSE_CONTENT_TYPES) ) content_type = None if response.content_type: content_type = response.content_type.split(';')[0] is_html = content_type == 'text/html' if debug: msg = render_error_debug(request, exc, is_html) else: msg = escape(error_messages.get(response.status_code) or exc) if is_html: msg = textwrap.dedent(""" <h1>{0[reason]}</h1> {0[msg]} <h3>{0[version]}</h3> """).format({"reason": response.status, "msg": msg, "version": request.environ['SERVER_SOFTWARE']}) # if content_type == 'text/html': doc = HtmlDocument(title=response.status) doc.head.embedded_css.append(error_css) doc.body.append(Html('div', msg, cn='pulsar-error')) return doc.to_bytes(request) elif content_type in JSON_CONTENT_TYPES: return json.dumps({'status': response.status_code, 'message': msg}) else: return '\n'.join(msg) if isinstance(msg, (list, tuple)) else msg
[ "def", "render_error", "(", "request", ",", "exc", ")", ":", "cfg", "=", "request", ".", "get", "(", "'pulsar.cfg'", ")", "debug", "=", "cfg", ".", "debug", "if", "cfg", "else", "False", "response", "=", "request", ".", "response", "if", "not", "response", ".", "content_type", ":", "content_type", "=", "request", ".", "get", "(", "'default.content_type'", ")", "response", ".", "content_type", "=", "request", ".", "content_types", ".", "best_match", "(", "as_tuple", "(", "content_type", "or", "DEFAULT_RESPONSE_CONTENT_TYPES", ")", ")", "content_type", "=", "None", "if", "response", ".", "content_type", ":", "content_type", "=", "response", ".", "content_type", ".", "split", "(", "';'", ")", "[", "0", "]", "is_html", "=", "content_type", "==", "'text/html'", "if", "debug", ":", "msg", "=", "render_error_debug", "(", "request", ",", "exc", ",", "is_html", ")", "else", ":", "msg", "=", "escape", "(", "error_messages", ".", "get", "(", "response", ".", "status_code", ")", "or", "exc", ")", "if", "is_html", ":", "msg", "=", "textwrap", ".", "dedent", "(", "\"\"\"\n <h1>{0[reason]}</h1>\n {0[msg]}\n <h3>{0[version]}</h3>\n \"\"\"", ")", ".", "format", "(", "{", "\"reason\"", ":", "response", ".", "status", ",", "\"msg\"", ":", "msg", ",", "\"version\"", ":", "request", ".", "environ", "[", "'SERVER_SOFTWARE'", "]", "}", ")", "#", "if", "content_type", "==", "'text/html'", ":", "doc", "=", "HtmlDocument", "(", "title", "=", "response", ".", "status", ")", "doc", ".", "head", ".", "embedded_css", ".", "append", "(", "error_css", ")", "doc", ".", "body", ".", "append", "(", "Html", "(", "'div'", ",", "msg", ",", "cn", "=", "'pulsar-error'", ")", ")", "return", "doc", ".", "to_bytes", "(", "request", ")", "elif", "content_type", "in", "JSON_CONTENT_TYPES", ":", "return", "json", ".", "dumps", "(", "{", "'status'", ":", "response", ".", "status_code", ",", "'message'", ":", "msg", "}", ")", "else", ":", "return", "'\\n'", ".", "join", "(", "msg", ")", "if", "isinstance", "(", "msg", ",", "(", "list", ",", "tuple", ")", ")", "else", "msg" ]
Default renderer for errors.
[ "Default", "renderer", "for", "errors", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L203-L239
231,256
quantmind/pulsar
pulsar/apps/wsgi/utils.py
render_error_debug
def render_error_debug(request, exception, is_html): '''Render the ``exception`` traceback ''' error = Html('div', cn='well well-lg') if is_html else [] for trace in format_traceback(exception): counter = 0 for line in trace.split('\n'): if line.startswith(' '): counter += 1 line = line[2:] if line: if is_html: line = Html('p', escape(line), cn='text-danger') if counter: line.css({'margin-left': '%spx' % (20*counter)}) error.append(line) if is_html: error = Html('div', Html('h1', request.response.status), error) return error
python
def render_error_debug(request, exception, is_html): '''Render the ``exception`` traceback ''' error = Html('div', cn='well well-lg') if is_html else [] for trace in format_traceback(exception): counter = 0 for line in trace.split('\n'): if line.startswith(' '): counter += 1 line = line[2:] if line: if is_html: line = Html('p', escape(line), cn='text-danger') if counter: line.css({'margin-left': '%spx' % (20*counter)}) error.append(line) if is_html: error = Html('div', Html('h1', request.response.status), error) return error
[ "def", "render_error_debug", "(", "request", ",", "exception", ",", "is_html", ")", ":", "error", "=", "Html", "(", "'div'", ",", "cn", "=", "'well well-lg'", ")", "if", "is_html", "else", "[", "]", "for", "trace", "in", "format_traceback", "(", "exception", ")", ":", "counter", "=", "0", "for", "line", "in", "trace", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "' '", ")", ":", "counter", "+=", "1", "line", "=", "line", "[", "2", ":", "]", "if", "line", ":", "if", "is_html", ":", "line", "=", "Html", "(", "'p'", ",", "escape", "(", "line", ")", ",", "cn", "=", "'text-danger'", ")", "if", "counter", ":", "line", ".", "css", "(", "{", "'margin-left'", ":", "'%spx'", "%", "(", "20", "*", "counter", ")", "}", ")", "error", ".", "append", "(", "line", ")", "if", "is_html", ":", "error", "=", "Html", "(", "'div'", ",", "Html", "(", "'h1'", ",", "request", ".", "response", ".", "status", ")", ",", "error", ")", "return", "error" ]
Render the ``exception`` traceback
[ "Render", "the", "exception", "traceback" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/utils.py#L242-L260
231,257
quantmind/pulsar
pulsar/async/monitor.py
arbiter
def arbiter(**params): '''Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing. ''' arbiter = get_actor() if arbiter is None: # Create the arbiter return set_actor(_spawn_actor('arbiter', None, **params)) elif arbiter.is_arbiter(): return arbiter
python
def arbiter(**params): '''Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing. ''' arbiter = get_actor() if arbiter is None: # Create the arbiter return set_actor(_spawn_actor('arbiter', None, **params)) elif arbiter.is_arbiter(): return arbiter
[ "def", "arbiter", "(", "*", "*", "params", ")", ":", "arbiter", "=", "get_actor", "(", ")", "if", "arbiter", "is", "None", ":", "# Create the arbiter", "return", "set_actor", "(", "_spawn_actor", "(", "'arbiter'", ",", "None", ",", "*", "*", "params", ")", ")", "elif", "arbiter", ".", "is_arbiter", "(", ")", ":", "return", "arbiter" ]
Obtain the ``arbiter``. It returns the arbiter instance only if we are on the arbiter context domain, otherwise it returns nothing.
[ "Obtain", "the", "arbiter", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L24-L35
231,258
quantmind/pulsar
pulsar/async/monitor.py
MonitorMixin.manage_actor
def manage_actor(self, monitor, actor, stop=False): '''If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is not. ''' if not monitor.is_running(): stop = True if not actor.is_alive(): if not actor.should_be_alive() and not stop: return 1 actor.join() self._remove_monitored_actor(monitor, actor) return 0 timeout = None started_stopping = bool(actor.stopping_start) # if started_stopping is True, set stop to True stop = stop or started_stopping if not stop and actor.notified: gap = time() - actor.notified stop = timeout = gap > actor.cfg.timeout if stop: # we are stopping the actor dt = actor.should_terminate() if not actor.mailbox or dt: if not actor.mailbox: monitor.logger.warning('kill %s - no mailbox.', actor) else: monitor.logger.warning('kill %s - could not stop ' 'after %.2f seconds.', actor, dt) actor.kill() self._remove_monitored_actor(monitor, actor) return 0 elif not started_stopping: if timeout: monitor.logger.warning('Stopping %s. Timeout %.2f', actor, timeout) else: monitor.logger.info('Stopping %s.', actor) actor.stop() return 1
python
def manage_actor(self, monitor, actor, stop=False): '''If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is not. ''' if not monitor.is_running(): stop = True if not actor.is_alive(): if not actor.should_be_alive() and not stop: return 1 actor.join() self._remove_monitored_actor(monitor, actor) return 0 timeout = None started_stopping = bool(actor.stopping_start) # if started_stopping is True, set stop to True stop = stop or started_stopping if not stop and actor.notified: gap = time() - actor.notified stop = timeout = gap > actor.cfg.timeout if stop: # we are stopping the actor dt = actor.should_terminate() if not actor.mailbox or dt: if not actor.mailbox: monitor.logger.warning('kill %s - no mailbox.', actor) else: monitor.logger.warning('kill %s - could not stop ' 'after %.2f seconds.', actor, dt) actor.kill() self._remove_monitored_actor(monitor, actor) return 0 elif not started_stopping: if timeout: monitor.logger.warning('Stopping %s. Timeout %.2f', actor, timeout) else: monitor.logger.info('Stopping %s.', actor) actor.stop() return 1
[ "def", "manage_actor", "(", "self", ",", "monitor", ",", "actor", ",", "stop", "=", "False", ")", ":", "if", "not", "monitor", ".", "is_running", "(", ")", ":", "stop", "=", "True", "if", "not", "actor", ".", "is_alive", "(", ")", ":", "if", "not", "actor", ".", "should_be_alive", "(", ")", "and", "not", "stop", ":", "return", "1", "actor", ".", "join", "(", ")", "self", ".", "_remove_monitored_actor", "(", "monitor", ",", "actor", ")", "return", "0", "timeout", "=", "None", "started_stopping", "=", "bool", "(", "actor", ".", "stopping_start", ")", "# if started_stopping is True, set stop to True", "stop", "=", "stop", "or", "started_stopping", "if", "not", "stop", "and", "actor", ".", "notified", ":", "gap", "=", "time", "(", ")", "-", "actor", ".", "notified", "stop", "=", "timeout", "=", "gap", ">", "actor", ".", "cfg", ".", "timeout", "if", "stop", ":", "# we are stopping the actor", "dt", "=", "actor", ".", "should_terminate", "(", ")", "if", "not", "actor", ".", "mailbox", "or", "dt", ":", "if", "not", "actor", ".", "mailbox", ":", "monitor", ".", "logger", ".", "warning", "(", "'kill %s - no mailbox.'", ",", "actor", ")", "else", ":", "monitor", ".", "logger", ".", "warning", "(", "'kill %s - could not stop '", "'after %.2f seconds.'", ",", "actor", ",", "dt", ")", "actor", ".", "kill", "(", ")", "self", ".", "_remove_monitored_actor", "(", "monitor", ",", "actor", ")", "return", "0", "elif", "not", "started_stopping", ":", "if", "timeout", ":", "monitor", ".", "logger", ".", "warning", "(", "'Stopping %s. Timeout %.2f'", ",", "actor", ",", "timeout", ")", "else", ":", "monitor", ".", "logger", ".", "info", "(", "'Stopping %s.'", ",", "actor", ")", "actor", ".", "stop", "(", ")", "return", "1" ]
If an actor failed to notify itself to the arbiter for more than the timeout, stop the actor. :param actor: the :class:`Actor` to manage. :param stop: if ``True``, stop the actor. :return: if the actor is alive 0 if it is not.
[ "If", "an", "actor", "failed", "to", "notify", "itself", "to", "the", "arbiter", "for", "more", "than", "the", "timeout", "stop", "the", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L102-L143
231,259
quantmind/pulsar
pulsar/async/monitor.py
MonitorMixin.spawn_actors
def spawn_actors(self, monitor): '''Spawn new actors if needed. ''' to_spawn = monitor.cfg.workers - len(self.managed_actors) if monitor.cfg.workers and to_spawn > 0: for _ in range(to_spawn): monitor.spawn()
python
def spawn_actors(self, monitor): '''Spawn new actors if needed. ''' to_spawn = monitor.cfg.workers - len(self.managed_actors) if monitor.cfg.workers and to_spawn > 0: for _ in range(to_spawn): monitor.spawn()
[ "def", "spawn_actors", "(", "self", ",", "monitor", ")", ":", "to_spawn", "=", "monitor", ".", "cfg", ".", "workers", "-", "len", "(", "self", ".", "managed_actors", ")", "if", "monitor", ".", "cfg", ".", "workers", "and", "to_spawn", ">", "0", ":", "for", "_", "in", "range", "(", "to_spawn", ")", ":", "monitor", ".", "spawn", "(", ")" ]
Spawn new actors if needed.
[ "Spawn", "new", "actors", "if", "needed", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L145-L151
231,260
quantmind/pulsar
pulsar/async/monitor.py
MonitorMixin.stop_actors
def stop_actors(self, monitor): """Maintain the number of workers by spawning or killing as required """ if monitor.cfg.workers: num_to_kill = len(self.managed_actors) - monitor.cfg.workers for i in range(num_to_kill, 0, -1): w, kage = 0, sys.maxsize for worker in self.managed_actors.values(): age = worker.impl.age if age < kage: w, kage = worker, age self.manage_actor(monitor, w, True)
python
def stop_actors(self, monitor): """Maintain the number of workers by spawning or killing as required """ if monitor.cfg.workers: num_to_kill = len(self.managed_actors) - monitor.cfg.workers for i in range(num_to_kill, 0, -1): w, kage = 0, sys.maxsize for worker in self.managed_actors.values(): age = worker.impl.age if age < kage: w, kage = worker, age self.manage_actor(monitor, w, True)
[ "def", "stop_actors", "(", "self", ",", "monitor", ")", ":", "if", "monitor", ".", "cfg", ".", "workers", ":", "num_to_kill", "=", "len", "(", "self", ".", "managed_actors", ")", "-", "monitor", ".", "cfg", ".", "workers", "for", "i", "in", "range", "(", "num_to_kill", ",", "0", ",", "-", "1", ")", ":", "w", ",", "kage", "=", "0", ",", "sys", ".", "maxsize", "for", "worker", "in", "self", ".", "managed_actors", ".", "values", "(", ")", ":", "age", "=", "worker", ".", "impl", ".", "age", "if", "age", "<", "kage", ":", "w", ",", "kage", "=", "worker", ",", "age", "self", ".", "manage_actor", "(", "monitor", ",", "w", ",", "True", ")" ]
Maintain the number of workers by spawning or killing as required
[ "Maintain", "the", "number", "of", "workers", "by", "spawning", "or", "killing", "as", "required" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L153-L164
231,261
quantmind/pulsar
pulsar/async/monitor.py
ArbiterMixin.add_monitor
def add_monitor(self, actor, monitor_name, **params): '''Add a new ``monitor``. :param monitor_class: a :class:`.Monitor` class. :param monitor_name: a unique name for the monitor. :param kwargs: dictionary of key-valued parameters for the monitor. :return: the :class:`.Monitor` added. ''' if monitor_name in self.registered: raise KeyError('Monitor "%s" already available' % monitor_name) params.update(actor.actorparams()) params['name'] = monitor_name params['kind'] = 'monitor' return actor.spawn(**params)
python
def add_monitor(self, actor, monitor_name, **params): '''Add a new ``monitor``. :param monitor_class: a :class:`.Monitor` class. :param monitor_name: a unique name for the monitor. :param kwargs: dictionary of key-valued parameters for the monitor. :return: the :class:`.Monitor` added. ''' if monitor_name in self.registered: raise KeyError('Monitor "%s" already available' % monitor_name) params.update(actor.actorparams()) params['name'] = monitor_name params['kind'] = 'monitor' return actor.spawn(**params)
[ "def", "add_monitor", "(", "self", ",", "actor", ",", "monitor_name", ",", "*", "*", "params", ")", ":", "if", "monitor_name", "in", "self", ".", "registered", ":", "raise", "KeyError", "(", "'Monitor \"%s\" already available'", "%", "monitor_name", ")", "params", ".", "update", "(", "actor", ".", "actorparams", "(", ")", ")", "params", "[", "'name'", "]", "=", "monitor_name", "params", "[", "'kind'", "]", "=", "'monitor'", "return", "actor", ".", "spawn", "(", "*", "*", "params", ")" ]
Add a new ``monitor``. :param monitor_class: a :class:`.Monitor` class. :param monitor_name: a unique name for the monitor. :param kwargs: dictionary of key-valued parameters for the monitor. :return: the :class:`.Monitor` added.
[ "Add", "a", "new", "monitor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/monitor.py#L202-L215
231,262
quantmind/pulsar
pulsar/apps/data/store.py
PubSub.publish_event
def publish_event(self, channel, event, message): '''Publish a new event ``message`` to a ``channel``. ''' assert self.protocol is not None, "Protocol required" msg = {'event': event, 'channel': channel} if message: msg['data'] = message return self.publish(channel, msg)
python
def publish_event(self, channel, event, message): '''Publish a new event ``message`` to a ``channel``. ''' assert self.protocol is not None, "Protocol required" msg = {'event': event, 'channel': channel} if message: msg['data'] = message return self.publish(channel, msg)
[ "def", "publish_event", "(", "self", ",", "channel", ",", "event", ",", "message", ")", ":", "assert", "self", ".", "protocol", "is", "not", "None", ",", "\"Protocol required\"", "msg", "=", "{", "'event'", ":", "event", ",", "'channel'", ":", "channel", "}", "if", "message", ":", "msg", "[", "'data'", "]", "=", "message", "return", "self", ".", "publish", "(", "channel", ",", "msg", ")" ]
Publish a new event ``message`` to a ``channel``.
[ "Publish", "a", "new", "event", "message", "to", "a", "channel", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/store.py#L303-L310
231,263
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.spawn
def spawn(self, actor, aid=None, **params): '''Spawn a new actor from ``actor``. ''' aid = aid or create_aid() future = actor.send('arbiter', 'spawn', aid=aid, **params) return actor_proxy_future(aid, future)
python
def spawn(self, actor, aid=None, **params): '''Spawn a new actor from ``actor``. ''' aid = aid or create_aid() future = actor.send('arbiter', 'spawn', aid=aid, **params) return actor_proxy_future(aid, future)
[ "def", "spawn", "(", "self", ",", "actor", ",", "aid", "=", "None", ",", "*", "*", "params", ")", ":", "aid", "=", "aid", "or", "create_aid", "(", ")", "future", "=", "actor", ".", "send", "(", "'arbiter'", ",", "'spawn'", ",", "aid", "=", "aid", ",", "*", "*", "params", ")", "return", "actor_proxy_future", "(", "aid", ",", "future", ")" ]
Spawn a new actor from ``actor``.
[ "Spawn", "a", "new", "actor", "from", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L90-L95
231,264
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.run_actor
def run_actor(self, actor): '''Start running the ``actor``. ''' set_actor(actor) if not actor.mailbox.address: address = ('127.0.0.1', 0) actor._loop.create_task( actor.mailbox.start_serving(address=address) ) actor._loop.run_forever()
python
def run_actor(self, actor): '''Start running the ``actor``. ''' set_actor(actor) if not actor.mailbox.address: address = ('127.0.0.1', 0) actor._loop.create_task( actor.mailbox.start_serving(address=address) ) actor._loop.run_forever()
[ "def", "run_actor", "(", "self", ",", "actor", ")", ":", "set_actor", "(", "actor", ")", "if", "not", "actor", ".", "mailbox", ".", "address", ":", "address", "=", "(", "'127.0.0.1'", ",", "0", ")", "actor", ".", "_loop", ".", "create_task", "(", "actor", ".", "mailbox", ".", "start_serving", "(", "address", "=", "address", ")", ")", "actor", ".", "_loop", ".", "run_forever", "(", ")" ]
Start running the ``actor``.
[ "Start", "running", "the", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L97-L106
231,265
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.setup_event_loop
def setup_event_loop(self, actor): '''Set up the event loop for ``actor``. ''' actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name) try: loop = asyncio.get_event_loop() except RuntimeError: if self.cfg and self.cfg.concurrency == 'thread': loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) else: raise if not hasattr(loop, 'logger'): loop.logger = actor.logger actor.mailbox = self.create_mailbox(actor, loop) return loop
python
def setup_event_loop(self, actor): '''Set up the event loop for ``actor``. ''' actor.logger = self.cfg.configured_logger('pulsar.%s' % actor.name) try: loop = asyncio.get_event_loop() except RuntimeError: if self.cfg and self.cfg.concurrency == 'thread': loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) else: raise if not hasattr(loop, 'logger'): loop.logger = actor.logger actor.mailbox = self.create_mailbox(actor, loop) return loop
[ "def", "setup_event_loop", "(", "self", ",", "actor", ")", ":", "actor", ".", "logger", "=", "self", ".", "cfg", ".", "configured_logger", "(", "'pulsar.%s'", "%", "actor", ".", "name", ")", "try", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "except", "RuntimeError", ":", "if", "self", ".", "cfg", "and", "self", ".", "cfg", ".", "concurrency", "==", "'thread'", ":", "loop", "=", "asyncio", ".", "new_event_loop", "(", ")", "asyncio", ".", "set_event_loop", "(", "loop", ")", "else", ":", "raise", "if", "not", "hasattr", "(", "loop", ",", "'logger'", ")", ":", "loop", ".", "logger", "=", "actor", ".", "logger", "actor", ".", "mailbox", "=", "self", ".", "create_mailbox", "(", "actor", ",", "loop", ")", "return", "loop" ]
Set up the event loop for ``actor``.
[ "Set", "up", "the", "event", "loop", "for", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L111-L126
231,266
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.hand_shake
def hand_shake(self, actor, run=True): '''Perform the hand shake for ``actor`` The hand shake occurs when the ``actor`` is in starting state. It performs the following actions: * set the ``actor`` as the actor of the current thread * bind two additional callbacks to the ``start`` event * fire the ``start`` event If the hand shake is successful, the actor will eventually results in a running state. ''' try: assert actor.state == ACTOR_STATES.STARTING if actor.cfg.debug: actor.logger.debug('starting handshake') actor.event('start').fire() if run: self._switch_to_run(actor) except Exception as exc: actor.stop(exc)
python
def hand_shake(self, actor, run=True): '''Perform the hand shake for ``actor`` The hand shake occurs when the ``actor`` is in starting state. It performs the following actions: * set the ``actor`` as the actor of the current thread * bind two additional callbacks to the ``start`` event * fire the ``start`` event If the hand shake is successful, the actor will eventually results in a running state. ''' try: assert actor.state == ACTOR_STATES.STARTING if actor.cfg.debug: actor.logger.debug('starting handshake') actor.event('start').fire() if run: self._switch_to_run(actor) except Exception as exc: actor.stop(exc)
[ "def", "hand_shake", "(", "self", ",", "actor", ",", "run", "=", "True", ")", ":", "try", ":", "assert", "actor", ".", "state", "==", "ACTOR_STATES", ".", "STARTING", "if", "actor", ".", "cfg", ".", "debug", ":", "actor", ".", "logger", ".", "debug", "(", "'starting handshake'", ")", "actor", ".", "event", "(", "'start'", ")", ".", "fire", "(", ")", "if", "run", ":", "self", ".", "_switch_to_run", "(", "actor", ")", "except", "Exception", "as", "exc", ":", "actor", ".", "stop", "(", "exc", ")" ]
Perform the hand shake for ``actor`` The hand shake occurs when the ``actor`` is in starting state. It performs the following actions: * set the ``actor`` as the actor of the current thread * bind two additional callbacks to the ``start`` event * fire the ``start`` event If the hand shake is successful, the actor will eventually results in a running state.
[ "Perform", "the", "hand", "shake", "for", "actor" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L128-L149
231,267
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.create_mailbox
def create_mailbox(self, actor, loop): '''Create the mailbox for ``actor``.''' client = MailboxClient(actor.monitor.address, actor, loop) loop.call_soon_threadsafe(self.hand_shake, actor) return client
python
def create_mailbox(self, actor, loop): '''Create the mailbox for ``actor``.''' client = MailboxClient(actor.monitor.address, actor, loop) loop.call_soon_threadsafe(self.hand_shake, actor) return client
[ "def", "create_mailbox", "(", "self", ",", "actor", ",", "loop", ")", ":", "client", "=", "MailboxClient", "(", "actor", ".", "monitor", ".", "address", ",", "actor", ",", "loop", ")", "loop", ".", "call_soon_threadsafe", "(", "self", ".", "hand_shake", ",", "actor", ")", "return", "client" ]
Create the mailbox for ``actor``.
[ "Create", "the", "mailbox", "for", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L156-L160
231,268
quantmind/pulsar
pulsar/async/concurrency.py
Concurrency.stop
def stop(self, actor, exc=None, exit_code=None): """Gracefully stop the ``actor``. """ if actor.state <= ACTOR_STATES.RUN: # The actor has not started the stopping process. Starts it now. actor.state = ACTOR_STATES.STOPPING actor.event('start').clear() if exc: if not exit_code: exit_code = getattr(exc, 'exit_code', 1) if exit_code == 1: exc_info = sys.exc_info() if exc_info[0] is not None: actor.logger.critical('Stopping', exc_info=exc_info) else: actor.logger.critical('Stopping: %s', exc) elif exit_code == 2: actor.logger.error(str(exc)) elif exit_code: actor.stream.writeln(str(exc)) else: if not exit_code: exit_code = getattr(actor._loop, 'exit_code', 0) # # Fire stopping event actor.exit_code = exit_code actor.stopping_waiters = [] actor.event('stopping').fire() if actor.stopping_waiters and actor._loop.is_running(): actor.logger.info('asynchronous stopping') # make sure to return the future (used by arbiter for waiting) return actor._loop.create_task(self._async_stopping(actor)) else: if actor.logger: actor.logger.info('stopping') self._stop_actor(actor) elif actor.stopped(): return self._stop_actor(actor, True)
python
def stop(self, actor, exc=None, exit_code=None): """Gracefully stop the ``actor``. """ if actor.state <= ACTOR_STATES.RUN: # The actor has not started the stopping process. Starts it now. actor.state = ACTOR_STATES.STOPPING actor.event('start').clear() if exc: if not exit_code: exit_code = getattr(exc, 'exit_code', 1) if exit_code == 1: exc_info = sys.exc_info() if exc_info[0] is not None: actor.logger.critical('Stopping', exc_info=exc_info) else: actor.logger.critical('Stopping: %s', exc) elif exit_code == 2: actor.logger.error(str(exc)) elif exit_code: actor.stream.writeln(str(exc)) else: if not exit_code: exit_code = getattr(actor._loop, 'exit_code', 0) # # Fire stopping event actor.exit_code = exit_code actor.stopping_waiters = [] actor.event('stopping').fire() if actor.stopping_waiters and actor._loop.is_running(): actor.logger.info('asynchronous stopping') # make sure to return the future (used by arbiter for waiting) return actor._loop.create_task(self._async_stopping(actor)) else: if actor.logger: actor.logger.info('stopping') self._stop_actor(actor) elif actor.stopped(): return self._stop_actor(actor, True)
[ "def", "stop", "(", "self", ",", "actor", ",", "exc", "=", "None", ",", "exit_code", "=", "None", ")", ":", "if", "actor", ".", "state", "<=", "ACTOR_STATES", ".", "RUN", ":", "# The actor has not started the stopping process. Starts it now.", "actor", ".", "state", "=", "ACTOR_STATES", ".", "STOPPING", "actor", ".", "event", "(", "'start'", ")", ".", "clear", "(", ")", "if", "exc", ":", "if", "not", "exit_code", ":", "exit_code", "=", "getattr", "(", "exc", ",", "'exit_code'", ",", "1", ")", "if", "exit_code", "==", "1", ":", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "if", "exc_info", "[", "0", "]", "is", "not", "None", ":", "actor", ".", "logger", ".", "critical", "(", "'Stopping'", ",", "exc_info", "=", "exc_info", ")", "else", ":", "actor", ".", "logger", ".", "critical", "(", "'Stopping: %s'", ",", "exc", ")", "elif", "exit_code", "==", "2", ":", "actor", ".", "logger", ".", "error", "(", "str", "(", "exc", ")", ")", "elif", "exit_code", ":", "actor", ".", "stream", ".", "writeln", "(", "str", "(", "exc", ")", ")", "else", ":", "if", "not", "exit_code", ":", "exit_code", "=", "getattr", "(", "actor", ".", "_loop", ",", "'exit_code'", ",", "0", ")", "#", "# Fire stopping event", "actor", ".", "exit_code", "=", "exit_code", "actor", ".", "stopping_waiters", "=", "[", "]", "actor", ".", "event", "(", "'stopping'", ")", ".", "fire", "(", ")", "if", "actor", ".", "stopping_waiters", "and", "actor", ".", "_loop", ".", "is_running", "(", ")", ":", "actor", ".", "logger", ".", "info", "(", "'asynchronous stopping'", ")", "# make sure to return the future (used by arbiter for waiting)", "return", "actor", ".", "_loop", ".", "create_task", "(", "self", ".", "_async_stopping", "(", "actor", ")", ")", "else", ":", "if", "actor", ".", "logger", ":", "actor", ".", "logger", ".", "info", "(", "'stopping'", ")", "self", ".", "_stop_actor", "(", "actor", ")", "elif", "actor", ".", "stopped", "(", ")", ":", "return", "self", ".", "_stop_actor", "(", "actor", ",", "True", ")" ]
Gracefully stop the ``actor``.
[ "Gracefully", "stop", "the", "actor", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/concurrency.py#L179-L218
231,269
quantmind/pulsar
pulsar/apps/wsgi/auth.py
DigestAuth.authenticated
def authenticated(self, environ, username=None, password=None, **params): '''Called by the server to check if client is authenticated.''' if username != self.username: return False o = self.options qop = o.get('qop') method = environ['REQUEST_METHOD'] uri = environ.get('PATH_INFO', '') ha1 = self.ha1(o['realm'], password) ha2 = self.ha2(qop, method, uri) if qop is None: response = hexmd5(":".join((ha1, self.nonce, ha2))) elif qop == 'auth' or qop == 'auth-int': response = hexmd5(":".join((ha1, o['nonce'], o['nc'], o['cnonce'], qop, ha2))) else: raise ValueError("qop value are wrong") return o['response'] == response
python
def authenticated(self, environ, username=None, password=None, **params): '''Called by the server to check if client is authenticated.''' if username != self.username: return False o = self.options qop = o.get('qop') method = environ['REQUEST_METHOD'] uri = environ.get('PATH_INFO', '') ha1 = self.ha1(o['realm'], password) ha2 = self.ha2(qop, method, uri) if qop is None: response = hexmd5(":".join((ha1, self.nonce, ha2))) elif qop == 'auth' or qop == 'auth-int': response = hexmd5(":".join((ha1, o['nonce'], o['nc'], o['cnonce'], qop, ha2))) else: raise ValueError("qop value are wrong") return o['response'] == response
[ "def", "authenticated", "(", "self", ",", "environ", ",", "username", "=", "None", ",", "password", "=", "None", ",", "*", "*", "params", ")", ":", "if", "username", "!=", "self", ".", "username", ":", "return", "False", "o", "=", "self", ".", "options", "qop", "=", "o", ".", "get", "(", "'qop'", ")", "method", "=", "environ", "[", "'REQUEST_METHOD'", "]", "uri", "=", "environ", ".", "get", "(", "'PATH_INFO'", ",", "''", ")", "ha1", "=", "self", ".", "ha1", "(", "o", "[", "'realm'", "]", ",", "password", ")", "ha2", "=", "self", ".", "ha2", "(", "qop", ",", "method", ",", "uri", ")", "if", "qop", "is", "None", ":", "response", "=", "hexmd5", "(", "\":\"", ".", "join", "(", "(", "ha1", ",", "self", ".", "nonce", ",", "ha2", ")", ")", ")", "elif", "qop", "==", "'auth'", "or", "qop", "==", "'auth-int'", ":", "response", "=", "hexmd5", "(", "\":\"", ".", "join", "(", "(", "ha1", ",", "o", "[", "'nonce'", "]", ",", "o", "[", "'nc'", "]", ",", "o", "[", "'cnonce'", "]", ",", "qop", ",", "ha2", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "\"qop value are wrong\"", ")", "return", "o", "[", "'response'", "]", "==", "response" ]
Called by the server to check if client is authenticated.
[ "Called", "by", "the", "server", "to", "check", "if", "client", "is", "authenticated", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/auth.py#L103-L120
231,270
quantmind/pulsar
pulsar/apps/data/channels.py
Channels.register
async def register(self, channel, event, callback): """Register a callback to ``channel_name`` and ``event``. A prefix will be added to the channel name if not already available or the prefix is an empty string :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel where the callback was registered """ channel = self.channel(channel) event = channel.register(event, callback) await channel.connect(event.name) return channel
python
async def register(self, channel, event, callback): """Register a callback to ``channel_name`` and ``event``. A prefix will be added to the channel name if not already available or the prefix is an empty string :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel where the callback was registered """ channel = self.channel(channel) event = channel.register(event, callback) await channel.connect(event.name) return channel
[ "async", "def", "register", "(", "self", ",", "channel", ",", "event", ",", "callback", ")", ":", "channel", "=", "self", ".", "channel", "(", "channel", ")", "event", "=", "channel", ".", "register", "(", "event", ",", "callback", ")", "await", "channel", ".", "connect", "(", "event", ".", "name", ")", "return", "channel" ]
Register a callback to ``channel_name`` and ``event``. A prefix will be added to the channel name if not already available or the prefix is an empty string :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel where the callback was registered
[ "Register", "a", "callback", "to", "channel_name", "and", "event", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L135-L150
231,271
quantmind/pulsar
pulsar/apps/data/channels.py
Channels.unregister
async def unregister(self, channel, event, callback): """Safely unregister a callback from the list of ``event`` callbacks for ``channel_name``. :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel object where the ``callback`` was removed (if found) """ channel = self.channel(channel, create=False) if channel: channel.unregister(event, callback) if not channel: await channel.disconnect() self.channels.pop(channel.name) return channel
python
async def unregister(self, channel, event, callback): """Safely unregister a callback from the list of ``event`` callbacks for ``channel_name``. :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel object where the ``callback`` was removed (if found) """ channel = self.channel(channel, create=False) if channel: channel.unregister(event, callback) if not channel: await channel.disconnect() self.channels.pop(channel.name) return channel
[ "async", "def", "unregister", "(", "self", ",", "channel", ",", "event", ",", "callback", ")", ":", "channel", "=", "self", ".", "channel", "(", "channel", ",", "create", "=", "False", ")", "if", "channel", ":", "channel", ".", "unregister", "(", "event", ",", "callback", ")", "if", "not", "channel", ":", "await", "channel", ".", "disconnect", "(", ")", "self", ".", "channels", ".", "pop", "(", "channel", ".", "name", ")", "return", "channel" ]
Safely unregister a callback from the list of ``event`` callbacks for ``channel_name``. :param channel: channel name :param event: event name :param callback: callback to execute when event on channel occurs :return: a coroutine which results in the channel object where the ``callback`` was removed (if found)
[ "Safely", "unregister", "a", "callback", "from", "the", "list", "of", "event", "callbacks", "for", "channel_name", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L152-L168
231,272
quantmind/pulsar
pulsar/apps/data/channels.py
Channels.connect
async def connect(self, next_time=None): """Connect with store :return: a coroutine and therefore it must be awaited """ if self.status in can_connect: loop = self._loop if loop.is_running(): self.status = StatusType.connecting await self._connect(next_time)
python
async def connect(self, next_time=None): """Connect with store :return: a coroutine and therefore it must be awaited """ if self.status in can_connect: loop = self._loop if loop.is_running(): self.status = StatusType.connecting await self._connect(next_time)
[ "async", "def", "connect", "(", "self", ",", "next_time", "=", "None", ")", ":", "if", "self", ".", "status", "in", "can_connect", ":", "loop", "=", "self", ".", "_loop", "if", "loop", ".", "is_running", "(", ")", ":", "self", ".", "status", "=", "StatusType", ".", "connecting", "await", "self", ".", "_connect", "(", "next_time", ")" ]
Connect with store :return: a coroutine and therefore it must be awaited
[ "Connect", "with", "store" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L170-L179
231,273
quantmind/pulsar
pulsar/apps/data/channels.py
Channel.register
def register(self, event, callback): """Register a ``callback`` for ``event`` """ pattern = self.channels.event_pattern(event) entry = self.callbacks.get(pattern) if not entry: entry = event_callbacks(event, pattern, re.compile(pattern), []) self.callbacks[entry.pattern] = entry if callback not in entry.callbacks: entry.callbacks.append(callback) return entry
python
def register(self, event, callback): """Register a ``callback`` for ``event`` """ pattern = self.channels.event_pattern(event) entry = self.callbacks.get(pattern) if not entry: entry = event_callbacks(event, pattern, re.compile(pattern), []) self.callbacks[entry.pattern] = entry if callback not in entry.callbacks: entry.callbacks.append(callback) return entry
[ "def", "register", "(", "self", ",", "event", ",", "callback", ")", ":", "pattern", "=", "self", ".", "channels", ".", "event_pattern", "(", "event", ")", "entry", "=", "self", ".", "callbacks", ".", "get", "(", "pattern", ")", "if", "not", "entry", ":", "entry", "=", "event_callbacks", "(", "event", ",", "pattern", ",", "re", ".", "compile", "(", "pattern", ")", ",", "[", "]", ")", "self", ".", "callbacks", "[", "entry", ".", "pattern", "]", "=", "entry", "if", "callback", "not", "in", "entry", ".", "callbacks", ":", "entry", ".", "callbacks", ".", "append", "(", "callback", ")", "return", "entry" ]
Register a ``callback`` for ``event``
[ "Register", "a", "callback", "for", "event" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/channels.py#L329-L341
231,274
quantmind/pulsar
pulsar/async/futures.py
add_errback
def add_errback(future, callback, loop=None): '''Add a ``callback`` to a ``future`` executed only if an exception or cancellation has occurred.''' def _error_back(fut): if fut._exception: callback(fut.exception()) elif fut.cancelled(): callback(CancelledError()) future = ensure_future(future, loop=None) future.add_done_callback(_error_back) return future
python
def add_errback(future, callback, loop=None): '''Add a ``callback`` to a ``future`` executed only if an exception or cancellation has occurred.''' def _error_back(fut): if fut._exception: callback(fut.exception()) elif fut.cancelled(): callback(CancelledError()) future = ensure_future(future, loop=None) future.add_done_callback(_error_back) return future
[ "def", "add_errback", "(", "future", ",", "callback", ",", "loop", "=", "None", ")", ":", "def", "_error_back", "(", "fut", ")", ":", "if", "fut", ".", "_exception", ":", "callback", "(", "fut", ".", "exception", "(", ")", ")", "elif", "fut", ".", "cancelled", "(", ")", ":", "callback", "(", "CancelledError", "(", ")", ")", "future", "=", "ensure_future", "(", "future", ",", "loop", "=", "None", ")", "future", ".", "add_done_callback", "(", "_error_back", ")", "return", "future" ]
Add a ``callback`` to a ``future`` executed only if an exception or cancellation has occurred.
[ "Add", "a", "callback", "to", "a", "future", "executed", "only", "if", "an", "exception", "or", "cancellation", "has", "occurred", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/futures.py#L58-L69
231,275
quantmind/pulsar
pulsar/async/futures.py
AsyncObject.timeit
def timeit(self, method, times, *args, **kwargs): '''Useful utility for benchmarking an asynchronous ``method``. :param method: the name of the ``method`` to execute :param times: number of times to execute the ``method`` :param args: positional arguments to pass to the ``method`` :param kwargs: key-valued arguments to pass to the ``method`` :return: a :class:`~asyncio.Future` which results in a :class:`Bench` object if successful The usage is simple:: >>> b = self.timeit('asyncmethod', 100) ''' bench = Bench(times, loop=self._loop) return bench(getattr(self, method), *args, **kwargs)
python
def timeit(self, method, times, *args, **kwargs): '''Useful utility for benchmarking an asynchronous ``method``. :param method: the name of the ``method`` to execute :param times: number of times to execute the ``method`` :param args: positional arguments to pass to the ``method`` :param kwargs: key-valued arguments to pass to the ``method`` :return: a :class:`~asyncio.Future` which results in a :class:`Bench` object if successful The usage is simple:: >>> b = self.timeit('asyncmethod', 100) ''' bench = Bench(times, loop=self._loop) return bench(getattr(self, method), *args, **kwargs)
[ "def", "timeit", "(", "self", ",", "method", ",", "times", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "bench", "=", "Bench", "(", "times", ",", "loop", "=", "self", ".", "_loop", ")", "return", "bench", "(", "getattr", "(", "self", ",", "method", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Useful utility for benchmarking an asynchronous ``method``. :param method: the name of the ``method`` to execute :param times: number of times to execute the ``method`` :param args: positional arguments to pass to the ``method`` :param kwargs: key-valued arguments to pass to the ``method`` :return: a :class:`~asyncio.Future` which results in a :class:`Bench` object if successful The usage is simple:: >>> b = self.timeit('asyncmethod', 100)
[ "Useful", "utility", "for", "benchmarking", "an", "asynchronous", "method", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/futures.py#L194-L209
231,276
quantmind/pulsar
pulsar/apps/http/stream.py
HttpStream.read
async def read(self, n=None): """Read all content """ if self._streamed: return b'' buffer = [] async for body in self: buffer.append(body) return b''.join(buffer)
python
async def read(self, n=None): """Read all content """ if self._streamed: return b'' buffer = [] async for body in self: buffer.append(body) return b''.join(buffer)
[ "async", "def", "read", "(", "self", ",", "n", "=", "None", ")", ":", "if", "self", ".", "_streamed", ":", "return", "b''", "buffer", "=", "[", "]", "async", "for", "body", "in", "self", ":", "buffer", ".", "append", "(", "body", ")", "return", "b''", ".", "join", "(", "buffer", ")" ]
Read all content
[ "Read", "all", "content" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/http/stream.py#L27-L35
231,277
quantmind/pulsar
pulsar/async/commands.py
notify
def notify(request, info): '''The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update ''' t = time() actor = request.actor remote_actor = request.caller if isinstance(remote_actor, ActorProxyMonitor): remote_actor.mailbox = request.connection info['last_notified'] = t remote_actor.info = info callback = remote_actor.callback # if a callback is still available, this is the first # time we got notified if callback: remote_actor.callback = None callback.set_result(remote_actor) if actor.cfg.debug: actor.logger.debug('Got first notification from %s', remote_actor) elif actor.cfg.debug: actor.logger.debug('Got notification from %s', remote_actor) else: actor.logger.warning('notify got a bad actor') return t
python
def notify(request, info): '''The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update ''' t = time() actor = request.actor remote_actor = request.caller if isinstance(remote_actor, ActorProxyMonitor): remote_actor.mailbox = request.connection info['last_notified'] = t remote_actor.info = info callback = remote_actor.callback # if a callback is still available, this is the first # time we got notified if callback: remote_actor.callback = None callback.set_result(remote_actor) if actor.cfg.debug: actor.logger.debug('Got first notification from %s', remote_actor) elif actor.cfg.debug: actor.logger.debug('Got notification from %s', remote_actor) else: actor.logger.warning('notify got a bad actor') return t
[ "def", "notify", "(", "request", ",", "info", ")", ":", "t", "=", "time", "(", ")", "actor", "=", "request", ".", "actor", "remote_actor", "=", "request", ".", "caller", "if", "isinstance", "(", "remote_actor", ",", "ActorProxyMonitor", ")", ":", "remote_actor", ".", "mailbox", "=", "request", ".", "connection", "info", "[", "'last_notified'", "]", "=", "t", "remote_actor", ".", "info", "=", "info", "callback", "=", "remote_actor", ".", "callback", "# if a callback is still available, this is the first", "# time we got notified", "if", "callback", ":", "remote_actor", ".", "callback", "=", "None", "callback", ".", "set_result", "(", "remote_actor", ")", "if", "actor", ".", "cfg", ".", "debug", ":", "actor", ".", "logger", ".", "debug", "(", "'Got first notification from %s'", ",", "remote_actor", ")", "elif", "actor", ".", "cfg", ".", "debug", ":", "actor", ".", "logger", ".", "debug", "(", "'Got notification from %s'", ",", "remote_actor", ")", "else", ":", "actor", ".", "logger", ".", "warning", "(", "'notify got a bad actor'", ")", "return", "t" ]
The actor notify itself with a dictionary of information. The command perform the following actions: * Update the mailbox to the current consumer of the actor connection * Update the info dictionary * Returns the time of the update
[ "The", "actor", "notify", "itself", "with", "a", "dictionary", "of", "information", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/commands.py#L49-L78
231,278
quantmind/pulsar
pulsar/async/mixins.py
FlowControl.write
def write(self, data): """Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing. """ if self.closed: raise ConnectionResetError( 'Transport closed - cannot write on %s' % self ) else: t = self.transport if self._paused or self._buffer: self._buffer.appendleft(data) self._buffer_size += len(data) self._write_from_buffer() if self._buffer_size > 2 * self._b_limit: if self._waiter and not self._waiter.cancelled(): self.logger.warning( '%s buffer size is %d: limit is %d ', self._buffer_size, self._b_limit ) else: t.pause_reading() self._waiter = self._loop.create_future() else: t.write(data) self.changed() return self._waiter
python
def write(self, data): """Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing. """ if self.closed: raise ConnectionResetError( 'Transport closed - cannot write on %s' % self ) else: t = self.transport if self._paused or self._buffer: self._buffer.appendleft(data) self._buffer_size += len(data) self._write_from_buffer() if self._buffer_size > 2 * self._b_limit: if self._waiter and not self._waiter.cancelled(): self.logger.warning( '%s buffer size is %d: limit is %d ', self._buffer_size, self._b_limit ) else: t.pause_reading() self._waiter = self._loop.create_future() else: t.write(data) self.changed() return self._waiter
[ "def", "write", "(", "self", ",", "data", ")", ":", "if", "self", ".", "closed", ":", "raise", "ConnectionResetError", "(", "'Transport closed - cannot write on %s'", "%", "self", ")", "else", ":", "t", "=", "self", ".", "transport", "if", "self", ".", "_paused", "or", "self", ".", "_buffer", ":", "self", ".", "_buffer", ".", "appendleft", "(", "data", ")", "self", ".", "_buffer_size", "+=", "len", "(", "data", ")", "self", ".", "_write_from_buffer", "(", ")", "if", "self", ".", "_buffer_size", ">", "2", "*", "self", ".", "_b_limit", ":", "if", "self", ".", "_waiter", "and", "not", "self", ".", "_waiter", ".", "cancelled", "(", ")", ":", "self", ".", "logger", ".", "warning", "(", "'%s buffer size is %d: limit is %d '", ",", "self", ".", "_buffer_size", ",", "self", ".", "_b_limit", ")", "else", ":", "t", ".", "pause_reading", "(", ")", "self", ".", "_waiter", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "else", ":", "t", ".", "write", "(", "data", ")", "self", ".", "changed", "(", ")", "return", "self", ".", "_waiter" ]
Write ``data`` into the wire. Returns an empty tuple or a :class:`~asyncio.Future` if this protocol has paused writing.
[ "Write", "data", "into", "the", "wire", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L20-L48
231,279
quantmind/pulsar
pulsar/async/mixins.py
Pipeline.pipeline
def pipeline(self, consumer): """Add a consumer to the pipeline """ if self._pipeline is None: self._pipeline = ResponsePipeline(self) self.event('connection_lost').bind(self._close_pipeline) self._pipeline.put(consumer)
python
def pipeline(self, consumer): """Add a consumer to the pipeline """ if self._pipeline is None: self._pipeline = ResponsePipeline(self) self.event('connection_lost').bind(self._close_pipeline) self._pipeline.put(consumer)
[ "def", "pipeline", "(", "self", ",", "consumer", ")", ":", "if", "self", ".", "_pipeline", "is", "None", ":", "self", ".", "_pipeline", "=", "ResponsePipeline", "(", "self", ")", "self", ".", "event", "(", "'connection_lost'", ")", ".", "bind", "(", "self", ".", "_close_pipeline", ")", "self", ".", "_pipeline", ".", "put", "(", "consumer", ")" ]
Add a consumer to the pipeline
[ "Add", "a", "consumer", "to", "the", "pipeline" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mixins.py#L157-L163
231,280
quantmind/pulsar
pulsar/utils/pylib/websocket.py
FrameParser.encode
def encode(self, message, final=True, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0): '''Encode a ``message`` for writing into the wire. To produce several frames for a given large message use :meth:`multi_encode` method. ''' fin = 1 if final else 0 opcode, masking_key, data = self._info(message, opcode, masking_key) return self._encode(data, opcode, masking_key, fin, rsv1, rsv2, rsv3)
python
def encode(self, message, final=True, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0): '''Encode a ``message`` for writing into the wire. To produce several frames for a given large message use :meth:`multi_encode` method. ''' fin = 1 if final else 0 opcode, masking_key, data = self._info(message, opcode, masking_key) return self._encode(data, opcode, masking_key, fin, rsv1, rsv2, rsv3)
[ "def", "encode", "(", "self", ",", "message", ",", "final", "=", "True", ",", "masking_key", "=", "None", ",", "opcode", "=", "None", ",", "rsv1", "=", "0", ",", "rsv2", "=", "0", ",", "rsv3", "=", "0", ")", ":", "fin", "=", "1", "if", "final", "else", "0", "opcode", ",", "masking_key", ",", "data", "=", "self", ".", "_info", "(", "message", ",", "opcode", ",", "masking_key", ")", "return", "self", ".", "_encode", "(", "data", ",", "opcode", ",", "masking_key", ",", "fin", ",", "rsv1", ",", "rsv2", ",", "rsv3", ")" ]
Encode a ``message`` for writing into the wire. To produce several frames for a given large message use :meth:`multi_encode` method.
[ "Encode", "a", "message", "for", "writing", "into", "the", "wire", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/websocket.py#L140-L150
231,281
quantmind/pulsar
pulsar/utils/pylib/websocket.py
FrameParser.multi_encode
def multi_encode(self, message, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0, max_payload=0): '''Encode a ``message`` into several frames depending on size. Returns a generator of bytes to be sent over the wire. ''' max_payload = max(2, max_payload or self._max_payload) opcode, masking_key, data = self._info(message, opcode, masking_key) # while data: if len(data) >= max_payload: chunk, data, fin = (data[:max_payload], data[max_payload:], 0) else: chunk, data, fin = data, b'', 1 yield self._encode(chunk, opcode, masking_key, fin, rsv1, rsv2, rsv3)
python
def multi_encode(self, message, masking_key=None, opcode=None, rsv1=0, rsv2=0, rsv3=0, max_payload=0): '''Encode a ``message`` into several frames depending on size. Returns a generator of bytes to be sent over the wire. ''' max_payload = max(2, max_payload or self._max_payload) opcode, masking_key, data = self._info(message, opcode, masking_key) # while data: if len(data) >= max_payload: chunk, data, fin = (data[:max_payload], data[max_payload:], 0) else: chunk, data, fin = data, b'', 1 yield self._encode(chunk, opcode, masking_key, fin, rsv1, rsv2, rsv3)
[ "def", "multi_encode", "(", "self", ",", "message", ",", "masking_key", "=", "None", ",", "opcode", "=", "None", ",", "rsv1", "=", "0", ",", "rsv2", "=", "0", ",", "rsv3", "=", "0", ",", "max_payload", "=", "0", ")", ":", "max_payload", "=", "max", "(", "2", ",", "max_payload", "or", "self", ".", "_max_payload", ")", "opcode", ",", "masking_key", ",", "data", "=", "self", ".", "_info", "(", "message", ",", "opcode", ",", "masking_key", ")", "#", "while", "data", ":", "if", "len", "(", "data", ")", ">=", "max_payload", ":", "chunk", ",", "data", ",", "fin", "=", "(", "data", "[", ":", "max_payload", "]", ",", "data", "[", "max_payload", ":", "]", ",", "0", ")", "else", ":", "chunk", ",", "data", ",", "fin", "=", "data", ",", "b''", ",", "1", "yield", "self", ".", "_encode", "(", "chunk", ",", "opcode", ",", "masking_key", ",", "fin", ",", "rsv1", ",", "rsv2", ",", "rsv3", ")" ]
Encode a ``message`` into several frames depending on size. Returns a generator of bytes to be sent over the wire.
[ "Encode", "a", "message", "into", "several", "frames", "depending", "on", "size", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/pylib/websocket.py#L152-L168
231,282
quantmind/pulsar
pulsar/apps/data/redis/client.py
RedisClient.sort
def sort(self, key, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=False): '''Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning items from external keys rather than the sorted data itself. Use an "*" to indicate where int he key the item value is located ``desc`` allows for reversing the sort ``alpha`` allows for sorting lexicographically rather than numerically ``store`` allows for storing the result of the sort into the key ``store`` ``groups`` if set to True and if ``get`` contains at least two elements, sort will return a list of tuples, each containing the values fetched from the arguments to ``get``. ''' if ((start is not None and num is None) or (num is not None and start is None)): raise CommandError("``start`` and ``num`` must both be specified") pieces = [key] if by is not None: pieces.append('BY') pieces.append(by) if start is not None and num is not None: pieces.append('LIMIT') pieces.append(start) pieces.append(num) if get is not None: # If get is a string assume we want to get a single value. # Otherwise assume it's an interable and we want to get multiple # values. We can't just iterate blindly because strings are # iterable. if isinstance(get, str): pieces.append('GET') pieces.append(get) else: for g in get: pieces.append('GET') pieces.append(g) if desc: pieces.append('DESC') if alpha: pieces.append('ALPHA') if store is not None: pieces.append('STORE') pieces.append(store) if groups: if not get or isinstance(get, str) or len(get) < 2: raise CommandError('when using "groups" the "get" argument ' 'must be specified and contain at least ' 'two keys') options = {'groups': len(get) if groups else None} return self.execute_command('SORT', *pieces, **options)
python
def sort(self, key, start=None, num=None, by=None, get=None, desc=False, alpha=False, store=None, groups=False): '''Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning items from external keys rather than the sorted data itself. Use an "*" to indicate where int he key the item value is located ``desc`` allows for reversing the sort ``alpha`` allows for sorting lexicographically rather than numerically ``store`` allows for storing the result of the sort into the key ``store`` ``groups`` if set to True and if ``get`` contains at least two elements, sort will return a list of tuples, each containing the values fetched from the arguments to ``get``. ''' if ((start is not None and num is None) or (num is not None and start is None)): raise CommandError("``start`` and ``num`` must both be specified") pieces = [key] if by is not None: pieces.append('BY') pieces.append(by) if start is not None and num is not None: pieces.append('LIMIT') pieces.append(start) pieces.append(num) if get is not None: # If get is a string assume we want to get a single value. # Otherwise assume it's an interable and we want to get multiple # values. We can't just iterate blindly because strings are # iterable. if isinstance(get, str): pieces.append('GET') pieces.append(get) else: for g in get: pieces.append('GET') pieces.append(g) if desc: pieces.append('DESC') if alpha: pieces.append('ALPHA') if store is not None: pieces.append('STORE') pieces.append(store) if groups: if not get or isinstance(get, str) or len(get) < 2: raise CommandError('when using "groups" the "get" argument ' 'must be specified and contain at least ' 'two keys') options = {'groups': len(get) if groups else None} return self.execute_command('SORT', *pieces, **options)
[ "def", "sort", "(", "self", ",", "key", ",", "start", "=", "None", ",", "num", "=", "None", ",", "by", "=", "None", ",", "get", "=", "None", ",", "desc", "=", "False", ",", "alpha", "=", "False", ",", "store", "=", "None", ",", "groups", "=", "False", ")", ":", "if", "(", "(", "start", "is", "not", "None", "and", "num", "is", "None", ")", "or", "(", "num", "is", "not", "None", "and", "start", "is", "None", ")", ")", ":", "raise", "CommandError", "(", "\"``start`` and ``num`` must both be specified\"", ")", "pieces", "=", "[", "key", "]", "if", "by", "is", "not", "None", ":", "pieces", ".", "append", "(", "'BY'", ")", "pieces", ".", "append", "(", "by", ")", "if", "start", "is", "not", "None", "and", "num", "is", "not", "None", ":", "pieces", ".", "append", "(", "'LIMIT'", ")", "pieces", ".", "append", "(", "start", ")", "pieces", ".", "append", "(", "num", ")", "if", "get", "is", "not", "None", ":", "# If get is a string assume we want to get a single value.", "# Otherwise assume it's an interable and we want to get multiple", "# values. We can't just iterate blindly because strings are", "# iterable.", "if", "isinstance", "(", "get", ",", "str", ")", ":", "pieces", ".", "append", "(", "'GET'", ")", "pieces", ".", "append", "(", "get", ")", "else", ":", "for", "g", "in", "get", ":", "pieces", ".", "append", "(", "'GET'", ")", "pieces", ".", "append", "(", "g", ")", "if", "desc", ":", "pieces", ".", "append", "(", "'DESC'", ")", "if", "alpha", ":", "pieces", ".", "append", "(", "'ALPHA'", ")", "if", "store", "is", "not", "None", ":", "pieces", ".", "append", "(", "'STORE'", ")", "pieces", ".", "append", "(", "store", ")", "if", "groups", ":", "if", "not", "get", "or", "isinstance", "(", "get", ",", "str", ")", "or", "len", "(", "get", ")", "<", "2", ":", "raise", "CommandError", "(", "'when using \"groups\" the \"get\" argument '", "'must be specified and contain at least '", "'two keys'", ")", "options", "=", "{", "'groups'", ":", "len", "(", "get", ")", "if", "groups", "else", "None", "}", "return", "self", ".", "execute_command", "(", "'SORT'", ",", "*", "pieces", ",", "*", "*", "options", ")" ]
Sort and return the list, set or sorted set at ``key``. ``start`` and ``num`` allow for paging through the sorted data ``by`` allows using an external key to weight and sort the items. Use an "*" to indicate where in the key the item value is located ``get`` allows for returning items from external keys rather than the sorted data itself. Use an "*" to indicate where int he key the item value is located ``desc`` allows for reversing the sort ``alpha`` allows for sorting lexicographically rather than numerically ``store`` allows for storing the result of the sort into the key ``store`` ``groups`` if set to True and if ``get`` contains at least two elements, sort will return a list of tuples, each containing the values fetched from the arguments to ``get``.
[ "Sort", "and", "return", "the", "list", "set", "or", "sorted", "set", "at", "key", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/client.py#L434-L498
231,283
quantmind/pulsar
pulsar/apps/data/redis/client.py
Pipeline.commit
def commit(self, raise_on_error=True): '''Send commands to redis. ''' cmds = list(chain([(('multi',), {})], self.command_stack, [(('exec',), {})])) self.reset() return self.store.execute_pipeline(cmds, raise_on_error)
python
def commit(self, raise_on_error=True): '''Send commands to redis. ''' cmds = list(chain([(('multi',), {})], self.command_stack, [(('exec',), {})])) self.reset() return self.store.execute_pipeline(cmds, raise_on_error)
[ "def", "commit", "(", "self", ",", "raise_on_error", "=", "True", ")", ":", "cmds", "=", "list", "(", "chain", "(", "[", "(", "(", "'multi'", ",", ")", ",", "{", "}", ")", "]", ",", "self", ".", "command_stack", ",", "[", "(", "(", "'exec'", ",", ")", ",", "{", "}", ")", "]", ")", ")", "self", ".", "reset", "(", ")", "return", "self", ".", "store", ".", "execute_pipeline", "(", "cmds", ",", "raise_on_error", ")" ]
Send commands to redis.
[ "Send", "commands", "to", "redis", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/data/redis/client.py#L533-L539
231,284
quantmind/pulsar
pulsar/utils/config.py
Config.copy_globals
def copy_globals(self, cfg): """Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified. """ for name, setting in cfg.settings.items(): csetting = self.settings.get(name) if (setting.is_global and csetting is not None and not csetting.modified): csetting.set(setting.get())
python
def copy_globals(self, cfg): """Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified. """ for name, setting in cfg.settings.items(): csetting = self.settings.get(name) if (setting.is_global and csetting is not None and not csetting.modified): csetting.set(setting.get())
[ "def", "copy_globals", "(", "self", ",", "cfg", ")", ":", "for", "name", ",", "setting", "in", "cfg", ".", "settings", ".", "items", "(", ")", ":", "csetting", "=", "self", ".", "settings", ".", "get", "(", "name", ")", "if", "(", "setting", ".", "is_global", "and", "csetting", "is", "not", "None", "and", "not", "csetting", ".", "modified", ")", ":", "csetting", ".", "set", "(", "setting", ".", "get", "(", ")", ")" ]
Copy global settings from ``cfg`` to this config. The settings are copied only if they were not already modified.
[ "Copy", "global", "settings", "from", "cfg", "to", "this", "config", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L197-L206
231,285
quantmind/pulsar
pulsar/utils/config.py
Config.parse_command_line
def parse_command_line(self, argv=None): """Parse the command line """ if self.config: parser = argparse.ArgumentParser(add_help=False) self.settings['config'].add_argument(parser) opts, _ = parser.parse_known_args(argv) if opts.config is not None: self.set('config', opts.config) self.params.update(self.import_from_module()) parser = self.parser() opts = parser.parse_args(argv) for k, v in opts.__dict__.items(): if v is None: continue self.set(k.lower(), v)
python
def parse_command_line(self, argv=None): """Parse the command line """ if self.config: parser = argparse.ArgumentParser(add_help=False) self.settings['config'].add_argument(parser) opts, _ = parser.parse_known_args(argv) if opts.config is not None: self.set('config', opts.config) self.params.update(self.import_from_module()) parser = self.parser() opts = parser.parse_args(argv) for k, v in opts.__dict__.items(): if v is None: continue self.set(k.lower(), v)
[ "def", "parse_command_line", "(", "self", ",", "argv", "=", "None", ")", ":", "if", "self", ".", "config", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "add_help", "=", "False", ")", "self", ".", "settings", "[", "'config'", "]", ".", "add_argument", "(", "parser", ")", "opts", ",", "_", "=", "parser", ".", "parse_known_args", "(", "argv", ")", "if", "opts", ".", "config", "is", "not", "None", ":", "self", ".", "set", "(", "'config'", ",", "opts", ".", "config", ")", "self", ".", "params", ".", "update", "(", "self", ".", "import_from_module", "(", ")", ")", "parser", "=", "self", ".", "parser", "(", ")", "opts", "=", "parser", ".", "parse_args", "(", "argv", ")", "for", "k", ",", "v", "in", "opts", ".", "__dict__", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "continue", "self", ".", "set", "(", "k", ".", "lower", "(", ")", ",", "v", ")" ]
Parse the command line
[ "Parse", "the", "command", "line" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/config.py#L291-L308
231,286
quantmind/pulsar
pulsar/utils/tools/text.py
num2eng
def num2eng(num): '''English representation of a number up to a trillion. ''' num = str(int(num)) # Convert to string, throw if bad number if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check return num elif num == '0': # Zero is a special case return 'zero' pron = [] # Result accumulator first = True for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')): num = ''.join(reversed(bits)) n = int(num) bits = [] if n > 99: # Got hundred bits.append('%s hundred' % _SMALL[num[0]]) num = num[1:] n = int(num) num = str(n) if (n > 20) and (n != (n // 10 * 10)): bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]])) elif n: bits.append(_SMALL[num]) if len(bits) == 2 and first: first = False p = ' and '.join(bits) else: p = ' '.join(bits) if p and pr: p = '%s %s' % (p, pr) pron.append(p) return ', '.join(reversed(pron))
python
def num2eng(num): '''English representation of a number up to a trillion. ''' num = str(int(num)) # Convert to string, throw if bad number if (len(num) / 3 >= len(_PRONOUNCE)): # Sanity check return num elif num == '0': # Zero is a special case return 'zero' pron = [] # Result accumulator first = True for pr, bits in zip(_PRONOUNCE, grouper(3, reversed(num), '')): num = ''.join(reversed(bits)) n = int(num) bits = [] if n > 99: # Got hundred bits.append('%s hundred' % _SMALL[num[0]]) num = num[1:] n = int(num) num = str(n) if (n > 20) and (n != (n // 10 * 10)): bits.append('%s %s' % (_SMALL[num[0] + '0'], _SMALL[num[1]])) elif n: bits.append(_SMALL[num]) if len(bits) == 2 and first: first = False p = ' and '.join(bits) else: p = ' '.join(bits) if p and pr: p = '%s %s' % (p, pr) pron.append(p) return ', '.join(reversed(pron))
[ "def", "num2eng", "(", "num", ")", ":", "num", "=", "str", "(", "int", "(", "num", ")", ")", "# Convert to string, throw if bad number", "if", "(", "len", "(", "num", ")", "/", "3", ">=", "len", "(", "_PRONOUNCE", ")", ")", ":", "# Sanity check", "return", "num", "elif", "num", "==", "'0'", ":", "# Zero is a special case", "return", "'zero'", "pron", "=", "[", "]", "# Result accumulator", "first", "=", "True", "for", "pr", ",", "bits", "in", "zip", "(", "_PRONOUNCE", ",", "grouper", "(", "3", ",", "reversed", "(", "num", ")", ",", "''", ")", ")", ":", "num", "=", "''", ".", "join", "(", "reversed", "(", "bits", ")", ")", "n", "=", "int", "(", "num", ")", "bits", "=", "[", "]", "if", "n", ">", "99", ":", "# Got hundred", "bits", ".", "append", "(", "'%s hundred'", "%", "_SMALL", "[", "num", "[", "0", "]", "]", ")", "num", "=", "num", "[", "1", ":", "]", "n", "=", "int", "(", "num", ")", "num", "=", "str", "(", "n", ")", "if", "(", "n", ">", "20", ")", "and", "(", "n", "!=", "(", "n", "//", "10", "*", "10", ")", ")", ":", "bits", ".", "append", "(", "'%s %s'", "%", "(", "_SMALL", "[", "num", "[", "0", "]", "+", "'0'", "]", ",", "_SMALL", "[", "num", "[", "1", "]", "]", ")", ")", "elif", "n", ":", "bits", ".", "append", "(", "_SMALL", "[", "num", "]", ")", "if", "len", "(", "bits", ")", "==", "2", "and", "first", ":", "first", "=", "False", "p", "=", "' and '", ".", "join", "(", "bits", ")", "else", ":", "p", "=", "' '", ".", "join", "(", "bits", ")", "if", "p", "and", "pr", ":", "p", "=", "'%s %s'", "%", "(", "p", ",", "pr", ")", "pron", ".", "append", "(", "p", ")", "return", "', '", ".", "join", "(", "reversed", "(", "pron", ")", ")" ]
English representation of a number up to a trillion.
[ "English", "representation", "of", "a", "number", "up", "to", "a", "trillion", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/text.py#L48-L79
231,287
quantmind/pulsar
pulsar/apps/rpc/jsonrpc.py
JsonProxy.get_params
def get_params(self, *args, **kwargs): ''' Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible. ''' kwargs.update(self._data) if args and kwargs: raise ValueError('Cannot mix positional and named parameters') if args: return list(args) else: return kwargs
python
def get_params(self, *args, **kwargs): ''' Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible. ''' kwargs.update(self._data) if args and kwargs: raise ValueError('Cannot mix positional and named parameters') if args: return list(args) else: return kwargs
[ "def", "get_params", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_data", ")", "if", "args", "and", "kwargs", ":", "raise", "ValueError", "(", "'Cannot mix positional and named parameters'", ")", "if", "args", ":", "return", "list", "(", "args", ")", "else", ":", "return", "kwargs" ]
Create an array or positional or named parameters Mixing positional and named parameters in one call is not possible.
[ "Create", "an", "array", "or", "positional", "or", "named", "parameters", "Mixing", "positional", "and", "named", "parameters", "in", "one", "call", "is", "not", "possible", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/rpc/jsonrpc.py#L253-L265
231,288
quantmind/pulsar
pulsar/async/mailbox.py
MessageConsumer.send
def send(self, command, sender, target, args, kwargs): """Used by the server to send messages to the client. Returns a future. """ command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(sender), 'target': actor_identity(target), 'args': args if args is not None else (), 'kwargs': kwargs if kwargs is not None else {}} waiter = self._loop.create_future() ack = None if command.ack: ack = create_aid() data['ack'] = ack self.pending_responses[ack] = waiter try: self.write(data) except Exception as exc: waiter.set_exception(exc) if ack: self.pending_responses.pop(ack, None) else: if not ack: waiter.set_result(None) return waiter
python
def send(self, command, sender, target, args, kwargs): """Used by the server to send messages to the client. Returns a future. """ command = get_command(command) data = {'command': command.__name__, 'id': create_aid(), 'sender': actor_identity(sender), 'target': actor_identity(target), 'args': args if args is not None else (), 'kwargs': kwargs if kwargs is not None else {}} waiter = self._loop.create_future() ack = None if command.ack: ack = create_aid() data['ack'] = ack self.pending_responses[ack] = waiter try: self.write(data) except Exception as exc: waiter.set_exception(exc) if ack: self.pending_responses.pop(ack, None) else: if not ack: waiter.set_result(None) return waiter
[ "def", "send", "(", "self", ",", "command", ",", "sender", ",", "target", ",", "args", ",", "kwargs", ")", ":", "command", "=", "get_command", "(", "command", ")", "data", "=", "{", "'command'", ":", "command", ".", "__name__", ",", "'id'", ":", "create_aid", "(", ")", ",", "'sender'", ":", "actor_identity", "(", "sender", ")", ",", "'target'", ":", "actor_identity", "(", "target", ")", ",", "'args'", ":", "args", "if", "args", "is", "not", "None", "else", "(", ")", ",", "'kwargs'", ":", "kwargs", "if", "kwargs", "is", "not", "None", "else", "{", "}", "}", "waiter", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "ack", "=", "None", "if", "command", ".", "ack", ":", "ack", "=", "create_aid", "(", ")", "data", "[", "'ack'", "]", "=", "ack", "self", ".", "pending_responses", "[", "ack", "]", "=", "waiter", "try", ":", "self", ".", "write", "(", "data", ")", "except", "Exception", "as", "exc", ":", "waiter", ".", "set_exception", "(", "exc", ")", "if", "ack", ":", "self", ".", "pending_responses", ".", "pop", "(", "ack", ",", "None", ")", "else", ":", "if", "not", "ack", ":", "waiter", ".", "set_result", "(", "None", ")", "return", "waiter" ]
Used by the server to send messages to the client. Returns a future.
[ "Used", "by", "the", "server", "to", "send", "messages", "to", "the", "client", ".", "Returns", "a", "future", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/async/mailbox.py#L156-L184
231,289
quantmind/pulsar
pulsar/utils/tools/pidfile.py
Pidfile.read
def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid except IOError: return
python
def read(self): """ Validate pidfile and make it stale if needed""" if not self.fname: return try: with open(self.fname, "r") as f: wpid = int(f.read() or 0) if wpid <= 0: return return wpid except IOError: return
[ "def", "read", "(", "self", ")", ":", "if", "not", "self", ".", "fname", ":", "return", "try", ":", "with", "open", "(", "self", ".", "fname", ",", "\"r\"", ")", "as", "f", ":", "wpid", "=", "int", "(", "f", ".", "read", "(", ")", "or", "0", ")", "if", "wpid", "<=", "0", ":", "return", "return", "wpid", "except", "IOError", ":", "return" ]
Validate pidfile and make it stale if needed
[ "Validate", "pidfile", "and", "make", "it", "stale", "if", "needed" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/pidfile.py#L54-L65
231,290
quantmind/pulsar
pulsar/apps/greenio/lock.py
GreenLock.acquire
def acquire(self, timeout=None): """Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine. """ green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') if self._local.locked: future = create_future(self._loop) self._queue.append(future) parent.switch(future) self._local.locked = green return self.locked()
python
def acquire(self, timeout=None): """Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine. """ green = getcurrent() parent = green.parent if parent is None: raise MustBeInChildGreenlet('GreenLock.acquire in main greenlet') if self._local.locked: future = create_future(self._loop) self._queue.append(future) parent.switch(future) self._local.locked = green return self.locked()
[ "def", "acquire", "(", "self", ",", "timeout", "=", "None", ")", ":", "green", "=", "getcurrent", "(", ")", "parent", "=", "green", ".", "parent", "if", "parent", "is", "None", ":", "raise", "MustBeInChildGreenlet", "(", "'GreenLock.acquire in main greenlet'", ")", "if", "self", ".", "_local", ".", "locked", ":", "future", "=", "create_future", "(", "self", ".", "_loop", ")", "self", ".", "_queue", ".", "append", "(", "future", ")", "parent", ".", "switch", "(", "future", ")", "self", ".", "_local", ".", "locked", "=", "green", "return", "self", ".", "locked", "(", ")" ]
Acquires the lock if in the unlocked state otherwise switch back to the parent coroutine.
[ "Acquires", "the", "lock", "if", "in", "the", "unlocked", "state", "otherwise", "switch", "back", "to", "the", "parent", "coroutine", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/greenio/lock.py#L38-L53
231,291
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.cookies
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
python
def cookies(self): """Container of request cookies """ cookies = SimpleCookie() cookie = self.environ.get('HTTP_COOKIE') if cookie: cookies.load(cookie) return cookies
[ "def", "cookies", "(", "self", ")", ":", "cookies", "=", "SimpleCookie", "(", ")", "cookie", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_COOKIE'", ")", "if", "cookie", ":", "cookies", ".", "load", "(", "cookie", ")", "return", "cookies" ]
Container of request cookies
[ "Container", "of", "request", "cookies" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L172-L179
231,292
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.data_and_files
def data_and_files(self, data=True, files=True, stream=None): """Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached. """ if self.method in ENCODE_URL_METHODS: value = {}, None else: value = self.cache.get('data_and_files') if not value: return self._data_and_files(data, files, stream) elif data and files: return value elif data: return value[0] elif files: return value[1] else: return None
python
def data_and_files(self, data=True, files=True, stream=None): """Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached. """ if self.method in ENCODE_URL_METHODS: value = {}, None else: value = self.cache.get('data_and_files') if not value: return self._data_and_files(data, files, stream) elif data and files: return value elif data: return value[0] elif files: return value[1] else: return None
[ "def", "data_and_files", "(", "self", ",", "data", "=", "True", ",", "files", "=", "True", ",", "stream", "=", "None", ")", ":", "if", "self", ".", "method", "in", "ENCODE_URL_METHODS", ":", "value", "=", "{", "}", ",", "None", "else", ":", "value", "=", "self", ".", "cache", ".", "get", "(", "'data_and_files'", ")", "if", "not", "value", ":", "return", "self", ".", "_data_and_files", "(", "data", ",", "files", ",", "stream", ")", "elif", "data", "and", "files", ":", "return", "value", "elif", "data", ":", "return", "value", "[", "0", "]", "elif", "files", ":", "return", "value", "[", "1", "]", "else", ":", "return", "None" ]
Retrieve body data. Returns a two-elements tuple of a :class:`~.MultiValueDict` containing data from the request body, and data from uploaded files. If the body data is not ready, return a :class:`~asyncio.Future` which results in the tuple. The result is cached.
[ "Retrieve", "body", "data", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L266-L292
231,293
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.get_host
def get_host(self, use_x_forwarded=True): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ): host = self.environ['HTTP_X_FORWARDED_HOST'] port = self.environ.get('HTTP_X_FORWARDED_PORT') if port and port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, port) return host elif 'HTTP_HOST' in self.environ: host = self.environ['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.environ['SERVER_NAME'] server_port = str(self.environ['SERVER_PORT']) if server_port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, server_port) return host
python
def get_host(self, use_x_forwarded=True): """Returns the HTTP host using the environment or request headers.""" # We try three options, in order of decreasing preference. if use_x_forwarded and ('HTTP_X_FORWARDED_HOST' in self.environ): host = self.environ['HTTP_X_FORWARDED_HOST'] port = self.environ.get('HTTP_X_FORWARDED_PORT') if port and port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, port) return host elif 'HTTP_HOST' in self.environ: host = self.environ['HTTP_HOST'] else: # Reconstruct the host using the algorithm from PEP 333. host = self.environ['SERVER_NAME'] server_port = str(self.environ['SERVER_PORT']) if server_port != ('443' if self.is_secure else '80'): host = '%s:%s' % (host, server_port) return host
[ "def", "get_host", "(", "self", ",", "use_x_forwarded", "=", "True", ")", ":", "# We try three options, in order of decreasing preference.", "if", "use_x_forwarded", "and", "(", "'HTTP_X_FORWARDED_HOST'", "in", "self", ".", "environ", ")", ":", "host", "=", "self", ".", "environ", "[", "'HTTP_X_FORWARDED_HOST'", "]", "port", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_X_FORWARDED_PORT'", ")", "if", "port", "and", "port", "!=", "(", "'443'", "if", "self", ".", "is_secure", "else", "'80'", ")", ":", "host", "=", "'%s:%s'", "%", "(", "host", ",", "port", ")", "return", "host", "elif", "'HTTP_HOST'", "in", "self", ".", "environ", ":", "host", "=", "self", ".", "environ", "[", "'HTTP_HOST'", "]", "else", ":", "# Reconstruct the host using the algorithm from PEP 333.", "host", "=", "self", ".", "environ", "[", "'SERVER_NAME'", "]", "server_port", "=", "str", "(", "self", ".", "environ", "[", "'SERVER_PORT'", "]", ")", "if", "server_port", "!=", "(", "'443'", "if", "self", ".", "is_secure", "else", "'80'", ")", ":", "host", "=", "'%s:%s'", "%", "(", "host", ",", "server_port", ")", "return", "host" ]
Returns the HTTP host using the environment or request headers.
[ "Returns", "the", "HTTP", "host", "using", "the", "environment", "or", "request", "headers", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L325-L342
231,294
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.get_client_address
def get_client_address(self, use_x_forwarded=True): """Obtain the client IP address """ xfor = self.environ.get('HTTP_X_FORWARDED_FOR') if use_x_forwarded and xfor: return xfor.split(',')[-1].strip() else: return self.environ['REMOTE_ADDR']
python
def get_client_address(self, use_x_forwarded=True): """Obtain the client IP address """ xfor = self.environ.get('HTTP_X_FORWARDED_FOR') if use_x_forwarded and xfor: return xfor.split(',')[-1].strip() else: return self.environ['REMOTE_ADDR']
[ "def", "get_client_address", "(", "self", ",", "use_x_forwarded", "=", "True", ")", ":", "xfor", "=", "self", ".", "environ", ".", "get", "(", "'HTTP_X_FORWARDED_FOR'", ")", "if", "use_x_forwarded", "and", "xfor", ":", "return", "xfor", ".", "split", "(", "','", ")", "[", "-", "1", "]", ".", "strip", "(", ")", "else", ":", "return", "self", ".", "environ", "[", "'REMOTE_ADDR'", "]" ]
Obtain the client IP address
[ "Obtain", "the", "client", "IP", "address" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L344-L351
231,295
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.full_path
def full_path(self, *args, **query): """Return a full path""" path = None if args: if len(args) > 1: raise TypeError("full_url() takes exactly 1 argument " "(%s given)" % len(args)) path = args[0] if not path: path = self.path elif not path.startswith('/'): path = remove_double_slash('%s/%s' % (self.path, path)) return iri_to_uri(path, query)
python
def full_path(self, *args, **query): """Return a full path""" path = None if args: if len(args) > 1: raise TypeError("full_url() takes exactly 1 argument " "(%s given)" % len(args)) path = args[0] if not path: path = self.path elif not path.startswith('/'): path = remove_double_slash('%s/%s' % (self.path, path)) return iri_to_uri(path, query)
[ "def", "full_path", "(", "self", ",", "*", "args", ",", "*", "*", "query", ")", ":", "path", "=", "None", "if", "args", ":", "if", "len", "(", "args", ")", ">", "1", ":", "raise", "TypeError", "(", "\"full_url() takes exactly 1 argument \"", "\"(%s given)\"", "%", "len", "(", "args", ")", ")", "path", "=", "args", "[", "0", "]", "if", "not", "path", ":", "path", "=", "self", ".", "path", "elif", "not", "path", ".", "startswith", "(", "'/'", ")", ":", "path", "=", "remove_double_slash", "(", "'%s/%s'", "%", "(", "self", ".", "path", ",", "path", ")", ")", "return", "iri_to_uri", "(", "path", ",", "query", ")" ]
Return a full path
[ "Return", "a", "full", "path" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L353-L365
231,296
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.absolute_uri
def absolute_uri(self, location=None, scheme=None, **query): """Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`. """ if not is_absolute_uri(location): if location or location is None: location = self.full_path(location, **query) if not scheme: scheme = self.is_secure and 'https' or 'http' base = '%s://%s' % (scheme, self.get_host()) return '%s%s' % (base, location) elif not scheme: return iri_to_uri(location) else: raise ValueError('Absolute location with scheme not valid')
python
def absolute_uri(self, location=None, scheme=None, **query): """Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`. """ if not is_absolute_uri(location): if location or location is None: location = self.full_path(location, **query) if not scheme: scheme = self.is_secure and 'https' or 'http' base = '%s://%s' % (scheme, self.get_host()) return '%s%s' % (base, location) elif not scheme: return iri_to_uri(location) else: raise ValueError('Absolute location with scheme not valid')
[ "def", "absolute_uri", "(", "self", ",", "location", "=", "None", ",", "scheme", "=", "None", ",", "*", "*", "query", ")", ":", "if", "not", "is_absolute_uri", "(", "location", ")", ":", "if", "location", "or", "location", "is", "None", ":", "location", "=", "self", ".", "full_path", "(", "location", ",", "*", "*", "query", ")", "if", "not", "scheme", ":", "scheme", "=", "self", ".", "is_secure", "and", "'https'", "or", "'http'", "base", "=", "'%s://%s'", "%", "(", "scheme", ",", "self", ".", "get_host", "(", ")", ")", "return", "'%s%s'", "%", "(", "base", ",", "location", ")", "elif", "not", "scheme", ":", "return", "iri_to_uri", "(", "location", ")", "else", ":", "raise", "ValueError", "(", "'Absolute location with scheme not valid'", ")" ]
Builds an absolute URI from ``location`` and variables available in this request. If no ``location`` is specified, the relative URI is built from :meth:`full_path`.
[ "Builds", "an", "absolute", "URI", "from", "location", "and", "variables", "available", "in", "this", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L367-L384
231,297
quantmind/pulsar
pulsar/apps/wsgi/wrappers.py
WsgiRequest.set_response_content_type
def set_response_content_type(self, response_content_types=None): '''Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match. ''' request_content_types = self.content_types if request_content_types: ct = request_content_types.best_match(response_content_types) if ct and '*' in ct: ct = None if not ct and response_content_types: raise HttpException(status=415, msg=request_content_types) self.response.content_type = ct
python
def set_response_content_type(self, response_content_types=None): '''Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match. ''' request_content_types = self.content_types if request_content_types: ct = request_content_types.best_match(response_content_types) if ct and '*' in ct: ct = None if not ct and response_content_types: raise HttpException(status=415, msg=request_content_types) self.response.content_type = ct
[ "def", "set_response_content_type", "(", "self", ",", "response_content_types", "=", "None", ")", ":", "request_content_types", "=", "self", ".", "content_types", "if", "request_content_types", ":", "ct", "=", "request_content_types", ".", "best_match", "(", "response_content_types", ")", "if", "ct", "and", "'*'", "in", "ct", ":", "ct", "=", "None", "if", "not", "ct", "and", "response_content_types", ":", "raise", "HttpException", "(", "status", "=", "415", ",", "msg", "=", "request_content_types", ")", "self", ".", "response", ".", "content_type", "=", "ct" ]
Evaluate the content type for the response to a client ``request``. The method uses the :attr:`response_content_types` parameter of accepted content types and the content types accepted by the client ``request`` and figures out the best match.
[ "Evaluate", "the", "content", "type", "for", "the", "response", "to", "a", "client", "request", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/apps/wsgi/wrappers.py#L391-L405
231,298
quantmind/pulsar
pulsar/utils/tools/arity.py
checkarity
def checkarity(func, args, kwargs, discount=0): '''Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``. ''' spec = inspect.getargspec(func) self = getattr(func, '__self__', None) if self and spec.args: discount += 1 args = list(args) defaults = list(spec.defaults or ()) len_defaults = len(defaults) len_args = len(spec.args) - discount len_args_input = len(args) minlen = len_args - len_defaults totlen = len_args_input + len(kwargs) maxlen = len_args if spec.varargs or spec.keywords: maxlen = None if not minlen: return if not spec.defaults and maxlen: start = '"{0}" takes'.format(func.__name__) else: if maxlen and totlen > maxlen: start = '"{0}" takes at most'.format(func.__name__) else: start = '"{0}" takes at least'.format(func.__name__) if totlen < minlen: return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen) elif maxlen and totlen > maxlen: return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen) # Length of parameter OK, check names if len_args_input < len_args: le = minlen - len_args_input for arg in spec.args[discount:]: if args: args.pop(0) else: if le > 0: if defaults: defaults.pop(0) elif arg not in kwargs: return ('"{0}" has missing "{1}" parameter.' .format(func.__name__, arg)) kwargs.pop(arg, None) le -= 1 if kwargs and maxlen: s = '' if len(kwargs) > 1: s = 's' p = ', '.join('"{0}"'.format(p) for p in kwargs) return ('"{0}" does not accept {1} parameter{2}.' .format(func.__name__, p, s)) elif len_args_input > len_args + len_defaults: n = len_args + len_defaults start = '"{0}" takes'.format(func.__name__) return ('{0} {1} positional parameters. {2} given.' .format(start, n, len_args_input))
python
def checkarity(func, args, kwargs, discount=0): '''Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``. ''' spec = inspect.getargspec(func) self = getattr(func, '__self__', None) if self and spec.args: discount += 1 args = list(args) defaults = list(spec.defaults or ()) len_defaults = len(defaults) len_args = len(spec.args) - discount len_args_input = len(args) minlen = len_args - len_defaults totlen = len_args_input + len(kwargs) maxlen = len_args if spec.varargs or spec.keywords: maxlen = None if not minlen: return if not spec.defaults and maxlen: start = '"{0}" takes'.format(func.__name__) else: if maxlen and totlen > maxlen: start = '"{0}" takes at most'.format(func.__name__) else: start = '"{0}" takes at least'.format(func.__name__) if totlen < minlen: return '{0} {1} parameters. {2} given.'.format(start, minlen, totlen) elif maxlen and totlen > maxlen: return '{0} {1} parameters. {2} given.'.format(start, maxlen, totlen) # Length of parameter OK, check names if len_args_input < len_args: le = minlen - len_args_input for arg in spec.args[discount:]: if args: args.pop(0) else: if le > 0: if defaults: defaults.pop(0) elif arg not in kwargs: return ('"{0}" has missing "{1}" parameter.' .format(func.__name__, arg)) kwargs.pop(arg, None) le -= 1 if kwargs and maxlen: s = '' if len(kwargs) > 1: s = 's' p = ', '.join('"{0}"'.format(p) for p in kwargs) return ('"{0}" does not accept {1} parameter{2}.' .format(func.__name__, p, s)) elif len_args_input > len_args + len_defaults: n = len_args + len_defaults start = '"{0}" takes'.format(func.__name__) return ('{0} {1} positional parameters. {2} given.' .format(start, n, len_args_input))
[ "def", "checkarity", "(", "func", ",", "args", ",", "kwargs", ",", "discount", "=", "0", ")", ":", "spec", "=", "inspect", ".", "getargspec", "(", "func", ")", "self", "=", "getattr", "(", "func", ",", "'__self__'", ",", "None", ")", "if", "self", "and", "spec", ".", "args", ":", "discount", "+=", "1", "args", "=", "list", "(", "args", ")", "defaults", "=", "list", "(", "spec", ".", "defaults", "or", "(", ")", ")", "len_defaults", "=", "len", "(", "defaults", ")", "len_args", "=", "len", "(", "spec", ".", "args", ")", "-", "discount", "len_args_input", "=", "len", "(", "args", ")", "minlen", "=", "len_args", "-", "len_defaults", "totlen", "=", "len_args_input", "+", "len", "(", "kwargs", ")", "maxlen", "=", "len_args", "if", "spec", ".", "varargs", "or", "spec", ".", "keywords", ":", "maxlen", "=", "None", "if", "not", "minlen", ":", "return", "if", "not", "spec", ".", "defaults", "and", "maxlen", ":", "start", "=", "'\"{0}\" takes'", ".", "format", "(", "func", ".", "__name__", ")", "else", ":", "if", "maxlen", "and", "totlen", ">", "maxlen", ":", "start", "=", "'\"{0}\" takes at most'", ".", "format", "(", "func", ".", "__name__", ")", "else", ":", "start", "=", "'\"{0}\" takes at least'", ".", "format", "(", "func", ".", "__name__", ")", "if", "totlen", "<", "minlen", ":", "return", "'{0} {1} parameters. {2} given.'", ".", "format", "(", "start", ",", "minlen", ",", "totlen", ")", "elif", "maxlen", "and", "totlen", ">", "maxlen", ":", "return", "'{0} {1} parameters. {2} given.'", ".", "format", "(", "start", ",", "maxlen", ",", "totlen", ")", "# Length of parameter OK, check names", "if", "len_args_input", "<", "len_args", ":", "le", "=", "minlen", "-", "len_args_input", "for", "arg", "in", "spec", ".", "args", "[", "discount", ":", "]", ":", "if", "args", ":", "args", ".", "pop", "(", "0", ")", "else", ":", "if", "le", ">", "0", ":", "if", "defaults", ":", "defaults", ".", "pop", "(", "0", ")", "elif", "arg", "not", "in", "kwargs", ":", "return", "(", "'\"{0}\" has missing \"{1}\" parameter.'", ".", "format", "(", "func", ".", "__name__", ",", "arg", ")", ")", "kwargs", ".", "pop", "(", "arg", ",", "None", ")", "le", "-=", "1", "if", "kwargs", "and", "maxlen", ":", "s", "=", "''", "if", "len", "(", "kwargs", ")", ">", "1", ":", "s", "=", "'s'", "p", "=", "', '", ".", "join", "(", "'\"{0}\"'", ".", "format", "(", "p", ")", "for", "p", "in", "kwargs", ")", "return", "(", "'\"{0}\" does not accept {1} parameter{2}.'", ".", "format", "(", "func", ".", "__name__", ",", "p", ",", "s", ")", ")", "elif", "len_args_input", ">", "len_args", "+", "len_defaults", ":", "n", "=", "len_args", "+", "len_defaults", "start", "=", "'\"{0}\" takes'", ".", "format", "(", "func", ".", "__name__", ")", "return", "(", "'{0} {1} positional parameters. {2} given.'", ".", "format", "(", "start", ",", "n", ",", "len_args_input", ")", ")" ]
Check if arguments respect a given function arity and return an error message if the check did not pass, otherwise it returns ``None``. :parameter func: the function. :parameter args: function arguments. :parameter kwargs: function key-valued parameters. :parameter discount: optional integer which discount the number of positional argument to check. Default ``0``.
[ "Check", "if", "arguments", "respect", "a", "given", "function", "arity", "and", "return", "an", "error", "message", "if", "the", "check", "did", "not", "pass", "otherwise", "it", "returns", "None", "." ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/pulsar/utils/tools/arity.py#L6-L73
231,299
quantmind/pulsar
docs/_ext/sphinxtogithub.py
sphinx_extension
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if exception: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Exception raised in main build, doing nothing.") return dir_helper = DirHelper( os.path.isdir, os.listdir, os.walk, shutil.rmtree ) file_helper = FileSystemHelper( open, os.path.join, shutil.move, os.path.exists ) operations_factory = OperationsFactory() handler_factory = HandlerFactory() layout_factory = LayoutFactory( operations_factory, handler_factory, file_helper, dir_helper, app.config.sphinx_to_github_verbose, sys.stdout, force=True ) layout = layout_factory.create_layout(app.outdir) layout.process()
python
def sphinx_extension(app, exception): "Wrapped up as a Sphinx Extension" if not app.builder.name in ("html", "dirhtml"): return if not app.config.sphinx_to_github: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Disabled, doing nothing.") return if exception: if app.config.sphinx_to_github_verbose: print("Sphinx-to-github: Exception raised in main build, doing nothing.") return dir_helper = DirHelper( os.path.isdir, os.listdir, os.walk, shutil.rmtree ) file_helper = FileSystemHelper( open, os.path.join, shutil.move, os.path.exists ) operations_factory = OperationsFactory() handler_factory = HandlerFactory() layout_factory = LayoutFactory( operations_factory, handler_factory, file_helper, dir_helper, app.config.sphinx_to_github_verbose, sys.stdout, force=True ) layout = layout_factory.create_layout(app.outdir) layout.process()
[ "def", "sphinx_extension", "(", "app", ",", "exception", ")", ":", "if", "not", "app", ".", "builder", ".", "name", "in", "(", "\"html\"", ",", "\"dirhtml\"", ")", ":", "return", "if", "not", "app", ".", "config", ".", "sphinx_to_github", ":", "if", "app", ".", "config", ".", "sphinx_to_github_verbose", ":", "print", "(", "\"Sphinx-to-github: Disabled, doing nothing.\"", ")", "return", "if", "exception", ":", "if", "app", ".", "config", ".", "sphinx_to_github_verbose", ":", "print", "(", "\"Sphinx-to-github: Exception raised in main build, doing nothing.\"", ")", "return", "dir_helper", "=", "DirHelper", "(", "os", ".", "path", ".", "isdir", ",", "os", ".", "listdir", ",", "os", ".", "walk", ",", "shutil", ".", "rmtree", ")", "file_helper", "=", "FileSystemHelper", "(", "open", ",", "os", ".", "path", ".", "join", ",", "shutil", ".", "move", ",", "os", ".", "path", ".", "exists", ")", "operations_factory", "=", "OperationsFactory", "(", ")", "handler_factory", "=", "HandlerFactory", "(", ")", "layout_factory", "=", "LayoutFactory", "(", "operations_factory", ",", "handler_factory", ",", "file_helper", ",", "dir_helper", ",", "app", ".", "config", ".", "sphinx_to_github_verbose", ",", "sys", ".", "stdout", ",", "force", "=", "True", ")", "layout", "=", "layout_factory", ".", "create_layout", "(", "app", ".", "outdir", ")", "layout", ".", "process", "(", ")" ]
Wrapped up as a Sphinx Extension
[ "Wrapped", "up", "as", "a", "Sphinx", "Extension" ]
fee44e871954aa6ca36d00bb5a3739abfdb89b26
https://github.com/quantmind/pulsar/blob/fee44e871954aa6ca36d00bb5a3739abfdb89b26/docs/_ext/sphinxtogithub.py#L242-L285