blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2cae1f3e767f0614a0283c6300726f6188b42338 | [
"if codecs is None:\n encoding = None\nself.baseFilename = os.path.abspath(filename)\nself.mode = mode\nself.encoding = encoding\nself.delay = delay\nself.dblog = dblog\nself.connect = connect\nself.just_write_table = just_write_table\nif delay:\n logging.Handler.__init__(self)\n self.stream = None\nelse:\... | <|body_start_0|>
if codecs is None:
encoding = None
self.baseFilename = os.path.abspath(filename)
self.mode = mode
self.encoding = encoding
self.delay = delay
self.dblog = dblog
self.connect = connect
self.just_write_table = just_write_table
... | A handler class which writes formatted logging records to disk files. | SCFileHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SCFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
<|body... | stack_v2_sparse_classes_75kplus_train_001200 | 4,529 | no_license | [
{
"docstring": "Open the specified file and use it as the stream for logging.",
"name": "__init__",
"signature": "def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0)"
},
{
"docstring": "Closes the stream.",
"name": "close",
"signa... | 4 | stack_v2_sparse_classes_30k_train_038454 | Implement the Python class `SCFileHandler` described below.
Class description:
A handler class which writes formatted logging records to disk files.
Method signatures and docstrings:
- def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0): Open the specified fil... | Implement the Python class `SCFileHandler` described below.
Class description:
A handler class which writes formatted logging records to disk files.
Method signatures and docstrings:
- def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0): Open the specified fil... | df354eb1de71b459b92a5a505e27b9d17880332c | <|skeleton|>
class SCFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
<|body... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SCFileHandler:
"""A handler class which writes formatted logging records to disk files."""
def __init__(self, filename, dblog={}, connect=None, just_write_table=None, mode='a', encoding=None, delay=0):
"""Open the specified file and use it as the stream for logging."""
if codecs is None:
... | the_stack_v2_python_sparse | IDEA/pythod_work/nlsync_data/sync_logger.py | maizi12580/test | train | 0 |
c2da97542ab770c854bd221064294d68c8cb56e3 | [
"Configuration.__init__(self)\nself.isHomoComplex = isHomoComplex\nself.stepName = stepName\nself.averageLRscores = averageLRscores\nif not savedModelsPath is None:\n self.savedModelsPath = savedModelsPath\nself.model = None\nprint(stepName)\nself.savedModelsPath = os.path.join(self.savedModelsPath, 'homo' if se... | <|body_start_0|>
Configuration.__init__(self)
self.isHomoComplex = isHomoComplex
self.stepName = stepName
self.averageLRscores = averageLRscores
if not savedModelsPath is None:
self.savedModelsPath = savedModelsPath
self.model = None
print(stepName)
... | This class is used to predict new pdbs once models have already been computed. | ComplexPredictor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, ... | stack_v2_sparse_classes_75kplus_train_001201 | 3,490 | permissive | [
{
"docstring": ":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, structX, seq_train1... are also valid) :param isHomoComplex: boolean. Is the target complex homo or hetero :param savedModelsPath: str. A path to the directory where models have been saved. If None, it will u... | 2 | stack_v2_sparse_classes_30k_train_019460 | Implement the Python class `ComplexPredictor` described below.
Class description:
This class is used to predict new pdbs once models have already been computed.
Method signatures and docstrings:
- def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False): :param stepName: str. Must star... | Implement the Python class `ComplexPredictor` described below.
Class description:
This class is used to predict new pdbs once models have already been computed.
Method signatures and docstrings:
- def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False): :param stepName: str. Must star... | 1d9801a176323ba238c8d10e673cf2055f83a4b6 | <|skeleton|>
class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ComplexPredictor:
"""This class is used to predict new pdbs once models have already been computed."""
def __init__(self, stepName, isHomoComplex, savedModelsPath=None, averageLRscores=False):
""":param stepName: str. Must startswith seq_train or struct or mixed (seq_train, mixed_2, structX, seq_... | the_stack_v2_python_sparse | trainAndTest/predictOneCodifiedComplex.py | rsanchezgarc/BIPSPI | train | 9 |
c3bb9a9a17f1501dfff13cad7e64ea9f00cb4705 | [
"super(SARSALearningAgent, self).__init__(data_collection_config, reward_config, model_config)\nif model_config is None:\n raise ValueError('Learning agents require model.')\nself.model = create_model(model_config)\nself.discount_factor = discount_factor\nself.epsilon = epsilon\nself.learning_rate = learning_rat... | <|body_start_0|>
super(SARSALearningAgent, self).__init__(data_collection_config, reward_config, model_config)
if model_config is None:
raise ValueError('Learning agents require model.')
self.model = create_model(model_config)
self.discount_factor = discount_factor
se... | Agent that uses SARSA-Learning strategy to figure out policy. | SARSALearningAgent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SARSALearningAgent:
"""Agent that uses SARSA-Learning strategy to figure out policy."""
def __init__(self, data_collection_config, reward_config=None, model_config=None, discount_factor=0.1, epsilon=0.1, learning_rate=0.1, num_epochs=5, initial_num_epochs=50):
"""Initializer for Foll... | stack_v2_sparse_classes_75kplus_train_001202 | 4,867 | permissive | [
{
"docstring": "Initializer for FollowingFeatureAgent class. Args: data_collection_config: configuration for the data collection used by the agent. reward_config: configuration for reward used by the agent. model_config: configuration for model used by the agent. discount_factor: discount factor. epsilon: epsil... | 3 | stack_v2_sparse_classes_30k_train_045230 | Implement the Python class `SARSALearningAgent` described below.
Class description:
Agent that uses SARSA-Learning strategy to figure out policy.
Method signatures and docstrings:
- def __init__(self, data_collection_config, reward_config=None, model_config=None, discount_factor=0.1, epsilon=0.1, learning_rate=0.1, n... | Implement the Python class `SARSALearningAgent` described below.
Class description:
Agent that uses SARSA-Learning strategy to figure out policy.
Method signatures and docstrings:
- def __init__(self, data_collection_config, reward_config=None, model_config=None, discount_factor=0.1, epsilon=0.1, learning_rate=0.1, n... | 7161026b7b4deb78a934b66550c85a27c6b32933 | <|skeleton|>
class SARSALearningAgent:
"""Agent that uses SARSA-Learning strategy to figure out policy."""
def __init__(self, data_collection_config, reward_config=None, model_config=None, discount_factor=0.1, epsilon=0.1, learning_rate=0.1, num_epochs=5, initial_num_epochs=50):
"""Initializer for Foll... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SARSALearningAgent:
"""Agent that uses SARSA-Learning strategy to figure out policy."""
def __init__(self, data_collection_config, reward_config=None, model_config=None, discount_factor=0.1, epsilon=0.1, learning_rate=0.1, num_epochs=5, initial_num_epochs=50):
"""Initializer for FollowingFeatureA... | the_stack_v2_python_sparse | stock_trading_backend/agent/sarsa_learning_agent.py | iryzhkov/stock-trading-backend | train | 1 |
351e015a8b1abdf48074ed2818cd1155bf99b5f5 | [
"self.x = x_center\nself.y = y_center\nself.radius = radius",
"length = random.random() * self.radius\nangel = random.random() * 360\nreturn [length * cos(angel), length * sin(angel)]",
"x_ret = random.random() * 2 * self.radius - self.radius + self.x\ny_ret = random.random() * 2 * self.radius - self.radius + s... | <|body_start_0|>
self.x = x_center
self.y = y_center
self.radius = radius
<|end_body_0|>
<|body_start_1|>
length = random.random() * self.radius
angel = random.random() * 360
return [length * cos(angel), length * sin(angel)]
<|end_body_1|>
<|body_start_2|>
x_ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
def randPoint_1(self):
""":rtype: List[float]"""
... | stack_v2_sparse_classes_75kplus_train_001203 | 1,108 | no_license | [
{
"docstring": ":type radius: float :type x_center: float :type y_center: float",
"name": "__init__",
"signature": "def __init__(self, radius, x_center, y_center)"
},
{
"docstring": ":rtype: List[float]",
"name": "randPoint",
"signature": "def randPoint(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_053807 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
- def randPoint_1(self)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def __init__(self, radius, x_center, y_center): :type radius: float :type x_center: float :type y_center: float
- def randPoint(self): :rtype: List[float]
- def randPoint_1(self)... | 70bdd75b6af2e1811c1beab22050c01d28d7373e | <|skeleton|>
class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
<|body_0|>
def randPoint(self):
""":rtype: List[float]"""
<|body_1|>
def randPoint_1(self):
""":rtype: List[float]"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def __init__(self, radius, x_center, y_center):
""":type radius: float :type x_center: float :type y_center: float"""
self.x = x_center
self.y = y_center
self.radius = radius
def randPoint(self):
""":rtype: List[float]"""
length = random.random() ... | the_stack_v2_python_sparse | python/leetcode/478_Generate_Random_Point_in_a_Circle.py | bobcaoge/my-code | train | 0 | |
613d0f42bb819c998dc4d6a5c3d8988133930c0e | [
"contato = get_a_contact(id)\nif not contato:\n api.abort(404)\nelse:\n return contato",
"contato = get_a_contact(id)\nif not contato:\n api.abort(404)\nelse:\n data = request.json\n return update_contact(contato, data=data)"
] | <|body_start_0|>
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
return contato
<|end_body_0|>
<|body_start_1|>
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
data = request.json
... | Contato | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
contato = get_a_co... | stack_v2_sparse_classes_75kplus_train_001204 | 2,424 | no_license | [
{
"docstring": "Obtem informações de um contato com base no seu id",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Atualiza um contato Obs: para inativar, coloque 'ativo': false",
"name": "patch",
"signature": "def patch(self, id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018063 | Implement the Python class `Contato` described below.
Class description:
Implement the Contato class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um contato com base no seu id
- def patch(self, id): Atualiza um contato Obs: para inativar, coloque 'ativo': false | Implement the Python class `Contato` described below.
Class description:
Implement the Contato class.
Method signatures and docstrings:
- def get(self, id): Obtem informações de um contato com base no seu id
- def patch(self, id): Atualiza um contato Obs: para inativar, coloque 'ativo': false
<|skeleton|>
class Cont... | a86fcb085af8567a661d47876f8b9f13d7b062a9 | <|skeleton|>
class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
<|body_0|>
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ativo': false"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Contato:
def get(self, id):
"""Obtem informações de um contato com base no seu id"""
contato = get_a_contact(id)
if not contato:
api.abort(404)
else:
return contato
def patch(self, id):
"""Atualiza um contato Obs: para inativar, coloque 'ati... | the_stack_v2_python_sparse | backend/app/main/controller/contato_controller.py | AnderSilva/ozomali | train | 1 | |
6c332649851f1ee551eedb5b8daac3639cb1395b | [
"super().__init__(coordinator, description)\nself._serial_number = serial_number\nself._attr_unique_id = f'{serial_number}_{description.key}'\nencharge_inventory = self.data.encharge_inventory\nassert encharge_inventory is not None\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, serial_number)}, manufact... | <|body_start_0|>
super().__init__(coordinator, description)
self._serial_number = serial_number
self._attr_unique_id = f'{serial_number}_{description.key}'
encharge_inventory = self.data.encharge_inventory
assert encharge_inventory is not None
self._attr_device_info = Dev... | Defines an Encharge binary_sensor entity. | EnvoyEnchargeBinarySensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EnvoyEnchargeBinarySensorEntity:
"""Defines an Encharge binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None:
"""Init the Encharge base entity."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001205 | 5,991 | permissive | [
{
"docstring": "Init the Encharge base entity.",
"name": "__init__",
"signature": "def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None"
},
{
"docstring": "Return the state of the Encharge binary_sensor.",
... | 2 | stack_v2_sparse_classes_30k_train_026661 | Implement the Python class `EnvoyEnchargeBinarySensorEntity` described below.
Class description:
Defines an Encharge binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None:... | Implement the Python class `EnvoyEnchargeBinarySensorEntity` described below.
Class description:
Defines an Encharge binary_sensor entity.
Method signatures and docstrings:
- def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None:... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class EnvoyEnchargeBinarySensorEntity:
"""Defines an Encharge binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None:
"""Init the Encharge base entity."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EnvoyEnchargeBinarySensorEntity:
"""Defines an Encharge binary_sensor entity."""
def __init__(self, coordinator: EnphaseUpdateCoordinator, description: EnvoyEnchargeBinarySensorEntityDescription, serial_number: str) -> None:
"""Init the Encharge base entity."""
super().__init__(coordinato... | the_stack_v2_python_sparse | homeassistant/components/enphase_envoy/binary_sensor.py | home-assistant/core | train | 35,501 |
4ed696d2a0a4dac761c54325ba5b9e822c0a8d50 | [
"self.dynamics_net = ForwardModel(state_dim, action_dim)\nself.rewards_net = RewardModel(state_dim, action_dim)\nself.done_net = RewardModel(state_dim, action_dim)\nself.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay)\nself.reward_optimizer = tfa_optimizers.AdamW(learnin... | <|body_start_0|>
self.dynamics_net = ForwardModel(state_dim, action_dim)
self.rewards_net = RewardModel(state_dim, action_dim)
self.done_net = RewardModel(state_dim, action_dim)
self.dyn_optimizer = tfa_optimizers.AdamW(learning_rate=learning_rate, weight_decay=weight_decay)
self... | A class that learns models and estimated returns via rollouts. | ModelBased | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin... | stack_v2_sparse_classes_75kplus_train_001206 | 7,358 | permissive | [
{
"docstring": "Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Critic learning rate. weight_decay: Weight decay.",
"name": "__init__",
"signature": "def __init__(self, state_dim, action_dim, learning_rate, weight_de... | 3 | stack_v2_sparse_classes_30k_train_019196 | Implement the Python class `ModelBased` described below.
Class description:
A class that learns models and estimated returns via rollouts.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args... | Implement the Python class `ModelBased` described below.
Class description:
A class that learns models and estimated returns via rollouts.
Method signatures and docstrings:
- def __init__(self, state_dim, action_dim, learning_rate, weight_decay): Creates networks and optimizers for model based policy evaluation. Args... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learnin... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModelBased:
"""A class that learns models and estimated returns via rollouts."""
def __init__(self, state_dim, action_dim, learning_rate, weight_decay):
"""Creates networks and optimizers for model based policy evaluation. Args: state_dim: State size. action_dim: Action size. learning_rate: Criti... | the_stack_v2_python_sparse | policy_eval/model_based.py | Jimmy-INL/google-research | train | 1 |
0c0057735c8aed188032bf401b29a37aca7c081e | [
"self.key = settings.PERMISSION_KEY\nself.mode = AES.MODE_ECB\nself.prefix = settings.PERMISSION_PREFIX",
"length = 32\nif len(text) > length:\n return ''\ntext = ''.join(random.sample(self.prefix, length - len(text))) + text\nencryptor = AES.new(self.key, self.mode)\ncurrent_time = time.time()\nself.save_to_a... | <|body_start_0|>
self.key = settings.PERMISSION_KEY
self.mode = AES.MODE_ECB
self.prefix = settings.PERMISSION_PREFIX
<|end_body_0|>
<|body_start_1|>
length = 32
if len(text) > length:
return ''
text = ''.join(random.sample(self.prefix, length - len(text))) +... | preceeding class for AuthList | KSMP_Permission | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KSMP_Permission:
"""preceeding class for AuthList"""
def __init__(self):
"""initiate object properties"""
<|body_0|>
def set_permission(self, text):
"""params: text allways is username 16*n bytes return: encoded auth code"""
<|body_1|>
def get_permis... | stack_v2_sparse_classes_75kplus_train_001207 | 2,888 | no_license | [
{
"docstring": "initiate object properties",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "params: text allways is username 16*n bytes return: encoded auth code",
"name": "set_permission",
"signature": "def set_permission(self, text)"
},
{
"docstring": ... | 6 | stack_v2_sparse_classes_30k_train_040821 | Implement the Python class `KSMP_Permission` described below.
Class description:
preceeding class for AuthList
Method signatures and docstrings:
- def __init__(self): initiate object properties
- def set_permission(self, text): params: text allways is username 16*n bytes return: encoded auth code
- def get_permission... | Implement the Python class `KSMP_Permission` described below.
Class description:
preceeding class for AuthList
Method signatures and docstrings:
- def __init__(self): initiate object properties
- def set_permission(self, text): params: text allways is username 16*n bytes return: encoded auth code
- def get_permission... | 7f801a569a396a27371d0831752595877c224a6b | <|skeleton|>
class KSMP_Permission:
"""preceeding class for AuthList"""
def __init__(self):
"""initiate object properties"""
<|body_0|>
def set_permission(self, text):
"""params: text allways is username 16*n bytes return: encoded auth code"""
<|body_1|>
def get_permis... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KSMP_Permission:
"""preceeding class for AuthList"""
def __init__(self):
"""initiate object properties"""
self.key = settings.PERMISSION_KEY
self.mode = AES.MODE_ECB
self.prefix = settings.PERMISSION_PREFIX
def set_permission(self, text):
"""params: text allwa... | the_stack_v2_python_sparse | Python_projects/flask_projects/unicorn_project/session/permission.py | sdtimothy8/Coding | train | 0 |
ac9e4e745235c05787e3a53544d9ee7a34b618f6 | [
"model_name = kwargs.pop('model_name')\neffective_date = kwargs.pop('effective_date')\nmodel = apps.get_model('api', model_name)\nreturn model.objects.filter(effective_date__lte=effective_date, **kwargs).exclude(expiration_date__lt=effective_date).exclude(expiration_date=F('effective_date')).order_by('-effective_da... | <|body_start_0|>
model_name = kwargs.pop('model_name')
effective_date = kwargs.pop('effective_date')
model = apps.get_model('api', model_name)
return model.objects.filter(effective_date__lte=effective_date, **kwargs).exclude(expiration_date__lt=effective_date).exclude(expiration_date=F('... | Helper functions for Credit Calculation | CreditCalculationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreditCalculationService:
"""Helper functions for Credit Calculation"""
def get(**kwargs):
"""Gets the ratio/density that applies to the date provided"""
<|body_0|>
def get_all(**kwargs):
"""Gets the ratio/density that has an effective date prior to the date prov... | stack_v2_sparse_classes_75kplus_train_001208 | 6,371 | permissive | [
{
"docstring": "Gets the ratio/density that applies to the date provided",
"name": "get",
"signature": "def get(**kwargs)"
},
{
"docstring": "Gets the ratio/density that has an effective date prior to the date provided. This is so we can update it later an make sure no overlaps occur",
"name... | 5 | null | Implement the Python class `CreditCalculationService` described below.
Class description:
Helper functions for Credit Calculation
Method signatures and docstrings:
- def get(**kwargs): Gets the ratio/density that applies to the date provided
- def get_all(**kwargs): Gets the ratio/density that has an effective date p... | Implement the Python class `CreditCalculationService` described below.
Class description:
Helper functions for Credit Calculation
Method signatures and docstrings:
- def get(**kwargs): Gets the ratio/density that applies to the date provided
- def get_all(**kwargs): Gets the ratio/density that has an effective date p... | 80ae1ef5938ef5e580128ed0c622071b307fc7e1 | <|skeleton|>
class CreditCalculationService:
"""Helper functions for Credit Calculation"""
def get(**kwargs):
"""Gets the ratio/density that applies to the date provided"""
<|body_0|>
def get_all(**kwargs):
"""Gets the ratio/density that has an effective date prior to the date prov... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreditCalculationService:
"""Helper functions for Credit Calculation"""
def get(**kwargs):
"""Gets the ratio/density that applies to the date provided"""
model_name = kwargs.pop('model_name')
effective_date = kwargs.pop('effective_date')
model = apps.get_model('api', model... | the_stack_v2_python_sparse | backend/api/services/CreditCalculationService.py | kuanfandevops/tfrs | train | 0 |
63ea4dcd5c0304418a13cccf3b12cfa055cbe659 | [
"l = len(nums)\nif l < 3:\n return False\ns3 = -float('inf')\ni = l - 1\nwhile i >= 0:\n if i > 0 and nums[i - 1] > nums[i]:\n s3 = max([x for x in nums[i:] if x < nums[i - 1]])\n if i - 2 >= 0 and nums[i - 2] < s3:\n return True\n elif nums[i] < s3:\n return True\n i -= ... | <|body_start_0|>
l = len(nums)
if l < 3:
return False
s3 = -float('inf')
i = l - 1
while i >= 0:
if i > 0 and nums[i - 1] > nums[i]:
s3 = max([x for x in nums[i:] if x < nums[i - 1]])
if i - 2 >= 0 and nums[i - 2] < s3:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def find132pattern1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
l = len(nums)
if l < 3:
... | stack_v2_sparse_classes_75kplus_train_001209 | 1,060 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "find132pattern1",
"signature": "def find132pattern1(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: bool",
"name": "find132pattern",
"signature": "def find132pattern(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_046878 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern1(self, nums): :type nums: List[int] :rtype: bool
- def find132pattern(self, nums): :type nums: List[int] :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def find132pattern1(self, nums): :type nums: List[int] :rtype: bool
- def find132pattern(self, nums): :type nums: List[int] :rtype: bool
<|skeleton|>
class Solution:
def fi... | e5b018493bbd12edcdcd0434f35d9c358106d391 | <|skeleton|>
class Solution:
def find132pattern1(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_0|>
def find132pattern(self, nums):
""":type nums: List[int] :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def find132pattern1(self, nums):
""":type nums: List[int] :rtype: bool"""
l = len(nums)
if l < 3:
return False
s3 = -float('inf')
i = l - 1
while i >= 0:
if i > 0 and nums[i - 1] > nums[i]:
s3 = max([x for x in n... | the_stack_v2_python_sparse | py/leetcode/456.py | wfeng1991/learnpy | train | 0 | |
8496714db6f57c9989103f96d62f28058c26e1ab | [
"for i in range(len(body.sensors)):\n action_to_check = actions[len(actions) - i - 1]\n sensor_to_check = body.sensors[len(body.sensors) - i - 1]\n if action_to_check > 0:\n sensor_to_check.userData.ready_to_attach = True\n else:\n sensor_to_check.userData.ready_to_attach = False\n ... | <|body_start_0|>
for i in range(len(body.sensors)):
action_to_check = actions[len(actions) - i - 1]
sensor_to_check = body.sensors[len(body.sensors) - i - 1]
if action_to_check > 0:
sensor_to_check.userData.ready_to_attach = True
else:
... | ClimbingDynamics | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClimbingDynamics:
def before_step_climbing_dynamics(self, actions, body, world):
"""Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise, check if a joint is existing and destroy it."""
<|body_0|>
def after_step_climbing_dynamic... | stack_v2_sparse_classes_75kplus_train_001210 | 4,977 | permissive | [
{
"docstring": "Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise, check if a joint is existing and destroy it.",
"name": "before_step_climbing_dynamics",
"signature": "def before_step_climbing_dynamics(self, actions, body, world)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_052231 | Implement the Python class `ClimbingDynamics` described below.
Class description:
Implement the ClimbingDynamics class.
Method signatures and docstrings:
- def before_step_climbing_dynamics(self, actions, body, world): Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise... | Implement the Python class `ClimbingDynamics` described below.
Class description:
Implement the ClimbingDynamics class.
Method signatures and docstrings:
- def before_step_climbing_dynamics(self, actions, body, world): Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise... | 6c157511a609e84596c4f8aad99e7576a015ee15 | <|skeleton|>
class ClimbingDynamics:
def before_step_climbing_dynamics(self, actions, body, world):
"""Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise, check if a joint is existing and destroy it."""
<|body_0|>
def after_step_climbing_dynamic... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClimbingDynamics:
def before_step_climbing_dynamics(self, actions, body, world):
"""Check if sensors are in 'grasping mode' (i.e. their associated action is greater than 0). Otherwise, check if a joint is existing and destroy it."""
for i in range(len(body.sensors)):
action_to_chec... | the_stack_v2_python_sparse | TeachMyAgent/environments/envs/Box2D_dynamics/climbing_dynamics.py | flowersteam/TeachMyAgent | train | 70 | |
c22dcadbf149d335f3dfdb7873cefe51ae0ef90e | [
"self._set('subscription-notify-socket', client_notify_address)\nself._set('subscription-mountpoint', mountpoints_depth)\nself._set('subscription-vassal-required', require_vassal, cast=bool)\nself._set('subscription-tolerance', tolerance)\nself._set('subscription-tolerance-inactive', tolerance_inactive)\nself._set(... | <|body_start_0|>
self._set('subscription-notify-socket', client_notify_address)
self._set('subscription-mountpoint', mountpoints_depth)
self._set('subscription-vassal-required', require_vassal, cast=bool)
self._set('subscription-tolerance', tolerance)
self._set('subscription-tole... | This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some routers provide subscription server functionality. See `.routing.routers`. .. note:: ... | Subscriptions | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Subscriptions:
"""This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some routers provide subscription server function... | stack_v2_sparse_classes_75kplus_train_001211 | 8,707 | permissive | [
{
"docstring": "Sets subscription server related params. :param str client_notify_address: Set the notification socket for subscriptions. When you subscribe to a server, you can ask it to \"acknowledge\" the acceptance of your request. pointing address (Unix socket or UDP), on which your instance will bind and ... | 4 | stack_v2_sparse_classes_30k_train_045126 | Implement the Python class `Subscriptions` described below.
Class description:
This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some route... | Implement the Python class `Subscriptions` described below.
Class description:
This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some route... | 1060d6c9e15695b65f1875df66128fb4ff1a5c0d | <|skeleton|>
class Subscriptions:
"""This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some routers provide subscription server function... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Subscriptions:
"""This allows some uWSGI instances to announce their presence to subscriptions managing server, which in its turn can address those nodes (e.g. delegate request processing to them) and automatically remove dead nodes from the pool. Some routers provide subscription server functionality. See `.... | the_stack_v2_python_sparse | uwsgiconf/options/subscriptions.py | idlesign/uwsgiconf | train | 79 |
08e2e20e7b3fa046fc9d926ccfe1d9e4cc8322cb | [
"self.chassis_id = chassis_id\nself.chassis_name = chassis_name\nself.chassis_serial = chassis_serial\nself.location = location\nself.rack_id = rack_id",
"if dictionary is None:\n return None\nchassis_id = dictionary.get('chassisId')\nchassis_name = dictionary.get('chassisName')\nchassis_serial = dictionary.ge... | <|body_start_0|>
self.chassis_id = chassis_id
self.chassis_name = chassis_name
self.chassis_serial = chassis_serial
self.location = location
self.rack_id = rack_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
chassis_id = diction... | Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This could be the chassis serial number by default. chassis_serial (string): Chassis s... | ChassisInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChassisInfo:
"""Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This could be the chassis serial number by defa... | stack_v2_sparse_classes_75kplus_train_001212 | 2,429 | permissive | [
{
"docstring": "Constructor for the ChassisInfo class",
"name": "__init__",
"signature": "def __init__(self, chassis_id=None, chassis_name=None, chassis_serial=None, location=None, rack_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary)... | 2 | stack_v2_sparse_classes_30k_train_036057 | Implement the Python class `ChassisInfo` described below.
Class description:
Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This cou... | Implement the Python class `ChassisInfo` described below.
Class description:
Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This cou... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ChassisInfo:
"""Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This could be the chassis serial number by defa... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ChassisInfo:
"""Implementation of the 'ChassisInfo' model. ChassisInfo is the struct for the Chassis. Attributes: chassis_id (long|int): ChassisId is a unique id assigned to the chassis. chassis_name (string): ChassisName is the name of the chassis. This could be the chassis serial number by default. chassis_... | the_stack_v2_python_sparse | cohesity_management_sdk/models/chassis_info.py | cohesity/management-sdk-python | train | 24 |
ebc7da655fdc10bb67b649be0739224df8d7b0fd | [
"super().__init__()\nself.num_iters = num_iters\nself.epsilon = epsilon\nself.world_size = world_size",
"Q = torch.exp(Q / self.epsilon).t()\nB = Q.shape[1] * self.world_size\nK = Q.shape[0]\nsum_Q = torch.sum(Q)\nif dist.is_available() and dist.is_initialized():\n dist.all_reduce(sum_Q)\nQ /= sum_Q\nfor _ in ... | <|body_start_0|>
super().__init__()
self.num_iters = num_iters
self.epsilon = epsilon
self.world_size = world_size
<|end_body_0|>
<|body_start_1|>
Q = torch.exp(Q / self.epsilon).t()
B = Q.shape[1] * self.world_size
K = Q.shape[0]
sum_Q = torch.sum(Q)
... | SinkhornKnopp | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinkhornKnopp:
def __init__(self, num_iters: int=3, epsilon: float=0.05, world_size: int=1):
"""Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative method to approach the double stochastic matrix is to alternately rescale rows and columns of the matrix t... | stack_v2_sparse_classes_75kplus_train_001213 | 44,029 | no_license | [
{
"docstring": "Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative method to approach the double stochastic matrix is to alternately rescale rows and columns of the matrix to sum to 1. Args: num_iters (int, optional): number of times to perform row and column normalization. De... | 2 | null | Implement the Python class `SinkhornKnopp` described below.
Class description:
Implement the SinkhornKnopp class.
Method signatures and docstrings:
- def __init__(self, num_iters: int=3, epsilon: float=0.05, world_size: int=1): Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative meth... | Implement the Python class `SinkhornKnopp` described below.
Class description:
Implement the SinkhornKnopp class.
Method signatures and docstrings:
- def __init__(self, num_iters: int=3, epsilon: float=0.05, world_size: int=1): Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative meth... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SinkhornKnopp:
def __init__(self, num_iters: int=3, epsilon: float=0.05, world_size: int=1):
"""Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative method to approach the double stochastic matrix is to alternately rescale rows and columns of the matrix t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SinkhornKnopp:
def __init__(self, num_iters: int=3, epsilon: float=0.05, world_size: int=1):
"""Approximates optimal transport using the Sinkhorn-Knopp algorithm. A simple iterative method to approach the double stochastic matrix is to alternately rescale rows and columns of the matrix to sum to 1. Ar... | the_stack_v2_python_sparse | generated/test_vturrisi_solo_learn.py | jansel/pytorch-jit-paritybench | train | 35 | |
30e6ae233122832735c171c2e58ba352236a40ce | [
"from torch.nn import LeakyReLU\nfrom torch.nn import Conv2d\nsuper().__init__()\nself.batch_discriminator = MinibatchStdDev()\nif use_eql:\n self.conv_1 = EqualConv2d(in_channels + 1, in_channels, kernel_size=3, padding=1)\n self.conv_2 = EqualConv2d(in_channels, in_channels, kernel_size=4)\n self.conv_3 ... | <|body_start_0|>
from torch.nn import LeakyReLU
from torch.nn import Conv2d
super().__init__()
self.batch_discriminator = MinibatchStdDev()
if use_eql:
self.conv_1 = EqualConv2d(in_channels + 1, in_channels, kernel_size=3, padding=1)
self.conv_2 = EqualCon... | Final block for the Discriminator | DisFinalBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels, use_eql=True):
"""constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning rate"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_75kplus_train_001214 | 14,606 | no_license | [
{
"docstring": "constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning rate",
"name": "__init__",
"signature": "def __init__(self, in_channels, use_eql=True)"
},
{
"docstring": "forward pass of the FinalBlock :param x: input :retur... | 2 | null | Implement the Python class `DisFinalBlock` described below.
Class description:
Final block for the Discriminator
Method signatures and docstrings:
- def __init__(self, in_channels, use_eql=True): constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning ra... | Implement the Python class `DisFinalBlock` described below.
Class description:
Final block for the Discriminator
Method signatures and docstrings:
- def __init__(self, in_channels, use_eql=True): constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning ra... | 428abe1fefe5ea4ef00290155e7e59657bc83444 | <|skeleton|>
class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels, use_eql=True):
"""constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning rate"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DisFinalBlock:
"""Final block for the Discriminator"""
def __init__(self, in_channels, use_eql=True):
"""constructor of the class :param in_channels: number of input channels :param use_eql: whether to use equalized learning rate"""
from torch.nn import LeakyReLU
from torch.nn imp... | the_stack_v2_python_sparse | src/style_msg_gan_customlayers.py | blakecheng/lafin | train | 0 |
eb3082acc31962bd8e655a494d06778a024537bd | [
"self.kappa = kappa\nself.theta = theta\nself.sigma = sigma\nself.r0 = r0\nself.params = {'kappa': self.kappa, 'theta': self.theta, 'sigma': sigma, 'r0': self.r0}\nif calc_norm_method is None:\n raise ValueError('No calc norm method provided')\nself.calc_norm_method = calc_norm_method",
"if isinstance(self.kap... | <|body_start_0|>
self.kappa = kappa
self.theta = theta
self.sigma = sigma
self.r0 = r0
self.params = {'kappa': self.kappa, 'theta': self.theta, 'sigma': sigma, 'r0': self.r0}
if calc_norm_method is None:
raise ValueError('No calc norm method provided')
... | base class corresponding to mean reverting short rate model | hjm_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class hjm_model:
"""base class corresponding to mean reverting short rate model"""
def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None):
"""constructor"""
<|body_0|>
def __repr__(self):
"""print elements of short rate_model"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus_train_001215 | 1,719 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None)"
},
{
"docstring": "print elements of short rate_model",
"name": "__repr__",
"signature": "def __repr__(self)"
},
{
"docstring": "calc norm method",
... | 3 | null | Implement the Python class `hjm_model` described below.
Class description:
base class corresponding to mean reverting short rate model
Method signatures and docstrings:
- def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None): constructor
- def __repr__(self): print elements of short rate_model
- def calc... | Implement the Python class `hjm_model` described below.
Class description:
base class corresponding to mean reverting short rate model
Method signatures and docstrings:
- def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None): constructor
- def __repr__(self): print elements of short rate_model
- def calc... | 2e08363642fd4e2afb5ab76596d75aa10f2a6e3b | <|skeleton|>
class hjm_model:
"""base class corresponding to mean reverting short rate model"""
def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None):
"""constructor"""
<|body_0|>
def __repr__(self):
"""print elements of short rate_model"""
<|body_1|>
def ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class hjm_model:
"""base class corresponding to mean reverting short rate model"""
def __init__(self, kappa, theta, sigma, r0, calc_norm_method=None):
"""constructor"""
self.kappa = kappa
self.theta = theta
self.sigma = sigma
self.r0 = r0
self.params = {'kappa': ... | the_stack_v2_python_sparse | src/interest_rate_hjm.py | slpenn13/pythoninterestrates | train | 0 |
31ea009c064d8563d71e44c719094fbb9f03f610 | [
"token = decode_token(data['authorization'], data['secret'], 1)\nif token['username'] != self.context['request'].user.username:\n raise serializers.ValidationError('Invalid keys')\nself.context['data'] = data\nreturn data",
"request = self.context['request']\nif not request.user.is_authenticated:\n return s... | <|body_start_0|>
token = decode_token(data['authorization'], data['secret'], 1)
if token['username'] != self.context['request'].user.username:
raise serializers.ValidationError('Invalid keys')
self.context['data'] = data
return data
<|end_body_0|>
<|body_start_1|>
re... | Favorite destroy all serialzer. | FavoriteDestroyAllSerializer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FavoriteDestroyAllSerializer:
"""Favorite destroy all serialzer."""
def validate(self, data):
"""Validate data."""
<|body_0|>
def destroy_all(self):
"""It will delete all favorite items."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
token = de... | stack_v2_sparse_classes_75kplus_train_001216 | 10,323 | no_license | [
{
"docstring": "Validate data.",
"name": "validate",
"signature": "def validate(self, data)"
},
{
"docstring": "It will delete all favorite items.",
"name": "destroy_all",
"signature": "def destroy_all(self)"
}
] | 2 | null | Implement the Python class `FavoriteDestroyAllSerializer` described below.
Class description:
Favorite destroy all serialzer.
Method signatures and docstrings:
- def validate(self, data): Validate data.
- def destroy_all(self): It will delete all favorite items. | Implement the Python class `FavoriteDestroyAllSerializer` described below.
Class description:
Favorite destroy all serialzer.
Method signatures and docstrings:
- def validate(self, data): Validate data.
- def destroy_all(self): It will delete all favorite items.
<|skeleton|>
class FavoriteDestroyAllSerializer:
"... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class FavoriteDestroyAllSerializer:
"""Favorite destroy all serialzer."""
def validate(self, data):
"""Validate data."""
<|body_0|>
def destroy_all(self):
"""It will delete all favorite items."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FavoriteDestroyAllSerializer:
"""Favorite destroy all serialzer."""
def validate(self, data):
"""Validate data."""
token = decode_token(data['authorization'], data['secret'], 1)
if token['username'] != self.context['request'].user.username:
raise serializers.Validation... | the_stack_v2_python_sparse | api/services/serializers.py | ignite7/backproject | train | 0 |
0f3523e36b486756b67e717e0ca05968a884befe | [
"logger.info(command)\nfrom subprocess import Popen, PIPE\nprocess = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)\noutput, error = process.communicate()\nret = process.wait()\nif output:\n logger.info(output)\nif error:\n if ret == 0:\n logger.info(error)\n else:\n logger.error(error)... | <|body_start_0|>
logger.info(command)
from subprocess import Popen, PIPE
process = Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
output, error = process.communicate()
ret = process.wait()
if output:
logger.info(output)
if error:
if r... | a collection of os utilities | OSUtilities | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OSUtilities:
"""a collection of os utilities"""
def RunCommandAndLogStdOutStdErr(command, logger):
"""Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file"""
<|body_0|>
def GetNullRed... | stack_v2_sparse_classes_75kplus_train_001217 | 1,408 | no_license | [
{
"docstring": "Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file",
"name": "RunCommandAndLogStdOutStdErr",
"signature": "def RunCommandAndLogStdOutStdErr(command, logger)"
},
{
"docstring": "Return NULL r... | 2 | stack_v2_sparse_classes_30k_train_030178 | Implement the Python class `OSUtilities` described below.
Class description:
a collection of os utilities
Method signatures and docstrings:
- def RunCommandAndLogStdOutStdErr(command, logger): Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the conso... | Implement the Python class `OSUtilities` described below.
Class description:
a collection of os utilities
Method signatures and docstrings:
- def RunCommandAndLogStdOutStdErr(command, logger): Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the conso... | 9ff48f61cfd4e0c5994ad3dabab3987255cea953 | <|skeleton|>
class OSUtilities:
"""a collection of os utilities"""
def RunCommandAndLogStdOutStdErr(command, logger):
"""Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file"""
<|body_0|>
def GetNullRed... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OSUtilities:
"""a collection of os utilities"""
def RunCommandAndLogStdOutStdErr(command, logger):
"""Use this function to capture the output from a command Capture both the output and the errors Send output/errors to the console and log file"""
logger.info(command)
from subproces... | the_stack_v2_python_sparse | EAA_Dataloader/src/AACloudTools/OSUtilities.py | eulertech/backup | train | 0 |
630e67cf5a05c64305b6116765d7b0b37dfbcddf | [
"try:\n job_type = 'job-{}'.format(algo_id)\n response = hysds.get_job_spec(job_type)\n params = response.get('result').get('params')\n queue = response.get('result').get('recommended-queues')[0]\n response_body = ogc.describe_process_response(algo_id, params, queue)\n return Response(response_bod... | <|body_start_0|>
try:
job_type = 'job-{}'.format(algo_id)
response = hysds.get_job_spec(job_type)
params = response.get('result').get('params')
queue = response.get('result').get('recommended-queues')[0]
response_body = ogc.describe_process_response(al... | Describe | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Describe:
def get(self, algo_id):
"""request detailed metadata on selected processes offered by a server :return:"""
<|body_0|>
def delete(self, algo_id):
"""delete a registered algorithm :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:... | stack_v2_sparse_classes_75kplus_train_001218 | 17,721 | permissive | [
{
"docstring": "request detailed metadata on selected processes offered by a server :return:",
"name": "get",
"signature": "def get(self, algo_id)"
},
{
"docstring": "delete a registered algorithm :return:",
"name": "delete",
"signature": "def delete(self, algo_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004711 | Implement the Python class `Describe` described below.
Class description:
Implement the Describe class.
Method signatures and docstrings:
- def get(self, algo_id): request detailed metadata on selected processes offered by a server :return:
- def delete(self, algo_id): delete a registered algorithm :return: | Implement the Python class `Describe` described below.
Class description:
Implement the Describe class.
Method signatures and docstrings:
- def get(self, algo_id): request detailed metadata on selected processes offered by a server :return:
- def delete(self, algo_id): delete a registered algorithm :return:
<|skelet... | 90a11f06bd6404bae7a9da1feb541a0469b3c34c | <|skeleton|>
class Describe:
def get(self, algo_id):
"""request detailed metadata on selected processes offered by a server :return:"""
<|body_0|>
def delete(self, algo_id):
"""delete a registered algorithm :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Describe:
def get(self, algo_id):
"""request detailed metadata on selected processes offered by a server :return:"""
try:
job_type = 'job-{}'.format(algo_id)
response = hysds.get_job_spec(job_type)
params = response.get('result').get('params')
qu... | the_stack_v2_python_sparse | api/endpoints/algorithm.py | MAAP-Project/maap-api-nasa | train | 6 | |
e1d5ecf4b46f17ca85f33fd0c62e27d7dc72e515 | [
"self.lg('%s STARTED' % self._testID)\nresponse = self.get_request_response(uri='/attributes')\nself.lg('#. Get /attributes, should succeed')\nself.assertEqual(response.status_code, 200)\nself.assertTrue(response.ok)\n\"\\n self.lg('#. Check response headers, should succeed')\\n [self.assertIn(header,... | <|body_start_0|>
self.lg('%s STARTED' % self._testID)
response = self.get_request_response(uri='/attributes')
self.lg('#. Get /attributes, should succeed')
self.assertEqual(response.status_code, 200)
self.assertTrue(response.ok)
"\n self.lg('#. Check response heade... | TestAttributes | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestAttributes:
def test001_get_attributes(self):
"""TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
<|body_0|>
def test002_get_attribut... | stack_v2_sparse_classes_75kplus_train_001219 | 4,747 | no_license | [
{
"docstring": "TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, should succeed #. Check response body, should succeed",
"name": "test001_get_attributes",
"signature": "def test001_get_attributes(self)"
},
{
"docstr... | 2 | stack_v2_sparse_classes_30k_train_044036 | Implement the Python class `TestAttributes` described below.
Class description:
Implement the TestAttributes class.
Method signatures and docstrings:
- def test001_get_attributes(self): TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, sh... | Implement the Python class `TestAttributes` described below.
Class description:
Implement the TestAttributes class.
Method signatures and docstrings:
- def test001_get_attributes(self): TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, sh... | 9b25ce55fd44976b1b8afc1fb638c1a1b4d3589d | <|skeleton|>
class TestAttributes:
def test001_get_attributes(self):
"""TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
<|body_0|>
def test002_get_attribut... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestAttributes:
def test001_get_attributes(self):
"""TestCase-2: Test case for test get /attributes.* **Test Scenario:** #. Get /attributes, should succeed #. Check response headers, should succeed #. Check response body, should succeed"""
self.lg('%s STARTED' % self._testID)
response ... | the_stack_v2_python_sparse | mobile_api_testing/testsuite/test_attributes.py | simplymahmoud/sss-scripts | train | 0 | |
09de470be2c2634ab66936a3c925e44de07bb43b | [
"if text.startswith('\"'):\n return PVS_dquotedString.decode(text)\nreturn PVS_ptoken.decode(text)",
"m = PVS_ptoken._re.match(value)\nif m is not None and len(value) == m.end():\n return PVS_ptoken.encode(value)\nreturn PVS_dquotedString.encode(value)"
] | <|body_start_0|>
if text.startswith('"'):
return PVS_dquotedString.decode(text)
return PVS_ptoken.decode(text)
<|end_body_0|>
<|body_start_1|>
m = PVS_ptoken._re.match(value)
if m is not None and len(value) == m.end():
return PVS_ptoken.encode(value)
retu... | Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value. | PVS_unknown | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins wit... | stack_v2_sparse_classes_75kplus_train_001220 | 11,879 | permissive | [
{
"docstring": "Override base class to support either dquotedString or ptoken. If the text begins with double-quotes, this processes as :meth:`PVS_dquotedString.decode`. Otherwise, it processes as :meth:`PVS_ptoken.decode`.",
"name": "decode",
"signature": "def decode(self, text)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_val_000572 | Implement the Python class `PVS_unknown` described below.
Class description:
Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value.
Method signatures and docstrings:
- def decode(self, text): Override base class to suppo... | Implement the Python class `PVS_unknown` described below.
Class description:
Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value.
Method signatures and docstrings:
- def decode(self, text): Override base class to suppo... | f512355c5fde6bf027d23558e256b96e2296e0f2 | <|skeleton|>
class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins wit... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PVS_unknown:
"""Value support for unrecognized parameters. This matches either :class:`PVS_ptoken` or :class:`PVS_dquotedString`, depending on the content of the value."""
def decode(self, text):
"""Override base class to support either dquotedString or ptoken. If the text begins with double-quot... | the_stack_v2_python_sparse | eds/openmtc-gevent/common/openmtc/lib/coap/coapy/coapy/link.py | elastest/elastest-device-emulator-service | train | 3 |
e53f989c318f09dc4283c2c5933a5b0d739d83ef | [
"if not product_id:\n products = product_db.Product.all()\n products_result = [{'product_id': p.key().name()} for p in products]\n result = {'products': products_result}\nelse:\n product = product_db.Product.get_by_key_name(product_id)\n if not product:\n self.error(httplib.NOT_FOUND)\n ... | <|body_start_0|>
if not product_id:
products = product_db.Product.all()
products_result = [{'product_id': p.key().name()} for p in products]
result = {'products': products_result}
else:
product = product_db.Product.get_by_key_name(product_id)
i... | A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the handler. Note that PUT is not handled beca... | ProductHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the ... | stack_v2_sparse_classes_75kplus_train_001221 | 3,664 | no_license | [
{
"docstring": "Responds with information about all products or a specific product. /products/ Responds with a JSON encoded object that contains a list of product IDs. /products/<product> Responds with a JSON encoded object of the product ID and its child client IDs for the given product. Args: product_id. The ... | 3 | stack_v2_sparse_classes_30k_train_024317 | Implement the Python class `ProductHandler` described below.
Class description:
A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so t... | Implement the Python class `ProductHandler` described below.
Class description:
A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so t... | 4fe608d3225f38e765928c137214428cb60c3cd1 | <|skeleton|>
class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProductHandler:
"""A class to handle creating, reading, updating and deleting products. Handles GET, POST and DELETE requests for /products/ and /products/<product>. All functions have the same signature, even though they may not use all the parameters, so that a single route can be used for the handler. Note... | the_stack_v2_python_sparse | syzygy/dashboard/handler/product.py | TheRyuu/sawbuck | train | 4 |
a9976c8a058a79d2316cc6a852756807759278e1 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), full_name=full_name, phone_number=phone_number)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, full_name=full_na... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), full_name=full_name, phone_number=phone_number)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<... | AppUserManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppUserManager:
def create_user(self, email, full_name, phone_number, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, full_name, phone_number, password):
"""Creates and save... | stack_v2_sparse_classes_75kplus_train_001222 | 6,087 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, full_name, phone_number, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, phone_number and password... | 2 | null | Implement the Python class `AppUserManager` described below.
Class description:
Implement the AppUserManager class.
Method signatures and docstrings:
- def create_user(self, email, full_name, phone_number, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuse... | Implement the Python class `AppUserManager` described below.
Class description:
Implement the AppUserManager class.
Method signatures and docstrings:
- def create_user(self, email, full_name, phone_number, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuse... | ac1491fa057b2dc89357cee98856919d0c2f2a0d | <|skeleton|>
class AppUserManager:
def create_user(self, email, full_name, phone_number, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, full_name, phone_number, password):
"""Creates and save... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppUserManager:
def create_user(self, email, full_name, phone_number, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_e... | the_stack_v2_python_sparse | core/models.py | Chithien994/myapp | train | 1 | |
b42cd3bb8e5279f575e5be41b39b387ec110fb05 | [
"records = []\nfor _ in range(start_id, start_id + record_count):\n record = self.__create_record()\n records.append(record)\nreturn records",
"instrument = self.get_random_instrument()\nrecord = {'instrument_id': instrument['instrument_id'], 'price': self.create_random_decimal(min=1, max=10, dp=2), 'curren... | <|body_start_0|>
records = []
for _ in range(start_id, start_id + record_count):
record = self.__create_record()
records.append(record)
return records
<|end_body_0|>
<|body_start_1|>
instrument = self.get_random_instrument()
record = {'instrument_id': ins... | Class to create prices. Create method will create a set amount of prices. | PriceFactory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create... | stack_v2_sparse_classes_75kplus_train_001223 | 1,577 | no_license | [
{
"docstring": "Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create from lock : Lock Locks critical section of InstrumentFactory class. Defaults to None in all other Factory classes. Returns ------- List Containing 'record_count'... | 2 | stack_v2_sparse_classes_30k_train_046130 | Implement the Python class `PriceFactory` described below.
Class description:
Class to create prices. Create method will create a set amount of prices.
Method signatures and docstrings:
- def create(self, record_count, start_id, lock=None): Create a set number of prices Parameters ---------- record_count : int Number... | Implement the Python class `PriceFactory` described below.
Class description:
Class to create prices. Create method will create a set amount of prices.
Method signatures and docstrings:
- def create(self, record_count, start_id, lock=None): Create a set number of prices Parameters ---------- record_count : int Number... | 1d8257bdd9e4533161f64e114f57312905adad5c | <|skeleton|>
class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PriceFactory:
"""Class to create prices. Create method will create a set amount of prices."""
def create(self, record_count, start_id, lock=None):
"""Create a set number of prices Parameters ---------- record_count : int Number of prices to create start_id : int Starting id to create from lock : ... | the_stack_v2_python_sparse | src/domainobjectfactories/price_factory.py | galatea-associates/fuse-test-data-gen | train | 0 |
8c82b5d0f509b1da59c09261d10c2fa84ec3815c | [
"def reverse(start, end):\n first = start.next\n current = first.next\n while current != end:\n first.next = current.next\n current.next = start.next\n start.next = current\n current = first.next\ndummy = ListNode(-1)\ndummy.next = head\ncurrent, current_dummy = (head, dummy)\nc... | <|body_start_0|>
def reverse(start, end):
first = start.next
current = first.next
while current != end:
first.next = current.next
current.next = start.next
start.next = current
current = first.next
dummy ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def reverseKGroup_failed(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
def reverseKGroup_attempt2(self, ... | stack_v2_sparse_classes_75kplus_train_001224 | 4,444 | no_license | [
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup",
"signature": "def reverseKGroup(self, head, k)"
},
{
"docstring": ":type head: ListNode :type k: int :rtype: ListNode",
"name": "reverseKGroup_failed",
"signature": "def reverseKGroup_failed(sel... | 4 | stack_v2_sparse_classes_30k_train_003724 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def reverseKGroup_failed(self, head, k): :type head: ListNode :type k: int :rtype: ListNode... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverseKGroup(self, head, k): :type head: ListNode :type k: int :rtype: ListNode
- def reverseKGroup_failed(self, head, k): :type head: ListNode :type k: int :rtype: ListNode... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_0|>
def reverseKGroup_failed(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
def reverseKGroup_attempt2(self, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def reverseKGroup(self, head, k):
""":type head: ListNode :type k: int :rtype: ListNode"""
def reverse(start, end):
first = start.next
current = first.next
while current != end:
first.next = current.next
current.next... | the_stack_v2_python_sparse | src/lt_25.py | oxhead/CodingYourWay | train | 0 | |
3064504dc9bc70e64d4a51d972c78837678d0c61 | [
"logits = tf.constant([[0.1, 0.2, 0.7], [0.3, 0.5, 0.2]], dtype='float32')\nlabels = tf.constant([2, 1], dtype='int32')\nadv_target_config = configs.AdvTargetConfig(target_method=configs.AdvTargetType.SECOND)\nself.assertAllEqual(tf.constant([1, 0], dtype='int32'), self.evaluate(utils.get_target_indices(logits, lab... | <|body_start_0|>
logits = tf.constant([[0.1, 0.2, 0.7], [0.3, 0.5, 0.2]], dtype='float32')
labels = tf.constant([2, 1], dtype='int32')
adv_target_config = configs.AdvTargetConfig(target_method=configs.AdvTargetType.SECOND)
self.assertAllEqual(tf.constant([1, 0], dtype='int32'), self.eval... | GetTargetIndicesTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetTargetIndicesTest:
def testGetSecondIndices(self):
"""Test get_target_indices function with AdvTargetType.SECOND."""
<|body_0|>
def testGetLeastIndices(self):
"""Test get_target_indices function with AdvTargetType.LEAST."""
<|body_1|>
def testGetGroun... | stack_v2_sparse_classes_75kplus_train_001225 | 36,436 | permissive | [
{
"docstring": "Test get_target_indices function with AdvTargetType.SECOND.",
"name": "testGetSecondIndices",
"signature": "def testGetSecondIndices(self)"
},
{
"docstring": "Test get_target_indices function with AdvTargetType.LEAST.",
"name": "testGetLeastIndices",
"signature": "def tes... | 4 | stack_v2_sparse_classes_30k_train_014133 | Implement the Python class `GetTargetIndicesTest` described below.
Class description:
Implement the GetTargetIndicesTest class.
Method signatures and docstrings:
- def testGetSecondIndices(self): Test get_target_indices function with AdvTargetType.SECOND.
- def testGetLeastIndices(self): Test get_target_indices funct... | Implement the Python class `GetTargetIndicesTest` described below.
Class description:
Implement the GetTargetIndicesTest class.
Method signatures and docstrings:
- def testGetSecondIndices(self): Test get_target_indices function with AdvTargetType.SECOND.
- def testGetLeastIndices(self): Test get_target_indices funct... | 995064233479e806a3187ede8a395319520db75e | <|skeleton|>
class GetTargetIndicesTest:
def testGetSecondIndices(self):
"""Test get_target_indices function with AdvTargetType.SECOND."""
<|body_0|>
def testGetLeastIndices(self):
"""Test get_target_indices function with AdvTargetType.LEAST."""
<|body_1|>
def testGetGroun... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GetTargetIndicesTest:
def testGetSecondIndices(self):
"""Test get_target_indices function with AdvTargetType.SECOND."""
logits = tf.constant([[0.1, 0.2, 0.7], [0.3, 0.5, 0.2]], dtype='float32')
labels = tf.constant([2, 1], dtype='int32')
adv_target_config = configs.AdvTargetCon... | the_stack_v2_python_sparse | neural_structured_learning/lib/utils_test.py | RubensZimbres/neural-structured-learning | train | 1 | |
a830b750fc9af21bb10fa3e3201be43b9626ca98 | [
"self.__config = config\nself.__logger = SLoggerHandler().getLogger(LoggerNames.EXPERIMENT_C)\nself.__num_gpus = ConfigProvider().get_config('controllerConfig.json')['hardware']['numGPUs']",
"for csnn_config in self.__config['csnnConfigs']:\n csnn_name = csnn_config['modelName']\n try:\n for dataset_... | <|body_start_0|>
self.__config = config
self.__logger = SLoggerHandler().getLogger(LoggerNames.EXPERIMENT_C)
self.__num_gpus = ConfigProvider().get_config('controllerConfig.json')['hardware']['numGPUs']
<|end_body_0|>
<|body_start_1|>
for csnn_config in self.__config['csnnConfigs']:
... | The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutional Neural Networks for Representation Learning". The experiment test each pre trained CSNN mod... | CsnnReconstructionExperiment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CsnnReconstructionExperiment:
"""The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutional Neural Networks for Representation ... | stack_v2_sparse_classes_75kplus_train_001226 | 5,474 | permissive | [
{
"docstring": "Constructor, initialize member variables. :param config: (Dictionary) The config of the experiment, containing all model parameters. Refer to the config csnnReconstructionExperiment.json as an example.",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstrin... | 2 | stack_v2_sparse_classes_30k_train_014548 | Implement the Python class `CsnnReconstructionExperiment` described below.
Class description:
The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutio... | Implement the Python class `CsnnReconstructionExperiment` described below.
Class description:
The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutio... | 4bfea618727eb403e8b6f9863488e8b6e7d021cd | <|skeleton|>
class CsnnReconstructionExperiment:
"""The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutional Neural Networks for Representation ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CsnnReconstructionExperiment:
"""The CsnnReconstructionExperiment test the given pre-trained CSNN by reconstructing the images from the encoding. The reconstructions are presented in Figure 6 of our paper: "CSNNs: Unsupervised, ackpropagation-Free Convolutional Neural Networks for Representation Learning". Th... | the_stack_v2_python_sparse | Experiment_Component/Experiments/CsnnReconstructionExperiment.py | BonifazStuhr/CSNN | train | 7 |
8ccdd5278b6e9bee47f5f3b81ceb0bc1a4b5aec4 | [
"BaseModel.__init__(self, env, handle)\nself.name = name\nself.subclass_name = subclass_name",
"if has_gpu():\n return mx.gpu()\nelse:\n return mx.cpu()",
"if not os.path.exists(dir_name):\n os.mkdir(dir_name)\ndir_name = os.path.join(dir_name, self.name)\nif not os.path.exists(dir_name):\n os.mkdir... | <|body_start_0|>
BaseModel.__init__(self, env, handle)
self.name = name
self.subclass_name = subclass_name
<|end_body_0|>
<|body_start_1|>
if has_gpu():
return mx.gpu()
else:
return mx.cpu()
<|end_body_1|>
<|body_start_2|>
if not os.path.exists(d... | MXBaseModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MXBaseModel:
def __init__(self, env, handle, name, subclass_name):
"""init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: str name of subclass"""
<|body_0|>
def _get_ctx(self):
"""return correct context ... | stack_v2_sparse_classes_75kplus_train_001227 | 1,779 | permissive | [
{
"docstring": "init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: str name of subclass",
"name": "__init__",
"signature": "def __init__(self, env, handle, name, subclass_name)"
},
{
"docstring": "return correct context , priority:... | 4 | stack_v2_sparse_classes_30k_train_054294 | Implement the Python class `MXBaseModel` described below.
Class description:
Implement the MXBaseModel class.
Method signatures and docstrings:
- def __init__(self, env, handle, name, subclass_name): init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: st... | Implement the Python class `MXBaseModel` described below.
Class description:
Implement the MXBaseModel class.
Method signatures and docstrings:
- def __init__(self, env, handle, name, subclass_name): init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: st... | 2144dbd4bef49a8bda499dee95956c3fa04d6a43 | <|skeleton|>
class MXBaseModel:
def __init__(self, env, handle, name, subclass_name):
"""init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: str name of subclass"""
<|body_0|>
def _get_ctx(self):
"""return correct context ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MXBaseModel:
def __init__(self, env, handle, name, subclass_name):
"""init a model Parameters ---------- env: magent.Environment handle: handle (ctypes.c_int32) name: str subclass_name: str name of subclass"""
BaseModel.__init__(self, env, handle)
self.name = name
self.subclass... | the_stack_v2_python_sparse | python/magent/builtin/mx_model/base.py | geek-ai/MAgent | train | 1,741 | |
9cf7479ac7893d4c1e9b1041b07c465c6840fb3e | [
"with h5py.File(file_name, 'w') as f:\n f.attrs['name'] = self.name\n f.attrs['description'] = self.description\n f.attrs['interpolation_degree'] = self.interpolation_degree\n f.attrs['spline_smoothing_factor'] = self.spline_smoothing_factor\n f.create_dataset('energies', data=self.energies, compress... | <|body_start_0|>
with h5py.File(file_name, 'w') as f:
f.attrs['name'] = self.name
f.attrs['description'] = self.description
f.attrs['interpolation_degree'] = self.interpolation_degree
f.attrs['spline_smoothing_factor'] = self.spline_smoothing_factor
f.... | simple container to read and write the data to an hdf5 file | TemplateFile | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
<|body_0|>
def from_file(cls, file_name: str):
"""read contents... | stack_v2_sparse_classes_75kplus_train_001228 | 30,788 | permissive | [
{
"docstring": "serialize the contents to a file :param file_name: :type file_name: str :returns:",
"name": "save",
"signature": "def save(self, file_name: str)"
},
{
"docstring": "read contents from a file :param cls: :type cls: :param file_name: :type file_name: str :returns:",
"name": "fr... | 2 | stack_v2_sparse_classes_30k_train_001839 | Implement the Python class `TemplateFile` described below.
Class description:
simple container to read and write the data to an hdf5 file
Method signatures and docstrings:
- def save(self, file_name: str): serialize the contents to a file :param file_name: :type file_name: str :returns:
- def from_file(cls, file_name... | Implement the Python class `TemplateFile` described below.
Class description:
simple container to read and write the data to an hdf5 file
Method signatures and docstrings:
- def save(self, file_name: str): serialize the contents to a file :param file_name: :type file_name: str :returns:
- def from_file(cls, file_name... | 1ffa3f8d9f5459fa181864e91eab6cb1945c69c7 | <|skeleton|>
class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
<|body_0|>
def from_file(cls, file_name: str):
"""read contents... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TemplateFile:
"""simple container to read and write the data to an hdf5 file"""
def save(self, file_name: str):
"""serialize the contents to a file :param file_name: :type file_name: str :returns:"""
with h5py.File(file_name, 'w') as f:
f.attrs['name'] = self.name
... | the_stack_v2_python_sparse | astromodels/functions/template_model.py | threeML/astromodels | train | 30 |
e48ecdb4971af81115051efecde872e2ebffd3c8 | [
"if N == 0:\n return '0'\nt = N\nk = 1\nr = ''\nwhile t != 0:\n if t % 2 == 1:\n r = '1' + r\n t -= k\n else:\n r = '0' + r\n t = t // 2\n k *= -1\nreturn r",
"if N == 0:\n return '0'\nlist_tail = ['0b000', '0b001', '0b110', '0b111', '0b1001']\nlist_start = [0, 0, 1, 1]\nres... | <|body_start_0|>
if N == 0:
return '0'
t = N
k = 1
r = ''
while t != 0:
if t % 2 == 1:
r = '1' + r
t -= k
else:
r = '0' + r
t = t // 2
k *= -1
return r
<|end_body_0... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
<|body_0|>
def baseNeg2_2(self, N: int) -> str:
"""空虚解法 :param N: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if N == 0:
return '0'
... | stack_v2_sparse_classes_75kplus_train_001229 | 1,088 | no_license | [
{
"docstring": "so hard 补偿的思路 :param N: :return:",
"name": "baseNeg2",
"signature": "def baseNeg2(self, N: int) -> str"
},
{
"docstring": "空虚解法 :param N: :return:",
"name": "baseNeg2_2",
"signature": "def baseNeg2_2(self, N: int) -> str"
}
] | 2 | stack_v2_sparse_classes_30k_train_022084 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def baseNeg2(self, N: int) -> str: so hard 补偿的思路 :param N: :return:
- def baseNeg2_2(self, N: int) -> str: 空虚解法 :param N: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def baseNeg2(self, N: int) -> str: so hard 补偿的思路 :param N: :return:
- def baseNeg2_2(self, N: int) -> str: 空虚解法 :param N: :return:
<|skeleton|>
class Solution:
def baseNeg2... | 4105e18050b15fc0409c75353ad31be17187dd34 | <|skeleton|>
class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
<|body_0|>
def baseNeg2_2(self, N: int) -> str:
"""空虚解法 :param N: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def baseNeg2(self, N: int) -> str:
"""so hard 补偿的思路 :param N: :return:"""
if N == 0:
return '0'
t = N
k = 1
r = ''
while t != 0:
if t % 2 == 1:
r = '1' + r
t -= k
else:
... | the_stack_v2_python_sparse | baseNeg2.py | NeilWangziyu/Leetcode_py | train | 2 | |
23b05c29e736b822f673b1dd5246ae11126df428 | [
"context = {}\nclient = get_object_or_404(Client, id=kwargs['client_id'])\ncontext['form'] = ClientForm(instance=client)\nreturn render(self.request, self.template_name, context)",
"client = get_object_or_404(Client, id=kwargs['client_id'])\nform = ClientForm(self.request.POST, instance=client, company=self.reque... | <|body_start_0|>
context = {}
client = get_object_or_404(Client, id=kwargs['client_id'])
context['form'] = ClientForm(instance=client)
return render(self.request, self.template_name, context)
<|end_body_0|>
<|body_start_1|>
client = get_object_or_404(Client, id=kwargs['client_id... | View edit form client | ClientEditView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Getting the filled client form"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cont... | stack_v2_sparse_classes_75kplus_train_001230 | 4,241 | no_license | [
{
"docstring": "Display the client form",
"name": "get",
"signature": "def get(self, *args, **kwargs)"
},
{
"docstring": "Getting the filled client form",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020015 | Implement the Python class `ClientEditView` described below.
Class description:
View edit form client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, request, *args, **kwargs): Getting the filled client form | Implement the Python class `ClientEditView` described below.
Class description:
View edit form client
Method signatures and docstrings:
- def get(self, *args, **kwargs): Display the client form
- def post(self, request, *args, **kwargs): Getting the filled client form
<|skeleton|>
class ClientEditView:
"""View e... | 17615ea9bfb1edebe41d60dbf2e977f0018d5339 | <|skeleton|>
class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Getting the filled client form"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClientEditView:
"""View edit form client"""
def get(self, *args, **kwargs):
"""Display the client form"""
context = {}
client = get_object_or_404(Client, id=kwargs['client_id'])
context['form'] = ClientForm(instance=client)
return render(self.request, self.template... | the_stack_v2_python_sparse | clients/views.py | Swiftkind/invoice | train | 0 |
6daae0224b7e97ce995a68440691d77ed888b217 | [
"self.number = number\nself.holder_name = holder_name\nself.exp_month = exp_month\nself.exp_year = exp_year\nself.cvv = cvv\nself.brand = brand\nself.label = label",
"if dictionary is None:\n return None\nnumber = dictionary.get('number')\nholder_name = dictionary.get('holder_name')\nexp_month = dictionary.get... | <|body_start_0|>
self.number = number
self.holder_name = holder_name
self.exp_month = exp_month
self.exp_year = exp_year
self.cvv = cvv
self.brand = brand
self.label = label
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
... | Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informed with 2 or 4 digits cvv (string): The card's secu... | CreateCardTokenRequest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informe... | stack_v2_sparse_classes_75kplus_train_001231 | 2,734 | permissive | [
{
"docstring": "Constructor for the CreateCardTokenRequest class",
"name": "__init__",
"signature": "def __init__(self, number=None, holder_name=None, exp_month=None, exp_year=None, cvv=None, brand=None, label=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: di... | 2 | stack_v2_sparse_classes_30k_train_009884 | Implement the Python class `CreateCardTokenRequest` described below.
Class description:
Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): T... | Implement the Python class `CreateCardTokenRequest` described below.
Class description:
Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): T... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informe... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateCardTokenRequest:
"""Implementation of the 'CreateCardTokenRequest' model. Card token data Attributes: number (string): Credit card number holder_name (string): Holder name, as written on the card exp_month (int): The expiration month exp_year (int): The expiration year, that can be informed with 2 or 4... | the_stack_v2_python_sparse | mundiapi/models/create_card_token_request.py | mundipagg/MundiAPI-PYTHON | train | 10 |
6d078a3d1c2f0c49120e51b78407890462e0c6c6 | [
"if model_Y is None:\n model_Y = model_X\nnX = model_X / self.length_scales\nnY = model_Y / self.length_scales\ndist_sq = cdist(nX, nY, 'sqeuclidean')\ndist = np.sqrt(dist_sq)\nK = (1.0 + np.sqrt(5.0) * dist + 5.0 / 3.0 * dist_sq) * np.exp(-np.sqrt(5.0) * dist)\nreturn self.amplitude * K",
"diff = x - Y\ndiff ... | <|body_start_0|>
if model_Y is None:
model_Y = model_X
nX = model_X / self.length_scales
nY = model_Y / self.length_scales
dist_sq = cdist(nX, nY, 'sqeuclidean')
dist = np.sqrt(dist_sq)
K = (1.0 + np.sqrt(5.0) * dist + 5.0 / 3.0 * dist_sq) * np.exp(-np.sqrt(5.... | Matern-5/2 Kernel Class | MaternKernel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaternKernel:
"""Matern-5/2 Kernel Class"""
def cov(self, model_X, model_Y=None):
"""Implementation of abstract base class method."""
<|body_0|>
def grad_input(self, x, Y):
"""Implementation of abstract base class method. This code was taken from the implementati... | stack_v2_sparse_classes_75kplus_train_001232 | 4,675 | permissive | [
{
"docstring": "Implementation of abstract base class method.",
"name": "cov",
"signature": "def cov(self, model_X, model_Y=None)"
},
{
"docstring": "Implementation of abstract base class method. This code was taken from the implementation in scikit-optimize [1]. Per the New BSD License: Copyrig... | 3 | null | Implement the Python class `MaternKernel` described below.
Class description:
Matern-5/2 Kernel Class
Method signatures and docstrings:
- def cov(self, model_X, model_Y=None): Implementation of abstract base class method.
- def grad_input(self, x, Y): Implementation of abstract base class method. This code was taken ... | Implement the Python class `MaternKernel` described below.
Class description:
Matern-5/2 Kernel Class
Method signatures and docstrings:
- def cov(self, model_X, model_Y=None): Implementation of abstract base class method.
- def grad_input(self, x, Y): Implementation of abstract base class method. This code was taken ... | cb63d6dd476eba7dfe701643dc21694089ed881b | <|skeleton|>
class MaternKernel:
"""Matern-5/2 Kernel Class"""
def cov(self, model_X, model_Y=None):
"""Implementation of abstract base class method."""
<|body_0|>
def grad_input(self, x, Y):
"""Implementation of abstract base class method. This code was taken from the implementati... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaternKernel:
"""Matern-5/2 Kernel Class"""
def cov(self, model_X, model_Y=None):
"""Implementation of abstract base class method."""
if model_Y is None:
model_Y = model_X
nX = model_X / self.length_scales
nY = model_Y / self.length_scales
dist_sq = cdi... | the_stack_v2_python_sparse | sif/kernels/matern_kernel.py | afcarl/Sif-1 | train | 0 |
cc78fcab44d7e3b51de7078bbda7bef25935addd | [
"if self.material:\n lit = 1\n alpha = self.material.render(mode=mode)\nelse:\n lit = 0\n alpha = 1\n glColor3f(1, 1, 1)\ntextureToken = None\nif self.texture:\n textured = 1\n if self.texture.render(lit=lit, mode=mode):\n if alpha == 1.0:\n alpha = 0.5\n if self.textureTra... | <|body_start_0|>
if self.material:
lit = 1
alpha = self.material.render(mode=mode)
else:
lit = 0
alpha = 1
glColor3f(1, 1, 1)
textureToken = None
if self.texture:
textured = 1
if self.texture.render(lit=l... | Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearance to the appropriate geometry. Note that multiple Shape nodes are likely to u... | Appearance | [
"LicenseRef-scancode-warranty-disclaimer",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LGPL-2.1-or-later",
"GPL-3.0-only",
"LGPL-2.0-or-later",
"GPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Appearance:
"""Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearance to the appropriate geometry. Note tha... | stack_v2_sparse_classes_75kplus_train_001233 | 3,876 | permissive | [
{
"docstring": "Render Appearance, return (lit, textured, alpha, textureToken) Renders the appearance node, returning 3 status flags and a token which can be used to disable any enabled textures. Should only be called during visible rendering runs",
"name": "render",
"signature": "def render(self, mode=... | 3 | stack_v2_sparse_classes_30k_train_015457 | Implement the Python class `Appearance` described below.
Class description:
Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearanc... | Implement the Python class `Appearance` described below.
Class description:
Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearanc... | 7f600ad153270feff12aa7aa86d7ed0a49ebc71c | <|skeleton|>
class Appearance:
"""Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearance to the appropriate geometry. Note tha... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Appearance:
"""Specifies visual properties for geometry The appearance node specifies a set of appearance properties to be applied to some number of geometry objects. The Appearance node should be managed by a surrounding Shape node which binds the Appearance to the appropriate geometry. Note that multiple Sh... | the_stack_v2_python_sparse | pythonAnimations/pyOpenGLChess/engineDirectory/oglc-env/lib/python2.7/site-packages/OpenGLContext/scenegraph/appearance.py | alexus37/AugmentedRealityChess | train | 1 |
7b59e629146ee1d483c89a9077339d9db42b239e | [
"msg = 'Must give values for either `value`, `value_id`, or both'\nvalue, value_id = (values.get('value'), values.get('value_id'))\nassert value or value_id, msg\nreturn values",
"if v is not None:\n assert bool(re.match('^[A-Z*\\\\-]*$', v))\nreturn v"
] | <|body_start_0|>
msg = 'Must give values for either `value`, `value_id`, or both'
value, value_id = (values.get('value'), values.get('value_id'))
assert value or value_id, msg
return values
<|end_body_0|>
<|body_start_1|>
if v is not None:
assert bool(re.match('^[A-Z... | GA4GH Value Object Descriptor. | VariationDescriptor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VariationDescriptor:
"""GA4GH Value Object Descriptor."""
def check_value_or_value_id_present(cls, values):
"""Check that at least one of {`value`, `value_id`} is provided."""
<|body_0|>
def check_vrs_ref_allele_seq(cls, v):
"""Validate vrs_ref_allele_seq"""
... | stack_v2_sparse_classes_75kplus_train_001234 | 6,756 | permissive | [
{
"docstring": "Check that at least one of {`value`, `value_id`} is provided.",
"name": "check_value_or_value_id_present",
"signature": "def check_value_or_value_id_present(cls, values)"
},
{
"docstring": "Validate vrs_ref_allele_seq",
"name": "check_vrs_ref_allele_seq",
"signature": "de... | 2 | null | Implement the Python class `VariationDescriptor` described below.
Class description:
GA4GH Value Object Descriptor.
Method signatures and docstrings:
- def check_value_or_value_id_present(cls, values): Check that at least one of {`value`, `value_id`} is provided.
- def check_vrs_ref_allele_seq(cls, v): Validate vrs_r... | Implement the Python class `VariationDescriptor` described below.
Class description:
GA4GH Value Object Descriptor.
Method signatures and docstrings:
- def check_value_or_value_id_present(cls, values): Check that at least one of {`value`, `value_id`} is provided.
- def check_vrs_ref_allele_seq(cls, v): Validate vrs_r... | d41e9ee786b14f47d17ea8e458eed08ec00ba339 | <|skeleton|>
class VariationDescriptor:
"""GA4GH Value Object Descriptor."""
def check_value_or_value_id_present(cls, values):
"""Check that at least one of {`value`, `value_id`} is provided."""
<|body_0|>
def check_vrs_ref_allele_seq(cls, v):
"""Validate vrs_ref_allele_seq"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VariationDescriptor:
"""GA4GH Value Object Descriptor."""
def check_value_or_value_id_present(cls, values):
"""Check that at least one of {`value`, `value_id`} is provided."""
msg = 'Must give values for either `value`, `value_id`, or both'
value, value_id = (values.get('value'), ... | the_stack_v2_python_sparse | variation/schemas/ga4gh_vrsatile.py | richardhj/vicc-variation-normalization | train | 0 |
a2b025d9ea3072936da646d90a6429de8def6334 | [
"if key:\n self.key = key\nelse:\n from wsgi import application\n self.key = application.make('key')\nif not self.key:\n raise InvalidSecretKey('The encryption key passed in is: None. Be sure there is a secret key present in your .env file or your config/application.py file.')\nself.encryption = None",
... | <|body_start_0|>
if key:
self.key = key
else:
from wsgi import application
self.key = application.make('key')
if not self.key:
raise InvalidSecretKey('The encryption key passed in is: None. Be sure there is a secret key present in your .env file or... | Cryptographic signing class. | Sign | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Sign:
"""Cryptographic signing class."""
def __init__(self, key=None):
"""Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file. (default: {None}) Raises: InvalidSecretKey -- Thrown if ... | stack_v2_sparse_classes_75kplus_train_001235 | 2,357 | permissive | [
{
"docstring": "Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file. (default: {None}) Raises: InvalidSecretKey -- Thrown if the secret key does not exist.",
"name": "__init__",
"signature": "def __init_... | 3 | stack_v2_sparse_classes_30k_train_048608 | Implement the Python class `Sign` described below.
Class description:
Cryptographic signing class.
Method signatures and docstrings:
- def __init__(self, key=None): Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file.... | Implement the Python class `Sign` described below.
Class description:
Cryptographic signing class.
Method signatures and docstrings:
- def __init__(self, key=None): Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file.... | e8e55e5fdced9f28cc8acb1577457a490e5b4b74 | <|skeleton|>
class Sign:
"""Cryptographic signing class."""
def __init__(self, key=None):
"""Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file. (default: {None}) Raises: InvalidSecretKey -- Thrown if ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Sign:
"""Cryptographic signing class."""
def __init__(self, key=None):
"""Sign constructor. Keyword Arguments: key {string} -- The secret key to use. If nothing is passed it then it will use the secret key from the config file. (default: {None}) Raises: InvalidSecretKey -- Thrown if the secret ke... | the_stack_v2_python_sparse | src/masonite/auth/Sign.py | MasoniteFramework/masonite | train | 2,173 |
feecfe613f41f17b45455c0935ec56d78a542f5d | [
"self.mode = mode\nself.data_std = 0\nself.wn = None\nif self.mode == 'scale':\n self.data_std = np.std(data)\nelif self.mode.startswith('whiten.ZCA'):\n self.wn = mdp.nodes.WhiteningNode(svd=True)\n self.wn.train(data)\n self.wn.stop_training()\nelif self.mode.startswith('whiten'):\n self.wn = mdp.n... | <|body_start_0|>
self.mode = mode
self.data_std = 0
self.wn = None
if self.mode == 'scale':
self.data_std = np.std(data)
elif self.mode.startswith('whiten.ZCA'):
self.wn = mdp.nodes.WhiteningNode(svd=True)
self.wn.train(data)
self.w... | normalizer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class normalizer:
def __init__(self, data, mode):
"""Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on further data the exact same function is performed. For more information on whitening, look here: http... | stack_v2_sparse_classes_75kplus_train_001236 | 25,173 | no_license | [
{
"docstring": "Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on further data the exact same function is performed. For more information on whitening, look here: http://stats.stackexchange.com/questions/117427/what-is-the... | 2 | stack_v2_sparse_classes_30k_train_005314 | Implement the Python class `normalizer` described below.
Class description:
Implement the normalizer class.
Method signatures and docstrings:
- def __init__(self, data, mode): Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on fu... | Implement the Python class `normalizer` described below.
Class description:
Implement the normalizer class.
Method signatures and docstrings:
- def __init__(self, data, mode): Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on fu... | 2faa96c4c298274fb0b10aa9f4443cc5eae38e8d | <|skeleton|>
class normalizer:
def __init__(self, data, mode):
"""Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on further data the exact same function is performed. For more information on whitening, look here: http... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class normalizer:
def __init__(self, data, mode):
"""Initialize a normalizer to perform whitening or scaling of the data. The transformation parameters are fixed on initialization such that on further data the exact same function is performed. For more information on whitening, look here: http://stats.stack... | the_stack_v2_python_sparse | source/core/streamlined.py | sencheng/memories-improve-sensory-representations | train | 0 | |
780fb64f052cbe629bd0201d50ec4b1b5965feb6 | [
"if not value:\n msg = 'Traffic filter expression required.'\n raise AppResponseException(msg)\nif type_ and type_.upper() not in self.valid_types:\n msg = 'Traffic filter type needs to be one of {}'.format(self.valid_types)\n raise AppResponseException(msg)\nif type_ and type_.upper() == 'WIRESHARK' an... | <|body_start_0|>
if not value:
msg = 'Traffic filter expression required.'
raise AppResponseException(msg)
if type_ and type_.upper() not in self.valid_types:
msg = 'Traffic filter type needs to be one of {}'.format(self.valid_types)
raise AppResponseExcep... | TrafficFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<va... | stack_v2_sparse_classes_75kplus_train_001237 | 7,858 | permissive | [
{
"docstring": "Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<value1> OR <column_id>==<value2> where \"column_id\" refers to the ID of the ... | 2 | stack_v2_sparse_classes_30k_val_000935 | Implement the Python class `TrafficFilter` described below.
Class description:
Implement the TrafficFilter class.
Method signatures and docstrings:
- def __init__(self, value, type_=None, id_=None): Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTE... | Implement the Python class `TrafficFilter` described below.
Class description:
Implement the TrafficFilter class.
Method signatures and docstrings:
- def __init__(self, value, type_=None, id_=None): Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTE... | 69fafaa19f36efc33fdd9a407f41520bdbea78d4 | <|skeleton|>
class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<va... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TrafficFilter:
def __init__(self, value, type_=None, id_=None):
"""Initialize a TrafficFilter object. :param value: string, the actual filter expression :param type_: string, 'STEELFILTER' or 'WIRESHARK' or 'BPF', defaults to 'STEELFILTER' example STEELFILTER expression: <column_id>==<value1> OR <colu... | the_stack_v2_python_sparse | steelscript/appresponse/core/types.py | riverbed/steelscript-appresponse | train | 8 | |
2588d01a37cf249648a50a19ace788cf8cfd2d6e | [
"transientTerm = TransientTerm(coeff=1)\nconvectionTerm = ExplicitUpwindConvectionTerm(_ConvectionCoeff(distanceVar))\nself.bc = (FixedValue(distanceVar.getMesh().getExteriorFaces(), 0),)\nself.eq = transientTerm - convectionTerm",
"if type(boundaryConditions) not in (type(()), type([])):\n boundaryConditions ... | <|body_start_0|>
transientTerm = TransientTerm(coeff=1)
convectionTerm = ExplicitUpwindConvectionTerm(_ConvectionCoeff(distanceVar))
self.bc = (FixedValue(distanceVar.getMesh().getExteriorFaces(), 0),)
self.eq = transientTerm - convectionTerm
<|end_body_0|>
<|body_start_1|>
if t... | A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediately in front of the advancing interface. The method only works for a positive velocit... | SurfactantEquation | [
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SurfactantEquation:
"""A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediately in front of the advancing interface... | stack_v2_sparse_classes_75kplus_train_001238 | 4,589 | permissive | [
{
"docstring": "Creates a `SurfactantEquation` object. :Parameters: - `distanceVar`: The `DistanceVariable` that marks the interface.",
"name": "__init__",
"signature": "def __init__(self, distanceVar=None)"
},
{
"docstring": "Builds and solves the `SurfactantEquation`'s linear system once. :Par... | 3 | null | Implement the Python class `SurfactantEquation` described below.
Class description:
A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediat... | Implement the Python class `SurfactantEquation` described below.
Class description:
A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediat... | eb4aacf5a8e35cdb0e41beb0d79a93e7c8aacbad | <|skeleton|>
class SurfactantEquation:
"""A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediately in front of the advancing interface... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SurfactantEquation:
"""A `SurfactantEquation` aims to evolve a surfactant on an interface defined by the zero level set of the `distanceVar`. The method should completely conserve the total coverage of surfactant. The surfactant is only in the cells immediately in front of the advancing interface. The method ... | the_stack_v2_python_sparse | src/fipy/models/levelSet/surfactant/surfactantEquation.py | regmi/fipy | train | 1 |
2d70e053e3b4d924e649511c6329f31d89bb85e1 | [
"obj = self.get_object()\ncontext = {'user': request.user}\narchive_serializer = ArchiveSerializer(instance=obj, data=request.data, context=context, validators=self.archive_validators)\narchive_serializer.is_valid(raise_exception=True)\narchive_serializer.save()\nobj_serializer = self.get_serializer_class()(obj)\nr... | <|body_start_0|>
obj = self.get_object()
context = {'user': request.user}
archive_serializer = ArchiveSerializer(instance=obj, data=request.data, context=context, validators=self.archive_validators)
archive_serializer.is_valid(raise_exception=True)
archive_serializer.save()
... | To be used with archivable models. | ArchivableViewSetMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArchivableViewSetMixin:
"""To be used with archivable models."""
def archive(self, request, pk):
"""Archive the object."""
<|body_0|>
def unarchive(self, request, pk):
"""Unarchive the object."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
obj ... | stack_v2_sparse_classes_75kplus_train_001239 | 2,102 | permissive | [
{
"docstring": "Archive the object.",
"name": "archive",
"signature": "def archive(self, request, pk)"
},
{
"docstring": "Unarchive the object.",
"name": "unarchive",
"signature": "def unarchive(self, request, pk)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001844 | Implement the Python class `ArchivableViewSetMixin` described below.
Class description:
To be used with archivable models.
Method signatures and docstrings:
- def archive(self, request, pk): Archive the object.
- def unarchive(self, request, pk): Unarchive the object. | Implement the Python class `ArchivableViewSetMixin` described below.
Class description:
To be used with archivable models.
Method signatures and docstrings:
- def archive(self, request, pk): Archive the object.
- def unarchive(self, request, pk): Unarchive the object.
<|skeleton|>
class ArchivableViewSetMixin:
"... | a92faabf73fb93b5bfd94fd465eafc3e29aa6d8e | <|skeleton|>
class ArchivableViewSetMixin:
"""To be used with archivable models."""
def archive(self, request, pk):
"""Archive the object."""
<|body_0|>
def unarchive(self, request, pk):
"""Unarchive the object."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ArchivableViewSetMixin:
"""To be used with archivable models."""
def archive(self, request, pk):
"""Archive the object."""
obj = self.get_object()
context = {'user': request.user}
archive_serializer = ArchiveSerializer(instance=obj, data=request.data, context=context, vali... | the_stack_v2_python_sparse | datahub/core/mixins.py | cgsunkel/data-hub-api | train | 0 |
e94622c1359a5fc3f7ec8832a5b92607625e5c39 | [
"if not self._config:\n self._config = MTConfig().get_config()\nreturn self._config",
"if not self._config:\n self._config = MTConfig().get_config()\nreturn self._config[section]",
"if not self._config:\n self._config = MTConfig().get_config()\nencrypted = self._config"
] | <|body_start_0|>
if not self._config:
self._config = MTConfig().get_config()
return self._config
<|end_body_0|>
<|body_start_1|>
if not self._config:
self._config = MTConfig().get_config()
return self._config[section]
<|end_body_1|>
<|body_start_2|>
if n... | Handle Bender Config | MTConfigHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MTConfigHandler:
"""Handle Bender Config"""
def get_config(self):
"""Return static config, if not exist, get new config"""
<|body_0|>
def get_config_section(self, section=None):
"""Return config section, if not exist, init one and get anew"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus_train_001240 | 811 | no_license | [
{
"docstring": "Return static config, if not exist, get new config",
"name": "get_config",
"signature": "def get_config(self)"
},
{
"docstring": "Return config section, if not exist, init one and get anew",
"name": "get_config_section",
"signature": "def get_config_section(self, section=... | 3 | stack_v2_sparse_classes_30k_train_024779 | Implement the Python class `MTConfigHandler` described below.
Class description:
Handle Bender Config
Method signatures and docstrings:
- def get_config(self): Return static config, if not exist, get new config
- def get_config_section(self, section=None): Return config section, if not exist, init one and get anew
- ... | Implement the Python class `MTConfigHandler` described below.
Class description:
Handle Bender Config
Method signatures and docstrings:
- def get_config(self): Return static config, if not exist, get new config
- def get_config_section(self, section=None): Return config section, if not exist, init one and get anew
- ... | 7c8e4a596977995e055ee24913fbb22077984388 | <|skeleton|>
class MTConfigHandler:
"""Handle Bender Config"""
def get_config(self):
"""Return static config, if not exist, get new config"""
<|body_0|>
def get_config_section(self, section=None):
"""Return config section, if not exist, init one and get anew"""
<|body_1|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MTConfigHandler:
"""Handle Bender Config"""
def get_config(self):
"""Return static config, if not exist, get new config"""
if not self._config:
self._config = MTConfig().get_config()
return self._config
def get_config_section(self, section=None):
"""Return... | the_stack_v2_python_sparse | bender/app/controllers/mt_config_handler.py | nvh-gel/new_benderrodriguez | train | 0 |
0bd014b6dce430927457717c341b692a521baf4e | [
"self.availability_time_data_signal_id = availability_time_data_signal_id\nself.availability_production_data_signal_id = availability_production_data_signal_id\nself.lost_production_data_signal_id = lost_production_data_signal_id\nself.performance_data_signal_id = performance_data_signal_id",
"if dictionary is No... | <|body_start_0|>
self.availability_time_data_signal_id = availability_time_data_signal_id
self.availability_production_data_signal_id = availability_production_data_signal_id
self.lost_production_data_signal_id = lost_production_data_signal_id
self.performance_data_signal_id = performanc... | Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availability data. availability_production_data_signal_id (int): The id of the data signal used for p... | DataSignalConfiguration | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSignalConfiguration:
"""Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availability data. availability_production_data_si... | stack_v2_sparse_classes_75kplus_train_001241 | 3,074 | permissive | [
{
"docstring": "Constructor for the DataSignalConfiguration class",
"name": "__init__",
"signature": "def __init__(self, availability_time_data_signal_id=None, availability_production_data_signal_id=None, lost_production_data_signal_id=None, performance_data_signal_id=None)"
},
{
"docstring": "C... | 2 | stack_v2_sparse_classes_30k_train_037829 | Implement the Python class `DataSignalConfiguration` described below.
Class description:
Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availabilit... | Implement the Python class `DataSignalConfiguration` described below.
Class description:
Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availabilit... | 6835ee1f6a667b5c7827c5248391081f06b75513 | <|skeleton|>
class DataSignalConfiguration:
"""Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availability data. availability_production_data_si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSignalConfiguration:
"""Implementation of the 'DataSignalConfiguration' model. Your data signal configuration. These only apply to wind devices. Attributes: availability_time_data_signal_id (int): The id of the data signal used for time-based availability data. availability_production_data_signal_id (int)... | the_stack_v2_python_sparse | greenbyteapi/models/data_signal_configuration.py | charlie9578/greenbyte-api-sdk | train | 0 |
a45814e0049e61ec36c933421b5e0862aa1113b1 | [
"super(PprofEventObjectQueueConsumer, self).__init__(queue_object)\nself.counter = collections.Counter()\nself.parsers = []\nself.plugins = []",
"parser = getattr(event_object, 'parser', u'N/A')\nif parser not in self.parsers:\n self.parsers.append(parser)\nplugin = getattr(event_object, 'plugin', u'N/A')\nif ... | <|body_start_0|>
super(PprofEventObjectQueueConsumer, self).__init__(queue_object)
self.counter = collections.Counter()
self.parsers = []
self.plugins = []
<|end_body_0|>
<|body_start_1|>
parser = getattr(event_object, 'parser', u'N/A')
if parser not in self.parsers:
... | Class that implements an event object queue consumer for pprof. | PprofEventObjectQueueConsumer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PprofEventObjectQueueConsumer:
"""Class that implements an event object queue consumer for pprof."""
def __init__(self, queue_object):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue)."""
<|body_0|>
def _ConsumeEventObject(self,... | stack_v2_sparse_classes_75kplus_train_001242 | 1,272 | permissive | [
{
"docstring": "Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue).",
"name": "__init__",
"signature": "def __init__(self, queue_object)"
},
{
"docstring": "Consumes an event object callback for ConsumeEventObject.",
"name": "_ConsumeEventObject",
"s... | 2 | stack_v2_sparse_classes_30k_train_039628 | Implement the Python class `PprofEventObjectQueueConsumer` described below.
Class description:
Class that implements an event object queue consumer for pprof.
Method signatures and docstrings:
- def __init__(self, queue_object): Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue).... | Implement the Python class `PprofEventObjectQueueConsumer` described below.
Class description:
Class that implements an event object queue consumer for pprof.
Method signatures and docstrings:
- def __init__(self, queue_object): Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue).... | 2c504690d589bb9e6203d00d9ad53bfd45b32255 | <|skeleton|>
class PprofEventObjectQueueConsumer:
"""Class that implements an event object queue consumer for pprof."""
def __init__(self, queue_object):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue)."""
<|body_0|>
def _ConsumeEventObject(self,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PprofEventObjectQueueConsumer:
"""Class that implements an event object queue consumer for pprof."""
def __init__(self, queue_object):
"""Initializes the queue consumer. Args: queue_object: the queue object (instance of Queue)."""
super(PprofEventObjectQueueConsumer, self).__init__(queue_... | the_stack_v2_python_sparse | plaso/frontend/pprof.py | f-s-p/plaso | train | 0 |
3e48f9a43a606598b1fd815f8dd180a1cec9c502 | [
"super().__init__(max_health)\nself.inventory = Inventory()\nself.speed = speed\nself.attack_speed: float\nif self.speed - self.inventory.get_equipped_weight() <= 0:\n self.attack_speed = 1\nelse:\n self.attack_speed = 1 / (self.speed - self.inventory.get_equipped_weight())\nself.last_attack = 0\nself.blockin... | <|body_start_0|>
super().__init__(max_health)
self.inventory = Inventory()
self.speed = speed
self.attack_speed: float
if self.speed - self.inventory.get_equipped_weight() <= 0:
self.attack_speed = 1
else:
self.attack_speed = 1 / (self.speed - self... | A fighter is a living entity that can fight. It has an inventory. | Fighter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fighter:
"""A fighter is a living entity that can fight. It has an inventory."""
def __init__(self, max_health: int, speed: int) -> None:
""":param max_health: The maximum amount of health the fighter entity can have. :param speed: The initial speed of the fighter."""
<|body_... | stack_v2_sparse_classes_75kplus_train_001243 | 2,045 | no_license | [
{
"docstring": ":param max_health: The maximum amount of health the fighter entity can have. :param speed: The initial speed of the fighter.",
"name": "__init__",
"signature": "def __init__(self, max_health: int, speed: int) -> None"
},
{
"docstring": "Damages the entity, accounting for the equi... | 3 | null | Implement the Python class `Fighter` described below.
Class description:
A fighter is a living entity that can fight. It has an inventory.
Method signatures and docstrings:
- def __init__(self, max_health: int, speed: int) -> None: :param max_health: The maximum amount of health the fighter entity can have. :param sp... | Implement the Python class `Fighter` described below.
Class description:
A fighter is a living entity that can fight. It has an inventory.
Method signatures and docstrings:
- def __init__(self, max_health: int, speed: int) -> None: :param max_health: The maximum amount of health the fighter entity can have. :param sp... | e39aad09c180ce96353c9d0316c16de18178832c | <|skeleton|>
class Fighter:
"""A fighter is a living entity that can fight. It has an inventory."""
def __init__(self, max_health: int, speed: int) -> None:
""":param max_health: The maximum amount of health the fighter entity can have. :param speed: The initial speed of the fighter."""
<|body_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Fighter:
"""A fighter is a living entity that can fight. It has an inventory."""
def __init__(self, max_health: int, speed: int) -> None:
""":param max_health: The maximum amount of health the fighter entity can have. :param speed: The initial speed of the fighter."""
super().__init__(max... | the_stack_v2_python_sparse | source/traits/fighter.py | L0UARN/boring-dungeon | train | 1 |
c0daa33531b411122da1f3c9bf9530204f80a8c9 | [
"response = {}\ncountry = [country for country in TUYA_COUNTRIES if country.name == user_input[CONF_COUNTRY_CODE]][0]\ndata = {CONF_ENDPOINT: country.endpoint, CONF_AUTH_TYPE: AuthType.CUSTOM, CONF_ACCESS_ID: user_input[CONF_ACCESS_ID], CONF_ACCESS_SECRET: user_input[CONF_ACCESS_SECRET], CONF_USERNAME: user_input[C... | <|body_start_0|>
response = {}
country = [country for country in TUYA_COUNTRIES if country.name == user_input[CONF_COUNTRY_CODE]][0]
data = {CONF_ENDPOINT: country.endpoint, CONF_AUTH_TYPE: AuthType.CUSTOM, CONF_ACCESS_ID: user_input[CONF_ACCESS_ID], CONF_ACCESS_SECRET: user_input[CONF_ACCESS_SE... | Tuya Config Flow. | TuyaConfigFlow | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TuyaConfigFlow:
"""Tuya Config Flow."""
def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]:
"""Try login."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Step user."""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_75kplus_train_001244 | 4,649 | permissive | [
{
"docstring": "Try login.",
"name": "_try_login",
"signature": "def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]"
},
{
"docstring": "Step user.",
"name": "async_step_user",
"signature": "async def async_step_user(self, user_input=None)"
}
] | 2 | null | Implement the Python class `TuyaConfigFlow` described below.
Class description:
Tuya Config Flow.
Method signatures and docstrings:
- def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]: Try login.
- async def async_step_user(self, user_input=None): Step user. | Implement the Python class `TuyaConfigFlow` described below.
Class description:
Tuya Config Flow.
Method signatures and docstrings:
- def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]: Try login.
- async def async_step_user(self, user_input=None): Step user.
<|skeleton|>
class TuyaC... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class TuyaConfigFlow:
"""Tuya Config Flow."""
def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]:
"""Try login."""
<|body_0|>
async def async_step_user(self, user_input=None):
"""Step user."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TuyaConfigFlow:
"""Tuya Config Flow."""
def _try_login(user_input: dict[str, Any]) -> tuple[dict[Any, Any], dict[str, Any]]:
"""Try login."""
response = {}
country = [country for country in TUYA_COUNTRIES if country.name == user_input[CONF_COUNTRY_CODE]][0]
data = {CONF_EN... | the_stack_v2_python_sparse | homeassistant/components/tuya/config_flow.py | home-assistant/core | train | 35,501 |
946d5c9cf9e4cb627e3b51d14465ccf60cb00664 | [
"self.V = V\nself.VW = VW\nself.E = E\nself.EW = EW\nself.D = []\nself.P = []\nself.BP = []",
"self.D = np.full(shape=np.shape(self.V), fill_value=0.0)\nself.P = np.full(shape=np.shape(self.V), fill_value=0.0)\nfor i in range(np.shape(self.V)[0]):\n if 0 == i:\n self.D[i] = np.multiply(self.V[i], self.V... | <|body_start_0|>
self.V = V
self.VW = VW
self.E = E
self.EW = EW
self.D = []
self.P = []
self.BP = []
<|end_body_0|>
<|body_start_1|>
self.D = np.full(shape=np.shape(self.V), fill_value=0.0)
self.P = np.full(shape=np.shape(self.V), fill_value=0.0)... | 实现条件随机场预测问题的维特比算法 | CRFLgb_1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRFLgb_1:
"""实现条件随机场预测问题的维特比算法"""
def __init__(self, V, VW, E, EW):
"""Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值"""
<|body_0|>
def Viterbi(self):
"""条件随机场预测问题的维特比算法,此算法一定要结合CRF参数化形式对应的状态路径图来... | stack_v2_sparse_classes_75kplus_train_001245 | 3,764 | no_license | [
{
"docstring": "Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值",
"name": "__init__",
"signature": "def __init__(self, V, VW, E, EW)"
},
{
"docstring": "条件随机场预测问题的维特比算法,此算法一定要结合CRF参数化形式对应的状态路径图来理解,更容易理解.",
"name": "Viterbi",
... | 2 | stack_v2_sparse_classes_30k_train_003549 | Implement the Python class `CRFLgb_1` described below.
Class description:
实现条件随机场预测问题的维特比算法
Method signatures and docstrings:
- def __init__(self, V, VW, E, EW): Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值
- def Viterbi(self): 条件随机场预测问题的维特比算法,此算法一... | Implement the Python class `CRFLgb_1` described below.
Class description:
实现条件随机场预测问题的维特比算法
Method signatures and docstrings:
- def __init__(self, V, VW, E, EW): Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值
- def Viterbi(self): 条件随机场预测问题的维特比算法,此算法一... | 32ba7b316a4945d062377a3cc37a926aa79b10b9 | <|skeleton|>
class CRFLgb_1:
"""实现条件随机场预测问题的维特比算法"""
def __init__(self, V, VW, E, EW):
"""Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值"""
<|body_0|>
def Viterbi(self):
"""条件随机场预测问题的维特比算法,此算法一定要结合CRF参数化形式对应的状态路径图来... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CRFLgb_1:
"""实现条件随机场预测问题的维特比算法"""
def __init__(self, V, VW, E, EW):
"""Init CRFLgb class :param V: 是定义在节点上的特征函数,称为状态特征 :param VW: 是V对应的权值 :param E: 是定义在边上的特征函数,称为转移特征 :param EW: 是E对应的权值"""
self.V = V
self.VW = VW
self.E = E
self.EW = EW
self.D = []
... | the_stack_v2_python_sparse | longgb/Algorithm/TextMining/NLP/methods/CRF.py | longgb246/pythonstudy | train | 20 |
848b3f52b926fdc07717e1d0c24a2f0b32270235 | [
"direct_vec = np.zeros((11,))\nnext_direction = bp.Policy.TURNS[direction][action]\nnext_pos = head_pos.move(next_direction)\nboard_value = board[next_pos[0], next_pos[1]]\ndirect_vec[board_value + 1] = 1\nreturn direct_vec.tolist()",
"head_pos, direction = head\nvalues = np.zeros((11,))\nFeature1.features_around... | <|body_start_0|>
direct_vec = np.zeros((11,))
next_direction = bp.Policy.TURNS[direction][action]
next_pos = head_pos.move(next_direction)
board_value = board[next_pos[0], next_pos[1]]
direct_vec[board_value + 1] = 1
return direct_vec.tolist()
<|end_body_0|>
<|body_start... | Feature1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Feature1:
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :param board: board :return: zeros ... | stack_v2_sparse_classes_75kplus_train_001246 | 6,657 | no_license | [
{
"docstring": "Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :param board: board :return: zeros vector of size (11,) with 1 at the index of the value in the next position",
"... | 4 | stack_v2_sparse_classes_30k_train_019444 | Implement the Python class `Feature1` described below.
Class description:
Implement the Feature1 class.
Method signatures and docstrings:
- def next_action_feature(head_pos, direction, action, board): Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: he... | Implement the Python class `Feature1` described below.
Class description:
Implement the Feature1 class.
Method signatures and docstrings:
- def next_action_feature(head_pos, direction, action, board): Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: he... | d42d64300da96ac3c9c5378b1faba9693e93f14d | <|skeleton|>
class Feature1:
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :param board: board :return: zeros ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Feature1:
def next_action_feature(head_pos, direction, action, board):
"""Checks what is the value in the cell of the next action and return a vector according to he value :param head_pos: head position :param direction: direction :param action: action :param board: board :return: zeros vector of size... | the_stack_v2_python_sparse | policies/Feature1.py | LotanLevy/snake_game | train | 0 | |
13f94c2a08709ce33f70342c6c6cb7dad3b5ce42 | [
"self.name = name\nself.index = index\nself.resource_types = resource_types\nself.resource_tree = resource_tree",
"matched_nodes = set()\nfor resource in resources:\n if resource.type not in self.resource_types:\n continue\n node = self.resource_tree.match(resource, self.resource_types)\n if node:... | <|body_start_0|>
self.name = name
self.index = index
self.resource_types = resource_types
self.resource_tree = resource_tree
<|end_body_0|>
<|body_start_1|>
matched_nodes = set()
for resource in resources:
if resource.type not in self.resource_types:
... | Rule properties from the rule definition file. Also finds violations. | Rule | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, name, index, resource_types, resource_tree):
"""Initialize. Args: name (str): Name of the loaded rule. index (int): The index of the rule from the rule definitions. resource_types (Li... | stack_v2_sparse_classes_75kplus_train_001247 | 13,538 | permissive | [
{
"docstring": "Initialize. Args: name (str): Name of the loaded rule. index (int): The index of the rule from the rule definitions. resource_types (List[str]): The applicable resource types of this rule. resource_tree (ResourceTree): Tree representing the valid resources.",
"name": "__init__",
"signatu... | 2 | stack_v2_sparse_classes_30k_test_001306 | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, name, index, resource_types, resource_tree): Initialize. Args: name (str): Name of the loaded rule. index (int): The index ... | Implement the Python class `Rule` described below.
Class description:
Rule properties from the rule definition file. Also finds violations.
Method signatures and docstrings:
- def __init__(self, name, index, resource_types, resource_tree): Initialize. Args: name (str): Name of the loaded rule. index (int): The index ... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, name, index, resource_types, resource_tree):
"""Initialize. Args: name (str): Name of the loaded rule. index (int): The index of the rule from the rule definitions. resource_types (Li... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Rule:
"""Rule properties from the rule definition file. Also finds violations."""
def __init__(self, name, index, resource_types, resource_tree):
"""Initialize. Args: name (str): Name of the loaded rule. index (int): The index of the rule from the rule definitions. resource_types (List[str]): The... | the_stack_v2_python_sparse | google/cloud/forseti/scanner/audit/resource_rules_engine.py | kevensen/forseti-security | train | 1 |
b39c2636ecc0a419bab3a42117f8392ed86c90ea | [
"if not isinstance(q, np.ndarray):\n q = np.array(q)\nif q[0] != 0.0 or q[-1] != 1.0:\n raise RuntimeError('Invalid quantiles boundaries [' + ','.join([str(q[i]) for i in range(q.shape[0])]) + ']')\nif np.any(q[:-1] > q[1:]):\n raise RuntimeError('Quantile edges not increasing [' + ','.join([str(q[i]) for ... | <|body_start_0|>
if not isinstance(q, np.ndarray):
q = np.array(q)
if q[0] != 0.0 or q[-1] != 1.0:
raise RuntimeError('Invalid quantiles boundaries [' + ','.join([str(q[i]) for i in range(q.shape[0])]) + ']')
if np.any(q[:-1] > q[1:]):
raise RuntimeError('Quan... | Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized | Quantile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
<|body_0|>
def rebin_method(x, ... | stack_v2_sparse_classes_75kplus_train_001248 | 35,100 | no_license | [
{
"docstring": "h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]",
"name": "__init__",
"signature": "def __init__(self, h, q)"
},
{
"docstring": "x: bin centers w: bin heights (bin content) q: quantiles",
"name": "rebin_method",
"signature": "def rebin_method(x, w, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007543 | Implement the Python class `Quantile` described below.
Class description:
Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized
Method signatures and docstrings:
- def __init__(self, h, q): h : either TH1 or list of TH1 q : quantiles list [0... | Implement the Python class `Quantile` described below.
Class description:
Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized
Method signatures and docstrings:
- def __init__(self, h, q): h : either TH1 or list of TH1 q : quantiles list [0... | 30df434202df51017309b5bf88a1d9b94041b6ef | <|skeleton|>
class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
<|body_0|>
def rebin_method(x, ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
if not isinstance(q, np.ndarray):
q =... | the_stack_v2_python_sparse | ZAStatAnalysis/Rebinning.py | kjaffel/ZA_FullAnalysis | train | 11 |
32578fa394c6ef10c8ebe636cccb497310ed34b8 | [
"with open(file_path) as file:\n file_contents = [line for line in file]\nunchanged_contents = copy.deepcopy(file_contents)\nfile_contents = list(enumerate(file_contents))\nif verbose:\n print('Removing commented lines.')\nfile_contents = self.remove_commented(file_contents)\nif verbose:\n print('Splitting... | <|body_start_0|>
with open(file_path) as file:
file_contents = [line for line in file]
unchanged_contents = copy.deepcopy(file_contents)
file_contents = list(enumerate(file_contents))
if verbose:
print('Removing commented lines.')
file_contents = self.remo... | Parse the master rgt input file and get necessary information. | ParseRGTInput | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParseRGTInput:
"""Parse the master rgt input file and get necessary information."""
def parse_file(self, file_path, verbose=False):
"""Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.input.master. :param verbose: (boolean) Whether to show sta... | stack_v2_sparse_classes_75kplus_train_001249 | 14,450 | no_license | [
{
"docstring": "Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.input.master. :param verbose: (boolean) Whether to show status. :returns: path_to_tests: (str) Path to location of tests in rgt, test_list: (list) List of dictionaries containing test information.",
"na... | 5 | stack_v2_sparse_classes_30k_train_003017 | Implement the Python class `ParseRGTInput` described below.
Class description:
Parse the master rgt input file and get necessary information.
Method signatures and docstrings:
- def parse_file(self, file_path, verbose=False): Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.in... | Implement the Python class `ParseRGTInput` described below.
Class description:
Parse the master rgt input file and get necessary information.
Method signatures and docstrings:
- def parse_file(self, file_path, verbose=False): Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.in... | e10166847bd112fcd4fb7044e1478515104017e4 | <|skeleton|>
class ParseRGTInput:
"""Parse the master rgt input file and get necessary information."""
def parse_file(self, file_path, verbose=False):
"""Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.input.master. :param verbose: (boolean) Whether to show sta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ParseRGTInput:
"""Parse the master rgt input file and get necessary information."""
def parse_file(self, file_path, verbose=False):
"""Get the path to tests and the tests from an rgt file. :param file_path: (str) Path to rgt.input.master. :param verbose: (boolean) Whether to show status. :returns... | the_stack_v2_python_sparse | scripts/parse_file.py | Tubbz-alt/harmony | train | 0 |
601edc3ad80c9b220c131372348260c6c25a9bb6 | [
"super(InvertedResidual, self).__init__()\nself.stride = stride\nassert stride in [1, 2]\nhidden_dim = int(round(inp * expand_ratio))\nself.use_res_connect = self.stride == 1 and inp == oup\nself.kernel_size = kernel_size\nlayers = []\nif expand_ratio != 1:\n layers.append(ConvBNNonLinear(nc, inp, hidden_dim, ke... | <|body_start_0|>
super(InvertedResidual, self).__init__()
self.stride = stride
assert stride in [1, 2]
hidden_dim = int(round(inp * expand_ratio))
self.use_res_connect = self.stride == 1 and inp == oup
self.kernel_size = kernel_size
layers = []
if expand_r... | InvertedResidual | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InvertedResidual:
def __init__(self, nc, inp, oup, stride, expand_ratio, kernel_size=3, nl_type=NonLinearType.RELU6, se_ratio=0, survival_prob=0, batch_norm_epsilon=1e-05, batch_norm_momentum=0.1, tf_padding=False):
"""A Inverted Residual block use in Efficient-Net :param nc: The network... | stack_v2_sparse_classes_75kplus_train_001250 | 9,304 | no_license | [
{
"docstring": "A Inverted Residual block use in Efficient-Net :param nc: The network quantization controller :param inp: The number of input channels :param oup: The number of output channels :param stride: The depth wise convolution stride :param expand_ratio: The block expand ratio for depth-wise convolution... | 2 | stack_v2_sparse_classes_30k_train_023277 | Implement the Python class `InvertedResidual` described below.
Class description:
Implement the InvertedResidual class.
Method signatures and docstrings:
- def __init__(self, nc, inp, oup, stride, expand_ratio, kernel_size=3, nl_type=NonLinearType.RELU6, se_ratio=0, survival_prob=0, batch_norm_epsilon=1e-05, batch_no... | Implement the Python class `InvertedResidual` described below.
Class description:
Implement the InvertedResidual class.
Method signatures and docstrings:
- def __init__(self, nc, inp, oup, stride, expand_ratio, kernel_size=3, nl_type=NonLinearType.RELU6, se_ratio=0, survival_prob=0, batch_norm_epsilon=1e-05, batch_no... | 3db2636d8682355179b34d5a8dda4f7837919f97 | <|skeleton|>
class InvertedResidual:
def __init__(self, nc, inp, oup, stride, expand_ratio, kernel_size=3, nl_type=NonLinearType.RELU6, se_ratio=0, survival_prob=0, batch_norm_epsilon=1e-05, batch_norm_momentum=0.1, tf_padding=False):
"""A Inverted Residual block use in Efficient-Net :param nc: The network... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InvertedResidual:
def __init__(self, nc, inp, oup, stride, expand_ratio, kernel_size=3, nl_type=NonLinearType.RELU6, se_ratio=0, survival_prob=0, batch_norm_epsilon=1e-05, batch_norm_momentum=0.1, tf_padding=False):
"""A Inverted Residual block use in Efficient-Net :param nc: The network quantization ... | the_stack_v2_python_sparse | networks/blocks.py | GH-Jo/HMQ_practice | train | 0 | |
3f33287eecefe78325409a694de6fc6fd0d505a0 | [
"if self.request.version == 'v6':\n return ScaleFileSerializerV6\nelif self.request.version == 'v7':\n return ScaleFileSerializerV6",
"if request.version == 'v6':\n return self._get_v6(request, recipe_id)\nelif request.version == 'v7':\n return self._get_v6(request, recipe_id)\nraise Http404()",
"st... | <|body_start_0|>
if self.request.version == 'v6':
return ScaleFileSerializerV6
elif self.request.version == 'v7':
return ScaleFileSerializerV6
<|end_body_0|>
<|body_start_1|>
if request.version == 'v6':
return self._get_v6(request, recipe_id)
elif req... | This is the endpoint for retrieving details about input files associated with a given recipe. | RecipeInputFilesView | [
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecipeInputFilesView:
"""This is the endpoint for retrieving details about input files associated with a given recipe."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
<|body_0|>
def get(self, req... | stack_v2_sparse_classes_75kplus_train_001251 | 29,952 | permissive | [
{
"docstring": "Returns the appropriate serializer based off the requests version of the REST API.",
"name": "get_serializer_class",
"signature": "def get_serializer_class(self)"
},
{
"docstring": "Retrieve detailed information about the input files for a recipe :param request: the HTTP GET requ... | 3 | stack_v2_sparse_classes_30k_train_033328 | Implement the Python class `RecipeInputFilesView` described below.
Class description:
This is the endpoint for retrieving details about input files associated with a given recipe.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of t... | Implement the Python class `RecipeInputFilesView` described below.
Class description:
This is the endpoint for retrieving details about input files associated with a given recipe.
Method signatures and docstrings:
- def get_serializer_class(self): Returns the appropriate serializer based off the requests version of t... | 28618aee07ceed9e4a6eb7b8d0e6f05b31d8fd6b | <|skeleton|>
class RecipeInputFilesView:
"""This is the endpoint for retrieving details about input files associated with a given recipe."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
<|body_0|>
def get(self, req... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RecipeInputFilesView:
"""This is the endpoint for retrieving details about input files associated with a given recipe."""
def get_serializer_class(self):
"""Returns the appropriate serializer based off the requests version of the REST API."""
if self.request.version == 'v6':
r... | the_stack_v2_python_sparse | scale/recipe/views.py | kfconsultant/scale | train | 0 |
cc0701021b6dfea75c9b2d1732a3944c5c42d6be | [
"kwargs = {}\nkwargs.setdefault('method', 'POST')\nkwargs.setdefault('url', '/ime-container/imeLogBillReport/createByTrackBill.action')\nkwargs.setdefault('data', data)\nreq = nr(**kwargs)\nreturn req",
"kwargs = {}\nkwargs.setdefault('method', 'POST')\nkwargs.setdefault('url', '/ime-container/imeLogBillReport/re... | <|body_start_0|>
kwargs = {}
kwargs.setdefault('method', 'POST')
kwargs.setdefault('url', '/ime-container/imeLogBillReport/createByTrackBill.action')
kwargs.setdefault('data', data)
req = nr(**kwargs)
return req
<|end_body_0|>
<|body_start_1|>
kwargs = {}
... | 物流报工类 | LogBillReport | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogBillReport:
"""物流报工类"""
def logbillreport_createByTrackBill(self, data):
"""物流单转换物流单报工单并保存接口 :param data: :return:"""
<|body_0|>
def logbillreport_reportByBill(self, data):
"""物流单报工-整单完工接口 :param data: :return:"""
<|body_1|>
def logbillreport_repo... | stack_v2_sparse_classes_75kplus_train_001252 | 2,241 | no_license | [
{
"docstring": "物流单转换物流单报工单并保存接口 :param data: :return:",
"name": "logbillreport_createByTrackBill",
"signature": "def logbillreport_createByTrackBill(self, data)"
},
{
"docstring": "物流单报工-整单完工接口 :param data: :return:",
"name": "logbillreport_reportByBill",
"signature": "def logbillreport... | 5 | stack_v2_sparse_classes_30k_train_043916 | Implement the Python class `LogBillReport` described below.
Class description:
物流报工类
Method signatures and docstrings:
- def logbillreport_createByTrackBill(self, data): 物流单转换物流单报工单并保存接口 :param data: :return:
- def logbillreport_reportByBill(self, data): 物流单报工-整单完工接口 :param data: :return:
- def logbillreport_reportBy... | Implement the Python class `LogBillReport` described below.
Class description:
物流报工类
Method signatures and docstrings:
- def logbillreport_createByTrackBill(self, data): 物流单转换物流单报工单并保存接口 :param data: :return:
- def logbillreport_reportByBill(self, data): 物流单报工-整单完工接口 :param data: :return:
- def logbillreport_reportBy... | 2c3b0f5667c9526130a57c5ce2f0865e8f97302f | <|skeleton|>
class LogBillReport:
"""物流报工类"""
def logbillreport_createByTrackBill(self, data):
"""物流单转换物流单报工单并保存接口 :param data: :return:"""
<|body_0|>
def logbillreport_reportByBill(self, data):
"""物流单报工-整单完工接口 :param data: :return:"""
<|body_1|>
def logbillreport_repo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogBillReport:
"""物流报工类"""
def logbillreport_createByTrackBill(self, data):
"""物流单转换物流单报工单并保存接口 :param data: :return:"""
kwargs = {}
kwargs.setdefault('method', 'POST')
kwargs.setdefault('url', '/ime-container/imeLogBillReport/createByTrackBill.action')
kwargs.setd... | the_stack_v2_python_sparse | 测试用例/接口自动化/接口自动化_V2/接口管理/物流管理/物流单报工.py | liuzhengxing/NeuSoftEEP_API_Test | train | 0 |
fcb7d218e4154d621c44e617d101713703eee8df | [
"if x <= 1:\n return x\nstart = 0\nend = x\nwhile start != end - 1:\n mid = (start + end) // 2\n if mid ** 2 <= x:\n start = mid\n else:\n end = mid\nreturn start",
"if x <= 1:\n return x\ncur = 1\nwhile True:\n cur, pre = ((cur + x / cur) / 2, cur)\n if isclose(cur, pre):\n ... | <|body_start_0|>
if x <= 1:
return x
start = 0
end = x
while start != end - 1:
mid = (start + end) // 2
if mid ** 2 <= x:
start = mid
else:
end = mid
return start
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""20190921"""
<|body_0|>
def mySqrt(self, x: int) -> int:
"""20190921"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if x <= 1:
return x
start = 0
end = x
while start !... | stack_v2_sparse_classes_75kplus_train_001253 | 1,185 | no_license | [
{
"docstring": "20190921",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
},
{
"docstring": "20190921",
"name": "mySqrt",
"signature": "def mySqrt(self, x: int) -> int"
}
] | 2 | stack_v2_sparse_classes_30k_train_053977 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 20190921
- def mySqrt(self, x: int) -> int: 20190921 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mySqrt(self, x: int) -> int: 20190921
- def mySqrt(self, x: int) -> int: 20190921
<|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""20190921"""
... | 99a3abf1774933af73a8405f9b59e5e64906bca4 | <|skeleton|>
class Solution:
def mySqrt(self, x: int) -> int:
"""20190921"""
<|body_0|>
def mySqrt(self, x: int) -> int:
"""20190921"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def mySqrt(self, x: int) -> int:
"""20190921"""
if x <= 1:
return x
start = 0
end = x
while start != end - 1:
mid = (start + end) // 2
if mid ** 2 <= x:
start = mid
else:
end = mid... | the_stack_v2_python_sparse | leetcode/69.sqrt.py | iamkissg/leetcode | train | 0 | |
1dc4e629a58d44b90370bd89ca7e60112e6d74ef | [
"if not isinstance(cookies, list) and cookies is not None:\n raise TypeError(\"'cookies' must be of type list or None\")\nif not isinstance(headers, dict) and headers is not None:\n raise TypeError(\"'headers' must be of type dict or None\")\nif not isinstance(query_string_params, dict) and query_string_param... | <|body_start_0|>
if not isinstance(cookies, list) and cookies is not None:
raise TypeError("'cookies' must be of type list or None")
if not isinstance(headers, dict) and headers is not None:
raise TypeError("'headers' must be of type dict or None")
if not isinstance(query... | ApiGatewayV2LambdaEvent | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApiGatewayV2LambdaEvent:
def __init__(self, route_key=None, raw_path=None, raw_query_string=None, cookies=None, headers=None, query_string_params=None, request_context=None, body=None, path_parameters=None, stage_variables=None, is_base_64_encoded=False):
"""Constructs an ApiGatewayV2Lam... | stack_v2_sparse_classes_75kplus_train_001254 | 17,708 | permissive | [
{
"docstring": "Constructs an ApiGatewayV2LambdaEvent. :param str route_key: The route key for the route. :param str raw_path: The raw path of the request. :param str raw_query_string: The raw query string of the request. :param list cookies: All cookie headers in the request are combined with commas and added ... | 2 | null | Implement the Python class `ApiGatewayV2LambdaEvent` described below.
Class description:
Implement the ApiGatewayV2LambdaEvent class.
Method signatures and docstrings:
- def __init__(self, route_key=None, raw_path=None, raw_query_string=None, cookies=None, headers=None, query_string_params=None, request_context=None,... | Implement the Python class `ApiGatewayV2LambdaEvent` described below.
Class description:
Implement the ApiGatewayV2LambdaEvent class.
Method signatures and docstrings:
- def __init__(self, route_key=None, raw_path=None, raw_query_string=None, cookies=None, headers=None, query_string_params=None, request_context=None,... | b297ff015f2b69d7c74059c2d42ece1c29ea73ee | <|skeleton|>
class ApiGatewayV2LambdaEvent:
def __init__(self, route_key=None, raw_path=None, raw_query_string=None, cookies=None, headers=None, query_string_params=None, request_context=None, body=None, path_parameters=None, stage_variables=None, is_base_64_encoded=False):
"""Constructs an ApiGatewayV2Lam... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApiGatewayV2LambdaEvent:
def __init__(self, route_key=None, raw_path=None, raw_query_string=None, cookies=None, headers=None, query_string_params=None, request_context=None, body=None, path_parameters=None, stage_variables=None, is_base_64_encoded=False):
"""Constructs an ApiGatewayV2LambdaEvent. :par... | the_stack_v2_python_sparse | samcli/local/events/api_event.py | aws/aws-sam-cli | train | 1,402 | |
651a7ea980a2b3e631454143183e385466e1f691 | [
"if self.version < 0 or self.type_id < 0:\n return False\nif self.type_id != BITSPacket.TYPE_LITERAL:\n return self.operator_mode != -1 and self.operator_value != -1\nreturn True",
"if not self.is_valid():\n return -1\nreturn len(self.raw)",
"if len(data) < 6 or int(data, 2) == 0:\n return (BITSPack... | <|body_start_0|>
if self.version < 0 or self.type_id < 0:
return False
if self.type_id != BITSPacket.TYPE_LITERAL:
return self.operator_mode != -1 and self.operator_value != -1
return True
<|end_body_0|>
<|body_start_1|>
if not self.is_valid():
return... | Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator). | BITSPacketHeader | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BITSPacketHeader:
"""Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator)."""
def is_valid(self) -> bool:
"""Is this header valid?"""
<|body_0|>
def size(self) -> int:
... | stack_v2_sparse_classes_75kplus_train_001255 | 12,227 | no_license | [
{
"docstring": "Is this header valid?",
"name": "is_valid",
"signature": "def is_valid(self) -> bool"
},
{
"docstring": "The size of the header.",
"name": "size",
"signature": "def size(self) -> int"
},
{
"docstring": "Takes a binary data stream and returns a header and payload."... | 3 | null | Implement the Python class `BITSPacketHeader` described below.
Class description:
Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator).
Method signatures and docstrings:
- def is_valid(self) -> bool: Is this header valid... | Implement the Python class `BITSPacketHeader` described below.
Class description:
Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator).
Method signatures and docstrings:
- def is_valid(self) -> bool: Is this header valid... | f3af1f213c57350d61a0a3ca04c590a7685a26f3 | <|skeleton|>
class BITSPacketHeader:
"""Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator)."""
def is_valid(self) -> bool:
"""Is this header valid?"""
<|body_0|>
def size(self) -> int:
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BITSPacketHeader:
"""Packet header for the [BITS protocol](https://adventofcode.com/2021/day/16). Contains the packet version, type_id and operator values (if an operator)."""
def is_valid(self) -> bool:
"""Is this header valid?"""
if self.version < 0 or self.type_id < 0:
retu... | the_stack_v2_python_sparse | 2021/bits.py | zachwlewis/adventofcode | train | 0 |
3e82be6a7be9c6a3f11d437da0bfe16949a6ad38 | [
"for c in pipe.components:\n if isinstance(c.model, NerConverter):\n return 'ner'\n if isinstance(c.model, DependencyParserModel):\n return 'dep'",
"document_col, entities_col = VizUtilsOS.infer_ner_dependencies(pipe)\nner_vis = NerVisualizer()\nner_vis.set_label_colors(viz_colors)\nif write_t... | <|body_start_0|>
for c in pipe.components:
if isinstance(c.model, NerConverter):
return 'ner'
if isinstance(c.model, DependencyParserModel):
return 'dep'
<|end_body_0|>
<|body_start_1|>
document_col, entities_col = VizUtilsOS.infer_ner_dependencie... | Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source | VizUtilsOS | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VizUtilsOS:
"""Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source"""
def infer_viz_open_source(pipe) -> str:
"""For a given NLUPipeline with only open source components, infers which visualizations are applicable."""
<|body_0... | stack_v2_sparse_classes_75kplus_train_001256 | 4,565 | permissive | [
{
"docstring": "For a given NLUPipeline with only open source components, infers which visualizations are applicable.",
"name": "infer_viz_open_source",
"signature": "def infer_viz_open_source(pipe) -> str"
},
{
"docstring": "Infer columns required for ner viz and then viz it. viz_colors : set l... | 5 | null | Implement the Python class `VizUtilsOS` described below.
Class description:
Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source
Method signatures and docstrings:
- def infer_viz_open_source(pipe) -> str: For a given NLUPipeline with only open source components, infers... | Implement the Python class `VizUtilsOS` described below.
Class description:
Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source
Method signatures and docstrings:
- def infer_viz_open_source(pipe) -> str: For a given NLUPipeline with only open source components, infers... | fd7e73bc3e331b49361fca93cf8d07cccd934adc | <|skeleton|>
class VizUtilsOS:
"""Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source"""
def infer_viz_open_source(pipe) -> str:
"""For a given NLUPipeline with only open source components, infers which visualizations are applicable."""
<|body_0... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VizUtilsOS:
"""Utils for interfacing with the Spark-NLP-Display lib and vizzing Open Source Components - Open source"""
def infer_viz_open_source(pipe) -> str:
"""For a given NLUPipeline with only open source components, infers which visualizations are applicable."""
for c in pipe.compone... | the_stack_v2_python_sparse | nlu/pipe/viz/vis_utils_OS.py | prakashcinna/nlu | train | 0 |
9e3d3cfd491d98cc28042f02a8b7422c3819d7b6 | [
"schema = BusinessSchema()\nbusiness = Business.get_by_id(business_id)\nif not business:\n return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)\nbusiness_data, errors = schema.dumps(business)\nif errors:\n return (dict(status='fail', message=errors), 500)\nreturn (dict(status... | <|body_start_0|>
schema = BusinessSchema()
business = Business.get_by_id(business_id)
if not business:
return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)
business_data, errors = schema.dumps(business)
if errors:
return (... | BusinessDetailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
<|body_0|>
def patch(self, business_id):
"""Update a single business"""
<|body_1|>
def delete(self, business_id):
"""Delete a single business"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus_train_001257 | 3,207 | no_license | [
{
"docstring": "Getting individual business",
"name": "get",
"signature": "def get(self, business_id)"
},
{
"docstring": "Update a single business",
"name": "patch",
"signature": "def patch(self, business_id)"
},
{
"docstring": "Delete a single business",
"name": "delete",
... | 3 | stack_v2_sparse_classes_30k_train_018033 | Implement the Python class `BusinessDetailView` described below.
Class description:
Implement the BusinessDetailView class.
Method signatures and docstrings:
- def get(self, business_id): Getting individual business
- def patch(self, business_id): Update a single business
- def delete(self, business_id): Delete a sin... | Implement the Python class `BusinessDetailView` described below.
Class description:
Implement the BusinessDetailView class.
Method signatures and docstrings:
- def get(self, business_id): Getting individual business
- def patch(self, business_id): Update a single business
- def delete(self, business_id): Delete a sin... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
<|body_0|>
def patch(self, business_id):
"""Update a single business"""
<|body_1|>
def delete(self, business_id):
"""Delete a single business"""
<|body_2|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BusinessDetailView:
def get(self, business_id):
"""Getting individual business"""
schema = BusinessSchema()
business = Business.get_by_id(business_id)
if not business:
return (dict(status='fail', message=f'Business with id {business_id} not found'), 404)
bus... | the_stack_v2_python_sparse | app/controllers/business.py | MutegekiHenry/project-cohort-backend | train | 0 | |
a168c17ea98eeea90e3ad2995316124b4d444755 | [
"if not quota_max_calls:\n use_rate_limiter = False\nself._organizations_roles = None\nself._projects_roles = None\nself._projects_serviceaccounts = None\nself._projects_serviceaccounts_keys = None\nself._roles = None\nsuper(IamRepositoryClient, self).__init__(API_NAME, versions=['v1'], quota_max_calls=quota_max... | <|body_start_0|>
if not quota_max_calls:
use_rate_limiter = False
self._organizations_roles = None
self._projects_roles = None
self._projects_serviceaccounts = None
self._projects_serviceaccounts_keys = None
self._roles = None
super(IamRepositoryClient... | IAM API Respository. | IamRepositoryClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IamRepositoryClient:
"""IAM API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to limit the requests... | stack_v2_sparse_classes_75kplus_train_001258 | 18,615 | permissive | [
{
"docstring": "Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to limit the requests within. use_rate_limiter (bool): Set to false to disable the use of a rate limiter for this service.",
"name": "__init__",
"signature": "... | 6 | null | Implement the Python class `IamRepositoryClient` described below.
Class description:
IAM API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. qu... | Implement the Python class `IamRepositoryClient` described below.
Class description:
IAM API Respository.
Method signatures and docstrings:
- def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True): Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. qu... | d4421afa50a17ed47cbebe942044ebab3720e0f5 | <|skeleton|>
class IamRepositoryClient:
"""IAM API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to limit the requests... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IamRepositoryClient:
"""IAM API Respository."""
def __init__(self, quota_max_calls=None, quota_period=1.0, use_rate_limiter=True):
"""Constructor. Args: quota_max_calls (int): Allowed requests per <quota_period> for the API. quota_period (float): The time period to limit the requests within. use_... | the_stack_v2_python_sparse | google/cloud/forseti/common/gcp_api/iam.py | kevensen/forseti-security | train | 1 |
f56c18108a790befe169d114b1fc7588eda64022 | [
"self._observer = observer\nself._shouldLogEvent = partial(shouldLogEvent, list(predicates))\nself._negativeObserver = negativeObserver",
"if self._shouldLogEvent(event):\n if 'log_trace' in event:\n event['log_trace'].append((self, self.observer))\n self._observer(event)\nelse:\n self._negativeOb... | <|body_start_0|>
self._observer = observer
self._shouldLogEvent = partial(shouldLogEvent, list(predicates))
self._negativeObserver = negativeObserver
<|end_body_0|>
<|body_start_1|>
if self._shouldLogEvent(event):
if 'log_trace' in event:
event['log_trace'].a... | L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s. | FilteringLogObserver | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this o... | stack_v2_sparse_classes_75kplus_train_001259 | 6,986 | permissive | [
{
"docstring": "@param observer: An observer to which this observer will forward events when C{predictates} yield a positive result. @type observer: L{ILogObserver} @param predicates: Predicates to apply to events before forwarding to the wrapped observer. @type predicates: ordered iterable of predicates @param... | 2 | stack_v2_sparse_classes_30k_train_006138 | Implement the Python class `FilteringLogObserver` described below.
Class description:
L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s.
Method signatures and docstrings:
- def __init__(self, observer, predicates, negativeObserver=lambda e... | Implement the Python class `FilteringLogObserver` described below.
Class description:
L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s.
Method signatures and docstrings:
- def __init__(self, observer, predicates, negativeObserver=lambda e... | 40861791ec4ed3bbd14b07875af25cc740f76920 | <|skeleton|>
class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this o... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FilteringLogObserver:
"""L{ILogObserver} that wraps another L{ILogObserver}, but filters out events based on applying a series of L{ILogFilterPredicate}s."""
def __init__(self, observer, predicates, negativeObserver=lambda event: None):
"""@param observer: An observer to which this observer will ... | the_stack_v2_python_sparse | stackoverflow/venv/lib/python3.6/site-packages/twisted/logger/_filter.py | wistbean/learn_python3_spider | train | 14,403 |
d6762308bd28add160ae74ce5c7a16db34577367 | [
"self.sid = sid\nself.pid = pid\nself.uid = uid\nself.position = 0\nself.status = 0\nself.stoploss = 0\nself.df = df.iloc[-250 * 5:]",
"price = np.float64(ticker['close'])\nhigh10 = self.df.iloc[-10 * 5:]['high'].max()\nlow10 = self.df.iloc[-10 * 5:]['low'].min()\nma250 = ma(self.df, n=250 * 5)\nangle = ma250.ilo... | <|body_start_0|>
self.sid = sid
self.pid = pid
self.uid = uid
self.position = 0
self.status = 0
self.stoploss = 0
self.df = df.iloc[-250 * 5:]
<|end_body_0|>
<|body_start_1|>
price = np.float64(ticker['close'])
high10 = self.df.iloc[-10 * 5:]['hig... | MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点; | Ma | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ma:
"""MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点;"""
def __init__(self, sid, pid, df, uid=None):
""":param sid: 策略ID :param pid: 品种ID :param uid: 用户ID :param df: 初始化数据表用于后期计算(pandas DataF... | stack_v2_sparse_classes_75kplus_train_001260 | 2,613 | no_license | [
{
"docstring": ":param sid: 策略ID :param pid: 品种ID :param uid: 用户ID :param df: 初始化数据表用于后期计算(pandas DataFrame)",
"name": "__init__",
"signature": "def __init__(self, sid, pid, df, uid=None)"
},
{
"docstring": ":param ticker: 订阅的数据 :return:",
"name": "algorithm",
"signature": "def algorithm... | 2 | null | Implement the Python class `Ma` described below.
Class description:
MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点;
Method signatures and docstrings:
- def __init__(self, sid, pid, df, uid=None): :param sid: 策略ID :param pid: 品... | Implement the Python class `Ma` described below.
Class description:
MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点;
Method signatures and docstrings:
- def __init__(self, sid, pid, df, uid=None): :param sid: 策略ID :param pid: 品... | ab0e4d114bcaf445a596d53889bbe79df323b27f | <|skeleton|>
class Ma:
"""MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点;"""
def __init__(self, sid, pid, df, uid=None):
""":param sid: 策略ID :param pid: 品种ID :param uid: 用户ID :param df: 初始化数据表用于后期计算(pandas DataF... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Ma:
"""MA 策略,应用周期:5分钟线 当ma250角度小于0,且价格大于ma250,记录状态为-1; 当ma250角度大于0,且价格小于ma250,记录状态为+1; 状态为-1时,向上突破10根K线高点,做多,止损10低点; 状态位+1时,向下突破10根K线低点,做空,止损10高点;"""
def __init__(self, sid, pid, df, uid=None):
""":param sid: 策略ID :param pid: 品种ID :param uid: 用户ID :param df: 初始化数据表用于后期计算(pandas DataFrame)"""
... | the_stack_v2_python_sparse | algorithm/ma.py | sylinuxhy/SignalPool | train | 0 |
4285f0d59ceb8d444865378384b0fa9f002261b0 | [
"course_certificates = self._get_ordered_certificates_for_user(request, username)\ncontext = {'course_certificates': course_certificates, 'own_profile': own_profile, 'disable_courseware_js': True}\nif course_certificates or own_profile:\n html = render_to_string('learner_profile/learner-achievements-fragment.htm... | <|body_start_0|>
course_certificates = self._get_ordered_certificates_for_user(request, username)
context = {'course_certificates': course_certificates, 'own_profile': own_profile, 'disable_courseware_js': True}
if course_certificates or own_profile:
html = render_to_string('learner_... | A fragment to render a learner's achievements. | LearnerAchievementsFragmentView | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LearnerAchievementsFragmentView:
"""A fragment to render a learner's achievements."""
def render_to_fragment(self, request, username=None, own_profile=False, **kwargs):
"""Renders the current learner's achievements."""
<|body_0|>
def _get_ordered_certificates_for_user(se... | stack_v2_sparse_classes_75kplus_train_001261 | 2,703 | permissive | [
{
"docstring": "Renders the current learner's achievements.",
"name": "render_to_fragment",
"signature": "def render_to_fragment(self, request, username=None, own_profile=False, **kwargs)"
},
{
"docstring": "Returns a user's certificates sorted by course name.",
"name": "_get_ordered_certifi... | 2 | null | Implement the Python class `LearnerAchievementsFragmentView` described below.
Class description:
A fragment to render a learner's achievements.
Method signatures and docstrings:
- def render_to_fragment(self, request, username=None, own_profile=False, **kwargs): Renders the current learner's achievements.
- def _get_... | Implement the Python class `LearnerAchievementsFragmentView` described below.
Class description:
A fragment to render a learner's achievements.
Method signatures and docstrings:
- def render_to_fragment(self, request, username=None, own_profile=False, **kwargs): Renders the current learner's achievements.
- def _get_... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class LearnerAchievementsFragmentView:
"""A fragment to render a learner's achievements."""
def render_to_fragment(self, request, username=None, own_profile=False, **kwargs):
"""Renders the current learner's achievements."""
<|body_0|>
def _get_ordered_certificates_for_user(se... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LearnerAchievementsFragmentView:
"""A fragment to render a learner's achievements."""
def render_to_fragment(self, request, username=None, own_profile=False, **kwargs):
"""Renders the current learner's achievements."""
course_certificates = self._get_ordered_certificates_for_user(request,... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/features/learner_profile/views/learner_achievements.py | luque/better-ways-of-thinking-about-software | train | 3 |
caeaf1d808ac9917645b985392db23e63befdf42 | [
"user = User.objects.create_user(username='hede', password='hede')\nurl = reverse('user-reports', args=[user.username])\nself.token_login()\ndata = simplejson.dumps({'text': 'Test'})\nrequest = self.c.post(path=url, content_type='application/json', data=data, **self.client_header)\nself.assertEqual(request.status_c... | <|body_start_0|>
user = User.objects.create_user(username='hede', password='hede')
url = reverse('user-reports', args=[user.username])
self.token_login()
data = simplejson.dumps({'text': 'Test'})
request = self.c.post(path=url, content_type='application/json', data=data, **self.c... | UserReportTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserReportTestCase:
def test_report_create(self):
"""Create Report"""
<|body_0|>
def test_invalid_user_create_report(self):
"""invalid user Create Report"""
<|body_1|>
def test_report_list(self):
"""Report List"""
<|body_2|>
def test... | stack_v2_sparse_classes_75kplus_train_001262 | 10,007 | no_license | [
{
"docstring": "Create Report",
"name": "test_report_create",
"signature": "def test_report_create(self)"
},
{
"docstring": "invalid user Create Report",
"name": "test_invalid_user_create_report",
"signature": "def test_invalid_user_create_report(self)"
},
{
"docstring": "Report ... | 5 | stack_v2_sparse_classes_30k_test_002654 | Implement the Python class `UserReportTestCase` described below.
Class description:
Implement the UserReportTestCase class.
Method signatures and docstrings:
- def test_report_create(self): Create Report
- def test_invalid_user_create_report(self): invalid user Create Report
- def test_report_list(self): Report List
... | Implement the Python class `UserReportTestCase` described below.
Class description:
Implement the UserReportTestCase class.
Method signatures and docstrings:
- def test_report_create(self): Create Report
- def test_invalid_user_create_report(self): invalid user Create Report
- def test_report_list(self): Report List
... | b8ba25fdde5d4ee92a3f73cb42ff892ed436d3f2 | <|skeleton|>
class UserReportTestCase:
def test_report_create(self):
"""Create Report"""
<|body_0|>
def test_invalid_user_create_report(self):
"""invalid user Create Report"""
<|body_1|>
def test_report_list(self):
"""Report List"""
<|body_2|>
def test... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserReportTestCase:
def test_report_create(self):
"""Create Report"""
user = User.objects.create_user(username='hede', password='hede')
url = reverse('user-reports', args=[user.username])
self.token_login()
data = simplejson.dumps({'text': 'Test'})
request = sel... | the_stack_v2_python_sparse | chatproject/apps/account/tests.py | QilinGu/chat-project | train | 0 | |
bbf771a38895a27528da1f5fce3587b4fa42e030 | [
"self.post_parser = reqparse.RequestParser()\nself.post_parser.add_argument('Name', type=str, required=True, help='No rule object name provided', location='json')\nself.post_parser.add_argument('Method', type=str, required=True, help='No rule method provided', location='json')\nself.post_parser.add_argument('Role',... | <|body_start_0|>
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Name', type=str, required=True, help='No rule object name provided', location='json')
self.post_parser.add_argument('Method', type=str, required=True, help='No rule method provided', location='json')
... | DefaultRules | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DefaultRules:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche toutes les regles par defaut associees aux noms d'objets"""
<|body_1|>
def post(self):
"""ajoute une regle par... | stack_v2_sparse_classes_75kplus_train_001263 | 2,623 | no_license | [
{
"docstring": "Constructeur: liste les champs attendus dans le corps HTML",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "affiche toutes les regles par defaut associees aux noms d'objets",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "... | 3 | stack_v2_sparse_classes_30k_train_040443 | Implement the Python class `DefaultRules` described below.
Class description:
Implement the DefaultRules class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche toutes les regles par defaut associees aux noms d'objets
- def pos... | Implement the Python class `DefaultRules` described below.
Class description:
Implement the DefaultRules class.
Method signatures and docstrings:
- def __init__(self): Constructeur: liste les champs attendus dans le corps HTML
- def get(self): affiche toutes les regles par defaut associees aux noms d'objets
- def pos... | 8f107644a74fe46827ec5ed53d0457022bd1608b | <|skeleton|>
class DefaultRules:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
<|body_0|>
def get(self):
"""affiche toutes les regles par defaut associees aux noms d'objets"""
<|body_1|>
def post(self):
"""ajoute une regle par... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DefaultRules:
def __init__(self):
"""Constructeur: liste les champs attendus dans le corps HTML"""
self.post_parser = reqparse.RequestParser()
self.post_parser.add_argument('Name', type=str, required=True, help='No rule object name provided', location='json')
self.post_parser.a... | the_stack_v2_python_sparse | authapp/view_def_rules.py | ldurandadomia/Flask-Restful | train | 0 | |
554ba4b34fbe2a9570439814ca148a902ee02591 | [
"EasyFrame.__init__(self)\nself.label = self.addLabel(text='Ticket Discount Calculator', row=0, column=0, columnspan=2, sticky='NSEW')\nself.label2 = self.addLabel(text='Original Ticket Price = $25.00', row=1, column=0, columnspan=2, sticky='NSEW')\nself.label3 = self.addLabel(text='Children (16 & Younger) = 10% Di... | <|body_start_0|>
EasyFrame.__init__(self)
self.label = self.addLabel(text='Ticket Discount Calculator', row=0, column=0, columnspan=2, sticky='NSEW')
self.label2 = self.addLabel(text='Original Ticket Price = $25.00', row=1, column=0, columnspan=2, sticky='NSEW')
self.label3 = self.addLab... | Illustrates command buttons and user events. | ButtonDemo | [
"CC0-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ButtonDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
<|body_0|>
def calculate(self):
"""."""
<|body_1|>
def clear(self):
"""Resets the label to the empty string and t... | stack_v2_sparse_classes_75kplus_train_001264 | 3,933 | permissive | [
{
"docstring": "Sets up the window, label, and buttons.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": ".",
"name": "calculate",
"signature": "def calculate(self)"
},
{
"docstring": "Resets the label to the empty string and the button states.",
"nam... | 3 | null | Implement the Python class `ButtonDemo` described below.
Class description:
Illustrates command buttons and user events.
Method signatures and docstrings:
- def __init__(self): Sets up the window, label, and buttons.
- def calculate(self): .
- def clear(self): Resets the label to the empty string and the button state... | Implement the Python class `ButtonDemo` described below.
Class description:
Illustrates command buttons and user events.
Method signatures and docstrings:
- def __init__(self): Sets up the window, label, and buttons.
- def calculate(self): .
- def clear(self): Resets the label to the empty string and the button state... | f4f4a9ca771c5254f530e9e92cd9e32fe46be41f | <|skeleton|>
class ButtonDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
<|body_0|>
def calculate(self):
"""."""
<|body_1|>
def clear(self):
"""Resets the label to the empty string and t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ButtonDemo:
"""Illustrates command buttons and user events."""
def __init__(self):
"""Sets up the window, label, and buttons."""
EasyFrame.__init__(self)
self.label = self.addLabel(text='Ticket Discount Calculator', row=0, column=0, columnspan=2, sticky='NSEW')
self.label2... | the_stack_v2_python_sparse | Joshua David Sakharny - Ticket Discount Calculator (Python GUI).py | joshuadavidsakharny/pythonProjects | train | 0 |
3207b24b55371b1f12e102101a7bc8a2abad83d4 | [
"res = []\nif not root:\n return []\n\ndef _recur_func(node, level):\n if len(res) == level:\n res.append([])\n res[level].append(node.val)\n if node.left:\n _recur_func(node.left, level + 1)\n if node.right:\n _recur_func(node.right, level + 1)\n_recur_func(root, 0)\nreturn res"... | <|body_start_0|>
res = []
if not root:
return []
def _recur_func(node, level):
if len(res) == level:
res.append([])
res[level].append(node.val)
if node.left:
_recur_func(node.left, level + 1)
if node.rig... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def levelOrder_recursion(self, root: TreeNode):
"""递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list"""
<|body_0|>
def levelOrder_iteration_t(self, root: TreeNode):
"""迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res"""
<|body_1|>
def level... | stack_v2_sparse_classes_75kplus_train_001265 | 3,953 | no_license | [
{
"docstring": "递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list",
"name": "levelOrder_recursion",
"signature": "def levelOrder_recursion(self, root: TreeNode)"
},
{
"docstring": "迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res",
"name": "levelOrder_iteration_t",
"signature": "def ... | 3 | stack_v2_sparse_classes_30k_train_019928 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder_recursion(self, root: TreeNode): 递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list
- def levelOrder_iteration_t(self, root: TreeNode): 迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def levelOrder_recursion(self, root: TreeNode): 递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list
- def levelOrder_iteration_t(self, root: TreeNode): 迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :... | 62ad010a992c031e8c0fe4d1a9b6f9364f96ed4c | <|skeleton|>
class Solution:
def levelOrder_recursion(self, root: TreeNode):
"""递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list"""
<|body_0|>
def levelOrder_iteration_t(self, root: TreeNode):
"""迭代实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: res"""
<|body_1|>
def level... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def levelOrder_recursion(self, root: TreeNode):
"""递归实现层次遍历二叉树,并逐层返回该层的值列表。 :param root: :return: list"""
res = []
if not root:
return []
def _recur_func(node, level):
if len(res) == level:
res.append([])
res[level]... | the_stack_v2_python_sparse | leetcode/solved/102_.py | usnnu/python_foundation | train | 0 | |
3521bc10d1058a01403545ad6d3a488e80d29253 | [
"super().__init__()\nself._attention_type = attention\nself.fc_subj = nn.Sequential(nn.Linear(1024, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU())\nself.fc_obj = nn.Sequential(nn.Linear(1024, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU())\nself.fc_subj_b = nn.Sequential(nn.Linear(1024, 256), nn.ReLU(), nn.Linea... | <|body_start_0|>
super().__init__()
self._attention_type = attention
self.fc_subj = nn.Sequential(nn.Linear(1024, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU())
self.fc_obj = nn.Sequential(nn.Linear(1024, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU())
self.fc_subj_b = nn.Sequ... | Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> | | ObjectSubjectBranch | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectSubjectBranch:
"""Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> |"""
def __init__(self, num_classes, attention='multi_head', use_language=True, use_spatial=True):
"""Initialize model.""... | stack_v2_sparse_classes_75kplus_train_001266 | 13,005 | no_license | [
{
"docstring": "Initialize model.",
"name": "__init__",
"signature": "def __init__(self, num_classes, attention='multi_head', use_language=True, use_spatial=True)"
},
{
"docstring": "Forward pass, return output scores.",
"name": "forward",
"signature": "def forward(self, subj_feats, obj_... | 2 | null | Implement the Python class `ObjectSubjectBranch` described below.
Class description:
Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> |
Method signatures and docstrings:
- def __init__(self, num_classes, attention='multi_head', ... | Implement the Python class `ObjectSubjectBranch` described below.
Class description:
Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> |
Method signatures and docstrings:
- def __init__(self, num_classes, attention='multi_head', ... | 810c79541a8584de3fe37943d244af366d361689 | <|skeleton|>
class ObjectSubjectBranch:
"""Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> |"""
def __init__(self, num_classes, attention='multi_head', use_language=True, use_spatial=True):
"""Initialize model.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ObjectSubjectBranch:
"""Object-Subject Branch. obj. features -> FC -> RELU -> FC -> RELU -> | - -> Att. Clsfr -> out subj. features -> FC -> RELU -> FC -> RELU -> |"""
def __init__(self, num_classes, attention='multi_head', use_language=True, use_spatial=True):
"""Initialize model."""
sup... | the_stack_v2_python_sparse | common/models/sg_generator/atr_net.py | bgzu/zs-vrd-bmvc20 | train | 0 |
9093b3e64c668357105e5b22a94a21af35526b82 | [
"assert type(jobs) == list\nassert type(number_jobs) == int\nassert jobs.__len__() == sum_jobs\nassert type(mode) == str\nassert mode in ['diff', 'ratio']\nself.jobs = jobs\nself.number_jobs = number_jobs\nself.mode = mode",
"if self.mode == 'diff':\n self.jobs.sort(key=lambda job: (job['weight'] - job['length... | <|body_start_0|>
assert type(jobs) == list
assert type(number_jobs) == int
assert jobs.__len__() == sum_jobs
assert type(mode) == str
assert mode in ['diff', 'ratio']
self.jobs = jobs
self.number_jobs = number_jobs
self.mode = mode
<|end_body_0|>
<|body_s... | GreedyJobScheduler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GreedyJobScheduler:
def __init__(self, jobs: [dict], number_jobs: int, mode: str='diff'):
"""schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :param number_jobs: number of jobs :param mode: must be "diff" or "ratio". If diff jobs will be scheduled by w... | stack_v2_sparse_classes_75kplus_train_001267 | 2,180 | no_license | [
{
"docstring": "schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :param number_jobs: number of jobs :param mode: must be \"diff\" or \"ratio\". If diff jobs will be scheduled by weight minus length. If ratio it will be weight / length",
"name": "__init__",
"signature"... | 3 | null | Implement the Python class `GreedyJobScheduler` described below.
Class description:
Implement the GreedyJobScheduler class.
Method signatures and docstrings:
- def __init__(self, jobs: [dict], number_jobs: int, mode: str='diff'): schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :pa... | Implement the Python class `GreedyJobScheduler` described below.
Class description:
Implement the GreedyJobScheduler class.
Method signatures and docstrings:
- def __init__(self, jobs: [dict], number_jobs: int, mode: str='diff'): schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :pa... | b94e9e89e50122e8c1c979b14657784933a79027 | <|skeleton|>
class GreedyJobScheduler:
def __init__(self, jobs: [dict], number_jobs: int, mode: str='diff'):
"""schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :param number_jobs: number of jobs :param mode: must be "diff" or "ratio". If diff jobs will be scheduled by w... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GreedyJobScheduler:
def __init__(self, jobs: [dict], number_jobs: int, mode: str='diff'):
"""schedules jobs based on weight and length :param jobs: list of jobs (weight, length) :param number_jobs: number of jobs :param mode: must be "diff" or "ratio". If diff jobs will be scheduled by weight minus le... | the_stack_v2_python_sparse | algorithms/GreedyJobScheduler.py | FelixKleineBoesing/algorithms | train | 0 | |
f624fe26f77d7a82b04b32ea8a9d1ab4c61b6c40 | [
"self.homepage = homepage\nself.pages = [homepage]\nself.current = 0",
"if self.current != len(self.pages) - 1:\n self.pages = self.pages[:self.current + 1]\n self.pages.append(url)\n self.current = len(self.pages) - 1\n return self.pages[self.current]\nelse:\n self.pages.append(url)\n self.curr... | <|body_start_0|>
self.homepage = homepage
self.pages = [homepage]
self.current = 0
<|end_body_0|>
<|body_start_1|>
if self.current != len(self.pages) - 1:
self.pages = self.pages[:self.current + 1]
self.pages.append(url)
self.current = len(self.pages)... | BrowserHistory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str if the user chooses steps too big, then r... | stack_v2_sparse_classes_75kplus_train_001268 | 1,465 | no_license | [
{
"docstring": ":type homepage: str",
"name": "__init__",
"signature": "def __init__(self, homepage)"
},
{
"docstring": ":type url: str :rtype: None",
"name": "visit",
"signature": "def visit(self, url)"
},
{
"docstring": ":type steps: int :rtype: str if the user chooses steps to... | 4 | stack_v2_sparse_classes_30k_train_000306 | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str if the use... | Implement the Python class `BrowserHistory` described below.
Class description:
Implement the BrowserHistory class.
Method signatures and docstrings:
- def __init__(self, homepage): :type homepage: str
- def visit(self, url): :type url: str :rtype: None
- def back(self, steps): :type steps: int :rtype: str if the use... | 6d6afba93d20665d033fe542c97e3eb50368bd3c | <|skeleton|>
class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
<|body_0|>
def visit(self, url):
""":type url: str :rtype: None"""
<|body_1|>
def back(self, steps):
""":type steps: int :rtype: str if the user chooses steps too big, then r... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BrowserHistory:
def __init__(self, homepage):
""":type homepage: str"""
self.homepage = homepage
self.pages = [homepage]
self.current = 0
def visit(self, url):
""":type url: str :rtype: None"""
if self.current != len(self.pages) - 1:
self.pages ... | the_stack_v2_python_sparse | browser_history.py | naomi397liu/AlgorithmPactice | train | 1 | |
802dc88788bd1e97330f5e65dec7e4f2bcad8eaf | [
"for st_line in self.filtered('move_name'):\n if st_line.journal_entry_ids.filtered(lambda x: x.payment_id.payment_reference == st_line.move_name):\n check_operation = self.env['account.check.operation'].search([('origin', '=', 'account.bank.statement.line,%s' % st_line.id)])\n check_operation.chec... | <|body_start_0|>
for st_line in self.filtered('move_name'):
if st_line.journal_entry_ids.filtered(lambda x: x.payment_id.payment_reference == st_line.move_name):
check_operation = self.env['account.check.operation'].search([('origin', '=', 'account.bank.statement.line,%s' % st_line.i... | AccountBankStatementLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountBankStatementLine:
def button_cancel_reconciliation(self):
"""Delete operation of checks that are debited from statement"""
<|body_0|>
def process_reconciliation(self, counterpart_aml_dicts=None, payment_aml_rec=None, new_aml_dicts=None):
"""Si el move line de... | stack_v2_sparse_classes_75kplus_train_001269 | 2,694 | no_license | [
{
"docstring": "Delete operation of checks that are debited from statement",
"name": "button_cancel_reconciliation",
"signature": "def button_cancel_reconciliation(self)"
},
{
"docstring": "Si el move line de contrapartida es un cheque entregado, entonces registramos el debito desde el extracto ... | 2 | stack_v2_sparse_classes_30k_val_000202 | Implement the Python class `AccountBankStatementLine` described below.
Class description:
Implement the AccountBankStatementLine class.
Method signatures and docstrings:
- def button_cancel_reconciliation(self): Delete operation of checks that are debited from statement
- def process_reconciliation(self, counterpart_... | Implement the Python class `AccountBankStatementLine` described below.
Class description:
Implement the AccountBankStatementLine class.
Method signatures and docstrings:
- def button_cancel_reconciliation(self): Delete operation of checks that are debited from statement
- def process_reconciliation(self, counterpart_... | c04e2b9730db07848c153d8245d2df65ec4e2c8f | <|skeleton|>
class AccountBankStatementLine:
def button_cancel_reconciliation(self):
"""Delete operation of checks that are debited from statement"""
<|body_0|>
def process_reconciliation(self, counterpart_aml_dicts=None, payment_aml_rec=None, new_aml_dicts=None):
"""Si el move line de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccountBankStatementLine:
def button_cancel_reconciliation(self):
"""Delete operation of checks that are debited from statement"""
for st_line in self.filtered('move_name'):
if st_line.journal_entry_ids.filtered(lambda x: x.payment_id.payment_reference == st_line.move_name):
... | the_stack_v2_python_sparse | account_check/models/account_bank_statement_line.py | aaltinisik/customaddons | train | 15 | |
ec77e5f2083daba0c58efe8a6e8f2644aeabb214 | [
"super().__init__(name)\nself.__name__ = name\nself.gen = gen",
"rval = []\nfor tup, param in zip(tups, params):\n if not isinstance(tup, AbstractTuple):\n raise MyiaTypeError(f'Expected AbstractTuple, not {tup}')\n rval.append([g.apply(P.tuple_getitem, param, i) for i, elem in enumerate(tup.elements... | <|body_start_0|>
super().__init__(name)
self.__name__ = name
self.gen = gen
<|end_body_0|>
<|body_start_1|>
rval = []
for tup, param in zip(tups, params):
if not isinstance(tup, AbstractTuple):
raise MyiaTypeError(f'Expected AbstractTuple, not {tup}')... | Parametrizable MetaGraph to combine or extract tuples. | TupleReorganizer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
<|body_0|>
def map_tuples(self, g, params, tups):
"""Map each element of each tuple to a getitem on the parameter.""... | stack_v2_sparse_classes_75kplus_train_001270 | 2,705 | permissive | [
{
"docstring": "Initialize a TupleReorganizer.",
"name": "__init__",
"signature": "def __init__(self, name, gen)"
},
{
"docstring": "Map each element of each tuple to a getitem on the parameter.",
"name": "map_tuples",
"signature": "def map_tuples(self, g, params, tups)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_037115 | Implement the Python class `TupleReorganizer` described below.
Class description:
Parametrizable MetaGraph to combine or extract tuples.
Method signatures and docstrings:
- def __init__(self, name, gen): Initialize a TupleReorganizer.
- def map_tuples(self, g, params, tups): Map each element of each tuple to a getite... | Implement the Python class `TupleReorganizer` described below.
Class description:
Parametrizable MetaGraph to combine or extract tuples.
Method signatures and docstrings:
- def __init__(self, name, gen): Initialize a TupleReorganizer.
- def map_tuples(self, g, params, tups): Map each element of each tuple to a getite... | d7b12c15453079e1a2c4fdae611c5f741574363d | <|skeleton|>
class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
<|body_0|>
def map_tuples(self, g, params, tups):
"""Map each element of each tuple to a getitem on the parameter.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TupleReorganizer:
"""Parametrizable MetaGraph to combine or extract tuples."""
def __init__(self, name, gen):
"""Initialize a TupleReorganizer."""
super().__init__(name)
self.__name__ = name
self.gen = gen
def map_tuples(self, g, params, tups):
"""Map each ele... | the_stack_v2_python_sparse | myia/operations/ops_tuple.py | breuleux/myia | train | 1 |
c581754286e5329a33b15c42b59075d3b5d56812 | [
"self.score_components = constants.score_components\nself.score_type = constants.score_type\nself.qsar_models = constants.qsar_models\nself.device = constants.device\nself.max_n_nodes = constants.max_n_nodes\nself.score_thresholds = constants.score_thresholds\nself.n_graphs = None\nassert len(self.score_components)... | <|body_start_0|>
self.score_components = constants.score_components
self.score_type = constants.score_type
self.qsar_models = constants.qsar_models
self.device = constants.device
self.max_n_nodes = constants.max_n_nodes
self.score_thresholds = constants.score_thresholds
... | A class for defining the scoring function components. | ScoringFunction | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScoringFunction:
"""A class for defining the scoring function components."""
def __init__(self, constants: namedtuple) -> None:
"""Args: ---- constants (namedtuple) : Contains job parameters as well as global constants."""
<|body_0|>
def compute_score(self, graphs: list,... | stack_v2_sparse_classes_75kplus_train_001271 | 7,314 | permissive | [
{
"docstring": "Args: ---- constants (namedtuple) : Contains job parameters as well as global constants.",
"name": "__init__",
"signature": "def __init__(self, constants: namedtuple) -> None"
},
{
"docstring": "Computes the overall score for the input molecular graphs. Args: ---- graphs (list) :... | 4 | stack_v2_sparse_classes_30k_train_019456 | Implement the Python class `ScoringFunction` described below.
Class description:
A class for defining the scoring function components.
Method signatures and docstrings:
- def __init__(self, constants: namedtuple) -> None: Args: ---- constants (namedtuple) : Contains job parameters as well as global constants.
- def c... | Implement the Python class `ScoringFunction` described below.
Class description:
A class for defining the scoring function components.
Method signatures and docstrings:
- def __init__(self, constants: namedtuple) -> None: Args: ---- constants (namedtuple) : Contains job parameters as well as global constants.
- def c... | bdd69ffd11816f8781be9fc8f807750375f61809 | <|skeleton|>
class ScoringFunction:
"""A class for defining the scoring function components."""
def __init__(self, constants: namedtuple) -> None:
"""Args: ---- constants (namedtuple) : Contains job parameters as well as global constants."""
<|body_0|>
def compute_score(self, graphs: list,... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ScoringFunction:
"""A class for defining the scoring function components."""
def __init__(self, constants: namedtuple) -> None:
"""Args: ---- constants (namedtuple) : Contains job parameters as well as global constants."""
self.score_components = constants.score_components
self.sc... | the_stack_v2_python_sparse | graphinvent/ScoringFunction.py | JennyW5/GraphINVENT | train | 0 |
f6aea1c581943b394045c9e2bc41bee7adce264d | [
"self.url = '/openydt/api/v2/mockInOut'\ndata = {'carCard': '', 'carNo': carNum, 'mockType': mockType, 'operateTime': '2017-09-11 14:04:04', 'operator': 'operator', 'parkCode': parkCode}\ntime.sleep(5)\nre = self.post(self.openYDT_api, json=data, headers=json_headers)\nreturn re.json()",
"self.url = '/openydt/api... | <|body_start_0|>
self.url = '/openydt/api/v2/mockInOut'
data = {'carCard': '', 'carNo': carNum, 'mockType': mockType, 'operateTime': '2017-09-11 14:04:04', 'operator': 'operator', 'parkCode': parkCode}
time.sleep(5)
re = self.post(self.openYDT_api, json=data, headers=json_headers)
... | vems车场业务 | OpenYDTReq | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OpenYDTReq:
"""vems车场业务"""
def carInOut(self, parkCode, carNum, mockType):
"""开放平台模拟vems车进出"""
<|body_0|>
def getParkFee(self, parkCode, carNum):
"""查费"""
<|body_1|>
def payParkFee(self, parkCode, carNum):
"""缴费"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus_train_001272 | 2,933 | no_license | [
{
"docstring": "开放平台模拟vems车进出",
"name": "carInOut",
"signature": "def carInOut(self, parkCode, carNum, mockType)"
},
{
"docstring": "查费",
"name": "getParkFee",
"signature": "def getParkFee(self, parkCode, carNum)"
},
{
"docstring": "缴费",
"name": "payParkFee",
"signature":... | 5 | stack_v2_sparse_classes_30k_val_001711 | Implement the Python class `OpenYDTReq` described below.
Class description:
vems车场业务
Method signatures and docstrings:
- def carInOut(self, parkCode, carNum, mockType): 开放平台模拟vems车进出
- def getParkFee(self, parkCode, carNum): 查费
- def payParkFee(self, parkCode, carNum): 缴费
- def getVipType(self, parkCode, customVipNam... | Implement the Python class `OpenYDTReq` described below.
Class description:
vems车场业务
Method signatures and docstrings:
- def carInOut(self, parkCode, carNum, mockType): 开放平台模拟vems车进出
- def getParkFee(self, parkCode, carNum): 查费
- def payParkFee(self, parkCode, carNum): 缴费
- def getVipType(self, parkCode, customVipNam... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class OpenYDTReq:
"""vems车场业务"""
def carInOut(self, parkCode, carNum, mockType):
"""开放平台模拟vems车进出"""
<|body_0|>
def getParkFee(self, parkCode, carNum):
"""查费"""
<|body_1|>
def payParkFee(self, parkCode, carNum):
"""缴费"""
<|body_2|>
def... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class OpenYDTReq:
"""vems车场业务"""
def carInOut(self, parkCode, carNum, mockType):
"""开放平台模拟vems车进出"""
self.url = '/openydt/api/v2/mockInOut'
data = {'carCard': '', 'carNo': carNum, 'mockType': mockType, 'operateTime': '2017-09-11 14:04:04', 'operator': 'operator', 'parkCode': parkCode}
... | the_stack_v2_python_sparse | Api/offLineParking_service/openYDTReq.py | oyebino/pomp_api | train | 1 |
d3d35901fb23c2df7e5063d4e20d118d8065757a | [
"super().__init__(**kwargs)\nif fig_args is None:\n self.fig_args = {}\nelse:\n self.fig_args = fig_args",
"params = self.fig_args.copy()\nif fig_args is not None:\n params.update(**fig_args)\nreturn figure.savefig(filename.path, **params)"
] | <|body_start_0|>
super().__init__(**kwargs)
if fig_args is None:
self.fig_args = {}
else:
self.fig_args = fig_args
<|end_body_0|>
<|body_start_1|>
params = self.fig_args.copy()
if fig_args is not None:
params.update(**fig_args)
return ... | File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a simple plot dataset as output. | Plotter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plotter:
"""File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a simple plot dataset as output."""
... | stack_v2_sparse_classes_75kplus_train_001273 | 30,719 | permissive | [
{
"docstring": "Initializes a Plotter file handler class. Args: fig_args: A dictionary of additional keyword arguments for the fig.savefig method.",
"name": "__init__",
"signature": "def __init__(self, fig_args=None, **kwargs)"
},
{
"docstring": "Saves a matplotlib.figure object to a file. Args:... | 2 | stack_v2_sparse_classes_30k_train_017021 | Implement the Python class `Plotter` described below.
Class description:
File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a ... | Implement the Python class `Plotter` described below.
Class description:
File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a ... | 2a353f5adff0ff9470dffaded4e4d367e85340d2 | <|skeleton|>
class Plotter:
"""File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a simple plot dataset as output."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plotter:
"""File handler that can save matplotlib.figure objects to a file. This is a specialised file handler object that can just store matplotlib.figure objects. It cannot read from a file nor get the time coverage from one. This is designed for having a simple plot dataset as output."""
def __init__(... | the_stack_v2_python_sparse | typhon/files/handlers/common.py | simonpf/typhon | train | 1 |
61520da6366e8c7600166590be71283fad1df059 | [
"super(LatticeSolver, self).__init__(dim, nbins=nbins)\nfrom mystic.termination import NormalizedChangeOverGeneration\nconvergence_tol = 0.0001\nself._termination = NormalizedChangeOverGeneration(convergence_tol)",
"nbins = self._nbins or self._npts\nif isinstance(nbins, int):\n from mystic.math.grid import ra... | <|body_start_0|>
super(LatticeSolver, self).__init__(dim, nbins=nbins)
from mystic.termination import NormalizedChangeOverGeneration
convergence_tol = 0.0001
self._termination = NormalizedChangeOverGeneration(convergence_tol)
<|end_body_0|>
<|body_start_1|>
nbins = self._nbins o... | parallel mapped optimization starting from the centers of N grid points | LatticeSolver | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LatticeSolver:
"""parallel mapped optimization starting from the centers of N grid points"""
def __init__(self, dim, nbins=8):
"""Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins in each dimension All important class members are inherite... | stack_v2_sparse_classes_75kplus_train_001274 | 23,877 | permissive | [
{
"docstring": "Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins in each dimension All important class members are inherited from AbstractEnsembleSolver.",
"name": "__init__",
"signature": "def __init__(self, dim, nbins=8)"
},
{
"docstring": "Genera... | 2 | stack_v2_sparse_classes_30k_train_042614 | Implement the Python class `LatticeSolver` described below.
Class description:
parallel mapped optimization starting from the centers of N grid points
Method signatures and docstrings:
- def __init__(self, dim, nbins=8): Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins i... | Implement the Python class `LatticeSolver` described below.
Class description:
parallel mapped optimization starting from the centers of N grid points
Method signatures and docstrings:
- def __init__(self, dim, nbins=8): Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins i... | d8ecdc54fe422737e39cfc65b310b0fdebbd59ec | <|skeleton|>
class LatticeSolver:
"""parallel mapped optimization starting from the centers of N grid points"""
def __init__(self, dim, nbins=8):
"""Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins in each dimension All important class members are inherite... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LatticeSolver:
"""parallel mapped optimization starting from the centers of N grid points"""
def __init__(self, dim, nbins=8):
"""Takes two initial inputs: dim -- dimensionality of the problem nbins -- tuple of number of bins in each dimension All important class members are inherited from Abstra... | the_stack_v2_python_sparse | mystic/ensemble.py | jamesbrownlow/mystic | train | 0 |
09708350bf3d70b4c8c284e8cb9f8ec62cbe963e | [
"if len(nums) < 3:\n return 0\nfirstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))\nfirstSmallest, secondSmallest = (float('-inf'), float('-inf'))\nC = Counter(nums)\nfirstBiggest = max(C)\nC[firstBiggest] -= 1\nif not C[firstBiggest]:\n del C[firstBiggest]\nsecondBiggest... | <|body_start_0|>
if len(nums) < 3:
return 0
firstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))
firstSmallest, secondSmallest = (float('-inf'), float('-inf'))
C = Counter(nums)
firstBiggest = max(C)
C[firstBiggest] -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumProductFirstSolution(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(nums) < 3:
... | stack_v2_sparse_classes_75kplus_train_001275 | 1,631 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumProduct",
"signature": "def maximumProduct(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumProductFirstSolution",
"signature": "def maximumProductFirstSolution(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015604 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums): :type nums: List[int] :rtype: int
- def maximumProductFirstSolution(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maximumProduct(self, nums): :type nums: List[int] :rtype: int
- def maximumProductFirstSolution(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 25e5caf324e25edfdf0a7a3be1e572f5d4c88837 | <|skeleton|>
class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def maximumProductFirstSolution(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maximumProduct(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) < 3:
return 0
firstBiggest, secondBiggest, thirdBiggest = (float('-inf'), float('-inf'), float('-inf'))
firstSmallest, secondSmallest = (float('-inf'), float('-inf'))
... | the_stack_v2_python_sparse | Arrays/maximum_product_of_three_numbers.py | msraju2009/CodingProblemsPractice | train | 0 | |
504965ca16c711d8ffdf189e653d12c7e6dccfab | [
"self.type = 'OPTIM'\nself.date = ''\nself.modules = []\nself.minmax = 'min'\nself.objective = ['cl']\nself.driver = 'COBYLA'\nself.save_iter = 1\nself.max_iter = 200\nself.tol = 0.001\nself.doedriver = 'Uniform'\nself.samplesnb = 3\nself.doe_file = ''\nself.user_config = Path(MODULE_DIR, 'files', 'Default_config.c... | <|body_start_0|>
self.type = 'OPTIM'
self.date = ''
self.modules = []
self.minmax = 'min'
self.objective = ['cl']
self.driver = 'COBYLA'
self.save_iter = 1
self.max_iter = 200
self.tol = 0.001
self.doedriver = 'Uniform'
self.samples... | Setup the routine to launch in Openmdao. | Routine | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Routine:
"""Setup the routine to launch in Openmdao."""
def __init__(self):
"""Define default main parameters."""
<|body_0|>
def get_user_inputs(self, tixi):
"""Take user inputs from the GUI."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.... | stack_v2_sparse_classes_75kplus_train_001276 | 16,742 | permissive | [
{
"docstring": "Define default main parameters.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Take user inputs from the GUI.",
"name": "get_user_inputs",
"signature": "def get_user_inputs(self, tixi)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009055 | Implement the Python class `Routine` described below.
Class description:
Setup the routine to launch in Openmdao.
Method signatures and docstrings:
- def __init__(self): Define default main parameters.
- def get_user_inputs(self, tixi): Take user inputs from the GUI. | Implement the Python class `Routine` described below.
Class description:
Setup the routine to launch in Openmdao.
Method signatures and docstrings:
- def __init__(self): Define default main parameters.
- def get_user_inputs(self, tixi): Take user inputs from the GUI.
<|skeleton|>
class Routine:
"""Setup the rout... | 30ca55b39dc14e3f8ec1e00a475f76024d1b5fef | <|skeleton|>
class Routine:
"""Setup the routine to launch in Openmdao."""
def __init__(self):
"""Define default main parameters."""
<|body_0|>
def get_user_inputs(self, tixi):
"""Take user inputs from the GUI."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Routine:
"""Setup the routine to launch in Openmdao."""
def __init__(self):
"""Define default main parameters."""
self.type = 'OPTIM'
self.date = ''
self.modules = []
self.minmax = 'min'
self.objective = ['cl']
self.driver = 'COBYLA'
self.sa... | the_stack_v2_python_sparse | ceasiompy/Optimisation/func/optimfunctions.py | cfsengineering/CEASIOMpy | train | 60 |
3f773d82bf47dac9ab99bae68035a060837accc1 | [
"changes = 0\ntable_differences = TableDiff(table1.get_name())\ntable_differences.from_table = table1\ntable1_columns = table1.get_columns()\ntable2_columns = table2.get_columns()\nfor column_name, column in table2_columns.items():\n if not table1.has_column(column_name):\n table_differences.added_columns... | <|body_start_0|>
changes = 0
table_differences = TableDiff(table1.get_name())
table_differences.from_table = table1
table1_columns = table1.get_columns()
table2_columns = table2.get_columns()
for column_name, column in table2_columns.items():
if not table1.has... | Compares two Schemas and return an instance of SchemaDiff. | Comparator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Comparator:
"""Compares two Schemas and return an instance of SchemaDiff."""
def diff_table(self, table1, table2):
"""Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff"""
<|body_0|>
def detect_column_re... | stack_v2_sparse_classes_75kplus_train_001277 | 7,301 | permissive | [
{
"docstring": "Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff",
"name": "diff_table",
"signature": "def diff_table(self, table1, table2)"
},
{
"docstring": "Try to find columns that only changed their names. :type table_dif... | 3 | stack_v2_sparse_classes_30k_train_036898 | Implement the Python class `Comparator` described below.
Class description:
Compares two Schemas and return an instance of SchemaDiff.
Method signatures and docstrings:
- def diff_table(self, table1, table2): Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: ... | Implement the Python class `Comparator` described below.
Class description:
Compares two Schemas and return an instance of SchemaDiff.
Method signatures and docstrings:
- def diff_table(self, table1, table2): Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: ... | fa4c428c063f1828b8035a76115752ea0c7c2bb0 | <|skeleton|>
class Comparator:
"""Compares two Schemas and return an instance of SchemaDiff."""
def diff_table(self, table1, table2):
"""Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff"""
<|body_0|>
def detect_column_re... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Comparator:
"""Compares two Schemas and return an instance of SchemaDiff."""
def diff_table(self, table1, table2):
"""Returns the difference between the tables table1 and table2. :type table1: Table :type table2: Table :rtype: TableDiff"""
changes = 0
table_differences = TableDiff... | the_stack_v2_python_sparse | orator/dbal/comparator.py | MakarenaLabs/Orator-Google-App-Engine | train | 2 |
ea64585ad2159e3910c01d657ab4f8dee1850a47 | [
"super().__init__(name)\nif match is None:\n match = lambda _: True\nif loader is None:\n loader = DefaultPackageRepositoryLoader()\nself.match = match\nself.loader = loader",
"if (path := pathfromlocation(location)):\n if path.exists() and self.match(path):\n return self.loader.load(location.name... | <|body_start_0|>
super().__init__(name)
if match is None:
match = lambda _: True
if loader is None:
loader = DefaultPackageRepositoryLoader()
self.match = match
self.loader = loader
<|end_body_0|>
<|body_start_1|>
if (path := pathfromlocation(loca... | Provide a package from the local filesystem. | LocalProvider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LocalProvider:
"""Provide a package from the local filesystem."""
def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None:
"""Initialize."""
<|body_0|>
def provide(self, location: Location) ->... | stack_v2_sparse_classes_75kplus_train_001278 | 4,520 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None"
},
{
"docstring": "Retrieve the package repository at the given location.",
"name": "provide... | 2 | stack_v2_sparse_classes_30k_train_028703 | Implement the Python class `LocalProvider` described below.
Class description:
Provide a package from the local filesystem.
Method signatures and docstrings:
- def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None: Initialize.
- def prov... | Implement the Python class `LocalProvider` described below.
Class description:
Provide a package from the local filesystem.
Method signatures and docstrings:
- def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None: Initialize.
- def prov... | c6b26377153d60d5da825002e03f9a28467378a9 | <|skeleton|>
class LocalProvider:
"""Provide a package from the local filesystem."""
def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None:
"""Initialize."""
<|body_0|>
def provide(self, location: Location) ->... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LocalProvider:
"""Provide a package from the local filesystem."""
def __init__(self, name: str='local', /, *, match: Optional[PathMatcher]=None, loader: Optional[PackageRepositoryLoader]=None) -> None:
"""Initialize."""
super().__init__(name)
if match is None:
match = ... | the_stack_v2_python_sparse | src/cutty/packages/domain/providers.py | cjolowicz/cutty | train | 4 |
0be809ecf80680d51e016d5060c4fb8066e9640e | [
"action = payload['action']\ngithub_team = payload['team']\ngithub_id = str(github_team['id'])\ngithub_team_name = github_team['name']\nlogging.info(f'Github Team webhook triggered with{{action: {action}, team: {github_team_name}, team_id: {github_id}}}')\nif action == 'created':\n return self.team_created(githu... | <|body_start_0|>
action = payload['action']
github_team = payload['team']
github_id = str(github_team['id'])
github_team_name = github_team['name']
logging.info(f'Github Team webhook triggered with{{action: {action}, team: {github_team_name}, team_id: {github_id}}}')
if a... | Encapsulate the handler methods for GitHub team events. | TeamEventHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeamEventHandler:
"""Encapsulate the handler methods for GitHub team events."""
def handle(self, payload: Dict[str, Any]) -> ResponseTuple:
"""Handle team events of the organization. This event is fired when a team is created, deleted, edited, or added or removed from a repository. I... | stack_v2_sparse_classes_75kplus_train_001279 | 6,541 | permissive | [
{
"docstring": "Handle team events of the organization. This event is fired when a team is created, deleted, edited, or added or removed from a repository. If a team is created, add or overwrite a team in rocket's db. If a team is deleted, delete the team from rocket's db if it exists. If a team is edited, over... | 6 | null | Implement the Python class `TeamEventHandler` described below.
Class description:
Encapsulate the handler methods for GitHub team events.
Method signatures and docstrings:
- def handle(self, payload: Dict[str, Any]) -> ResponseTuple: Handle team events of the organization. This event is fired when a team is created, ... | Implement the Python class `TeamEventHandler` described below.
Class description:
Encapsulate the handler methods for GitHub team events.
Method signatures and docstrings:
- def handle(self, payload: Dict[str, Any]) -> ResponseTuple: Handle team events of the organization. This event is fired when a team is created, ... | 7a4f05f46229d1c9a900aac1694b3d822f9d6b0f | <|skeleton|>
class TeamEventHandler:
"""Encapsulate the handler methods for GitHub team events."""
def handle(self, payload: Dict[str, Any]) -> ResponseTuple:
"""Handle team events of the organization. This event is fired when a team is created, deleted, edited, or added or removed from a repository. I... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TeamEventHandler:
"""Encapsulate the handler methods for GitHub team events."""
def handle(self, payload: Dict[str, Any]) -> ResponseTuple:
"""Handle team events of the organization. This event is fired when a team is created, deleted, edited, or added or removed from a repository. If a team is c... | the_stack_v2_python_sparse | app/controller/webhook/github/events/team.py | ubclaunchpad/rocket2 | train | 14 |
187cf368012ff420f590bdf8cc962e00711a4181 | [
"def getPrefix(pattern):\n prefix = [-1] * len(pattern)\n j = -1\n for i in range(1, len(pattern)):\n while j > -1 and pattern[j + 1] != pattern[i]:\n j = prefix[j]\n if pattern[j + 1] == pattern[i]:\n j += 1\n prefix[i] = j\n return prefix\nprefix = getPrefix(... | <|body_start_0|>
def getPrefix(pattern):
prefix = [-1] * len(pattern)
j = -1
for i in range(1, len(pattern)):
while j > -1 and pattern[j + 1] != pattern[i]:
j = prefix[j]
if pattern[j + 1] == pattern[i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, str):
""":type str: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern2(self, str):
""":type str: str :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def getPrefix(pattern):
... | stack_v2_sparse_classes_75kplus_train_001280 | 6,161 | no_license | [
{
"docstring": ":type str: str :rtype: bool",
"name": "repeatedSubstringPattern",
"signature": "def repeatedSubstringPattern(self, str)"
},
{
"docstring": ":type str: str :rtype: bool",
"name": "repeatedSubstringPattern2",
"signature": "def repeatedSubstringPattern2(self, str)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, str): :type str: str :rtype: bool
- def repeatedSubstringPattern2(self, str): :type str: str :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def repeatedSubstringPattern(self, str): :type str: str :rtype: bool
- def repeatedSubstringPattern2(self, str): :type str: str :rtype: bool
<|skeleton|>
class Solution:
de... | 035ef08434fa1ca781a6fb2f9eed3538b7d20c02 | <|skeleton|>
class Solution:
def repeatedSubstringPattern(self, str):
""":type str: str :rtype: bool"""
<|body_0|>
def repeatedSubstringPattern2(self, str):
""":type str: str :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def repeatedSubstringPattern(self, str):
""":type str: str :rtype: bool"""
def getPrefix(pattern):
prefix = [-1] * len(pattern)
j = -1
for i in range(1, len(pattern)):
while j > -1 and pattern[j + 1] != pattern[i]:
... | the_stack_v2_python_sparse | leetcode_python/String/repeated-substring-pattern.py | yennanliu/CS_basics | train | 64 | |
14bfba0cf7210bfd08a7ff3bf4b681adfd7995cc | [
"super(Contract, self).__init__()\nself.m_conId = 0\nself.m_strike = 0\nself.m_includeExpired = False",
"retval = super(Contract, self).clone()\nretval.m_comboLegs = self.m_comboLegs[:]\nreturn retval",
"super(Contract, self).__init__()\nself.m_conId = p_conId\nself.m_symbol = p_symbol\nself.m_secType = p_secTy... | <|body_start_0|>
super(Contract, self).__init__()
self.m_conId = 0
self.m_strike = 0
self.m_includeExpired = False
<|end_body_0|>
<|body_start_1|>
retval = super(Contract, self).clone()
retval.m_comboLegs = self.m_comboLegs[:]
return retval
<|end_body_1|>
<|body... | generated source for class Contract | Contract | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Contract:
"""generated source for class Contract"""
def __init__(self):
"""generated source for method __init__"""
<|body_0|>
def clone(self):
"""generated source for method clone"""
<|body_1|>
def __init___0(self, p_conId, p_symbol, p_secType, p_exp... | stack_v2_sparse_classes_75kplus_train_001281 | 4,457 | permissive | [
{
"docstring": "generated source for method __init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "generated source for method clone",
"name": "clone",
"signature": "def clone(self)"
},
{
"docstring": "generated source for method __init___0",
"nam... | 4 | stack_v2_sparse_classes_30k_train_041398 | Implement the Python class `Contract` described below.
Class description:
generated source for class Contract
Method signatures and docstrings:
- def __init__(self): generated source for method __init__
- def clone(self): generated source for method clone
- def __init___0(self, p_conId, p_symbol, p_secType, p_expiry,... | Implement the Python class `Contract` described below.
Class description:
generated source for class Contract
Method signatures and docstrings:
- def __init__(self): generated source for method __init__
- def clone(self): generated source for method clone
- def __init___0(self, p_conId, p_symbol, p_secType, p_expiry,... | f88df69d1332e8cc4d2fd2b2c6c07cc2c54dd737 | <|skeleton|>
class Contract:
"""generated source for class Contract"""
def __init__(self):
"""generated source for method __init__"""
<|body_0|>
def clone(self):
"""generated source for method clone"""
<|body_1|>
def __init___0(self, p_conId, p_symbol, p_secType, p_exp... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Contract:
"""generated source for class Contract"""
def __init__(self):
"""generated source for method __init__"""
super(Contract, self).__init__()
self.m_conId = 0
self.m_strike = 0
self.m_includeExpired = False
def clone(self):
"""generated source fo... | the_stack_v2_python_sparse | app/ib/ext/Contract.py | hamx0r/ibrest | train | 31 |
4c41a731f61fa6f09fa34cf7416e1ea900ce6ad6 | [
"_query_builder = Configuration.base_uri.format(Configuration.host)\n_query_builder += '/medicines/generics/{generic_id}'\n_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'generic_id': generic_id})\n_query_url = APIHelper.clean_url(_query_builder)\n_headers = {'accept': 'application/... | <|body_start_0|>
_query_builder = Configuration.base_uri.format(Configuration.host)
_query_builder += '/medicines/generics/{generic_id}'
_query_builder = APIHelper.append_url_with_template_parameters(_query_builder, {'generic_id': generic_id})
_query_url = APIHelper.clean_url(_query_buil... | A Controller to access Endpoints in the healthoslib API. | GenericsController | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenericsController:
"""A Controller to access Endpoints in the healthoslib API."""
def get_generic(self, generic_id):
"""Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TODO: type description here. Example: Returns: mixed: Respon... | stack_v2_sparse_classes_75kplus_train_001282 | 6,667 | permissive | [
{
"docstring": "Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TODO: type description here. Example: Returns: mixed: Response from the API. Raises: APIException: When an error occurs while fetching the data from the remote API. This exception includes the ... | 4 | stack_v2_sparse_classes_30k_train_018038 | Implement the Python class `GenericsController` described below.
Class description:
A Controller to access Endpoints in the healthoslib API.
Method signatures and docstrings:
- def get_generic(self, generic_id): Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TOD... | Implement the Python class `GenericsController` described below.
Class description:
A Controller to access Endpoints in the healthoslib API.
Method signatures and docstrings:
- def get_generic(self, generic_id): Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TOD... | 641b165344063affd50de27b8931cd851fee0d6f | <|skeleton|>
class GenericsController:
"""A Controller to access Endpoints in the healthoslib API."""
def get_generic(self, generic_id):
"""Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TODO: type description here. Example: Returns: mixed: Respon... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GenericsController:
"""A Controller to access Endpoints in the healthoslib API."""
def get_generic(self, generic_id):
"""Does a GET request to /medicines/generics/{generic_id}. Get a generic by id Args: generic_id (string): TODO: type description here. Example: Returns: mixed: Response from the A... | the_stack_v2_python_sparse | healthoslib/controllers/generics_controller.py | priyamsahoo/Day-Zero-Diagnostics | train | 2 |
9abe9eecfb320f6d312aaaca915ccbd59a96ba47 | [
"try:\n if self.pool != self.pool.check_signaling():\n self.env.reset()\n self = self.env()[self._name]\n log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1\n odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (self._cr.dbname, self._uid, '*', cron_name, server_action_... | <|body_start_0|>
try:
if self.pool != self.pool.check_signaling():
self.env.reset()
self = self.env()[self._name]
log_depth = None if _logger.isEnabledFor(logging.DEBUG) else 1
odoo.netsvc.log(_logger, logging.DEBUG, 'cron.object.execute', (sel... | 扩展添加用户数据 | IrCronExtend | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_75kplus_train_001283 | 4,343 | no_license | [
{
"docstring": "Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method.",
"name": "_callback",
"signature": "def _callback(self, cron_name, server_action_id, job_id, job_data=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_051412 | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | Implement the Python class `IrCronExtend` described below.
Class description:
扩展添加用户数据
Method signatures and docstrings:
- def _callback(self, cron_name, server_action_id, job_id, job_data=None): Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the ... | 13b428a5c4ade6278e3e5e996ef10d9fb0fea4b9 | <|skeleton|>
class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class IrCronExtend:
"""扩展添加用户数据"""
def _callback(self, cron_name, server_action_id, job_id, job_data=None):
"""Run the method associated to a given job. It takes care of logging and exception handling. Note that the user running the server action is the user calling this method."""
try:
... | the_stack_v2_python_sparse | mdias_addons/funenc_theme/models/funenc_extend_cron.py | rezaghanimi/main_mdias | train | 0 |
2ea436f30a73cb05c3e4638b0860ae76553ad758 | [
"super(DispToPix, self).__init__()\nself.batch_size = batch_size\nself.height = height\nself.width = width\nmeshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')\nself.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\nself.id_coords = nn.Parameter(torch.from_numpy(self.id_coords))\ns... | <|body_start_0|>
super(DispToPix, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
meshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')
self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)
self... | Layer to transform disparity into camera pixel coordiantes | DispToPix | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DispToPix:
"""Layer to transform disparity into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, disp, normalized=True):
"""Forward Args: disp (tensor, [Nx1xHxW]): dispari... | stack_v2_sparse_classes_75kplus_train_001284 | 13,421 | permissive | [
{
"docstring": "Prepare regular grid (Nx2xHxW)",
"name": "__init__",
"signature": "def __init__(self, batch_size, height, width)"
},
{
"docstring": "Forward Args: disp (tensor, [Nx1xHxW]): disparity normalized (bool): normalized to [-1, 1] if True; otherwise [0, H-1 or W-1] Returns: pix_coords (... | 2 | stack_v2_sparse_classes_30k_train_053266 | Implement the Python class `DispToPix` described below.
Class description:
Layer to transform disparity into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, disp, normalized=True): Forward Args: disp (tensor... | Implement the Python class `DispToPix` described below.
Class description:
Layer to transform disparity into camera pixel coordiantes
Method signatures and docstrings:
- def __init__(self, batch_size, height, width): Prepare regular grid (Nx2xHxW)
- def forward(self, disp, normalized=True): Forward Args: disp (tensor... | 50e6ffa9b5164a0dfb34d3215e86cc2288df256d | <|skeleton|>
class DispToPix:
"""Layer to transform disparity into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
<|body_0|>
def forward(self, disp, normalized=True):
"""Forward Args: disp (tensor, [Nx1xHxW]): dispari... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DispToPix:
"""Layer to transform disparity into camera pixel coordiantes"""
def __init__(self, batch_size, height, width):
"""Prepare regular grid (Nx2xHxW)"""
super(DispToPix, self).__init__()
self.batch_size = batch_size
self.height = height
self.width = width
... | the_stack_v2_python_sparse | libs/deep_models/depth/monodepth2/layers.py | Huangying-Zhan/DF-VO | train | 494 |
7452b2d7b29e652e8055e3c82cfd06e8b2e29718 | [
"super(SparseAttention, self).__init__()\nself.in_channels = in_channels\nself.softmax_temp = softmax_temp\nself.dropout = attention_dropout",
"_, l, _, e = queries.shape\nsoftmax_temp = self.softmax_temp or 1.0 / math.sqrt(e)\nif isinstance(adj, torch.Tensor):\n qk = torch.sum(queries.index_select(dim=-3, ind... | <|body_start_0|>
super(SparseAttention, self).__init__()
self.in_channels = in_channels
self.softmax_temp = softmax_temp
self.dropout = attention_dropout
<|end_body_0|>
<|body_start_1|>
_, l, _, e = queries.shape
softmax_temp = self.softmax_temp or 1.0 / math.sqrt(e)
... | Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4 | SparseAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SparseAttention:
"""Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4"""
def __init__(self, in_channels, softmax_temp=None, attention_dropout=0.1):
""":param heads (int): :param in_channels (int)... | stack_v2_sparse_classes_75kplus_train_001285 | 14,355 | no_license | [
{
"docstring": ":param heads (int): :param in_channels (int): :param softmax_temp (torch.Tensor): The temperature to use for the softmax attention. (default: 1/sqrt(d_keys) where d_keys is computed at runtime) :param attention_dropout (float): The dropout rate to apply to the attention (default: 0.1)",
"nam... | 2 | stack_v2_sparse_classes_30k_train_031636 | Implement the Python class `SparseAttention` described below.
Class description:
Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4
Method signatures and docstrings:
- def __init__(self, in_channels, softmax_temp=None, attention_d... | Implement the Python class `SparseAttention` described below.
Class description:
Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4
Method signatures and docstrings:
- def __init__(self, in_channels, softmax_temp=None, attention_d... | 96a401201040b83c7c21d08e4b0f78a31cb4330b | <|skeleton|>
class SparseAttention:
"""Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4"""
def __init__(self, in_channels, softmax_temp=None, attention_dropout=0.1):
""":param heads (int): :param in_channels (int)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SparseAttention:
"""Implement the sparse scaled dot product attention with softmax. Inspired by: https://tinyurl.com/yxq4ry64 and https://tinyurl.com/yy6l47p4"""
def __init__(self, in_channels, softmax_temp=None, attention_dropout=0.1):
""":param heads (int): :param in_channels (int): :param soft... | the_stack_v2_python_sparse | models/attentions.py | PeanutGeek/STAR | train | 0 |
b34dd614c6b7da0a6a80d608d0b45bca5a481470 | [
"dp = [[0 for _ in range(100)] for _ in range(100)]\ndp[0][0] = poured\ncur = [0, 1]\nrow = 0\nwhile cur[0] < cur[1] and row < 99:\n next_max = -1\n next_min = 100\n print(row, cur[0], cur[1])\n for i in range(cur[0], cur[1]):\n if dp[row][i] > 1:\n next_one = (dp[row][i] - 1) / 2.0\n ... | <|body_start_0|>
dp = [[0 for _ in range(100)] for _ in range(100)]
dp[0][0] = poured
cur = [0, 1]
row = 0
while cur[0] < cur[1] and row < 99:
next_max = -1
next_min = 100
print(row, cur[0], cur[1])
for i in range(cur[0], cur[1]):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
<|body_0|>
def champagneTower_1(self, poured, query_row, query_glass):
""":type poured: int :type query_row: in... | stack_v2_sparse_classes_75kplus_train_001286 | 4,193 | no_license | [
{
"docstring": ":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms",
"name": "champagneTower",
"signature": "def champagneTower(self, poured, query_row, query_glass)"
},
{
"docstring": ":type poured: int :type query_row: int :type query_glass: int :rtype: float 125... | 3 | stack_v2_sparse_classes_30k_train_002203 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured, query_row, query_glass): :type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms
- def champagneTower_1(self, poured, q... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def champagneTower(self, poured, query_row, query_glass): :type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms
- def champagneTower_1(self, poured, q... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
<|body_0|>
def champagneTower_1(self, poured, query_row, query_glass):
""":type poured: int :type query_row: in... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def champagneTower(self, poured, query_row, query_glass):
""":type poured: int :type query_row: int :type query_glass: int :rtype: float 392ms"""
dp = [[0 for _ in range(100)] for _ in range(100)]
dp[0][0] = poured
cur = [0, 1]
row = 0
while cur[0] < c... | the_stack_v2_python_sparse | ChampagneTower_MID_799.py | 953250587/leetcode-python | train | 2 | |
7de23b2baccf5e1f72ac1eb281f8ddd37e00a085 | [
"self.info('Starting tckgen creation from mrtrix on {}'.format(source))\ntmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))\ncmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi, self.get('number_tracks'), algor... | <|body_start_0|>
self.info('Starting tckgen creation from mrtrix on {}'.format(source))
tmp = os.path.join(self.workingDir, 'tmp_{}.tck'.format(algorithm))
cmd = 'tckgen {} {} -mask {} -act {} -seed_gmwmi {} -number {} -algorithm {} -nthreads {} -quiet'.format(source, tmp, mask, act, seed_gmwmi... | Tractography | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_75kplus_train_001287 | 3,574 | no_license | [
{
"docstring": "perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,Y,Z direction of a fibre population). - iFOD1/2 & SD_Stream: the SH image resulting from CSD. - Nulldist & SeedTes... | 3 | stack_v2_sparse_classes_30k_train_050690 | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | Implement the Python class `Tractography` described below.
Class description:
Implement the Tractography class.
Method signatures and docstrings:
- def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'): perform streamlines tractography. the image containing the source d... | 99682e1a03d56bac0e078bc816d0394fe1147a1a | <|skeleton|>
class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of vol... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Tractography:
def tckgen(self, source, target, mask=None, act=None, seed_gmwmi=None, bFile=None, algorithm='iFOD2'):
"""perform streamlines tractography. the image containing the source data. The type of data depends on the algorithm used: - FACT: the directions file (each triplet of volumes is the X,... | the_stack_v2_python_sparse | lib/tractography.py | alexhng/toad | train | 0 | |
e66da78d0fc723a0a41e0584f8444287d550848c | [
"try:\n logging.info('CRUDDataMonitoring create function')\n project = DataMonitoring(**kwargs)\n with session() as transaction_session:\n transaction_session.add(project)\n transaction_session.commit()\n transaction_session.refresh(project)\nexcept Exception as error:\n logging.err... | <|body_start_0|>
try:
logging.info('CRUDDataMonitoring create function')
project = DataMonitoring(**kwargs)
with session() as transaction_session:
transaction_session.add(project)
transaction_session.commit()
transaction_session... | CRUDDataMonitoring | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CRUDDataMonitoring:
def create(self, **kwargs):
"""[CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]"""
<|body_0|>
def delete(self, model_uri: str):
"""[CRUD function to Delete all Data Monitoring records for a M... | stack_v2_sparse_classes_75kplus_train_001288 | 3,658 | permissive | [
{
"docstring": "[CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]",
"name": "create",
"signature": "def create(self, **kwargs)"
},
{
"docstring": "[CRUD function to Delete all Data Monitoring records for a Model URI] Args: model_uri (str): [... | 4 | stack_v2_sparse_classes_30k_train_026216 | Implement the Python class `CRUDDataMonitoring` described below.
Class description:
Implement the CRUDDataMonitoring class.
Method signatures and docstrings:
- def create(self, **kwargs): [CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]
- def delete(self, model_... | Implement the Python class `CRUDDataMonitoring` described below.
Class description:
Implement the CRUDDataMonitoring class.
Method signatures and docstrings:
- def create(self, **kwargs): [CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]
- def delete(self, model_... | c71b1324ed270caa3724c0a8c58c4883b28dc19c | <|skeleton|>
class CRUDDataMonitoring:
def create(self, **kwargs):
"""[CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]"""
<|body_0|>
def delete(self, model_uri: str):
"""[CRUD function to Delete all Data Monitoring records for a M... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CRUDDataMonitoring:
def create(self, **kwargs):
"""[CRUD function to create a new Data Monitoring record] Raises: error: [Error returned from the DB layer]"""
try:
logging.info('CRUDDataMonitoring create function')
project = DataMonitoring(**kwargs)
with ses... | the_stack_v2_python_sparse | datahub/sql/crud/data_monitoring_crud.py | Chronicles-of-AI/osAIris | train | 4 | |
0d4315b7338f31036b199331da54eab9f80955de | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | AgentServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AgentServicer:
"""Missing associated documentation comment in .proto file."""
def Greet(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def CallInstruction(self, request, context):
"""Missing associated documenta... | stack_v2_sparse_classes_75kplus_train_001289 | 16,257 | permissive | [
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "Greet",
"signature": "def Greet(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "CallInstruction",
"signature": "def CallInstruction(self, re... | 2 | null | Implement the Python class `AgentServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Greet(self, request, context): Missing associated documentation comment in .proto file.
- def CallInstruction(self, request, context): Missing... | Implement the Python class `AgentServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Greet(self, request, context): Missing associated documentation comment in .proto file.
- def CallInstruction(self, request, context): Missing... | f1d20b444050ab0f445681ae39e93ffd44610f21 | <|skeleton|>
class AgentServicer:
"""Missing associated documentation comment in .proto file."""
def Greet(self, request, context):
"""Missing associated documentation comment in .proto file."""
<|body_0|>
def CallInstruction(self, request, context):
"""Missing associated documenta... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AgentServicer:
"""Missing associated documentation comment in .proto file."""
def Greet(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
ra... | the_stack_v2_python_sparse | gym/common/protobuf/gym_pb2_grpc.py | raphaelvrosa/gym | train | 4 |
7f7441224efecebccec72ca5d38ac67b72f19296 | [
"self.prefix = prefix\nself.filter_pattern = filter_pattern\nself.delimiter = delimiter\nself.suffix = suffix",
"prefix, wildcard_string = _split_on_wildcard(string)\nfilter_pattern, _, suffix = wildcard_string.partition(delimiter)\nif '**' in filter_pattern:\n delimiter = None\n filter_pattern = wildcard_s... | <|body_start_0|>
self.prefix = prefix
self.filter_pattern = filter_pattern
self.delimiter = delimiter
self.suffix = suffix
<|end_body_0|>
<|body_start_1|>
prefix, wildcard_string = _split_on_wildcard(string)
filter_pattern, _, suffix = wildcard_string.partition(delimiter... | Different parts of the wildcard string used for querying and filtering. | CloudWildcardParts | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CloudWildcardParts:
"""Different parts of the wildcard string used for querying and filtering."""
def __init__(self, prefix, filter_pattern, delimiter, suffix):
"""Initialize the CloudWildcardParts object. Args: prefix (str): The prefix string to be passed to the API request. This is... | stack_v2_sparse_classes_75kplus_train_001290 | 17,012 | permissive | [
{
"docstring": "Initialize the CloudWildcardParts object. Args: prefix (str): The prefix string to be passed to the API request. This is the substring before the first occurrance of the wildcard. filter_pattern (str): The pattern to be used to filter out the results returned by the list_objects call. This is a ... | 2 | stack_v2_sparse_classes_30k_train_001843 | Implement the Python class `CloudWildcardParts` described below.
Class description:
Different parts of the wildcard string used for querying and filtering.
Method signatures and docstrings:
- def __init__(self, prefix, filter_pattern, delimiter, suffix): Initialize the CloudWildcardParts object. Args: prefix (str): T... | Implement the Python class `CloudWildcardParts` described below.
Class description:
Different parts of the wildcard string used for querying and filtering.
Method signatures and docstrings:
- def __init__(self, prefix, filter_pattern, delimiter, suffix): Initialize the CloudWildcardParts object. Args: prefix (str): T... | 060174026ac068b6442b6c58bedf5adc7bc549cb | <|skeleton|>
class CloudWildcardParts:
"""Different parts of the wildcard string used for querying and filtering."""
def __init__(self, prefix, filter_pattern, delimiter, suffix):
"""Initialize the CloudWildcardParts object. Args: prefix (str): The prefix string to be passed to the API request. This is... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CloudWildcardParts:
"""Different parts of the wildcard string used for querying and filtering."""
def __init__(self, prefix, filter_pattern, delimiter, suffix):
"""Initialize the CloudWildcardParts object. Args: prefix (str): The prefix string to be passed to the API request. This is the substrin... | the_stack_v2_python_sparse | google-cloud-sdk/lib/googlecloudsdk/command_lib/storage/wildcard_iterator.py | salewski/google-cloud-sdk | train | 0 |
0fb59e9f70a950e42ca592196075b4e2ab34fdaa | [
"self._bus = bus\nself._address = address\nprint(f'starting with bus {bus} and address {address}')\nsuper(DfRobotWheelEncoderMcp23017, self).__init__(pin, name, max_data_length)",
"self._gpio = self.init_interface('gpio', impl='Mcp23017GPIO', bus=self._bus, address=self._address, signal=self.pin_num)\nself.hardwa... | <|body_start_0|>
self._bus = bus
self._address = address
print(f'starting with bus {bus} and address {address}')
super(DfRobotWheelEncoderMcp23017, self).__init__(pin, name, max_data_length)
<|end_body_0|>
<|body_start_1|>
self._gpio = self.init_interface('gpio', impl='Mcp23017G... | Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal. | DfRobotWheelEncoderMcp23017 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DfRobotWheelEncoderMcp23017:
"""Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal."""
def __init__(self, pin, bus=1, address=32, name='', max_data_length=0):
"""Constructor."... | stack_v2_sparse_classes_75kplus_train_001291 | 6,639 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self, pin, bus=1, address=32, name='', max_data_length=0)"
},
{
"docstring": "Initialize hardware and os resources.",
"name": "start",
"signature": "def start(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_024099 | Implement the Python class `DfRobotWheelEncoderMcp23017` described below.
Class description:
Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal.
Method signatures and docstrings:
- def __init__(self, pin, bus=... | Implement the Python class `DfRobotWheelEncoderMcp23017` described below.
Class description:
Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal.
Method signatures and docstrings:
- def __init__(self, pin, bus=... | 3a420f1c47e1cdcca76361c0a921a678f31e1ec1 | <|skeleton|>
class DfRobotWheelEncoderMcp23017:
"""Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal."""
def __init__(self, pin, bus=1, address=32, name='', max_data_length=0):
"""Constructor."... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DfRobotWheelEncoderMcp23017:
"""Class implementing df robot wheel encoders using mcp23017 gpio extender. Extends :class:`DfRobotWheelEncoder` Args: pin_num: The pin number of encoder's signal."""
def __init__(self, pin, bus=1, address=32, name='', max_data_length=0):
"""Constructor."""
se... | the_stack_v2_python_sparse | pidevices/sensors/df_robot_wheel_encoders.py | robotics-4-all/tektrain-robot-sw | train | 0 |
00210ab1cad2d1492054acc4cf68e8e5d8e1e855 | [
"obj = cls.__new__(cls)\nsuper(DeliveryDictable, obj).__init__()\nsource = camel_to_snake(source)\nfor key, value in source.items():\n if key == 'zip':\n setattr(obj, key, ZipSettings.from_dict(value))\n else:\n setattr(obj, key, value)\nreturn obj",
"for key, value in self.__dict__.items():\n... | <|body_start_0|>
obj = cls.__new__(cls)
super(DeliveryDictable, obj).__init__()
source = camel_to_snake(source)
for key, value in source.items():
if key == 'zip':
setattr(obj, key, ZipSettings.from_dict(value))
else:
setattr(obj, ke... | DeliveryDictable | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeliveryDictable:
def from_dict(cls, source, **kwargs):
"""Initialize Delivery object from dictionary."""
<|body_0|>
def validate(self):
"""Validate whether all obligatory properties of the Delivery object are present and whether all the properties present are of cor... | stack_v2_sparse_classes_75kplus_train_001292 | 20,086 | permissive | [
{
"docstring": "Initialize Delivery object from dictionary.",
"name": "from_dict",
"signature": "def from_dict(cls, source, **kwargs)"
},
{
"docstring": "Validate whether all obligatory properties of the Delivery object are present and whether all the properties present are of correct types.",
... | 2 | stack_v2_sparse_classes_30k_train_041371 | Implement the Python class `DeliveryDictable` described below.
Class description:
Implement the DeliveryDictable class.
Method signatures and docstrings:
- def from_dict(cls, source, **kwargs): Initialize Delivery object from dictionary.
- def validate(self): Validate whether all obligatory properties of the Delivery... | Implement the Python class `DeliveryDictable` described below.
Class description:
Implement the DeliveryDictable class.
Method signatures and docstrings:
- def from_dict(cls, source, **kwargs): Initialize Delivery object from dictionary.
- def validate(self): Validate whether all obligatory properties of the Delivery... | c6cea33b15bcd876ded4de25138b3f5e5165cd6d | <|skeleton|>
class DeliveryDictable:
def from_dict(cls, source, **kwargs):
"""Initialize Delivery object from dictionary."""
<|body_0|>
def validate(self):
"""Validate whether all obligatory properties of the Delivery object are present and whether all the properties present are of cor... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DeliveryDictable:
def from_dict(cls, source, **kwargs):
"""Initialize Delivery object from dictionary."""
obj = cls.__new__(cls)
super(DeliveryDictable, obj).__init__()
source = camel_to_snake(source)
for key, value in source.items():
if key == 'zip':
... | the_stack_v2_python_sparse | mstrio/distribution_services/subscription/delivery.py | MicroStrategy/mstrio-py | train | 84 | |
a16403fcf0714da7e9242cdb04eeba1445888cdb | [
"if n < 0:\n n = -n\n x = 1 / x\nres = 1\nwhile n:\n if n & 1:\n res *= x\n x *= x\n n >>= 1\nreturn res",
"if n == 0:\n return 1\nif n < 0:\n return 1 / self.myPow1(x, -n)\nif n & 1:\n return x * self.myPow1(x * x, n >> 1)\nelse:\n return self.myPow1(x * x, n >> 1)"
] | <|body_start_0|>
if n < 0:
n = -n
x = 1 / x
res = 1
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
<|end_body_0|>
<|body_start_1|>
if n == 0:
return 1
if n < 0:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow1(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n < 0:
n = -n
... | stack_v2_sparse_classes_75kplus_train_001293 | 714 | no_license | [
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow",
"signature": "def myPow(self, x, n)"
},
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "myPow1",
"signature": "def myPow1(self, x, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011158 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow1(self, x, n): :type x: float :type n: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def myPow(self, x, n): :type x: float :type n: int :rtype: float
- def myPow1(self, x, n): :type x: float :type n: int :rtype: float
<|skeleton|>
class Solution:
def myPow(... | f1d780b7e8b91b4df704651514018143c6931f9d | <|skeleton|>
class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def myPow1(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def myPow(self, x, n):
""":type x: float :type n: int :rtype: float"""
if n < 0:
n = -n
x = 1 / x
res = 1
while n:
if n & 1:
res *= x
x *= x
n >>= 1
return res
def myPow1(self, x,... | the_stack_v2_python_sparse | ProgramForLeetCode/LeetCode/50_myPow.py | DQDH/Algorithm_Code | train | 0 | |
c08494dc741be8154a6073e914159bd35540a70d | [
"super(TaskCacheDataParser, self).__init__()\nself._debug = debug\nself._output_writer = output_writer",
"if filetime == 0:\n return dfdatetime_semantic_time.SemanticTime(string='Not set')\nif filetime == 9223372036854775807:\n return dfdatetime_semantic_time.SemanticTime(string='Never')\nreturn dfdatetime_... | <|body_start_0|>
super(TaskCacheDataParser, self).__init__()
self._debug = debug
self._output_writer = output_writer
<|end_body_0|>
<|body_start_1|>
if filetime == 0:
return dfdatetime_semantic_time.SemanticTime(string='Not set')
if filetime == 9223372036854775807:
... | Task Cache data parser. | TaskCacheDataParser | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskCacheDataParser:
"""Task Cache data parser."""
def __init__(self, debug=False, output_writer=None):
"""Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_writer (Optional[OutputWriter]): output writer."""
... | stack_v2_sparse_classes_75kplus_train_001294 | 7,293 | permissive | [
{
"docstring": "Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_writer (Optional[OutputWriter]): output writer.",
"name": "__init__",
"signature": "def __init__(self, debug=False, output_writer=None)"
},
{
"docstring": "Pars... | 3 | stack_v2_sparse_classes_30k_train_003886 | Implement the Python class `TaskCacheDataParser` described below.
Class description:
Task Cache data parser.
Method signatures and docstrings:
- def __init__(self, debug=False, output_writer=None): Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_... | Implement the Python class `TaskCacheDataParser` described below.
Class description:
Task Cache data parser.
Method signatures and docstrings:
- def __init__(self, debug=False, output_writer=None): Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_... | d149aff1b8ff97e1cc8d7416fc583b964bad4ccd | <|skeleton|>
class TaskCacheDataParser:
"""Task Cache data parser."""
def __init__(self, debug=False, output_writer=None):
"""Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_writer (Optional[OutputWriter]): output writer."""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TaskCacheDataParser:
"""Task Cache data parser."""
def __init__(self, debug=False, output_writer=None):
"""Initializes a Task Cache data parser. Args: debug (Optional[bool]): True if debug information should be printed. output_writer (Optional[OutputWriter]): output writer."""
super(TaskC... | the_stack_v2_python_sparse | winregrc/task_cache.py | libyal/winreg-kb | train | 129 |
18fbd2fd25c60e0dcfcf90fcab7a2a0d7434493b | [
"self.name = None\nself.training_data = None\nself.test_data = None\nself.entities = None\nself.features_dim = features_dim\nself.feat_normalize = normalize\nself.target_transform = target_transform",
"if self.feat_normalize:\n for i in range(len(self.entities)):\n if isspmatrix_csr(self.entities[i]):\n... | <|body_start_0|>
self.name = None
self.training_data = None
self.test_data = None
self.entities = None
self.features_dim = features_dim
self.feat_normalize = normalize
self.target_transform = target_transform
<|end_body_0|>
<|body_start_1|>
if self.feat_n... | Base class that holds necessary (minimal) information needed | Dataset | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Dataset:
"""Base class that holds necessary (minimal) information needed"""
def __init__(self, name, features_dim=0, normalize=False, target_transform=''):
"""Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is ... | stack_v2_sparse_classes_75kplus_train_001295 | 8,650 | permissive | [
{
"docstring": "Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is performed on the features as the dimensionality reduction technique normalize (bool): Normalize the features target_transform (str): Transform the target values. Current o... | 4 | stack_v2_sparse_classes_30k_train_040625 | Implement the Python class `Dataset` described below.
Class description:
Base class that holds necessary (minimal) information needed
Method signatures and docstrings:
- def __init__(self, name, features_dim=0, normalize=False, target_transform=''): Initialize parameters Args: name (str): Name of the dataset features... | Implement the Python class `Dataset` described below.
Class description:
Base class that holds necessary (minimal) information needed
Method signatures and docstrings:
- def __init__(self, name, features_dim=0, normalize=False, target_transform=''): Initialize parameters Args: name (str): Name of the dataset features... | 787ae309ec78a9b2b1f58931931cb117affc4ea9 | <|skeleton|>
class Dataset:
"""Base class that holds necessary (minimal) information needed"""
def __init__(self, name, features_dim=0, normalize=False, target_transform=''):
"""Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Dataset:
"""Base class that holds necessary (minimal) information needed"""
def __init__(self, name, features_dim=0, normalize=False, target_transform=''):
"""Initialize parameters Args: name (str): Name of the dataset features_dim (uint): Dimension of the features. If not 0, PCA is performed on ... | the_stack_v2_python_sparse | recommenders/models/geoimc/geoimc_data.py | DaniBunny/recommenders | train | 1 |
16e13c5fef5a89b52f3ef953cae96a66512aac74 | [
"context = super(HostNamesView, self).get_context_data(**kwargs)\ndevicesdata = list()\nfor row in HostNames.objects.all():\n dd = dict()\n dd['url'] = row.url\n dd['hostname'] = row.hostname\n dd['is_online'] = row.is_online\n dd['is_healthy'] = row.is_healthy\n dd['username'] = row.username\n ... | <|body_start_0|>
context = super(HostNamesView, self).get_context_data(**kwargs)
devicesdata = list()
for row in HostNames.objects.all():
dd = dict()
dd['url'] = row.url
dd['hostname'] = row.hostname
dd['is_online'] = row.is_online
dd['... | Home Page View with a popup Login Form | HostNamesView | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HostNamesView:
"""Home Page View with a popup Login Form"""
def get_context_data(self, **kwargs):
"""Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""O... | stack_v2_sparse_classes_75kplus_train_001296 | 2,197 | permissive | [
{
"docstring": "Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Overrides FormView.post in order to return JSON data for JS Validation (/js/l... | 2 | stack_v2_sparse_classes_30k_train_041415 | Implement the Python class `HostNamesView` described below.
Class description:
Home Page View with a popup Login Form
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)
- def post(self, request... | Implement the Python class `HostNamesView` described below.
Class description:
Home Page View with a popup Login Form
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)
- def post(self, request... | 244912e10f4d0e17e29e9b6cf5182f14d554f25d | <|skeleton|>
class HostNamesView:
"""Home Page View with a popup Login Form"""
def get_context_data(self, **kwargs):
"""Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""O... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HostNamesView:
"""Home Page View with a popup Login Form"""
def get_context_data(self, **kwargs):
"""Overriding get_context_data to add data for filling up Nexus Dashboard Table Template (in index.html)"""
context = super(HostNamesView, self).get_context_data(**kwargs)
devicesdata... | the_stack_v2_python_sparse | nexusdash/hostnames/views.py | datacenter/nexus9000 | train | 201 |
567a387287bf9c62c3cd299a59c85a542af781f5 | [
"self.serializer_class = CommentSerializer\nimage_id = self.kwargs.get('image_id')\nif not image_id:\n return JsonResponse({'status': 'fail', 'code': 406, 'data': None, 'messages': ['Error: No image id provided!']})\nqueryset_list = Comment.objects.filter(image__pk=image_id)\nreturn queryset_list",
"self.seria... | <|body_start_0|>
self.serializer_class = CommentSerializer
image_id = self.kwargs.get('image_id')
if not image_id:
return JsonResponse({'status': 'fail', 'code': 406, 'data': None, 'messages': ['Error: No image id provided!']})
queryset_list = Comment.objects.filter(image__pk... | Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату | CreateGetCommentsAPI | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateGetCommentsAPI:
"""Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату"""
def get_queryset(self, *args, **kwargs):
"""Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QueryS... | stack_v2_sparse_classes_75kplus_train_001297 | 6,327 | no_license | [
{
"docstring": "Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet",
"name": "get_queryset",
"signature": "def get_queryset(self, *args, **kwargs)"
},
{
"docstring": "Mетода помоћу које се врши креирање :param request: :param args: :param kwargs: im... | 2 | stack_v2_sparse_classes_30k_train_054229 | Implement the Python class `CreateGetCommentsAPI` described below.
Class description:
Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Mетода помоћу које се добављају сви по... | Implement the Python class `CreateGetCommentsAPI` described below.
Class description:
Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату
Method signatures and docstrings:
- def get_queryset(self, *args, **kwargs): Mетода помоћу које се добављају сви по... | 9b49cdfdcfbbc911cec23ed30ded30f6c4042522 | <|skeleton|>
class CreateGetCommentsAPI:
"""Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату"""
def get_queryset(self, *args, **kwargs):
"""Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QueryS... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CreateGetCommentsAPI:
"""Класа која се користи за креирање коментара и за добављање листе свих коментара слике репрезентованих у JSON формату"""
def get_queryset(self, *args, **kwargs):
"""Mетода помоћу које се добављају сви подаци :param args: :param kwargs: image_id :return: QuerySet"""
... | the_stack_v2_python_sparse | src/comments/api/views.py | milosb793/django-gallery-api | train | 0 |
510a03632a8c6eafebd6b14c8786f73655d6f77f | [
"super(MaskedMSELoss, self).__init__()\nif reduction != 'mean':\n NotImplementedError\nself.reduction = reduction",
"assert x.shape == target.shape == mask.shape\nsquared_error = (torch.flatten(x) - torch.flatten(target)) ** 2.0 * torch.flatten(mask)\nif self.reduction == 'mean':\n result = torch.sum(square... | <|body_start_0|>
super(MaskedMSELoss, self).__init__()
if reduction != 'mean':
NotImplementedError
self.reduction = reduction
<|end_body_0|>
<|body_start_1|>
assert x.shape == target.shape == mask.shape
squared_error = (torch.flatten(x) - torch.flatten(target)) ** 2.... | Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss | MaskedMSELoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskedMSELoss:
"""Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss"""
def __init__(self, reduction: str='mean'):
"""Constructor Arguments: reduction (string, optional) -- how MSE should be reduced. Defaults to 'mean'."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_001298 | 2,211 | permissive | [
{
"docstring": "Constructor Arguments: reduction (string, optional) -- how MSE should be reduced. Defaults to 'mean'.",
"name": "__init__",
"signature": "def __init__(self, reduction: str='mean')"
},
{
"docstring": "Foreward pass Args: x (torch.Tensor): input tensor (output from neural network) ... | 2 | stack_v2_sparse_classes_30k_train_025211 | Implement the Python class `MaskedMSELoss` described below.
Class description:
Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss
Method signatures and docstrings:
- def __init__(self, reduction: str='mean'): Constructor Arguments: reduction (string, optional) -- how MSE shou... | Implement the Python class `MaskedMSELoss` described below.
Class description:
Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss
Method signatures and docstrings:
- def __init__(self, reduction: str='mean'): Constructor Arguments: reduction (string, optional) -- how MSE shou... | 5b4a61b5dd0bc259ffe68223877949ef4ebfa5e3 | <|skeleton|>
class MaskedMSELoss:
"""Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss"""
def __init__(self, reduction: str='mean'):
"""Constructor Arguments: reduction (string, optional) -- how MSE should be reduced. Defaults to 'mean'."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskedMSELoss:
"""Masked MSE Loss module Arguments: torch {torch.nn.modules.loss._Loss} -- inherits from _Loss"""
def __init__(self, reduction: str='mean'):
"""Constructor Arguments: reduction (string, optional) -- how MSE should be reduced. Defaults to 'mean'."""
super(MaskedMSELoss, sel... | the_stack_v2_python_sparse | src/models/anomalia/losses.py | maurony/ts-vrae | train | 1 |
6ef2daa89188673b05a275dea530ee33013e6eb2 | [
"self._lock.acquire()\ntry:\n key = int(target.__name__.split('_')[-1])\n if self._targets.has_key(key):\n exist_target = self._targets.get(key)\n raise 'target [%d] Already exists, Conflict between the %s and %s' % (key, exist_target.__name__, target.__name__)\n self._targets[... | <|body_start_0|>
self._lock.acquire()
try:
key = int(target.__name__.split('_')[-1])
if self._targets.has_key(key):
exist_target = self._targets.get(key)
raise 'target [%d] Already exists, Conflict between the %s and %s' % (key, exis... | A remoting service According to Command ID search target | CommandService | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandService:
"""A remoting service According to Command ID search target"""
def mapTarget(self, target):
"""Add a target to the service."""
<|body_0|>
def unMapTarget(self, target):
"""Remove a target from the service."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_75kplus_train_001299 | 4,997 | permissive | [
{
"docstring": "Add a target to the service.",
"name": "mapTarget",
"signature": "def mapTarget(self, target)"
},
{
"docstring": "Remove a target from the service.",
"name": "unMapTarget",
"signature": "def unMapTarget(self, target)"
}
] | 2 | stack_v2_sparse_classes_30k_train_044733 | Implement the Python class `CommandService` described below.
Class description:
A remoting service According to Command ID search target
Method signatures and docstrings:
- def mapTarget(self, target): Add a target to the service.
- def unMapTarget(self, target): Remove a target from the service. | Implement the Python class `CommandService` described below.
Class description:
A remoting service According to Command ID search target
Method signatures and docstrings:
- def mapTarget(self, target): Add a target to the service.
- def unMapTarget(self, target): Remove a target from the service.
<|skeleton|>
class ... | 8205dff0d423aaedfa7fca8790d1d6fe50213e6e | <|skeleton|>
class CommandService:
"""A remoting service According to Command ID search target"""
def mapTarget(self, target):
"""Add a target to the service."""
<|body_0|>
def unMapTarget(self, target):
"""Remove a target from the service."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandService:
"""A remoting service According to Command ID search target"""
def mapTarget(self, target):
"""Add a target to the service."""
self._lock.acquire()
try:
key = int(target.__name__.split('_')[-1])
if self._targets.has_key(key):
... | the_stack_v2_python_sparse | firefly/utils/services.py | hw233/lolita_son | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.