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
c910ffcc868944c395e325f9
train
function
def validate_ipv6_address(value): if not is_valid_ipv6_address(value): raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
def validate_ipv6_address(value):
if not is_valid_ipv6_address(value): raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid')
?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}\Z') validate_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid') def validate_ipv6_address(value):
64
64
34
7
57
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
validate_ipv6_address
validate_ipv6_address
230
232
230
230
aa5d8b1b3026a0380e37ab86784a9ffdb7943855
bigcode/the-stack
train
3e7cb7d1cd15e708c13bf267
train
function
def validate_ipv46_address(value): try: validate_ipv4_address(value) except ValidationError: try: validate_ipv6_address(value) except ValidationError: raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
def validate_ipv46_address(value):
try: validate_ipv4_address(value) except ValidationError: try: validate_ipv6_address(value) except ValidationError: raise ValidationError(_('Enter a valid IPv4 or IPv6 address.'), code='invalid')
_ipv4_address = RegexValidator(ipv4_re, _('Enter a valid IPv4 address.'), 'invalid') def validate_ipv6_address(value): if not is_valid_ipv6_address(value): raise ValidationError(_('Enter a valid IPv6 address.'), code='invalid') def validate_ipv46_address(value):
64
64
57
7
57
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
validate_ipv46_address
validate_ipv46_address
235
242
235
235
ead7c3b73b0025220c027624f3442cc061f1d4d8
bigcode/the-stack
train
e4dac92404f742006beaf8f1
train
function
def validate_integer(value): return integer_validator(value)
def validate_integer(value):
return integer_validator(value)
6_address(potential_ip) except ValidationError: raise ValidationError(self.message, code=self.code) url = value integer_validator = RegexValidator( re.compile('^-?\d+\Z'), message=_('Enter a valid integer.'), code='invalid', ) def validate_integer(value):
64
64
11
5
59
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
validate_integer
validate_integer
142
143
142
142
c79643d42f3114959ec4c47659255b308ad915f8
bigcode/the-stack
train
9b4a200cf5d600f674e8739b
train
class
@deconstructible class MinLengthValidator(BaseValidator): compare = lambda self, a, b: a < b clean = lambda self, x: len(x) message = ungettext_lazy( 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at least %(limit_value)d character...
@deconstructible class MinLengthValidator(BaseValidator):
compare = lambda self, a, b: a < b clean = lambda self, x: len(x) message = ungettext_lazy( 'Ensure this value has at least %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).', 'limit_value') co...
' @deconstructible class MinValueValidator(BaseValidator): compare = lambda self, a, b: a < b message = _('Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value' @deconstructible class MinLengthValidator(BaseValidator):
64
64
100
12
52
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
MinLengthValidator
MinLengthValidator
316
324
316
317
b5eaf503e43fee28694f24e6b5e520910a8beb18
bigcode/the-stack
train
4cc15e579611901eda619bb0
train
class
@deconstructible class MaxLengthValidator(BaseValidator): compare = lambda self, a, b: a > b clean = lambda self, x: len(x) message = ungettext_lazy( 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at most %(limit_value)d characters ...
@deconstructible class MaxLengthValidator(BaseValidator):
compare = lambda self, a, b: a > b clean = lambda self, x: len(x) message = ungettext_lazy( 'Ensure this value has at most %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at most %(limit_value)d characters (it has %(show_value)d).', 'limit_value') code...
value has at least %(limit_value)d character (it has %(show_value)d).', 'Ensure this value has at least %(limit_value)d characters (it has %(show_value)d).', 'limit_value') code = 'min_length' @deconstructible class MaxLengthValidator(BaseValidator):
64
64
100
12
52
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
MaxLengthValidator
MaxLengthValidator
327
335
327
328
3332bd742a8ac8813f8cfe580f25ceb03a52f305
bigcode/the-stack
train
ea906eb089c1eca1977af8ad
train
class
@deconstructible class RegexValidator(object): regex = '' message = _('Enter a valid value.') code = 'invalid' inverse_match = False flags = 0 def __init__(self, regex=None, message=None, code=None, inverse_match=None, flags=None): if regex is not None: self.regex = regex ...
@deconstructible class RegexValidator(object):
regex = '' message = _('Enter a valid value.') code = 'invalid' inverse_match = False flags = 0 def __init__(self, regex=None, message=None, code=None, inverse_match=None, flags=None): if regex is not None: self.regex = regex if message is not None: self....
Error from django.utils import six from django.utils.deconstruct import deconstructible from django.utils.encoding import force_text from django.utils.ipv6 import is_valid_ipv6_address from django.utils.six.moves.urllib.parse import urlsplit, urlunsplit from django.utils.translation import ugettext_lazy as _, ungettext...
106
107
358
10
96
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
RegexValidator
RegexValidator
17
63
17
18
29cc4122cc01bf7b6fc07fe53bf63a19afc372c5
bigcode/the-stack
train
dd8cf6e1eff9afec656850db
train
class
@deconstructible class URLValidator(RegexValidator): ul = '\u00a1-\uffff' # unicode letters range (must be a unicode string, not a raw string) # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated ...
@deconstructible class URLValidator(RegexValidator):
ul = '\u00a1-\uffff' # unicode letters range (must be a unicode string, not a raw string) # IP patterns ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}' ipv6_re = r'\[[0-9a-f:\.]+\]' # (simple regex, validated later) # Host patterns hostname_re = r'[a-z'...
.flags = flags if self.flags and not isinstance(self.regex, six.string_types): raise TypeError("If the flags are set, regex must be a regular expression string.") # Compile the regex if it was not passed pre-compiled. if isinstance(self.regex, six.string_types): self.reg...
242
242
807
12
230
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
URLValidator
URLValidator
66
133
66
67
7431fbd3d3637cfac3af776c4c0066fc382c6427
bigcode/the-stack
train
4a828c59cc18190278bea960
train
class
@deconstructible class BaseValidator(object): compare = lambda self, a, b: a is not b clean = lambda self, x: x message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).') code = 'limit_value' def __init__(self, limit_value, message=None): self.limit_value = limit_value ...
@deconstructible class BaseValidator(object):
compare = lambda self, a, b: a is not b clean = lambda self, x: x message = _('Ensure this value is %(limit_value)s (it is %(show_value)s).') code = 'limit_value' def __init__(self, limit_value, message=None): self.limit_value = limit_value if message: self.message = mes...
_validator_map))) comma_separated_int_list_re = re.compile('^[\d,]+\Z') validate_comma_separated_integer_list = RegexValidator( comma_separated_int_list_re, _('Enter only digits separated by commas.'), 'invalid' ) @deconstructible class BaseValidator(object):
64
64
209
10
54
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
BaseValidator
BaseValidator
275
299
275
276
8ff5e1fe621fd4b65ff8601d21ceafb0d40eb54c
bigcode/the-stack
train
c7a2efbe9a06ee61050ee8a8
train
function
def ip_address_validators(protocol, unpack_ipv4): """ Depending on the given parameters returns the appropriate validators for the GenericIPAddressField. This code is here, because it is exactly the same for the model and the form field. """ if protocol != 'both' and unpack_ipv4: raise ...
def ip_address_validators(protocol, unpack_ipv4):
""" Depending on the given parameters returns the appropriate validators for the GenericIPAddressField. This code is here, because it is exactly the same for the model and the form field. """ if protocol != 'both' and unpack_ipv4: raise ValueError( "You can only use `unpack_...
_('Enter a valid IPv4 or IPv6 address.')), 'ipv4': ([validate_ipv4_address], _('Enter a valid IPv4 address.')), 'ipv6': ([validate_ipv6_address], _('Enter a valid IPv6 address.')), } def ip_address_validators(protocol, unpack_ipv4):
64
64
139
11
53
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
ip_address_validators
ip_address_validators
251
265
251
251
57f8eb3f6dce8d4d70dab54d0a9ad3bae369a0ac
bigcode/the-stack
train
ac66fece79a6a3e4de07f0fc
train
class
@deconstructible class EmailValidator(object): message = _('Enter a valid email address.') code = 'invalid' user_regex = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])...
@deconstructible class EmailValidator(object):
message = _('Enter a valid email address.') code = 'invalid' user_regex = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)', # quoted-string re.IGNORECASE)...
except UnicodeError: # invalid domain part raise e url = urlunsplit((scheme, netloc, path, query, fragment)) super(URLValidator, self).__call__(url) else: raise else: # Now verify IPv6 in the netloc part...
197
197
658
10
187
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
EmailValidator
EmailValidator
146
215
146
147
0fa42856f9fcaf982f212b3e45440a8feb93b8ef
bigcode/the-stack
train
dca980bcb78a14c392ddd646
train
class
@deconstructible class MinValueValidator(BaseValidator): compare = lambda self, a, b: a < b message = _('Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value'
@deconstructible class MinValueValidator(BaseValidator):
compare = lambda self, a, b: a < b message = _('Ensure this value is greater than or equal to %(limit_value)s.') code = 'min_value'
) @deconstructible class MaxValueValidator(BaseValidator): compare = lambda self, a, b: a > b message = _('Ensure this value is less than or equal to %(limit_value)s.') code = 'max_value' @deconstructible class MinValueValidator(BaseValidator):
64
64
51
12
52
okwow123/finaltest
env/lib/python2.7/site-packages/django/core/validators.py
Python
MinValueValidator
MinValueValidator
309
313
309
310
58e3d983f5baf25fc41e708d674d7675ef44bcc8
bigcode/the-stack
train
83e02f4b2a112f75becc5c8c
train
function
def compute_neighbors_rapids( X: np.ndarray, n_neighbors: int ): """Compute nearest neighbors using RAPIDS cuml. Parameters ---------- X: array of shape (n_samples, n_features) The data to compute nearest neighbors for. n_neighbors The number of neighbors to use. Re...
def compute_neighbors_rapids( X: np.ndarray, n_neighbors: int ):
"""Compute nearest neighbors using RAPIDS cuml. Parameters ---------- X: array of shape (n_samples, n_features) The data to compute nearest neighbors for. n_neighbors The number of neighbors to use. Returns ------- **knn_indices**, **knn_dists** : np.arrays of shape...
_neighbors, random_state=random_state, metric=metric, metric_kwds=metric_kwds, angular=angular, verbose=verbose, ) return knn_indices, knn_dists, forest def compute_neighbors_rapids( X: np.ndarray, n_neighbors: int ):
64
64
194
20
43
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
compute_neighbors_rapids
compute_neighbors_rapids
254
276
254
257
6a6b89af1c0e1cf59de660aab1a763a08eb6b795
bigcode/the-stack
train
3087f5b607c1da4ba947c14b
train
function
@_doc_params(n_pcs=doc_n_pcs, use_rep=doc_use_rep) def neighbors( adata: AnnData, n_neighbors: int = 15, n_pcs: Optional[int] = None, use_rep: Optional[str] = None, knn: bool = True, random_state: AnyRandom = 0, method: Optional[_Method] = 'umap', metric: Union[_Metric, _MetricFn] = 'euc...
@_doc_params(n_pcs=doc_n_pcs, use_rep=doc_use_rep) def neighbors( adata: AnnData, n_neighbors: int = 15, n_pcs: Optional[int] = None, use_rep: Optional[str] = None, knn: bool = True, random_state: AnyRandom = 0, method: Optional[_Method] = 'umap', metric: Union[_Metric, _MetricFn] = 'euc...
"""\ Compute a neighborhood graph of observations [McInnes18]_. The neighbor search efficiency of this heavily relies on UMAP [McInnes18]_, which also provides a method for estimating connectivities of data points - the connectivity of the manifold (`method=='umap'`). If `method=='gauss'`, conn...
'manhattan' ] _MetricScipySpatial = Literal[ 'braycurtis', 'canberra', 'chebyshev', 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule' ] _Metric = Union[_MetricSparseCa...
256
256
1,030
136
120
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
neighbors
neighbors
36
134
36
48
14b4cdf3bac8cd623ce045fa4099580211ce916a
bigcode/the-stack
train
7db9ef8c1dd6b953939ef6cb
train
function
def _get_sparse_matrix_from_indices_distances_umap(knn_indices, knn_dists, n_obs, n_neighbors): rows = np.zeros((n_obs * n_neighbors), dtype=np.int64) cols = np.zeros((n_obs * n_neighbors), dtype=np.int64) vals = np.zeros((n_obs * n_neighbors), dtype=np.float64) for i in range(knn_indices.shape[0]): ...
def _get_sparse_matrix_from_indices_distances_umap(knn_indices, knn_dists, n_obs, n_neighbors):
rows = np.zeros((n_obs * n_neighbors), dtype=np.int64) cols = np.zeros((n_obs * n_neighbors), dtype=np.int64) vals = np.zeros((n_obs * n_neighbors), dtype=np.float64) for i in range(knn_indices.shape[0]): for j in range(n_neighbors): if knn_indices[i, j] == -1: conti...
knn_distsq, knn_indices = nn.kneighbors(X_contiguous) return knn_indices, np.sqrt(knn_distsq) # cuml uses sqeuclidean metric so take sqrt def _get_sparse_matrix_from_indices_distances_umap(knn_indices, knn_dists, n_obs, n_neighbors):
70
70
236
26
43
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_get_sparse_matrix_from_indices_distances_umap
_get_sparse_matrix_from_indices_distances_umap
279
300
279
279
42b15c37811f878bb497564785f1336f6b599812
bigcode/the-stack
train
a3a2be953aca9937641a2289
train
function
def _get_sparse_matrix_from_indices_distances_numpy(indices, distances, n_obs, n_neighbors): n_nonzero = n_obs * n_neighbors indptr = np.arange(0, n_nonzero + 1, n_neighbors) D = csr_matrix(( distances.copy().ravel(), # copy the data, otherwise strange behavior here indices.copy().ravel(), ...
def _get_sparse_matrix_from_indices_distances_numpy(indices, distances, n_obs, n_neighbors):
n_nonzero = n_obs * n_neighbors indptr = np.arange(0, n_nonzero + 1, n_neighbors) D = csr_matrix(( distances.copy().ravel(), # copy the data, otherwise strange behavior here indices.copy().ravel(), indptr, ), shape=(n_obs, n_obs)) D.eliminate_zeros() return D
0] distances = _get_sparse_matrix_from_indices_distances_umap( knn_indices, knn_dists, n_obs, n_neighbors ) return distances, connectivities.tocsr() def _get_sparse_matrix_from_indices_distances_numpy(indices, distances, n_obs, n_neighbors):
64
64
107
20
44
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_get_sparse_matrix_from_indices_distances_numpy
_get_sparse_matrix_from_indices_distances_numpy
343
352
343
343
80c7b51d963f0eabb20d580e7ec35a9d5794d411
bigcode/the-stack
train
9769ecce5119c12014622886
train
function
def _get_indices_distances_from_dense_matrix(D, n_neighbors: int): sample_range = np.arange(D.shape[0])[:, None] indices = np.argpartition(D, n_neighbors-1, axis=1)[:, :n_neighbors] indices = indices[sample_range, np.argsort(D[sample_range, indices])] distances = D[sample_range, indices] return indi...
def _get_indices_distances_from_dense_matrix(D, n_neighbors: int):
sample_range = np.arange(D.shape[0])[:, None] indices = np.argpartition(D, n_neighbors-1, axis=1)[:, :n_neighbors] indices = indices[sample_range, np.argsort(D[sample_range, indices])] distances = D[sample_range, indices] return indices, distances
neighbors[0][sorted_indices], neighbors[1][sorted_indices]] else: indices[i, 1:] = neighbors[1] distances[i, 1:] = D[i][neighbors] return indices, distances def _get_indices_distances_from_dense_matrix(D, n_neighbors: int):
64
64
86
16
47
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_get_indices_distances_from_dense_matrix
_get_indices_distances_from_dense_matrix
377
382
377
377
1a4661d8317313c83b9dbfd1e53534baed20e2d5
bigcode/the-stack
train
a2d3929c0d96ce1f2ba657df
train
class
class Neighbors: """\ Data represented as graph of nearest neighbors. Represent a data matrix as a graph of nearest neighbor relations (edges) among data points (nodes). Parameters ---------- adata Annotated data object. n_dcs Number of diffusion components to use. ...
class Neighbors:
"""\ Data represented as graph of nearest neighbors. Represent a data matrix as a graph of nearest neighbor relations (edges) among data points (nodes). Parameters ---------- adata Annotated data object. n_dcs Number of diffusion components to use. """ def __in...
the global index glob_index = self.restrict_array[index] if glob_index not in self.rows: self.rows[glob_index] = self.get_row(glob_index) row = self.rows[glob_index] if self.restrict_array is None: return row else: ...
256
256
4,817
4
252
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
Neighbors
Neighbors
477
972
477
477
6e566d431db5d2776f6075faece133eb02db9b05
bigcode/the-stack
train
b0ece91b8741f6223746fb1a
train
function
def _rp_forest_generate(rp_forest_dict: RPForestDict) -> Generator[FlatTree, None, None]: props = FlatTree._fields num_trees = len(rp_forest_dict[props[0]]['start'])-1 for i in range(num_trees): tree = [] for prop in props: start = rp_forest_dict[prop]['start'][i] en...
def _rp_forest_generate(rp_forest_dict: RPForestDict) -> Generator[FlatTree, None, None]:
props = FlatTree._fields num_trees = len(rp_forest_dict[props[0]]['start'])-1 for i in range(num_trees): tree = [] for prop in props: start = rp_forest_dict[prop]['start'][i] end = rp_forest_dict[prop]['start'][i+1] tree.append(rp_forest_dict[prop]['data'...
amedTuple): hyperplanes: None offsets: None children: None indices: None RPForestDict = Mapping[str, Mapping[str, np.ndarray]] def _rp_forest_generate(rp_forest_dict: RPForestDict) -> Generator[FlatTree, None, None]:
63
64
171
26
37
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_rp_forest_generate
_rp_forest_generate
147
163
147
147
13d3f68803a6539f1563300993a6dae2bad65ba0
bigcode/the-stack
train
fc65ed27e98da097b2cef601
train
class
class OnFlySymMatrix: """Emulate a matrix where elements are calculated on the fly. """ def __init__( self, get_row: Callable[[Any], np.ndarray], shape: Tuple[int, int], DC_start: int = 0, DC_end: int = -1, rows: Optional[Mapping[Any, np.ndarray]] = None, ...
class OnFlySymMatrix:
"""Emulate a matrix where elements are calculated on the fly. """ def __init__( self, get_row: Callable[[Any], np.ndarray], shape: Tuple[int, int], DC_start: int = 0, DC_end: int = -1, rows: Optional[Mapping[Any, np.ndarray]] = None, restrict_array: Op...
(sizes) if prop == 'offsets': dims = sizes.sum() else: dims = (sizes.sum(), getattr(forest[0], prop).shape[1]) dtype = getattr(forest[0], prop).dtype dat = np.empty(dims, dtype=dtype) start = 0 for i, size in enumerate(sizes): d[prop]['...
135
135
452
6
128
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
OnFlySymMatrix
OnFlySymMatrix
423
474
423
423
3e0d7ad06297da1c05a66e79bf00f59fcbafd677
bigcode/the-stack
train
5a2673c8f99de683903e099d
train
function
def _backwards_compat_get_full_eval(adata: AnnData): if 'X_diffmap0' in adata.obs: return np.r_[1, adata.uns['diffmap_evals']] else: return adata.uns['diffmap_evals']
def _backwards_compat_get_full_eval(adata: AnnData):
if 'X_diffmap0' in adata.obs: return np.r_[1, adata.uns['diffmap_evals']] else: return adata.uns['diffmap_evals']
map0' in adata.obs: return np.c_[adata.obs['X_diffmap0'].values[:, None], adata.obsm['X_diffmap']] else: return adata.obsm['X_diffmap'] def _backwards_compat_get_full_eval(adata: AnnData):
64
64
58
15
49
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_backwards_compat_get_full_eval
_backwards_compat_get_full_eval
393
397
393
393
71d2f794e208a82d131bce6e8ecc068aba21e5a6
bigcode/the-stack
train
07762502a7b95013159a1139
train
function
def _make_forest_dict(forest): d = {} props = ('hyperplanes', 'offsets', 'children', 'indices') for prop in props: d[prop] = {} sizes = np.fromiter((getattr(tree, prop).shape[0] for tree in forest), dtype=int) d[prop]['start'] = np.zeros_like(sizes) if prop == 'offsets': ...
def _make_forest_dict(forest):
d = {} props = ('hyperplanes', 'offsets', 'children', 'indices') for prop in props: d[prop] = {} sizes = np.fromiter((getattr(tree, prop).shape[0] for tree in forest), dtype=int) d[prop]['start'] = np.zeros_like(sizes) if prop == 'offsets': dims = sizes.sum() ...
wards_compat_get_full_eval(adata: AnnData): if 'X_diffmap0' in adata.obs: return np.r_[1, adata.uns['diffmap_evals']] else: return adata.uns['diffmap_evals'] def _make_forest_dict(forest):
64
64
206
9
55
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_make_forest_dict
_make_forest_dict
400
420
400
400
a7b70f01f9fe5f5070b0804b026bca14ec643838
bigcode/the-stack
train
168e906c573453dd15c6dfa7
train
function
def _get_indices_distances_from_sparse_matrix(D, n_neighbors: int): indices = np.zeros((D.shape[0], n_neighbors), dtype=int) distances = np.zeros((D.shape[0], n_neighbors), dtype=D.dtype) n_neighbors_m1 = n_neighbors - 1 for i in range(indices.shape[0]): neighbors = D[i].nonzero() # 'true' and ...
def _get_indices_distances_from_sparse_matrix(D, n_neighbors: int):
indices = np.zeros((D.shape[0], n_neighbors), dtype=int) distances = np.zeros((D.shape[0], n_neighbors), dtype=D.dtype) n_neighbors_m1 = n_neighbors - 1 for i in range(indices.shape[0]): neighbors = D[i].nonzero() # 'true' and 'spurious' zeros indices[i, 0] = i distances[i, 0] =...
1, n_neighbors) D = csr_matrix(( distances.copy().ravel(), # copy the data, otherwise strange behavior here indices.copy().ravel(), indptr, ), shape=(n_obs, n_obs)) D.eliminate_zeros() return D def _get_indices_distances_from_sparse_matrix(D, n_neighbors: int):
79
79
266
16
62
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_get_indices_distances_from_sparse_matrix
_get_indices_distances_from_sparse_matrix
355
374
355
355
9f7bed90f35c274955e17b6f71e11d70f03c5c01
bigcode/the-stack
train
cf36c7c9fa866be00f6a21d5
train
function
def _compute_connectivities_umap( knn_indices, knn_dists, n_obs, n_neighbors, set_op_mix_ratio=1.0, local_connectivity=1.0, ): """\ This is from umap.fuzzy_simplicial_set [McInnes18]_. Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (he...
def _compute_connectivities_umap( knn_indices, knn_dists, n_obs, n_neighbors, set_op_mix_ratio=1.0, local_connectivity=1.0, ):
"""\ This is from umap.fuzzy_simplicial_set [McInnes18]_. Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geode...
+ j] = knn_indices[i, j] vals[i * n_neighbors + j] = val result = coo_matrix((vals, (rows, cols)), shape=(n_obs, n_obs)) result.eliminate_zeros() return result.tocsr() def _compute_connectivities_umap( knn_indices, knn_dists, n_obs, n_neighbors, se...
104
104
349
44
60
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_compute_connectivities_umap
_compute_connectivities_umap
303
340
303
307
1c72ffe8762b9932124224de1ff079b08c8d5f47
bigcode/the-stack
train
d877e40a5aa8059a596f8d5f
train
function
def compute_neighbors_umap( X: Union[np.ndarray, csr_matrix], n_neighbors: int, random_state: AnyRandom = None, metric: Union[_Metric, _MetricFn] = 'euclidean', metric_kwds: Mapping[str, Any] = MappingProxyType({}), angular: bool = False, verbose: bool = False, ): """This is from umap.fu...
def compute_neighbors_umap( X: Union[np.ndarray, csr_matrix], n_neighbors: int, random_state: AnyRandom = None, metric: Union[_Metric, _MetricFn] = 'euclidean', metric_kwds: Mapping[str, Any] = MappingProxyType({}), angular: bool = False, verbose: bool = False, ):
"""This is from umap.fuzzy_simplicial_set [McInnes18]_. Given a set of data X, a neighborhood size, and a measure of distance compute the fuzzy simplicial set (here represented as a fuzzy graph in the form of a sparse matrix) associated to the data. This is done by locally approximating geodesic di...
None]: props = FlatTree._fields num_trees = len(rp_forest_dict[props[0]]['start'])-1 for i in range(num_trees): tree = [] for prop in props: start = rp_forest_dict[prop]['start'][i] end = rp_forest_dict[prop]['start'][i+1] tree.append(rp_forest_dict[prop...
225
225
751
78
147
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
compute_neighbors_umap
compute_neighbors_umap
166
251
166
174
0f642e17db79c7c7333dab0e83fcf8269745d7e4
bigcode/the-stack
train
2a0e3fa7cbc7e564bcec764a
train
function
def _backwards_compat_get_full_X_diffmap(adata: AnnData) -> np.ndarray: if 'X_diffmap0' in adata.obs: return np.c_[adata.obs['X_diffmap0'].values[:, None], adata.obsm['X_diffmap']] else: return adata.obsm['X_diffmap']
def _backwards_compat_get_full_X_diffmap(adata: AnnData) -> np.ndarray:
if 'X_diffmap0' in adata.obs: return np.c_[adata.obs['X_diffmap0'].values[:, None], adata.obsm['X_diffmap']] else: return adata.obsm['X_diffmap']
axis=1)[:, :n_neighbors] indices = indices[sample_range, np.argsort(D[sample_range, indices])] distances = D[sample_range, indices] return indices, distances def _backwards_compat_get_full_X_diffmap(adata: AnnData) -> np.ndarray:
64
64
75
21
42
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
_backwards_compat_get_full_X_diffmap
_backwards_compat_get_full_X_diffmap
385
390
385
385
a090b3edddbb329bc210e6978a54a1a142b6ee83
bigcode/the-stack
train
dc62c593dbad112fb2611dd1
train
class
class FlatTree(NamedTuple): hyperplanes: None offsets: None children: None indices: None
class FlatTree(NamedTuple):
hyperplanes: None offsets: None children: None indices: None
deep=( 'added to `.uns[\'neighbors\']`\n' ' \'distances\', distances for each pair of neighbors\n' ' \'connectivities\', weighted adjacency matrix' ), ) return adata if copy else None class FlatTree(NamedTuple):
64
64
28
7
56
LouisFaure/scanpy
scanpy/neighbors/__init__.py
Python
FlatTree
FlatTree
137
141
137
137
2f3289b3b790cf83135256c48f8ece92fe248fdb
bigcode/the-stack
train
f123a20bbb95b2f84f1babf5
train
class
class BasePluginTestCase(TestCase): tempdir = None cwd = None def setUp(self) -> None: self.cwd = os.getcwd() self.tempdir = TemporaryDirectory() os.chdir(self.tempdir.name) def tearDown(self) -> None: if self.tempdir: assert self.cwd os.chdir(s...
class BasePluginTestCase(TestCase):
tempdir = None cwd = None def setUp(self) -> None: self.cwd = os.getcwd() self.tempdir = TemporaryDirectory() os.chdir(self.tempdir.name) def tearDown(self) -> None: if self.tempdir: assert self.cwd os.chdir(self.cwd) self.tempdir.cle...
mock_config import mock_config import bandersnatch.filter from bandersnatch.master import Master from bandersnatch.mirror import BandersnatchMirror from bandersnatch.package import Package from bandersnatch_filter_plugins import filename_name class BasePluginTestCase(TestCase):
64
64
90
8
55
isidentical/bandersnatch
src/bandersnatch/tests/plugins/test_filename.py
Python
BasePluginTestCase
BasePluginTestCase
15
30
15
16
43a40871f58f58789a6ee9e682addd7d7674eeeb
bigcode/the-stack
train
b0e97c12cbb23a377e69a243
train
class
class TestExcludePlatformFilter(BasePluginTestCase): config_contents = """\ [plugins] enabled = exclude_platform [blocklist] platforms = windows freebsd macos linux_armv7l """ def test_plugin_compiles_patterns(self) -> None: mock_config(self.config_contents) plugins = ban...
class TestExcludePlatformFilter(BasePluginTestCase):
config_contents = """\ [plugins] enabled = exclude_platform [blocklist] platforms = windows freebsd macos linux_armv7l """ def test_plugin_compiles_patterns(self) -> None: mock_config(self.config_contents) plugins = bandersnatch.filter.LoadedFilters().filter_release_file_p...
import os from pathlib import Path from tempfile import TemporaryDirectory from unittest import TestCase from mock_config import mock_config import bandersnatch.filter from bandersnatch.master import Master from bandersnatch.mirror import BandersnatchMirror from bandersnatch.package import Package from bandersnatch_f...
177
256
967
10
166
isidentical/bandersnatch
src/bandersnatch/tests/plugins/test_filename.py
Python
TestExcludePlatformFilter
TestExcludePlatformFilter
33
162
33
34
2291bef903f3ceb47d1d93558468a19fb3eb26f7
bigcode/the-stack
train
f28cc739539333462675a4d9
train
function
def is_balanced(root): return (max_depth(root) - min_depth(root) < 2)
def is_balanced(root):
return (max_depth(root) - min_depth(root) < 2)
else: return 1 + max(max_depth(root.left), max_depth(root.right)) def min_depth(root): # base case if root is None: return 0 else: return 1 + min(min_depth(root.left), min_depth(root.right)) def is_balanced(root):
64
64
22
6
58
kgraves/ctci
edition4/py/ch04/4-1.py
Python
is_balanced
is_balanced
21
22
21
21
fb01616dfd81e918b72ccc9189090eb675a45602
bigcode/the-stack
train
938341f1e5b9d7ef6c552d37
train
class
class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right
class Node(object):
def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right
class Node(object):
4
64
37
4
0
kgraves/ctci
edition4/py/ch04/4-1.py
Python
Node
Node
1
5
1
1
5775c3aa0f20b253c60962ef2cae3b0558ee5f2e
bigcode/the-stack
train
d752e596fc463927a5115d90
train
function
def min_depth(root): # base case if root is None: return 0 else: return 1 + min(min_depth(root.left), min_depth(root.right))
def min_depth(root): # base case
if root is None: return 0 else: return 1 + min(min_depth(root.left), min_depth(root.right))
value self.left = left self.right = right def max_depth(root): # base case if root is None: return 0 else: return 1 + max(max_depth(root.left), max_depth(root.right)) def min_depth(root): # base case
64
64
40
10
54
kgraves/ctci
edition4/py/ch04/4-1.py
Python
min_depth
min_depth
14
19
14
15
f14d4027fa9b90366ec68517dd849f4e2a75ef2e
bigcode/the-stack
train
4ea546a65d096563c9f2984d
train
function
def max_depth(root): # base case if root is None: return 0 else: return 1 + max(max_depth(root.left), max_depth(root.right))
def max_depth(root): # base case
if root is None: return 0 else: return 1 + max(max_depth(root.left), max_depth(root.right))
class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def max_depth(root): # base case
47
64
40
10
36
kgraves/ctci
edition4/py/ch04/4-1.py
Python
max_depth
max_depth
7
12
7
8
0342095783a472c08e4fc5f2638ce8709f987346
bigcode/the-stack
train
6a594d8e7fc7b0c6026674a2
train
class
class TestIsBalanced(unittest.TestCase): def test_is_balanced(self): n1 = Node(1) n2 = Node(1) n3 = Node(1, n1, n2) n4 = Node(1) n5 = Node(1) n6 = Node(1, n4, n5) root = Node(1, n3, n6) self.assertTrue(is_balanced(root)) n7 = Node(1) ...
class TestIsBalanced(unittest.TestCase):
def test_is_balanced(self): n1 = Node(1) n2 = Node(1) n3 = Node(1, n1, n2) n4 = Node(1) n5 = Node(1) n6 = Node(1, n4, n5) root = Node(1, n3, n6) self.assertTrue(is_balanced(root)) n7 = Node(1) n4.left = n7 self.assertTrue(is_...
if root is None: return 0 else: return 1 + min(min_depth(root.left), min_depth(root.right)) def is_balanced(root): return (max_depth(root) - min_depth(root) < 2) import unittest class TestIsBalanced(unittest.TestCase):
64
64
148
8
55
kgraves/ctci
edition4/py/ch04/4-1.py
Python
TestIsBalanced
TestIsBalanced
25
45
25
26
4a949adaf06645496a0b41fb7543541210c3d9b6
bigcode/the-stack
train
d313ce10b8347d6c332481bd
train
class
class HelloWorldService(ServiceBase): @srpc(_returns=DateTime) def get_utc_time(): return datetime.utcnow()
class HelloWorldService(ServiceBase): @srpc(_returns=DateTime)
def get_utc_time(): return datetime.utcnow()
import MessagePackRpc from protocol import PngClock from protocol import SvgClock tns = 'spyne.examples.multiple_protocols' port = 9910 host = '127.0.0.1' class HelloWorldService(ServiceBase): @srpc(_returns=DateTime)
64
64
29
17
47
leobispo/spyne
examples/multiple_protocols/server.py
Python
HelloWorldService
HelloWorldService
72
75
72
73
7c28299fbbece0fade8345eb8e6d43bf2072562a
bigcode/the-stack
train
87bd7d1fac4e3a644fdd14c0
train
function
def list(request): # do something.... return JsonResponse( [ { 'key' : 'value' }, { 'key2' : 'value2'} ], safe=False # dictionary 형태가 아닌 list와 같은 형태 사용디 반드시 safe=False )
def list(request): # do something....
return JsonResponse( [ { 'key' : 'value' }, { 'key2' : 'value2'} ], safe=False # dictionary 형태가 아닌 list와 같은 형태 사용디 반드시 safe=False )
u>') # JSON 1개 짜리 def dict(request): # do something.... return JsonResponse({ 'key' : 'value', 'key2' : 'value2' }) # JSON 여러개 짜리 def list(request): # do something....
64
64
58
9
54
ekjongh/django
tutorial/config/views.py
Python
list
list
23
30
23
24
094fec6df9deeac7cb9d3e936f8f208798521b23
bigcode/the-stack
train
8940234377a55009e200778e
train
function
def index(request): # request 파라미터 필수 # do something.... # return HttpResponse('<u>View</u>') return render(request, 'index.html')
def index(request): # request 파라미터 필수 # do something.... # return HttpResponse('<u>View</u>')
return render(request, 'index.html')
from django.http import HttpResponse from django.http.response import JsonResponse from django.shortcuts import render def index(request): # request 파라미터 필수 # do something.... # return HttpResponse('<u>View</u>')
51
64
39
30
20
ekjongh/django
tutorial/config/views.py
Python
index
index
5
8
5
7
07b2402e7547435a8c307181f7c045fbc7bd931c
bigcode/the-stack
train
06f9a2b16b9aed96ef9fa7ea
train
function
def home(request): # request 파라미터 필수 # do something.... return HttpResponse('<u>View</u>')
def home(request): # request 파라미터 필수 # do something....
return HttpResponse('<u>View</u>')
from django.shortcuts import render def index(request): # request 파라미터 필수 # do something.... # return HttpResponse('<u>View</u>') return render(request, 'index.html') def home(request): # request 파라미터 필수 # do something....
64
64
29
18
46
ekjongh/django
tutorial/config/views.py
Python
home
home
10
12
10
11
03c51ba508e6323f6325ad61cbc4440863cbc26f
bigcode/the-stack
train
5889a9ec9e9b57c980c5b9a1
train
function
def dict(request): # do something.... return JsonResponse({ 'key' : 'value', 'key2' : 'value2' })
def dict(request): # do something....
return JsonResponse({ 'key' : 'value', 'key2' : 'value2' })
u>View</u>') return render(request, 'index.html') def home(request): # request 파라미터 필수 # do something.... return HttpResponse('<u>View</u>') # JSON 1개 짜리 def dict(request): # do something....
64
64
35
10
53
ekjongh/django
tutorial/config/views.py
Python
dict
dict
15
20
15
16
59b16bd856d466e4370f414d921ed7ed4eee12db
bigcode/the-stack
train
09b29e41c90e89bcd1084094
train
class
class ScatteringQueueManager(MemoryTaskQueue): class TaskWrapper: def __init__(self, future, manager, timeout=10): self.future: Future = future self.timeout = timeout self.manager: ScatteringQueueManager = manager self.future.add_done_callback(self.callback) ...
class ScatteringQueueManager(MemoryTaskQueue):
class TaskWrapper: def __init__(self, future, manager, timeout=10): self.future: Future = future self.timeout = timeout self.manager: ScatteringQueueManager = manager self.future.add_done_callback(self.callback) def __del__(self): self.fu...
import queue import threading from concurrent.futures import Future from multiprocessing import Queue import psutil from pardec.Interfaces.MessageQueue import MemoryTaskQueue class ScatteringQueueManager(MemoryTaskQueue):
43
226
754
10
32
wylswz/ParallelDecoder
pardec/MQ.py
Python
ScatteringQueueManager
ScatteringQueueManager
11
121
11
11
8aa78e75453cdaf45d367439b96f5e5d1cd064d9
bigcode/the-stack
train
4c0c86b0243d2ea3fecc5b52
train
class
class GetHeightmap(ConnectionBasedTransport): def __init__(self): super(GetHeightmap, self).__init__() self.heightmap_frame = rospy.get_param('~heightmap_frame') # Size[m] of each height map pixel self.voxel_size = rospy.get_param('~voxel_size') self.listener = tf.Transfor...
class GetHeightmap(ConnectionBasedTransport):
def __init__(self): super(GetHeightmap, self).__init__() self.heightmap_frame = rospy.get_param('~heightmap_frame') # Size[m] of each height map pixel self.voxel_size = rospy.get_param('~voxel_size') self.listener = tf.TransformListener() self.tft = tf.TransformerRO...
#!/usr/bin/env python import cv_bridge import message_filters import numpy as np import rospy import tf # For debug # import grasp_fusion_lib from jsk_topic_tools import ConnectionBasedTransport from jsk_topic_tools.log_utils import logerr_throttle from sensor_msgs.msg import CameraInfo from sensor_msgs.msg import Im...
93
256
1,364
8
84
pazeshun/jsk_apc
demos/grasp_fusion/ros/grasp_fusion/node_scripts/get_heightmap.py
Python
GetHeightmap
GetHeightmap
19
172
19
20
e7a9570bf0daae78f56e1bcfaf8b51dd516557b0
bigcode/the-stack
train
3fc13ae83826b8c6a10c6e58
train
class
class Character(object): def __init__(self, x, y, health, damage, speed, regeneration, mana): self.x = x self.y = y self.health = health self.damage = damage self.speed = speed self.regeneration = regeneration self.mana = mana self.object = {}
class Character(object):
def __init__(self, x, y, health, damage, speed, regeneration, mana): self.x = x self.y = y self.health = health self.damage = damage self.speed = speed self.regeneration = regeneration self.mana = mana self.object = {}
class Character(object):
4
64
74
4
0
Victor804/Sky-s-Land
game_files/character.py
Python
Character
Character
1
10
1
1
95273750abc426a0046bdcbe1c0e9bf4809277c1
bigcode/the-stack
train
9634d8aab29837a219c29347
train
function
def _promote_args(fun_name, *args): """Convenience function to apply Numpy argument shape and dtype promotion.""" _check_arraylike(fun_name, *args) return _promote_shapes(*_promote_dtypes(*args))
def _promote_args(fun_name, *args):
"""Convenience function to apply Numpy argument shape and dtype promotion.""" _check_arraylike(fun_name, *args) return _promote_shapes(*_promote_dtypes(*args))
pos, arg = next((i, arg) for i, arg in enumerate(args) if not_array(arg)) msg = "{} requires ndarray or scalar arguments, got {} at position {}." raise TypeError(msg.format(fun_name, type(arg), pos)) def _promote_args(fun_name, *args):
64
64
52
11
53
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_promote_args
_promote_args
184
187
184
184
c6dc8f10d710a054122dc1da701ac613c12f78f7
bigcode/the-stack
train
4f886218e54c423168678ca7
train
function
@_wraps(onp.power) def power(x1, x2): x1 = asarray(x1) x2 = asarray(x2) x1, x2 = _promote_args_like(onp.power, x1, x2) dtype = lax._dtype(x1) if not issubdtype(dtype, integer): return lax.pow(x1, x2) # Integer power => use binary exponentiation. # TODO(phawkins): add integer pow support to XLA. bi...
@_wraps(onp.power) def power(x1, x2):
x1 = asarray(x1) x2 = asarray(x2) x1, x2 = _promote_args_like(onp.power, x1, x2) dtype = lax._dtype(x1) if not issubdtype(dtype, integer): return lax.pow(x1, x2) # Integer power => use binary exponentiation. # TODO(phawkins): add integer pow support to XLA. bits = 6 # Anything more would overflow...
2) != lax.sign(mod)) mod = lax.select(ind, mod + x1, mod) div = lax.select(ind, div - _constant_like(div, 1), div) return lax.round(div), mod @_wraps(onp.power) def power(x1, x2):
64
64
216
16
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
power
power
394
413
394
395
6b2ee97a00f221e595d9a6a46eed5d4d5eeb5235
bigcode/the-stack
train
329c353d3ba6c712189ebb1f
train
function
@_wraps(onp.sinc) def sinc(x): x, = _promote_to_result_dtype(onp.sinc, x) pi_x = lax.mul(lax._const(x, pi), x) return where(lax.eq(x, lax._const(x, 0)), lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))
@_wraps(onp.sinc) def sinc(x):
x, = _promote_to_result_dtype(onp.sinc, x) pi_x = lax.mul(lax._const(x, pi), x) return where(lax.eq(x, lax._const(x, 0)), lax._const(x, 1), lax.div(lax.sin(pi_x), pi_x))
*y) @_wraps(onp.reciprocal) def reciprocal(x): x, = _promote_to_result_dtype(onp.reciprocal, x) return lax.div(lax._const(x, 1), x) @_wraps(onp.sinc) def sinc(x):
64
64
82
13
51
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
sinc
sinc
506
511
506
507
b9113f2672b691e93d314692452cf1bd5d3957c8
bigcode/the-stack
train
5f2c241b2c2c375665e23726
train
function
@_wraps(onp.nan_to_num) def nan_to_num(x, copy=True): del copy if iscomplexobj(x): raise ValueError("nan_to_num is not well defined for complex types") info = finfo(xla_bridge.canonicalize_dtype(_dtype(x))) x = where(isnan(x), _constant_like(x, 0), x) x = where(isposinf(x), _constant_like(x, info.max), x)...
@_wraps(onp.nan_to_num) def nan_to_num(x, copy=True):
del copy if iscomplexobj(x): raise ValueError("nan_to_num is not well defined for complex types") info = finfo(xla_bridge.canonicalize_dtype(_dtype(x))) x = where(isnan(x), _constant_like(x, 0), x) x = where(isposinf(x), _constant_like(x, info.max), x) x = where(isneginf(x), _constant_like(x, info.min),...
posneginf, -inf)) @_wraps(onp.isnan) def isnan(x): return lax.bitwise_and(lax.bitwise_not(isfinite(x)), lax.bitwise_not(isinf(x))) @_wraps(onp.nan_to_num) def nan_to_num(x, copy=True):
64
64
123
19
45
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
nan_to_num
nan_to_num
851
860
851
852
a1dbd562b1dac29571b7455213e3819d452187e6
bigcode/the-stack
train
57fe94b426673f1fec32ab79
train
function
@_wraps(onp.floor_divide) def floor_divide(x1, x2): x1, x2 = _promote_args("floor_divide", x1, x2) dtype = _dtype(x1) if issubdtype(dtype, integer): quotient = lax.div(x1, x2) select = logical_and(lax.sign(x1) != lax.sign(x2), lax.rem(x1, x2) != 0) # TODO(mattjj): investigate why subtracting a scalar ...
@_wraps(onp.floor_divide) def floor_divide(x1, x2):
x1, x2 = _promote_args("floor_divide", x1, x2) dtype = _dtype(x1) if issubdtype(dtype, integer): quotient = lax.div(x1, x2) select = logical_and(lax.sign(x1) != lax.sign(x2), lax.rem(x1, x2) != 0) # TODO(mattjj): investigate why subtracting a scalar was causing promotion return where(select, quoti...
umpy result dtype, as a # way to check whether Python 3 style division is active in Numpy result_dtype = _result_dtype(onp.divide, x1, x2) if onp.issubdtype(result_dtype, onp.integer): return floor_divide(x1, x2) else: return true_divide(x1, x2) @_wraps(onp.floor_divide) def floor_divide(x1, x2):
101
101
338
20
81
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
floor_divide
floor_divide
349
370
349
350
9c49385e98daa80403b4fa9b8bf26f1b7e69d74f
bigcode/the-stack
train
6771b9a1336619b293c4959f
train
function
def _is_advanced_int_indexer_without_slices(idx): """Returns True iff idx is an advanced int idx without slice/ellipsis/none.""" if _is_advanced_int_indexer(idx): if isinstance(idx, (tuple, list)): return not _any(e is None or e is Ellipsis or isinstance(e, slice) for e in idx) e...
def _is_advanced_int_indexer_without_slices(idx):
"""Returns True iff idx is an advanced int idx without slice/ellipsis/none.""" if _is_advanced_int_indexer(idx): if isinstance(idx, (tuple, list)): return not _any(e is None or e is Ellipsis or isinstance(e, slice) for e in idx) else: return True
a sequence if it's a tuple return _all(e is None or e is Ellipsis or isinstance(e, slice) or _is_int_arraylike(e) for e in idx) else: return _is_int_arraylike(idx) def _is_advanced_int_indexer_without_slices(idx):
64
64
84
13
51
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_is_advanced_int_indexer_without_slices
_is_advanced_int_indexer_without_slices
2,098
2,105
2,098
2,098
175131ec5390bc05fdbbe8417eb3142499c471a2
bigcode/the-stack
train
0e8ebe1c3a173ef42f880d00
train
function
@_wraps(onp.vdot) def vdot(a, b): if onp.issubdtype(_dtype(a), onp.complexfloating): a = conj(a) return dot(a.ravel(), b.ravel())
@_wraps(onp.vdot) def vdot(a, b):
if onp.issubdtype(_dtype(a), onp.complexfloating): a = conj(a) return dot(a.ravel(), b.ravel())
new_m = () if a_is_vec else (m,) new_n = () if b_is_vec else (n,) return lax.reshape(result, batch_shape + new_m + new_n) else: return result @_wraps(onp.vdot) def vdot(a, b):
64
64
51
16
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
vdot
vdot
1,467
1,471
1,467
1,468
c04dcc4242d73429820a78de9454e08fb2198ada
bigcode/the-stack
train
0c7195d3beebc671b19e0f8b
train
function
@_wraps(onp.reciprocal) def reciprocal(x): x, = _promote_to_result_dtype(onp.reciprocal, x) return lax.div(lax._const(x, 1), x)
@_wraps(onp.reciprocal) def reciprocal(x):
x, = _promote_to_result_dtype(onp.reciprocal, x) return lax.div(lax._const(x, 1), x)
y)) @_wraps(onp.hypot) def hypot(x, y): x, y = _promote_to_result_dtype(onp.hypot, x, y) return lax.sqrt(x*x + y*y) @_wraps(onp.reciprocal) def reciprocal(x):
64
64
49
15
49
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
reciprocal
reciprocal
500
503
500
501
a87a4ec41a8b92c8b2f688c6f4ebd4fc2d7f4292
bigcode/the-stack
train
f111a655ab4bc9c62c662d94
train
function
@_wraps(onp.full_like) def full_like(a, fill_value, dtype=None): return lax.full_like(a, fill_value, dtype)
@_wraps(onp.full_like) def full_like(a, fill_value, dtype=None):
return lax.full_like(a, fill_value, dtype)
dtype=None): return lax.full_like(x, 1, dtype) @_wraps(onp.full) def full(shape, fill_value, dtype=None): return lax.full(shape, fill_value, dtype) @_wraps(onp.full_like) def full_like(a, fill_value, dtype=None):
64
64
32
20
44
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
full_like
full_like
1,217
1,219
1,217
1,218
95d2efef0ce9e4b57dc0746bf2c64c6caf09892b
bigcode/the-stack
train
b43125cd9d5d9be8ac06cc00
train
function
@_wraps(onp.logaddexp2) def logaddexp2(x1, x2): x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp2, x1, x2)) amax = lax.max(x1, x2) return lax.add(amax, log2(lax.add(exp2(lax.sub(x1, amax)), exp2(lax.sub(x2, amax)))))
@_wraps(onp.logaddexp2) def logaddexp2(x1, x2):
x1, x2 = _promote_shapes(*_promote_to_result_dtype(onp.logaddexp2, x1, x2)) amax = lax.max(x1, x2) return lax.add(amax, log2(lax.add(exp2(lax.sub(x1, amax)), exp2(lax.sub(x2, amax)))))
1, x2) return lax.add(amax, lax.log(lax.add(lax.exp(lax.sub(x1, amax)), lax.exp(lax.sub(x2, amax))))) @_wraps(onp.logaddexp2) def logaddexp2(x1, x2):
63
64
100
22
42
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
logaddexp2
logaddexp2
424
429
424
425
3a07681a4ade5dbcd1b7e76220f1035102649257
bigcode/the-stack
train
9911f62f1e0fb0f1ec415cac
train
function
def _constant_like(x, const): return onp.array(const, dtype=_dtype(x))
def _constant_like(x, const):
return onp.array(const, dtype=_dtype(x))
def _promote_args_like(op, *args): """Convenience function to apply shape and dtype promotion to result type.""" _check_arraylike(op.__name__, *args) return _promote_shapes(*_promote_to_result_dtype(op, *args)) def _constant_like(x, const):
64
64
20
8
56
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_constant_like
_constant_like
196
197
196
196
411bbdc7c200501f1ace440cc41f5f0f9c1be733
bigcode/the-stack
train
aa1b8d304d7926e5727acc4b
train
function
@_wraps(onp.true_divide) def true_divide(x1, x2): result_dtype = _result_dtype(onp.true_divide, x1, x2) x1, x2 = _promote_shapes(x1, x2) return lax.div(lax.convert_element_type(x1, result_dtype), lax.convert_element_type(x2, result_dtype))
@_wraps(onp.true_divide) def true_divide(x1, x2):
result_dtype = _result_dtype(onp.true_divide, x1, x2) x1, x2 = _promote_shapes(x1, x2) return lax.div(lax.convert_element_type(x1, result_dtype), lax.convert_element_type(x2, result_dtype))
p.logical_not, lax.bitwise_not) logical_or = _logical_op(onp.logical_or, lax.bitwise_or) logical_xor = _logical_op(onp.logical_xor, lax.bitwise_xor) @_wraps(onp.true_divide) def true_divide(x1, x2):
64
64
82
20
44
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
true_divide
true_divide
330
335
330
331
d1a449fb88a3a3c55027e07fe5204ce1a1fca004
bigcode/the-stack
train
2be857658cd1a50e335e9eb1
train
function
@_wraps(onp.mean) def mean(a, axis=None, dtype=None, out=None, keepdims=False): if out is not None: raise ValueError("mean does not support the `out` argument.") if axis is None: normalizer = size(a) else: normalizer = onp.prod(onp.take(shape(a), axis)) if dtype is None: if (onp.issubdtype(_dty...
@_wraps(onp.mean) def mean(a, axis=None, dtype=None, out=None, keepdims=False):
if out is not None: raise ValueError("mean does not support the `out` argument.") if axis is None: normalizer = size(a) else: normalizer = onp.prod(onp.take(shape(a), axis)) if dtype is None: if (onp.issubdtype(_dtype(a), onp.bool_) or onp.issubdtype(_dtype(a), onp.integer)): dtyp...
, lax.bitwise_and, True, _cast_to_bool) any = sometrue = _make_reduction(onp.any, lax.bitwise_or, False, _cast_to_bool) @_wraps(onp.mean) def mean(a, axis=None, dtype=None, out=None, keepdims=False):
64
64
186
25
39
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
mean
mean
918
937
918
919
29e7e352fe56100c19dbe0c44b29190506333ca2
bigcode/the-stack
train
a9b4086f5c34828cc404d7e9
train
function
@_wraps(onp.rot90) def rot90(m, k=1, axes=(0, 1)): ax1, ax2 = axes if ax1 % m.ndim == ax2 % m.ndim: raise ValueError("Axes must be different") # same as numpy error k = k % 4 if k == 0: return m elif k == 2: return flip(flip(m, ax1), ax2) else: perm = list(range(m.ndim)) perm[ax1], perm...
@_wraps(onp.rot90) def rot90(m, k=1, axes=(0, 1)):
ax1, ax2 = axes if ax1 % m.ndim == ax2 % m.ndim: raise ValueError("Axes must be different") # same as numpy error k = k % 4 if k == 0: return m elif k == 2: return flip(flip(m, ax1), ax2) else: perm = list(range(m.ndim)) perm[ax1], perm[ax2] = perm[ax2], perm[ax1] if k == 1: r...
(onp.transpose) def transpose(x, axis=None): axis = onp.arange(ndim(x))[::-1] if axis is None else axis return lax.transpose(x, axis) @_wraps(onp.rot90) def rot90(m, k=1, axes=(0, 1)):
64
64
174
25
39
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
rot90
rot90
520
536
520
521
8b52c4cef27204161046352ea5fc43c95fd821e0
bigcode/the-stack
train
b327544d48d2866e0135c03d
train
function
@_wraps(onp.triu) def triu(m, k=0): mask = tri(*shape(m)[-2:], k=k - 1, dtype=bool) return where(mask, zeros_like(m), m)
@_wraps(onp.triu) def triu(m, k=0):
mask = tri(*shape(m)[-2:], k=k - 1, dtype=bool) return where(mask, zeros_like(m), m)
@_wraps(onp.tril) def tril(m, k=0): mask = tri(*shape(m)[-2:], k=k, dtype=bool) return where(mask, m, zeros_like(m)) @_wraps(onp.triu) def triu(m, k=0):
64
64
50
18
46
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
triu
triu
1,330
1,333
1,330
1,331
20a8b3c4e572998c8248c3fdbbb8bf06bfd4b948
bigcode/the-stack
train
37b9e7c6fed7cb9e40c62281
train
function
def _comparison_op(numpy_fn, lax_fn): def fn(x, y): x, y = _promote_args(numpy_fn.__name__, x, y) # Comparison on complex types are defined as a lexicographic ordering on # the (real, imag) pair. if issubdtype(_dtype(x), complexfloating): rx = lax.real(x) ry = lax.real(y) return lax...
def _comparison_op(numpy_fn, lax_fn):
def fn(x, y): x, y = _promote_args(numpy_fn.__name__, x, y) # Comparison on complex types are defined as a lexicographic ordering on # the (real, imag) pair. if issubdtype(_dtype(x), complexfloating): rx = lax.real(x) ry = lax.real(y) return lax.select(lax.eq(rx, ry), lax_fn(lax.ima...
2, True) minimum = _one_to_one_binop(onp.minimum, lax.min) maximum = _one_to_one_binop(onp.maximum, lax.max) float_power = _one_to_one_binop(onp.float_power, lax.pow, True) def _comparison_op(numpy_fn, lax_fn):
64
64
138
11
53
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_comparison_op
_comparison_op
296
307
296
296
371538d082cddf25206676c950a251b818e326fb
bigcode/the-stack
train
919cfd9a9e70270698d0c6e8
train
function
def _float_divmod(x1, x2): # see float_divmod in floatobject.c of CPython mod = lax.rem(x1, x2) div = lax.div(lax.sub(x1, mod), x2) ind = lax.bitwise_and(mod != 0, lax.sign(x2) != lax.sign(mod)) mod = lax.select(ind, mod + x1, mod) div = lax.select(ind, div - _constant_like(div, 1), div) return lax.roun...
def _float_divmod(x1, x2): # see float_divmod in floatobject.c of CPython
mod = lax.rem(x1, x2) div = lax.div(lax.sub(x1, mod), x2) ind = lax.bitwise_and(mod != 0, lax.sign(x2) != lax.sign(mod)) mod = lax.select(ind, mod + x1, mod) div = lax.select(ind, div - _constant_like(div, 1), div) return lax.round(div), mod
1), onp.integer): return floor_divide(x1, x2), remainder(x1, x2) else: return _float_divmod(x1, x2) def _float_divmod(x1, x2): # see float_divmod in floatobject.c of CPython
64
64
115
25
39
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_float_divmod
_float_divmod
382
391
382
383
455dc1ec0d287748b2ba462e7ef82b86c1c8e2ea
bigcode/the-stack
train
302f7a789141337918159559
train
function
@_wraps(onp.roll) def roll(a, shift, axis=None): a = asarray(a) a_shape = shape(a) if axis is None: return lax.reshape(roll(ravel(a), shift, axis=0), a_shape) a_ndim = len(a_shape) if isinstance(shift, tuple): if isinstance(axis, tuple): if len(axis) != len(shift): msg = "Mismatched len...
@_wraps(onp.roll) def roll(a, shift, axis=None):
a = asarray(a) a_shape = shape(a) if axis is None: return lax.reshape(roll(ravel(a), shift, axis=0), a_shape) a_ndim = len(a_shape) if isinstance(shift, tuple): if isinstance(axis, tuple): if len(axis) != len(shift): msg = "Mismatched lengths between shift ({}) and axis ({}) for np.roll...
.") if axis is None: return argsort(a.ravel(), 0) else: axis = axis % ndim(a) iota = lax.broadcasted_iota(onp.int64, shape(a), axis) _, perm = lax.sort_key_val(a, iota, dimension=axis) return perm @_wraps(onp.roll) def roll(a, shift, axis=None):
86
86
287
17
68
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
roll
roll
1,863
1,895
1,863
1,864
ac4d630f81a29d571a52578e5d122b07d2c73240
bigcode/the-stack
train
8ebacebadd7aa918edd9b17e
train
function
@_wraps(onp.trace) def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None): if out: raise NotImplementedError("The 'out' argument to trace is not supported.") a_shape = shape(a) if dtype is None: dtype = _dtype(a) if issubdtype(dtype, integer): default_int = xla_bridge.canonicalize_dtype...
@_wraps(onp.trace) def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
if out: raise NotImplementedError("The 'out' argument to trace is not supported.") a_shape = shape(a) if dtype is None: dtype = _dtype(a) if issubdtype(dtype, integer): default_int = xla_bridge.canonicalize_dtype(onp.int_) if iinfo(dtype).bits < iinfo(default_int).bits: dtype = de...
, k=0): mask = tri(*shape(m)[-2:], k=k - 1, dtype=bool) return where(mask, zeros_like(m), m) @_wraps(onp.trace) def trace(a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
69
69
232
32
37
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
trace
trace
1,336
1,357
1,336
1,337
6323b985d1869ce8356c42070c3bf4035644c1b9
bigcode/the-stack
train
cb171ce24640b00b937971b5
train
function
@_wraps(onp.isclose) def isclose(a, b, rtol=1e-05, atol=1e-08): a, b = _promote_args("isclose", asarray(a), asarray(b)) dtype = _dtype(a) if issubdtype(dtype, inexact): if issubdtype(dtype, complexfloating): dtype = _result_dtype(real, a) rtol = lax.convert_element_type(rtol, dtype) atol = lax.c...
@_wraps(onp.isclose) def isclose(a, b, rtol=1e-05, atol=1e-08):
a, b = _promote_args("isclose", asarray(a), asarray(b)) dtype = _dtype(a) if issubdtype(dtype, inexact): if issubdtype(dtype, complexfloating): dtype = _result_dtype(real, a) rtol = lax.convert_element_type(rtol, dtype) atol = lax.convert_element_type(atol, dtype) out = lax.le( lax.abs...
if i not in source] for dest, src in sorted(zip(destination, source)): perm.insert(dest, src) return lax.transpose(a, perm) @_wraps(onp.isclose) def isclose(a, b, rtol=1e-05, atol=1e-08):
64
64
172
31
33
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
isclose
isclose
668
682
668
669
94ede1840fada83417f831807a20f0f64eb328c7
bigcode/the-stack
train
659d44887a3f18613b102d22
train
function
@_wraps(onp.divide) def divide(x1, x2): # decide whether to perform integer division based on Numpy result dtype, as a # way to check whether Python 3 style division is active in Numpy result_dtype = _result_dtype(onp.divide, x1, x2) if onp.issubdtype(result_dtype, onp.integer): return floor_divide(x1, x2) ...
@_wraps(onp.divide) def divide(x1, x2): # decide whether to perform integer division based on Numpy result dtype, as a # way to check whether Python 3 style division is active in Numpy
result_dtype = _result_dtype(onp.divide, x1, x2) if onp.issubdtype(result_dtype, onp.integer): return floor_divide(x1, x2) else: return true_divide(x1, x2)
_dtype), lax.convert_element_type(x2, result_dtype)) @_wraps(onp.divide) def divide(x1, x2): # decide whether to perform integer division based on Numpy result dtype, as a # way to check whether Python 3 style division is active in Numpy
64
64
108
51
13
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
divide
divide
338
346
338
341
c87af177e10eda9d46ff15cece84c7189f618421
bigcode/the-stack
train
290a241a904d421c756e28b8
train
function
@_wraps(onp.sort) def sort(a, axis=-1, kind='quicksort', order=None): if kind != 'quicksort': warnings.warn("'kind' argument to sort is ignored.") if order is not None: raise ValueError("'order' argument to sort is not supported.") if axis is None: return lax.sort(a.ravel(), 0) else: return lax...
@_wraps(onp.sort) def sort(a, axis=-1, kind='quicksort', order=None):
if kind != 'quicksort': warnings.warn("'kind' argument to sort is ignored.") if order is not None: raise ValueError("'order' argument to sort is not supported.") if axis is None: return lax.sort(a.ravel(), 0) else: return lax.sort(a, axis % ndim(a))
)).max mask_idxs = where(lax._eq_meet(a, op(a, axis, keepdims=True)), idxs, maxval) return min(mask_idxs, axis) @_wraps(onp.sort) def sort(a, axis=-1, kind='quicksort', order=None):
64
64
98
25
39
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
sort
sort
1,834
1,844
1,834
1,835
3d535521c68946ec016df80f45af389a7ae08d6d
bigcode/the-stack
train
2c96393da0b32e01ab8fd20a
train
function
def _one_to_one_unop(numpy_fn, lax_fn, promote_like=False): if promote_like: fn = lambda x: lax_fn(lax.convert_element_type(x, _result_dtype(numpy_fn, x))) else: fn = lambda x: lax_fn(x) return _wraps(numpy_fn)(fn)
def _one_to_one_unop(numpy_fn, lax_fn, promote_like=False):
if promote_like: fn = lambda x: lax_fn(lax.convert_element_type(x, _result_dtype(numpy_fn, x))) else: fn = lambda x: lax_fn(x) return _wraps(numpy_fn)(fn)
name__, body=body)) op.__name__ = fun.__name__ op.__doc__ = docstr finally: return op return wrap ### implementations of numpy functions in terms of lax def _one_to_one_unop(numpy_fn, lax_fn, promote_like=False):
64
64
71
18
45
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_one_to_one_unop
_one_to_one_unop
239
244
239
239
c7ebf88a3d9fc553b739896c7f8949410852086d
bigcode/the-stack
train
36f22d400f4e6a582e27f267
train
function
@_wraps(onp.flip) def flip(m, axis): # Negative axes wrap around if axis < 0: rank = len(m.shape) assert axis >= -rank, "axis={} is invalid for the {}-dimensional input array".format(axis, rank) return lax.rev(m, [axis % rank]) else: return lax.rev(m, [axis])
@_wraps(onp.flip) def flip(m, axis): # Negative axes wrap around
if axis < 0: rank = len(m.shape) assert axis >= -rank, "axis={} is invalid for the {}-dimensional input array".format(axis, rank) return lax.rev(m, [axis % rank]) else: return lax.rev(m, [axis])
[ax2], perm[ax1] if k == 1: return transpose(flip(m, ax2), perm) else: return flip(transpose(m, perm), ax2) @_wraps(onp.flip) def flip(m, axis): # Negative axes wrap around
64
64
84
21
43
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
flip
flip
539
547
539
541
b9f7ef879fc0e1c199c522dd1da3ed32c8f9dcc0
bigcode/the-stack
train
4b08a9a1e25f0769ffa2c0c5
train
function
def _one_to_one_binop(numpy_fn, lax_fn, promote_like=False): if promote_like: fn = lambda x, y: lax_fn(*_promote_args_like(numpy_fn, x, y)) else: fn = lambda x, y: lax_fn(*_promote_args(numpy_fn.__name__, x, y)) return _wraps(numpy_fn)(fn)
def _one_to_one_binop(numpy_fn, lax_fn, promote_like=False):
if promote_like: fn = lambda x, y: lax_fn(*_promote_args_like(numpy_fn, x, y)) else: fn = lambda x, y: lax_fn(*_promote_args(numpy_fn.__name__, x, y)) return _wraps(numpy_fn)(fn)
= lambda x: lax_fn(lax.convert_element_type(x, _result_dtype(numpy_fn, x))) else: fn = lambda x: lax_fn(x) return _wraps(numpy_fn)(fn) def _one_to_one_binop(numpy_fn, lax_fn, promote_like=False):
64
64
86
18
46
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_one_to_one_binop
_one_to_one_binop
246
251
246
246
98f88d1317bcafebaaf8ec7b1afff00deff68c95
bigcode/the-stack
train
4c1f9698ef6faa67266f3c61
train
function
@_wraps(onp.real) def real(x): return lax.real(x) if iscomplexobj(x) else x
@_wraps(onp.real) def real(x):
return lax.real(x) if iscomplexobj(x) else x
): return lax.conj(x) if iscomplexobj(x) else x conj = conjugate @_wraps(onp.imag) def imag(x): return lax.imag(x) if iscomplexobj(x) else zeros_like(x) @_wraps(onp.real) def real(x):
64
64
27
12
52
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
real
real
571
573
571
572
269808841ebc0ba3fadf0cb0564efd395a8a0eb1
bigcode/the-stack
train
a3ca64f8cfc62bd60cfd3717
train
function
@_wraps(onp.tri) def tri(N, M=None, k=0, dtype=None): M = M if M is not None else N dtype = dtype or float32 x = arange(N, dtype=int32) y = arange(M, dtype=int32) mask = lax.ge( (lax.broadcast_in_dim(x, shape=(N, M), broadcast_dimensions=(0,)) + int32(k)), lax.broadcast(y, [N])) return la...
@_wraps(onp.tri) def tri(N, M=None, k=0, dtype=None):
M = M if M is not None else N dtype = dtype or float32 x = arange(N, dtype=int32) y = arange(M, dtype=int32) mask = lax.ge( (lax.broadcast_in_dim(x, shape=(N, M), broadcast_dimensions=(0,)) + int32(k)), lax.broadcast(y, [N])) return lax.convert_element_type(mask, dtype)
+ 2, num_dims + 1))) a_shape[axis] *= repeats return lax.reshape( lax.broadcast_in_dim(a, broadcast_shape, broadcast_dims), a_shape) @_wraps(onp.tri) def tri(N, M=None, k=0, dtype=None):
64
64
116
23
41
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
tri
tri
1,311
1,321
1,311
1,312
30708759aa81ed721bfd8343009b889ad6a1f5f9
bigcode/the-stack
train
9a1b742481c9c0d2974d16cf
train
function
def _promote_dtypes(*args): """Convenience function to apply Numpy argument dtype promotion.""" # TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing. if len(args) < 2: return args else: from_dtypes = (x if type(x) in _builtin_numeric_types else _dtype(x) for x ...
def _promote_dtypes(*args):
"""Convenience function to apply Numpy argument dtype promotion.""" # TODO(dougalm,mattjj): This is a performance bottleneck. Consider memoizing. if len(args) < 2: return args else: from_dtypes = (x if type(x) in _builtin_numeric_types else _dtype(x) for x in args) to_dtype = xla_...
] nd = len(lax.broadcast_shapes(*shapes)) return [lax.reshape(arg, (1,) * (nd - len(shp)) + shp) if len(shp) != nd else arg for arg, shp in zip(args, shapes)] def _promote_dtypes(*args):
64
64
134
9
55
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_promote_dtypes
_promote_dtypes
146
156
146
146
7ecc9bcb42c27d7d6c75975c817ac6c91e54f136
bigcode/the-stack
train
7b498c6cdeb75d37e9fe45bc
train
function
@_wraps(onp.hstack) def hstack(tup): arrs = [atleast_1d(m) for m in tup] if arrs[0].ndim == 1: return concatenate(arrs, 0) return concatenate(arrs, 1)
@_wraps(onp.hstack) def hstack(tup):
arrs = [atleast_1d(m) for m in tup] if arrs[0].ndim == 1: return concatenate(arrs, 0) return concatenate(arrs, 1)
axis % ndim(arrays[0])) @_wraps(onp.vstack) def vstack(tup): return concatenate([atleast_2d(m) for m in tup], axis=0) row_stack = vstack @_wraps(onp.hstack) def hstack(tup):
64
64
63
15
48
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
hstack
hstack
1,117
1,122
1,117
1,118
fe535f9a7ffaa1dbec71218ac61b0afa367805bf
bigcode/the-stack
train
acc3dbc5a790780f96f9b44b
train
function
@_wraps(onp.tril) def tril(m, k=0): mask = tri(*shape(m)[-2:], k=k, dtype=bool) return where(mask, m, zeros_like(m))
@_wraps(onp.tril) def tril(m, k=0):
mask = tri(*shape(m)[-2:], k=k, dtype=bool) return where(mask, m, zeros_like(m))
.ge( (lax.broadcast_in_dim(x, shape=(N, M), broadcast_dimensions=(0,)) + int32(k)), lax.broadcast(y, [N])) return lax.convert_element_type(mask, dtype) @_wraps(onp.tril) def tril(m, k=0):
64
64
46
17
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
tril
tril
1,324
1,327
1,324
1,325
ce2667ad108c4eb4a726717afee0d7b094719c57
bigcode/the-stack
train
83c8d9a2dcb1b02ffe2e8a90
train
function
def _reduction_init_val(a, init_val): a_dtype = xla_bridge.canonicalize_dtype(_dtype(a)) try: return onp.array(init_val, dtype=a_dtype) except OverflowError: assert onp.issubdtype(a_dtype, onp.integer) sign, iinfo = onp.sign(init_val), onp.iinfo(a_dtype) return onp.array(iinfo.min if sign < 0 else...
def _reduction_init_val(a, init_val):
a_dtype = xla_bridge.canonicalize_dtype(_dtype(a)) try: return onp.array(init_val, dtype=a_dtype) except OverflowError: assert onp.issubdtype(a_dtype, onp.integer) sign, iinfo = onp.sign(init_val), onp.iinfo(a_dtype) return onp.array(iinfo.min if sign < 0 else iinfo.max, dtype=a_dtype)
, list)): return onp.mod(onp.asarray(axis), ndim(a)) elif isinstance(axis, int): return onp.mod([axis], ndim(a)) else: raise TypeError("Unexpected type of axis argument: {}".format(type(axis))) def _reduction_init_val(a, init_val):
64
64
102
11
53
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_reduction_init_val
_reduction_init_val
899
906
899
899
2fbc8324f5ff0c87bbef61e50351ecd1c322117e
bigcode/the-stack
train
8ff9117d81dffaeb6ba089fc
train
function
def _swap_args(f): return lambda x, y: f(y, x)
def _swap_args(f):
return lambda x, y: f(y, x)
### add method and operator overloads to arraylike classes # We add operator overloads to DeviceArray and ShapedArray. These method and # operator overloads mainly just forward calls to the corresponding lax_numpy # functions, which can themselves handle instances from any of these classes. def _swap_args(f):
64
64
18
6
58
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_swap_args
_swap_args
2,205
2,206
2,205
2,205
032c2445fddb76c2080fc17c6007379fbcd71761
bigcode/the-stack
train
238080efe4b47bd1e608a5c4
train
function
@_wraps(onp.vander) def vander(x, N=None, increasing=False): x = asarray(x) dtype = _dtype(x) if ndim(x) != 1: raise ValueError("x must be a one-dimensional array") x_shape = shape(x) N = N or x_shape[0] if N < 0: raise ValueError("N must be nonnegative") iota = lax.iota(dtype, N) if not increa...
@_wraps(onp.vander) def vander(x, N=None, increasing=False):
x = asarray(x) dtype = _dtype(x) if ndim(x) != 1: raise ValueError("x must be a one-dimensional array") x_shape = shape(x) N = N or x_shape[0] if N < 0: raise ValueError("N must be nonnegative") iota = lax.iota(dtype, N) if not increasing: iota = lax.sub(lax._const(iota, N - 1), iota) re...
roadcast = lax.broadcast_in_dim( b, b_broadcast_shape, list(range(b_ndims - d)) + b_broadcast_dims) return lax.reshape(a_broadcast * b_broadcast, out_shape) @_wraps(onp.vander) def vander(x, N=None, increasing=False):
64
64
138
20
44
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
vander
vander
1,787
1,802
1,787
1,788
78a2986e18c370a722856445da6b9e25b4a50fee
bigcode/the-stack
train
c06494a4d53933691dedef34
train
function
def _is_int_arraylike(x): """Returns True if x is array-like with integer dtype, False otherwise.""" return (isinstance(x, int) and not isinstance(x, bool) or onp.issubdtype(getattr(x, "dtype", None), onp.integer) or isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))
def _is_int_arraylike(x):
"""Returns True if x is array-like with integer dtype, False otherwise.""" return (isinstance(x, int) and not isinstance(x, bool) or onp.issubdtype(getattr(x, "dtype", None), onp.integer) or isinstance(x, (list, tuple)) and _all(_is_int_arraylike(e) for e in x))
/none.""" if _is_advanced_int_indexer(idx): if isinstance(idx, (tuple, list)): return not _any(e is None or e is Ellipsis or isinstance(e, slice) for e in idx) else: return True def _is_int_arraylike(x):
64
64
86
8
55
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_is_int_arraylike
_is_int_arraylike
2,108
2,112
2,108
2,108
25de89179f79c31e22199a1f6b7c15f8cc146753
bigcode/the-stack
train
0a5ca7d42a88cdc51ed99d0e
train
function
@partial(jit, static_argnums=(1,)) def _einsum(operands, contractions): operands = list(_promote_dtypes(*operands)) sum = lambda x, axes: lax.reduce(x, onp.array(0, x.dtype), lax.add, axes) def sum_uniques(operand, names, uniques): if uniques: axes = [names.index(name) for name in uniques] operan...
@partial(jit, static_argnums=(1,)) def _einsum(operands, contractions):
operands = list(_promote_dtypes(*operands)) sum = lambda x, axes: lax.reduce(x, onp.array(0, x.dtype), lax.add, axes) def sum_uniques(operand, names, uniques): if uniques: axes = [names.index(name) for name in uniques] operand = sum(operand, axes) names = removechars(names, uniques) ret...
tuples of ints.") raise TypeError(msg) @_wraps(onp.einsum) def einsum(*operands, **kwargs): optimize = kwargs.pop('optimize', 'auto') optimize = 'greedy' if optimize is True else optimize if kwargs: msg = 'invalid keyword arguments for einsum: {}' raise TypeError(msg.format(', '.join(kwargs))) # usi...
256
256
1,265
21
235
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_einsum
_einsum
1,525
1,641
1,525
1,526
6f8cb84ea365856e71ab31d677c0531aca49e22a
bigcode/the-stack
train
861aa385d832e4adf39826c8
train
function
@_wraps(onp.log2) def log2(x): x, = _promote_to_result_dtype(onp.log2, x) return lax.div(lax.log(x), lax.log(_constant_like(x, 2)))
@_wraps(onp.log2) def log2(x):
x, = _promote_to_result_dtype(onp.log2, x) return lax.div(lax.log(x), lax.log(_constant_like(x, 2)))
2)) amax = lax.max(x1, x2) return lax.add(amax, log2(lax.add(exp2(lax.sub(x1, amax)), exp2(lax.sub(x2, amax))))) @_wraps(onp.log2) def log2(x):
63
64
50
14
50
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
log2
log2
432
435
432
433
1c5231afcd207a4caea26db74c4dee354a40b82e
bigcode/the-stack
train
f82eb778cc223264a7bbf701
train
function
@_wraps(onp.sqrt) def sqrt(x): x, = _promote_to_result_dtype(onp.sqrt, x) return power(x, _constant_like(x, 0.5))
@_wraps(onp.sqrt) def sqrt(x):
x, = _promote_to_result_dtype(onp.sqrt, x) return power(x, _constant_like(x, 0.5))
, x2) return lax.rem(lax.add(lax.rem(x1, x2), x2), x2) mod = remainder fmod = _wraps(onp.fmod)(lambda x, y: lax.rem(x, y)) @_wraps(onp.sqrt) def sqrt(x):
64
64
43
12
52
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
sqrt
sqrt
458
461
458
459
80811d2ecf808f3d0f88e0bc24d0d326fb6282e2
bigcode/the-stack
train
49fa1dd00629b7ac73ec6a47
train
function
@_wraps(onp.diag) def diag(v, k=0): v_shape = shape(v) if len(v_shape) == 1: zero = lambda x: lax.full_like(x, shape=(), fill_value=0) n = v_shape[0] + _abs(k) v = lax.pad(v, zero(v), ((_max(0, k), _max(0, -k), 0),)) return where(eye(n, k=k, dtype=bool), v, zeros_like(v)) elif len(v_shape) == 2: ...
@_wraps(onp.diag) def diag(v, k=0):
v_shape = shape(v) if len(v_shape) == 1: zero = lambda x: lax.full_like(x, shape=(), fill_value=0) n = v_shape[0] + _abs(k) v = lax.pad(v, zero(v), ((_max(0, k), _max(0, -k), 0),)) return where(eye(n, k=k, dtype=bool), v, zeros_like(v)) elif len(v_shape) == 2: return diagonal(v, offset=k) el...
(a_shape[axis1] + _min(offset, 0), a_shape[axis2] - _max(offset, 0))) return lax.slice_in_dim(d, 0, diag_size, axis=-1) @_wraps(onp.diag) def diag(v, k=0):
64
64
153
17
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
diag
diag
1,387
1,398
1,387
1,388
f0abb28fdd13aa7ab48e2735d242c24689a585ff
bigcode/the-stack
train
ded53bc1204351e41dd32930
train
function
@_wraps(onp.column_stack) def column_stack(tup): arrays = [] for v in tup: arr = array(v) if arr.ndim < 2: arr = arr.reshape((-1, 1)) arrays.append(arr) return concatenate(arrays, 1)
@_wraps(onp.column_stack) def column_stack(tup):
arrays = [] for v in tup: arr = array(v) if arr.ndim < 2: arr = arr.reshape((-1, 1)) arrays.append(arr) return concatenate(arrays, 1)
s, 0) return concatenate(arrs, 1) @_wraps(onp.dstack) def dstack(tup): return concatenate([atleast_3d(m) for m in tup], axis=2) @_wraps(onp.column_stack) def column_stack(tup):
64
64
65
15
49
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
column_stack
column_stack
1,130
1,138
1,130
1,131
9d1bdc9fef66357fb1e7a13296187c8e207269a4
bigcode/the-stack
train
d1786f3264ad2a6c675f7942
train
function
@_wraps(onp.eye) def eye(N, M=None, k=None, dtype=onp.dtype("float64")): M = N if M is None else M if N < 0 or M < 0: msg = "negative dimensions are not allowed, got {} and {}" raise ValueError(msg.format(N, M)) if k is None: return lax.broadcasted_eye(dtype, (N, M), (0, 1)) else: k_dtype = _dty...
@_wraps(onp.eye) def eye(N, M=None, k=None, dtype=onp.dtype("float64")):
M = N if M is None else M if N < 0 or M < 0: msg = "negative dimensions are not allowed, got {} and {}" raise ValueError(msg.format(N, M)) if k is None: return lax.broadcasted_eye(dtype, (N, M), (0, 1)) else: k_dtype = _dtype(k) if not onp.issubdtype(k_dtype, onp.integer): msg = "eye a...
return lax.full(shape, 1, dtype) # We can't create uninitialized arrays in XLA; use zeros for empty. empty_like = zeros_like empty = zeros @_wraps(onp.eye) def eye(N, M=None, k=None, dtype=onp.dtype("float64")):
64
64
210
28
35
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
eye
eye
1,238
1,253
1,238
1,239
85326178d73ef599d3dedb8e8c1e53c59204e56c
bigcode/the-stack
train
cd3f97d28a4a7bec8ec1843b
train
function
@_wraps(onp.std) def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False): if out is not None: raise ValueError("std does not support the `out` argument.") return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))
@_wraps(onp.std) def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
if out is not None: raise ValueError("std does not support the `out` argument.") return sqrt(var(a, axis=axis, dtype=dtype, ddof=ddof, keepdims=keepdims))
(centered): centered = lax.abs(centered) return mean(lax.mul(centered, centered), axis, dtype=dtype, keepdims=keepdims) @_wraps(onp.std) def std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=False):
64
64
78
30
34
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
std
std
957
961
957
958
0aa78c10cb68b42740fb6f86806b071cb119db32
bigcode/the-stack
train
3b8de70ecf94f6d2e45aec37
train
function
@_wraps(onp.inner) def inner(a, b): if ndim(a) == 0 or ndim(b) == 0: return a * b return tensordot(a, b, (-1, -1))
@_wraps(onp.inner) def inner(a, b):
if ndim(a) == 0 or ndim(b) == 0: return a * b return tensordot(a, b, (-1, -1))
axis on identifier strings.""" chars = [c for i, c in enumerate(s) if i not in src] for i, j in sorted(zip(dst, src)): chars.insert(i, s[j]) return ''.join(chars) @_wraps(onp.inner) def inner(a, b):
64
64
51
14
50
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
inner
inner
1,696
1,700
1,696
1,697
685b2f9eb2d0180784e918b1d81ceb0df909bec1
bigcode/the-stack
train
39b17b0eb85d5c1a48fcf311
train
function
@_wraps(onp.diagonal) def diagonal(a, offset=0, axis1=0, axis2=1): a_shape = shape(a) a_ndims = len(a_shape) # Move the two dimensions to the end. axis1 %= a_ndims axis2 %= a_ndims perm = [i for i in range(a_ndims) if i != axis1 and i != axis2] perm = perm + [axis1, axis2] a = lax.transpose(a, perm) ...
@_wraps(onp.diagonal) def diagonal(a, offset=0, axis1=0, axis2=1):
a_shape = shape(a) a_ndims = len(a_shape) # Move the two dimensions to the end. axis1 %= a_ndims axis2 %= a_ndims perm = [i for i in range(a_ndims) if i != axis1 and i != axis2] perm = perm + [axis1, axis2] a = lax.transpose(a, perm) # Mask out the diagonal and reduce over one of the axes a = wher...
[axis1], a_shape[axis2], k=offset, dtype=bool), a, zeros_like(a)) return sum(a, axis=(-2, -1), dtype=dtype) diag_indices = onp.diag_indices @_wraps(onp.diagonal) def diagonal(a, offset=0, axis1=0, axis2=1):
77
77
259
27
49
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
diagonal
diagonal
1,363
1,384
1,363
1,364
3d9e1091e29f2cd7828d634e090619afeab00ef6
bigcode/the-stack
train
ec8aa0d01e6ab10ee83bbf5a
train
function
@_wraps(onp.moveaxis) def moveaxis(a, source, destination): source = onp.mod(source, ndim(a)).reshape(-1) destination = onp.mod(destination, ndim(a)).reshape(-1) if len(source) != len(destination): raise ValueError("Inconsistent number of elements: {} vs {}" .format(len(source), len(desti...
@_wraps(onp.moveaxis) def moveaxis(a, source, destination):
source = onp.mod(source, ndim(a)).reshape(-1) destination = onp.mod(destination, ndim(a)).reshape(-1) if len(source) != len(destination): raise ValueError("Inconsistent number of elements: {} vs {}" .format(len(source), len(destination))) perm = [i for i in range(ndim(a)) if i not in so...
axis1, axis2): perm = onp.arange(ndim(a)) perm[axis1], perm[axis2] = perm[axis2], perm[axis1] return lax.transpose(a, perm) @_wraps(onp.moveaxis) def moveaxis(a, source, destination):
64
64
127
18
46
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
moveaxis
moveaxis
655
665
655
656
175b5efeaa2e2ec8784a71cbf55da4840f9ab134
bigcode/the-stack
train
5db2a425249ddbb5016f9a18
train
function
@_wraps(onp.full) def full(shape, fill_value, dtype=None): return lax.full(shape, fill_value, dtype)
@_wraps(onp.full) def full(shape, fill_value, dtype=None):
return lax.full(shape, fill_value, dtype)
(x, dtype=None): return lax.full_like(x, 0, dtype) @_wraps(onp.ones_like) def ones_like(x, dtype=None): return lax.full_like(x, 1, dtype) @_wraps(onp.full) def full(shape, fill_value, dtype=None):
64
64
29
18
46
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
full
full
1,212
1,214
1,212
1,213
a67c01967c15362898985233bdc5767f83cf3337
bigcode/the-stack
train
773274a672567dd14da261db
train
function
@_wraps(onp.isfinite) def isfinite(x): dtype = _dtype(x) if issubdtype(dtype, floating): return lax.is_finite(x) elif issubdtype(dtype, complexfloating): return lax.bitwise_and(lax.is_finite(real(x)), lax.is_finite(imag(x))) else: return full_like(x, True, dtype=bool_)
@_wraps(onp.isfinite) def isfinite(x):
dtype = _dtype(x) if issubdtype(dtype, floating): return lax.is_finite(x) elif issubdtype(dtype, complexfloating): return lax.bitwise_and(lax.is_finite(real(x)), lax.is_finite(imag(x))) else: return full_like(x, True, dtype=bool_)
are not # preserved by XLA/LLVM, and the behavior of inf/nan values is unpredictable. # To disable fast math mode on CPU, set the environment variable # XLA_FLAGS=--xla_cpu_enable_fast_math=false. @_wraps(onp.isfinite) def isfinite(x):
64
64
85
14
50
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
isfinite
isfinite
813
821
813
814
642c7ca05ab7ae9a5e31304dc6aa43dab4502ca8
bigcode/the-stack
train
f395ebe5d42d1d92ed805f24
train
function
@_wraps(onp.concatenate) def concatenate(arrays, axis=0): if not arrays: raise ValueError("Need at least one array to concatenate.") if ndim(arrays[0]) == 0: raise ValueError("Zero-dimensional arrays cannot be concatenated.") return lax.concatenate(_promote_dtypes(*arrays), axis % ndim(arrays[0]))
@_wraps(onp.concatenate) def concatenate(arrays, axis=0):
if not arrays: raise ValueError("Need at least one array to concatenate.") if ndim(arrays[0]) == 0: raise ValueError("Zero-dimensional arrays cannot be concatenated.") return lax.concatenate(_promote_dtypes(*arrays), axis % ndim(arrays[0]))
in arrays: if shape(a) != shape0: raise ValueError("All input arrays must have the same shape.") new_arrays.append(reshape(a, new_shape)) return concatenate(new_arrays, axis=axis) @_wraps(onp.concatenate) def concatenate(arrays, axis=0):
64
64
80
17
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
concatenate
concatenate
1,102
1,108
1,102
1,103
7c66571c354e3d4dbeb2298068af696452e4f9fe
bigcode/the-stack
train
472ab6f1e41744d1f64844d2
train
function
@_wraps(onp.iscomplex) def iscomplex(x): i = imag(x) return lax.ne(i, lax._const(i, 0))
@_wraps(onp.iscomplex) def iscomplex(x):
i = imag(x) return lax.ne(i, lax._const(i, 0))
.imag) def imag(x): return lax.imag(x) if iscomplexobj(x) else zeros_like(x) @_wraps(onp.real) def real(x): return lax.real(x) if iscomplexobj(x) else x @_wraps(onp.iscomplex) def iscomplex(x):
64
64
34
14
49
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
iscomplex
iscomplex
576
579
576
577
bd3da8ca8dc0deb4cc1a72f17f855d05fb3fe339
bigcode/the-stack
train
6783cc407cc45d13be1dca6f
train
function
@_wraps(onp.dot) def dot(a, b): # pylint: disable=missing-docstring _check_arraylike("dot", a, b) a, b = _promote_dtypes(a, b) a_ndim, b_ndim = ndim(a), ndim(b) if a_ndim == 0 or b_ndim == 0: return lax.mul(a, b) if _max(a_ndim, b_ndim) <= 2: return lax.dot(a, b) if b_ndim == 1: contract_dims ...
@_wraps(onp.dot) def dot(a, b): # pylint: disable=missing-docstring
_check_arraylike("dot", a, b) a, b = _promote_dtypes(a, b) a_ndim, b_ndim = ndim(a), ndim(b) if a_ndim == 0 or b_ndim == 0: return lax.mul(a, b) if _max(a_ndim, b_ndim) <= 2: return lax.dot(a, b) if b_ndim == 1: contract_dims = ((a_ndim - 1,), (0,)) else: contract_dims = ((a_ndim - 1,), (...
if axis is None: return concatenate([ravel(arr), ravel(values)], 0) else: return concatenate([arr, values], axis=axis) ### Tensor contraction operations @_wraps(onp.dot) def dot(a, b): # pylint: disable=missing-docstring
64
64
183
24
39
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
dot
dot
1,425
1,440
1,425
1,426
89f60c439557fd051c35df9b9222d4cca03b2d6c
bigcode/the-stack
train
998bb3fca20d778898ab4a76
train
class
class ndarray(six.with_metaclass(_ArrayMeta, onp.ndarray)): pass
class ndarray(six.with_metaclass(_ArrayMeta, onp.ndarray)):
pass
.""" def __instancecheck__(self, instance): try: return isinstance(instance.aval, _arraylike_types) except AttributeError: return isinstance(instance, _arraylike_types) # pylint: disable=invalid-name class ndarray(six.with_metaclass(_ArrayMeta, onp.ndarray)):
64
64
18
15
48
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
ndarray
ndarray
83
84
83
83
c483fe6e9a51c40eebb9a72cb91faaba9bf3275f
bigcode/the-stack
train
f2a7d05128887f2121a0538b
train
function
@_wraps(onp.outer) def outer(a, b, out=None): if out: raise NotImplementedError("The 'out' argument to outer is not supported.") return ravel(a)[:, None] * ravel(b)
@_wraps(onp.outer) def outer(a, b, out=None):
if out: raise NotImplementedError("The 'out' argument to outer is not supported.") return ravel(a)[:, None] * ravel(b)
(onp.inner) def inner(a, b): if ndim(a) == 0 or ndim(b) == 0: return a * b return tensordot(a, b, (-1, -1)) @_wraps(onp.outer) def outer(a, b, out=None):
64
64
52
17
47
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
outer
outer
1,703
1,707
1,703
1,704
95a13af26f2aa5d36cecbdf1033f6f14ed84a9a9
bigcode/the-stack
train
6be1fb4ea5523efaf2967d8f
train
function
def _promote_args_like(op, *args): """Convenience function to apply shape and dtype promotion to result type.""" _check_arraylike(op.__name__, *args) return _promote_shapes(*_promote_to_result_dtype(op, *args))
def _promote_args_like(op, *args):
"""Convenience function to apply shape and dtype promotion to result type.""" _check_arraylike(op.__name__, *args) return _promote_shapes(*_promote_to_result_dtype(op, *args))
)) def _promote_args(fun_name, *args): """Convenience function to apply Numpy argument shape and dtype promotion.""" _check_arraylike(fun_name, *args) return _promote_shapes(*_promote_dtypes(*args)) def _promote_args_like(op, *args):
64
64
56
11
53
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_promote_args_like
_promote_args_like
190
193
190
190
fd6457da221b304c5430133a5fb828b82737dd9d
bigcode/the-stack
train
ad5f18736bc1f944ef958c75
train
function
def _is_slice_none(idx): """Return True if idx is equal to slice(None), False otherwise.""" if isinstance(idx, slice): return idx.start is None and idx.stop is None and idx.step is None
def _is_slice_none(idx):
"""Return True if idx is equal to slice(None), False otherwise.""" if isinstance(idx, slice): return idx.start is None and idx.stop is None and idx.step is None
0].ndim out = moveaxis(out, list(range(naxes)), list(range(start, start + naxes))) return out msg = "Indexing mode not yet supported. Open a feature request!\n{}" raise IndexError(msg.format(idx)) def _is_slice_none(idx):
64
64
46
7
57
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_is_slice_none
_is_slice_none
2,080
2,083
2,080
2,080
d932083af811089b071eaa63d45ae1e25e7f740a
bigcode/the-stack
train
a65451d29d1253a5d888c392
train
function
def _make_cumulative_reduction(onp_reduction, window_reduce, init_val, squash_nan=False): @_wraps(onp_reduction) def cumulative_reduction(a, axis=None, dtype=None): if axis is None or isscalar(a): a = ravel(a) axis = 0 a_shape = list(shape(a)) num_dims = len(a...
def _make_cumulative_reduction(onp_reduction, window_reduce, init_val, squash_nan=False): @_wraps(onp_reduction)
def cumulative_reduction(a, axis=None, dtype=None): if axis is None or isscalar(a): a = ravel(a) axis = 0 a_shape = list(shape(a)) num_dims = len(a_shape) if axis < 0: axis = axis + num_dims if axis < 0 or axis >= num_dims: raise ValueError( "axis {} is out of b...
-inf, nan_if_all_nan=True) nansum = _make_nan_reduction(onp.nansum, sum, 0, nan_if_all_nan=False) nanprod = _make_nan_reduction(onp.nanprod, prod, 1, nan_if_all_nan=False) def _make_cumulative_reduction(onp_reduction, window_reduce, init_val, squash_nan=False): @_wraps(onp_reduction)
91
91
306
32
59
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_make_cumulative_reduction
_make_cumulative_reduction
1,003
1,039
1,003
1,005
d5e3921fea66558fb4e9c2c454ac49fea61ec60e
bigcode/the-stack
train
4dd4256d0cc2a2e062904e6a
train
function
def broadcast_to(arr, shape): """Like Numpy's broadcast_to but doesn't necessarily return views.""" arr = arr if isinstance(arr, ndarray) or isscalar(arr) else array(arr) if _shape(arr) != shape: # TODO(mattjj): revise this to call lax.broadcast_in_dim rather than # lax.broadcast and lax.transpose lax...
def broadcast_to(arr, shape):
"""Like Numpy's broadcast_to but doesn't necessarily return views.""" arr = arr if isinstance(arr, ndarray) or isscalar(arr) else array(arr) if _shape(arr) != shape: # TODO(mattjj): revise this to call lax.broadcast_in_dim rather than # lax.broadcast and lax.transpose lax.broadcast_shapes(shape, _shap...
apes)) == 1: return [arg if isinstance(arg, ndarray) or isscalar(arg) else array(arg) for arg in args] result_shape = lax.broadcast_shapes(*shapes) return [broadcast_to(arg, result_shape) for arg in args] def broadcast_to(arr, shape):
64
64
214
7
57
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
broadcast_to
broadcast_to
721
739
721
721
1988078a142af3b41603681a540553d638a25bc9
bigcode/the-stack
train
17f8b349ac52c6feb176e74d
train
function
def _static_idx(idx, size): """Helper function to compute the static slice start/limit/stride values.""" indices = onp.arange(size)[idx] # get shape statically if not len(indices): # pylint: disable=g-explicit-length-test return 0, 0, 1, False # sliced to size zero start, stop_inclusive = indices[0], ind...
def _static_idx(idx, size):
"""Helper function to compute the static slice start/limit/stride values.""" indices = onp.arange(size)[idx] # get shape statically if not len(indices): # pylint: disable=g-explicit-length-test return 0, 0, 1, False # sliced to size zero start, stop_inclusive = indices[0], indices[-1] step = 1 if idx.s...
] + colons + idx[ellipsis_index + 1:] elif len_without_none < arr.ndim: colons = (slice(None),) * (arr.ndim - len_without_none) idx = tuple(idx) + colons return idx def _static_idx(idx, size):
64
64
163
8
55
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
_static_idx
_static_idx
2,135
2,147
2,135
2,135
cc948c57493d03423d5db99f0e0fc12a5251a25c
bigcode/the-stack
train
d4eb006161aa8c5f5aa94c6c
train
function
@_wraps(onp.tensordot) def tensordot(a, b, axes=2): _check_arraylike("tensordot", a, b) if not (ndim(a) >= 1 and ndim(b) >= 1): msg = "tensordot requires a.ndim and b.dim to be at least 1, got {} and {}." raise TypeError(msg.format(ndim(a), ndim(b))) if type(axes) is int: a, b = _promote_dtypes(a, b)...
@_wraps(onp.tensordot) def tensordot(a, b, axes=2):
_check_arraylike("tensordot", a, b) if not (ndim(a) >= 1 and ndim(b) >= 1): msg = "tensordot requires a.ndim and b.dim to be at least 1, got {} and {}." raise TypeError(msg.format(ndim(a), ndim(b))) if type(axes) is int: a, b = _promote_dtypes(a, b) a_reshape = lax.reshape(a, (_prod(a.shape[:-axe...
batch_dims))) if a_is_vec or b_is_vec: m, n = shape(result)[-2:] new_m = () if a_is_vec else (m,) new_n = () if b_is_vec else (n,) return lax.reshape(result, batch_shape + new_m + new_n) else: return result @_wraps(onp.vdot) def vdot(a, b): if onp.issubdtype(_dtype(a), onp.complexfloating)...
146
146
487
23
123
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
tensordot
tensordot
1,474
1,503
1,474
1,475
ef3ca5e12afe469f1d7ede3510c919a1773c2b28
bigcode/the-stack
train
7edd6662ec4e484f7251e163
train
function
@_wraps(onp.reshape) def reshape(a, newshape, order="C"): try: return a.reshape(newshape, order=order) except AttributeError: return _reshape(a, newshape, order=order)
@_wraps(onp.reshape) def reshape(a, newshape, order="C"):
try: return a.reshape(newshape, order=order) except AttributeError: return _reshape(a, newshape, order=order)
): dtype = xla_bridge.canonicalize_dtype(float64) re = lax.convert_element_type(re, dtype) im = lax.convert_element_type(im, dtype) return lax.atan2(im, re) @_wraps(onp.reshape) def reshape(a, newshape, order="C"):
64
64
51
19
45
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
reshape
reshape
599
604
599
600
419057d4d4fb60c750f43ce459c728ff5289d877
bigcode/the-stack
train
7aa9c215ffbcce2599eb24d4
train
function
@_wraps(onp.allclose) def allclose(a, b, rtol=1e-05, atol=1e-08): return all(isclose(a, b, rtol, atol))
@_wraps(onp.allclose) def allclose(a, b, rtol=1e-05, atol=1e-08):
return all(isclose(a, b, rtol, atol))
=axis, keepdims=keepdims) y = amin(a, axis=axis, keepdims=keepdims) return lax.sub(x, y) @_wraps(onp.allclose) def allclose(a, b, rtol=1e-05, atol=1e-08):
64
64
45
31
33
navneet-nmk/jax
jax/numpy/lax_numpy.py
Python
allclose
allclose
973
975
973
974
f5e7777b71ebaffc00e318ee944e36dbc7242712
bigcode/the-stack
train