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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9752ec49bb2112a2fac98d7d | train | function | def _decoder_layer_forward(self,
x,
memory,
memory_pos=None,
query_pos=None,
memory_attn_mask=None,
target_attn_mask=None,
memory_k... | def _decoder_layer_forward(self,
x,
memory,
memory_pos=None,
query_pos=None,
memory_attn_mask=None,
target_attn_mask=None,
memory_k... | norm_cnt = 0
inp_residual = x
for layer in self.order:
if layer == 'selfattn':
x = self.self_attn(
x,
x,
x,
inp_residual if self.pre_norm else None,
query_pos,
attn_mask=target_attn_mask,
... | x = self.ffn(x, inp_residual if self.pre_norm else None)
else:
raise ValueError(f'Unsupported layer type {layer}.')
return x
def _decoder_layer_forward(self,
x,
memory,
memory_pos=None,
q... | 88 | 88 | 295 | 51 | 36 | Ascend/modelzoo | built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py | Python | _decoder_layer_forward | _decoder_layer_forward | 81 | 122 | 81 | 89 | 2c72c1b96dc5c8511a355e479bd168c9c24ecd74 | bigcode/the-stack | train |
b0e506875589c6f88ea6dac4 | train | function | def test_transformer_encoder(num_layers=2,
embed_dims=8,
num_heads=2,
feedforward_channels=8,
num_key=10,
batch_size=1):
module = TransformerEncoder(num_layers, embed_dims... | def test_transformer_encoder(num_layers=2,
embed_dims=8,
num_heads=2,
feedforward_channels=8,
num_key=10,
batch_size=1):
| module = TransformerEncoder(num_layers, embed_dims, num_heads,
feedforward_channels)
assert not module.pre_norm
assert module.norm is None
x = torch.rand(num_key, batch_size, embed_dims)
out = module(x)
assert out.shape == (num_key, batch_size, embed_dims)
# ... | order=order)
out = module('input', 'memory')
assert out == 'input_norm0_selfattn(residual=input)_norm1_' \
'multiheadattn(residual=selfattn)_norm2_ffn(residual=' \
'multiheadattn)'
test_order()
def test_transformer_encoder(num_layers=2,
embed_di... | 106 | 106 | 355 | 41 | 65 | Ascend/modelzoo | built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py | Python | test_transformer_encoder | test_transformer_encoder | 370 | 406 | 370 | 375 | 1f3ebcaf4ea63af32afbbb5763367ab8c5312a71 | bigcode/the-stack | train |
a89538dc915b03a279768290 | train | function | def test_ffn(embed_dims=8, feedforward_channels=8, num_fcs=2, batch_size=1):
# test invalid num_fcs
with pytest.raises(AssertionError):
module = FFN(embed_dims, feedforward_channels, 1)
module = FFN(embed_dims, feedforward_channels, num_fcs)
x = torch.rand(batch_size, embed_dims)
out = modu... | def test_ffn(embed_dims=8, feedforward_channels=8, num_fcs=2, batch_size=1):
# test invalid num_fcs
| with pytest.raises(AssertionError):
module = FFN(embed_dims, feedforward_channels, 1)
module = FFN(embed_dims, feedforward_channels, num_fcs)
x = torch.rand(batch_size, embed_dims)
out = module(x)
assert out.shape == (batch_size, embed_dims)
# set residual
residual = torch.rand(batc... | query_pos, key_pos, attn_mask,
key_padding_mask)
assert out.shape == (num_query, batch_size, embed_dims)
def test_ffn(embed_dims=8, feedforward_channels=8, num_fcs=2, batch_size=1):
# test invalid num_fcs
| 64 | 64 | 196 | 34 | 30 | Ascend/modelzoo | built-in/PyTorch/Official/cv/image_object_detection/YoloV3_ID1790_for_PyTorch/tests/test_models/test_transformer.py | Python | test_ffn | test_ffn | 166 | 184 | 166 | 167 | ba340099ac0e546a96b601c6c46275c13021476b | bigcode/the-stack | train |
db0431b229e64d170bb45633 | train | function | def suite():
tests = unittest.TestSuite()
tests.addTest(unittest.makeSuite(InsiderAuctionSwitchAuctionResourceTest))
tests.addTest(unittest.makeSuite(InsiderAuctionAwardSwitchResourceTest))
tests.addTest(unittest.makeSuite(InsiderAuctionAwardSwitch2ResourceTest))
tests.addTest(unittest.makeSuite(Ins... | def suite():
| tests = unittest.TestSuite()
tests.addTest(unittest.makeSuite(InsiderAuctionSwitchAuctionResourceTest))
tests.addTest(unittest.makeSuite(InsiderAuctionAwardSwitchResourceTest))
tests.addTest(unittest.makeSuite(InsiderAuctionAwardSwitch2ResourceTest))
tests.addTest(unittest.makeSuite(InsiderAuctionDo... | = auction['awards'][0]
self.second_award = auction['awards'][1]
self.award_id = self.first_award_id = self.first_award['id']
self.second_award_id = self.second_award['id']
self.app.authorization = authorization
def suite():
| 64 | 64 | 102 | 3 | 60 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | suite | suite | 162 | 169 | 162 | 162 | 008396916dfaf95456f28ab2c4df5f84f597cb7c | bigcode/the-stack | train |
fd525bd739942939f125e594 | train | class | class InsiderAuctionSwitchAuctionResourceTest(BaseInsiderAuctionWebTest):
initial_bids = test_bids
test_switch_to_auction = snitch(switch_to_auction)
| class InsiderAuctionSwitchAuctionResourceTest(BaseInsiderAuctionWebTest):
| initial_bids = test_bids
test_switch_to_auction = snitch(switch_to_auction)
| 2,
switch_active_to_unsuccessful_2,
)
from openprocurement.auctions.core.utils import get_now
from openprocurement.auctions.insider.tests.base import (
BaseInsiderAuctionWebTest, test_bids,
)
class InsiderAuctionSwitchAuctionResourceTest(BaseInsiderAuctionWebTest):
| 64 | 64 | 38 | 14 | 50 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | InsiderAuctionSwitchAuctionResourceTest | InsiderAuctionSwitchAuctionResourceTest | 28 | 31 | 28 | 28 | 742eff06403822ac92769ac32032f49506a2066f | bigcode/the-stack | train |
a8763444ade41c9c43c9173a | train | class | class InsiderAuctionAwardSwitchResourceTest(BaseInsiderAuctionWebTest, AuctionAwardSwitchResourceTestMixin):
initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionAwardSwitchResourceTest, self).setUp()
authorization = self.app.authorization
... | class InsiderAuctionAwardSwitchResourceTest(BaseInsiderAuctionWebTest, AuctionAwardSwitchResourceTestMixin):
| initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionAwardSwitchResourceTest, self).setUp()
authorization = self.app.authorization
self.app.authorization = ('Basic', ('auction', ''))
now = get_now()
response = self.app.get('... | _active_to_unsuccessful_2,
)
from openprocurement.auctions.core.utils import get_now
from openprocurement.auctions.insider.tests.base import (
BaseInsiderAuctionWebTest, test_bids,
)
class InsiderAuctionSwitchAuctionResourceTest(BaseInsiderAuctionWebTest):
initial_bids = test_bids
test_switch_to_auction... | 105 | 105 | 353 | 21 | 84 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | InsiderAuctionAwardSwitchResourceTest | InsiderAuctionAwardSwitchResourceTest | 34 | 70 | 34 | 34 | e3e52cf9ab49b14b88d905c3ef1c085df994f055 | bigcode/the-stack | train |
0d7bff39457d6039d38a381b | train | class | class InsiderAuctionDontSwitchSuspendedAuctionResourceTest(BaseInsiderAuctionWebTest,
AuctionDontSwitchSuspendedAuctionResourceTestMixin):
initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionDontS... | class InsiderAuctionDontSwitchSuspendedAuctionResourceTest(BaseInsiderAuctionWebTest,
AuctionDontSwitchSuspendedAuctionResourceTestMixin):
| initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionDontSwitchSuspendedAuctionResourceTest, self).setUp()
authorization = self.app.authorization
self.app.authorization = ('Basic', ('auction', ''))
now = get_now()
response =... | _verification_to_unsuccessful_2)
test_switch_active_to_unsuccessful = snitch(switch_active_to_unsuccessful_2)
class InsiderAuctionDontSwitchSuspendedAuction2ResourceTest(BaseInsiderAuctionWebTest):
initial_bids = test_bids
test_switch_suspended_auction_to_auction = snitch(switch_suspended_auction_to_auct... | 108 | 108 | 363 | 28 | 80 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | InsiderAuctionDontSwitchSuspendedAuctionResourceTest | InsiderAuctionDontSwitchSuspendedAuctionResourceTest | 122 | 159 | 122 | 123 | a4f0d87ffbf8478203bdfd09eb0f27af67aff86e | bigcode/the-stack | train |
6b897b780c1ea1e2e68806a9 | train | class | class InsiderAuctionDontSwitchSuspendedAuction2ResourceTest(BaseInsiderAuctionWebTest):
initial_bids = test_bids
test_switch_suspended_auction_to_auction = snitch(switch_suspended_auction_to_auction)
| class InsiderAuctionDontSwitchSuspendedAuction2ResourceTest(BaseInsiderAuctionWebTest):
| initial_bids = test_bids
test_switch_suspended_auction_to_auction = snitch(switch_suspended_auction_to_auction)
| authorization
test_switch_verification_to_unsuccessful = snitch(switch_verification_to_unsuccessful_2)
test_switch_active_to_unsuccessful = snitch(switch_active_to_unsuccessful_2)
class InsiderAuctionDontSwitchSuspendedAuction2ResourceTest(BaseInsiderAuctionWebTest):
| 64 | 64 | 50 | 18 | 46 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | InsiderAuctionDontSwitchSuspendedAuction2ResourceTest | InsiderAuctionDontSwitchSuspendedAuction2ResourceTest | 116 | 119 | 116 | 116 | ed63284bfdbce686fb6b5056b884e13b2d6115da | bigcode/the-stack | train |
d44cc600f30d498005ff0dfb | train | class | class InsiderAuctionAwardSwitch2ResourceTest(BaseInsiderAuctionWebTest):
initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionAwardSwitch2ResourceTest, self).setUp()
authorization = self.app.authorization
self.app.authorization = ('Basic', ... | class InsiderAuctionAwardSwitch2ResourceTest(BaseInsiderAuctionWebTest):
| initial_status = 'active.auction'
initial_bids = test_bids
def setUp(self):
super(InsiderAuctionAwardSwitch2ResourceTest, self).setUp()
authorization = self.app.authorization
self.app.authorization = ('Basic', ('auction', ''))
response = self.app.get('/auctions/{}'.format(s... | self.assertEqual(response.content_type, 'application/json')
auction = response.json['data']
self.assertEqual('active.qualification', auction["status"])
self.award = self.first_award = auction['awards'][0]
self.second_award = auction['awards'][1]
self.award_id = self.first_award_... | 117 | 117 | 392 | 15 | 101 | openprocurement/openprocurement.auctions.insider | openprocurement/auctions/insider/tests/chronograph.py | Python | InsiderAuctionAwardSwitch2ResourceTest | InsiderAuctionAwardSwitch2ResourceTest | 73 | 113 | 73 | 73 | 6a4cac48409fe35eb5144c7d51113a84293e19a6 | bigcode/the-stack | train |
fbdf6745bbdc97982f69d21b | train | class | class Migration(migrations.Migration):
dependencies = [
('auctions', '0008_listing_name'),
]
operations = [
migrations.AddField(
model_name='listing',
name='user',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='auctio... | class Migration(migrations.Migration):
| dependencies = [
('auctions', '0008_listing_name'),
]
operations = [
migrations.AddField(
model_name='listing',
name='user',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='auctions.user'),
preserve_default=... | # Generated by Django 3.1.3 on 2020-11-25 02:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
| 45 | 64 | 78 | 7 | 37 | jaewoochung/commerce | auctions/migrations/0009_listing_user.py | Python | Migration | Migration | 7 | 20 | 7 | 8 | 3167671b676bf1de4af61b8953c9159a35337365 | bigcode/the-stack | train |
2b6bf24859c4ae290bcf062c | train | function | def biasamp_attribute_to_task(task_labels, attribute_labels, task_preds, task_labels_train=None, attribute_labels_train=None, names=None):
'''
for each of the following, an entry of 1 is a prediction, and 0 is not
task_labels: n x |T|, these are labels on the test set, where n is the number of samples, and ... | def biasamp_attribute_to_task(task_labels, attribute_labels, task_preds, task_labels_train=None, attribute_labels_train=None, names=None):
| '''
for each of the following, an entry of 1 is a prediction, and 0 is not
task_labels: n x |T|, these are labels on the test set, where n is the number of samples, and |T| is the number of tasks to be classified
attribute_labels: n x |A|, these are labels on the test set, where n is the number of sampl... | a][np.where(task_labels[:, t]==1)[0]])
ahat_cond_t[a][t] = np.mean(attribute_preds[:, a][np.where(task_labels[:, t]==1)[0]])
delta_at = ahat_cond_t - a_cond_t
values = y_at*delta_at
val = np.nanmean(values)
if names is not None:
assert len(names) == 2, "Names should be a list of t... | 243 | 244 | 814 | 28 | 214 | princetonvisualai/directional-bias-amp | directional_biasamp.py | Python | biasamp_attribute_to_task | biasamp_attribute_to_task | 59 | 112 | 59 | 59 | d305c65de945d82b906bc6308677150397adf1fb | bigcode/the-stack | train |
68afb191a4607db45fba1b01 | train | function | def biasamp_task_to_attribute(task_labels, attribute_labels, attribute_preds, task_labels_train=None, attribute_labels_train=None, names=None):
'''
for each of the following, an entry of 1 is a prediction, and 0 is not
task_labels: n x |T|, these are labels on the test set, where n is the number of samples,... | def biasamp_task_to_attribute(task_labels, attribute_labels, attribute_preds, task_labels_train=None, attribute_labels_train=None, names=None):
| '''
for each of the following, an entry of 1 is a prediction, and 0 is not
task_labels: n x |T|, these are labels on the test set, where n is the number of samples, and |T| is the number of tasks to be classified
attribute_labels: n x |A|, these are labels on the test set, where n is the number of sampl... | import numpy as np
from scipy import stats
import pickle
def biasamp_task_to_attribute(task_labels, attribute_labels, attribute_preds, task_labels_train=None, attribute_labels_train=None, names=None):
| 41 | 245 | 817 | 28 | 12 | princetonvisualai/directional-bias-amp | directional_biasamp.py | Python | biasamp_task_to_attribute | biasamp_task_to_attribute | 5 | 57 | 5 | 5 | 77e497f8d194d10c3645c723099664110eeb4af1 | bigcode/the-stack | train |
b2342c642e82c922874e7d07 | train | function | def generate_sets_of_words():
main_forms = {
f"{prefix}{spelling}{suffix}"
for spelling in spellings
for suffix in set.union(suffixes,comp_suffixes)
for prefix in prefixes
if not(prefix != "" and suffix in comp_suffixes)
}
extra_forms1 = {
f"{spelling}{skap}{s... | def generate_sets_of_words():
| main_forms = {
f"{prefix}{spelling}{suffix}"
for spelling in spellings
for suffix in set.union(suffixes,comp_suffixes)
for prefix in prefixes
if not(prefix != "" and suffix in comp_suffixes)
}
extra_forms1 = {
f"{spelling}{skap}{skap_suffix}{man}"
for ... | ",
"unvm",
"unnvm",
"vnum",
"vnnum",
"vnom",
"vnvm",
"vnnvm",
"vnvm",
"vnvm",
"vnvm",
"vnnvm",
"vnvm",
"anna",
"ana",
}
def generate_sets_of_words():
| 64 | 64 | 180 | 6 | 58 | mmehdig/thegn_extraction | word_generation.py | Python | generate_sets_of_words | generate_sets_of_words | 535 | 557 | 535 | 535 | 348f294fab7ab78d36c67743dad67beb08d7a30d | bigcode/the-stack | train |
087e688235117e779327c2de | train | class | class BackupPolicy(sdk_resource.Resource):
base_path = '/instances/%(instance_id)s/backups/policy'
resource_key = 'policy'
# capabilities
allow_update = True
allow_get = True
#: instaceId
instance_id = resource.URI('instance_id')
# project_id = resource.URI('project_id')
# Proper... | class BackupPolicy(sdk_resource.Resource):
| base_path = '/instances/%(instance_id)s/backups/policy'
resource_key = 'policy'
# capabilities
allow_update = True
allow_get = True
#: instaceId
instance_id = resource.URI('instance_id')
# project_id = resource.URI('project_id')
# Properties
#: Policy keep days
#: Indicat... | #: Back file name
name = resource.Body('name')
#: Back file size in GB
#: *Type:int*
size = resource.Body('size', type=int)
#: Backup status
status = resource.Body('status')
#: Finished time
updated = resource.Body('updated')
#: Backup type
backuptype = resource.Body('backupt... | 134 | 134 | 447 | 8 | 126 | zsoltn/python-otcextensions | otcextensions/sdk/rds/v1/backup.py | Python | BackupPolicy | BackupPolicy | 68 | 124 | 68 | 69 | db8eb13f013a74366a27969c81f0f52a67d5a927 | bigcode/the-stack | train |
b161ce419e27c05449a6110c | train | class | class Backup(sdk_resource.Resource):
base_path = '/backups'
resource_key = 'backup'
resources_key = 'backups'
service_expectes_json_type = True
# capabilities
allow_create = True
allow_delete = True
allow_list = True
# Properties
# project_id = resource.URI('project_id')
#... | class Backup(sdk_resource.Resource):
| base_path = '/backups'
resource_key = 'backup'
resources_key = 'backups'
service_expectes_json_type = True
# capabilities
allow_create = True
allow_delete = True
allow_list = True
# Properties
# project_id = resource.URI('project_id')
#: Backup id
#: Type: uuid*
id ... | " BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from openstack import _log
from openstack import resource
from otcextensions.sdk import sdk_resource
_logger = _log.setup_logging('... | 77 | 77 | 259 | 7 | 70 | zsoltn/python-otcextensions | otcextensions/sdk/rds/v1/backup.py | Python | Backup | Backup | 20 | 58 | 20 | 21 | f830b07e0a88cffeb9ca5d392c7e2dd0a9d2f983 | bigcode/the-stack | train |
af2dad6c8052fe917c021c0b | train | class | @init_model_state_from_kwargs
class ResourcePrincipalSessionTokenRequest(object):
"""
ResourcePrincipalSessionTokenRequest model.
"""
def __init__(self, **kwargs):
"""
Initializes a new ResourcePrincipalSessionTokenRequest object with values from keyword arguments.
The following... | @init_model_state_from_kwargs
class ResourcePrincipalSessionTokenRequest(object):
| """
ResourcePrincipalSessionTokenRequest model.
"""
def __init__(self, **kwargs):
"""
Initializes a new ResourcePrincipalSessionTokenRequest object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this cla... | # coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | 148 | 253 | 846 | 15 | 132 | xjuarez/oci-python-sdk | src/oci/identity_data_plane/models/resource_principal_session_token_request.py | Python | ResourcePrincipalSessionTokenRequest | ResourcePrincipalSessionTokenRequest | 10 | 132 | 10 | 11 | 4003c0fc93f20014464c1d46e9288fb93221e6cf | bigcode/the-stack | train |
6e768b8352b6c1e6af25140a | train | function | async def create_delete_role_txns(key_pair, next_id, txn_list):
"""Create the delete transactions for a role object.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles where user is the admin
txn_list:
... | async def create_delete_role_txns(key_pair, next_id, txn_list):
| """Create the delete transactions for a role object.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles where user is the admin
txn_list:
list: transactions for batch submission
Returns:
... | .common.role.delete_role_admin import DeleteRoleAdmin
from rbac.common.role.delete_role_owner import DeleteRoleOwner
from rbac.common.role.delete_role_member import DeleteRoleMember
from rbac.common.sawtooth import batcher
async def create_delete_role_txns(key_pair, next_id, txn_list):
| 64 | 64 | 186 | 16 | 47 | Nonj/sawtooth-next-directory | rbac/server/blockchain_transactions/role_transaction.py | Python | create_delete_role_txns | create_delete_role_txns | 26 | 46 | 26 | 26 | dd2e1cb2848001ea0738180835b6b379f956dacc | bigcode/the-stack | train |
6363ecd1b32e4c809df2bc85 | train | function | async def create_delete_role_member_txns(key_pair, next_id, txn_list):
"""Create the delete transactions for a member if user is an member of any roles.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles w... | async def create_delete_role_member_txns(key_pair, next_id, txn_list):
| """Create the delete transactions for a member if user is an member of any roles.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles where user is the admin
txn_list:
list: transa... | =next_id)
payload = role_delete.make_payload(
message=message, signer_keypair=key_pair, signer_user_id=key_pair.public_key
)
transaction = batcher.make_transaction(payload=payload, signer_keypair=key_pair)
txn_list.extend([transaction])
return txn_list
async def create_delete_role_member_txn... | 82 | 82 | 274 | 17 | 64 | Nonj/sawtooth-next-directory | rbac/server/blockchain_transactions/role_transaction.py | Python | create_delete_role_member_txns | create_delete_role_member_txns | 49 | 85 | 49 | 49 | b98c13a1c16f10d064172fdc031b2b6bad18530c | bigcode/the-stack | train |
168c2652aa6a4117720581f3 | train | function | async def create_delete_role_owner_txns(key_pair, next_id, txn_list):
"""Create the delete transactions for an owner if ownership of a role(s) exists.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles whe... | async def create_delete_role_owner_txns(key_pair, next_id, txn_list):
| """Create the delete transactions for an owner if ownership of a role(s) exists.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles where user is the admin
txn_list:
list: transac... | _delete.make_payload(
message=admin_delete_message,
signer_keypair=key_pair,
signer_user_id=key_pair.public_key,
)
transaction = batcher.make_transaction(
payload=payload, signer_keypair=key_pair
)
txn_list.e... | 82 | 82 | 275 | 17 | 64 | Nonj/sawtooth-next-directory | rbac/server/blockchain_transactions/role_transaction.py | Python | create_delete_role_owner_txns | create_delete_role_owner_txns | 88 | 124 | 88 | 88 | 4172a206e687102956748575a7eafe73a57585e5 | bigcode/the-stack | train |
795fd43872d7bf5ee0c284c4 | train | function | async def create_delete_role_admin_txns(key_pair, next_id, txn_list):
"""Create the delete transactions for an admin if user is an admin of any roles.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles whe... | async def create_delete_role_admin_txns(key_pair, next_id, txn_list):
| """Create the delete transactions for an admin if user is an admin of any roles.
Args:
key_pair:
obj: public and private keys for user
next_id: next_
str: next_id to search for the roles where user is the admin
txn_list:
list: transac... | _delete.make_payload(
message=owner_delete_message,
signer_keypair=key_pair,
signer_user_id=key_pair.public_key,
)
transaction = batcher.make_transaction(
payload=payload, signer_keypair=key_pair
)
txn_list.e... | 82 | 82 | 275 | 17 | 64 | Nonj/sawtooth-next-directory | rbac/server/blockchain_transactions/role_transaction.py | Python | create_delete_role_admin_txns | create_delete_role_admin_txns | 127 | 163 | 127 | 127 | f3db7307c3933c2813db418a6bf55009bd2053c5 | bigcode/the-stack | train |
92e3d6d93ee4cea4d17f6fd9 | train | function | def get_roots(reload: bool = False) -> list[str]:
"""Gets the list of root names as defined in the AaC model specification.
Args:
reload: If True the cached root name values will be reloaded.
Default is False.
Returns:
A list of strings, one entry for each root name in the AaC ... | def get_roots(reload: bool = False) -> list[str]:
| """Gets the list of root names as defined in the AaC model specification.
Args:
reload: If True the cached root name values will be reloaded.
Default is False.
Returns:
A list of strings, one entry for each root name in the AaC model specification.
"""
global ROOT_NAME... | len(PRIMITIVES) == 0 or reload:
_, aac_enums = get_aac_spec()
PRIMITIVES = search(aac_enums["Primitives"], ["enum", "values"])
return PRIMITIVES
def get_roots(reload: bool = False) -> list[str]:
| 64 | 64 | 133 | 15 | 48 | Coffee2Bits/AaC | python/src/aac/spec/core.py | Python | get_roots | get_roots | 91 | 108 | 91 | 91 | ca96ebadd990baea7f1aec9a39261366077ac0ba | bigcode/the-stack | train |
023842e505cac43e92babe44 | train | function | def get_primitives(reload: bool = False) -> list[str]:
"""Gets the list of primitives as defined in the AaC model specification.
Args:
reload: If True the cached primitive values will be reloaded.
Default is False.
Returns:
A list of strings, one entry for each primitive type i... | def get_primitives(reload: bool = False) -> list[str]:
| """Gets the list of primitives as defined in the AaC model specification.
Args:
reload: If True the cached primitive values will be reloaded.
Default is False.
Returns:
A list of strings, one entry for each primitive type in the AaC model specification.
"""
global PRIM... | is_first = False
else:
aac_yaml = aac_yaml + "---\n"
aac_yaml = aac_yaml + yaml.dump(aac_model[aac_name]) + "\n"
return aac_yaml
def get_primitives(reload: bool = False) -> list[str]:
| 64 | 64 | 134 | 15 | 48 | Coffee2Bits/AaC | python/src/aac/spec/core.py | Python | get_primitives | get_primitives | 71 | 88 | 71 | 71 | f7e2acb5ea42d6b86c484ec29a16cb1b18fe2891 | bigcode/the-stack | train |
94f1d48a302c70b3a284f80d | train | function | def get_aac_spec() -> tuple[dict[str, dict], dict[str, dict]]:
"""
Get the specification for Architecture-as-Code itself.
The AaC model specification is
defined as an AaC model and is needed for model validation.
Returns:
Returns a tuple (aac_data, aac_enums), where aac_data is a dict of t... | def get_aac_spec() -> tuple[dict[str, dict], dict[str, dict]]:
| """
Get the specification for Architecture-as-Code itself.
The AaC model specification is
defined as an AaC model and is needed for model validation.
Returns:
Returns a tuple (aac_data, aac_enums), where aac_data is a dict of the AaC model spec
with root types of data and aac_enums... | os
import yaml
from aac import parser
from aac.package_resources import get_resource_file_contents
from aac.util import get_models_by_type, search
PRIMITIVES: list[str] = []
ROOT_NAMES: list[str] = []
AAC_MODEL: dict[str, dict] = {}
def get_aac_spec() -> tuple[dict[str, dict], dict[str, dict]]:
| 80 | 81 | 270 | 19 | 61 | Coffee2Bits/AaC | python/src/aac/spec/core.py | Python | get_aac_spec | get_aac_spec | 15 | 42 | 15 | 15 | 569dc6bd6cf61c130e992bd1455eea4f3ed3c60a | bigcode/the-stack | train |
199e858a4c0b624a4fb2d994 | train | function | def get_aac_spec_as_yaml() -> str:
"""Get the base AaC spec in YAML.
Utility to provide the current base AaC model specification (including plugin extensions)
in an easy to read yaml format (just as it is defined internally).
Returns:
Returns a string containing YAML for the current AaC spec. ... | def get_aac_spec_as_yaml() -> str:
| """Get the base AaC spec in YAML.
Utility to provide the current base AaC model specification (including plugin extensions)
in an easy to read yaml format (just as it is defined internally).
Returns:
Returns a string containing YAML for the current AaC spec. Each model entry is separated
... | parser.parse_str(file_path, model_content)
aac_data = get_models_by_type(AAC_MODEL, "data")
aac_enums = get_models_by_type(AAC_MODEL, "enum")
return aac_data, aac_enums
def get_aac_spec_as_yaml() -> str:
| 64 | 64 | 212 | 11 | 52 | Coffee2Bits/AaC | python/src/aac/spec/core.py | Python | get_aac_spec_as_yaml | get_aac_spec_as_yaml | 45 | 68 | 45 | 45 | 273b029f811bfccc6119bc866f6164a5039a26e1 | bigcode/the-stack | train |
780c844b7111ac8052913911 | train | function | def huber_loss(x, t, delta):
"""Loss function which is less sensitive to outliers in data than MSE.
.. math::
a = x - t
and
.. math::
L_{\\delta}(a) = \\left \\{ \\begin{array}{cc}
\\frac{1}{2} a^2 & {\\rm if~|a| \\leq \\delta} \\\\
\\delta ... | def huber_loss(x, t, delta):
| """Loss function which is less sensitive to outliers in data than MSE.
.. math::
a = x - t
and
.. math::
L_{\\delta}(a) = \\left \\{ \\begin{array}{cc}
\\frac{1}{2} a^2 & {\\rm if~|a| \\leq \\delta} \\\\
\\delta (|a| - \\frac{1}{2} \\delta) ... | .delta)
y *= 0.5
return y.sum(axis=1),
def backward(self, inputs, gy):
xp = cuda.get_array_module(*inputs)
mask = xp.abs(self.diff) <= self.delta
gx = xp.where(mask, self.diff, self.delta * xp.sign(self.diff))
return gx, -gx
def huber_loss(x, t, delta):
| 84 | 84 | 283 | 10 | 73 | fukuta0614/Chainer | chainer/functions/loss/huber_loss.py | Python | huber_loss | huber_loss | 38 | 68 | 38 | 38 | aa989437e7977eed6e3cc8fa192aee7572443e23 | bigcode/the-stack | train |
09d0ed595c45218b63c67abf | train | class | class HuberLoss(function.Function):
def __init__(self, delta):
self.delta = delta
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
type_check.expect(
in_types[0].dtype == numpy.float32,
in_types[1].dtype == numpy.float32,
... | class HuberLoss(function.Function):
| def __init__(self, delta):
self.delta = delta
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
type_check.expect(
in_types[0].dtype == numpy.float32,
in_types[1].dtype == numpy.float32,
in_types[0].shape == in_types[1].s... | import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class HuberLoss(function.Function):
| 30 | 69 | 233 | 7 | 22 | fukuta0614/Chainer | chainer/functions/loss/huber_loss.py | Python | HuberLoss | HuberLoss | 8 | 35 | 8 | 9 | 3f9f3a8bb2780fc329d1336119157874ab5654df | bigcode/the-stack | train |
e038f99b4ae62e06e42f0cd4 | train | class | class MolGraphSplitError(Exception):
# Raised when a molecule graph is failed to split into two disconnected
# subgraphs
pass
| class MolGraphSplitError(Exception):
# Raised when a molecule graph is failed to split into two disconnected
# subgraphs
| pass
| cule(species, coords)
# shift so origin is at center of mass
molecule = molecule.get_centered_molecule()
molecules.append(molecule)
return molecules
class MolGraphSplitError(Exception):
# Raised when a molecule graph is failed to split into two disconnected
# subgr... | 64 | 64 | 30 | 27 | 36 | XinWeiShen/pymatgen | pymatgen/analysis/graphs.py | Python | MolGraphSplitError | MolGraphSplitError | 1,452 | 1,455 | 1,452 | 1,454 | 08b1d0460f57abd134d52791442a4bb2126d8a18 | bigcode/the-stack | train |
bdd5020633fadb11e05688ab | train | class | class MoleculeGraph(MSONable):
"""
This is a class for annotating a Molecule with
bond information, stored in the form of a graph. A "bond" does
not necessarily have to be a chemical bond, but can store any
kind of information that connects two Sites.
"""
def __init__(self, molecule, graph_... | class MoleculeGraph(MSONable):
| """
This is a class for annotating a Molecule with
bond information, stored in the form of a graph. A "bond" does
not necessarily have to be a chemical bond, but can store any
kind of information that connects two Sites.
"""
def __init__(self, molecule, graph_data=None):
"""
... | ie']
def edge_match(e1, e2):
if use_weights:
return e1['weight'] == e2['weight']
else:
return True
# prune duplicate subgraphs
unique_subgraphs = []
for subgraph in molecule_subgraphs:
already_present = [nx.is_isomorph... | 256 | 256 | 10,913 | 8 | 247 | XinWeiShen/pymatgen | pymatgen/analysis/graphs.py | Python | MoleculeGraph | MoleculeGraph | 1,458 | 2,776 | 1,458 | 1,458 | 627004ed529e1a4b9d64187ad1722ed8ddc9e5d0 | bigcode/the-stack | train |
416099044accf781900bafc3 | train | class | class StructureGraph(MSONable):
"""
This is a class for annotating a Structure with
bond information, stored in the form of a graph. A "bond" does
not necessarily have to be a chemical bond, but can store any
kind of information that connects two Sites.
"""
def __init__(self, structure, gra... | class StructureGraph(MSONable):
| """
This is a class for annotating a Structure with
bond information, stored in the form of a graph. A "bond" does
not necessarily have to be a chemical bond, but can store any
kind of information that connects two Sites.
"""
def __init__(self, structure, graph_data=None):
"""
... | os.path
import copy
from itertools import combinations
from pymatgen.core import Structure, Lattice, PeriodicSite, Molecule
from pymatgen.core.structure import FunctionalGroups
from pymatgen.util.coord import lattice_points_in_supercell
from pymatgen.vis.structure_vtk import EL_COLORS
from monty.json import MSONable... | 256 | 256 | 11,748 | 7 | 249 | XinWeiShen/pymatgen | pymatgen/analysis/graphs.py | Python | StructureGraph | StructureGraph | 45 | 1,449 | 45 | 45 | 1d71e4e4471b991ce5c7fbf987d0409cacf1c6d4 | bigcode/the-stack | train |
5cba2d7866e876adbf77ffdf | train | function | @cli.command()
@click.option(
"--port", type=int, default="8080", help="Persia k8s schedule server port"
)
def server(
port: int,
):
executable_path = resolve_binary_execute_path("server")
cmd = [
executable_path,
"--port",
port,
]
run_command(cmd)
| @cli.command()
@click.option(
"--port", type=int, default="8080", help="Persia k8s schedule server port"
)
def server(
port: int,
):
| executable_path = resolve_binary_execute_path("server")
cmd = [
executable_path,
"--port",
port,
]
run_command(cmd)
| .command()
def operator():
executable_path = resolve_binary_execute_path("operator")
run_command([executable_path])
@cli.command()
@click.option(
"--port", type=int, default="8080", help="Persia k8s schedule server port"
)
def server(
port: int,
):
| 64 | 64 | 73 | 40 | 24 | dumpmemory/PERSIA | persia/k8s_utils.py | Python | server | server | 36 | 49 | 36 | 42 | e032cdf1c70a564141c03a9c4b0ba9042fc32f30 | bigcode/the-stack | train |
0fd55d46d0508430a9313300 | train | function | @cli.command()
def operator():
executable_path = resolve_binary_execute_path("operator")
run_command([executable_path])
| @cli.command()
def operator():
| executable_path = resolve_binary_execute_path("operator")
run_command([executable_path])
| ia k8s custom resource definition description file",
)
def gencrd(
output: str,
):
executable_path = resolve_binary_execute_path("gencrd")
cmd = [
executable_path,
"--output",
output,
]
run_command(cmd)
@cli.command()
def operator():
| 64 | 64 | 26 | 7 | 57 | dumpmemory/PERSIA | persia/k8s_utils.py | Python | operator | operator | 30 | 33 | 30 | 31 | bec60f8577f9bddb1ef74d2af7cf895d51d5fe3b | bigcode/the-stack | train |
7e8f865c7678867e4200da61 | train | function | @click.group()
def cli():
...
| @click.group()
def cli():
| ...
| import click
from persia.utils import resolve_binary_execute_path, run_command
@click.group()
def cli():
| 22 | 64 | 8 | 6 | 15 | dumpmemory/PERSIA | persia/k8s_utils.py | Python | cli | cli | 6 | 8 | 6 | 7 | 6c2d0faeff608073bd0fed5558aba56bd1f5cadf | bigcode/the-stack | train |
7229be39976e1da097838cf2 | train | function | @cli.command()
@click.option(
"--output",
type=str,
default="./jobs.persia.com.yaml",
help="Persia k8s custom resource definition description file",
)
def gencrd(
output: str,
):
executable_path = resolve_binary_execute_path("gencrd")
cmd = [
executable_path,
"--output",
... | @cli.command()
@click.option(
"--output",
type=str,
default="./jobs.persia.com.yaml",
help="Persia k8s custom resource definition description file",
)
def gencrd(
output: str,
):
| executable_path = resolve_binary_execute_path("gencrd")
cmd = [
executable_path,
"--output",
output,
]
run_command(cmd)
| _path, run_command
@click.group()
def cli():
...
@cli.command()
@click.option(
"--output",
type=str,
default="./jobs.persia.com.yaml",
help="Persia k8s custom resource definition description file",
)
def gencrd(
output: str,
):
| 64 | 64 | 86 | 51 | 13 | dumpmemory/PERSIA | persia/k8s_utils.py | Python | gencrd | gencrd | 11 | 27 | 11 | 20 | d6444e81d27889622c7a7a99b810a925bc4b62ed | bigcode/the-stack | train |
5016a156b0b79601fa38416e | train | function | def bitstring(bits):
return ''.join(str(int(b)) for b in bits)
| def bitstring(bits):
| return ''.join(str(int(b)) for b in bits)
| c.append(cirq.X.on(input_qubit[1])) # number=22
c.append(cirq.X.on(input_qubit[1])) # number=23
# circuit end
c.append(cirq.measure(*input_qubit, key='result'))
return c
def bitstring(bits):
| 64 | 64 | 18 | 5 | 58 | UCLA-SEAL/QDiff | benchmark/startCirq1138.py | Python | bitstring | bitstring | 74 | 75 | 74 | 74 | d8906cddcb2bd582e6d3ac5751986873fa7d631d | bigcode/the-stack | train |
0afbc2204fd05dc836d8ee39 | train | function | def make_circuit(n: int, input_qubit):
c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=3
c.append(cirq.rx(-1.3603096190043806).on(input_qubit[2])) # number=28
c.append(cirq.H.on(input_qubit[1])) # number=4
c.append(cirq.H.on(input_qubit[2])) # number=5
c.appe... | def make_circuit(n: int, input_qubit):
| c = cirq.Circuit() # circuit begin
c.append(cirq.H.on(input_qubit[0])) # number=3
c.append(cirq.rx(-1.3603096190043806).on(input_qubit[2])) # number=28
c.append(cirq.H.on(input_qubit[1])) # number=4
c.append(cirq.H.on(input_qubit[2])) # number=5
c.append(cirq.H.on(input_qubit[3])) # number... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 5/15/20 4:49 PM
# @File : grover.py
# qubit number=5
# total number=46
import cirq
import cirq.google as cg
from typing import Optional
import sys
from math import log2
import numpy as np
#thatsNoCode
from cirq.contrib.svg import SVGCircuit
# Symbols for... | 124 | 256 | 868 | 12 | 112 | UCLA-SEAL/QDiff | benchmark/startCirq1138.py | Python | make_circuit | make_circuit | 20 | 72 | 20 | 20 | accee531ae008e39460610fcbd74ceb7970a6002 | bigcode/the-stack | train |
7d4944c5f7a26737f2741148 | train | class | class PrioritySort(Dataset):
"""A Dataset class to generate random examples for priority sort task.
In the input sequence, each vector is generated randomly along with a
scalar priority rating. The priority is drawn uniformly from the range
[-1,1) and is provided on a separate input channel.
The t... | class PrioritySort(Dataset):
| """A Dataset class to generate random examples for priority sort task.
In the input sequence, each vector is generated randomly along with a
scalar priority rating. The priority is drawn uniformly from the range
[-1,1) and is provided on a separate input channel.
The target contains the binary vec... | import torch
from torch.utils.data import Dataset
from torch.distributions.uniform import Uniform
from torch.distributions.beta import Beta
from torch.distributions.binomial import Binomial
class PrioritySort(Dataset):
| 42 | 167 | 558 | 6 | 35 | geektoni/ntm-pytorch | ntm/datasets/prioritysort.py | Python | PrioritySort | PrioritySort | 8 | 67 | 8 | 8 | 1d9f368d6c65a331658a1f5f121d129044e3eb65 | bigcode/the-stack | train |
e3fe2eef7d115f474306ba83 | train | function | async def _hunt():
assigned_ids = utils.get_assigned_user_ids()
if _hunt.message.author.id not in assigned_ids:
await _hunt.message.channel.send(":warning: Your id is not assigned")
else:
filename = f"data/users/{_hunt.message.author.id}.ini"
data = iniparser2.INI(convert_property... | async def _hunt():
| assigned_ids = utils.get_assigned_user_ids()
if _hunt.message.author.id not in assigned_ids:
await _hunt.message.channel.send(":warning: Your id is not assigned")
else:
filename = f"data/users/{_hunt.message.author.id}.ini"
data = iniparser2.INI(convert_property=True)
data... | import random
import iniparser2
import discord
from lib import statics
from lib import utils
async def _hunt():
| 29 | 219 | 732 | 5 | 23 | HugeBrain16/ZenRPG | src/commands/hunt.py | Python | _hunt | _hunt | 9 | 91 | 9 | 9 | aa8b90678cfce47c12e981da3f3350a2f445b97c | bigcode/the-stack | train |
efb2958a5c2a1d170300fc84 | train | function | def set_logging_to_file(node: CephAdmin) -> bool:
"""
Enables the cluster logging into files at var/log/ceph and checks file permissions
Args:
node: Cephadm node where the commands need to be executed
Returns: True -> pass, False -> fail
"""
try:
cmd = "ceph config set global lo... | def set_logging_to_file(node: CephAdmin) -> bool:
| """
Enables the cluster logging into files at var/log/ceph and checks file permissions
Args:
node: Cephadm node where the commands need to be executed
Returns: True -> pass, False -> fail
"""
try:
cmd = "ceph config set global log_to_file true"
node.shell([cmd])
... | "rados --no-log-to-stderr -p {pool_name} bench {duration} seq"
node.shell([cmd])
cmd = f"rados --no-log-to-stderr -p {pool_name} bench {duration} rand"
node.shell([cmd])
return True
except Exception as err:
log.error(f"Error running rados bench write on pool : {pool_name}")
... | 109 | 109 | 364 | 14 | 94 | anrao19/cephci | tests/rados/rados_prep.py | Python | set_logging_to_file | set_logging_to_file | 193 | 231 | 193 | 193 | 4c251ad92b556f35143803c965f32a48da7d0056 | bigcode/the-stack | train |
078ec4d2c49eabfa52c0e946 | train | function | def detete_pool(node: CephAdmin, pool: str) -> bool:
"""
Deletes the given pool from the cluster
Args:
node: Cephadm node where the commands need to be executed
pool: name of the pool to be deleted
Returns: True -> pass, False -> fail
"""
# Checking if config is set to allow poo... | def detete_pool(node: CephAdmin, pool: str) -> bool:
| """
Deletes the given pool from the cluster
Args:
node: Cephadm node where the commands need to be executed
pool: name of the pool to be deleted
Returns: True -> pass, False -> fail
"""
# Checking if config is set to allow pool deletion
config_dump = run_ceph_command(node, c... | ("default_mode"):
default_mode = kwargs.get("default_mode")
cmd = (
f"ceph config set global osd_pool_default_pg_autoscale_mode {default_mode}"
)
node.shell([cmd])
cmd = "ceph osd pool autoscale-status -f json"
log.info(node.shell([cmd]))
return True
def detete_p... | 92 | 92 | 309 | 17 | 74 | anrao19/cephci | tests/rados/rados_prep.py | Python | detete_pool | detete_pool | 380 | 408 | 380 | 380 | dd54885bd99dd7fc7fe960271b2a8babada572ce | bigcode/the-stack | train |
56cc414bf42bb0eb5798f5fb | train | function | def run_rados_bench_write(node: CephAdmin, pool_name: str, **kwargs) -> bool:
"""
Method to trigger Write operations via the Rados Bench tool
Args:
node: Cephadm node where the commands need to be executed
pool_name: pool on which the operation will be performed
kwargs: Any other par... | def run_rados_bench_write(node: CephAdmin, pool_name: str, **kwargs) -> bool:
| """
Method to trigger Write operations via the Rados Bench tool
Args:
node: Cephadm node where the commands need to be executed
pool_name: pool on which the operation will be performed
kwargs: Any other param that needs to passed
Returns: True -> pass, False -> fail
"""
... | cephadm config-check enable {check}"
node.shell([cmd])
cmd = "ceph cephadm config-check ls"
log.info(node.shell([cmd]))
return True
def run_rados_bench_write(node: CephAdmin, pool_name: str, **kwargs) -> bool:
| 64 | 64 | 204 | 24 | 39 | anrao19/cephci | tests/rados/rados_prep.py | Python | run_rados_bench_write | run_rados_bench_write | 146 | 166 | 146 | 146 | ce34df8c8e0c84ecbd81734b49e47d79e08f57fd | bigcode/the-stack | train |
ae091e4132f32636597e12eb | train | function | def configure_pg_autoscaler(node: CephAdmin, **kwargs) -> bool:
"""
Configures pg_Autoscaler as a global global parameter and on pools
Args:
node: Cephadm node where the commands need to be executed
**kwargs: Any other param that needs to be set
Returns: True -> pass, False -> fail
... | def configure_pg_autoscaler(node: CephAdmin, **kwargs) -> bool:
| """
Configures pg_Autoscaler as a global global parameter and on pools
Args:
node: Cephadm node where the commands need to be executed
**kwargs: Any other param that needs to be set
Returns: True -> pass, False -> fail
"""
if kwargs.get("enable"):
mgr_modules = run_ceph... |
if not create_pool(
node=node,
ec_profile_name=profile_name,
**kwargs,
):
log.error(f"Failed to create Pool {pool_name}")
return False
log.info(f"Created the ec profile : {profile_name} and pool : {pool_name}")
return True
def configure_pg_autoscaler(node: CephAd... | 85 | 85 | 286 | 18 | 66 | anrao19/cephci | tests/rados/rados_prep.py | Python | configure_pg_autoscaler | configure_pg_autoscaler | 346 | 377 | 346 | 346 | 8f617bdc622136acdbadd0ca2b73043b48ae0182 | bigcode/the-stack | train |
4d980ec64d9a438720f93832 | train | function | def enable_balancer(node: CephAdmin, **kwargs) -> bool:
"""
Enables the balancer module with the given mode
Args:
node: Cephadm node where the commands need to be executed
kwargs: Any other args that need to be passed
Returns: True -> pass, False -> fail
"""
# balancer is always ... | def enable_balancer(node: CephAdmin, **kwargs) -> bool:
| """
Enables the balancer module with the given mode
Args:
node: Cephadm node where the commands need to be executed
kwargs: Any other args that need to be passed
Returns: True -> pass, False -> fail
"""
# balancer is always enabled module, There is no need to enable the module vi... | d pool delete {pool} {pool} --yes-i-really-really-mean-it"
node.shell([cmd])
existing_pools = run_ceph_command(node, cmd="ceph df")
if pool not in [ele["name"] for ele in existing_pools["pools"]]:
log.info(f"Pool:{pool} deleted Successfully")
return True
log.error(f"Pool:{pool} could no... | 116 | 116 | 389 | 16 | 99 | anrao19/cephci | tests/rados/rados_prep.py | Python | enable_balancer | enable_balancer | 411 | 450 | 411 | 411 | 06c00a0b107d3fc5899bc65c47d0f08dc10c2b01 | bigcode/the-stack | train |
3616d1270ff7a6bc3e714767 | train | function | def run(ceph_cluster, **kw):
"""
Prepares the cluster to run rados tests.
Actions Performed:
1. Create a Replicated and Erasure coded pools and write Objects into pools
2. Setup email alerts for sending errors/warnings on the cluster.
Verifies Bugs:
https://bugzilla.redhat.com/show_b... | def run(ceph_cluster, **kw):
| """
Prepares the cluster to run rados tests.
Actions Performed:
1. Create a Replicated and Erasure coded pools and write Objects into pools
2. Setup email alerts for sending errors/warnings on the cluster.
Verifies Bugs:
https://bugzilla.redhat.com/show_bug.cgi?id=1849894
htt... | import json
import logging
import re
import time
from ceph.ceph_admin import CephAdmin
log = logging.getLogger(__name__)
def run(ceph_cluster, **kw):
| 41 | 256 | 974 | 10 | 31 | anrao19/cephci | tests/rados/rados_prep.py | Python | run | run | 11 | 106 | 11 | 11 | 7c026028ad39add07ca0137284944bf264c75328 | bigcode/the-stack | train |
55c2e1ae889289b9a317fd94 | train | function | def run_rados_bench_read(node: CephAdmin, pool_name: str, **kwargs) -> bool:
"""
Method to trigger Read operations via the Rados Bench tool
Args:
node: Cephadm node where the commands need to be executed
pool_name: pool on which the operation will be performed
kwargs: Any other param... | def run_rados_bench_read(node: CephAdmin, pool_name: str, **kwargs) -> bool:
| """
Method to trigger Read operations via the Rados Bench tool
Args:
node: Cephadm node where the commands need to be executed
pool_name: pool on which the operation will be performed
kwargs: Any other param that needs to passed
Returns: True -> pass, False -> fail
"""
... | ([cmd])
return True
except Exception as err:
log.error(f"Error running rados bench write on pool : {pool_name}")
log.error(err)
return False
def run_rados_bench_read(node: CephAdmin, pool_name: str, **kwargs) -> bool:
| 64 | 64 | 210 | 24 | 39 | anrao19/cephci | tests/rados/rados_prep.py | Python | run_rados_bench_read | run_rados_bench_read | 169 | 190 | 169 | 169 | a90191e9946d326cb879fc9db37e5048af490d59 | bigcode/the-stack | train |
221d2892ffb7fe9537d8829b | train | function | def run_ceph_command(node: CephAdmin, cmd: str) -> dict:
"""
Runs ceph commands with json tag for the action specified otherwise treats action as command
and returns formatted output
Args:
node: Cephadm node where the commands need to be executed
cmd: Command that needs to be run
Re... | def run_ceph_command(node: CephAdmin, cmd: str) -> dict:
| """
Runs ceph commands with json tag for the action specified otherwise treats action as command
and returns formatted output
Args:
node: Cephadm node where the commands need to be executed
cmd: Command that needs to be run
Returns: dictionary of the output
"""
cmd = f"{cmd... | log.error(f"Error setting the property : {key} for pool : {pool_name}")
log.error(err)
return False
log.info(f"Created pool {pool_name} successfully")
return True
def run_ceph_command(node: CephAdmin, cmd: str) -> dict:
| 64 | 64 | 114 | 18 | 45 | anrao19/cephci | tests/rados/rados_prep.py | Python | run_ceph_command | run_ceph_command | 502 | 516 | 502 | 502 | cb7fd4f1f468eaff5e8b1b061430c28fbd78ca94 | bigcode/the-stack | train |
79872e942728040f2e44f40b | train | function | def create_erasure_pool(node: CephAdmin, name: str, **kwargs) -> bool:
"""
Creates a erasure code profile and then creates a pool with the same
Args:
node: Cephadm node where the commands need to be executed
name: Name of the profile to create
**kwargs: Any other param that needs to ... | def create_erasure_pool(node: CephAdmin, name: str, **kwargs) -> bool:
| """
Creates a erasure code profile and then creates a pool with the same
Args:
node: Cephadm node where the commands need to be executed
name: Name of the profile to create
**kwargs: Any other param that needs to be set in the EC profile
Returns: True -> pass, False -> fail
... | :
log.error("Error while enabling/disabling alerts module after configuration")
log.error(err)
return False
# Triggering email alert
try:
cmd = "ceph alerts send"
node.shell([cmd])
except Exception as err:
log.error("Error while Sending email alerts")
... | 110 | 110 | 368 | 21 | 88 | anrao19/cephci | tests/rados/rados_prep.py | Python | create_erasure_pool | create_erasure_pool | 303 | 343 | 303 | 303 | 6138527703eb93913b258c2e1e67285c1d5cd691 | bigcode/the-stack | train |
42ab999edabed1bba24f9fdf | train | function | def create_pool(node: CephAdmin, pool_name: str, pg_num: int = 64, **kwargs) -> bool:
"""
Create a pool named from the pool_name parameter.
Args:
node: Cephadm node where the commands need to be executed
pool_name: name of the pool being created.
pg_num: initial number of pgs.
... | def create_pool(node: CephAdmin, pool_name: str, pg_num: int = 64, **kwargs) -> bool:
| """
Create a pool named from the pool_name parameter.
Args:
node: Cephadm node where the commands need to be executed
pool_name: name of the pool being created.
pg_num: initial number of pgs.
kwargs: Any other args that need to be passed
Returns: True -> pass, False ->... | map")
cmd = f"ceph balancer mode {balancer_mode}"
node.shell([cmd])
# Turning on the balancer on the system
cmd = "ceph balancer on"
node.shell([cmd])
# Sleeping for 10 seconds after enabling balancer and then collecting the evaluation status
time.sleep(10)
cmd = "ceph balancer status"
... | 154 | 154 | 514 | 28 | 125 | anrao19/cephci | tests/rados/rados_prep.py | Python | create_pool | create_pool | 453 | 499 | 453 | 453 | b02eb03b6c5b26c7246800126582174e6623cdf1 | bigcode/the-stack | train |
0604a6f88a2393531abb4181 | train | function | def enable_email_alerts(node: CephAdmin, **kwargs) -> bool:
"""
Enables the email alerts module and configures alerts to be sent
Args:
node: Cephadm node where the commands need to be executed
**kwargs: Any other param that needs to be set
Returns: True -> pass, False -> fail
"""
... | def enable_email_alerts(node: CephAdmin, **kwargs) -> bool:
| """
Enables the email alerts module and configures alerts to be sent
Args:
node: Cephadm node where the commands need to be executed
**kwargs: Any other param that needs to be set
Returns: True -> pass, False -> fail
"""
alert_cmds = {
"smtp_host": f"ceph config set mgr ... | \s+([\w]*)\s+[\w\s:]*(ceph[\w.]*log)"
perm = "-rw-------"
user = "ceph"
files = ["ceph.log", "ceph.audit.log"]
if re.search(regex, out):
match = re.findall(regex, out)
for val in match:
if not (val[0] == perm and val[1] == user and val[2] == user):
log.error(f... | 180 | 181 | 606 | 17 | 162 | anrao19/cephci | tests/rados/rados_prep.py | Python | enable_email_alerts | enable_email_alerts | 234 | 300 | 234 | 234 | d7b0e5dd639a4c848551709ffe5314b12b4568d8 | bigcode/the-stack | train |
24c495ddf478a9650293329e | train | function | def set_cluster_configuration_checks(node: CephAdmin, **kwargs) -> bool:
"""
Sets up Cephadm to periodically scan each of the hosts in the cluster, and to understand the state of the OS,
disks, NICs etc
ref doc : https://docs.ceph.com/en/latest/cephadm/operations/#cluster-configuration-checks
Args... | def set_cluster_configuration_checks(node: CephAdmin, **kwargs) -> bool:
| """
Sets up Cephadm to periodically scan each of the hosts in the cluster, and to understand the state of the OS,
disks, NICs etc
ref doc : https://docs.ceph.com/en/latest/cephadm/operations/#cluster-configuration-checks
Args:
node: Cephadm node where the commands need to be executed
... | caler")
if not configure_pg_autoscaler(node=cephadm, **autoscaler_config):
log.error("Error while setting up pg_autoscaler on the Cluster")
return 1
log.info("Set up pg_autoscaler on the cluster")
log.info("All Pre-requisites completed to run Rados suite")
return 0
def s... | 93 | 93 | 312 | 17 | 75 | anrao19/cephci | tests/rados/rados_prep.py | Python | set_cluster_configuration_checks | set_cluster_configuration_checks | 109 | 143 | 109 | 109 | 6bae9ddbde25382b867a8958adde83784c88135a | bigcode/the-stack | train |
d401d0dbfe60376df35f0183 | train | function | @app.route('/mine', methods=['GET'])
def mine():
# Run the proof of work algorithm to get the next proof
proof = blockchain.proof_of_work()
# Forge the new Block by adding it to the chain with the proof
previous_hash = blockchain.hash(blockchain.last_block)
block = blockchain.new_block(proof, previ... | @app.route('/mine', methods=['GET'])
def mine():
# Run the proof of work algorithm to get the next proof
| proof = blockchain.proof_of_work()
# Forge the new Block by adding it to the chain with the proof
previous_hash = blockchain.hash(blockchain.last_block)
block = blockchain.new_block(proof, previous_hash)
response = {
'message': "New Block Forged",
'index': block['index'],
'... |
app = Flask(__name__)
# Generate a globally unique address for this node
node_identifier = str(uuid4()).replace('-', '')
# Instantiate the Blockchain
blockchain = Blockchain()
@app.route('/mine', methods=['GET'])
def mine():
# Run the proof of work algorithm to get the next proof
| 64 | 64 | 132 | 26 | 38 | bradzickafoose/Blockchain | basic_block_gp/blockchain.py | Python | mine | mine | 118 | 135 | 118 | 120 | 50685e40e706aa84646e09056652226ec1bd1a84 | bigcode/the-stack | train |
874b84621bfbeb36c3f9df0c | train | function | @app.route('/chain', methods=['GET'])
def full_chain():
response = {
'length': len(blockchain.chain),
'chain': blockchain.chain
}
return jsonify(response), 200
| @app.route('/chain', methods=['GET'])
def full_chain():
| response = {
'length': len(blockchain.chain),
'chain': blockchain.chain
}
return jsonify(response), 200
| ': "New Block Forged",
'index': block['index'],
'transactions': block['transactions'],
'proof': block['proof'],
'previous_hash': block['previous_hash'],
}
return jsonify(response), 200
@app.route('/chain', methods=['GET'])
def full_chain():
| 64 | 64 | 43 | 13 | 50 | bradzickafoose/Blockchain | basic_block_gp/blockchain.py | Python | full_chain | full_chain | 138 | 144 | 138 | 139 | ab63af417c86593e5c5c1695548d1e564452a67e | bigcode/the-stack | train |
3ba635e828f87fe39ab47565 | train | class | class Blockchain(object):
def __init__(self):
self.chain = []
self.current_transactions = []
# Create the genesis block
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain
... | class Blockchain(object):
| def __init__(self):
self.chain = []
self.current_transactions = []
# Create the genesis block
self.new_block(previous_hash=1, proof=100)
def new_block(self, proof, previous_hash=None):
"""
Create a new Block in the Blockchain
A block should have:
... | import hashlib
import json
from time import time
from uuid import uuid4
from flask import Flask, jsonify, request
class Blockchain(object):
| 30 | 226 | 754 | 4 | 25 | bradzickafoose/Blockchain | basic_block_gp/blockchain.py | Python | Blockchain | Blockchain | 8 | 106 | 8 | 8 | 236b2dd0417dee737ec7bd1b4dee1efe371a895b | bigcode/the-stack | train |
26287ddac819bb41d89c7c18 | train | function | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(... | def build_oracle(n: int, f) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-yo... | 138 | 83 | 278 | 138 | 0 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2162.py | Python | build_oracle | build_oracle | 29 | 49 | 29 | 34 | b7a8ed7a88aaeae13a59b1564c24bee83d544220 | bigcode/the-stack | train |
de88f52d4dc26cba577de883 | train | function | def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| def bitwise_dot(s: str, t: str) -> str:
| length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| (s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
| 64 | 64 | 54 | 15 | 49 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2162.py | Python | bitwise_dot | bitwise_dot | 22 | 27 | 22 | 22 | 078fbe078cfdf1766c9b9ac20f7a3207be47445c | bigcode/the-stack | train |
0357c076efdf556b8e2ed3c2 | train | function | def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| def bitwise_xor(s: str, t: str) -> str:
| length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| Register
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2
import numpy as np
import networkx as nx
def bitwise_xor(s: str, t: str) -> str:
| 64 | 64 | 54 | 16 | 47 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2162.py | Python | bitwise_xor | bitwise_xor | 14 | 19 | 14 | 14 | 643dca80c9054c8a7c10bfe226d5dd994f1f8215 | bigcode/the-stack | train |
ee41133f90615b9e3c9a2c2d | train | function | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.x(input_qubit[3]) # number=1
prog.h(input_qubit[0]) # number=18
prog.cz(input_qubit[3],input_qubit[0]) ... | def make_circuit(n:int,f) -> QuantumCircuit:
# circuit begin
| input_qubit = QuantumRegister(n,"qc")
classical = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classical)
prog.x(input_qubit[3]) # number=1
prog.h(input_qubit[0]) # number=18
prog.cz(input_qubit[3],input_qubit[0]) # number=19
prog.h(input_qubit[2]) # number=24
prog.h(inp... | "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.m... | 150 | 150 | 502 | 17 | 132 | UCLA-SEAL/QDiff | benchmark/startQiskit_Class2162.py | Python | make_circuit | make_circuit | 51 | 90 | 51 | 52 | 96bb81a285f0acdf99a91eadfdbc5217daef22fe | bigcode/the-stack | train |
3f5221a2e5f1062e7b4a12e2 | train | function | def runner():
import stacklog
return stacklog.gather()
| def runner():
| import stacklog
return stacklog.gather()
| dv = None
"""
maybe the data structure we really want is
key: [(value, children),(value, children),(value, children)]
where each value is the time it took on each process.
'prox': [(total_time, {}), ]
"""
# put the wrapping timing code in runner?
def runner():
| 64 | 64 | 15 | 3 | 61 | ajfriend/stacklog | stacklog/parallel.py | Python | runner | runner | 22 | 24 | 22 | 22 | 5f8bc629729c01b2943560d1f75fc4ddaa2baa05 | bigcode/the-stack | train |
eb9af0cde1eb69b61a20a2fa | train | function | def paralell_init(the_dv):
global dv
dv = the_dv
#todo: relative import?
dv.execute('import stacklog', block=True)
| def paralell_init(the_dv):
| global dv
dv = the_dv
#todo: relative import?
dv.execute('import stacklog', block=True)
|
dv.execute('stacklog.gather()', block=True)
logger.tic(key)
yield
elapsed, children = logger.toc(record=False)
dicts = dv.apply_sync(runner)
logger.record(key, elapsed, children, *dicts)
def paralell_init(the_dv):
| 64 | 64 | 37 | 8 | 56 | ajfriend/stacklog | stacklog/parallel.py | Python | paralell_init | paralell_init | 42 | 47 | 42 | 42 | 3622e53161365fa4ec4ccdb2de69b7d4eda26d50 | bigcode/the-stack | train |
02481393c581aa088bf7f8a3 | train | function | @contextmanager
def par(key):
global logs, dv
logger = logs['default']
# clear the remote stacks
dv.execute('stacklog.gather()', block=True)
logger.tic(key)
yield
elapsed, children = logger.toc(record=False)
dicts = dv.apply_sync(runner)
logger.record(key, elapsed, children, *dict... | @contextmanager
def par(key):
| global logs, dv
logger = logs['default']
# clear the remote stacks
dv.execute('stacklog.gather()', block=True)
logger.tic(key)
yield
elapsed, children = logger.toc(record=False)
dicts = dv.apply_sync(runner)
logger.record(key, elapsed, children, *dicts)
| ),(value, children),(value, children)]
where each value is the time it took on each process.
'prox': [(total_time, {}), ]
"""
# put the wrapping timing code in runner?
def runner():
import stacklog
return stacklog.gather()
@contextmanager
def par(key):
| 64 | 64 | 83 | 8 | 56 | ajfriend/stacklog | stacklog/parallel.py | Python | par | par | 26 | 39 | 26 | 27 | d12964039a10a5ced0d8fd0c6ae385a3634ffeb9 | bigcode/the-stack | train |
ffd6aaca432fe206edfe9a26 | train | function | def parse_arguments(sah_user):
parser = argparse.ArgumentParser(
description="Configures DHCP server on SAH node for use by iDRACs.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("sah_ip",
help="""The IP address of the SAH node on the
... | def parse_arguments(sah_user):
| parser = argparse.ArgumentParser(
description="Configures DHCP server on SAH node for use by iDRACs.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("sah_ip",
help="""The IP address of the SAH node on the
provi... | command_helper import Scp
from command_helper import Ssh
from getpass import getpass
from logging_helper import LoggingHelper
from network_helper import NetworkHelper
logging.basicConfig()
LOG = logging.getLogger(os.path.splitext(os.path.basename(sys.argv[0]))[0])
def parse_arguments(sah_user):
| 64 | 64 | 114 | 7 | 57 | calsoft-internal/JetPack | src/pilot/config_idrac_dhcp.py | Python | parse_arguments | parse_arguments | 32 | 45 | 32 | 32 | aa2bc3870bbab45b03652211615763f6df0abdf9 | bigcode/the-stack | train |
c6629f685f91339c8b7a0f5a | train | function | def main():
sah_user = "root"
args = parse_arguments(sah_user)
LoggingHelper.configure_logging(args.logging_level,
noisy_logger="paramiko")
sah_password = args.password
if not sah_password:
sah_password = getpass("Enter the password for the "
... | def main():
| sah_user = "root"
args = parse_arguments(sah_user)
LoggingHelper.configure_logging(args.logging_level,
noisy_logger="paramiko")
sah_password = args.password
if not sah_password:
sah_password = getpass("Enter the password for the "
... | 2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License... | 256 | 256 | 903 | 3 | 253 | calsoft-internal/JetPack | src/pilot/config_idrac_dhcp.py | Python | main | main | 48 | 146 | 48 | 48 | c8ff17acb1f16f11e8ff427199d02e9ec8ed35ec | bigcode/the-stack | train |
327738de674b6876b6057bd5 | train | function | def scaled(target, prop, factor):
r"""
Scales an existing value by a factor. Useful for constricting some throat
property.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also pr... | def scaled(target, prop, factor):
| r"""
Scales an existing value by a factor. Useful for constricting some throat
property.
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
nec... | `
by including additional arguments in the function call (i.e. ``prop3 =
'pore.foo'``).
"""
value = target[prop1]*target[prop2]
for item in kwargs.values():
value *= target[item]
return value
def scaled(target, prop, factor):
| 64 | 64 | 153 | 8 | 55 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | scaled | scaled | 181 | 206 | 181 | 181 | 1d2d3ee163c021b9119b17b5022acacc414d91fa | bigcode/the-stack | train |
d065b056673b62eac0093508 | train | function | def constant(target, value):
r"""
Places the given constant value into the target object
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessar... | def constant(target, value):
| r"""
Places the given constant value into the target object
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
value : sc... | necessary properties.
xmin : float
Values below this limit will be replaced with ``xmin``.
xmax : float
Values above this limit will be replaced with ``xmax``.
"""
vals = np.clip(target[prop], xmin, xmax)
return vals
def constant(target, value):
| 64 | 64 | 140 | 6 | 57 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | constant | constant | 118 | 143 | 118 | 118 | 0b0f768886b7fd4da1c577b1ce5e4a3c5551b9c8 | bigcode/the-stack | train |
baf3a334382876b6b62b4e8b | train | function | def summation(target, props=[]):
r"""
Sums the values in the given arrays
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
... | def summation(target, props=[]):
| r"""
Sums the values in the given arrays
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
props : list of dictionary ke... | access to other
necessary properties.
numerator : string
Dictionary key pointing the numerator values
denominator : string
Dictionary key pointing the denominator values
"""
x = target[numerator]
y = target[denominator]
return x/y
def summation(target, props=[]):
| 64 | 64 | 117 | 8 | 55 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | summation | summation | 52 | 70 | 52 | 52 | 2203b60ff0849e2f372f12af9833b3466b9f4caf | bigcode/the-stack | train |
2e6ca00ba5a0ab162b5f596d | train | function | def normalize(target, prop, xmin=0, xmax=1):
r"""
Normalizes the given array between the supplied limits
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
... | def normalize(target, prop, xmin=0, xmax=1):
| r"""
Normalizes the given array between the supplied limits
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
xmin : flo... | props : list of dictionary keys
The dictionary keys pointing the arrays whose elements should be summed
"""
vals = np.zeros_like(target[props[0]])
for item in props:
vals += target[item]
return vals
def normalize(target, prop, xmin=0, xmax=1):
| 64 | 64 | 155 | 14 | 49 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | normalize | normalize | 73 | 94 | 73 | 73 | 57c9d4c3cc253e19e0abd9dbf6f5de85ef299fcf | bigcode/the-stack | train |
24ae674ccf161048e09f13fe | train | function | def blank(target):
pass
| def blank(target):
| pass
| r"""
"""
import numpy as np
from openpnm.utils import logging
logger = logging.getLogger(__name__)
def blank(target):
| 28 | 64 | 7 | 4 | 24 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | blank | blank | 8 | 9 | 8 | 8 | 17f496333f85686f016a15b2c1c2383ec21a81ee | bigcode/the-stack | train |
50b44e40b560640d2295a246 | train | function | def fraction(target, numerator, denominator):
r"""
Calculates the ratio between two values
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necess... | def fraction(target, numerator, denominator):
| r"""
Calculates the ratio between two values
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
numerator : string
... | object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : string
Dictionary key pointing the values to invert
"""
return 1.0/target[prop]
def fraction(target, numerator, denominator)... | 64 | 64 | 112 | 8 | 56 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | fraction | fraction | 30 | 49 | 30 | 30 | 7079973d36255d01db68795712dc899607ff180c | bigcode/the-stack | train |
daf2ebbf2f9e33e8d4f713cd | train | function | def invert(target, prop):
r"""
Inverts the given array
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : string
... | def invert(target, prop):
| r"""
Inverts the given array
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop : string
Dictionary key poin... | r"""
"""
import numpy as np
from openpnm.utils import logging
logger = logging.getLogger(__name__)
def blank(target):
pass
def invert(target, prop):
| 37 | 64 | 87 | 6 | 30 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | invert | invert | 12 | 27 | 12 | 12 | e2edc1e8e6f19186d0a6f797a2bb624856e40a8a | bigcode/the-stack | train |
e9659900e32205a7f6a6ea67 | train | function | def clip(target, prop, xmax, xmin=0):
r"""
Clips the given array within the supplied limits
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
neces... | def clip(target, prop, xmax, xmin=0):
| r"""
Clips the given array within the supplied limits
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
xmin : float
... | """
vals = target[prop]
# Scale to 0 to 1
vals = (vals - vals.min())/(vals.max() - vals.min())
vals = vals*(xmax - xmin) + xmin
return vals
def clip(target, prop, xmax, xmin=0):
| 64 | 64 | 124 | 12 | 51 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | clip | clip | 97 | 115 | 97 | 97 | cc0ab529ba9982b05dc771c78e178c8d9ea76a92 | bigcode/the-stack | train |
8ff3a7cb62f8208c8737d36d | train | function | def product(target, prop1, prop2, **kwargs):
r"""
Calculates the product of multiple property values
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
... | def product(target, prop1, prop2, **kwargs):
| r"""
Calculates the product of multiple property values
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the calculated array, and also provides access to other
necessary properties.
prop1 : string... | Array containing constant values equal to ``value``.
Notes
-----
This model is mostly useless and for testing purposes, but might be used
to 'reset' an array back to a default value.
"""
return value
def product(target, prop1, prop2, **kwargs):
| 64 | 64 | 209 | 13 | 50 | halotudio/openPNM-copy2 | openpnm/models/misc/basic_math.py | Python | product | product | 146 | 178 | 146 | 146 | a6fbbcdab83a4492b93e8379afd70f4104a557f2 | bigcode/the-stack | train |
7ddd19c313f8ff11abc24c7c | train | class | class EndDuelCommand(BaseSwgCommand):
def Run(self):
actor = self.GetActor()
target = self.GetTarget()
service_mgr = self.GetKernel().service_manager()
combat_svc = service_mgr.combat_service()
if (actor and target):
combat_svc.end_duel(actor, target)
| class EndDuelCommand(BaseSwgCommand):
| def Run(self):
actor = self.GetActor()
target = self.GetTarget()
service_mgr = self.GetKernel().service_manager()
combat_svc = service_mgr.combat_service()
if (actor and target):
combat_svc.end_duel(actor, target)
| from swgpy.command import BaseSwgCommand
class EndDuelCommand(BaseSwgCommand):
| 21 | 64 | 70 | 10 | 10 | JohnShandy/swganh | data/scripts/commands/endduel.py | Python | EndDuelCommand | EndDuelCommand | 3 | 11 | 3 | 3 | 4ed9ee3a0599fdff1e0e3899ce6b0403e443ac6e | bigcode/the-stack | train |
588851d85538bd56cd075366 | train | class | class SigningMessage(Message):
"""A protocol for communication between skills and decision maker."""
protocol_id = PublicId.from_str("fetchai/signing:1.0.0")
protocol_specification_id = PublicId.from_str("fetchai/signing:1.0.0")
ErrorCode = CustomErrorCode
RawMessage = CustomRawMessage
RawTr... | class SigningMessage(Message):
| """A protocol for communication between skills and decision maker."""
protocol_id = PublicId.from_str("fetchai/signing:1.0.0")
protocol_specification_id = PublicId.from_str("fetchai/signing:1.0.0")
ErrorCode = CustomErrorCode
RawMessage = CustomRawMessage
RawTransaction = CustomRawTransactio... | .
#
# ------------------------------------------------------------------------------
"""This module contains signing's message definition."""
# pylint: disable=too-many-statements,too-many-locals,no-member,too-few-public-methods,too-many-branches,not-an-iterable,unidiomatic-typecheck,unsubscriptable-object
import log... | 256 | 256 | 1,934 | 5 | 250 | BuildJet/agents-aea | packages/fetchai/protocols/signing/message.py | Python | SigningMessage | SigningMessage | 51 | 316 | 51 | 51 | 4d855f086c9998728c89744e34af3b52cece9ff3 | bigcode/the-stack | train |
518fb5ef685804931f892861 | train | function | def compare_evals_with_precision(fit_eval, calc_eval, rtol=1e-6, atol=1e-8, skip_last_column_in_fit=True):
df_fit = read_csv(fit_eval, sep='\t')
if skip_last_column_in_fit:
df_fit = df_fit.iloc[:, :-1]
df_calc = read_csv(calc_eval, sep='\t')
if np.any(df_fit.columns != df_calc.columns):
... | def compare_evals_with_precision(fit_eval, calc_eval, rtol=1e-6, atol=1e-8, skip_last_column_in_fit=True):
| df_fit = read_csv(fit_eval, sep='\t')
if skip_last_column_in_fit:
df_fit = df_fit.iloc[:, :-1]
df_calc = read_csv(calc_eval, sep='\t')
if np.any(df_fit.columns != df_calc.columns):
sys.stderr.write('column sets differ: {}, {}'.format(df_fit.columns, df_calc.columns))
return Fal... | (csv_calc)
while True:
try:
line_fit = next(csv_fit)
line_calc = next(csv_calc)
if line_fit[:-1] != line_calc:
return False
except StopIteration:
break
return True
def compare_evals_with_precision(fit_eval, calc_eval, rtol=1e-6, ato... | 88 | 88 | 296 | 35 | 52 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | compare_evals_with_precision | compare_evals_with_precision | 303 | 334 | 303 | 303 | 67827510b292803b758cd94e1f84e777e4e95914 | bigcode/the-stack | train |
014658b67dab8710abc38db7 | train | function | def append_params_to_cmdline(cmd, params):
if isinstance(params, dict):
for param in params.items():
key = "{}".format(param[0])
value = "{}".format(param[1])
cmd.append(key)
cmd.append(value)
else:
for param in params:
cmd.append(param... | def append_params_to_cmdline(cmd, params):
| if isinstance(params, dict):
for param in params.items():
key = "{}".format(param[0])
value = "{}".format(param[1])
cmd.append(key)
cmd.append(value)
else:
for param in params:
cmd.append(param)
| _file, cd_file):
columns_metadata = read_cd(cd_file, data_file=pool_file, canonize_column_types=True)
data = load_dataset_as_dataframe(pool_file, columns_metadata)
return (data['features'], columns_metadata['cat_feature_indices'])
def append_params_to_cmdline(cmd, params):
| 63 | 64 | 68 | 10 | 53 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | append_params_to_cmdline | append_params_to_cmdline | 379 | 388 | 379 | 379 | 6a1d3034730f7a6187ac0fdb99438d48b1c30ab7 | bigcode/the-stack | train |
675fbba4e22e58b463b38c76 | train | function | def remove_time_from_json(filename):
with open(filename) as f:
log = json.load(f)
iterations = log['iterations']
for i, iter_info in enumerate(iterations):
for key in ['remaining_time', 'passed_time']:
if key in iter_info.keys():
del iter_info[key]
with open(f... | def remove_time_from_json(filename):
| with open(filename) as f:
log = json.load(f)
iterations = log['iterations']
for i, iter_info in enumerate(iterations):
for key in ['remaining_time', 'passed_time']:
if key in iter_info.keys():
del iter_info[key]
with open(filename, 'w') as f:
json.dump... | test_output_path = yatest.common.test_output_path
except ImportError:
def binary_path(*path):
return os.path.join(os.environ["BINARY_PATH"], *path)
def test_output_path(*path):
return os.path.join(os.getcwd(), *path)
def remove_time_from_json(filename):
| 64 | 64 | 92 | 7 | 57 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | remove_time_from_json | remove_time_from_json | 47 | 57 | 47 | 47 | 843573cdfd0d84fb77dfba5286436c1a438e44b4 | bigcode/the-stack | train |
8cb4cf176f7a217a67c45612 | train | function | def get_limited_precision_numpy_diff_tool(rtol=None, atol=None):
diff_tool = [
binary_path("catboost/tools/limited_precision_numpy_diff/limited_precision_numpy_diff"),
]
if rtol is not None:
diff_tool += ['--rtol', str(rtol)]
if atol is not None:
diff_tool += ['--atol', str(atol)... | def get_limited_precision_numpy_diff_tool(rtol=None, atol=None):
| diff_tool = [
binary_path("catboost/tools/limited_precision_numpy_diff/limited_precision_numpy_diff"),
]
if rtol is not None:
diff_tool += ['--rtol', str(rtol)]
if atol is not None:
diff_tool += ['--atol', str(atol)]
return diff_tool
| _tool = [
binary_path("catboost/tools/limited_precision_json_diff/limited_precision_json_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
return diff_tool
def get_limited_precision_numpy_diff_tool(rtol=None, atol=None):
| 64 | 64 | 86 | 15 | 48 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | get_limited_precision_numpy_diff_tool | get_limited_precision_numpy_diff_tool | 416 | 424 | 416 | 416 | 5399092cf8210b0fbbcb38d8cf6f90652100df49 | bigcode/the-stack | train |
13f01f7dc03f804ee90c4b1f | train | function | def format_crossvalidation(is_inverted, n, k):
cv_type = 'Inverted' if is_inverted else 'Classical'
return '{}:{};{}'.format(cv_type, n, k)
| def format_crossvalidation(is_inverted, n, k):
| cv_type = 'Inverted' if is_inverted else 'Classical'
return '{}:{};{}'.format(cv_type, n, k)
| ):
for param in params.items():
key = "{}".format(param[0])
value = "{}".format(param[1])
cmd.append(key)
cmd.append(value)
else:
for param in params:
cmd.append(param)
def format_crossvalidation(is_inverted, n, k):
| 64 | 64 | 43 | 12 | 52 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | format_crossvalidation | format_crossvalidation | 391 | 393 | 391 | 391 | a74d76d031543afb216f3a6838a8ea1a6dba703a | bigcode/the-stack | train |
6378a7d7860e42c6830949f4 | train | function | def load_dataset_as_dataframe(data_file, columns_metadata, has_header=False):
"""
returns dict with 'features', 'target' keys
"""
if 'Label' not in columns_metadata['column_type_to_indices']:
raise Exception('no target in dataset')
df = read_csv(
data_file,
sep='\t',
... | def load_dataset_as_dataframe(data_file, columns_metadata, has_header=False):
| """
returns dict with 'features', 'target' keys
"""
if 'Label' not in columns_metadata['column_type_to_indices']:
raise Exception('no target in dataset')
df = read_csv(
data_file,
sep='\t',
header=1 if has_header else None
)
df.columns = columns_metadat... | =1e-8):
return compare_evals_with_precision(
fit_eval_1,
fit_eval_2,
rtol=rtol,
atol=atol,
skip_last_column_in_fit=False
)
def load_dataset_as_dataframe(data_file, columns_metadata, has_header=False):
| 64 | 64 | 161 | 15 | 49 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | load_dataset_as_dataframe | load_dataset_as_dataframe | 347 | 369 | 347 | 347 | c88d94d776600470ea78166176daea55bad3d97a | bigcode/the-stack | train |
efa7b624b482402fcdc4e60a | train | function | def compare_evals(fit_eval, calc_eval, skip_header=False):
csv_fit = csv.reader(open(fit_eval, "r"), dialect='excel-tab')
csv_calc = csv.reader(open(calc_eval, "r"), dialect='excel-tab')
if skip_header:
next(csv_fit)
next(csv_calc)
while True:
try:
line_fit = next(csv... | def compare_evals(fit_eval, calc_eval, skip_header=False):
| csv_fit = csv.reader(open(fit_eval, "r"), dialect='excel-tab')
csv_calc = csv.reader(open(calc_eval, "r"), dialect='excel-tab')
if skip_header:
next(csv_fit)
next(csv_calc)
while True:
try:
line_fit = next(csv_fit)
line_calc = next(csv_calc)
if... | Exception('{}, iter {}: fit vs calc = {} vs {}, err = {} > eps = {}'.format(
metric_name, line_fit[0], fit_value, calc_value, err, eps))
except StopIteration:
break
def compare_evals(fit_eval, calc_eval, skip_header=False):
| 64 | 64 | 117 | 15 | 48 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | compare_evals | compare_evals | 286 | 300 | 286 | 286 | d89a87b5a1efc20f3977b1e6db77d0aff3076b4e | bigcode/the-stack | train |
374278151c8be9856d6414f3 | train | function | def compare_fit_evals_with_precision(fit_eval_1, fit_eval_2, rtol=1e-6, atol=1e-8):
return compare_evals_with_precision(
fit_eval_1,
fit_eval_2,
rtol=rtol,
atol=atol,
skip_last_column_in_fit=False
)
| def compare_fit_evals_with_precision(fit_eval_1, fit_eval_2, rtol=1e-6, atol=1e-8):
| return compare_evals_with_precision(
fit_eval_1,
fit_eval_2,
rtol=rtol,
atol=atol,
skip_last_column_in_fit=False
)
| np.any(is_close == 0):
print_diff(column, np.where(is_close == 0)[0])
return False
return True
def compare_fit_evals_with_precision(fit_eval_1, fit_eval_2, rtol=1e-6, atol=1e-8):
| 64 | 64 | 76 | 33 | 30 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | compare_fit_evals_with_precision | compare_fit_evals_with_precision | 337 | 344 | 337 | 337 | 9b9d6fb11f125d9092f3337289c44e50c174d73b | bigcode/the-stack | train |
5dfc67a19f2b1f09518df72f | train | function | def load_pool_features_as_df(pool_file, cd_file):
columns_metadata = read_cd(cd_file, data_file=pool_file, canonize_column_types=True)
data = load_dataset_as_dataframe(pool_file, columns_metadata)
return (data['features'], columns_metadata['cat_feature_indices'])
| def load_pool_features_as_df(pool_file, cd_file):
| columns_metadata = read_cd(cd_file, data_file=pool_file, canonize_column_types=True)
data = load_dataset_as_dataframe(pool_file, columns_metadata)
return (data['features'], columns_metadata['cat_feature_indices'])
| column_type_to_indices']['Label'][0]].values
df.drop(columns=df.columns[columns_metadata['non_feature_column_indices']], inplace=True)
result['features'] = df
return result
# returns (features DataFrame, cat_feature_indices)
def load_pool_features_as_df(pool_file, cd_file):
| 64 | 64 | 60 | 12 | 52 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | load_pool_features_as_df | load_pool_features_as_df | 373 | 376 | 373 | 373 | 91b010aed87e43889852929ab7be166232f5c10c | bigcode/the-stack | train |
3385bb15cc1557f63da43ca3 | train | function | def permute_dataset_columns(test_pool_path, cd_path, seed=123):
permuted_test_path = test_output_path('permuted_test')
permuted_cd_path = test_output_path('permuted_cd')
generator = random.Random(seed)
column_count = len(open(test_pool_path).readline().split('\t'))
permutation = list(range(column_co... | def permute_dataset_columns(test_pool_path, cd_path, seed=123):
| permuted_test_path = test_output_path('permuted_test')
permuted_cd_path = test_output_path('permuted_cd')
generator = random.Random(seed)
column_count = len(open(test_pool_path).readline().split('\t'))
permutation = list(range(column_count))
generator.shuffle(permutation)
with open(cd_path) ... | .flush()
os.dup2(self._old_src_stream, self.src_stream.fileno())
self.dst_stream.seek(self._old_dst_stream_pos)
shutil.copyfileobj(self.dst_stream, self.src_stream)
self.dst_stream.seek(self._old_dst_stream_pos)
def permute_dataset_columns(test_pool_path, cd_path, seed=123):
| 72 | 72 | 241 | 16 | 56 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | permute_dataset_columns | permute_dataset_columns | 81 | 100 | 81 | 81 | 9ac08283caa0d4dd7d3eca49e09714270fb813bd | bigcode/the-stack | train |
3e2a7ff21c3d8ddae8c99d06 | train | function | def generate_patients_datasets(train_path, test_path):
samples = 237
for samples, path in zip([237, 154], [train_path, test_path]):
data = DataFrame()
data['age'] = np.random.randint(20, 71, size=samples)
data['gender'] = np.where(np.random.binomial(1, 0.7, samples) == 1, 'male', 'femal... | def generate_patients_datasets(train_path, test_path):
| samples = 237
for samples, path in zip([237, 154], [train_path, test_path]):
data = DataFrame()
data['age'] = np.random.randint(20, 71, size=samples)
data['gender'] = np.where(np.random.binomial(1, 0.7, samples) == 1, 'male', 'female')
data['diet'] = np.where(np.random.binomial(... | ated_random_labeled_dataset(nrows, nvals, labels, seed=20181219, prng=None):
if prng is None:
prng = np.random.RandomState(seed=seed)
label = prng.choice(labels, [nrows, 1])
feature = prng.random_sample([nrows, nvals])
return np.concatenate([label, feature], axis=1)
def generate_patients_dataset... | 96 | 96 | 322 | 12 | 84 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | generate_patients_datasets | generate_patients_datasets | 111 | 131 | 111 | 111 | e9ad0244f4501a770ed866db17ce1e3ed96a42f1 | bigcode/the-stack | train |
9763652b342bbfad02d4d8d3 | train | function | def compare_metrics_with_diff(custom_metric, fit_eval, calc_eval, eps=1e-7):
csv_fit = csv.reader(open(fit_eval, "r"), dialect='excel-tab')
csv_calc = csv.reader(open(calc_eval, "r"), dialect='excel-tab')
head_fit = next(csv_fit)
head_calc = next(csv_calc)
if isinstance(custom_metric, str):
... | def compare_metrics_with_diff(custom_metric, fit_eval, calc_eval, eps=1e-7):
| csv_fit = csv.reader(open(fit_eval, "r"), dialect='excel-tab')
csv_calc = csv.reader(open(calc_eval, "r"), dialect='excel-tab')
head_fit = next(csv_fit)
head_calc = next(csv_calc)
if isinstance(custom_metric, str):
custom_metric = [custom_metric]
for metric_name in deepcopy(custom_met... | _lower[train_ids], y_upper[train_ids]
X_test, y_lower_test, y_upper_test = X[test_ids], y_lower[test_ids], y_upper[test_ids]
return [(X_train, y_lower_train, y_upper_train), (X_test, y_lower_test, y_upper_test)]
BY_CLASS_METRICS = ['AUC', 'Precision', 'Recall', 'F1']
def compare_metrics_with_diff(custom_metr... | 105 | 105 | 353 | 21 | 84 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | compare_metrics_with_diff | compare_metrics_with_diff | 245 | 283 | 245 | 245 | 3e10eb2dd794ac003b94afe1f538001a6d5670d6 | bigcode/the-stack | train |
a5110fecc904f17b5d76a0a9 | train | function | def get_limited_precision_json_diff_tool(diff_limit):
diff_tool = [
binary_path("catboost/tools/limited_precision_json_diff/limited_precision_json_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
return diff_tool
| def get_limited_precision_json_diff_tool(diff_limit):
| diff_tool = [
binary_path("catboost/tools/limited_precision_json_diff/limited_precision_json_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
return diff_tool
| _precision_dsv_diff/limited_precision_dsv_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
if have_header:
diff_tool += ['--have-header']
return diff_tool
def get_limited_precision_json_diff_tool(diff_limit):
| 64 | 64 | 62 | 11 | 52 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | get_limited_precision_json_diff_tool | get_limited_precision_json_diff_tool | 407 | 413 | 407 | 407 | 238b6b6f424628acb98c1b305567b46c4d3b5090 | bigcode/the-stack | train |
bd871a3393dcf5442459a00b | train | function | def generate_concatenated_random_labeled_dataset(nrows, nvals, labels, seed=20181219, prng=None):
if prng is None:
prng = np.random.RandomState(seed=seed)
label = prng.choice(labels, [nrows, 1])
feature = prng.random_sample([nrows, nvals])
return np.concatenate([label, feature], axis=1)
| def generate_concatenated_random_labeled_dataset(nrows, nvals, labels, seed=20181219, prng=None):
| if prng is None:
prng = np.random.RandomState(seed=seed)
label = prng.choice(labels, [nrows, 1])
feature = prng.random_sample([nrows, nvals])
return np.concatenate([label, feature], axis=1)
| ')
permuted_test.write('\t'.join([splitted[i] for i in permutation]) + '\n')
return permuted_test_path, permuted_cd_path
def generate_concatenated_random_labeled_dataset(nrows, nvals, labels, seed=20181219, prng=None):
| 64 | 64 | 89 | 28 | 35 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | generate_concatenated_random_labeled_dataset | generate_concatenated_random_labeled_dataset | 103 | 108 | 103 | 103 | eea30e5633832a0705a3910662c3aa070815608b | bigcode/the-stack | train |
fe4ac17c6f486540ababeb7a | train | function | def generate_survival_dataset(seed=20201015):
np.random.seed(seed)
X = np.random.rand(200, 20)*10
mean_y = np.sin(X[:, 0])
y = np.random.randn(200, 10) * 0.3 + mean_y[:, None]
y_lower = np.min(y, axis=1)
y_upper = np.max(y, axis=1)
y_upper = np.where(y_upper >= 1.4, -1, y_upper+abs(np.mi... | def generate_survival_dataset(seed=20201015):
| np.random.seed(seed)
X = np.random.rand(200, 20)*10
mean_y = np.sin(X[:, 0])
y = np.random.randn(200, 10) * 0.3 + mean_y[:, None]
y_lower = np.min(y, axis=1)
y_upper = np.max(y, axis=1)
y_upper = np.where(y_upper >= 1.4, -1, y_upper+abs(np.min(y_lower)))
y_lower += abs(np.min(y_lower... | 1] - num_features_range[0]) * (v1 / num_features_density)
)
values.append(num_features_dtype(value))
feature_columns['n' + str(num_feature_idx)] = values
num_feature_idx += 1
labels = [random.choice(labels) for i in range(n_samples)]
return (DataFram... | 87 | 87 | 290 | 11 | 76 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | generate_survival_dataset | generate_survival_dataset | 214 | 239 | 214 | 214 | 28325094b5474be0f965c305123684eeb40ee64a | bigcode/the-stack | train |
1b35bad1fc486eadad5d9277 | train | function | def generate_dataset_with_num_and_cat_features(
n_samples,
n_num_features,
n_cat_features,
labels,
num_features_density=1.0,
num_features_dtype=np.float32,
num_features_range=(-1., 1.),
cat_features_uniq_value_count=5,
cat_features_dtype=np.int32,
seed=20201015
):
assert num_... | def generate_dataset_with_num_and_cat_features(
n_samples,
n_num_features,
n_cat_features,
labels,
num_features_density=1.0,
num_features_dtype=np.float32,
num_features_range=(-1., 1.),
cat_features_uniq_value_count=5,
cat_features_dtype=np.int32,
seed=20201015
):
| assert num_features_density > 0.0
assert cat_features_uniq_value_count > 0
random.seed(seed)
# put num and categ features to the result DataFrame in random order but keep sequential names within each type
feature_columns = collections.OrderedDict()
num_feature_idx = 0
cat_feature_idx = 0
... | labels = [random.choice(labels) for _ in range(n_samples)]
return (features, labels)
# returns (features : pandas.DataFrame, labels : list) tuple
def generate_dataset_with_num_and_cat_features(
n_samples,
n_num_features,
n_cat_features,
labels,
num_features_density=1.0,
num_features_dtyp... | 116 | 116 | 387 | 80 | 35 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | generate_dataset_with_num_and_cat_features | generate_dataset_with_num_and_cat_features | 165 | 211 | 165 | 176 | 9330276bd54ad6aaeae8bf40f59ba54f56e02129 | bigcode/the-stack | train |
bc39b695c69ab33645381a58 | train | function | def get_limited_precision_dsv_diff_tool(diff_limit, have_header=False):
diff_tool = [
binary_path("catboost/tools/limited_precision_dsv_diff/limited_precision_dsv_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
if have_header:
diff_tool += ['--... | def get_limited_precision_dsv_diff_tool(diff_limit, have_header=False):
| diff_tool = [
binary_path("catboost/tools/limited_precision_dsv_diff/limited_precision_dsv_diff"),
]
if diff_limit is not None:
diff_tool += ['--diff-limit', str(diff_limit)]
if have_header:
diff_tool += ['--have-header']
return diff_tool
| cmd.append(param)
def format_crossvalidation(is_inverted, n, k):
cv_type = 'Inverted' if is_inverted else 'Classical'
return '{}:{};{}'.format(cv_type, n, k)
def get_limited_precision_dsv_diff_tool(diff_limit, have_header=False):
| 64 | 64 | 83 | 16 | 48 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | get_limited_precision_dsv_diff_tool | get_limited_precision_dsv_diff_tool | 396 | 404 | 396 | 396 | 2de083ee1b670735f2f81727728d8a88d29da304 | bigcode/the-stack | train |
a02d3d3f114d34a192b8a1ee | train | class | class DelayedTee(object):
def __init__(self, src_stream, dst_stream):
self.src_stream = src_stream
self.dst_stream = dst_stream
def __enter__(self):
self.src_stream.flush()
self._old_src_stream = os.dup(self.src_stream.fileno())
self._old_dst_stream_pos = self.dst_strea... | class DelayedTee(object):
| def __init__(self, src_stream, dst_stream):
self.src_stream = src_stream
self.dst_stream = dst_stream
def __enter__(self):
self.src_stream.flush()
self._old_src_stream = os.dup(self.src_stream.fileno())
self._old_dst_stream_pos = self.dst_stream.tell()
os.dup2(se... | if key in iter_info.keys():
del iter_info[key]
with open(filename, 'w') as f:
json.dump(log, f, sort_keys=True)
return filename
# rewinds dst_stream to the start of the captured output so you can read it
class DelayedTee(object):
| 64 | 64 | 170 | 7 | 56 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | DelayedTee | DelayedTee | 61 | 78 | 61 | 62 | 4b216ac114bdbff24185a5d703f0e9a55912bd3a | bigcode/the-stack | train |
045f7e3aed330a389afc27ff | train | function | def generate_random_labeled_dataset(
n_samples,
n_features,
labels,
features_density=1.0,
features_dtype=np.float32,
features_range=(-1., 1.),
features_order='C',
seed=20191008
):
assert features_density > 0.0
random.seed(seed)
features = np.empty((n_samples, n_features), d... | def generate_random_labeled_dataset(
n_samples,
n_features,
labels,
features_density=1.0,
features_dtype=np.float32,
features_range=(-1., 1.),
features_order='C',
seed=20191008
):
| assert features_density > 0.0
random.seed(seed)
features = np.empty((n_samples, n_features), dtype=features_dtype, order=features_order)
for feature_idx in range(n_features):
for sample_idx in range(n_samples):
v1 = random.random()
if v1 > features_density:
... | , labels : list) tuple
def generate_random_labeled_dataset(
n_samples,
n_features,
labels,
features_density=1.0,
features_dtype=np.float32,
features_range=(-1., 1.),
features_order='C',
seed=20191008
):
| 64 | 64 | 201 | 57 | 6 | jochenater/catboost | catboost/pytest/lib/common_helpers.py | Python | generate_random_labeled_dataset | generate_random_labeled_dataset | 135 | 161 | 135 | 144 | 1d0bb75526ef3830ce4aa0e8cb963f41936ee278 | bigcode/the-stack | train |
c944d8799a8bf42651d53931 | train | class | class _Prefix:
def __init__(self, path):
# type: (str) -> None
self.path = path
self.setup = False
self.bin_dir = get_paths(
'nt' if os.name == 'nt' else 'posix_prefix',
vars={'base': path, 'platbase': path}
)['scripts']
# ... | class _Prefix:
| def __init__(self, path):
# type: (str) -> None
self.path = path
self.setup = False
self.bin_dir = get_paths(
'nt' if os.name == 'nt' else 'posix_prefix',
vars={'base': path, 'platbase': path}
)['scripts']
# Note: prefer distuti... | Y_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from types import TracebackType
from typing import Iterable, List, Optional, Set, Tuple, Type
from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
class _Prefix:
| 62 | 64 | 180 | 5 | 57 | brianherrera/lumberyard | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/build_env.py | Python | _Prefix | _Prefix | 57 | 91 | 57 | 60 | 3e8b830af24b6dc3731780fa8bee61ea0d9f026b | bigcode/the-stack | train |
0507c742bcd7538c70f3d8d5 | train | class | class NoOpBuildEnvironment(BuildEnvironment):
"""A no-op drop-in replacement for BuildEnvironment
"""
def __init__(self):
# type: () -> None
pass
def __enter__(self):
# type: () -> None
pass
def __exit__(
self,
exc_type, ... | class NoOpBuildEnvironment(BuildEnvironment):
| """A no-op drop-in replacement for BuildEnvironment
"""
def __init__(self):
# type: () -> None
pass
def __enter__(self):
# type: () -> None
pass
def __exit__(
self,
exc_type, # type: Optional[Type[BaseException]]
... | pre')
if finder.prefer_binary:
args.append('--prefer-binary')
args.append('--')
args.extend(requirements)
with open_spinner(message) as spinner:
call_subprocess(args, spinner=spinner)
class NoOpBuildEnvironment(BuildEnvironment):
| 62 | 64 | 216 | 9 | 53 | brianherrera/lumberyard | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/build_env.py | Python | NoOpBuildEnvironment | NoOpBuildEnvironment | 417 | 483 | 417 | 418 | 08f498f601d2d8e7255a6d5784f4468b8f6fde2b | bigcode/the-stack | train |
1b542334a74df412885e4aa1 | train | class | class BuildEnvironment:
"""Creates and manages an isolated environment to install build deps
"""
def __init__(self):
# type: () -> None
temp_dir = TempDirectory(
kind=tempdir_kinds.BUILD_ENV, globally_managed=True
)
self._prefixes = OrderedDi... | class BuildEnvironment:
| """Creates and manages an isolated environment to install build deps
"""
def __init__(self):
# type: () -> None
temp_dir = TempDirectory(
kind=tempdir_kinds.BUILD_ENV, globally_managed=True
)
self._prefixes = OrderedDict((
(name, ... |
from pip._internal.utils.typing import MYPY_CHECK_RUNNING
if MYPY_CHECK_RUNNING:
from types import TracebackType
from typing import Iterable, List, Optional, Set, Tuple, Type
from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
class... | 254 | 256 | 1,346 | 5 | 249 | brianherrera/lumberyard | dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/pip/_internal/build_env.py | Python | BuildEnvironment | BuildEnvironment | 97 | 411 | 97 | 98 | b19e8b184fdcbcaba73580c40c35559d96381a41 | bigcode/the-stack | train |
e9fb7e1a8aa71e9302c7f32e | train | function | def addToken(tokens,tok,c):
tok = tok.lstrip().rstrip()
if tok and not tok.isspace():
tokens.append(tok)
if not c.isspace() and not c == '"':
tokens.append(c)
return ""
| def addToken(tokens,tok,c):
| tok = tok.lstrip().rstrip()
if tok and not tok.isspace():
tokens.append(tok)
if not c.isspace() and not c == '"':
tokens.append(c)
return ""
| Command(self,name):
if self.pointer is None:
return
obj = self.pointer.pushCommand(name)
self.pointer = obj
def todict(buffer):
data = dict()
for c in buf_all:
print(c)
return data
def addToken(tokens,tok,c):
| 64 | 64 | 54 | 8 | 55 | wulffern/cicpytools | cicpytools/skill.py | Python | addToken | addToken | 191 | 202 | 191 | 192 | 7b8ba101670e13513551da141a828d021e035e11 | bigcode/the-stack | train |
c387104b2aaaea86c15703c1 | train | function | def read(f,level,pkey=""):
data = dict()
buf = list()
for line in f:
if(level < 1 and re.search(r"^\s*;",line)):
continue
if(re.search(r"^\s*$",line)):
continue
if( level > 0 and re.search(r"^\s*\)\s+;" + pkey,line)):
read_data(b... | def read(f,level,pkey=""):
| data = dict()
buf = list()
for line in f:
if(level < 1 and re.search(r"^\s*;",line)):
continue
if(re.search(r"^\s*$",line)):
continue
if( level > 0 and re.search(r"^\s*\)\s+;" + pkey,line)):
read_data(buf)
#data["buff... | 0].startswith(";"):
# print(f"INFO: don't know how to parse this buffer '{buffer}'")
return
header = buffer[0].replace(";","")
print(header)
htok = tokenize(header)
print(htok)
def read(f,level,pkey=""):
| 62 | 64 | 210 | 9 | 53 | wulffern/cicpytools | cicpytools/skill.py | Python | read | read | 354 | 383 | 354 | 354 | fe4aa2ee2d11c6e2f1c10792516adf2b6659f066 | bigcode/the-stack | train |
adb4a9d6f9b92642484bd5bc | train | function | def read_tokens(tokens):
ind = 0
atoms = ['(',')','"','"']
# Try to figure out whether this level is a dict or list
# A dict will start with <key>(, while a list will start with ( <key>)
# First I need to remove comments
while(tokens[0] == ';'):
tokens.pop(0)
tokens.pop(0)
... | def read_tokens(tokens):
| ind = 0
atoms = ['(',')','"','"']
# Try to figure out whether this level is a dict or list
# A dict will start with <key>(, while a list will start with ( <key>)
# First I need to remove comments
while(tokens[0] == ';'):
tokens.pop(0)
tokens.pop(0)
isdict = False
data =... | '\\':
char_ignore = True
if stack_match and c == stack_match[-1]:
tok = addToken(tokens,tok,c)
stack_match.pop()
atom = False
continue
if atom == False and c in token_delimiter:
if c in atoms:
atom = True
... | 113 | 113 | 379 | 5 | 107 | wulffern/cicpytools | cicpytools/skill.py | Python | read_tokens | read_tokens | 269 | 336 | 269 | 270 | e71522737ee2732fd36c6454f52a352ba1e2bafc | bigcode/the-stack | train |
9403978a050af6a2fe536538 | train | class | class ReadSkill:
def __init__(self):
self.obj = SkillObject()
self.pointer = self.obj
self.stack = list()
def read(self,f):
isComment = False
isString = False
pushToken = False
buf = ""
while True:
c = f.read(1)
if not... | class ReadSkill:
| def __init__(self):
self.obj = SkillObject()
self.pointer = self.obj
self.stack = list()
def read(self,f):
isComment = False
isString = False
pushToken = False
buf = ""
while True:
c = f.read(1)
if not c: break
... | (self):
d = dict()
if self.name:
d["name"] = self.name
if len(self.commands) > 0:
cmd = dict()
for c in self.commands:
obj = self.commands[c]
cmd[c] = obj.toJson()
d["cmd"] = cmd
d["tokens"] ... | 141 | 141 | 473 | 4 | 136 | wulffern/cicpytools | cicpytools/skill.py | Python | ReadSkill | ReadSkill | 87 | 178 | 87 | 88 | 100b9059db99d9c787788ef6c91286aa6e784644 | bigcode/the-stack | train |
84b3112ff31e0fc448fc29db | train | function | def todict(buffer):
data = dict()
for c in buf_all:
print(c)
return data
| def todict(buffer):
| data = dict()
for c in buf_all:
print(c)
return data
|
def popList(self):
if self.pointer is None:
return
self.pointer = self.pointer.parent
def pushCommand(self,name):
if self.pointer is None:
return
obj = self.pointer.pushCommand(name)
self.pointer = obj
def todict(buffer):
| 62 | 64 | 25 | 5 | 56 | wulffern/cicpytools | cicpytools/skill.py | Python | todict | todict | 183 | 189 | 183 | 183 | eb8a70ab5f1dedee968d1f541df57c6a842c1c49 | bigcode/the-stack | train |
dd560559332d265588e0e9f7 | train | function | def tokenize(f):
tokens = list()
tok = ""
char_ignore = False
atom = False
ignore_list = ['\r','\n']
stack_match = list()
atoms = {
'"':'"',
';':'\n'
}
token_delimiter = {
'(' : ')'
}
token_delimiter = {**atoms,**token_delimiter}
ind = 0
... | def tokenize(f):
| tokens = list()
tok = ""
char_ignore = False
atom = False
ignore_list = ['\r','\n']
stack_match = list()
atoms = {
'"':'"',
';':'\n'
}
token_delimiter = {
'(' : ')'
}
token_delimiter = {**atoms,**token_delimiter}
ind = 0
while True:
... | .pointer = obj
def todict(buffer):
data = dict()
for c in buf_all:
print(c)
return data
def addToken(tokens,tok,c):
tok = tok.lstrip().rstrip()
if tok and not tok.isspace():
tokens.append(tok)
if not c.isspace() and not c == '"':
tokens.... | 89 | 90 | 300 | 4 | 85 | wulffern/cicpytools | cicpytools/skill.py | Python | tokenize | tokenize | 205 | 265 | 205 | 205 | 9abe48ffdb39400c38c4d91dcdffea9ae8dc6592 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.