uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
b75868b226cf460ea40ea262
train
function
def is_valid_inferred_type(typ: Type) -> bool: """Is an inferred type valid? Examples of invalid types include the None type or List[<uninhabited>]. When not doing strict Optional checking, all types containing None are invalid. When doing strict Optional checking, only None and types that are in...
def is_valid_inferred_type(typ: Type) -> bool:
"""Is an inferred type valid? Examples of invalid types include the None type or List[<uninhabited>]. When not doing strict Optional checking, all types containing None are invalid. When doing strict Optional checking, only None and types that are incompletely defined (i.e. contain UninhabitedTyp...
, Instance): if operator in operators.ops_with_inplace_method: inplace_method = '__i' + method[2:] if typ.type.has_readable_member(inplace_method): return True, inplace_method return False, method def is_valid_inferred_type(typ: Type) -> bool:
64
64
186
14
49
fperrin/mypy
mypy/checker.py
Python
is_valid_inferred_type
is_valid_inferred_type
6,189
6,204
6,189
6,189
ba56ca8d67a2dcab917350656a2aa64403de8e32
bigcode/the-stack
train
b9e898195306f83624144df3
train
function
def is_true_literal(n: Expression) -> bool: """Returns true if this expression is the 'True' literal/keyword.""" return (refers_to_fullname(n, 'builtins.True') or isinstance(n, IntExpr) and n.value != 0)
def is_true_literal(n: Expression) -> bool:
"""Returns true if this expression is the 'True' literal/keyword.""" return (refers_to_fullname(n, 'builtins.True') or isinstance(n, IntExpr) and n.value != 0)
that does not appear in table by appending numbers to base.""" if base not in table: return base i = 1 while base + str(i) in table: i += 1 return base + str(i) def is_true_literal(n: Expression) -> bool:
64
64
57
11
53
fperrin/mypy
mypy/checker.py
Python
is_true_literal
is_true_literal
5,759
5,762
5,759
5,759
0c7ce316a83aff8a27d2fe50dc123fc2233d7731
bigcode/the-stack
train
de2f6c43ced5f064a74f4743
train
function
def is_false_literal(n: Expression) -> bool: """Returns true if this expression is the 'False' literal/keyword.""" return (refers_to_fullname(n, 'builtins.False') or isinstance(n, IntExpr) and n.value == 0)
def is_false_literal(n: Expression) -> bool:
"""Returns true if this expression is the 'False' literal/keyword.""" return (refers_to_fullname(n, 'builtins.False') or isinstance(n, IntExpr) and n.value == 0)
(n: Expression) -> bool: """Returns true if this expression is the 'True' literal/keyword.""" return (refers_to_fullname(n, 'builtins.True') or isinstance(n, IntExpr) and n.value != 0) def is_false_literal(n: Expression) -> bool:
64
64
57
11
53
fperrin/mypy
mypy/checker.py
Python
is_false_literal
is_false_literal
5,765
5,768
5,765
5,765
afde339068fd5c5e217b47c32054f19277cfb6a6
bigcode/the-stack
train
31ebb1de8900cf0dcb6196d6
train
class
class SetNothingToAny(TypeTranslator): """Replace all ambiguous <nothing> types with Any (to avoid spurious extra errors).""" def visit_uninhabited_type(self, t: UninhabitedType) -> Type: if t.ambiguous: return AnyType(TypeOfAny.from_error) return t def visit_type_alias_type(se...
class SetNothingToAny(TypeTranslator):
"""Replace all ambiguous <nothing> types with Any (to avoid spurious extra errors).""" def visit_uninhabited_type(self, t: UninhabitedType) -> Type: if t.ambiguous: return AnyType(TypeOfAny.from_error) return t def visit_type_alias_type(self, t: TypeAliasType) -> Type: ...
types resulting from failed (ambiguous) type inference.""" def __init__(self) -> None: super().__init__(any) def visit_uninhabited_type(self, t: UninhabitedType) -> bool: return t.ambiguous class SetNothingToAny(TypeTranslator):
64
64
127
8
55
fperrin/mypy
mypy/checker.py
Python
SetNothingToAny
SetNothingToAny
6,217
6,228
6,217
6,217
590fa0fb7ced06c81493d5262c4ae77a46d92dfb
bigcode/the-stack
train
d5afcf7b6e36821aae2b767b
train
function
def is_private(node_name: str) -> bool: """Check if node is private to class definition.""" return node_name.startswith('__') and not node_name.endswith('__')
def is_private(node_name: str) -> bool:
"""Check if node is private to class definition.""" return node_name.startswith('__') and not node_name.endswith('__')
Type) -> bool: return is_subtype(left, right, ignore_promotions=True) def is_overlapping_types_no_promote(left: Type, right: Type) -> bool: return is_overlapping_types(left, right, ignore_promotions=True) def is_private(node_name: str) -> bool:
64
64
36
11
53
fperrin/mypy
mypy/checker.py
Python
is_private
is_private
6,551
6,553
6,551
6,551
f6c03532fcf575d10edbc2b5f4508d776ca0bcde
bigcode/the-stack
train
77f124bc0bef8f8f9fded335
train
function
def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap: """Calculate what information we can learn from the truth of (e1 and e2) in terms of the information that we can learn from the truth of e1 and the truth of e2. """ if m1 is None or m2 is None: # One of the conditions can never ...
def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
"""Calculate what information we can learn from the truth of (e1 and e2) in terms of the information that we can learn from the truth of e1 and the truth of e2. """ if m1 is None or m2 is None: # One of the conditions can never be true. return None # Both conditions can be true;...
if base.fullname == 'typing.Mapping': return map_instance_to_supertype(tp.fallback, base).args[0] assert False, 'No Mapping base class found for TypedDict fallback' return None def and_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
67
67
225
21
45
fperrin/mypy
mypy/checker.py
Python
and_conditional_maps
and_conditional_maps
5,855
5,874
5,855
5,855
4c32d1217d040c576ea3769673b01233d5c126df
bigcode/the-stack
train
b1dd8d9e5bfe45d054b14a2e
train
function
def is_static(func: Union[FuncBase, Decorator]) -> bool: if isinstance(func, Decorator): return is_static(func.func) elif isinstance(func, FuncBase): return func.is_static assert False, "Unexpected func type: {}".format(type(func))
def is_static(func: Union[FuncBase, Decorator]) -> bool:
if isinstance(func, Decorator): return is_static(func.func) elif isinstance(func, FuncBase): return func.is_static assert False, "Unexpected func type: {}".format(type(func))
else: return not is_typed_callable(method.type) else: return False elif isinstance(typ, Overloaded): return any(is_untyped_decorator(item) for item in typ.items) return True def is_static(func: Union[FuncBase, Decorator]) -> bool:
64
64
59
16
47
fperrin/mypy
mypy/checker.py
Python
is_static
is_static
6,535
6,540
6,535
6,535
c542a70a39032f1f3f35a2b3a388b26eabd9ced8
bigcode/the-stack
train
ab6f9360ac234045586bdf8e
train
function
def collapse_walrus(e: Expression) -> Expression: """If an expression is an AssignmentExpr, pull out the assignment target. We don't make any attempt to pull out all the targets in code like `x := (y := z)`. We could support narrowing those if that sort of code turns out to be common. """ if isinst...
def collapse_walrus(e: Expression) -> Expression:
"""If an expression is an AssignmentExpr, pull out the assignment target. We don't make any attempt to pull out all the targets in code like `x := (y := z)`. We could support narrowing those if that sort of code turns out to be common. """ if isinstance(e, AssignmentExpr): return e.target ...
item.""" if is_named_instance(typ, 'builtins.bool'): return True if isinstance(typ, UnionType): return any(is_named_instance(item, 'builtins.bool') for item in typ.items) return False def collapse_walrus(e: Expression) -> Expression:
64
64
88
12
51
fperrin/mypy
mypy/checker.py
Python
collapse_walrus
collapse_walrus
6,571
6,579
6,571
6,571
940b56ee322411916d2621556d1291bf14be1d5d
bigcode/the-stack
train
85ed671d441c31688ab85643
train
function
def has_bool_item(typ: ProperType) -> bool: """Return True if type is 'bool' or a union with a 'bool' item.""" if is_named_instance(typ, 'builtins.bool'): return True if isinstance(typ, UnionType): return any(is_named_instance(item, 'builtins.bool') for item in typ.items) ...
def has_bool_item(typ: ProperType) -> bool:
"""Return True if type is 'bool' or a union with a 'bool' item.""" if is_named_instance(typ, 'builtins.bool'): return True if isinstance(typ, UnionType): return any(is_named_instance(item, 'builtins.bool') for item in typ.items) return False
_name.startswith('__') and not node_name.endswith('__') def is_string_literal(typ: Type) -> bool: strs = try_getting_str_literals_from_type(typ) return strs is not None and len(strs) == 1 def has_bool_item(typ: ProperType) -> bool:
64
64
83
13
50
fperrin/mypy
mypy/checker.py
Python
has_bool_item
has_bool_item
6,561
6,568
6,561
6,561
357a08eb3b511fa02b22183d4c3483149f5c5529
bigcode/the-stack
train
f5cafa39c98d4a36f1c57adc
train
function
def reduce_conditional_maps(type_maps: List[Tuple[TypeMap, TypeMap]], ) -> Tuple[TypeMap, TypeMap]: """Reduces a list containing pairs of if/else TypeMaps into a single pair. We "and" together all of the if TypeMaps and "or" together the else TypeMaps. So for example, if we had ...
def reduce_conditional_maps(type_maps: List[Tuple[TypeMap, TypeMap]], ) -> Tuple[TypeMap, TypeMap]:
"""Reduces a list containing pairs of if/else TypeMaps into a single pair. We "and" together all of the if TypeMaps and "or" together the else TypeMaps. So for example, if we had the input: [ ({x: TypeIfX, shared: TypeIfShared1}, {x: TypeElseX, shared: TypeElseShared1}), ({...
do not # learn anything about expressions whose type is refined by only # one condition.) result: Dict[Expression, Type] = {} for n1 in m1: for n2 in m2: if literal_hash(n1) == literal_hash(n2): result[n1] = make_simplified_union([m1[n1], m2[n2]]) return result d...
116
116
387
29
86
fperrin/mypy
mypy/checker.py
Python
reduce_conditional_maps
reduce_conditional_maps
5,899
5,934
5,899
5,900
316235b32047397fd96f99dd55ab93ea22f99136
bigcode/the-stack
train
b2fb1cc65206dd13736dcb8a
train
function
def convert_to_typetype(type_map: TypeMap) -> TypeMap: converted_type_map: Dict[Expression, Type] = {} if type_map is None: return None for expr, typ in type_map.items(): t = typ if isinstance(t, TypeVarType): t = t.upper_bound # TODO: should we only allow unions ...
def convert_to_typetype(type_map: TypeMap) -> TypeMap:
converted_type_map: Dict[Expression, Type] = {} if type_map is None: return None for expr, typ in type_map.items(): t = typ if isinstance(t, TypeVarType): t = t.upper_bound # TODO: should we only allow unions of instances as per PEP 484? if not isinstance(...
in type_maps[1:]: final_if_map = and_conditional_maps(final_if_map, if_map) final_else_map = or_conditional_maps(final_else_map, else_map) return final_if_map, final_else_map def convert_to_typetype(type_map: TypeMap) -> TypeMap:
64
64
140
15
48
fperrin/mypy
mypy/checker.py
Python
convert_to_typetype
convert_to_typetype
5,937
5,950
5,937
5,937
68af132921e7c347943708fb9e21e246ab844b7f
bigcode/the-stack
train
261bda7386b17d6409982a41
train
function
def detach_callable(typ: CallableType) -> CallableType: """Ensures that the callable's type variables are 'detached' and independent of the context. A callable normally keeps track of the type variables it uses within its 'variables' field. However, if the callable is from a method and that method is using...
def detach_callable(typ: CallableType) -> CallableType:
"""Ensures that the callable's type variables are 'detached' and independent of the context. A callable normally keeps track of the type variables it uses within its 'variables' field. However, if the callable is from a method and that method is using a class type variable, the callable will not keep t...
_compat_return=lambda l, r: not is_subtype_no_promote(l, r), ignore_return=False, check_args_covariantly=True, allow_partial_overlap=True) or is_callable_compatible(other, signature, ...
114
114
382
13
101
fperrin/mypy
mypy/checker.py
Python
detach_callable
detach_callable
6,077
6,121
6,077
6,077
47f1cc8b4d66712f53664b317622da1dee0add83
bigcode/the-stack
train
0aa6295ed0bd1ae2dcc5bc58
train
function
def is_literal_enum(type_map: Mapping[Expression, Type], n: Expression) -> bool: """Returns true if this expression (with the given type context) is an Enum literal. For example, if we had an enum: class Foo(Enum): A = 1 B = 2 ...and if the expression 'Foo' referred to tha...
def is_literal_enum(type_map: Mapping[Expression, Type], n: Expression) -> bool:
"""Returns true if this expression (with the given type context) is an Enum literal. For example, if we had an enum: class Foo(Enum): A = 1 B = 2 ...and if the expression 'Foo' referred to that enum within the current type context, then the expression 'Foo.A' would be ...
') or isinstance(n, IntExpr) and n.value != 0) def is_false_literal(n: Expression) -> bool: """Returns true if this expression is the 'False' literal/keyword.""" return (refers_to_fullname(n, 'builtins.False') or isinstance(n, IntExpr) and n.value == 0) def is_literal_enum(type_map: Ma...
93
93
313
20
73
fperrin/mypy
mypy/checker.py
Python
is_literal_enum
is_literal_enum
5,771
5,804
5,771
5,771
ab7bea32236b1770a91f6300619a40e11b57e71f
bigcode/the-stack
train
823da5be66523f9670887015
train
function
def is_node_static(node: Optional[Node]) -> Optional[bool]: """Find out if a node describes a static function method.""" if isinstance(node, FuncDef): return node.is_static if isinstance(node, Var): return node.is_staticmethod return None
def is_node_static(node: Optional[Node]) -> Optional[bool]:
"""Find out if a node describes a static function method.""" if isinstance(node, FuncDef): return node.is_static if isinstance(node, Var): return node.is_staticmethod return None
t: TypeAliasType) -> Type: # Target of the alias cannot by an ambiguous <nothing>, so we just # replace the arguments. return t.copy_modified(args=[a.accept(self) for a in t.args]) def is_node_static(node: Optional[Node]) -> Optional[bool]:
64
64
60
15
49
fperrin/mypy
mypy/checker.py
Python
is_node_static
is_node_static
6,231
6,240
6,231
6,231
0cb99eb40b7599622eb71a43af1a38f4dc17dde6
bigcode/the-stack
train
f3a54c002833f8be372c0cf4
train
function
def infer_operator_assignment_method(typ: Type, operator: str) -> Tuple[bool, str]: """Determine if operator assignment on given value type is in-place, and the method name. For example, if operator is '+', return (True, '__iadd__') or (False, '__add__') depending on which method is supported by the type. ...
def infer_operator_assignment_method(typ: Type, operator: str) -> Tuple[bool, str]:
"""Determine if operator assignment on given value type is in-place, and the method name. For example, if operator is '+', return (True, '__iadd__') or (False, '__add__') depending on which method is supported by the type. """ typ = get_proper_type(typ) method = operators.op_methods[operator] ...
Type) -> bool: return is_callable_compatible(t, s, is_compat=is_same_type, ignore_return=True, check_args_covariantly=True, ignore_pos_arg_names=True) def infer_operator_assignment...
64
64
153
21
43
fperrin/mypy
mypy/checker.py
Python
infer_operator_assignment_method
infer_operator_assignment_method
6,173
6,186
6,173
6,173
9cd03c55b3984c6dc94710d0653926d12ea56c5e
bigcode/the-stack
train
91d0a2367e60f87cef4a474a
train
function
def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool: """Can a single call match both t and s, based just on positional argument counts? """ min_args = max(t.min_args, s.min_args) max_args = min(t.max_possible_positional_args(), s.max_possible_positional_args()) return min_a...
def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool:
"""Can a single call match both t and s, based just on positional argument counts? """ min_args = max(t.min_args, s.min_args) max_args = min(t.max_possible_positional_args(), s.max_possible_positional_args()) return min_args <= max_args
map: Dict[TypeVarId, Type]) -> None: super().__init__() self.map = map def type(self, type: Type) -> Type: return expand_type(type, self.map) def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool:
64
64
80
19
45
fperrin/mypy
mypy/checker.py
Python
are_argument_counts_overlapping
are_argument_counts_overlapping
6,023
6,028
6,023
6,023
629415f043869478330dbda3e723592a33856cb3
bigcode/the-stack
train
3947153786c4e018f1424102
train
function
def group_comparison_operands(pairwise_comparisons: Iterable[Tuple[str, Expression, Expression]], operand_to_literal_hash: Mapping[int, Key], operators_to_group: Set[str], ) -> List[Tuple[str, List[int]]]: """Group a series of...
def group_comparison_operands(pairwise_comparisons: Iterable[Tuple[str, Expression, Expression]], operand_to_literal_hash: Mapping[int, Key], operators_to_group: Set[str], ) -> List[Tuple[str, List[int]]]:
"""Group a series of comparison operands together chained by any operand in the 'operators_to_group' set. All other pairwise operands are kept in groups of size 2. For example, suppose we have the input comparison expression: x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8 If we ...
_lookup_or_make_root_id(self, key: TKey) -> int: if key in self._key_to_id: return self._lookup_root_id(key) else: new_id = len(self._key_to_id) self._key_to_id[key] = new_id self._id_to_parent_id[new_id] = new_id self._root_id_to_values[new_i...
256
256
1,093
52
203
fperrin/mypy
mypy/checker.py
Python
group_comparison_operands
group_comparison_operands
6,402
6,498
6,402
6,405
2cabdd6edbd30fcde94dd671cb2a3bee70caf429
bigcode/the-stack
train
ba47aa749c3609222cdd00c9
train
function
def is_literal_none(n: Expression) -> bool: """Returns true if this expression is the 'None' literal/keyword.""" return isinstance(n, NameExpr) and n.fullname == 'builtins.None'
def is_literal_none(n: Expression) -> bool:
"""Returns true if this expression is the 'None' literal/keyword.""" return isinstance(n, NameExpr) and n.fullname == 'builtins.None'
isinstance(parent_type, FunctionLike) or not isinstance(member_type, LiteralType): return False if not parent_type.is_type_obj(): return False return member_type.is_enum_literal() and member_type.fallback.type == parent_type.type_object() def is_literal_none(n: Expression) -> bool:
64
64
45
11
53
fperrin/mypy
mypy/checker.py
Python
is_literal_none
is_literal_none
5,807
5,809
5,807
5,807
4340a639624f2a45ced924986eaba7a04f20c9d9
bigcode/the-stack
train
178c6c9c90226516c04c0cca
train
function
def builtin_item_type(tp: Type) -> Optional[Type]: """Get the item type of a builtin container. If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict) or if the container is not parameterized (like List or List[Any]) return None. This function is used to narrow optional ty...
def builtin_item_type(tp: Type) -> Optional[Type]:
"""Get the item type of a builtin container. If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict) or if the container is not parameterized (like List or List[Any]) return None. This function is used to narrow optional types in situations like this: x: Optional[i...
return False return member_type.is_enum_literal() and member_type.fallback.type == parent_type.type_object() def is_literal_none(n: Expression) -> bool: """Returns true if this expression is the 'None' literal/keyword.""" return isinstance(n, NameExpr) and n.fullname == 'builtins.None' def is_l...
114
114
382
13
101
fperrin/mypy
mypy/checker.py
Python
builtin_item_type
builtin_item_type
5,816
5,852
5,816
5,816
cb54c85ed48bafe06dae33a1612815ad7e7623b1
bigcode/the-stack
train
448afbd9f97512146caa475e
train
function
def is_subtype_no_promote(left: Type, right: Type) -> bool: return is_subtype(left, right, ignore_promotions=True)
def is_subtype_no_promote(left: Type, right: Type) -> bool:
return is_subtype(left, right, ignore_promotions=True)
-> bool: if isinstance(func, Decorator): return is_static(func.func) elif isinstance(func, FuncBase): return func.is_static assert False, "Unexpected func type: {}".format(type(func)) def is_subtype_no_promote(left: Type, right: Type) -> bool:
64
64
32
18
46
fperrin/mypy
mypy/checker.py
Python
is_subtype_no_promote
is_subtype_no_promote
6,543
6,544
6,543
6,543
1cff0322dd1e166a83d18902de0390932dcfb6e5
bigcode/the-stack
train
cbb440d8d3565a4c37d3ae36
train
function
def overload_can_never_match(signature: CallableType, other: CallableType) -> bool: """Check if the 'other' method can never be matched due to 'signature'. This can happen if signature's parameters are all strictly broader then other's parameters. Assumes that both signatures have overlapping argument...
def overload_can_never_match(signature: CallableType, other: CallableType) -> bool:
"""Check if the 'other' method can never be matched due to 'signature'. This can happen if signature's parameters are all strictly broader then other's parameters. Assumes that both signatures have overlapping argument counts. """ # The extra erasure is needed to prevent spurious errors # ...
.values, upper_bound=var.upper_bound, variance=var.variance, )) out = typ.copy_modified( variables=new_variables, arg_types=type_list[:-1], ret_type=type_list[-1], ) return out def overload_can_never_match(signature: CallableType, other: CallableType) ...
74
74
247
19
54
fperrin/mypy
mypy/checker.py
Python
overload_can_never_match
overload_can_never_match
6,124
6,145
6,124
6,124
4369b5b5eb82a83fcfd945dbbbfae1f89c0c5683
bigcode/the-stack
train
c683f35d4b3cc9c22f9a7b73
train
function
def is_typed_callable(c: Optional[Type]) -> bool: c = get_proper_type(c) if not c or not isinstance(c, CallableType): return False return not all(isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated for t in get_proper_types(c.arg_types + [c.ret_type]))
def is_typed_callable(c: Optional[Type]) -> bool:
c = get_proper_type(c) if not c or not isinstance(c, CallableType): return False return not all(isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated for t in get_proper_types(c.arg_types + [c.ret_type]))
_dict.items(): simplified_operator_list.append((operator, sorted(indices))) # For stability, reorder list by the first operand index to appear simplified_operator_list.sort(key=lambda item: item[1][0]) return simplified_operator_list def is_typed_callable(c: Optional[Type]) -> bool:
64
64
80
14
49
fperrin/mypy
mypy/checker.py
Python
is_typed_callable
is_typed_callable
6,501
6,506
6,501
6,501
64024c2ff8951a2a97899294ec2811fadeb325b4
bigcode/the-stack
train
823ed463478948c58078c7c3
train
function
def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap: """Calculate what information we can learn from the truth of (e1 or e2) in terms of the information that we can learn from the truth of e1 and the truth of e2. """ if m1 is None: return m2 if m2 is None: return m1 ...
def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
"""Calculate what information we can learn from the truth of (e1 or e2) in terms of the information that we can learn from the truth of e1 and the truth of e2. """ if m1 is None: return m2 if m2 is None: return m1 # Both conditions can be true. Combine information about ...
for n2 in m2) for n1 in m1: if literal_hash(n1) not in m2_keys: result[n1] = m1[n1] return result def or_conditional_maps(m1: TypeMap, m2: TypeMap) -> TypeMap:
64
64
203
21
42
fperrin/mypy
mypy/checker.py
Python
or_conditional_maps
or_conditional_maps
5,877
5,896
5,877
5,877
29fdf6b9bf3f0ded51925cf561a671cb9e039ade
bigcode/the-stack
train
efe31b8e75a2f96aec1f6027
train
function
def flatten_types(t: Type) -> List[Type]: """Flatten a nested sequence of tuples into one list of nodes.""" t = get_proper_type(t) if isinstance(t, TupleType): return [b for a in t.items for b in flatten_types(a)] else: return [t]
def flatten_types(t: Type) -> List[Type]:
"""Flatten a nested sequence of tuples into one list of nodes.""" t = get_proper_type(t) if isinstance(t, TupleType): return [b for a in t.items for b in flatten_types(a)] else: return [t]
if isinstance(t, TupleExpr) or isinstance(t, ListExpr): return [b for a in t.items for b in flatten(a)] elif isinstance(t, StarExpr): return flatten(t.expr) else: return [t] def flatten_types(t: Type) -> List[Type]:
64
64
67
12
52
fperrin/mypy
mypy/checker.py
Python
flatten_types
flatten_types
5,963
5,969
5,963
5,963
3d56d84e1f732c7be2067abbb0abd768a6b085c3
bigcode/the-stack
train
7c2f65590077e57f2578303c
train
function
@overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: None = None ) -> Tuple[Optional[Type], Optional[Type]]: ...
@overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: None = None
) -> Tuple[Optional[Type], Optional[Type]]: ...
node.is_property: first_item = cast(Decorator, node.items[0]) return first_item.var.is_settable_property else: return False @overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], defaul...
64
64
45
30
33
fperrin/mypy
mypy/checker.py
Python
conditional_types
conditional_types
5,670
5,674
5,670
5,673
89e819ea569e0c92eb0a50cc6b1b249d14586268
bigcode/the-stack
train
8352fa1bd52afbee2ada2512
train
function
def is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool: """Does t have wider arguments than s?""" # TODO should an overload with additional items be allowed to be more # general than one with fewer items (or just one item)? if isinstance(t, CallableType): if isinstance(s, ...
def is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool:
"""Does t have wider arguments than s?""" # TODO should an overload with additional items be allowed to be more # general than one with fewer items (or just one item)? if isinstance(t, CallableType): if isinstance(s, CallableType): return is_callable_compatible(t, s, ...
.variables}) assert isinstance(exp_signature, ProperType) assert isinstance(exp_signature, CallableType) return is_callable_compatible(exp_signature, other, is_compat=is_more_precise, ignore_return=True) def is_more_general_arg_prefix(t: Fu...
64
64
158
19
45
fperrin/mypy
mypy/checker.py
Python
is_more_general_arg_prefix
is_more_general_arg_prefix
6,148
6,162
6,148
6,148
bf8f6e0b277f1e5f319b557e14ca16454129e484
bigcode/the-stack
train
1399baf930e763baf56989a2
train
function
def is_unsafe_overlapping_overload_signatures(signature: CallableType, other: CallableType) -> bool: """Check if two overloaded signatures are unsafely overlapping or partially overlapping. We consider two functions 's' and 't' to be unsafely overlapping if both ...
def is_unsafe_overlapping_overload_signatures(signature: CallableType, other: CallableType) -> bool:
"""Check if two overloaded signatures are unsafely overlapping or partially overlapping. We consider two functions 's' and 't' to be unsafely overlapping if both of the following are true: 1. s's parameters are all more precise or partially overlapping with t's 2. s's return type is NOT a subtyp...
Type]) -> None: super().__init__() self.map = map def type(self, type: Type) -> Type: return expand_type(type, self.map) def are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool: """Can a single call match both t and s, based just on positional argument counts? ...
141
141
471
24
116
fperrin/mypy
mypy/checker.py
Python
is_unsafe_overlapping_overload_signatures
is_unsafe_overlapping_overload_signatures
6,031
6,074
6,031
6,032
8defaf3fd5eba3bb270bc298a7a287ae540e4d08
bigcode/the-stack
train
f49c675827a98ab1694d26a3
train
function
def is_overlapping_types_no_promote(left: Type, right: Type) -> bool: return is_overlapping_types(left, right, ignore_promotions=True)
def is_overlapping_types_no_promote(left: Type, right: Type) -> bool:
return is_overlapping_types(left, right, ignore_promotions=True)
assert False, "Unexpected func type: {}".format(type(func)) def is_subtype_no_promote(left: Type, right: Type) -> bool: return is_subtype(left, right, ignore_promotions=True) def is_overlapping_types_no_promote(left: Type, right: Type) -> bool:
64
64
34
19
45
fperrin/mypy
mypy/checker.py
Python
is_overlapping_types_no_promote
is_overlapping_types_no_promote
6,547
6,548
6,547
6,547
e1c93a74f3b93d29ab05f6340bf7bf6264306776
bigcode/the-stack
train
a7881c6b943d9cfdcdaa9d8f
train
function
def flatten(t: Expression) -> List[Expression]: """Flatten a nested sequence of tuples/lists into one list of nodes.""" if isinstance(t, TupleExpr) or isinstance(t, ListExpr): return [b for a in t.items for b in flatten(a)] elif isinstance(t, StarExpr): return flatten(t.expr) else: ...
def flatten(t: Expression) -> List[Expression]:
"""Flatten a nested sequence of tuples/lists into one list of nodes.""" if isinstance(t, TupleExpr) or isinstance(t, ListExpr): return [b for a in t.items for b in flatten(a)] elif isinstance(t, StarExpr): return flatten(t.expr) else: return [t]
? if not isinstance(get_proper_type(t), (UnionType, Instance)): # unknown type; error was likely reported earlier return {} converted_type_map[expr] = TypeType.make_normalized(typ) return converted_type_map def flatten(t: Expression) -> List[Expression]:
64
64
79
11
52
fperrin/mypy
mypy/checker.py
Python
flatten
flatten
5,953
5,960
5,953
5,953
121d1625e3e26f7c62ef5d59e3c9febd76d8f820
bigcode/the-stack
train
8f73b537fabd64e44535a076
train
function
def is_untyped_decorator(typ: Optional[Type]) -> bool: typ = get_proper_type(typ) if not typ: return True elif isinstance(typ, CallableType): return not is_typed_callable(typ) elif isinstance(typ, Instance): method = typ.type.get_method('__call__') if method: ...
def is_untyped_decorator(typ: Optional[Type]) -> bool:
typ = get_proper_type(typ) if not typ: return True elif isinstance(typ, CallableType): return not is_typed_callable(typ) elif isinstance(typ, Instance): method = typ.type.get_method('__call__') if method: if isinstance(method, Decorator): retur...
Type): return False return not all(isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated for t in get_proper_types(c.arg_types + [c.ret_type])) def is_untyped_decorator(typ: Optional[Type]) -> bool:
63
64
186
16
47
fperrin/mypy
mypy/checker.py
Python
is_untyped_decorator
is_untyped_decorator
6,509
6,532
6,509
6,509
6ec1840947daa292262ea740840e27faa885d270
bigcode/the-stack
train
b9aa998a655c738d01efb1d6
train
function
def get_isinstance_type(expr: Expression, type_map: Dict[Expression, Type]) -> Optional[List[TypeRange]]: if isinstance(expr, OpExpr) and expr.op == '|': left = get_isinstance_type(expr.left, type_map) right = get_isinstance_type(expr.right, type_map) if left is None ...
def get_isinstance_type(expr: Expression, type_map: Dict[Expression, Type]) -> Optional[List[TypeRange]]:
if isinstance(expr, OpExpr) and expr.op == '|': left = get_isinstance_type(expr.left, type_map) right = get_isinstance_type(expr.right, type_map) if left is None or right is None: return None return left + right all_types = get_proper_types(flatten_types(type_map[expr...
t.items for b in flatten(a)] elif isinstance(t, StarExpr): return flatten(t.expr) else: return [t] def flatten_types(t: Type) -> List[Type]: """Flatten a nested sequence of tuples into one list of nodes.""" t = get_proper_type(t) if isinstance(t, TupleType): return [b for ...
123
123
410
26
97
fperrin/mypy
mypy/checker.py
Python
get_isinstance_type
get_isinstance_type
5,972
6,004
5,972
5,973
17401c1ea1e1d14a75be32b4e8972d0146c0cb76
bigcode/the-stack
train
16e1c23afcd34f27ed607882
train
function
def gen_unique_name(base: str, table: SymbolTable) -> str: """Generate a name that does not appear in table by appending numbers to base.""" if base not in table: return base i = 1 while base + str(i) in table: i += 1 return base + str(i)
def gen_unique_name(base: str, table: SymbolTable) -> str:
"""Generate a name that does not appear in table by appending numbers to base.""" if base not in table: return base i = 1 while base + str(i) in table: i += 1 return base + str(i)
.append(None) elif proper_type is None: maps.append({}) else: assert typ is not None maps.append({expr: typ}) return cast(Tuple[TypeMap, TypeMap], tuple(maps)) def gen_unique_name(base: str, table: SymbolTable) -> str:
64
64
74
16
48
fperrin/mypy
mypy/checker.py
Python
gen_unique_name
gen_unique_name
5,749
5,756
5,749
5,749
f122788682f28e5d8907ed35c6993f705c227d0e
bigcode/the-stack
train
3e1a505a53cf127ddfb16c85
train
function
def expand_func(defn: FuncItem, map: Dict[TypeVarId, Type]) -> FuncItem: visitor = TypeTransformVisitor(map) ret = defn.accept(visitor) assert isinstance(ret, FuncItem) return ret
def expand_func(defn: FuncItem, map: Dict[TypeVarId, Type]) -> FuncItem:
visitor = TypeTransformVisitor(map) ret = defn.accept(visitor) assert isinstance(ret, FuncItem) return ret
isinstance # strictly speaking, we should return UninhabitedType but for simplicity we will simply # refuse to do any type inference for now return None return types def expand_func(defn: FuncItem, map: Dict[TypeVarId, Type]) -> FuncItem:
64
64
51
23
40
fperrin/mypy
mypy/checker.py
Python
expand_func
expand_func
6,007
6,011
6,007
6,007
f9ec1f4a4c16f29de3cb90fc8b9f558658db2885
bigcode/the-stack
train
9a285de2796c790710c732fd
train
class
class CheckerScope: # We keep two stacks combined, to maintain the relative order stack: List[Union[TypeInfo, FuncItem, MypyFile]] def __init__(self, module: MypyFile) -> None: self.stack = [module] def top_function(self) -> Optional[FuncItem]: for e in reversed(self.stack): ...
class CheckerScope: # We keep two stacks combined, to maintain the relative order
stack: List[Union[TypeInfo, FuncItem, MypyFile]] def __init__(self, module: MypyFile) -> None: self.stack = [module] def top_function(self) -> Optional[FuncItem]: for e in reversed(self.stack): if isinstance(e, FuncItem): return e return None def to...
_type_alias_type(self, t: TypeAliasType) -> Type: # Target of the alias cannot by an ambiguous <nothing>, so we just # replace the arguments. return t.copy_modified(args=[a.accept(self) for a in t.args]) def is_node_static(node: Optional[Node]) -> Optional[bool]: """Find out if a node desc...
132
132
442
18
113
fperrin/mypy
mypy/checker.py
Python
CheckerScope
CheckerScope
6,243
6,301
6,243
6,244
b1088e9f07fefb1f54c0db516e0e693d0e901380
bigcode/the-stack
train
29f53c3917537465849edac0
train
function
@overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: Type ) -> Tuple[Type, Type]: ...
@overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: Type
) -> Tuple[Type, Type]: ...
: Type, proposed_type_ranges: Optional[List[TypeRange]], default: None = None ) -> Tuple[Optional[Type], Optional[Type]]: ... @overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], ...
64
64
38
28
36
fperrin/mypy
mypy/checker.py
Python
conditional_types
conditional_types
5,677
5,681
5,677
5,680
dc9b2e0b4e77e21ee7158fb3b1ce23c07ea3c92d
bigcode/the-stack
train
7d448ff0309e62756468b032
train
class
class TypeTransformVisitor(TransformVisitor): def __init__(self, map: Dict[TypeVarId, Type]) -> None: super().__init__() self.map = map def type(self, type: Type) -> Type: return expand_type(type, self.map)
class TypeTransformVisitor(TransformVisitor):
def __init__(self, map: Dict[TypeVarId, Type]) -> None: super().__init__() self.map = map def type(self, type: Type) -> Type: return expand_type(type, self.map)
return types def expand_func(defn: FuncItem, map: Dict[TypeVarId, Type]) -> FuncItem: visitor = TypeTransformVisitor(map) ret = defn.accept(visitor) assert isinstance(ret, FuncItem) return ret class TypeTransformVisitor(TransformVisitor):
64
64
60
8
55
fperrin/mypy
mypy/checker.py
Python
TypeTransformVisitor
TypeTransformVisitor
6,014
6,020
6,014
6,014
46173931fd4e5f7d7a445199d55b7c86bf09f38b
bigcode/the-stack
train
2648e3664116f824db554b79
train
function
def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool: return is_callable_compatible(t, s, is_compat=is_same_type, ignore_return=True, check_args_covariantly=True, ignor...
def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool:
return is_callable_compatible(t, s, is_compat=is_same_type, ignore_return=True, check_args_covariantly=True, ignore_pos_arg_names=True)
(s, FunctionLike): if len(t.items) == len(s.items): return all(is_same_arg_prefix(items, itemt) for items, itemt in zip(t.items, s.items)) return False def is_same_arg_prefix(t: CallableType, s: CallableType) -> bool:
64
64
56
18
45
fperrin/mypy
mypy/checker.py
Python
is_same_arg_prefix
is_same_arg_prefix
6,165
6,170
6,165
6,165
1eec4448ac6cf513d2a99c97ae6dd9b358616cc7
bigcode/the-stack
train
5059f95730e3bcf3ba1ecc39
train
function
def is_literal_not_implemented(n: Expression) -> bool: return isinstance(n, NameExpr) and n.fullname == 'builtins.NotImplemented'
def is_literal_not_implemented(n: Expression) -> bool:
return isinstance(n, NameExpr) and n.fullname == 'builtins.NotImplemented'
== parent_type.type_object() def is_literal_none(n: Expression) -> bool: """Returns true if this expression is the 'None' literal/keyword.""" return isinstance(n, NameExpr) and n.fullname == 'builtins.None' def is_literal_not_implemented(n: Expression) -> bool:
64
64
32
13
51
fperrin/mypy
mypy/checker.py
Python
is_literal_not_implemented
is_literal_not_implemented
5,812
5,813
5,812
5,812
cbf5e383d6de41702068e48878dba7703c484320
bigcode/the-stack
train
6d95ee5bdc8dd4279837a77b
train
function
def is_string_literal(typ: Type) -> bool: strs = try_getting_str_literals_from_type(typ) return strs is not None and len(strs) == 1
def is_string_literal(typ: Type) -> bool:
strs = try_getting_str_literals_from_type(typ) return strs is not None and len(strs) == 1
: return is_overlapping_types(left, right, ignore_promotions=True) def is_private(node_name: str) -> bool: """Check if node is private to class definition.""" return node_name.startswith('__') and not node_name.endswith('__') def is_string_literal(typ: Type) -> bool:
64
64
40
12
52
fperrin/mypy
mypy/checker.py
Python
is_string_literal
is_string_literal
6,556
6,558
6,556
6,556
c414d5de55fe9a65824c50fc29dcc8aa33732a38
bigcode/the-stack
train
663f1c99f7c80be5e7274900
train
class
class NothingSeeker(TypeQuery[bool]): """Find any <nothing> types resulting from failed (ambiguous) type inference.""" def __init__(self) -> None: super().__init__(any) def visit_uninhabited_type(self, t: UninhabitedType) -> bool: return t.ambiguous
class NothingSeeker(TypeQuery[bool]):
"""Find any <nothing> types resulting from failed (ambiguous) type inference.""" def __init__(self) -> None: super().__init__(any) def visit_uninhabited_type(self, t: UninhabitedType) -> bool: return t.ambiguous
the initializer is None, but we only do that if we can't infer a # specific Optional type. This resolution happens in # leave_partial_types when we pop a partial types scope. return False return not typ.accept(NothingSeeker()) class NothingSeeker(TypeQuery[bool]):
64
64
72
9
55
fperrin/mypy
mypy/checker.py
Python
NothingSeeker
NothingSeeker
6,207
6,214
6,207
6,207
f998c2bd8c0c824f0d405eb8862823648b780182
bigcode/the-stack
train
488c3301145afd6ff6c162c1
train
function
def conditional_types_to_typemaps(expr: Expression, yes_type: Optional[Type], no_type: Optional[Type] ) -> Tuple[TypeMap, TypeMap]: maps: List[TypeMap] = [] for typ in (yes_type, no_type): proper_type =...
def conditional_types_to_typemaps(expr: Expression, yes_type: Optional[Type], no_type: Optional[Type] ) -> Tuple[TypeMap, TypeMap]:
maps: List[TypeMap] = [] for typ in (yes_type, no_type): proper_type = get_proper_type(typ) if isinstance(proper_type, UninhabitedType): maps.append(None) elif proper_type is None: maps.append({}) else: assert typ is not None maps.a...
remaining_type else: # An isinstance check, but we don't understand the type return current_type, default def conditional_types_to_typemaps(expr: Expression, yes_type: Optional[Type], no_type: Optional[Type] ...
64
64
133
38
25
fperrin/mypy
mypy/checker.py
Python
conditional_types_to_typemaps
conditional_types_to_typemaps
5,731
5,746
5,731
5,734
1a966fce408906cc93909eaf306dd9f6ef77e693
bigcode/the-stack
train
04dcc9c62f1bea5b72097d9a
train
class
class DisjointDict(Generic[TKey, TValue]): """An variation of the union-find algorithm/data structure where instead of keeping track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint. ...
class DisjointDict(Generic[TKey, TValue]):
"""An variation of the union-find algorithm/data structure where instead of keeping track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint. This data structure is currently used excl...
method must be called from inside a function" index = self.stack.index(top) assert index, "CheckerScope stack must always start with a module" enclosing = self.stack[index - 1] if isinstance(enclosing, TypeInfo): return enclosing return None def active_self_type...
256
256
1,107
10
246
fperrin/mypy
mypy/checker.py
Python
DisjointDict
DisjointDict
6,308
6,399
6,308
6,308
483d56ba967e3d5ef76b88c0a73e68cdef176a3d
bigcode/the-stack
train
b65af112ebca68fea1ed9424
train
class
class TypeChecker(NodeVisitor[None], CheckerPluginInterface): """Mypy type checker. Type check mypy source files that have been semantically analyzed. You must create a separate instance for each source file. """ # Are we type checking a stub? is_stub = False # Error message reporter ...
class TypeChecker(NodeVisitor[None], CheckerPluginInterface):
"""Mypy type checker. Type check mypy source files that have been semantically analyzed. You must create a separate instance for each source file. """ # Are we type checking a stub? is_stub = False # Error message reporter errors: Errors # Utility for generating messages msg: ...
: The keys of this dict are nodes in the original source program, # which are compared by reference equality--effectively, being *the # same* expression of the program, not just two identical expressions # (such as two references to the same variable). TODO: it would # probably be better to have the dict keyed by the n...
255
256
54,168
12
243
fperrin/mypy
mypy/checker.py
Python
TypeChecker
TypeChecker
153
5,667
153
153
8fe5bc5bb44b2d6216d9a594f0b80d054d8d693d
bigcode/the-stack
train
feed54e915611000a4e176c7
train
function
def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: Optional[Type] = None ) -> Tuple[Optional[Type], Optional[Type]]: """Takes in the current type and a proposed type of an expression. Returns a 2-...
def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: Optional[Type] = None ) -> Tuple[Optional[Type], Optional[Type]]:
"""Takes in the current type and a proposed type of an expression. Returns a 2-tuple: The first element is the proposed type, if the expression can be the proposed type. The second element is the type it would hold if it was not the proposed type, if any. UninhabitedType means unreachable. None mea...
_item = cast(Decorator, node.items[0]) return first_item.var.is_settable_property else: return False @overload def conditional_types(current_type: Type, proposed_type_ranges: Optional[List[TypeRange]], default: None = None ...
153
153
510
42
111
fperrin/mypy
mypy/checker.py
Python
conditional_types
conditional_types
5,684
5,728
5,684
5,687
16b8af0d07cee61dafeeb1f47b4920f6339713b2
bigcode/the-stack
train
476bb7a8991b180c99393b80
train
class
class DependencySettings(GClientKeywords): """Immutable configuration settings.""" def __init__( self, parent, url, managed, custom_deps, custom_vars, custom_hooks, deps_file, should_process, relative): GClientKeywords.__init__(self) # These are not mutable: self._parent = parent self._...
class DependencySettings(GClientKeywords):
"""Immutable configuration settings.""" def __init__( self, parent, url, managed, custom_deps, custom_vars, custom_hooks, deps_file, should_process, relative): GClientKeywords.__init__(self) # These are not mutable: self._parent = parent self._deps_file = deps_file self._url = url ...
, module_name, sub_target_name=None): """module_name is the dep module we want to include from. It can also be the name of a subdirectory to include from. sub_target_name is an optional parameter if the module name in the other DEPS file is different. E.g., you might want to map src/net to net...
250
250
836
7
243
AppGyver/depot_tools
gclient.py
Python
DependencySettings
DependencySettings
191
290
191
191
6965834a031805d8f9dddfb01b9033c48f430473
bigcode/the-stack
train
f2572834de7a761f31d1ed1c
train
class
class Dependency(gclient_utils.WorkItem, DependencySettings): """Object that represents a dependency checkout.""" def __init__(self, parent, name, url, managed, custom_deps, custom_vars, custom_hooks, deps_file, should_process, relative): gclient_utils.WorkItem.__init__(self, name...
class Dependency(gclient_utils.WorkItem, DependencySettings):
"""Object that represents a dependency checkout.""" def __init__(self, parent, name, url, managed, custom_deps, custom_vars, custom_hooks, deps_file, should_process, relative): gclient_utils.WorkItem.__init__(self, name) DependencySettings.__init__( self, parent, url, ...
# This line is to signal pylint that it could be a GClient instance. return self or GClient(None, None) return self.parent.root @property def should_process(self): """True if this dependency should be processed, i.e. checked out.""" return self._should_process @property def custom_vars...
256
256
7,278
11
245
AppGyver/depot_tools
gclient.py
Python
Dependency
Dependency
293
1,086
293
293
5176f3f093f043169f1df0007f7a044f633e49fe
bigcode/the-stack
train
9df058a075bf4ec6661d7432
train
function
def main(argv): """Doesn't parse the arguments here, just find the right subcommand to execute.""" if sys.hexversion < 0x02060000: print( '\nYour python version %s is unsupported, please upgrade.\n' % sys.version.split(' ', 1)[0], file=sys.stderr) return 2 if not sys.executable: ...
def main(argv):
"""Doesn't parse the arguments here, just find the right subcommand to execute.""" if sys.hexversion < 0x02060000: print( '\nYour python version %s is unsupported, please upgrade.\n' % sys.version.split(' ', 1)[0], file=sys.stderr) return 2 if not sys.executable: print( ...
stdout auto-flush so buildbot doesn't kill us during lengthy # operations. Python as a strong tendency to buffer sys.stdout. sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout) # Make stdout annotated with the thread ids. sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout) def main(argv):
68
68
229
4
64
AppGyver/depot_tools
gclient.py
Python
main
main
2,099
2,127
2,099
2,099
83015cd3e4e916929602f3e9b52f70799f3e126a
bigcode/the-stack
train
c470c9164708917a7eb9fb89
train
class
class OptionParser(optparse.OptionParser): gclientfile_default = os.environ.get('GCLIENT_FILE', '.gclient') def __init__(self, **kwargs): optparse.OptionParser.__init__( self, version='%prog ' + __version__, **kwargs) # Some arm boards have issues with parallel sync. if platform.machine().star...
class OptionParser(optparse.OptionParser):
gclientfile_default = os.environ.get('GCLIENT_FILE', '.gclient') def __init__(self, **kwargs): optparse.OptionParser.__init__( self, version='%prog ' + __version__, **kwargs) # Some arm boards have issues with parallel sync. if platform.machine().startswith('arm'): jobs = 1 else: ...
_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunOnDeps(None, []) # Look at each first-level dependency of this gclient only. for dep in client.dependencies: bad_deps = dep.findDepsFromNotAllowed...
189
189
631
8
180
AppGyver/depot_tools
gclient.py
Python
OptionParser
OptionParser
2,024
2,088
2,024
2,024
ae8c2a4d44102d6aea8a2c9cc1850c3708d6da64
bigcode/the-stack
train
06e2b3b76f7ef29eb5821a33
train
function
@subcommand.usage('[args ...]') def CMDfetch(parser, args): """Fetches upstream commits for all modules. Completely git-specific. Simply runs 'git fetch [args ...]' for each module. """ (options, args) = parser.parse_args(args) return CMDrecurse(OptionParser(), [ '--jobs=%d' % options.jobs, '--scm=git'...
@subcommand.usage('[args ...]') def CMDfetch(parser, args):
"""Fetches upstream commits for all modules. Completely git-specific. Simply runs 'git fetch [args ...]' for each module. """ (options, args) = parser.parse_args(args) return CMDrecurse(OptionParser(), [ '--jobs=%d' % options.jobs, '--scm=git', 'git', 'fetch'] + args)
.scm = scm_set options.nohooks = True client = GClient.LoadCurrentConfig(options) return client.RunOnDeps('recurse', args, ignore_requirements=True, progress=not options.no_progress) @subcommand.usage('[args ...]') def CMDfetch(parser, args):
64
64
93
16
48
AppGyver/depot_tools
gclient.py
Python
CMDfetch
CMDfetch
1,611
1,619
1,611
1,612
5dbc773970ddef6f2812365f00871e7041b4f2ed
bigcode/the-stack
train
a6778156cbaa7dba65745b12
train
function
def CMDstatus(parser, args): """Shows modification status for every dependencies.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' ...
def CMDstatus(parser, args):
"""Shows modification status for every dependencies.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' 'references') (opt...
client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') if options.verbose: client.PrintLocationAndContents() return client.RunOnDeps('pack', args) def CMDstatus(parser, args):
64
64
132
7
57
AppGyver/depot_tools
gclient.py
Python
CMDstatus
CMDstatus
1,755
1,767
1,755
1,755
9cb2a1fa1854fbce35f5e840916dd3a864f0ad1c
bigcode/the-stack
train
8572af29195439f61dcaed6c
train
function
def CMDrevert(parser, args): """Reverts all modifications in every dependencies. That's the nuclear option to get back to a 'clean' state. It removes anything that shows up in git status.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified...
def CMDrevert(parser, args):
"""Reverts all modifications in every dependencies. That's the nuclear option to get back to a 'clean' state. It removes anything that shows up in git status.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' ...
override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' 'references') (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not config...
104
104
349
8
96
AppGyver/depot_tools
gclient.py
Python
CMDrevert
CMDrevert
1,913
1,942
1,913
1,913
9a53fcaec41d8f75d346e12ec9ccec667d832dc4
bigcode/the-stack
train
ab9a35fbea213d7dd7cce5be
train
function
def CMDroot(parser, args): """Outputs the solution root (or current dir if there isn't one).""" (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if client: print(os.path.abspath(client.root_dir)) else: print(os.path.abspath('.'))
def CMDroot(parser, args):
"""Outputs the solution root (or current dir if there isn't one).""" (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if client: print(os.path.abspath(client.root_dir)) else: print(os.path.abspath('.'))
args[:2], args[2:] return CMDrecurse( parser, jobs_arg + ['--ignore', '--prepend-dir', '--no-progress', '--scm=git', 'git', 'grep', '--null', '--color=Always'] + args) def CMDroot(parser, args):
64
64
68
7
57
AppGyver/depot_tools
gclient.py
Python
CMDroot
CMDroot
1,651
1,658
1,651
1,651
ea3c620a6a3a47c386ac90e466278aa98a3bd5a7
bigcode/the-stack
train
82e85ece9407d32450e2bdb6
train
function
@subcommand.epilog("""Examples: gclient sync update files from SCM according to current configuration, *for modules which have changed since last update or sync* gclient sync --force update files from SCM according to current configuration, for all modules (useful for recovering files delete...
@subcommand.epilog("""Examples: gclient sync update files from SCM according to current configuration, *for modules which have changed since last update or sync* gclient sync --force update files from SCM according to current configuration, for all modules (useful for recovering files delete...
"""Checkout/update all modules.""" parser.add_option('-f', '--force', action='store_true', help='force update even for unchanged modules') parser.add_option('-n', '--nohooks', action='store_true', help='don\'t run hooks after the update is complete') parser.add_option('-p...
gclient_utils.Error('client not configured; see \'gclient config\'') if options.verbose: client.PrintLocationAndContents() return client.RunOnDeps('status', args) @subcommand.epilog("""Examples: gclient sync update files from SCM according to current configuration, *for modules which have changed...
256
256
1,408
217
39
AppGyver/depot_tools
gclient.py
Python
CMDsync
CMDsync
1,770
1,892
1,770
1,795
470f694ef2d4cd80989c42fecf1f31c56307a57e
bigcode/the-stack
train
e3eed24e4dfa34f1eff0a97a
train
function
def CMDhookinfo(parser, args): """Outputs the hooks that would be run by `gclient runhooks`.""" (options, args) = parser.parse_args(args) options.force = True client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunO...
def CMDhookinfo(parser, args):
"""Outputs the hooks that would be run by `gclient runhooks`.""" (options, args) = parser.parse_args(args) options.force = True client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunOnDeps(None, []) print('; '.jo...
(options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.PrintRevInfo() return 0 def CMDhookinfo(parser, args):
64
64
108
8
55
AppGyver/depot_tools
gclient.py
Python
CMDhookinfo
CMDhookinfo
1,991
2,000
1,991
1,991
ad555c61bf45f4c576b2df277171de1440cef425
bigcode/the-stack
train
008fb35f111a77260009840c
train
function
@subcommand.epilog("""Example: gclient pack > patch.txt generate simple patch for configured client and dependences """) def CMDpack(parser, args): """Generates a patch which can be applied at the root of the tree. Internally, runs 'git diff' on each checked out module and dependencies, and performs minima...
@subcommand.epilog("""Example: gclient pack > patch.txt generate simple patch for configured client and dependences """) def CMDpack(parser, args):
"""Generates a patch which can be applied at the root of the tree. Internally, runs 'git diff' on each checked out module and dependencies, and performs minimal postprocessing of the output. The resulting patch is printed to stdout and can be applied to a freshly checked out tree via 'patch -p0 < patchfile'....
ps_file client.SetDefaultConfig(name, deps_file, base_url, managed=not options.unmanaged, cache_dir=options.cache_dir) client.SaveConfig() return 0 @subcommand.epilog("""Example: gclient pack > patch.txt generate simple patch for configured client an...
78
78
262
36
41
AppGyver/depot_tools
gclient.py
Python
CMDpack
CMDpack
1,727
1,752
1,727
1,731
fa76a4041d90ac1b9af242d9ab41dae2fc65cd31
bigcode/the-stack
train
04436e99761befd853ffab37
train
function
def CMDgrep(parser, args): """Greps through git repos managed by gclient. Runs 'git grep [args...]' for each module. """ # We can't use optparse because it will try to parse arguments sent # to git grep and throw an error. :-( if not args or re.match('(-h|--help)$', args[0]): print( 'Usage: gcl...
def CMDgrep(parser, args):
"""Greps through git repos managed by gclient. Runs 'git grep [args...]' for each module. """ # We can't use optparse because it will try to parse arguments sent # to git grep and throw an error. :-( if not args or re.match('(-h|--help)$', args[0]): print( 'Usage: gclient grep [-j <N>] git-grep...
('[args ...]') def CMDfetch(parser, args): """Fetches upstream commits for all modules. Completely git-specific. Simply runs 'git fetch [args ...]' for each module. """ (options, args) = parser.parse_args(args) return CMDrecurse(OptionParser(), [ '--jobs=%d' % options.jobs, '--scm=git', 'git', 'fetch']...
95
95
318
7
88
AppGyver/depot_tools
gclient.py
Python
CMDgrep
CMDgrep
1,622
1,648
1,622
1,622
f4d21ddca62831e129805f3d38d86f6293fb0f18
bigcode/the-stack
train
a83b3fa596736ed958129548
train
function
def ast2str(node, indent=0): """Return a pretty-printed rendition of an ast.Node.""" t = type(node) if t is ast.Module: return '\n'.join([ast2str(x, indent) for x in node.body]) elif t is ast.Assign: return ((' ' * indent) + ' = '.join([ast2str(x) for x in node.targets] + ...
def ast2str(node, indent=0):
"""Return a pretty-printed rendition of an ast.Node.""" t = type(node) if t is ast.Module: return '\n'.join([ast2str(x, indent) for x in node.body]) elif t is ast.Assign: return ((' ' * indent) + ' = '.join([ast2str(x) for x in node.targets] + [ast2str(node.value, ind...
IUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git' def ast_dict_index(dnode, key): """Search an ast.Dict for the argument key, and return its index.""" idx = [i for i in range(len(dnode.keys)) if ( type(dnode.keys[i]) is ast.Str and dnode.keys[i].s == key)] if not idx: return -1 elif...
132
132
443
10
122
AppGyver/depot_tools
gclient.py
Python
ast2str
ast2str
121
157
121
121
18be2854c8d87b7e4416c2be49624bd654ba03dd
bigcode/the-stack
train
df2ea301329a7f655eb1a9f6
train
function
@subcommand.usage('[url]') def CMDconfig(parser, args): """Creates a .gclient file in the current directory. This specifies the configuration for further commands. After update/sync, top-level DEPS files in each module are read to determine dependent modules to operate on as well. If optional [url] parameter i...
@subcommand.usage('[url]') def CMDconfig(parser, args):
"""Creates a .gclient file in the current directory. This specifies the configuration for further commands. After update/sync, top-level DEPS files in each module are read to determine dependent modules to operate on as well. If optional [url] parameter is provided, then configuration is read from a specifie...
if re.match(r'(-j|--jobs=)\d+$', args[0]): jobs_arg, args = args[:1], args[1:] elif re.match(r'(-j|--jobs)$', args[0]): jobs_arg, args = args[:2], args[2:] return CMDrecurse( parser, jobs_arg + ['--ignore', '--prepend-dir', '--no-progress', '--scm=git', 'git', 'grep', '--nul...
197
198
663
15
182
AppGyver/depot_tools
gclient.py
Python
CMDconfig
CMDconfig
1,661
1,724
1,661
1,662
aaf66f60f8b8c13487a0f64e7e3736bdcaba3f92
bigcode/the-stack
train
3063627d0e35ea46018fa283
train
function
def CMDverify(parser, args): """Verifies the DEPS file deps are only from allowed_hosts.""" (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunOnDeps(None, []) # Look at...
def CMDverify(parser, args):
"""Verifies the DEPS file deps are only from allowed_hosts.""" (options, args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunOnDeps(None, []) # Look at each first-level dependency ...
(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') client.RunOnDeps(None, []) print('; '.join(' '.join(hook) for hook in client.GetHooks(options))) return 0 def CMDverify(parser, args):
64
64
212
7
56
AppGyver/depot_tools
gclient.py
Python
CMDverify
CMDverify
2,003
2,022
2,003
2,003
a35aec3e6c8f8855f482539f8a9bc44458af15d2
bigcode/the-stack
train
383e96563c1cafce67f75959
train
function
@subcommand.usage('[command] [args ...]') def CMDrecurse(parser, args): """Operates [command args ...] on all the dependencies. Runs a shell command on all entries. Sets GCLIENT_DEP_PATH environment variable as the dep's relative location to root directory of the checkout. """ # Stop parsing at the first n...
@subcommand.usage('[command] [args ...]') def CMDrecurse(parser, args):
"""Operates [command args ...] on all the dependencies. Runs a shell command on all entries. Sets GCLIENT_DEP_PATH environment variable as the dep's relative location to root directory of the checkout. """ # Stop parsing at the first non-arg so that these go through to the command parser.disable_interspe...
.""" return self._enforced_os @property def recursion_limit(self): """How recursive can each dependencies in DEPS file can load DEPS file.""" return self._recursion_limit @property def try_recursedeps(self): """Whether to attempt using recursedeps-style recursion processing.""" return True...
118
118
396
20
98
AppGyver/depot_tools
gclient.py
Python
CMDrecurse
CMDrecurse
1,569
1,608
1,569
1,570
2a573f3e1f98e640a8f8be81ce43d1bc98ae9b91
bigcode/the-stack
train
dc8292c8e4ab134cb2a7e29b
train
class
class GClientKeywords(object): class FromImpl(object): """Used to implement the From() syntax.""" def __init__(self, module_name, sub_target_name=None): """module_name is the dep module we want to include from. It can also be the name of a subdirectory to include from. sub_target_name is ...
class GClientKeywords(object):
class FromImpl(object): """Used to implement the From() syntax.""" def __init__(self, module_name, sub_target_name=None): """module_name is the dep module we want to include from. It can also be the name of a subdirectory to include from. sub_target_name is an optional parameter if the mo...
(len(node.keys))]) + '\n' + (' ' * indent) + '}') elif t is ast.Str: return "'%s'" % node.s else: raise gclient_utils.Error("Unexpected AST node at line %d, column %d: %s" % (node.lineno, node.col_offset, t)) class GClientKeywords(object):
81
81
271
6
75
AppGyver/depot_tools
gclient.py
Python
GClientKeywords
GClientKeywords
160
188
160
160
51d51070f0f61e010829e6f8a3ef0bd55c89e70c
bigcode/the-stack
train
20e4081ef974cc2cc6cf67b7
train
function
def CMDrevinfo(parser, args): """Outputs revision info mapping for the client and its dependencies. This allows the capture of an overall 'revision' for the source tree that can be used to reproduce the same tree in the future. It is only useful for 'unpinned dependencies', i.e. DEPS/deps references without a ...
def CMDrevinfo(parser, args):
"""Outputs revision info mapping for the client and its dependencies. This allows the capture of an overall 'revision' for the source tree that can be used to reproduce the same tree in the future. It is only useful for 'unpinned dependencies', i.e. DEPS/deps references without a git hash. A git branch name ...
args) = parser.parse_args(args) client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') if options.verbose: client.PrintLocationAndContents() options.force = True options.nohooks = False return client.RunOnDeps('runhooks'...
86
86
289
8
78
AppGyver/depot_tools
gclient.py
Python
CMDrevinfo
CMDrevinfo
1,964
1,988
1,964
1,964
774020e3a88343b949d73b40fdc54c4685ca0f64
bigcode/the-stack
train
54117c0097808610410abca1
train
function
def ast_dict_index(dnode, key): """Search an ast.Dict for the argument key, and return its index.""" idx = [i for i in range(len(dnode.keys)) if ( type(dnode.keys[i]) is ast.Str and dnode.keys[i].s == key)] if not idx: return -1 elif len(idx) > 1: raise gclient_utils.Error('Multiple dict entries w...
def ast_dict_index(dnode, key):
"""Search an ast.Dict for the argument key, and return its index.""" idx = [i for i in range(len(dnode.keys)) if ( type(dnode.keys[i]) is ast.Str and dnode.keys[i].s == key)] if not idx: return -1 elif len(idx) > 1: raise gclient_utils.Error('Multiple dict entries with same key in AST') return i...
import gclient_utils import git_cache from third_party.repo.progress import Progress import subcommand import subprocess2 import setup_color import shutil CHROMIUM_SRC_URL = 'https://chromium.googlesource.com/chromium/src.git' def ast_dict_index(dnode, key):
64
64
102
9
55
AppGyver/depot_tools
gclient.py
Python
ast_dict_index
ast_dict_index
111
119
111
111
50bae15ebbf84058f9111cbb093f9e93292feb0e
bigcode/the-stack
train
eece04e9377e52c6a38df9eb
train
function
def CMDrunhooks(parser, args): """Runs hooks for files that have been modified in the local working copy.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all de...
def CMDrunhooks(parser, args):
"""Runs hooks for files that have been modified in the local working copy.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' ...
rees = False options.merge = False client = GClient.LoadCurrentConfig(options) if not client: raise gclient_utils.Error('client not configured; see \'gclient config\'') return client.RunOnDeps('revert', args) def CMDrunhooks(parser, args):
64
64
181
9
55
AppGyver/depot_tools
gclient.py
Python
CMDrunhooks
CMDrunhooks
1,945
1,961
1,945
1,945
0f1b93b2264468c5f51cc64864633963a51fa7fc
bigcode/the-stack
train
9f31204b7b0df4dd3dc64040
train
function
def disable_buffering(): # Make stdout auto-flush so buildbot doesn't kill us during lengthy # operations. Python as a strong tendency to buffer sys.stdout. sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout) # Make stdout annotated with the thread ids. sys.stdout = gclient_utils.MakeFileAnnotated(sys.st...
def disable_buffering(): # Make stdout auto-flush so buildbot doesn't kill us during lengthy # operations. Python as a strong tendency to buffer sys.stdout.
sys.stdout = gclient_utils.MakeFileAutoFlush(sys.stdout) # Make stdout annotated with the thread ids. sys.stdout = gclient_utils.MakeFileAnnotated(sys.stdout)
options.deps_os = None if not hasattr(options, 'force'): options.force = None return (options, args) def disable_buffering(): # Make stdout auto-flush so buildbot doesn't kill us during lengthy # operations. Python as a strong tendency to buffer sys.stdout.
64
64
72
35
29
AppGyver/depot_tools
gclient.py
Python
disable_buffering
disable_buffering
2,091
2,096
2,091
2,093
7c4fc86e9e7376627f2c21d1a2a7954dac46cce7
bigcode/the-stack
train
222e739415ab2653c08e292d
train
class
class GClient(Dependency): """Object that represent a gclient checkout. A tree of Dependency(), one per solution or DEPS entry.""" DEPS_OS_CHOICES = { "win32": "win", "win": "win", "cygwin": "win", "darwin": "mac", "mac": "mac", "unix": "unix", "linux": "unix", "linux2": "unix", ...
class GClient(Dependency):
"""Object that represent a gclient checkout. A tree of Dependency(), one per solution or DEPS entry.""" DEPS_OS_CHOICES = { "win32": "win", "win": "win", "cygwin": "win", "darwin": "mac", "mac": "mac", "unix": "unix", "linux": "unix", "linux2": "unix", "linux3": "unix", "a...
', 'parsed_url', 'custom_deps', 'custom_vars', 'deps_hooks', 'file_list', 'should_process', 'processed', 'hooks_ran', 'deps_parsed', 'requirements', 'allowed_hosts'): # First try the native property if it exists. if hasattr(self, '_' + i): value = getattr(se...
256
256
4,289
6
249
AppGyver/depot_tools
gclient.py
Python
GClient
GClient
1,089
1,563
1,089
1,089
59df8864273811d45c1edb597e1d6ade5de8cd71
bigcode/the-stack
train
aa57a45f35c7f43e0eda0ce5
train
function
def CMDdiff(parser, args): """Displays local diff for every dependencies.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' ...
def CMDdiff(parser, args):
"""Displays local diff for every dependencies.""" parser.add_option('--deps', dest='deps_os', metavar='OS_LIST', help='override deps for the specified (comma-separated) ' 'platform(s); \'all\' will process all deps_os ' 'references') (options, ...
d.used_scm else None, 'url': str(d.url) if d.url else None, } with open(options.output_json, 'wb') as f: json.dump({'solutions': slns}, f) return ret CMDupdate = CMDsync def CMDdiff(parser, args):
64
64
132
7
56
AppGyver/depot_tools
gclient.py
Python
CMDdiff
CMDdiff
1,898
1,910
1,898
1,898
94912b34c67542e1600f73ece74dfa9b3a245d22
bigcode/the-stack
train
8da242472327e8751fd2e8d4
train
function
def test_swi_ts_reader_no_data_in_folder(): """ Test SWI time series reader when no data is in folder. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts_non_existing') with pytest.raises(IOError): SWI_TS(data_path)
def test_swi_ts_reader_no_data_in_folder():
""" Test SWI time series reader when no data is in folder. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts_non_existing') with pytest.raises(IOError): SWI_TS(data_path)
is there reference_index = pd.date_range('20070101T12:00:00', '20161231T12:00:00') assert len(data) == len(reference_index) assert np.all(data_sorted.index == reference_index) def test_swi_ts_reader_no_data_in_folder():
64
64
76
11
53
joostbarten/ascat
tests/test_cgls.py
Python
test_swi_ts_reader_no_data_in_folder
test_swi_ts_reader_no_data_in_folder
67
75
67
67
87f3f0ae91d6193d802cee570ba69aadfa7d3db3
bigcode/the-stack
train
52f139ac6b4f92b6c50e6284
train
function
def test_swi_ts_qflag_reading(): """ Test SWI time series quality flag reader. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts') rd = SWI_TS(data_path, parameters=['SWI_001', 'QFLAG_001', 'SSF']) data = rd.read_ts(3002621, mask_frozen=True) ...
def test_swi_ts_qflag_reading():
""" Test SWI time series quality flag reader. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts') rd = SWI_TS(data_path, parameters=['SWI_001', 'QFLAG_001', 'SSF']) data = rd.read_ts(3002621, mask_frozen=True) # check if QFLAG is correctly ...
data is in folder. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts_non_existing') with pytest.raises(IOError): SWI_TS(data_path) def test_swi_ts_qflag_reading():
64
64
177
10
54
joostbarten/ascat
tests/test_cgls.py
Python
test_swi_ts_qflag_reading
test_swi_ts_qflag_reading
78
90
78
78
14187c97191764b06e5c19209b330c604a5aa7fc
bigcode/the-stack
train
44cff2efbf5c9e5533ba564f
train
function
def test_swi_ts_reader(): """ Test SWI time series reader. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts') rd = SWI_TS(data_path) data = rd.read_ts(3002621, mask_frozen=False) data_sorted = data.sort_index() assert np.all(data_sor...
def test_swi_ts_reader():
""" Test SWI time series reader. """ data_path = os.path.join( os.path.dirname(__file__), 'ascat_test_data', 'cglops', 'swi_ts') rd = SWI_TS(data_path) data = rd.read_ts(3002621, mask_frozen=False) data_sorted = data.sort_index() assert np.all(data_sorted.index == data.index) ...
TORT (INCLUDING NEGLIGENCE OR # OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ Tests for reading CGLOPS SWI data. """ from ascat.cgls import SWI_TS import os import pandas as pd import numpy as np import pytest def test_swi_ts_reader():
79
79
266
7
71
joostbarten/ascat
tests/test_cgls.py
Python
test_swi_ts_reader
test_swi_ts_reader
39
64
39
39
b6e07eb00c293ee5c3eecd07d89bbaa943112841
bigcode/the-stack
train
da327353b301784cf6889ead
train
function
def create_account(id, type, data): url = 'http://localhost:8080/api/v0.1/user/' + str(id) + '/account/' + type r = requests.put( url, data=data) pprint.pprint(r.json())
def create_account(id, type, data):
url = 'http://localhost:8080/api/v0.1/user/' + str(id) + '/account/' + type r = requests.put( url, data=data) pprint.pprint(r.json())
requests.post( 'http://localhost:8080/api/v0.1/auth/register', data=payload) if r.status_code != 200: return None pprint.pprint(r.json()) user = r.json() return user['_id'] def create_account(id, type, data):
64
64
55
9
55
udaik/typescript-express-starter
server/src/kick-start/db_populate.py
Python
create_account
create_account
25
28
25
25
0821ce63d779b8c698b48d9716a9913354c633bd
bigcode/the-stack
train
8d15c78f7faf3bb20e21c8b2
train
function
def create_user(): username = "s.udaikiran@gmail.com" payload = { 'mmUserName': username, 'password': 'password', 'password2': 'password' } r = requests.post( 'http://localhost:8080/api/v0.1/auth/register', data=payload) if r.status_code != 200: return None ...
def create_user():
username = "s.udaikiran@gmail.com" payload = { 'mmUserName': username, 'password': 'password', 'password2': 'password' } r = requests.post( 'http://localhost:8080/api/v0.1/auth/register', data=payload) if r.status_code != 200: return None pprint.ppr...
import requests import json import pprint def create_user():
13
64
103
4
8
udaik/typescript-express-starter
server/src/kick-start/db_populate.py
Python
create_user
create_user
6
22
6
6
6141065159201781e42ab6a5166562a0a3684a38
bigcode/the-stack
train
f68f4c3770b4d188fca09c45
train
function
def bankAccountGet(userId, type, data): url = 'http://localhost:8080/api/v0.1/user/' + str(id) + '/account/' + type r = requests.get(url, data=data) pprint.pprint(r.json())
def bankAccountGet(userId, type, data):
url = 'http://localhost:8080/api/v0.1/user/' + str(id) + '/account/' + type r = requests.get(url, data=data) pprint.pprint(r.json())
NAGENDLA', 'description' : 'MC-SBI HL MAXGAIN (WOM) JUN 17', 'bookBalance' : 0, 'availableBalance' : 0, 'drawingPower' : 0 } def bankAccountGet(userId, type, data):
64
64
56
11
53
udaik/typescript-express-starter
server/src/kick-start/db_populate.py
Python
bankAccountGet
bankAccountGet
78
81
78
78
51b5bbae37023ba51628ad496b1cb70595b8b1c2
bigcode/the-stack
train
8b81d1370ffea05835cff34c
train
class
class ThreadPool(object): mapWorkerThreads = {} activeWorkerThreads = [] inactiveWorkerThreads = [] mapPackageToCycle = {} pkgBuildType = "chroot" logger = None statusEvent = None @staticmethod def clear(): ThreadPool.mapWorkerThreads.clear() ThreadPool.activeWorker...
class ThreadPool(object):
mapWorkerThreads = {} activeWorkerThreads = [] inactiveWorkerThreads = [] mapPackageToCycle = {} pkgBuildType = "chroot" logger = None statusEvent = None @staticmethod def clear(): ThreadPool.mapWorkerThreads.clear() ThreadPool.activeWorkerThreads = [] Thread...
import WorkerThread class ThreadPool(object):
9
120
401
5
3
username-is-already-taken2/photon
support/package-builder/ThreadPool.py
Python
ThreadPool
ThreadPool
3
61
3
4
d055911d359c9d62ed2739dde5c1f849b97da72e
bigcode/the-stack
train
3a47ccbbd1a4133a7c980c4a
train
class
class LightningNode(object): def __init__(self, node_id, lightning_dir, zcored, executor, may_fail=False, may_reconnect=False, allow_broken_log=False, allow_bad_gossip=False, db=None, port=None, disconnect=None, random_hsm=None, log_all_io=None, options=None, **kwargs): sel...
class LightningNode(object):
def __init__(self, node_id, lightning_dir, zcored, executor, may_fail=False, may_reconnect=False, allow_broken_log=False, allow_bad_gossip=False, db=None, port=None, disconnect=None, random_hsm=None, log_all_io=None, options=None, **kwargs): self.zcore = zcored self...
self.disconnect_file: with open(self.disconnect_file, "w") as f: f.truncate() @property def cmd_line(self): opts = [] for k, v in self.opts.items(): if v is None: opts.append("--{}".format(k)) elif isinstance(v, list): ...
256
256
3,376
5
250
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
LightningNode
LightningNode
542
900
542
542
db47ab95ccf366a6b978d5054db9ceaec5b2fd32
bigcode/the-stack
train
39ef165c88e7bfdac0d33051
train
class
class ZCoreD(TailableProc): def __init__(self, zcore_dir="/tmp/zcored-test", rpcport=None): TailableProc.__init__(self, zcore_dir, verbose=False) if rpcport is None: rpcport = reserve() self.zcore_dir = zcore_dir self.rpcport = rpcport self.prefix = 'zcored' ...
class ZCoreD(TailableProc):
def __init__(self, zcore_dir="/tmp/zcored-test", rpcport=None): TailableProc.__init__(self, zcore_dir, verbose=False) if rpcport is None: rpcport = reserve() self.zcore_dir = zcore_dir self.rpcport = rpcport self.prefix = 'zcored' regtestdir = os.path.j...
the logs. Convenience wrapper for the common case of only seeking a single entry. """ return self.wait_for_logs([regex], timeout) class SimpleZCoreProxy: """Wrapper for ZCoreProxy to reconnect. Long wait times between calls to the ZCore RPC could result in `zcored` closing the c...
256
256
1,146
8
247
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
ZCoreD
ZCoreD
302
416
302
303
2140c289ac9b3df7c61323530d5554cf3fc2e87f
bigcode/the-stack
train
9e5090b686d0e79f4a1acc5c
train
function
def get_tx_p2wsh_outnum(zcored, tx, amount): """Get output number of this tx which is p2wsh of amount""" decoded = zcored.rpc.decoderawtransaction(tx, True) for out in decoded['vout']: if out['scriptPubKey']['type'] == 'witness_v0_scripthash': if out['value'] == Decimal(amount) / 10**8:...
def get_tx_p2wsh_outnum(zcored, tx, amount):
"""Get output number of this tx which is p2wsh of amount""" decoded = zcored.rpc.decoderawtransaction(tx, True) for out in decoded['vout']: if out['scriptPubKey']['type'] == 'witness_v0_scripthash': if out['value'] == Decimal(amount) / 10**8: return out['n'] return ...
['channels'])['htlcs'] == []) wait_for(lambda: only_one(only_one(n2.rpc.listpeers(n1.info['id'])['peers'])['channels'])['htlcs'] == []) def get_tx_p2wsh_outnum(zcored, tx, amount):
63
64
104
17
46
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
get_tx_p2wsh_outnum
get_tx_p2wsh_outnum
116
125
116
116
75d900dad9ac4ffa5abc5f00476a9332779bde30
bigcode/the-stack
train
be816d7a4592d402bf5afce3
train
class
class LightningD(TailableProc): def __init__(self, lightning_dir, zcoredproxy, port=9735, random_hsm=False, node_id=0): TailableProc.__init__(self, lightning_dir) self.executable = 'lightningd' self.lightning_dir = lightning_dir self.port = port self.cmd_prefix = [] s...
class LightningD(TailableProc):
def __init__(self, lightning_dir, zcoredproxy, port=9735, random_hsm=False, node_id=0): TailableProc.__init__(self, lightning_dir) self.executable = 'lightningd' self.lightning_dir = lightning_dir self.port = port self.cmd_prefix = [] self.disconnect_file = None ...
blocks=1, wait_for_mempool=0): if wait_for_mempool: if isinstance(wait_for_mempool, str): wait_for_mempool = [wait_for_mempool] if isinstance(wait_for_mempool, list): wait_for(lambda: all(txid in self.rpc.getrawmempool() for txid in wait_for_mempool)) ...
193
193
645
7
186
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
LightningD
LightningD
465
539
465
465
248d770eefa871f415cddb175847ff0edce5c3c8
bigcode/the-stack
train
50b03f2d7c3a8b3e223689d7
train
class
class SimpleZCoreProxy: """Wrapper for ZCoreProxy to reconnect. Long wait times between calls to the ZCore RPC could result in `zcored` closing the connection, so here we just create throwaway connections. This is easier than to reach into the RPC library to close, reopen and reauth upon failure. ...
class SimpleZCoreProxy:
"""Wrapper for ZCoreProxy to reconnect. Long wait times between calls to the ZCore RPC could result in `zcored` closing the connection, so here we just create throwaway connections. This is easier than to reach into the RPC library to close, reopen and reauth upon failure. """ def __init__(...
] pos += 1 def wait_for_log(self, regex, timeout=TIMEOUT): """Look for `regex` in the logs. Convenience wrapper for the common case of only seeking a single entry. """ return self.wait_for_logs([regex], timeout) class SimpleZCoreProxy:
65
65
218
6
59
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
SimpleZCoreProxy
SimpleZCoreProxy
274
299
274
274
3085ca00e29bfc82267762120303d2a452d9128e
bigcode/the-stack
train
19c721ffd1d0c08058b40f21
train
class
class NodeFactory(object): """A factory to setup and start `lightningd` daemons. """ def __init__(self, testname, zcored, executor, directory, db_provider, node_cls): self.testname = testname self.next_id = 1 self.nodes = [] self.executor = executor self.zcored = zcor...
class NodeFactory(object):
"""A factory to setup and start `lightningd` daemons. """ def __init__(self, testname, zcored, executor, directory, db_provider, node_cls): self.testname = testname self.next_id = 1 self.nodes = [] self.executor = executor self.zcored = zcored self.directory =...
def query_gossip(self, querytype, *args, filters=[]): """Generate a gossip query, feed it into this node and get responses in hex""" query = subprocess.run(['devtools/mkquery', querytype] + [str(a) for a in args], check=True, ...
256
256
1,688
5
250
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
NodeFactory
NodeFactory
903
1,099
903
903
d416a8512c07fcf96dda3122b0c38595bc0e528f
bigcode/the-stack
train
e6a35dc7f13538f4433f1456
train
function
def sync_blockheight(zcored, nodes): height = zcored.rpc.getblockchaininfo()['blocks'] for n in nodes: wait_for(lambda: n.rpc.getinfo()['blockheight'] == height)
def sync_blockheight(zcored, nodes):
height = zcored.rpc.getblockchaininfo()['blocks'] for n in nodes: wait_for(lambda: n.rpc.getinfo()['blockheight'] == height)
(): f.write("{}={}\n".format(k, v)) def only_one(arr): """Many JSON RPC calls return an array; often we only expect a single entry """ assert len(arr) == 1 return arr[0] def sync_blockheight(zcored, nodes):
64
64
46
10
54
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
sync_blockheight
sync_blockheight
105
108
105
105
b19a845a82d0b1ca05c77c833eaae0e94e1cb5dc
bigcode/the-stack
train
b773aa875a0a3750d936b647
train
function
def wait_channel_quiescent(n1, n2): wait_for(lambda: only_one(only_one(n1.rpc.listpeers(n2.info['id'])['peers'])['channels'])['htlcs'] == []) wait_for(lambda: only_one(only_one(n2.rpc.listpeers(n1.info['id'])['peers'])['channels'])['htlcs'] == [])
def wait_channel_quiescent(n1, n2):
wait_for(lambda: only_one(only_one(n1.rpc.listpeers(n2.info['id'])['peers'])['channels'])['htlcs'] == []) wait_for(lambda: only_one(only_one(n2.rpc.listpeers(n1.info['id'])['peers'])['channels'])['htlcs'] == [])
return arr[0] def sync_blockheight(zcored, nodes): height = zcored.rpc.getblockchaininfo()['blocks'] for n in nodes: wait_for(lambda: n.rpc.getinfo()['blockheight'] == height) def wait_channel_quiescent(n1, n2):
64
64
84
12
52
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
wait_channel_quiescent
wait_channel_quiescent
111
113
111
111
b8ea32f95224929c9ed72a49f72d08f5e2a1489a
bigcode/the-stack
train
1943ec964a63d15fa9c7ffdb
train
function
def wait_for(success, timeout=TIMEOUT): start_time = time.time() interval = 0.25 while not success() and time.time() < start_time + timeout: time.sleep(interval) interval *= 2 if interval > 5: interval = 5 if time.time() > start_time + timeout: raise ValueErro...
def wait_for(success, timeout=TIMEOUT):
start_time = time.time() interval = 0.25 while not success() and time.time() < start_time + timeout: time.sleep(interval) interval *= 2 if interval > 5: interval = 5 if time.time() > start_time + timeout: raise ValueError("Error waiting for {}", success)
1" SLOW_MACHINE = env("SLOW_MACHINE", "0") == "1" TIMEOUT = int(env("TIMEOUT", 180 if SLOW_MACHINE else 60)) if TEST_DEBUG: logging.basicConfig(level=logging.DEBUG, stream=sys.stdout) def wait_for(success, timeout=TIMEOUT):
64
64
86
10
54
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
wait_for
wait_for
76
85
76
76
a99728166b187c01cbde9e54e40d608cf7b099be
bigcode/the-stack
train
0c6331ff5da57c0f456ea23d
train
class
class TailableProc(object): """A monitorable process that we can start, stop and tail. This is the base class for the daemons. It allows us to directly tail the processes and react to their output. """ def __init__(self, outputDir=None, verbose=True): self.logs = [] self.logs_cond ...
class TailableProc(object):
"""A monitorable process that we can start, stop and tail. This is the base class for the daemons. It allows us to directly tail the processes and react to their output. """ def __init__(self, outputDir=None, verbose=True): self.logs = [] self.logs_cond = threading.Condition(thread...
assert len(arr) == 1 return arr[0] def sync_blockheight(zcored, nodes): height = zcored.rpc.getblockchaininfo()['blocks'] for n in nodes: wait_for(lambda: n.rpc.getinfo()['blockheight'] == height) def wait_channel_quiescent(n1, n2): wait_for(lambda: only_one(only_one(n1.rpc.listpeers(n2....
256
256
1,070
6
249
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
TailableProc
TailableProc
128
271
128
128
3868bbfb7763705b3f29f59f31441b159de60301
bigcode/the-stack
train
a94f8cfb3015570c190dae82
train
class
class ElementsD(ZCoreD): def __init__(self, zcore_dir="/tmp/zcored-test", rpcport=None): config = ZCORED_CONFIG.copy() if 'regtest' in config: del config['regtest'] config['chain'] = 'liquid-regtest' ZCoreD.__init__(self, zcore_dir, rpcport) self.cmd_line = [ ...
class ElementsD(ZCoreD):
def __init__(self, zcore_dir="/tmp/zcored-test", rpcport=None): config = ZCORED_CONFIG.copy() if 'regtest' in config: del config['regtest'] config['chain'] = 'liquid-regtest' ZCoreD.__init__(self, zcore_dir, rpcport) self.cmd_line = [ 'elementsd', ...
so they are not mined self.rpc.prioritisetransaction(txid, None, -fee_delta) hashes += self.generate_block(shift) for txid in memp: # restore priority so they are mined self.rpc.prioritisetransaction(txid, None, fee_delta) hashes += s...
130
130
435
7
123
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
ElementsD
ElementsD
419
462
419
419
36e842b75b54006ccc62949ca8b94f310bf00db9
bigcode/the-stack
train
887815a418a585e4b9d68697
train
function
def env(name, default=None): """Access to environment variables Allows access to environment variables, falling back to config.vars (part of c-lightning's `./configure` output), and finally falling back to a default value. """ fname = 'config.vars' if os.path.exists(fname): lines =...
def env(name, default=None):
"""Access to environment variables Allows access to environment variables, falling back to config.vars (part of c-lightning's `./configure` output), and finally falling back to a default value. """ fname = 'config.vars' if os.path.exists(fname): lines = open(fname, 'r').readlines()...
OrderedDict({ "log-level": "debug", "cltv-delta": 6, "cltv-final": 5, "watchtime-blocks": 5, "rescan": 1, 'disable-dns': None, }) def env(name, default=None):
64
64
137
7
57
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
env
env
41
61
41
41
6b6a43c0c7586451de7447f4e08b50b3f7079833
bigcode/the-stack
train
db813c03d56763f88ac6bfd2
train
function
def only_one(arr): """Many JSON RPC calls return an array; often we only expect a single entry """ assert len(arr) == 1 return arr[0]
def only_one(arr):
"""Many JSON RPC calls return an array; often we only expect a single entry """ assert len(arr) == 1 return arr[0]
in opts.items(): f.write("{}={}\n".format(k, v)) if regtest_opts: f.write("[{}]\n".format(section_name)) for k, v in regtest_opts.items(): f.write("{}={}\n".format(k, v)) def only_one(arr):
64
64
40
5
59
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
only_one
only_one
98
102
98
98
ac797fb6d5d490e498c5f90c9fc32d130357825f
bigcode/the-stack
train
1f11290f60389d723fbc0578
train
function
def write_config(filename, opts, regtest_opts=None, section_name='regtest'): with open(filename, 'w') as f: for k, v in opts.items(): f.write("{}={}\n".format(k, v)) if regtest_opts: f.write("[{}]\n".format(section_name)) for k, v in regtest_opts.items(): ...
def write_config(filename, opts, regtest_opts=None, section_name='regtest'):
with open(filename, 'w') as f: for k, v in opts.items(): f.write("{}={}\n".format(k, v)) if regtest_opts: f.write("[{}]\n".format(section_name)) for k, v in regtest_opts.items(): f.write("{}={}\n".format(k, v))
time.sleep(interval) interval *= 2 if interval > 5: interval = 5 if time.time() > start_time + timeout: raise ValueError("Error waiting for {}", success) def write_config(filename, opts, regtest_opts=None, section_name='regtest'):
64
64
93
18
46
mosqueiro/lightning
contrib/pyln-testing/pyln/testing/utils.py
Python
write_config
write_config
88
95
88
88
5ad1f5ee9aa61c111a3fdc52e5a06f10d658d068
bigcode/the-stack
train
6e6309d1054904bdd824bfe0
train
class
@optendersresource( name="esco:Tender Award Complaint Post Documents", collection_path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents", path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents/{document_id}", procuremen...
@optendersresource( name="esco:Tender Award Complaint Post Documents", collection_path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents", path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents/{document_id}", procuremen...
pass
@optendersresource( name="esco:Tender Award Complaint Post Documents", collection_path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents", path="/tenders/{tender_id}/awards/{award_id}/complaints/{complaint_id}/posts/{post_id}/documents/{document_id}", procuremen...
111
64
114
111
0
pontostroy/api
src/openprocurement/tender/esco/views/award_complaint_post_document.py
Python
TenderAwardComplaintPostDocumentResource
TenderAwardComplaintPostDocumentResource
6
14
6
13
c61037455d6b064044f4dcc3c350243384c108b5
bigcode/the-stack
train
e4c48dc68d9f03c9ae6a7b76
train
class
class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nu...
class Migration(migrations.Migration):
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.IntegerField()), ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-09-10 22:09 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
61
64
165
7
53
GouravSardana/MDU_FACULTY_HOUSING
housing/migrations/0001_initial.py
Python
Migration
Migration
9
32
9
10
9b15170c5c5fd81b4230c39defe80a042749230f
bigcode/the-stack
train
96fae9f0ad9346be35a881a4
train
function
def exibeMsg(): print(("Criando Funções!!!"))
def exibeMsg():
print(("Criando Funções!!!"))
def exibeMsg():
5
64
14
5
0
FR7/Meus-Projetos
IMPACTA/Unid03_Sem7.py/exe_aula7.py
Python
exibeMsg
exibeMsg
1
2
1
1
c3556240e50a9cee154a20c4561608fa763cdec7
bigcode/the-stack
train
89f265c1171dd10b7918e967
train
function
def read_package_variable(key): """Read the value of a variable from the package without importing.""" module_path = os.path.join(PACKAGE_NAME, '__init__.py') with open(module_path) as module: for line in module: parts = line.strip().split(' ') if parts and parts[0] == key: ...
def read_package_variable(key):
"""Read the value of a variable from the package without importing.""" module_path = os.path.join(PACKAGE_NAME, '__init__.py') with open(module_path) as module: for line in module: parts = line.strip().split(' ') if parts and parts[0] == key: return parts[-1]....
_VERSION = 3, 5 def check_python_version(): """Exit when the Python version is too low.""" if sys.version_info < MINIMUM_PYTHON_VERSION: sys.exit("Python {}.{}+ is required.".format(*MINIMUM_PYTHON_VERSION)) def read_package_variable(key):
64
64
103
6
58
FrancescoPinto/pyprob
setup.py
Python
read_package_variable
read_package_variable
14
22
14
14
b3cefcbb4927206abbc4e6a4b42126e5e1313834
bigcode/the-stack
train
48a7d869fff977f26f2b898a
train
function
def check_python_version(): """Exit when the Python version is too low.""" if sys.version_info < MINIMUM_PYTHON_VERSION: sys.exit("Python {}.{}+ is required.".format(*MINIMUM_PYTHON_VERSION))
def check_python_version():
"""Exit when the Python version is too low.""" if sys.version_info < MINIMUM_PYTHON_VERSION: sys.exit("Python {}.{}+ is required.".format(*MINIMUM_PYTHON_VERSION))
import os import sys from setuptools import setup, find_packages PACKAGE_NAME = 'pyprob' MINIMUM_PYTHON_VERSION = 3, 5 def check_python_version():
39
64
50
5
33
FrancescoPinto/pyprob
setup.py
Python
check_python_version
check_python_version
8
11
8
8
fe14ea1423f8bea235598200d4703098c5deb458
bigcode/the-stack
train
4533735ed043495d89bae163
train
class
class OSMPlacesConnector(IEnricherConnector): """OSMconnector implements interface IEnricherConnector, so this is a connector that can be used to enrich data. Parameters ---------- dict_keys: List[str] dict_keys is the principal argument to the connector. The connector doesn't know where to get...
class OSMPlacesConnector(IEnricherConnector):
"""OSMconnector implements interface IEnricherConnector, so this is a connector that can be used to enrich data. Parameters ---------- dict_keys: List[str] dict_keys is the principal argument to the connector. The connector doesn't know where to get data to make the relationship, so you have to...
from moredata.models.data import GeopandasData, JsonData from ..enricher import IEnricherConnector from ...utils import OSM_util import pandas as pd from shapely import wkt import geopandas import pyproj from functools import partial from shapely.geometry import MultiPolygon, Polygon from shapely.ops import transform...
132
256
1,240
11
120
thomassonobe/more-data
moredata/enricher/osm/osm_places_connector.py
Python
OSMPlacesConnector
OSMPlacesConnector
21
193
21
21
1e025235d8bcc772192cd864149d4f29e6f6373f
bigcode/the-stack
train
7d65268fcd177be2285f6742
train
class
@dataclass class LinkedList: """Doubly linked list which unlinks entries from any other list they might be in when they are added. See https://github.com/dagrejs/dagre/blob/933822b991ea9b077521e5b797b8b4927c94f0a4/lib/data/list.js""" sentinel: LinkedListEntry = field(default_factory=lambda: LinkedListEntry(...
@dataclass class LinkedList:
"""Doubly linked list which unlinks entries from any other list they might be in when they are added. See https://github.com/dagrejs/dagre/blob/933822b991ea9b077521e5b797b8b4927c94f0a4/lib/data/list.js""" sentinel: LinkedListEntry = field(default_factory=lambda: LinkedListEntry(None)) def enqueue(s...
Entry | None' = None prev: 'LinkedListEntry | None' = None def unlink(self): if self.prev is not None: self.prev.next = self.next if self.next is not None: self.next.prev = self.prev @dataclass class LinkedList:
64
64
192
7
56
norabelrose/whisper
classroom/fas.py
Python
LinkedList
LinkedList
27
46
27
28
4e40c71558515ce1fd3bdb7738a566d7f38b5e56
bigcode/the-stack
train
e2f2543f357e5dcb0cbe9d9b
train
class
@dataclass class LinkedListEntry: value: Any next: 'LinkedListEntry | None' = None prev: 'LinkedListEntry | None' = None def unlink(self): if self.prev is not None: self.prev.next = self.next if self.next is not None: self.next.prev = self.prev
@dataclass class LinkedListEntry:
value: Any next: 'LinkedListEntry | None' = None prev: 'LinkedListEntry | None' = None def unlink(self): if self.prev is not None: self.prev.next = self.next if self.next is not None: self.next.prev = self.prev
use heuristics to find decent approximations. <https://en.wikipedia.org/wiki/Feedback_arc_set> """ from dataclasses import dataclass, field from typing import Any, cast, Iterable, Literal import networkx as nx import numpy as np import random @dataclass class LinkedListEntry:
64
64
76
8
55
norabelrose/whisper
classroom/fas.py
Python
LinkedListEntry
LinkedListEntry
15
25
15
16
82d362afa0e75b5accfc9aa0cd648ec25be13ad7
bigcode/the-stack
train
5cdb6b5e85f03673cb0de8d7
train
function
def max_acyclic_subgraph( graph: nx.DiGraph, method: Literal['berger_shor', 'eades'], seed: int | None = 42, # None for non-deterministic output; ignored by Eades ) -> nx.DiGraph: """Given a potentially cyclic digraph, return (an approximation to) the maximum acyclic subgraph.""" ma...
def max_acyclic_subgraph( graph: nx.DiGraph, method: Literal['berger_shor', 'eades'], seed: int | None = 42, # None for non-deterministic output; ignored by Eades ) -> nx.DiGraph:
"""Given a potentially cyclic digraph, return (an approximation to) the maximum acyclic subgraph.""" match method: case 'berger_shor': return fas_to_max_acyclic_subgraph(graph, berger_shor_fas(graph, seed=seed)) case 'eades': return fas_to_max_acyclic_subgraph(graph, eade...
graph def max_acyclic_subgraph( graph: nx.DiGraph, method: Literal['berger_shor', 'eades'], seed: int | None = 42, # None for non-deterministic output; ignored by Eades ) -> nx.DiGraph:
64
64
158
62
1
norabelrose/whisper
classroom/fas.py
Python
max_acyclic_subgraph
max_acyclic_subgraph
161
173
161
165
2db1502aec06b44a8d74b9bd8942b2f31d4104d0
bigcode/the-stack
train
a530ee60284ddca27b7a31ca
train
function
def berger_shor_fas(graph: nx.DiGraph, seed: int | None = None) -> list: """See https://github.com/vereena42/Feedback-Arc-Set-Heuristics/blob/master/berger_shor.py""" nodes = list(graph.nodes) visited = np.zeros(len(nodes)) edge_list = [] # Create random linear ordering on vertices random.seed(...
def berger_shor_fas(graph: nx.DiGraph, seed: int | None = None) -> list:
"""See https://github.com/vereena42/Feedback-Arc-Set-Heuristics/blob/master/berger_shor.py""" nodes = list(graph.nodes) visited = np.zeros(len(nodes)) edge_list = [] # Create random linear ordering on vertices random.seed(seed) random.shuffle(nodes) # Main loop of Berger-Shor algorithm...
dequeue(self) -> LinkedListEntry | None: entry = self.sentinel.next if entry is not None and entry is not self.sentinel: entry.unlink() return entry def berger_shor_fas(graph: nx.DiGraph, seed: int | None = None) -> list:
64
64
210
24
39
norabelrose/whisper
classroom/fas.py
Python
berger_shor_fas
berger_shor_fas
49
77
49
49
7184d5080f85f22979e2e64ebb904a8b8913dbe7
bigcode/the-stack
train
e7c08ca490a6482df2acc281
train
function
def fas_to_max_acyclic_subgraph(graph: nx.DiGraph, fas: Iterable): """Given a feedback arc set, return the maximum acyclic subgraph.""" subgraph = cast(nx.DiGraph, graph.copy()) for a, b in fas: subgraph.remove_edge(a, b) return subgraph
def fas_to_max_acyclic_subgraph(graph: nx.DiGraph, fas: Iterable):
"""Given a feedback arc set, return the maximum acyclic subgraph.""" subgraph = cast(nx.DiGraph, graph.copy()) for a, b in fas: subgraph.remove_edge(a, b) return subgraph
) # Remove the node with largest delta for bucket in reversed(buckets[:-1]): if entry := bucket.dequeue(): yield from remove_node(entry.value, return_parents=True) break def fas_to_max_acyclic_subgraph(graph: nx.DiGraph, fas: Iterable):
64
64
72
20
43
norabelrose/whisper
classroom/fas.py
Python
fas_to_max_acyclic_subgraph
fas_to_max_acyclic_subgraph
152
158
152
152
64c6901795aec73f00da9b23aeaab0efab1ac740
bigcode/the-stack
train
32ada1da270c743db1ff5ed5
train
function
def eades_fas(graph: nx.DiGraph, weight: str = 'weight'): """ Linear time algorithm for computing a "small" feedback arc set for a digraph. Variation of 'A fast and effective heuristic for the feedback arc set problem' by Eades, Lin, and Smyth (1993) for weighted digraphs. Adapted and ported from ht...
def eades_fas(graph: nx.DiGraph, weight: str = 'weight'):
""" Linear time algorithm for computing a "small" feedback arc set for a digraph. Variation of 'A fast and effective heuristic for the feedback arc set problem' by Eades, Lin, and Smyth (1993) for weighted digraphs. Adapted and ported from https://github.com/dagrejs/dagre/blob/933822b991ea9b077521e5...
-Arc-Set-Heuristics/blob/master/berger_shor.py""" nodes = list(graph.nodes) visited = np.zeros(len(nodes)) edge_list = [] # Create random linear ordering on vertices random.seed(seed) random.shuffle(nodes) # Main loop of Berger-Shor algorithm for node in nodes: left = [] ...
192
192
643
19
172
norabelrose/whisper
classroom/fas.py
Python
eades_fas
eades_fas
80
149
80
80
a5d4b86c017cb01d7987b5dbd11e7e822c7821c5
bigcode/the-stack
train