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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5d9e0f144348a8e3ff446fe4 | train | function | def save_real_predictions(model,
mask_threshold,
bandwidth,
im_id,
n_objects=12,
save_dir='figures/'):
scene_ds = RealSceneDataset(DS_DIR / 'real-cubes-1to12', n_objects=n_objects,
... | def save_real_predictions(model,
mask_threshold,
bandwidth,
im_id,
n_objects=12,
save_dir='figures/'):
| scene_ds = RealSceneDataset(DS_DIR / 'real-cubes-1to12', n_objects=n_objects,
resize=(640, 480))
rgb, mask, obs = scene_ds[im_id]
rgb = rgb[..., :3].unsqueeze(0)
joints = torch.tensor(obs['joints']).unsqueeze(0)
objects, segm, pred = model.predict_objects(rgb, joints=... | , 2, figsize=(width, height))
for ax, aabbs, title in zip(axs, (src_aabbs, tgt_aabbs), ('Source', 'Target')):
plot_gt_objects(ax, aabbs, plot_center=False, target_box=False,
alpha=1.0, collision_alpha=0.1,
collision_radius=radius, plot_collision_radius=True)
... | 256 | 256 | 1,422 | 31 | 224 | ylabbe/rearrangement-planning | rearrangement/figures/figures.py | Python | save_real_predictions | save_real_predictions | 68 | 170 | 68 | 73 | 6e82a42e9bfc1ba7ced5e2dd800d02fd28544783 | bigcode/the-stack | train |
10db651a647892fcc9cf2c21 | train | class | class CartItem(models.Model):
"""
CartItem represents the an Item present in a Cart.
A CartItem can be parts of many Carts.
CartItem is generic representation of the Product class,
so much of all message send to this instance is delegated to
the associated product member.
"""
cart = mode... | class CartItem(models.Model):
| """
CartItem represents the an Item present in a Cart.
A CartItem can be parts of many Carts.
CartItem is generic representation of the Product class,
so much of all message send to this instance is delegated to
the associated product member.
"""
cart = models.ForeignKey(Cart, unique=Fal... | cart.cart_service instead
"""
"""
count = 0
start_time = datetime.datetime.now()
items = self.get_items()
for item in items:
count += item.quantity
end_time = datetime.datetime.now()
elapsed_time = end_time - start_time
print("Cart : ... | 142 | 142 | 475 | 6 | 135 | cyrildzumts/django-cart | cart/models.py | Python | CartItem | CartItem | 259 | 341 | 259 | 259 | ffad72d44809fddd3bed30a665fabbc78a22abeb | bigcode/the-stack | train |
de3812415e5fec1f50ee0d07 | train | class | class LineItemManager(models.Manager):
def get(self, *args, **kwargs):
if 'product' in kwargs:
kwargs['content_type'] = ContentType.objects.get_for_model(
type(kwargs['product']))
kwargs['object_id'] = kwargs['product'].pk
del(kwargs['product'])
re... | class LineItemManager(models.Manager):
| def get(self, *args, **kwargs):
if 'product' in kwargs:
kwargs['content_type'] = ContentType.objects.get_for_model(
type(kwargs['product']))
kwargs['object_id'] = kwargs['product'].pk
del(kwargs['product'])
return super(LineItemManager, self).get(*... | get_absolute_url(self):
return self.product.get_absolute_url()
def change_quantity(self, quantity):
if quantity <= self.product.quantity:
self.quantity = quantity
self.save()
else:
raise QuantityError(available=self.product.quantity,
... | 64 | 64 | 81 | 7 | 57 | cyrildzumts/django-cart | cart/models.py | Python | LineItemManager | LineItemManager | 344 | 351 | 344 | 344 | d799841af0b66a807efa43f1d13ca1219346cb64 | bigcode/the-stack | train |
fb713538e7a32dfaeeb7ae26 | train | class | class LineItem(models.Model):
unit_price = models.IntegerField()
quantity = models.PositiveIntegerField()
# defining product as a generic relation
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey... | class LineItem(models.Model):
| unit_price = models.IntegerField()
quantity = models.PositiveIntegerField()
# defining product as a generic relation
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
... | **kwargs):
if 'product' in kwargs:
kwargs['content_type'] = ContentType.objects.get_for_model(
type(kwargs['product']))
kwargs['object_id'] = kwargs['product'].pk
del(kwargs['product'])
return super(LineItemManager, self).get(*args, **kwargs)
class Li... | 72 | 72 | 241 | 6 | 66 | cyrildzumts/django-cart | cart/models.py | Python | LineItem | LineItem | 354 | 387 | 354 | 354 | 27cadb8f7920293e0c9d63c9ae45e9358657c83e | bigcode/the-stack | train |
e28e6008c8ea235118012a13 | train | class | class Cart(models.Model):
"""
Every User has a Cart.
When checking out a Cart, an Order can be created from a Cart.
"""
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(... | class Cart(models.Model):
| """
Every User has a Cart.
When checking out a Cart, an Order can be created from a Cart.
"""
id = models.AutoField(primary_key=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User)
class Meta:
... | from django.db import models
import datetime
from catalog.models import Product, ProductVariant, VariantOption, Color, Size
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
# from django.conf import se... | 242 | 256 | 1,514 | 5 | 237 | cyrildzumts/django-cart | cart/models.py | Python | Cart | Cart | 41 | 256 | 41 | 41 | 92b8b439061099f23ceebf9a63500f07d348aa29 | bigcode/the-stack | train |
7b6ebd597260fe3fe41457a6 | train | function | @pytest.fixture
def erc20_caller(erc20, get_contract):
erc20_caller_code = """
token_address: address(ERC20)
@public
def __init__(token_addr: address):
self.token_address = token_addr
@public
def name() -> bytes32:
return self.token_address.name()
@public
def symbol() -> bytes32:
return self.token_ad... | @pytest.fixture
def erc20_caller(erc20, get_contract):
| erc20_caller_code = """
token_address: address(ERC20)
@public
def __init__(token_addr: address):
self.token_address = token_addr
@public
def name() -> bytes32:
return self.token_address.name()
@public
def symbol() -> bytes32:
return self.token_address.symbol()
@public
def decimals() -> uint256:
... | * (10 ** TOKEN_DECIMALS)
@pytest.fixture
def erc20(get_contract):
with open('examples/tokens/vypercoin.v.py') as f:
contract = get_contract(f.read(), *[TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_INITIAL_SUPPLY])
return contract
@pytest.fixture
def erc20_caller(erc20, get_contract):
| 81 | 81 | 272 | 16 | 64 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | erc20_caller | erc20_caller | 19 | 60 | 19 | 20 | bc5570f66932694eafc043515883bdb519edbcff | bigcode/the-stack | train |
e868793594c2cd96a321cbe3 | train | function | def pad_bytes32(instr):
""" Pad a string \x00 bytes to return correct bytes32 representation. """
return instr + (32 - len(instr)) * b'\x00'
| def pad_bytes32(instr):
| """ Pad a string \x00 bytes to return correct bytes32 representation. """
return instr + (32 - len(instr)) * b'\x00'
| , _to, _value)
@public
def allowance(_owner: address, _spender: address) -> uint256:
return self.token_address.allowance(_owner, _spender)
"""
return get_contract(erc20_caller_code, *[erc20.address])
def pad_bytes32(instr):
| 64 | 64 | 39 | 6 | 58 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | pad_bytes32 | pad_bytes32 | 63 | 65 | 63 | 63 | 941dd64fc8c3e272cc1e9f769bab99d192a93c77 | bigcode/the-stack | train |
62fc379ce99193d7a30f6b2e | train | function | def test_caller_approve_allowance(w3, erc20, erc20_caller):
assert erc20_caller.allowance(erc20.address, erc20_caller.address) == 0
assert erc20.approve(erc20_caller.address, 10, transact={})
assert erc20_caller.allowance(w3.eth.accounts[0], erc20_caller.address) == 10
| def test_caller_approve_allowance(w3, erc20, erc20_caller):
| assert erc20_caller.allowance(erc20.address, erc20_caller.address) == 0
assert erc20.approve(erc20_caller.address, 10, transact={})
assert erc20_caller.allowance(w3.eth.accounts[0], erc20_caller.address) == 10
| PLY))
# Negative transfer value.
assert_tx_failed(
function_to_test=lambda: erc20_caller.transfer(w3.eth.accounts[1], -1),
exception=ValidationError
)
def test_caller_approve_allowance(w3, erc20, erc20_caller):
| 64 | 64 | 93 | 21 | 43 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | test_caller_approve_allowance | test_caller_approve_allowance | 95 | 98 | 95 | 95 | 5307c2c891ce474938ed41ca353eea390d47cd55 | bigcode/the-stack | train |
52f7bfb2223c07bc36a8529f | train | function | def test_call_transfer(w3, erc20, erc20_caller, assert_tx_failed):
# Basic transfer.
erc20.transfer(erc20_caller.address, 10, transact={})
assert erc20.balanceOf(erc20_caller.address) == 10
erc20_caller.transfer(w3.eth.accounts[1], 10, transact={})
assert erc20.balanceOf(erc20_caller.address) == 0
... | def test_call_transfer(w3, erc20, erc20_caller, assert_tx_failed):
# Basic transfer.
| erc20.transfer(erc20_caller.address, 10, transact={})
assert erc20.balanceOf(erc20_caller.address) == 10
erc20_caller.transfer(w3.eth.accounts[1], 10, transact={})
assert erc20.balanceOf(erc20_caller.address) == 0
assert erc20.balanceOf(w3.eth.accounts[1]) == 10
# more than allowed
assert_t... | 32(TOKEN_NAME)
assert erc20_caller.symbol() == pad_bytes32(TOKEN_SYMBOL)
assert erc20_caller.decimals() == TOKEN_DECIMALS
def test_call_transfer(w3, erc20, erc20_caller, assert_tx_failed):
# Basic transfer.
| 64 | 64 | 189 | 26 | 37 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | test_call_transfer | test_call_transfer | 76 | 92 | 76 | 78 | 7159055c3be4051fca4a7f21bab5b463a433658a | bigcode/the-stack | train |
c060a0e5022736d6352aa3ab | train | function | def test_initial_state(w3, erc20_caller):
assert erc20_caller.totalSupply() == TOKEN_TOTAL_SUPPLY == erc20_caller.balanceOf(w3.eth.accounts[0])
assert erc20_caller.balanceOf(w3.eth.accounts[1]) == 0
assert erc20_caller.name() == pad_bytes32(TOKEN_NAME)
assert erc20_caller.symbol() == pad_bytes32(TOKEN_S... | def test_initial_state(w3, erc20_caller):
| assert erc20_caller.totalSupply() == TOKEN_TOTAL_SUPPLY == erc20_caller.balanceOf(w3.eth.accounts[0])
assert erc20_caller.balanceOf(w3.eth.accounts[1]) == 0
assert erc20_caller.name() == pad_bytes32(TOKEN_NAME)
assert erc20_caller.symbol() == pad_bytes32(TOKEN_SYMBOL)
assert erc20_caller.decimals() ... | erc20_caller_code, *[erc20.address])
def pad_bytes32(instr):
""" Pad a string \x00 bytes to return correct bytes32 representation. """
return instr + (32 - len(instr)) * b'\x00'
def test_initial_state(w3, erc20_caller):
| 64 | 64 | 113 | 13 | 51 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | test_initial_state | test_initial_state | 68 | 73 | 68 | 68 | b0f31fcae33a4801c9fd7d14e796ef1eb5617b2c | bigcode/the-stack | train |
2999241762c2e92e3ae26266 | train | function | def test_caller_tranfer_from(w3, erc20, erc20_caller, assert_tx_failed):
# Cannot transfer tokens that are unavailable
assert_tx_failed(lambda: erc20_caller.transferFrom(w3.eth.accounts[0], erc20_caller.address, 10))
assert erc20.balanceOf(erc20_caller.address) == 0
assert erc20.approve(erc20_caller.add... | def test_caller_tranfer_from(w3, erc20, erc20_caller, assert_tx_failed):
# Cannot transfer tokens that are unavailable
| assert_tx_failed(lambda: erc20_caller.transferFrom(w3.eth.accounts[0], erc20_caller.address, 10))
assert erc20.balanceOf(erc20_caller.address) == 0
assert erc20.approve(erc20_caller.address, 10, transact={})
erc20_caller.transferFrom(w3.eth.accounts[0], erc20_caller.address, 5, transact={})
assert e... | (erc20_caller.address, 10, transact={})
assert erc20_caller.allowance(w3.eth.accounts[0], erc20_caller.address) == 10
def test_caller_tranfer_from(w3, erc20, erc20_caller, assert_tx_failed):
# Cannot transfer tokens that are unavailable
| 74 | 74 | 248 | 34 | 39 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | test_caller_tranfer_from | test_caller_tranfer_from | 101 | 111 | 101 | 102 | 026532a60a6105cc8000ba64ed4e113216e702c6 | bigcode/the-stack | train |
d6322136ea60da22cab4b616 | train | function | @pytest.fixture
def erc20(get_contract):
with open('examples/tokens/vypercoin.v.py') as f:
contract = get_contract(f.read(), *[TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_INITIAL_SUPPLY])
return contract
| @pytest.fixture
def erc20(get_contract):
| with open('examples/tokens/vypercoin.v.py') as f:
contract = get_contract(f.read(), *[TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, TOKEN_INITIAL_SUPPLY])
return contract
| b"Vypercoin"
TOKEN_SYMBOL = b"FANG"
TOKEN_DECIMALS = 18
TOKEN_INITIAL_SUPPLY = (21 * 10 ** 6)
TOKEN_TOTAL_SUPPLY = TOKEN_INITIAL_SUPPLY * (10 ** TOKEN_DECIMALS)
@pytest.fixture
def erc20(get_contract):
| 64 | 64 | 56 | 10 | 54 | rohithpr/vyper | tests/parser/features/external_contracts/test_erc20_abi.py | Python | erc20 | erc20 | 12 | 16 | 12 | 13 | 31a13a7796048518a8a5c3a0aded241ec9d175f3 | bigcode/the-stack | train |
f1178d44e46bf89c23d00d13 | train | function | def export(export_dir,
pipeline_config,
checkpoint_path='',
asset_files=None,
verbose=False,
**redis_params):
"""Export model defined in pipeline_config_path.
Args:
export_dir: base directory where the model should be exported
pipeline_config: proto.Ea... | def export(export_dir,
pipeline_config,
checkpoint_path='',
asset_files=None,
verbose=False,
**redis_params):
| """Export model defined in pipeline_config_path.
Args:
export_dir: base directory where the model should be exported
pipeline_config: proto.EasyRecConfig instance or file path
specify proto.EasyRecConfig
checkpoint_path: if specified, will use this model instead of
model in model_dir in p... |
Raises:
AssertionError, if:
* pipeline_config_path does not exist
"""
pipeline_config = config_util.get_configs_from_pipeline_file(pipeline_config)
if pipeline_config.fg_json_path:
fg_util.load_fg_json_to_config(pipeline_config)
if data_path is not None:
logging.info('Predict on data: %s' ... | 256 | 256 | 939 | 28 | 227 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | export | export | 689 | 795 | 689 | 694 | c24fc79962a0fbf5fda8af92c157afa4e28dc694 | bigcode/the-stack | train |
8ddc00c77b03b2796fadb9ec | train | function | def _get_ckpt_path(pipeline_config, checkpoint_path):
if checkpoint_path != '' and checkpoint_path is not None:
ckpt_path = checkpoint_path
elif gfile.IsDirectory(pipeline_config.model_dir):
ckpt_path = tf.train.latest_checkpoint(pipeline_config.model_dir)
logging.info('checkpoint_path is not specified,... | def _get_ckpt_path(pipeline_config, checkpoint_path):
| if checkpoint_path != '' and checkpoint_path is not None:
ckpt_path = checkpoint_path
elif gfile.IsDirectory(pipeline_config.model_dir):
ckpt_path = tf.train.latest_checkpoint(pipeline_config.model_dir)
logging.info('checkpoint_path is not specified, '
'will use latest checkpoint %s fro... | use only])' % (
model_dir, model_dir)
else:
if not gfile.IsDirectory(model_dir):
logging.info('%s does not exists, create it automatically' % model_dir)
gfile.MakeDirs(model_dir)
def _get_ckpt_path(pipeline_config, checkpoint_path):
| 64 | 64 | 129 | 13 | 51 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _get_ckpt_path | _get_ckpt_path | 221 | 232 | 221 | 221 | d9987ededa8a97a7d2ff6f23d48ad7f9e57f00c2 | bigcode/the-stack | train |
698b1613233f8e90953a6015 | train | function | def predict(pipeline_config, checkpoint_path='', data_path=None):
"""Predict a EasyRec model defined in pipeline_config_path.
Predict the model defined in pipeline_config_path on the eval data.
Args:
pipeline_config: either EasyRecConfig path or its instance
checkpoint_path: if specified, will use this ... | def predict(pipeline_config, checkpoint_path='', data_path=None):
| """Predict a EasyRec model defined in pipeline_config_path.
Predict the model defined in pipeline_config_path on the eval data.
Args:
pipeline_config: either EasyRecConfig path or its instance
checkpoint_path: if specified, will use this model instead of
model specified by model_dir in pipeline_... | ))
with gfile.GFile(eval_result_file, 'w') as ofile:
result_to_write = {}
for key in sorted(eval_result):
# skip logging binary data
if isinstance(eval_result[key], six.binary_type):
continue
# convert numpy float to python float
result_to_write[key] = eval_resu... | 103 | 103 | 346 | 13 | 89 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | predict | predict | 647 | 686 | 647 | 647 | 777c0ece931f109d10879b8ef3fd54cb4c24d0af | bigcode/the-stack | train |
16a237521a609098d82fddce | train | function | def distribute_evaluate(pipeline_config,
eval_checkpoint_path='',
eval_data_path=None,
eval_result_filename='eval_result.txt'):
"""Evaluate a EasyRec model defined in pipeline_config_path.
Evaluate the model defined in pipeline_config_path on ... | def distribute_evaluate(pipeline_config,
eval_checkpoint_path='',
eval_data_path=None,
eval_result_filename='eval_result.txt'):
| """Evaluate a EasyRec model defined in pipeline_config_path.
Evaluate the model defined in pipeline_config_path on the eval data,
the metrics will be displayed on tensorboard and saved into eval_result.txt.
Args:
pipeline_config: either EasyRecConfig path or its instance
eval_checkpoint_path: if speci... | # with tf.device(
# replica_device_setter(
# worker_device='/job:master/task:0', cluster=cluster)):
eval_result = estimator.evaluate(
eval_spec.input_fn, eval_spec.steps, checkpoint_path=ckpt_path)
logging.info('Evaluate finish')
print('eval_result = ', eval_result)
logging.info('e... | 256 | 256 | 1,613 | 29 | 226 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | distribute_evaluate | distribute_evaluate | 477 | 644 | 477 | 480 | 6a77ad7365ca5e14c705e7dca845241cd34e97f8 | bigcode/the-stack | train |
ed13f80bdd5360373adf7f5a | train | function | def _train_and_evaluate_impl(pipeline_config, continue_train=False):
# Tempoary for EMR
if (not is_on_pai()) and 'TF_CONFIG' in os.environ:
print('===> 分布式环境配置...')
tf_config = json.loads(os.environ['TF_CONFIG'])
# for ps on emr currently evaluator is not supported
# the cluster has one chief instea... | def _train_and_evaluate_impl(pipeline_config, continue_train=False):
# Tempoary for EMR
| if (not is_on_pai()) and 'TF_CONFIG' in os.environ:
print('===> 分布式环境配置...')
tf_config = json.loads(os.environ['TF_CONFIG'])
# for ps on emr currently evaluator is not supported
# the cluster has one chief instead of master
# evaluation will not be done, so we replace chief with master
if 'clu... | .model_dir)
logging.info('checkpoint_path is not specified, '
'will use latest checkpoint %s from %s' %
(ckpt_path, pipeline_config.model_dir))
else:
assert False, 'pipeline_config.model_dir(%s) does not exist' \
% pipeline_config.model_dir
return ckpt_pat... | 256 | 256 | 946 | 23 | 232 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _train_and_evaluate_impl | _train_and_evaluate_impl | 257 | 348 | 257 | 258 | 06e6d8a833f136a0b014aa416db7d5bb47626400 | bigcode/the-stack | train |
f0a632bcc4424aaa19e51b87 | train | function | def evaluate(pipeline_config,
eval_checkpoint_path='',
eval_data_path=None,
eval_result_filename='eval_result.txt'):
"""Evaluate a EasyRec model defined in pipeline_config_path.
Evaluate the model defined in pipeline_config_path on the eval data,
the metrics will be display... | def evaluate(pipeline_config,
eval_checkpoint_path='',
eval_data_path=None,
eval_result_filename='eval_result.txt'):
| """Evaluate a EasyRec model defined in pipeline_config_path.
Evaluate the model defined in pipeline_config_path on the eval data,
the metrics will be displayed on tensorboard and saved into eval_result.txt.
Args:
pipeline_config: either EasyRecConfig path or its instance
eval_checkpoint_path: if speci... | with gfile.GFile(version_file, 'w') as f:
f.write(easy_rec.__version__ + '\n')
if gfile.Exists(master_stat_file):
gfile.Remove(master_stat_file)
train_steps = pipeline_config.train_config.num_steps
if train_steps <= 0:
train_steps = None
logging.warn('will train INFINITE number of steps')
... | 256 | 256 | 1,158 | 27 | 229 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | evaluate | evaluate | 351 | 474 | 351 | 354 | d0a8e349c5d9e66963bbf870aadcc2a49601bb81 | bigcode/the-stack | train |
e4a35f8d575871b85bc60e66 | train | function | def _create_eval_export_spec(pipeline_config, eval_data):
data_config = pipeline_config.data_config
# feature_configs = pipeline_config.feature_configs
feature_configs = config_util.get_compatible_feature_configs(pipeline_config)
eval_config = pipeline_config.eval_config
export_config = pipeline_config.export... | def _create_eval_export_spec(pipeline_config, eval_data):
| data_config = pipeline_config.data_config
# feature_configs = pipeline_config.feature_configs
feature_configs = config_util.get_compatible_feature_configs(pipeline_config)
eval_config = pipeline_config.eval_config
export_config = pipeline_config.export_config
if eval_config.num_examples > 0:
eval_steps ... | save_checkpoints_steps = train_config.save_checkpoints_steps
run_config = tf.estimator.RunConfig(
model_dir=pipeline_config.model_dir,
log_step_count_steps=train_config.log_step_count_steps,
save_summary_steps=train_config.save_summary_steps,
save_checkpoints_steps=save_checkpoints_steps,
... | 166 | 166 | 555 | 13 | 152 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _create_eval_export_spec | _create_eval_export_spec | 140 | 202 | 140 | 140 | 282b70a98723174ea5ab47b9dd3c799c4c55fd79 | bigcode/the-stack | train |
34b08e4491c34d1c722d9e84 | train | function | def _check_model_dir(model_dir, continue_train):
if not continue_train:
if not gfile.IsDirectory(model_dir):
gfile.MakeDirs(model_dir)
else:
assert len(gfile.Glob(model_dir + '/model.ckpt-*.meta')) == 0, \
'model_dir[=%s] already exists and not empty(if you ' \
'want to continu... | def _check_model_dir(model_dir, continue_train):
| if not continue_train:
if not gfile.IsDirectory(model_dir):
gfile.MakeDirs(model_dir)
else:
assert len(gfile.Glob(model_dir + '/model.ckpt-*.meta')) == 0, \
'model_dir[=%s] already exists and not empty(if you ' \
'want to continue train on current model_dir please ' \
... | feature_configs, eval_data)
eval_spec = tf.estimator.EvalSpec(
name='val',
input_fn=eval_input_fn,
steps=eval_steps,
throttle_secs=10,
exporters=exporters)
return eval_spec
def _check_model_dir(model_dir, continue_train):
| 64 | 64 | 155 | 11 | 52 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _check_model_dir | _check_model_dir | 205 | 218 | 205 | 205 | 012b26f486cb9456f92200742c150b78dbcfe88a | bigcode/the-stack | train |
22b13e22390ee0e1a417c1d3 | train | function | def _get_input_fn(data_config,
feature_configs,
data_path=None,
export_config=None):
"""Build estimator input function.
Args:
data_config: dataset config
feature_configs: FeatureConfig
data_path: input_data_path
export_config: configuration for... | def _get_input_fn(data_config,
feature_configs,
data_path=None,
export_config=None):
| """Build estimator input function.
Args:
data_config: dataset config
feature_configs: FeatureConfig
data_path: input_data_path
export_config: configuration for exporting models,
only used to build input_fn when exporting models
Returns:
subclass of Input
"""
print('===>data_config... | _axis_mask
# so temporarily modify strip_default_attrs of _SavedModelExporter in
# tf.estimator.exporter to false by default
FinalExporter = exporter.FinalExporter
LatestExporter = exporter.LatestExporter
BestExporter = exporter.BestExporter
def _get_input_fn(data_config,
feature_configs,
... | 73 | 73 | 245 | 22 | 50 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _get_input_fn | _get_input_fn | 62 | 93 | 62 | 65 | ea55894627982857d1ee43b12958f33e4a416441 | bigcode/the-stack | train |
a54be3d84df6199c5e41c0cc | train | function | def _create_estimator(pipeline_config, distribution=None, params={}):
print("===> _create_estimator()")
model_config = pipeline_config.model_config
train_config = pipeline_config.train_config
gpu_options = GPUOptions(allow_growth=False)
session_config = ConfigProto(
gpu_options=gpu_options,
allow_... | def _create_estimator(pipeline_config, distribution=None, params={}):
| print("===> _create_estimator()")
model_config = pipeline_config.model_config
train_config = pipeline_config.train_config
gpu_options = GPUOptions(allow_growth=False)
session_config = ConfigProto(
gpu_options=gpu_options,
allow_soft_placement=True,
log_device_placement=params.get('log_device... | .items()}
print('===>data_config.input_type: ' + str(data_config.input_type))
input_cls_name = input_class_map[data_config.input_type]
input_class = Input.create_class(input_cls_name)
print('===>input_class: ' + str(input_class))
task_id, task_num = estimator_utils.get_task_index_and_num()
input_obj = inpu... | 137 | 137 | 459 | 15 | 121 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | _create_estimator | _create_estimator | 96 | 137 | 96 | 96 | 1a3b9ab3d8e10ad9192e7db70d2f86975a738576 | bigcode/the-stack | train |
028a85bcbf992cf744847a34 | train | function | def train_and_evaluate(pipeline_config_path, continue_train=False):
"""Train and evaluate a EasyRec model defined in pipeline_config_path.
Build an EasyRecEstimator, and then train and evaluate the estimator.
Args:
pipeline_config_path: a path to EasyRecConfig object, specifies
train_config: model_confi... | def train_and_evaluate(pipeline_config_path, continue_train=False):
| """Train and evaluate a EasyRec model defined in pipeline_config_path.
Build an EasyRecEstimator, and then train and evaluate the estimator.
Args:
pipeline_config_path: a path to EasyRecConfig object, specifies
train_config: model_config, data_config and eval_config
continue_train: whether to restar... | s from %s' %
(ckpt_path, pipeline_config.model_dir))
else:
assert False, 'pipeline_config.model_dir(%s) does not exist' \
% pipeline_config.model_dir
return ckpt_path
def train_and_evaluate(pipeline_config_path, continue_train=False):
| 64 | 64 | 162 | 14 | 49 | Bfat-boy/EasyRec | easy_rec/python/main.py | Python | train_and_evaluate | train_and_evaluate | 235 | 254 | 235 | 235 | 5be8d1f9eaed173f40c36247c77da92ca3b69fe9 | bigcode/the-stack | train |
b32665452233c9b92628676d | train | class | class SensitiveDataFilterTest(TestCase):
def _check_vars_sanitized(self, vars, proc):
"""
Helper to check that keys have been sanitized.
"""
self.assertTrue('foo' in vars)
self.assertEquals(vars['foo'], 'bar')
self.assertTrue('password' in vars)
self.assertEq... | class SensitiveDataFilterTest(TestCase):
| def _check_vars_sanitized(self, vars, proc):
"""
Helper to check that keys have been sanitized.
"""
self.assertTrue('foo' in vars)
self.assertEquals(vars['foo'], 'bar')
self.assertTrue('password' in vars)
self.assertEquals(vars['password'], proc.MASK)
... | # -*- coding: utf-8 -*-
from sentry.testutils import TestCase
from sentry.utils.data_scrubber import SensitiveDataFilter
VARS = {
'foo': 'bar',
'password': 'hello',
'the_secret': 'hello',
'a_password_here': 'hello',
'api_key': 'secret_key',
'apiKey': 'secret_key',
}
class SensitiveDataFilterT... | 91 | 256 | 1,033 | 8 | 83 | ChadKillingsworth/sentry | tests/sentry/utils/test_data_scrubber.py | Python | SensitiveDataFilterTest | SensitiveDataFilterTest | 17 | 151 | 17 | 18 | 2a1b453318148d95c1c75c9968602875f41ae1c4 | bigcode/the-stack | train |
01c898297467c1d559d36152 | train | class | class SetAnnouncementHandler(webapp2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
# TODO 1
# use _cacheAnnouncement() to set announcement in Memcache
ConferenceApi._cacheAnnouncement()
self.response.set_status(204)
| class SetAnnouncementHandler(webapp2.RequestHandler):
| def get(self):
"""Set Announcement in Memcache."""
# TODO 1
# use _cacheAnnouncement() to set announcement in Memcache
ConferenceApi._cacheAnnouncement()
self.response.set_status(204)
| usr/bin/env python
import webapp2
from google.appengine.api import app_identity
from google.appengine.api import mail
from google.appengine.api import memcache
from conference import ConferenceApi
from conference import MEMCACHE_FEATURED_SPEAKER_KEY
class SetAnnouncementHandler(webapp2.RequestHandler):
| 64 | 64 | 58 | 10 | 53 | melliss67/lively-oxide-104800 | main.py | Python | SetAnnouncementHandler | SetAnnouncementHandler | 10 | 16 | 10 | 10 | f38bcbc8172502dcab50d039508de9289d8b8d0d | bigcode/the-stack | train |
fb6ac08c63188765ea745cce | train | class | class AddFeaturedSpeakerHandler(webapp2.RequestHandler):
def post(self):
"""add memcache entry for featured speaker"""
# memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY,
# '%s is our latest Featured Speaker' % 'Matt')
memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY,
... | class AddFeaturedSpeakerHandler(webapp2.RequestHandler):
| def post(self):
"""add memcache entry for featured speaker"""
# memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY,
# '%s is our latest Featured Speaker' % 'Matt')
memcache.set(MEMCACHE_FEATURED_SPEAKER_KEY,
'%s is our latest Featured Speaker' % self.request.get(
... | '), # to
'You created a new Conference!', # subj
'Hi, you have created a following ' # body
'conference:\r\n\r\n%s' % self.request.get(
'conferenceInfo')
)
class AddFeaturedSpeakerHandler(webapp2.RequestHandler):
| 64 | 64 | 91 | 11 | 53 | melliss67/lively-oxide-104800 | main.py | Python | AddFeaturedSpeakerHandler | AddFeaturedSpeakerHandler | 33 | 41 | 33 | 33 | 00fcb52c8c2d9e9b583cb8f0170e691779651633 | bigcode/the-stack | train |
994b3eee13bf0a3d35e3e091 | train | class | class SendConfirmationEmailHandler(webapp2.RequestHandler):
def post(self):
"""Send email confirming Conference creation."""
mail.send_mail(
'noreply@%s.appspotmail.com' % (
app_identity.get_application_id()), # from
self.request.get('email'), ... | class SendConfirmationEmailHandler(webapp2.RequestHandler):
| def post(self):
"""Send email confirming Conference creation."""
mail.send_mail(
'noreply@%s.appspotmail.com' % (
app_identity.get_application_id()), # from
self.request.get('email'), # to
'You created a new Conference!', ... | app2.RequestHandler):
def get(self):
"""Set Announcement in Memcache."""
# TODO 1
# use _cacheAnnouncement() to set announcement in Memcache
ConferenceApi._cacheAnnouncement()
self.response.set_status(204)
class SendConfirmationEmailHandler(webapp2.RequestHandler):
| 64 | 64 | 113 | 11 | 53 | melliss67/lively-oxide-104800 | main.py | Python | SendConfirmationEmailHandler | SendConfirmationEmailHandler | 19 | 30 | 19 | 19 | 5dfe3c3237a244c7bd542b81f3d694da809115d1 | bigcode/the-stack | train |
f19f98835757dd0a4fc09d3d | train | class | class LiveMigrationOpsTestCase(test_base.HyperVBaseTestCase):
"""Unit tests for the Hyper-V LiveMigrationOps class."""
def setUp(self):
super(LiveMigrationOpsTestCase, self).setUp()
self.context = 'fake_context'
self._livemigrops = livemigrationops.LiveMigrationOps()
self._livem... | class LiveMigrationOpsTestCase(test_base.HyperVBaseTestCase):
| """Unit tests for the Hyper-V LiveMigrationOps class."""
def setUp(self):
super(LiveMigrationOpsTestCase, self).setUp()
self.context = 'fake_context'
self._livemigrops = livemigrationops.LiveMigrationOps()
self._livemigrops._livemigrutils = mock.MagicMock()
self._livemig... | # Copyright 2014 Cloudbase Solutions Srl
# All Rights Reserved.
#
# 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 r... | 247 | 256 | 1,976 | 15 | 231 | lixiaoy1/nova | nova/tests/unit/virt/hyperv/test_livemigrationops.py | Python | LiveMigrationOpsTestCase | LiveMigrationOpsTestCase | 30 | 242 | 30 | 30 | 88ee2119348fc9d59932de1dc7229c01eb8193a8 | bigcode/the-stack | train |
215ba1c1e78cc87898a17f5d | train | class | class piece(ABC):
@abstractmethod
def get_valid_positions(self, board_positions, row, column):
pass
| class piece(ABC):
@abstractmethod
| def get_valid_positions(self, board_positions, row, column):
pass
| from abc import ABC, abstractmethod
class piece(ABC):
@abstractmethod
| 19 | 64 | 28 | 11 | 7 | nicolaspaquette/Projet-Synthese-Chess-GamByte | Dev/pieces_script/piece.py | Python | piece | piece | 3 | 7 | 3 | 5 | 437380d63423416bab003a640bdf40690453033b | bigcode/the-stack | train |
3f49bc78eca55b1162920cf2 | train | function | def newclient():
global serv2
global clients
global dx
try:
while True:
conn, addr = serv2.accept() #accept the connection
clients.append(conn)
if dx != "":
conn.send(dx) # HACK -- for faster detection
except KeyboardInterrupt:
s... | def newclient():
| global serv2
global clients
global dx
try:
while True:
conn, addr = serv2.accept() #accept the connection
clients.append(conn)
if dx != "":
conn.send(dx) # HACK -- for faster detection
except KeyboardInterrupt:
sys.exit(0)
| #!/usr/bin/python3
# author: Karel Fiala
# email: fiala.karel@gmail.com
from socket import *
from threading import Thread
import sys
BUFSIZE = 4096 # buffer size for data
def newclient():
| 56 | 64 | 73 | 4 | 51 | fialakarel/rpi-cam-proxy | rpi-cam-proxy.py | Python | newclient | newclient | 12 | 24 | 12 | 12 | bb8fab7ae93fa4e63fc370660ddd5768d73efef4 | bigcode/the-stack | train |
e8fdd90748d29709574a1ea2 | train | class | class ParquetSourceMapping(BaseSourceMapping):
_debug = False
class UprootLikeShim:
def __init__(self, source, column):
self.source = source
self.column = column
def array(self, entry_start, entry_stop):
import pyarrow as pa
aspa = self.source.r... | class ParquetSourceMapping(BaseSourceMapping):
| _debug = False
class UprootLikeShim:
def __init__(self, source, column):
self.source = source
self.column = column
def array(self, entry_start, entry_stop):
import pyarrow as pa
aspa = self.source.read(self.column)[entry_start:entry_stop][0].chu... | None else pqmeta.get(b"uuid", None)
pfn = None if pqmeta is None else pqmeta.get(b"url", None)
if str(pquuid) != uuid:
raise RuntimeError(
f"UUID of file {pfn} does not match expected value ({uuid})"
)
return TrivialParquetOpener.UprootLikeShim(parfile)
... | 256 | 256 | 1,003 | 9 | 246 | danbarto/coffea | coffea/nanoevents/mapping/parquet.py | Python | ParquetSourceMapping | ParquetSourceMapping | 75 | 193 | 75 | 75 | 782f539c447190be1240839ab877005dbaf975ec | bigcode/the-stack | train |
0e1d6aba142d10aabe68ffbd | train | class | class TrivialParquetOpener(UUIDOpener):
class UprootLikeShim:
def __init__(self, file, dataset):
self.file = file
self.dataset = dataset
def read(self, column_name):
# make sure uproot is single-core since our calling context might not be
return self.... | class TrivialParquetOpener(UUIDOpener):
| class UprootLikeShim:
def __init__(self, file, dataset):
self.file = file
self.dataset = dataset
def read(self, column_name):
# make sure uproot is single-core since our calling context might not be
return self.dataset.to_table(use_threads=False, colu... |
from collections.abc import Mapping
import awkward
import numpy
import json
from coffea.nanoevents.mapping.base import UUIDOpener, BaseSourceMapping
from coffea.nanoevents.util import quote, key_to_tuple, tuple_to_key
import pyarrow.dataset as ds
# IMPORTANT -> For now the uuid is just the uuid of the pfn.
# ... | 99 | 99 | 333 | 11 | 88 | danbarto/coffea | coffea/nanoevents/mapping/parquet.py | Python | TrivialParquetOpener | TrivialParquetOpener | 14 | 47 | 14 | 14 | 39788479d36986a99021b94c7c6ad20c3be9201e | bigcode/the-stack | train |
4bc1d31686447859ce1db87a | train | function | def arrow_schema_to_awkward_form(schema):
import pyarrow as pa
if isinstance(schema, (pa.lib.ListType, pa.lib.LargeListType)):
dtype = schema.value_type.to_pandas_dtype()()
return awkward.forms.ListOffsetForm(
offsets="i64",
content=awkward.forms.NumpyForm(
... | def arrow_schema_to_awkward_form(schema):
| import pyarrow as pa
if isinstance(schema, (pa.lib.ListType, pa.lib.LargeListType)):
dtype = schema.value_type.to_pandas_dtype()()
return awkward.forms.ListOffsetForm(
offsets="i64",
content=awkward.forms.NumpyForm(
inner_shape=[],
itemsiz... | None)
if str(pquuid) != uuid:
raise RuntimeError(
f"UUID of file {pfn} does not match expected value ({uuid})"
)
return TrivialParquetOpener.UprootLikeShim(parfile)
def arrow_schema_to_awkward_form(schema):
| 64 | 64 | 165 | 10 | 54 | danbarto/coffea | coffea/nanoevents/mapping/parquet.py | Python | arrow_schema_to_awkward_form | arrow_schema_to_awkward_form | 50 | 72 | 50 | 50 | e201932fb45dacf2172e7a7159af48b3d1bdf23b | bigcode/the-stack | train |
52d35bf490125b3046516262 | train | class | class EventForm(ModelForm):
class Meta:
model = Event
fields = [
'title',
'description',
'location',
'country'
]
| class EventForm(ModelForm):
| class Meta:
model = Event
fields = [
'title',
'description',
'location',
'country'
]
| from django import forms
from django.forms import ModelForm
from events.models import Comment
from events.models import Event
from tasks.models import Task
class EventForm(ModelForm):
| 36 | 64 | 37 | 6 | 29 | ralcabes/EventManager | eventmanager/events/forms.py | Python | EventForm | EventForm | 10 | 18 | 10 | 10 | 66bdf238d10e68464397f744c1b26f5b48cfb0fe | bigcode/the-stack | train |
26ed2c9bb17829796a33fbec | train | class | class CommentForm(ModelForm):
class Meta:
model = Comment
fields = [
'title',
'content'
]
| class CommentForm(ModelForm):
| class Meta:
model = Comment
fields = [
'title',
'content'
]
| Form
from events.models import Comment
from events.models import Event
from tasks.models import Task
class EventForm(ModelForm):
class Meta:
model = Event
fields = [
'title',
'description',
'location',
'country'
]
class CommentForm(ModelFor... | 63 | 64 | 29 | 6 | 57 | ralcabes/EventManager | eventmanager/events/forms.py | Python | CommentForm | CommentForm | 21 | 27 | 21 | 21 | e915793096ab4ec8cd58a8e84cb54633b19cdf07 | bigcode/the-stack | train |
1ce57d8476634981b6c5eb13 | train | class | class TaskForm(ModelForm):
class Meta:
model = Task
fields = [
'title',
'description',
'status',
'assignee'
]
| class TaskForm(ModelForm):
| class Meta:
model = Task
fields = [
'title',
'description',
'status',
'assignee'
]
| model = Event
fields = [
'title',
'description',
'location',
'country'
]
class CommentForm(ModelForm):
class Meta:
model = Comment
fields = [
'title',
'content'
]
class TaskForm(ModelForm):
| 63 | 64 | 38 | 6 | 57 | ralcabes/EventManager | eventmanager/events/forms.py | Python | TaskForm | TaskForm | 30 | 39 | 30 | 31 | 8846710b932fc306bbfa017f72386efa47c0d42c | bigcode/the-stack | train |
fe77ae74c9b0199de40cb5dc | train | class | class VisibilitySettings(forms.Form):
Options = (
('1', 'Public'),
('2', 'Logged users only'),
('3', 'Invited only'),
)
visibility = forms.ChoiceField(
label='Choose event visibility',
widget=forms.Select,
choices=Options)
class Meta:
fields = [
... | class VisibilitySettings(forms.Form):
| Options = (
('1', 'Public'),
('2', 'Logged users only'),
('3', 'Invited only'),
)
visibility = forms.ChoiceField(
label='Choose event visibility',
widget=forms.Select,
choices=Options)
class Meta:
fields = [
'visibility',
]
| model = Comment
fields = [
'title',
'content'
]
class TaskForm(ModelForm):
class Meta:
model = Task
fields = [
'title',
'description',
'status',
'assignee'
]
class VisibilitySettings(forms.Form):
| 63 | 64 | 76 | 6 | 57 | ralcabes/EventManager | eventmanager/events/forms.py | Python | VisibilitySettings | VisibilitySettings | 42 | 56 | 42 | 42 | b4121c9b40f05d1c0ccba9dfedd96b5d18f8b541 | bigcode/the-stack | train |
85922d22ddae366d76dd4f6a | train | class | class DbGateway(DbGatewayABC):
def __init__(self, db_name: str, echo: bool = False) -> None:
self.engine = create_engine(db_name, echo=echo)
self.session = sessionmaker(bind=self.engine)()
def fetch_playlist_by_date(self, playlist_date: date) -> Optional[Playlist]:
query = self.session... | class DbGateway(DbGatewayABC):
| def __init__(self, db_name: str, echo: bool = False) -> None:
self.engine = create_engine(db_name, echo=echo)
self.session = sessionmaker(bind=self.engine)()
def fetch_playlist_by_date(self, playlist_date: date) -> Optional[Playlist]:
query = self.session.query(SqlPlaylist).filter(SqlPl... | date
from typing import Optional
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from playlists.abc import DbGateway as DbGatewayABC
from playlists.definitions import MusicProviderPlaylist, Playlist
from playlists.gateways.db_gateway.models import Base, SqlPlaylist
class DbGateway(DbGate... | 64 | 64 | 192 | 7 | 56 | zhammer/morning-cd-playlists | playlists/gateways/db_gateway/db_gateway.py | Python | DbGateway | DbGateway | 12 | 32 | 12 | 13 | b24bc7ea9f0bb215c36882b3a0df526e42cba6ee | bigcode/the-stack | train |
bfbf4f6f64b9632b0b69e5d6 | train | function | def _pluck_playlist(sql_playlist: SqlPlaylist) -> Playlist:
return Playlist(
id=sql_playlist.id,
playlist_date=sql_playlist.playlist_date,
music_provider_playlist_id=sql_playlist.music_provider_playlist_id,
music_provider=sql_playlist.music_provider
)
| def _pluck_playlist(sql_playlist: SqlPlaylist) -> Playlist:
| return Playlist(
id=sql_playlist.id,
playlist_date=sql_playlist.playlist_date,
music_provider_playlist_id=sql_playlist.music_provider_playlist_id,
music_provider=sql_playlist.music_provider
)
| _playlist: MusicProviderPlaylist,
playlist_date: date) -> SqlPlaylist:
return SqlPlaylist(
playlist_date=playlist_date,
music_provider=music_provider_playlist.music_provider,
music_provider_playlist_id=music_provider_playlist.id
)
def _pluck_playlist(sql_playlist:... | 64 | 64 | 58 | 13 | 51 | zhammer/morning-cd-playlists | playlists/gateways/db_gateway/db_gateway.py | Python | _pluck_playlist | _pluck_playlist | 44 | 50 | 44 | 44 | f0425176edf55e8204fbedd69713520039a9ff1c | bigcode/the-stack | train |
1ea1a6964eceee48add6f0cf | train | function | def _build_sql_playlist(music_provider_playlist: MusicProviderPlaylist,
playlist_date: date) -> SqlPlaylist:
return SqlPlaylist(
playlist_date=playlist_date,
music_provider=music_provider_playlist.music_provider,
music_provider_playlist_id=music_provider_playlist.id
... | def _build_sql_playlist(music_provider_playlist: MusicProviderPlaylist,
playlist_date: date) -> SqlPlaylist:
| return SqlPlaylist(
playlist_date=playlist_date,
music_provider=music_provider_playlist.music_provider,
music_provider_playlist_id=music_provider_playlist.id
)
| )
self.session.commit()
return _pluck_playlist(sql_playlist)
def persist_schema(self) -> None:
"""Not part of DbGatewayABC."""
Base.metadata.create_all(self.engine)
def _build_sql_playlist(music_provider_playlist: MusicProviderPlaylist,
playlist_date: date) -... | 64 | 64 | 59 | 24 | 40 | zhammer/morning-cd-playlists | playlists/gateways/db_gateway/db_gateway.py | Python | _build_sql_playlist | _build_sql_playlist | 35 | 41 | 35 | 36 | 8999998168b586b3fbc05755d4fe7ca4c6475acb | bigcode/the-stack | train |
815df72fe561fc1df17175a6 | train | class | class MessageActionSerializer(serializers.ModelSerializer):
class Meta:
model = MessageAction
fields = "__all__"
| class MessageActionSerializer(serializers.ModelSerializer):
| class Meta:
model = MessageAction
fields = "__all__"
| Action,
ForwardedMessage,
)
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = "__all__"
class ThreadMemberSerializer(serializers.ModelSerializer):
class Meta:
model = ThreadMember
fields = "__all__"
class MessageActionSerializer(se... | 64 | 64 | 25 | 8 | 56 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | MessageActionSerializer | MessageActionSerializer | 24 | 27 | 24 | 24 | c07ff211af7308271e50e7fe43674b623aa5dd04 | bigcode/the-stack | train |
bcb8a5e9259f1261e55c9de1 | train | class | class ForwardedMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ForwardedMessage
fields = "__all__"
| class ForwardedMessageSerializer(serializers.ModelSerializer):
| class Meta:
model = ForwardedMessage
fields = "__all__"
| fields = "__all__"
class MessageActionSerializer(serializers.ModelSerializer):
class Meta:
model = MessageAction
fields = "__all__"
class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = "__all__"
class ForwardedMessageSerializer(seri... | 64 | 64 | 27 | 9 | 55 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | ForwardedMessageSerializer | ForwardedMessageSerializer | 36 | 39 | 36 | 36 | 30f9e80d0b41d56ed7258975801e9219e6040481 | bigcode/the-stack | train |
f13406b724657e5e8c878bd8 | train | class | class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = "__all__"
| class MessageSerializer(serializers.ModelSerializer):
| class Meta:
model = Message
fields = "__all__"
| from rest_framework import serializers
from chat.models import (
MessageAction,
ThreadMember,
Thread,
Message,
ThreadAction,
ForwardedMessage,
)
class MessageSerializer(serializers.ModelSerializer):
| 42 | 64 | 23 | 7 | 35 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | MessageSerializer | MessageSerializer | 12 | 15 | 12 | 12 | 3ef2f21da3e410a56a5be3d20c21773bda5b69f7 | bigcode/the-stack | train |
c2565a92046dd96ce019aa1a | train | class | class ThreadActionSerializer(serializers.ModelSerializer):
class Meta:
model = ThreadAction
fields = "__all__"
| class ThreadActionSerializer(serializers.ModelSerializer):
| class Meta:
model = ThreadAction
fields = "__all__"
| fields = "__all__"
class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = "__all__"
class ForwardedMessageSerializer(serializers.ModelSerializer):
class Meta:
model = ForwardedMessage
fields = "__all__"
class ThreadActionSerializer(serialize... | 64 | 64 | 25 | 8 | 56 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | ThreadActionSerializer | ThreadActionSerializer | 42 | 45 | 42 | 42 | 46c0f7ac8198d83a1fa601c2c8c2b5b063ace513 | bigcode/the-stack | train |
2a3d296e82eee655b9c312bd | train | class | class ThreadMemberSerializer(serializers.ModelSerializer):
class Meta:
model = ThreadMember
fields = "__all__"
| class ThreadMemberSerializer(serializers.ModelSerializer):
| class Meta:
model = ThreadMember
fields = "__all__"
| _framework import serializers
from chat.models import (
MessageAction,
ThreadMember,
Thread,
Message,
ThreadAction,
ForwardedMessage,
)
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = "__all__"
class ThreadMemberSerializer(serializ... | 64 | 64 | 25 | 8 | 56 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | ThreadMemberSerializer | ThreadMemberSerializer | 18 | 21 | 18 | 18 | 56eef27e2bfa93dad9eab7ca35728533efb9aae5 | bigcode/the-stack | train |
c4185749a8828c21f7119505 | train | class | class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = "__all__"
| class ThreadSerializer(serializers.ModelSerializer):
| class Meta:
model = Thread
fields = "__all__"
| fields = "__all__"
class ThreadMemberSerializer(serializers.ModelSerializer):
class Meta:
model = ThreadMember
fields = "__all__"
class MessageActionSerializer(serializers.ModelSerializer):
class Meta:
model = MessageAction
fields = "__all__"
class ThreadSerializer(se... | 64 | 64 | 23 | 7 | 57 | crowdbotics-apps/agileevac-31534 | backend/chat/api/v1/serializers.py | Python | ThreadSerializer | ThreadSerializer | 30 | 33 | 30 | 30 | 30629977b20522121b33a3dafacd18e8106405ca | bigcode/the-stack | train |
093cc0dc39e1e11c27be142a | train | function | def update_param(name, param):
if name == 'data_leakage_handling':
param['values'] = ["leave_one_out", "k_fold", "none", "LeaveOneOut", "KFold", "None"]
return param
return None # param untouched
| def update_param(name, param):
| if name == 'data_leakage_handling':
param['values'] = ["leave_one_out", "k_fold", "none", "LeaveOneOut", "KFold", "None"]
return param
return None # param untouched
| def update_param(name, param):
| 7 | 64 | 61 | 7 | 0 | stefanbuck/h2o-3 | h2o-bindings/bin/custom/R/gen_targetencoder.py | Python | update_param | update_param | 1 | 5 | 1 | 1 | 712990645a419d23bc3d7d9c86ae052718e795b3 | bigcode/the-stack | train |
e3559687420d3442be47627d | train | function | def get_prodgen_func(dsformat, dsname, dstype):
"""
maps the dataset format into its processing function
Parameters
----------
dsformat : str
dataset group. The following is a list of dataset groups with the
function that is called to generate their products. For details about
... | def get_prodgen_func(dsformat, dsname, dstype):
| """
maps the dataset format into its processing function
Parameters
----------
dsformat : str
dataset group. The following is a list of dataset groups with the
function that is called to generate their products. For details about
what the functions do check the function docu... | _cosmo_coord_products
from .process_product import generate_occurrence_products
from .process_product import generate_qvp_products
from .process_product import generate_ml_products
from .process_product import generate_cosmo_to_radar_products
from .process_vol_products import generate_vol_products
from .process_grid_p... | 192 | 192 | 642 | 14 | 177 | jfigui/pyrad | src/pyrad_proc/pyrad/prod/product_aux.py | Python | get_prodgen_func | get_prodgen_func | 33 | 106 | 33 | 33 | 0237f3e3cba3784b7f68522e4c978030a7e489d8 | bigcode/the-stack | train |
edceb9e47d7eece8baa5a3fd | train | class | class MyClient(discpy.Client):
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = f'Welcome {member.mention} to ... | class MyClient(discpy.Client):
| async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
async def on_member_join(self, member):
guild = member.guild
if guild.system_channel is not None:
to_send = f'Welcome {member.mention} to {guild.name}!'
awai... | # This example requires the 'members' privileged intents
import discpy
class MyClient(discpy.Client):
| 23 | 64 | 92 | 8 | 14 | DiscPy/DiscPy | examples/new_member.py | Python | MyClient | MyClient | 5 | 14 | 5 | 5 | 5492d2265c0cde26df5b37a0a2950b96c87bf77c | bigcode/the-stack | train |
2bfda62c1f6ac687acfc8bb3 | train | class | class IndividualTDE(BaseClassifier):
"""Single TDE classifier, an extension of the Bag of SFA Symbols (BOSS) model.
Base classifier for the TDE classifier. Implementation of single TDE base model
from Middlehurst (2021). [1]_
Overview: input "n" series of length "m" and IndividualTDE performs a SFA
... | class IndividualTDE(BaseClassifier):
| """Single TDE classifier, an extension of the Bag of SFA Symbols (BOSS) model.
Base classifier for the TDE classifier. Implementation of single TDE base model
from Middlehurst (2021). [1]_
Overview: input "n" series of length "m" and IndividualTDE performs a SFA
transform to form a sparse dictiona... | )
if divisors[i] == 0
else results[i] / (np.ones(self.n_classes) * divisors[i])
)
return results
def _individual_train_acc(self, tde, y, train_size, lowest_acc):
correct = 0
required_correct = int(lowest_acc * train_size)
if self.n_jobs ... | 256 | 256 | 2,430 | 7 | 248 | BINAYKUMAR943/sktime | sktime/classification/dictionary_based/_tde.py | Python | IndividualTDE | IndividualTDE | 481 | 803 | 481 | 481 | 0046a96562cf443956f4aea996363b35a2ac59bc | bigcode/the-stack | train |
ca6c5258b5a6610081abfb8b | train | class | class TemporalDictionaryEnsemble(BaseClassifier):
"""Temporal Dictionary Ensemble (TDE).
Implementation of the dictionary based Temporal Dictionary Ensemble as described
in [1]_.
Overview: Input "n" series length "m" with "d" dimensions
TDE searches "k" parameter values selected using a Gaussian p... | class TemporalDictionaryEnsemble(BaseClassifier):
| """Temporal Dictionary Ensemble (TDE).
Implementation of the dictionary based Temporal Dictionary Ensemble as described
in [1]_.
Overview: Input "n" series length "m" with "d" dimensions
TDE searches "k" parameter values selected using a Gaussian processes
regressor, evaluating each with a LOO... | # -*- coding: utf-8 -*-
"""TDE classifiers.
Dictionary based TDE classifiers based on SFA transform. Contains a single
IndividualTDE and TDE.
"""
__author__ = "MatthewMiddlehurst"
__all__ = ["TemporalDictionaryEnsemble", "IndividualTDE", "histogram_intersection"]
import math
import time
from collections import defau... | 191 | 256 | 3,622 | 8 | 182 | BINAYKUMAR943/sktime | sktime/classification/dictionary_based/_tde.py | Python | TemporalDictionaryEnsemble | TemporalDictionaryEnsemble | 30 | 478 | 30 | 30 | 08dc8f138743c20eaf5c6b4aca042feb64136a27 | bigcode/the-stack | train |
bc6eff0260faca7ee9da568a | train | function | def histogram_intersection(first, second):
"""Find the distance between two histograms using the histogram intersection.
This distance function is designed for sparse matrix, represented as a
dictionary or numba Dict, but can accept arrays.
Parameters
----------
first : dict, numba.Dict or arr... | def histogram_intersection(first, second):
| """Find the distance between two histograms using the histogram intersection.
This distance function is designed for sparse matrix, represented as a
dictionary or numba Dict, but can accept arrays.
Parameters
----------
first : dict, numba.Dict or array
First dictionary used in distanc... | None
for n, bag in enumerate(bags):
if n == train_num:
continue
sim = histogram_intersection(test_bag, bag)
if sim > best_sim:
best_sim = sim
nn = self._class_vals[n]
return nn
def histogram_intersection(first, seco... | 68 | 68 | 229 | 8 | 59 | BINAYKUMAR943/sktime | sktime/classification/dictionary_based/_tde.py | Python | histogram_intersection | histogram_intersection | 806 | 838 | 806 | 806 | b03f3539e53f87802d96b897542df2fab061bc2a | bigcode/the-stack | train |
1019014ab488e7ecb657b290 | train | function | @njit(fastmath=True)
def _histogram_intersection_dict(first, second):
sim = 0
for word, val_a in first.items():
val_b = second.get(word, types.uint32(0))
sim += min(val_a, val_b)
return sim
| @njit(fastmath=True)
def _histogram_intersection_dict(first, second):
| sim = 0
for word, val_a in first.items():
val_b = second.get(word, types.uint32(0))
sim += min(val_a, val_b)
return sim
| (first, second)
else:
return np.sum(
[
0 if first[n] == 0 else np.min(first[n], second[n])
for n in range(len(first))
]
)
@njit(fastmath=True)
def _histogram_intersection_dict(first, second):
| 64 | 64 | 63 | 19 | 45 | BINAYKUMAR943/sktime | sktime/classification/dictionary_based/_tde.py | Python | _histogram_intersection_dict | _histogram_intersection_dict | 841 | 847 | 841 | 842 | fc41905c84feb7e0a7e4004fbf37158c5dbe29bf | bigcode/the-stack | train |
72cd1144eb119ff9a773d0da | train | function | def registryget_regkey_field_namevalue_pairs(key_object: RegistryKey):
"""For a given RegistryKey object, returns a list of the field (name, value) pairs within that key.
Examples:
>>> import Registry\n
>>> reghive = Registry.Registry.Registry('SOFTWARE')\n
>>> # Below, because our ... | def registryget_regkey_field_namevalue_pairs(key_object: RegistryKey):
| """For a given RegistryKey object, returns a list of the field (name, value) pairs within that key.
Examples:
>>> import Registry\n
>>> reghive = Registry.Registry.Registry('SOFTWARE')\n
>>> # Below, because our registry key's path already contains escaped '\\' backslashes we are no... | # %%
#######################################
def registryget_regkey_field_namevalue_pairs(key_object: RegistryKey):
| 20 | 220 | 735 | 15 | 5 | SecTraversl/python_registry_Tools | registryget_regkey_field_namevalue_pairs.py | Python | registryget_regkey_field_namevalue_pairs | registryget_regkey_field_namevalue_pairs | 3 | 36 | 3 | 3 | c0f41f034583b6ed0e63ec8b72b7fbb1145a513c | bigcode/the-stack | train |
57bceb78d12cac7def286767 | train | function | def glsl_compress(s, shortNames):
# strip leading whitespace
s = re.sub(r'\A\s+', '', s)
# strip trailing whitespace
s = re.sub(r'\s+\Z', '', s)
# strip multi-line comments
s = re.sub(r'/\*.*?\*/', '', s)
# strip single line comments
s = re.sub(r'//.*?\n', '', s)
# replace multiple w... | def glsl_compress(s, shortNames):
# strip leading whitespace
| s = re.sub(r'\A\s+', '', s)
# strip trailing whitespace
s = re.sub(r'\s+\Z', '', s)
# strip multi-line comments
s = re.sub(r'/\*.*?\*/', '', s)
# strip single line comments
s = re.sub(r'//.*?\n', '', s)
# replace multiple whitespace with a single space
s = re.sub(r'\s+', ' ', s)
... | _SEQUENCE = {
'\\': '\\\\',
'\n': '\\n',
'\t': '\\t'
}
def js_escape(s):
return ''.join(ESCAPE_SEQUENCE.get(c, c) for c in s)
def glsl_compress(s, shortNames):
# strip leading whitespace
| 64 | 64 | 212 | 16 | 48 | dbca-wa/ol3 | bin/pyglslunit.py | Python | glsl_compress | glsl_compress | 21 | 38 | 21 | 22 | 4c12e2c54950882b048d38638c4c02ec87fcf8f1 | bigcode/the-stack | train |
5a5a6382f6529e9c15ee64c6 | train | function | def js_escape(s):
return ''.join(ESCAPE_SEQUENCE.get(c, c) for c in s)
| def js_escape(s):
| return ''.join(ESCAPE_SEQUENCE.get(c, c) for c in s)
| #!/usr/bin/python
from optparse import OptionParser
import json
import re
import sys
ESCAPE_SEQUENCE = {
'\\': '\\\\',
'\n': '\\n',
'\t': '\\t'
}
def js_escape(s):
| 53 | 64 | 23 | 5 | 48 | dbca-wa/ol3 | bin/pyglslunit.py | Python | js_escape | js_escape | 17 | 18 | 17 | 17 | 7ebf1b3c8c7b2eaf3979576ed890331ba448d3f7 | bigcode/the-stack | train |
8f206dd09b8e8d9bf9ff9247 | train | function | def main(argv):
option_parser = OptionParser()
option_parser.add_option('--input')
option_parser.add_option('--output')
options, args = option_parser.parse_args(argv[1:])
context = {}
nextShortName = ord('a')
shortNames = {}
common, vertex, fragment = [], [], []
attributes, uniform... | def main(argv):
| option_parser = OptionParser()
option_parser.add_option('--input')
option_parser.add_option('--output')
options, args = option_parser.parse_args(argv[1:])
context = {}
nextShortName = ord('a')
shortNames = {}
common, vertex, fragment = [], [], []
attributes, uniforms, varyings = {}... | _compress(s, shortNames):
# strip leading whitespace
s = re.sub(r'\A\s+', '', s)
# strip trailing whitespace
s = re.sub(r'\s+\Z', '', s)
# strip multi-line comments
s = re.sub(r'/\*.*?\*/', '', s)
# strip single line comments
s = re.sub(r'//.*?\n', '', s)
# replace multiple whitespac... | 213 | 213 | 713 | 4 | 208 | dbca-wa/ol3 | bin/pyglslunit.py | Python | main | main | 41 | 116 | 41 | 41 | 17a02e3f11c3d8d7bd7873affdb494951ec04585 | bigcode/the-stack | train |
1d74f741486e1e20d586bfd3 | train | class | class RedisStore(Store):
def __init__(self, storage_engine):
Store.__init__(self)
self._storage_engine = storage_engine
@property
def storage_engine(self):
return self._storage_engine
def commit(self, commit=True):
del commit
pass # pragma: no cover
def... | class RedisStore(Store):
| def __init__(self, storage_engine):
Store.__init__(self)
self._storage_engine = storage_engine
@property
def storage_engine(self):
return self._storage_engine
def commit(self, commit=True):
del commit
pass # pragma: no cover
def delete(self, key):
... | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from programy.storage.entities.store import Store
class RedisStore(Store):
| 64 | 64 | 173 | 5 | 58 | cdoebler1/AIML2 | src/programy/storage/stores/nosql/redis/store/redisstore.py | Python | RedisStore | RedisStore | 20 | 49 | 20 | 21 | c7ef79ca737bd865711dd29849cfd95e111f5493 | bigcode/the-stack | train |
c0406f03b070109aa38878be | train | class | class Smileys(registry.Value):
def set(self, s):
L = s.split()
self.setValue(L)
def setValue(self, v):
self._lastModified = registry.monotonic_time()
self.s = ' '.join(v)
self.value = re.compile('|'.join(map(re.escape, v)))
def __str__(self):
return self.s
| class Smileys(registry.Value):
| def set(self, s):
L = s.split()
self.setValue(L)
def setValue(self, v):
self._lastModified = registry.monotonic_time()
self.s = ' '.join(v)
self.value = re.compile('|'.join(map(re.escape, v)))
def __str__(self):
return self.s
| whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions import expect, anything, something, yn
conf.registerPlugin('ChannelStats', True)
class Smileys(registry.Value):
| 64 | 64 | 82 | 7 | 57 | nemchik/Limnoria | plugins/ChannelStats/config.py | Python | Smileys | Smileys | 47 | 58 | 47 | 47 | af75796212b58e79b3d62e31b2b2ffd318f29dbf | bigcode/the-stack | train |
bc1b2ebc37fd4940f06ed0ec | train | function | def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
from supybot.questions impo... | def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
| from supybot.questions import expect, anything, something, yn
conf.registerPlugin('ChannelStats', True)
| Stats')
def configure(advanced):
# This will be called by supybot to configure this module. advanced is
# a bool that specifies whether the user identified themself as an advanced
# user or not. You should effect your configuration by manipulating the
# registry as appropriate.
| 64 | 64 | 87 | 62 | 2 | nemchik/Limnoria | plugins/ChannelStats/config.py | Python | configure | configure | 39 | 45 | 39 | 43 | fefbcbad760993fa9c6d80e1bfa4927e78db3b40 | bigcode/the-stack | train |
ca3e6beb0287809105e016bf | train | function | def clamp(value: float) -> float:
"""Clamp value to the range 0..255."""
return min(max(value, 0), 255)
| def clamp(value: float) -> float:
| """Clamp value to the range 0..255."""
return min(max(value, 0), 255)
| discovery_hash=discovery_hash)]
)
hass.data[
DATA_REMOVE_DISCOVER_COMPONENT.format(light.DOMAIN)
] = async_dispatcher_connect(
hass,
TASMOTA_DISCOVERY_ENTITY_NEW.format(light.DOMAIN),
async_discover,
)
def clamp(value: float) -> float:
| 64 | 64 | 33 | 9 | 55 | basicpail/core | homeassistant/components/tasmota/light.py | Python | clamp | clamp | 73 | 75 | 73 | 73 | 553f72776dc4c06ef747ae1c6679464018f3eb73 | bigcode/the-stack | train |
57a47f4665297ed53f06ab5c | train | function | def scale_brightness(brightness: float) -> float:
"""Scale brightness from 0..255 to 1..100."""
brightness_normalized = brightness / DEFAULT_BRIGHTNESS_MAX
device_brightness = min(
round(brightness_normalized * TASMOTA_BRIGHTNESS_MAX),
TASMOTA_BRIGHTNESS_MAX,
)
# Make sure the bright... | def scale_brightness(brightness: float) -> float:
| """Scale brightness from 0..255 to 1..100."""
brightness_normalized = brightness / DEFAULT_BRIGHTNESS_MAX
device_brightness = min(
round(brightness_normalized * TASMOTA_BRIGHTNESS_MAX),
TASMOTA_BRIGHTNESS_MAX,
)
# Make sure the brightness is not rounded down to 0
return max(devic... | ASMOTA_DISCOVERY_ENTITY_NEW.format(light.DOMAIN),
async_discover,
)
def clamp(value: float) -> float:
"""Clamp value to the range 0..255."""
return min(max(value, 0), 255)
def scale_brightness(brightness: float) -> float:
| 64 | 64 | 99 | 13 | 51 | basicpail/core | homeassistant/components/tasmota/light.py | Python | scale_brightness | scale_brightness | 78 | 86 | 78 | 78 | d2415e47e5dad2857450c25cc2d81b449ed8f1cc | bigcode/the-stack | train |
33a65069e6404b1744c9d5dc | train | function | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Tasmota light dynamically through discovery."""
@callback
def async_discover(
tasmota_entity: HATasmotaEntity, discovery_hash: DiscoveryHashType
... | async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
| """Set up Tasmota light dynamically through discovery."""
@callback
def async_discover(
tasmota_entity: HATasmotaEntity, discovery_hash: DiscoveryHashType
) -> None:
"""Discover and add a Tasmota light."""
async_add_entities(
[TasmotaLight(tasmota_entity=tasmota_enti... | asmotaDiscoveryUpdate, TasmotaOnOffEntity
DEFAULT_BRIGHTNESS_MAX = 255
TASMOTA_BRIGHTNESS_MAX = 100
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
| 64 | 64 | 164 | 32 | 31 | basicpail/core | homeassistant/components/tasmota/light.py | Python | async_setup_entry | async_setup_entry | 48 | 70 | 48 | 52 | ac9ca461a78b1654b4e1c9e2988a2dd4eb3ee3ba | bigcode/the-stack | train |
b0fc89bf1afc68e32362e187 | train | class | class TasmotaLight(
TasmotaAvailability,
TasmotaDiscoveryUpdate,
TasmotaOnOffEntity,
LightEntity,
):
"""Representation of a Tasmota light."""
_tasmota_entity: tasmota_light.TasmotaLight
def __init__(self, **kwds: Any) -> None:
"""Initialize Tasmota light."""
self._supported... | class TasmotaLight(
TasmotaAvailability,
TasmotaDiscoveryUpdate,
TasmotaOnOffEntity,
LightEntity,
):
| """Representation of a Tasmota light."""
_tasmota_entity: tasmota_light.TasmotaLight
def __init__(self, **kwds: Any) -> None:
"""Initialize Tasmota light."""
self._supported_color_modes: set[str] | None = None
self._supported_features = 0
self._brightness: int | None = Non... |
) -> None:
"""Discover and add a Tasmota light."""
async_add_entities(
[TasmotaLight(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)]
)
hass.data[
DATA_REMOVE_DISCOVER_COMPONENT.format(light.DOMAIN)
] = async_dispatcher_connect(
hass,
... | 256 | 256 | 1,634 | 32 | 224 | basicpail/core | homeassistant/components/tasmota/light.py | Python | TasmotaLight | TasmotaLight | 89 | 288 | 89 | 94 | e6bae6212bd4bb39a3ac9d6e1b24a1f495ae6204 | bigcode/the-stack | train |
dbfa4004b2872fb29cb51637 | train | function | @contextmanager
def tmp_environ(**kwargs):
orig_values = {}
for key, value in kwargs.items():
orig_values[key] = os.environ.get(key)
os.environ[key] = value
try:
yield
finally:
for key, value in kwargs.items():
orig_value = orig_values[key]
if orig... | @contextmanager
def tmp_environ(**kwargs):
| orig_values = {}
for key, value in kwargs.items():
orig_values[key] = os.environ.get(key)
os.environ[key] = value
try:
yield
finally:
for key, value in kwargs.items():
orig_value = orig_values[key]
if orig_value is not None:
os.envi... | import sys
import time
import io
import os
import argparse
import json
from contextlib import contextmanager
import ir_datasets
_logger = ir_datasets.log.easy()
@contextmanager
def tmp_environ(**kwargs):
| 49 | 64 | 96 | 11 | 38 | tuberj/ir_datasets | ir_datasets/commands/build_download_cache.py | Python | tmp_environ | tmp_environ | 14 | 28 | 14 | 15 | 1657091e3e68078eddf1b047764002226ee4995a | bigcode/the-stack | train |
6e50887e0938e14e92954c52 | train | function | def _build_cache(data, dir, prefix=''):
if 'url' in data and 'expected_md5' in data:
cache_path = f'{dir}/{data["expected_md5"]}'
if os.path.exists(cache_path):
_logger.info(f'skipping {prefix}; already exists')
return
try:
with ir_datasets.util.finialized... | def _build_cache(data, dir, prefix=''):
| if 'url' in data and 'expected_md5' in data:
cache_path = f'{dir}/{data["expected_md5"]}'
if os.path.exists(cache_path):
_logger.info(f'skipping {prefix}; already exists')
return
try:
with ir_datasets.util.finialized_file(cache_path, 'wb') as fout, _logger... | ():
orig_values[key] = os.environ.get(key)
os.environ[key] = value
try:
yield
finally:
for key, value in kwargs.items():
orig_value = orig_values[key]
if orig_value is not None:
os.environ[key] = orig_value
else:
... | 83 | 83 | 279 | 11 | 72 | tuberj/ir_datasets | ir_datasets/commands/build_download_cache.py | Python | _build_cache | _build_cache | 31 | 57 | 31 | 31 | f7e65de283f89dc874c46a3733eb55640a9c5717 | bigcode/the-stack | train |
c7d1adf2a43de5560427dc30 | train | function | def main(args):
parser = argparse.ArgumentParser(prog='ir_datasets build_download_cache', description='Builds a cache of downloadable content')
parser.add_argument('--dir', default=f'{ir_datasets.util.home_path()}/downloads')
parser.add_argument('--retries', default='10')
args = parser.parse_args(args)
... | def main(args):
| parser = argparse.ArgumentParser(prog='ir_datasets build_download_cache', description='Builds a cache of downloadable content')
parser.add_argument('--dir', default=f'{ir_datasets.util.home_path()}/downloads')
parser.add_argument('--retries', default='10')
args = parser.parse_args(args)
with open('... | )
except Exception as ex:
_logger.warn(f'error: {ex}')
elif 'instructions' in data:
pass
else:
for key in data.keys():
_build_cache(data[key], dir, prefix=f'{prefix}/{key}' if prefix else key)
def main(args):
| 64 | 64 | 116 | 4 | 60 | tuberj/ir_datasets | ir_datasets/commands/build_download_cache.py | Python | main | main | 60 | 69 | 60 | 60 | f0f183ab2fe0a445a60a6fe03a0dce6271c9f14d | bigcode/the-stack | train |
7c8c8385d40c6dd144552661 | train | class | class TestEqual(TestCase):
def cpu_op_exec(self, input1, input2):
output = torch.eq(input1, input2)
output = output.numpy()
return output
def npu_op_exec(self, input1, input2):
output = torch.eq(input1, input2)
output = output.to("cpu")
output = output.numpy()
... | class TestEqual(TestCase):
| def cpu_op_exec(self, input1, input2):
output = torch.eq(input1, input2)
output = output.numpy()
return output
def npu_op_exec(self, input1, input2):
output = torch.eq(input1, input2)
output = output.to("cpu")
output = output.numpy()
return output
de... | # Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law... | 188 | 256 | 1,104 | 6 | 181 | Ascend/pytorch | test/test_npu/test_network_ops/test_eq.py | Python | TestEqual | TestEqual | 24 | 108 | 24 | 24 | 99f09a43b0740424e3d1fc54c3889a50501c80b3 | bigcode/the-stack | train |
7e120365bc83ae9db520eaa3 | train | function | def piecewise_constant_pdf(
key, bins, weights, num_coarse_samples, use_stratified_sampling
):
"""Piecewise-Constant PDF sampling.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
weights: jnp.ndarray(float32), [batch_si... | def piecewise_constant_pdf(
key, bins, weights, num_coarse_samples, use_stratified_sampling
):
| """Piecewise-Constant PDF sampling.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
weights: jnp.ndarray(float32), [batch_size, n_bins].
num_coarse_samples: int, the number of samples.
use_stratified_sampling: b... | _vals).sum(axis=-1)
med_depth = compute_depth_map(weights, z_vals)
acc = weights.sum(axis=-1)
if use_white_background:
rgb = rgb + (1.0 - acc[..., None])
if sample_at_infinity:
acc = weights[..., :-1].sum(axis=-1)
prefix = f"{key}_" if key is not None and le... | 168 | 168 | 561 | 25 | 142 | kacperkan/conerf | conerf/model_utils.py | Python | piecewise_constant_pdf | piecewise_constant_pdf | 202 | 253 | 202 | 204 | 8705d4c92a3950bf9832f0264cc28e618144a74f | bigcode/the-stack | train |
b346e2c813d1c735ebbc6989 | train | function | def compute_depth_index(weights, depth_threshold=0.5):
"""Compute the sample index of the median depth accumulation."""
opaqueness_mask = compute_opaqueness_mask(weights, depth_threshold)
return jnp.argmax(opaqueness_mask, axis=-1)
| def compute_depth_index(weights, depth_threshold=0.5):
| """Compute the sample index of the median depth accumulation."""
opaqueness_mask = compute_opaqueness_mask(weights, depth_threshold)
return jnp.argmax(opaqueness_mask, axis=-1)
| 1]], axis=-1
)
opaqueness_mask = jnp.logical_xor(opaqueness, padded_opaqueness)
opaqueness_mask = opaqueness_mask.astype(weights.dtype)
return opaqueness_mask
def compute_depth_index(weights, depth_threshold=0.5):
| 64 | 64 | 57 | 13 | 50 | kacperkan/conerf | conerf/model_utils.py | Python | compute_depth_index | compute_depth_index | 319 | 322 | 319 | 319 | ed3109f7afc010adb23c3f7ee6a2c9694c5e20a4 | bigcode/the-stack | train |
3bdb24d9e2313018f3743e6e | train | function | def vmap_module(module, in_axes=0, out_axes=0, num_batch_dims=1):
"""Vectorize a module.
Args:
module: the module to vectorize.
in_axes: the `in_axes` argument passed to vmap. See `jax.vmap`.
out_axes: the `out_axes` argument passed to vmap. See `jax.vmap`.
num_batch_dims: the number of... | def vmap_module(module, in_axes=0, out_axes=0, num_batch_dims=1):
| """Vectorize a module.
Args:
module: the module to vectorize.
in_axes: the `in_axes` argument passed to vmap. See `jax.vmap`.
out_axes: the `out_axes` argument passed to vmap. See `jax.vmap`.
num_batch_dims: the number of batch dimensions (how many times to apply
vmap to the mod... | , metadata_id):
"""Create a metadata array like a ray batch."""
return jnp.full_like(
rays[..., :1], fill_value=metadata_id, dtype=jnp.uint32
)
def vmap_module(module, in_axes=0, out_axes=0, num_batch_dims=1):
| 64 | 64 | 173 | 22 | 42 | kacperkan/conerf | conerf/model_utils.py | Python | vmap_module | vmap_module | 436 | 458 | 436 | 436 | 66d985400be33d957d159f29313c15b86ed0cfe6 | bigcode/the-stack | train |
6c90b9f5362fdc4862347de6 | train | function | def posenc_window(min_deg, max_deg, alpha):
"""Windows a posenc using a cosiney window.
This is equivalent to taking a truncated Hann window and sliding it to the
right along the frequency spectrum.
Args:
min_deg: the lower frequency band.
max_deg: the upper frequency band.
alpha: wi... | def posenc_window(min_deg, max_deg, alpha):
| """Windows a posenc using a cosiney window.
This is equivalent to taking a truncated Hann window and sliding it to the
right along the frequency spectrum.
Args:
min_deg: the lower frequency band.
max_deg: the upper frequency band.
alpha: will ease in each frequency as alpha goes from... | # (*, 2*F*C).
four_feat = four_feat.reshape((*batch_shape, -1))
if use_identity:
return jnp.concatenate([x, four_feat], axis=-1)
else:
return four_feat
def posenc_window(min_deg, max_deg, alpha):
| 64 | 64 | 164 | 12 | 51 | kacperkan/conerf | conerf/model_utils.py | Python | posenc_window | posenc_window | 488 | 504 | 488 | 488 | efea2f185a883ab2e31bd56bee46b927ba26d1ae | bigcode/the-stack | train |
06ff25801c60e99971d39924 | train | function | def compute_depth_map(weights, z_vals, depth_threshold=0.5):
"""Compute the depth using the median accumulation.
Note that this differs from the depth computation in NeRF-W's codebase!
Args:
weights: the density weights from NeRF.
z_vals: the z coordinates of the samples.
depth_threshold... | def compute_depth_map(weights, z_vals, depth_threshold=0.5):
| """Compute the depth using the median accumulation.
Note that this differs from the depth computation in NeRF-W's codebase!
Args:
weights: the density weights from NeRF.
z_vals: the z coordinates of the samples.
depth_threshold: the accumulation threshold which will be used as the
... | 0.5):
"""Compute the sample index of the median depth accumulation."""
opaqueness_mask = compute_opaqueness_mask(weights, depth_threshold)
return jnp.argmax(opaqueness_mask, axis=-1)
def compute_depth_map(weights, z_vals, depth_threshold=0.5):
| 64 | 64 | 137 | 16 | 48 | kacperkan/conerf | conerf/model_utils.py | Python | compute_depth_map | compute_depth_map | 325 | 340 | 325 | 325 | ebd64d0910ad4648f8f270def7cdb68a11955303 | bigcode/the-stack | train |
ac504e9b9c639fd1049bc8e7 | train | function | def compute_depth_map_attribute(weights, z_vals, depth_threshold=0.5):
"""Compute the depth using the median accumulation.
Note that this differs from the depth computation in NeRF-W's codebase!
Args:
weights: the density weights from NeRF.
z_vals: the z coordinates of the samples.
depth... | def compute_depth_map_attribute(weights, z_vals, depth_threshold=0.5):
| """Compute the depth using the median accumulation.
Note that this differs from the depth computation in NeRF-W's codebase!
Args:
weights: the density weights from NeRF.
z_vals: the z coordinates of the samples.
depth_threshold: the accumulation threshold which will be used as the
... | 2
)
opaqueness_mask = jnp.logical_xor(opaqueness, padded_opaqueness)
opaqueness_mask = opaqueness_mask.astype(weights.dtype)
return opaqueness_mask
def compute_depth_map_attribute(weights, z_vals, depth_threshold=0.5):
| 64 | 64 | 143 | 17 | 46 | kacperkan/conerf | conerf/model_utils.py | Python | compute_depth_map_attribute | compute_depth_map_attribute | 368 | 385 | 368 | 368 | 0be6eeef8eaee12e42ce409b91a1f1d2c5a76a72 | bigcode/the-stack | train |
8abc6bc88eb150a66e7e2d4b | train | function | def sample_pdf(
key,
bins,
weights,
origins,
directions,
z_vals,
num_coarse_samples,
use_stratified_sampling,
):
"""Hierarchical sampling.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
weig... | def sample_pdf(
key,
bins,
weights,
origins,
directions,
z_vals,
num_coarse_samples,
use_stratified_sampling,
):
| """Hierarchical sampling.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
bins: jnp.ndarray(float32), [batch_size, n_bins + 1].
weights: jnp.ndarray(float32), [batch_size, n_bins].
origins: ray origins.
directions: ray directions.
z_vals: jnp.ndarray(float32)... | denom)
t = (u - cdf_g0) / denom
z_samples = bins_g0 + t * (bins_g1 - bins_g0)
# Prevent gradient from backprop-ing through samples
return lax.stop_gradient(z_samples)
def sample_pdf(
key,
bins,
weights,
origins,
directions,
z_vals,
num_coarse_samples,
use_stratified_sam... | 91 | 91 | 306 | 37 | 54 | kacperkan/conerf | conerf/model_utils.py | Python | sample_pdf | sample_pdf | 256 | 291 | 256 | 265 | 42bfeed19ff82eb0bbf0c35699df8adec9f5241d | bigcode/the-stack | train |
ea80b8f99371043b32ff57fe | train | class | @struct.dataclass
class TrainState:
"""Stores training state, including the optimizer and model params."""
optimizer: optim.Optimizer
nerf_alpha: Optional[jnp.ndarray] = None
warp_alpha: Optional[jnp.ndarray] = None
hyper_alpha: Optional[jnp.ndarray] = None
hyper_sheet_alpha: Optional[jnp.ndarr... | @struct.dataclass
class TrainState:
| """Stores training state, including the optimizer and model params."""
optimizer: optim.Optimizer
nerf_alpha: Optional[jnp.ndarray] = None
warp_alpha: Optional[jnp.ndarray] = None
hyper_alpha: Optional[jnp.ndarray] = None
hyper_sheet_alpha: Optional[jnp.ndarray] = None
masking_gamma: Option... | specific language governing permissions and
# limitations under the License.
"""Helper functions/classes for model definition."""
from typing import Optional
import jax.numpy as jnp
from flax import linen as nn
from flax import optim, struct
from jax import lax, random
@struct.dataclass
class TrainState:
| 64 | 64 | 183 | 9 | 54 | kacperkan/conerf | conerf/model_utils.py | Python | TrainState | TrainState | 24 | 45 | 24 | 25 | 4873e27e82dc615104a2be7f01bd8fed70b62db0 | bigcode/the-stack | train |
7af0c2392e4494b25daef530 | train | function | def compute_opaqueness_mask(weights, depth_threshold=0.5):
"""Computes a mask which will be 1.0 at the depth point.
Args:
weights: the density weights from NeRF.
depth_threshold: the accumulation threshold which will be used as the
depth termination point.
Returns:
A tensor conta... | def compute_opaqueness_mask(weights, depth_threshold=0.5):
| """Computes a mask which will be 1.0 at the depth point.
Args:
weights: the density weights from NeRF.
depth_threshold: the accumulation threshold which will be used as the
depth termination point.
Returns:
A tensor containing a mask with the same size as weights that has one
... | z_vals and sample points
z_vals = jnp.sort(jnp.concatenate([z_vals, z_samples], axis=-1), axis=-1)
return z_vals, (
origins[..., None, :] + z_vals[..., None] * directions[..., None, :]
)
def compute_opaqueness_mask(weights, depth_threshold=0.5):
| 73 | 73 | 244 | 16 | 57 | kacperkan/conerf | conerf/model_utils.py | Python | compute_opaqueness_mask | compute_opaqueness_mask | 294 | 316 | 294 | 294 | e37feee552c985197781f5f3e47dc02631ea4bd0 | bigcode/the-stack | train |
74fcfba5867876775bdcc0cc | train | function | def sample_along_rays(
key,
origins,
directions,
num_coarse_samples,
near,
far,
use_stratified_sampling,
use_linear_disparity,
):
"""Stratified sampling along the rays.
Args:
key: jnp.ndarray, random generator key.
origins: ray origins.
directions: ray directio... | def sample_along_rays(
key,
origins,
directions,
num_coarse_samples,
near,
far,
use_stratified_sampling,
use_linear_disparity,
):
| """Stratified sampling along the rays.
Args:
key: jnp.ndarray, random generator key.
origins: ray origins.
directions: ray directions.
num_coarse_samples: int.
near: float, near clip.
far: float, far clip.
use_stratified_sampling: use stratified sampling.
use_lin... | attribute_sheet_alpha: Optional[jnp.ndarray] = None
@property
def extra_params(self):
return {
"nerf_alpha": self.nerf_alpha,
"warp_alpha": self.warp_alpha,
"hyper_alpha": self.hyper_alpha,
"hyper_sheet_alpha": self.hyper_sheet_alpha,
"mas... | 135 | 135 | 453 | 43 | 92 | kacperkan/conerf | conerf/model_utils.py | Python | sample_along_rays | sample_along_rays | 48 | 99 | 48 | 57 | 37db0570f89b52969f6dd6e75947087eb7dd24db | bigcode/the-stack | train |
0a2d0dbb8d3cc703460f436b | train | function | def metadata_like(rays, metadata_id):
"""Create a metadata array like a ray batch."""
return jnp.full_like(
rays[..., :1], fill_value=metadata_id, dtype=jnp.uint32
)
| def metadata_like(rays, metadata_id):
| """Create a metadata array like a ray batch."""
return jnp.full_like(
rays[..., :1], fill_value=metadata_id, dtype=jnp.uint32
)
| array: the array to broadcast.
shape: the shape to broadcast the tensor to.
Returns:
The broadcasted tensor.
"""
out_shape = (*shape[:-1], array.shape[-1])
return jnp.broadcast_to(array, out_shape)
def metadata_like(rays, metadata_id):
| 64 | 64 | 47 | 9 | 55 | kacperkan/conerf | conerf/model_utils.py | Python | metadata_like | metadata_like | 429 | 433 | 429 | 429 | b873c0d9d39630825d963db107c35984c3cd5f97 | bigcode/the-stack | train |
3cf8310b7e059e222e588b8d | train | function | def volumetric_rendering(
rgb,
sigma,
z_vals,
dirs,
use_white_background,
sample_at_infinity=True,
eps=1e-10,
key: Optional[str] = None,
):
"""Volumetric Rendering Function.
Args:
rgb: an array of size (B,S,3) containing the RGB color values.
sigma: an array of size ... | def volumetric_rendering(
rgb,
sigma,
z_vals,
dirs,
use_white_background,
sample_at_infinity=True,
eps=1e-10,
key: Optional[str] = None,
):
| """Volumetric Rendering Function.
Args:
rgb: an array of size (B,S,3) containing the RGB color values.
sigma: an array of size (B,S) containing the densities.
z_vals: an array of size (B,S) containing the z-coordinate of the
samples.
dirs: an array of size (B,3) containing the d... | 1.0 / (1.0 / near * (1.0 - t_vals) + 1.0 / far * t_vals)
if use_stratified_sampling:
mids = 0.5 * (z_vals[..., 1:] + z_vals[..., :-1])
upper = jnp.concatenate([mids, z_vals[..., -1:]], -1)
lower = jnp.concatenate([z_vals[..., :1], mids], -1)
t_rand = random.uniform(key, [batch_size,... | 256 | 256 | 904 | 49 | 207 | kacperkan/conerf | conerf/model_utils.py | Python | volumetric_rendering | volumetric_rendering | 102 | 199 | 102 | 111 | ed160ce6cc7e02c4b4cba89e1cda44e6afe7ef3d | bigcode/the-stack | train |
90b406726cfb4ff76fd981c3 | train | function | def posenc(x, min_deg, max_deg, use_identity=False, alpha=None):
"""Encode `x` with sinusoids scaled by 2^[min_deg:max_deg-1]."""
batch_shape = x.shape[:-1]
scales = 2.0 ** jnp.arange(min_deg, max_deg)
# (*, F, C).
xb = x[..., None, :] * scales[:, None]
# (*, F, 2, C).
four_feat = jnp.sin(jn... | def posenc(x, min_deg, max_deg, use_identity=False, alpha=None):
| """Encode `x` with sinusoids scaled by 2^[min_deg:max_deg-1]."""
batch_shape = x.shape[:-1]
scales = 2.0 ** jnp.arange(min_deg, max_deg)
# (*, F, C).
xb = x[..., None, :] * scales[:, None]
# (*, F, 2, C).
four_feat = jnp.sin(jnp.stack([xb, xb + 0.5 * jnp.pi], axis=-2))
if alpha is not N... | ,
out_axes=out_axes,
)
return module
def identity_initializer(_, shape):
max_shape = max(shape)
return jnp.eye(max_shape)[: shape[0], : shape[1]]
def posenc(x, min_deg, max_deg, use_identity=False, alpha=None):
| 63 | 64 | 214 | 18 | 45 | kacperkan/conerf | conerf/model_utils.py | Python | posenc | posenc | 466 | 485 | 466 | 466 | a273c3ea6a609d084edf2dfe1eb87735da0366b5 | bigcode/the-stack | train |
e1f5ec619624a304f1111bf5 | train | function | def broadcast_feature_to(array: jnp.ndarray, shape: jnp.shape):
"""Matches the shape dimensions (everything except the channel dims).
This is useful when you watch to match the shape of two features that have
a different number of channels.
Args:
array: the array to broadcast.
shape: the s... | def broadcast_feature_to(array: jnp.ndarray, shape: jnp.shape):
| """Matches the shape dimensions (everything except the channel dims).
This is useful when you watch to match the shape of two features that have
a different number of channels.
Args:
array: the array to broadcast.
shape: the shape to broadcast the tensor to.
Returns:
The broadca... | )
noise = (
random.normal(key, raw["alpha"].shape, dtype=raw["alpha"].dtype)
* noise_std
)
raw["alpha"] = raw["alpha"] + noise
return raw
def broadcast_feature_to(array: jnp.ndarray, shape: jnp.shape):
| 64 | 64 | 111 | 16 | 47 | kacperkan/conerf | conerf/model_utils.py | Python | broadcast_feature_to | broadcast_feature_to | 412 | 426 | 412 | 412 | 8b372a5dfb8969a723de01189774321435935602 | bigcode/the-stack | train |
517b75dea700384260510920 | train | function | def identity_initializer(_, shape):
max_shape = max(shape)
return jnp.eye(max_shape)[: shape[0], : shape[1]]
| def identity_initializer(_, shape):
| max_shape = max(shape)
return jnp.eye(max_shape)[: shape[0], : shape[1]]
| .
"""
for _ in range(num_batch_dims):
module = nn.vmap(
module,
variable_axes={"params": None},
split_rngs={"params": False},
in_axes=in_axes,
out_axes=out_axes,
)
return module
def identity_initializer(_, shape):
| 64 | 64 | 31 | 6 | 57 | kacperkan/conerf | conerf/model_utils.py | Python | identity_initializer | identity_initializer | 461 | 463 | 461 | 461 | 43dc6e33f0d1fa50bec83aedc41d3fa04d204c9f | bigcode/the-stack | train |
866d19363193e3b9638957f3 | train | function | def noise_regularize(key, raw, noise_std, use_stratified_sampling):
"""Regularize the density prediction by adding gaussian noise.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
raw: jnp.ndarray(float32), [batch_size, num_coarse_samples, 4].
noise_std: float, std dev of noise... | def noise_regularize(key, raw, noise_std, use_stratified_sampling):
| """Regularize the density prediction by adding gaussian noise.
Args:
key: jnp.ndarray(float32), [2,], random number generator.
raw: jnp.ndarray(float32), [batch_size, num_coarse_samples, 4].
noise_std: float, std dev of noise added to regularize sigma output.
use_stratified_sampling: ad... | the depth of each input pixel.
"""
opaqueness_mask = compute_opaqueness_mask_attribute(
weights, depth_threshold
)
return jnp.sum(opaqueness_mask * z_vals, axis=-2)
def noise_regularize(key, raw, noise_std, use_stratified_sampling):
| 66 | 66 | 220 | 17 | 49 | kacperkan/conerf | conerf/model_utils.py | Python | noise_regularize | noise_regularize | 388 | 409 | 388 | 388 | 46e58877176c347e1965a38e0e77a691d849f216 | bigcode/the-stack | train |
74e6ed64ce80a5bfd6d8d9e5 | train | function | def compute_opaqueness_mask_attribute(weights, depth_threshold=0.5):
"""Computes a mask which will be 1.0 at the depth point.
Args:
weights: the density weights from NeRF.
depth_threshold: the accumulation threshold which will be used as the
depth termination point.
Returns:
A te... | def compute_opaqueness_mask_attribute(weights, depth_threshold=0.5):
| """Computes a mask which will be 1.0 at the depth point.
Args:
weights: the density weights from NeRF.
depth_threshold: the accumulation threshold which will be used as the
depth termination point.
Returns:
A tensor containing a mask with the same size as weights that has one
... |
depth termination point.
Returns:
A tensor containing the depth of each input pixel.
"""
opaqueness_mask = compute_opaqueness_mask(weights, depth_threshold)
return jnp.sum(opaqueness_mask * z_vals, axis=-1)
def compute_opaqueness_mask_attribute(weights, depth_threshold=0.5):
| 74 | 74 | 249 | 17 | 57 | kacperkan/conerf | conerf/model_utils.py | Python | compute_opaqueness_mask_attribute | compute_opaqueness_mask_attribute | 343 | 365 | 343 | 343 | 1553b528fc37b39412c960413171b58345f138b5 | bigcode/the-stack | train |
293a2485563e3a60eb7cb9fb | train | class | class Migration(migrations.Migration):
dependencies = [
('theme', '0007_auto_20170427_1553'),
]
operations = [
migrations.AlterField(
model_name='userquota',
name='allocated_value',
field=models.FloatField(default=20),
),
migrations.Alter... | class Migration(migrations.Migration):
| dependencies = [
('theme', '0007_auto_20170427_1553'),
]
operations = [
migrations.AlterField(
model_name='userquota',
name='allocated_value',
field=models.FloatField(default=20),
),
migrations.AlterField(
model_name='userquota... | # -*- coding: utf-8 -*-
from django.db import migrations, models
class Migration(migrations.Migration):
| 24 | 64 | 93 | 7 | 16 | hydroshare/hydroshare | theme/migrations/0008_auto_20170622_2141.py | Python | Migration | Migration | 7 | 24 | 7 | 8 | 5b10c04d2357f2276d5e86d5dc022b21f07a1fa6 | bigcode/the-stack | train |
131e0d7ec2e2958ec5c4276f | train | class | class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = 'users.User'
django_get_or_create = ('username',)
id = factory.Sequence(lambda n: uuid.uuid4())
username = factory.Sequence(lambda n: 'testuser{}'.format(n))
password = factory.Faker('password', length=10, specia... | class UserFactory(factory.django.DjangoModelFactory):
| class Meta:
model = 'users.User'
django_get_or_create = ('username',)
id = factory.Sequence(lambda n: uuid.uuid4())
username = factory.Sequence(lambda n: 'testuser{}'.format(n))
password = factory.Faker('password', length=10, special_chars=True, digits=True, upper_case=True, lower_case=... | import uuid
import factory
class UserFactory(factory.django.DjangoModelFactory):
| 17 | 64 | 130 | 11 | 5 | shirishgoyal/scholars | scholars/users/test/factories.py | Python | UserFactory | UserFactory | 4 | 17 | 4 | 5 | 3e75b96031a019e182de7307c61e36c8da4f74c4 | bigcode/the-stack | train |
0b9f64a220ed63b25b0460aa | train | class | class Producer:
conf: 'ProducerConfig'
_producer: confluent_kafka.Producer
logger: logging.Logger
def __init__(self, conf: 'ProducerConfig') -> None:
self.logger = logging.getLogger("adc-streaming.producer")
self.conf = conf
self.logger.debug(f"connecting to producer with config... | class Producer:
| conf: 'ProducerConfig'
_producer: confluent_kafka.Producer
logger: logging.Logger
def __init__(self, conf: 'ProducerConfig') -> None:
self.logger = logging.getLogger("adc-streaming.producer")
self.conf = conf
self.logger.debug(f"connecting to producer with config {conf._to_confl... | import abc
import dataclasses
import logging
from datetime import timedelta
from typing import Dict, List, Optional, Union
import confluent_kafka # type: ignore
from .auth import SASLAuth
from .errors import (DeliveryCallback, ErrorCallback, log_client_errors,
log_delivery_errors)
class Producer... | 68 | 127 | 424 | 3 | 65 | myNameIsPatrick/genesis-client | adc/producer.py | Python | Producer | Producer | 14 | 63 | 14 | 14 | aab63b68803b544242df14e4902e2db799cbc382 | bigcode/the-stack | train |
b8231ec33cd6264713a150a2 | train | class | class Serializable(abc.ABC):
def serialize(self) -> bytes:
raise NotImplementedError()
| class Serializable(abc.ABC):
| def serialize(self) -> bytes:
raise NotImplementedError()
| .timeout.ms": self.produce_timeout.total_seconds() * 1000.0,
}
if self.error_callback is not None:
config["error_cb"] = self.error_callback
if self.auth is not None:
config.update(self.auth())
return config
class Serializable(abc.ABC):
| 64 | 64 | 21 | 7 | 56 | myNameIsPatrick/genesis-client | adc/producer.py | Python | Serializable | Serializable | 90 | 92 | 90 | 90 | 2afebd7f9cc7f8f72b5e0669d5f27247f0990a5b | bigcode/the-stack | train |
0adf4cb2c0d66629f3d0db94 | train | class | @dataclasses.dataclass
class ProducerConfig:
broker_urls: List[str]
topic: str
auth: Optional[SASLAuth] = None
delivery_callback: Optional[DeliveryCallback] = log_delivery_errors
error_callback: Optional[ErrorCallback] = log_client_errors
# produce_timeout sets the maximum amount of time that t... | @dataclasses.dataclass
class ProducerConfig:
| broker_urls: List[str]
topic: str
auth: Optional[SASLAuth] = None
delivery_callback: Optional[DeliveryCallback] = log_delivery_errors
error_callback: Optional[ErrorCallback] = log_client_errors
# produce_timeout sets the maximum amount of time that the backend can take
# to send a message t... | and value is None and traceback is None:
n_unsent = self.close()
if n_unsent > 0:
raise Exception(f"{n_unsent} messages remain unsent, some data may have been lost!")
return False
return False
@dataclasses.dataclass
class ProducerConfig:
| 64 | 64 | 197 | 9 | 54 | myNameIsPatrick/genesis-client | adc/producer.py | Python | ProducerConfig | ProducerConfig | 66 | 87 | 66 | 67 | 27bd6ecdce24c0ad5818676ebc6e15ba0b8d71a4 | bigcode/the-stack | train |
29f4b3ccce291ce98549c752 | train | function | def diffusion_coefficient_calculator(
diameter: float, viscosity: float, temperature: float
) -> float:
return k_B * temperature / (3 * pi * viscosity * diameter) * 1.0e12
| def diffusion_coefficient_calculator(
diameter: float, viscosity: float, temperature: float
) -> float:
| return k_B * temperature / (3 * pi * viscosity * diameter) * 1.0e12
| from math import pi
from scipy import constants
from uncertainties import UFloat
from ddmtools.types import IntensiveParameters
k_B: float = constants.Boltzmann
def diffusion_coefficient_calculator(
diameter: float, viscosity: float, temperature: float
) -> float:
| 60 | 64 | 48 | 24 | 35 | JeppeKlitgaard/DDMTools | ddmtools/utils/equations.py | Python | diffusion_coefficient_calculator | diffusion_coefficient_calculator | 12 | 15 | 12 | 14 | 45d012fe2e40c6551781fc67e9d02a2073b12bb2 | bigcode/the-stack | train |
99a0a55a37bbc090345ae13e | train | function | def diameter_calculator(
diffusion_coefficient: UFloat, intensive_parameters: IntensiveParameters
) -> UFloat:
scaling_factor = (
intensive_parameters.micrometre_per_pixel**2
) * intensive_parameters.framerate
diameter: UFloat = (
k_B
* intensive_parameters.temperature
/ ... | def diameter_calculator(
diffusion_coefficient: UFloat, intensive_parameters: IntensiveParameters
) -> UFloat:
| scaling_factor = (
intensive_parameters.micrometre_per_pixel**2
) * intensive_parameters.framerate
diameter: UFloat = (
k_B
* intensive_parameters.temperature
/ (3 * pi * intensive_parameters.viscosity * scaling_factor * diffusion_coefficient)
* 1.0e12
)
retu... | diameter: float, viscosity: float, temperature: float
) -> float:
return k_B * temperature / (3 * pi * viscosity * diameter) * 1.0e12
def diameter_calculator(
diffusion_coefficient: UFloat, intensive_parameters: IntensiveParameters
) -> UFloat:
| 64 | 64 | 102 | 24 | 39 | JeppeKlitgaard/DDMTools | ddmtools/utils/equations.py | Python | diameter_calculator | diameter_calculator | 18 | 31 | 18 | 20 | 19bfbbd2f278c2b9840fc78635f5918abef8d65c | bigcode/the-stack | train |
0fc1eec999969c67acaa6dcc | train | function | def pytest_addoption(parser: Parser) -> None:
parser.addoption(
"--full-ci",
action="store_true",
default=False,
help="run tests that are marked as only for CI",
)
parser.addoption(
"--include-slow-tests",
action="store_true",
default=False,
he... | def pytest_addoption(parser: Parser) -> None:
| parser.addoption(
"--full-ci",
action="store_true",
default=False,
help="run tests that are marked as only for CI",
)
parser.addoption(
"--include-slow-tests",
action="store_true",
default=False,
help="run tests that are a bit slow",
)
| import pytest
sys.dont_write_bytecode = True
sys.stdout = (
sys.stderr
) # allow printing of pytest output when running pytest-xdist https://stackoverflow.com/questions/27006884/pytest-xdist-without-capturing-output
def pytest_addoption(parser: Parser) -> None:
| 64 | 64 | 81 | 11 | 52 | CuriBio/domain-models | conftest.py | Python | pytest_addoption | pytest_addoption | 17 | 29 | 17 | 17 | d4ad49bb8d6c05ce4b66c8e768d7cf0e22d0837c | bigcode/the-stack | train |
23dd168398935a64432499dc | train | function | def pytest_collection_modifyitems(config: Config, items: List[Function]) -> None:
if not config.getoption("--full-ci"):
skip_ci_only = pytest.mark.skip(
reason="these tests are skipped unless --full-ci option is set"
)
for item in items:
if "only_run_in_ci" in item.ke... | def pytest_collection_modifyitems(config: Config, items: List[Function]) -> None:
| if not config.getoption("--full-ci"):
skip_ci_only = pytest.mark.skip(
reason="these tests are skipped unless --full-ci option is set"
)
for item in items:
if "only_run_in_ci" in item.keywords:
item.add_marker(skip_ci_only)
if not config.getoption... | tests that are marked as only for CI",
)
parser.addoption(
"--include-slow-tests",
action="store_true",
default=False,
help="run tests that are a bit slow",
)
def pytest_collection_modifyitems(config: Config, items: List[Function]) -> None:
| 64 | 64 | 145 | 18 | 46 | CuriBio/domain-models | conftest.py | Python | pytest_collection_modifyitems | pytest_collection_modifyitems | 32 | 47 | 32 | 32 | 5adcb4f9619d0040e8bd2e59ad93935795661a84 | bigcode/the-stack | train |
734de3d924cb4b3fe4dce0ad | train | function | def update_cyberark_aim_name(apps, schema_editor):
CredentialType.setup_tower_managed_defaults()
aim_types = apps.get_model('main', 'CredentialType').objects.filter(namespace='aim').order_by('id')
if aim_types.count() == 2:
original, renamed = aim_types.all()
apps.get_model('main', 'Credent... | def update_cyberark_aim_name(apps, schema_editor):
| CredentialType.setup_tower_managed_defaults()
aim_types = apps.get_model('main', 'CredentialType').objects.filter(namespace='aim').order_by('id')
if aim_types.count() == 2:
original, renamed = aim_types.all()
apps.get_model('main', 'Credential').objects.filter(credential_type_id=original.id... | # Generated by Django 2.2.4 on 2019-10-16 19:51
from django.db import migrations
from awx.main.models import CredentialType
def update_cyberark_aim_name(apps, schema_editor):
| 53 | 64 | 103 | 15 | 37 | bhyunki/awx | awx/main/migrations/0098_v360_rename_cyberark_aim_credential_type.py | Python | update_cyberark_aim_name | update_cyberark_aim_name | 7 | 14 | 7 | 7 | a378fa370855657b9d98493f559c8fb5a75b3fc1 | bigcode/the-stack | train |
f1d348917955785dacb9841c | train | class | class Migration(migrations.Migration):
dependencies = [
('main', '0097_v360_workflowapproval_approved_or_denied_by'),
]
operations = [migrations.RunPython(update_cyberark_aim_name)]
| class Migration(migrations.Migration):
| dependencies = [
('main', '0097_v360_workflowapproval_approved_or_denied_by'),
]
operations = [migrations.RunPython(update_cyberark_aim_name)]
| _by('id')
if aim_types.count() == 2:
original, renamed = aim_types.all()
apps.get_model('main', 'Credential').objects.filter(credential_type_id=original.id).update(credential_type_id=renamed.id)
original.delete()
class Migration(migrations.Migration):
| 64 | 64 | 49 | 7 | 57 | bhyunki/awx | awx/main/migrations/0098_v360_rename_cyberark_aim_credential_type.py | Python | Migration | Migration | 17 | 23 | 17 | 18 | 1b80be0d4432e14dce25b57a29a24930fda9b912 | bigcode/the-stack | train |
dd8b55f69335f9cb2a2c6759 | train | function | def init_logging(level=logging.DEBUG, log_to_file=False, logsize=1024, logcount=5):
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('enocean')
logger.setLevel(level)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(le... | def init_logging(level=logging.DEBUG, log_to_file=False, logsize=1024, logcount=5):
| formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('enocean')
logger.setLevel(level)
stream_handler = logging.StreamHandler()
stream_handler.setLevel(level)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler... | # -*- encoding: utf-8 -*-
from __future__ import print_function, unicode_literals, division, absolute_import
import logging
import logging.handlers
def init_logging(level=logging.DEBUG, log_to_file=False, logsize=1024, logcount=5):
| 54 | 64 | 150 | 23 | 30 | j5lien/enocean | enocean/consolelogger.py | Python | init_logging | init_logging | 7 | 22 | 7 | 7 | bed0b1664b8602d343c393ef59a9a9d978c53d8f | bigcode/the-stack | train |
08e506e6567ae1306b87e9ea | train | function | def is_palindrome(n):
if str(n) == str(n)[::-1]:
return True
| def is_palindrome(n):
| if str(n) == str(n)[::-1]:
return True
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
def is_palindrome(n):
| 21 | 64 | 21 | 6 | 15 | leeliang/python-learning | code/03_Filter.py | Python | is_palindrome | is_palindrome | 4 | 6 | 4 | 4 | e61e495bdf187825c920db3cc499ddf8afc91b9f | bigcode/the-stack | train |
b61614e1a91cfe4d722b9daf | train | class | class SingleDiscreteDistribution(Basic, NamedArgsMixin):
""" Discrete distribution of a single variable
Serves as superclass for PoissonDistribution etc....
Provides methods for pdf, cdf, and sampling
See Also:
sympy.stats.crv_types.*
"""
set = S.Integers
def __new__(cls, *args)... | class SingleDiscreteDistribution(Basic, NamedArgsMixin):
| """ Discrete distribution of a single variable
Serves as superclass for PoissonDistribution etc....
Provides methods for pdf, cdf, and sampling
See Also:
sympy.stats.crv_types.*
"""
set = S.Integers
def __new__(cls, *args):
args = list(map(sympify, args))
return ... | from __future__ import print_function, division
from sympy import (Basic, sympify, symbols, Dummy, Lambda, summation,
Piecewise, S, cacheit, Sum, exp, I, oo)
from sympy.solvers.solveset import solveset
from sympy.stats.rv import NamedArgsMixin, SinglePSpace, SingleDomain
from sympy.functions.elementary.integer... | 102 | 218 | 729 | 11 | 90 | atul107/sympy | sympy/stats/drv.py | Python | SingleDiscreteDistribution | SingleDiscreteDistribution | 10 | 104 | 10 | 10 | f86f72a45fe07fcac1193d410742703999f9d329 | bigcode/the-stack | train |
5a38acfe64eb2363faffd79b | train | class | class SingleDiscretePSpace(SinglePSpace):
""" Discrete probability space over a single univariate variable """
is_real = True
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return SingleDiscreteDomain(self.symbol, self.set)
def sample(sel... | class SingleDiscretePSpace(SinglePSpace):
| """ Discrete probability space over a single univariate variable """
is_real = True
@property
def set(self):
return self.distribution.set
@property
def domain(self):
return SingleDiscreteDomain(self.symbol, self.set)
def sample(self):
"""
Internal sample me... | stepsizes
if evaluate:
return summation(expr * self.pdf(var),
(var, self.set.inf, self.set.sup), **kwargs)
else:
return Sum(expr * self.pdf(var),
(var, self.set.inf, self.set.sup), **kwargs)
def __call__(self, *args):
... | 97 | 97 | 325 | 10 | 86 | atul107/sympy | sympy/stats/drv.py | Python | SingleDiscretePSpace | SingleDiscretePSpace | 109 | 159 | 109 | 109 | 2ebfd59af2be404dde16bd012d78d344f559f70c | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.