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
0f7289da5fd18dd9f5b0f103
train
function
def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name return lax._dot_general_transpose_rhs( g, x, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None)
def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name
return lax._dot_general_transpose_rhs( g, x, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None)
( g, y, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None) def _pdot_transpose_rhs(g, x, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name
64
64
73
39
25
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_transpose_rhs
_pdot_transpose_rhs
1,457
1,461
1,457
1,458
d7e123a58977ba4ce4998f840ea6bc6a35e20135
bigcode/the-stack
train
43c89cbb500124ca0d906f04
train
function
def _foldaxis(axis, x): new_shape = list(x.shape) new_shape[axis:axis+2] = [x.shape[axis] * x.shape[axis + 1]] return x.reshape(new_shape)
def _foldaxis(axis, x):
new_shape = list(x.shape) new_shape[axis:axis+2] = [x.shape[axis] * x.shape[axis + 1]] return x.reshape(new_shape)
_shape = list(x.shape) assert new_shape[axis] % factor == 0, (new_shape[axis], factor) new_shape[axis:axis+1] = [factor, new_shape[axis] // factor] return x.reshape(new_shape) def _foldaxis(axis, x):
64
64
49
8
56
rsepassi/jax
jax/_src/lax/parallel.py
Python
_foldaxis
_foldaxis
827
830
827
827
f90f5387e9acc6142b9712ce3798d00962d9a7d4
bigcode/the-stack
train
546c18462b3ff85fdedc9caf
train
function
def _axis_index_abstract_eval(*, axis_name): frame = core.axis_frame(axis_name) return ShapedArray((), np.int32, named_shape={axis_name: frame.size})
def _axis_index_abstract_eval(*, axis_name):
frame = core.axis_frame(axis_name) return ShapedArray((), np.int32, named_shape={axis_name: frame.size})
xla.dtype_to_primitive_type(np.dtype(np.int32))) def _axis_index_translation_rule(ctx, avals_in, avals_out, *, axis_name): return [_build_axis_index_lowering(ctx.builder, axis_name, ctx.axis_env)] def _axis_index_abstract_eval(*, axis_name):
63
64
41
12
51
rsepassi/jax
jax/_src/lax/parallel.py
Python
_axis_index_abstract_eval
_axis_index_abstract_eval
1,350
1,352
1,350
1,350
a81aae3b78b5c3dc624bc6d6f30bd22abcfe4fe9
bigcode/the-stack
train
a0a6ef37888e891457e54c7c
train
function
def _pgather_impl(src, idx, *, axes): assert all(isinstance(axis, int) for axis in axes) src_axes_front = moveaxis(src, axes, range(len(axes))) non_axes_shape = src_axes_front.shape[len(axes):] src_one_axis_front = src_axes_front.reshape((-1,) + non_axes_shape) slice_sizes = (1,) + non_axes_shape idx = lax....
def _pgather_impl(src, idx, *, axes):
assert all(isinstance(axis, int) for axis in axes) src_axes_front = moveaxis(src, axes, range(len(axes))) non_axes_shape = src_axes_front.shape[len(axes):] src_one_axis_front = src_axes_front.reshape((-1,) + non_axes_shape) slice_sizes = (1,) + non_axes_shape idx = lax.reshape(idx, idx.shape + (1,)) offse...
=[pos_contract, pos_batch], precision=precision, preferred_element_type=None) ad.defbilinear(pdot_p, _pdot_transpose_lhs, _pdot_transpose_rhs) pxla.multi_host_supported_collectives.add(pdot_p) def _pgather_impl(src, idx, *, axes):
64
64
182
12
52
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pgather_impl
_pgather_impl
1,467
1,480
1,467
1,467
d64ac2e3da9167fa1befe457a6f890c8ce8d1abb
bigcode/the-stack
train
84610466c90ba1283716af96
train
function
def _all_to_all_transpose_rule(cts, x, axis_name, split_axis, concat_axis, axis_index_groups): return (all_to_all( cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis, axis_index_groups=axis_index_groups),)
def _all_to_all_transpose_rule(cts, x, axis_name, split_axis, concat_axis, axis_index_groups):
return (all_to_all( cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis, axis_index_groups=axis_index_groups),)
_in, avals_out, x, axis_name=axis_name, split_axis=split_axis, concat_axis=concat_axis, axis_index_groups=axis_index_groups) def _all_to_all_transpose_rule(cts, x, axis_name, split_axis, concat_axis, axis_index_groups):
64
64
68
26
38
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_transpose_rule
_all_to_all_transpose_rule
881
887
881
881
c019bf060eaf89aff01d4fb31618a2e54096c156
bigcode/the-stack
train
fdeb5c28b69328d6747c2018
train
function
def ppermute(x, axis_name, perm): """Perform a collective permutation according to the permutation ``perm``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This function is an analog of the CollectivePermute XLA HLO. Args: x: array(s) with a mapped...
def ppermute(x, axis_name, perm):
"""Perform a collective permutation according to the permutation ``perm``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. This function is an analog of the CollectivePermute XLA HLO. Args: x: array(s) with a mapped axis named ``axis_name``. axi...
min(validx, axis_name) def _validate_reduce_axis_index_groups(axis_index_groups): if axis_index_groups is None: return axis_space = range(sum(len(group) for group in axis_index_groups)) if {i for g in axis_index_groups for i in g} != set(axis_space): raise ValueError("axis_index_groups must cover all ind...
91
91
306
11
80
rsepassi/jax
jax/_src/lax/parallel.py
Python
ppermute
ppermute
205
231
205
205
3bc28eac176fa2133890028525a2c5e118d67dd8
bigcode/the-stack
train
ec707020e454798d3a1f240b
train
function
def _pdot_vmap_collective_rule(axis_size, frame_name, _, vals_in, dims_in, *, axis_name, pos_contract, pos_batch, precision): x, y = vals_in x_dim, y_dim = dims_in x_pos_contract, y_pos_contract = pos_contract x_pos_contract = [x_dim] + [d + (d >= x_dim) for d in x_pos_contract] ...
def _pdot_vmap_collective_rule(axis_size, frame_name, _, vals_in, dims_in, *, axis_name, pos_contract, pos_batch, precision):
x, y = vals_in x_dim, y_dim = dims_in x_pos_contract, y_pos_contract = pos_contract x_pos_contract = [x_dim] + [d + (d >= x_dim) for d in x_pos_contract] y_pos_contract = [y_dim] + [d + (d >= y_dim) for d in y_pos_contract] x_pos_batch, y_pos_batch = pos_batch x_pos_batch = [d + (d >= x_dim) for d in x_po...
= {name: size for name, size in common_named_shape.items() if name not in axis_name} return pos_aval.update(named_shape=named_shape) def _pdot_vmap_collective_rule(axis_size, frame_name, _, vals_in, dims_in, *, axis_name, pos_contract, pos_batch, preci...
72
72
242
35
37
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_vmap_collective_rule
_pdot_vmap_collective_rule
1,413
1,428
1,413
1,414
d0d3d930ea45899d0fc2c504301fa0302b2bfa92
bigcode/the-stack
train
c49da57b28ee45477d6fc0d8
train
function
def _axis_index_translation_rule(ctx, avals_in, avals_out, *, axis_name): return [_build_axis_index_lowering(ctx.builder, axis_name, ctx.axis_env)]
def _axis_index_translation_rule(ctx, avals_in, avals_out, *, axis_name):
return [_build_axis_index_lowering(ctx.builder, axis_name, ctx.axis_env)]
= xops.Rem(xops.Div(xops.ReplicaId(c), div), mod) return xops.ConvertElementType( unsigned_index, xla.dtype_to_primitive_type(np.dtype(np.int32))) def _axis_index_translation_rule(ctx, avals_in, avals_out, *, axis_name):
64
64
38
20
44
rsepassi/jax
jax/_src/lax/parallel.py
Python
_axis_index_translation_rule
_axis_index_translation_rule
1,346
1,347
1,346
1,346
910dd12ed828549dda04599acff6da81012bbd60
bigcode/the-stack
train
28facbfa9c048bb16bca19fb
train
function
def pshuffle(x, axis_name, perm): """Convenience wrapper of jax.lax.ppermute with alternate permutation encoding If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python ob...
def pshuffle(x, axis_name, perm):
"""Convenience wrapper of jax.lax.ppermute with alternate permutation encoding If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (...
Returns: Array(s) with the same shape as ``x`` with slices along the axis ``axis_name`` gathered from ``x`` according to the permutation ``perm``. """ return tree_util.tree_map( partial(ppermute_p.bind, axis_name=axis_name, perm=tuple(perm)), x) def pshuffle(x, axis_name, perm):
79
79
264
10
69
rsepassi/jax
jax/_src/lax/parallel.py
Python
pshuffle
pshuffle
233
254
233
233
cdbe508ea0cac9c063799f3c126e3a3705ad43ed
bigcode/the-stack
train
b5fc5c5c08a595550e11c6e5
train
function
def _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): assert axis_index_groups is None, "axis_index_groups not supported in vmap" assert axis_size ==...
def _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
assert axis_index_groups is None, "axis_index_groups not supported in vmap" assert axis_size == frame_size, "axis size doesn't match" if not isinstance(axis_name, tuple): axis_name = (axis_name,) if len(axis_name) > 1: raise NotImplementedError("Please open a feature request!") assert axis_name == (fr...
, axis_name=axis_name, axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled) return result, d def _all_gather_batched_collective(frame_size, frame_name, _, vals_in, dims_in, all_gather_dimension, axis_name, ...
76
76
255
41
34
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_batched_collective
_all_gather_batched_collective
1,131
1,151
1,131
1,133
7d69e9ed1343eb7c37db77fccc849df83d13787e
bigcode/the-stack
train
36824fff3a0b444efb2bfa78
train
function
def pargmax(x, axis_name): if isinstance(axis_name, (tuple, list)): raise TypeError(f"pargmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmax(x, axis_name), axis_name)
def pargmax(x, axis_name):
if isinstance(axis_name, (tuple, list)): raise TypeError(f"pargmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmax(x, axis_name), axis_name)
gmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmin(x, axis_name), axis_name) # TODO(mattjj): add a pargmax_p, or add named axis support to lax.argmax_p def pargmax(x, axis_name):
64
64
59
9
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
pargmax
pargmax
188
191
188
188
b3c6213a1f62f6e6641d382aa22ade00530296c9
bigcode/the-stack
train
c370fe5c9c0d59c0acecb498
train
function
def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name return lax._dot_general_transpose_lhs( g, y, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None)
def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name
return lax._dot_general_transpose_lhs( g, y, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None)
xla.lower_fun(_pdot_lowering, multiple_results=False, new_style=True), is_collective=True) def _pdot_transpose_lhs(g, y, *, axis_name, pos_contract, pos_batch, precision): # TODO: avals with names, call pbroadcast with axis_name
64
64
75
40
24
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_transpose_lhs
_pdot_transpose_lhs
1,452
1,456
1,452
1,453
fdd5c4380fc10d87a5d11f636dd116db8e1ef2fc
bigcode/the-stack
train
ff6d45a66a820deee5b706a5
train
function
def _reduce_scatter_translation_rule(prim, reducer, ctx, avals_in, avals_out, x, *, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled): c = ctx.builder if ctx.platform in ("tpu", "gpu"): scalar = ShapedArray((), c.get_shap...
def _reduce_scatter_translation_rule(prim, reducer, ctx, avals_in, avals_out, x, *, scatter_dimension, axis_name, axis_index_groups, axis_size, tiled):
c = ctx.builder if ctx.platform in ("tpu", "gpu"): scalar = ShapedArray((), c.get_shape(x).numpy_dtype()) computation = xla.primitive_subcomputation( ctx.platform, ctx.axis_env, prim, scalar, scalar) replica_groups = _replica_groups(ctx.axis_env, axis_name, axis_index_groups) x = xops.Reduce...
=index * scatter_dim_output_size, slice_size=scatter_dim_output_size, axis=scatter_dimension) if not tiled: outs = lax.squeeze(outs, [scatter_dimension]) return outs def _reduce_scatter_translation_rule(prim, reducer, ctx, avals_in, avals_out, x, *, scatter_dimen...
85
85
285
42
42
rsepassi/jax
jax/_src/lax/parallel.py
Python
_reduce_scatter_translation_rule
_reduce_scatter_translation_rule
1,190
1,219
1,190
1,192
1aa7db2a92e7228bb98c19e7820559764cf3b648
bigcode/the-stack
train
15bf85be77e7cd80f989c56b
train
function
def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) x_aval = raise_to_shaped(x) new_shape = list(x_aval.shape) if tiled: new_shape[all_gather_dimension] *= axis_size else: n...
def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) x_aval = raise_to_shaped(x) new_shape = list(x_aval.shape) if tiled: new_shape[all_gather_dimension] *= axis_size else: new_shape.insert(all_gather_dimension, axis_size) new_named_shape = {name: size for name, size in x_aval.n...
all_gather_dimension=all_gather_dimension, axis_name=axis_name, axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled) def _all_gather_abstract_eval(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
64
64
146
28
36
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_abstract_eval
_all_gather_abstract_eval
1,090
1,101
1,090
1,090
7e3b3ae82572b64843e9c6c357c8ae835c69f34e
bigcode/the-stack
train
ade3ac73ec31379e26b52fff
train
function
def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ()), precision=None): if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) return pdot_p.bind(x, y, axis_name=axis_name, pos_contract=pos_contract, pos_batch=pos_batch, precision=l...
def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ()), precision=None):
if not isinstance(axis_name, (list, tuple)): axis_name = (axis_name,) return pdot_p.bind(x, y, axis_name=axis_name, pos_contract=pos_contract, pos_batch=pos_batch, precision=lax.canonicalize_precision(precision))
[[0 1] [0 1] [0 1] [0 1]] """ return axis_index_p.bind(axis_name=axis_name) def pdot(x, y, axis_name, pos_contract=((), ()), pos_batch=((), ()), precision=None):
64
64
86
26
38
rsepassi/jax
jax/_src/lax/parallel.py
Python
pdot
pdot
399
405
399
400
c6589f6c7332b771d89eff45177e5d2d74ce2ef5
bigcode/the-stack
train
da97cc5b1ab4dac7de89dbee
train
function
def _pdot_lowering(x, y, *, axis_name, pos_contract, pos_batch, precision): local_out = lax.dot_general(x, y, dimension_numbers=(pos_contract, pos_batch), precision=precision, preferred_element_type=None) return psum(local_out, axis_name) if axis_name is not None else local_out
def _pdot_lowering(x, y, *, axis_name, pos_contract, pos_batch, precision):
local_out = lax.dot_general(x, y, dimension_numbers=(pos_contract, pos_batch), precision=precision, preferred_element_type=None) return psum(local_out, axis_name) if axis_name is not None else local_out
pos_contract, pos_batch=pos_batch, precision=precision) return out, result_batch_dim batching.primitive_batchers[pdot_p] = _pdot_vmap_batching_rule def _pdot_lowering(x, y, *, axis_name, pos_contract, pos_batch, precision):
64
64
72
22
41
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_lowering
_pdot_lowering
1,442
1,445
1,442
1,442
81e352fab787353b4f667188be79ed31aac841c1
bigcode/the-stack
train
dae031e3763389e37e2c67d0
train
function
def _ppermute_batcher(axis_size, frame_name, _, vals_in, dims_in, axis_name, perm): (v,), (d,) = vals_in, dims_in if not isinstance(axis_name, (tuple, list)): axis_name = (axis_name,) remaining_axes = tuple(axis for axis in axis_name if axis != frame_name) if axis_size == 1 and remaining_axes: return pp...
def _ppermute_batcher(axis_size, frame_name, _, vals_in, dims_in, axis_name, perm):
(v,), (d,) = vals_in, dims_in if not isinstance(axis_name, (tuple, list)): axis_name = (axis_name,) remaining_axes = tuple(axis for axis in axis_name if axis != frame_name) if axis_size == 1 and remaining_axes: return ppermute_p.bind(v, perm=perm, axis_name=remaining_axes), d if remaining_axes: ra...
srcs, dsts = unzip2(perm) inverse_perm = list(zip(dsts, srcs)) return [ppermute(t, axis_name=axis_name, perm=inverse_perm)] def _ppermute_batcher(axis_size, frame_name, _, vals_in, dims_in, axis_name, perm):
67
67
224
25
42
rsepassi/jax
jax/_src/lax/parallel.py
Python
_ppermute_batcher
_ppermute_batcher
785
800
785
785
7842e5b80ca3587192d2562b48d8e6c477fb4271
bigcode/the-stack
train
f093e678b986669f6e7af18d
train
function
def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): index = _index_in_group(axis_name, axis_index_groups) outs = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index, tiled), x) return psum(outs, axis_name, axis_index_groups=axis_index_groups...
def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
index = _index_in_group(axis_name, axis_index_groups) outs = tree_util.tree_map(partial(_expand, all_gather_dimension, axis_size, index, tiled), x) return psum(outs, axis_name, axis_index_groups=axis_index_groups)
(dim, size) out = lax.full(shape, lax._const(x, 0)) return slicing.dynamic_update_index_in_dim(out, x, index, dim) def _all_gather_via_psum(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
64
64
87
29
35
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_via_psum
_all_gather_via_psum
1,058
1,061
1,058
1,058
8880e10a91507f34e8bf681de7fb2abc10b909cd
bigcode/the-stack
train
03a4931a8f0b1921ee1aed1d
train
function
def _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): raise AssertionError("Unexpected call to _all_gather_impl")
def _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
raise AssertionError("Unexpected call to _all_gather_impl")
_map(partial(_expand, all_gather_dimension, axis_size, index, tiled), x) return psum(outs, axis_name, axis_index_groups=axis_index_groups) def _all_gather_impl(x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
64
64
40
26
38
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_impl
_all_gather_impl
1,063
1,064
1,063
1,063
11a175e3344a2593e611c797f94a44430200fa00
bigcode/the-stack
train
f75fbbb274cdb24d0a9e9f72
train
function
def _pgather_collective_batcher(axis_size, frame_name, _, vals_in, dims_in, *, axes): src, idx = vals_in dsrc, didx = dims_in if dsrc is batching.not_mapped: raise ValueError("pgather axis {frame.name} is missing from the indexed value") if didx is not batching.not_mapped: # NOTE: This is allowed and th...
def _pgather_collective_batcher(axis_size, frame_name, _, vals_in, dims_in, *, axes):
src, idx = vals_in dsrc, didx = dims_in if dsrc is batching.not_mapped: raise ValueError("pgather axis {frame.name} is missing from the indexed value") if didx is not batching.not_mapped: # NOTE: This is allowed and the output would be mapped along this axis! raise NotImplementedError("Please open a...
_last_batched = moveaxis(src, dsrc, -1) result = pgather_p.bind(src_last_batched, idx, axes=axes) return result, result.ndim - 1 else: assert False # This shouldn't get called anyway def _pgather_collective_batcher(axis_size, frame_name, _, vals_in, dims_in, *, axes):
81
81
272
24
56
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pgather_collective_batcher
_pgather_collective_batcher
1,514
1,534
1,514
1,514
8db7d4d5daf293a95a44c4dc1656514f840642f5
bigcode/the-stack
train
cbde8d7e54e74a30c20301d7
train
function
def _validate_reduce_axis_index_groups(axis_index_groups): if axis_index_groups is None: return axis_space = range(sum(len(group) for group in axis_index_groups)) if {i for g in axis_index_groups for i in g} != set(axis_space): raise ValueError("axis_index_groups must cover all indices exactly once")
def _validate_reduce_axis_index_groups(axis_index_groups):
if axis_index_groups is None: return axis_space = range(sum(len(group) for group in axis_index_groups)) if {i for g in axis_index_groups for i in g} != set(axis_space): raise ValueError("axis_index_groups must cover all indices exactly once")
axis_index_of_val(x, val, axis_name): idx = axis_index(axis_name) validx = lax_numpy.where(val == x, idx, dtypes.iinfo(dtypes.dtype(idx)).max) return pmin(validx, axis_name) def _validate_reduce_axis_index_groups(axis_index_groups):
64
64
73
11
53
rsepassi/jax
jax/_src/lax/parallel.py
Python
_validate_reduce_axis_index_groups
_validate_reduce_axis_index_groups
198
203
198
198
8423fedc2ef4f615a17706fb27cd271e271f3d09
bigcode/the-stack
train
e166a65049d3bc429cf1bf22
train
function
@pdot_p.def_abstract_eval def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch, precision): # TODO(frostig,mattjj,jekbradbury): check inputs have given axis names? if not len(set(axis_name)) == len(axis_name): raise ValueError pos_aval = lax.dot_general_p.abstract_eval( x, y, dimension_number...
@pdot_p.def_abstract_eval def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch, precision): # TODO(frostig,mattjj,jekbradbury): check inputs have given axis names?
if not len(set(axis_name)) == len(axis_name): raise ValueError pos_aval = lax.dot_general_p.abstract_eval( x, y, dimension_numbers=[pos_contract, pos_batch], precision=precision, preferred_element_type=None) common_named_shape = core.join_named_shapes(x.named_shape, y.named_shape) named_shape = {nam...
pos_contract, pos_batch), precision=precision) @pdot_p.def_abstract_eval def _pdot_abstract_eval(x, y, *, axis_name, pos_contract, pos_batch, precision): # TODO(frostig,mattjj,jekbradbury): check inputs have given axis names?
64
64
164
54
10
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_abstract_eval
_pdot_abstract_eval
1,400
1,411
1,400
1,402
9f65d8d45b92a8d4c796867985580007d280da68
bigcode/the-stack
train
ca19ea5d1cdcfdb296e4ab77
train
function
@psum_p.def_custom_bind def psum_bind(*args, axes, axis_index_groups): if all(not isinstance(x, core.Tracer) for x in args): named_axes, pos_axes = axes_partition = [], [] for axis in axes: axes_partition[isinstance(axis, int)].append(axis) def pos_reduce(x): if not pos_axes: return x ...
@psum_p.def_custom_bind def psum_bind(*args, axes, axis_index_groups):
if all(not isinstance(x, core.Tracer) for x in args): named_axes, pos_axes = axes_partition = [], [] for axis in axes: axes_partition[isinstance(axis, int)].append(axis) def pos_reduce(x): if not pos_axes: return x return lax._reduce_sum(x, [canonicalize_axis(axis, getattr(x, 'nd...
psum_p] = partial(_subst_all_names_in_param, 'axes') # We set a special bind rule for psum so that psum(1, 'i') can be evaluated at # tracing time. @psum_p.def_custom_bind def psum_bind(*args, axes, axis_index_groups):
64
64
213
20
44
rsepassi/jax
jax/_src/lax/parallel.py
Python
psum_bind
psum_bind
717
735
717
718
493d61c2607cdbbc5839a955b17d28c74692cc49
bigcode/the-stack
train
ed2ff9b49353b6600460f349
train
function
def pswapaxes(x, axis_name, axis, *, axis_index_groups=None): """Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. The group size of the mapped axis size must be equal to the size of the ...
def pswapaxes(x, axis_name, axis, *, axis_index_groups=None):
"""Swap the pmapped axis ``axis_name`` with the unmapped axis ``axis``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. The group size of the mapped axis size must be equal to the size of the unmapped axis; that is, we must have ``lax.psum(1, axis_name...
once for axis size N. Returns: Array(s) with the same shape as ``x`` with slices along the axis ``axis_name`` gathered from ``x`` according to the permutation ``perm``. """ if set(perm) != set(range(len(perm))): raise ValueError(f"`perm` does not represent a permutation: {perm}") return ppermute(x...
115
116
387
17
99
rsepassi/jax
jax/_src/lax/parallel.py
Python
pswapaxes
pswapaxes
257
286
257
257
496c9d56e8cc20eeefdd9033e77ff6b89494f891
bigcode/the-stack
train
a1bbf6db68079ab99a4771e6
train
function
def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): if tiled: raise NotImplementedError("Please open a feature request!") # TODO(cjfj): Use lax.reduce_scatter here concat_axis = 0 return (lax_numpy.sum(all_to_all( cts, axis_name=axis_name, s...
def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
if tiled: raise NotImplementedError("Please open a feature request!") # TODO(cjfj): Use lax.reduce_scatter here concat_axis = 0 return (lax_numpy.sum(all_to_all( cts, axis_name=axis_name, split_axis=all_gather_dimension, concat_axis=concat_axis, axis_index_groups=axis_index_groups), axis=c...
size in x_aval.named_shape.items() if name not in axis_name} return x_aval.update(shape=new_shape, named_shape=new_named_shape) def _all_gather_transpose_rule(cts, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
64
64
119
31
33
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_transpose_rule
_all_gather_transpose_rule
1,103
1,111
1,103
1,103
0008016f28bed9b9de7f1c0a3eddc749247e9ebb
bigcode/the-stack
train
a2e8b0b3240432439e663a31
train
function
def psum(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Inputs of boolean dtype are converted to integers before the reduction. Args: ...
def psum(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce sum on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Inputs of boolean dtype are converted to integers before the reduction. Args: x: array(s) with a mapped axis named ``axis_name...
jax.interpreters import ad from jax.interpreters import xla from jax.interpreters import pxla from jax.interpreters import batching from jax._src import dtypes from jax._src.lax import lax from jax._src.lax import slicing from jax._src.lib import xla_client as xc from jax._src.numpy import lax_numpy from jax._src.util...
151
151
506
14
136
rsepassi/jax
jax/_src/lax/parallel.py
Python
psum
psum
46
88
46
46
60aac7ac012f97df145df324603d48973e75b48a
bigcode/the-stack
train
82e943a319a26c399a5f7298
train
function
def _axis_index_bind(*, axis_name): def name_idx(name): frame = core.axis_frame(name) dynamic = core.thread_local_state.trace_state.trace_stack.dynamic if (frame.main_trace is None or dynamic.level > frame.main_trace.level): return core.Primitive.bind(axis_index_p, axis_name=name) else: tr...
def _axis_index_bind(*, axis_name):
def name_idx(name): frame = core.axis_frame(name) dynamic = core.thread_local_state.trace_state.trace_stack.dynamic if (frame.main_trace is None or dynamic.level > frame.main_trace.level): return core.Primitive.bind(axis_index_p, axis_name=name) else: trace = frame.main_trace.with_cur_subl...
default bind would have no # way to call into a data-dependency based trace such as vmap. Each trace that # wants to bind an axis name has to additionally implement `process_axis_index` # and put its main trace on the axis env stack. def _axis_index_bind(*, axis_name):
64
64
160
10
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
_axis_index_bind
_axis_index_bind
1,365
1,383
1,365
1,365
bd329e71079a9aca421fb04845304f7850fe3d02
bigcode/the-stack
train
3c90e500fed5f6675ffb6ea8
train
function
def _allreduce_abstract_eval(*args, axes, axis_index_groups): # TODO(frostig,mattjj,jekbradbury): maybe check aval names here pos_axes = tuple(axis for axis in axes if isinstance(axis, int)) named_shapes = [arg.named_shape for arg in args] if axis_index_groups is None: named_axes = set(axis for axis in axes...
def _allreduce_abstract_eval(*args, axes, axis_index_groups): # TODO(frostig,mattjj,jekbradbury): maybe check aval names here
pos_axes = tuple(axis for axis in axes if isinstance(axis, int)) named_shapes = [arg.named_shape for arg in args] if axis_index_groups is None: named_axes = set(axis for axis in axes if not isinstance(axis, int)) named_shapes = [{name: size for name, size in arg.named_shape.items() if...
all(isinstance(axis, int) for axis in axes) return [pos_reducer(arg, axes) for arg in args] def _allreduce_abstract_eval(*args, axes, axis_index_groups): # TODO(frostig,mattjj,jekbradbury): maybe check aval names here
64
64
212
37
27
rsepassi/jax
jax/_src/lax/parallel.py
Python
_allreduce_abstract_eval
_allreduce_abstract_eval
630
644
630
631
13fd7e6675724aef3e50b74bc96a04c12346d489
bigcode/the-stack
train
defb6105693b720ebcda4a25
train
function
def _index_in_group(axis_name, axis_index_groups): cur_device_id = axis_index(axis_name) if axis_index_groups is None: return cur_device_id # We use argsort to invert the axis_index_groups permutation flat_groups = np.array(axis_index_groups).flatten() device_id_to_idx = flat_groups.argsort() % len(axis_i...
def _index_in_group(axis_name, axis_index_groups):
cur_device_id = axis_index(axis_name) if axis_index_groups is None: return cur_device_id # We use argsort to invert the axis_index_groups permutation flat_groups = np.array(axis_index_groups).flatten() device_id_to_idx = flat_groups.argsort() % len(axis_index_groups[0]) return lax.squeeze( slicing...
(new_shape) def _foldaxis(axis, x): new_shape = list(x.shape) new_shape[axis:axis+2] = [x.shape[axis] * x.shape[axis + 1]] return x.reshape(new_shape) def _index_in_group(axis_name, axis_index_groups):
64
64
107
12
52
rsepassi/jax
jax/_src/lax/parallel.py
Python
_index_in_group
_index_in_group
832
840
832
832
691086f1790f5c42378a1666c7661d041f22e950
bigcode/the-stack
train
bd57a0a8944d4a76970011f3
train
class
class XeinsumSpecParser: spec: str pos: int def __init__(self, spec: str): self.spec = spec self.pos = 0 @property def eof(self): return self.pos == len(self.spec) @property def cur(self): return self.spec[self.pos] def parse_subscript(self): if self.cur in string.ascii_lowercase...
class XeinsumSpecParser:
spec: str pos: int def __init__(self, spec: str): self.spec = spec self.pos = 0 @property def eof(self): return self.pos == len(self.spec) @property def cur(self): return self.spec[self.pos] def parse_subscript(self): if self.cur in string.ascii_lowercase: out = self.cur ...
unzip2((lhs_subs.index(n), rhs_subs.index(n)) for n in subs_contract - (lhs_uniques | rhs_uniques)) # if a subscript apperas in both inputs _and_ the outputs, batch! subs_batch = all_subs - subs_contract if subs_batch & (lhs_uniques | rhs_uniques): raise NotImplementedError pos_ba...
142
142
474
7
135
rsepassi/jax
jax/_src/lax/parallel.py
Python
XeinsumSpecParser
XeinsumSpecParser
453
532
453
453
ace64bf51115f91941db8998769a10053b963fbd
bigcode/the-stack
train
d0504fdab09b5dc97b394989
train
function
def pmax(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce max on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hasha...
def pmax(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce max on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see ...
i')(x) >>> print(y) [0. 0.6666667 1.3333334 2. ] """ x = psum(x, axis_name=axis_name, axis_index_groups=axis_index_groups) n = psum(1, axis_name=axis_name, axis_index_groups=axis_index_groups) return tree_util.tree_map(lambda v: v / n, x) def pmax(x, axis_name, *, axis_index_groups=None):
105
105
350
14
91
rsepassi/jax
jax/_src/lax/parallel.py
Python
pmax
pmax
123
150
123
123
f5cf5604497c3d1921806a084a7b8267d340223a
bigcode/the-stack
train
5dab1f96ac0a294f8a5e23cd
train
function
def pmean(x, axis_name, *, axis_index_groups=None): """Compute an all-reduce mean on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: has...
def pmean(x, axis_name, *, axis_index_groups=None):
"""Compute an all-reduce mean on ``x`` over the pmapped axis ``axis_name``. If ``x`` is a pytree then the result is equivalent to mapping this function to each leaf in the tree. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see...
axis_index_groups only supported for sums over just named axes") _validate_reduce_axis_index_groups(axis_index_groups) leaves, treedef = tree_util.tree_flatten(x) leaves = [lax.convert_element_type(l, np.int32) if dtypes.dtype(l) == np.bool_ else l for l in leaves] out_flat = psum_p.bind(*leaves, ax...
123
123
413
14
109
rsepassi/jax
jax/_src/lax/parallel.py
Python
pmean
pmean
90
121
90
90
91cc2861e88c05d9d2bcd744345e0c121157eb00
bigcode/the-stack
train
1fd6cdf91e0200e0f51b5c4e
train
function
@pdot_p.def_impl def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch, precision): if axis_name: raise NameError(f"unbound axis name: {axis_name[0]}") return lax.dot_general(x, y, (pos_contract, pos_batch), precision=precision)
@pdot_p.def_impl def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch, precision):
if axis_name: raise NameError(f"unbound axis name: {axis_name[0]}") return lax.dot_general(x, y, (pos_contract, pos_batch), precision=precision)
: ignore pdot_p = core.AxisPrimitive('pdot') core.axis_substitution_rules[pdot_p] = partial(_subst_all_names_in_param, 'axis_name') @pdot_p.def_impl def _pdot_impl(x, y, *, axis_name, pos_contract, pos_batch, precision):
64
64
70
28
36
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pdot_impl
_pdot_impl
1,395
1,398
1,395
1,396
6050cdcdb582b25a10eee4b507fcfb10ff011a64
bigcode/the-stack
train
c4a5f9a29f76885427948cc6
train
function
def _all_gather_translation_rule( ctx, avals_in, avals_out, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): # TODO(jekbradbury): enable for all_gather_dimension > 0 c = ctx.builder if ctx.platform == 'tpu' or ctx.platform == 'gpu' and all_gather_dimension == 0: if not tile...
def _all_gather_translation_rule( ctx, avals_in, avals_out, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): # TODO(jekbradbury): enable for all_gather_dimension > 0
c = ctx.builder if ctx.platform == 'tpu' or ctx.platform == 'gpu' and all_gather_dimension == 0: if not tiled: new_shape = list(c.get_shape(x).dimensions()) new_shape.insert(all_gather_dimension, 1) broadcast_dimensions = [i for i in range(len(new_shape)) if i != all_gather_dimension] x ...
_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): raise AssertionError("Unexpected call to _all_gather_impl") def _all_gather_translation_rule( ctx, avals_in, avals_out, x, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): # TODO(jekbradbury): enable for all_gather_...
89
89
297
59
30
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_translation_rule
_all_gather_translation_rule
1,066
1,088
1,066
1,069
c0c09048129e4979e95f9acf35b9d585b3542277
bigcode/the-stack
train
1ceddc69157dfa5a3f7c5cff
train
function
def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled): (x,), (d,) = vals_in, dims_in if d <= all_gather_dimension: all_gather_dimension += 1 elif not tiled: # Tiled all-gather doesn't modify the set of dimensions d += 1 result = all_gather_p....
def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
(x,), (d,) = vals_in, dims_in if d <= all_gather_dimension: all_gather_dimension += 1 elif not tiled: # Tiled all-gather doesn't modify the set of dimensions d += 1 result = all_gather_p.bind( x, all_gather_dimension=all_gather_dimension, axis_name=axis_name, axis_index_groups=a...
replication. # return (lax.dynamic_index_in_dim(cts, idx, axis=all_gather_dimension, keepdims=False) * axis_size,) def _all_gather_batcher(vals_in, dims_in, *, all_gather_dimension, axis_name, axis_index_groups, axis_size, tiled):
63
64
145
31
32
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_gather_batcher
_all_gather_batcher
1,116
1,129
1,116
1,116
2825193cf8f5e126b194ad57c4a08bd90c30b5c8
bigcode/the-stack
train
4eb292cf3e827cfeb82f5d7f
train
function
def psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, tiled=False): """Compute an all-reduce sum over the axis ``axis_name``, and scatter the result. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the ...
def psum_scatter(x, axis_name, *, scatter_dimension=0, axis_index_groups=None, tiled=False):
"""Compute an all-reduce sum over the axis ``axis_name``, and scatter the result. Args: x: array(s) with a mapped axis named ``axis_name``. axis_name: hashable Python object used to name a pmapped axis (see the :func:`jax.pmap` documentation for more details). scatter_dimension: a positional axis...
new_shape[scatter_dimension] = scatter_dim_input_size // axis_size else: if scatter_dim_input_size != axis_size: raise ValueError(f"reduce_scatter operand scatter dimension size " f"{scatter_dim_input_size} must match shard count " f"{axis_size}") del new_s...
219
219
732
24
195
rsepassi/jax
jax/_src/lax/parallel.py
Python
psum_scatter
psum_scatter
1,259
1,326
1,259
1,259
e0f3dc3dc6416fbdee5ceaa8decd35ed24e80cf9
bigcode/the-stack
train
ace6612df9c13e34868a9ada
train
function
def _ppermute_translation_rule(ctx, avals_in, avals_out, x, *, axis_name, perm): replica_groups = _replica_groups(ctx.axis_env, axis_name, None) group_size = len(replica_groups[0]) srcs, dsts = unzip2((src % group_size, dst % group_size) for src, dst in perm) if not (len(srcs) == len(set(srcs)) and len(dsts) ==...
def _ppermute_translation_rule(ctx, avals_in, avals_out, x, *, axis_name, perm):
replica_groups = _replica_groups(ctx.axis_env, axis_name, None) group_size = len(replica_groups[0]) srcs, dsts = unzip2((src % group_size, dst % group_size) for src, dst in perm) if not (len(srcs) == len(set(srcs)) and len(dsts) == len(set(dsts))): msg = "ppermute sources and destinations must be unique, go...
ched_reduction_collective, pmin_p, lambda v, axis_size: v) core.axis_substitution_rules[pmin_p] = partial(_subst_all_names_in_param, 'axes') def _ppermute_translation_rule(ctx, avals_in, avals_out, x, *, axis_name, perm):
64
64
186
25
39
rsepassi/jax
jax/_src/lax/parallel.py
Python
_ppermute_translation_rule
_ppermute_translation_rule
766
778
766
766
4fe75163fcbcbec080e34e590b97acd7ea125448
bigcode/the-stack
train
5d1da3c830c99b2dc8718c77
train
function
def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis, axis_index_groups): input_aval = raise_to_shaped(x) shape = list(input_aval.shape) axis_size = psum(1, axis_name) if axis_index_groups is None else len(axis_index_groups[0]) assert shape[split_axis] % axis_size == 0, (shape[split_axis], axis_s...
def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis, axis_index_groups):
input_aval = raise_to_shaped(x) shape = list(input_aval.shape) axis_size = psum(1, axis_name) if axis_index_groups is None else len(axis_index_groups[0]) assert shape[split_axis] % axis_size == 0, (shape[split_axis], axis_size) shape[split_axis] //= axis_size shape[concat_axis] *= axis_size return input_a...
(0, concat_axis - 1, x)) new_d -= 1 # We've removed 0th dimension, so new_d needs to be adjusted return x, new_d def _all_to_all_abstract_eval(x, axis_name, split_axis, concat_axis, axis_index_groups):
64
64
128
23
40
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_abstract_eval
_all_to_all_abstract_eval
956
963
956
956
e1de7424c353fafbba5555cb389736561e009271
bigcode/the-stack
train
76b923dcd796c73a803a5d3d
train
function
def _build_axis_index_lowering(c, axis_name, axis_env): if isinstance(axis_name, tuple): assert axis_name, 'empty axis name' if len(axis_name) > 1: raise NotImplementedError( '`axis_index` translation rule does not support multiple axis names.') axis_name, = axis_name axis_pos = list(axi...
def _build_axis_index_lowering(c, axis_name, axis_env):
if isinstance(axis_name, tuple): assert axis_name, 'empty axis name' if len(axis_name) > 1: raise NotImplementedError( '`axis_index` translation rule does not support multiple axis names.') axis_name, = axis_name axis_pos = list(axis_env.names).index(axis_name) nreplicas = axis_env.nre...
atter_p.bind, axis_name=axis_name, scatter_dimension=scatter_dimension, axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled) return tree_util.tree_map(bind, x) def _build_axis_index_lowering(c, axis_name, axis_env):
64
64
204
15
49
rsepassi/jax
jax/_src/lax/parallel.py
Python
_build_axis_index_lowering
_build_axis_index_lowering
1,329
1,344
1,329
1,329
4f389e919892fe67bf20a1119d6864fe2bb8aaf9
bigcode/the-stack
train
8b08c05517f5bbd8ddf69650
train
function
def pargmin(x, axis_name): if isinstance(axis_name, (tuple, list)): raise TypeError(f"pargmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmin(x, axis_name), axis_name)
def pargmin(x, axis_name):
if isinstance(axis_name, (tuple, list)): raise TypeError(f"pargmin only accepts a single axis, got {axis_name}") return _axis_index_of_val(x, pmin(x, axis_name), axis_name)
leaves, axes=axis_name, axis_index_groups=axis_index_groups) return tree_util.tree_unflatten(treedef, out_flat) # TODO(mattjj): add a pargmin_p, or add named axis support to lax.argmin_p def pargmin(x, axis_name):
64
64
59
9
54
rsepassi/jax
jax/_src/lax/parallel.py
Python
pargmin
pargmin
182
185
182
182
8adebb27278525b6a97d4246f0ba66978b3020ba
bigcode/the-stack
train
a06124244fa26f72584a693f
train
function
def _pgather_abstract_eval(src, idx, *, axes): # TODO: Avals with names rule: remove all axes from src, insert those from idx # The order is important, because it is ok to re-insert one of the deleted axes! shape = list(src.shape) for axis in sorted((a for a in axes if isinstance(a, int)), reverse=True): ...
def _pgather_abstract_eval(src, idx, *, axes): # TODO: Avals with names rule: remove all axes from src, insert those from idx # The order is important, because it is ok to re-insert one of the deleted axes!
shape = list(src.shape) for axis in sorted((a for a in axes if isinstance(a, int)), reverse=True): del shape[axis] shape = idx.shape + tuple(shape) return ShapedArray(shape, src.dtype)
slice_sizes=tuple(slice_sizes)) def _pgather_abstract_eval(src, idx, *, axes): # TODO: Avals with names rule: remove all axes from src, insert those from idx # The order is important, because it is ok to re-insert one of the deleted axes!
64
64
109
57
7
rsepassi/jax
jax/_src/lax/parallel.py
Python
_pgather_abstract_eval
_pgather_abstract_eval
1,482
1,489
1,482
1,484
db38d804978f56556b0c7a113a2e0306101e8a3b
bigcode/the-stack
train
3c69cdb6fe73ae3d7173dbd4
train
function
def _ppermute_transpose_rule(t, x, perm, axis_name): srcs, dsts = unzip2(perm) inverse_perm = list(zip(dsts, srcs)) return [ppermute(t, axis_name=axis_name, perm=inverse_perm)]
def _ppermute_transpose_rule(t, x, perm, axis_name):
srcs, dsts = unzip2(perm) inverse_perm = list(zip(dsts, srcs)) return [ppermute(t, axis_name=axis_name, perm=inverse_perm)]
grp in replica_groups: grp = list(sorted(grp)) full_perm.extend((grp[src], grp[dst]) for src, dst in perm) return [xops.CollectivePermute(x, full_perm)] def _ppermute_transpose_rule(t, x, perm, axis_name):
64
64
60
17
47
rsepassi/jax
jax/_src/lax/parallel.py
Python
_ppermute_transpose_rule
_ppermute_transpose_rule
780
783
780
780
3b8e984d5cbded52e60da4f8507483cef0116e05
bigcode/the-stack
train
371e62183576ddac5f0690b3
train
function
def _psum_transpose_rule(cts, *args, axes, axis_index_groups): named_axes, pos_axes = axes_partition = [], [] for axis in axes: axes_partition[isinstance(axis, int)].append(axis) if pos_axes: def broadcast_positional(ct, arg): assert ad.is_undefined_primal(arg) if type(ct) is ad.Zero: return ...
def _psum_transpose_rule(cts, *args, axes, axis_index_groups):
named_axes, pos_axes = axes_partition = [], [] for axis in axes: axes_partition[isinstance(axis, int)].append(axis) if pos_axes: def broadcast_positional(ct, arg): assert ad.is_undefined_primal(arg) if type(ct) is ad.Zero: return ad.Zero(arg.aval) return lax._reduce_sum_transpose_rule(c...
(xops.Real(x)), all_reduce(xops.Imag(x))) if dtypes.issubdtype(c.get_shape(x).numpy_dtype(), np.complexfloating) else all_reduce(x) for x in args] return outs def _psum_transpose_rule(cts, *args, axes, axis_index_groups):
67
67
225
18
48
rsepassi/jax
jax/_src/lax/parallel.py
Python
_psum_transpose_rule
_psum_transpose_rule
682
699
682
682
8552ee64f5194864656ffeb9d60b57826f234145
bigcode/the-stack
train
c2f067a54112413dad2d3e3e
train
function
def _expand(dim, size, index, tiled, x): shape = list(x.shape) if tiled: tile_size = shape[dim] shape[dim] *= size out = lax.full(shape, lax._const(x, 0)) return slicing.dynamic_update_slice_in_dim(out, x, index * tile_size, dim) else: shape.insert(dim, size) out = lax.full(shape, lax._con...
def _expand(dim, size, index, tiled, x):
shape = list(x.shape) if tiled: tile_size = shape[dim] shape[dim] *= size out = lax.full(shape, lax._const(x, 0)) return slicing.dynamic_update_slice_in_dim(out, x, index * tile_size, dim) else: shape.insert(dim, size) out = lax.full(shape, lax._const(x, 0)) return slicing.dynamic_upda...
= partial(all_gather_p.bind, all_gather_dimension=axis, axis_name=axis_name, axis_index_groups=axis_index_groups, axis_size=axis_size, tiled=tiled) return tree_util.tree_map(bind, x) def _expand(dim, size, index, tiled, x):
64
64
115
13
51
rsepassi/jax
jax/_src/lax/parallel.py
Python
_expand
_expand
1,046
1,056
1,046
1,046
664783faf5273d4ff84b3ee4c11cf4a1a8b46417
bigcode/the-stack
train
635a3f238e4d4daf23c2765b
train
function
def _all_to_all_batched_collective(axis_size, frame_name, _, vals_in, dims_in, axis_name, split_axis, concat_axis, axis_index_groups): if axis_index_groups is not None: raise NotImplementedError("Please open a feature request!") x, = vals_in ...
def _all_to_all_batched_collective(axis_size, frame_name, _, vals_in, dims_in, axis_name, split_axis, concat_axis, axis_index_groups):
if axis_index_groups is not None: raise NotImplementedError("Please open a feature request!") x, = vals_in d, = dims_in if d is batching.not_mapped: # TODO(sharadmv,apaszke): Remove this broadcast that comes from # all_gather_transpose and instead avoid using all_to_all in # all_gather_transpose...
_all_to_all_transpose_rule(cts, x, axis_name, split_axis, concat_axis, axis_index_groups): return (all_to_all( cts, axis_name=axis_name, split_axis=concat_axis, concat_axis=split_axis, axis_index_groups=axis_index_groups),) def _all_to_all_batcher(vals_in, dims_in, *, axis_name, split_...
205
205
685
37
167
rsepassi/jax
jax/_src/lax/parallel.py
Python
_all_to_all_batched_collective
_all_to_all_batched_collective
900
954
900
902
319db24bdb6a1d95ce3232b067817248a4442fb1
bigcode/the-stack
train
d67548d73b7f3b131ce3f7b4
train
function
def convolution_nd(x, W, b=None, stride=1, pad=0, use_cudnn=True, cover_all=False): """N-dimensional convolution function. This is an implementation of N-dimensional convolution which is generalized two-dimensional convolution in ConvNets. It takes three variables: the input ``x``, t...
def convolution_nd(x, W, b=None, stride=1, pad=0, use_cudnn=True, cover_all=False):
"""N-dimensional convolution function. This is an implementation of N-dimensional convolution which is generalized two-dimensional convolution in ConvNets. It takes three variables: the input ``x``, the filter weight ``W`` and the bias vector ``b``. Notation: here is a notation for dimensionalitie...
0,) + tuple(moves.range(2, self.ndim + 2)) gb = gy.sum(axis=axis) return gx, gW, gb def backward(self, inputs, grad_outputs): x, W = inputs[:2] b = inputs[2] if len(inputs) == 3 else None gy = grad_outputs[0] # (n, c_O, out_1, out_2, ..., out_N) xp = cuda...
215
215
717
29
186
asrlabncku/RAP
chainer/functions/connection/convolution_nd.py
Python
convolution_nd
convolution_nd
291
351
291
292
89bd8493a352830977aded5ea0e172ec08ecb5eb
bigcode/the-stack
train
bdbe944fbcd789ea166fad43
train
class
class ConvolutionND(function.Function): def __init__(self, ndim, stride=1, pad=0, use_cudnn=True, cover_all=False): self.ndim = ndim self.stride = conv_nd.as_tuple(stride, ndim) self.pad = conv_nd.as_tuple(pad, ndim) self.use_cudnn = use_cudnn self.cover_all = cover_all ...
class ConvolutionND(function.Function):
def __init__(self, ndim, stride=1, pad=0, use_cudnn=True, cover_all=False): self.ndim = ndim self.stride = conv_nd.as_tuple(stride, ndim) self.pad = conv_nd.as_tuple(pad, ndim) self.use_cudnn = use_cudnn self.cover_all = cover_all def check_type_forward(self, in_types): ...
import numpy from six import moves from chainer import cuda from chainer import function from chainer.functions.connection import convolution_2d from chainer.utils import conv from chainer.utils import conv_nd from chainer.utils import type_check if cuda.cudnn_enabled: cudnn = cuda.cudnn libcudnn = cuda.cud...
213
256
2,661
7
205
asrlabncku/RAP
chainer/functions/connection/convolution_nd.py
Python
ConvolutionND
ConvolutionND
28
288
28
29
e6ade1cd844cd98be78fca01c9d0b352f037f048
bigcode/the-stack
train
a70d1fc9a04379ad6f4f2e8a
train
class
class DataShareManagementClient(object): """Creates a Microsoft.DataShare management client. :ivar accounts: AccountsOperations operations :vartype accounts: azure.mgmt.datashare.operations.AccountsOperations :ivar consumer_invitations: ConsumerInvitationsOperations operations :vartype consumer_inv...
class DataShareManagementClient(object):
"""Creates a Microsoft.DataShare management client. :ivar accounts: AccountsOperations operations :vartype accounts: azure.mgmt.datashare.operations.AccountsOperations :ivar consumer_invitations: ConsumerInvitationsOperations operations :vartype consumer_invitations: azure.mgmt.datashare.operations...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
255
256
1,039
7
247
rsdoherty/azure-sdk-for-python
sdk/datashare/azure-mgmt-datashare/azure/mgmt/datashare/_data_share_management_client.py
Python
DataShareManagementClient
DataShareManagementClient
36
125
36
36
03618e21516c37efe603263d7bf90f30b2fe18f9
bigcode/the-stack
train
3eead81566cfea9c30c0a918
train
class
class ProcessRpcClientService(IScoped): @inject def __init__(self, process_rpc_client_config: ProcessRpcClientConfig, ): self.process_rpc_client_config = process_rpc_client_config def connect_rpc(self): conn = rpyc.connect(self.process_rpc_client_config.ho...
class ProcessRpcClientService(IScoped): @inject
def __init__(self, process_rpc_client_config: ProcessRpcClientConfig, ): self.process_rpc_client_config = process_rpc_client_config def connect_rpc(self): conn = rpyc.connect(self.process_rpc_client_config.host, self.process_rpc_client_config.port) conn...
import rpyc from injector import inject from infrastructor.dependency.scopes import IScoped from models.configs.ProcessRpcClientConfig import ProcessRpcClientConfig class ProcessRpcClientService(IScoped): @inject
48
64
168
13
34
jedicontributors/pythondataintegrator
src/api/rpc/ProcessRpcClientService.py
Python
ProcessRpcClientService
ProcessRpcClientService
7
25
7
9
bd5675d2b066a5121234a8bd60b8aff45fd87548
bigcode/the-stack
train
3c9a2887f0df2fd3b52c7e57
train
class
class ItemTypeEnum(StrEnum): APP = "APP" COINS = "COINS" INGAMEITEM = "INGAMEITEM" BUNDLE = "BUNDLE" CODE = "CODE" SUBSCRIPTION = "SUBSCRIPTION" SEASON = "SEASON"
class ItemTypeEnum(StrEnum):
APP = "APP" COINS = "COINS" INGAMEITEM = "INGAMEITEM" BUNDLE = "BUNDLE" CODE = "CODE" SUBSCRIPTION = "SUBSCRIPTION" SEASON = "SEASON"
List, Optional, Tuple, Union from ....core import Model from ....core import StrEnum from ..models.image import Image from ..models.reward_currency import RewardCurrency class TypeEnum(StrEnum): ITEM = "ITEM" CURRENCY = "CURRENCY" class ItemTypeEnum(StrEnum):
64
64
63
7
57
AccelByte/accelbyte-python-sdk
accelbyte_py_sdk/api/seasonpass/models/reward_info.py
Python
ItemTypeEnum
ItemTypeEnum
40
47
40
40
d1b824ff8177437fcb95e458b57b609ab136e916
bigcode/the-stack
train
3b50b79bfb9fdf1747a48374
train
class
class RewardInfo(Model): """A DTO object for reward info. (RewardInfo) Properties: code: (code) REQUIRED str namespace: (namespace) REQUIRED str season_id: (seasonId) REQUIRED str type_: (type) REQUIRED Union[str, TypeEnum] currency: (currency) OPTIONAL RewardCurrenc...
class RewardInfo(Model):
"""A DTO object for reward info. (RewardInfo) Properties: code: (code) REQUIRED str namespace: (namespace) REQUIRED str season_id: (seasonId) REQUIRED str type_: (type) REQUIRED Union[str, TypeEnum] currency: (currency) OPTIONAL RewardCurrency image: (image)...
: disable=line-too-long # pylint: disable=missing-function-docstring # pylint: disable=missing-module-docstring # pylint: disable=too-many-arguments # pylint: disable=too-many-branches # pylint: disable=too-many-instance-attributes # pylint: disable=too-many-lines # pylint: disable=too-many-locals # pylint: disable=too...
256
256
2,290
5
251
AccelByte/accelbyte-python-sdk
accelbyte_py_sdk/api/seasonpass/models/reward_info.py
Python
RewardInfo
RewardInfo
50
339
50
50
5945c4ff6c57fd44eed4b01ff458a4188ec75e80
bigcode/the-stack
train
f345919566e9e3aeefe8f41f
train
class
class TypeEnum(StrEnum): ITEM = "ITEM" CURRENCY = "CURRENCY"
class TypeEnum(StrEnum):
ITEM = "ITEM" CURRENCY = "CURRENCY"
pylint: disable=unused-import from __future__ import annotations from typing import Any, Dict, List, Optional, Tuple, Union from ....core import Model from ....core import StrEnum from ..models.image import Image from ..models.reward_currency import RewardCurrency class TypeEnum(StrEnum):
64
64
20
6
57
AccelByte/accelbyte-python-sdk
accelbyte_py_sdk/api/seasonpass/models/reward_info.py
Python
TypeEnum
TypeEnum
35
37
35
35
29452782d6ec1653f0b195d6a58fccd16010bdc0
bigcode/the-stack
train
02b4226b2e83cebe0f1d6adc
train
class
class UserProfileApplication(ExtApplication): """ main.userprofile application """ title = _("User Profile") implied_permissions = {"launch": ["main:timepattern:lookup"]} @view(url="^$", method=["GET"], access=PermitLogged(), api=True) def api_get(self, request): user = request.use...
class UserProfileApplication(ExtApplication):
""" main.userprofile application """ title = _("User Profile") implied_permissions = {"launch": ["main:timepattern:lookup"]} @view(url="^$", method=["GET"], access=PermitLogged(), api=True) def api_get(self, request): user = request.user language = user.preferred_language ...
application # --------------------------------------------------------------------- # Copyright (C) 2007-2019 The NOC Project # See LICENSE for details # --------------------------------------------------------------------- # NOC modules from noc.lib.app.extapplication import ExtApplication, view, PermitLogged from n...
128
129
432
8
120
xUndero/noc
services/web/apps/main/userprofile/views.py
Python
UserProfileApplication
UserProfileApplication
19
82
19
19
c9806193d94f1b0c3bd735666c113e77a620c491
bigcode/the-stack
train
e9d79cb1daf733c7ba1ce09d
train
class
class TestStepAndCost: """Tests for the step_and_cost method""" def test_qnode_cost(self, tol): """Test that the cost is correctly returned when using a QNode as the cost function""" dev = qml.device("default.qubit", wires=1, shots=10) @qml.qnode(dev) def circu...
class TestStepAndCost:
"""Tests for the step_and_cost method""" def test_qnode_cost(self, tol): """Test that the cost is correctly returned when using a QNode as the cost function""" dev = qml.device("default.qubit", wires=1, shots=10) @qml.qnode(dev) def circuit(x): qml....
_grad=True) initial_loss = cost(params) min_shots = 10 loss = initial_loss opt = qml.ShotAdaptiveOptimizer(min_shots=10) for i in range(100): params = opt.step(cost, params) loss = cost(params) assert loss < initial_loss asse...
117
117
392
6
110
therooler/pennylane
tests/optimize/test_optimize_shot_adapative.py
Python
TestStepAndCost
TestStepAndCost
564
604
564
564
9d3e1cab3e4c2bc9a1d39fb9023d3d3b55fd4d0e
bigcode/the-stack
train
2c385d5f8116b2b3e69a6c63
train
class
class TestWeightedRandomSampling: """Tests for weighted random Hamiltonian term sampling""" def test_wrs_expval_cost(self, mocker): """Checks that cost functions that are expval costs can make use of weighted random sampling""" coeffs = [0.2, 0.1] dev = qml.device("defaul...
class TestWeightedRandomSampling:
"""Tests for weighted random Hamiltonian term sampling""" def test_wrs_expval_cost(self, mocker): """Checks that cost functions that are expval costs can make use of weighted random sampling""" coeffs = [0.2, 0.1] dev = qml.device("default.qubit", wires=2, shots=100) ...
np.var(single_shot_grads[0][:8, 0, 0], ddof=1)) # check other elements of arg 0 assert np.allclose(grad[0][0, 1], np.mean(single_shot_grads[0][:5, 0, 1])) assert np.allclose(grad_variance[0][0, 1], np.var(single_shot_grads[0][:5, 0, 1], ddof=1)) # check zeroth element of arg 1 ...
255
256
1,293
6
249
therooler/pennylane
tests/optimize/test_optimize_shot_adapative.py
Python
TestWeightedRandomSampling
TestWeightedRandomSampling
401
497
401
401
45f3a384b277d4d48e2f8478e28ac57c8d1836e1
bigcode/the-stack
train
b465c631befe993dbc0c7164
train
class
class TestExceptions: """Test exceptions are raised for incorrect usage""" def test_analytic_device_error(self): """Test that an exception is raised if an analytic device is used""" H = qml.Hamiltonian([0.3, 0.1], [qml.PauliX(0), qml.PauliZ(0)]) dev = qml.device("default.qubit", w...
class TestExceptions:
"""Test exceptions are raised for incorrect usage""" def test_analytic_device_error(self): """Test that an exception is raised if an analytic device is used""" H = qml.Hamiltonian([0.3, 0.1], [qml.PauliX(0), qml.PauliZ(0)]) dev = qml.device("default.qubit", wires=1, shots=None) ...
# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicabl...
170
227
758
4
165
therooler/pennylane
tests/optimize/test_optimize_shot_adapative.py
Python
TestExceptions
TestExceptions
22
100
22
22
38d22dd5e1a42d2288fdc8c12bc3bc9498d87588
bigcode/the-stack
train
a570007f4b8ad0e29e51a240
train
class
class TestSingleShotGradientIntegration: """Integration tests to ensure that the single shot gradient is correctly computed for a variety of argument types.""" dev = qml.device("default.qubit", wires=1, shots=100) H = qml.Hamiltonian([1.0], [qml.PauliZ(0)]) def ansatz(x, **kwargs): ...
class TestSingleShotGradientIntegration:
"""Integration tests to ensure that the single shot gradient is correctly computed for a variety of argument types.""" dev = qml.device("default.qubit", wires=1, shots=100) H = qml.Hamiltonian([1.0], [qml.PauliZ(0)]) def ansatz(x, **kwargs): qml.RX(x, wires=0) expval_cost = q...
pytest.raises(ValueError, match=f"The learning rate must be less than {2 / 1}"): opt.step(expval_cost.qnodes[0], np.array(0.5, requires_grad=True)) def test_unknown_objective_function(self): """Test that an exception is raised if an unknown objective function is passed""" dev = qm...
256
256
3,609
7
249
therooler/pennylane
tests/optimize/test_optimize_shot_adapative.py
Python
TestSingleShotGradientIntegration
TestSingleShotGradientIntegration
103
398
103
103
698bede47e54afe3ce268923d1bae47c4d058fe5
bigcode/the-stack
train
adf60bca89b1f0ae4b74ab43
train
class
class TestOptimization: """Integration test to ensure that the optimizer minimizes simple examples""" def test_multi_qubit_rotation(self): """Test that multiple qubit rotation can be optimized""" dev = qml.device("default.qubit", wires=2, shots=100) @qml.qnode(dev) ...
class TestOptimization:
"""Integration test to ensure that the optimizer minimizes simple examples""" def test_multi_qubit_rotation(self): """Test that multiple qubit rotation can be optimized""" dev = qml.device("default.qubit", wires=2, shots=100) @qml.qnode(dev) def circuit(x): ...
Layers, H, dev) weights = np.random.random(qml.templates.StronglyEntanglingLayers.shape(3, 2)) opt = qml.ShotAdaptiveOptimizer(min_shots=10) spy = mocker.spy(qml, "jacobian") spy_dims = mocker.spy(np, "expand_dims") mocker.patch( "scipy.stats._multivariate.m...
180
180
601
4
176
therooler/pennylane
tests/optimize/test_optimize_shot_adapative.py
Python
TestOptimization
TestOptimization
500
561
500
500
36458638bc2f2fea67a9a5d3304b447a3218d9f2
bigcode/the-stack
train
18b72e8bf93c4b1941ecd986
train
function
@patch('praw.Reddit', autospec=True) def test_initialize_experiment(mock_reddit): r = mock_reddit.return_value patch('praw.') experiment_name_to_controller = { #"sticky_comment_0": AMAStickyCommentExperimentController, #"sticky_comment_frontpage_test": FrontPageStickyCommentExperimentContro...
@patch('praw.Reddit', autospec=True) def test_initialize_experiment(mock_reddit):
r = mock_reddit.return_value patch('praw.') experiment_name_to_controller = { #"sticky_comment_0": AMAStickyCommentExperimentController, #"sticky_comment_frontpage_test": FrontPageStickyCommentExperimentController, "messaging_experiment_test": MessagingExperimentController }...
delete() db_session.query(SubredditPage).delete() db_session.query(Subreddit).delete() db_session.query(Post).delete() db_session.query(User).delete() db_session.query(Comment).delete() db_session.query(Experiment).delete() db_session.query(ExperimentThing).delete() db_session.query(Expe...
141
141
471
21
120
notconfusing/CivilServant
tests/test_experiment.py
Python
test_initialize_experiment
test_initialize_experiment
54
97
54
55
bea0be70a2f160ec4ac3df32686ebdcd77d44a13
bigcode/the-stack
train
59bfb7a1e46432ff65149bff
train
function
@patch('praw.Reddit', autospec=True) @patch('praw.objects.Subreddit', autospec=True) def test_identify_condition(mock_subreddit, mock_reddit): r = mock_reddit.return_value experiment_name_to_controller = { "sticky_comment_0": AMAStickyCommentExperimentController, "sticky_comment_frontpage_test"...
@patch('praw.Reddit', autospec=True) @patch('praw.objects.Subreddit', autospec=True) def test_identify_condition(mock_subreddit, mock_reddit):
r = mock_reddit.return_value experiment_name_to_controller = { "sticky_comment_0": AMAStickyCommentExperimentController, "sticky_comment_frontpage_test": FrontPageStickyCommentExperimentController#, #"mod_user_test": ModUserExperimentController } sub_data = [] with open("{s...
UTC").localize(experiment.end_time) == parser.parse(experiment_config['end_time'])) settings = json.loads(experiment.settings_json) for key in ['subreddit', 'subreddit_id', 'shadow_subreddit', 'shadow_subreddit_id', 'username', 'max_eligibility_age', 'min_eligibility_age...
252
252
841
38
214
notconfusing/CivilServant
tests/test_experiment.py
Python
test_identify_condition
test_identify_condition
99
179
99
101
8500315b81f295f2466ff9b25af9cbecb2b607a2
bigcode/the-stack
train
8524af721d4c3b9b1e06e34e
train
function
def clear_all_tables(): db_session.query(FrontPage).delete() db_session.query(SubredditPage).delete() db_session.query(Subreddit).delete() db_session.query(Post).delete() db_session.query(User).delete() db_session.query(Comment).delete() db_session.query(Experiment).delete() db_session.q...
def clear_all_tables():
db_session.query(FrontPage).delete() db_session.query(SubredditPage).delete() db_session.query(Subreddit).delete() db_session.query(Post).delete() db_session.query(User).delete() db_session.query(Comment).delete() db_session.query(Experiment).delete() db_session.query(ExperimentThing).de...
CLASSES TO TEST from app.models import * import app.cs_logger db_session = DbEngine(os.path.join(TEST_DIR, "../", "config") + "/{env}.json".format(env=ENV)).new_session() log = app.cs_logger.get_logger(ENV, BASE_DIR) def clear_all_tables():
64
64
113
5
59
notconfusing/CivilServant
tests/test_experiment.py
Python
clear_all_tables
clear_all_tables
34
46
34
34
8a2972ca3e968e0fa40e95ae1d40224bab83631a
bigcode/the-stack
train
2f73c2d89e52d4f38fe1f835
train
function
def teardown_function(function): clear_all_tables()
def teardown_function(function):
clear_all_tables()
).delete() db_session.query(ExperimentThing).delete() db_session.query(ExperimentAction).delete() db_session.query(ExperimentThingSnapshot).delete() db_session.query(EventHook).delete() db_session.commit() def setup_function(function): clear_all_tables() def teardown_function(function):
64
64
10
5
59
notconfusing/CivilServant
tests/test_experiment.py
Python
teardown_function
teardown_function
51
52
51
51
2e0392bb0896b7f981675bfa0b327227d07742dd
bigcode/the-stack
train
6ce881c07e2ad7fa86c440cb
train
function
def setup_function(function): clear_all_tables()
def setup_function(function):
clear_all_tables()
(Comment).delete() db_session.query(Experiment).delete() db_session.query(ExperimentThing).delete() db_session.query(ExperimentAction).delete() db_session.query(ExperimentThingSnapshot).delete() db_session.query(EventHook).delete() db_session.commit() def setup_function(function):
63
64
10
5
58
notconfusing/CivilServant
tests/test_experiment.py
Python
setup_function
setup_function
48
49
48
48
3d538173548768c348d96c4ad57c06c3499b2f82
bigcode/the-stack
train
947b000421a9c9033c70c2ec
train
class
class Extension(ext.Extension): dist_name = 'Mopidy-libNotify' ext_name = 'libnotify' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = sup...
class Extension(ext.Extension):
dist_name = 'Mopidy-libNotify' ext_name = 'libnotify' version = __version__ def get_default_config(self): conf_file = os.path.join(os.path.dirname(__file__), 'ext.conf') return config.read(conf_file) def get_config_schema(self): schema = super(Extension, self).get_config_sc...
from __future__ import unicode_literals import os from mopidy import config, ext __version__ = '0.2.0' class Extension(ext.Extension):
35
64
131
5
30
Mellich/mopidy-libnotify
mopidy_libnotify/__init__.py
Python
Extension
Extension
12
31
12
13
0170485f4a241f950b804993c7b4fcce99fe591e
bigcode/the-stack
train
fecbe4feeb311c89919fdea0
train
function
def print_phase_header(message): global COUNTER; print ("\n[" + str("%02d" % int(COUNTER)) + "] >>> " + message) COUNTER += 1;
def print_phase_header(message):
global COUNTER; print ("\n[" + str("%02d" % int(COUNTER)) + "] >>> " + message) COUNTER += 1;
ASSET_FINAL_NAME = "Python Sample-Face Detection" PROCESSOR_NAME = "Azure Media Redactor" MODE = "Combined" FACE_REDACTION_CONFIG = "redaction_config.json" # Just a simple wrapper function to print the title of each of our phases to the console... def print_phase_header(message):
64
64
43
6
58
gbowerman/azurerm
examples/media_services/analytics/face_redaction/Face_Redaction.py
Python
print_phase_header
print_phase_header
82
85
82
82
00767c6c3a0878036b4194223f7b9f51f0dbb4bc
bigcode/the-stack
train
55c5abcb6e30eaf9d94f8faa
train
function
def print_phase_message(message): time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print (str(time_stamp) + ": " + message)
def print_phase_message(message):
time_stamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print (str(time_stamp) + ": " + message)
... def print_phase_header(message): global COUNTER; print ("\n[" + str("%02d" % int(COUNTER)) + "] >>> " + message) COUNTER += 1; # This wrapper function prints our messages to the console with a timestamp... def print_phase_message(message):
64
64
42
6
58
gbowerman/azurerm
examples/media_services/analytics/face_redaction/Face_Redaction.py
Python
print_phase_message
print_phase_message
88
90
88
88
134dcf88bfd2fbc495a033df2930f313d4753f6e
bigcode/the-stack
train
d53fc8ced1989c7be030bee5
train
function
def uploadCallback(current, total): if (current != None): print_phase_message('{0:2,f}/{1:2,.0f} MB'.format(current,total/1024/1024))
def uploadCallback(current, total):
if (current != None): print_phase_message('{0:2,f}/{1:2,.0f} MB'.format(current,total/1024/1024))
+ str(response.content)) ### Use the Azure Blob Blob Servic library from the Azure Storage SDK. block_blob_service = BlockBlobService(account_name=sto_account_name, sas_token=saslocator_cac[1:]) ### Define a callback method to show progress of large uploads def uploadCallback(current, total):
64
64
42
7
56
gbowerman/azurerm
examples/media_services/analytics/face_redaction/Face_Redaction.py
Python
uploadCallback
uploadCallback
168
170
168
168
bb76fd084718b61154101a37f3d337354fb0ba4a
bigcode/the-stack
train
77e421f207c90c375c375267
train
function
def _base64(string): return base64.standard_b64encode(string.encode()).decode()
def _base64(string):
return base64.standard_b64encode(string.encode()).decode()
ST_EXPIRY_TIMEDELTA = 2 # should be more than kube_config.EXPIRY_SKEW_PREVENTION_DELAY FUTURE_EXPIRY_TIMEDELTA = 60 NON_EXISTING_FILE = "zz_non_existing_file_472398324" def _base64(string):
64
64
19
6
58
MridulS/python-base
config/kube_config_test.py
Python
_base64
_base64
53
54
53
53
557af48e903b8f139796ac5e04cab69e19d1ca74
bigcode/the-stack
train
bd896261bc9420f061d20c99
train
class
class TestFileOrData(BaseTestCase): @staticmethod def get_file_content(filename): with open(filename) as f: return f.read() def test_file_given_file(self): temp_filename = _create_temp_file_with_content(TEST_DATA) obj = {TEST_FILE_KEY: temp_filename} t = FileOrD...
class TestFileOrData(BaseTestCase): @staticmethod
def get_file_content(filename): with open(filename) as f: return f.read() def test_file_given_file(self): temp_filename = _create_temp_file_with_content(TEST_DATA) obj = {TEST_FILE_KEY: temp_filename} t = FileOrData(obj=obj, file_key_name=TEST_FILE_KEY) self....
added_b64encode(TEST_CLIENT_CERT) ]) TEST_OIDC_INVALID_PADDING_LENGTH = ".".join([ _urlsafe_unpadded_b64encode(TEST_OIDC_TOKEN), "aaaaa", _urlsafe_unpadded_b64encode(TEST_CLIENT_CERT) ]) TEST_OIDC_CA = _base64(TEST_CERTIFICATE_AUTH) TEST_AZURE_LOGIN = TEST_OIDC_LOGIN TEST_AZURE_TOKEN = "test-azure-token" ...
256
256
997
13
243
MridulS/python-base
config/kube_config_test.py
Python
TestFileOrData
TestFileOrData
164
267
164
166
2db8c5cfb5ae2586cbf26851fc4a8a381f5604c8
bigcode/the-stack
train
14c5c2d58ddbd8c9e97855bf
train
class
class TestKubeConfigLoader(BaseTestCase): TEST_KUBE_CONFIG = { "current-context": "no_user", "contexts": [ { "name": "no_user", "context": { "cluster": "default" } }, { "name": "si...
class TestKubeConfigLoader(BaseTestCase):
TEST_KUBE_CONFIG = { "current-context": "no_user", "contexts": [ { "name": "no_user", "context": { "cluster": "default" } }, { "name": "simple_token", "context": { ...
if k in self.FILE_KEYS: if v and other.__dict__[k]: try: with open(v) as f1, open(other.__dict__[k]) as f2: if f1.read() != f2.read(): return except IOError: ...
256
256
7,870
10
245
MridulS/python-base
config/kube_config_test.py
Python
TestKubeConfigLoader
TestKubeConfigLoader
396
1,449
396
396
29948f5a2be285ee0edd550004b3ab584d74a7de
bigcode/the-stack
train
4690bfa3365f8be233b9e0c8
train
function
def _format_expiry_datetime(dt): return dt.strftime(EXPIRY_DATETIME_FORMAT)
def _format_expiry_datetime(dt):
return dt.strftime(EXPIRY_DATETIME_FORMAT)
_non_existing_file_472398324" def _base64(string): return base64.standard_b64encode(string.encode()).decode() def _urlsafe_unpadded_b64encode(string): return base64.urlsafe_b64encode(string.encode()).decode().rstrip('=') def _format_expiry_datetime(dt):
64
64
20
8
57
MridulS/python-base
config/kube_config_test.py
Python
_format_expiry_datetime
_format_expiry_datetime
61
62
61
61
70ce9f81b4847e9d9cde314cfa5f25d114fa0019
bigcode/the-stack
train
1a722e9e6779f6c2a9c1880a
train
function
def _raise_exception(st): raise Exception(st)
def _raise_exception(st):
raise Exception(st)
expired_gcp_conf = (item for item in loader._config.value.get("users") if item.get("name") == active_context) return next(expired_gcp_conf).get("user").get("auth-provider") \ .get("config").get("expiry") def _raise_exception(st):
64
64
11
6
58
MridulS/python-base
config/kube_config_test.py
Python
_raise_exception
_raise_exception
72
73
72
72
77e1dcea713cbd9c3599b84f227677add9b1abdb
bigcode/the-stack
train
de7e7979939b1f94539c2eeb
train
class
class TestKubeConfigMerger(BaseTestCase): TEST_KUBE_CONFIG_PART1 = { "current-context": "no_user", "contexts": [ { "name": "no_user", "context": { "cluster": "default" } }, ], "clusters": [ ...
class TestKubeConfigMerger(BaseTestCase):
TEST_KUBE_CONFIG_PART1 = { "current-context": "no_user", "contexts": [ { "name": "no_user", "context": { "cluster": "default" } }, ], "clusters": [ { "name": "defau...
None(actual._config_persister) class TestKubernetesClientConfiguration(BaseTestCase): # Verifies properties of kubernetes.client.Configuration. # These tests guard against changes to the upstream configuration class, # since GCP authorization overrides get_api_key_with_prefix to refresh its # token re...
255
256
1,403
11
244
MridulS/python-base
config/kube_config_test.py
Python
TestKubeConfigMerger
TestKubeConfigMerger
1,482
1,702
1,482
1,482
3a6376f6ff90d6a6be5719965d8369525227af34
bigcode/the-stack
train
3570475e8a9d275c71a9f0bf
train
class
class BaseTestCase(unittest.TestCase): def setUp(self): self._temp_files = [] def tearDown(self): for f in self._temp_files: os.remove(f) def _create_temp_file(self, content=""): handler, name = tempfile.mkstemp() self._temp_files.append(name) os.write(...
class BaseTestCase(unittest.TestCase):
def setUp(self): self._temp_files = [] def tearDown(self): for f in self._temp_files: os.remove(f) def _create_temp_file(self, content=""): handler, name = tempfile.mkstemp() self._temp_files.append(name) os.write(handler, str.encode(content)) os...
_CERT) ]) TEST_OIDC_CA = _base64(TEST_CERTIFICATE_AUTH) TEST_AZURE_LOGIN = TEST_OIDC_LOGIN TEST_AZURE_TOKEN = "test-azure-token" TEST_AZURE_TOKEN_FULL = "Bearer " + TEST_AZURE_TOKEN class BaseTestCase(unittest.TestCase):
64
64
135
8
55
MridulS/python-base
config/kube_config_test.py
Python
BaseTestCase
BaseTestCase
142
161
142
143
be441b6c6d45d9a7beebedc7e8acce8cf9fb3601
bigcode/the-stack
train
b36fec31c23e3f60ec4baf2d
train
class
class FakeConfig: FILE_KEYS = ["ssl_ca_cert", "key_file", "cert_file"] def __init__(self, token=None, **kwargs): self.api_key = {} if token: self.api_key['authorization'] = token self.__dict__.update(kwargs) def __eq__(self, other): if len(self.__dict__) != le...
class FakeConfig:
FILE_KEYS = ["ssl_ca_cert", "key_file", "cert_file"] def __init__(self, token=None, **kwargs): self.api_key = {} if token: self.api_key['authorization'] = token self.__dict__.update(kwargs) def __eq__(self, other): if len(self.__dict__) != len(other.__dict__): ...
_get_with_name_on_name_does_not_exists(self): self.expect_exception( lambda: self.node['with_names'].get_with_name('no-name'), "Expected object with name no-name in test_obj/with_names list") def test_get_with_name_on_duplicate_name(self): self.expect_exception( ...
107
107
359
4
103
MridulS/python-base
config/kube_config_test.py
Python
FakeConfig
FakeConfig
346
393
346
347
2bedc209c2425fdcceca1430c339e6d850f359a2
bigcode/the-stack
train
40c2c9d7a6966de1e4fc7f66
train
class
class TestConfigNode(BaseTestCase): test_obj = {"key1": "test", "key2": ["a", "b", "c"], "key3": {"inner_key": "inner_value"}, "with_names": [{"name": "test_name", "value": "test_value"}, {"name": "test_name2", "value": ...
class TestConfigNode(BaseTestCase):
test_obj = {"key1": "test", "key2": ["a", "b", "c"], "key3": {"inner_key": "inner_value"}, "with_names": [{"name": "test_name", "value": "test_value"}, {"name": "test_name2", "value": {"key1", "test"}}, ...
test_file_given_data_bytes(self): obj = {TEST_DATA_KEY: TEST_DATA_BASE64.encode()} t = FileOrData(obj=obj, file_key_name=TEST_FILE_KEY, data_key_name=TEST_DATA_KEY) self.assertEqual(TEST_DATA, self.get_file_content(t.as_file())) def test_file_given_data_bytes_no_base...
232
232
775
8
224
MridulS/python-base
config/kube_config_test.py
Python
TestConfigNode
TestConfigNode
270
343
270
271
d4bd9753f97394e9ccfb6fe429f80b4c00511a7d
bigcode/the-stack
train
a45ad64c2415f7e862ffd292
train
function
def _urlsafe_unpadded_b64encode(string): return base64.urlsafe_b64encode(string.encode()).decode().rstrip('=')
def _urlsafe_unpadded_b64encode(string):
return base64.urlsafe_b64encode(string.encode()).decode().rstrip('=')
_PREVENTION_DELAY FUTURE_EXPIRY_TIMEDELTA = 60 NON_EXISTING_FILE = "zz_non_existing_file_472398324" def _base64(string): return base64.standard_b64encode(string.encode()).decode() def _urlsafe_unpadded_b64encode(string):
64
64
29
12
52
MridulS/python-base
config/kube_config_test.py
Python
_urlsafe_unpadded_b64encode
_urlsafe_unpadded_b64encode
57
58
57
57
ab68da1c5a1fc9a6a9fcd01d6752368fa00a09d8
bigcode/the-stack
train
092b6718103b7fdd287381c1
train
function
def _get_expiry(loader, active_context): expired_gcp_conf = (item for item in loader._config.value.get("users") if item.get("name") == active_context) return next(expired_gcp_conf).get("user").get("auth-provider") \ .get("config").get("expiry")
def _get_expiry(loader, active_context):
expired_gcp_conf = (item for item in loader._config.value.get("users") if item.get("name") == active_context) return next(expired_gcp_conf).get("user").get("auth-provider") \ .get("config").get("expiry")
(string.encode()).decode() def _urlsafe_unpadded_b64encode(string): return base64.urlsafe_b64encode(string.encode()).decode().rstrip('=') def _format_expiry_datetime(dt): return dt.strftime(EXPIRY_DATETIME_FORMAT) def _get_expiry(loader, active_context):
64
64
69
10
54
MridulS/python-base
config/kube_config_test.py
Python
_get_expiry
_get_expiry
65
69
65
65
b85431564e8e571df6a6f1d2f55deece721ff7b4
bigcode/the-stack
train
df8bd97f952bb876c3af0336
train
class
class TestKubernetesClientConfiguration(BaseTestCase): # Verifies properties of kubernetes.client.Configuration. # These tests guard against changes to the upstream configuration class, # since GCP authorization overrides get_api_key_with_prefix to refresh its # token regularly. def test_get_api_ke...
class TestKubernetesClientConfiguration(BaseTestCase): # Verifies properties of kubernetes.client.Configuration. # These tests guard against changes to the upstream configuration class, # since GCP authorization overrides get_api_key_with_prefix to refresh its # token regularly.
def test_get_api_key_with_prefix_exists(self): self.assertTrue(hasattr(Configuration, 'get_api_key_with_prefix')) def test_get_api_key_with_prefix_returns_token(self): expected_token = 'expected_token' config = Configuration() config.api_key['authorization'] = expected_token ...
_CONFIG) self.assertIsNone(actual._config_persister) class TestKubernetesClientConfiguration(BaseTestCase): # Verifies properties of kubernetes.client.Configuration. # These tests guard against changes to the upstream configuration class, # since GCP authorization overrides get_api_key_with_prefix t...
70
70
236
56
14
MridulS/python-base
config/kube_config_test.py
Python
TestKubernetesClientConfiguration
TestKubernetesClientConfiguration
1,452
1,479
1,452
1,457
758f377d672b3a027b2683991f9e2b418761456d
bigcode/the-stack
train
b0fee866439aaf810e6b61ed
train
function
def main(): logger.info('Starting the application') app = QApplication(sys.argv) while True: # Asking the user to specify which interface to work with try: iface, iface_kwargs, dsdl_directory = run_setup_window(get_app_icon(), args.dsdl) if not iface: ...
def main():
logger.info('Starting the application') app = QApplication(sys.argv) while True: # Asking the user to specify which interface to work with try: iface, iface_kwargs, dsdl_directory = run_setup_window(get_app_icon(), args.dsdl) if not iface: sys.exit(0)...
msg = 'Node spin error [%d of %d]: %r' % (self._successive_node_errors, self.MAX_SUCCESSIVE_NODE_ERRORS, ex) if self._successive_node_errors >= self.MAX_SUCCESSIVE_NODE_ERRORS: show_error('Node failure', 'Local UAVCAN node has generated too many erro...
174
174
581
3
171
akkawimo/gui_tool
uavcan_gui_tool/main.py
Python
main
main
566
636
566
566
fc4b988c987cc17530a6e93b3d82f4a1ee381ecc
bigcode/the-stack
train
8962e9e2203e68f9ff7e9dc2
train
class
class MainWindow(QMainWindow): MAX_SUCCESSIVE_NODE_ERRORS = 1000 # noinspection PyTypeChecker,PyCallByClass,PyUnresolvedReferences def __init__(self, node, iface_name): # Parent super(MainWindow, self).__init__() self.setWindowTitle('UAVCAN GUI Tool') self.setWindowIcon(get_...
class MainWindow(QMainWindow):
MAX_SUCCESSIVE_NODE_ERRORS = 1000 # noinspection PyTypeChecker,PyCallByClass,PyUnresolvedReferences def __init__(self, node, iface_name): # Parent super(MainWindow, self).__init__() self.setWindowTitle('UAVCAN GUI Tool') self.setWindowIcon(get_app_icon()) self._node...
, QMainWindow, QWidget, QVBoxLayout, QSplitter, QAction from PyQt5.QtGui import QKeySequence, QDesktopServices from PyQt5.QtCore import QTimer, Qt, QUrl from .version import __version__ from .setup_window import run_setup_window from .active_data_type_detector import ActiveDataTypeDetector from . import update_checker...
256
256
4,308
7
249
akkawimo/gui_tool
uavcan_gui_tool/main.py
Python
MainWindow
MainWindow
93
563
93
93
c16434c7c567de16154f6b2ab4885b32484ab087
bigcode/the-stack
train
9b51c8113853e08a1162d2c6
train
function
def execute(code): pos=x=y=0 direction=1 res=[["*"]] while pos<len(code): temp="" if code[pos]=="F": pos+=1 while pos<len(code) and code[pos].isdigit(): temp+=code[pos] pos+=1 temp=1 if not temp else int(temp) ...
def execute(code):
pos=x=y=0 direction=1 res=[["*"]] while pos<len(code): temp="" if code[pos]=="F": pos+=1 while pos<len(code) and code[pos].isdigit(): temp+=code[pos] pos+=1 temp=1 if not temp else int(temp) if direction==0: ...
def execute(code):
4
163
546
4
0
mwk0408/codewars_solutions
5 kyu/RoboScript 2 Implement the RS1 Specification.py
Python
execute
execute
1
73
1
1
fce81e1ecd475c8041bab6da3a0e93038013cb51
bigcode/the-stack
train
385103db61f99acd466153fc
train
class
class ApiException(Exception): def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: ...
class ApiException(Exception):
def __init__(self, status=None, reason=None, http_resp=None): if http_resp: self.status = http_resp.status self.reason = http_resp.reason self.body = http_resp.data self.headers = http_resp.getheaders() else: self.status = status ...
body=None, _preload_content=True, _request_timeout=None): return self.request("PATCH", url, headers=headers, query_params=query_params, post_params=post_params, _preload_content=_preload...
69
69
233
5
64
ekmixon/demisto-py
demisto_client/demisto_api/rest.py
Python
ApiException
ApiException
299
329
299
300
8c2b8bbad9405b87581bbc791b417926b98cebd6
bigcode/the-stack
train
7e06f4ab8312216585df20e9
train
class
class RESTClientObject(object): def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # htt...
class RESTClientObject(object):
def __init__(self, configuration, pools_size=4, maxsize=None): # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/bl...
\":\"-status:closed -category:job\",\"period\":{\"by\":\"day\",\"fromValue\":7}}}' --compressed ``` # noqa: E501 OpenAPI spec version: 2.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import io import json import logging import re import...
256
256
2,048
6
250
ekmixon/demisto-py
demisto_client/demisto_api/rest.py
Python
RESTClientObject
RESTClientObject
54
296
54
55
fe390ae2d0e4c7db294ddcce3e8ec4783bb1b9b9
bigcode/the-stack
train
ca3231b7f593617c7308f45f
train
class
class RESTResponse(io.IOBase): def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason self.data = resp.data def getheaders(self): """Returns a dictionary of the response headers.""" return self.urllib3_response...
class RESTResponse(io.IOBase):
def __init__(self, resp): self.urllib3_response = resp self.status = resp.status self.reason = resp.reason self.data = resp.data def getheaders(self): """Returns a dictionary of the response headers.""" return self.urllib3_response.getheaders() def getheader...
ifi # python 2 and python 3 compatibility library import six from six.moves.urllib.parse import urlencode try: import urllib3 except ImportError: raise ImportError('Swagger python client requires urllib3.') logger = logging.getLogger(__name__) class RESTResponse(io.IOBase):
64
64
104
7
57
ekmixon/demisto-py
demisto_client/demisto_api/rest.py
Python
RESTResponse
RESTResponse
37
51
37
38
483864ab4849b6113704d32014a93b9ee1f459ad
bigcode/the-stack
train
47589702c8cd02cd697a8e57
train
function
def buildmodel(show_model=False): input1 = Input(shape=(rows*cols,2),dtype='float32') # x = Conv2D(16,(2,2),strides=(1,1),padding='same', # activation='relu', # kernel_initializer=TruncatedNormal(), # bias_initializer='zeros')(input1) flat1 = Flatten()(input1) # i...
def buildmodel(show_model=False):
input1 = Input(shape=(rows*cols,2),dtype='float32') # x = Conv2D(16,(2,2),strides=(1,1),padding='same', # activation='relu', # kernel_initializer=TruncatedNormal(), # bias_initializer='zeros')(input1) flat1 = Flatten()(input1) # input2 = Input(shape=[2],dtype='flo...
this number EXPLORE = 5000 # how many episodes from INITIAL_EPSILON to FINAL_EPSILON REPLAY_MEMORY = 3000 # number of states to remember for replaying BATCH = 100 # size of a minibatch GAMMA = 0.99 # the decay rate def buildmodel(show_model=False):
74
74
248
7
66
yanglyuxun/game_play_snake
train15_15.py
Python
buildmodel
buildmodel
31
50
31
31
562b8da4f97ef64543861139160a17b0dd50fd33
bigcode/the-stack
train
3bbe8dd6e75bc564eb7f4e32
train
class
class AsyncKey(Key): def __init__(self, bucket=None, name=None): Key.__init__(self, bucket=bucket, name=name) def __repr__(self): if self.bucket: return '<AsyncKey: %s,%s>' % (self.bucket.name, self.name) else: return '<AsyncKey: None,%s>' % self.name def op...
class AsyncKey(Key):
def __init__(self, bucket=None, name=None): Key.__init__(self, bucket=bucket, name=name) def __repr__(self): if self.bucket: return '<AsyncKey: %s,%s>' % (self.bucket.name, self.name) else: return '<AsyncKey: None,%s>' % self.name def open_read(self, headers...
- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the fol- # lowing conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE ...
256
256
7,380
5
251
bopopescu/botornado
botornado/s3/key.py
Python
AsyncKey
AsyncKey
43
897
43
43
8418f743944d85b2da9dbe5077a19657b5e9363c
bigcode/the-stack
train
8dfd6794c0253cda0e03dd6a
train
function
def isPrime(num): if num == 1: return False n = int(math.sqrt(num)) for i in range(2,n+1): if num%i==0: return False return True
def isPrime(num):
if num == 1: return False n = int(math.sqrt(num)) for i in range(2,n+1): if num%i==0: return False return True
import sys import math N = int(sys.stdin.readline()) res = list(map(int, sys.stdin.readline().split())) cnt = 0 def isPrime(num):
35
64
50
5
29
Jaesin22/TIL
BOJ/1978.py
Python
isPrime
isPrime
8
15
8
8
2d3bb51744247af5cb02a024bc40ce31787189ed
bigcode/the-stack
train
62e6f341b22dc6b772558fda
train
function
def main(unused_argv): tf.logging.set_verbosity(FLAGS.log) config = drums_rnn_config_flags.config_from_flags() pipeline_instance = get_pipeline( config, FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_seria...
def main(unused_argv):
tf.logging.set_verbosity(FLAGS.log) config = drums_rnn_config_flags.config_from_flags() pipeline_instance = get_pipeline( config, FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_serial( pipeline_insta...
drums_extractor_train, encoder_pipeline_eval: drums_extractor_eval, dag_pipeline.DagOutput('training_drum_tracks'): encoder_pipeline_train, dag_pipeline.DagOutput('eval_drum_tracks'): encoder_pipeline_eval} return dag_pipeline.DAGPipeline(dag) def main(unused_argv):
64
64
98
7
57
jopdorp/classical-polyphony-rnn
magenta/models/drums_rnn/drums_rnn_create_dataset.py
Python
main
main
87
99
87
87
50e8c75c431d5c92794bded905ce4790877f06ad
bigcode/the-stack
train
1091473d891e73c31bbf1c51
train
function
def get_pipeline(config, eval_ratio): """Returns the Pipeline instance which creates the RNN dataset. Args: config: A DrumsRnnConfig object. eval_ratio: Fraction of input to set aside for evaluation set. Returns: A pipeline.Pipeline instance. """ quantizer = pipelines_common.Quantizer(steps_per_...
def get_pipeline(config, eval_ratio):
"""Returns the Pipeline instance which creates the RNN dataset. Args: config: A DrumsRnnConfig object. eval_ratio: Fraction of input to set aside for evaluation set. Returns: A pipeline.Pipeline instance. """ quantizer = pipelines_common.Quantizer(steps_per_quarter=4) drums_extractor_train = d...
'Directory to write training and eval TFRecord ' 'files. The TFRecord files are populated with ' 'SequenceExample protos.') tf.app.flags.DEFINE_float('eval_ratio', 0.1, 'Fraction of input to set aside for eval set...
110
111
370
8
102
jopdorp/classical-polyphony-rnn
magenta/models/drums_rnn/drums_rnn_create_dataset.py
Python
get_pipeline
get_pipeline
50
84
50
50
f90b7cd7709c362cee93f81f0d0d999d27dc6532
bigcode/the-stack
train
889ef2d28212c58b60c46d96
train
function
def console_entry_point(): tf.app.run(main)
def console_entry_point():
tf.app.run(main)
FLAGS.eval_ratio) FLAGS.input = os.path.expanduser(FLAGS.input) FLAGS.output_dir = os.path.expanduser(FLAGS.output_dir) pipeline.run_pipeline_serial( pipeline_instance, pipeline.tf_record_iterator(FLAGS.input, pipeline_instance.input_type), FLAGS.output_dir) def console_entry_point():
64
64
11
5
59
jopdorp/classical-polyphony-rnn
magenta/models/drums_rnn/drums_rnn_create_dataset.py
Python
console_entry_point
console_entry_point
102
103
102
102
6325f1c5fe70ec6637e74ecf2cec11f05f4f9072
bigcode/the-stack
train
b4fb147baa3d77a4a926a5d6
train
class
class ModelSchemaTest(unittest.TestCase): def setUp(self): self.schema = validators.ModelSchema() self.definition = { 'title': u'Flavors', 'description': u'Flavors', 'fields': [{'type': 'string', 'name': 'flavor'}] } def test_fails_if_no_definition(s...
class ModelSchemaTest(unittest.TestCase):
def setUp(self): self.schema = validators.ModelSchema() self.definition = { 'title': u'Flavors', 'description': u'Flavors', 'fields': [{'type': 'string', 'name': 'flavor'}] } def test_fails_if_no_definition(self): incomplete = {'records': []} ...
("submitButtonLabel", definition["extra"]) self.assertEqual("Let's go!", definition["extra"]["submitButtonLabel"]) def test_extra_may_not_be_present(self): schema = validators.DefinitionSchema() definition = schema.deserialize({ "title": "Foobar", "description": "foo...
110
110
368
8
102
spiral-project/daybed
daybed/tests/test_schemas_validators.py
Python
ModelSchemaTest
ModelSchemaTest
165
212
165
166
e3c5ec0b65ccdc3e1c5911ac6d403f930ad3f510
bigcode/the-stack
train
04f46cda92999ec00f0ec17f
train
class
class PermissionsSchemaTest(BaseWebTest): def setUp(self): super(PermissionsSchemaTest, self).setUp() self.db.store_credentials('abc', {'id': 'doctor', 'key': 'who'}) self.schema = validators.PermissionsSchema(name='permissions') self.permissions = { 'doctor': ['ALL'], ...
class PermissionsSchemaTest(BaseWebTest):
def setUp(self): super(PermissionsSchemaTest, self).setUp() self.db.store_credentials('abc', {'id': 'doctor', 'key': 'who'}) self.schema = validators.PermissionsSchema(name='permissions') self.permissions = { 'doctor': ['ALL'], 'Everyone': ['read_own_records']...
definition': self.definition, 'records': [{'flavor': 'vanilla'}]} validated = self.schema.deserialize(with_records) self.assertEqual(self.definition['title'], validated['definition']['title']) def test_fails_if_record_is_invalid_for_definition(self):...
169
169
566
8
161
spiral-project/daybed
daybed/tests/test_schemas_validators.py
Python
PermissionsSchemaTest
PermissionsSchemaTest
215
282
215
216
e1513a2fc7541526aefd6bc652f8f75a78cbb38c
bigcode/the-stack
train
7c5048d92933bcbdff737ca8
train
class
class ValidatorTests(unittest.TestCase): def setUp(self): self.request = DummyRequest() self.request.db = mock.MagicMock() self.request.matchdict = mock.MagicMock() self.request.errors = Errors() self.request.body = b'' def test_adds_body_error_if_json_invalid(self): ...
class ValidatorTests(unittest.TestCase):
def setUp(self): self.request = DummyRequest() self.request.db = mock.MagicMock() self.request.matchdict = mock.MagicMock() self.request.errors = Errors() self.request.body = b'' def test_adds_body_error_if_json_invalid(self): self.request.body = b'{wrong,"format...
import mock import colander from cornice.errors import Errors from pyramid.testing import DummyRequest from daybed import schemas from daybed.schemas import validators from daybed.tests.support import unittest, BaseWebTest class ValidatorTests(unittest.TestCase):
53
99
330
7
45
spiral-project/daybed
daybed/tests/test_schemas_validators.py
Python
ValidatorTests
ValidatorTests
11
46
11
11
7a03f1ae2d2670a6de547eb120bc19b3ed019597
bigcode/the-stack
train
2d461363a56fe519a5223ed9
train
class
class DefinitionSchemaTest(unittest.TestCase): def setUp(self): self.schema = schemas.TypeField.definition() def test_field_type_is_required(self): self.assertRaises(colander.Invalid, self.schema.deserialize, {'name': 'secret'}) def test_field_type_must_be_known_f...
class DefinitionSchemaTest(unittest.TestCase):
def setUp(self): self.schema = schemas.TypeField.definition() def test_field_type_is_required(self): self.assertRaises(colander.Invalid, self.schema.deserialize, {'name': 'secret'}) def test_field_type_must_be_known_from_registry(self): self.assertRaises(c...
(self.request, mock.Mock()) self.assertEqual('body', self.request.errors[0]['location']) def test_records_validation_adds_errors_to_response(self): self.request.db.get_model_definition.return_value = { 'fields': [{ 'name': 'wishlist', 'type': 'list', ...
255
256
910
8
247
spiral-project/daybed
daybed/tests/test_schemas_validators.py
Python
DefinitionSchemaTest
DefinitionSchemaTest
49
162
49
49
c2252d1f23758379388cf11a30c296c4a8ff8f6c
bigcode/the-stack
train
8377245685a22d7372473a47
train
class
class AlgorithmInput(Pluggable): _PROBLEM_SET = ['energy', 'excited_states', 'eoh', 'search', 'svm_classification', 'ising', 'linear_system'] @abstractmethod def __init__(self): super().__init__() if 'problems' not in self.configuration or len(self.configuration['proble...
class AlgorithmInput(Pluggable):
_PROBLEM_SET = ['energy', 'excited_states', 'eoh', 'search', 'svm_classification', 'ising', 'linear_system'] @abstractmethod def __init__(self): super().__init__() if 'problems' not in self.configuration or len(self.configuration['problems']) <= 0: raise AquaE...
agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ===================================...
95
95
318
8
86
pistoia/qiskit-aqua
qiskit/aqua/input/algorithminput.py
Python
AlgorithmInput
AlgorithmInput
24
68
24
25
7045a19632f743c94b6061c7dbf368920f3d4343
bigcode/the-stack
train
75a81d395df84320f19247b6
train
function
def translate_rgb_to_ansi_code(red, green, blue, offset, colormode): """ Translate the given RGB color into the appropriate ANSI escape code for the given color mode. The offset is used for the base color which is used. The ``colormode`` has to be one of: * 0: no colors / disabled *...
def translate_rgb_to_ansi_code(red, green, blue, offset, colormode):
""" Translate the given RGB color into the appropriate ANSI escape code for the given color mode. The offset is used for the base color which is used. The ``colormode`` has to be one of: * 0: no colors / disabled * 8: use ANSI 8 colors * 16: use ANSI 16 colors (same as 8 but...
. import styles from . import terminal from .utils import PY2, DEFAULT_ENCODE, UNICODE #: Holds the name of the env variable which is # used as path to the default rgb.txt file DEFAULT_RGB_TXT_PATH = os.environ.get( 'COLORFUL_DEFAULT_COLOR_PALETTE', os.path.join(os.path.dirname(__file__), 'data', 'rgb.txt'))...
157
157
525
19
137
0ki/colorful
colorful/core.py
Python
translate_rgb_to_ansi_code
translate_rgb_to_ansi_code
43
85
43
43
93ca9f3d12d32b5b0ccbb74dd4d8448ea4d43010
bigcode/the-stack
train
2b2a7a59fbd8175fe06366d7
train
function
def resolve_modifier_to_ansi_code(modifiername, colormode): """ Resolve the given modifier name to a valid ANSI escape code. :param str modifiername: the name of the modifier to resolve :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code`` :returns str: the ANSI escap...
def resolve_modifier_to_ansi_code(modifiername, colormode):
""" Resolve the given modifier name to a valid ANSI escape code. :param str modifiername: the name of the modifier to resolve :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code`` :returns str: the ANSI escape code for the modifier :raises ColorfulError: if the g...
a color in your color palette (by default: X11 rgb.txt)'.format( # noqa colorname)) else: return translate_rgb_to_ansi_code(red, green, blue, offset, colormode) def resolve_modifier_to_ansi_code(modifiername, colormode):
64
64
213
15
49
0ki/colorful
colorful/core.py
Python
resolve_modifier_to_ansi_code
resolve_modifier_to_ansi_code
111
134
111
111
09e5a843bc4bafe1fac702f66aba09e1516c33f6
bigcode/the-stack
train
c4273d0669f81bdce28bd5d4
train
function
def translate_style(style, colormode, colorpalette): """ Translate the given style to an ANSI escape code sequence. ``style`` examples are: * green * bold * red_on_black * bold_green * italic_yellow_on_cyan :param str style: the style to translate :param int colormode: the...
def translate_style(style, colormode, colorpalette):
""" Translate the given style to an ANSI escape code sequence. ``style`` examples are: * green * bold * red_on_black * bold_green * italic_yellow_on_cyan :param str style: the style to translate :param int colormode: the color mode to use. See ``translate_rgb_to_ansi_code`...
:raises ColorfulError: if the given modifier name is invalid """ if colormode == terminal.NO_COLORS: # return empty string if colors are disabled return '', '' try: start_code, end_code = ansi.MODIFIERS[modifiername] except KeyError: raise ColorfulError('the modifier "{0}" ...
141
141
472
12
129
0ki/colorful
colorful/core.py
Python
translate_style
translate_style
137
193
137
137
1cb2df65bfbec14030863a4e406b72fef7e30cb6
bigcode/the-stack
train
2b71747f397303d2dac070f5
train
class
class ColorfulString(object): """ Represents a colored string """ def __init__(self, orig_string, styled_string): self.orig_string = orig_string self.styled_string = styled_string if PY2: def __unicode__(self): return self.styled_string def __str__(self)...
class ColorfulString(object):
""" Represents a colored string """ def __init__(self, orig_string, styled_string): self.orig_string = orig_string self.styled_string = styled_string if PY2: def __unicode__(self): return self.styled_string def __str__(self): return self.styl...
color mode to use. See ``translate_rgb_to_ansi_code`` :returns: a string containing proper ANSI sequence """ ansi_start_code, ansi_end_code = ansi_style # replace nest placeholders with the current begin style if PY2: if isinstance(string, str): string = string.decode(DEFAULT_...
149
150
502
6
143
0ki/colorful
colorful/core.py
Python
ColorfulString
ColorfulString
222
294
222
222
76cad9adf1c6bc5cd172081db73b6381ab11d2ac
bigcode/the-stack
train