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
d006c25f7342603da9ac23d9
train
function
def test_SciPyPrinter(): p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p...
def test_SciPyPrinter():
p = SciPyPrinter() expr = acos(x) assert 'numpy' not in p.module_imports assert p.doprint(expr) == 'numpy.arccos(x)' assert 'numpy' in p.module_imports assert not any(m.startswith('scipy') for m in p.module_imports) smat = SparseMatrix(2, 5, {(0, 1): 3}) assert p.doprint(smat) == 'scipy....
x) + y' # Workaround for numpy negative integer power errors assert p.doprint(x**-1) == 'x**(-1.0)' assert p.doprint(x**-2) == 'x**(-2.0)' def test_SciPyPrinter():
63
64
147
7
56
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
test_SciPyPrinter
test_SciPyPrinter
86
95
86
86
7ee52b0b38eeb2b9c11a30943a538fd9d5d454e0
bigcode/the-stack
train
50d7189d1d9d984aba1c68c5
train
function
def test_NumPyPrinter(): p = NumPyPrinter() assert p.doprint(sign(x)) == 'numpy.sign(x)' A = MatrixSymbol("A", 2, 2) assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" assert p.doprint(Identity(3)) == "numpy.eye(3)" u = MatrixSymbo...
def test_NumPyPrinter():
p = NumPyPrinter() assert p.doprint(sign(x)) == 'numpy.sign(x)' A = MatrixSymbol("A", 2, 2) assert p.doprint(A**(-1)) == "numpy.linalg.inv(A)" assert p.doprint(A**5) == "numpy.linalg.matrix_power(A, 5)" assert p.doprint(Identity(3)) == "numpy.eye(3)" u = MatrixSymbol('x', 2, 1) v = Matr...
test_MpmathPrinter(): p = MpmathPrinter() assert p.doprint(sign(x)) == 'mpmath.sign(x)' assert p.doprint(Rational(1, 2)) == 'mpmath.mpf(1)/mpmath.mpf(2)' def test_NumPyPrinter():
66
67
226
6
60
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
test_NumPyPrinter
test_NumPyPrinter
69
83
69
69
9bbe1237ac42ba3c6646a8528746ff5310a251ce
bigcode/the-stack
train
f0a16b9433fbcd729362b480
train
function
def test_printmethod(): obj = CustomPrintedObject() assert NumPyPrinter().doprint(obj) == 'numpy' assert MpmathPrinter().doprint(obj) == 'mpmath'
def test_printmethod():
obj = CustomPrintedObject() assert NumPyPrinter().doprint(obj) == 'numpy' assert MpmathPrinter().doprint(obj) == 'mpmath'
tr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' class CustomPrintedObject(Expr): def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath' def test_printmethod():
64
64
44
5
59
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
test_printmethod
test_printmethod
144
147
144
144
60965de4cd8fbce22b7bb52c58938ec2a50a879f
bigcode/the-stack
train
1fe60b2c30d6074a108dd914
train
function
def test_pycode_reserved_words(): s1, s2 = symbols('if else') raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True)) py_str = pycode(s1 + s2) assert py_str in ('else_ + if_', 'if_ + else_')
def test_pycode_reserved_words():
s1, s2 = symbols('if else') raises(ValueError, lambda: pycode(s1 + s2, error_on_reserved=True)) py_str = pycode(s1 + s2) assert py_str in ('else_ + if_', 'if_ + else_')
0, 1): 3}) assert p.doprint(smat) == 'scipy.sparse.coo_matrix([3], ([0], [1]), shape=(2, 5))' assert 'scipy.sparse' in p.module_imports def test_pycode_reserved_words():
64
64
69
7
56
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
test_pycode_reserved_words
test_pycode_reserved_words
98
102
98
98
2481e6f5e97819072cbfb75be04d5ee8f3d17c68
bigcode/the-stack
train
93365baffb8d4c886603c982
train
function
def test_NumPyPrinter_print_seq(): n = NumPyPrinter() assert n._print_seq(range(2)) == '(0, 1,)'
def test_NumPyPrinter_print_seq():
n = NumPyPrinter() assert n._print_seq(range(2)) == '(0, 1,)'
== 'None' def test_issue_14283(): prntr = PythonCodePrinter() assert prntr.doprint(zoo) == "float('nan')" assert prntr.doprint(-oo) == "float('-inf')" def test_NumPyPrinter_print_seq():
64
64
33
8
55
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
test_NumPyPrinter_print_seq
test_NumPyPrinter_print_seq
160
163
160
160
ff20df0736aa31616882fcafc57e73656bb89b37
bigcode/the-stack
train
ba85df2ca83713ee250df198
train
class
class CustomPrintedObject(Expr): def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath'
class CustomPrintedObject(Expr):
def _numpycode(self, printer): return 'numpy' def _mpmathcode(self, printer): return 'mpmath'
prntr = SymPyPrinter() assert prntr._print_Pow(sqrt(x), rational=False) == 'sympy.sqrt(x)' assert prntr._print_Pow(sqrt(x), rational=True) == 'x**(1/2)' class CustomPrintedObject(Expr):
63
64
37
7
56
miguelmarco/sympy
sympy/printing/tests/test_pycode.py
Python
CustomPrintedObject
CustomPrintedObject
136
141
136
136
f9b7a5af5a1cbeb1c1ba80dae688e4955a5221d1
bigcode/the-stack
train
02525efc7fe43b67ffd63ed8
train
class
class PercentileStatisticCollector(OfflineTensorStatisticCollector): def __init__(self, percentiles_to_collect: List[float], reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, ...
class PercentileStatisticCollector(OfflineTensorStatisticCollector):
def __init__(self, percentiles_to_collect: List[float], reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples, window_size) self._percentiles_to_collect = perc...
(numpy_median).to(dtype=torch.float) mad_tensor = torch.from_numpy(numpy_mad).to(dtype=torch.float) median_tensor = expand_like(median_tensor, reduction_shape) mad_tensor = expand_like(mad_tensor, reduction_shape) retval[reduction_shape] = MedianMADTensorStatistic(median...
87
87
291
11
75
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
PercentileStatisticCollector
PercentileStatisticCollector
181
201
181
181
b45441425e09a13793712fdd7f1694a244256e81
bigcode/the-stack
train
f33c9cead62c88caa9cb82e0
train
class
class OnlineTensorStatisticCollector(TensorStatisticCollectorBase, ABC): pass
class OnlineTensorStatisticCollector(TensorStatisticCollectorBase, ABC):
pass
_samples = 0 self._reset() @abstractmethod def _reset(self): pass def collected_samples(self) -> int: return self._collected_samples class StatisticsNotCollectedError(Exception): pass class OnlineTensorStatisticCollector(TensorStatisticCollectorBase, ABC):
64
64
16
13
50
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
OnlineTensorStatisticCollector
OnlineTensorStatisticCollector
68
69
68
68
b0d0880480016640928a58716d7f3c8bf62c6cc3
bigcode/the-stack
train
0c8bec00b9d68921615c3e1b
train
class
class OfflineTensorStatisticCollector(TensorStatisticCollectorBase, ABC): def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples) self._samples = deque(maxlen=window_size) # ...
class OfflineTensorStatisticCollector(TensorStatisticCollectorBase, ABC):
def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples) self._samples = deque(maxlen=window_size) # type: Deque[torch.Tensor] def _register_input(self, x: torch.Tensor):...
def _reset(self): pass def collected_samples(self) -> int: return self._collected_samples class StatisticsNotCollectedError(Exception): pass class OnlineTensorStatisticCollector(TensorStatisticCollectorBase, ABC): pass class OfflineTensorStatisticCollector(TensorStatisticCollectorBase,...
64
64
123
13
50
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
OfflineTensorStatisticCollector
OfflineTensorStatisticCollector
72
83
72
72
813e0b9f68eec6ca5edcdd1295897ae87937b7f9
bigcode/the-stack
train
75db7a84ca987c78ea8dc5aa
train
class
class MeanMinMaxStatisticCollector(OfflineTensorStatisticCollector): def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples, window_size) self._window_size = window_size self._all_min_...
class MeanMinMaxStatisticCollector(OfflineTensorStatisticCollector):
def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples, window_size) self._window_size = window_size self._all_min_values = {} # type: Dict[ReductionShape, Deque] self._all_ma...
self._max_values[reduction_shape]) def _get_statistics(self) -> Dict[ReductionShape, MinMaxTensorStatistic]: return {rs: MinMaxTensorStatistic(self._min_values[rs], self._max_values[rs]) for rs in self._reduction_shapes} def _reset(self): self._min_values = {rs: None for rs in self._reduction...
133
133
445
12
121
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
MeanMinMaxStatisticCollector
MeanMinMaxStatisticCollector
120
155
120
120
c801b6566692611c7187e820884b0638858e6405
bigcode/the-stack
train
1b7a3252468ba9bcc67c23f1
train
class
class TensorStatisticCollectorBase(ABC): def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None): self._reduction_shapes = reduction_shapes self._enabled = True self._collected_samples = 0 self._num_samples = num_samples def register_input(self,...
class TensorStatisticCollectorBase(ABC):
def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None): self._reduction_shapes = reduction_shapes self._enabled = True self._collected_samples = 0 self._num_samples = num_samples def register_input(self, x: torch.Tensor) -> torch.Tensor: ...
, Dict, Set, Tuple, Deque import torch import numpy as np from nncf.dynamic_graph.context import no_nncf_trace from nncf.tensor_statistics.reduction import min_reduce_like, max_reduce_like, get_per_channel_history, expand_like from nncf.tensor_statistics.statistics import TensorStatistic, MinMaxTensorStatistic, Media...
95
95
317
8
87
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
TensorStatisticCollectorBase
TensorStatisticCollectorBase
16
61
16
16
81c2ad2340b25cb2f2c801c1b015ba768ec610d1
bigcode/the-stack
train
2308a53b3c440048ae6addde
train
class
class MedianMADStatisticCollector(OfflineTensorStatisticCollector): def _get_statistics(self) -> Dict[ReductionShape, MedianMADTensorStatistic]: retval = {} # type: Dict[ReductionShape, MedianMADTensorStatistic] for reduction_shape in self._reduction_shapes: per_channel_history = get_per...
class MedianMADStatisticCollector(OfflineTensorStatisticCollector):
def _get_statistics(self) -> Dict[ReductionShape, MedianMADTensorStatistic]: retval = {} # type: Dict[ReductionShape, MedianMADTensorStatistic] for reduction_shape in self._reduction_shapes: per_channel_history = get_per_channel_history(self._samples, reduction_shape, ...
min_values = stacked_min.mean(dim=0).view(rs) stacked_max = torch.stack(list(self._all_max_values[rs])) max_values = stacked_max.mean(dim=0).view(rs) retval[rs] = MinMaxTensorStatistic(min_values, max_values) return retval class MedianMADStatisticCollector(OfflineTensorStat...
73
73
244
11
61
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
MedianMADStatisticCollector
MedianMADStatisticCollector
158
178
158
158
89eef7a602a162befe65dc1b822fdfce0143f940
bigcode/the-stack
train
4f588c28d7c2cba70174bf33
train
class
class StatisticsNotCollectedError(Exception): pass
class StatisticsNotCollectedError(Exception):
pass
self._enabled = False def reset(self): self._collected_samples = 0 self._reset() @abstractmethod def _reset(self): pass def collected_samples(self) -> int: return self._collected_samples class StatisticsNotCollectedError(Exception):
64
64
10
7
56
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
StatisticsNotCollectedError
StatisticsNotCollectedError
64
65
64
64
c6bc65ca5ad55a1abc6687a461637e327a3438be
bigcode/the-stack
train
bd241c806504d9d82837652a
train
class
class MinMaxStatisticCollector(OnlineTensorStatisticCollector): def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None): super().__init__(reduction_shapes, num_samples) if self._reduction_shapes is not None: self._min_values = {rs: None for rs in self._r...
class MinMaxStatisticCollector(OnlineTensorStatisticCollector):
def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None): super().__init__(reduction_shapes, num_samples) if self._reduction_shapes is not None: self._min_values = {rs: None for rs in self._reduction_shapes} # type: Dict[ReductionShape] self....
pass class OfflineTensorStatisticCollector(TensorStatisticCollectorBase, ABC): def __init__(self, reduction_shapes: Set[ReductionShape] = None, num_samples: int = None, window_size: int = None): super().__init__(reduction_shapes, num_samples) self._samples = deque(maxlen=window_s...
136
136
456
11
125
kshpv/nncf_pytorch
nncf/tensor_statistics/collectors.py
Python
MinMaxStatisticCollector
MinMaxStatisticCollector
86
117
86
86
74eccc4000007ff9b98e66ed06af8873cec77102
bigcode/the-stack
train
5d502ec2cd86bbb917fed890
train
function
def get_model_params(model_name, override_params): """Get the block args and global params for a given model.""" if model_name.startswith('efficientnet'): width_coefficient, depth_coefficient, _, dropout_rate, se_coefficient = ( efficientnet_x_params(model_name)) blocks_args, global_params = efficie...
def get_model_params(model_name, override_params):
"""Get the block args and global params for a given model.""" if model_name.startswith('efficientnet'): width_coefficient, depth_coefficient, _, dropout_rate, se_coefficient = ( efficientnet_x_params(model_name)) blocks_args, global_params = efficientnet_x( width_coefficient, depth_coefficie...
.layers.BatchNormalization. batch_norm=utils.TpuBatchNormalization, # TPU-specific requirement. use_se=True, se_coefficient=se_coefficient) decoder = efficientnet_builder.BlockDecoder() return decoder.decode(blocks_args), global_params def get_model_params(model_name, override_params):
64
64
182
10
53
aigagror/tpu
models/official/efficientnet/tpu/efficientnet_x_builder.py
Python
get_model_params
get_model_params
88
105
88
88
ef32cbfbf33094f7e0d0127b9c07038fb836060f
bigcode/the-stack
train
f9c97b1a508d49c5e69b80af
train
function
def efficientnet_x(width_coefficient=None, depth_coefficient=None, se_coefficient=None, dropout_rate=0.2, survival_prob=0.8): """Creates a efficientnet model.""" blocks_args = [ 'r1_k3_s11_e1_i32_o16_se0.25_d1_a0', 'r2_k3_s22_e6...
def efficientnet_x(width_coefficient=None, depth_coefficient=None, se_coefficient=None, dropout_rate=0.2, survival_prob=0.8):
"""Creates a efficientnet model.""" blocks_args = [ 'r1_k3_s11_e1_i32_o16_se0.25_d1_a0', 'r2_k3_s22_e6_i16_o24_se0.25_f1_d2_a1', 'r2_k5_s22_e6_i24_o40_se0.25_f1_a1', 'r3_k3_s22_e6_i40_o80_se0.25_a0', 'r3_k5_s11_e6_i80_o112_se0.25_a0', 'r4_k5_s22_e6_i112_o192_se0.25_a0', 'r1...
0.4, 1), 'efficientnet-x-b6': (1.8, 2.6, 528, 0.5, 1), 'efficientnet-x-b7': (2.0, 3.1, 600, 0.5, 1), } return params_dict[model_name] def efficientnet_x(width_coefficient=None, depth_coefficient=None, se_coefficient=None, dropout_rate=0.2, ...
112
112
376
37
75
aigagror/tpu
models/official/efficientnet/tpu/efficientnet_x_builder.py
Python
efficientnet_x
efficientnet_x
52
85
52
56
cf0041e879349ebc0244c896821ff8b9e9add1b4
bigcode/the-stack
train
94c306eeb8b39e9f78f9cb0c
train
function
def build_model_base(images, model_name, training, override_params=None): """Create a base feature network and return the features before pooling. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. over...
def build_model_base(images, model_name, training, override_params=None):
"""Create a base feature network and return the features before pooling. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. override_params: A dictionary of params for overriding. Fields must exist in ...
outputs = tf.identity(outputs, 'features') elif pooled_features_only: outputs = tf.identity(outputs, 'pooled_features') else: outputs = tf.identity(outputs, 'logits') return outputs, model.endpoints def build_model_base(images, model_name, training, override_params=None):
64
64
215
15
48
aigagror/tpu
models/official/efficientnet/tpu/efficientnet_x_builder.py
Python
build_model_base
build_model_base
177
203
177
177
e70c1efd62d16738d477195a1b258e91a78616d2
bigcode/the-stack
train
f7134eeb658465a364fdac98
train
function
def efficientnet_x_params(model_name): """Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate, # se_coefficient) 'efficientnet-x-b0': (1.0, 1.0, 224, 0.2, 4), 'efficientnet-x-b1': (1.0, 1.1, 240, 0.2, 2), 'e...
def efficientnet_x_params(model_name):
"""Get efficientnet params based on model name.""" params_dict = { # (width_coefficient, depth_coefficient, resolution, dropout_rate, # se_coefficient) 'efficientnet-x-b0': (1.0, 1.0, 224, 0.2, 4), 'efficientnet-x-b1': (1.0, 1.1, 240, 0.2, 2), 'efficientnet-x-b2': (1.1, 1.2, 260, 0.3,...
import tensorflow.compat.v1 as tf import efficientnet_builder import efficientnet_model import utils MEAN_RGB = [0.485 * 255, 0.456 * 255, 0.406 * 255] STDDEV_RGB = [0.229 * 255, 0.224 * 255, 0.225 * 255] def efficientnet_x_params(model_name):
86
86
289
8
78
aigagror/tpu
models/official/efficientnet/tpu/efficientnet_x_builder.py
Python
efficientnet_x_params
efficientnet_x_params
35
49
35
35
270cab651090ed3498c954df876f016d7d8d57b3
bigcode/the-stack
train
636d6108f9329a88bad5d451
train
function
def build_model(images, model_name, training, override_params=None, model_dir=None, fine_tuning=False, features_only=False, pooled_features_only=False): """A helper function to creates a model and returns p...
def build_model(images, model_name, training, override_params=None, model_dir=None, fine_tuning=False, features_only=False, pooled_features_only=False):
"""A helper function to creates a model and returns predicted logits. Args: images: input images tensor. model_name: string, the predefined model name. training: boolean, whether the model is constructed for training. override_params: A dictionary of params for overriding. Fields must exist in ...
se_coefficient = ( efficientnet_x_params(model_name)) blocks_args, global_params = efficientnet_x( width_coefficient, depth_coefficient, se_coefficient, dropout_rate) else: raise NotImplementedError('model name is not pre-defined: %s' % model_name) if override_params: # ValueError will...
175
175
585
39
135
aigagror/tpu
models/official/efficientnet/tpu/efficientnet_x_builder.py
Python
build_model
build_model
108
174
108
115
640e26eb416ae4f7538ec0ca4c9471cb66998aa8
bigcode/the-stack
train
42c15be00223b3f738679ad2
train
class
class RealAnnularGeometry(object): def __init__(self, speed, curvature, AAG): k = np.fft.fftfreq(curvature.shape[0], 1.0/curvature.shape[0]) dt_curvature = np.fft.ifft(np.fft.fft(curvature)*1j*k).real rv0 = AAG.rv0 rv1 = AAG.rv1 rv2 = AAG.rv2 self.psi0 = speed*(1+rv0[...
class RealAnnularGeometry(object):
def __init__(self, speed, curvature, AAG): k = np.fft.fftfreq(curvature.shape[0], 1.0/curvature.shape[0]) dt_curvature = np.fft.ifft(np.fft.fft(curvature)*1j*k).real rv0 = AAG.rv0 rv1 = AAG.rv1 rv2 = AAG.rv2 self.psi0 = speed*(1+rv0[:,None]*curvature) self.psi...
.radius+self.rv1 self.approx_psi2 = self.radius+self.rv2 self.approx_inv_psi0 = 1.0/self.approx_psi0 self.approx_inv_psi1 = 1.0/self.approx_psi1 self.approx_inv_psi2 = 1.0/self.approx_psi2 # Chebyshev Operators self.CO = ChebyshevOperators(M, self.ratio) class RealAnnular...
107
107
359
7
100
dbstein/ipde
ipde/annular/annular.py
Python
RealAnnularGeometry
RealAnnularGeometry
87
108
87
87
1311362f6e790980e6f3d50a757f801c2b58f33c
bigcode/the-stack
train
d788026df401dc627a9fa7d4
train
class
class ApproximateAnnularGeometry(object): """ Approximate Annular Geometry for solving PDE in annular regions n: number of discrete points in tangential direction M: number of chebyshev modes in radial direction width: width of radial region approx_r: approximate radius of annulus """ de...
class ApproximateAnnularGeometry(object):
""" Approximate Annular Geometry for solving PDE in annular regions n: number of discrete points in tangential direction M: number of chebyshev modes in radial direction width: width of radial region approx_r: approximate radius of annulus """ def __init__(self, n, M, width, approx_r): ...
(temp.dot(self.VI0)) temp = np.zeros([M-2, M-1], dtype=float) np.fill_diagonal(temp, 1.0) self.R12 = self.V2.dot(temp.dot(self.VI1)) self.R02 = self.R12.dot(self.R01) # get poof operator from M-1 --> M temp = np.zeros([M, M-1], dtype=float) np.fill_diagonal(temp, ...
129
129
433
8
121
dbstein/ipde
ipde/annular/annular.py
Python
ApproximateAnnularGeometry
ApproximateAnnularGeometry
52
85
52
52
8af18c1f54291626b7e391e2a908dccb8e650fce
bigcode/the-stack
train
ebab87b04bfc44dc54b336de
train
class
class ChebyshevOperators(object): def __init__(self, M, rat): """ Construct Chebyshev operators to be used in annular solvers Inputs: M (int), number of modes in chebyshev grid rat (float), ratio giving width of annulus to [-1,1] """ self.M = M ...
class ChebyshevOperators(object):
def __init__(self, M, rat): """ Construct Chebyshev operators to be used in annular solvers Inputs: M (int), number of modes in chebyshev grid rat (float), ratio giving width of annulus to [-1,1] """ self.M = M xc0, _ = np.polynomial.cheby...
import numpy as np import scipy as sp import scipy.linalg import scipy.sparse.linalg from ..utilities import concat, get_chebyshev_nodes class ChebyshevOperators(object):
39
192
640
7
31
dbstein/ipde
ipde/annular/annular.py
Python
ChebyshevOperators
ChebyshevOperators
7
50
7
7
db3749bba9388697ec9571abc6d07d3f4d648d07
bigcode/the-stack
train
f036c166ef8f84fccc8f08ac
train
function
def lik_unsampled_fathers(offspring, mothers, allele_freqs, mu, mother_index=None): """ Calculate a matrix of multilocus transition probabilities for an array of offspring and known mothers, but where the paternal allele is drawn from population allele frequencies. Parameters ---------- off...
def lik_unsampled_fathers(offspring, mothers, allele_freqs, mu, mother_index=None):
""" Calculate a matrix of multilocus transition probabilities for an array of offspring and known mothers, but where the paternal allele is drawn from population allele frequencies. Parameters ---------- offspring: genotypeArray Array of observed genotype data for the offspring. ...
import numpy as np from faps.pr_unsampled import pr_unsampled from faps.genotypeArray import genotypeArray def lik_unsampled_fathers(offspring, mothers, allele_freqs, mu, mother_index=None):
48
215
719
22
25
ellisztamas/faps
faps/lik_unsampled_fathers.py
Python
lik_unsampled_fathers
lik_unsampled_fathers
5
73
5
5
8c493f49cf4435df4b99e94fe0f1e5264d045829
bigcode/the-stack
train
20bb631a9dc26a70c76a243b
train
function
def collect_assigned_words(word_iterator, lead_word): have_comment = False last_word = lead_word result = [] while True: word = word_iterator.try_pop(settings_index=1) if (word is None): break if (not have_comment and word.quote_token is None and word.value in ["{", "}", ";", "#"]): ...
def collect_assigned_words(word_iterator, lead_word):
have_comment = False last_word = lead_word result = [] while True: word = word_iterator.try_pop(settings_index=1) if (word is None): break if (not have_comment and word.quote_token is None and word.value in ["{", "}", ";", "#"]): if (word.value == ";"): break if (...
from __future__ import division import libtbx.phil def collect_assigned_words(word_iterator, lead_word):
25
73
246
11
13
hickerson/bbn
fable/fable_sources/libtbx/phil/parser.py
Python
collect_assigned_words
collect_assigned_words
4
32
4
4
a609be2875e788c8c778c6c9ef4bae28408a5661
bigcode/the-stack
train
0192683f34344d73fd85e64f
train
function
def collect_objects( word_iterator, converter_registry, primary_id_generator, primary_parent_scope, stop_token=None, start_word=None, definition_converter_cache=None, scope_extract_call_proxy_cache=None): if (definition_converter_cache is None): definition_converter...
def collect_objects( word_iterator, converter_registry, primary_id_generator, primary_parent_scope, stop_token=None, start_word=None, definition_converter_cache=None, scope_extract_call_proxy_cache=None):
if (definition_converter_cache is None): definition_converter_cache = {} if (scope_extract_call_proxy_cache is None): scope_extract_call_proxy_cache = {} prev_line_number = 0 active_definition = None while True: lead_word = word_iterator.try_pop_unquoted() if (lead_word is None): break if ...
_iterator.try_pop(settings_index=1) if (word is None): break if (not have_comment and word.quote_token is None and word.value in ["{", "}", ";", "#"]): if (word.value == ";"): break if (word.value != "#"): word_iterator.backup() break have_comment = True...
256
256
1,109
46
209
hickerson/bbn
fable/fable_sources/libtbx/phil/parser.py
Python
collect_objects
collect_objects
34
162
34
42
b55f83351404a636bc8f9427b49e9efc8ddbfef7
bigcode/the-stack
train
5e920c430bc3b3b06d067fb0
train
function
def main(): """Main module execution code path""" AzureRMCdnEndpointInfo()
def main():
"""Main module execution code path""" AzureRMCdnEndpointInfo()
host_name=cdnendpoint.origins[0].host_name, http_port=cdnendpoint.origins[0].http_port, https_port=cdnendpoint.origins[0].https_port ) new_result['tags'] = cdnendpoint.tags return new_result def main():
64
64
19
3
60
portos060474/azure_modules
library/azure_rm_cdnendpoint_info.py
Python
main
main
308
311
308
308
4c25fd0ec92b8d741778d429b0a0f2107a82bca6
bigcode/the-stack
train
45e70d7873e11f3c9862c853
train
class
class AzureRMCdnEndpointInfo(AzureRMModuleBase): """Utility class to get Azure Azure CDN endpoint facts""" def __init__(self): self.module_args = dict( name=dict(type='str'), resource_group=dict( type='str', required=True ), ...
class AzureRMCdnEndpointInfo(AzureRMModuleBase):
"""Utility class to get Azure Azure CDN endpoint facts""" def __init__(self): self.module_args = dict( name=dict(type='str'), resource_group=dict( type='str', required=True ), profile_name=dict( type='str',...
: description: - The source of the content being delivered via CDN. sample: { "host_name": "xxxxxxxx.blob.core.windows.net", "http_port": null, "https_port": null, "name": "xxxxxxxx-blob-core-windows-net" ...
256
256
958
13
243
portos060474/azure_modules
library/azure_rm_cdnendpoint_info.py
Python
AzureRMCdnEndpointInfo
AzureRMCdnEndpointInfo
183
305
183
183
e83d2baf67386030f89423e35acb4f4debccde34
bigcode/the-stack
train
b60905d26cdb7b44115b1e4b
train
class
class BertAttention(nn.Module): def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, hidden_states, attention_mask=None, encoder_hidden_states=None, split_lengths=None): sel...
class BertAttention(nn.Module):
def __init__(self, config): super(BertAttention, self).__init__() self.self = BertSelfAttention(config) self.output = BertSelfOutput(config) def forward(self, hidden_states, attention_mask=None, encoder_hidden_states=None, split_lengths=None): self_outputs = self.self( ...
part_length: sum_length, :sum_length] )[0]) outputs = (torch.cat(outputs, dim=1), ) else: outputs = self.multi_head_attention( mixed_query_layer, mixed_key_layer, mixed_value_layer, attention_mask) return outputs class BertAttention(nn.Module):
64
64
137
6
57
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertAttention
BertAttention
275
287
275
275
bec01e66e7ac5d7867da20a03af398be628efad2
bigcode/the-stack
train
56a15b46ee82644e09a55f8b
train
class
class LabelSmoothingLoss(_Loss): """ With label smoothing, KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. """ def __init__(self, label_smoothing=0, tgt_vocab_size=0, ignore_index=0, size_average=None, reduce=None, reduction='mean'): ...
class LabelSmoothingLoss(_Loss):
""" With label smoothing, KL-divergence between q_{smoothed ground truth prob.}(w) and p_{prob. computed by model}(w) is minimized. """ def __init__(self, label_smoothing=0, tgt_vocab_size=0, ignore_index=0, size_average=None, reduce=None, reduction='mean'): assert 0.0 < label_smoothing...
embedding_output = self.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds) encoder_outputs = self.encoder( embedding_output, attention_mask=extended_attention_mask, split_lengths=split_lengths) sequence_...
123
123
410
8
115
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
LabelSmoothingLoss
LabelSmoothingLoss
421
457
421
421
9f6cd5ba20df2f529608ae354d20f7c92b1827e0
bigcode/the-stack
train
0c0b3612840294cc76cfa7fc
train
class
class BertLayer(nn.Module): def __init__(self, config): super(BertLayer, self).__init__() self.attention = BertAttention(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward(self, hidden_states, attention_mask=None, split_lengths=None...
class BertLayer(nn.Module):
def __init__(self, config): super(BertLayer, self).__init__() self.attention = BertAttention(config) self.intermediate = BertIntermediate(config) self.output = BertOutput(config) def forward(self, hidden_states, attention_mask=None, split_lengths=None): self_attention_ou...
_mask, encoder_hidden_states=encoder_hidden_states, split_lengths=split_lengths) attention_output = self.output(self_outputs[0], hidden_states) outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them return outputs class BertLayer(nn.Module):
64
64
141
6
57
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertLayer
BertLayer
290
305
290
290
5f4e8f25bd0c562f4b8eab909b673d47b07ad0db
bigcode/the-stack
train
be2e8b02153ed9ad73af3842
train
class
class BertPreTrainedForSeq2SeqModel(BertPreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for dowloading and loading pretrained models. """ config_class = BertForSeq2SeqConfig supported_convert_pretrained_model_archive_map = { "bert": BERT_PR...
class BertPreTrainedForSeq2SeqModel(BertPreTrainedModel):
""" An abstract class to handle weights initialization and a simple interface for dowloading and loading pretrained models. """ config_class = BertForSeq2SeqConfig supported_convert_pretrained_model_archive_map = { "bert": BERT_PRETRAINED_MODEL_ARCHIVE_MAP, "roberta": ROBERTA_PRE...
.modeling_xlm_roberta import XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP from s2s_ft.config import BertForSeq2SeqConfig from s2s_ft.convert_state_dict import get_checkpoint_from_transformer_cache, state_dict_convert logger = logging.getLogger(__name__) BertLayerNorm = torch.nn.LayerNorm UNILM_PRETRAINED_MODEL_ARCHIVE_...
256
256
1,382
17
239
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertPreTrainedForSeq2SeqModel
BertPreTrainedForSeq2SeqModel
35
139
35
35
ccaf7d04f9c2bb901ea11275f90d3a52d802454b
bigcode/the-stack
train
d3870cdec348c16b8ea3bb12
train
class
class BertOnlyMLMHead(nn.Module): def __init__(self, config, decoder_weight): super(BertOnlyMLMHead, self).__init__() self.predictions = BertLMPredictionHead(config, decoder_weight) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return ...
class BertOnlyMLMHead(nn.Module):
def __init__(self, config, decoder_weight): super(BertOnlyMLMHead, self).__init__() self.predictions = BertLMPredictionHead(config, decoder_weight) def forward(self, sequence_output): prediction_scores = self.predictions(sequence_output) return prediction_scores
_weight self.bias = nn.Parameter(torch.zeros(config.vocab_size)) def forward(self, hidden_states): hidden_states = self.transform(hidden_states) hidden_states = F.linear(hidden_states, weight=self.decoder_weight, bias=self.bias) return hidden_states class BertOnlyMLMHead(nn.Module)...
64
64
73
9
54
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertOnlyMLMHead
BertOnlyMLMHead
477
484
477
477
06abada87bae20a2edf4058131f778f7caea33bc
bigcode/the-stack
train
006225625ededb470730bff5
train
class
class BertLMPredictionHead(nn.Module): def __init__(self, config, decoder_weight): super(BertLMPredictionHead, self).__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each...
class BertLMPredictionHead(nn.Module):
def __init__(self, config, decoder_weight): super(BertLMPredictionHead, self).__init__() self.transform = BertPredictionHeadTransform(config) # The output weights are the same as the input embeddings, but there is # an output-only bias for each token. self.decoder_weight = d...
.confidence) model_prob.masked_fill_((target == self.ignore_index).unsqueeze(1), 0) return F.kl_div(output, model_prob, reduction='none').view(batch_size, num_pos, -1).sum(2) class BertLMPredictionHead(nn.Module):
64
64
134
10
54
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertLMPredictionHead
BertLMPredictionHead
460
474
460
460
dca23fb7a03a65f1229d0da35f8f3966ebad48c7
bigcode/the-stack
train
ade60a35e0605bd0bb2e7054
train
class
class BertEncoder(nn.Module): def __init__(self, config): super(BertEncoder, self).__init__() self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layer...
class BertEncoder(nn.Module):
def __init__(self, config): super(BertEncoder, self).__init__() self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)]) def forward(self, hi...
self_attention_outputs = self.attention( hidden_states, attention_mask, split_lengths=split_lengths) attention_output = self_attention_outputs[0] intermediate_output = self.intermediate(attention_output) layer_output = self.output(intermediate_output, attention_output) ...
80
80
267
6
73
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertEncoder
BertEncoder
308
337
308
308
889eccf791455be47376043cc063edc80db243f4
bigcode/the-stack
train
7524d2f2e7405fb80bf7bb81
train
class
class BertEmbeddings(nn.Module): """Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config): super(BertEmbeddings, self).__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) self.position_e...
class BertEmbeddings(nn.Module):
"""Construct the embeddings from word, position and token_type embeddings. """ def __init__(self, config): super(BertEmbeddings, self).__init__() self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=0) self.position_embeddings = nn.Embedding(config.m...
_position_embeddings, state_dict[_k].shape[1])), dtype=torch.float) new_postion_embedding = nn.Parameter(data=new_postion_embedding, requires_grad=True) new_postion_embedding.data.normal_(mean=0.0, std=config.initializer_range) new_postion_embedding.data.copy_(state_dict[...
122
122
408
7
115
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertEmbeddings
BertEmbeddings
142
184
142
142
f0385ee6458164e5fbc172138d961af3522cf5d4
bigcode/the-stack
train
a2f09d193e51952c242360d5
train
class
class BertModel(BertPreTrainedForSeq2SeqModel): r""" Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)`` Sequence of hidden-states at the output o...
class BertModel(BertPreTrainedForSeq2SeqModel):
r""" Outputs: `Tuple` comprising various elements depending on the configuration (config) and inputs: **last_hidden_state**: ``torch.FloatTensor`` of shape ``(batch_size, sequence_length, hidden_size)`` Sequence of hidden-states at the output of the last layer of the model. **pooler_...
self.output_attentions = config.output_attentions self.output_hidden_states = config.output_hidden_states self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)]) def forward(self, hidden_states, attention_mask=None, split_lengths=None): all_hidden_st...
256
256
1,054
14
242
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertModel
BertModel
340
418
340
340
83598155944dded5d4a03da30e383fb5857d3082
bigcode/the-stack
train
4b55eaf4fd2f5c1b197e53a3
train
class
class BertForSequenceToSequence(BertPreTrainedForSeq2SeqModel): def __init__(self, config): super(BertForSequenceToSequence, self).__init__(config) self.bert = BertModel(config) self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight) self.init_weights() ...
class BertForSequenceToSequence(BertPreTrainedForSeq2SeqModel):
def __init__(self, config): super(BertForSequenceToSequence, self).__init__(config) self.bert = BertModel(config) self.cls = BertOnlyMLMHead(config, self.bert.embeddings.word_embeddings.weight) self.init_weights() self.log_softmax = nn.LogSoftmax() # setattr(config,...
0) return F.kl_div(output, model_prob, reduction='none').view(batch_size, num_pos, -1).sum(2) class BertLMPredictionHead(nn.Module): def __init__(self, config, decoder_weight): super(BertLMPredictionHead, self).__init__() self.transform = BertPredictionHeadTransform(config) # Th...
256
256
1,024
17
238
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertForSequenceToSequence
BertForSequenceToSequence
487
580
487
487
9608dca500e38ce1c0abfc487d67c882010eddef
bigcode/the-stack
train
14f947ef90409f8c644bf366
train
class
class BertSelfAttention(nn.Module): def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads...
class BertSelfAttention(nn.Module):
def __init__(self, config): super(BertSelfAttention, self).__init__() if config.hidden_size % config.num_attention_heads != 0: raise ValueError( "The hidden size (%d) is not a multiple of the number of attention " "heads (%d)" % (config.hidden_size, config...
LayerNorm(config.hidden_size, eps=config.layer_norm_eps) self.dropout = nn.Dropout(config.hidden_dropout_prob) def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None): if input_ids is not None: input_shape = input_ids.size() else: ...
256
256
934
7
248
imadcat/unilm
s2s-ft/s2s_ft/modeling.py
Python
BertSelfAttention
BertSelfAttention
187
272
187
187
da91d222f42f28e10d1ebafa66350eed7133afa5
bigcode/the-stack
train
4f4c07240e2b031321b392f6
train
class
class TypeCompileTest(fixtures.TestBase, AssertsCompiledSQL): __dialect__ = mysql.dialect() @testing.combinations( # column type, args, kwargs, expected ddl # e.g. Column(Integer(10, unsigned=True)) == # 'INTEGER(10) UNSIGNED' (mysql.MSNumeric, [], {}, "NUMERIC"), (mysql...
class TypeCompileTest(fixtures.TestBase, AssertsCompiledSQL):
__dialect__ = mysql.dialect() @testing.combinations( # column type, args, kwargs, expected ddl # e.g. Column(Integer(10, unsigned=True)) == # 'INTEGER(10) UNSIGNED' (mysql.MSNumeric, [], {}, "NUMERIC"), (mysql.MSNumeric, [None], {}, "NUMERIC"), (mysql.MSNumeric, ...
# coding: utf-8 from collections import OrderedDict import datetime import decimal from sqlalchemy import BOOLEAN from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import DefaultClause from sqlalchemy import Enum from sqlalchemy import exc from sqlalchemy import Integer from sqlalchemy impor...
206
256
3,533
14
191
abrahamsangha/sqlalchemy
test/dialect/mysql/test_types.py
Python
TypeCompileTest
TypeCompileTest
36
465
36
36
bdce0df7d0cf52ce2a5562236fa29e41a3579185
bigcode/the-stack
train
7c32ed0d6bb227c991cf3934
train
class
class EnumSetTest( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ): __only_on__ = "mysql" __dialect__ = mysql.dialect() __backend__ = True class SomeEnum(object): # Implements PEP 435 in the minimal fashion needed by SQLAlchemy __members__ = OrderedDict() ...
class EnumSetTest( fixtures.TestBase, AssertsExecutionResults, AssertsCompiledSQL ):
__only_on__ = "mysql" __dialect__ = mysql.dialect() __backend__ = True class SomeEnum(object): # Implements PEP 435 in the minimal fashion needed by SQLAlchemy __members__ = OrderedDict() def __init__(self, name, value): self.name = name self.value = val...
__only_on__ = "mysql" __backend__ = True @testing.provide_metadata @testing.requires.reflects_json_type def test_reflection(self): Table("mysql_json", self.metadata, Column("foo", mysql.JSON)) self.metadata.create_all() reflected = Table("mysql_json", MetaData(), autoload_...
256
256
4,387
21
235
abrahamsangha/sqlalchemy
test/dialect/mysql/test_types.py
Python
EnumSetTest
EnumSetTest
791
1,337
791
794
5b7662a8cd0a2505059a02677a2da3338b7b2cdf
bigcode/the-stack
train
8def447664a7b1bcacc87f57
train
class
class TypeRoundTripTest(fixtures.TestBase, AssertsExecutionResults): __dialect__ = mysql.dialect() __only_on__ = "mysql" __backend__ = True # fixed in mysql-connector as of 2.0.1, # see http://bugs.mysql.com/bug.php?id=73266 @testing.provide_metadata def test_precision_float_roundtrip(self...
class TypeRoundTripTest(fixtures.TestBase, AssertsExecutionResults):
__dialect__ = mysql.dialect() __only_on__ = "mysql" __backend__ = True # fixed in mysql-connector as of 2.0.1, # see http://bugs.mysql.com/bug.php?id=73266 @testing.provide_metadata def test_precision_float_roundtrip(self): t = Table( "t", self.metadata, ...
}, "TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP " "ON UPDATE CURRENT_TIMESTAMP", ), ) def test_timestamp_defaults(self, spec, kw, expected): """Exercise funky TIMESTAMP default syntax when used in columns.""" c = Column("t", *spec, **kw) Table("t", MetaD...
256
256
2,670
15
241
abrahamsangha/sqlalchemy
test/dialect/mysql/test_types.py
Python
TypeRoundTripTest
TypeRoundTripTest
468
754
468
469
11ab0e237d68757ae219f464ae2e9046c0ed65fc
bigcode/the-stack
train
bfdd86ddc19cc70442285e81
train
function
def colspec(c): return testing.db.dialect.ddl_compiler( testing.db.dialect, None ).get_column_specification(c)
def colspec(c):
return testing.db.dialect.ddl_compiler( testing.db.dialect, None ).get_column_specification(c)
, "e2": None}) eq_( conn.execute( select([t.c.e1, t.c.e2]).order_by(t.c.id) ).fetchall(), [("", ""), ("", ""), ("two", "two"), (None, None)], ) def colspec(c):
64
64
32
5
59
abrahamsangha/sqlalchemy
test/dialect/mysql/test_types.py
Python
colspec
colspec
1,340
1,343
1,340
1,340
717ec4f7b775651ed969bd50241e68d7ad62c2b2
bigcode/the-stack
train
43369f9e0a8b4d362fcf4da3
train
class
class JSONTest(fixtures.TestBase): __requires__ = ("json_type",) __only_on__ = "mysql" __backend__ = True @testing.provide_metadata @testing.requires.reflects_json_type def test_reflection(self): Table("mysql_json", self.metadata, Column("foo", mysql.JSON)) self.metadata.create...
class JSONTest(fixtures.TestBase):
__requires__ = ("json_type",) __only_on__ = "mysql" __backend__ = True @testing.provide_metadata @testing.requires.reflects_json_type def test_reflection(self): Table("mysql_json", self.metadata, Column("foo", mysql.JSON)) self.metadata.create_all() reflected = Table("...
.execute(table.select()).first() eq_(list(row), [1950, 2050, None, 1950]) conn.execute(table.delete()) self.assert_(colspec(table.c.y1).startswith("y1 YEAR")) eq_(colspec(table.c.y5), "y5 YEAR(4)") class JSONTest(fixtures.TestBase):
74
75
253
8
66
abrahamsangha/sqlalchemy
test/dialect/mysql/test_types.py
Python
JSONTest
JSONTest
757
788
757
757
1afb0a79d3d5a1b9f61405194e155d29648b722f
bigcode/the-stack
train
bf9c6f296a81cabd9f628f83
train
function
def plot_sensor_img(path: OpticalPath, ax: Axes, only_wavelength=False, pixel=3280): """ Plots a ray path and plots the ray distribution on the last element in the path Args: path: (OpticalPath) ax: (matplotlib.Axes) axes to plot the path in only_wavelength: (bool) pixel: (in...
def plot_sensor_img(path: OpticalPath, ax: Axes, only_wavelength=False, pixel=3280):
""" Plots a ray path and plots the ray distribution on the last element in the path Args: path: (OpticalPath) ax: (matplotlib.Axes) axes to plot the path in only_wavelength: (bool) pixel: (int) number of pixels the sensor have Returns: (pandas.Dataframe) with sen...
import numpy as np from matplotlib.axes import Axes from raypy2d.paths import OpticalPath from raypy2d.utils import wavelength_to_rgb def plot_sensor_img(path: OpticalPath, ax: Axes, only_wavelength=False, pixel=3280):
57
198
663
24
32
toschoch/python-raypy
raypy2d/analysis.py
Python
plot_sensor_img
plot_sensor_img
8
71
8
8
8494e4da84cf591763a380861b4cc5823c47d36a
bigcode/the-stack
train
2afa7be2f17eb72d8227b0ea
train
class
class TestPostComments: pytestmark = pytest.mark.django_db def test_comment_form_not_included(self, client, post, comments_not_enabled): slugs = {"blog_slug": post.blog.slug, "slug": post.slug} detail_url = reverse("cast:post_detail", kwargs=slugs) r = client.get(detail_url) as...
class TestPostComments:
pytestmark = pytest.mark.django_db def test_comment_form_not_included(self, client, post, comments_not_enabled): slugs = {"blog_slug": post.blog.slug, "slug": post.slug} detail_url = reverse("cast:post_detail", kwargs=slugs) r = client.get(detail_url) assert r.status_code == 20...
import pytest from django.urls import reverse from django_comments import get_model as get_comments_model class TestPostComments:
25
184
614
5
19
ephes/django-cast
tests/test_comments.py
Python
TestPostComments
TestPostComments
8
81
8
8
2d43e651b46070958cdf23696463ad4eb8c08726
bigcode/the-stack
train
465946bad9648958506e3992
train
class
class GreendayChannelManager(object): """ A manager to encapsulate a memcache-based messaging queue """ def __init__( self, client_namespace="channel-clients", message_namespace="channel-buckets", channels=None, max_message_backlog=200, ...
class GreendayChannelManager(object):
""" A manager to encapsulate a memcache-based messaging queue """ def __init__( self, client_namespace="channel-clients", message_namespace="channel-buckets", channels=None, max_message_backlog=200, pull_retries=37, ...
""" Defines the channel manager """ import time import uuid from google.appengine.api import memcache from .utils import retry_until_truthy class GreendayChannelManager(object):
40
234
782
8
31
meedan/montage
appengine/src/greenday_channel/channel.py
Python
GreendayChannelManager
GreendayChannelManager
12
151
12
12
3099b823b5fdfd43a937dd6abccc0be793558b6c
bigcode/the-stack
train
813cd59dcdef97ec923890d6
train
function
def quantDemo(img_path: str, rep: int): img = imReadAndConvert(img_path, rep) st = time.time() img_lst, err_lst = quantizeImage(img, 3, 20) print("Time:%.2f" % (time.time() - st)) print("Error 0:\t %f" % err_lst[0]) print("Error last:\t %f" % err_lst[-1]) plt.gray() plt.imshow(img_lst...
def quantDemo(img_path: str, rep: int):
img = imReadAndConvert(img_path, rep) st = time.time() img_lst, err_lst = quantizeImage(img, 3, 20) print("Time:%.2f" % (time.time() - st)) print("Error 0:\t %f" % err_lst[0]) print("Error last:\t %f" % err_lst[-1]) plt.gray() plt.imshow(img_lst[0]) plt.figure() plt.imshow(img...
256), cumsum, 'r') plt.plot(range(256), cumsumEq, 'g') # Display the images plt.figure() plt.imshow(img) plt.figure() plt.imshow(imgeq) plt.show() def quantDemo(img_path: str, rep: int):
64
64
139
12
52
kggold4/image-processing-ex1
ex1_main.py
Python
quantDemo
quantDemo
28
45
28
28
eab3b7868fbed481e51c67f3f7453109274a33c6
bigcode/the-stack
train
8e6bcebf91fa8104f51ca3f6
train
function
def histEqDemo(img_path: str, rep: int): img = imReadAndConvert(img_path, rep) imgeq, histOrg, histEq = hsitogramEqualize(img) # Display cumsum cumsum = np.cumsum(histOrg) cumsumEq = np.cumsum(histEq) plt.gray() plt.plot(range(256), cumsum, 'r') plt.plot(range(256), cumsumEq, 'g') ...
def histEqDemo(img_path: str, rep: int):
img = imReadAndConvert(img_path, rep) imgeq, histOrg, histEq = hsitogramEqualize(img) # Display cumsum cumsum = np.cumsum(histOrg) cumsumEq = np.cumsum(histEq) plt.gray() plt.plot(range(256), cumsum, 'r') plt.plot(range(256), cumsumEq, 'g') # Display the images plt.figure() ...
from ex1_utils import * from gamma import gammaDisplay import numpy as np import matplotlib.pyplot as plt import time def histEqDemo(img_path: str, rep: int):
39
64
131
13
25
kggold4/image-processing-ex1
ex1_main.py
Python
histEqDemo
histEqDemo
8
25
8
8
10d35017b226b50dcd80eb19b02220fd9c224b1a
bigcode/the-stack
train
4142b4c599c52f6d1a79cb80
train
function
def main(): print("ID:", myID()) img_path = 'testImg2.jpg' # Basic read and display imDisplay(img_path, LOAD_GRAY_SCALE) imDisplay(img_path, LOAD_RGB) # Convert Color spaces img = imReadAndConvert(img_path, LOAD_RGB) yiq_img = transformRGB2YIQ(img) f, ax = plt.subplots(1, 2) ax...
def main():
print("ID:", myID()) img_path = 'testImg2.jpg' # Basic read and display imDisplay(img_path, LOAD_GRAY_SCALE) imDisplay(img_path, LOAD_RGB) # Convert Color spaces img = imReadAndConvert(img_path, LOAD_RGB) yiq_img = transformRGB2YIQ(img) f, ax = plt.subplots(1, 2) ax[0].imshow(i...
_lst[0]) print("Error last:\t %f" % err_lst[-1]) plt.gray() plt.imshow(img_lst[0]) plt.figure() plt.imshow(img_lst[-1]) plt.figure() plt.plot(err_lst, 'r') plt.show() def main():
64
64
180
3
61
kggold4/image-processing-ex1
ex1_main.py
Python
main
main
48
73
48
48
e349953c7c8cd914eb0540030a58506ac4ded21c
bigcode/the-stack
train
2a8e577d737fe8ab62111189
train
function
def main(): with open("conf/sample_config.json", "r") as f: sample_conf = json.load(f) image_height = sample_conf["image_height"] image_width = sample_conf["image_width"] max_captcha = sample_conf["max_captcha"] char_set = sample_conf["char_set"] model_save_dir = sample_conf["model_save_...
def main():
with open("conf/sample_config.json", "r") as f: sample_conf = json.load(f) image_height = sample_conf["image_height"] image_width = sample_conf["image_width"] max_captcha = sample_conf["max_captcha"] char_set = sample_conf["char_set"] model_save_dir = sample_conf["model_save_dir"] R ...
test_image], self.keep_prob: 1.}) # 获取结果 predict_text = text_list[0].tolist() p_text = "" for p in predict_text: p_text += str(self.char_set[p]) # 返回识别结果 return p_text def main():
64
64
152
3
60
wmm1996528/cnn_test
cnnlib/recognition_object.py
Python
main
main
63
74
63
63
f22e504776e4c099451f0fd1d023b55c49bf5c74
bigcode/the-stack
train
81cc681620a46d00d362a19f
train
class
class Recognizer(CNN): def __init__(self, image_height, image_width, max_captcha, char_set, model_save_dir): # 初始化变量 super(Recognizer, self).__init__(image_height, image_width, max_captcha, char_set, model_save_dir) # 新建图和会话 self.g = tf.Graph() self.sess = tf.Session(graph=s...
class Recognizer(CNN):
def __init__(self, image_height, image_width, max_captcha, char_set, model_save_dir): # 初始化变量 super(Recognizer, self).__init__(image_height, image_width, max_captcha, char_set, model_save_dir) # 新建图和会话 self.g = tf.Graph() self.sess = tf.Session(graph=self.g) # 使用指定的图...
# -*- coding: utf-8 -*- """ 识别图像的类,为了快速进行多次识别可以调用此类下面的方法: R = Recognizer(image_height, image_width, max_captcha) for i in range(10): r_img = Image.open(str(i) + ".jpg") t = R.rec_image(r_img) 简单的图片每张基本上可以达到毫秒级的识别速度 """ import tensorflow as tf import numpy as np from PIL import Image import json from cnnlib.netw...
122
141
472
6
115
wmm1996528/cnn_test
cnnlib/recognition_object.py
Python
Recognizer
Recognizer
17
60
17
17
df8b1d9a69e9caa31229f437b791725466a5a909
bigcode/the-stack
train
6a56c4ff32279a634bfd5ba1
train
function
def add(x, y): """add 2 number together""" return x + y
def add(x, y):
"""add 2 number together""" return x + y
def add(x, y):
6
64
20
6
0
howard5248/django-restAPI-1
app/app/trash_bin/calc.py
Python
add
add
1
4
1
1
e770d53a7dafca4c1939a341ee5c7901b36d2e62
bigcode/the-stack
train
f8a43efc227078ce185a8608
train
class
class CachedFactoryMeta(type): """ Meta class that implements pattern similar to Singleton, except there are more instances cached based on a input parameter. It utilizes Factory pattern and forbids direct instantion of the class. To retrieve/create unique instance use `factory(key)` class method. ...
class CachedFactoryMeta(type):
""" Meta class that implements pattern similar to Singleton, except there are more instances cached based on a input parameter. It utilizes Factory pattern and forbids direct instantion of the class. To retrieve/create unique instance use `factory(key)` class method. It is possible to leave out 'k...
import logging from pprint import pformat from traceback import format_stack logger = logging.getLogger('toggl.utils.metas') sentinel = object() class CachedFactoryMeta(type):
38
140
469
6
32
Bass-03/toggl-cli
toggl/utils/metas.py
Python
CachedFactoryMeta
CachedFactoryMeta
10
62
10
10
aef3d54a9e78934595156ad87be17915e015882a
bigcode/the-stack
train
9e52bb9dff6803e27100bced
train
class
class ClassAttributeModificationWarning(type): """ Meta class that logs warnings when class's attributes are overridden. """ def __setattr__(cls, attr, value): logger.warning('You are modifying class attribute of \'{}\' class. You better know what you are doing!' .format(c...
class ClassAttributeModificationWarning(type):
""" Meta class that logs warnings when class's attributes are overridden. """ def __setattr__(cls, attr, value): logger.warning('You are modifying class attribute of \'{}\' class. You better know what you are doing!' .format(cls.__name__)) logger.debug(pformat(for...
set_default(_, obj): mcs.cache[mcs.SENTINEL_KEY] = obj namespace['set_default'] = classmethod(set_default) namespace['factory'] = classmethod(factory) return super().__new__(mcs, name, bases, namespace) class ClassAttributeModificationWarning(type):
64
64
85
7
57
Bass-03/toggl-cli
toggl/utils/metas.py
Python
ClassAttributeModificationWarning
ClassAttributeModificationWarning
65
75
65
65
7df2eefb4c33fd5e1fca0ac27fcc6ed87348ab43
bigcode/the-stack
train
8902087643166de1f15098ef
train
class
class EventPublisher(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' The interface that takes master events and republishes them out to anyone who wants to listen ''' def __init__(self, opts, **kwargs): super(EventPublisher, self).__init__(**kwargs) self.opts = salt.con...
class EventPublisher(salt.utils.process.SignalHandlingMultiprocessingProcess):
''' The interface that takes master events and republishes them out to anyone who wants to listen ''' def __init__(self, opts, **kwargs): super(EventPublisher, self).__init__(**kwargs) self.opts = salt.config.DEFAULT_MASTER_OPTS.copy() self.opts.update(opts) self._clo...
.ipc.IPCMessageServer( self.opts, epull_uri, io_loop=self.io_loop, payload_handler=self.handle_publish ) log.info('Starting pull socket on %s', epull_uri) with salt.utils.files.set_umask(0o177): self.publisher.start() self....
233
233
777
13
220
yohonet/salt
salt/utils/event.py
Python
EventPublisher
EventPublisher
1,085
1,192
1,085
1,085
dfb93fd34cd16778c54b65aa70bf8607c66bdf26
bigcode/the-stack
train
96709498ed29c551eeefd891
train
function
def fire_args(opts, jid, tag_data, prefix=''): ''' Fire an event containing the arguments passed to an orchestration job ''' try: tag_suffix = [jid, 'args'] except NameError: pass else: tag = tagify(tag_suffix, prefix) try: _event = get_master_event(op...
def fire_args(opts, jid, tag_data, prefix=''):
''' Fire an event containing the arguments passed to an orchestration job ''' try: tag_suffix = [jid, 'args'] except NameError: pass else: tag = tagify(tag_suffix, prefix) try: _event = get_master_event(opts, opts['sock_dir'], listen=False) ...
transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop) def fire_args(opts, jid, tag_data, prefix=''):
64
64
150
13
51
yohonet/salt
salt/utils/event.py
Python
fire_args
fire_args
157
175
157
157
13d4401aea8b1f718b89f8496c490e2e674c4c9a
bigcode/the-stack
train
8466a4adf87042ab0e44e5b4
train
class
class AsyncEventPublisher(object): ''' An event publisher class intended to run in an ioloop (within a single process) TODO: remove references to "minion_event" whenever we need to use this for other things ''' def __init__(self, opts, io_loop=None): self.opts = salt.config.DEFAULT_MINION_O...
class AsyncEventPublisher(object):
''' An event publisher class intended to run in an ioloop (within a single process) TODO: remove references to "minion_event" whenever we need to use this for other things ''' def __init__(self, opts, io_loop=None): self.opts = salt.config.DEFAULT_MINION_OPTS.copy() default_minion_s...
A wrapper for sending events within a specific base namespace ''' def __init__(self, event, base, print_func=None): self.event = event self.base = base self.print_func = print_func def fire_event(self, data, tag): self.event.fire_event(data, tagify(tag, base=self.base)) ...
248
248
828
6
242
yohonet/salt
salt/utils/event.py
Python
AsyncEventPublisher
AsyncEventPublisher
978
1,082
978
978
2acf0b86302a232347a6abc5bb15c06db65e66a6
bigcode/the-stack
train
ba5e04e59746af48d14dd5fd
train
class
class MasterEvent(SaltEvent): ''' Warning! Use the get_event function or the code will not be RAET compatible Create a master event management object ''' def __init__( self, sock_dir, opts=None, listen=True, io_loop=None, ke...
class MasterEvent(SaltEvent):
''' Warning! Use the get_event function or the code will not be RAET compatible Create a master event management object ''' def __init__( self, sock_dir, opts=None, listen=True, io_loop=None, keep_loop=False, rai...
-- since destroy() doesn't cover interpreter # shutdown-- where globals start going missing try: self.destroy() except Exception: pass def __enter__(self): return self def __exit__(self, *args): self.destroy() class MasterEvent(SaltEvent):
64
64
121
7
57
yohonet/salt
salt/utils/event.py
Python
MasterEvent
MasterEvent
908
929
908
908
0e2b1bf57a5546eaac33dde3775533e32d4bf114
bigcode/the-stack
train
51d78a48773903eb918b9edb
train
class
class SaltEvent(object): ''' Warning! Use the get_event function or the code will not be RAET compatible The base class used to manage salt events ''' def __init__( self, node, sock_dir=None, opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=...
class SaltEvent(object):
''' Warning! Use the get_event function or the code will not be RAET compatible The base class used to manage salt events ''' def __init__( self, node, sock_dir=None, opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False): ''' ...
PARTER.join([part for part in parts if part]) def update_stats(stats, start_time, data): ''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: ...
256
256
5,149
5
250
yohonet/salt
salt/utils/event.py
Python
SaltEvent
SaltEvent
230
905
230
230
f78af531c02192ebb0d8affe283c227d8005e78d
bigcode/the-stack
train
ce05ed54b572574d77befbc4
train
function
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False): ''' Return an event object suitable for the named transport ''' # TODO: AIO core is separate from transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, ...
def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise_errors=False, keep_loop=False):
''' Return an event object suitable for the named transport ''' # TODO: AIO core is separate from transport if opts['transport'] in ('zeromq', 'tcp', 'detect'): return MasterEvent(sock_dir, opts, listen=listen, io_loop=io_loop, raise_errors=raise_errors, keep_loop=keep_loop)
) return SaltEvent(node, sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors) def get_master_event(opts, sock_dir, listen=True, io_loop=None, raise...
64
64
100
24
40
yohonet/salt
salt/utils/event.py
Python
get_master_event
get_master_event
148
154
148
148
46e68a228d9183f113a28d356e2c48f3843c88b1
bigcode/the-stack
train
f0eb02b94ded39ebf2e06655
train
class
class NamespacedEvent(object): ''' A wrapper for sending events within a specific base namespace ''' def __init__(self, event, base, print_func=None): self.event = event self.base = base self.print_func = print_func def fire_event(self, data, tag): self.event.fire_ev...
class NamespacedEvent(object):
''' A wrapper for sending events within a specific base namespace ''' def __init__(self, event, base, print_func=None): self.event = event self.base = base self.print_func = print_func def fire_event(self, data, tag): self.event.fire_event(data, tagify(tag, base=self...
ClientEvent(MasterEvent): ''' Warning! Use the get_event function or the code will not be RAET compatible This class is just used to differentiate who is handling the events, specially on logs, but it's the same as MasterEvent. ''' class NamespacedEvent(object):
63
64
134
6
57
yohonet/salt
salt/utils/event.py
Python
NamespacedEvent
NamespacedEvent
941
962
941
941
622e7b4c62803eea058c1cd92e7f00007e2b2de1
bigcode/the-stack
train
8df638338440b3d978707bf3
train
class
class StateFire(object): ''' Evaluate the data from a state run and fire events on the master and minion for each returned chunk that is not "green" This object is made to only run on a minion ''' def __init__(self, opts, auth=None): self.opts = opts if not auth: self...
class StateFire(object):
''' Evaluate the data from a state run and fire events on the master and minion for each returned chunk that is not "green" This object is made to only run on a minion ''' def __init__(self, opts, auth=None): self.opts = opts if not auth: self.auth = salt.crypt.SAuth(...
.event_queue: self.flush_events() def _filter(self, event): ''' Take an event and run it through configured filters. Returns True if event should be stored, else False ''' tag = event['tag'] if self.opts['event_return_whitelist']: ret = F...
146
146
488
5
140
yohonet/salt
salt/utils/event.py
Python
StateFire
StateFire
1,328
1,402
1,328
1,328
aec63fce8086cb8c9ad1a456c9e16c5866dd1fcc
bigcode/the-stack
train
d73b9e0e977722a183e1ad05
train
class
class MinionEvent(SaltEvent): ''' Warning! Use the get_event function or the code will not be RAET compatible Create a master event management object ''' def __init__(self, opts, listen=True, io_loop=None, keep_loop=False, raise_errors=False): super(MinionEvent, self).__init__( ...
class MinionEvent(SaltEvent):
''' Warning! Use the get_event function or the code will not be RAET compatible Create a master event management object ''' def __init__(self, opts, listen=True, io_loop=None, keep_loop=False, raise_errors=False): super(MinionEvent, self).__init__( 'minion', sock_dir=opts.get...
base=self.base)) if self.print_func is not None: self.print_func(tag, data) def destroy(self): self.event.destroy() def __enter__(self): return self def __exit__(self, *args): self.destroy() class MinionEvent(SaltEvent):
64
64
116
8
56
yohonet/salt
salt/utils/event.py
Python
MinionEvent
MinionEvent
965
975
965
965
d1d6def288c2642dbb755aef84776f1c9ffaac85
bigcode/the-stack
train
2d8674f76102324940c5edea
train
class
class EventReturn(salt.utils.process.SignalHandlingMultiprocessingProcess): ''' A dedicated process which listens to the master event bus and queues and forwards events to the specified returner. ''' def __new__(cls, *args, **kwargs): if sys.platform.startswith('win'): # This is ...
class EventReturn(salt.utils.process.SignalHandlingMultiprocessingProcess):
''' A dedicated process which listens to the master event bus and queues and forwards events to the specified returner. ''' def __new__(cls, *args, **kwargs): if sys.platform.startswith('win'): # This is required for Windows. On Linux, when a process is # forked, the...
_pub.ipc'), 0o666) # Make sure the IO loop and respective sockets are closed and # destroyed Finalize(self, self.close, exitpriority=15) self.io_loop.start() def handle_publish(self, package, _): ''' Get something from epull, publish it out epub, an...
256
256
1,055
13
243
yohonet/salt
salt/utils/event.py
Python
EventReturn
EventReturn
1,195
1,325
1,195
1,195
33ad299d67486b30e37b503cbbd976ec7d02229b
bigcode/the-stack
train
8bf6406e7b88e28e0572388f
train
function
def update_stats(stats, start_time, data): ''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: try: jid = data['data']['__pub_...
def update_stats(stats, start_time, data):
''' Calculate the master stats and return the updated stat info ''' end_time = time.time() cmd = data['cmd'] # the jid is used as the create time try: jid = data['jid'] except KeyError: try: jid = data['data']['__pub_jid'] except KeyError: ...
parts.append(suffix) for index, _ in enumerate(parts): try: parts[index] = salt.utils.stringutils.to_str(parts[index]) except TypeError: parts[index] = str(parts[index]) return TAGPARTER.join([part for part in parts if part]) def update_stats(stats, start_time, d...
71
71
239
10
61
yohonet/salt
salt/utils/event.py
Python
update_stats
update_stats
204
227
204
204
7e28bfea667481212190273986047066917d4393
bigcode/the-stack
train
d6177712accc1fff5528b561
train
class
class LocalClientEvent(MasterEvent): ''' Warning! Use the get_event function or the code will not be RAET compatible This class is just used to differentiate who is handling the events, specially on logs, but it's the same as MasterEvent. '''
class LocalClientEvent(MasterEvent):
''' Warning! Use the get_event function or the code will not be RAET compatible This class is just used to differentiate who is handling the events, specially on logs, but it's the same as MasterEvent. '''
keep_loop=False, raise_errors=False): super(MasterEvent, self).__init__( 'master', sock_dir, opts, listen=listen, io_loop=io_loop, keep_loop=keep_loop, raise_errors=raise_errors) class LocalClientEvent(MasterEvent):...
64
64
59
8
56
yohonet/salt
salt/utils/event.py
Python
LocalClientEvent
LocalClientEvent
932
938
932
932
a675b3e018673697e0c3328cc59efdb48fdd68d9
bigcode/the-stack
train
7197ce679ead30bb2c27ab1c
train
function
def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False): ''' Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous opera...
def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):
''' Return an event object suitable for the named transport :param IOLoop io_loop: Pass in an io_loop if you want asynchronous operation for obtaining events. Eg use of set_event_handler() API. Otherwise, operation will be syn...
# prefix for all salt/fileserver events 'queue': 'queue', # prefix for all salt/queue events } def get_event( node, sock_dir=None, transport='zeromq', opts=None, listen=True, io_loop=None, keep_loop=False, raise_errors=False):
64
64
202
36
28
yohonet/salt
salt/utils/event.py
Python
get_event
get_event
119
145
119
121
7a490aa7534d70c2da391df6d24fe8563f530ab2
bigcode/the-stack
train
80c0e7f8a0e686bdb92b4a73
train
function
def tagify(suffix='', prefix='', base=SALT): ''' convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list T...
def tagify(suffix='', prefix='', base=SALT):
''' convenience function to build a namespaced event tag string from joining with the TABPART character the base, prefix and suffix If string prefix is a valid key in TAGS Then use the value of key prefix Else use prefix string If suffix is a list Then join all string elements of suffix indivi...
except Exception as exc: # Don't let a problem here hold up the rest of the orchestration log.warning( 'Failed to fire args event %s with data %s: %s', tag, tag_data, exc ) def tagify(suffix='', prefix='', base=SALT):
64
64
194
12
52
yohonet/salt
salt/utils/event.py
Python
tagify
tagify
178
201
178
178
17da5d6b48123a67f252993e5476c6b204b8c7a3
bigcode/the-stack
train
b74e313f933deb4a0034c1fb
train
function
def test_suite(): '''Create the suite of tests. ''' suite = unittest.TestSuite() suite.addTest(profileTest.test_suite()) suite.addTest(queryTest.test_suite()) suite.addTest(xmlutilsTest.test_suite()) return suite
def test_suite():
'''Create the suite of tests. ''' suite = unittest.TestSuite() suite.addTest(profileTest.test_suite()) suite.addTest(queryTest.test_suite()) suite.addTest(xmlutilsTest.test_suite()) return suite
, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. '''Agile OODT Tests. ''' __docformat__ = 'restructuredtext' import unittest import profileTest, queryTest, xmlutilsTest def test_suite():
64
64
53
4
59
chrismattmann/oodt
agility/oodt/tests/__init__.py
Python
test_suite
test_suite
26
33
26
26
449920d898baaa6bebd01920d77a5ef2bcf98c26
bigcode/the-stack
train
404ad21cd2556f733e1668c8
train
class
class Subversion(AutotoolsPackage): """Apache Subversion - an open source version control system.""" homepage = 'https://subversion.apache.org/' url = 'https://archive.apache.org/dist/subversion/subversion-1.12.2.tar.gz' version('1.12.2', sha256='f4927d6603d96c5ddabebbafe9a0f6833c18a891ff0ce1ea6f...
class Subversion(AutotoolsPackage):
"""Apache Subversion - an open source version control system.""" homepage = 'https://subversion.apache.org/' url = 'https://archive.apache.org/dist/subversion/subversion-1.12.2.tar.gz' version('1.12.2', sha256='f4927d6603d96c5ddabebbafe9a0f6833c18a891ff0ce1ea6ffd186ce9bc21f3') version('1.9.7'...
# Copyright 2013-2019 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 Subversion(AutotoolsPackage):
63
256
1,119
9
54
slabasan/spack
var/spack/repos/builtin/packages/subversion/package.py
Python
Subversion
Subversion
9
107
9
9
7e2589da091e7bf0f2fb8ff1ec665ea56dca2b2b
bigcode/the-stack
train
9b6be64a19be07e9bb03a118
train
class
class MarkerValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__( self, plotly_name="marker", parent_name="scattergeo.selected", **kwargs ): super(MarkerValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_...
class MarkerValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__( self, plotly_name="marker", parent_name="scattergeo.selected", **kwargs ): super(MarkerValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Marker"), data_docs=kwarg...
import _plotly_utils.basevalidators class MarkerValidator(_plotly_utils.basevalidators.CompoundValidator):
21
64
140
13
7
mastermind88/plotly.py
packages/python/plotly/plotly/validators/scattergeo/selected/_marker.py
Python
MarkerValidator
MarkerValidator
4
24
4
4
5a7a45736283381446209826d48569f63cb24977
bigcode/the-stack
train
019aedee536cc93a861b08a1
train
function
def hexrep(data, delimit=True): delimiter = ":" if not delimit: delimiter = "" hexrep = delimiter.join("{:02x}".format(ord(c)) for c in data) return hexrep
def hexrep(data, delimit=True):
delimiter = ":" if not delimit: delimiter = "" hexrep = delimiter.join("{:02x}".format(ord(c)) for c in data) return hexrep
if (logdest == LOG_FILE and logfile != None): file = open(logfile, "a") file.write(logstring+"\n") file.close() def rand(): result = random.random() return result def hexprint(data): print(hexrep(hexrep)) def hexrep(data, delimit=True):
64
64
46
8
56
scottrcarlson/Reticulum
RNS/__init__.py
Python
hexrep
hexrep
79
84
79
79
f5c9d054ce165d004b6db5fdd025a6ec3946157b
bigcode/the-stack
train
78a793588dcdb444b5b49049
train
function
def hexprint(data): print(hexrep(hexrep))
def hexprint(data):
print(hexrep(hexrep))
(logdest == LOG_STDOUT): print(logstring) if (logdest == LOG_FILE and logfile != None): file = open(logfile, "a") file.write(logstring+"\n") file.close() def rand(): result = random.random() return result def hexprint(data):
64
64
11
5
58
scottrcarlson/Reticulum
RNS/__init__.py
Python
hexprint
hexprint
76
77
76
76
12de0508663b4dcc2763eaf0dbaa9539c8864059
bigcode/the-stack
train
66c312f1a1ceafb0c558c7c3
train
function
def panic(): os._exit(255)
def panic():
os._exit(255)
hexrep = delimiter.join("{:02x}".format(ord(c)) for c in data) return hexrep def prettyhexrep(data): delimiter = "" hexrep = "<"+delimiter.join("{:02x}".format(ord(c)) for c in data)+">" return hexrep def panic():
64
64
9
3
60
scottrcarlson/Reticulum
RNS/__init__.py
Python
panic
panic
91
92
91
91
f0d558a7db731eb6d1e1a70b64b582f79840d1fd
bigcode/the-stack
train
67c2c6c6d669a8e54597808e
train
function
def loglevelname(level): if (level == LOG_CRITICAL): return "Critical" if (level == LOG_ERROR): return "Error" if (level == LOG_WARNING): return "Warning" if (level == LOG_NOTICE): return "Notice" if (level == LOG_INFO): return "Info" if (level == LOG_VERBOSE): return "Verbose" if (level == LOG_DEBUG...
def loglevelname(level):
if (level == LOG_CRITICAL): return "Critical" if (level == LOG_ERROR): return "Error" if (level == LOG_WARNING): return "Warning" if (level == LOG_NOTICE): return "Notice" if (level == LOG_INFO): return "Info" if (level == LOG_VERBOSE): return "Verbose" if (level == LOG_DEBUG): return "Debug" if (...
LOG_FILE = 0x92 loglevel = LOG_NOTICE logfile = None logdest = LOG_STDOUT logtimefmt = "%Y-%m-%d %H:%M:%S" random.seed(os.urandom(10)) def loglevelname(level):
64
64
110
6
58
scottrcarlson/Reticulum
RNS/__init__.py
Python
loglevelname
loglevelname
38
56
38
38
d70c5765393d18afc855f79946d90a7c1bf33881
bigcode/the-stack
train
ba80adc5e34a2df260420c39
train
function
def prettyhexrep(data): delimiter = "" hexrep = "<"+delimiter.join("{:02x}".format(ord(c)) for c in data)+">" return hexrep
def prettyhexrep(data):
delimiter = "" hexrep = "<"+delimiter.join("{:02x}".format(ord(c)) for c in data)+">" return hexrep
def hexprint(data): print(hexrep(hexrep)) def hexrep(data, delimit=True): delimiter = ":" if not delimit: delimiter = "" hexrep = delimiter.join("{:02x}".format(ord(c)) for c in data) return hexrep def prettyhexrep(data):
64
64
38
6
57
scottrcarlson/Reticulum
RNS/__init__.py
Python
prettyhexrep
prettyhexrep
86
89
86
86
70ce263be373a5bb7eea29fd4bcfddcde65470c9
bigcode/the-stack
train
92d355bdef5f824657074371
train
function
def log(msg, level=3): # TODO: not thread safe if loglevel >= level: timestamp = time.time() logstring = "["+time.strftime(logtimefmt)+"] ["+loglevelname(level)+"] "+msg if (logdest == LOG_STDOUT): print(logstring) if (logdest == LOG_FILE and logfile != None): file = open(logfile, "a") file.write(l...
def log(msg, level=3): # TODO: not thread safe
if loglevel >= level: timestamp = time.time() logstring = "["+time.strftime(logtimefmt)+"] ["+loglevelname(level)+"] "+msg if (logdest == LOG_STDOUT): print(logstring) if (logdest == LOG_FILE and logfile != None): file = open(logfile, "a") file.write(logstring+"\n") file.close()
return "Info" if (level == LOG_VERBOSE): return "Verbose" if (level == LOG_DEBUG): return "Debug" if (level == LOG_EXTREME): return "Extra" return "Unknown" def log(msg, level=3): # TODO: not thread safe
64
64
103
16
48
scottrcarlson/Reticulum
RNS/__init__.py
Python
log
log
58
70
58
59
de1eda55715eb4e99cf7d59281d230612fbe8cd8
bigcode/the-stack
train
053383e414307755f51f28a5
train
function
def rand(): result = random.random() return result
def rand():
result = random.random() return result
["+loglevelname(level)+"] "+msg if (logdest == LOG_STDOUT): print(logstring) if (logdest == LOG_FILE and logfile != None): file = open(logfile, "a") file.write(logstring+"\n") file.close() def rand():
64
64
11
3
61
scottrcarlson/Reticulum
RNS/__init__.py
Python
rand
rand
72
74
72
72
18108467f53c4d305deb14f4c9abc981a93fa5cb
bigcode/the-stack
train
3fe081d4e68e567e10002591
train
function
def create_db(): # TODO, all the rest # for the moment I'm just starting to structure the DB ideas in the gutenberg_sql.py file pass
def create_db(): # TODO, all the rest # for the moment I'm just starting to structure the DB ideas in the gutenberg_sql.py file
pass
_dir, exist_ok=True) with open(f'{target_dir}/{author}.json', 'w') as f: f.write(json_data) def create_db(): # TODO, all the rest # for the moment I'm just starting to structure the DB ideas in the gutenberg_sql.py file
64
64
37
34
30
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
create_db
create_db
123
126
123
125
d3cd989d05bdb02d31a28e2942fd7b3937c50afc
bigcode/the-stack
train
9971aa895ed679c17afaf75b
train
function
def aggregate_by_language(): languages = os.listdir(LANGUAGES_DIR) for language in languages: print(f'Aggregating by language: [{language}]') aggregated_stats = sum_stats(f'{LANGUAGES_DIR}/{language}') json_data = json.dumps(aggregated_stats) target_dir = f'{TARGET_DIR}/by_lang...
def aggregate_by_language():
languages = os.listdir(LANGUAGES_DIR) for language in languages: print(f'Aggregating by language: [{language}]') aggregated_stats = sum_stats(f'{LANGUAGES_DIR}/{language}') json_data = json.dumps(aggregated_stats) target_dir = f'{TARGET_DIR}/by_language' os.makedirs(tar...
][dist_name]) # MAYBE: remove Counters return aggregated_stats # for manual testing purposes def aggregate_sample(): sample_data_path = 'gutenberg_stats_examples' # print(sum_stats(sample_data_path)['doc']) print(sum_stats(sample_data_path)) def aggregate_by_language():
64
64
107
5
59
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
aggregate_by_language
aggregate_by_language
88
100
88
88
ca4a5480f1c3afbc9af80d080eafd4d0a28e313a
bigcode/the-stack
train
e6203410f5a548a944330bbe
train
function
def main(): # aggregate_sample() aggregate_by_language() if not 'short' in TARGET_DIR: aggregate_by_author()
def main(): # aggregate_sample()
aggregate_by_language() if not 'short' in TARGET_DIR: aggregate_by_author()
import sqlite3 LANGUAGES_DIR = 'gutenberg_stats/clean_results' TARGET_DIR = 'gutenberg_stats_short/aggregate' # uncomment to include by word statistics, will not be committed # TARGET_DIR = 'gutenberg_stats/aggregate' def main(): # aggregate_sample()
64
64
28
8
56
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
main
main
24
29
24
25
bf9f0a01f5219580577a6fcfea1c5b0e37e361fc
bigcode/the-stack
train
47e97bc7eef6f28ce05fc608
train
function
def aggregate_by_author(): languages = os.listdir(LANGUAGES_DIR) for language in languages: authors = os.listdir(f'{LANGUAGES_DIR}/{language}') for author in authors: print(f'Aggregating by language: [{language}], Author: [{author}]') aggregated_stats = sum_stats(f'{L...
def aggregate_by_author():
languages = os.listdir(LANGUAGES_DIR) for language in languages: authors = os.listdir(f'{LANGUAGES_DIR}/{language}') for author in authors: print(f'Aggregating by language: [{language}], Author: [{author}]') aggregated_stats = sum_stats(f'{LANGUAGES_DIR}/{language}/{a...
language}') json_data = json.dumps(aggregated_stats) target_dir = f'{TARGET_DIR}/by_language' os.makedirs(target_dir, exist_ok=True) with open(f'{target_dir}/{language}.json', 'w') as f: f.write(json_data) def aggregate_by_author():
64
64
137
5
59
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
aggregate_by_author
aggregate_by_author
103
120
103
103
47dc64fd1db588ad859c45ce290d46559c78a69f
bigcode/the-stack
train
9c8d7b9ecd2bb11484b53f39
train
function
def sum_stats(data_source_path): ''' :param data_source_path: directory with json.gz files to aggregate :returns: a dict with summed values ''' aggregated_stats = { 'doc': Counter(), 'by_paragraph': { 'sentence_length': Counter(), 'word_length': Counter...
def sum_stats(data_source_path):
''' :param data_source_path: directory with json.gz files to aggregate :returns: a dict with summed values ''' aggregated_stats = { 'doc': Counter(), 'by_paragraph': { 'sentence_length': Counter(), 'word_length': Counter(), 'token_length': ...
import json import sqlite3 LANGUAGES_DIR = 'gutenberg_stats/clean_results' TARGET_DIR = 'gutenberg_stats_short/aggregate' # uncomment to include by word statistics, will not be committed # TARGET_DIR = 'gutenberg_stats/aggregate' def main(): # aggregate_sample() aggregate_by_language() if not 'sho...
94
94
315
7
87
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
sum_stats
sum_stats
32
78
32
32
79354d715792c71017ef37154eb4a8a4b5be2bf1
bigcode/the-stack
train
6f6aa30a18918c41cdbe9ee5
train
function
def aggregate_sample(): sample_data_path = 'gutenberg_stats_examples' # print(sum_stats(sample_data_path)['doc']) print(sum_stats(sample_data_path))
def aggregate_sample():
sample_data_path = 'gutenberg_stats_examples' # print(sum_stats(sample_data_path)['doc']) print(sum_stats(sample_data_path))
# MAYBE: deal with nesting dynamically for level in levels: for dist_name, agg_dist in aggregated_stats[level].items(): agg_dist.update(book_stats[level][dist_name]) # MAYBE: remove Counters return aggregated_stats # for manual testing purposes def aggregate_sample():
64
64
35
4
59
leomrocha/mix_nlp
utf8/postprocessors/gutenberg_aggregate.py
Python
aggregate_sample
aggregate_sample
82
85
82
82
9c4b7978a3f09c8bf74d28dc4f64206e6bd4e3ab
bigcode/the-stack
train
38618b1d34245ce665981acd
train
class
class MyBuilder2(MyBuilder): def __init__(self): super().__init__() self.tasks += [ { 'name': 'afile', 'reqs': ['testfolder'], 'outputs': ['testfolder/testfile'], 'action': self.mkfile } ] def mkfi...
class MyBuilder2(MyBuilder):
def __init__(self): super().__init__() self.tasks += [ { 'name': 'afile', 'reqs': ['testfolder'], 'outputs': ['testfolder/testfile'], 'action': self.mkfile } ] def mkfile(self, t): with open...
'folder', 'outputs': ['testfolder'], 'action': self.mkfolder, 'flags': Builder.PRESENT # Up to date of output is present } ] def mkfolder(self, t): os.mkdir(t['outputs'][0]) class MyBuilder2(MyBuilder):
64
64
94
7
57
jpcaram/simplebuilder
tests/test_builder.py
Python
MyBuilder2
MyBuilder2
28
44
28
29
b2daa709a970e4e88019553a867179b83cc9e739
bigcode/the-stack
train
53881047ad94816a99efea1f
train
class
class MyBuilder(Builder): def __init__(self): super().__init__() self.logger.setLevel('DEBUG') self.tasks = [ { 'name': 'folder', 'outputs': ['testfolder'], 'action': self.mkfolder, 'flags': Builder.PRESENT # Up ...
class MyBuilder(Builder):
def __init__(self): super().__init__() self.logger.setLevel('DEBUG') self.tasks = [ { 'name': 'folder', 'outputs': ['testfolder'], 'action': self.mkfolder, 'flags': Builder.PRESENT # Up to date of output is presen...
from unittest import TestCase from simplebuilder import Builder import os from time import sleep from pathlib import Path class MyBuilder(Builder):
31
64
94
6
24
jpcaram/simplebuilder
tests/test_builder.py
Python
MyBuilder
MyBuilder
8
25
8
9
fb0162e3dbda3cf06786c27686ffb79613d685c5
bigcode/the-stack
train
f7f717e64f7e666a97dbcf9b
train
class
class TestBuilder(TestCase): def test_flags1(self): builder = MyBuilder() try: os.rmdir(builder.tasks[0]['outputs'][0]) except FileNotFoundError: pass self.assertTrue(builder.run('folder')) self.assertFalse(builder.run('folder')) os.rmdir(bui...
class TestBuilder(TestCase):
def test_flags1(self): builder = MyBuilder() try: os.rmdir(builder.tasks[0]['outputs'][0]) except FileNotFoundError: pass self.assertTrue(builder.run('folder')) self.assertFalse(builder.run('folder')) os.rmdir(builder.tasks[0]['outputs'][0]) ...
self.tasks = [ { 'name': 'folder', 'outputs': ['testfolder'], 'action': self.mkfolder, 'flags': Builder.PRESENT # Up to date of output is present } ] def mkfolder(self, t): os.mkdir(t['outputs'][0]) c...
168
169
564
6
163
jpcaram/simplebuilder
tests/test_builder.py
Python
TestBuilder
TestBuilder
47
139
47
48
275e4f8b2b42f717ac9dbf1ef69ef016e3643314
bigcode/the-stack
train
85452f0631974d229e160b19
train
function
def fake_gethostbyname(hostname): try: host_ip = None # for templates/index.py if hostname == config.get("broker", "bind_address"): host_ip = gethostbyname_orig(hostname) else: # faking hostip fake_hosts_file = config.get('unittest', 'fake_hosts_lo...
def fake_gethostbyname(hostname):
try: host_ip = None # for templates/index.py if hostname == config.get("broker", "bind_address"): host_ip = gethostbyname_orig(hostname) else: # faking hostip fake_hosts_file = config.get('unittest', 'fake_hosts_location') fake_hosts = ...
: disable=W0611 from aquilon.worker import depends # pylint: disable=W0611 from aquilon.config import Config # dwim options parser for i in range(0, len(sys.argv)): if sys.argv[i] == "--config": configpath = sys.argv[i + 1] break config = Config(configfile=configpath) # do the patches def fake_...
91
91
306
9
81
ned21/aquilon
lib/aquilon/unittest_patches.py
Python
fake_gethostbyname
fake_gethostbyname
51
87
51
51
c86725897e785200d74bade9ad9dc4353e50031c
bigcode/the-stack
train
59a7bbe4daa374f7e1f44b50
train
function
@pytest.fixture def pool_value_delta(): return 100000000000000000000
@pytest.fixture def pool_value_delta():
return 100000000000000000000
@pytest.fixture def keeper_id(): return 1 @pytest.fixture def pool_duration(): return 3600 @pytest.fixture def pool_threshold(): return 4000000000000000000000 @pytest.fixture def round_id(): return 1 @pytest.fixture def pool_value_delta():
64
64
19
8
55
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
pool_value_delta
pool_value_delta
88
90
88
89
17486c32957e0d10854939fe500eaa016910d520
bigcode/the-stack
train
6f0db33f7f8e0dd37a8125fc
train
function
@pytest.fixture def node_account(): return accounts[1]
@pytest.fixture def node_account():
return accounts[1]
["networks"]: return config["networks"][network.show_active()]["jobId"] else: pytest.skip("Invalid network/link token specified") @pytest.fixture def get_data(): return 100 @pytest.fixture def dev_account(): return accounts[0] @pytest.fixture def node_account():
64
64
13
7
57
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
node_account
node_account
43
45
43
44
bb271b787da02bbd1881ea8840b95dffe9312ee7
bigcode/the-stack
train
9410e81502251371281b8436
train
function
@pytest.fixture def min_bet(): return 1000000000
@pytest.fixture def min_bet():
return 1000000000
.fixture def dev_account(): return accounts[0] @pytest.fixture def node_account(): return accounts[1] @pytest.fixture def chainlink_fee(): return 1000000000000000000 @pytest.fixture def expiry_time(): return 300 @pytest.fixture def min_bet():
64
64
16
8
55
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
min_bet
min_bet
58
60
58
59
d712d444e284abf2b3b7049dbc09a71462f63f8b
bigcode/the-stack
train
e420feaacbe27f74fff0c217
train
function
@pytest.fixture def keeper_id(): return 1
@pytest.fixture def keeper_id():
return 1
def chainlink_fee(): return 1000000000000000000 @pytest.fixture def expiry_time(): return 300 @pytest.fixture def min_bet(): return 1000000000 @pytest.fixture def fee_bps(): return 100 @pytest.fixture def keeper_id():
64
64
12
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
keeper_id
keeper_id
68
70
68
69
73655530d44361f81afc2e44f7f480ac17ed2647
bigcode/the-stack
train
71dd5745a820375ab165779a
train
function
@pytest.fixture def pool_duration(): return 3600
@pytest.fixture def pool_duration():
return 3600
0000000 @pytest.fixture def expiry_time(): return 300 @pytest.fixture def min_bet(): return 1000000000 @pytest.fixture def fee_bps(): return 100 @pytest.fixture def keeper_id(): return 1 @pytest.fixture def pool_duration():
64
64
13
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
pool_duration
pool_duration
73
75
73
74
6b68d70ff05cd7eb44ae4a12b2e8b645b457f55e
bigcode/the-stack
train
6a988d487f1803f4bc829bfe
train
function
@pytest.fixture def dev_account(): return accounts[0]
@pytest.fixture def dev_account():
return accounts[0]
return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["jobId"] else: pytest.skip("Invalid network/link token specified") @pytest.fixture def get_data(): return 100 @pytest.fixture def dev_account():
64
64
13
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
dev_account
dev_account
38
40
38
39
3a8e7f93b43f1b6acc8cab4ff2d3e0f3ca03befa
bigcode/the-stack
train
b55e268516b8692528873a1d
train
function
@pytest.fixture def pool_threshold(): return 4000000000000000000000
@pytest.fixture def pool_threshold():
return 4000000000000000000000
300 @pytest.fixture def min_bet(): return 1000000000 @pytest.fixture def fee_bps(): return 100 @pytest.fixture def keeper_id(): return 1 @pytest.fixture def pool_duration(): return 3600 @pytest.fixture def pool_threshold():
64
64
19
7
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
pool_threshold
pool_threshold
78
80
78
79
760152f46736fb1ec9d3c4853b1f58429dd5fe24
bigcode/the-stack
train
e35933b4ef01134f3544d967
train
function
@pytest.fixture def get_keyhash(): if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["keyhash"] else: pytest.skip("Invalid network/link token specified ")
@pytest.fixture def get_keyhash():
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["keyhash"] else: pytest.skip("Invalid network/link token specified ")
import pytest from brownie import ( accounts, config, network, ) from scripts.helpful_scripts import ( LOCAL_BLOCKCHAIN_ENVIRONMENTS, get_contract ) @pytest.fixture def get_keyhash():
45
64
67
8
37
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
get_keyhash
get_keyhash
13
20
13
14
806a7a559f4bedf7abcd4b112c7713337bca8a01
bigcode/the-stack
train
2010f9f27ddb79f272841f4b
train
function
@pytest.fixture def get_data(): return 100
@pytest.fixture def get_data():
return 100
network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["jobId"] else: pytest.skip("Invalid network/link token specified") @pytest.fixture def get_data():
64
64
12
7
57
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
get_data
get_data
33
35
33
34
b0bf2aa4aac69aee832fd4f6d32952f8a459b310
bigcode/the-stack
train
30b6d0686adf99464a32b14c
train
function
@pytest.fixture def chainlink_fee(): return 1000000000000000000
@pytest.fixture def chainlink_fee():
return 1000000000000000000
()]["jobId"] else: pytest.skip("Invalid network/link token specified") @pytest.fixture def get_data(): return 100 @pytest.fixture def dev_account(): return accounts[0] @pytest.fixture def node_account(): return accounts[1] @pytest.fixture def chainlink_fee():
64
64
19
8
56
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
chainlink_fee
chainlink_fee
48
50
48
49
7797ca140064beec7bb42b2b821992bac754a4a4
bigcode/the-stack
train
1474f9559db840a00731904c
train
function
@pytest.fixture def get_job_id(): if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["jobId"] else: pytest.skip("Invalid network/link token specified")
@pytest.fixture def get_job_id():
if network.show_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["jobId"] else: pytest.skip("Invalid network/link token specified")
_active() in LOCAL_BLOCKCHAIN_ENVIRONMENTS: return 0 if network.show_active() in config["networks"]: return config["networks"][network.show_active()]["keyhash"] else: pytest.skip("Invalid network/link token specified ") @pytest.fixture def get_job_id():
63
64
67
8
55
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
get_job_id
get_job_id
23
30
23
24
7f68b316dbc5f0b5a92d5a63d5f0cf265e3ffd61
bigcode/the-stack
train
eb758e0d9670366fa83af68d
train
function
@pytest.fixture def fee_bps(): return 100
@pytest.fixture def fee_bps():
return 100
node_account(): return accounts[1] @pytest.fixture def chainlink_fee(): return 1000000000000000000 @pytest.fixture def expiry_time(): return 300 @pytest.fixture def min_bet(): return 1000000000 @pytest.fixture def fee_bps():
64
64
13
8
55
irustandi/chainlink-hackathon-fall-2021
tests/conftest.py
Python
fee_bps
fee_bps
63
65
63
64
6112a8170cd9b4a858fe23e5d6c1fc654924cb0c
bigcode/the-stack
train