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
ea350fb245f7ca7f900058b3
train
function
def test_full(): # shape/len, value[, dtype=] assert cupy.full(10, 5).tolist() == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] assert cupy.full(10, 5, dtype=int).tolist() == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] assert cupy.full((2, 3), 5).tolist() == [[5, 5, 5], [5, 5, 5]] assert cupy.full((2, 3), 5, dtype=int).tolist(...
def test_full(): # shape/len, value[, dtype=]
assert cupy.full(10, 5).tolist() == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] assert cupy.full(10, 5, dtype=int).tolist() == [5, 5, 5, 5, 5, 5, 5, 5, 5, 5] assert cupy.full((2, 3), 5).tolist() == [[5, 5, 5], [5, 5, 5]] assert cupy.full((2, 3), 5, dtype=int).tolist() == [[5, 5, 5], [5, 5, 5]]
dtype=int).shape == (10,) assert cupy.empty((2, 3)).shape == (2, 3) assert cupy.empty((2, 3), dtype=int).shape == (2, 3) def test_full(): # shape/len, value[, dtype=]
64
64
179
15
49
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_full
test_full
81
86
81
82
5474981fa0edd6abbdc5479e5a039e6f78aa7e66
bigcode/the-stack
train
6652a612816eee1f6e18e276
train
function
def test_searchsorted(): # haystack, needle, side="right" np_haystack = numpy.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]) np_needle = numpy.array([2.1, 5.3, 5.5, 5.6, 3.8, 7.0, 2.1, 3.3, -2.0, 15.0]) assert numpy.searchsorted(np_haystack, np_needle).tolist() == [2, 5, 5, 6, 4, 7, 2, 3, 0, ...
def test_searchsorted(): # haystack, needle, side="right"
np_haystack = numpy.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9]) np_needle = numpy.array([2.1, 5.3, 5.5, 5.6, 3.8, 7.0, 2.1, 3.3, -2.0, 15.0]) assert numpy.searchsorted(np_haystack, np_needle).tolist() == [2, 5, 5, 6, 4, 7, 2, 3, 0, 10] cp_haystack = cupy.array([0.0, 1.1, 2.2, 3.3, 4.4, 5....
, 4.0, 5.0]), cupy.array([1, 2, 3, 4, 5])) def test_size(): # array assert numpy.size(numpy.arange(2*3*5).reshape(2, 3, 5)) == cupy.size(cupy.arange(2*3*5).reshape(2, 3, 5)) def test_searchsorted(): # haystack, needle, side="right"
102
102
343
16
86
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_searchsorted
test_searchsorted
135
143
135
136
2921c5da14271371e5d483776546244b14101484
bigcode/the-stack
train
c169cc8012ff9ffb8b002d46
train
function
def test_cumsum(): # arrays[, out=] np_prefixsum = numpy.empty(5) assert numpy.cumsum([3, 5, 5, 0, 2], out=np_prefixsum).tolist() == [3, 8, 13, 13, 15] assert np_prefixsum.tolist() == [3, 8, 13, 13, 15] cp_prefixsum = cupy.empty(5) assert cupy.cumsum(cupy.array([3, 5, 5, 0, 2]), out=cp_prefixsu...
def test_cumsum(): # arrays[, out=]
np_prefixsum = numpy.empty(5) assert numpy.cumsum([3, 5, 5, 0, 2], out=np_prefixsum).tolist() == [3, 8, 13, 13, 15] assert np_prefixsum.tolist() == [3, 8, 13, 13, 15] cp_prefixsum = cupy.empty(5) assert cupy.cumsum(cupy.array([3, 5, 5, 0, 2]), out=cp_prefixsum).tolist() == [3, 8, 13, 13, 15] as...
assert cupy.searchsorted(cp_haystack, cp_needle).tolist() == [2, 5, 5, 6, 4, 7, 2, 3, 0, 10] ############################ manipulation def test_cumsum(): # arrays[, out=]
64
64
170
12
51
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_cumsum
test_cumsum
148
156
148
149
b46f4cb1ec887d5b0f34940728e31b0b1c6859c4
bigcode/the-stack
train
384d2ffb87ebffada5e4e974
train
function
def test_bitwise_or(): # array1, array2[, out=output] np_array1 = numpy.array([0, 0, 1, 1, 4, 7, 0, 1], dtype=np.uint8) np_array2 = numpy.array([0, 1, 0, 1, 4, 4, 0, 5], dtype=np.uint8) np_arrayout = numpy.zeros(8, dtype=np.uint8) cp_array1 = cupy.array([0, 0, 1, 1, 4, 7, 0, 1], dtype=np.uint8) ...
def test_bitwise_or(): # array1, array2[, out=output]
np_array1 = numpy.array([0, 0, 1, 1, 4, 7, 0, 1], dtype=np.uint8) np_array2 = numpy.array([0, 1, 0, 1, 4, 4, 0, 5], dtype=np.uint8) np_arrayout = numpy.zeros(8, dtype=np.uint8) cp_array1 = cupy.array([0, 0, 1, 1, 4, 7, 0, 1], dtype=np.uint8) cp_array2 = cupy.array([0, 1, 0, 1, 4, 4, 0, 5], dtype=np...
]), numpy.array([1.0, 10.0, 7.0])).tolist() == cupy.true_divide(cupy.array([1.1, 2.2, 3.3]), cupy.array([1.0, 10.0, 7.0])).tolist() def test_bitwise_or(): # array1, array2[, out=output]
82
82
275
18
64
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_bitwise_or
test_bitwise_or
259
272
259
260
038beae09878b59ca23d62e5f5355be2c85ece80
bigcode/the-stack
train
5b0223e0f4ce8c17a0323f5e
train
function
def test_zeros(): # shape/len[, dtype=] assert cupy.zeros(10).tolist() == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert cupy.zeros(10, dtype=int).tolist() == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert cupy.zeros((2, 3)).tolist() == [[0, 0, 0], [0, 0, 0]] assert cupy.zeros((2, 3), dtype=int).tolist() == [[0, 0, 0...
def test_zeros(): # shape/len[, dtype=]
assert cupy.zeros(10).tolist() == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert cupy.zeros(10, dtype=int).tolist() == [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] assert cupy.zeros((2, 3)).tolist() == [[0, 0, 0], [0, 0, 0]] assert cupy.zeros((2, 3), dtype=int).tolist() == [[0, 0, 0], [0, 0, 0]]
=] np_array = numpy.frombuffer(b"one two three", dtype=np.uint8) cp_array = cupy.frombuffer(b"one two three", dtype=np.uint8) assert cp_array.tolist() == np_array.tolist() def test_zeros(): # shape/len[, dtype=]
64
64
166
14
50
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_zeros
test_zeros
57
62
57
58
c5b46136fff79531c66a30d62f0bdb554b4ca185
bigcode/the-stack
train
e24845ccf8f5e9b0958bf956
train
function
def test_vstack(): # arrays assert numpy.vstack([numpy.array([[0, 1, 2], [3, 4, 5]]), numpy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [0.0, 1.1, 2.2], [3.3, 4.4, 5.5]] assert cupy.vstack([cupy.array([[0, 1, 2], [3, 4, 5]]), cupy.array([[0.0, 1.1, 2.2], [3.3, ...
def test_vstack(): # arrays
assert numpy.vstack([numpy.array([[0, 1, 2], [3, 4, 5]]), numpy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[0.0, 1.0, 2.0], [3.0, 4.0, 5.0], [0.0, 1.1, 2.2], [3.3, 4.4, 5.5]] assert cupy.vstack([cupy.array([[0, 1, 2], [3, 4, 5]]), cupy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[0.0,...
5]])]).tolist() == [[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], [[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]]] def test_vstack(): # arrays
76
76
256
9
66
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_vstack
test_vstack
208
211
208
209
102538d5bfbbb608a77c76ea570b57525f6c4d90
bigcode/the-stack
train
b4a38aec3adc8493a129f961
train
function
def test_packbits(): # array assert numpy.packbits(numpy.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0])).tolist() == [29, 8] assert cupy.packbits(cupy.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0])).tolist() == [29, 8]
def test_packbits(): # array
assert numpy.packbits(numpy.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0])).tolist() == [29, 8] assert cupy.packbits(cupy.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0])).tolist() == [29, 8]
1.0, 2.0], [3.0, 4.0, 5.0], [0.0, 1.1, 2.2], [3.3, 4.4, 5.5]] def test_packbits(): # array
63
64
128
9
54
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_packbits
test_packbits
214
217
214
215
40977ae2d78213071c7793a3e4fed040f3051a8b
bigcode/the-stack
train
a175f7d5d1dda93fa3f5f061
train
function
def test_concatenate(): # arrays np_one = numpy.array([2, 3, 5, 7, 9]) np_two = numpy.array([11.1, 13.3, 17.7, 19.9]) np_three = numpy.array([21, 23, 29]) assert numpy.concatenate([np_one, np_two, np_three]).tolist() == [2, 3, 5, 7, 9, 11.1, 13.3, 17.7, 19.9, 21, 23, 29] cp_one = cupy.array([2,...
def test_concatenate(): # arrays
np_one = numpy.array([2, 3, 5, 7, 9]) np_two = numpy.array([11.1, 13.3, 17.7, 19.9]) np_three = numpy.array([21, 23, 29]) assert numpy.concatenate([np_one, np_two, np_three]).tolist() == [2, 3, 5, 7, 9, 11.1, 13.3, 17.7, 19.9, 21, 23, 29] cp_one = cupy.array([2, 3, 5, 7, 9]) cp_two = cupy.array...
2.2, 6.6, 2.2, 3.3, 0.0, 1.1, 5.5])).tolist() == [0.0, 1.1, 2.2, 3.3, 5.5, 6.6] def test_concatenate(): # arrays
78
78
260
10
68
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_concatenate
test_concatenate
175
185
175
176
91d55c86111f8ae7c91664f32a24d7de492ec5e3
bigcode/the-stack
train
e4b667f8fd07ff55bd49f30e
train
function
def test_array_equal(): # array1, array2 assert numpy.array_equal(numpy.array([1.0, 2.0, 3.0, 4.0, 5.0]), numpy.array([1, 2, 3, 4, 5])) assert cupy.array_equal(cupy.array([1.0, 2.0, 3.0, 4.0, 5.0]), cupy.array([1, 2, 3, 4, 5]))
def test_array_equal(): # array1, array2
assert numpy.array_equal(numpy.array([1.0, 2.0, 3.0, 4.0, 5.0]), numpy.array([1, 2, 3, 4, 5])) assert cupy.array_equal(cupy.array([1.0, 2.0, 3.0, 4.0, 5.0]), cupy.array([1, 2, 3, 4, 5]))
_a.tolist() assert np_b.tolist() == cp_b.tolist() assert np_x.tolist() == cp_x.tolist() assert np_y.tolist() == cp_y.tolist() assert np_z.tolist() == cp_z.tolist() ############################ testing def test_array_equal(): # array1, array2
64
64
115
13
50
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_array_equal
test_array_equal
124
127
124
125
153ae8a817615187cf02c47634cfeb402fb97ba9
bigcode/the-stack
train
012d46c3704a02d42981cfa0
train
function
def test_unpackbits(): # array assert numpy.unpackbits(numpy.array([29, 8], dtype=np.uint8)).tolist() == [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0] assert cupy.unpackbits(cupy.array([29, 8], dtype=np.uint8)).tolist() == [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]
def test_unpackbits(): # array
assert numpy.unpackbits(numpy.array([29, 8], dtype=np.uint8)).tolist() == [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0] assert cupy.unpackbits(cupy.array([29, 8], dtype=np.uint8)).tolist() == [0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0]
bits(cupy.array([0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0])).tolist() == [29, 8] def test_unpackbits(): # array
64
64
150
9
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_unpackbits
test_unpackbits
220
223
220
221
0f8d735b316acd2430f093802c793f2ffd1abb34
bigcode/the-stack
train
b97b0fc44af84b0f80638564
train
function
def test_array(): # data[, dtype=[, copy=]] cp_array = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5]) np_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5]) assert cp_array.tolist() == np_array.tolist() cp_array = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=int) np_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5....
def test_array(): # data[, dtype=[, copy=]]
cp_array = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5]) np_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5]) assert cp_array.tolist() == np_array.tolist() cp_array = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=int) np_array = numpy.array([1.1, 2.2, 3.3, 4.4, 5.5], dtype=int) assert cp_array.tolist() == n...
.0/blob/master/LICENSE from __future__ import absolute_import import sys import pytest import awkward1 import awkward1.nplike np = awkward1.nplike.NumpyMetadata.instance() numpy = awkward1.nplike.Numpy.instance() cupy = awkward1.nplike.Cupy.instance() ############################ array creation def test_array()...
85
85
285
14
70
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_array
test_array
20
36
20
21
c4ddc2a09e308f89ce635d741fea729de8d241e1
bigcode/the-stack
train
f99e36f01c60d79797649c0a
train
function
def test_repeat(): # array, int # array1, array2 np_one = numpy.array([2.2, 3.3, 5.5, 7.7, 9.9]) np_two = numpy.array([2, 0, 1, 4, 3]) assert numpy.repeat(np_one, 3).tolist() == [2.2, 2.2, 2.2, 3.3, 3.3, 3.3, 5.5, 5.5, 5.5, 7.7, 7.7, 7.7, 9.9, 9.9, 9.9] assert numpy.repeat(np_one, np_two).tolist...
def test_repeat(): # array, int # array1, array2
np_one = numpy.array([2.2, 3.3, 5.5, 7.7, 9.9]) np_two = numpy.array([2, 0, 1, 4, 3]) assert numpy.repeat(np_one, 3).tolist() == [2.2, 2.2, 2.2, 3.3, 3.3, 3.3, 5.5, 5.5, 5.5, 7.7, 7.7, 7.7, 9.9, 9.9, 9.9] assert numpy.repeat(np_one, np_two).tolist() == [2.2, 2.2, 5.5, 7.7, 7.7, 7.7, 7.7, 9.9, 9.9, 9.9] ...
7, 9]) cp_two = cupy.array([11.1, 13.3, 17.7, 19.9]) cp_three = cupy.array([21, 23, 29]) assert cupy.concatenate([cp_one, cp_two, cp_three]).tolist() == [2, 3, 5, 7, 9, 11.1, 13.3, 17.7, 19.9, 21, 23, 29] def test_repeat(): # array, int # array1, array2
128
128
428
18
110
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_repeat
test_repeat
188
199
188
190
20d013910cee603390b8681bd0edbc284f04df81
bigcode/the-stack
train
90a32299057a96cce5852409
train
function
def test_max(): # array assert numpy.max(numpy.array([2, 5, 1, 4])) == cupy.max(cupy.array([2, 5, 1, 4]))
def test_max(): # array
assert numpy.max(numpy.array([2, 5, 1, 4])) == cupy.max(cupy.array([2, 5, 1, 4]))
3, 5, 7])) def test_min(): # array assert numpy.min(numpy.array([2, 5, 1, 4])) == cupy.min(cupy.array([2, 5, 1, 4])) def test_max(): # array
63
64
46
8
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_max
test_max
331
333
331
332
fa3772989ffddc60df7724360ccb80f40c3ffd77
bigcode/the-stack
train
ba01836c2df767a58b5e85fd
train
function
def test_equal(): # array1, array2 assert numpy.equal(numpy.array([3.3, 2.2, 5.5, 2.2, 1.1]), numpy.array([4.4, 2.2, 5.5, 1.1, 5.5])).tolist() == cupy.equal(cupy.array([3.3, 2.2, 5.5, 2.2, 1.1]), cupy.array([4.4, 2.2, 5.5, 1.1, 5.5])).tolist()
def test_equal(): # array1, array2
assert numpy.equal(numpy.array([3.3, 2.2, 5.5, 2.2, 1.1]), numpy.array([4.4, 2.2, 5.5, 1.1, 5.5])).tolist() == cupy.equal(cupy.array([3.3, 2.2, 5.5, 2.2, 1.1]), cupy.array([4.4, 2.2, 5.5, 1.1, 5.5])).tolist()
False, False, True, True]), numpy.array([False, True, False, True])).tolist() == cupy.logical_and(cupy.array([False, False, True, True]), cupy.array([False, True, False, True])).tolist() def test_equal(): # array1, array2
64
64
135
12
52
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_equal
test_equal
280
282
280
281
8287ed3d8dc1bed1a151ad461ceac62fea6110be
bigcode/the-stack
train
88cecea36a05bc610ee5053c
train
function
def test_exp(): # array assert numpy.exp(numpy.array([1, 2, 3, 4, 5])).tolist() == cupy.exp(cupy.array([1, 2, 3, 4, 5])).tolist() assert numpy.exp(numpy.array([1.1, 2.2, 3.3, 4.4, 5.5])).tolist() == cupy.exp(cupy.array([1.1, 2.2, 3.3, 4.4, 5.5])).tolist()
def test_exp(): # array
assert numpy.exp(numpy.array([1, 2, 3, 4, 5])).tolist() == cupy.exp(cupy.array([1, 2, 3, 4, 5])).tolist() assert numpy.exp(numpy.array([1.1, 2.2, 3.3, 4.4, 5.5])).tolist() == cupy.exp(cupy.array([1.1, 2.2, 3.3, 4.4, 5.5])).tolist()
4.4, 9.9, 16.16, 25.25])).tolist() == cupy.sqrt(cupy.array([1.1, 4.4, 9.9, 16.16, 25.25])).tolist() def test_exp(): # array
64
64
124
8
56
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_exp
test_exp
248
251
248
249
e9f5680d110499246abd562eb50ad855c1e2c21b
bigcode/the-stack
train
2de9d188e6d799134a7c3748
train
function
def test_arange(): # stop[, dtype=] # start, stop[, dtype=] # start, stop, step[, dtype=] assert cupy.arange(10).tolist() == numpy.arange(10).tolist() assert cupy.arange(10, 15).tolist() == numpy.arange(10, 15).tolist() assert cupy.arange(10, 30, 5).tolist() == numpy.arange(10, 30, 5).tolist() ...
def test_arange(): # stop[, dtype=] # start, stop[, dtype=] # start, stop, step[, dtype=]
assert cupy.arange(10).tolist() == numpy.arange(10).tolist() assert cupy.arange(10, 15).tolist() == numpy.arange(10, 15).tolist() assert cupy.arange(10, 30, 5).tolist() == numpy.arange(10, 30, 5).tolist() assert cupy.arange(10, dtype=float).dtype.kind == "f" assert cupy.arange(10, 15, dtype=float).d...
, 3), 5, dtype=int).tolist() == [[5, 5, 5], [5, 5, 5]] def test_arange(): # stop[, dtype=] # start, stop[, dtype=] # start, stop, step[, dtype=]
63
64
164
32
31
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_arange
test_arange
89
98
89
92
55bea290295d239bf8681a522f35d8d7a93fdc39
bigcode/the-stack
train
31037691f5b899180f0bb616
train
function
def test_size(): # array assert numpy.size(numpy.arange(2*3*5).reshape(2, 3, 5)) == cupy.size(cupy.arange(2*3*5).reshape(2, 3, 5))
def test_size(): # array
assert numpy.size(numpy.arange(2*3*5).reshape(2, 3, 5)) == cupy.size(cupy.arange(2*3*5).reshape(2, 3, 5))
5])) assert cupy.array_equal(cupy.array([1.0, 2.0, 3.0, 4.0, 5.0]), cupy.array([1, 2, 3, 4, 5])) def test_size(): # array
63
64
56
8
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_size
test_size
130
132
130
131
b7e38a9d8aae597232fecc2a25c7cc858584dbda
bigcode/the-stack
train
560ef93fc0ddd6523d00044e
train
function
def test_true_divide(): # array1, array2 assert numpy.true_divide(numpy.array([1.1, 2.2, 3.3]), numpy.array([1.0, 10.0, 7.0])).tolist() == cupy.true_divide(cupy.array([1.1, 2.2, 3.3]), cupy.array([1.0, 10.0, 7.0])).tolist()
def test_true_divide(): # array1, array2
assert numpy.true_divide(numpy.array([1.1, 2.2, 3.3]), numpy.array([1.0, 10.0, 7.0])).tolist() == cupy.true_divide(cupy.array([1.1, 2.2, 3.3]), cupy.array([1.0, 10.0, 7.0])).tolist()
3.3, 4.4, 5.5])).tolist() == cupy.exp(cupy.array([1.1, 2.2, 3.3, 4.4, 5.5])).tolist() def test_true_divide(): # array1, array2
64
64
101
14
50
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_true_divide
test_true_divide
254
256
254
255
e6dc3deb3e718354513447fe8457f3ef890a2453
bigcode/the-stack
train
1a2079d898f78253a73902e8
train
function
def test_min(): # array assert numpy.min(numpy.array([2, 5, 1, 4])) == cupy.min(cupy.array([2, 5, 1, 4]))
def test_min(): # array
assert numpy.min(numpy.array([2, 5, 1, 4])) == cupy.min(cupy.array([2, 5, 1, 4]))
5, 0, 4])) def test_prod(): # array assert numpy.prod(numpy.array([2, 3, 5, 7])) == cupy.prod(cupy.array([2, 3, 5, 7])) def test_min(): # array
63
64
46
8
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_min
test_min
326
328
326
327
bd6621465b0d1ee8ca7abb1725a9df9d04223827
bigcode/the-stack
train
4f03657fce75be52cc195e7f
train
function
def test_unique(): # array assert numpy.unique(numpy.array([3.3, 2.2, 5.5, 2.2, 6.6, 2.2, 3.3, 0.0, 1.1, 5.5])).tolist() == [0.0, 1.1, 2.2, 3.3, 5.5, 6.6] assert cupy.unique(cupy.array([3.3, 2.2, 5.5, 2.2, 6.6, 2.2, 3.3, 0.0, 1.1, 5.5])).tolist() == [0.0, 1.1, 2.2, 3.3, 5.5, 6.6]
def test_unique(): # array
assert numpy.unique(numpy.array([3.3, 2.2, 5.5, 2.2, 6.6, 2.2, 3.3, 0.0, 1.1, 5.5])).tolist() == [0.0, 1.1, 2.2, 3.3, 5.5, 6.6] assert cupy.unique(cupy.array([3.3, 2.2, 5.5, 2.2, 6.6, 2.2, 3.3, 0.0, 1.1, 5.5])).tolist() == [0.0, 1.1, 2.2, 3.3, 5.5, 6.6]
(cupy.array([3.3, 2.2, 0.0, 5.5, 0.0, 0.0, 2.2])) assert out.tolist() == [0, 1, 3, 6] def test_unique(): # array
64
64
189
8
56
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_unique
test_unique
168
172
168
169
9d781238493a3dac2bebdb812916553e5e5a1996
bigcode/the-stack
train
41872a22f7efc0a64075ac0a
train
function
def test_nonzero(): # array out, = numpy.nonzero(numpy.array([3.3, 2.2, 0.0, 5.5, 0.0, 0.0, 2.2])) assert out.tolist() == [0, 1, 3, 6] out, = cupy.nonzero(cupy.array([3.3, 2.2, 0.0, 5.5, 0.0, 0.0, 2.2])) assert out.tolist() == [0, 1, 3, 6]
def test_nonzero(): # array
out, = numpy.nonzero(numpy.array([3.3, 2.2, 0.0, 5.5, 0.0, 0.0, 2.2])) assert out.tolist() == [0, 1, 3, 6] out, = cupy.nonzero(cupy.array([3.3, 2.2, 0.0, 5.5, 0.0, 0.0, 2.2])) assert out.tolist() == [0, 1, 3, 6]
5, 0, 2]), out=cp_prefixsum).tolist() == [3, 8, 13, 13, 15] assert cp_prefixsum.tolist() == [3, 8, 13, 13, 15] def test_nonzero(): # array
64
64
136
9
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_nonzero
test_nonzero
159
165
159
160
962ba52b8e863d760dc5bc57a565484bd838081b
bigcode/the-stack
train
a2037508e6e6e8126ea0e410
train
function
def test_asarray(): # array[, dtype=] cp_array1 = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5]) cp_array2 = cupy.asarray(cp_array1) cp_array1[2] = 99.9 assert cp_array2[2] == 99.9 cp_array3 = cupy.asarray(cp_array1, dtype=int) assert cp_array3.tolist() == [1, 2, 99, 4, 5]
def test_asarray(): # array[, dtype=]
cp_array1 = cupy.array([1.1, 2.2, 3.3, 4.4, 5.5]) cp_array2 = cupy.asarray(cp_array1) cp_array1[2] = 99.9 assert cp_array2[2] == 99.9 cp_array3 = cupy.asarray(cp_array1, dtype=int) assert cp_array3.tolist() == [1, 2, 99, 4, 5]
2[2] == 99.9 cp_array3 = cupy.array(cp_array1, copy=True) cp_array1[2] = 12.3 assert cp_array3[2] == 99.9 def test_asarray(): # array[, dtype=]
64
64
122
12
51
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_asarray
test_asarray
39
47
39
40
370f4b6826c64e95d6a60af9f91505fd05ce4d9a
bigcode/the-stack
train
f6e77b85fbf9bc4a8b13d546
train
function
def test_prod(): # array assert numpy.prod(numpy.array([2, 3, 5, 7])) == cupy.prod(cupy.array([2, 3, 5, 7]))
def test_prod(): # array
assert numpy.prod(numpy.array([2, 3, 5, 7])) == cupy.prod(cupy.array([2, 3, 5, 7]))
0, 0, 1])) def test_sum(): # array assert numpy.sum(numpy.array([2, 5, 0, 4])) == cupy.sum(cupy.array([2, 5, 0, 4])) def test_prod(): # array
63
64
46
8
55
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_prod
test_prod
321
323
321
322
e585b4cbde34ee3e5667b3c80ce05fbd574e03fb
bigcode/the-stack
train
6a15dd9e953edfd08f885e07
train
function
def test_stack(): # arrays assert numpy.stack([numpy.array([[0, 1, 2], [3, 4, 5]]), numpy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], [[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]]] assert cupy.stack([cupy.array([[0, 1, 2], [3, 4, 5]]), cupy.array([[0.0, 1.1, 2.2], [3.3,...
def test_stack(): # arrays
assert numpy.stack([numpy.array([[0, 1, 2], [3, 4, 5]]), numpy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]], [[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]]] assert cupy.stack([cupy.array([[0, 1, 2], [3, 4, 5]]), cupy.array([[0.0, 1.1, 2.2], [3.3, 4.4, 5.5]])]).tolist() == [[[0...
9.9] assert cupy.repeat(cp_one, cp_two).tolist() == [2.2, 2.2, 5.5, 7.7, 7.7, 7.7, 7.7, 9.9, 9.9, 9.9] def test_stack(): # arrays
77
77
257
8
69
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_stack
test_stack
202
205
202
203
2ae0fccd5234c271f5aecc133c9d373480557e49
bigcode/the-stack
train
e32aa213905e9924dcbac3c3
train
function
def test_empty(): # shape/len[, dtype=] assert cupy.empty(10).shape == (10,) assert cupy.empty(10, dtype=int).shape == (10,) assert cupy.empty((2, 3)).shape == (2, 3) assert cupy.empty((2, 3), dtype=int).shape == (2, 3)
def test_empty(): # shape/len[, dtype=]
assert cupy.empty(10).shape == (10,) assert cupy.empty(10, dtype=int).shape == (10,) assert cupy.empty((2, 3)).shape == (2, 3) assert cupy.empty((2, 3), dtype=int).shape == (2, 3)
1, 1], [1, 1, 1]] assert cupy.ones((2, 3), dtype=int).tolist() == [[1, 1, 1], [1, 1, 1]] def test_empty(): # shape/len[, dtype=]
63
64
83
13
50
uccross/awkward-1.0
tests-cuda/test_0388-abstract-all-uses-of-numpy.py
Python
test_empty
test_empty
73
78
73
74
6f33c3a979c01730fefa09938399912893bd90fd
bigcode/the-stack
train
93744ccda1ac8a1f3577e89e
train
class
class MoE(nn.Module): def __init__(self, dim, num_experts = 16, hidden_dim = None, activation = nn.ReLU, second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, capacity_factor_t...
class MoE(nn.Module):
def __init__(self, dim, num_experts = 16, hidden_dim = None, activation = nn.ReLU, second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, capacity_factor_train = 1.25, c...
)[..., None] * safe_one_hot(position_in_expert_1.long(), expert_capacity)[..., None, :] + gate_2[..., None, None] * mask_2_flat[..., None, None] * F.one_hot(index_2, num_gates)[..., None] * safe_one_hot(position_in_expert_2.long(), expert_capacity)[..., None, ...
118
118
395
6
111
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
MoE
MoE
229
265
229
229
e309bc2f89d7cdb40d4508c094d55b157341031b
bigcode/the-stack
train
db9e172f08db27f76af19060
train
function
def safe_one_hot(indexes, max_length): max_index = indexes.max() + 1 return F.one_hot(indexes, max(max_index + 1, max_length))[..., :max_length]
def safe_one_hot(indexes, max_length):
max_index = indexes.max() + 1 return F.one_hot(indexes, max(max_index + 1, max_length))[..., :max_length]
, 0)).cumsum(dim=dim) return padded_t[(..., slice(None, -1), *pre_slice)] # pytorch one hot throws an error if there are out of bound indices. # tensorflow, in contrast, does not throw an error def safe_one_hot(indexes, max_length):
64
64
44
10
53
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
safe_one_hot
safe_one_hot
38
40
38
38
b185b649ba76cbf54372d6340c5d80455d4a6c22
bigcode/the-stack
train
6a618e85dcaebd7135d4e27c
train
function
def default(val, default_val): default_val = default_val() if isfunction(default_val) else default_val return val if val is not None else default_val
def default(val, default_val):
default_val = default_val() if isfunction(default_val) else default_val return val if val is not None else default_val
import torch from torch import nn import torch.nn.functional as F import math from inspect import isfunction # constants MIN_EXPERT_CAPACITY = 4 # helper functions def default(val, default_val):
47
64
36
7
39
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
default
default
14
16
14
14
c097e5ca84ff4b06bb0ea7e3908350a67aac7734
bigcode/the-stack
train
1c9486513dd7dcc14900dc0c
train
class
class GELU_(nn.Module): def forward(self, x): return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
class GELU_(nn.Module):
def forward(self, x): return 0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3))))
.one_hot(indexes, max(max_index + 1, max_length))[..., :max_length] def init_(t): dim = t.shape[-1] std = 1 / math.sqrt(dim) return t.uniform_(-std, std) # activations class GELU_(nn.Module):
64
64
54
7
56
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
GELU_
GELU_
49
51
49
49
a9c61675666d0e91e28209d8734218bf3c8fae43
bigcode/the-stack
train
9c8abec99f68fc3ec4444056
train
class
class HeirarchicalMoE(nn.Module): def __init__(self, dim, num_experts = (4, 4), hidden_dim = None, activation = nn.ReLU, second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, c...
class HeirarchicalMoE(nn.Module):
def __init__(self, dim, num_experts = (4, 4), hidden_dim = None, activation = nn.ReLU, second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, capacity_factor_train = 1.25, ...
Gating(dim, num_gates = num_experts, **gating_kwargs) self.experts = default(experts, lambda: Experts(dim, num_experts = num_experts, hidden_dim = hidden_dim, activation = activation)) self.loss_coef = loss_coef def forward(self, inputs, **kwargs): b, n, d, e = *inputs.shape, self.num_exper...
228
228
760
9
218
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
HeirarchicalMoE
HeirarchicalMoE
269
324
269
269
cce81dc596199de8a30111fd584a31d7b54c6f87
bigcode/the-stack
train
f272636d80b8d5d160990131
train
class
class Top2Gating(nn.Module): def __init__( self, dim, num_gates, eps = 1e-9, outer_expert_dims = tuple(), second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, capacity...
class Top2Gating(nn.Module):
def __init__( self, dim, num_gates, eps = 1e-9, outer_expert_dims = tuple(), second_policy_train = 'random', second_policy_eval = 'random', second_threshold_train = 0.2, second_threshold_eval = 0.2, capacity_factor_train = 1.25, ...
def __init__(self, dim, num_experts = 16, hidden_dim = None, activation = GELU): super().__init__() hidden_dim = default(hidden_dim, dim * 4) num_experts = cast_tuple(num_experts) w1 = torch.zeros(*num_experts, dim, hidden_dim) w2 = torch.zeros(...
256
256
1,384
8
247
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
Top2Gating
Top2Gating
89
225
89
89
4539dcc227c2f1de14f142d75c1e9bc3169e886c
bigcode/the-stack
train
9608efd223beb48d835b1790
train
function
def top1(t): values, index = t.topk(k=1, dim=-1) values, index = map(lambda x: x.squeeze(dim=-1), (values, index)) return values, index
def top1(t):
values, index = t.topk(k=1, dim=-1) values, index = map(lambda x: x.squeeze(dim=-1), (values, index)) return values, index
(val, default_val): default_val = default_val() if isfunction(default_val) else default_val return val if val is not None else default_val def cast_tuple(el): return el if isinstance(el, tuple) else (el,) # tensor related helper functions def top1(t):
64
64
47
5
58
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
top1
top1
23
26
23
23
e5621cc7ed3350652787d29d64a48f582a5cd8e8
bigcode/the-stack
train
f5a46ae0ab86338f9ce994ad
train
function
def cast_tuple(el): return el if isinstance(el, tuple) else (el,)
def cast_tuple(el):
return el if isinstance(el, tuple) else (el,)
from inspect import isfunction # constants MIN_EXPERT_CAPACITY = 4 # helper functions def default(val, default_val): default_val = default_val() if isfunction(default_val) else default_val return val if val is not None else default_val def cast_tuple(el):
64
64
18
5
58
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
cast_tuple
cast_tuple
18
19
18
18
1587d4abde13da00ed864923f902b4330fce5b82
bigcode/the-stack
train
5c73b79875ce54b992e251a3
train
class
class Experts(nn.Module): def __init__(self, dim, num_experts = 16, hidden_dim = None, activation = GELU): super().__init__() hidden_dim = default(hidden_dim, dim * 4) num_experts = cast_tuple(num_experts) w1 = torch.zeros(*num_experts, dim, hidden_d...
class Experts(nn.Module):
def __init__(self, dim, num_experts = 16, hidden_dim = None, activation = GELU): super().__init__() hidden_dim = default(hidden_dim, dim * 4) num_experts = cast_tuple(num_experts) w1 = torch.zeros(*num_experts, dim, hidden_dim) w2 = torch.zer...
* x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.044715 * torch.pow(x, 3)))) GELU = nn.GELU if hasattr(nn, 'GELU') else GELU_ # expert class class Experts(nn.Module):
64
64
203
5
58
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
Experts
Experts
57
82
57
57
d1ab2a6cac5d78521b4821b5705a7045d5d4ed0d
bigcode/the-stack
train
3ee690bab8b61b2a00a2b8b9
train
function
def cumsum_exclusive(t, dim=-1): num_dims = len(t.shape) num_pad_dims = - dim - 1 pre_padding = (0, 0) * num_pad_dims pre_slice = (slice(None),) * num_pad_dims padded_t = F.pad(t, (*pre_padding, 1, 0)).cumsum(dim=dim) return padded_t[(..., slice(None, -1), *pre_slice)]
def cumsum_exclusive(t, dim=-1):
num_dims = len(t.shape) num_pad_dims = - dim - 1 pre_padding = (0, 0) * num_pad_dims pre_slice = (slice(None),) * num_pad_dims padded_t = F.pad(t, (*pre_padding, 1, 0)).cumsum(dim=dim) return padded_t[(..., slice(None, -1), *pre_slice)]
# tensor related helper functions def top1(t): values, index = t.topk(k=1, dim=-1) values, index = map(lambda x: x.squeeze(dim=-1), (values, index)) return values, index def cumsum_exclusive(t, dim=-1):
64
64
100
11
52
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
cumsum_exclusive
cumsum_exclusive
28
34
28
28
633b157290c110b8231707f9528af4acf6d3440a
bigcode/the-stack
train
3f77e4164e894e7ca0a677f2
train
function
def init_(t): dim = t.shape[-1] std = 1 / math.sqrt(dim) return t.uniform_(-std, std)
def init_(t):
dim = t.shape[-1] std = 1 / math.sqrt(dim) return t.uniform_(-std, std)
bound indices. # tensorflow, in contrast, does not throw an error def safe_one_hot(indexes, max_length): max_index = indexes.max() + 1 return F.one_hot(indexes, max(max_index + 1, max_length))[..., :max_length] def init_(t):
64
64
33
5
59
Frank-Abagnal/pytorch-image-models
timm/models/layers/mixture_of_experts.py
Python
init_
init_
42
45
42
42
0e8a31e9aed0826c50e8b3f9a0b6dc52702582e2
bigcode/the-stack
train
a25fc579446ee2dc3b8d29ae
train
function
def main(filename): workbook = Workbook() sheet = workbook.active data = [ ['Month', "Bulbs", "Seeds", "Flowers", "Trees & shrubs"], ['Jan', 0, 2500, 500, 0,], ['Feb', 0, 5500, 750, 1500], ['Mar', 0, 9000, 1500, 2500], ['Apr', 0, 6500, 2000, 4000], ['May', 0,...
def main(filename):
workbook = Workbook() sheet = workbook.active data = [ ['Month', "Bulbs", "Seeds", "Flowers", "Trees & shrubs"], ['Jan', 0, 2500, 500, 0,], ['Feb', 0, 5500, 750, 1500], ['Mar', 0, 9000, 1500, 2500], ['Apr', 0, 6500, 2000, 4000], ['May', 0, 3500, 5500, 3500], ...
# radar_chart.py from openpyxl import Workbook from openpyxl.chart import RadarChart, Reference def main(filename):
27
116
387
4
22
r00c/automating_excel_with_python
07_chart_types/radar_chart.py
Python
main
main
7
43
7
7
b84ad65430ec038ba49ee847b3815af2479ef5a2
bigcode/the-stack
train
69cecffe42ba392e63fc5fd3
train
class
class EventSubscriptions(BaseSchema): # Communication swagger.json items = fields.List(fields.Nested(EventSubscription, required=False), required=False) page = fields.Nested(Page, required=False)
class EventSubscriptions(BaseSchema): # Communication swagger.json
items = fields.List(fields.Nested(EventSubscription, required=False), required=False) page = fields.Nested(Page, required=False)
"""Platform Models.""" from marshmallow import fields, Schema from marshmallow.validate import OneOf from ..enums import * from ..models.BaseSchema import BaseSchema from .EventSubscription import EventSubscription from .Page import Page class EventSubscriptions(BaseSchema): # Communication swagger.json
62
64
42
13
48
kavish-d/fdk-client-python
fdk_client/platform/models/EventSubscriptions.py
Python
EventSubscriptions
EventSubscriptions
13
19
13
16
1295b9002d5b2b2355011fa65ea1b826b55f37e5
bigcode/the-stack
train
d2a919ef602353165aaefe30
train
class
class RCallr(RPackage): """Call R from R. It is sometimes useful to perform a computation in a separate R process, without affecting the current R process at all. This packages does exactly that.""" cran = "callr" version('3.7.0', sha256='d67255148595c6d0ba4c4d241bc9f6b5e00cafe25fdc13e38c10ac...
class RCallr(RPackage):
"""Call R from R. It is sometimes useful to perform a computation in a separate R process, without affecting the current R process at all. This packages does exactly that.""" cran = "callr" version('3.7.0', sha256='d67255148595c6d0ba4c4d241bc9f6b5e00cafe25fdc13e38c10acc38653360a') version...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class RCallr(RPackage):
61
147
492
7
54
player1537-forks/spack
var/spack/repos/builtin/packages/r-callr/package.py
Python
RCallr
RCallr
9
28
9
9
968b4ae5fe5dd1ea9df8c6169684522a60ce55b2
bigcode/the-stack
train
c88c98807d5139b4bc1f60a5
train
class
class TestCreatePersonSerializer(TestCase): """ Tests PersonSerializer creation and functions. """ def setUp(self): self.person_data = model_to_dict(PersonFactory.build()) self.person_data["cpf"] = self.person_data["_cpf"] def test_serializer_with_empty_data(self): serializer = Per...
class TestCreatePersonSerializer(TestCase):
""" Tests PersonSerializer creation and functions. """ def setUp(self): self.person_data = model_to_dict(PersonFactory.build()) self.person_data["cpf"] = self.person_data["_cpf"] def test_serializer_with_empty_data(self): serializer = PersonSerializer(data={}) eq_(serialize...
from django.forms.models import model_to_dict from django.test import TestCase from nose.tools import eq_, ok_ from inquest.persons.serializers import PersonSerializer from inquest.persons.test.factories import PersonFactory pytestmark = pytest.mark.django_db class TestCreatePersonSerializer(TestCase):
64
64
102
8
55
lucasOlivio/inquest
server/inquest/persons/test/test_serializers.py
Python
TestCreatePersonSerializer
TestCreatePersonSerializer
12
25
12
12
279e8abd1b039805b97a2d1eee4fc6741368ff00
bigcode/the-stack
train
bedf6274b1b7fc79f04095a9
train
function
def rules_python_internal_deps(): """Fetches all required dependencies for rules_python tests and tools.""" maybe( http_archive, name = "bazel_skylib", sha256 = "c6966ec828da198c5d9adbaa94c05e3a1c7f21bd012a0b29ba8ddbccb2c93b0d", urls = [ "https://github.com/bazelbuil...
def rules_python_internal_deps():
"""Fetches all required dependencies for rules_python tests and tools.""" maybe( http_archive, name = "bazel_skylib", sha256 = "c6966ec828da198c5d9adbaa94c05e3a1c7f21bd012a0b29ba8ddbccb2c93b0d", urls = [ "https://github.com/bazelbuild/bazel-skylib/releases/download/1...
"""Dependencies that are needed for rules_python tests and tools.""" load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("@rules_python//python/legacy_...
101
256
1,928
7
94
gibfahn/rules_python
internal_deps.bzl
Python
rules_python_internal_deps
rules_python_internal_deps
8
123
8
8
954c61dd79b7b1f18d812fadd29acfbf00a37c2a
bigcode/the-stack
train
eadd81b257d2e19bc2bf2a4c
train
function
def _output_html(view, content=None): ''' Common html file formatter. ''' settings = sublime.load_settings(SETTINGS_FN) output_type = settings.get('render_output') s = "" if content is None else "".join(content) if output_type == 'clipboard': sublime.set_clipboard(s) # elif output_type...
def _output_html(view, content=None):
''' Common html file formatter. ''' settings = sublime.load_settings(SETTINGS_FN) output_type = settings.get('render_output') s = "" if content is None else "".join(content) if output_type == 'clipboard': sublime.set_clipboard(s) # elif output_type == 'new_file': # view = creat...
\" charset=\"utf-8\"></script><script>window.alreadyProcessedMarkdeep||(document.body.style.visibility=\"visible\")</script>") _output_html(self.view, '\n'.join(html)) except Exception as e: plugin_exception(e) #--------------------------------------------------------------------------...
64
64
215
9
55
cepthomas/SublimeBagOfTricks
sbot_render.py
Python
_output_html
_output_html
283
302
283
283
c6ca2d6fe5e3670ba9088ecd6ee8ed1120434a41
bigcode/the-stack
train
cd53c5ebd498d1dde50b2a83
train
class
class SbotRenderToHtmlCommand(sublime_plugin.TextCommand): ''' Make a pretty. ''' def __init__(self, view): # Get prefs. self.settings = sublime.load_settings(SETTINGS_FN) self.rows = 0 self.row_num = 0 super(SbotRenderToHtmlCommand, self).__init__(view) self.vie...
class SbotRenderToHtmlCommand(sublime_plugin.TextCommand):
''' Make a pretty. ''' def __init__(self, view): # Get prefs. self.settings = sublime.load_settings(SETTINGS_FN) self.rows = 0 self.row_num = 0 super(SbotRenderToHtmlCommand, self).__init__(view) self.view = view def run(self, edit, line_numbers): tr...
import os import time import math import textwrap import webbrowser from html import escape import sublime import sublime_plugin from sbot_common import * print('Python: load sbot_render') #----------------------------------------------------------------------------------- class SbotRenderToHtmlCommand(sublime_plugi...
61
256
1,832
14
47
cepthomas/SublimeBagOfTricks
sbot_render.py
Python
SbotRenderToHtmlCommand
SbotRenderToHtmlCommand
15
251
15
15
3943a396a4075a5cdb3b421d5d03a997f0a2d899
bigcode/the-stack
train
0cc585c26da0bf2e0c3f1bfb
train
class
class SbotRenderMarkdownCommand(sublime_plugin.TextCommand): # Need a multi-file combining type like Neb. ''' Turn md into html.''' def is_visible(self): return self.view.settings().get('syntax') == SYNTAX_MD def run(self, edit): try: # Get prefs. settings = sublime...
class SbotRenderMarkdownCommand(sublime_plugin.TextCommand): # Need a multi-file combining type like Neb.
''' Turn md into html.''' def is_visible(self): return self.view.settings().get('syntax') == SYNTAX_MD def run(self, edit): try: # Get prefs. settings = sublime.load_settings(SETTINGS_FN) html_background = settings.get('html_background') html...
div class="container"> <div class="contentpane"> ''') html3 = textwrap.dedent(''' </div> </div> </body> </html> ''') _output_html(self.view, [html1, style_text, html2, "".join(content), html3]) #---------------------...
95
95
317
23
72
cepthomas/SublimeBagOfTricks
sbot_render.py
Python
SbotRenderMarkdownCommand
SbotRenderMarkdownCommand
255
279
255
255
010e83d1b4762ca61271f95abfda555a59841398
bigcode/the-stack
train
b31654c7fbce473b2b6c4f47
train
function
@products_blueprint.route('/products/<int:product_id>', methods=['GET']) def read_product(product_id: int): """ Get product by its ID. @param product_id: ID of wanted product. @return: Wanted product representation. """ product: Product = Product.get(product_id) return jsonify(product.serial...
@products_blueprint.route('/products/<int:product_id>', methods=['GET']) def read_product(product_id: int):
""" Get product by its ID. @param product_id: ID of wanted product. @return: Wanted product representation. """ product: Product = Product.get(product_id) return jsonify(product.serialized)
_data = build_product_args(create_input) product: Product = Product.create(create_data) db.session.add(product) db.session.commit() return jsonify(product.serialized), 201 @products_blueprint.route('/products/<int:product_id>', methods=['GET']) def read_product(product_id: int):
64
64
72
25
38
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
read_product
read_product
62
70
62
63
54f4455c56b723c35fc2de5bf710727cdce7ed9a
bigcode/the-stack
train
798a399cab28890a81ddcada
train
function
@products_blueprint.route('/products/<int:product_id>', methods=['DELETE']) def delete_product(product_id: int): """ Remove product by its ID. @param product_id: ID of product we want to delete. @return: Simple status message. """ product: Product = Product.get(product_id) db.session.delete...
@products_blueprint.route('/products/<int:product_id>', methods=['DELETE']) def delete_product(product_id: int):
""" Remove product by its ID. @param product_id: ID of product we want to delete. @return: Simple status message. """ product: Product = Product.get(product_id) db.session.delete(product) db.session.commit() return jsonify({"status": "ok"})
()) update_data = build_product_args(update_input) product: Product = Product.get(product_id) product.update(update_data) db.session.commit() return jsonify(product.serialized) @products_blueprint.route('/products/<int:product_id>', methods=['DELETE']) def delete_product(product_id: int):
64
64
88
25
39
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
delete_product
delete_product
93
105
93
94
cfcab004d7ffe5fe58a163def6efe61b547f118c
bigcode/the-stack
train
fca68b2846a465904878e1a9
train
function
def build_product_args(data: ProductUpdateRequest) -> Dict: """ Turn ProductSchema into dict for updating Product orm object. Result can be used can be used as constructor argument or can be iterated through to update field values. @param data: request data ProductCreateRequest @return: dict wi...
def build_product_args(data: ProductUpdateRequest) -> Dict:
""" Turn ProductSchema into dict for updating Product orm object. Result can be used can be used as constructor argument or can be iterated through to update field values. @param data: request data ProductCreateRequest @return: dict with data """ create_args = data.dict(exclude_unset=Tr...
Dict from flask import Blueprint, jsonify, request from app import db from app.models.products import Product, Brand, Category from app.schema.products import ProductCreateRequest, ProductUpdateRequest products_blueprint = Blueprint('products', __name__) def build_product_args(data: ProductUpdateRequest) -> Dict:
64
64
130
13
51
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
build_product_args
build_product_args
12
29
12
12
665c9891cb63e39adf074c8312b76c040a551927
bigcode/the-stack
train
c9543077f85f772a4c8578f7
train
function
@products_blueprint.route('/products', methods=['POST']) def create_product(): """ Create new product. @see ProductCreateRequest for request body fields. @return: Created product representation. """ create_input = ProductCreateRequest(**request.get_json()) create_data = build_product_args(...
@products_blueprint.route('/products', methods=['POST']) def create_product():
""" Create new product. @see ProductCreateRequest for request body fields. @return: Created product representation. """ create_input = ProductCreateRequest(**request.get_json()) create_data = build_product_args(create_input) product: Product = Product.create(create_data) db.sessio...
=['GET']) def get_products(): """ Get full list of products. @return: List of product representations. """ return jsonify({ 'results': [p.serialized for p in Product.query.all()] }) @products_blueprint.route('/products', methods=['POST']) def create_product():
64
64
97
16
48
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
create_product
create_product
43
59
43
44
025750795fd3acf3b44d15260d788f5d0d94da7d
bigcode/the-stack
train
37f7f90bada857a316f0e7e9
train
function
@products_blueprint.route('/products', methods=['GET']) def get_products(): """ Get full list of products. @return: List of product representations. """ return jsonify({ 'results': [p.serialized for p in Product.query.all()] })
@products_blueprint.route('/products', methods=['GET']) def get_products():
""" Get full list of products. @return: List of product representations. """ return jsonify({ 'results': [p.serialized for p in Product.query.all()] })
=True) if data.brand is not None: create_args["brand"] = Brand.get(data.brand) if data.categories is not None: create_args["categories"] = Category.get_all(data.categories) return create_args @products_blueprint.route('/products', methods=['GET']) def get_products():
64
64
57
16
47
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
get_products
get_products
32
40
32
33
7ace554b6503bcc3545bd7ac82b28df5a50c3d2f
bigcode/the-stack
train
83b16faaa1c465925ea22951
train
function
@products_blueprint.route('/products/<int:product_id>', methods=['PATCH']) def update_product(product_id: int): """ Update product. Endpoint accepts difference (patch update). @see ProductUpdateRequest for request body fields. @param product_id: ID of product we want to update. @return: Representat...
@products_blueprint.route('/products/<int:product_id>', methods=['PATCH']) def update_product(product_id: int):
""" Update product. Endpoint accepts difference (patch update). @see ProductUpdateRequest for request body fields. @param product_id: ID of product we want to update. @return: Representation of product after update. """ update_input = ProductUpdateRequest(**request.get_json()) update_d...
. @param product_id: ID of wanted product. @return: Wanted product representation. """ product: Product = Product.get(product_id) return jsonify(product.serialized) @products_blueprint.route('/products/<int:product_id>', methods=['PATCH']) def update_product(product_id: int):
64
64
125
25
39
XuntoSparkequation/trial.python.3hr
app/endpoints/products.py
Python
update_product
update_product
73
90
73
74
8146e89504c59e72f99e7885dd19baa7d62838d2
bigcode/the-stack
train
5acfaa1bd0a3af3d6c1fd586
train
class
class LoginForm(View): """ Basic login functionality in login page """ username_field = TextInput(id='session_username') username_label = Text('//input[@id="session_username"]/preceding-sibling::label') password_field = TextInput(id='session_password') password_label = Text('//input[@id=...
class LoginForm(View):
""" Basic login functionality in login page """ username_field = TextInput(id='session_username') username_label = Text('//input[@id="session_username"]/preceding-sibling::label') password_field = TextInput(id='session_password') password_label = Text('//input[@id="session_password"]/pre...
"""Login portion which is the same for admin and master""" from widgetastic.widget import TextInput, View, Text from testsuite.ui.widgets.buttons import ThreescaleSubmitButton class LoginForm(View):
43
64
216
5
37
dlaso99/3scale-tests
testsuite/ui/views/common/login.py
Python
LoginForm
LoginForm
7
31
7
7
04a1c3f9af7460950aa53c08c5134e41027c8e8e
bigcode/the-stack
train
2c21785ecddf1f7d5cbb5567
train
function
def create_parser(): parser = argparse.ArgumentParser(description="Measure the performance of suffix array building: C= suffix_array(V)") parser.add_argument('hostname', help='Hostname of arkouda server') parser.add_argument('port', type=int, help='Port of arkouda server') parser.add_argument('-v', '--l...
def create_parser():
parser = argparse.ArgumentParser(description="Measure the performance of suffix array building: C= suffix_array(V)") parser.add_argument('hostname', help='Hostname of arkouda server') parser.add_argument('port', type=int, help='Port of arkouda server') parser.add_argument('-v', '--logvertices', type=int...
Directed=i[3] FileName=i[4] print(Edges,",",Vertices,",",Columns,",",Directed,",",str(FileName)) njit.graph_file_preprocessing(Edges,Vertices,Columns,Directed,str(FileName),1,1,0,0,1) end = time.time() return def create_parser():
74
74
248
4
69
Bears-R-Us/arkouda-njit
test/client/benchmarks/preprocess.py
Python
create_parser
create_parser
60
71
60
60
460f17811d9731590f4310f0d1eddd2081035603
bigcode/the-stack
train
4ff62341c0a1dc3257cfaeae
train
function
def time_ak_process_graph(): print("Graph Truss Analysis") cfg = ak.get_config() print("server Hostname =",cfg["serverHostname"]) print("Number of Locales=",cfg["numLocales"]) print("number of PUs =",cfg["numPUs"]) print("Max Tasks =",cfg["maxTaskPar"]) print("Memory =",cfg["physicalMemory"]...
def time_ak_process_graph():
print("Graph Truss Analysis") cfg = ak.get_config() print("server Hostname =",cfg["serverHostname"]) print("Number of Locales=",cfg["numLocales"]) print("number of PUs =",cfg["numPUs"]) print("Max Tasks =",cfg["maxTaskPar"]) print("Memory =",cfg["physicalMemory"]) HomeDir="/rhome/zhihui/...
#!/usr/bin/env python3 import time, argparse import numpy as np import arkouda as ak import random import string import arkouda_njit as njit TYPES = ('int64', 'float64', 'bool', 'str') def time_ak_process_graph():
65
227
759
7
58
Bears-R-Us/arkouda-njit
test/client/benchmarks/preprocess.py
Python
time_ak_process_graph
time_ak_process_graph
12
57
12
12
13ebd7ff9f8438840e55a0ed30f0f6ca40cad3e9
bigcode/the-stack
train
0a206eef367264d33aab6da0
train
class
class ErrorHandler: def __init__(self, config): self.config = config def handle_error(self, context, handler, exception): pass
class ErrorHandler:
def __init__(self, config): self.config = config def handle_error(self, context, handler, exception): pass
class ErrorHandler:
4
64
34
4
0
bear8421/thumbor
tests/fixtures/custom_error_handler.py
Python
ErrorHandler
ErrorHandler
1
6
1
1
04ce0d82a886e31909b4af6a67f53b239be21160
bigcode/the-stack
train
1b7fbc3c1d2d644eba249522
train
function
def spectral_norm(module: Module, name: str = 'weight', n_power_iterations: int = 1, eps: float = 1e-12, dim: Optional[int] = None) -> Module: r"""Applies spectral normalization to a parameter in the given module. .. math:: \mathbf...
def spectral_norm(module: Module, name: str = 'weight', n_power_iterations: int = 1, eps: float = 1e-12, dim: Optional[int] = None) -> Module:
r"""Applies spectral normalization to a parameter in the given module. .. math:: \mathbf{W}_{SN} = \dfrac{\mathbf{W}}{\sigma(\mathbf{W})}, \sigma(\mathbf{W}) = \max_{\mathbf{h}: \mathbf{h} \ne 0} \dfrac{\|\mathbf{W} \mathbf{h}\|_2}{\|\mathbf{h}\|_2} When applied on a vector, it simplifies ...
.ndim == 1: # Faster and more exact path, no need to approximate anything return F.normalize(weight, dim=0, eps=self.eps) else: weight_mat = self._reshape_weight_to_matrix(weight) if self.training: self._power_method(weight_mat, self.n_power_iterat...
256
256
904
48
207
vulcantron/pytorch
torch/nn/utils/parametrizations.py
Python
spectral_norm
spectral_norm
120
212
120
124
9e39d546098ac38f91221f95c410d613e02daa36
bigcode/the-stack
train
f3b5a266d99989ab7bce4215
train
class
class _SpectralNorm(Module): def __init__( self, weight: torch.Tensor, n_power_iterations: int = 1, dim: int = 0, eps: float = 1e-12 ) -> None: super().__init__() ndim = weight.ndim if dim >= ndim or dim < -ndim: raise IndexError("Dimen...
class _SpectralNorm(Module):
def __init__( self, weight: torch.Tensor, n_power_iterations: int = 1, dim: int = 0, eps: float = 1e-12 ) -> None: super().__init__() ndim = weight.ndim if dim >= ndim or dim < -ndim: raise IndexError("Dimension out of range (expected t...
import torch from ..utils import parametrize from ..modules import Module from .. import functional as F from typing import Optional class _SpectralNorm(Module):
35
256
1,317
7
27
vulcantron/pytorch
torch/nn/utils/parametrizations.py
Python
_SpectralNorm
_SpectralNorm
8
117
8
8
84f64ae592e504472a9c7838aa6e3862860f4db5
bigcode/the-stack
train
9820a70743a4a015357c91eb
train
function
def rotate_point_cloud(batch_data): """ Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds """ rotated_data =...
def rotate_point_cloud(batch_data):
""" Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds """ rotated_data = np.zeros(batch_data.shape, dtype=np...
return pc def load_pc_files(filenames): pcs=[] for filename in filenames: #print(filename) pc=load_pc_file(filename) if(pc.shape[0]!=1024): continue pcs.append(pc) pcs=np.array(pcs) return pcs def rotate_point_cloud(batch_data):
67
67
226
7
59
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
rotate_point_cloud
rotate_point_cloud
47
67
47
47
e635cb55586ed586b949a79fd35e17cbb3cda1e9
bigcode/the-stack
train
5b0d5fd2ea1f61fa67a31149
train
function
def jitter_point_cloud(batch_data, sigma=0.005, clip=0.05): """ Randomly jitter points. jittering is per point. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, jittered batch of point clouds """ B, N, C = batch_data.shape assert(clip > 0) j...
def jitter_point_cloud(batch_data, sigma=0.005, clip=0.05):
""" Randomly jitter points. jittering is per point. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, jittered batch of point clouds """ B, N, C = batch_data.shape assert(clip > 0) jittered_data = np.clip(sigma * np.random.randn(B, N, C), -1*...
0, 0, 1]]) shape_pc = batch_data[k, ...] rotated_data[k, ...] = np.dot(shape_pc.reshape((-1, 3)), rotation_matrix) return rotated_data def jitter_point_cloud(batch_data, sigma=0.005, clip=0.05):
64
64
126
19
44
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
jitter_point_cloud
jitter_point_cloud
69
80
69
69
beff65eb8c69f135953a0b2cb9d778bacdd63476
bigcode/the-stack
train
2077bfcfe046100fbd1f300b
train
function
def get_rotated_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[],other_neg=False): query=load_pc_file(dict_value["query"]) #Nx3 q_rot= rotate_point_cloud(np.expand_dims(query, axis=0)) q_rot= np.squeeze(q_rot) random.shuffle(dict_value["positives"]) pos_files=[] for i in range(num_pos): pos_files.ap...
def get_rotated_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[],other_neg=False):
query=load_pc_file(dict_value["query"]) #Nx3 q_rot= rotate_point_cloud(np.expand_dims(query, axis=0)) q_rot= np.squeeze(q_rot) random.shuffle(dict_value["positives"]) pos_files=[] for i in range(num_pos): pos_files.append(QUERY_DICT[dict_value["positives"][i]]["query"]) #positives= load_pc_files(dict_value["p...
negatives and query neighbors=[] for pos in dict_value["positives"]: neighbors.append(pos) for neg in neg_indices: for pos in QUERY_DICT[neg]["positives"]: neighbors.append(pos) possible_negs= list(set(QUERY_DICT.keys())-set(neighbors)) random.shuffle(possible_negs) if(len(possible_negs)==0): ...
158
158
527
24
134
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
get_rotated_tuple
get_rotated_tuple
141
197
141
141
d4700a3dfa3ae7519da8dd53b41a2faf044d8686
bigcode/the-stack
train
b7d5872092309cdc90ca63fb
train
function
def load_pc_file(filename): #returns Nx3 matrix pc=np.fromfile(os.path.join(BASE_PATH,filename), dtype=np.float64) if(pc.shape[0]!= 1024*3): print("Error in pointcloud shape") return np.array([]) pc=np.reshape(pc,(pc.shape[0]//3,3)) return pc
def load_pc_file(filename): #returns Nx3 matrix
pc=np.fromfile(os.path.join(BASE_PATH,filename), dtype=np.float64) if(pc.shape[0]!= 1024*3): print("Error in pointcloud shape") return np.array([]) pc=np.reshape(pc,(pc.shape[0]//3,3)) return pc
cloud:{'query':file,'northing':value,'easting':value}}, ...} with open(filename, 'rb') as handle: trajectories = pickle.load(handle) print("Trajectories Loaded.") return trajectories def load_pc_file(filename): #returns Nx3 matrix
64
64
75
13
50
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
load_pc_file
load_pc_file
25
34
25
26
36719c3f8e9cb736cc548fb6b07d5d38ab5030c0
bigcode/the-stack
train
ea247ac558967bf18aaf8c13
train
function
def load_pc_files(filenames): pcs=[] for filename in filenames: #print(filename) pc=load_pc_file(filename) if(pc.shape[0]!=1024): continue pcs.append(pc) pcs=np.array(pcs) return pcs
def load_pc_files(filenames):
pcs=[] for filename in filenames: #print(filename) pc=load_pc_file(filename) if(pc.shape[0]!=1024): continue pcs.append(pc) pcs=np.array(pcs) return pcs
.path.join(BASE_PATH,filename), dtype=np.float64) if(pc.shape[0]!= 1024*3): print("Error in pointcloud shape") return np.array([]) pc=np.reshape(pc,(pc.shape[0]//3,3)) return pc def load_pc_files(filenames):
64
64
57
7
56
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
load_pc_files
load_pc_files
36
45
36
36
595ad1390f61384c50518d4f299a1fbce7b5fb32
bigcode/the-stack
train
97029b150813096c1201ca8e
train
function
def get_sets_dict(filename): #[key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}},key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}}, ...} with open(filename, 'rb') as handle: trajectories = pickle.load(handle) print("Trajectories Loaded.") return trajectories...
def get_sets_dict(filename): #[key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}},key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}}, ...}
with open(filename, 'rb') as handle: trajectories = pickle.load(handle) print("Trajectories Loaded.") return trajectories
print("Queries Loaded.") return queries def get_sets_dict(filename): #[key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}},key_dataset:{key_pointcloud:{'query':file,'northing':value,'easting':value}}, ...}
64
64
86
54
9
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
get_sets_dict
get_sets_dict
18
23
18
19
23590c4b519e12a34d6d4b5ac8694953a8545280
bigcode/the-stack
train
01064a9850efe2f7bde67292
train
function
def get_query_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[], other_neg=False): #get query tuple for dictionary entry #return list [query,positives,negatives] query=load_pc_file(dict_value["query"]) #Nx3 random.shuffle(dict_value["positives"]) pos_files=[] for i in range(num_pos): pos_files.appe...
def get_query_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[], other_neg=False): #get query tuple for dictionary entry #return list [query,positives,negatives]
query=load_pc_file(dict_value["query"]) #Nx3 random.shuffle(dict_value["positives"]) pos_files=[] for i in range(num_pos): pos_files.append(QUERY_DICT[dict_value["positives"][i]]["query"]) #positives= load_pc_files(dict_value["positives"][0:num_pos]) positives=load_pc_files(pos_files) neg_files=[] neg_indi...
per point. Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, jittered batch of point clouds """ B, N, C = batch_data.shape assert(clip > 0) jittered_data = np.clip(sigma * np.random.randn(B, N, C), -1*clip, clip) jittered_data += batch_data ...
141
141
473
44
96
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
get_query_tuple
get_query_tuple
82
138
82
85
4ae9c3c7409d3d120cc088d0382dae000f8ab1eb
bigcode/the-stack
train
c37adc1093a24533a1b719b3
train
function
def get_jittered_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[],other_neg=False): query=load_pc_file(dict_value["query"]) #Nx3 #q_rot= rotate_point_cloud(np.expand_dims(query, axis=0)) q_jit= jitter_point_cloud(np.expand_dims(query, axis=0)) q_jit= np.squeeze(q_jit) random.shuffle(dict_value["positiv...
def get_jittered_tuple(dict_value, num_pos, num_neg, QUERY_DICT, hard_neg=[],other_neg=False):
query=load_pc_file(dict_value["query"]) #Nx3 #q_rot= rotate_point_cloud(np.expand_dims(query, axis=0)) q_jit= jitter_point_cloud(np.expand_dims(query, axis=0)) q_jit= np.squeeze(q_jit) random.shuffle(dict_value["positives"]) pos_files=[] for i in range(num_pos): pos_files.append(QUERY_DICT[dict_value["positiv...
for neg in neg_indices: for pos in QUERY_DICT[neg]["positives"]: neighbors.append(pos) possible_negs= list(set(QUERY_DICT.keys())-set(neighbors)) random.shuffle(possible_negs) if(len(possible_negs)==0): return [q_jit, p_jit, n_jit, np.array([])] neg2= load_pc_file(QUERY_DICT[possible_negs[0]]["quer...
168
168
560
25
143
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
get_jittered_tuple
get_jittered_tuple
199
256
199
199
31b8b332aa2b282505603747ac4392c5dbf4c408
bigcode/the-stack
train
3c9a80e27f74bd13760d296f
train
function
def get_queries_dict(filename): #key:{'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]} with open(filename, 'rb') as handle: queries = pickle.load(handle) print("Queries Loaded.") return queries
def get_queries_dict(filename): #key:{'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]}
with open(filename, 'rb') as handle: queries = pickle.load(handle) print("Queries Loaded.") return queries
'dataset/')partial_dataset print(BASE_PATH) #BASE_PATH = "/media/deep-three/Deep_Store/CVPR2018/benchmark_datasets/" def get_queries_dict(filename): #key:{'query':file,'positives':[files],'negatives:[files], 'neighbors':[keys]}
63
64
58
30
33
phd-jaybie/3d-spatial-privacy-1
loading_pointclouds.py
Python
get_queries_dict
get_queries_dict
11
16
11
12
ebad78c0009116e2cf2a4ff38852347f6cdce88e
bigcode/the-stack
train
c26574b9034d7cf27db02137
train
function
def iter_evented_container_events( module: ModuleType = napari, container_class=LayerList ) -> Iterator[Ev]: for mod in walk_modules(module): for kls in iter_classes(mod): if not issubclass(kls, container_class): continue docs = class_doc_attrs(kls) kl...
def iter_evented_container_events( module: ModuleType = napari, container_class=LayerList ) -> Iterator[Ev]:
for mod in walk_modules(module): for kls in iter_classes(mod): if not issubclass(kls, container_class): continue docs = class_doc_attrs(kls) kls_instance = kls() for name, emitter in kls_instance.events._emitters.items(): descr ...
"{finfo.title.lower()}" if finfo.title else docs.get(name) ) yield Ev(name, kls, descr, field_.type_) def iter_evented_container_events( module: ModuleType = napari, container_class=LayerList ) -> Iterator[Ev]:
63
64
190
28
35
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
iter_evented_container_events
iter_evented_container_events
121
141
121
123
1b0550ae75b6c9a947e1f8dfb4a3484b44c8ecd6
bigcode/the-stack
train
a953ab6f0a81e81bc7668b30
train
class
class BaseEmitterVisitor(ast.NodeVisitor): def __init__(self) -> None: super().__init__() self._emitters: List[str] = [] def visit_Call(self, node: ast.Call): if getattr(node.func, 'id', None) == 'EmitterGroup': self._emitters.extend([name.arg for name in node.keywords]) # ...
class BaseEmitterVisitor(ast.NodeVisitor):
def __init__(self) -> None: super().__init__() self._emitters: List[str] = [] def visit_Call(self, node: ast.Call): if getattr(node.func, 'id', None) == 'EmitterGroup': self._emitters.extend([name.arg for name in node.keywords]) # type: ignore
, emitter in selection.events._emitters.items(): if name.startswith('_'): # skip private emitters continue name = 'selection.' + name descr = docs.get(name) yield Ev(name, kls, descr, type_=No...
64
64
83
8
56
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
BaseEmitterVisitor
BaseEmitterVisitor
144
151
144
144
c8ecbac6784b2208a684e9f1095942d4975cf7f4
bigcode/the-stack
train
9c4e98b971ef64ba43455b79
train
function
def walk_modules( module: ModuleType, pkg='napari', _walked=None ) -> Iterator[ModuleType]: """walk all modules in pkg, starting with `module`.""" if not _walked: _walked = set() yield module _walked.add(module) for name in dir(module): attr = getattr(module, name) if ( ...
def walk_modules( module: ModuleType, pkg='napari', _walked=None ) -> Iterator[ModuleType]:
"""walk all modules in pkg, starting with `module`.""" if not _walked: _walked = set() yield module _walked.add(module) for name in dir(module): attr = getattr(module, name) if ( inspect.ismodule(attr) and attr.__package__.startswith(pkg) # type: igno...
self.model.__name__}`', f'`{self.name}`', f'`{self.access_at()}`', self.description or '', '', ] def walk_modules( module: ModuleType, pkg='napari', _walked=None ) -> Iterator[ModuleType]:
63
64
133
27
36
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
walk_modules
walk_modules
70
85
70
72
7e492c513390f33d31f08cfd4b7ab6bf243db37c
bigcode/the-stack
train
dcf33e1a8c0c38c77d29c596
train
function
def class_doc_attrs(kls: Type) -> Dict[str, Parameter]: docs = {p.name: " ".join(p.desc) for p in ClassDoc(kls).get('Attributes')} docs.update( {p.name: " ".join(p.desc) for p in ClassDoc(kls).get('Parameters')} ) return docs
def class_doc_attrs(kls: Type) -> Dict[str, Parameter]:
docs = {p.name: " ".join(p.desc) for p in ClassDoc(kls).get('Attributes')} docs.update( {p.name: " ".join(p.desc) for p in ClassDoc(kls).get('Parameters')} ) return docs
Iterator[Type]: """iter all classes in module""" for name in dir(module): attr = getattr(module, name) if inspect.isclass(attr) and attr.__module__ == module.__name__: yield attr def class_doc_attrs(kls: Type) -> Dict[str, Parameter]:
64
64
73
15
48
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
class_doc_attrs
class_doc_attrs
96
101
96
96
5bc67f888be5bb98170ee7c25ac4225be4818d20
bigcode/the-stack
train
713050379dfb9a198b80295e
train
class
@dataclass class Ev: name: str model: Type description: Optional[str] = None type_: Optional[Type] = None def access_at(self): """Where this event can be accessed (in code)""" if issubclass(self.model, layers.Layer): return f'layer.events.{self.name}' if issubcl...
@dataclass class Ev:
name: str model: Type description: Optional[str] = None type_: Optional[Type] = None def access_at(self): """Where this event can be accessed (in code)""" if issubclass(self.model, layers.Layer): return f'layer.events.{self.name}' if issubclass(self.model, Layer...
types import ModuleType from typing import Dict, Iterator, List, Optional, Type import numpy as np from numpydoc.docscrape import ClassDoc, Parameter import napari from docs._scripts._table_maker import table_repr from napari import layers from napari.components.layerlist import LayerList from napari.components.view...
105
105
351
6
98
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
Ev
Ev
21
67
21
22
1aeb70cdebc5277e4ee7de3336264180367319a4
bigcode/the-stack
train
e6b3faa7c524cb532d0a7bb0
train
function
def merge_image_and_label_rows(rows: List[List[str]]): """Merge events common to _ImageBase or IntensityVisualizationMixin.""" # find events that are common across both Image, Labels and Surface layers. image_events = {r[1] for r in rows if r[0] == '`Image`'} labels_events = {r[1] for r in rows if r[0] ...
def merge_image_and_label_rows(rows: List[List[str]]):
"""Merge events common to _ImageBase or IntensityVisualizationMixin.""" # find events that are common across both Image, Labels and Surface layers. image_events = {r[1] for r in rows if r[0] == '`Image`'} labels_events = {r[1] for r in rows if r[0] == '`Labels`'} surface_events = {r[1] for r in rows...
) ), layers.Tracks( np.column_stack( (np.ones(20), np.arange(20), 20 * np.random.random((20, 2))) ) ), ] for lay in EXAMPLE_LAYERS: docs = class_doc_attrs(type(lay)) for name in [i for i in lay.events.emitters if i not in basename...
111
111
370
13
98
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
merge_image_and_label_rows
merge_image_and_label_rows
195
230
195
195
0645193bca44b4458de1f86e67a212158d4cb8b9
bigcode/the-stack
train
07f70d64af655374142f6c24
train
function
def base_event_names() -> List[str]: from napari.layers.base import base root = ast.parse(Path(base.__file__).read_text()) visitor = BaseEmitterVisitor() visitor.visit(root) return visitor._emitters
def base_event_names() -> List[str]:
from napari.layers.base import base root = ast.parse(Path(base.__file__).read_text()) visitor = BaseEmitterVisitor() visitor.visit(root) return visitor._emitters
: List[str] = [] def visit_Call(self, node: ast.Call): if getattr(node.func, 'id', None) == 'EmitterGroup': self._emitters.extend([name.arg for name in node.keywords]) # type: ignore def base_event_names() -> List[str]:
64
64
50
9
54
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
base_event_names
base_event_names
154
160
154
154
d86551b8c50be89dfcc6f9ced4e6d8d3f9c26c15
bigcode/the-stack
train
0dc267388a03a813f5b19657
train
function
def iter_evented_model_events(module: ModuleType = napari) -> Iterator[Ev]: for mod in walk_modules(module): for kls in iter_classes(mod): if not issubclass(kls, EventedModel): continue docs = class_doc_attrs(kls) for name, field_ in kls.__fields__.items()...
def iter_evented_model_events(module: ModuleType = napari) -> Iterator[Ev]:
for mod in walk_modules(module): for kls in iter_classes(mod): if not issubclass(kls, EventedModel): continue docs = class_doc_attrs(kls) for name, field_ in kls.__fields__.items(): finfo = field_.field_info if finfo.allow_m...
for p in ClassDoc(kls).get('Attributes')} docs.update( {p.name: " ".join(p.desc) for p in ClassDoc(kls).get('Parameters')} ) return docs def iter_evented_model_events(module: ModuleType = napari) -> Iterator[Ev]:
64
64
133
19
44
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
iter_evented_model_events
iter_evented_model_events
104
118
104
104
4797e8e75202d0836ab6212407b8a084e4588386
bigcode/the-stack
train
0c509dc0d3a5602e0e7ea452
train
function
def main(): HEADER = [ 'Event', 'Description', 'Event.value type', ] # Do viewer events rows = [ ev.ev_model_row()[2:] for ev in iter_evented_model_events() if ev.access_at() ] table1 = table_repr(rows, padding=2, header=HEADER, divide_rows=False)...
def main():
HEADER = [ 'Event', 'Description', 'Event.value type', ] # Do viewer events rows = [ ev.ev_model_row()[2:] for ev in iter_evented_model_events() if ev.access_at() ] table1 = table_repr(rows, padding=2, header=HEADER, divide_rows=False) (DOCS /...
] == '`Image`' and r[1] in imagebase_events else r for r in rows ] rows = [ ['`Image`, `Labels`, `Surface`'] + r[1:] if r[0] == '`Image`' and r[1] in common_events else r for r in rows ] return rows def main():
88
88
296
3
84
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
main
main
233
272
233
233
15f2140853e30ff6c251d64795d88b1abfda4aca
bigcode/the-stack
train
a186ff5cd5f8fb4fbcba23f8
train
function
def iter_layer_events() -> Iterator[Ev]: basenames = base_event_names() docs = class_doc_attrs(layers.Layer) for name in basenames: yield Ev(name, layers.Layer, description=docs.get(name)) EXAMPLE_LAYERS: List[layers.Layer] = [ layers.Image(np.random.random((2, 2))), layers.Labe...
def iter_layer_events() -> Iterator[Ev]:
basenames = base_event_names() docs = class_doc_attrs(layers.Layer) for name in basenames: yield Ev(name, layers.Layer, description=docs.get(name)) EXAMPLE_LAYERS: List[layers.Layer] = [ layers.Image(np.random.random((2, 2))), layers.Labels(np.random.randint(20, size=(10, 15))),...
EmitterGroup': self._emitters.extend([name.arg for name in node.keywords]) # type: ignore def base_event_names() -> List[str]: from napari.layers.base import base root = ast.parse(Path(base.__file__).read_text()) visitor = BaseEmitterVisitor() visitor.visit(root) return visitor._emit...
85
85
284
10
74
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
iter_layer_events
iter_layer_events
163
192
163
163
ab853bbcaa967db589a924fe8706a0aca9722c3b
bigcode/the-stack
train
d6bf4d46330a7d8dbaffe9a3
train
function
def iter_classes(module: ModuleType) -> Iterator[Type]: """iter all classes in module""" for name in dir(module): attr = getattr(module, name) if inspect.isclass(attr) and attr.__module__ == module.__name__: yield attr
def iter_classes(module: ModuleType) -> Iterator[Type]:
"""iter all classes in module""" for name in dir(module): attr = getattr(module, name) if inspect.isclass(attr) and attr.__module__ == module.__name__: yield attr
if ( inspect.ismodule(attr) and attr.__package__.startswith(pkg) # type: ignore and attr not in _walked ): yield from walk_modules(attr, pkg, _walked=_walked) def iter_classes(module: ModuleType) -> Iterator[Type]:
64
64
58
13
51
amgfernandes/napari
docs/_scripts/update_event_docs.py
Python
iter_classes
iter_classes
88
93
88
88
faa55767ff05db0b4f9b9a3de82a2f9b14a9f1f6
bigcode/the-stack
train
9dea4cb90fbcde4c01255411
train
function
def main(): filename = sys.argv[1] cf = CookieFile(filename) print(cf.pick())
def main():
filename = sys.argv[1] cf = CookieFile(filename) print(cf.pick())
(cls, path): for name in glob.glob(os.path.join(path, '*')): if not os.path.isfile(name): continue if '.' in os.path.basename(name): continue yield name def pick(self): return self.cookies[random.randint(0, self.last)] def main():
64
64
23
3
61
meffie/grpc-demos
fortune/fortune.py
Python
main
main
30
33
30
30
8ae4c9e99d045e353125b56dd76f1b0b45043d99
bigcode/the-stack
train
23167905e08ff6075fadeed4
train
class
class CookieFile: def __init__(self, filename): with open(filename) as f: text = f.read() sep = os.linesep + '%' + os.linesep self.cookies = [c for c in text.split(sep) if c] if len(self.cookies) == 0: raise ValueError('No cookies found in file {0}'.format(fi...
class CookieFile:
def __init__(self, filename): with open(filename) as f: text = f.read() sep = os.linesep + '%' + os.linesep self.cookies = [c for c in text.split(sep) if c] if len(self.cookies) == 0: raise ValueError('No cookies found in file {0}'.format(filename)) se...
import os import random import sys import glob class CookieFile:
17
64
163
4
12
meffie/grpc-demos
fortune/fortune.py
Python
CookieFile
CookieFile
7
28
7
8
cb10f13fd40f1154d95b0acdd2340f326170ae40
bigcode/the-stack
train
3859f4b305d5fdb927050301
train
function
def ceil4(n): """returns the next integer which is a multiple of 4""" return (n + 3) & ~3
def ceil4(n):
"""returns the next integer which is a multiple of 4""" return (n + 3) & ~3
# First released as C++ program by Hiroyuki Tsutsumi as part of the free software suite “Beer” # I thought porting it to Python could be both a challenge and useful from sys import argv, exit, getsizeof from struct import pack_into, unpack_from def ceil4(n):
64
64
31
5
58
michaelgale/pdfdoc-py
fonts/ttc2ttf.py
Python
ceil4
ceil4
11
13
11
11
ce0f478fee2fd241ca6e37d6921396f8110fb828
bigcode/the-stack
train
b027620b468eab22e4a730d1
train
class
class SurfaceService: WIREFRAME_TYPE = 'W' SURFACE_TYPE = 'S' @staticmethod def visualize_surface(surface: Surface) -> None: fig = plt.figure(figsize=(surface.window_size[0], surface.window_size[1])) ax = fig.add_subplot(projection='3d') fig.canvas.set_window_title(surface.windo...
class SurfaceService:
WIREFRAME_TYPE = 'W' SURFACE_TYPE = 'S' @staticmethod def visualize_surface(surface: Surface) -> None: fig = plt.figure(figsize=(surface.window_size[0], surface.window_size[1])) ax = fig.add_subplot(projection='3d') fig.canvas.set_window_title(surface.window_title) fig.s...
# @author Denis Chuprynin <denischuprynin@gmail.com> import numpy as np import matplotlib.pyplot as plt from py_expression_eval import Parser from app.lib.chart import Surface from app.lib.chart.SurfaceServiceException import SurfaceServiceException class SurfaceService:
58
90
303
4
53
Jamesforelock/data-visualizer
app/lib/chart/SurfaceService.py
Python
SurfaceService
SurfaceService
11
43
11
11
51965fd2745690c292d68ab5e66ba8705aaba1e5
bigcode/the-stack
train
0debde20cd4ff6235b80a684
train
class
class common_data(object): """ This is a middleware class that eagerly retrieves page data that might be common to most requests. It is basically a wrapper around Sherif's implementation of common_page_data. The data is stored as a field of request. """ def process_view (self, request, view_...
class common_data(object):
""" This is a middleware class that eagerly retrieves page data that might be common to most requests. It is basically a wrapper around Sherif's implementation of common_page_data. The data is stored as a field of request. """ def process_view (self, request, view_func, view_args, view_kwarg...
from courses.common_page_data import get_common_page_data from django.http import Http404 from c2g.models import Course import logging logger = logging.getLogger(__name__) class common_data(object):
42
74
247
5
37
csev/class2go
main/courses/common_page_data_middleware.py
Python
common_data
common_data
8
34
8
8
b9316e3d0cf621fd09fe270c32ba0e03a1b96225
bigcode/the-stack
train
ce782faade8da355a0efc088
train
function
def get_stopwords_list(stopwords_path): """返回stopwords列表""" stopwords_list = [i.strip() for i in codecs.open(stopwords_path, encoding='utf-8').readlines()] return stopwords_list
def get_stopwords_list(stopwords_path):
"""返回stopwords列表""" stopwords_list = [i.strip() for i in codecs.open(stopwords_path, encoding='utf-8').readlines()] return stopwords_list
预处理模块 @Description : 分词 """ import os import re import jieba import jieba.analyse import jieba.posseg as pseg import codecs abspath = "../../words/" # 加载停用词列表 def get_stopwords_list(stopwords_path):
64
64
50
9
54
yangpanyang/DemoPractice
recsys/projects/textReco/offline/feature_engineering/preprocessing.py
Python
get_stopwords_list
get_stopwords_list
22
26
22
22
56a42b8ac5dd63636c2f7092919d1f1db895bd2b
bigcode/the-stack
train
4e98fc33619bf3d6ce4c3866
train
function
def textrank(partition): # 结巴加载用户词典 userDict_path = os.path.join(abspath, "ITKeywords.txt") jieba.load_userdict(userDict_path) # 加载停用词列表 stopwords_path = os.path.join(abspath, "stopwords.txt") stopwords_list = get_stopwords_list(stopwords_path) # TextRank过滤窗口大小为5,单词最小为2 textrank_model ...
def textrank(partition): # 结巴加载用户词典
userDict_path = os.path.join(abspath, "ITKeywords.txt") jieba.load_userdict(userDict_path) # 加载停用词列表 stopwords_path = os.path.join(abspath, "stopwords.txt") stopwords_list = get_stopwords_list(stopwords_path) # TextRank过滤窗口大小为5,单词最小为2 textrank_model = TextRank(stopwords_list, window=5, wor...
return False if wp.flag in self.pos_filt and len(wp.word.strip()) >= self.word_min_len \ and wp.word.lower() not in self.stopwords_list: return True # texrank def textrank(partition): # 结巴加载用户词典
64
64
214
17
46
yangpanyang/DemoPractice
recsys/projects/textReco/offline/feature_engineering/preprocessing.py
Python
textrank
textrank
93
109
93
94
bb5a4d451f2b46a3ae682af4d0820c4d61672919
bigcode/the-stack
train
a708452db00d2bd3f58de51c
train
class
class TextRank(jieba.analyse.TextRank): def __init__(self, stopwords_list, window=20, word_min_len=2): super(TextRank, self).__init__() self.stopwords_list = stopwords_list self.span = window # 窗口大小 self.word_min_len = word_min_len # 单词的最小长度 # 要保留的词性,根据jieba github ,具体参见htt...
class TextRank(jieba.analyse.TextRank):
def __init__(self, stopwords_list, window=20, word_min_len=2): super(TextRank, self).__init__() self.stopwords_list = stopwords_list self.span = window # 窗口大小 self.word_min_len = word_min_len # 单词的最小长度 # 要保留的词性,根据jieba github ,具体参见https://github.com/baidu/lac self.p...
结果 for row in partition: sentence = re.sub("<.*?>", "", row.sentence) # 替换掉标签数据 words = cut_sentence(sentence, stopwords_list) yield row.article_id, row.channel_id, words # 重写分词部分 class TextRank(jieba.analyse.TextRank):
72
72
241
11
60
yangpanyang/DemoPractice
recsys/projects/textReco/offline/feature_engineering/preprocessing.py
Python
TextRank
TextRank
71
89
71
71
f79bef4f0a34f9ac0a37f29f51a9412367651649
bigcode/the-stack
train
3ef7f6ab40585806ef83330f
train
function
def cut_sentence(sentence, stopwords_list): """对切割之后的词语进行过滤,去除停用词,保留名词,英文和自定义词库中的词,长度大于2的词""" # print(sentence,"*"*100) # eg:[pair('今天', 't'), pair('有', 'd'), pair('雾', 'n'), pair('霾', 'g')] seg_list = pseg.lcut(sentence) seg_list = [i for i in seg_list if i.flag not in stopwords_list] filtered_...
def cut_sentence(sentence, stopwords_list):
"""对切割之后的词语进行过滤,去除停用词,保留名词,英文和自定义词库中的词,长度大于2的词""" # print(sentence,"*"*100) # eg:[pair('今天', 't'), pair('有', 'd'), pair('雾', 'n'), pair('霾', 'g')] seg_list = pseg.lcut(sentence) seg_list = [i for i in seg_list if i.flag not in stopwords_list] filtered_words_list = [] for seg in seg_list: ...
# 加载停用词列表 def get_stopwords_list(stopwords_path): """返回stopwords列表""" stopwords_list = [i.strip() for i in codecs.open(stopwords_path, encoding='utf-8').readlines()] return stopwords_list # 分词实现 def cut_sentence(sentence, stopwords_list):
73
73
244
9
63
yangpanyang/DemoPractice
recsys/projects/textReco/offline/feature_engineering/preprocessing.py
Python
cut_sentence
cut_sentence
30
50
30
30
e9b895e8eba3f1c21c0de5b691e2da3898e22201
bigcode/the-stack
train
0d18d000b3098def8c4f7ccc
train
function
def segmentation(partition): # 结巴加载用户词典 userDict_path = os.path.join(abspath, "ITKeywords.txt") jieba.load_userdict(userDict_path) # 加载停用词列表 stopwords_path = os.path.join(abspath, "stopwords.txt") stopwords_list = get_stopwords_list(stopwords_path) # 对每一行的sentence字段分词,以生成器的方式返回结果 for r...
def segmentation(partition): # 结巴加载用户词典
userDict_path = os.path.join(abspath, "ITKeywords.txt") jieba.load_userdict(userDict_path) # 加载停用词列表 stopwords_path = os.path.join(abspath, "stopwords.txt") stopwords_list = get_stopwords_list(stopwords_path) # 对每一行的sentence字段分词,以生成器的方式返回结果 for row in partition: sentence = re.sub("...
eng"]: # 是自定一个词语、或者是英文单词,可以加些处理 filtered_words_list.append(seg.word) return filtered_words_list # 将文章数据进行分词处理,得到分词结果 def segmentation(partition): # 结巴加载用户词典
64
64
150
15
48
yangpanyang/DemoPractice
recsys/projects/textReco/offline/feature_engineering/preprocessing.py
Python
segmentation
segmentation
54
67
54
55
d5c342b2ee96fb055cfb0949053982625d46b2f9
bigcode/the-stack
train
6dc837f4ae9c1572375369d6
train
class
class ScalingInterface(abc.ABC): @abc.abstractmethod def get_scaled_input_expressions(self, input_vars): """ This method returns a list of expressions for the scaled inputs from the unscaled inputs""" pass @abc.abstractmethod def get_unscaled_output_expressions(self, scaled_outp...
class ScalingInterface(abc.ABC): @abc.abstractmethod
def get_scaled_input_expressions(self, input_vars): """ This method returns a list of expressions for the scaled inputs from the unscaled inputs""" pass @abc.abstractmethod def get_unscaled_output_expressions(self, scaled_output_vars): """This method returns a list of expres...
import abc """ This module describes the interface for providing different scaling expressions to the Pyomo model for the inputs and outputs of the neural network. An implementation of a common scaling approach is included below. """ class ScalingInterface(abc.ABC): @abc.abstractmethod
60
64
94
14
46
or-fusion/OptML
opt/scaling.py
Python
ScalingInterface
ScalingInterface
9
20
9
10
57c2c655846e34983d8928a7bfd85cbbbe84746e
bigcode/the-stack
train
0fdcbe8753ab57499e9628fe
train
class
class OffsetScaling(ScalingInterface): def __init__(self, offset_inputs, factor_inputs, offset_outputs, factor_outputs): """ This scaling object represents the following scaling equations for inputs (x) and outputs (y) scaled_x_i = (x_i-offset_inputs_i)/factor_inputs_i scale...
class OffsetScaling(ScalingInterface):
def __init__(self, offset_inputs, factor_inputs, offset_outputs, factor_outputs): """ This scaling object represents the following scaling equations for inputs (x) and outputs (y) scaled_x_i = (x_i-offset_inputs_i)/factor_inputs_i scaled_y_i = (y_i-offset_outputs_i)/factor_o...
. """ class ScalingInterface(abc.ABC): @abc.abstractmethod def get_scaled_input_expressions(self, input_vars): """ This method returns a list of expressions for the scaled inputs from the unscaled inputs""" pass @abc.abstractmethod def get_unscaled_output_expressions(self, scale...
103
103
344
7
95
or-fusion/OptML
opt/scaling.py
Python
OffsetScaling
OffsetScaling
22
61
22
22
b15a74d48c4b57a89a0f80389294709107dd6426
bigcode/the-stack
train
bc255b46a85487fe7513f477
train
class
class Test_lin_to_db_input_datatypes(unittest.TestCase): def test_single(self): x = lin2db(1) self.assertEqual(x.ndim, 0) self.assertAlmostEqual(x, 0.0, places=6) def test_tuple(self): x = lin2db((1, 0.1)) self.assertEqual(x.ndim, 1) self.assertAlmostEqual(x[0], ...
class Test_lin_to_db_input_datatypes(unittest.TestCase):
def test_single(self): x = lin2db(1) self.assertEqual(x.ndim, 0) self.assertAlmostEqual(x, 0.0, places=6) def test_tuple(self): x = lin2db((1, 0.1)) self.assertEqual(x.ndim, 1) self.assertAlmostEqual(x[0], 0.0, places=6) self.assertAlmostEqual(x[1], -20...
def test_known_value_6(self): x = db2pow(6.02) self.assertAlmostEqual(x, 4.0, places=2) def test_known_value_neg_3(self): x = db2pow(-3) self.assertAlmostEqual(x, 0.5, places=2) def test_known_value_neg_10(self): x = db2pow(-10) self.assertAlmostEqual(x, 0.1, p...
117
117
392
12
105
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_lin_to_db_input_datatypes
Test_lin_to_db_input_datatypes
130
164
130
130
58b01889e2c301841780ec38c96aa925db6ee44d
bigcode/the-stack
train
5633185af3f85cef92825094
train
class
class Test_db_to_lin_input_datatypes(unittest.TestCase): def test_single(self): x = db2lin(0) self.assertEqual(x.ndim, 0) self.assertAlmostEqual(x, 1.0, places=6) def test_tuple(self): x = db2lin((40, -40)) self.assertEqual(x.ndim, 1) self.assertAlmostEqual(x[0],...
class Test_db_to_lin_input_datatypes(unittest.TestCase):
def test_single(self): x = db2lin(0) self.assertEqual(x.ndim, 0) self.assertAlmostEqual(x, 1.0, places=6) def test_tuple(self): x = db2lin((40, -40)) self.assertEqual(x.ndim, 1) self.assertAlmostEqual(x[0], 100.0, places=6) self.assertAlmostEqual(x[1], ...
2) self.assertTrue((x < 0.0001).all()) self.assertTrue((x > -0.0001).all()) def test_np_ndim_2_4x10(self): x = lin2db(np.ones((4, 10))) self.assertEqual(x.ndim, 2) self.assertTrue((x < 0.0001).all()) self.assertTrue((x > -0.0001).all()) class Test_db_to_lin_input_...
116
116
389
12
104
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_db_to_lin_input_datatypes
Test_db_to_lin_input_datatypes
166
200
166
166
ca206a06b04338dd8e9d19022edff93c916b300a
bigcode/the-stack
train
079897f031813eca9cea839b
train
class
class Test_lin_to_db_known_values(unittest.TestCase): def test_known_value_1(self): x = lin2db(1) self.assertAlmostEqual(x, 0.0, places=6) def test_known_value_0_1(self): x = lin2db(0.1) self.assertAlmostEqual(x, -20.0, places=6) def test_known_value_0_5(self): x ...
class Test_lin_to_db_known_values(unittest.TestCase):
def test_known_value_1(self): x = lin2db(1) self.assertAlmostEqual(x, 0.0, places=6) def test_known_value_0_1(self): x = lin2db(0.1) self.assertAlmostEqual(x, -20.0, places=6) def test_known_value_0_5(self): x = lin2db(0.5) self.assertAlmostEqual(x, -6.02,...
) self.assertEqual(len(x), 2) self.assertAlmostEqual(x[0], 1.234567, places=6) self.assertAlmostEqual(x[1], 2.345678, places=6) class Test_lin_to_db_known_values(unittest.TestCase):
64
64
191
11
53
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_lin_to_db_known_values
Test_lin_to_db_known_values
46
65
46
46
112f89164de6115a340d5c86eafb8a21f88012e7
bigcode/the-stack
train
d2e943c1d2527ee5061336d9
train
class
class Test_db_to_lin_known_values(unittest.TestCase): def test_known_value_0(self): x = db2lin(0) self.assertAlmostEqual(x, 1.0, places=6) def test_known_value_neg20(self): x = db2lin(-20) self.assertAlmostEqual(x, 0.1, places=6) def test_known_value_neg6(self): x =...
class Test_db_to_lin_known_values(unittest.TestCase):
def test_known_value_0(self): x = db2lin(0) self.assertAlmostEqual(x, 1.0, places=6) def test_known_value_neg20(self): x = db2lin(-20) self.assertAlmostEqual(x, 0.1, places=6) def test_known_value_neg6(self): x = db2lin(-6) # -6.020599913 self.assertAlmostEq...
(2) self.assertAlmostEqual(x, 6.02, places=2) def test_known_value_0_0(self): x = lin2db(0.0) self.assertTrue(np.isneginf(x)) class Test_db_to_lin_known_values(unittest.TestCase):
64
64
191
11
53
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_db_to_lin_known_values
Test_db_to_lin_known_values
67
86
67
67
7568d54fa71db1b475bc4b332a8da0a01911703e
bigcode/the-stack
train
fef91a238df4c7a2ca228d82
train
class
class Test_pow_to_db_known_values(unittest.TestCase): def test_known_value_1(self): x = pow2db(1) self.assertAlmostEqual(x, 0.0, places=6) def test_known_value_0_1(self): x = pow2db(0.1) self.assertAlmostEqual(x, -10.0, places=6) def test_known_value_0_5(self): x ...
class Test_pow_to_db_known_values(unittest.TestCase):
def test_known_value_1(self): x = pow2db(1) self.assertAlmostEqual(x, 0.0, places=6) def test_known_value_0_1(self): x = pow2db(0.1) self.assertAlmostEqual(x, -10.0, places=6) def test_known_value_0_5(self): x = pow2db(0.5) self.assertAlmostEqual(x, -3.01,...
) self.assertAlmostEqual(x, 2.0, places=2) def test_known_value_neg_inf(self): x = db2lin(float('-inf')) self.assertAlmostEqual(x, 0.0, places=6) class Test_pow_to_db_known_values(unittest.TestCase):
64
64
191
11
53
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_pow_to_db_known_values
Test_pow_to_db_known_values
88
107
88
88
5bfa47cff098a5497d772cf6e1e5faefce8f44d6
bigcode/the-stack
train
69cb74fd13cef0c3bcabc70c
train
class
class Test_back_to_back(unittest.TestCase): def test_nested(self): x = lin2db(db2pow(pow2db(db2lin(1.234567)))) self.assertAlmostEqual(x, 1.234567, places=6) def test_lin_to_db_to_lin(self): x = lin2db(db2lin( 1.234567)) self.assertAlmostEqual(x, 1.2345...
class Test_back_to_back(unittest.TestCase):
def test_nested(self): x = lin2db(db2pow(pow2db(db2lin(1.234567)))) self.assertAlmostEqual(x, 1.234567, places=6) def test_lin_to_db_to_lin(self): x = lin2db(db2lin( 1.234567)) self.assertAlmostEqual(x, 1.234567, places=6) def test_pow_to_db_to_po...
''' Created on 23 Oct 2014 @author: Ronny Andersson (ronny@andersson.tk) @copyright: (c) 2014 Ronny Andersson @license: MIT ''' # standard library import unittest # external libraries import numpy as np import nose # local libraries from zignal import lin2db, db2lin, pow2db, db2pow class Test_back_to_back(unittest....
96
102
343
9
86
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_back_to_back
Test_back_to_back
19
44
19
19
5a134f2381f54c6a8a5b51d08a536e0dfb2fd75c
bigcode/the-stack
train
500854fd9418cee5bb4feb8c
train
class
class Test_db_to_pow_known_values(unittest.TestCase): def test_known_value_0(self): x = db2pow(0) self.assertAlmostEqual(x, 1.0, places=6) def test_known_value_3(self): x = db2pow(3) self.assertAlmostEqual(x, 2.0, places=2) def test_known_value_6(self): x = db2pow(6...
class Test_db_to_pow_known_values(unittest.TestCase):
def test_known_value_0(self): x = db2pow(0) self.assertAlmostEqual(x, 1.0, places=6) def test_known_value_3(self): x = db2pow(3) self.assertAlmostEqual(x, 2.0, places=2) def test_known_value_6(self): x = db2pow(6.02) self.assertAlmostEqual(x, 4.0, places=2) ...
(2) self.assertAlmostEqual(x, 3.01, places=2) def test_known_value_0_0(self): x = pow2db(0.0) self.assertTrue(np.isneginf(x)) class Test_db_to_pow_known_values(unittest.TestCase):
64
64
185
11
53
ZenulAbidin/zignal
zignal/tests/test_db_conversions.py
Python
Test_db_to_pow_known_values
Test_db_to_pow_known_values
109
128
109
109
81756f336533f70e3f1df32337b59aebcfe6bfd5
bigcode/the-stack
train
3643391e857322513163ad41
train
function
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('comments') op.drop_table('pitches') op.drop_index(op.f('ix_users_username'), table_name='users') op.drop_index(op.f('ix_users_email'), table_name='users') op.drop_table('users')
def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.drop_table('comments') op.drop_table('pitches') op.drop_index(op.f('ix_users_username'), table_name='users') op.drop_index(op.f('ix_users_email'), table_name='users') op.drop_table('users')
.ForeignKeyConstraint(['pitch'], ['pitches.id'], ), sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ###
63
64
72
18
45
AmimoG/1MPitch
migrations/versions/837fe2c21f34_initial_migration.py
Python
downgrade
downgrade
59
65
59
60
592f2111192e9d8cf6f8b2986c0df1a6a412286f
bigcode/the-stack
train
fc2e9aefc0a1036917b52ad3
train
function
def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=255), nullable=True), sa.Column('firstname', sa.String(length=255), nullable=True), sa.Column('lastname', sa...
def upgrade(): # ### commands auto generated by Alembic - please adjust! ###
op.create_table('users', sa.Column('id', sa.Integer(), nullable=False), sa.Column('username', sa.String(length=255), nullable=True), sa.Column('firstname', sa.String(length=255), nullable=True), sa.Column('lastname', sa.String(length=255), nullable=True), sa.Column('email', sa.String(length=255)...
"""Initial Migration Revision ID: 837fe2c21f34 Revises: Create Date: 2020-09-24 14:06:24.205591 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '837fe2c21f34' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ge...
108
132
443
18
89
AmimoG/1MPitch
migrations/versions/837fe2c21f34_initial_migration.py
Python
upgrade
upgrade
19
55
19
20
3fefbd213f3a23104b7470c39ba63fa59fb74023
bigcode/the-stack
train
417dc077fcc777e103667afb
train
function
def save_query(text): global opfile opfile.write(text) opfile.flush() return
def save_query(text):
global opfile opfile.write(text) opfile.flush() return
SCLstm(pretrained=True), # "scrnn-bert": CorrectorSCLstmBert(pretrained=True) } print("\n") for k,v in PRELOADED_MODELS.items(): print(f"{k}: {v}") print("\n") return def save_query(text):
64
64
20
5
58
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
save_query
save_query
133
137
133
133
e3386fb62b2c03e9329c8d000aad6dd9e5cccb89
bigcode/the-stack
train
08bdf16f84931e2e46fde3aa
train
function
@app.route('/') @app.route('/home', methods=['POST']) def home(): return render_template('home.html')
@app.route('/') @app.route('/home', methods=['POST']) def home():
return render_template('home.html')
(os.path.join( LOGS_PATH, str(time())+".logs.txt" ), "w") # Define the app app = Flask(__name__) CORS(app) # needed for cross-domain requests, allow everything by default @app.route('/') @app.route('/home', methods=['POST']) def home():
64
64
23
16
47
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
home
home
38
41
38
40
5fed6f4352f900680a4a2b5ef733cea85296c91a
bigcode/the-stack
train
e21a210203e032c16464caeb
train
function
def load_model(model_keyword="elmosc-rnn"): global PRELOADED_MODELS if model_keyword in PRELOADED_MODELS: return PRELOADED_MODELS[model_keyword] if model_keyword=="aspell": return CorrectorAspell(tokenize=TOKENIZE) elif model_keyword=="jamspell": return CorrectorJamspell(tokenize=TOKENIZE) elif mod...
def load_model(model_keyword="elmosc-rnn"):
global PRELOADED_MODELS if model_keyword in PRELOADED_MODELS: return PRELOADED_MODELS[model_keyword] if model_keyword=="aspell": return CorrectorAspell(tokenize=TOKENIZE) elif model_keyword=="jamspell": return CorrectorJamspell(tokenize=TOKENIZE) elif model_keyword=="cnn-rnn": return CorrectorCnn...
= PRELOADED_MODELS[CURR_MODEL_KEYWORD].correct_strings_for_ui([message], topk=TOPK) # save_query(CURR_MODEL_KEYWORD+"\t"+message+"\t"+"\t".join(results)+"\n") # return render_template('results.html', prediction=results, message=message) return render_template('home.html') def load_model(model_keyword="elmos...
91
91
304
12
79
suryabulusu/neuspell
neuspell/flask-server/app.py
Python
load_model
load_model
83
110
83
83
e53b9fe06c2d00377ed89f40d6720093148a2a18
bigcode/the-stack
train