signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def crawl_up(arg):<EOL>
dir, mod = os.path.split(arg)<EOL>mod = strip_py(mod) or mod<EOL>while dir and get_init_file(dir):<EOL><INDENT>dir, base = os.path.split(dir)<EOL>if not base:<EOL><INDENT>break<EOL><DEDENT>if mod == '<STR_LIT>' or not mod:<EOL><INDENT>mod = base<EOL><DEDENT>else:<EOL><INDENT>mod = base + '<STR_LIT:.>' + mod<EOL><DEDENT><DEDENT>return dir, mod<EOL>
Given a .py[i] filename, return (root directory, module). We crawl up the path until we find a directory without __init__.py[i], or until we run out of path components.
f14139:m0
def strip_py(arg):<EOL>
for ext in PY_EXTENSIONS:<EOL><INDENT>if arg.endswith(ext):<EOL><INDENT>return arg[:-len(ext)]<EOL><DEDENT><DEDENT>return None<EOL>
Strip a trailing .py or .pyi suffix. Return None if no such suffix is found.
f14139:m1
def get_init_file(dir):<EOL>
for ext in PY_EXTENSIONS:<EOL><INDENT>f = os.path.join(dir, '<STR_LIT>' + ext)<EOL>if os.path.isfile(f):<EOL><INDENT>return f<EOL><DEDENT><DEDENT>return None<EOL>
Check whether a directory contains a file named __init__.py[i]. If so, return the file's name (with dir prefixed). If not, return None. This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS).
f14139:m2
def get_funcname(name, node):<EOL>
funcname = name.value<EOL>if node.parent and node.parent.parent:<EOL><INDENT>grand = node.parent.parent<EOL>if grand.type == syms.classdef:<EOL><INDENT>grandname = grand.children[<NUM_LIT:1>]<EOL>assert grandname.type == token.NAME, repr(name)<EOL>assert isinstance(grandname, Leaf) <EOL>funcname = grandname.value + '<STR_LIT:.>' + funcname<EOL><DEDENT><DEDENT>return funcname<EOL>
Get function name by the following rules: - function -> function_name - instance method -> ClassName.function_name
f14139:m3
def count_args(node, results):<EOL>
count = <NUM_LIT:0><EOL>selfish = False<EOL>star = False<EOL>starstar = False<EOL>args = results.get('<STR_LIT:args>')<EOL>if isinstance(args, Node):<EOL><INDENT>children = args.children<EOL><DEDENT>elif isinstance(args, Leaf):<EOL><INDENT>children = [args]<EOL><DEDENT>else:<EOL><INDENT>children = []<EOL><DEDENT>skip = False<EOL>previous_token_is_star = False<EOL>for child in children:<EOL><INDENT>if skip:<EOL><INDENT>skip = False<EOL><DEDENT>elif isinstance(child, Leaf):<EOL><INDENT>if child.type == token.STAR:<EOL><INDENT>previous_token_is_star = True<EOL><DEDENT>elif child.type == token.DOUBLESTAR:<EOL><INDENT>starstar = True<EOL><DEDENT>elif child.type == token.NAME:<EOL><INDENT>if count == <NUM_LIT:0>:<EOL><INDENT>if child.value in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>selfish = True<EOL><DEDENT><DEDENT>count += <NUM_LIT:1><EOL>if previous_token_is_star:<EOL><INDENT>star = True<EOL><DEDENT><DEDENT>elif child.type == token.EQUAL:<EOL><INDENT>skip = True<EOL><DEDENT>if child.type != token.STAR:<EOL><INDENT>previous_token_is_star = False<EOL><DEDENT><DEDENT><DEDENT>return count, selfish, star, starstar<EOL>
Count arguments and check for self and *args, **kwds. Return (selfish, count, star, starstar) where: - count is total number of args (including *args, **kwds) - selfish is True if the initial arg is named 'self' or 'cls' - star is True iff *args is found - starstar is True iff **kwds is found
f14139:m4
def dump_annotations(type_info, files):
with open(type_info) as f:<EOL><INDENT>data = json.load(f)<EOL><DEDENT>for item in data:<EOL><INDENT>path, line, func_name = item['<STR_LIT:path>'], item['<STR_LIT>'], item['<STR_LIT>']<EOL>if files and path not in files:<EOL><INDENT>for f in files:<EOL><INDENT>if path.startswith(os.path.join(f, '<STR_LIT>')):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>continue <EOL><DEDENT><DEDENT>print("<STR_LIT>" % (path, line, func_name))<EOL>type_comments = item['<STR_LIT>']<EOL>signature = unify_type_comments(type_comments)<EOL>arg_types = signature['<STR_LIT>']<EOL>return_type = signature['<STR_LIT>']<EOL>print("<STR_LIT>" % ("<STR_LIT:U+002CU+0020>".join(arg_types), return_type))<EOL><DEDENT>
Dump annotations out of type_info, filtered by files. If files is non-empty, only dump items either if the path in the item matches one of the files exactly, or else if one of the files is a path prefix of the path.
f14146:m0
def generate_annotations_json_string(source_path, only_simple=False):<EOL>
items = parse_json(source_path)<EOL>results = []<EOL>for item in items:<EOL><INDENT>signature = unify_type_comments(item.type_comments)<EOL>if is_signature_simple(signature) or not only_simple:<EOL><INDENT>data = {<EOL>'<STR_LIT:path>': item.path,<EOL>'<STR_LIT>': item.line,<EOL>'<STR_LIT>': item.func_name,<EOL>'<STR_LIT>': signature,<EOL>'<STR_LIT>': item.samples<EOL>} <EOL>results.append(data)<EOL><DEDENT><DEDENT>return results<EOL>
Produce annotation data JSON file from a JSON file with runtime-collected types. Data formats: * The source JSON is a list of pyannotate_tools.annotations.parse.RawEntry items. * The output JSON is a list of FunctionData items.
f14147:m2
def generate_annotations_json(source_path, target_path, only_simple=False):<EOL>
results = generate_annotations_json_string(source_path, only_simple=only_simple)<EOL>with open(target_path, '<STR_LIT:w>') as f:<EOL><INDENT>json.dump(results, f, sort_keys=True, indent=<NUM_LIT:4>)<EOL><DEDENT>
Like generate_annotations_json_string() but writes JSON to a file.
f14147:m3
def infer_annotation(type_comments):<EOL>
assert type_comments<EOL>args = {} <EOL>returns = set()<EOL>for comment in type_comments:<EOL><INDENT>arg_types, return_type = parse_type_comment(comment)<EOL>for i, arg_type in enumerate(arg_types):<EOL><INDENT>args.setdefault(i, set()).add(arg_type)<EOL><DEDENT>returns.add(return_type)<EOL><DEDENT>combined_args = []<EOL>for i in sorted(args):<EOL><INDENT>arg_infos = list(args[i])<EOL>kind = argument_kind(arg_infos)<EOL>if kind is None:<EOL><INDENT>raise InferError('<STR_LIT>' + '<STR_LIT:\n>'.join(type_comments))<EOL><DEDENT>types = [arg.type for arg in arg_infos]<EOL>combined = combine_types(types)<EOL>if str(combined) == '<STR_LIT:None>':<EOL><INDENT>combined = UnionType([ClassType('<STR_LIT:None>'), AnyType()])<EOL><DEDENT>if kind != ARG_POS and (len(str(combined)) > <NUM_LIT> or isinstance(combined, UnionType)):<EOL><INDENT>combined = AnyType()<EOL><DEDENT>combined_args.append(Argument(combined, kind))<EOL><DEDENT>combined_return = combine_types(returns)<EOL>return combined_args, combined_return<EOL>
Given some type comments, return a single inferred signature. Args: type_comments: Strings of form '(arg1, ... argN) -> ret' Returns: Tuple of (argument types and kinds, return type).
f14149:m0
def argument_kind(args):<EOL>
kinds = set(arg.kind for arg in args)<EOL>if len(kinds) != <NUM_LIT:1>:<EOL><INDENT>return None<EOL><DEDENT>return kinds.pop()<EOL>
Return the kind of an argument, based on one or more descriptions of the argument. Return None if every item does not have the same kind.
f14149:m1
def combine_types(types):<EOL>
items = simplify_types(types)<EOL>if len(items) == <NUM_LIT:1>:<EOL><INDENT>return items[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>return UnionType(items)<EOL><DEDENT>
Given some types, return a combined and simplified type. For example, if given 'int' and 'List[int]', return Union[int, List[int]]. If given 'int' and 'int', return just 'int'.
f14149:m2
def simplify_types(types):<EOL>
flattened = flatten_types(types)<EOL>items = filter_ignored_items(flattened)<EOL>items = [simplify_recursive(item) for item in items]<EOL>items = merge_items(items)<EOL>items = dedupe_types(items)<EOL>items = remove_redundant_items(items)<EOL>if len(items) > <NUM_LIT:3>:<EOL><INDENT>return [AnyType()]<EOL><DEDENT>else:<EOL><INDENT>return items<EOL><DEDENT>
Given some types, give simplified types representing the union of types.
f14149:m3
def simplify_recursive(typ):<EOL>
if isinstance(typ, UnionType):<EOL><INDENT>return combine_types(typ.items)<EOL><DEDENT>elif isinstance(typ, ClassType):<EOL><INDENT>simplified = ClassType(typ.name, [simplify_recursive(arg) for arg in typ.args])<EOL>args = simplified.args<EOL>if (simplified.name == '<STR_LIT>' and len(args) == <NUM_LIT:2><EOL>and isinstance(args[<NUM_LIT:0>], ClassType) and args[<NUM_LIT:0>].name in ('<STR_LIT:str>', '<STR_LIT>')<EOL>and isinstance(args[<NUM_LIT:1>], UnionType) and not is_optional(args[<NUM_LIT:1>])):<EOL><INDENT>return ClassType('<STR_LIT>', [args[<NUM_LIT:0>], AnyType()])<EOL><DEDENT>return simplified<EOL><DEDENT>elif isinstance(typ, TupleType):<EOL><INDENT>return TupleType([simplify_recursive(item) for item in typ.items])<EOL><DEDENT>return typ<EOL>
Simplify all components of a type.
f14149:m4
def remove_redundant_items(items):<EOL>
result = []<EOL>for item in items:<EOL><INDENT>for other in items:<EOL><INDENT>if item is not other and is_redundant_union_item(item, other):<EOL><INDENT>break<EOL><DEDENT><DEDENT>else:<EOL><INDENT>result.append(item)<EOL><DEDENT><DEDENT>return result<EOL>
Filter out redundant union items.
f14149:m8
def is_redundant_union_item(first, other):<EOL>
if isinstance(first, ClassType) and isinstance(other, ClassType):<EOL><INDENT>if first.name == '<STR_LIT:str>' and other.name == '<STR_LIT>':<EOL><INDENT>return True<EOL><DEDENT>elif first.name == '<STR_LIT:bool>' and other.name == '<STR_LIT:int>':<EOL><INDENT>return True<EOL><DEDENT>elif first.name == '<STR_LIT:int>' and other.name == '<STR_LIT:float>':<EOL><INDENT>return True<EOL><DEDENT>elif (first.name in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>') and<EOL>other.name == first.name):<EOL><INDENT>if not first.args and other.args:<EOL><INDENT>return True<EOL><DEDENT>elif len(first.args) == len(other.args) and first.args:<EOL><INDENT>result = all(first_arg == other_arg or other_arg == AnyType()<EOL>for first_arg, other_arg<EOL>in zip(first.args, other.args))<EOL>return result<EOL><DEDENT><DEDENT><DEDENT>return False<EOL>
If union has both items, is the first one redundant? For example, if first is 'str' and the other is 'Text', return True. If items are equal, return False.
f14149:m9
def merge_items(items):<EOL>
result = []<EOL>while items:<EOL><INDENT>item = items.pop()<EOL>merged = None<EOL>for i, other in enumerate(items):<EOL><INDENT>merged = merged_type(item, other)<EOL>if merged:<EOL><INDENT>break<EOL><DEDENT><DEDENT>if merged:<EOL><INDENT>del items[i]<EOL>items.append(merged)<EOL><DEDENT>else:<EOL><INDENT>result.append(item)<EOL><DEDENT><DEDENT>return list(reversed(result))<EOL>
Merge union items that can be merged.
f14149:m10
def merged_type(t, s):<EOL>
if isinstance(t, TupleType) and isinstance(s, TupleType):<EOL><INDENT>if len(t.items) == len(s.items):<EOL><INDENT>return TupleType([combine_types([ti, si]) for ti, si in zip(t.items, s.items)])<EOL><DEDENT>all_items = t.items + s.items<EOL>if all_items and all(item == all_items[<NUM_LIT:0>] for item in all_items[<NUM_LIT:1>:]):<EOL><INDENT>return ClassType('<STR_LIT>', [all_items[<NUM_LIT:0>]])<EOL><DEDENT><DEDENT>elif (isinstance(t, TupleType) and isinstance(s, ClassType) and s.name == '<STR_LIT>'<EOL>and len(s.args) == <NUM_LIT:1>):<EOL><INDENT>if all(item == s.args[<NUM_LIT:0>] for item in t.items):<EOL><INDENT>return s<EOL><DEDENT><DEDENT>elif isinstance(s, TupleType) and isinstance(t, ClassType) and t.name == '<STR_LIT>':<EOL><INDENT>return merged_type(s, t)<EOL><DEDENT>elif isinstance(s, NoReturnType):<EOL><INDENT>return t<EOL><DEDENT>elif isinstance(t, NoReturnType):<EOL><INDENT>return s<EOL><DEDENT>elif isinstance(s, AnyType):<EOL><INDENT>return t<EOL><DEDENT>elif isinstance(t, AnyType):<EOL><INDENT>return s<EOL><DEDENT>return None<EOL>
Return merged type if two items can be merged in to a different, more general type. Return None if merging is not possible.
f14149:m11
def parse_json(path):<EOL>
with open(path) as f:<EOL><INDENT>data = json.load(f) <EOL><DEDENT>result = []<EOL>def assert_type(value, typ):<EOL><INDENT>assert isinstance(value, typ), '<STR_LIT>' % (path, type(value).__name__)<EOL><DEDENT>def assert_dict_item(dictionary, key, typ):<EOL><INDENT>assert key in dictionary, '<STR_LIT>' % (path, key)<EOL>value = dictionary[key]<EOL>assert isinstance(value, typ), '<STR_LIT>' % (<EOL>path, type(value).__name__, key)<EOL><DEDENT>assert_type(data, list)<EOL>for item in data:<EOL><INDENT>assert_type(item, dict)<EOL>assert_dict_item(item, '<STR_LIT:path>', Text)<EOL>assert_dict_item(item, '<STR_LIT>', int)<EOL>assert_dict_item(item, '<STR_LIT>', Text)<EOL>assert_dict_item(item, '<STR_LIT>', list)<EOL>for comment in item['<STR_LIT>']:<EOL><INDENT>assert_type(comment, Text)<EOL><DEDENT>assert_type(item['<STR_LIT>'], int)<EOL>info = FunctionInfo(encode(item['<STR_LIT:path>']),<EOL>item['<STR_LIT>'],<EOL>encode(item['<STR_LIT>']),<EOL>[encode(comment) for comment in item['<STR_LIT>']],<EOL>item['<STR_LIT>'])<EOL>result.append(info)<EOL><DEDENT>return result<EOL>
Deserialize a JSON file containing runtime collected types. The input JSON is expected to to have a list of RawEntry items.
f14150:m0
def tokenize(s):<EOL>
original = s<EOL>tokens = [] <EOL>while True:<EOL><INDENT>if not s:<EOL><INDENT>tokens.append(End())<EOL>return tokens<EOL><DEDENT>elif s[<NUM_LIT:0>] == '<STR_LIT:U+0020>':<EOL><INDENT>s = s[<NUM_LIT:1>:]<EOL><DEDENT>elif s[<NUM_LIT:0>] in '<STR_LIT>':<EOL><INDENT>tokens.append(Separator(s[<NUM_LIT:0>]))<EOL>s = s[<NUM_LIT:1>:]<EOL><DEDENT>elif s[:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>tokens.append(Separator('<STR_LIT>'))<EOL>s = s[<NUM_LIT:2>:]<EOL><DEDENT>else:<EOL><INDENT>m = re.match(r'<STR_LIT>', s)<EOL>if not m:<EOL><INDENT>raise ParseError(original)<EOL><DEDENT>fullname = m.group(<NUM_LIT:0>)<EOL>fullname = fullname.replace('<STR_LIT:U+0020>', '<STR_LIT>')<EOL>if fullname in TYPE_FIXUPS:<EOL><INDENT>fullname = TYPE_FIXUPS[fullname]<EOL><DEDENT>if fullname.startswith('<STR_LIT>'):<EOL><INDENT>fullname = '<STR_LIT>'<EOL><DEDENT>if '<STR_LIT:->' in fullname or '<STR_LIT:/>' in fullname:<EOL><INDENT>fullname = '<STR_LIT>'<EOL><DEDENT>tokens.append(DottedName(fullname))<EOL>s = s[len(m.group(<NUM_LIT:0>)):]<EOL><DEDENT><DEDENT>
Translate a type comment into a list of tokens.
f14150:m1
def parse_type_comment(comment):<EOL>
return Parser(comment).parse()<EOL>
Parse a type comment of form '(arg1, ..., argN) -> ret'.
f14150:m2
def assert_type_comments(self, func_name, comments):<EOL>
stat_items = [item for item in self.stats if item.get('<STR_LIT>') == func_name]<EOL>if not comments and not stat_items:<EOL><INDENT>return<EOL><DEDENT>assert len(stat_items) == <NUM_LIT:1><EOL>item = stat_items[<NUM_LIT:0>]<EOL>if set(item['<STR_LIT>']) != set(comments):<EOL><INDENT>print('<STR_LIT>')<EOL>for comment in sorted(item['<STR_LIT>']):<EOL><INDENT>print('<STR_LIT:U+0020>' + comment)<EOL><DEDENT>print('<STR_LIT>')<EOL>for comment in sorted(comments):<EOL><INDENT>print('<STR_LIT:U+0020>' + comment)<EOL><DEDENT>assert set(item['<STR_LIT>']) == set(comments)<EOL><DEDENT>assert len(item['<STR_LIT>']) == len(comments)<EOL>assert os.path.join(collect_types.TOP_DIR, item['<STR_LIT:path>']) == __file__<EOL>
Assert that we generated expected comment for the func_name function in self.stats
f14156:c6:m4
def foo(self, int_arg, list_arg):<EOL>
self.bar(int_arg, list_arg)<EOL>
foo
f14156:c7:m1
def bar(self, int_arg, list_arg):<EOL>
return len(self.baz(list_arg)) + int_arg<EOL>
bar
f14156:c7:m2
def baz(self, list_arg):<EOL>
return set([int(s) for s in list_arg])<EOL>
baz
f14156:c7:m3
def bar_another_thread(self, int_arg, list_arg):<EOL>
return len(self.baz_another_thread(list_arg)) + int_arg<EOL>
bar
f14156:c7:m5
def baz_another_thread(self, list_arg):<EOL>
return set([int(s) for s in list_arg])<EOL>
baz
f14156:c7:m6
def _my_hash(arg_list):<EOL>
res = <NUM_LIT:0><EOL>for arg in arg_list:<EOL><INDENT>res = res * <NUM_LIT> + hash(arg)<EOL><DEDENT>return res<EOL>
Simple helper hash function
f14157:m0
def name_from_type(type_):<EOL>
if isinstance(type_, (DictType, ListType, TupleType, SetType, IteratorType)):<EOL><INDENT>return repr(type_)<EOL><DEDENT>else:<EOL><INDENT>if type_.__name__ != '<STR_LIT>':<EOL><INDENT>module = type_.__module__<EOL>if module in BUILTIN_MODULES or module == '<STR_LIT>':<EOL><INDENT>return type_.__name__<EOL><DEDENT>else:<EOL><INDENT>name = getattr(type_, '<STR_LIT>', None) or type_.__name__<EOL>delim = '<STR_LIT:.>' if '<STR_LIT:.>' not in name else '<STR_LIT::>'<EOL>return '<STR_LIT>' % (module, delim, name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return '<STR_LIT:None>'<EOL><DEDENT><DEDENT>
Helper function to get PEP-484 compatible string representation of our internal types.
f14157:m1
def get_function_name_from_frame(frame):<EOL>
def bases_to_mro(cls, bases):<EOL><INDENT>"""<STR_LIT>"""<EOL>mro = [cls]<EOL>for base in bases:<EOL><INDENT>if base not in mro:<EOL><INDENT>mro.append(base)<EOL><DEDENT>sub_bases = getattr(base, '<STR_LIT>', None)<EOL>if sub_bases:<EOL><INDENT>sub_bases = [sb for sb in sub_bases if sb not in mro and sb not in bases]<EOL>if sub_bases:<EOL><INDENT>mro.extend(bases_to_mro(base, sub_bases))<EOL><DEDENT><DEDENT><DEDENT>return mro<EOL><DEDENT>code = frame.f_code<EOL>funcname = code.co_name<EOL>if code.co_varnames:<EOL><INDENT>varname = code.co_varnames[<NUM_LIT:0>]<EOL>if varname == '<STR_LIT>':<EOL><INDENT>inst = frame.f_locals.get(varname)<EOL>if inst is not None:<EOL><INDENT>try:<EOL><INDENT>mro = inst.__class__.__mro__<EOL><DEDENT>except AttributeError:<EOL><INDENT>mro = None<EOL>try:<EOL><INDENT>bases = inst.__class__.__bases__<EOL><DEDENT>except AttributeError:<EOL><INDENT>bases = None<EOL><DEDENT>else:<EOL><INDENT>mro = bases_to_mro(inst.__class__, bases)<EOL><DEDENT><DEDENT>if mro:<EOL><INDENT>for cls in mro:<EOL><INDENT>bare_method = cls.__dict__.get(funcname)<EOL>if bare_method and getattr(bare_method, '<STR_LIT>', None) is code:<EOL><INDENT>return '<STR_LIT>' % (cls.__name__, funcname)<EOL><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT><DEDENT>return funcname<EOL>
Heuristic to find the class-specified name by @guido For instance methods we return "ClassName.method_name" For functions we return "function_name"
f14157:m2
def resolve_type(arg):<EOL>
arg_type = type(arg)<EOL>if arg_type == list:<EOL><INDENT>assert isinstance(arg, list) <EOL>sample = arg[:min(<NUM_LIT:4>, len(arg))]<EOL>tentative_type = TentativeType()<EOL>for sample_item in sample:<EOL><INDENT>tentative_type.add(resolve_type(sample_item))<EOL><DEDENT>return ListType(tentative_type)<EOL><DEDENT>elif arg_type == set:<EOL><INDENT>assert isinstance(arg, set) <EOL>sample = []<EOL>iterator = iter(arg)<EOL>for i in range(<NUM_LIT:0>, min(<NUM_LIT:4>, len(arg))):<EOL><INDENT>sample.append(next(iterator))<EOL><DEDENT>tentative_type = TentativeType()<EOL>for sample_item in sample:<EOL><INDENT>tentative_type.add(resolve_type(sample_item))<EOL><DEDENT>return SetType(tentative_type)<EOL><DEDENT>elif arg_type == FakeIterator:<EOL><INDENT>assert isinstance(arg, FakeIterator) <EOL>sample = []<EOL>iterator = iter(arg)<EOL>for i in range(<NUM_LIT:0>, min(<NUM_LIT:4>, len(arg))):<EOL><INDENT>sample.append(next(iterator))<EOL><DEDENT>tentative_type = TentativeType()<EOL>for sample_item in sample:<EOL><INDENT>tentative_type.add(resolve_type(sample_item))<EOL><DEDENT>return IteratorType(tentative_type)<EOL><DEDENT>elif arg_type == tuple:<EOL><INDENT>assert isinstance(arg, tuple) <EOL>sample = list(arg[:min(<NUM_LIT:10>, len(arg))])<EOL>return TupleType([resolve_type(sample_item) for sample_item in sample])<EOL><DEDENT>elif arg_type == dict:<EOL><INDENT>assert isinstance(arg, dict) <EOL>key_tt = TentativeType()<EOL>val_tt = TentativeType()<EOL>for i, (k, v) in enumerate(iteritems(arg)):<EOL><INDENT>if i > <NUM_LIT:4>:<EOL><INDENT>break<EOL><DEDENT>key_tt.add(resolve_type(k))<EOL>val_tt.add(resolve_type(v))<EOL><DEDENT>return DictType(key_tt, val_tt)<EOL><DEDENT>else:<EOL><INDENT>return type(arg)<EOL><DEDENT>
Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve
f14157:m3
def prep_args(arg_info):<EOL>
<EOL>filtered_args = [a for a in arg_info.args if getattr(arg_info, '<STR_LIT>', None) != a]<EOL>if filtered_args and (filtered_args[<NUM_LIT:0>] in ('<STR_LIT>', '<STR_LIT>')):<EOL><INDENT>filtered_args = filtered_args[<NUM_LIT:1>:]<EOL><DEDENT>pos_args = [] <EOL>if filtered_args:<EOL><INDENT>for arg in filtered_args:<EOL><INDENT>if isinstance(arg, str) and arg in arg_info.locals:<EOL><INDENT>resolved_type = resolve_type(arg_info.locals[arg])<EOL>pos_args.append(resolved_type)<EOL><DEDENT>else:<EOL><INDENT>pos_args.append(type(UnknownType()))<EOL><DEDENT><DEDENT><DEDENT>varargs = None <EOL>if arg_info.varargs:<EOL><INDENT>varargs_tuple = arg_info.locals[arg_info.varargs]<EOL>if isinstance(varargs_tuple, tuple):<EOL><INDENT>varargs = [resolve_type(arg) for arg in varargs_tuple[:<NUM_LIT:4>]]<EOL><DEDENT><DEDENT>return ResolvedTypes(pos_args=pos_args, varargs=varargs)<EOL>
Resolve types from ArgInfo
f14157:m4
def _make_type_comment(args_info, return_type):<EOL>
if not args_info.pos_args:<EOL><INDENT>args_string = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>args_string = '<STR_LIT:U+002CU+0020>'.join([repr(t) for t in args_info.pos_args])<EOL><DEDENT>if args_info.varargs:<EOL><INDENT>varargs = '<STR_LIT>' % repr(args_info.varargs)<EOL>if args_string:<EOL><INDENT>args_string += '<STR_LIT>' % varargs<EOL><DEDENT>else:<EOL><INDENT>args_string = varargs<EOL><DEDENT><DEDENT>return_name = name_from_type(return_type)<EOL>return '<STR_LIT>' % (args_string, return_name)<EOL>
Generate a type comment of form '(arg, ...) -> ret'.
f14157:m5
def _flush_signature(key, return_type):<EOL>
signatures = collected_signatures.setdefault(key, set())<EOL>args_info = collected_args.pop(key)<EOL>if len(signatures) < MAX_ITEMS_PER_FUNCTION:<EOL><INDENT>signatures.add((args_info, return_type))<EOL><DEDENT>num_samples[key] = num_samples.get(key, <NUM_LIT:0>) + <NUM_LIT:1><EOL>
Store signature for a function. Assume that argument types have been stored previously to 'collected_args'. As the 'return_type' argument provides the return type, we now have a complete signature. As a side effect, removes the argument types for the function from 'collected_args'.
f14157:m6
def type_consumer():<EOL>
<EOL>while True:<EOL><INDENT>item = _task_queue.get()<EOL>if isinstance(item, KeyAndTypes):<EOL><INDENT>if item.key in collected_args:<EOL><INDENT>_flush_signature(item.key, UnknownType)<EOL><DEDENT>collected_args[item.key] = ArgTypes(item.types)<EOL><DEDENT>else:<EOL><INDENT>assert isinstance(item, KeyAndReturn)<EOL>if item.key in collected_args:<EOL><INDENT>_flush_signature(item.key, item.return_type)<EOL><DEDENT><DEDENT>_task_queue.task_done()<EOL><DEDENT>
Infinite loop of the type consumer thread. It gets types to process from the task query.
f14157:m7
def _make_sampling_sequence(n):<EOL>
seq = list(range(<NUM_LIT:5>))<EOL>i = <NUM_LIT:50><EOL>while len(seq) < n:<EOL><INDENT>seq.append(i)<EOL>i += <NUM_LIT:50><EOL><DEDENT>return seq<EOL>
Return a list containing the proposed call event sampling sequence. Return events are paired with call events and not counted separately. This is 0, 1, 2, ..., 4 plus 50, 100, 150, 200, etc. The total list size is n.
f14157:m8
def pause():<EOL>
<EOL>return stop()<EOL>
Deprecated, replaced by stop().
f14157:m10
def stop():<EOL>
global running <EOL>running = False<EOL>_task_queue.join()<EOL>
Start collecting type information.
f14157:m11
def resume():<EOL>
<EOL>return start()<EOL>
Deprecated, replaced by start().
f14157:m12
def start():<EOL>
global running <EOL>running = True<EOL>sampling_counters.clear()<EOL>
Stop collecting type information.
f14157:m13
def default_filter_filename(filename):<EOL>
if filename is None:<EOL><INDENT>return None<EOL><DEDENT>elif filename.startswith(TOP_DIR):<EOL><INDENT>if filename.startswith(TOP_DIR_DOT):<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return filename[TOP_DIR_LEN:].lstrip(os.sep)<EOL><DEDENT><DEDENT>elif filename.startswith(os.sep):<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>return filename<EOL><DEDENT>
Default filter for filenames. Returns either a normalized filename or None. You can pass your own filter to init_types_collection().
f14157:m14
def _trace_dispatch(frame, event, arg):<EOL>
<EOL>if not running:<EOL><INDENT>return<EOL><DEDENT>code = frame.f_code<EOL>key = id(code)<EOL>n = sampling_counters.get(key, <NUM_LIT:0>)<EOL>if n is None:<EOL><INDENT>return<EOL><DEDENT>if event == '<STR_LIT>':<EOL><INDENT>sampling_counters[key] = n + <NUM_LIT:1><EOL>if n not in sampling_sequence:<EOL><INDENT>if n > LAST_SAMPLE:<EOL><INDENT>sampling_counters[key] = None <EOL><DEDENT>call_pending.discard(key) <EOL>return<EOL><DEDENT>call_pending.add(key)<EOL><DEDENT>elif event == '<STR_LIT>':<EOL><INDENT>if key not in call_pending:<EOL><INDENT>return<EOL><DEDENT>call_pending.discard(key) <EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>filename = _filter_filename(code.co_filename)<EOL>if filename:<EOL><INDENT>func_name = get_function_name_from_frame(frame)<EOL>if not func_name or func_name[<NUM_LIT:0>] == '<STR_LIT:<>':<EOL><INDENT>sampling_counters[key] = None<EOL><DEDENT>else:<EOL><INDENT>function_key = FunctionKey(filename, code.co_firstlineno, func_name)<EOL>if event == '<STR_LIT>':<EOL><INDENT>arg_info = inspect.getargvalues(frame) <EOL>resolved_types = prep_args(arg_info)<EOL>_task_queue.put(KeyAndTypes(function_key, resolved_types))<EOL><DEDENT>elif event == '<STR_LIT>':<EOL><INDENT>last_opcode = code.co_code[frame.f_lasti]<EOL>if last_opcode == RETURN_VALUE_OPCODE:<EOL><INDENT>if code.co_flags & CO_GENERATOR:<EOL><INDENT>t = resolve_type(FakeIterator([]))<EOL><DEDENT>else:<EOL><INDENT>t = resolve_type(arg)<EOL><DEDENT><DEDENT>elif last_opcode == YIELD_VALUE_OPCODE:<EOL><INDENT>t = resolve_type(FakeIterator([arg]))<EOL><DEDENT>else:<EOL><INDENT>t = NoReturnType<EOL><DEDENT>_task_queue.put(KeyAndReturn(function_key, t))<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>sampling_counters[key] = None<EOL><DEDENT>
This is the main hook passed to setprofile(). It implement python profiler interface. Arguments are described in https://docs.python.org/2/library/sys.html#sys.settrace
f14157:m15
def _filter_types(types_dict):<EOL>
def exclude(k):<EOL><INDENT>"""<STR_LIT>"""<EOL>return k.path.startswith('<STR_LIT:<>') or k.func_name == '<STR_LIT>'<EOL><DEDENT>return {k: v for k, v in iteritems(types_dict) if not exclude(k)}<EOL>
Filter type info before dumping it to the file.
f14157:m16
def _dump_impl():<EOL>
filtered_signatures = _filter_types(collected_signatures)<EOL>sorted_by_file = sorted(iteritems(filtered_signatures),<EOL>key=(lambda p: (p[<NUM_LIT:0>].path, p[<NUM_LIT:0>].line, p[<NUM_LIT:0>].func_name)))<EOL>res = [] <EOL>for function_key, signatures in sorted_by_file:<EOL><INDENT>comments = [_make_type_comment(args, ret_type) for args, ret_type in signatures]<EOL>res.append(<EOL>{<EOL>'<STR_LIT:path>': function_key.path,<EOL>'<STR_LIT>': function_key.line,<EOL>'<STR_LIT>': function_key.func_name,<EOL>'<STR_LIT>': comments,<EOL>'<STR_LIT>': num_samples.get(function_key, <NUM_LIT:0>),<EOL>}<EOL>)<EOL><DEDENT>return res<EOL>
Internal implementation for dump_stats and dumps_stats
f14157:m17
def dump_stats(filename):<EOL>
res = _dump_impl()<EOL>f = open(filename, '<STR_LIT:w>')<EOL>json.dump(res, f, indent=<NUM_LIT:4>)<EOL>f.close()<EOL>
Write collected information to file. Args: filename: absolute filename
f14157:m18
def dumps_stats():<EOL>
res = _dump_impl()<EOL>return json.dumps(res, indent=<NUM_LIT:4>)<EOL>
Return collected information as a json string.
f14157:m19
def init_types_collection(filter_filename=default_filter_filename):<EOL>
global _filter_filename<EOL>_filter_filename = filter_filename<EOL>sys.setprofile(_trace_dispatch)<EOL>threading.setprofile(_trace_dispatch)<EOL>
Setup profiler hooks to enable type collection. Call this one time from the main thread. The optional argument is a filter that maps a filename (from code.co_filename) to either a normalized filename or None. For the default filter see default_filter_filename().
f14157:m20
def stop_types_collection():<EOL>
sys.setprofile(None)<EOL>threading.setprofile(None)<EOL>
Remove profiler hooks.
f14157:m21
def add(self, type):<EOL>
try:<EOL><INDENT>if isinstance(type, SetType):<EOL><INDENT>if EMPTY_SET_TYPE in self.types_hashable:<EOL><INDENT>self.types_hashable.remove(EMPTY_SET_TYPE)<EOL><DEDENT><DEDENT>elif isinstance(type, ListType):<EOL><INDENT>if EMPTY_LIST_TYPE in self.types_hashable:<EOL><INDENT>self.types_hashable.remove(EMPTY_LIST_TYPE)<EOL><DEDENT><DEDENT>elif isinstance(type, IteratorType):<EOL><INDENT>if EMPTY_ITERATOR_TYPE in self.types_hashable:<EOL><INDENT>self.types_hashable.remove(EMPTY_ITERATOR_TYPE)<EOL><DEDENT><DEDENT>elif isinstance(type, DictType):<EOL><INDENT>if EMPTY_DICT_TYPE in self.types_hashable:<EOL><INDENT>self.types_hashable.remove(EMPTY_DICT_TYPE)<EOL><DEDENT>for item in self.types_hashable:<EOL><INDENT>if isinstance(item, DictType):<EOL><INDENT>if item.key_type == type.key_type:<EOL><INDENT>item.val_type.merge(type.val_type)<EOL>return<EOL><DEDENT><DEDENT><DEDENT><DEDENT>self.types_hashable.add(type)<EOL><DEDENT>except (TypeError, AttributeError):<EOL><INDENT>try:<EOL><INDENT>if type not in self.types:<EOL><INDENT>self.types.append(type)<EOL><DEDENT><DEDENT>except AttributeError:<EOL><INDENT>if TypeWasIncomparable not in self.types:<EOL><INDENT>self.types.append(TypeWasIncomparable)<EOL><DEDENT><DEDENT><DEDENT>
Add type to the runtime type samples.
f14157:c9:m4
def merge(self, other):<EOL>
for hashables in other.types_hashable:<EOL><INDENT>self.add(hashables)<EOL><DEDENT>for non_hashbles in other.types:<EOL><INDENT>self.add(non_hashbles)<EOL><DEDENT>
Merge two TentativeType instances
f14157:c9:m5
def get_network_address(self):
connect_target = '<STR_LIT>'<EOL>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)<EOL>sock.connect((connect_target, <NUM_LIT>))<EOL>local_address = sock.getsockname()[<NUM_LIT:0>]<EOL>return local_address<EOL>
Since the w3af scan is run inside one docker container and the target app is run inside ANOTHER container, I need to get the address of the network interface and use that as a target. Get the "public" IP address without sending any packets. :return: The IP address of the network interface
f14160:c0:m1
def wait_until_running(self, scan):
for _ in xrange(<NUM_LIT:10>):<EOL><INDENT>time.sleep(<NUM_LIT:0.5>)<EOL>status = scan.get_status()<EOL>if status['<STR_LIT>'] == True:<EOL><INDENT>return<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>
Wait until the scan is in Running state :return: The HTTP response
f14160:c0:m2
def wait_until_finish(self, scan, wait_loops=<NUM_LIT:100>):
for _ in xrange(wait_loops):<EOL><INDENT>time.sleep(<NUM_LIT:0.5>)<EOL>status = scan.get_status()<EOL>if status['<STR_LIT>'] == False:<EOL><INDENT>return<EOL><DEDENT><DEDENT>raise RuntimeError('<STR_LIT>')<EOL>
Wait until the scan is in Stopped state :return: The HTTP response
f14160:c0:m3
def can_access_api(self):
try:<EOL><INDENT>version_dict = self.get_version()<EOL><DEDENT>except Exception as e:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise APIException(msg % e)<EOL><DEDENT>else:<EOL><INDENT>"""<STR_LIT>"""<EOL>if '<STR_LIT:version>' in version_dict:<EOL><INDENT>return True<EOL><DEDENT>msg = '<STR_LIT>'<EOL>raise APIException(msg)<EOL><DEDENT>
:return: True when we can access the REST API
f14162:c0:m1
def get_scans(self):
code, data = self.send_request('<STR_LIT>', method='<STR_LIT:GET>')<EOL>if code != <NUM_LIT:200>:<EOL><INDENT>msg = '<STR_LIT>'<EOL>raise APIException(msg % code)<EOL><DEDENT>scans = data.get('<STR_LIT>', None)<EOL>if scans is None:<EOL><INDENT>raise APIException('<STR_LIT>')<EOL><DEDENT>scan_instances = []<EOL>for scan_json in scans:<EOL><INDENT>scan_id = scan_json['<STR_LIT:id>']<EOL>scan_status = scan_json['<STR_LIT:status>']<EOL>scan = Scan(self, scan_id=scan_id, status=scan_status)<EOL>scan_instances.append(scan)<EOL><DEDENT>return scan_instances<EOL>
:return: A list with all the Scan instances available in the remote API
f14162:c0:m6
def log_entry_generator(log_instance):
current_page_num = <NUM_LIT:0><EOL>while True:<EOL><INDENT>has_results = False<EOL>for log_entry in log_instance.get_page(current_page_num):<EOL><INDENT>has_results = True<EOL>yield log_entry<EOL><DEDENT>if not has_results:<EOL><INDENT>break<EOL><DEDENT>current_page_num += <NUM_LIT:1><EOL><DEDENT>
:yield: The next LogEntry from the REST API :raise: StopIteration when there are no more log entries to show, please note that if you call this again at a later time the REST API could have different results and more data could be returned
f14173:m0
@classmethod<EOL><INDENT>def from_entry_dict(cls, entry_dict):<DEDENT>
<EOL>try:<EOL><INDENT>_type = entry_dict['<STR_LIT:type>']<EOL>_id = entry_dict['<STR_LIT:id>']<EOL>_time = entry_dict['<STR_LIT:time>']<EOL>message = entry_dict['<STR_LIT:message>']<EOL>severity = entry_dict['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>msg = ('<STR_LIT>'<EOL>'<STR_LIT>')<EOL>raise APIException(msg % json.dumps(entry_dict, indent=<NUM_LIT:4>))<EOL><DEDENT>return cls(_type, message, _time, severity, _id)<EOL>
This is a "constructor" for the LogEntry class. :param entry_dict: A dict we get from the REST API :return: An instance of LogEntry.
f14173:c0:m2
def get_by_start_id(self, start_id):
url = '<STR_LIT>' % (self.scan_id, start_id)<EOL>code, page = self.conn.send_request(url, method='<STR_LIT:GET>')<EOL>if code != <NUM_LIT:200>:<EOL><INDENT>message = page.get('<STR_LIT:message>', '<STR_LIT:None>')<EOL>args = (code, message)<EOL>raise APIException('<STR_LIT>'<EOL>'<STR_LIT>' % args)<EOL><DEDENT>entries = page.get('<STR_LIT>', None)<EOL>if entries is None:<EOL><INDENT>raise APIException('<STR_LIT>')<EOL><DEDENT>for entry_dict in entries:<EOL><INDENT>yield LogEntry.from_entry_dict(entry_dict)<EOL><DEDENT>
:yield: Log entries starting from :start_id: and ending 200 entries after. In most cases easier to call than the paginate one because there is no need to keep track of the already read entries in a specific page.
f14173:c1:m2
def get_page(self, page_number):
url = '<STR_LIT>' % (self.scan_id, page_number)<EOL>code, page = self.conn.send_request(url, method='<STR_LIT:GET>')<EOL>if code != <NUM_LIT:200>:<EOL><INDENT>message = page.get('<STR_LIT:message>', '<STR_LIT:None>')<EOL>args = (code, message)<EOL>raise APIException('<STR_LIT>'<EOL>'<STR_LIT>' % args)<EOL><DEDENT>entries = page.get('<STR_LIT>', None)<EOL>if entries is None:<EOL><INDENT>raise APIException('<STR_LIT>')<EOL><DEDENT>for entry_dict in entries:<EOL><INDENT>yield LogEntry.from_entry_dict(entry_dict)<EOL><DEDENT>
:yield: Log entries for the given page number
f14173:c1:m3
def __getattr__(self, attribute_name):
try:<EOL><INDENT>return self.resource_data[attribute_name]<EOL><DEDENT>except KeyError:<EOL><INDENT>msg = "<STR_LIT>"<EOL>raise AttributeError(msg % attribute_name)<EOL><DEDENT>
:param attribute_name: The name of the attribute to access :return: The value of that attribute according to the REST API
f14178:c0:m3
@property<EOL><INDENT>def resource_data(self):<DEDENT>
if self._data is not None:<EOL><INDENT>return self._data<EOL><DEDENT>return self.update()<EOL>
Cached access to the KB so a piece of code that accesses this finding doesn't perform one HTTP request to the REST API for each attribute :return: The JSON data
f14178:c0:m4
def stop(self, timeout=None):
assert self.scan_id is not None, '<STR_LIT>'<EOL>if timeout is None:<EOL><INDENT>url = '<STR_LIT>' % self.scan_id<EOL>self.conn.send_request(url, method='<STR_LIT:GET>')<EOL>return<EOL><DEDENT>self.stop()<EOL>for _ in xrange(timeout):<EOL><INDENT>time.sleep(<NUM_LIT:1>)<EOL>is_running = self.get_status()['<STR_LIT>']<EOL>if not is_running:<EOL><INDENT>return<EOL><DEDENT><DEDENT>msg = '<STR_LIT>'<EOL>raise ScanStopTimeoutException(msg % timeout)<EOL>
Send the GET request required to stop the scan If timeout is not specified we just send the request and return. When it is the method will wait for (at most) :timeout: seconds until the scan changes it's status/stops. If the timeout is reached then an exception is raised. :param timeout: The timeout in seconds :return: None, an exception is raised if the timeout is exceeded
f14182:c0:m4
def post(self, request):
serializer = CreateUserSerializer(data=request.data)<EOL>serializer.is_valid(raise_exception=True)<EOL>email = serializer.validated_data.get("<STR_LIT:email>")<EOL>try:<EOL><INDENT>user = User.objects.get(username=email)<EOL><DEDENT>except User.DoesNotExist:<EOL><INDENT>user = User.objects.create_user(email, email=email)<EOL><DEDENT>token, created = Token.objects.get_or_create(user=user)<EOL>return Response(status=status.HTTP_201_CREATED, data={"<STR_LIT>": token.key})<EOL>
Create a user and token, given an email. If user exists just provide the token.
f14192:c5:m0
def run(self, target, payload, instance_id=None, hook_id=None, **kwargs):
requests.post(<EOL>url=target,<EOL>data=json.dumps(payload),<EOL>headers={<EOL>"<STR_LIT:Content-Type>": "<STR_LIT:application/json>",<EOL>"<STR_LIT>": "<STR_LIT>" % settings.HOOK_AUTH_TOKEN,<EOL>},<EOL>)<EOL>
target: the url to receive the payload. payload: a python primitive data structure instance_id: a possibly None "trigger" instance ID hook_id: the ID of defining Hook object
f14194:c0:m0
def run(self, schedule_id, auth_token, endpoint, payload, **kwargs):
log = self.get_logger(**kwargs)<EOL>log.info("<STR_LIT>" % (schedule_id,))<EOL>if self.request.retries > <NUM_LIT:0>:<EOL><INDENT>retry_delay = utils.calculate_retry_delay(self.request.retries)<EOL><DEDENT>else:<EOL><INDENT>retry_delay = self.default_retry_delay<EOL><DEDENT>headers = {"<STR_LIT:Content-Type>": "<STR_LIT:application/json>"}<EOL>if auth_token is not None:<EOL><INDENT>headers["<STR_LIT>"] = "<STR_LIT>" % auth_token<EOL><DEDENT>try:<EOL><INDENT>response = requests.post(<EOL>url=endpoint,<EOL>data=json.dumps(payload),<EOL>headers=headers,<EOL>timeout=settings.DEFAULT_REQUEST_TIMEOUT,<EOL>)<EOL>response.raise_for_status()<EOL><DEDENT>except requests_exceptions.ConnectionError as exc:<EOL><INDENT>log.info("<STR_LIT>" % endpoint)<EOL>fire_metric.delay("<STR_LIT>", <NUM_LIT:1>)<EOL>self.retry(exc=exc, countdown=retry_delay)<EOL><DEDENT>except requests_exceptions.HTTPError as exc:<EOL><INDENT>log.info("<STR_LIT>" % exc.response.status_code)<EOL>metric_name = (<EOL>"<STR_LIT>" % exc.response.status_code<EOL>)<EOL>fire_metric.delay(metric_name, <NUM_LIT:1>)<EOL>self.retry(exc=exc, countdown=retry_delay)<EOL><DEDENT>except requests_exceptions.Timeout as exc:<EOL><INDENT>log.info("<STR_LIT>")<EOL>fire_metric.delay("<STR_LIT>", <NUM_LIT:1>)<EOL>self.retry(exc=exc, countdown=retry_delay)<EOL><DEDENT>return True<EOL>
Runs an instance of a scheduled task
f14194:c1:m0
def run(self, schedule_type, lookup_id, **kwargs):
log = self.get_logger(**kwargs)<EOL>log.info("<STR_LIT>" % (schedule_type, lookup_id))<EOL>task_run = QueueTaskRun()<EOL>task_run.task_id = self.request.id or uuid4()<EOL>task_run.started_at = now()<EOL>tr_qs = QueueTaskRun.objects<EOL>schedules = Schedule.objects.filter(enabled=True)<EOL>if schedule_type == "<STR_LIT>":<EOL><INDENT>schedules = schedules.filter(celery_cron_definition=lookup_id)<EOL>tr_qs = tr_qs.filter(celery_cron_definition=lookup_id)<EOL>scheduler_type = CrontabSchedule<EOL>task_run.celery_cron_definition_id = lookup_id<EOL><DEDENT>elif schedule_type == "<STR_LIT>":<EOL><INDENT>schedules = schedules.filter(celery_interval_definition=lookup_id)<EOL>tr_qs = tr_qs.filter(celery_interval_definition=lookup_id)<EOL>scheduler_type = IntervalSchedule<EOL>task_run.celery_interval_definition_id = lookup_id<EOL><DEDENT>try:<EOL><INDENT>last_task_run = tr_qs.latest("<STR_LIT>")<EOL><DEDENT>except QueueTaskRun.DoesNotExist:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>sched = scheduler_type.objects.get(id=lookup_id)<EOL>due, due_next = sched.schedule.is_due(last_task_run.started_at)<EOL>if not due and due_next >= settings.DEFAULT_CLOCK_SKEW_SECONDS:<EOL><INDENT>return (<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>% (<EOL>schedule_type,<EOL>lookup_id,<EOL>last_task_run.id,<EOL>last_task_run.started_at,<EOL>)<EOL>)<EOL><DEDENT><DEDENT>task_run.save()<EOL>queued = <NUM_LIT:0><EOL>schedules = schedules.values("<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>")<EOL>for schedule in schedules.iterator():<EOL><INDENT>schedule["<STR_LIT>"] = str(schedule.pop("<STR_LIT:id>"))<EOL>DeliverTask.apply_async(kwargs=schedule)<EOL>queued += <NUM_LIT:1><EOL><DEDENT>task_run.completed_at = now()<EOL>task_run.save()<EOL>return "<STR_LIT>" % (queued,)<EOL>
Loads Schedule linked to provided lookup
f14194:c2:m0
def run(self, **kwargs):
log = self.get_logger(**kwargs)<EOL>failures = ScheduleFailure.objects<EOL>log.info("<STR_LIT>" % failures.count())<EOL>for failure in failures.iterator():<EOL><INDENT>schedule = Schedule.objects.values(<EOL>"<STR_LIT:id>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"<EOL>)<EOL>schedule = schedule.get(id=failure.schedule_id)<EOL>schedule["<STR_LIT>"] = str(schedule.pop("<STR_LIT:id>"))<EOL>failure.delete()<EOL>DeliverTask.apply_async(kwargs=schedule)<EOL><DEDENT>
Runs an instance of a scheduled task
f14194:c4:m0
def add_metrics_response(self):
responses.add(<EOL>responses.POST, "<STR_LIT>", status=<NUM_LIT>, json={}<EOL>)<EOL>
Adds a response for any requests to the metrics API endpoint.
f14198:c6:m1
def get_version(package):
init_py = open(os.path.join(package, "<STR_LIT>")).read()<EOL>return re.search("<STR_LIT>", init_py).group(<NUM_LIT:1>)<EOL>
Return package version as listed in `__version__` in `init.py`.
f14199:m1
def calculate_retry_delay(attempt, max_delay=<NUM_LIT>):
delay = int(random.uniform(<NUM_LIT:2>, <NUM_LIT:4>) ** attempt)<EOL>if delay > max_delay:<EOL><INDENT>delay = int(random.uniform(max_delay - <NUM_LIT:20>, max_delay + <NUM_LIT:20>))<EOL><DEDENT>return delay<EOL>
Calculates an exponential backoff for retry attempts with a small amount of jitter.
f14207:m1
def internal_only(view_func):
@functools.wraps(view_func)<EOL>def wrapper(request, *args, **kwargs):<EOL><INDENT>forwards = request.META.get("<STR_LIT>", "<STR_LIT>").split("<STR_LIT:U+002C>")<EOL>if len(forwards) > <NUM_LIT:1>:<EOL><INDENT>raise PermissionDenied()<EOL><DEDENT>return view_func(request, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL>
A view decorator which blocks access for requests coming through the load balancer.
f14208:m0
def methodview(methods=(), ifnset=None, ifset=None):
return _MethodViewInfo(methods, ifnset, ifset).decorator<EOL>
Decorator to mark a method as a view. NOTE: This should be a top-level decorator! :param methods: List of HTTP verbs it works with :type methods: str|Iterable[str] :param ifnset: Conditional matching: only if the route param is not set (or is None) :type ifnset: str|Iterable[str]|None :param ifset: Conditional matching: only if the route param is set (and is not None) :type ifset: str|Iterable[str]|None
f14212:m0
def decorator(self, func):
if inspect.isfunction(func):<EOL><INDENT>func._methodview = self<EOL><DEDENT>elif inspect.ismethod(func):<EOL><INDENT>func.__func__._methodview = self<EOL><DEDENT>else:<EOL><INDENT>raise AssertionError('<STR_LIT>'.format(func))<EOL><DEDENT>return func<EOL>
Wrapper function to decorate a function
f14212:c0:m0
@classmethod<EOL><INDENT>def get_info(cls, func):<DEDENT>
try: return func._methodview<EOL>except AttributeError: return None<EOL>
:rtype: _MethodViewInfo|None
f14212:c0:m1
def matches(self, verb, params):
return (self.ifset is None or self.ifset <= params) and(self.ifnset is None or self.ifnset.isdisjoint(params)) and(self.methods is None or verb in self.methods)<EOL>
Test if the method matches the provided set of arguments :param verb: HTTP verb. Uppercase :type verb: str :param params: Existing route parameters :type params: set :returns: Whether this view matches :rtype: bool
f14212:c0:m3
def _match_view(self, method, route_params):
method = method.upper()<EOL>route_params = frozenset(k for k, v in route_params.items() if v is not None)<EOL>for view_name, info in self.methods_map[method].items():<EOL><INDENT>if info.matches(method, route_params):<EOL><INDENT>return getattr(self, view_name)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
Detect a view matching the query :param method: HTTP method :param route_params: Route parameters dict :return: Method :rtype: Callable|None
f14212:c2:m0
@classmethod<EOL><INDENT>def route_as_view(cls, app, name, rules, *class_args, **class_kwargs):<DEDENT>
view = super(MethodView, cls).as_view(name, *class_args, **class_kwargs)<EOL>for rule in rules:<EOL><INDENT>app.add_url_rule(rule, view_func=view)<EOL><DEDENT>return view<EOL>
Register the view with an URL route :param app: Flask application :type app: flask.Flask|flask.Blueprint :param name: Unique view name :type name: str :param rules: List of route rules to use :type rules: Iterable[str|werkzeug.routing.Rule] :param class_args: Args to pass to object constructor :param class_kwargs: KwArgs to pass to object constructor :return: View callable :rtype: Callable
f14212:c2:m2
def open(self, path, json=None, **kwargs):
<EOL>if json:<EOL><INDENT>kwargs['<STR_LIT:data>'] = flask.json.dumps(json)<EOL>kwargs['<STR_LIT>'] = '<STR_LIT:application/json>'<EOL>kwargs.setdefault('<STR_LIT>', '<STR_LIT:POST>')<EOL><DEDENT>rv = super(FlaskJsonClient, self).open(path, **kwargs)<EOL>'<STR_LIT>'<EOL>if rv.mimetype == '<STR_LIT:application/json>':<EOL><INDENT>response = flask.json.loads(rv.get_data())<EOL>return JsonResponse(response, rv.status_code, rv.headers)<EOL><DEDENT>return rv<EOL>
Open an URL, optionally posting JSON data :param path: URI to request :type path: str :param json: JSON data to post :param method: HTTP Method to use. 'POST' by default if data is provided :param data: Custom data to post, if required
f14213:c0:m0
def jsonapi(f):
@wraps(f)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>rv = f(*args, **kwargs)<EOL>return make_json_response(rv)<EOL><DEDENT>return wrapper<EOL>
Declare the view as a JSON API method This converts view return value into a :cls:JsonResponse. The following return types are supported: - tuple: a tuple of (response, status, headers) - any other object is converted to JSON
f14215:m0
def get_entity_propnames(entity):
ins = entity if isinstance(entity, InstanceState) else inspect(entity)<EOL>return set(<EOL>ins.mapper.column_attrs.keys() + <EOL>ins.mapper.relationships.keys() <EOL>)<EOL>
Get entity property names :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set
f14216:m0
def get_entity_loaded_propnames(entity):
ins = inspect(entity)<EOL>keynames = get_entity_propnames(ins)<EOL>if not ins.transient:<EOL><INDENT>keynames -= ins.unloaded<EOL><DEDENT>if ins.expired:<EOL><INDENT>keynames |= ins.expired_attributes<EOL><DEDENT>return keynames<EOL>
Get entity property names that are loaded (e.g. won't produce new queries) :param entity: Entity :type entity: sqlalchemy.ext.declarative.api.DeclarativeMeta :returns: Set of entity property names :rtype: set
f14216:m1
def normalize_response_value(rv):
status = headers = None<EOL>if isinstance(rv, tuple):<EOL><INDENT>rv, status, headers = rv + (None,) * (<NUM_LIT:3> - len(rv))<EOL><DEDENT>return rv, status, headers<EOL>
Normalize the response value into a 3-tuple (rv, status, headers) :type rv: tuple|* :returns: tuple(rv, status, headers) :rtype: tuple(Response|JsonResponse|*, int|None, dict|None)
f14217:m0
def make_json_response(rv):
<EOL>rv, status, headers = normalize_response_value(rv)<EOL>if isinstance(rv, JsonResponse):<EOL><INDENT>return rv<EOL><DEDENT>return JsonResponse(rv, status, headers)<EOL>
Make JsonResponse :param rv: Response: the object to encode, or tuple (response, status, headers) :type rv: tuple|* :rtype: JsonResponse
f14217:m1
def __init__(self, response, status=None, headers=None, **kwargs):
<EOL>self._response_data = self.preprocess_response_data(response)<EOL>try:<EOL><INDENT>indent = <NUM_LIT:2> if current_app.config['<STR_LIT>'] and not request.is_xhr else None<EOL><DEDENT>except RuntimeError: <EOL><INDENT>indent = None<EOL><DEDENT>super(JsonResponse, self).__init__(<EOL>json.dumps(self._response_data, indent=indent),<EOL>headers=headers, status=status, mimetype='<STR_LIT:application/json>',<EOL>direct_passthrough=True, **kwargs)<EOL>
Init a JSON response :param response: Response data :type response: * :param status: Status code :type status: int|None :param headers: Additional headers :type headers: dict|None
f14217:c0:m0
def preprocess_response_data(self, response):
return response<EOL>
Preprocess the response data. Override this method to have custom handling of the response :param response: Return value from the view function :type response: * :return: Preprocessed value
f14217:c0:m1
def get_json(self):
return self._response_data<EOL>
Get the response data object (preprocessed)
f14217:c0:m2
def __getitem__(self, item):
return self._response_data[item]<EOL>
Proxy method to get items from the underlying object
f14217:c0:m3
def data_path(name):
return os.path.join(os.path.dirname(__file__), "<STR_LIT:data>", name)<EOL>
Return the absolute path to a file in the test/data directory. The name specified should be relative to test/data.
f14223:m0
def drop_prefix(strings):
strings_without_extensions = [<EOL>s.split("<STR_LIT:.>", <NUM_LIT:2>)[<NUM_LIT:0>] for s in strings<EOL>]<EOL>if len(strings_without_extensions) == <NUM_LIT:1>:<EOL><INDENT>return [os.path.basename(strings_without_extensions[<NUM_LIT:0>])]<EOL><DEDENT>prefix_len = len(os.path.commonprefix(strings_without_extensions))<EOL>result = [string[prefix_len:] for string in strings_without_extensions]<EOL>if len(set(result)) != len(strings):<EOL><INDENT>return strings<EOL><DEDENT>return result<EOL>
Removes common prefix from a collection of strings
f14227:m1
def alignment_key(pysam_alignment_record):
return (<EOL>read_key(pysam_alignment_record),<EOL>pysam_alignment_record.query_alignment_start,<EOL>pysam_alignment_record.query_alignment_end,<EOL>)<EOL>
Return the identifying attributes of a `pysam.AlignedSegment` instance. This is necessary since these objects do not support a useful notion of equality (they compare on identify by default).
f14228:m0
def read_key(pysam_alignment_record):
return (<EOL>pysam_alignment_record.query_name,<EOL>pysam_alignment_record.is_duplicate,<EOL>pysam_alignment_record.is_read1,<EOL>pysam_alignment_record.is_read2,<EOL>)<EOL>
Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments.
f14228:m1
def variant_context(<EOL>reference_fasta,<EOL>contig,<EOL>inclusive_start,<EOL>inclusive_end,<EOL>alt,<EOL>context_length):
<EOL>start = int(inclusive_start) - <NUM_LIT:1><EOL>end = int(inclusive_end)<EOL>full_sequence = reference_fasta[contig]<EOL>left = str(full_sequence[start - context_length:start].seq).upper()<EOL>middle = str(full_sequence[start: end].seq).upper()<EOL>right = str(full_sequence[end: end + context_length].seq).upper()<EOL>if middle[<NUM_LIT:0>] in ('<STR_LIT:A>', '<STR_LIT>'):<EOL><INDENT>context_5prime = pyfaidx.complement(right)[::-<NUM_LIT:1>]<EOL>context_3prime = pyfaidx.complement(left)[::-<NUM_LIT:1>]<EOL>context_mutation = "<STR_LIT>" % (<EOL>pyfaidx.complement(middle)[::-<NUM_LIT:1>], pyfaidx.complement(alt)[::-<NUM_LIT:1>])<EOL><DEDENT>else:<EOL><INDENT>context_5prime = left<EOL>context_3prime = right<EOL>context_mutation = "<STR_LIT>" % (middle, alt)<EOL><DEDENT>return (context_5prime, context_mutation, context_3prime)<EOL>
Retrieve the surronding reference region from a variant. SNVs are canonicalized so the reference base is a pyrmidine (C/T). For indels the reverse complement will still be taken if the first base of the reference is not a pyrmidine, but since the reference will also be reversed, that doesn't guarantee it will start with a pyrmidine. Parameters ---------- reference_fasta : FastaReference reference sequence from pyfaidx package contig : str Chromosome of the variant inclusive_start : int start of the variant in 1-based inclusive coordinates inclusive_end : int end of the variant in 1-based inclusive coordinates alt : string alt sequence context_length : int number of bases on either side of the variant to return Returns --------- A tuple of (5', mutation, 3') where 5' - bases immediately 5 prime to the mutation 3' - bases immediately 3 prime to the mutation mutation - the ref sequence followed by a > character followed by the the alt sequence
f14229:m0
@property<EOL><INDENT>def positions(self):<DEDENT>
return range(self.start, self.end)<EOL>
A Python range object giving the bases included in this locus.
f14230:c0:m2
@property<EOL><INDENT>def position(self):<DEDENT>
if self.end != self.start + <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>" % str(self))<EOL><DEDENT>return self.start<EOL>
If this locus spans a single base, this property gives that position. Otherwise, raises a ValueError.
f14230:c0:m3
@staticmethod<EOL><INDENT>def from_inclusive_coordinates(contig, start, end=None):<DEDENT>
typechecks.require_string(contig)<EOL>typechecks.require_integer(start)<EOL>if end is None:<EOL><INDENT>end = start<EOL><DEDENT>typechecks.require_integer(end)<EOL>contig = pyensembl.locus.normalize_chromosome(contig)<EOL>return Locus(contig, start - <NUM_LIT:1>, end)<EOL>
Given coordinates in 1-based coordinates that are inclusive on start and end, return a Locus instance. Locus instances are always 0-based "interbase" coordinates.
f14230:c0:m4
@staticmethod<EOL><INDENT>def from_interbase_coordinates(contig, start, end=None):<DEDENT>
typechecks.require_string(contig)<EOL>typechecks.require_integer(start)<EOL>if end is None:<EOL><INDENT>end = start + <NUM_LIT:1><EOL><DEDENT>typechecks.require_integer(end)<EOL>contig = pyensembl.locus.normalize_chromosome(contig)<EOL>return Locus(contig, start, end)<EOL>
Given coordinates in 0-based interbase coordinates, return a Locus instance.
f14230:c0:m5
def add_args(parser, positional=False):
group = parser.add_argument_group("<STR_LIT>")<EOL>group.add_argument("<STR_LIT>" if positional else "<STR_LIT>",<EOL>nargs="<STR_LIT:+>", default=[],<EOL>help="<STR_LIT>")<EOL>group.add_argument(<EOL>"<STR_LIT>",<EOL>nargs="<STR_LIT:+>",<EOL>help="<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>group = parser.add_argument_group(<EOL>"<STR_LIT>",<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>"<EOL>"<STR_LIT>")<EOL>for (name, (kind, message, function)) in READ_FILTERS.items():<EOL><INDENT>extra = {}<EOL>if kind is bool:<EOL><INDENT>extra["<STR_LIT:action>"] = "<STR_LIT:store_true>"<EOL>extra["<STR_LIT:default>"] = None<EOL><DEDENT>elif kind is int:<EOL><INDENT>extra["<STR_LIT:type>"] = int<EOL>extra["<STR_LIT>"] = "<STR_LIT:N>"<EOL><DEDENT>elif kind is str:<EOL><INDENT>extra["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT>group.add_argument("<STR_LIT>" + name.replace("<STR_LIT:_>", "<STR_LIT:->"),<EOL>help=message,<EOL>**extra)<EOL><DEDENT>
Extends a commandline argument parser with arguments for specifying read sources.
f14236:m1
def load_from_args(args):
if not args.reads:<EOL><INDENT>return None<EOL><DEDENT>if args.read_source_name:<EOL><INDENT>read_source_names = util.expand(<EOL>args.read_source_name,<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>len(args.reads))<EOL><DEDENT>else:<EOL><INDENT>read_source_names = util.drop_prefix(args.reads)<EOL><DEDENT>filters = []<EOL>for (name, info) in READ_FILTERS.items():<EOL><INDENT>value = getattr(args, name)<EOL>if value is not None:<EOL><INDENT>filters.append(functools.partial(info[-<NUM_LIT:1>], value))<EOL><DEDENT><DEDENT>return [<EOL>load_bam(filename, name, filters)<EOL>for (filename, name)<EOL>in zip(args.reads, read_source_names)<EOL>]<EOL>
Given parsed commandline arguments, returns a list of ReadSource objects
f14236:m2
def alignment_key(pysam_alignment_record):
return (<EOL>read_key(pysam_alignment_record),<EOL>pysam_alignment_record.query_alignment_start,<EOL>pysam_alignment_record.query_alignment_end,<EOL>)<EOL>
Return the identifying attributes of a `pysam.AlignedSegment` instance. This is necessary since these objects do not support a useful notion of equality (they compare on identify by default).
f14238:m0
def read_key(pysam_alignment_record):
return (<EOL>pysam_alignment_record.query_name,<EOL>pysam_alignment_record.is_duplicate,<EOL>pysam_alignment_record.is_read1,<EOL>pysam_alignment_record.is_read2,<EOL>)<EOL>
Given a `pysam.AlignedSegment` instance, return the attributes identifying the *read* it comes from (not the alignment). There may be more than one alignment for a read, e.g. chimeric and secondary alignments.
f14238:m1
def __init__(self, locus, elements):
self.locus = locus<EOL>self.elements = OrderedDict((e, None) for e in elements)<EOL>assert all(e.locus == self.locus for e in self.elements)<EOL>
Construct a new Pileup. Parameters ---------- locus : Varcode.Locus The reference locus. Must be length 1, i.e. a single base. elements : iterable of PileupElement The pileup elements. The locus field of these instances must match the locus parameter.
f14239:c0:m0