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
88d7d6d8ce9560be5d67cc0a
train
function
def _wrap_class_function_pass(pass_cls, pass_info): """Wrap a python class as function pass""" class PyFunctionPass(FunctionPass): """Internal wrapper class to create a class instance.""" def __init__(self, *args, **kwargs): # initialize handle in cass pass_cls creation failed.fg ...
def _wrap_class_function_pass(pass_cls, pass_info):
"""Wrap a python class as function pass""" class PyFunctionPass(FunctionPass): """Internal wrapper class to create a class instance.""" def __init__(self, *args, **kwargs): # initialize handle in cass pass_cls creation failed.fg self.handle = None inst = pass_...
is higher order, they will still be in cps form. Parameters ---------- func: tvm.relay.Function The input function Returns ------- result: tvm.relay.Function The output function """ return _ffi_api.un_cps(func) def _wrap_class_function_pass(pass_cls, pass_info):
74
74
248
12
62
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
_wrap_class_function_pass
_wrap_class_function_pass
783
807
783
783
c47338fa094f2eed74d412ca878a6f66db9658ff
bigcode/the-stack
train
d79fc410cde15045978affc5
train
function
def BackwardFoldScaleAxis(): """Backward fold axis scaling into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis ...
def BackwardFoldScaleAxis():
"""Backward fold axis scaling into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets t...
The registered pass to fold expressions. Note ---- Internally, we will call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern. """ return _ffi_api.FoldScaleAxis() def BackwardFoldScaleAxis():
64
64
94
7
57
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
BackwardFoldScaleAxis
BackwardFoldScaleAxis
120
134
120
120
ff2639c6e381db16220ec50ca0e04f3dbadf30a3
bigcode/the-stack
train
068fe32fc62ff55157efb1ba
train
class
@function_pass(opt_level=1) class ChangeBatch: """ Change the batch size. Parameters ---------- data: Dict[relay.Var, int] A dictionary of all the params to change. The keys are all params, and the values are which dimension hold the batch. batch_size: int The batch size to c...
@function_pass(opt_level=1) class ChangeBatch:
""" Change the batch size. Parameters ---------- data: Dict[relay.Var, int] A dictionary of all the params to change. The keys are all params, and the values are which dimension hold the batch. batch_size: int The batch size to change to. Returns ------- pass: Fu...
if not isinstance(pass_arg, (types.FunctionType, types.LambdaType)): raise TypeError("pass_func must be a callable for Module pass") return _ffi_api.MakeFunctionPass(pass_arg, info) if pass_func: return create_function_pass(pass_func) return create_function_pass @function_pass(opt_...
75
75
251
12
62
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ChangeBatch
ChangeBatch
911
945
911
912
c3fa96aab1c3e0ce51b57e3882f6e5cc07ddf042
bigcode/the-stack
train
d4849fb1e646ba07c553900d
train
function
def CanonicalizeOps(): """Canonicalize special operators to basic operators. This can simplify followed analysis, e.g. expanding bias_add to expand_dims and broadcast_add. Returns ------- ret: tvm.transform.Pass The registered pass performing the canonicalization. """ return _ff...
def CanonicalizeOps():
"""Canonicalize special operators to basic operators. This can simplify followed analysis, e.g. expanding bias_add to expand_dims and broadcast_add. Returns ------- ret: tvm.transform.Pass The registered pass performing the canonicalization. """ return _ffi_api.CanonicalizeOps()...
_api.SimplifyInference() def FastMath(): """ Converts the expensive non linear functions to their fast but approximate counterparts. Returns ------- ret: tvm.transform.Pass The registered pass to perform fast math operations. """ return _ffi_api.FastMath() def CanonicalizeOps():
64
64
72
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
CanonicalizeOps
CanonicalizeOps
193
203
193
193
8fd06cf0e48f095fd08d35a2676ce8d333e7ac08
bigcode/the-stack
train
60c8b910b919a1326a296b8d
train
function
def ToCPS(expr, mod=None): """ Turn expression into continuation passing style(CPS). Every intermediate compute will be passed to a continuation. Returns ------- result: tvm.transform.Pass The registered pass that transforms an expression into CPS. """ return _ffi_api.to_cps(ex...
def ToCPS(expr, mod=None):
""" Turn expression into continuation passing style(CPS). Every intermediate compute will be passed to a continuation. Returns ------- result: tvm.transform.Pass The registered pass that transforms an expression into CPS. """ return _ffi_api.to_cps(expr, mod)
scope is the least common ancestor of blocks this value is used. Returns ------- ret: tvm.transform.Pass The registered pass that transforms an expression into Basic Block Normal Form. """ return _ffi_api.ToBasicBlockNormalForm() def ToCPS(expr, mod=None):
64
64
70
9
55
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ToCPS
ToCPS
549
560
549
549
2ec53e96276bfebe8dfea537ce0ac674d4d4a638
bigcode/the-stack
train
41fe8489e9053f0c2156598f
train
function
def LazyGradientInit(): """Reduces memory usage of gradient tensors Parameters ---------- Returns ------- ret: tvm.transform.Pass A pass which delays and/or reduces memory allocation, by lazily allocating 0 or one filled tensors. """ return _ffi_api.LazyGradientInit()
def LazyGradientInit():
"""Reduces memory usage of gradient tensors Parameters ---------- Returns ------- ret: tvm.transform.Pass A pass which delays and/or reduces memory allocation, by lazily allocating 0 or one filled tensors. """ return _ffi_api.LazyGradientInit()
_once: Optional[Bool] Whether to inline binding that occurs only once. Returns ------- ret: tvm.transform.Pass The registered pass that eliminates the dead code in a Relay program. """ return _ffi_api.DeadCodeElimination(inline_once) def LazyGradientInit():
64
64
69
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
LazyGradientInit
LazyGradientInit
221
233
221
221
763cf5c48e72f08dd857de59cc43f5dedf35188a
bigcode/the-stack
train
5b8e8212601ec7410da75226
train
function
def LambdaLift(): """ Lift the closure to global function. Returns ------- ret : tvm.transform.Pass The registered pass that lifts the lambda function. """ return _ffi_api.LambdaLift()
def LambdaLift():
""" Lift the closure to global function. Returns ------- ret : tvm.transform.Pass The registered pass that lifts the lambda function. """ return _ffi_api.LambdaLift()
.PartialEvaluate() def CanonicalizeCast(): """ Canonicalize cast expressions to make operator fusion more efficient. Returns ------- ret : tvm.transform.Pass The registered pass that canonicalizes cast expression. """ return _ffi_api.CanonicalizeCast() def LambdaLift():
64
64
48
4
60
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
LambdaLift
LambdaLift
640
649
640
640
eb5acedbcee7230ac4731a58c3c09cfe5cc999cd
bigcode/the-stack
train
ce0b7a9c6e3efffedd283668
train
function
def SimplifyInference(): """Simplify the data-flow graph for inference phase. An simplified expression which is semantically equal to the input expression will be returned. Returns ------- ret: tvm.transform.Pass The registered pass to perform operator simplification. """ return _ff...
def SimplifyInference():
"""Simplify the data-flow graph for inference phase. An simplified expression which is semantically equal to the input expression will be returned. Returns ------- ret: tvm.transform.Pass The registered pass to perform operator simplification. """ return _ffi_api.SimplifyInference()...
The registered pass to forward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis, as backward folding targets the common conv->bn pattern. """ return _ffi_api.ForwardFoldScaleAxis() def SimplifyInference():
64
64
70
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
SimplifyInference
SimplifyInference
170
179
170
170
5a3ba19ae591e1d1e7258df33b75f262c0d7bb79
bigcode/the-stack
train
f2f52d1e4dbb2d8a38cedbda
train
function
def ToANormalFormExpr(e): """ToANormalForm, but on expression level. Parameters ---------- e : Expr The graph expression. Returns ------- ret : Expr The transformed expresion. """ return _ffi_api.ToANormalFormExpr(e)
def ToANormalFormExpr(e):
"""ToANormalForm, but on expression level. Parameters ---------- e : Expr The graph expression. Returns ------- ret : Expr The transformed expresion. """ return _ffi_api.ToANormalFormExpr(e)
are ordered by post-DFS order in each scope. Returns ------- ret : Union[tvm.transform.Pass, tvm.relay.Expr] The registered pass that transforms an expression into A Normal Form. """ return _ffi_api.ToANormalForm() def ToANormalFormExpr(e):
64
64
65
8
56
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ToANormalFormExpr
ToANormalFormExpr
518
531
518
518
90fbb998202422c218e8a71052a3a01e078f7c29
bigcode/the-stack
train
1113c4b1babd782a304fedec
train
function
def MergeCompilerRegions(): """Merge together compiler regions. Returns ------- ret : tvm.transform.Pass The registered pass that merges compiler regions. """ return _ffi_api.MergeCompilerRegions()
def MergeCompilerRegions():
"""Merge together compiler regions. Returns ------- ret : tvm.transform.Pass The registered pass that merges compiler regions. """ return _ffi_api.MergeCompilerRegions()
check = lambda extract: True elif len(tup) == 3: pattern_name, pattern, check = tup pattern_names.append(pattern_name) patterns.append(pattern) checks.append(check) return _ffi_api.MergeComposite(pattern_names, patterns, *checks) def MergeCompilerRegions():
64
64
45
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
MergeCompilerRegions
MergeCompilerRegions
473
481
473
473
379af116e4b0428738fef9129d2ee0be33ae0e08
bigcode/the-stack
train
2842e21dbd43f8bd3dbecd9d
train
function
def PartialEvaluate(): """Evaluate the static fragment of the code. Note ---- This transformation could be either `Module -> Module` or `Expr -> Expr`. It will directly transform the input expression to a new one if the target expression is provided. Otherwise, it will rely on the pass manager ...
def PartialEvaluate():
"""Evaluate the static fragment of the code. Note ---- This transformation could be either `Module -> Module` or `Expr -> Expr`. It will directly transform the input expression to a new one if the target expression is provided. Otherwise, it will rely on the pass manager to carry out transf...
fskip: Callable The callback function that decides whether an expression should be skipped. Returns ------- ret : tvm.transform.Pass The registered pass that eliminates common subexpressions. """ return _ffi_api.EliminateCommonSubexpr(fskip) def PartialEvaluate():
64
64
110
4
60
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
PartialEvaluate
PartialEvaluate
610
625
610
610
fda6b4cf4da1d56744d410e1f7f5e121dbd4baf0
bigcode/the-stack
train
f30c23bc64b2866613febe0c
train
function
def FoldConstant(): """Fold the constant expressions in a Relay program. Returns ------- ret : tvm.transform.Pass The registered pass for constant folding. """ return _ffi_api.FoldConstant()
def FoldConstant():
"""Fold the constant expressions in a Relay program. Returns ------- ret : tvm.transform.Pass The registered pass for constant folding. """ return _ffi_api.FoldConstant()
memory usage of gradient tensors Parameters ---------- Returns ------- ret: tvm.transform.Pass A pass which delays and/or reduces memory allocation, by lazily allocating 0 or one filled tensors. """ return _ffi_api.LazyGradientInit() def FoldConstant():
64
64
47
4
60
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
FoldConstant
FoldConstant
235
243
235
235
52916e6d3cc1cd9d2dd98eb8eb0cf74ac1733544
bigcode/the-stack
train
e17af774343b866edc227d5b
train
function
def Inline(): """Perform inlining on the given Relay IR module. The global functions that are marked as `inline` should be always inlined. A cost model will be needed in the future to decide if it is profitable to inline the function. Returns ------- ret: tvm.transform.Pass The register...
def Inline():
"""Perform inlining on the given Relay IR module. The global functions that are marked as `inline` should be always inlined. A cost model will be needed in the future to decide if it is profitable to inline the function. Returns ------- ret: tvm.transform.Pass The registered pass that p...
for t in targets]) def DynamicToStatic(): """If possible, convert tvm.relay.dynamic* ops to static versions Returns ------- ret : tvm.transform.Pass The registered pass for dynamic->static conversion. """ return _ffi_api.DynamicToStatic() def Inline():
64
64
92
3
61
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
Inline
Inline
696
706
696
696
ea418ed75f71c2113cabd6898be28ed1a5869f5d
bigcode/the-stack
train
988df7b9c0062b3dae601fd5
train
function
def SimplifyExpr(): """ Simplify the Relay expression, including merging consecutive reshapes. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass. """ return _ffi_api.SimplifyExpr()
def SimplifyExpr():
""" Simplify the Relay expression, including merging consecutive reshapes. Returns ------- ret : tvm.transform.Pass The registered SimplifyExpr pass. """ return _ffi_api.SimplifyExpr()
, 0]))``` This parameter is generated by ```analysis.search_fc_transpose``` function Returns ------- ret : tvm.transform.Pass The registered SimplifyFCTranspose pass. """ return _ffi_api.SimplifyFCTranspose(target_weight_name) def SimplifyExpr():
64
64
53
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
SimplifyExpr
SimplifyExpr
989
998
989
989
3cdfe9f56462e55fdde956d475a89452476d2cdd
bigcode/the-stack
train
2c2331d60ef4363da7109223
train
function
def EliminateCommonSubexpr(fskip=None): """Eliminate common subexpressions. Parameters ---------- fskip: Callable The callback function that decides whether an expression should be skipped. Returns ------- ret : tvm.transform.Pass The registered pass that eliminates...
def EliminateCommonSubexpr(fskip=None):
"""Eliminate common subexpressions. Parameters ---------- fskip: Callable The callback function that decides whether an expression should be skipped. Returns ------- ret : tvm.transform.Pass The registered pass that eliminates common subexpressions. """ retu...
(): """Turn a Relay program in A Normal Form into Graph Normal Form Returns ------- ret : tvm.transform.Pass The registered pass that transforms an expression into Graph Normal Form. """ return _ffi_api.ToGraphNormalForm() def EliminateCommonSubexpr(fskip=None):
64
64
84
10
54
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
EliminateCommonSubexpr
EliminateCommonSubexpr
593
607
593
593
3913c28dd562c0dc907a149d2b3e8dbacfa9f6ce
bigcode/the-stack
train
1adf862363b13f5f293782d1
train
function
def DynamicToStatic(): """If possible, convert tvm.relay.dynamic* ops to static versions Returns ------- ret : tvm.transform.Pass The registered pass for dynamic->static conversion. """ return _ffi_api.DynamicToStatic()
def DynamicToStatic():
"""If possible, convert tvm.relay.dynamic* ops to static versions Returns ------- ret : tvm.transform.Pass The registered pass for dynamic->static conversion. """ return _ffi_api.DynamicToStatic()
.Pass The annotated pass that wrapps ops with subgraph_start and subgraph_end. """ if isinstance(targets, str): targets = [targets] return _ffi_api.AnnotateTarget([tvm.runtime.container.String(t) for t in targets]) def DynamicToStatic():
64
64
56
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
DynamicToStatic
DynamicToStatic
685
693
685
685
a233cb59d2654c93d9782eb38ca9bf963a41a8c0
bigcode/the-stack
train
fe11d0f562253645352b7588
train
function
def RewriteAnnotatedOps(fallback_device): """Rewrite the annotated program where annotation operators, e.g. `on_deivce`, mark which device an expression should be scheduled to. This pass helps heterogeneous execution where different operators may need to be allocated on various devices. Parameters ...
def RewriteAnnotatedOps(fallback_device):
"""Rewrite the annotated program where annotation operators, e.g. `on_deivce`, mark which device an expression should be scheduled to. This pass helps heterogeneous execution where different operators may need to be allocated on various devices. Parameters ---------- fallback_device : int ...
_api.MergeComposite(pattern_names, patterns, *checks) def MergeCompilerRegions(): """Merge together compiler regions. Returns ------- ret : tvm.transform.Pass The registered pass that merges compiler regions. """ return _ffi_api.MergeCompilerRegions() def RewriteAnnotatedOps(fallback_...
64
64
139
8
56
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
RewriteAnnotatedOps
RewriteAnnotatedOps
484
502
484
484
e4f663f333a16848fc56c19d63ff265121c1f84b
bigcode/the-stack
train
78cb75edae783af3033cb756
train
function
def CombineParallelDense(min_num_branches=3, to_batch=True): """Combine multiple dense operators into one. For example: .. code-block data / \ dense (2,2) dense (2,2) | | elemwise/bcast (2,2) elemwise/bcast (2,2) ...
def CombineParallelDense(min_num_branches=3, to_batch=True):
"""Combine multiple dense operators into one. For example: .. code-block data / \ dense (2,2) dense (2,2) | | elemwise/bcast (2,2) elemwise/bcast (2,2) Would become: .. code-block data ...
The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel conv2d operators. """ return _ffi_api.CombineParallelConv2D(min_num_branches) def CombineParallelDense(min_nu...
72
72
242
15
57
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
CombineParallelDense
CombineParallelDense
280
321
280
280
1fa8019ca43e0bb28e1bc6afa58c88f547af732e
bigcode/the-stack
train
08d647bc2c46364613bf7069
train
function
def CanonicalizeCast(): """ Canonicalize cast expressions to make operator fusion more efficient. Returns ------- ret : tvm.transform.Pass The registered pass that canonicalizes cast expression. """ return _ffi_api.CanonicalizeCast()
def CanonicalizeCast():
""" Canonicalize cast expressions to make operator fusion more efficient. Returns ------- ret : tvm.transform.Pass The registered pass that canonicalizes cast expression. """ return _ffi_api.CanonicalizeCast()
expression is provided. Otherwise, it will rely on the pass manager to carry out transformation. Returns ------- ret: tvm.transform.Pass The registered pass that performs partial evaluation on an expression. """ return _ffi_api.PartialEvaluate() def CanonicalizeCast():
64
64
56
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
CanonicalizeCast
CanonicalizeCast
628
637
628
628
6044c092176c8d0339f85b79118381bf15248d53
bigcode/the-stack
train
1daddae6730066a138ba8c35
train
function
def ForwardFoldScaleAxis(): """Fold the scaling of axis into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to forward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis, as ...
def ForwardFoldScaleAxis():
"""Fold the scaling of axis into weights of conv2d/dense. Returns ------- ret : tvm.transform.Pass The registered pass to forward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis, as backward folding targets the...
The set of entry functions to start from. Returns ------- ret : tvm.transform.Pass The registered pass to remove unused functions. """ if entry_functions is None: entry_functions = ['main'] return _ffi_api.RemoveUnusedFunctions(entry_functions) def ForwardFoldScaleAxis():
64
64
95
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ForwardFoldScaleAxis
ForwardFoldScaleAxis
153
167
153
153
2e1cece3ccae449e889b1022a9b397bba54607fd
bigcode/the-stack
train
2e7b1bc7e9517fd3131c01e2
train
function
def InferType(): """Infer the type of an expr. Returns ------- ret : tvm.transform.Pass The registered type inference pass. """ return _ffi_api.InferType()
def InferType():
"""Infer the type of an expr. Returns ------- ret : tvm.transform.Pass The registered type inference pass. """ return _ffi_api.InferType()
disabled_pass, trace) @tvm._ffi.register_object("relay.FunctionPass") class FunctionPass(tvm.ir.transform.Pass): """A pass that works on each tvm.relay.Function in a module. A function pass class should be created through `function_pass`. """ def InferType():
63
64
44
4
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
InferType
InferType
91
99
91
91
a41d09fc6ce7a7feaeb38fa3dec879c308a0e024
bigcode/the-stack
train
f14bbf8b01d13e3db69e5de9
train
function
def ToBasicBlockNormalForm(): """Turn an expression to Basic Block Normal Form. We define a block as a group of expressions implied by the scope structure. Each graph node can only belong to a single block. For any value that is being used in multiple blocks, it has to be referred by a Var which is ...
def ToBasicBlockNormalForm():
"""Turn an expression to Basic Block Normal Form. We define a block as a group of expressions implied by the scope structure. Each graph node can only belong to a single block. For any value that is being used in multiple blocks, it has to be referred by a Var which is defined in a block, whose scop...
"""ToANormalForm, but on expression level. Parameters ---------- e : Expr The graph expression. Returns ------- ret : Expr The transformed expresion. """ return _ffi_api.ToANormalFormExpr(e) def ToBasicBlockNormalForm():
64
64
131
7
57
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ToBasicBlockNormalForm
ToBasicBlockNormalForm
533
546
533
533
797fae25edd5cdb01bd0c40147b7a68302299144
bigcode/the-stack
train
f14fa1eac488f334fd933fa9
train
function
def SimplifyFCTranspose(target_weight_name): """ Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)``` This pass is used in ```data_dep_optimization.simplify_fc_transpose``` Parameters ---------- weight_name: Array[String] Names of weights which qualified ```y =...
def SimplifyFCTranspose(target_weight_name):
""" Rewrite ```y = nn.dense(x, transpose(w, [1, 0]))``` to ```y = nn.dense(x, wt)``` This pass is used in ```data_dep_optimization.simplify_fc_transpose``` Parameters ---------- weight_name: Array[String] Names of weights which qualified ```y = nn.dense(x, transpose(w, [1, 0]))``` T...
weight_shape: Array[Array[IntImm]] Weights shape in BSR format. Returns ------- ret : tvm.transform.Pass The registered DenseToSparse pass. """ return _ffi_api.DenseToSparse(weight_name, weight_shape) def SimplifyFCTranspose(target_weight_name):
64
64
153
9
55
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
SimplifyFCTranspose
SimplifyFCTranspose
970
986
970
970
720ff8dae1c7375d5c61040896312fcc7b5502fb
bigcode/the-stack
train
75e2a439a787d0d60427ce2f
train
function
def MergeComposite(pattern_table): """Merge multiple operators into a single composite relay function. Parameters ---------- pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]] A list of (pattern_name, pattern, check) tuples. The order of the patterns in the...
def MergeComposite(pattern_table):
"""Merge multiple operators into a single composite relay function. Parameters ---------- pattern_table : List[Tuple[str, tvm.relay.dataflow_pattern.DFPattern, Function]] A list of (pattern_name, pattern, check) tuples. The order of the patterns in the list will determine the order ...
---------- legalize_map_attr_name : str The Op's attr name which corresponds to the legalize rule function. Returns ------- ret : tvm.transform.Pass The registered pass that rewrites an expr. """ return _ffi_api.Legalize(legalize_map_attr_name) def MergeComposite(pattern_ta...
73
73
246
6
67
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
MergeComposite
MergeComposite
437
470
437
437
db2d6648273115dcaa711f6a908cc6b4a123f03b
bigcode/the-stack
train
98ccea64e01d9014c71019c2
train
function
def gradient(expr, mod=None, mode='higher_order'): """ Transform the input function, returning a function that calculate the original result, paired with gradient of the input. Parameters ---------- expr : tvm.relay.Expr The input expression, which is a Function or a GlobalVar. ...
def gradient(expr, mod=None, mode='higher_order'):
""" Transform the input function, returning a function that calculate the original result, paired with gradient of the input. Parameters ---------- expr : tvm.relay.Expr The input expression, which is a Function or a GlobalVar. mod : Optional[tvm.IRModule] mode : Optional[...
needed in the future to decide if it is profitable to inline the function. Returns ------- ret: tvm.transform.Pass The registered pass that performs inlining for a Relay IR module. """ return _ffi_api.Inline() def gradient(expr, mod=None, mode='higher_order'):
64
64
192
12
52
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
gradient
gradient
709
737
709
709
48926887ec841d0f131f7d39e0ea474deaa0cebd
bigcode/the-stack
train
6ec1aa6be5e1b122bba1d6f1
train
function
def RemoveUnusedFunctions(entry_functions=None): """Remove unused global relay functions in a relay module. Parameters ---------- entry_functions: list[string] The set of entry functions to start from. Returns ------- ret : tvm.transform.Pass The registered pass to remove u...
def RemoveUnusedFunctions(entry_functions=None):
"""Remove unused global relay functions in a relay module. Parameters ---------- entry_functions: list[string] The set of entry functions to start from. Returns ------- ret : tvm.transform.Pass The registered pass to remove unused functions. """ if entry_functions i...
pass to backward fold expressions. Note ---- It is recommended to call backward_fold_scale_axis before using forward_fold_scale_axis as backward folding targets the common conv->bn pattern. """ return _ffi_api.BackwardFoldScaleAxis() def RemoveUnusedFunctions(entry_functions=None):
64
64
91
8
56
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
RemoveUnusedFunctions
RemoveUnusedFunctions
136
151
136
136
87d319eb53900f42bec242bf40181dd06f2e767c
bigcode/the-stack
train
7139c34dd26a14b0ebb06bfc
train
function
def AnnotateTarget(targets): """Annotate ops in an experession with a provied compiler/target and then use it for codegen. Parameters ---------- targets : str or List[str] The list of target compilers used for codegen. Returns ------- ret : tvm.transform.Pass The annota...
def AnnotateTarget(targets):
"""Annotate ops in an experession with a provied compiler/target and then use it for codegen. Parameters ---------- targets : str or List[str] The list of target compilers used for codegen. Returns ------- ret : tvm.transform.Pass The annotated pass that wrapps ops with...
def PartitionGraph(): """Partition a Relay program into regions that can be executed on different backends. Returns ------- ret: tvm.transform.Pass The registered pass that partitions the Relay program. """ return _ffi_api.PartitionGraph() def AnnotateTarget(targets):
64
64
128
7
57
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
AnnotateTarget
AnnotateTarget
665
682
665
665
e7140e188e78198ac77b3d480c1d9a8f2f66ba57
bigcode/the-stack
train
a44472e912d95c822dc2d77b
train
function
def ConvertLayout(desired_layouts): """ Given a dest layout, this pass transforms the expr such that most of the ops input data layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms, one at the start and one at the end. This pass is not a part of relay.build and i...
def ConvertLayout(desired_layouts):
""" Given a dest layout, this pass transforms the expr such that most of the ops input data layout is changed to the dest layout. In ideal situation, there are only 2 layout transforms, one at the start and one at the end. This pass is not a part of relay.build and is expected to be called between fram...
]) def AlterOpLayout(): """Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. Returns ------- ret : tvm.transform.Pass The regis...
90
90
300
8
82
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ConvertLayout
ConvertLayout
386
414
386
386
81af93c0b64b33029b058db5a5577627a243364a
bigcode/the-stack
train
5c6b2ce1cb0107a4bf7c7e91
train
function
def AlterOpLayout(): """Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. Returns ------- ret : tvm.transform.Pass The registered pas...
def AlterOpLayout():
"""Alternate the layouts of operators or replace primitive operators with other expressions. This pass can be used for computing convolution in custom layouts or other general weight pre-transformation. Returns ------- ret : tvm.transform.Pass The registered pass that alters the lay...
Matmul. Returns ------- ret: tvm.transform.Pass The sequential pass which apply batching for different operator types. """ return tvm.transform.Sequential([ CombineParallelConv2D(), CombineParallelDense(), CombineParallelBatchMatmul() ]) def AlterOpLayout():
63
64
79
5
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
AlterOpLayout
AlterOpLayout
372
383
372
372
6ad35a7a7e3d5111876009d1dbc1744be6c550ca
bigcode/the-stack
train
0589b573c2226941e37acaeb
train
class
@tvm._ffi.register_object("relay.FunctionPass") class FunctionPass(tvm.ir.transform.Pass): """A pass that works on each tvm.relay.Function in a module. A function pass class should be created through `function_pass`. """
@tvm._ffi.register_object("relay.FunctionPass") class FunctionPass(tvm.ir.transform.Pass):
"""A pass that works on each tvm.relay.Function in a module. A function pass class should be created through `function_pass`. """
.warn("relay.build_config will be deprecated. Please use \ tvm.transform.PassContext directly", DeprecationWarning) return tvm.transform.PassContext(opt_level, required_pass, disabled_pass, trace) @tvm._ffi.register_object("relay.FunctionPass") class FunctionPass(tvm.ir.transform.Pass):
64
64
54
21
43
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
FunctionPass
FunctionPass
84
88
84
85
9f8d9dd7a995e78161e4d00c77f7874a1ea0a618
bigcode/the-stack
train
315b42beedb9b4bc895eaa42
train
function
def BatchingOps(): """Batching parallel operators into one for Conv2D, Dense and BatchMatmul. Returns ------- ret: tvm.transform.Pass The sequential pass which apply batching for different operator types. """ return tvm.transform.Sequential([ CombineParallelConv2D(), Com...
def BatchingOps():
"""Batching parallel operators into one for Conv2D, Dense and BatchMatmul. Returns ------- ret: tvm.transform.Pass The sequential pass which apply batching for different operator types. """ return tvm.transform.Sequential([ CombineParallelConv2D(), CombineParallelDense()...
anches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators. """ return _ffi_api.CombineParallelBatchMatmul(min_num_branches) def BatchingOp...
64
64
79
5
59
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
BatchingOps
BatchingOps
357
369
357
357
38be09ba59716f80ef555f091264bb25cc6748c5
bigcode/the-stack
train
241e576a7a939d14856cfa79
train
function
def function_pass(pass_func=None, opt_level=None, name=None, required=None): """Decorate a function pass. This function returns a callback when pass_func is provided. Otherwise, it returns the created function pass using the given optimization function. Parameters ---------- pass_func : Op...
def function_pass(pass_func=None, opt_level=None, name=None, required=None):
"""Decorate a function pass. This function returns a callback when pass_func is provided. Otherwise, it returns the created function pass using the given optimization function. Parameters ---------- pass_func : Optional[Callable[(Function, Module, PassContext) -> Function]] The tra...
instance.""" def __init__(self, *args, **kwargs): # initialize handle in cass pass_cls creation failed.fg self.handle = None inst = pass_cls(*args, **kwargs) # it is important not to capture self to # avoid a cyclic dependency def _pass_fu...
226
226
755
17
208
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
function_pass
function_pass
810
908
810
810
1410ff13e9225e3a96e91e968ab3c1a35a5eb7fd
bigcode/the-stack
train
2fa925825eedc3d198477eaf
train
function
def EtaExpand(expand_constructor=False, expand_global_var=False): """Add abstraction over a constructor or global variable bound to a function Parameters ---------- expand_constructor: bool Whether to expand constructors. expand_global_var: bool Whether to expand global variables. ...
def EtaExpand(expand_constructor=False, expand_global_var=False):
"""Add abstraction over a constructor or global variable bound to a function Parameters ---------- expand_constructor: bool Whether to expand constructors. expand_global_var: bool Whether to expand global variables. Returns ------- ret: tvm.transform.Pass The r...
PS). Every intermediate compute will be passed to a continuation. Returns ------- result: tvm.transform.Pass The registered pass that transforms an expression into CPS. """ return _ffi_api.to_cps(expr, mod) def EtaExpand(expand_constructor=False, expand_global_var=False):
64
64
100
13
51
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
EtaExpand
EtaExpand
563
579
563
563
7bf402c9e544633e895e0180ea07c0b6993923e4
bigcode/the-stack
train
833b5282df4a4fcb1b14ad57
train
function
def PartitionGraph(): """Partition a Relay program into regions that can be executed on different backends. Returns ------- ret: tvm.transform.Pass The registered pass that partitions the Relay program. """ return _ffi_api.PartitionGraph()
def PartitionGraph():
"""Partition a Relay program into regions that can be executed on different backends. Returns ------- ret: tvm.transform.Pass The registered pass that partitions the Relay program. """ return _ffi_api.PartitionGraph()
""" return _ffi_api.CanonicalizeCast() def LambdaLift(): """ Lift the closure to global function. Returns ------- ret : tvm.transform.Pass The registered pass that lifts the lambda function. """ return _ffi_api.LambdaLift() def PartitionGraph():
64
64
57
4
60
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
PartitionGraph
PartitionGraph
652
661
652
652
374f8df0943119906fd1497f52d9ac993508e9ee
bigcode/the-stack
train
72d4ef743c022d18ce41f634
train
function
def CombineParallelConv2D(min_num_branches=3): """Combine multiple conv2d operators into one. Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The ...
def CombineParallelConv2D(min_num_branches=3):
"""Combine multiple conv2d operators into one. Parameters ---------- min_num_branches : int The minimum number of required parallel branches for performing this optimization. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel conv2d o...
-1 indicates that the level will be inferred from pass context. Returns ------- ret : tvm.transform.Pass The registered pass for operator fusion. """ return _ffi_api.FuseOps(fuse_opt_level) def CombineParallelConv2D(min_num_branches=3):
64
64
94
13
51
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
CombineParallelConv2D
CombineParallelConv2D
263
277
263
263
4680599648208ec7604b4c71c744e89d13888093
bigcode/the-stack
train
1681e5fce5f8793c37e233ba
train
function
def build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None): """Configure the build behavior by setting config variables. This function will be deprecated in TVM v0.7. Instead, we should directly use tvm.transform.PassContext. Par...
def build_config(opt_level=2, required_pass=None, disabled_pass=None, trace=None):
"""Configure the build behavior by setting config variables. This function will be deprecated in TVM v0.7. Instead, we should directly use tvm.transform.PassContext. Parameters ---------- opt_level: int, optional Optimization level. The optimization pass name and level are as the ...
language governing permissions and limitations # under the License. # pylint: disable=invalid-name, unused-argument, missing-docstring, unused-import """ Relay pass transformation infrastructure. """ import types import inspect import functools import warnings import tvm.ir from tvm import te from tvm.runtime import ...
105
105
350
22
82
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
build_config
build_config
34
81
34
37
e24f55c12bbb72143e3fadd76053e4ecfd269d97
bigcode/the-stack
train
c759d3d1c730d7f5dc97ae6b
train
function
def CombineParallelBatchMatmul(min_num_branches=3): """Combine multiple batch matmul operators into one. For example: .. code-block data (1, 2, 3) / \ batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3)) | ...
def CombineParallelBatchMatmul(min_num_branches=3):
"""Combine multiple batch matmul operators into one. For example: .. code-block data (1, 2, 3) / \ batch_matmul(data, (1, 4, 3)) batch_matmul(data, (1, 5, 3)) | | elemwise/bcast ...
mul op. If False, combine parallel dense ops into dense op. Returns ------- ret: tvm.transform.Pass The registered pass that combines parallel dense operators. """ return _ffi_api.CombineParallelDense(min_num_branches, to_batch) def CombineParallelBatchMatmul(min_num_branches=3):
69
69
233
13
56
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
CombineParallelBatchMatmul
CombineParallelBatchMatmul
323
354
323
323
ed2c3cb0e9cc4ff4cafe3f441916f998b35dc00e
bigcode/the-stack
train
3611ffd5287702630109f73e
train
function
def ToANormalForm(): """Turn Graph Normal Form expression into A Normal Form Expression. The scope of the root expression is the global scope. The scope of any non root expression is the least common ancestor of all it's scope. Values are ordered by post-DFS order in each scope. Returns -------...
def ToANormalForm():
"""Turn Graph Normal Form expression into A Normal Form Expression. The scope of the root expression is the global scope. The scope of any non root expression is the least common ancestor of all it's scope. Values are ordered by post-DFS order in each scope. Returns ------- ret : Union[tvm....
default device for operators with no annotated device. Returns ------- ret: tvm.transform.Pass The registered pass that rewrites an expression with annotated `on_device` operators. """ return _ffi_api.RewriteDeviceAnnotation(fallback_device) def ToANormalForm():
64
64
107
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ToANormalForm
ToANormalForm
505
516
505
505
39fb8fb0bea61cb04f47ad6d262aaebccb5a4653
bigcode/the-stack
train
71beb4150f05956737750345
train
function
def ToGraphNormalForm(): """Turn a Relay program in A Normal Form into Graph Normal Form Returns ------- ret : tvm.transform.Pass The registered pass that transforms an expression into Graph Normal Form. """ return _ffi_api.ToGraphNormalForm()
def ToGraphNormalForm():
"""Turn a Relay program in A Normal Form into Graph Normal Form Returns ------- ret : tvm.transform.Pass The registered pass that transforms an expression into Graph Normal Form. """ return _ffi_api.ToGraphNormalForm()
expand constructors. expand_global_var: bool Whether to expand global variables. Returns ------- ret: tvm.transform.Pass The registered pass that eta expands an expression. """ return _ffi_api.EtaExpand(expand_constructor, expand_global_var) def ToGraphNormalForm():
64
64
59
6
58
jacobpostman/incubator-tvm
python/tvm/relay/transform/transform.py
Python
ToGraphNormalForm
ToGraphNormalForm
582
590
582
582
cafd276c225ce4f5289c738e7faa23f5f0838e3f
bigcode/the-stack
train
371fa70f9c4b503f0782cef1
train
class
class LabelsTests(unittest.TestCase): @drop_datasets def test_create(self): labels = fo.Classification(label="cow", confidence=0.98) self.assertIsInstance(labels, fo.Classification) with self.assertRaises(ValidationError): fo.Classification(label=100) @drop_datasets ...
class LabelsTests(unittest.TestCase): @drop_datasets
def test_create(self): labels = fo.Classification(label="cow", confidence=0.98) self.assertIsInstance(labels, fo.Classification) with self.assertRaises(ValidationError): fo.Classification(label=100) @drop_datasets def test_copy(self): dataset = fo.Dataset() ...
time import unittest from mongoengine.errors import ValidationError import numpy as np import fiftyone as fo import fiftyone.constants as foc import fiftyone.core.media as fom import fiftyone.core.uid as fou from fiftyone.migrations.runner import MigrationRunner from decorators import drop_datasets class LabelsTest...
77
77
258
13
63
FLIR/fiftyone
tests/unittests/utils_tests.py
Python
LabelsTests
LabelsTests
23
60
23
24
96d0d9195554e78d1de9a6f842abaf4ba0c46da8
bigcode/the-stack
train
50482013330a12df06e628b3
train
class
class MigrationTests(unittest.TestCase): def test_runner(self): def revs(versions): return [(v, v + ".py") for v in versions] runner = MigrationRunner( head="0.0.1", destination="0.3", _revisions=revs(["0.1", "0.2", "0.3"]), ) self.ass...
class MigrationTests(unittest.TestCase):
def test_runner(self): def revs(versions): return [(v, v + ".py") for v in versions] runner = MigrationRunner( head="0.0.1", destination="0.3", _revisions=revs(["0.1", "0.2", "0.3"]), ) self.assertEqual(runner.revisions, ["0.1", "0.2",...
.media_type, fom.IMAGE) self.assertEqual(self.img_dataset.media_type, fom.IMAGE) def test_vid_types(self): self.assertEqual(self.vid_sample.media_type, fom.VIDEO) self.assertEqual(self.vid_dataset.media_type, fom.VIDEO) def test_img_change_attempts(self): with self.assertRaises...
129
129
432
7
122
FLIR/fiftyone
tests/unittests/utils_tests.py
Python
MigrationTests
MigrationTests
185
236
185
185
c1806a3c50d531d3c716f833b0ead9a62d55fb47
bigcode/the-stack
train
4aa609006aee280ee4520773
train
class
class UIDTests(unittest.TestCase): def test_log_import(self): fo.config.do_not_track = False foc.UA_ID = foc.UA_DEV fou.log_import_if_allowed(test=True) time.sleep(2) self.assertTrue(fou._import_logged)
class UIDTests(unittest.TestCase):
def test_log_import(self): fo.config.do_not_track = False foc.UA_ID = foc.UA_DEV fou.log_import_if_allowed(test=True) time.sleep(2) self.assertTrue(fou._import_logged)
", destination=future_ver) # Downgrading from a future version is not allowed with self.assertRaises(EnvironmentError): MigrationRunner(head=future_ver) with self.assertRaises(EnvironmentError): MigrationRunner(head=future_ver, destination="0.1") class UIDTests(unittes...
64
64
59
7
57
FLIR/fiftyone
tests/unittests/utils_tests.py
Python
UIDTests
UIDTests
239
246
239
239
8bf38ce8a7b796a71b91bb024ceb043d2e4397c5
bigcode/the-stack
train
3f7b3353b2ab5daeaac02b40
train
class
class SerializationTests(unittest.TestCase): def test_embedded_document(self): label1 = fo.Classification(label="cat", logits=np.arange(4)) label2 = fo.Classification(label="cat", logits=np.arange(4)) d1 = label1.to_dict() d2 = label2.to_dict() d1.pop("_id") d2.pop(...
class SerializationTests(unittest.TestCase):
def test_embedded_document(self): label1 = fo.Classification(label="cat", logits=np.arange(4)) label2 = fo.Classification(label="cat", logits=np.arange(4)) d1 = label1.to_dict() d2 = label2.to_dict() d1.pop("_id") d2.pop("_id") self.assertDictEqual(d1, d2) ...
.Dataset() dataset.add_sample( fo.Sample( filepath="filepath1.jpg", test_dets=fo.Detections( detections=[ fo.Detection( label="friend", confidence=0.9, ...
186
186
622
7
179
FLIR/fiftyone
tests/unittests/utils_tests.py
Python
SerializationTests
SerializationTests
63
154
63
63
9523f91c8321afcd0810e060b36244bcca259c96
bigcode/the-stack
train
2237068992f678b5ed21b93a
train
class
class MediaTypeTests(unittest.TestCase): @drop_datasets def setUp(self): self.img_sample = fo.Sample(filepath="image.png") self.img_dataset = fo.Dataset() self.img_dataset.add_sample(self.img_sample) self.vid_sample = fo.Sample(filepath="video.mp4") self.vid_dataset = fo...
class MediaTypeTests(unittest.TestCase): @drop_datasets
def setUp(self): self.img_sample = fo.Sample(filepath="image.png") self.img_dataset = fo.Dataset() self.img_dataset.add_sample(self.img_sample) self.vid_sample = fo.Sample(filepath="video.mp4") self.vid_dataset = fo.Dataset() self.vid_dataset.add_sample(self.vid_samp...
1.to_dict()) s2 = fo.Sample.from_dict(sample2.to_dict()) self.assertFalse(s1.in_dataset) self.assertNotEqual(s1, sample1) self.assertDictEqual(s1.to_dict(), s2.to_dict()) class MediaTypeTests(unittest.TestCase): @drop_datasets
66
66
221
14
52
FLIR/fiftyone
tests/unittests/utils_tests.py
Python
MediaTypeTests
MediaTypeTests
157
182
157
158
082bf681103ff8074841a7ab198e6d6dba628dbb
bigcode/the-stack
train
40db71bd5c009decf918ad2b
train
class
class BaseProvider(AbstractProvider): def __init__( self, repository: BaseRepository, allow_prereleases: bool | None = None, overrides: dict[str, str] = None, ) -> None: self.repository = repository self.allow_prereleases = allow_prereleases # Root allow_prerelea...
class BaseProvider(AbstractProvider):
def __init__( self, repository: BaseRepository, allow_prereleases: bool | None = None, overrides: dict[str, str] = None, ) -> None: self.repository = repository self.allow_prereleases = allow_prereleases # Root allow_prereleases value self.fetched_depende...
from __future__ import annotations from typing import TYPE_CHECKING from packaging.specifiers import InvalidSpecifier, SpecifierSet from resolvelib import AbstractProvider from pdm.models.candidates import Candidate from pdm.models.requirements import parse_requirement from pdm.resolver.python import ( PythonCan...
160
256
1,445
6
153
houbie/pdm
pdm/resolver/providers.py
Python
BaseProvider
BaseProvider
28
199
28
28
f78b03bbb8e7edbe9651fee1287a4508cb67cf3e
bigcode/the-stack
train
9fc748123aea4bfaf4b79602
train
class
class EagerUpdateProvider(ReusePinProvider): """A specialized provider to handle an "eager" upgrade strategy. An eager upgrade tries to upgrade not only packages specified, but also their dependencies (recursively). This contrasts to the "only-if-needed" default, which only promises to upgrade the spec...
class EagerUpdateProvider(ReusePinProvider):
"""A specialized provider to handle an "eager" upgrade strategy. An eager upgrade tries to upgrade not only packages specified, but also their dependencies (recursively). This contrasts to the "only-if-needed" default, which only promises to upgrade the specified package, and prevents touching anyt...
.tracked_names and identifier in self.preferred_pins: pin = self.preferred_pins[identifier] incompat = list(incompatibilities[identifier]) demanded_req = next(requirements[identifier], None) if demanded_req and demanded_req.is_named: pin.req = demanded_req...
125
125
419
10
115
houbie/pdm
pdm/resolver/providers.py
Python
EagerUpdateProvider
EagerUpdateProvider
240
283
240
240
2f9e5eff558a5b5ce63a45d091da8266ee55b37c
bigcode/the-stack
train
89d4cd2845093937dd98a67f
train
class
class ReusePinProvider(BaseProvider): """A provider that reuses preferred pins if possible. This is used to implement "add", "remove", and "reuse upgrade", where already-pinned candidates in lockfile should be preferred. """ def __init__( self, preferred_pins: dict[str, Candidate],...
class ReusePinProvider(BaseProvider):
"""A provider that reuses preferred pins if possible. This is used to implement "add", "remove", and "reuse upgrade", where already-pinned candidates in lockfile should be preferred. """ def __init__( self, preferred_pins: dict[str, Candidate], tracked_names: Iterable[str],...
But it is eligible if A has environment marker # A1; python_version>='3.8' new_requires_python = ( candidate.req.requires_python & self.repository.environment.python_requires ) if not requires_python.is_superset(new_requires_python): valid_deps.append(PythonRequi...
86
86
288
8
77
houbie/pdm
pdm/resolver/providers.py
Python
ReusePinProvider
ReusePinProvider
202
237
202
202
41472f1b139729a774daa09fc7351c5374205a38
bigcode/the-stack
train
e34dab187f48e3dee200b106
train
class
class SendgridEmailProvider(BaseEmailProvider): """An email provider for sending emails using the Sendgrid Service""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sg_client = SendGridAPIClient(self.conn_info["API_KEY"]) def send_email(self, message): ...
class SendgridEmailProvider(BaseEmailProvider):
"""An email provider for sending emails using the Sendgrid Service""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.sg_client = SendGridAPIClient(self.conn_info["API_KEY"]) def send_email(self, message): """Send messages via the sendgrid api""" ...
""" Define the send-grid email provider """ import logging from python_http_client.exceptions import HTTPError from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail, TemplateId from protean.core.email import BaseEmailProvider from protean.exceptions import SendError logger = logging.getLogger...
75
82
274
9
66
mpsiva89/protean
src/protean/adapters/email/sendgrid.py
Python
SendgridEmailProvider
SendgridEmailProvider
14
48
14
14
750b32972ab9bfdc46116194fa68afd3bbdd968b
bigcode/the-stack
train
cff394f6f0e4ad6fc999c0e5
train
class
class RSom(RPackage): """Self-Organizing Map (with application in gene clustering).""" homepage = "https://cran.r-project.org/web/packages/som/index.html" url = "https://cran.r-project.org/src/contrib/som_0.3-5.1.tar.gz" list_url = "https://cran.rstudio.com/src/contrib/Archive/som" version('0...
class RSom(RPackage):
"""Self-Organizing Map (with application in gene clustering).""" homepage = "https://cran.r-project.org/web/packages/som/index.html" url = "https://cran.r-project.org/src/contrib/som_0.3-5.1.tar.gz" list_url = "https://cran.rstudio.com/src/contrib/Archive/som" version('0.3-5.1', '802a5a809025...
License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## f...
74
74
247
6
68
ctuning/ck-spack
package/spack-r-som/package.py
Python
RSom
RSom
28
41
28
28
1bf189ac7fc75e6b6e9b9722ff435b20e4e29f14
bigcode/the-stack
train
3b77eca2ce110dccaa0bae08
train
class
class RequestServiceImpl(RequestService): def __init__(self, req_dao: RequestDao): self.req_dao = req_dao def create_request(self, req: Request, emp_id: int) -> Request: try: return self.req_dao.create_request(req, emp_id) except IndexError: raise EmployeeNotFoun...
class RequestServiceImpl(RequestService):
def __init__(self, req_dao: RequestDao): self.req_dao = req_dao def create_request(self, req: Request, emp_id: int) -> Request: try: return self.req_dao.create_request(req, emp_id) except IndexError: raise EmployeeNotFoundError("Error...\nEmployee does not exist....
from typing import List from daos.request_dao import RequestDao from entities.request import Request from exceptions.employee_not_found import EmployeeNotFoundError from exceptions.request_not_found import RequestNotFoundError from exceptions.wrong_data_type import WrongDataTypeError from services.request_service impo...
70
194
649
7
62
wolfryan97/Project1Backend
Project1Backend/services/request_service_impl.py
Python
RequestServiceImpl
RequestServiceImpl
11
85
11
11
d64eea77848a38ae0db1000e57060efcc5a59a87
bigcode/the-stack
train
ac6cc00cbe5df266c5cec613
train
class
class TestHtseqCount(unittest.TestCase): cur_dir = os.path.dirname(__file__) organism_dir = os.path.join(cur_dir, "data", "organisms", "mouse") data_dir = os.path.join(cur_dir, "data", "count", "test_data") correct_dir = os.path.join(cur_dir, "data", "count", "correct") out_dir = os.path.join(cur_di...
class TestHtseqCount(unittest.TestCase):
cur_dir = os.path.dirname(__file__) organism_dir = os.path.join(cur_dir, "data", "organisms", "mouse") data_dir = os.path.join(cur_dir, "data", "count", "test_data") correct_dir = os.path.join(cur_dir, "data", "count", "correct") out_dir = os.path.join(cur_dir, "htseq-test") def setUp(self): ...
import os import unittest from bcbio.rnaseq import count from bcbio.utils import safe_makedir, file_exists import tempfile import stat import shutil class TestHtseqCount(unittest.TestCase):
48
146
488
9
38
brentp/bcbio-nextgen
tests/unit/test_count.py
Python
TestHtseqCount
TestHtseqCount
10
56
10
10
4a982e5f9a78a57708390decc886a7c82470dee8
bigcode/the-stack
train
e5644a7f99f0b6358d614834
train
function
def testChr(ss_seq = ""): # some chromatin test sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[...)))))...
def testChr(ss_seq = ""): # some chromatin test sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[...)))))...
if ss_seq == "": # default chromatin test sequence ss_seq = ".(((.(((......(((....))).......))).)))." # chrseq = genChrSeq(ss_seq) print ("Chromatin") iSetUpChr = InputSettings("Chromatin") iSetUpChr.set_source("main SettingsPacket)") # set up the actual FE D...
def testChr(ss_seq = ""): # some chromatin test sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[...)))))...
165
141
473
165
0
plewczynski/looper
chreval/SettingsPacket.py
Python
testChr
testChr
723
770
723
733
771b328db4f1d67be97382ffc8e9563e83e39700
bigcode/the-stack
train
7913142af6badb2aaf6844d9
train
class
class InputSettings(object): def __init__(self, system = "Chromatin"): self.show_info = False # True # # initially, we enter in some bogus names and paramters so # that they are defined. self.system = "unassigned" # left undefined because needs to be chec...
class InputSettings(object):
def __init__(self, system = "Chromatin"): self.show_info = False # True # # initially, we enter in some bogus names and paramters so # that they are defined. self.system = "unassigned" # left undefined because needs to be checked # presen...
vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv from FileTools import FileTools from FileTools import getHeadExt from Seq import Seq # set up Vienna and gMatrix and other FE parameterS from MolSystem import genRNASeq # make fake RNA sequences from structures from MolSystem import genChrSeq # make fake Chr...
256
256
5,006
5
251
plewczynski/looper
chreval/SettingsPacket.py
Python
InputSettings
InputSettings
58
666
58
58
8637baa97b78c6e2dd6d21ed5e82c1c945e1a183
bigcode/the-stack
train
676ba16459dcada195220a3c
train
function
def usage_main(): print ("%s system [sequence]")
def usage_main():
print ("%s system [sequence]")
settings iSetUpChr.set_sequence(chrseq) bb_seq = '.'*len(chrseq) iSetUpChr.set_structure(bb_seq) iSetUpChr.show_InputSettings() #print ("stop here at 2b"); sys.exit(0) # def usage_main():
63
64
12
4
59
plewczynski/looper
chreval/SettingsPacket.py
Python
usage_main
usage_main
774
775
774
774
61c3632cf498b2428870458966934a44aa73b58d
bigcode/the-stack
train
93320a5a16efc2f9c29b60b9
train
function
def testRNA(ss_seq = ""): # some allowed RNA readable sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[.....
def testRNA(ss_seq = ""): # some allowed RNA readable sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[.....
if ss_seq == "": # default RNA test sequence ss_seq = ".(((.(((......(((....))).......))).)))." # rnaseq = genRNASeq(ss_seq) print ("RNA") iSetUpRNA = InputSettings("RNA") iSetUpRNA.set_source("main SettingsPacket)") iSetUpRNA.set_JobType("evaluation") iSetUp...
def testRNA(ss_seq = ""): # some allowed RNA readable sequences # 0 10 20 30 40 50 60 70 80 90 # | | | | | | | | | | #ss_seq = ".(((.(((((((.[[.....
164
161
537
164
0
plewczynski/looper
chreval/SettingsPacket.py
Python
testRNA
testRNA
671
717
671
680
17690ff7965019de0e16017bd6d49b4953ba962d
bigcode/the-stack
train
aaa4fbb2c0d2f1ea449753e5
train
function
def main(cl): print (cl) if len(cl) < 2: print ("ERROR: must specify the system and optional sequence") sys.exit(1) # if not cl[1] in sysDefLabels: print ("ERROR: first argument must be either RNA or Chromatin") sys.exit(0) # struct = "" if len(cl) =...
def main(cl):
print (cl) if len(cl) < 2: print ("ERROR: must specify the system and optional sequence") sys.exit(1) # if not cl[1] in sysDefLabels: print ("ERROR: first argument must be either RNA or Chromatin") sys.exit(0) # struct = "" if len(cl) == 3: s...
bb_seq = '.'*len(chrseq) iSetUpChr.set_structure(bb_seq) iSetUpChr.show_InputSettings() #print ("stop here at 2b"); sys.exit(0) # def usage_main(): print ("%s system [sequence]") def main(cl):
63
64
133
4
60
plewczynski/looper
chreval/SettingsPacket.py
Python
main
main
778
801
778
778
3b2307cdaa5952ce9801bfdf46377b160be528bf
bigcode/the-stack
train
a9e4cd5a8902aff3e4562352
train
function
def list_storage_account_sas(account_name: Optional[str] = None, i_p_address_or_range: Optional[str] = None, key_to_sign: Optional[str] = None, permissions: Optional[Union[str, 'Permissions']] = None, pro...
def list_storage_account_sas(account_name: Optional[str] = None, i_p_address_or_range: Optional[str] = None, key_to_sign: Optional[str] = None, permissions: Optional[Union[str, 'Permissions']] = None, pro...
""" The List SAS credentials operation response. :param str account_name: The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. :param str i_p_address_or_range: An IP address...
account_sas_token") class AwaitableListStorageAccountSASResult(ListStorageAccountSASResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListStorageAccountSASResult( account_sas_token=self.account_sas_token) def list_storage_ac...
221
221
737
154
67
pulumi-bot/pulumi-azure-native
sdk/python/pulumi_azure_native/storage/v20180701/list_storage_account_sas.py
Python
list_storage_account_sas
list_storage_account_sas
46
90
46
56
ca38de5b95c5feb7feb5f82df82160b16986da20
bigcode/the-stack
train
0dabfcee4a0e4fa6beb39014
train
class
class AwaitableListStorageAccountSASResult(ListStorageAccountSASResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return ListStorageAccountSASResult( account_sas_token=self.account_sas_token)
class AwaitableListStorageAccountSASResult(ListStorageAccountSASResult): # pylint: disable=using-constant-test
def __await__(self): if False: yield self return ListStorageAccountSASResult( account_sas_token=self.account_sas_token)
") def account_sas_token(self) -> str: """ List SAS credentials of storage account. """ return pulumi.get(self, "account_sas_token") class AwaitableListStorageAccountSASResult(ListStorageAccountSASResult): # pylint: disable=using-constant-test
64
64
62
27
37
pulumi-bot/pulumi-azure-native
sdk/python/pulumi_azure_native/storage/v20180701/list_storage_account_sas.py
Python
AwaitableListStorageAccountSASResult
AwaitableListStorageAccountSASResult
37
43
37
38
fc8632b77cb0419770cbb95497e22a9b6f84e0c6
bigcode/the-stack
train
a07e3a782820c45465801d85
train
class
@pulumi.output_type class ListStorageAccountSASResult: """ The List SAS credentials operation response. """ def __init__(__self__, account_sas_token=None): if account_sas_token and not isinstance(account_sas_token, str): raise TypeError("Expected argument 'account_sas_token' to be a ...
@pulumi.output_type class ListStorageAccountSASResult:
""" The List SAS credentials operation response. """ def __init__(__self__, account_sas_token=None): if account_sas_token and not isinstance(account_sas_token, str): raise TypeError("Expected argument 'account_sas_token' to be a str") pulumi.set(__self__, "account_sas_token",...
from ... import _utilities, _tables from ._enums import * __all__ = [ 'ListStorageAccountSASResult', 'AwaitableListStorageAccountSASResult', 'list_storage_account_sas', ] @pulumi.output_type class ListStorageAccountSASResult:
64
64
145
14
50
pulumi-bot/pulumi-azure-native
sdk/python/pulumi_azure_native/storage/v20180701/list_storage_account_sas.py
Python
ListStorageAccountSASResult
ListStorageAccountSASResult
18
34
18
19
ced2e8c676c016cab1f81000374edcd83732734d
bigcode/the-stack
train
7163509b2cdfcbe43e140849
train
function
def serialize(obj: Any) -> Any: """Return a serializable version of an object.""" if isinstance(obj, Enum): return obj.value if hasattr(obj, '__dict__'): return obj.__dict__ return f'[Non-Serializable {repr(obj)}]'
def serialize(obj: Any) -> Any:
"""Return a serializable version of an object.""" if isinstance(obj, Enum): return obj.value if hasattr(obj, '__dict__'): return obj.__dict__ return f'[Non-Serializable {repr(obj)}]'
one of the following:\n ' msg += '\n '.join(options) result = '' while not valid: print(msg, file=sys.stderr) result = input('') if result in options: valid = True return result def serialize(obj: Any) -> Any:
64
64
59
9
54
LaudateCorpus1/m
packages/python/m/core/io.py
Python
serialize
serialize
130
136
130
130
f713221b506d3b31481fb4b3a6bc55a05c86f83f
bigcode/the-stack
train
3305ef8348d5d341988da4c1
train
function
def get_ci_tool() -> Type[CITool]: """Return the current CI Tool based on the environment variables.""" if env('GITHUB_ACTIONS'): return GithubActions if env('TC') or env('TEAMCITY'): return Teamcity return CITool
def get_ci_tool() -> Type[CITool]:
"""Return the current CI Tool based on the environment variables.""" if env('GITHUB_ACTIONS'): return GithubActions if env('TC') or env('TEAMCITY'): return Teamcity return CITool
'[{loc}]: ' if loc else '' desc = Teamcity.escape_msg(f'{info}{description}' or '') print( f"##teamcity[message status='WARNING' text='{desc}']", file=stream, ) def get_ci_tool() -> Type[CITool]:
64
64
60
11
53
LaudateCorpus1/m
packages/python/m/core/io.py
Python
get_ci_tool
get_ci_tool
385
391
385
385
21a47677300edc37cef01bde1bf3129a785693d4
bigcode/the-stack
train
1238a3d5f0b878c0dba9338d
train
function
def env(name: str, def_val='') -> str: """Access an environment variable. Return empty string if not defined. """ return os.environ.get(name, def_val)
def env(name: str, def_val='') -> str:
"""Access an environment variable. Return empty string if not defined. """ return os.environ.get(name, def_val)
}m' if mins else '', f'{sec}s' if sec else '', f'{_ms}ms' if _ms else '', ] return ':'.join([x for x in entries if x]) or '0s' def env(name: str, def_val='') -> str:
64
64
40
13
51
LaudateCorpus1/m
packages/python/m/core/io.py
Python
env
env
39
44
39
39
738d433cd943751852c3a6ce91b121b0d9ee460a
bigcode/the-stack
train
cff1b6fb7d96671a4d79304e
train
class
@dataclass class EnvVars(JsonStr): """Class to store the values of the environment variables.""" # pylint: disable=too-many-instance-attributes ci_env: bool = False github_token: str = '' server_url: str = '' run_id: str = '' run_number: str = '' run_url: str = '' git_branch: str = '...
@dataclass class EnvVars(JsonStr):
"""Class to store the values of the environment variables.""" # pylint: disable=too-many-instance-attributes ci_env: bool = False github_token: str = '' server_url: str = '' run_id: str = '' run_number: str = '' run_url: str = '' git_branch: str = '' git_sha: str = '' trigger...
Serializable {repr(obj)}]' class JsonStr: """Base class to stringify dataclasses.""" # pylint: disable=too-few-public-methods def __str__(self) -> str: return json.dumps(self.__dict__, default=serialize) @dataclass class EnvVars(JsonStr):
64
64
113
9
55
LaudateCorpus1/m
packages/python/m/core/io.py
Python
EnvVars
EnvVars
147
161
147
148
98713170eea1abed64253f98422ae37f37292554
bigcode/the-stack
train
3542f88774b845d3d391384a
train
function
def renv_vars(keys: List[str]) -> OneOf[Issue, List[str]]: """Require multiple env vars to be defined.""" result: List[str] = [] missing: List[str] = [] for key in keys: value = os.environ.get(key) if value is None: missing.append(key) else: result.append(...
def renv_vars(keys: List[str]) -> OneOf[Issue, List[str]]:
"""Require multiple env vars to be defined.""" result: List[str] = [] missing: List[str] = [] for key in keys: value = os.environ.get(key) if value is None: missing.append(key) else: result.append(value) if missing: mstr = ', '.join(missing) ...
value = os.environ.get(key) # Value may still be an empty string, checking against None if value is not None: return Good(value) return issue(f'missing {key} in env') def renv_vars(keys: List[str]) -> OneOf[Issue, List[str]]:
64
64
109
18
46
LaudateCorpus1/m
packages/python/m/core/io.py
Python
renv_vars
renv_vars
56
69
56
56
2f12e5be83cafc6fa628a698245425aa0c86272c
bigcode/the-stack
train
dc19c1c261d1491f382ee392
train
function
def renv(key: str) -> OneOf[Issue, str]: """Require an environment variable to be defined.""" value = os.environ.get(key) # Value may still be an empty string, checking against None if value is not None: return Good(value) return issue(f'missing {key} in env')
def renv(key: str) -> OneOf[Issue, str]:
"""Require an environment variable to be defined.""" value = os.environ.get(key) # Value may still be an empty string, checking against None if value is not None: return Good(value) return issue(f'missing {key} in env')
entries if x]) or '0s' def env(name: str, def_val='') -> str: """Access an environment variable. Return empty string if not defined. """ return os.environ.get(name, def_val) def renv(key: str) -> OneOf[Issue, str]:
64
64
71
15
49
LaudateCorpus1/m
packages/python/m/core/io.py
Python
renv
renv
47
53
47
47
ce8814c38743dd509e1ef577a8ef07d2df2afe43
bigcode/the-stack
train
461ca9979dd9fbe233ebc5a4
train
function
def error_block(issue_: str, stream: TextIO = sys.stderr) -> None: """Print an issue within an error block.""" CiTool.open_block('error', '') print(issue_, file=stream) CiTool.close_block('error')
def error_block(issue_: str, stream: TextIO = sys.stderr) -> None:
"""Print an issue within an error block.""" CiTool.open_block('error', '') print(issue_, file=stream) CiTool.close_block('error')
environment variables.""" if env('GITHUB_ACTIONS'): return GithubActions if env('TC') or env('TEAMCITY'): return Teamcity return CITool CiTool = get_ci_tool() def error_block(issue_: str, stream: TextIO = sys.stderr) -> None:
64
64
53
18
46
LaudateCorpus1/m
packages/python/m/core/io.py
Python
error_block
error_block
397
401
397
397
9c0b9284a5a16f11f504411a484ecd4b9bf1182f
bigcode/the-stack
train
3a26a156dbe580d0b3b581f0
train
class
class Teamcity(CITool): """Collection of methods used to communicate with Teamcity.""" @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Read basic environment variables from Teamcity.""" # WIP: Need to map the to the object return Good(EnvVars(ci_env=True)) @staticmeth...
class Teamcity(CITool):
"""Collection of methods used to communicate with Teamcity.""" @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Read basic environment variables from Teamcity.""" # WIP: Need to map the to the object return Good(EnvVars(ci_env=True)) @staticmethod def escape_msg(ms...
'file={file},line={line},col={col}' if file else '' info = f' {loc}' if loc else '' print(f'::error{info}::{description}', file=stream) @staticmethod def warn( description: str, file: Optional[str] = None, line: Optional[str] = None, col: Optional[str] = None, ...
191
191
639
7
184
LaudateCorpus1/m
packages/python/m/core/io.py
Python
Teamcity
Teamcity
307
382
307
307
34969b6ee163cec8f647842176ac0306638c912c
bigcode/the-stack
train
98f611490c40e926bc94bcf2
train
function
def warn_block(issue_: str, stream: TextIO = sys.stderr) -> None: """Print an issue within a warning block.""" CiTool.open_block('warning', '') print(issue_, file=stream) CiTool.close_block('warning')
def warn_block(issue_: str, stream: TextIO = sys.stderr) -> None:
"""Print an issue within a warning block.""" CiTool.open_block('warning', '') print(issue_, file=stream) CiTool.close_block('warning')
stream: TextIO = sys.stderr) -> None: """Print an issue within an error block.""" CiTool.open_block('error', '') print(issue_, file=stream) CiTool.close_block('error') def warn_block(issue_: str, stream: TextIO = sys.stderr) -> None:
64
64
53
18
46
LaudateCorpus1/m
packages/python/m/core/io.py
Python
warn_block
warn_block
404
408
404
404
9b131733a0d616f0fe4ef43234ee0a0becc92d52
bigcode/the-stack
train
ca7b67c50a0b351f54493bc5
train
function
def _ver_str(major: int, minor: int, patch: int) -> str: return f'{major}.{minor}.{patch}'
def _ver_str(major: int, minor: int, patch: int) -> str:
return f'{major}.{minor}.{patch}'
fp: fp.write(contents) return Good(0) except Exception as ex: return issue( 'failed to write file', data={'filename': filename}, cause=ex, ) def _ver_str(major: int, minor: int, patch: int) -> str:
64
64
30
20
44
LaudateCorpus1/m
packages/python/m/core/io.py
Python
_ver_str
_ver_str
99
100
99
99
b2d05470b00825a70a4b69431980f3c5c2165bf5
bigcode/the-stack
train
732918a00fb045e2734452b8
train
function
def format_seconds(number_of_seconds: Union[int, float]) -> str: """Return a string representing the number of seconds in a friendly format: Xd:Xh:Xm:Xs:Xms. """ milliseconds = int(math.floor(number_of_seconds * 1000)) _ms = milliseconds % 1000 seconds = int(math.floor(milliseconds / 1000)) sec ...
def format_seconds(number_of_seconds: Union[int, float]) -> str:
"""Return a string representing the number of seconds in a friendly format: Xd:Xh:Xm:Xs:Xms. """ milliseconds = int(math.floor(number_of_seconds * 1000)) _ms = milliseconds % 1000 seconds = int(math.floor(milliseconds / 1000)) sec = seconds % 60 minutes = int(math.floor(seconds / 60)) mi...
enum import Enum from typing import Any, List, Optional, TextIO, Type, Union, cast from .. import git from . import issue, one_of from .fp import Good, OneOf from .issue import Issue def format_seconds(number_of_seconds: Union[int, float]) -> str:
65
65
218
15
49
LaudateCorpus1/m
packages/python/m/core/io.py
Python
format_seconds
format_seconds
16
36
16
16
8ad6c4b57e119c84dcfeee90262b2a93994b6973
bigcode/the-stack
train
e0abccf31d432bc1b28ac932
train
function
def read_file(filename: str) -> OneOf[Issue, str]: """Return a `Good` containing the contents of the file.""" try: with open(filename, encoding='UTF-8') as fp: return Good(fp.read()) except Exception as ex: return issue( 'failed to read file', data={'filen...
def read_file(filename: str) -> OneOf[Issue, str]:
"""Return a `Good` containing the contents of the file.""" try: with open(filename, encoding='UTF-8') as fp: return Good(fp.read()) except Exception as ex: return issue( 'failed to read file', data={'filename': filename}, cause=ex, )
value is None: missing.append(key) else: result.append(value) if missing: mstr = ', '.join(missing) return issue(f'missing [{mstr}] in env') return Good(result) def read_file(filename: str) -> OneOf[Issue, str]:
64
64
83
15
49
LaudateCorpus1/m
packages/python/m/core/io.py
Python
read_file
read_file
72
82
72
72
165b63e3c1b736c131998fff1d7d5ddf0973065a
bigcode/the-stack
train
0b77117d7dd91c39dc43b50f
train
function
def prompt_next_version(version: str, release_type: str) -> str: """Display the possible major, minor and patch versions and prompt the user to enter one of them. Return one of the versions. https://semver.org/ """ ver = version.split('-')[0] parts = [int(x) for x in ver.split('.')] patch =...
def prompt_next_version(version: str, release_type: str) -> str:
"""Display the possible major, minor and patch versions and prompt the user to enter one of them. Return one of the versions. https://semver.org/ """ ver = version.split('-')[0] parts = [int(x) for x in ver.split('.')] patch = _ver_str(parts[0], parts[1], parts[2] + 1) if release_type =...
( 'failed to write file', data={'filename': filename}, cause=ex, ) def _ver_str(major: int, minor: int, patch: int) -> str: return f'{major}.{minor}.{patch}' def prompt_next_version(version: str, release_type: str) -> str:
68
69
233
16
52
LaudateCorpus1/m
packages/python/m/core/io.py
Python
prompt_next_version
prompt_next_version
103
127
103
103
a8bde1e05b8103f245d48141a63ffb1d0f25eca8
bigcode/the-stack
train
43e496eab852076aae29306b
train
function
def write_file(filename: str, contents: str) -> OneOf[Issue, int]: """Return a `Good` containing 0 if the file was written.""" try: with open(filename, 'w', encoding='UTF-8') as fp: fp.write(contents) return Good(0) except Exception as ex: return issue( 'faile...
def write_file(filename: str, contents: str) -> OneOf[Issue, int]:
"""Return a `Good` containing 0 if the file was written.""" try: with open(filename, 'w', encoding='UTF-8') as fp: fp.write(contents) return Good(0) except Exception as ex: return issue( 'failed to write file', data={'filename': filename}, ...
='UTF-8') as fp: return Good(fp.read()) except Exception as ex: return issue( 'failed to read file', data={'filename': filename}, cause=ex, ) def write_file(filename: str, contents: str) -> OneOf[Issue, int]:
64
64
97
19
45
LaudateCorpus1/m
packages/python/m/core/io.py
Python
write_file
write_file
85
96
85
85
3840fbbb55aab4cb4be33363c79c1c44900d528c
bigcode/the-stack
train
4c5824ff2566bb54e5ebdb28
train
class
class JsonStr: """Base class to stringify dataclasses.""" # pylint: disable=too-few-public-methods def __str__(self) -> str: return json.dumps(self.__dict__, default=serialize)
class JsonStr:
"""Base class to stringify dataclasses.""" # pylint: disable=too-few-public-methods def __str__(self) -> str: return json.dumps(self.__dict__, default=serialize)
def serialize(obj: Any) -> Any: """Return a serializable version of an object.""" if isinstance(obj, Enum): return obj.value if hasattr(obj, '__dict__'): return obj.__dict__ return f'[Non-Serializable {repr(obj)}]' class JsonStr:
63
64
48
4
59
LaudateCorpus1/m
packages/python/m/core/io.py
Python
JsonStr
JsonStr
139
144
139
139
502e97f32517772b6505078eb23e84802c160a81
bigcode/the-stack
train
c2df9b0caf36aaaa9fbbb70b
train
class
class GithubActions(CITool): """Collection of methods used to communicate with Github.""" @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Read the environment variables from Github Actions.""" res = EnvVars( ci_env=True, server_url='https://github.com', ...
class GithubActions(CITool):
"""Collection of methods used to communicate with Github.""" @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Read the environment variables from Github Actions.""" res = EnvVars( ci_env=True, server_url='https://github.com', ) return one_of(...
-> None: """Print an error message.""" parts = [x for x in [file, line, col] if x] loc = ':'.join(parts) info = f'[{loc}]' if loc else '' print(f'error{info}: {description}', file=stream) @staticmethod def warn( description: str, file: Optional[str] = No...
186
186
623
7
179
LaudateCorpus1/m
packages/python/m/core/io.py
Python
GithubActions
GithubActions
221
304
221
221
bf2471ab163a0068819522fdabd8325be2761425
bigcode/the-stack
train
3308bb31e47b10d41dde8897
train
class
class CITool(ABC): """Class representing a continuous integration tool. We can use this class static methods to display local messages. """ @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Obtain basic environment variables.""" res = EnvVars() return one_of( ...
class CITool(ABC):
"""Class representing a continuous integration tool. We can use this class static methods to display local messages. """ @staticmethod def env_vars() -> OneOf[Issue, EnvVars]: """Obtain basic environment variables.""" res = EnvVars() return one_of( lambda: [ ...
class EnvVars(JsonStr): """Class to store the values of the environment variables.""" # pylint: disable=too-many-instance-attributes ci_env: bool = False github_token: str = '' server_url: str = '' run_id: str = '' run_number: str = '' run_url: str = '' git_branch: str = '' git_...
117
118
394
6
111
LaudateCorpus1/m
packages/python/m/core/io.py
Python
CITool
CITool
164
218
164
164
fb72c115f340c93bd4fb34daf571ac2a24a8c1a0
bigcode/the-stack
train
2619d42cc6b62ffc85906a94
train
function
def pick_patients(): patient_params = pd.read_csv(PATIENT_PARA_FILE) patient_names = list(patient_params['Name'].values) while True: select1 = input('Select virtual patients:\n' + '[1] All\n' + '[2] All Adolescents\n' + '[3] All Adults\n' + '[4] All Ch...
def pick_patients():
patient_params = pd.read_csv(PATIENT_PARA_FILE) patient_names = list(patient_params['Name'].values) while True: select1 = input('Select virtual patients:\n' + '[1] All\n' + '[2] All Adolescents\n' + '[3] All Adults\n' + '[4] All Children\n' + '[5] By I...
InsulinPump from simglucose.patient.t1dpatient import T1DPatient from simglucose.simulation.scenario_gen import RandomScenario from simglucose.simulation.scenario import CustomScenario from simglucose.analysis.report import report import pandas as pd import copy import logging import os from datetime import datetime f...
150
150
501
5
145
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_patients
pick_patients
25
89
25
25
af0483b79cb4bf5aa872f780612a309736eb3ab7
bigcode/the-stack
train
b47dfada3c5bb03d9dfacb22
train
function
def pick_parallel(): while True: select = input('Use multiple processes? (y/n) ') if select == 'y': parallel = True break elif select == 'n': parallel = False break else: continue return parallel
def pick_parallel():
while True: select = input('Use multiple processes? (y/n) ') if select == 'y': parallel = True break elif select == 'n': parallel = False break else: continue return parallel
_animate(): while True: select = input('Show animation? (y/n) ') if select == 'y': animate = True break elif select == 'n': animate = False break else: continue return animate def pick_parallel():
64
64
62
4
59
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_parallel
pick_parallel
285
296
285
285
1ed7f9ca7f9cff14ffdeaced90014b97b86b5ae4
bigcode/the-stack
train
b95083f3cf2f9e9928e27b5f
train
function
def pick_animate(): while True: select = input('Show animation? (y/n) ') if select == 'y': animate = True break elif select == 'n': animate = False break else: continue return animate
def pick_animate():
while True: select = input('Show animation? (y/n) ') if select == 'y': animate = True break elif select == 'n': animate = False break else: continue return animate
name == '': foldername = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') save_path = os.path.join(os.path.abspath('./results/'), foldername) print('Results will be saved in {}'.format(save_path)) return save_path def pick_animate():
64
64
62
5
58
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_animate
pick_animate
271
282
271
271
24c0f42a7f0f8f022f5d0c8ceff4ac8ca14eed6b
bigcode/the-stack
train
6150231b57cadb0cefa283f3
train
function
def pick_start_time(): now = datetime.now() start_hour = timedelta( hours=float(input('Input simulation start time (hr): '))) start_time = datetime.combine(now.date(), datetime.min.time()) + start_hour print('Simulation start time is set to {}.'.format(start_time)) return start_time
def pick_start_time():
now = datetime.now() start_hour = timedelta( hours=float(input('Input simulation start time (hr): '))) start_time = datetime.combine(now.date(), datetime.min.time()) + start_hour print('Simulation start time is set to {}.'.format(start_time)) return start_time
seed = None break print('Please input an integer!') continue scenario = RandomScenario(start_time, seed=seed) else: custom_scenario = input_custom_scenario() scenario = CustomScenario(start_time, custom_scenario) return scenario def p...
64
64
68
5
58
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_start_time
pick_start_time
201
207
201
201
a23a8e31a00c9e8283c4ea353ca84fe96157a24b
bigcode/the-stack
train
3cdc9eb4bf31a1baffca4067
train
function
def pick_save_path(): foldername = input('Folder name to save results [default]: ') if foldername == 'default' or foldername == '': foldername = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') save_path = os.path.join(os.path.abspath('./results/'), foldername) print('Results will be saved in {}'.f...
def pick_save_path():
foldername = input('Folder name to save results [default]: ') if foldername == 'default' or foldername == '': foldername = datetime.now().strftime('%Y-%m-%d_%H-%M-%S') save_path = os.path.join(os.path.abspath('./results/'), foldername) print('Results will be saved in {}'.format(save_path)) ...
Error: print('Please input an integer!') continue if selection < 1 or selection > 1: print('Please input a number from the list!') else: break if selection == 1: controller = BBController() return controller def pick_save_path():
64
64
89
5
58
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_save_path
pick_save_path
261
268
261
261
8846ec602aa7b354d067a433d7cf03d7d5d5ff84
bigcode/the-stack
train
181850bf5bb8b40349ff5332
train
function
def pick_insulin_pump(): pump_params = pd.read_csv(INSULIN_PUMP_PARA_FILE) pump_names = list(pump_params['Name'].values) while True: print('Select the insulin pump:') for i, pump in enumerate(pump_names): print('[{}] {}'.format(i + 1, pump)) input_value = input('>>> ') ...
def pick_insulin_pump():
pump_params = pd.read_csv(INSULIN_PUMP_PARA_FILE) pump_names = list(pump_params['Name'].values) while True: print('Select the insulin pump:') for i, pump in enumerate(pump_names): print('[{}] {}'.format(i + 1, pump)) input_value = input('>>> ') try: se...
except ValueError: if input_value == '' or input_value == 'None': seed = None break else: print('Please input an integer!') continue logger.info('Sensor Random Seed: {}'.format(seed)) return seed def pick_insulin_pu...
64
64
201
7
56
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_insulin_pump
pick_insulin_pump
136
158
136
136
df143c4473c4fdd3099235f88dafecfa148ecf94
bigcode/the-stack
train
fb399bd7c83a1eaae93363e8
train
function
def pick_controller(): controller = None while True: print('Select controller:') print('[1] Basal-Bolus Controller') input_value = input('>>>') try: selection = int(input_value) except ValueError: print('Please input an integer!') conti...
def pick_controller():
controller = None while True: print('Select controller:') print('[1] Basal-Bolus Controller') input_value = input('>>>') try: selection = int(input_value) except ValueError: print('Please input an integer!') continue if selectio...
snack_size)) go_on = input('Continue input snack (y/n)? ') if go_on == 'n': break elif go_on == 'y': continue else: go_on = input('Continue input snack (y/n)? ') return scenario def pick_controller():
64
64
110
4
59
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_controller
pick_controller
241
258
241
241
0d00b51fb96c0ddcc839c9ff269abd99eee2a674
bigcode/the-stack
train
d6b4242a81e7ab1546a13014
train
function
def pick_cgm_sensor(): sensor_params = pd.read_csv(SENSOR_PARA_FILE) sensor_names = list(sensor_params['Name'].values) total_sensor_num = len(sensor_params.index) while True: print('Select the CGM sensor:') for i in range(total_sensor_num): print('[{0}] {1}'.format(i + 1, sen...
def pick_cgm_sensor():
sensor_params = pd.read_csv(SENSOR_PARA_FILE) sensor_names = list(sensor_params['Name'].values) total_sensor_num = len(sensor_params.index) while True: print('Select the CGM sensor:') for i in range(total_sensor_num): print('[{0}] {1}'.format(i + 1, sensor_names[i])) ...
- 1])) input('Press any key to continue ...') continue else: select_hist.append(select2) patients.append(patient_names[select2 - 1]) logger.info('Selected patients:\n{}'...
64
64
209
6
57
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_cgm_sensor
pick_cgm_sensor
92
116
92
92
c17b4531688e57c09ed612ce21d673706de5432d
bigcode/the-stack
train
ee4011935a8b8df524ffcea0
train
function
def pick_scenario(start_time=None): while True: print('Select scnenario:') print('[1] Random Scnenario') print('[2] Custom Scnenario') input_value = input('>>>') try: selection = int(input_value) except ValueError: print('Please input an intege...
def pick_scenario(start_time=None):
while True: print('Select scnenario:') print('[1] Random Scnenario') print('[2] Custom Scnenario') input_value = input('>>>') try: selection = int(input_value) except ValueError: print('Please input an integer!') continue if...
an integer from 1 to {0}!".format( len(pump_names))) input('Press any key to continue ...') continue break pump = pump_names[selection - 1] logger.info('Selected Pumps:\n{}'.format(pump)) return pump def pick_scenario(start_time=None):
70
70
235
8
61
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_scenario
pick_scenario
161
198
161
161
7374179b0e403a6cc421b4ff815e7f322d60f990
bigcode/the-stack
train
4eb8ed917cb7290fcb66e5d9
train
function
def simulate(sim_time=None, scenario=None, controller=None, patient_names=[], cgm_name=None, cgm_seed=None, insulin_pump_name=None, start_time=None, save_path=None, animate=None, parallel=No...
def simulate(sim_time=None, scenario=None, controller=None, patient_names=[], cgm_name=None, cgm_seed=None, insulin_pump_name=None, start_time=None, save_path=None, animate=None, parallel=No...
''' Main user interface. ---- Inputs: sim_time - a datetime.timedelta object specifying the simulation time. scenario - a simglucose.scenario.Scenario object. Use simglucose.scenario_gen.RandomScenario or simglucose.scenario.CustomScenario to create a scenar...
return save_path def pick_animate(): while True: select = input('Show animation? (y/n) ') if select == 'y': animate = True break elif select == 'n': animate = False break else: continue return animate def pick_paral...
184
184
615
56
127
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
simulate
simulate
299
381
299
309
69e44ff135bc190f1ecf5df9b27aca0d36c141c9
bigcode/the-stack
train
6fa45011a35093d500a3b108
train
function
def input_custom_scenario(): scenario = [] print('Input a custom scenario ...') breakfast_time = float(input('Input breakfast time (hr): ')) breakfast_size = float(input('Input breakfast size (g): ')) scenario.append((breakfast_time, breakfast_size)) lunch_time = float(input('Input lunch time ...
def input_custom_scenario():
scenario = [] print('Input a custom scenario ...') breakfast_time = float(input('Input breakfast time (hr): ')) breakfast_size = float(input('Input breakfast size (g): ')) scenario.append((breakfast_time, breakfast_size)) lunch_time = float(input('Input lunch time (hr): ')) lunch_size = fl...
(): now = datetime.now() start_hour = timedelta( hours=float(input('Input simulation start time (hr): '))) start_time = datetime.combine(now.date(), datetime.min.time()) + start_hour print('Simulation start time is set to {}.'.format(start_time)) return start_time def input_custom_scenario()...
70
70
236
6
63
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
input_custom_scenario
input_custom_scenario
210
238
210
210
37dcb4011eedbbc2686450e233887f89ed5cda73
bigcode/the-stack
train
43975a8cc836e8ae1ed5a5e6
train
function
def pick_cgm_seed(): while True: input_value = input('Select Random Seed for Sensor Noise [None]: ') try: seed = int(input_value) break except ValueError: if input_value == '' or input_value == 'None': seed = None break ...
def pick_cgm_seed():
while True: input_value = input('Select Random Seed for Sensor Noise [None]: ') try: seed = int(input_value) break except ValueError: if input_value == '' or input_value == 'None': seed = None break else: ...
to {0}!".format( total_sensor_num)) input('Press any key to continue ...') continue else: break sensor = sensor_names[selection - 1] logger.info('Selected sensor:\n{}'.format(sensor)) return sensor def pick_cgm_seed():
64
64
95
6
57
mia-jingyi/simglucose
simglucose/simulation/user_interface.py
Python
pick_cgm_seed
pick_cgm_seed
119
133
119
119
7f5ac5e0656106d27f52a76e1d5402998d988481
bigcode/the-stack
train
cfcfce0b4ae5d3995ddc5b4b
train
function
def update_item_quantity(request): data = json.loads(request.body) productId = data['productId'] quantity = data['quantity'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem...
def update_item_quantity(request):
data = json.loads(request.body) productId = data['productId'] quantity = data['quantity'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_o...
.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() # Get updated cart count cart_count = order.get_cart_count return JsonResponse({'cart_count': cart_count}) def update_item_quantity(request):
64
64
177
6
58
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
update_item_quantity
update_item_quantity
160
185
160
160
9c6b1d515da9af79307cca6458b31ad6aa2ce499
bigcode/the-stack
train
03eefd1d0f5d6b0834764349
train
function
def cart_view(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total': 0, 'get_cart_count': 0}...
def cart_view(request):
if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total': 0, 'get_cart_count': 0} context = ...
ShippingAddress stripe.api_key = settings.STRIPE_SECRET_KEY def product_detail(request, slug): product = Product.objects.get(slug=slug) context = {'title': product.name, 'product': product} return render(request, 'shopping/product_detail.html', context) def cart_view(request):
64
64
103
5
59
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
cart_view
cart_view
21
31
21
21
be69cb6c1864ad195b51c400328796f63ba7a2a7
bigcode/the-stack
train
16069f0e91c4f572cc6e266c
train
function
def process_order(request): data = json.loads(request.body) if request.user.is_authenticated: try: customer = request.user.customer order = Order.objects.get(id=data['order']['id'], customer=customer, complete=False) shipping_address = ShippingAddress.objects.create...
def process_order(request):
data = json.loads(request.body) if request.user.is_authenticated: try: customer = request.user.customer order = Order.objects.get(id=data['order']['id'], customer=customer, complete=False) shipping_address = ShippingAddress.objects.create( customer=c...
cart_count = order.get_cart_count item_total = orderItem.get_total cart_total = order.get_cart_total return JsonResponse({ 'cart_count': cart_count, 'item_total': item_total, 'cart_total': cart_total }) def process_order(request):
64
64
142
5
59
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
process_order
process_order
211
232
211
211
26a123db9c4f69cfc5bd18d33c807811fcd266fb
bigcode/the-stack
train
d8b908e3498c7a32bd6d1e17
train
function
def product_detail(request, slug): product = Product.objects.get(slug=slug) context = {'title': product.name, 'product': product} return render(request, 'shopping/product_detail.html', context)
def product_detail(request, slug):
product = Product.objects.get(slug=slug) context = {'title': product.name, 'product': product} return render(request, 'shopping/product_detail.html', context)
messages from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse, JsonResponse from django.shortcuts import redirect, render from .models import Order, OrderItem, Payment, Product, ShippingAddress stripe.api_key = settings.STRIPE_SECRET_KEY def product_detail(request, slug):
64
64
45
7
56
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
product_detail
product_detail
15
18
15
15
c1eee6180efb17aba53b2e3a02e608f452622828
bigcode/the-stack
train
80b1fc8ac1b1bb0e9336d9a0
train
function
def update_item(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = O...
def update_item(request):
data = json.loads(request.body) productId = data['productId'] action = data['action'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_cr...
"Something went wrong. You were not charged. Please try again.") return redirect("/") except Exception as e: # send an email to ourselves messages.warning( request, "A serious error occurred. We have been notifed.") return redirect("/") def updat...
61
64
173
5
56
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
update_item
update_item
134
157
134
134
6f3c5cea2dbdd1ce92124e1cfcdfb42c09248231
bigcode/the-stack
train
4fc5b97e024009cd5a39d5d0
train
function
def checkout_view(request): # >>> Render Checkout View if request.method == 'GET': try: if request.user.is_authenticated: customer = request.user.customer order = Order.objects.get(customer=customer, complete=False) items = order.orderitem_set....
def checkout_view(request): # >>> Render Checkout View
if request.method == 'GET': try: if request.user.is_authenticated: customer = request.user.customer order = Order.objects.get(customer=customer, complete=False) items = order.orderitem_set.all() else: items = [] ...
from .models import Order, OrderItem, Payment, Product, ShippingAddress stripe.api_key = settings.STRIPE_SECRET_KEY def product_detail(request, slug): product = Product.objects.get(slug=slug) context = {'title': product.name, 'product': product} return render(request, 'shopping/product_detail.html', cont...
187
187
625
12
175
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
checkout_view
checkout_view
34
128
34
35
ceb2812b1c14c25f7b17425fb1000104ddd8b6cc
bigcode/the-stack
train
0082df7226d6ac0cd2e669aa
train
function
def delete_item(request): data = json.loads(request.body) productId = data['productId'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_crea...
def delete_item(request):
data = json.loads(request.body) productId = data['productId'] customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(product=product, order=...
cart_count = order.get_cart_count item_total = orderItem.get_total cart_total = order.get_cart_total return JsonResponse({ 'cart_count': cart_count, 'item_total': item_total, 'cart_total': cart_total }) def delete_item(request):
64
64
147
5
59
onggiabayluon/DjangoSaleApp
saleapp/shopping/views.py
Python
delete_item
delete_item
188
208
188
188
16e552954f4c3ceedfe7c3ef19010ef4fa4ebd56
bigcode/the-stack
train
7668bbed5d0a26bf686181e6
train
class
class SetBackupPolicyRequestBody: """ Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive...
class SetBackupPolicyRequestBody:
""" Attributes: openapi_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ sensitive_list = [] openapi_types = { ...
# coding: utf-8 import pprint import re import six class SetBackupPolicyRequestBody:
23
256
857
7
15
wuchen-huawei/huaweicloud-sdk-python-v3
huaweicloud-sdk-rds/huaweicloudsdkrds/v3/model/set_backup_policy_request_body.py
Python
SetBackupPolicyRequestBody
SetBackupPolicyRequestBody
12
134
12
14
b1a24ee5fa841c9b9ae42b53bfc5d8e1f92f9025
bigcode/the-stack
train
754ec1dc7b18f8daf9db731d
train
function
def pulse_length_samples(pulse, samp_rate): """ Number of samples a given pulse is expected to occupy """ t_step = 1 / samp_rate # Number of samples n_pts = int( (pulse.dur - 0.5 * t_step) // t_step + 1 ) return n_pts
def pulse_length_samples(pulse, samp_rate):
""" Number of samples a given pulse is expected to occupy """ t_step = 1 / samp_rate # Number of samples n_pts = int( (pulse.dur - 0.5 * t_step) // t_step + 1 ) return n_pts
to sample array samp_dict[ch_name][indx_1: indx_2] = val_ar if debug: return samp_dict, n_pts, add_pts, t_ar else: return samp_dict, n_pts, add_pts def pulse_length_samples(pulse, samp_rate):
64
64
75
10
53
wi11dey/pylabnet
pylabnet/utils/pulseblock/pb_sample.py
Python
pulse_length_samples
pulse_length_samples
165
175
165
165
197a80ec032570a1204fe8d93d0d24e64b777520
bigcode/the-stack
train
151b9102542d56f6345c39ca
train
function
def pb_sample(pb_obj, samp_rate, len_min=0, len_max=float('inf'), len_step=1, len_adj=True, debug=False): """ Generate sample array. Unlike PulseBlock class, which makes now assumptions beyond the base class attributes, this function introduces one more requirement: each Pulse and DfltPulse object ...
def pb_sample(pb_obj, samp_rate, len_min=0, len_max=float('inf'), len_step=1, len_adj=True, debug=False):
""" Generate sample array. Unlike PulseBlock class, which makes now assumptions beyond the base class attributes, this function introduces one more requirement: each Pulse and DfltPulse object in the block must have get_value(t_ar) method with the following signature: :param t_a...
import numpy as np def pb_sample(pb_obj, samp_rate, len_min=0, len_max=float('inf'), len_step=1, len_adj=True, debug=False):
37
256
1,387
32
4
wi11dey/pylabnet
pylabnet/utils/pulseblock/pb_sample.py
Python
pb_sample
pb_sample
4
162
4
4
13a123e03124f5268beb252ebec28118b08b0607
bigcode/the-stack
train
ee2c94fd8c5a9fd6ddfb7eba
train
function
def pulse_sample(pulse, dflt_pulse, samp_rate, len_min=32, len_step=1, len_adj=True): """ Generate sample array from a single pulse object """ t_step = 1 / samp_rate # Number of samples n_pts_orig = pulse_length_samples(pulse, samp_rate) n_pts = n_pts_orig # Number of points added to meet...
def pulse_sample(pulse, dflt_pulse, samp_rate, len_min=32, len_step=1, len_adj=True):
""" Generate sample array from a single pulse object """ t_step = 1 / samp_rate # Number of samples n_pts_orig = pulse_length_samples(pulse, samp_rate) n_pts = n_pts_orig # Number of points added to meet length constraints add_pts = 0 # Sample array length fits hardware constrain...
_pts, add_pts, t_ar else: return samp_dict, n_pts, add_pts def pulse_length_samples(pulse, samp_rate): """ Number of samples a given pulse is expected to occupy """ t_step = 1 / samp_rate # Number of samples n_pts = int( (pulse.dur - 0.5 * t_step) // t_step + 1 ) retu...
125
125
417
28
96
wi11dey/pylabnet
pylabnet/utils/pulseblock/pb_sample.py
Python
pulse_sample
pulse_sample
178
229
178
178
db6a3501697d1d14017855b223eba9899df0eb0d
bigcode/the-stack
train
4c312f2d323f041c5bbf2cd7
train
class
class TestNoPublicationMetadataBarrier(LocalTestCase): def test__applies(self): book = Book(dict( id=-1, name='test__applies', )) metadata = self.add(PublicationMetadata, dict( book_id=book.id, )) barrier = NoPublicationMetadataBarrier(b...
class TestNoPublicationMetadataBarrier(LocalTestCase):
def test__applies(self): book = Book(dict( id=-1, name='test__applies', )) metadata = self.add(PublicationMetadata, dict( book_id=book.id, )) barrier = NoPublicationMetadataBarrier(book) self.assertFalse(barrier.applies()) ...
PagesBarrier(Book(id=123)) self.assertEqual(len(barrier.fixes), 1) self.assertTrue('>Upload</a> images' in barrier.fixes[0]) def test__reason(self): barrier = NoPagesBarrier({}) self.assertTrue('book has no pages' in barrier.reason) class TestNoPublicationMetadataBarrier(LocalTestCa...
77
77
257
10
67
zcomx/zco.mx
applications/zcomx/tests/book/test_release_barriers.py
Python
TestNoPublicationMetadataBarrier
TestNoPublicationMetadataBarrier
725
762
725
726
e305b94fa8bd00ef320ab26d3d4b0630f58d6977
bigcode/the-stack
train