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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d6a26e903e94838322be4fb7 | train | function | def factorize_from_iterables(iterables):
"""
A higher-level wrapper over `factorize_from_iterable`.
*This is an internal function*
Parameters
----------
iterables : list-like of list-likes
Returns
-------
codes_list : list of ndarrays
categories_list : list of Indexes
Not... | def factorize_from_iterables(iterables):
| """
A higher-level wrapper over `factorize_from_iterable`.
*This is an internal function*
Parameters
----------
iterables : list-like of list-likes
Returns
-------
codes_list : list of ndarrays
categories_list : list of Indexes
Notes
-----
See `factorize_from_iter... | categories, the order of which is independent
# from ordered. Set ordered to False as default. See GH #15457
cat = Categorical(values, ordered=False)
categories = cat.categories
codes = cat.codes
return codes, categories
def factorize_from_iterables(iterables):
| 64 | 64 | 143 | 9 | 54 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | factorize_from_iterables | factorize_from_iterables | 2,698 | 2,720 | 2,698 | 2,698 | 37e45e4ab59d52f11230872c5f53401b06d41779 | bigcode/the-stack | train |
67207daa02954bd9471e8b08 | train | function | def _cat_compare_op(op):
opname = f"__{op.__name__}__"
@unpack_zerodim_and_defer(opname)
def func(self, other):
if is_list_like(other) and len(other) != len(self):
# TODO: Could this fail if the categories are listlike objects?
raise ValueError("Lengths must match.")
... | def _cat_compare_op(op):
| opname = f"__{op.__name__}__"
@unpack_zerodim_and_defer(opname)
def func(self, other):
if is_list_like(other) and len(other) != len(self):
# TODO: Could this fail if the categories are listlike objects?
raise ValueError("Lengths must match.")
if not self.ordered:
... | .core.dtypes.inference import is_hashable
from pandas.core.dtypes.missing import isna, notna
from pandas.core import ops
from pandas.core.accessor import PandasDelegate, delegate_names
import pandas.core.algorithms as algorithms
from pandas.core.algorithms import _get_data_algo, factorize, take_1d, unique1d
from panda... | 211 | 211 | 705 | 7 | 203 | andresmcneill/pandas | pandas/core/arrays/categorical.py | Python | _cat_compare_op | _cat_compare_op | 59 | 141 | 59 | 59 | 85124596624f03af4f189c070b84832109b60b8f | bigcode/the-stack | train |
339ef73f02027c51618ad609 | train | function | def filter(args):
"""选择包含给定id的样本,并按包含数量从高到低排序。"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
badcases = read_badcases_file(args.badcases_file, args.distance_thrsh)
process_sample_file(args.sample_file, args.output_file, badcases)
| def filter(args):
| """选择包含给定id的样本,并按包含数量从高到低排序。"""
head = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=head)
badcases = read_badcases_file(args.badcases_file, args.distance_thrsh)
process_sample_file(args.sample_file, args.output_file, badcases)
| :
line = line.strip()
fields = line.split()
sample_fp = fields[0]
if sample_fp in badcases:
num_deleted += 1
else:
out_f.write(line + '\n')
print('%d samples are deleted' % num_deleted)
def filter(args):
| 64 | 64 | 83 | 4 | 60 | myuanz/cnocr | scripts/filter_samples.py | Python | filter | filter | 80 | 85 | 80 | 80 | 073aea1457cce3233ec363b9d8aded7b297e2a14 | bigcode/the-stack | train |
b0bab11579569a54cab58bb6 | train | function | def read_badcases_file(fp, dist_thrsh):
badcases = set()
with open(fp) as f:
for line in f:
line = line.strip()
fields = line.split('\t')
if fields[0] == 'distance':
continue
dist, fp = int(fields[0]), fields[1]
if dist >= dist_... | def read_badcases_file(fp, dist_thrsh):
| badcases = set()
with open(fp) as f:
for line in f:
line = line.strip()
fields = line.split('\t')
if fields[0] == 'distance':
continue
dist, fp = int(fields[0]), fields[1]
if dist >= dist_thrsh:
fp = '/'.join(fp.... | thrsh will be deleted", type=int, default=2
)
parser.add_argument(
"-o",
"--output_file",
help="the new sample file",
type=str,
required=True,
)
return parser.parse_args()
def read_badcases_file(fp, dist_thrsh):
| 64 | 64 | 119 | 11 | 53 | myuanz/cnocr | scripts/filter_samples.py | Python | read_badcases_file | read_badcases_file | 49 | 62 | 49 | 49 | a57e2d706c4a93f720a745b193025fc81bee1f32 | bigcode/the-stack | train |
b7d11a023d95cd5fafd24be1 | train | function | def process_sample_file(in_fp, out_fp, badcases):
num_deleted = 0
with open(in_fp) as in_f, open(out_fp, 'w') as out_f:
for line in in_f:
line = line.strip()
fields = line.split()
sample_fp = fields[0]
if sample_fp in badcases:
num_deleted... | def process_sample_file(in_fp, out_fp, badcases):
| num_deleted = 0
with open(in_fp) as in_f, open(out_fp, 'w') as out_f:
for line in in_f:
line = line.strip()
fields = line.split()
sample_fp = fields[0]
if sample_fp in badcases:
num_deleted += 1
else:
out_f.writ... | fields[1]
if dist >= dist_thrsh:
fp = '/'.join(fp.split('/')[-2:])
badcases.add(fp)
print('get %d badcase samples' % len(badcases))
return badcases
def process_sample_file(in_fp, out_fp, badcases):
| 64 | 64 | 107 | 13 | 50 | myuanz/cnocr | scripts/filter_samples.py | Python | process_sample_file | process_sample_file | 65 | 77 | 65 | 65 | 7479d47b23cd96befd266957f10401d877a66b9a | bigcode/the-stack | train |
678124d1484823cc71c79b49 | train | function | def parse_args():
# Parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"--sample_file", help="Path to train or test txt file", type=str, required=True
)
parser.add_argument(
"--badcases_file", help="Path to badcases file from evaluate mode", type=str... | def parse_args():
# Parse command line arguments
| parser = argparse.ArgumentParser()
parser.add_argument(
"--sample_file", help="Path to train or test txt file", type=str, required=True
)
parser.add_argument(
"--badcases_file", help="Path to badcases file from evaluate mode", type=str, required=True
)
parser.add_argument(
... | specific language governing permissions and limitations
# under the License.
"""
从badcases.txt中可以发现一些不好的训练样本。这个脚本就是为了过滤掉这些样本。
"""
from __future__ import print_function
import argparse
import logging
def parse_args():
# Parse command line arguments
| 64 | 64 | 146 | 11 | 52 | myuanz/cnocr | scripts/filter_samples.py | Python | parse_args | parse_args | 27 | 46 | 27 | 28 | aa875fa6a025b6ce7a4a2d8ce369087163180966 | bigcode/the-stack | train |
1e40f6b5b48a6a76582f1295 | train | class | class Solution:
def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
if not root.children:
return 1
currentMax = 1 + max(self.maxDepth(child) for child in root.children)
return currentMax | class Solution:
| def maxDepth(self, root: 'Node') -> int:
if not root:
return 0
if not root.children:
return 1
currentMax = 1 + max(self.maxDepth(child) for child in root.children)
return currentMax | """
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
| 39 | 64 | 61 | 3 | 36 | yuzhengcuhk/MyLeetcodeRecord | 559-maximum-depth-of-n-ary-tree/559-maximum-depth-of-n-ary-tree.py | Python | Solution | Solution | 9 | 16 | 9 | 9 | 2fa67374abda00a43f3a45617493de073397a93a | bigcode/the-stack | train |
12441fbeb638adb57dac250f | train | function | def get_unitary(self):
"""
Funtion to get the unitary matrix corresponding to an entire circuit.
Acts on self and returns the corresponding unitary
"""
num_qubits = int(
max(self.qubits) + 1
) # Coincides with self.qubit_count when qubit indexing is contiguous.
# Define the unitary... | def get_unitary(self):
| """
Funtion to get the unitary matrix corresponding to an entire circuit.
Acts on self and returns the corresponding unitary
"""
num_qubits = int(
max(self.qubits) + 1
) # Coincides with self.qubit_count when qubit indexing is contiguous.
# Define the unitary matrix. Start with the... | import numpy as np
from braket.circuits import Circuit, circuit
def get_unitary(self):
| 22 | 152 | 509 | 6 | 15 | FengShi0705/amazon-braket-examples | examples/advanced_circuits_algorithms/QAA/utils_circuit.py | Python | get_unitary | get_unitary | 5 | 55 | 5 | 5 | 56ed420e2912bcbe392d02e8cad97f6e1acdf7fb | bigcode/the-stack | train |
915669c3ea33ce3872d04222 | train | function | def adjoint(self):
"""Generates a circuit object corresponding to the adjoint of a given circuit, in which the order
of gates is reversed, and each gate is the adjoint (i.e., conjugate transpose) of the original.
"""
adjoint_circ = Circuit()
# Loop through the instructions (gates) in the circuit:
... | def adjoint(self):
| """Generates a circuit object corresponding to the adjoint of a given circuit, in which the order
of gates is reversed, and each gate is the adjoint (i.e., conjugate transpose) of the original.
"""
adjoint_circ = Circuit()
# Loop through the instructions (gates) in the circuit:
for instruction... | axes = (
np.arange(len(targets), 2 * len(targets)),
targets,
)
# Apply the gate by contracting the existing unitary with the new gate
unitary = np.tensordot(gate_matrix, unitary, axes=axes)
# tensordot causes the axes contracted to end up in the first positions... | 256 | 256 | 1,016 | 5 | 250 | FengShi0705/amazon-braket-examples | examples/advanced_circuits_algorithms/QAA/utils_circuit.py | Python | adjoint | adjoint | 58 | 155 | 58 | 58 | 8cf2a91f28d2a05749d85fbb084878bf9c3acf4d | bigcode/the-stack | train |
62c9936a99eaedcdcaa809ed | train | class | class TestFlattenConvert(OPConvertAutoScanTest):
"""
api: paddle.flatten
OPset version: 7, 9, 15
"""
def sample_convert_config(self, draw):
input_shape = draw(
st.lists(
st.integers(
min_value=1, max_value=20), min_size=2, max_size=5))
... | class TestFlattenConvert(OPConvertAutoScanTest):
| """
api: paddle.flatten
OPset version: 7, 9, 15
"""
def sample_convert_config(self, draw):
input_shape = draw(
st.lists(
st.integers(
min_value=1, max_value=20), min_size=2, max_size=5))
dtype = draw(st.sampled_from(["int32", "int64",... | OPConvertAutoScanTest, BaseNet
from hypothesis import reproduce_failure
import hypothesis.strategies as st
import numpy as np
import unittest
import paddle
class Net(BaseNet):
"""
simple Net
"""
def forward(self, x):
"""
forward
"""
x = paddle.flatten(
x,
... | 102 | 102 | 341 | 10 | 91 | neonhuang/Paddle2ONNX | tests/test_auto_scan_flatten.py | Python | TestFlattenConvert | TestFlattenConvert | 39 | 85 | 39 | 39 | 455ab50e2acf26fc2dbdf663053889e40da9966f | bigcode/the-stack | train |
cf2046f569ff29f8fce1b1e9 | train | class | class Net(BaseNet):
"""
simple Net
"""
def forward(self, x):
"""
forward
"""
x = paddle.flatten(
x,
start_axis=self.config["start_axis"],
stop_axis=self.config["stop_axis"])
return x
| class Net(BaseNet):
| """
simple Net
"""
def forward(self, x):
"""
forward
"""
x = paddle.flatten(
x,
start_axis=self.config["start_axis"],
stop_axis=self.config["stop_axis"])
return x
| implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from auto_scan_test import OPConvertAutoScanTest, BaseNet
from hypothesis import reproduce_failure
import hypothesis.strategies as st
import numpy as np
import unittest
import paddle
class Net(BaseNet):
| 64 | 64 | 58 | 5 | 58 | neonhuang/Paddle2ONNX | tests/test_auto_scan_flatten.py | Python | Net | Net | 23 | 36 | 23 | 23 | 70c408bd461b92d5365091c1429867ad083b42e3 | bigcode/the-stack | train |
5da316fb9762215814581372 | train | function | def _aggregate_predict_results(strategy, batch_outs, model):
if not isinstance(batch_outs, list):
batch_outs = [batch_outs]
total_batch_outs = []
for i in range(len(model.outputs)):
num_replicas = strategy.num_replicas_in_sync
nested_outs = batch_outs[i * num_replicas:i * num_replicas + num_replicas]
... | def _aggregate_predict_results(strategy, batch_outs, model):
| if not isinstance(batch_outs, list):
batch_outs = [batch_outs]
total_batch_outs = []
for i in range(len(model.outputs)):
num_replicas = strategy.num_replicas_in_sync
nested_outs = batch_outs[i * num_replicas:i * num_replicas + num_replicas]
total_batch_outs.append(
dist_utils.concat_along_... | () or not adapter.batch_size():
return None
total_sample = adapter.get_size() * adapter.batch_size()
if adapter.has_partial_batch():
total_sample -= (adapter.batch_size() - adapter.partial_batch_size())
return total_sample
def _aggregate_predict_results(strategy, batch_outs, model):
| 64 | 64 | 119 | 13 | 50 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _aggregate_predict_results | _aggregate_predict_results | 641 | 650 | 641 | 641 | 942cc7e115350c7390ef0b80d7e924c6479cab07 | bigcode/the-stack | train |
34a8140cec1310f817f9cce6 | train | function | def _process_inputs(model,
x,
y,
batch_size=None,
epochs=1,
sample_weights=None,
class_weights=None,
shuffle=False,
steps=None,
distribution... | def _process_inputs(model,
x,
y,
batch_size=None,
epochs=1,
sample_weights=None,
class_weights=None,
shuffle=False,
steps=None,
distribution... | """Process the inputs for fit/eval/predict()."""
adapter_cls = data_adapter.select_data_adapter(x, y)
if adapter_cls in _ADAPTER_FOR_STANDARDIZE_USER_DATA:
x, y, sample_weights = model._standardize_user_data(
x,
y,
sample_weight=sample_weights,
class_weight=class_weights,
... | ` should not be specified if '
'`validation_data` is None.')
return train_adapter, val_adapter
def _process_inputs(model,
x,
y,
batch_size=None,
epochs=1,
sample_weights=None,
... | 87 | 87 | 292 | 64 | 22 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _process_inputs | _process_inputs | 589 | 629 | 589 | 601 | a87cd8439e4c697264a1d8b3bf9dca6e453f3500 | bigcode/the-stack | train |
f7b7150c12f3b005e8f07531 | train | function | def _process_training_inputs(model,
x,
y,
batch_size=None,
epochs=1,
sample_weights=None,
class_weights=None,
steps_p... | def _process_training_inputs(model,
x,
y,
batch_size=None,
epochs=1,
sample_weights=None,
class_weights=None,
steps_p... | """Process the data input for fit() with respect to validation_split."""
if validation_split and 0. < validation_split < 1. and validation_data:
raise ValueError('validation_data and validation_split cannot be used '
'at same time.')
adapter_cls = data_adapter.select_data_adapter(x, y)
... | model, ModeKeys.PREDICT, x=x, batch_size=batch_size, verbose=verbose,
steps=steps, callbacks=callbacks, max_queue_size=max_queue_size,
workers=workers, use_multiprocessing=use_multiprocessing, **kwargs)
def _get_distribution_strategy(model):
"""Get the model's distribution strategy."""
if ... | 210 | 210 | 703 | 83 | 126 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _process_training_inputs | _process_training_inputs | 495 | 586 | 495 | 510 | 7828ecc1bc4c15bf30476d7ac6ac28cb5e7fd48b | bigcode/the-stack | train |
db53848b3c12cbf57f3ff305 | train | function | def _get_distribution_strategy(model):
"""Get the model's distribution strategy."""
if model._compile_time_distribution_strategy:
strategy = model._compile_time_distribution_strategy
else:
# Grab the active strategy if the model was never compiled
# but it is now predicting.
strategy = distributio... | def _get_distribution_strategy(model):
| """Get the model's distribution strategy."""
if model._compile_time_distribution_strategy:
strategy = model._compile_time_distribution_strategy
else:
# Grab the active strategy if the model was never compiled
# but it is now predicting.
strategy = distribution_strategy_context.get_strategy()
ret... | _iteration(
model, ModeKeys.PREDICT, x=x, batch_size=batch_size, verbose=verbose,
steps=steps, callbacks=callbacks, max_queue_size=max_queue_size,
workers=workers, use_multiprocessing=use_multiprocessing, **kwargs)
def _get_distribution_strategy(model):
| 64 | 64 | 72 | 7 | 57 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _get_distribution_strategy | _get_distribution_strategy | 484 | 492 | 484 | 484 | fcf5fa2540fa6bf259946e1fa3afac46fa4779fb | bigcode/the-stack | train |
45889d349b8e4d6ba321d6db | train | class | class TrainingContext(object):
"""Utility object that wrap around callbacks and progress bars."""
@tf_contextlib.contextmanager
def on_start(self, model, callbacks=None, use_samples=False, verbose=0,
mode=ModeKeys.TRAIN):
"""Provide a scope for the whole training process."""
# TODO(omalley... | class TrainingContext(object):
| """Utility object that wrap around callbacks and progress bars."""
@tf_contextlib.contextmanager
def on_start(self, model, callbacks=None, use_samples=False, verbose=0,
mode=ModeKeys.TRAIN):
"""Provide a scope for the whole training process."""
# TODO(omalleyt): Handle ProgBar as part of C... | _outs)))
return total_batch_outs
def _print_train_info(total_samples, steps, val_total_samples, val_steps):
increment = 'samples' if total_samples else 'steps'
conjunction = 'on' if total_samples else 'for'
msg = 'Train {} {} {}'.format(conjunction, total_samples or steps, increment)
if val_total_samples or... | 141 | 141 | 473 | 5 | 136 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | TrainingContext | TrainingContext | 665 | 719 | 665 | 665 | e47bf13f8b52fdfc95788bf295bbee9f9af8afe3 | bigcode/the-stack | train |
a1018ac4fae0f2869078a265 | train | function | def run_one_epoch(model,
iterator,
execution_function,
dataset_size=None,
batch_size=None,
strategy=None,
steps_per_epoch=None,
num_samples=None,
mode=ModeKeys.TRAIN,
... | def run_one_epoch(model,
iterator,
execution_function,
dataset_size=None,
batch_size=None,
strategy=None,
steps_per_epoch=None,
num_samples=None,
mode=ModeKeys.TRAIN,
... | """Run the execution function with the data from iterator.
Given the dataset iterator and execution function, get the data from iterator
and call it with the execution function to get the result (metric/loss).
It will run for steps_per_epoch or until to the iterator is fully consumed.
Args:
model: The k... |
from tensorflow.python.keras.engine import training_utils
from tensorflow.python.keras.engine import training_v2_utils
from tensorflow.python.keras.utils.mode_keys import ModeKeys
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import nest
from tensorflow.python.util import tf_... | 256 | 256 | 1,059 | 56 | 200 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | run_one_epoch | run_one_epoch | 57 | 181 | 57 | 67 | 6bfcefc18d66cd4b3cb4520a4afb14964e55c4d0 | bigcode/the-stack | train |
b0c96b3eb0778bc18c837aaf | train | function | def _print_train_info(total_samples, steps, val_total_samples, val_steps):
increment = 'samples' if total_samples else 'steps'
conjunction = 'on' if total_samples else 'for'
msg = 'Train {} {} {}'.format(conjunction, total_samples or steps, increment)
if val_total_samples or val_steps:
increment = 'samples'... | def _print_train_info(total_samples, steps, val_total_samples, val_steps):
| increment = 'samples' if total_samples else 'steps'
conjunction = 'on' if total_samples else 'for'
msg = 'Train {} {} {}'.format(conjunction, total_samples or steps, increment)
if val_total_samples or val_steps:
increment = 'samples' if val_total_samples else 'steps'
conjunction = 'on' if val_total_samp... | * num_replicas:i * num_replicas + num_replicas]
total_batch_outs.append(
dist_utils.concat_along_batch_dimension(nest.flatten(nested_outs)))
return total_batch_outs
def _print_train_info(total_samples, steps, val_total_samples, val_steps):
| 64 | 64 | 126 | 17 | 46 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _print_train_info | _print_train_info | 653 | 662 | 653 | 653 | 065864c28705aeac058b56cee549dc3d5feb0c90 | bigcode/the-stack | train |
35e9e3a7965bb5656d8e62e5 | train | class | class Loop(training_utils.TrainingLoop):
"""The training loop for the TF 2.0.
This class has some existing assumption for runtime, eg eager by default,
have distribution strategy, etc.
"""
def fit(
self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1,
callbacks=None, validation_spli... | class Loop(training_utils.TrainingLoop):
| """The training loop for the TF 2.0.
This class has some existing assumption for runtime, eg eager by default,
have distribution strategy, etc.
"""
def fit(
self, model, x=None, y=None, batch_size=None, epochs=1, verbose=1,
callbacks=None, validation_split=0., validation_data=None, shuffle=True,... | note the training_context that data inputs are exhausted, so all
# the post batch hooks can be skipped.
batch_logs['data_exhausted'] = True
break
if mode != ModeKeys.PREDICT:
data_batch_size = batch_outs['batch_size']
batch_outs = (batch_outs['total_loss'] + batch_outs['o... | 256 | 256 | 2,371 | 8 | 247 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | Loop | Loop | 184 | 481 | 184 | 184 | 168965a7fcada23243eb59e6e20a6b4fcf320dcb | bigcode/the-stack | train |
7371ddcf8353cb4444a0646e | train | function | def _get_total_number_of_samples(adapter):
if not adapter.get_size() or not adapter.batch_size():
return None
total_sample = adapter.get_size() * adapter.batch_size()
if adapter.has_partial_batch():
total_sample -= (adapter.batch_size() - adapter.partial_batch_size())
return total_sample
| def _get_total_number_of_samples(adapter):
| if not adapter.get_size() or not adapter.batch_size():
return None
total_sample = adapter.get_size() * adapter.batch_size()
if adapter.has_partial_batch():
total_sample -= (adapter.batch_size() - adapter.partial_batch_size())
return total_sample
| not work with
# _standardize_user_data, use the _prepare_model_with_inputs.
if adapter_cls not in _ADAPTER_FOR_STANDARDIZE_USER_DATA:
training_v2_utils._prepare_model_with_inputs(model, adapter.get_dataset())
return adapter
def _get_total_number_of_samples(adapter):
| 64 | 64 | 66 | 9 | 54 | akarmi/tensorflow | tensorflow/python/keras/engine/training_v2.py | Python | _get_total_number_of_samples | _get_total_number_of_samples | 632 | 638 | 632 | 632 | dd838a579f656963e573d08c1837513b79ca92fd | bigcode/the-stack | train |
82d6e2a962f05b41c406a75d | train | function | def interpolator(kind="castelli/kurucz", **kwargs):
logger.debug("Initialising {0} photosphere interpolator"\
.format(kind.upper()))
kind = kind.lower()
if kind == "castelli/kurucz":
return ck_interp(**kwargs)
elif kind == "marcs":
return marcs_interp(**kwargs)
elif kind[:... | def interpolator(kind="castelli/kurucz", **kwargs):
| logger.debug("Initialising {0} photosphere interpolator"\
.format(kind.upper()))
kind = kind.lower()
if kind == "castelli/kurucz":
return ck_interp(**kwargs)
elif kind == "marcs":
return marcs_interp(**kwargs)
elif kind[:9] == "stagger-o":
return stagger_interp("sta... | from .castelli_kurucz import Interpolator as ck_interp
from .marcs import Interpolator as marcs_interp
from .stagger import Interpolator as stagger_interp
from . import utils
logger = logging.getLogger(__name__)
def interpolator(kind="castelli/kurucz", **kwargs):
| 67 | 67 | 225 | 14 | 53 | alexji/smhr-session | smhr_session/photospheres/__init__.py | Python | interpolator | interpolator | 19 | 43 | 19 | 20 | 8922d55e626ea01c3bdda566f3fc7abf63e0bfc5 | bigcode/the-stack | train |
740ae14e9120730c3635c7c9 | train | class | class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
('extras', '0012_webhooks'),
]
operations = [
migrations.CreateModel(
name='ObjectChange',
... | class Migration(migrations.Migration):
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
('extras', '0012_webhooks'),
]
operations = [
migrations.CreateModel(
name='ObjectChange',
fields=[
('id', m... | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-06-22 18:13
from __future__ import unicode_literals
from django.conf import settings
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 76 | 103 | 344 | 7 | 68 | klahox/netbox | netbox/extras/migrations/0013_objectchange.py | Python | Migration | Migration | 11 | 40 | 11 | 12 | 4634c31d15048fce205a82cb3976e99781d8baf8 | bigcode/the-stack | train |
df6bb1915d5f2e035d2fa837 | train | function | def _transform_dss(srcs, mappers, args):
if __debug__:
debug("CMDLINE", "loading to-be-transformed data from %s" % srcs)
dss = [arg2ds(d) for d in srcs]
verbose(1, "Loaded %i to-be-transformed datasets" % len(dss))
if __debug__:
debug("CMDLINE", "transform datasets")
tdss = [mappers[... | def _transform_dss(srcs, mappers, args):
| if __debug__:
debug("CMDLINE", "loading to-be-transformed data from %s" % srcs)
dss = [arg2ds(d) for d in srcs]
verbose(1, "Loaded %i to-be-transformed datasets" % len(dss))
if __debug__:
debug("CMDLINE", "transform datasets")
tdss = [mappers[i].forward(td) for i, td in enumerate(dss... | "help": "Store common space transformation mappers for each training dataset.",
},
}
_supported_parameters = (
"alpha",
"level2_niter",
"ref_ds",
"zscore_all",
"zscore_common",
)
def _transform_dss(srcs, mappers, args):
| 64 | 64 | 121 | 13 | 51 | mortonne/PyMVPA | mvpa2/cmdline/cmd_hyperalign.py | Python | _transform_dss | _transform_dss | 69 | 77 | 69 | 69 | eb184d893f051cbfe1b233ff2ebe3c9cd526089b | bigcode/the-stack | train |
e8de9770fb0069638a9d5369 | train | function | def setup_parser(parser):
# order of calls is relevant!
inputargs = parser.add_argument_group("input data arguments")
parser_add_common_opt(inputargs, "multidata", action="append", required=True)
parser_add_common_opt(
inputargs,
"multidata",
names=("-t", "--transform"),
... | def setup_parser(parser):
# order of calls is relevant!
| inputargs = parser.add_argument_group("input data arguments")
parser_add_common_opt(inputargs, "multidata", action="append", required=True)
parser_add_common_opt(
inputargs,
"multidata",
names=("-t", "--transform"),
dest="transform",
help="""\
Additional datasets for ... | ds(d) for d in srcs]
verbose(1, "Loaded %i to-be-transformed datasets" % len(dss))
if __debug__:
debug("CMDLINE", "transform datasets")
tdss = [mappers[i].forward(td) for i, td in enumerate(dss)]
return tdss, dss
def setup_parser(parser):
# order of calls is relevant!
| 87 | 87 | 292 | 13 | 73 | mortonne/PyMVPA | mvpa2/cmdline/cmd_hyperalign.py | Python | setup_parser | setup_parser | 80 | 111 | 80 | 81 | 68317b05aa548c99271e8cfe3cfbf9ee1a06dde8 | bigcode/the-stack | train |
62c4c2f81a0661a8c0777ff5 | train | function | def run(args):
print(args.data)
dss = [arg2ds(d)[:, :100] for d in args.data]
verbose(1, "Loaded %i input datasets" % len(dss))
if __debug__:
for i, ds in enumerate(dss):
debug("CMDLINE", "dataset %i: %s" % (i, str(ds)))
# TODO at this point more check could be done, e.g. ref_ds ... | def run(args):
| print(args.data)
dss = [arg2ds(d)[:, :100] for d in args.data]
verbose(1, "Loaded %i input datasets" % len(dss))
if __debug__:
for i, ds in enumerate(dss):
debug("CMDLINE", "dataset %i: %s" % (i, str(ds)))
# TODO at this point more check could be done, e.g. ref_ds > len(dss)
... | order of these datasets have to match those of the training dataset arguments
as the correspond mapper will be used to transform each individual dataset.""",
)
algoparms = parser.add_argument_group("algorithm parameters")
for param in _supported_parameters:
param2arg(algoparms, Hyperalignment, param... | 205 | 205 | 684 | 4 | 201 | mortonne/PyMVPA | mvpa2/cmdline/cmd_hyperalign.py | Python | run | run | 114 | 180 | 114 | 114 | a65358ba78b7b584278915bdfaf0474ffe75506f | bigcode/the-stack | train |
0b716b5f8866327bed695990 | train | class | class Plugin(BasePlugin):
def init(self):
self.api.add_event_handler('muc_say', self.advert)
self.api.add_event_handler('conversation_say', self.advert)
self.api.add_event_handler('private_say', self.advert)
def advert(self, msg, tab):
msg['body'] = "%s\n\n%s" % (msg['body'],
... | class Plugin(BasePlugin):
| def init(self):
self.api.add_event_handler('muc_say', self.advert)
self.api.add_event_handler('conversation_say', self.advert)
self.api.add_event_handler('private_say', self.advert)
def advert(self, msg, tab):
msg['body'] = "%s\n\n%s" % (msg['body'],
... | """
Add a subtle little advertising in your messages.
Configuration
-------------
.. code-block:: ini
[spam]
ad = I’m a happy poezio user. Get it at http://poezio.eu
"""
from poezio.plugin import BasePlugin
class Plugin(BasePlugin):
| 61 | 64 | 97 | 5 | 55 | hrnciar/poezio | plugins/spam.py | Python | Plugin | Plugin | 17 | 25 | 17 | 17 | eedb820dd4bb829baed0e02721e11707a26b7412 | bigcode/the-stack | train |
542e7df9e626874531e78a11 | train | class | class Log10(Instruccion):
def __init__(self, valor, tipo, linea, columna):
Instruccion.__init__(self,tipo,linea,columna)
self.valor = valor
def ejecutar(self, tabla, arbol):
super().ejecutar(tabla,arbol)
print("LOG_10")
print(math.log10(self.valor))
return math.l... | class Log10(Instruccion):
| def __init__(self, valor, tipo, linea, columna):
Instruccion.__init__(self,tipo,linea,columna)
self.valor = valor
def ejecutar(self, tabla, arbol):
super().ejecutar(tabla,arbol)
print("LOG_10")
print(math.log10(self.valor))
return math.log10(self.valor)
|
import math
from Instrucciones.TablaSimbolos.Instruccion import Instruccion
class Log10(Instruccion):
| 28 | 64 | 88 | 7 | 20 | strickergt128/tytus | parser/team08/Tytus_SQLPARSER_G8/Instrucciones/FunctionMathematical/Log10.py | Python | Log10 | Log10 | 5 | 14 | 5 | 5 | 085c345a6606115bfeed2f28cd1481f001cb2470 | bigcode/the-stack | train |
64b9c3aa7387e9942a07f4bf | train | class | class InputNotifyBroadcasts(TLObject): # type: ignore
"""This object is a constructor of the base type :obj:`~pyrogram.raw.base.InputNotifyPeer`.
Details:
- Layer: ``117``
- ID: ``0xb1db7c7e``
**No parameters required.**
"""
__slots__: List[str] = []
ID = 0xb1db7c7e
QUAL... | class InputNotifyBroadcasts(TLObject): # type: ignore
| """This object is a constructor of the base type :obj:`~pyrogram.raw.base.InputNotifyPeer`.
Details:
- Layer: ``117``
- ID: ``0xb1db7c7e``
**No parameters required.**
"""
__slots__: List[str] = []
ID = 0xb1db7c7e
QUALNAME = "types.InputNotifyBroadcasts"
def __init__(... | !!! #
# This is a generated file! #
# All changes made in this file will be lost! #
# # # # # # # # # # # # # # # # # # # # # # # #
class InputNotifyBroadcasts(TLObject): # type: ignore
| 63 | 64 | 188 | 14 | 49 | iamgeorgiy/heroku-userbot | venv/Lib/site-packages/pyrogram/raw/types/input_notify_broadcasts.py | Python | InputNotifyBroadcasts | InputNotifyBroadcasts | 33 | 63 | 33 | 33 | 2319417e4694b7238d6f1edb4d4d4575edf5393e | bigcode/the-stack | train |
a02beeb74b7bc6bca2149483 | train | class | class AverageGradients:
"""Callable that averages the gradients in a batch.
This should be used with the .for_each() operator after a set of gradients
have been batched with .batch().
Examples:
>>> batched_grads = grads_op.batch(32)
>>> avg_grads = batched_grads.for_each(AverageGradien... | class AverageGradients:
| """Callable that averages the gradients in a batch.
This should be used with the .for_each() operator after a set of gradients
have been batched with .batch().
Examples:
>>> batched_grads = grads_op.batch(32)
>>> avg_grads = batched_grads.for_each(AverageGradients())
>>> print(... | current_actor` must be set "
"in the iterator context."
)
with metrics.timers[WORKER_UPDATE_TIMER]:
weights = self.local_worker.get_weights(
self.policies or self.local_worker.get_policies_to_train()
)
me... | 71 | 71 | 237 | 5 | 66 | dsctt/ray | rllib/execution/train_ops.py | Python | AverageGradients | AverageGradients | 481 | 509 | 481 | 481 | 0c7375c0a13f894e7984263d124b357d626032f3 | bigcode/the-stack | train |
800d4c1cefa2dd93573215b6 | train | class | class UpdateTargetNetwork:
"""Periodically call policy.update_target() on all trainable policies.
This should be used with the .for_each() operator after training step
has been taken.
Examples:
>>> train_op = ParallelRollouts(...).for_each(TrainOneStep(...))
>>> update_op = train_op.fo... | class UpdateTargetNetwork:
| """Periodically call policy.update_target() on all trainable policies.
This should be used with the .for_each() operator after training step
has been taken.
Examples:
>>> train_op = ParallelRollouts(...).for_each(TrainOneStep(...))
>>> update_op = train_op.for_each(
... Upd... | ]]
) -> Tuple[ModelGradients, int]:
acc = None
sum_count = 0
for grad, count in gradients:
if acc is None:
acc = grad
else:
acc = [a + b for a, b in zip(acc, grad)]
sum_count += count
logger.info(
"Comput... | 115 | 115 | 385 | 5 | 109 | dsctt/ray | rllib/execution/train_ops.py | Python | UpdateTargetNetwork | UpdateTargetNetwork | 512 | 556 | 512 | 512 | 8665bed844bcf5774994b9618f4bbd6d7ae3c30e | bigcode/the-stack | train |
f8cbaaf9c476cf03812e2350 | train | class | class ApplyGradients:
"""Callable that applies gradients and updates workers.
This should be used with the .for_each() operator.
Examples:
>>> apply_op = grads_op.for_each(ApplyGradients(workers))
>>> print(next(apply_op))
None
Updates the STEPS_TRAINED_COUNTER counter in the ... | class ApplyGradients:
| """Callable that applies gradients and updates workers.
This should be used with the .for_each() operator.
Examples:
>>> apply_op = grads_op.for_each(ApplyGradients(workers))
>>> print(next(apply_op))
None
Updates the STEPS_TRAINED_COUNTER counter in the local iterator context... | ..., ...}, 50 # grads, batch count
Updates the LEARNER_INFO info field in the local iterator context.
"""
def __init__(self, workers: WorkerSet):
self.workers = workers
def __call__(self, samples: SampleBatchType) -> Tuple[ModelGradients, int]:
_check_sample_batch_type(samples)
... | 165 | 165 | 551 | 5 | 159 | dsctt/ray | rllib/execution/train_ops.py | Python | ApplyGradients | ApplyGradients | 410 | 478 | 410 | 410 | 03786258a39b5e3f6de0876213569ced7a65b60a | bigcode/the-stack | train |
513fa459e7311b53173839ac | train | class | class MultiGPUTrainOneStep:
"""Multi-GPU version of TrainOneStep.
This should be used with the .for_each() operator. A tuple of the input
and learner stats will be returned.
Examples:
>>> rollouts = ParallelRollouts(...)
>>> train_op = rollouts.for_each(MultiGPUTrainOneStep(workers, ..... | class MultiGPUTrainOneStep:
| """Multi-GPU version of TrainOneStep.
This should be used with the .for_each() operator. A tuple of the input
and learner stats will be returned.
Examples:
>>> rollouts = ParallelRollouts(...)
>>> train_op = rollouts.for_each(MultiGPUTrainOneStep(workers, ...))
>>> print(next(t... | olicies_to_train(batch)
},
lw,
self.num_sgd_iter,
self.sgd_minibatch_size,
[],
)
# Single update step using train batch.
else:
learner_info = lw.learn_on_batch(batc... | 256 | 256 | 1,195 | 7 | 248 | dsctt/ray | rllib/execution/train_ops.py | Python | MultiGPUTrainOneStep | MultiGPUTrainOneStep | 237 | 375 | 237 | 237 | b4395eee40f540cd0cb4967a0db6218856dee5bb | bigcode/the-stack | train |
f69ee3055f81e441bceec557 | train | function | @ExperimentalAPI
def train_one_step(trainer, train_batch) -> Dict:
config = trainer.config
workers = trainer.workers
local_worker = workers.local_worker()
num_sgd_iter = config.get("num_sgd_iter", 1)
sgd_minibatch_size = config.get("sgd_minibatch_size", 0)
learn_timer = trainer._timers[LEARN_ON... | @ExperimentalAPI
def train_one_step(trainer, train_batch) -> Dict:
| config = trainer.config
workers = trainer.workers
local_worker = workers.local_worker()
num_sgd_iter = config.get("num_sgd_iter", 1)
sgd_minibatch_size = config.get("sgd_minibatch_size", 0)
learn_timer = trainer._timers[LEARN_ON_BATCH_TIMER]
with learn_timer:
# Subsample minibatches... | .metrics.learner_info import LearnerInfoBuilder, LEARNER_INFO
from ray.rllib.utils.sgd import do_minibatch_sgd
from ray.rllib.utils.typing import PolicyID, SampleBatchType, ModelGradients
tf1, tf, tfv = try_import_tf()
logger = logging.getLogger(__name__)
@ExperimentalAPI
def train_one_step(trainer, train_batch) -> D... | 87 | 87 | 291 | 17 | 70 | dsctt/ray | rllib/execution/train_ops.py | Python | train_one_step | train_one_step | 38 | 70 | 38 | 39 | d5ac23a5f19ad2bc503ed57099f22b74147e8a49 | bigcode/the-stack | train |
e4682bfa96059a7a7681976e | train | class | class TrainOneStep:
"""Callable that improves the policy and updates workers.
This should be used with the .for_each() operator. A tuple of the input
and learner stats will be returned.
Examples:
>>> rollouts = ParallelRollouts(...)
>>> train_op = rollouts.for_each(TrainOneStep(workers... | class TrainOneStep:
| """Callable that improves the policy and updates workers.
This should be used with the .for_each() operator. A tuple of the input
and learner stats will be returned.
Examples:
>>> rollouts = ParallelRollouts(...)
>>> train_op = rollouts.for_each(TrainOneStep(workers))
>>> print... | _size, buffer_index=0
)
learner_info_builder.add_learn_on_batch_results(results, policy_id)
# Tower reduce and finalize results.
learner_info = learner_info_builder.finalize()
load_timer.push_units_processed(train_batch.count)
learn_timer.push_units_pro... | 191 | 191 | 638 | 5 | 185 | dsctt/ray | rllib/execution/train_ops.py | Python | TrainOneStep | TrainOneStep | 164 | 234 | 164 | 164 | 1ec606bcf8d14cefa65f0ce548f6d6dfd671d6c2 | bigcode/the-stack | train |
ddbac1f9f59fbbb284b504d3 | train | function | @ExperimentalAPI
def multi_gpu_train_one_step(trainer, train_batch) -> Dict:
config = trainer.config
workers = trainer.workers
local_worker = workers.local_worker()
num_sgd_iter = config.get("sgd_num_iter", 1)
sgd_minibatch_size = config.get("sgd_minibatch_size", config["train_batch_size"])
# D... | @ExperimentalAPI
def multi_gpu_train_one_step(trainer, train_batch) -> Dict:
| config = trainer.config
workers = trainer.workers
local_worker = workers.local_worker()
num_sgd_iter = config.get("sgd_num_iter", 1)
sgd_minibatch_size = config.get("sgd_minibatch_size", config["train_batch_size"])
# Determine the number of devices (GPUs or 1 CPU) we use.
num_devices = int(... | .get("sgd_minibatch_size", 0)
learn_timer = trainer._timers[LEARN_ON_BATCH_TIMER]
with learn_timer:
# Subsample minibatches (size=`sgd_minibatch_size`) from the
# train batch and loop through train batch `num_sgd_iter` times.
if num_sgd_iter > 1 or sgd_minibatch_size > 0:
in... | 246 | 246 | 821 | 19 | 226 | dsctt/ray | rllib/execution/train_ops.py | Python | multi_gpu_train_one_step | multi_gpu_train_one_step | 73 | 161 | 73 | 74 | f36d9863ae7ada52b914bad980ea3a1c0b8ef8ec | bigcode/the-stack | train |
ebc11c56ae53c4bf9c93e47c | train | class | class ComputeGradients:
"""Callable that computes gradients with respect to the policy loss.
This should be used with the .for_each() operator.
Examples:
>>> grads_op = rollouts.for_each(ComputeGradients(workers))
>>> print(next(grads_op))
{"var_0": ..., ...}, 50 # grads, batch co... | class ComputeGradients:
| """Callable that computes gradients with respect to the policy loss.
This should be used with the .for_each() operator.
Examples:
>>> grads_op = rollouts.for_each(ComputeGradients(workers))
>>> print(next(grads_op))
{"var_0": ..., ...}, 50 # grads, batch count
Updates the LEA... | ():
e.set_weights.remote(weights, _get_global_vars())
# Also update global vars of the local worker.
self.workers.local_worker().set_global_vars(_get_global_vars())
return samples, learner_info
# Backward compatibility.
TrainTFMultiGPU = MultiGPUTrainOneStep
class ComputeG... | 67 | 67 | 224 | 5 | 61 | dsctt/ray | rllib/execution/train_ops.py | Python | ComputeGradients | ComputeGradients | 382 | 407 | 382 | 382 | d484a4092fe3d3876f1937173da07b6072f9dd48 | bigcode/the-stack | train |
5cfa1e5d03577b48ee8e344d | train | class | class Encoder_MultipleLayers(nn.Module):
def __init__(self, n_layer, hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Encoder_MultipleLayers, self).__init__()
layer = Encoder(hidden_size, intermediate_size, num_attention_heads, attention_... | class Encoder_MultipleLayers(nn.Module):
| def __init__(self, n_layer, hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Encoder_MultipleLayers, self).__init__()
layer = Encoder(hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob)
... | _dropout_prob)
def forward(self, hidden_states, attention_mask):
attention_output = self.attention(hidden_states, attention_mask)
intermediate_output = self.intermediate(attention_output)
layer_output = self.output(intermediate_output, attention_output)
return layer_output
class Enc... | 64 | 64 | 140 | 8 | 55 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Encoder_MultipleLayers | Encoder_MultipleLayers | 169 | 179 | 169 | 169 | 512542ec14c4245b0dddb3912eae7168eafc8789 | bigcode/the-stack | train |
2227243d66b3f06166e03bb7 | train | class | class Intermediate(nn.Module):
def __init__(self, hidden_size, intermediate_size):
super(Intermediate, self).__init__()
self.dense = nn.Linear(hidden_size, intermediate_size)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = F.relu(hidde... | class Intermediate(nn.Module):
| def __init__(self, hidden_size, intermediate_size):
super(Intermediate, self).__init__()
self.dense = nn.Linear(hidden_size, intermediate_size)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = F.relu(hidden_states)
return hidden... | , attention_probs_dropout_prob)
self.output = SelfOutput(hidden_size, hidden_dropout_prob)
def forward(self, input_tensor, attention_mask):
self_output = self.self(input_tensor, attention_mask)
attention_output = self.output(self_output, input_tensor)
return attention_output
class I... | 64 | 64 | 72 | 5 | 58 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Intermediate | Intermediate | 133 | 141 | 133 | 133 | 7f2e576bfd58362a8a45d7f7afe6235de9e7a7a6 | bigcode/the-stack | train |
a746280c2a1283cccdf67289 | train | class | class LayerNorm(nn.Module):
def __init__(self, hidden_size, variance_epsilon=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = variance_epsilon
def forward(self... | class LayerNorm(nn.Module):
| def __init__(self, hidden_size, variance_epsilon=1e-12):
super(LayerNorm, self).__init__()
self.gamma = nn.Parameter(torch.ones(hidden_size))
self.beta = nn.Parameter(torch.zeros(hidden_size))
self.variance_epsilon = variance_epsilon
def forward(self, x):
u = x.mean(-1,... | Hui Yang, Jiancong Xie
Code based on:
"""
import copy
import math
import collections
import numpy as np
import torch
from torch import nn
import torch.utils.data as Data
import torch.nn.functional as F
from torch.autograd import Variable
class LayerNorm(nn.Module):
| 64 | 64 | 136 | 6 | 57 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | LayerNorm | LayerNorm | 21 | 33 | 21 | 21 | 935481e78502dcfec373833b94b20bc1726a9773 | bigcode/the-stack | train |
bbdf102644271f344154d45c | train | class | class SelfOutput(nn.Module):
def __init__(self, hidden_size, hidden_dropout_prob):
super(SelfOutput, self).__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_prob)
def forward(self, hidden_... | class SelfOutput(nn.Module):
| def __init__(self, hidden_size, hidden_dropout_prob):
super(SelfOutput, self).__init__()
self.dense = nn.Linear(hidden_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
... | = context_layer.permute(0, 2, 1, 3).contiguous()
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
context_layer = context_layer.view(*new_context_layer_shape)
return context_layer
class SelfOutput(nn.Module):
| 64 | 64 | 111 | 6 | 57 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | SelfOutput | SelfOutput | 109 | 120 | 109 | 109 | 52d9163f218dde28023a0200bb995ad2f48a129a | bigcode/the-stack | train |
680710c479469ba4b8acb2c6 | train | class | class Encoder(nn.Module):
def __init__(self, hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Encoder, self).__init__()
self.attention = Attention(hidden_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob)
... | class Encoder(nn.Module):
| def __init__(self, hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Encoder, self).__init__()
self.attention = Attention(hidden_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob)
self.intermediate = Inte... | self.dropout = nn.Dropout(hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class Encode... | 64 | 64 | 143 | 5 | 58 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Encoder | Encoder | 156 | 167 | 156 | 156 | 613e61b97fad919e1b451fe0b99901b40623e1b2 | bigcode/the-stack | train |
bb37c2211a684763000eb6fd | train | class | class Attention(nn.Module):
def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Attention, self).__init__()
self.self = SelfAttention(hidden_size, num_attention_heads, attention_probs_dropout_prob)
self.output = SelfOutput(hidden_siz... | class Attention(nn.Module):
| def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Attention, self).__init__()
self.self = SelfAttention(hidden_size, num_attention_heads, attention_probs_dropout_prob)
self.output = SelfOutput(hidden_size, hidden_dropout_prob)
... | self.dropout = nn.Dropout(hidden_dropout_prob)
def forward(self, hidden_states, input_tensor):
hidden_states = self.dense(hidden_states)
hidden_states = self.dropout(hidden_states)
hidden_states = self.LayerNorm(hidden_states + input_tensor)
return hidden_states
class Attent... | 64 | 64 | 108 | 5 | 58 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Attention | Attention | 122 | 131 | 122 | 122 | c350863a53d7918e280bc9a746b3e68e0239bbfe | bigcode/the-stack | train |
f98d912f2fac75158f7102ee | train | class | class Output(nn.Module):
def __init__(self, intermediate_size, hidden_size, hidden_dropout_prob):
super(Output, self).__init__()
self.dense = nn.Linear(intermediate_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_prob)
def forw... | class Output(nn.Module):
| def __init__(self, intermediate_size, hidden_size, hidden_dropout_prob):
super(Output, self).__init__()
self.dense = nn.Linear(intermediate_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(hidden_dropout_prob)
def forward(self, hidden_states, ... | _size, intermediate_size):
super(Intermediate, self).__init__()
self.dense = nn.Linear(hidden_size, intermediate_size)
def forward(self, hidden_states):
hidden_states = self.dense(hidden_states)
hidden_states = F.relu(hidden_states)
return hidden_states
class Output(nn.Modul... | 64 | 64 | 113 | 5 | 58 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Output | Output | 143 | 154 | 143 | 143 | 4708afdfaa9c733929bff426a2e2257d47314e5c | bigcode/the-stack | train |
218ecdc985ff21a6414ab084 | train | class | class SelfAttention(nn.Module):
def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob):
super(SelfAttention, self).__init__()
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of ... | class SelfAttention(nn.Module):
| def __init__(self, hidden_size, num_attention_heads, attention_probs_dropout_prob):
super(SelfAttention, self).__init__()
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention "
"hea... | = nn.Embedding(vocab_size, hidden_size)
self.position_embeddings = nn.Embedding(max_position_size, hidden_size)
self.LayerNorm = LayerNorm(hidden_size)
self.dropout = nn.Dropout(dropout_rate)
def forward(self, input_ids):
seq_length = input_ids.size(1)
position_ids = torch... | 157 | 157 | 525 | 6 | 150 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | SelfAttention | SelfAttention | 59 | 107 | 59 | 59 | 90b55f6af8f6509d4bf8338e7f824cac302e4049 | bigcode/the-stack | train |
738699c4031fc17e969d855f | train | class | class Transformer(nn.Sequential):
def __init__(self, dim_features, dim_targets, model_configs, dataset_configs):
super(Transformer, self).__init__()
self.dim_features = dim_features
self.dim_targets = dim_targets
self.task_type = dataset_configs["task_type"]
self.multiclass... | class Transformer(nn.Sequential):
| def __init__(self, dim_features, dim_targets, model_configs, dataset_configs):
super(Transformer, self).__init__()
self.dim_features = dim_features
self.dim_targets = dim_targets
self.task_type = dataset_configs["task_type"]
self.multiclass_num_classes = dataset_configs["mu... | _output = self.output(intermediate_output, attention_output)
return layer_output
class Encoder_MultipleLayers(nn.Module):
def __init__(self, n_layer, hidden_size, intermediate_size, num_attention_heads, attention_probs_dropout_prob, hidden_dropout_prob):
super(Encoder_MultipleLayers, self).__init__... | 161 | 161 | 538 | 5 | 155 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Transformer | Transformer | 181 | 239 | 181 | 181 | 49f22ae6d6a2d1023840c755198c7965e4da2317 | bigcode/the-stack | train |
b46ab42bd507ffc12749f9df | train | class | class Embeddings(nn.Module):
"""Construct the embeddings from protein/target, position embeddings.
"""
def __init__(self, vocab_size, hidden_size, max_position_size, dropout_rate):
super(Embeddings, self).__init__()
self.word_embeddings = nn.Embedding(vocab_size, hidden_size)
self.po... | class Embeddings(nn.Module):
| """Construct the embeddings from protein/target, position embeddings.
"""
def __init__(self, vocab_size, hidden_size, max_position_size, dropout_rate):
super(Embeddings, self).__init__()
self.word_embeddings = nn.Embedding(vocab_size, hidden_size)
self.position_embeddings = nn.Embedd... | x.mean(-1, keepdim=True)
s = (x - u).pow(2).mean(-1, keepdim=True)
x = (x - u) / torch.sqrt(s + self.variance_epsilon)
return self.gamma * x + self.beta
class Embeddings(nn.Module):
| 64 | 64 | 206 | 6 | 57 | Jh-SYSU/MolRep | MolRep/Models/sequence_based/Transformer.py | Python | Embeddings | Embeddings | 35 | 57 | 35 | 35 | 102f321754858d880eef808413d9e21ad432fed3 | bigcode/the-stack | train |
845b0d5dc1790388e6f215e8 | train | function | def read_line(line):
"""Read a single string LINE as a Scheme expression."""
return scheme_read(Buffer(tokenize_lines([line])))
| def read_line(line):
| """Read a single string LINE as a Scheme expression."""
return scheme_read(Buffer(tokenize_lines([line])))
| buffer_lines(lines, prompt='scm> ', show_prompt=False):
"""Return a Buffer instance iterating through LINES."""
if show_prompt:
input_lines = lines
else:
input_lines = LineReader(lines, prompt)
return Buffer(tokenize_lines(input_lines))
def read_line(line):
| 64 | 64 | 28 | 5 | 59 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | read_line | read_line | 178 | 180 | 178 | 178 | 6e4bf01770f71e2a52f52a228d30a339e4694993 | bigcode/the-stack | train |
10a8d47b808caf7677dabb2f | train | function | def buffer_input(prompt='scm> '):
"""Return a Buffer instance containing interactive input."""
return Buffer(tokenize_lines(InputReader(prompt)))
| def buffer_input(prompt='scm> '):
| """Return a Buffer instance containing interactive input."""
return Buffer(tokenize_lines(InputReader(prompt)))
|
# of the outer expression and return a pair as the result
return Pair(scheme_read(src), read_tail(src))
# END PROBLEM 1
except EOFError:
raise SyntaxError('unexpected end of file')
# Convenience methods
def buffer_input(prompt='scm> '):
| 64 | 64 | 30 | 10 | 53 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | buffer_input | buffer_input | 166 | 168 | 166 | 166 | ac1ea3f9faabf74b8260b7e483350a9ddc98ce95 | bigcode/the-stack | train |
886f283b16a4c38f853f07bc | train | function | def read_tail(src):
"""Return the remainder of a list in SRC, starting before an element or ).
>>> read_tail(Buffer(tokenize_lines([')'])))
nil
>>> read_tail(Buffer(tokenize_lines(['2 3)'])))
Pair(2, Pair(3, nil))
>>> read_line('(1 . 2)')
Pair(1, 2)
"""
try:
if src.current()... | def read_tail(src):
| """Return the remainder of a list in SRC, starting before an element or ).
>>> read_tail(Buffer(tokenize_lines([')'])))
nil
>>> read_tail(Buffer(tokenize_lines(['2 3)'])))
Pair(2, Pair(3, nil))
>>> read_line('(1 . 2)')
Pair(1, 2)
"""
try:
if src.current() is None:
... | 1
return read_tail(src) # going into the parenthesis forest
# END PROBLEM 1
elif val == "'":
# BEGIN PROBLEM 7
return Pair('quote', Pair(scheme_read(src), nil))
# END PROBLEM 7
elif val not in DELIMITERS:
return val
else:
raise SyntaxError('unexpected ... | 95 | 95 | 318 | 5 | 90 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | read_tail | read_tail | 128 | 162 | 128 | 128 | 81bfadec111ba1e7a5d04e3278ea15a385aa8447 | bigcode/the-stack | train |
bb75879941e163590be0b346 | train | function | def scheme_read(src):
"""Read the next expression from SRC, a Buffer of tokens.
>>> scheme_read(Buffer(tokenize_lines(['nil'])))
nil
>>> scheme_read(Buffer(tokenize_lines(['1'])))
1
>>> scheme_read(Buffer(tokenize_lines(['true'])))
True
>>> scheme_read(Buffer(tokenize_lines(['(+ 1 2)'])... | def scheme_read(src):
| """Read the next expression from SRC, a Buffer of tokens.
>>> scheme_read(Buffer(tokenize_lines(['nil'])))
nil
>>> scheme_read(Buffer(tokenize_lines(['1'])))
1
>>> scheme_read(Buffer(tokenize_lines(['true'])))
True
>>> scheme_read(Buffer(tokenize_lines(['(+ 1 2)'])))
Pair('+', Pair(... | """
def __repr__(self):
return 'nil'
def __str__(self):
return '()'
def __len__(self):
return 0
def map(self, fn):
return self
nil = nil() # Assignment hides the nil class; there is only one instance
# Scheme list parser
def scheme_read(src):
| 75 | 75 | 253 | 5 | 69 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | scheme_read | scheme_read | 96 | 126 | 96 | 96 | 875f27e7e4755db85b85ad80a10d058c497e89c0 | bigcode/the-stack | train |
5a38d630986ba3512230670b | train | class | class Pair:
"""A pair has two instance attributes: first and second. For a Pair to be
a well-formed list, second is either a well-formed list or nil. Some
methods only apply to well-formed lists.
>>> s = Pair(1, Pair(2, nil))
>>> s
Pair(1, Pair(2, nil))
>>> print(s)
(1 2)
>>> prin... | class Pair:
| """A pair has two instance attributes: first and second. For a Pair to be
a well-formed list, second is either a well-formed list or nil. Some
methods only apply to well-formed lists.
>>> s = Pair(1, Pair(2, nil))
>>> s
Pair(1, Pair(2, nil))
>>> print(s)
(1 2)
>>> print(s.map(lamb... | int or float
symbol: string
boolean: bool
unspecified: None
The __repr__ method of a Scheme value will return a Python expression that
would be evaluated to the value, where possible.
The __str__ method of a Scheme value will return a Scheme expression that
would be read to the value, w... | 118 | 118 | 394 | 3 | 114 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | Pair | Pair | 24 | 74 | 24 | 24 | e1c602e8180d0e2dfbbc8dff931144e891b09d45 | bigcode/the-stack | train |
5ac9535421db71883528aa6d | train | class | class nil:
"""The empty list"""
def __repr__(self):
return 'nil'
def __str__(self):
return '()'
def __len__(self):
return 0
def map(self, fn):
return self
| class nil:
| """The empty list"""
def __repr__(self):
return 'nil'
def __str__(self):
return '()'
def __len__(self):
return 0
def map(self, fn):
return self
| (self, fn):
"""Return a Scheme list after mapping Python function FN to SELF."""
mapped = fn(self.first)
if self.second is nil or isinstance(self.second, Pair):
return Pair(mapped, self.second.map(fn))
else:
raise TypeError('ill-formed list')
class nil:
| 64 | 64 | 56 | 3 | 61 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | nil | nil | 76 | 89 | 76 | 76 | 9911f30243bec4cdb0cae8a6e3c60236e82da2f2 | bigcode/the-stack | train |
aa3de1a8bae96f3f300be8de | train | function | def buffer_lines(lines, prompt='scm> ', show_prompt=False):
"""Return a Buffer instance iterating through LINES."""
if show_prompt:
input_lines = lines
else:
input_lines = LineReader(lines, prompt)
return Buffer(tokenize_lines(input_lines))
| def buffer_lines(lines, prompt='scm> ', show_prompt=False):
| """Return a Buffer instance iterating through LINES."""
if show_prompt:
input_lines = lines
else:
input_lines = LineReader(lines, prompt)
return Buffer(tokenize_lines(input_lines))
| except EOFError:
raise SyntaxError('unexpected end of file')
# Convenience methods
def buffer_input(prompt='scm> '):
"""Return a Buffer instance containing interactive input."""
return Buffer(tokenize_lines(InputReader(prompt)))
def buffer_lines(lines, prompt='scm> ', show_prompt=False):
| 64 | 64 | 60 | 15 | 49 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | buffer_lines | buffer_lines | 170 | 176 | 170 | 170 | 710194aa91ecde84aaf2b5df91ffdedab4cd01fd | bigcode/the-stack | train |
5653e993dcda7f6f883d18f2 | train | function | def repl_str(val):
"""Should largely match str(val), except for booleans and undefined."""
if val is True:
return "#t"
if val is False:
return "#f"
if val is None:
return "undefined"
return str(val)
| def repl_str(val):
| """Should largely match str(val), except for booleans and undefined."""
if val is True:
return "#t"
if val is False:
return "#f"
if val is None:
return "undefined"
return str(val)
| _prompt:
input_lines = lines
else:
input_lines = LineReader(lines, prompt)
return Buffer(tokenize_lines(input_lines))
def read_line(line):
"""Read a single string LINE as a Scheme expression."""
return scheme_read(Buffer(tokenize_lines([line])))
def repl_str(val):
| 63 | 64 | 59 | 5 | 58 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | repl_str | repl_str | 182 | 190 | 182 | 182 | f83cbeba1c3d483c890e6fd30d335b1e5164cc98 | bigcode/the-stack | train |
b9d1799c4a6ddfe4ed6a515e | train | function | @main
def read_print_loop():
"""Run a read-print loop for Scheme expressions."""
while True:
try:
src = buffer_input('read> ')
while src.more_on_line:
expression = scheme_read(src)
print('str :', expression)
print('repr:', repr(expr... | @main
def read_print_loop():
| """Run a read-print loop for Scheme expressions."""
while True:
try:
src = buffer_input('read> ')
while src.more_on_line:
expression = scheme_read(src)
print('str :', expression)
print('repr:', repr(expression))
except (Synt... | Should largely match str(val), except for booleans and undefined."""
if val is True:
return "#t"
if val is False:
return "#f"
if val is None:
return "undefined"
return str(val)
# Interactive loop
@main
def read_print_loop():
| 64 | 64 | 112 | 8 | 55 | tejashah88/cs61a-self-study | projects/scheme/scheme_reader.py | Python | read_print_loop | read_print_loop | 194 | 208 | 194 | 195 | f0d39139fd07060aa44cc13b1f02c0e3b6788317 | bigcode/the-stack | train |
22851b0678fca74a13ffe373 | train | class | class FileBodyWrapper(ResponseHandler, DownloadHandler):
def __init__(self):
"""Creates an instance of FileBodyWrapper"""
super().__init__()
self.__file = None
self.__key_modified = dict()
def get_file(self):
"""
The method to get the file
Returns:
StreamWrapper: An instance of StreamWrapper
"""... | class FileBodyWrapper(ResponseHandler, DownloadHandler):
| def __init__(self):
"""Creates an instance of FileBodyWrapper"""
super().__init__()
self.__file = None
self.__key_modified = dict()
def get_file(self):
"""
The method to get the file
Returns:
StreamWrapper: An instance of StreamWrapper
"""
return self.__file
def set_file(self, file):
"""
... | try:
from zcrmsdk.src.com.zoho.crm.api.exception import SDKException
from zcrmsdk.src.com.zoho.crm.api.util import StreamWrapper, Constants
from zcrmsdk.src.com.zoho.crm.api.record.response_handler import ResponseHandler
from zcrmsdk.src.com.zoho.crm.api.record.download_handler import DownloadHandler
except Excepti... | 121 | 132 | 443 | 10 | 110 | zoho/zohocrm-python-sdk-2.0 | zcrmsdk/src/com/zoho/crm/api/record/file_body_wrapper.py | Python | FileBodyWrapper | FileBodyWrapper | 13 | 79 | 13 | 13 | b32655a4702b1e4727db316517da8b436e8a676f | bigcode/the-stack | train |
0872d4c6fa0503c425e49476 | train | function | def generate_canonical_identifier(platform, obj_type, id):
return f"{platform}:{obj_type}:{id}"
| def generate_canonical_identifier(platform, obj_type, id):
| return f"{platform}:{obj_type}:{id}"
| """
Created: 17 June 2020
"""
# -----------------------------------------------------------------------------
def generate_canonical_identifier(platform, obj_type, id):
| 26 | 64 | 23 | 12 | 14 | Revibe-Music/core-services | utils/branch/utils.py | Python | generate_canonical_identifier | generate_canonical_identifier | 7 | 8 | 7 | 7 | d0840362bfc6a0bea31f2134b1027fc12723ba1f | bigcode/the-stack | train |
64609f0433932833b0b2bb31 | train | class | class ErrorTests(unittest.TestCase):
def test_init_no_id(self):
error = Error(error="This is a error", file='afile', start='300', end='500')
self.assertIsNotNone(error)
self.assertIsNone(error.id)
self.assertEqual('This is a error', error.error)
self.assertEqual('afile', er... | class ErrorTests(unittest.TestCase):
| def test_init_no_id(self):
error = Error(error="This is a error", file='afile', start='300', end='500')
self.assertIsNotNone(error)
self.assertIsNone(error.id)
self.assertEqual('This is a error', error.error)
self.assertEqual('afile', error.file)
self.assertEqual('30... | is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF... | 151 | 151 | 506 | 7 | 143 | cotobadesign/cotoba-agent-oss | dialogue-engine/test/programytest/storage/stores/nosql/mongo/dao/test_error.py | Python | ErrorTests | ErrorTests | 21 | 63 | 21 | 22 | 95103262772c39a251e06cd1c6b69087cba6061f | bigcode/the-stack | train |
c7848ba2622df944884eabb9 | train | function | def resource_config_is_unchanged_including_network(original_config, new_config):
except_tags = ['id', 'creationTimestamp', 'fingerprint', 'networkIP',
'natIP', 'IPAddress']
return resource_config_is_unchanged_except_for_tags(original_config,
... | def resource_config_is_unchanged_including_network(original_config, new_config):
| except_tags = ['id', 'creationTimestamp', 'fingerprint', 'networkIP',
'natIP', 'IPAddress']
return resource_config_is_unchanged_except_for_tags(original_config,
new_config, except_tags)
| 'creationTimestamp', 'fingerprint', 'network',
'subnetwork', 'networkIP', 'natIP', 'IPAddress']
return resource_config_is_unchanged_except_for_tags(original_config,
new_config, except_tags)
def resource_config_is_unchanged_including_network... | 64 | 64 | 64 | 16 | 48 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | resource_config_is_unchanged_including_network | resource_config_is_unchanged_including_network | 53 | 57 | 53 | 53 | c6b6f2c3c496dd58d9203b651ecc77ef4c66df86 | bigcode/the-stack | train |
81b1c1f4dcdcc42b473ffb8f | train | function | def check_instance_network(instance_config, network_selfLink,
subnetwork_selfLink=None):
if instance_config['networkInterfaces'][0]['network'] != network_selfLink:
return False
if subnetwork_selfLink != None and instance_config['networkInterfaces'][0][
'subnetwork'] !=... | def check_instance_network(instance_config, network_selfLink,
subnetwork_selfLink=None):
| if instance_config['networkInterfaces'][0]['network'] != network_selfLink:
return False
if subnetwork_selfLink != None and instance_config['networkInterfaces'][0][
'subnetwork'] != subnetwork_selfLink:
return False
return True
| return False
if subnetwork_selfLink != None and \
instance_template_config['properties']['networkInterfaces'][
0]['subnetwork'] != subnetwork_selfLink:
return False
return True
def check_instance_network(instance_config, network_selfLink,
su... | 64 | 64 | 76 | 18 | 45 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | check_instance_network | check_instance_network | 125 | 132 | 125 | 126 | f1aae99fb2454d07eddbed6261274c4fbc977a83 | bigcode/the-stack | train |
9e3d7134fc5c123851ad7a38 | train | function | def instance_template_config_is_unchanged_except_for_network_and_name(
original_config, new_config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'name', 'network',
'subnetwork', 'selfLink'])
| def instance_template_config_is_unchanged_except_for_network_and_name(
original_config, new_config):
| return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'name', 'network',
'subnetwork', 'selfLink'])
| id', 'creationTimestamp', 'fingerprint', 'networkIP',
'natIP', 'IPAddress']
return resource_config_is_unchanged_except_for_tags(original_config,
new_config, except_tags)
def instance_template_config_is_unchanged_except_for_network_and_name(
... | 64 | 64 | 68 | 21 | 43 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | instance_template_config_is_unchanged_except_for_network_and_name | instance_template_config_is_unchanged_except_for_network_and_name | 60 | 66 | 60 | 61 | f31ed196485eb4760c49f7c7f2eeb79a7713b618 | bigcode/the-stack | train |
c9eba92fe9532b8cdcb98885 | train | function | def instance_template_config_is_unchanged(original_config, new_config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink'])
| def instance_template_config_is_unchanged(original_config, new_config):
| return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink'])
| _config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'name', 'network',
'subnetwork', 'selfLink'])
def instance_template_config_is_unchanged(original_config, new_config):
| 63 | 64 | 50 | 14 | 49 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | instance_template_config_is_unchanged | instance_template_config_is_unchanged | 69 | 73 | 69 | 69 | 2510c27c18bf06ed97e73172ac1be4495d3a37b2 | bigcode/the-stack | train |
f8f985bf49b388433e1cea8b | train | function | def compare_two_list(l1, l2):
for value in l1:
if value not in l2:
return False
for value in l2:
if value not in l1:
return False
return True
| def compare_two_list(l1, l2):
| for value in l1:
if value not in l2:
return False
for value in l2:
if value not in l1:
return False
return True
| comparing the test results
"""
def compare_instance_external_ip(config1, config2):
return config1['networkInterfaces'][0]['accessConfigs'][0]['natIP'] == \
config2['networkInterfaces'][0]['accessConfigs'][0]['natIP']
def compare_two_list(l1, l2):
| 64 | 64 | 52 | 10 | 54 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | compare_two_list | compare_two_list | 24 | 32 | 24 | 24 | 3e643ea4cbe399a0ea36a2ab3db1dd5644d78192 | bigcode/the-stack | train |
14982c71065ac625ad1dd82c | train | function | def resource_config_is_unchanged_except_for_network(original_config,
new_config):
except_tags = ['id', 'creationTimestamp', 'fingerprint', 'network',
'subnetwork', 'networkIP', 'natIP', 'IPAddress']
return resource_config_is_unchanged_except... | def resource_config_is_unchanged_except_for_network(original_config,
new_config):
| except_tags = ['id', 'creationTimestamp', 'fingerprint', 'network',
'subnetwork', 'networkIP', 'natIP', 'IPAddress']
return resource_config_is_unchanged_except_for_tags(original_config,
new_config, except_tags)
| /...' == '/project/project_id/...'
"""
traced_url1 = url1.split('project')[1]
traced_url2 = url2.split('project')[1]
return traced_url1 == traced_url2
def resource_config_is_unchanged_except_for_network(original_config,
new_config):
| 64 | 64 | 72 | 17 | 46 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | resource_config_is_unchanged_except_for_network | resource_config_is_unchanged_except_for_network | 45 | 50 | 45 | 46 | 4f746c9c8e4f24bb0bdf22b7984f55f503e444d8 | bigcode/the-stack | train |
011b588e5d54c2fe9a8722d8 | train | function | def managed_instance_group_config_is_unchanged_except_for_instance_template(original_config, new_config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink', 'instanceTemplate'])
| def managed_instance_group_config_is_unchanged_except_for_instance_template(original_config, new_config):
| return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink', 'instanceTemplate'])
| _unchanged(original_config, new_config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink'])
def managed_instance_group_config_is_unchanged_except_for_instance_template(original_config, new_config):
| 64 | 64 | 59 | 19 | 45 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | managed_instance_group_config_is_unchanged_except_for_instance_template | managed_instance_group_config_is_unchanged_except_for_instance_template | 75 | 79 | 75 | 75 | 7370bd3023fbc367add30b55d94f086c1b53913f | bigcode/the-stack | train |
8cd3f90a2a86da09c59ef78d | train | function | def compare_instance_external_ip(config1, config2):
return config1['networkInterfaces'][0]['accessConfigs'][0]['natIP'] == \
config2['networkInterfaces'][0]['accessConfigs'][0]['natIP']
| def compare_instance_external_ip(config1, config2):
| return config1['networkInterfaces'][0]['accessConfigs'][0]['natIP'] == \
config2['networkInterfaces'][0]['accessConfigs'][0]['natIP']
| License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Helper functions for comparing the test results
"""
def compare_instance_external_ip(config1... | 64 | 64 | 48 | 11 | 53 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | compare_instance_external_ip | compare_instance_external_ip | 19 | 21 | 19 | 19 | aeb32b6fbb911de8cb9ee40edd3cfff1c1014e3d | bigcode/the-stack | train |
688a2b1fdfac85f77f43bb15 | train | function | def check_instance_template_network(instance_template_config, network_selfLink,
subnetwork_selfLink=None):
if instance_template_config['properties']['networkInterfaces'][
0]['network'] != network_selfLink:
return False
if subnetwork_selfLink != None and \
... | def check_instance_template_network(instance_template_config, network_selfLink,
subnetwork_selfLink=None):
| if instance_template_config['properties']['networkInterfaces'][
0]['network'] != network_selfLink:
return False
if subnetwork_selfLink != None and \
instance_template_config['properties']['networkInterfaces'][
0]['subnetwork'] != subnetwork_selfLink:
return Fa... | :
if not resource_config_is_unchanged_except_for_tags(
original_config[i],
new_config[i],
except_tags):
print(i, original_config[i])
return False
return True
def check_instance_template_n... | 64 | 64 | 89 | 20 | 43 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | check_instance_template_network | check_instance_template_network | 113 | 122 | 113 | 114 | d1e1e792b5d82bd3ee893383427dde0c31f0974f | bigcode/the-stack | train |
a068085b6ebaff1d1d355ed8 | train | function | def check_selfLink_equal(url1, url2):
"""
'https://googleapi/project/project_id/...' == '/project/project_id/...'
"""
traced_url1 = url1.split('project')[1]
traced_url2 = url2.split('project')[1]
return traced_url1 == traced_url2
| def check_selfLink_equal(url1, url2):
| """
'https://googleapi/project/project_id/...' == '/project/project_id/...'
"""
traced_url1 = url1.split('project')[1]
traced_url2 = url2.split('project')[1]
return traced_url1 == traced_url2
| ']
def compare_two_list(l1, l2):
for value in l1:
if value not in l2:
return False
for value in l2:
if value not in l1:
return False
return True
def check_selfLink_equal(url1, url2):
| 64 | 64 | 69 | 11 | 52 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | check_selfLink_equal | check_selfLink_equal | 35 | 42 | 35 | 35 | 0e5ab23b630ea840bc4eaa6c8a0469bc763686b4 | bigcode/the-stack | train |
128c486ef27cb2df1393faff | train | function | def resource_config_is_unchanged_except_for_tags(original_config, new_config,
except_tags=[]):
""" Recursively compare if original_config is the same as new_config except
for the except_tags
"""
if type(original_config) is str:
if original_config... | def resource_config_is_unchanged_except_for_tags(original_config, new_config,
except_tags=[]):
| """ Recursively compare if original_config is the same as new_config except
for the except_tags
"""
if type(original_config) is str:
if original_config != new_config:
print(original_config)
return False
elif type(original_config) is list:
for i in range(len(o... | new_config):
return resource_config_is_unchanged_except_for_tags(
original_config,
new_config,
['id', 'creationTimestamp', 'fingerprint', 'selfLink', 'instanceTemplate'])
def resource_config_is_unchanged_except_for_tags(original_config, new_config,
... | 64 | 64 | 204 | 21 | 43 | googleinterns/vm-network-migration | vm_network_migration_end_to_end_tests/check_result.py | Python | resource_config_is_unchanged_except_for_tags | resource_config_is_unchanged_except_for_tags | 81 | 110 | 81 | 82 | f64650097240154e9fc9e1f0e5a3475562e6e077 | bigcode/the-stack | train |
e69a4f54b4a3b8932f4d1059 | train | function | def test():
file_folder = os.path.dirname(__file__)
prices_file = os.path.abspath(os.path.join(file_folder, os.pardir, "datasets", "prices.txt"))
prices = TabularData().read(prices_file).to_dataset()
lr = Base.make("linear_regression")
poly = Base.make("poly", deg=1)
sk_reg = LinearRegression(no... | def test():
| file_folder = os.path.dirname(__file__)
prices_file = os.path.abspath(os.path.join(file_folder, os.pardir, "datasets", "prices.txt"))
prices = TabularData().read(prices_file).to_dataset()
lr = Base.make("linear_regression")
poly = Base.make("poly", deg=1)
sk_reg = LinearRegression(normalize=True... | import os
from cfml import *
Experiment.suppress_warnings()
from cfdata.tabular import *
from sklearn.linear_model import LinearRegression
def test():
| 32 | 64 | 130 | 3 | 28 | carefree0910/carefree-ml | tests/unittests/test_linear_regression.py | Python | test | test | 10 | 22 | 10 | 10 | 93d26c6d603baf69ea975d6fa4a2fceae839d949 | bigcode/the-stack | train |
480b3b7b4cfa9b320e84717f | train | class | @PublicAPI
class DatasetPipeline(Generic[T]):
"""Implements a pipeline of Datasets.
Unlike Datasets, which execute all transformations synchronously,
DatasetPipelines implement pipelined execution. This allows for the
overlapped execution of data input (e.g., reading files), computation
(e.g. featu... | @PublicAPI
class DatasetPipeline(Generic[T]):
| """Implements a pipeline of Datasets.
Unlike Datasets, which execute all transformations synchronously,
DatasetPipelines implement pipelined execution. This allows for the
overlapped execution of data input (e.g., reading files), computation
(e.g. feature preprocessing), and output (e.g., distribut... | Block
from ray.data.row import TableRow
from ray.data.impl import progress_bar
from ray.data.impl.block_batching import batch_blocks, BatchType
from ray.data.impl.block_list import BlockList
from ray.data.impl.plan import ExecutionPlan
from ray.data.impl.stats import DatasetPipelineStats, DatasetStats
from ray.util.an... | 255 | 256 | 5,686 | 10 | 245 | siddgoel/ray | python/ray/data/dataset_pipeline.py | Python | DatasetPipeline | DatasetPipeline | 56 | 777 | 56 | 57 | 38ee13128657551eba9b7195f3b87fd1cf4dc67b | bigcode/the-stack | train |
987f21b178a78843c3863f0e | train | class | class TaskAdmin(admin.ModelAdmin):
list_display = ['path', 'frequency', 'is_enabled']
list_editable = ['is_enabled']
list_filter = ['is_enabled']
readonly_fields = ['path', 'frequency']
| class TaskAdmin(admin.ModelAdmin):
| list_display = ['path', 'frequency', 'is_enabled']
list_editable = ['is_enabled']
list_filter = ['is_enabled']
readonly_fields = ['path', 'frequency']
| from django.contrib import admin
from .models import Task
class TaskAdmin(admin.ModelAdmin):
| 19 | 64 | 48 | 7 | 11 | zhebrak/django-beatle | django_beatle/admin.py | Python | TaskAdmin | TaskAdmin | 6 | 11 | 6 | 6 | 984ad43f3fb69625ee3dfbf1456dfbd22db18279 | bigcode/the-stack | train |
7675867aaf426284ee989340 | train | function | @route(app, '/update_host_record/form', methods=['POST'])
@util.workflow_permission_required('update_host_record_page')
@util.exception_catcher
def update_host_record_update_host_record_page_form():
"""
Processes the final form after the user has input all the required data.
:return:
"""
# pylint: ... | @route(app, '/update_host_record/form', methods=['POST'])
@util.workflow_permission_required('update_host_record_page')
@util.exception_catcher
def update_host_record_update_host_record_page_form():
| """
Processes the final form after the user has input all the required data.
:return:
"""
# pylint: disable=broad-except
form = GenericFormTemplate()
# Remove this line if your workflow does not need to select a configuration
form.configuration.choices = util.get_configurations(default_... | def module_path():
"""
Get module path.
:return:
"""
return os.path.dirname(os.path.abspath(str(__file__)))
# The workflow name must be the first part of any endpoints defined in this file.
# If you break this rule, you will trip up on other people's endpoint names and
# chaos will ensue.
@route(... | 245 | 245 | 819 | 41 | 204 | ryutamura/gateway-workflows | Examples/Host Record/update_host_record/update_host_record_page.py | Python | update_host_record_update_host_record_page_form | update_host_record_update_host_record_page_form | 65 | 153 | 65 | 68 | 1be983330ca17a46810394add25dc3ec57408b57 | bigcode/the-stack | train |
c1a23ce6aa65f230ce1dd63d | train | function | def module_path():
"""
Get module path.
:return:
"""
return os.path.dirname(os.path.abspath(str(__file__)))
| def module_path():
| """
Get module path.
:return:
"""
return os.path.dirname(os.path.abspath(str(__file__)))
| , jsonify
from bluecat import route, util
from bluecat.constants import SelectiveDeploymentStatus
from bluecat.server_endpoints import get_result_template, empty_decorator
import config.default_config as config
from main_app import app
from .update_host_record_form import GenericFormTemplate
def module_path():
| 64 | 64 | 30 | 4 | 59 | ryutamura/gateway-workflows | Examples/Host Record/update_host_record/update_host_record_page.py | Python | module_path | module_path | 35 | 41 | 35 | 35 | 155d8e511df1a22e98c4a2edb56cea3d7cbb145e | bigcode/the-stack | train |
1150b054d61a072d46e478a3 | train | function | @route(app, '/update_host_record/update_host_record_endpoint')
@util.workflow_permission_required('update_host_record_page')
@util.exception_catcher
def update_host_record_update_host_record_page():
"""
Renders the form the user would first see when selecting the workflow.
:return:
"""
form = Gener... | @route(app, '/update_host_record/update_host_record_endpoint')
@util.workflow_permission_required('update_host_record_page')
@util.exception_catcher
def update_host_record_update_host_record_page():
| """
Renders the form the user would first see when selecting the workflow.
:return:
"""
form = GenericFormTemplate()
# Remove this line if your workflow does not need to select a configuration
form.configuration.choices = util.get_configurations(default_val=True)
return render_template(... | .
# If you break this rule, you will trip up on other people's endpoint names and
# chaos will ensue.
@route(app, '/update_host_record/update_host_record_endpoint')
@util.workflow_permission_required('update_host_record_page')
@util.exception_catcher
def update_host_record_update_host_record_page():
| 64 | 64 | 133 | 39 | 25 | ryutamura/gateway-workflows | Examples/Host Record/update_host_record/update_host_record_page.py | Python | update_host_record_update_host_record_page | update_host_record_update_host_record_page | 47 | 62 | 47 | 50 | b977e923ff7ecb26c5c07f6cb73424373d816ef6 | bigcode/the-stack | train |
b6e81e9883513f5afea8b7a9 | train | function | @route(app, '/update_host_record/get_deploy_status', methods=['POST'])
@util.rest_workflow_permission_required('update_host_record_page')
@util.rest_exception_catcher
def get_deploy_status():
"""
Retrieves and updates deployment task status
:return:
"""
result = get_result_template()
deploy_toke... | @route(app, '/update_host_record/get_deploy_status', methods=['POST'])
@util.rest_workflow_permission_required('update_host_record_page')
@util.rest_exception_catcher
def get_deploy_status():
| """
Retrieves and updates deployment task status
:return:
"""
result = get_result_template()
deploy_token = request.form['deploy_token']
try:
task_status = g.user.get_api().get_deployment_task_status(deploy_token)
result['status'] = task_status['status']
if task_stat... | ('view', ''),
host_record=request.form.get('host_record', ''),
name=form.name.data,
ip4_address=form.ip4_address.data,
text=util.get_text(module_path(), config.language),
... | 93 | 93 | 312 | 43 | 50 | ryutamura/gateway-workflows | Examples/Host Record/update_host_record/update_host_record_page.py | Python | get_deploy_status | get_deploy_status | 156 | 197 | 156 | 159 | 956bfd3ac6689863c6d30551dfdb137437613c98 | bigcode/the-stack | train |
1f56c3ddc883bd6423f3893c | train | function | def write_labels(
gdspath: Path,
label_layer: Tuple[int, int] = LAYER.LABEL,
filepath: Optional[PathType] = None,
prefix: str = "opt_",
) -> Path:
"""Load GDS mask and extracts the labels and coordinates from a GDS file"""
labels = list(find_labels(gdspath, label_layer=label_layer, prefix=prefi... | def write_labels(
gdspath: Path,
label_layer: Tuple[int, int] = LAYER.LABEL,
filepath: Optional[PathType] = None,
prefix: str = "opt_",
) -> Path:
| """Load GDS mask and extracts the labels and coordinates from a GDS file"""
labels = list(find_labels(gdspath, label_layer=label_layer, prefix=prefix))
gdspath = pathlib.Path(gdspath)
filepath = filepath or gdspath.with_suffix(".csv")
with open(filepath, "w", newline="") as f:
writer = csv... | text.string, transformed.x * dbu, transformed.y * dbu
def write_labels(
gdspath: Path,
label_layer: Tuple[int, int] = LAYER.LABEL,
filepath: Optional[PathType] = None,
prefix: str = "opt_",
) -> Path:
| 64 | 64 | 152 | 49 | 14 | tvt173/gdsfactory | gdsfactory/mask/write_labels.py | Python | write_labels | write_labels | 46 | 61 | 46 | 51 | 7e57da89b279b1135466041e7744ceab2b6f690f | bigcode/the-stack | train |
a61cdb8c64eb08b68926a957 | train | function | def test_find_labels():
import gdsfactory as gf
c = gf.components.straight(length=124)
cc = add_fiber_single(component=c)
gdspath = cc.write_gds()
assert len(list(find_labels(gdspath))) == 4
| def test_find_labels():
| import gdsfactory as gf
c = gf.components.straight(length=124)
cc = add_fiber_single(component=c)
gdspath = cc.write_gds()
assert len(list(find_labels(gdspath))) == 4
| .Path(gdspath)
filepath = filepath or gdspath.with_suffix(".csv")
with open(filepath, "w", newline="") as f:
writer = csv.writer(f)
writer.writerows(labels)
logger.info(f"Wrote labels in {filepath}")
return filepath
def test_find_labels():
| 64 | 64 | 58 | 5 | 58 | tvt173/gdsfactory | gdsfactory/mask/write_labels.py | Python | test_find_labels | test_find_labels | 64 | 70 | 64 | 64 | 6dafd288ab89d29b0754fbdf204fef98be662ef8 | bigcode/the-stack | train |
0f22f1bcc18183408ec02193 | train | function | def find_labels(
gdspath: Path, label_layer: Tuple[int, int] = LAYER.LABEL, prefix: str = "opt_"
) -> Iterator[Tuple[str, float, float]]:
"""finds labels and locations from a GDS file"""
# Load the layout
gdspath = str(gdspath)
layout = pya.Layout()
layout.read(gdspath)
# Get the top cell a... | def find_labels(
gdspath: Path, label_layer: Tuple[int, int] = LAYER.LABEL, prefix: str = "opt_"
) -> Iterator[Tuple[str, float, float]]:
| """finds labels and locations from a GDS file"""
# Load the layout
gdspath = str(gdspath)
layout = pya.Layout()
layout.read(gdspath)
# Get the top cell and the units, and find out the index of the layer
topcell = layout.top_cell()
dbu = layout.dbu
layer = pya.LayerInfo(label_layer[0... | gdsfactory.routing.add_fiber_single import add_fiber_single
from gdsfactory.types import Optional, PathType
def find_labels(
gdspath: Path, label_layer: Tuple[int, int] = LAYER.LABEL, prefix: str = "opt_"
) -> Iterator[Tuple[str, float, float]]:
| 68 | 68 | 228 | 43 | 24 | tvt173/gdsfactory | gdsfactory/mask/write_labels.py | Python | find_labels | find_labels | 18 | 43 | 18 | 20 | 0e57c9948b12003cfacfa40f379d9022439795b8 | bigcode/the-stack | train |
5c16a52b094d0026e58cbf56 | train | class | class SequenceClassifier(Model):
"""A sequence classifier."""
def __init__(self,
inputter,
encoder,
labels_vocabulary_file_key,
encoding="average",
daisy_chain_variables=False,
name="seqclassifier"):
"""Initializes a sequ... | class SequenceClassifier(Model):
| """A sequence classifier."""
def __init__(self,
inputter,
encoder,
labels_vocabulary_file_key,
encoding="average",
daisy_chain_variables=False,
name="seqclassifier"):
"""Initializes a sequence classifier.
Args:
... | """Sequence classifier."""
import tensorflow as tf
from opennmt.models.model import Model
#from opennmt.utils.cell import last_encoding_from_state
from opennmt.utils.misc import count_lines, print_bytes
from opennmt.utils.losses import cross_entropy_loss
class SequenceClassifier(Model):
| 60 | 243 | 810 | 5 | 54 | aquorio15/OpenNMT-tf | build/lib/opennmt/models/sequence_classifier.py | Python | SequenceClassifier | SequenceClassifier | 11 | 117 | 11 | 11 | bdfd40f16f32492474d1020c32cde04b039a4266 | bigcode/the-stack | train |
3cb4f1494eb4538a2dd985fa | train | function | @pytest.fixture
def targets():
return ()
| @pytest.fixture
def targets():
| return ()
| import pytest
import shutil
import tempfile
import pathlib
@pytest.fixture
def target():
return "./tests/test_files/addon_valid_single"
@pytest.fixture
def targets():
| 35 | 64 | 9 | 6 | 29 | winkelchri/blender_squirrel | tests/fixtures.py | Python | targets | targets | 12 | 14 | 12 | 13 | 4c5dd34e948b8179b5561083142d532b34ea24a4 | bigcode/the-stack | train |
2753e2b9147a1fbbf759f888 | train | function | @pytest.fixture
def zip_files(targets):
zipped_targets = list(map(create_zip_file, targets))
zip_files = [item[0] for item in zipped_targets]
temp_dirs = [item[1] for item in zipped_targets]
yield zip_files
for temp_dir in temp_dirs:
temp_dir.cleanup()
| @pytest.fixture
def zip_files(targets):
| zipped_targets = list(map(create_zip_file, targets))
zip_files = [item[0] for item in zipped_targets]
temp_dirs = [item[1] for item in zipped_targets]
yield zip_files
for temp_dir in temp_dirs:
temp_dir.cleanup()
| (zip_file):
# Will be a single zip file of the list_of_files list
print(zip_file)
'''
target_zip, temp_dir = create_zip_file(target)
yield target_zip
temp_dir.cleanup()
# Everything will be deleted now ...
@pytest.fixture
def zip_files(targets):
| 64 | 64 | 69 | 9 | 55 | winkelchri/blender_squirrel | tests/fixtures.py | Python | zip_files | zip_files | 64 | 74 | 64 | 66 | 9889f7be63ab0f109e22947b64c8ed0cdb6323b6 | bigcode/the-stack | train |
f47bef242f5a5e666edc0e5d | train | function | def create_zip_file(target):
''' `target` shall either be a file or a folder. '''
temp_dir = tempfile.TemporaryDirectory()
# Use pathlib path's
temp_path = pathlib.Path(temp_dir.name)
target = pathlib.Path(target)
# Create the target file (excluding extension)
base_name = temp_path / targ... | def create_zip_file(target):
| ''' `target` shall either be a file or a folder. '''
temp_dir = tempfile.TemporaryDirectory()
# Use pathlib path's
temp_path = pathlib.Path(temp_dir.name)
target = pathlib.Path(target)
# Create the target file (excluding extension)
base_name = temp_path / target.name
# Create the arc... | import pytest
import shutil
import tempfile
import pathlib
@pytest.fixture
def target():
return "./tests/test_files/addon_valid_single"
@pytest.fixture
def targets():
return ()
def create_zip_file(target):
| 44 | 64 | 122 | 6 | 38 | winkelchri/blender_squirrel | tests/fixtures.py | Python | create_zip_file | create_zip_file | 17 | 36 | 17 | 17 | e8b87d2fdfe89d25682fd5b54d9da13bc6b20bec | bigcode/the-stack | train |
a7f4815a12f70eb3fbd969cd | train | function | @pytest.fixture
def target():
return "./tests/test_files/addon_valid_single"
| @pytest.fixture
def target():
| return "./tests/test_files/addon_valid_single"
| import pytest
import shutil
import tempfile
import pathlib
@pytest.fixture
def target():
| 18 | 64 | 17 | 6 | 11 | winkelchri/blender_squirrel | tests/fixtures.py | Python | target | target | 7 | 9 | 7 | 8 | 06e567db14e8644304204aa2064a50955fa7ca77 | bigcode/the-stack | train |
7bf10831995853f4d86c3030 | train | function | @pytest.fixture
def zip_file(target):
''' Creates a zip file of the given folder or file within a temp folder
and return its filename.
Deletes the temp zip file afterwards.
Usage:
Use this fixture in the test as a parameter.
Add the `@pytest.mark.parametrize('target... | @pytest.fixture
def zip_file(target):
| ''' Creates a zip file of the given folder or file within a temp folder
and return its filename.
Deletes the temp zip file afterwards.
Usage:
Use this fixture in the test as a parameter.
Add the `@pytest.mark.parametrize('target', list_of_files)`
decorat... | _name = temp_path / target.name
# Create the archive and return it's name
target = shutil.make_archive(
base_name=base_name,
format="zip",
root_dir=target
)
return (pathlib.Path(target), temp_dir)
@pytest.fixture
def zip_file(target):
| 64 | 64 | 140 | 8 | 56 | winkelchri/blender_squirrel | tests/fixtures.py | Python | zip_file | zip_file | 39 | 60 | 39 | 40 | 8cc96f1e0ef10e0de821ca2946e653024115e610 | bigcode/the-stack | train |
6c290b2f6f22668f762e5e79 | train | class | class RMatrixmodels(RPackage):
"""Modelling with sparse and dense 'Matrix' matrices, using modular
prediction and response module classes."""
homepage = "http://matrix.r-forge.r-project.org/"
url = "https://cran.r-project.org/src/contrib/MatrixModels_0.4-1.tar.gz"
list_url = "https://cran.r-pr... | class RMatrixmodels(RPackage):
| """Modelling with sparse and dense 'Matrix' matrices, using modular
prediction and response module classes."""
homepage = "http://matrix.r-forge.r-project.org/"
url = "https://cran.r-project.org/src/contrib/MatrixModels_0.4-1.tar.gz"
list_url = "https://cran.r-project.org/src/contrib/Archive/M... | # 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 RMatrixmodels(RPackage):
| 61 | 64 | 137 | 7 | 54 | nkianggiss/spack | var/spack/repos/builtin/packages/r-matrixmodels/package.py | Python | RMatrixmodels | RMatrixmodels | 9 | 19 | 9 | 9 | 78c86b4ecdacd5b45c098617f8610d365b94a117 | bigcode/the-stack | train |
203bcafb9bc44de76491528f | train | class | class RunManager(object):
def __init__(self, config):
self.config = config
def deserialize_graph(self):
logger.info("Loading dependency graph file.")
base_target_path = self.config.target_path
graph_file = os.path.join(
base_target_path,
dbt.compilation.... | class RunManager(object):
| def __init__(self, config):
self.config = config
def deserialize_graph(self):
logger.info("Loading dependency graph file.")
base_target_path = self.config.target_path
graph_file = os.path.join(
base_target_path,
dbt.compilation.graph_file_name
)
... | import os
import time
from dbt.adapters.factory import get_adapter
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.contracts.graph.parsed import ParsedNode
from dbt.contracts.graph.manifest import CompileResultNode
from dbt.contracts.results import ExecutionResult
import dbt.clients.jinja
import dbt.compilati... | 147 | 256 | 1,456 | 5 | 142 | cwkrebs/dbt | dbt/runner.py | Python | RunManager | RunManager | 28 | 247 | 28 | 28 | 2b75275613af327cc824a3b859b0e84362a9b9a4 | bigcode/the-stack | train |
59a1898b70ecfbd89a55891f | train | class | class MapTransformer(nn.Module):
# TODO: Refactor this entire getting/setting idea
def __init__(self, source_map_size, world_size_px, world_size_m, dest_map_size=None):
super(MapTransformer, self).__init__()
if dest_map_size is None:
dest_map_size = source_map_size
self.ma... | class MapTransformer(nn.Module):
# TODO: Refactor this entire getting/setting idea
| def __init__(self, source_map_size, world_size_px, world_size_m, dest_map_size=None):
super(MapTransformer, self).__init__()
if dest_map_size is None:
dest_map_size = source_map_size
self.map_affine = MapAffine(
source_map_size=source_map_size,
dest_map_... | import torch
import torch.nn as nn
from learning.models.semantic_map.map_affine import MapAffine
from visualization import Presenter
class MapTransformer(nn.Module):
# TODO: Refactor this entire getting/setting idea
| 45 | 90 | 302 | 19 | 25 | esteng/guiding-multi-step | learning/modules/map_transformer.py | Python | MapTransformer | MapTransformer | 7 | 42 | 7 | 9 | e17eb60849df7617df1a36900733b389b8b5324b | bigcode/the-stack | train |
149d2dda7625df1b6a9b1599 | train | class | class Migration(migrations.Migration):
dependencies = [
('volunteers', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='volunteer',
old_name='picture',
new_name='avatar',
),
]
| class Migration(migrations.Migration):
| dependencies = [
('volunteers', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='volunteer',
old_name='picture',
new_name='avatar',
),
]
| # -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-03-14 17:12
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
| 52 | 64 | 56 | 7 | 44 | NewsNerdsAtCoJMC/ProjectTicoTeam6 | service/volunteers/migrations/0002_auto_20170314_1712.py | Python | Migration | Migration | 8 | 20 | 8 | 9 | e2a66c8216de76d0985d172fe6e24782773e5036 | bigcode/the-stack | train |
3bef20e8a268bbdde4630f22 | train | function | def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
This parser is RFC 3986 compliant.
:param str url: URL to parse into a :class:`.Url` namedtuple.
Partly backwards-compatible with ... | def parse_url(url):
| """
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
This parser is RFC 3986 compliant.
:param str url: URL to parse into a :class:`.Url` namedtuple.
Partly backwards-compatible with :mod:`urlparse`.
... | return url
def __str__(self):
return self.url
def split_first(s, delims):
"""
.. deprecated:: 1.25
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input... | 256 | 256 | 888 | 5 | 250 | elprans/urllib3 | src/urllib3/util/url.py | Python | parse_url | parse_url | 139 | 243 | 139 | 139 | 3a0fe1996fe0ea73c744ea13f40ccd5c4d4c4970 | bigcode/the-stack | train |
89bd50289b8a6e474d7dd68f | train | function | def get_host(url):
"""
Deprecated. Use :func:`parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
| def get_host(url):
| """
Deprecated. Use :func:`parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
| info),
host=to_input_type(uri_ref.host),
port=int(uri_ref.port) if uri_ref.port is not None else None,
path=to_input_type(path),
query=to_input_type(uri_ref.query),
fragment=to_input_type(uri_ref.fragment)
)
def get_host(url):
| 64 | 64 | 42 | 5 | 59 | elprans/urllib3 | src/urllib3/util/url.py | Python | get_host | get_host | 246 | 251 | 246 | 246 | dab149a1e920a271143a4db58bb29c9a12dd0d7a | bigcode/the-stack | train |
1b7ab557b304d137342fdae0 | train | function | def split_first(s, delims):
"""
.. deprecated:: 1.25
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz'... | def split_first(s, delims):
| """
.. deprecated:: 1.25
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'ba... | (port)
if path is not None:
url += path
if query is not None:
url += u'?' + query
if fragment is not None:
url += u'#' + fragment
return url
def __str__(self):
return self.url
def split_first(s, delims):
| 70 | 70 | 236 | 8 | 61 | elprans/urllib3 | src/urllib3/util/url.py | Python | split_first | split_first | 104 | 136 | 104 | 104 | 450692bd3f0a66bc2aaf37ea1974b53353fc229f | bigcode/the-stack | train |
e22563f33751f042d7799152 | train | class | class Url(namedtuple('Url', url_attrs)):
"""
Data structure for representing an HTTP URL. Used as a return value for
:func:`parse_url`. Both the scheme and host are normalized as they are
both case-insensitive according to RFC 3986.
"""
__slots__ = ()
def __new__(cls, scheme=None, auth=None... | class Url(namedtuple('Url', url_attrs)):
| """
Data structure for representing an HTTP URL. Used as a return value for
:func:`parse_url`. Both the scheme and host are normalized as they are
both case-insensitive according to RFC 3986.
"""
__slots__ = ()
def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None,
... | from collections import namedtuple
from ..exceptions import LocationParseError
from ..packages import six, rfc3986
from ..packages.rfc3986.exceptions import RFC3986Exception, ValidationError
from ..packages.rfc3986.validators import Validator
url_attrs = ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'... | 180 | 181 | 604 | 10 | 170 | elprans/urllib3 | src/urllib3/util/url.py | Python | Url | Url | 21 | 101 | 21 | 21 | fd46f80377e8baf166a19a052a9ee1ce1c512b38 | bigcode/the-stack | train |
671358b5638aa9cb02020b47 | train | class | class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prev = None
start = None
carry = 0
while l1 or l2:
sum = 0
if l1:
sum = sum + l1.val... | class Solution(object):
| def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
prev = None
start = None
carry = 0
while l1 or l2:
sum = 0
if l1:
sum = sum + l1.val
l1 = l1... | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
| 41 | 64 | 202 | 4 | 36 | alexwawl/leetcode-solutions-javascript-python | solutions/0002_AddTwoNumbers.py | Python | Solution | Solution | 7 | 39 | 7 | 7 | 49df53c2f50379040b770c7350894108f2b4ab79 | bigcode/the-stack | train |
72518f9f89da0a34055f31d2 | train | class | class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object('project.config.TestingConfig')
return app
def setUp(self):
db.create_all()
user = User(email="ad@min.com", password="admin_user")
db.session.add(user)
db.session.commit()
def tearDo... | class BaseTestCase(TestCase):
| def create_app(self):
app.config.from_object('project.config.TestingConfig')
return app
def setUp(self):
db.create_all()
user = User(email="ad@min.com", password="admin_user")
db.session.add(user)
db.session.commit()
def tearDown(self):
db.session.re... | # project/server/tests/base.py
from flask_testing import TestCase
from project.server import db, create_app
from project.server.models import User
app = create_app()
class BaseTestCase(TestCase):
| 42 | 64 | 83 | 7 | 35 | testdrivenio/openci | services/web/project/tests/base.py | Python | BaseTestCase | BaseTestCase | 12 | 26 | 12 | 13 | 9aab89bcdc390d4f0f71792019c764ee1ef4ef26 | bigcode/the-stack | train |
cb3a21e5d0df461d1d833331 | train | class | class rewritepolicy_binding_response(base_response) :
def __init__(self, length=1) :
self.rewritepolicy_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.rewritepolicy_binding = [rewritepolicy_binding() for _ in range(length)]
| class rewritepolicy_binding_response(base_response) :
| def __init__(self, length=1) :
self.rewritepolicy_binding = []
self.errorcode = 0
self.message = ""
self.severity = ""
self.sessionid = ""
self.rewritepolicy_binding = [rewritepolicy_binding() for _ in range(length)]
| rewritepolicy_binding() for _ in range(len(name))]
for i in range(len(name)) :
obj[i].name = name[i];
response[i] = obj[i].get_resource(service)
return response
except Exception as e:
raise e
class rewritepolicy_binding_response(base_response) :
| 64 | 64 | 71 | 9 | 54 | guardicore/nitro-python | nssrc/com/citrix/netscaler/nitro/resource/config/rewrite/rewritepolicy_binding.py | Python | rewritepolicy_binding_response | rewritepolicy_binding_response | 149 | 156 | 149 | 149 | d0c114ad1502ba99aa5ce53b58969e0f2f990adc | bigcode/the-stack | train |
c31ef601f72efaa6dd24dae5 | train | class | class rewritepolicy_binding(base_resource):
""" Binding class showing the resources that can be bound to rewritepolicy_binding.
"""
def __init__(self) :
self._name = None
self.rewritepolicy_csvserver_binding = []
self.rewritepolicy_rewriteglobal_binding = []
self.rewritepolicy_lbvserver_binding = []
self.... | class rewritepolicy_binding(base_resource):
| """ Binding class showing the resources that can be bound to rewritepolicy_binding.
"""
def __init__(self) :
self._name = None
self.rewritepolicy_csvserver_binding = []
self.rewritepolicy_rewriteglobal_binding = []
self.rewritepolicy_lbvserver_binding = []
self.rewritepolicy_vpnvserver_binding = []
self... | Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# di... | 249 | 249 | 832 | 7 | 241 | guardicore/nitro-python | nssrc/com/citrix/netscaler/nitro/resource/config/rewrite/rewritepolicy_binding.py | Python | rewritepolicy_binding | rewritepolicy_binding | 24 | 147 | 24 | 24 | 050f65b891217e1b9301e3f7ed6857d634d9fd60 | bigcode/the-stack | train |
8c4f11b16d60e3c96bf33685 | train | class | class TwitterClient(object):
'''
Generic Twitter Class for the App
'''
def __init__(self, query, retweets_only=False, with_sentiment=False):
# keys and tokens from the Twitter Dev Console
consumer_key = 'TW9Jd0pnZll4NUrVGsKDu7hdc'
consumer_secret = 'YOlIsFvjioIZ4ZOe2VxHmnKmDOfed3... | class TwitterClient(object):
| '''
Generic Twitter Class for the App
'''
def __init__(self, query, retweets_only=False, with_sentiment=False):
# keys and tokens from the Twitter Dev Console
consumer_key = 'TW9Jd0pnZll4NUrVGsKDu7hdc'
consumer_secret = 'YOlIsFvjioIZ4ZOe2VxHmnKmDOfed3rXvGktpseEeAdY6ScN0v'
... | # author = rhnvrm <hello@rohanverma.net>
import os
import re
import tweepy
from tweepy import OAuthHandler
from textblob import TextBlob
class TwitterClient(object):
| 45 | 201 | 671 | 5 | 39 | vitongos/amazon-web-services-course | scripts/demo-app/twitter.py | Python | TwitterClient | TwitterClient | 10 | 82 | 10 | 10 | f3992dd797d17341b4f58a4cbf83009f743232f6 | bigcode/the-stack | train |
4c68508b09a5c83f198cf174 | train | class | class AppConfigTests(TestCase):
def test_index_collection(self):
from haystack import connections
unified_index = connections["default"].get_unified_index()
models = unified_index.get_indexed_models()
self.assertIn(MicroBlogPost, models)
| class AppConfigTests(TestCase):
| def test_index_collection(self):
from haystack import connections
unified_index = connections["default"].get_unified_index()
models = unified_index.get_indexed_models()
self.assertIn(MicroBlogPost, models)
| from django.test import TestCase
from .models import MicroBlogPost
class AppConfigTests(TestCase):
| 22 | 64 | 55 | 7 | 14 | nakarinh14/django-haystack | test_haystack/test_app_using_appconfig/tests.py | Python | AppConfigTests | AppConfigTests | 6 | 13 | 6 | 6 | 0f36021c04a8247c05afa70bb5b5613f8c12292c | bigcode/the-stack | train |
0dd72837328124d0debde39d | train | function | def cancelDeviceHostScanner():
global deviceHostScanTimer
if deviceHostScanTimer is not None and deviceHostScanTimer.is_alive():
logger.debug('Canceling device host scanner')
deviceHostScanTimer.cancel()
deviceHostScanTimer = None
| def cancelDeviceHostScanner():
| global deviceHostScanTimer
if deviceHostScanTimer is not None and deviceHostScanTimer.is_alive():
logger.debug('Canceling device host scanner')
deviceHostScanTimer.cancel()
deviceHostScanTimer = None
| to scan every N seconds
deviceHostScanTimer = threading.Timer(
CONTINUOUS_DEVICE_HOST_SCAN_INTERVAL,
scanForDeviceHosts
)
deviceHostScanTimer.daemon = True
deviceHostScanTimer.start()
return gotAcceptableSetOfHosts
def cancelDeviceHostScanner():
| 64 | 64 | 55 | 6 | 57 | eriklindebratt/flic-chromecast-love | caster.py | Python | cancelDeviceHostScanner | cancelDeviceHostScanner | 170 | 176 | 170 | 170 | 79f9ffbf155b69417d2aa0e893974eb73a5b422f | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.