blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8ddb26ff3c6bee016b24c67f31390de196c1ff53 | [
"return_dict = {}\nif not table:\n return return_dict\nfor record in table.records:\n if record.get_number_of_values() != 2:\n continue\n identification = self._GetRecordValue(record, 0)\n filename = self._GetRecordValue(record, 1)\n if not identification:\n continue\n return_dict[id... | <|body_start_0|>
return_dict = {}
if not table:
return return_dict
for record in table.records:
if record.get_number_of_values() != 2:
continue
identification = self._GetRecordValue(record, 0)
filename = self._GetRecordValue(record,... | Parses a File History ESE database file. | FileHistoryEseDbPlugin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification fie... | stack_v2_sparse_classes_36k_train_004700 | 3,890 | permissive | [
{
"docstring": "Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification field as key and filename as value.",
"name": "_GetDictFromStringsTable",
"signature": "def _GetDictFromStringsTable(self, t... | 2 | null | Implement the Python class `FileHistoryEseDbPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, table): Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.tab... | Implement the Python class `FileHistoryEseDbPlugin` described below.
Class description:
Parses a File History ESE database file.
Method signatures and docstrings:
- def _GetDictFromStringsTable(self, table): Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.tab... | 923797fc00664fa9e3277781b0334d6eed5664fd | <|skeleton|>
class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification fie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FileHistoryEseDbPlugin:
"""Parses a File History ESE database file."""
def _GetDictFromStringsTable(self, table):
"""Build a dict for the strings table. Args: table: A table object for the strings table (instance of pyesedb.table). Returns: A dict that contains the identification field as key and... | the_stack_v2_python_sparse | plaso/parsers/esedb_plugins/file_history.py | CNR-ITTIG/plasodfaxp | train | 1 |
fd9cc5ce3ae80b34305304261b11a14f6d22af87 | [
"self.name = name\nself.sync = sync\nself.count = count",
"project_id = kwargs.get('project_id', context.tenant)\nif project_id:\n try:\n return driver.get_by_project(context, project_id, self.name)\n except exception.ProjectQuotaNotFound:\n pass\nreturn -1"
] | <|body_start_0|>
self.name = name
self.sync = sync
self.count = count
<|end_body_0|>
<|body_start_1|>
project_id = kwargs.get('project_id', context.tenant)
if project_id:
try:
return driver.get_by_project(context, project_id, self.name)
ex... | Describe a single resource for quota checking. | BaseResource | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseResource:
"""Describe a single resource for quota checking."""
def __init__(self, name, sync, count=None):
"""Initializes a Resource. :param name: The name of the resource, i.e., "servers". :param sync: A dbapi methods name which returns a dictionary to resynchronize the in_use c... | stack_v2_sparse_classes_36k_train_004701 | 17,744 | permissive | [
{
"docstring": "Initializes a Resource. :param name: The name of the resource, i.e., \"servers\". :param sync: A dbapi methods name which returns a dictionary to resynchronize the in_use count for one or more resources, as described above.",
"name": "__init__",
"signature": "def __init__(self, name, syn... | 2 | null | Implement the Python class `BaseResource` described below.
Class description:
Describe a single resource for quota checking.
Method signatures and docstrings:
- def __init__(self, name, sync, count=None): Initializes a Resource. :param name: The name of the resource, i.e., "servers". :param sync: A dbapi methods name... | Implement the Python class `BaseResource` described below.
Class description:
Describe a single resource for quota checking.
Method signatures and docstrings:
- def __init__(self, name, sync, count=None): Initializes a Resource. :param name: The name of the resource, i.e., "servers". :param sync: A dbapi methods name... | 6008c1d12b00e70d2cc651f7bd5d47968fc3aec7 | <|skeleton|>
class BaseResource:
"""Describe a single resource for quota checking."""
def __init__(self, name, sync, count=None):
"""Initializes a Resource. :param name: The name of the resource, i.e., "servers". :param sync: A dbapi methods name which returns a dictionary to resynchronize the in_use c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseResource:
"""Describe a single resource for quota checking."""
def __init__(self, name, sync, count=None):
"""Initializes a Resource. :param name: The name of the resource, i.e., "servers". :param sync: A dbapi methods name which returns a dictionary to resynchronize the in_use count for one ... | the_stack_v2_python_sparse | mogan/objects/quota.py | GURUIFENG9139/rocky-mogan | train | 0 |
aa3da683a2b93dcec2afbefb352ff374eebfd878 | [
"super(RLEncodingConfiguration, self).__init__(**kwargs)\nself.train_config = None\nself.test_config = None\nself.division = None\nself.max_update_steps = float('inf')\nself.max_test_steps = 30\nself.set_necessary_configs(**kwargs)\nself.set_unnecessary_configs(**kwargs)",
"try:\n self.model_config = ModelConf... | <|body_start_0|>
super(RLEncodingConfiguration, self).__init__(**kwargs)
self.train_config = None
self.test_config = None
self.division = None
self.max_update_steps = float('inf')
self.max_test_steps = 30
self.set_necessary_configs(**kwargs)
self.set_unnec... | class stores the rl encoding configuration | RLEncodingConfiguration | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RLEncodingConfiguration:
"""class stores the rl encoding configuration"""
def __init__(self, **kwargs):
"""initialize settings"""
<|body_0|>
def set_necessary_configs(self, **kwargs):
"""set encoding configs that necessarily provided by user"""
<|body_1|>... | stack_v2_sparse_classes_36k_train_004702 | 5,332 | no_license | [
{
"docstring": "initialize settings",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "set encoding configs that necessarily provided by user",
"name": "set_necessary_configs",
"signature": "def set_necessary_configs(self, **kwargs)"
},
{
"docstr... | 3 | null | Implement the Python class `RLEncodingConfiguration` described below.
Class description:
class stores the rl encoding configuration
Method signatures and docstrings:
- def __init__(self, **kwargs): initialize settings
- def set_necessary_configs(self, **kwargs): set encoding configs that necessarily provided by user
... | Implement the Python class `RLEncodingConfiguration` described below.
Class description:
class stores the rl encoding configuration
Method signatures and docstrings:
- def __init__(self, **kwargs): initialize settings
- def set_necessary_configs(self, **kwargs): set encoding configs that necessarily provided by user
... | b0e8f66b3ade742445a41d3d5667032a931d94d2 | <|skeleton|>
class RLEncodingConfiguration:
"""class stores the rl encoding configuration"""
def __init__(self, **kwargs):
"""initialize settings"""
<|body_0|>
def set_necessary_configs(self, **kwargs):
"""set encoding configs that necessarily provided by user"""
<|body_1|>... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RLEncodingConfiguration:
"""class stores the rl encoding configuration"""
def __init__(self, **kwargs):
"""initialize settings"""
super(RLEncodingConfiguration, self).__init__(**kwargs)
self.train_config = None
self.test_config = None
self.division = None
s... | the_stack_v2_python_sparse | config/rl_config.py | wz139704646/MBRL_on_VAEs | train | 1 |
605f20002a174659c4cf9f6defb33d98d55a291e | [
"super().__init__(order=CallbackOrder.external, node=CallbackNode.all)\nself.best_score = None\nself.metric = metric\nself.patience = patience\nself.num_bad_epochs = 0\nself.is_better = None\nif minimize:\n self.is_better = lambda score, best: score <= best - min_delta\nelse:\n self.is_better = lambda score, ... | <|body_start_0|>
super().__init__(order=CallbackOrder.external, node=CallbackNode.all)
self.best_score = None
self.metric = metric
self.patience = patience
self.num_bad_epochs = 0
self.is_better = None
if minimize:
self.is_better = lambda score, best: ... | Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(1e1) X, y = torch.rand(num_samples, num_features), torch.rand(num_samples) dataset = Ten... | EarlyStoppingCallback | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EarlyStoppingCallback:
"""Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(1e1) X, y = torch.rand(num_samples, num... | stack_v2_sparse_classes_36k_train_004703 | 6,187 | permissive | [
{
"docstring": "Args: patience: number of epochs with no improvement after which training will be stopped. metric: metric name to use for early stopping, default is ``\"loss\"``. minimize: if ``True`` then expected that metric should decrease and early stopping will be performed only when metric stops decreasin... | 2 | stack_v2_sparse_classes_30k_train_007783 | Implement the Python class `EarlyStoppingCallback` described below.
Class description:
Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(... | Implement the Python class `EarlyStoppingCallback` described below.
Class description:
Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(... | 8ce39fc31635eabc348b055a2df8ec8bc5700dce | <|skeleton|>
class EarlyStoppingCallback:
"""Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(1e1) X, y = torch.rand(num_samples, num... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EarlyStoppingCallback:
"""Early exit based on metric. Minimal working example (Notebook API): .. code-block:: python import torch from torch.utils.data import DataLoader, TensorDataset from catalyst import dl # data num_samples, num_features = int(1e4), int(1e1) X, y = torch.rand(num_samples, num_features), t... | the_stack_v2_python_sparse | catalyst/callbacks/early_stop.py | 418sec/catalyst | train | 0 |
3fc5f15b110f969934b89f649cb634b95ebae954 | [
"success, status = AppStatus.check_status()\nif success:\n return jsonify({'success': True})\nabort(503, status)",
"status = ''\nif os.path.exists(current_app.config['ACI_STARTED_FILE']):\n logger.debug('application started flag is set')\n try:\n from .utils import get_db\n assert len(get_d... | <|body_start_0|>
success, status = AppStatus.check_status()
if success:
return jsonify({'success': True})
abort(503, status)
<|end_body_0|>
<|body_start_1|>
status = ''
if os.path.exists(current_app.config['ACI_STARTED_FILE']):
logger.debug('application s... | AppStatus | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppStatus:
def api_check_status():
"""check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if not ready with an error description"""
<|body_0|>
def check_status():
"""check... | stack_v2_sparse_classes_36k_train_004704 | 10,625 | permissive | [
{
"docstring": "check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if not ready with an error description",
"name": "api_check_status",
"signature": "def api_check_status()"
},
{
"docstring": "check ... | 5 | null | Implement the Python class `AppStatus` described below.
Class description:
Implement the AppStatus class.
Method signatures and docstrings:
- def api_check_status(): check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if n... | Implement the Python class `AppStatus` described below.
Class description:
Implement the AppStatus class.
Method signatures and docstrings:
- def api_check_status(): check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if n... | a4de84c5fc00549e6539dbc1d8d927c74a704dcc | <|skeleton|>
class AppStatus:
def api_check_status():
"""check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if not ready with an error description"""
<|body_0|>
def check_status():
"""check... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AppStatus:
def api_check_status():
"""check the startup status of the app. A 500 error may occur if the webserver is not running or app is not ready. A 503 service unavailable is return if not ready with an error description"""
success, status = AppStatus.check_status()
if success:
... | the_stack_v2_python_sparse | Service/app/models/app_status.py | Hrishi5/ACI-EnhancedEndpointTracker | train | 0 | |
179a19a4ed70b7df48bb8346d33c255fcdec476e | [
"if cls._context_managed_task_group:\n cls._previous_context_managed_task_groups.append(cls._context_managed_task_group)\ncls._context_managed_task_group = task_group\ncls.active = True",
"old_task_group = cls._context_managed_task_group\nif cls._previous_context_managed_task_groups:\n cls._context_managed_... | <|body_start_0|>
if cls._context_managed_task_group:
cls._previous_context_managed_task_groups.append(cls._context_managed_task_group)
cls._context_managed_task_group = task_group
cls.active = True
<|end_body_0|>
<|body_start_1|>
old_task_group = cls._context_managed_task_gr... | TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager. | TaskGroupContext | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
<|body_0|>
def pop_conte... | stack_v2_sparse_classes_36k_train_004705 | 29,383 | permissive | [
{
"docstring": "Push a TaskGroup into the list of managed TaskGroups.",
"name": "push_context_managed_task_group",
"signature": "def push_context_managed_task_group(cls, task_group: TaskGroup)"
},
{
"docstring": "Pops the last TaskGroup from the list of manged TaskGroups and update the current T... | 3 | null | Implement the Python class `TaskGroupContext` described below.
Class description:
TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.
Method signatures and docstrings:
- def push_context_managed_task_group(cls, task_group: TaskGroup): Push a TaskGroup into the list of man... | Implement the Python class `TaskGroupContext` described below.
Class description:
TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager.
Method signatures and docstrings:
- def push_context_managed_task_group(cls, task_group: TaskGroup): Push a TaskGroup into the list of man... | 1b122c15030e99cef9d4ff26d3781a7a9d6949bc | <|skeleton|>
class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
<|body_0|>
def pop_conte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskGroupContext:
"""TaskGroup context is used to keep the current TaskGroup when TaskGroup is used as ContextManager."""
def push_context_managed_task_group(cls, task_group: TaskGroup):
"""Push a TaskGroup into the list of managed TaskGroups."""
if cls._context_managed_task_group:
... | the_stack_v2_python_sparse | airflow/utils/task_group.py | apache/airflow | train | 22,756 |
c8d1e0ec7f6e65d085e1896156d6f648df52d242 | [
"self.end_time_msecs = end_time_msecs\nself.entity_env = entity_env\nself.entity_id = entity_id\nself.entity_name = entity_name\nself.job_id = job_id\nself.job_run_id = job_run_id\nself.job_type = job_type\nself.start_time_msecs = start_time_msecs\nself.status = status",
"if dictionary is None:\n return None\n... | <|body_start_0|>
self.end_time_msecs = end_time_msecs
self.entity_env = entity_env
self.entity_id = entity_id
self.entity_name = entity_name
self.job_id = job_id
self.job_run_id = job_run_id
self.job_type = job_type
self.start_time_msecs = start_time_msecs... | Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. entity_id (long|int): Specifies the entity id of the object. entity_name (string): Specifie... | GetObjectsDetailsResult | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GetObjectsDetailsResult:
"""Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. entity_id (long|int): Specifies the enti... | stack_v2_sparse_classes_36k_train_004706 | 3,339 | permissive | [
{
"docstring": "Constructor for the GetObjectsDetailsResult class",
"name": "__init__",
"signature": "def __init__(self, end_time_msecs=None, entity_env=None, entity_id=None, entity_name=None, job_id=None, job_run_id=None, job_type=None, start_time_msecs=None, status=None)"
},
{
"docstring": "Cr... | 2 | null | Implement the Python class `GetObjectsDetailsResult` described below.
Class description:
Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. e... | Implement the Python class `GetObjectsDetailsResult` described below.
Class description:
Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. e... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class GetObjectsDetailsResult:
"""Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. entity_id (long|int): Specifies the enti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GetObjectsDetailsResult:
"""Implementation of the 'GetObjectsDetailsResult' model. TODO: type description here. Attributes: end_time_msecs (long|int): Specifies the end time of the run. entity_env (long|int): Specifies the entity environment of the object. entity_id (long|int): Specifies the entity id of the ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/get_objects_details_result.py | cohesity/management-sdk-python | train | 24 |
b663b95826214242ba3c8b9cc6342681b3c3c871 | [
"email = request.GET.get('email', '')\nif email and (not UserProfile.objects.filter(email=email)):\n status = email_send(email=email, send_type='update_email')\n if status:\n status = {'code': 0, 'msg': '邮箱验证码发送成功'}\n else:\n status = {'code': 1, 'msg': '邮箱验证码发送失败'}\nelse:\n status = {'cod... | <|body_start_0|>
email = request.GET.get('email', '')
if email and (not UserProfile.objects.filter(email=email)):
status = email_send(email=email, send_type='update_email')
if status:
status = {'code': 0, 'msg': '邮箱验证码发送成功'}
else:
statu... | 修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱 | UpdateEmailView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateEmailView:
"""修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱"""
def get(self, request):
"""获取邮箱验证码"""
<|body_0|>
def post(self, request):
"""修改用户的邮箱"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
email = request.GET.get('email', '')
if email and (not... | stack_v2_sparse_classes_36k_train_004707 | 17,587 | no_license | [
{
"docstring": "获取邮箱验证码",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "修改用户的邮箱",
"name": "post",
"signature": "def post(self, request)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020723 | Implement the Python class `UpdateEmailView` described below.
Class description:
修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱
Method signatures and docstrings:
- def get(self, request): 获取邮箱验证码
- def post(self, request): 修改用户的邮箱 | Implement the Python class `UpdateEmailView` described below.
Class description:
修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱
Method signatures and docstrings:
- def get(self, request): 获取邮箱验证码
- def post(self, request): 修改用户的邮箱
<|skeleton|>
class UpdateEmailView:
"""修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱"""
def get(self, request):
... | 58bcab94b5b4837fbcaf53b2753cec507c1f4f11 | <|skeleton|>
class UpdateEmailView:
"""修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱"""
def get(self, request):
"""获取邮箱验证码"""
<|body_0|>
def post(self, request):
"""修改用户的邮箱"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateEmailView:
"""修改用户邮箱: 1、获取邮箱验证码 2、修改用户邮箱"""
def get(self, request):
"""获取邮箱验证码"""
email = request.GET.get('email', '')
if email and (not UserProfile.objects.filter(email=email)):
status = email_send(email=email, send_type='update_email')
if status:
... | the_stack_v2_python_sparse | apps/users/views.py | txowner/XMooc | train | 1 |
3c701f1d11b2c355cfb4c45d0bf0e818b3477ea0 | [
"N = num_grid_points\nassert N % 2 == 0\n\"The derivative matrix is calculated using the 'Negative Sum Trick'.\"\nM = np.empty((N, N))\nfor i in range(N):\n M[i, i] = 0\n for j in range(N):\n if j != i:\n M[i, j] = 1 / 2 * (-1) ** (i + j) * (1 / np.tan((i - j) * np.pi / N))\nfor i in range(N... | <|body_start_0|>
N = num_grid_points
assert N % 2 == 0
"The derivative matrix is calculated using the 'Negative Sum Trick'."
M = np.empty((N, N))
for i in range(N):
M[i, i] = 0
for j in range(N):
if j != i:
M[i, j] = 1 /... | Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative. | FFT_lagrange | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FFT_lagrange:
"""Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative."""
def __init__(self, num_grid_points, period):
"""Initialisation for this FFT differential operator. Parameters ... | stack_v2_sparse_classes_36k_train_004708 | 10,646 | no_license | [
{
"docstring": "Initialisation for this FFT differential operator. Parameters --------- num_grid_points: int The number of grid points that the function will have. period: float",
"name": "__init__",
"signature": "def __init__(self, num_grid_points, period)"
},
{
"docstring": "Returns the deriva... | 2 | null | Implement the Python class `FFT_lagrange` described below.
Class description:
Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative.
Method signatures and docstrings:
- def __init__(self, num_grid_points, period): Initi... | Implement the Python class `FFT_lagrange` described below.
Class description:
Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative.
Method signatures and docstrings:
- def __init__(self, num_grid_points, period): Initi... | 2ce16d776448553e2ae5c45f3cf973c8271aefbf | <|skeleton|>
class FFT_lagrange:
"""Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative."""
def __init__(self, num_grid_points, period):
"""Initialisation for this FFT differential operator. Parameters ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FFT_lagrange:
"""Manually calculates the derivative using a cached matrix whose values are computed assuming application of a fourier transform to calculate a derivative."""
def __init__(self, num_grid_points, period):
"""Initialisation for this FFT differential operator. Parameters --------- num... | the_stack_v2_python_sparse | Code/packages/coffee/diffop/fft.py | mfuphi/SOFTX_2019_93 | train | 0 |
c5e2d6287868410769e8df23f70e7ef0efd7d5dc | [
"argument_group.add_argument('--user', dest='username', type=str, action='store', default=cls._DEFAULT_USERNAME, metavar='USERNAME', required=False, help='The username used to connect to the database.')\nargument_group.add_argument('--password', dest='password', type=str, action='store', default=cls._DEFAULT_PASSWO... | <|body_start_0|>
argument_group.add_argument('--user', dest='username', type=str, action='store', default=cls._DEFAULT_USERNAME, metavar='USERNAME', required=False, help='The username used to connect to the database.')
argument_group.add_argument('--password', dest='password', type=str, action='store', ... | Database configuration CLI arguments helper. | DatabaseArgumentsHelper | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatabaseArgumentsHelper:
"""Database configuration CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the comman... | stack_v2_sparse_classes_36k_train_004709 | 2,780 | permissive | [
{
"docstring": "Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|argparse.ArgumentParser): argparse group.",
... | 2 | stack_v2_sparse_classes_30k_train_000267 | Implement the Python class `DatabaseArgumentsHelper` described below.
Class description:
Database configuration CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments the helper supports to an argument group. This function takes an argument parser ... | Implement the Python class `DatabaseArgumentsHelper` described below.
Class description:
Database configuration CLI arguments helper.
Method signatures and docstrings:
- def AddArguments(cls, argument_group): Adds command line arguments the helper supports to an argument group. This function takes an argument parser ... | c69b2952b608cfce47ff8fd0d1409d856be35cb1 | <|skeleton|>
class DatabaseArgumentsHelper:
"""Database configuration CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the comman... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DatabaseArgumentsHelper:
"""Database configuration CLI arguments helper."""
def AddArguments(cls, argument_group):
"""Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line argume... | the_stack_v2_python_sparse | plaso/cli/helpers/database_config.py | cyb3rfox/plaso | train | 3 |
741c6773ee9da987a6884ccf683917d9f868c4c8 | [
"kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)\nkwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})\nreturn kwargs",
"super(NewbobAbs, self).__init__(**kwargs)\nself.errorThreshold = e... | <|body_start_0|>
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFactor': config.float('newbob_learning_rate_decay', 0.5)})
return kwargs
<|end_body_0|>
<|body_start_1|>
... | NewbobAbs | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_36k_train_004710 | 19,323 | no_license | [
{
"docstring": ":type config: Config.Config :rtype: dict[str]",
"name": "load_initial_kwargs_from_config",
"signature": "def load_initial_kwargs_from_config(cls, config)"
},
{
"docstring": ":type errorThreshold: float :type learningRateDecayFactor: float",
"name": "__init__",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_012643 | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | Implement the Python class `NewbobAbs` described below.
Class description:
Implement the NewbobAbs class.
Method signatures and docstrings:
- def load_initial_kwargs_from_config(cls, config): :type config: Config.Config :rtype: dict[str]
- def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs): :type e... | d494b3041069d377d6a7a9c296a14334f2fa5acc | <|skeleton|>
class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
<|body_0|>
def __init__(self, errorThreshold, learningRateDecayFactor, **kwargs):
""":type errorThreshold: float :type learningRateDecayFactor: float"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NewbobAbs:
def load_initial_kwargs_from_config(cls, config):
""":type config: Config.Config :rtype: dict[str]"""
kwargs = super(NewbobAbs, cls).load_initial_kwargs_from_config(config)
kwargs.update({'errorThreshold': config.float('newbob_error_threshold', -0.01), 'learningRateDecayFact... | the_stack_v2_python_sparse | python/rwth-i6_returnn/returnn-master/LearningRateControl.py | LiuFang816/SALSTM_py_data | train | 10 | |
7136d4ae62e2ae0b5068ec8bf798387d27d730c3 | [
"ObjectManager.__init__(self)\nself.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general'})\nself.setters.update({'session_template': 'set_foreign_key', 'session_user_role': 'set_foreign_key', 'max': 'set_general', 'min': 'set_gener... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key', 'max': 'get_general', 'min': 'get_general'})
self.setters.update({'session_template': 'set_foreign_key', 'session_user_role': 'set_foreign_key', 'max'... | Manage SessionTemplateUserRoleRequirements in the Power Reg system | SessionTemplateUserRoleRequirementManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, session_user_role_id, min, max, credential_type_ids=None... | stack_v2_sparse_classes_36k_train_004711 | 2,528 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new SessionTemplateUserRoleRequirement @param session_template_id Primary key for an session_template @param session_user_role_id Primary key for a session_user_role @param min Minimum... | 2 | stack_v2_sparse_classes_30k_train_000251 | Implement the Python class `SessionTemplateUserRoleRequirementManager` described below.
Class description:
Manage SessionTemplateUserRoleRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, session_user_role_id, mi... | Implement the Python class `SessionTemplateUserRoleRequirementManager` described below.
Class description:
Manage SessionTemplateUserRoleRequirements in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, session_template_id, session_user_role_id, mi... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, session_template_id, session_user_role_id, min, max, credential_type_ids=None... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SessionTemplateUserRoleRequirementManager:
"""Manage SessionTemplateUserRoleRequirements in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'session_template': 'get_foreign_key', 'session_user_role': 'get_foreign_key'... | the_stack_v2_python_sparse | pr_services/event_system/session_template_user_role_requirement_manager.py | ninemoreminutes/openassign-server | train | 0 |
44a40657a36509b78612ef7e806288fb25b3cdc9 | [
"n, start, end, step = (len(nums), 0, 0, 0)\nwhile end < n - 1:\n step += 1\n max_end = end + 1\n for i in range(start, end + 1):\n if i + nums[i] >= n - 1:\n return step\n max_end = max(max_end, i + nums[i])\n start, end = (end + 1, max_end)\nreturn step",
"nums_len = len(num... | <|body_start_0|>
n, start, end, step = (len(nums), 0, 0, 0)
while end < n - 1:
step += 1
max_end = end + 1
for i in range(start, end + 1):
if i + nums[i] >= n - 1:
return step
max_end = max(max_end, i + nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%"""
<|body_0|>
def jump1(self, nums):
""":param nums: :return: check indices before each index from 1 to nums_len... | stack_v2_sparse_classes_36k_train_004712 | 1,301 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%",
"name": "jump",
"signature": "def jump(self, nums)"
},
{
"docstring": ":param nums: :return: check indices before each index from 1 to nums_len - 1 stop at th... | 2 | stack_v2_sparse_classes_30k_train_009372 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%
- def jump1(self, nums): :param nums... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def jump(self, nums): :type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%
- def jump1(self, nums): :param nums... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%"""
<|body_0|>
def jump1(self, nums):
""":param nums: :return: check indices before each index from 1 to nums_len... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def jump(self, nums):
""":type nums: List[int] :rtype: int check every index in the current available range to reach the end or not beats 44.25%"""
n, start, end, step = (len(nums), 0, 0, 0)
while end < n - 1:
step += 1
max_end = end + 1
fo... | the_stack_v2_python_sparse | LeetCode/045_jump_game_ii.py | yao23/Machine_Learning_Playground | train | 12 | |
71a85d195c3565c577bc6167b12d67c451535048 | [
"if cal_parameter_name == 'amp':\n raise CalibrationError(\"The Half-Angle calibration experiment was changed from calibrating the pulse's complex amplitude, to calibrating the angle parameter in the real (amp,angle) representation. Setting cal_parameter_name to 'amp' thus indicates that you are probably using t... | <|body_start_0|>
if cal_parameter_name == 'amp':
raise CalibrationError("The Half-Angle calibration experiment was changed from calibrating the pulse's complex amplitude, to calibrating the angle parameter in the real (amp,angle) representation. Setting cal_parameter_name to 'amp' thus indicates tha... | Calibration version of the half-angle experiment. | HalfAngleCal | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HalfAngleCal:
"""Calibration version of the half-angle experiment."""
def __init__(self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend]=None, schedule_name: str='sx', cal_parameter_name: Optional[str]='angle', auto_update: bool=True):
"""The ex... | stack_v2_sparse_classes_36k_train_004713 | 7,538 | permissive | [
{
"docstring": "The experiment to update angle of half-pi rotation gates. Args: physical_qubits: Sequence containing the qubit for which to run the half-angle calibration. calibrations: The calibrations instance with the schedules. backend: Optional, the backend to run the experiment on. schedule_name: The name... | 4 | null | Implement the Python class `HalfAngleCal` described below.
Class description:
Calibration version of the half-angle experiment.
Method signatures and docstrings:
- def __init__(self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend]=None, schedule_name: str='sx', cal_parameter_nam... | Implement the Python class `HalfAngleCal` described below.
Class description:
Calibration version of the half-angle experiment.
Method signatures and docstrings:
- def __init__(self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend]=None, schedule_name: str='sx', cal_parameter_nam... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class HalfAngleCal:
"""Calibration version of the half-angle experiment."""
def __init__(self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend]=None, schedule_name: str='sx', cal_parameter_name: Optional[str]='angle', auto_update: bool=True):
"""The ex... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HalfAngleCal:
"""Calibration version of the half-angle experiment."""
def __init__(self, physical_qubits: Sequence[int], calibrations: Calibrations, backend: Optional[Backend]=None, schedule_name: str='sx', cal_parameter_name: Optional[str]='angle', auto_update: bool=True):
"""The experiment to u... | the_stack_v2_python_sparse | qiskit_experiments/library/calibration/half_angle_cal.py | oliverdial/qiskit-experiments | train | 0 |
2fc4911b097f4bfd0ff1b28ba801025153df3124 | [
"super().__init__()\nimport sklearn\nimport sklearn.linear_model\nself.model = sklearn.linear_model.ElasticNetCV",
"specs = super(ElasticNetCV, cls).getInputSpecification()\nspecs.description = 'The \\\\xmlNode{ElasticNetCV} employs\\n Linear regression with combined L1 and L2 priors as reg... | <|body_start_0|>
super().__init__()
import sklearn
import sklearn.linear_model
self.model = sklearn.linear_model.ElasticNetCV
<|end_body_0|>
<|body_start_1|>
specs = super(ElasticNetCV, cls).getInputSpecification()
specs.description = 'The \\xmlNode{ElasticNetCV} employs... | Linear Elastic Net model with iterative fitting along a regularization path. | ElasticNetCV | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ElasticNetCV:
"""Linear Elastic Net model with iterative fitting along a regularization path."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
... | stack_v2_sparse_classes_36k_train_004714 | 7,792 | permissive | [
{
"docstring": "Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Method to get a reference to a class that specifies the input data for class cls. @ In, cls, the class for... | 3 | null | Implement the Python class `ElasticNetCV` described below.
Class description:
Linear Elastic Net model with iterative fitting along a regularization path.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def ge... | Implement the Python class `ElasticNetCV` described below.
Class description:
Linear Elastic Net model with iterative fitting along a regularization path.
Method signatures and docstrings:
- def __init__(self): Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None
- def ge... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class ElasticNetCV:
"""Linear Elastic Net model with iterative fitting along a regularization path."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
<|body_0|>
def getInputSpecification(cls):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ElasticNetCV:
"""Linear Elastic Net model with iterative fitting along a regularization path."""
def __init__(self):
"""Constructor that will appropriately initialize a supervised learning object @ In, None @ Out, None"""
super().__init__()
import sklearn
import sklearn.li... | the_stack_v2_python_sparse | ravenframework/SupervisedLearning/ScikitLearn/LinearModel/ElasticNetCV.py | idaholab/raven | train | 201 |
d147be66a46875d93ef743b65b1917f1fec7292a | [
"try:\n music = {}\n music['music'] = self.manager.search(q=data['search'], limit=20, type='track')\n return music\nexcept (TypeError, KeyError, SpotifyException):\n raise exceptions.ValidationError(code=status.HTTP_400_BAD_REQUEST, detail=\"It's required `search` field.\")",
"try:\n music = {}\n ... | <|body_start_0|>
try:
music = {}
music['music'] = self.manager.search(q=data['search'], limit=20, type='track')
return music
except (TypeError, KeyError, SpotifyException):
raise exceptions.ValidationError(code=status.HTTP_400_BAD_REQUEST, detail="It's req... | Utilities for the service of music. | UtilsMusic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_36k_train_004715 | 11,622 | no_license | [
{
"docstring": "Search by all items.",
"name": "search_all",
"signature": "def search_all(self, data)"
},
{
"docstring": "Search by date.",
"name": "search_date",
"signature": "def search_date(self, data)"
},
{
"docstring": "Search by uuid.",
"name": "search_uuid",
"signa... | 4 | stack_v2_sparse_classes_30k_train_014996 | Implement the Python class `UtilsMusic` described below.
Class description:
Utilities for the service of music.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | Implement the Python class `UtilsMusic` described below.
Class description:
Utilities for the service of music.
Method signatures and docstrings:
- def search_all(self, data): Search by all items.
- def search_date(self, data): Search by date.
- def search_uuid(self, data): Search by uuid.
- def search_coming_soon(se... | cd8767b5eeaef3a09d77c936781b4126fd8591de | <|skeleton|>
class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
<|body_0|>
def search_date(self, data):
"""Search by date."""
<|body_1|>
def search_uuid(self, data):
"""Search by uuid."""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UtilsMusic:
"""Utilities for the service of music."""
def search_all(self, data):
"""Search by all items."""
try:
music = {}
music['music'] = self.manager.search(q=data['search'], limit=20, type='track')
return music
except (TypeError, KeyError,... | the_stack_v2_python_sparse | api/services/utils.py | ignite7/backproject | train | 0 |
35e7c37f6977f737d94941c1717c7b302b5feb4f | [
"self.SetStartDate(2004, 1, 1)\nself.SetEndDate(2015, 1, 1)\nself.symbol = self.AddSecurity(SecurityType.Equity, 'SPY', Resolution.Daily).Symbol\nself.macd = self.MACD(self.symbol, self.FastEmaPeriod, self.SlowEmaPeriod, 9, MovingAverageType.Exponential, Resolution.Daily)",
"if not self.macd.IsReady or not data.C... | <|body_start_0|>
self.SetStartDate(2004, 1, 1)
self.SetEndDate(2015, 1, 1)
self.symbol = self.AddSecurity(SecurityType.Equity, 'SPY', Resolution.Daily).Symbol
self.macd = self.MACD(self.symbol, self.FastEmaPeriod, self.SlowEmaPeriod, 9, MovingAverageType.Exponential, Resolution.Daily)
<|... | Demonstration algorithm showing how to easily convert an old algorithm into the framework. | ConvertToFrameworkAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertToFrameworkAlgorithm:
"""Demonstration algorithm showing how to easily convert an old algorithm into the framework."""
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initiali... | stack_v2_sparse_classes_36k_train_004716 | 4,564 | permissive | [
{
"docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "OnData event is the primary entry point for your algorithm. Eac... | 2 | null | Implement the Python class `ConvertToFrameworkAlgorithm` described below.
Class description:
Demonstration algorithm showing how to easily convert an old algorithm into the framework.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and start-e... | Implement the Python class `ConvertToFrameworkAlgorithm` described below.
Class description:
Demonstration algorithm showing how to easily convert an old algorithm into the framework.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the cash and start-e... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class ConvertToFrameworkAlgorithm:
"""Demonstration algorithm showing how to easily convert an old algorithm into the framework."""
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initiali... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertToFrameworkAlgorithm:
"""Demonstration algorithm showing how to easily convert an old algorithm into the framework."""
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
... | the_stack_v2_python_sparse | Algorithm.Python/ConvertToFrameworkAlgorithm.py | Capnode/Algoloop | train | 87 |
2e1fd26f62781ba9df41587ee8cbae5e72f487e1 | [
"if t == MOUSE:\n return [(m, p, 3 - t) for p in graph[c] if p != 0]\nelif t == CAT:\n return [(p, c, 3 - t) for p in graph[m] if p != 0]",
"childrenCount = {}\nfor m in range(len(graph)):\n for c in range(len(graph)):\n childrenCount[m, c, MOUSE] = len(graph[m])\n childrenCount[m, c, CAT] ... | <|body_start_0|>
if t == MOUSE:
return [(m, p, 3 - t) for p in graph[c] if p != 0]
elif t == CAT:
return [(p, c, 3 - t) for p in graph[m] if p != 0]
<|end_body_0|>
<|body_start_1|>
childrenCount = {}
for m in range(len(graph)):
for c in range(len(grap... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getParents(self, graph, m, c, t):
"""get parent states of (m, c, t)"""
<|body_0|>
def catMouseGame(self, graph):
"""Let (m,c,t) be the state of the game. m is the mouse location, c is cat location, t is 1 means it's mouse's turn, t is 2 means it's cat' ... | stack_v2_sparse_classes_36k_train_004717 | 4,078 | no_license | [
{
"docstring": "get parent states of (m, c, t)",
"name": "getParents",
"signature": "def getParents(self, graph, m, c, t)"
},
{
"docstring": "Let (m,c,t) be the state of the game. m is the mouse location, c is cat location, t is 1 means it's mouse's turn, t is 2 means it's cat' turn. Then the al... | 2 | stack_v2_sparse_classes_30k_train_016241 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getParents(self, graph, m, c, t): get parent states of (m, c, t)
- def catMouseGame(self, graph): Let (m,c,t) be the state of the game. m is the mouse location, c is cat loca... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getParents(self, graph, m, c, t): get parent states of (m, c, t)
- def catMouseGame(self, graph): Let (m,c,t) be the state of the game. m is the mouse location, c is cat loca... | ad2f5bd0aec3d2c2c77b7c18627c1dd8fe8c0653 | <|skeleton|>
class Solution:
def getParents(self, graph, m, c, t):
"""get parent states of (m, c, t)"""
<|body_0|>
def catMouseGame(self, graph):
"""Let (m,c,t) be the state of the game. m is the mouse location, c is cat location, t is 1 means it's mouse's turn, t is 2 means it's cat' ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getParents(self, graph, m, c, t):
"""get parent states of (m, c, t)"""
if t == MOUSE:
return [(m, p, 3 - t) for p in graph[c] if p != 0]
elif t == CAT:
return [(p, c, 3 - t) for p in graph[m] if p != 0]
def catMouseGame(self, graph):
"... | the_stack_v2_python_sparse | 913 Cat and Mouse.py | jz33/LeetCodeSolutions | train | 8 | |
a552a58f10b432411abec7012eba9003a34930ad | [
"paddle.set_default_dtype(np.float64)\nsuper(Conv2DNet, self).__init__()\nself._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=paddle.nn.initializer.Constant(val... | <|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', weight_attr=paddle.nn.initializer.Constant(value=0.5), bias_attr=... | model | Conv2DNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
sel... | stack_v2_sparse_classes_36k_train_004718 | 1,731 | no_license | [
{
"docstring": "__init__",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_011340 | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward | Implement the Python class `Conv2DNet` described below.
Class description:
model
Method signatures and docstrings:
- def __init__(self): __init__
- def forward(self, inputs): forward
<|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
<|body_0|>
def forward(self, inputs):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Conv2DNet:
"""model"""
def __init__(self):
"""__init__"""
paddle.set_default_dtype(np.float64)
super(Conv2DNet, self).__init__()
self._conv1 = paddle.nn.Conv2D(in_channels=3, out_channels=10, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, padding_mode='zeros', w... | the_stack_v2_python_sparse | framework/api/optimizer/conv2d_dygraph_model.py | PaddlePaddle/PaddleTest | train | 42 |
136179789a29ac14403dc31ad56dfe9f1db9e318 | [
"try:\n from avx_commons import get_db_credentials\n self.hostname = socket.gethostbyname(socket.gethostname())\n self.db_username, self.db_password, self.db_name = get_db_credentials()\n self.db_ip = db_ip\n self.db_port = db_port\n self.path = path\nexcept Exception as e:\n print(colored(e, '... | <|body_start_0|>
try:
from avx_commons import get_db_credentials
self.hostname = socket.gethostbyname(socket.gethostname())
self.db_username, self.db_password, self.db_name = get_db_credentials()
self.db_ip = db_ip
self.db_port = db_port
se... | . | PushLB | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PushLB:
"""."""
def __init__(self, path, db_ip, db_port):
"""."""
<|body_0|>
def generate_load_balancer():
"""."""
<|body_1|>
def push_load_balancer(self):
"""."""
<|body_2|>
def initialize(self):
"""."""
<|body_3... | stack_v2_sparse_classes_36k_train_004719 | 4,027 | no_license | [
{
"docstring": ".",
"name": "__init__",
"signature": "def __init__(self, path, db_ip, db_port)"
},
{
"docstring": ".",
"name": "generate_load_balancer",
"signature": "def generate_load_balancer()"
},
{
"docstring": ".",
"name": "push_load_balancer",
"signature": "def push... | 4 | stack_v2_sparse_classes_30k_test_001010 | Implement the Python class `PushLB` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, path, db_ip, db_port): .
- def generate_load_balancer(): .
- def push_load_balancer(self): .
- def initialize(self): . | Implement the Python class `PushLB` described below.
Class description:
.
Method signatures and docstrings:
- def __init__(self, path, db_ip, db_port): .
- def generate_load_balancer(): .
- def push_load_balancer(self): .
- def initialize(self): .
<|skeleton|>
class PushLB:
"""."""
def __init__(self, path, ... | e513224364dce05ea4d17ac25ecfa981238b1311 | <|skeleton|>
class PushLB:
"""."""
def __init__(self, path, db_ip, db_port):
"""."""
<|body_0|>
def generate_load_balancer():
"""."""
<|body_1|>
def push_load_balancer(self):
"""."""
<|body_2|>
def initialize(self):
"""."""
<|body_3... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PushLB:
"""."""
def __init__(self, path, db_ip, db_port):
"""."""
try:
from avx_commons import get_db_credentials
self.hostname = socket.gethostbyname(socket.gethostname())
self.db_username, self.db_password, self.db_name = get_db_credentials()
... | the_stack_v2_python_sparse | scripts_avx/scripts/scripts/Commons/push_lb.py | Poonammahunta/Integration | train | 0 |
ec57b1942cf7be4f81fcb36c4482425f3d2c6810 | [
"dataset_ref = URIRef(dataset_uri(dataset_dict))\nfor profile_class in self._profiles:\n profile = profile_class(self.g, self.compatibility_mode)\n profile.graph_from_dataset(dataset_dict, dataset_ref)\nreturn dataset_ref",
"catalog_ref = self.graph_from_catalog(catalog_dict)\nif dataset_dicts:\n for dat... | <|body_start_0|>
dataset_ref = URIRef(dataset_uri(dataset_dict))
for profile_class in self._profiles:
profile = profile_class(self.g, self.compatibility_mode)
profile.graph_from_dataset(dataset_dict, dataset_ref)
return dataset_ref
<|end_body_0|>
<|body_start_1|>
... | A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph. | AvoindataSerializer | [
"MIT",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvoindataSerializer:
"""A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph."""
def graph_from_dataset(self, dataset_dict):
"""Given a CKAN dataset dict, creates a graph using the loaded profiles The class RDFLib gr... | stack_v2_sparse_classes_36k_train_004720 | 30,860 | permissive | [
{
"docstring": "Given a CKAN dataset dict, creates a graph using the loaded profiles The class RDFLib graph (accessible via `serializer.g`) will be updated by the loaded profiles. Returns the reference to the dataset, which will be an rdflib URIRef.",
"name": "graph_from_dataset",
"signature": "def grap... | 2 | stack_v2_sparse_classes_30k_train_018061 | Implement the Python class `AvoindataSerializer` described below.
Class description:
A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph.
Method signatures and docstrings:
- def graph_from_dataset(self, dataset_dict): Given a CKAN dataset dict, crea... | Implement the Python class `AvoindataSerializer` described below.
Class description:
A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph.
Method signatures and docstrings:
- def graph_from_dataset(self, dataset_dict): Given a CKAN dataset dict, crea... | 8be356138044317a4c7e79f96d8ebc12d1d0a834 | <|skeleton|>
class AvoindataSerializer:
"""A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph."""
def graph_from_dataset(self, dataset_dict):
"""Given a CKAN dataset dict, creates a graph using the loaded profiles The class RDFLib gr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvoindataSerializer:
"""A CKAN to RDF serializer based on rdflib Supports different profiles which are the ones that will generate the RDF graph."""
def graph_from_dataset(self, dataset_dict):
"""Given a CKAN dataset dict, creates a graph using the loaded profiles The class RDFLib graph (accessib... | the_stack_v2_python_sparse | ckan/ckanext/ckanext-ytp_main/ckanext/ytp/dcat.py | vrk-kpa/opendata | train | 22 |
fa2b1af3fcce560759b11433fa2089adb8f47ccf | [
"sync_info = None\ntry:\n sync_info = self.last()\nexcept SyncInfo.DoesNotExist:\n pass\nexcept SyncInfo.MultipleObjectsReturned:\n pass\nif sync_info:\n return (sync_info.add_date, sync_info.bck_name)\nelse:\n return sync_info",
"sync_info = None\ntry:\n sync_info = self.get(pkg_name=pkg_name)\... | <|body_start_0|>
sync_info = None
try:
sync_info = self.last()
except SyncInfo.DoesNotExist:
pass
except SyncInfo.MultipleObjectsReturned:
pass
if sync_info:
return (sync_info.add_date, sync_info.bck_name)
else:
... | 更新记录信息. | DataManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataManager:
"""更新记录信息."""
def get_latest_datetime(self):
"""获取最后更新记录项."""
<|body_0|>
def get_pkg_name(self, pkg_name):
"""获取更新记录信息项. :param pkg_name: 更新包"""
<|body_1|>
def sync_info_exists(self, pkg_name):
"""判断更新记录是否存在. :param pkg_name: 更新包... | stack_v2_sparse_classes_36k_train_004721 | 2,795 | no_license | [
{
"docstring": "获取最后更新记录项.",
"name": "get_latest_datetime",
"signature": "def get_latest_datetime(self)"
},
{
"docstring": "获取更新记录信息项. :param pkg_name: 更新包",
"name": "get_pkg_name",
"signature": "def get_pkg_name(self, pkg_name)"
},
{
"docstring": "判断更新记录是否存在. :param pkg_name: 更新... | 4 | stack_v2_sparse_classes_30k_train_014078 | Implement the Python class `DataManager` described below.
Class description:
更新记录信息.
Method signatures and docstrings:
- def get_latest_datetime(self): 获取最后更新记录项.
- def get_pkg_name(self, pkg_name): 获取更新记录信息项. :param pkg_name: 更新包
- def sync_info_exists(self, pkg_name): 判断更新记录是否存在. :param pkg_name: 更新包
- def create_s... | Implement the Python class `DataManager` described below.
Class description:
更新记录信息.
Method signatures and docstrings:
- def get_latest_datetime(self): 获取最后更新记录项.
- def get_pkg_name(self, pkg_name): 获取更新记录信息项. :param pkg_name: 更新包
- def sync_info_exists(self, pkg_name): 判断更新记录是否存在. :param pkg_name: 更新包
- def create_s... | b7ecd2755853ffd536b9861ad7aa0e7df0f472e4 | <|skeleton|>
class DataManager:
"""更新记录信息."""
def get_latest_datetime(self):
"""获取最后更新记录项."""
<|body_0|>
def get_pkg_name(self, pkg_name):
"""获取更新记录信息项. :param pkg_name: 更新包"""
<|body_1|>
def sync_info_exists(self, pkg_name):
"""判断更新记录是否存在. :param pkg_name: 更新包... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataManager:
"""更新记录信息."""
def get_latest_datetime(self):
"""获取最后更新记录项."""
sync_info = None
try:
sync_info = self.last()
except SyncInfo.DoesNotExist:
pass
except SyncInfo.MultipleObjectsReturned:
pass
if sync_info:
... | the_stack_v2_python_sparse | sync_deploy/models.py | kydragon/sync-deploy | train | 0 |
1e9265aeb881ff02b9d5435fff1c45af5f9b0a99 | [
"context = super(GroupDeleteView, self).get_context_data(**kwargs)\ncontext['group'] = get_object_or_404(Group, pk=self.kwargs['pk'])\nreturn context",
"form.group = get_object_or_404(Group, pk=self.kwargs['pk'])\nresult = form.save()\nif result:\n messages.info(self.request, u'The group has not been deleted.'... | <|body_start_0|>
context = super(GroupDeleteView, self).get_context_data(**kwargs)
context['group'] = get_object_or_404(Group, pk=self.kwargs['pk'])
return context
<|end_body_0|>
<|body_start_1|>
form.group = get_object_or_404(Group, pk=self.kwargs['pk'])
result = form.save()
... | View for "deleting" a group. | GroupDeleteView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupDeleteView:
"""View for "deleting" a group."""
def get_context_data(self, **kwargs):
"""Add the group to the context."""
<|body_0|>
def form_valid(self, form):
"""Delete the group."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
context = s... | stack_v2_sparse_classes_36k_train_004722 | 19,778 | permissive | [
{
"docstring": "Add the group to the context.",
"name": "get_context_data",
"signature": "def get_context_data(self, **kwargs)"
},
{
"docstring": "Delete the group.",
"name": "form_valid",
"signature": "def form_valid(self, form)"
}
] | 2 | stack_v2_sparse_classes_30k_train_009305 | Implement the Python class `GroupDeleteView` described below.
Class description:
View for "deleting" a group.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add the group to the context.
- def form_valid(self, form): Delete the group. | Implement the Python class `GroupDeleteView` described below.
Class description:
View for "deleting" a group.
Method signatures and docstrings:
- def get_context_data(self, **kwargs): Add the group to the context.
- def form_valid(self, form): Delete the group.
<|skeleton|>
class GroupDeleteView:
"""View for "de... | a56c0f89df82694bf5db32a04d8b092974791972 | <|skeleton|>
class GroupDeleteView:
"""View for "deleting" a group."""
def get_context_data(self, **kwargs):
"""Add the group to the context."""
<|body_0|>
def form_valid(self, form):
"""Delete the group."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupDeleteView:
"""View for "deleting" a group."""
def get_context_data(self, **kwargs):
"""Add the group to the context."""
context = super(GroupDeleteView, self).get_context_data(**kwargs)
context['group'] = get_object_or_404(Group, pk=self.kwargs['pk'])
return context
... | the_stack_v2_python_sparse | open_connect/groups/views.py | ofa/connect | train | 66 |
116efe256c023310045547517a119a5d8f702552 | [
"self.name = name\nself.hparams = hparams\nself.verbose = getattr(self.hparams, 'verbose', True)\nself.noise_std = getattr(self.hparams, 'noise_std', 0.005)\nself.eps = getattr(self.hparams, 'eps', 0.05)\nself.d_samples = getattr(self.hparams, 'd_samples', 300)\nself.optimizer = getattr(self.hparams, 'optimizer', '... | <|body_start_0|>
self.name = name
self.hparams = hparams
self.verbose = getattr(self.hparams, 'verbose', True)
self.noise_std = getattr(self.hparams, 'noise_std', 0.005)
self.eps = getattr(self.hparams, 'eps', 0.05)
self.d_samples = getattr(self.hparams, 'd_samples', 300)... | Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905 | ParameterNoiseSampling | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParameterNoiseSampling:
"""Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905"""
def __init__(self, name, hparams):
"""Creates the algorithm, and sets up the adaptive Gaussian noise."""
<|body_0|>
def act... | stack_v2_sparse_classes_36k_train_004723 | 6,687 | permissive | [
{
"docstring": "Creates the algorithm, and sets up the adaptive Gaussian noise.",
"name": "__init__",
"signature": "def __init__(self, name, hparams)"
},
{
"docstring": "Selects action based on Thompson Sampling *after* adding noise.",
"name": "action",
"signature": "def action(self, con... | 6 | stack_v2_sparse_classes_30k_train_004037 | Implement the Python class `ParameterNoiseSampling` described below.
Class description:
Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905
Method signatures and docstrings:
- def __init__(self, name, hparams): Creates the algorithm, and sets up the ad... | Implement the Python class `ParameterNoiseSampling` described below.
Class description:
Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905
Method signatures and docstrings:
- def __init__(self, name, hparams): Creates the algorithm, and sets up the ad... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class ParameterNoiseSampling:
"""Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905"""
def __init__(self, name, hparams):
"""Creates the algorithm, and sets up the adaptive Gaussian noise."""
<|body_0|>
def act... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParameterNoiseSampling:
"""Parameter Noise Sampling algorithm based on adding noise to net params. Described in https://arxiv.org/abs/1706.01905"""
def __init__(self, name, hparams):
"""Creates the algorithm, and sets up the adaptive Gaussian noise."""
self.name = name
self.hparam... | the_stack_v2_python_sparse | models/research/deep_contextual_bandits/bandits/algorithms/parameter_noise_sampling.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
60f954efedb1dd54294da547e9250bff7f7377b9 | [
"def postorder(root):\n return [root.val] + postorder(root.left) + postorder(root.right) if root else ['#']\nreturn ' '.join(map(str, postorder(root)))",
"d = iter(data.split())\n\ndef helper():\n tmp = next(d)\n if tmp == '#':\n return\n node = TreeNode(int(tmp))\n node.left = helper()\n ... | <|body_start_0|>
def postorder(root):
return [root.val] + postorder(root.left) + postorder(root.right) if root else ['#']
return ' '.join(map(str, postorder(root)))
<|end_body_0|>
<|body_start_1|>
d = iter(data.split())
def helper():
tmp = next(d)
if... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_004724 | 2,111 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 6387d05b619d403414bad273fc3a7a2c58668db7 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def postorder(root):
return [root.val] + postorder(root.left) + postorder(root.right) if root else ['#']
return ' '.join(map(str, postorder(root)))
def deseriali... | the_stack_v2_python_sparse | Python3/0297. Serialize and Deserialize Binary Tree.py | yang4978/LeetCode | train | 0 | |
0782d804c865c6b451f993683f102d738a2a5485 | [
"self.logger = get_logger(name='OutputFilter')\nself.data = copy.deepcopy(data)\nself.required = None\nself.excluded = None\nif isinstance(required, list):\n self.required = required\nelse:\n self.required = []\n self.logger.error(msg='Required is not a list!')\nif isinstance(excluded, list):\n self.exc... | <|body_start_0|>
self.logger = get_logger(name='OutputFilter')
self.data = copy.deepcopy(data)
self.required = None
self.excluded = None
if isinstance(required, list):
self.required = required
else:
self.required = []
self.logger.error(... | This class helps to minimize dictionary structure by specifying only the desired keys. | OutputFilter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OutputFilter:
"""This class helps to minimize dictionary structure by specifying only the desired keys."""
def __init__(self, data=None, required=[], excluded=[]):
""":param data: Data to be filtered. :param list required: List of required keys. Returned entries will contain only the... | stack_v2_sparse_classes_36k_train_004725 | 13,875 | permissive | [
{
"docstring": ":param data: Data to be filtered. :param list required: List of required keys. Returned entries will contain only these specified keys. Example: `{\"key1\": \"value1\", \"key2\": \"value2\"}` with ``required`` `[\"key1\"]` will only return `{\"key1\": \"value1\"}`. :param list excluded: List of ... | 2 | stack_v2_sparse_classes_30k_train_011992 | Implement the Python class `OutputFilter` described below.
Class description:
This class helps to minimize dictionary structure by specifying only the desired keys.
Method signatures and docstrings:
- def __init__(self, data=None, required=[], excluded=[]): :param data: Data to be filtered. :param list required: List... | Implement the Python class `OutputFilter` described below.
Class description:
This class helps to minimize dictionary structure by specifying only the desired keys.
Method signatures and docstrings:
- def __init__(self, data=None, required=[], excluded=[]): :param data: Data to be filtered. :param list required: List... | 3e050be98404dac79c071eb035d30095bda33fac | <|skeleton|>
class OutputFilter:
"""This class helps to minimize dictionary structure by specifying only the desired keys."""
def __init__(self, data=None, required=[], excluded=[]):
""":param data: Data to be filtered. :param list required: List of required keys. Returned entries will contain only the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OutputFilter:
"""This class helps to minimize dictionary structure by specifying only the desired keys."""
def __init__(self, data=None, required=[], excluded=[]):
""":param data: Data to be filtered. :param list required: List of required keys. Returned entries will contain only these specified ... | the_stack_v2_python_sparse | nuaal/utils/Filter.py | mihudec/nuaal | train | 1 |
1f7a715132c3ce306afdf0e6aaabb9cdbf759025 | [
"MyCollection(self.driver).login_into_MyCollection()\nMyCollection(self.driver).deploy_image()\npo = MyCollection(self.driver)\nself.assertEqual(po.deploy_image_success(), '创建服务')\nfunction.insert_img(self.driver, 'deploy_image.png')",
"MyCollection(self.driver).login_into_MyCollection()\nMyCollection(self.driver... | <|body_start_0|>
MyCollection(self.driver).login_into_MyCollection()
MyCollection(self.driver).deploy_image()
po = MyCollection(self.driver)
self.assertEqual(po.deploy_image_success(), '创建服务')
function.insert_img(self.driver, 'deploy_image.png')
<|end_body_0|>
<|body_start_1|>
... | 我的收藏界面测试 | MyCollectionTst | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyCollectionTst:
"""我的收藏界面测试"""
def test_1_deploy_image_my(self):
"""我的收藏-部署服务测试"""
<|body_0|>
def test_2_export_image_my(self):
"""我的收藏-导出镜像测试"""
<|body_1|>
def test_3_collect_image_my(self):
"""我的收藏-收藏镜像测试"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k_train_004726 | 1,404 | no_license | [
{
"docstring": "我的收藏-部署服务测试",
"name": "test_1_deploy_image_my",
"signature": "def test_1_deploy_image_my(self)"
},
{
"docstring": "我的收藏-导出镜像测试",
"name": "test_2_export_image_my",
"signature": "def test_2_export_image_my(self)"
},
{
"docstring": "我的收藏-收藏镜像测试",
"name": "test_3_... | 3 | stack_v2_sparse_classes_30k_train_000410 | Implement the Python class `MyCollectionTst` described below.
Class description:
我的收藏界面测试
Method signatures and docstrings:
- def test_1_deploy_image_my(self): 我的收藏-部署服务测试
- def test_2_export_image_my(self): 我的收藏-导出镜像测试
- def test_3_collect_image_my(self): 我的收藏-收藏镜像测试 | Implement the Python class `MyCollectionTst` described below.
Class description:
我的收藏界面测试
Method signatures and docstrings:
- def test_1_deploy_image_my(self): 我的收藏-部署服务测试
- def test_2_export_image_my(self): 我的收藏-导出镜像测试
- def test_3_collect_image_my(self): 我的收藏-收藏镜像测试
<|skeleton|>
class MyCollectionTst:
"""我的收藏界... | dbd8aab0e0c479afd41f911198c4409d423e15f2 | <|skeleton|>
class MyCollectionTst:
"""我的收藏界面测试"""
def test_1_deploy_image_my(self):
"""我的收藏-部署服务测试"""
<|body_0|>
def test_2_export_image_my(self):
"""我的收藏-导出镜像测试"""
<|body_1|>
def test_3_collect_image_my(self):
"""我的收藏-收藏镜像测试"""
<|body_2|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyCollectionTst:
"""我的收藏界面测试"""
def test_1_deploy_image_my(self):
"""我的收藏-部署服务测试"""
MyCollection(self.driver).login_into_MyCollection()
MyCollection(self.driver).deploy_image()
po = MyCollection(self.driver)
self.assertEqual(po.deploy_image_success(), '创建服务')
... | the_stack_v2_python_sparse | bcm/testcase/mycollectionpage_sttta.py | xiaohuang0807/auto | train | 0 |
32bda878a583d63a656ac0de55bf366e69b8e487 | [
"self.__charWindowSize = charWindowSize\nself.__charWindow = Window(lexicon, charWindowSize, startPadding, endPadding)\nself.__wordWindow = Window(lexicon, wrdWindowSize, startPaddingWrd, endPaddingWrd)\nself.__lexicon = lexicon\nself.__numMaxChar = numMaxChar\nself.__wrdWindowSize = wrdWindowSize\nself.__filters =... | <|body_start_0|>
self.__charWindowSize = charWindowSize
self.__charWindow = Window(lexicon, charWindowSize, startPadding, endPadding)
self.__wordWindow = Window(lexicon, wrdWindowSize, startPaddingWrd, endPaddingWrd)
self.__lexicon = lexicon
self.__numMaxChar = numMaxChar
... | Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMaxChar characters, then it will be filled with an arti... | CharacterWindowGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMax... | stack_v2_sparse_classes_36k_train_004727 | 3,762 | no_license | [
{
"docstring": "Create a character window feature generator. TODO: Irving, comentar cada parâmetro. :param lexicon: :param numMaxChar: :param charWindowSize: :param wrdWindowSize: :param artificialChar: :param startPadding: :param endPadding: :param startPaddingWrd: :param endPaddingWrd: :param filters:",
"... | 2 | null | Implement the Python class `CharacterWindowGenerator` described below.
Class description:
Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numM... | Implement the Python class `CharacterWindowGenerator` described below.
Class description:
Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numM... | c2b6d502790fb1b15eee41b32636bd0a55ab3de2 | <|skeleton|>
class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMax... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CharacterWindowGenerator:
"""Generate sequences of character windows for a given sequence of words. For each word in the given sequence, a sequence of character windows will be generated. This class considers that words has the same number of character (numMaxChar). If a word has less than numMaxChar characte... | the_stack_v2_python_sparse | data/CharacterWindowGenerator.py | eraldoluis/lia-pln-deeplearning | train | 5 |
61823d4cde6ef8822f6c05a6de7a49f431b583b9 | [
"cursor = chars[0]\nmaxlen = 1\nn = len(chars)\nfor i in range(1, n):\n if chars[i] == cursor:\n maxlen += 1\n else:\n if maxlen > 1:\n chars.append(cursor)\n chars += list(str(maxlen))\n else:\n chars.append(cursor)\n cursor = chars[i]\n max... | <|body_start_0|>
cursor = chars[0]
maxlen = 1
n = len(chars)
for i in range(1, n):
if chars[i] == cursor:
maxlen += 1
else:
if maxlen > 1:
chars.append(cursor)
chars += list(str(maxlen))
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_0|>
def compress2(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
cursor = chars[0]
maxlen = 1
n... | stack_v2_sparse_classes_36k_train_004728 | 1,502 | no_license | [
{
"docstring": ":type chars: List[str] :rtype: int",
"name": "compress",
"signature": "def compress(self, chars)"
},
{
"docstring": ":type chars: List[str] :rtype: int",
"name": "compress2",
"signature": "def compress2(self, chars)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int
- def compress2(self, chars): :type chars: List[str] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def compress(self, chars): :type chars: List[str] :rtype: int
- def compress2(self, chars): :type chars: List[str] :rtype: int
<|skeleton|>
class Solution:
def compress(sel... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_0|>
def compress2(self, chars):
""":type chars: List[str] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def compress(self, chars):
""":type chars: List[str] :rtype: int"""
cursor = chars[0]
maxlen = 1
n = len(chars)
for i in range(1, n):
if chars[i] == cursor:
maxlen += 1
else:
if maxlen > 1:
... | the_stack_v2_python_sparse | 443. String Compression/compress.py | Macielyoung/LeetCode | train | 1 | |
706ef83f8504f257c5a7d287bf342f597038bd88 | [
"for name, infos in geom_dict.items():\n if name in optim_var_dict:\n self.add_input(name, val=infos[1][0])",
"cpacs_path = mif.get_tooloutput_file_path(Rt.modules[-1])\ncpacs_path_out = mif.get_toolinput_file_path(Rt.modules[0])\nfor name, infos in geom_dict.items():\n infos[1].append(inputs[name][0... | <|body_start_0|>
for name, infos in geom_dict.items():
if name in optim_var_dict:
self.add_input(name, val=infos[1][0])
<|end_body_0|>
<|body_start_1|>
cpacs_path = mif.get_tooloutput_file_path(Rt.modules[-1])
cpacs_path_out = mif.get_toolinput_file_path(Rt.modules[0... | Classe to define the geometric parameters | Geom_param | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
<|body_0|>
def compute(self, inputs, outputs):
"""Update the geometry of the CPACS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004729 | 21,151 | permissive | [
{
"docstring": "Setup inputs only for the geometry",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "Update the geometry of the CPACS",
"name": "compute",
"signature": "def compute(self, inputs, outputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008073 | Implement the Python class `Geom_param` described below.
Class description:
Classe to define the geometric parameters
Method signatures and docstrings:
- def setup(self): Setup inputs only for the geometry
- def compute(self, inputs, outputs): Update the geometry of the CPACS | Implement the Python class `Geom_param` described below.
Class description:
Classe to define the geometric parameters
Method signatures and docstrings:
- def setup(self): Setup inputs only for the geometry
- def compute(self, inputs, outputs): Update the geometry of the CPACS
<|skeleton|>
class Geom_param:
"""Cl... | 3cc211507caab176a76213e442238abfa43afa42 | <|skeleton|>
class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
<|body_0|>
def compute(self, inputs, outputs):
"""Update the geometry of the CPACS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Geom_param:
"""Classe to define the geometric parameters"""
def setup(self):
"""Setup inputs only for the geometry"""
for name, infos in geom_dict.items():
if name in optim_var_dict:
self.add_input(name, val=infos[1][0])
def compute(self, inputs, outputs):... | the_stack_v2_python_sparse | ceasiompy/Optimisation/optimisation.py | schneo/CEASIOMpy | train | 0 |
3e5f1255c2276781a1a4f553bef9fa53919a388e | [
"s, i, r = xs\nif isinstance(parameters, Parameters):\n beta = parameters['beta'].value\n gamma = parameters['gamma'].value\n N = parameters['N'].value\nelif isinstance(parameters, tuple):\n beta, gamma, N = parameters\nelse:\n raise ValueError('Cannot recognize parameter input')\ndSdt = -beta * s * ... | <|body_start_0|>
s, i, r = xs
if isinstance(parameters, Parameters):
beta = parameters['beta'].value
gamma = parameters['gamma'].value
N = parameters['N'].value
elif isinstance(parameters, tuple):
beta, gamma, N = parameters
else:
... | SIR Model | SIR | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SIR:
"""SIR Model"""
def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple:
"""SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :param... | stack_v2_sparse_classes_36k_train_004730 | 29,649 | permissive | [
{
"docstring": "SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :param parameters: parameters of the model (not including initial conditions), i.e. beta, gamma, N :return: tuple, the derivatives... | 2 | null | Implement the Python class `SIR` described below.
Class description:
SIR Model
Method signatures and docstrings:
- def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved... | Implement the Python class `SIR` described below.
Class description:
SIR Model
Method signatures and docstrings:
- def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple: SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved... | 4cf8ec75c4d85b16ec08371c46cc1a9ede9d72a2 | <|skeleton|>
class SIR:
"""SIR Model"""
def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple:
"""SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SIR:
"""SIR Model"""
def calibrate(cls, xs: tuple, t: float, parameters: Union[Parameters, tuple]) -> tuple:
"""SIR model derivatives at t. :param xs: variables that we are solving for, i.e. [S]usceptible, [I]nfected, [R]emoved :param t: time parameter, inactive for this model :param parameters: ... | the_stack_v2_python_sparse | gs_quant/models/epidemiology.py | goldmansachs/gs-quant | train | 2,088 |
e4544ec01a76785a5314c463637244b3673b1805 | [
"if isinstance(single_value, (int, float)):\n category = StatCategory.TIME_SERIES\n single_value = SingleValue().name(name).value(single_value).mode(category)\n return (single_value, category)\nelse:\n raise MLOpsStatisticsException('For outputting {}, {} should be of type numeric but got {}.'.format(na... | <|body_start_0|>
if isinstance(single_value, (int, float)):
category = StatCategory.TIME_SERIES
single_value = SingleValue().name(name).value(single_value).mode(category)
return (single_value, category)
else:
raise MLOpsStatisticsException('For outputting ... | MLStatObjectCreator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MLStatObjectCreator:
def get_single_value_stat_object(name, single_value):
"""Create Single Value stat object from numerical value :param name: Name of stat :param single_value: single numeric value :return: MLOps Single Value object, time series category"""
<|body_0|>
def g... | stack_v2_sparse_classes_36k_train_004731 | 5,437 | permissive | [
{
"docstring": "Create Single Value stat object from numerical value :param name: Name of stat :param single_value: single numeric value :return: MLOps Single Value object, time series category",
"name": "get_single_value_stat_object",
"signature": "def get_single_value_stat_object(name, single_value)"
... | 4 | null | Implement the Python class `MLStatObjectCreator` described below.
Class description:
Implement the MLStatObjectCreator class.
Method signatures and docstrings:
- def get_single_value_stat_object(name, single_value): Create Single Value stat object from numerical value :param name: Name of stat :param single_value: si... | Implement the Python class `MLStatObjectCreator` described below.
Class description:
Implement the MLStatObjectCreator class.
Method signatures and docstrings:
- def get_single_value_stat_object(name, single_value): Create Single Value stat object from numerical value :param name: Name of stat :param single_value: si... | 0fd2b6773f970c831038db47bf4920ada21a5f51 | <|skeleton|>
class MLStatObjectCreator:
def get_single_value_stat_object(name, single_value):
"""Create Single Value stat object from numerical value :param name: Name of stat :param single_value: single numeric value :return: MLOps Single Value object, time series category"""
<|body_0|>
def g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MLStatObjectCreator:
def get_single_value_stat_object(name, single_value):
"""Create Single Value stat object from numerical value :param name: Name of stat :param single_value: single numeric value :return: MLOps Single Value object, time series category"""
if isinstance(single_value, (int, f... | the_stack_v2_python_sparse | mlops/parallelm/mlops/ml_metrics_stat/ml_stat_object_creator.py | jialeiwang/mlpiper | train | 0 | |
49eeec3ea05a3b9008f498a79393de0afc5fc988 | [
"if not pHead:\n return\nslow = pHead.next\nif not slow:\n return\nfast = slow.next\nwhile fast and slow:\n if fast == slow:\n return fast\n slow = slow.next\n fast = fast.next\n if fast:\n fast = fast.next\nreturn None",
"meetingNode = self.MeetingNode(pHead)\nif not meetingNode:\... | <|body_start_0|>
if not pHead:
return
slow = pHead.next
if not slow:
return
fast = slow.next
while fast and slow:
if fast == slow:
return fast
slow = slow.next
fast = fast.next
if fast:
... | 本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新设置快慢双指针:让走得快的指针先走【环中结点数】步,然后让两个指针一起走,当两个指针相遇时,就是环的入口 | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新设置快慢双指针:让走得快的指针先走【环中结点数】步,然后让两个指针一起走,当两... | stack_v2_sparse_classes_36k_train_004732 | 2,502 | no_license | [
{
"docstring": "判断链表中是否有环,如果有的话,返回某个环中结点",
"name": "MeetingNode",
"signature": "def MeetingNode(self, pHead)"
},
{
"docstring": "找出链表中环的入口结点",
"name": "EntryNodeOfLoop",
"signature": "def EntryNodeOfLoop(self, pHead)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新... | Implement the Python class `Solution` described below.
Class description:
本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新... | 746d77e9bfbcb3877fefae9a915004b3bfbcc612 | <|skeleton|>
class Solution:
"""本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新设置快慢双指针:让走得快的指针先走【环中结点数】步,然后让两个指针一起走,当两... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""本题的重点是要把【找链表中环的入口结点】问题分解成三个子问题: 1、判断一个链表中是否有环: 方法:利用快慢双指针:如果走得快的指针追上了走得慢的指针,则说明链表中有环,并且相遇的结点一定在环中 如果走的快的指针走到了链表的末尾,fast.next = None,则说明链表中没环,返回None 2、确定链表中环中结点的个数: 方法:如果链表中有环,那么快慢指针相遇的结点就是环中结点,从该节点出发,再回到该节点时,经过的就是环中所有的结点,可以计数 3、确定链表中的入口节点: 方法:重新设置快慢双指针:让走得快的指针先走【环中结点数】步,然后让两个指针一起走,当两个指针相遇时,就是环的入口... | the_stack_v2_python_sparse | 剑指offer/第一遍/linkedlist/40.链表中环的入口节点.py | leilalu/algorithm | train | 0 |
e7abb2140293b8d3923786a3e2cff139e5101e92 | [
"for row in matrix:\n for el in row:\n print(str(el).rjust(2), end=' ')\n print()",
"n, m = (len(grid), len(grid[0]))\nresults = [[0] * m for i in range(n)]\nfor j in range(m):\n if grid[0][j] == 1:\n break\n results[0][j] = 1\nfor i in range(n):\n if grid[i][0] == 1:\n break\n... | <|body_start_0|>
for row in matrix:
for el in row:
print(str(el).rjust(2), end=' ')
print()
<|end_body_0|>
<|body_start_1|>
n, m = (len(grid), len(grid[0]))
results = [[0] * m for i in range(n)]
for j in range(m):
if grid[0][j] == 1:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def display(self, matrix):
"""Prints out 2D array."""
<|body_0|>
def unique_paths_obstacles(self, grid):
"""Dynamic programming solution. Time complexity: O(m * n). Space complexity: O(m * n), where m, n are dimensions of the grid."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_004733 | 2,570 | no_license | [
{
"docstring": "Prints out 2D array.",
"name": "display",
"signature": "def display(self, matrix)"
},
{
"docstring": "Dynamic programming solution. Time complexity: O(m * n). Space complexity: O(m * n), where m, n are dimensions of the grid.",
"name": "unique_paths_obstacles",
"signature... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def display(self, matrix): Prints out 2D array.
- def unique_paths_obstacles(self, grid): Dynamic programming solution. Time complexity: O(m * n). Space complexity: O(m * n), whe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def display(self, matrix): Prints out 2D array.
- def unique_paths_obstacles(self, grid): Dynamic programming solution. Time complexity: O(m * n). Space complexity: O(m * n), whe... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def display(self, matrix):
"""Prints out 2D array."""
<|body_0|>
def unique_paths_obstacles(self, grid):
"""Dynamic programming solution. Time complexity: O(m * n). Space complexity: O(m * n), where m, n are dimensions of the grid."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def display(self, matrix):
"""Prints out 2D array."""
for row in matrix:
for el in row:
print(str(el).rjust(2), end=' ')
print()
def unique_paths_obstacles(self, grid):
"""Dynamic programming solution. Time complexity: O(m * n). Sp... | the_stack_v2_python_sparse | Dynamic_programming/unique_paths_2.py | vladn90/Algorithms | train | 0 | |
968d2d4abced6c7a9433a25f0c24d7a5b565f002 | [
"all_relevant_participants = participant_records.read_all()\nsuccess_payload = payload_formatter.construct_success_payload(status=200, method='participants.get', params={}, data=all_relevant_participants)\nlogging.info('Participants: Bulk record retrieval successful!', code=200, description='Successfully retrieved ... | <|body_start_0|>
all_relevant_participants = participant_records.read_all()
success_payload = payload_formatter.construct_success_payload(status=200, method='participants.get', params={}, data=all_relevant_participants)
logging.info('Participants: Bulk record retrieval successful!', code=200, de... | Handles the entire collection of projects as a catalogue | Participants | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Participants:
"""Handles the entire collection of projects as a catalogue"""
def get(self):
"""Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switch to toggle logs) 5) verbose (boolean switch to toggle ve... | stack_v2_sparse_classes_36k_train_004734 | 13,154 | permissive | [
{
"docstring": "Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switch to toggle logs) 5) verbose (boolean switch to toggle verbosity)",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Takes in a partic... | 2 | stack_v2_sparse_classes_30k_train_007000 | Implement the Python class `Participants` described below.
Class description:
Handles the entire collection of projects as a catalogue
Method signatures and docstrings:
- def get(self): Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switc... | Implement the Python class `Participants` described below.
Class description:
Handles the entire collection of projects as a catalogue
Method signatures and docstrings:
- def get(self): Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switc... | d7b45216e5d1854fe65213f06ae3f3bb6d99cab0 | <|skeleton|>
class Participants:
"""Handles the entire collection of projects as a catalogue"""
def get(self):
"""Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switch to toggle logs) 5) verbose (boolean switch to toggle ve... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Participants:
"""Handles the entire collection of projects as a catalogue"""
def get(self):
"""Retrieve all metadata for each registered participant. Metadata here includes: 1) Worker ID 2) IP 3) port 4) Log_msgs (boolean switch to toggle logs) 5) verbose (boolean switch to toggle verbosity)"""
... | the_stack_v2_python_sparse | rest_rpc/connection/participants.py | markchc101/synergos_rest | train | 0 |
fb9e32f2ebd28157cbbc2fbf64704c5218cc924a | [
"if not request.user.is_authenticated():\n return Response(json.dumps({'error': 'you must be logged in'}), status=status.HTTP_401_UNAUTHORIZED)\nqueryset = Match.objects.filter(Q(player_1=request.user.profile) | Q(player_2=request.user.profile))\nserializer = MatchSerializer(queryset, many=True, context={'reques... | <|body_start_0|>
if not request.user.is_authenticated():
return Response(json.dumps({'error': 'you must be logged in'}), status=status.HTTP_401_UNAUTHORIZED)
queryset = Match.objects.filter(Q(player_1=request.user.profile) | Q(player_2=request.user.profile))
serializer = MatchSeriali... | Endpoints for playing a match | MatchViewSet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatchViewSet:
"""Endpoints for playing a match"""
def list(self, request):
"""List the matches the currently logged in user is in or has participated in"""
<|body_0|>
def retrieve(self, request, uuid=None):
"""Retrieves a particular match."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_004735 | 5,972 | permissive | [
{
"docstring": "List the matches the currently logged in user is in or has participated in",
"name": "list",
"signature": "def list(self, request)"
},
{
"docstring": "Retrieves a particular match.",
"name": "retrieve",
"signature": "def retrieve(self, request, uuid=None)"
},
{
"d... | 5 | stack_v2_sparse_classes_30k_train_017416 | Implement the Python class `MatchViewSet` described below.
Class description:
Endpoints for playing a match
Method signatures and docstrings:
- def list(self, request): List the matches the currently logged in user is in or has participated in
- def retrieve(self, request, uuid=None): Retrieves a particular match.
- ... | Implement the Python class `MatchViewSet` described below.
Class description:
Endpoints for playing a match
Method signatures and docstrings:
- def list(self, request): List the matches the currently logged in user is in or has participated in
- def retrieve(self, request, uuid=None): Retrieves a particular match.
- ... | fdfe9d46693f6dd753e4289b6327f4d18da3de4f | <|skeleton|>
class MatchViewSet:
"""Endpoints for playing a match"""
def list(self, request):
"""List the matches the currently logged in user is in or has participated in"""
<|body_0|>
def retrieve(self, request, uuid=None):
"""Retrieves a particular match."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatchViewSet:
"""Endpoints for playing a match"""
def list(self, request):
"""List the matches the currently logged in user is in or has participated in"""
if not request.user.is_authenticated():
return Response(json.dumps({'error': 'you must be logged in'}), status=status.HTT... | the_stack_v2_python_sparse | matches/views.py | mc706/prog-strat-game | train | 0 |
ffb4f3cabdba3a47df764231720a678c9e55464e | [
"self.capture = None\nself.image_receivers: List[ImageReceiver] = []\nif image_receivers:\n self.image_receivers = [receiver for receiver in image_receivers]",
"while True:\n capture = cv.VideoCapture(camera_index)\n if capture.isOpened():\n self.capture = capture\n break\n logger.error(... | <|body_start_0|>
self.capture = None
self.image_receivers: List[ImageReceiver] = []
if image_receivers:
self.image_receivers = [receiver for receiver in image_receivers]
<|end_body_0|>
<|body_start_1|>
while True:
capture = cv.VideoCapture(camera_index)
... | Manages a camera. | Camera | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Camera:
"""Manages a camera."""
def __init__(self, image_receivers: Optional[_ImageReceivers]=None):
"""Initialize member variables."""
<|body_0|>
def open(self, camera_index=0):
"""Try to start a capture with the specified camera index."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_004736 | 2,809 | permissive | [
{
"docstring": "Initialize member variables.",
"name": "__init__",
"signature": "def __init__(self, image_receivers: Optional[_ImageReceivers]=None)"
},
{
"docstring": "Try to start a capture with the specified camera index.",
"name": "open",
"signature": "def open(self, camera_index=0)"... | 5 | stack_v2_sparse_classes_30k_train_015818 | Implement the Python class `Camera` described below.
Class description:
Manages a camera.
Method signatures and docstrings:
- def __init__(self, image_receivers: Optional[_ImageReceivers]=None): Initialize member variables.
- def open(self, camera_index=0): Try to start a capture with the specified camera index.
- de... | Implement the Python class `Camera` described below.
Class description:
Manages a camera.
Method signatures and docstrings:
- def __init__(self, image_receivers: Optional[_ImageReceivers]=None): Initialize member variables.
- def open(self, camera_index=0): Try to start a capture with the specified camera index.
- de... | fc7043558072e77981206ae123dfd3a24ef89029 | <|skeleton|>
class Camera:
"""Manages a camera."""
def __init__(self, image_receivers: Optional[_ImageReceivers]=None):
"""Initialize member variables."""
<|body_0|>
def open(self, camera_index=0):
"""Try to start a capture with the specified camera index."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Camera:
"""Manages a camera."""
def __init__(self, image_receivers: Optional[_ImageReceivers]=None):
"""Initialize member variables."""
self.capture = None
self.image_receivers: List[ImageReceiver] = []
if image_receivers:
self.image_receivers = [receiver for r... | the_stack_v2_python_sparse | lhrhost/imaging/webcam.py | ethanjli/liquid-handling-robotics | 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_36k_train_004737 | 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_train_000622 | 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_36k | data/stack_v2_sparse_classes_30k | 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 | |
f29c29eda999869e4cc3c536f7babec319b52be5 | [
"testcase = helpers.get_testcase(testcase_id)\nissue_id = testcase.bug_information\ntestcase.bug_information = ''\ntestcase.put()\nhelpers.log('Removed the issue %s from the testcase %s' % (issue_id, testcase.key.id()), helpers.MODIFY_OPERATION)\nreturn testcase",
"testcase_id = request.get('testcaseId')\nupdated... | <|body_start_0|>
testcase = helpers.get_testcase(testcase_id)
issue_id = testcase.bug_information
testcase.bug_information = ''
testcase.put()
helpers.log('Removed the issue %s from the testcase %s' % (issue_id, testcase.key.id()), helpers.MODIFY_OPERATION)
return testcas... | Handler that removes an issue from a testcase. | Handler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Handler:
"""Handler that removes an issue from a testcase."""
def remove_issue(testcase_id):
"""Remove the issue from the testcase."""
<|body_0|>
def post(self):
"""Remove the issue from the testcase."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004738 | 1,665 | permissive | [
{
"docstring": "Remove the issue from the testcase.",
"name": "remove_issue",
"signature": "def remove_issue(testcase_id)"
},
{
"docstring": "Remove the issue from the testcase.",
"name": "post",
"signature": "def post(self)"
}
] | 2 | null | Implement the Python class `Handler` described below.
Class description:
Handler that removes an issue from a testcase.
Method signatures and docstrings:
- def remove_issue(testcase_id): Remove the issue from the testcase.
- def post(self): Remove the issue from the testcase. | Implement the Python class `Handler` described below.
Class description:
Handler that removes an issue from a testcase.
Method signatures and docstrings:
- def remove_issue(testcase_id): Remove the issue from the testcase.
- def post(self): Remove the issue from the testcase.
<|skeleton|>
class Handler:
"""Handl... | 6501a839b27a264500244f32bace8bee4d5cb9a2 | <|skeleton|>
class Handler:
"""Handler that removes an issue from a testcase."""
def remove_issue(testcase_id):
"""Remove the issue from the testcase."""
<|body_0|>
def post(self):
"""Remove the issue from the testcase."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Handler:
"""Handler that removes an issue from a testcase."""
def remove_issue(testcase_id):
"""Remove the issue from the testcase."""
testcase = helpers.get_testcase(testcase_id)
issue_id = testcase.bug_information
testcase.bug_information = ''
testcase.put()
... | the_stack_v2_python_sparse | src/appengine/handlers/testcase_detail/remove_issue.py | google/clusterfuzz | train | 5,420 |
0cf74fe152a4cf94f4f22190dd45c879a96611e3 | [
"if isinstance(start_date, str):\n start_date = parser.parse(start_date).date()\nif isinstance(end_date, str):\n end_date = parser.parse(end_date).date()\ncluster_id = get_cluster_id_from_provider(openshift_provider_uuid)\nwith OCPReportDBAccessor(self._schema) as accessor:\n report_period = accessor.repor... | <|body_start_0|>
if isinstance(start_date, str):
start_date = parser.parse(start_date).date()
if isinstance(end_date, str):
end_date = parser.parse(end_date).date()
cluster_id = get_cluster_id_from_provider(openshift_provider_uuid)
with OCPReportDBAccessor(self._s... | Class to update OCP report summary data. | OCPCloudParquetReportSummaryUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPCloudParquetReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date):
"""Update operations specifically for OpenShift on AWS."""
<|body_0|>
def update_azu... | stack_v2_sparse_classes_36k_train_004739 | 7,056 | permissive | [
{
"docstring": "Update operations specifically for OpenShift on AWS.",
"name": "update_aws_summary_tables",
"signature": "def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date)"
},
{
"docstring": "Update operations specifically for OpenShift on Azur... | 2 | stack_v2_sparse_classes_30k_train_019247 | Implement the Python class `OCPCloudParquetReportSummaryUpdater` described below.
Class description:
Class to update OCP report summary data.
Method signatures and docstrings:
- def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): Update operations specifically for Op... | Implement the Python class `OCPCloudParquetReportSummaryUpdater` described below.
Class description:
Class to update OCP report summary data.
Method signatures and docstrings:
- def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date): Update operations specifically for Op... | 88e2d679148d0e4735c5018faada638f73d4dc5c | <|skeleton|>
class OCPCloudParquetReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date):
"""Update operations specifically for OpenShift on AWS."""
<|body_0|>
def update_azu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OCPCloudParquetReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_aws_summary_tables(self, openshift_provider_uuid, aws_provider_uuid, start_date, end_date):
"""Update operations specifically for OpenShift on AWS."""
if isinstance(start_date, str):
... | the_stack_v2_python_sparse | koku/masu/processor/ocp/ocp_cloud_parquet_summary_updater.py | pavanyadavalli/koku | train | 2 |
0f9244d00e04275cfad90becf80c7928b50a756e | [
"super().__init__(db_file_name, read_only)\nself.std = std\nself.mo = mo",
"mdata = ModelData(model_dir)\ngpn_trained = self.mo.network_model()\ngpn_trained.load(mdata.ModelDefinition, mdata.LastCheckpoint)\nlead_in = np.full(gpn_trained.input_dims[2] - 1, np.mean(temp[:10]))\ntemp = np.r_[lead_in, temp]\nact_dic... | <|body_start_0|>
super().__init__(db_file_name, read_only)
self.std = std
self.mo = mo
<|end_body_0|>
<|body_start_1|>
mdata = ModelData(model_dir)
gpn_trained = self.mo.network_model()
gpn_trained.load(mdata.ModelDefinition, mdata.LastCheckpoint)
lead_in = np.fu... | Hdf5 backed store of network cell activity data | ActivityStore | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivityStore:
"""Hdf5 backed store of network cell activity data"""
def __init__(self, db_file_name, std: GradientStandards, mo: MoTypes, read_only=False):
"""Creates a new ActivityStore :param db_file_name: The backend database filename :param std: Gradient standards for input norm... | stack_v2_sparse_classes_36k_train_004740 | 10,990 | permissive | [
{
"docstring": "Creates a new ActivityStore :param db_file_name: The backend database filename :param std: Gradient standards for input normalization :param mo: Definition of model organism to use :param read_only: If true, no modifications will be made to the database",
"name": "__init__",
"signature":... | 3 | stack_v2_sparse_classes_30k_train_007986 | Implement the Python class `ActivityStore` described below.
Class description:
Hdf5 backed store of network cell activity data
Method signatures and docstrings:
- def __init__(self, db_file_name, std: GradientStandards, mo: MoTypes, read_only=False): Creates a new ActivityStore :param db_file_name: The backend databa... | Implement the Python class `ActivityStore` described below.
Class description:
Hdf5 backed store of network cell activity data
Method signatures and docstrings:
- def __init__(self, db_file_name, std: GradientStandards, mo: MoTypes, read_only=False): Creates a new ActivityStore :param db_file_name: The backend databa... | 679b48768ad74dccd58f8c2f434ad60036fc5cb7 | <|skeleton|>
class ActivityStore:
"""Hdf5 backed store of network cell activity data"""
def __init__(self, db_file_name, std: GradientStandards, mo: MoTypes, read_only=False):
"""Creates a new ActivityStore :param db_file_name: The backend database filename :param std: Gradient standards for input norm... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActivityStore:
"""Hdf5 backed store of network cell activity data"""
def __init__(self, db_file_name, std: GradientStandards, mo: MoTypes, read_only=False):
"""Creates a new ActivityStore :param db_file_name: The backend database filename :param std: Gradient standards for input normalization :pa... | the_stack_v2_python_sparse | data_stores.py | treestreamymw/GradientPrediction | train | 0 |
e4d45fe7dbdcd1656deed30e63b78e90b9b129cb | [
"params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True)\nparams.add(Param(name='lstm_hidden_size', value=5, desc='Integer, the hidden size of the bi-directional LSTM layer.'))\nparams.add(Param(name='lstm_num', value=3, desc='Integer, number of LSTM units'))\nparams.add(Param(nam... | <|body_start_0|>
params = super().get_default_params(with_embedding=True, with_multi_layer_perceptron=True)
params.add(Param(name='lstm_hidden_size', value=5, desc='Integer, the hidden size of the bi-directional LSTM layer.'))
params.add(Param(name='lstm_num', value=3, desc='Integer, number of L... | HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_func'] = nn.LeakyReLU(0.1) >>> mod... | HBMP | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HBMP:
"""HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_fu... | stack_v2_sparse_classes_36k_train_004741 | 4,584 | permissive | [
{
"docstring": ":return: model default parameters.",
"name": "get_default_params",
"signature": "def get_default_params(cls) -> ParamTable"
},
{
"docstring": "Build model structure. HBMP use Siamese arthitecture.",
"name": "build",
"signature": "def build(self)"
},
{
"docstring":... | 3 | stack_v2_sparse_classes_30k_train_014061 | Implement the Python class `HBMP` described below.
Class description:
HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] =... | Implement the Python class `HBMP` described below.
Class description:
HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] =... | 4198ebce942f4afe7ddca6a96ab6f4464ade4518 | <|skeleton|>
class HBMP:
"""HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_fu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HBMP:
"""HBMP model. Examples: >>> model = HBMP() >>> model.params['embedding_input_dim'] = 200 >>> model.params['embedding_output_dim'] = 100 >>> model.params['mlp_num_layers'] = 1 >>> model.params['mlp_num_units'] = 10 >>> model.params['mlp_num_fan_out'] = 10 >>> model.params['mlp_activation_func'] = nn.Lea... | the_stack_v2_python_sparse | poset_decoding/traversal_path_prediction/MatchZoo-py/matchzoo/models/hbmp.py | microsoft/ContextualSP | train | 332 |
84893598125c37ace7eed2810e7ebf96d52874ce | [
"assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)\nassert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)\nassert linker_pos('TTGATCTT', 'GGTC', 1) == (2, 6)\nassert linker_pos('NATCTT', 'GATC', 1) == (1, 4)\nassert linker_pos('NATCTT', 'GATC', 0) == (None, None)",
"self.assertEqual(linker_pair_pos('TGATCTTTT... | <|body_start_0|>
assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)
assert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)
assert linker_pos('TTGATCTT', 'GGTC', 1) == (2, 6)
assert linker_pos('NATCTT', 'GATC', 1) == (1, 4)
assert linker_pos('NATCTT', 'GATC', 0) == (None, None)
... | Test removal of two sided linkers from sequence data. | TwoSideLinkerTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
<|body_0|>
def test_2_linker_pair_pos(self):
"""Find pair of linkers in a larger sequence"""
... | stack_v2_sparse_classes_36k_train_004742 | 7,424 | no_license | [
{
"docstring": "Find a linker, with mismatches, in a larger sequence.",
"name": "test_1_linker_pos",
"signature": "def test_1_linker_pos(self)"
},
{
"docstring": "Find pair of linkers in a larger sequence",
"name": "test_2_linker_pair_pos",
"signature": "def test_2_linker_pair_pos(self)"... | 3 | null | Implement the Python class `TwoSideLinkerTest` described below.
Class description:
Test removal of two sided linkers from sequence data.
Method signatures and docstrings:
- def test_1_linker_pos(self): Find a linker, with mismatches, in a larger sequence.
- def test_2_linker_pair_pos(self): Find pair of linkers in a ... | Implement the Python class `TwoSideLinkerTest` described below.
Class description:
Test removal of two sided linkers from sequence data.
Method signatures and docstrings:
- def test_1_linker_pos(self): Find a linker, with mismatches, in a larger sequence.
- def test_2_linker_pair_pos(self): Find pair of linkers in a ... | 76ea8bc6ddb5fd09fec095c80a5092facfba6e8c | <|skeleton|>
class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
<|body_0|>
def test_2_linker_pair_pos(self):
"""Find pair of linkers in a larger sequence"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwoSideLinkerTest:
"""Test removal of two sided linkers from sequence data."""
def test_1_linker_pos(self):
"""Find a linker, with mismatches, in a larger sequence."""
assert linker_pos('TTGATCTT', 'GATC', 0) == (2, 6)
assert linker_pos('TTGATCTT', 'GGTC', 0) == (None, None)
... | the_stack_v2_python_sparse | ay_linkertrim/scripts/trim_twoside_linker.py | Rushikesh2703/projects | train | 0 |
8eee21d964f3eb2247c9a01ec7ee5685ad6fa52b | [
"events = []\nstack_traces = []\nwhile self.stack_trace_re.match(line):\n event = self.parse_stack_trace_line(line)\n if event:\n events.append(event)\n stack_traces.append(line)\n line = get_next(it)\nevents.reverse()\nreturn (stack_traces, events, line)",
"match = self.line_re.match(line)\nif... | <|body_start_0|>
events = []
stack_traces = []
while self.stack_trace_re.match(line):
event = self.parse_stack_trace_line(line)
if event:
events.append(event)
stack_traces.append(line)
line = get_next(it)
events.reverse()
... | Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7... | Parser | [
"LLVM-exception",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
<|body_0|>
def parse_sanitizer_messag... | stack_v2_sparse_classes_36k_train_004743 | 7,773 | permissive | [
{
"docstring": "Iterate over lines and parse stack traces.",
"name": "parse_stack_trace",
"signature": "def parse_stack_trace(self, it, line)"
},
{
"docstring": "Parses UndefinedBehaviorSanitizer output message.",
"name": "parse_sanitizer_message",
"signature": "def parse_sanitizer_messa... | 2 | stack_v2_sparse_classes_30k_train_016032 | Implement the Python class `Parser` described below.
Class description:
Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7...
Method signatures and docstrings:
- def parse_stack_trace(self, it, line): Iterate over lines and parse stack trac... | Implement the Python class `Parser` described below.
Class description:
Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7...
Method signatures and docstrings:
- def parse_stack_trace(self, it, line): Iterate over lines and parse stack trac... | f912cf0ccc7059240ae389823faf35225e6cabc8 | <|skeleton|>
class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
<|body_0|>
def parse_sanitizer_messag... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Parser:
"""Parser for Clang UndefinedBehaviourSanitizer console outputs. Example output /a/b/main.cpp:13:10: runtime error: load of value 7..."""
def parse_stack_trace(self, it, line):
"""Iterate over lines and parse stack traces."""
events = []
stack_traces = []
while sel... | the_stack_v2_python_sparse | tools/report-converter/codechecker_report_converter/analyzers/sanitizers/ub/parser.py | Ericsson/codechecker | train | 2,028 |
041d858ee08c418eb48215abc95cf8e83e8c30cb | [
"try:\n log.info('%s %r' % (request.remote_addr, request))\nexcept Exception as exception:\n log.exception(exception)",
"try:\n log.info('%s %r' % (request.remote_addr, request))\n log.info('api() | POST | Received request for Campaign')\n campaign_instance = api_controller.get_campaign(request.jso... | <|body_start_0|>
try:
log.info('%s %r' % (request.remote_addr, request))
except Exception as exception:
log.exception(exception)
<|end_body_0|>
<|body_start_1|>
try:
log.info('%s %r' % (request.remote_addr, request))
log.info('api() | POST | Recei... | CampaignList | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CampaignList:
def get(self):
""":return:"""
<|body_0|>
def post(self):
""":return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
log.info('%s %r' % (request.remote_addr, request))
except Exception as exception:
... | stack_v2_sparse_classes_36k_train_004744 | 23,973 | permissive | [
{
"docstring": ":return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": ":return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010741 | Implement the Python class `CampaignList` described below.
Class description:
Implement the CampaignList class.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): :return: | Implement the Python class `CampaignList` described below.
Class description:
Implement the CampaignList class.
Method signatures and docstrings:
- def get(self): :return:
- def post(self): :return:
<|skeleton|>
class CampaignList:
def get(self):
""":return:"""
<|body_0|>
def post(self):
... | c27812e6b846eb1e28ec0c6e8508e18886e37617 | <|skeleton|>
class CampaignList:
def get(self):
""":return:"""
<|body_0|>
def post(self):
""":return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CampaignList:
def get(self):
""":return:"""
try:
log.info('%s %r' % (request.remote_addr, request))
except Exception as exception:
log.exception(exception)
def post(self):
""":return:"""
try:
log.info('%s %r' % (request.remote_ad... | the_stack_v2_python_sparse | api/version1_0/application/api_main.py | gogasca/news_ml | train | 4 | |
2a3feb08fa08daf495524444d8b164af23d48f80 | [
"prefix = 0\nres = []\nfor a in A:\n prefix = (2 * prefix + a) % 5\n res.append(prefix == 0)\nreturn res",
"num = ''\nres = []\nfor bit in A:\n num += str(bit)\n if int(num, 2) % 5 == 0:\n res.append(True)\n else:\n res.append(False)\nreturn res"
] | <|body_start_0|>
prefix = 0
res = []
for a in A:
prefix = (2 * prefix + a) % 5
res.append(prefix == 0)
return res
<|end_body_0|>
<|body_start_1|>
num = ''
res = []
for bit in A:
num += str(bit)
if int(num, 2) % 5 ==... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_0|>
def prefixesDivBy5_2(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
prefix = 0
res = []
... | stack_v2_sparse_classes_36k_train_004745 | 1,661 | no_license | [
{
"docstring": ":type A: List[int] :rtype: List[bool]",
"name": "prefixesDivBy5",
"signature": "def prefixesDivBy5(self, A)"
},
{
"docstring": ":type A: List[int] :rtype: List[bool]",
"name": "prefixesDivBy5_2",
"signature": "def prefixesDivBy5_2(self, A)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018967 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prefixesDivBy5(self, A): :type A: List[int] :rtype: List[bool]
- def prefixesDivBy5_2(self, A): :type A: List[int] :rtype: List[bool] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def prefixesDivBy5(self, A): :type A: List[int] :rtype: List[bool]
- def prefixesDivBy5_2(self, A): :type A: List[int] :rtype: List[bool]
<|skeleton|>
class Solution:
def p... | 8595b04cf5a024c2cd8a97f750d890a818568401 | <|skeleton|>
class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_0|>
def prefixesDivBy5_2(self, A):
""":type A: List[int] :rtype: List[bool]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def prefixesDivBy5(self, A):
""":type A: List[int] :rtype: List[bool]"""
prefix = 0
res = []
for a in A:
prefix = (2 * prefix + a) % 5
res.append(prefix == 0)
return res
def prefixesDivBy5_2(self, A):
""":type A: List[int] ... | the_stack_v2_python_sparse | python/1018.binary-prefix-divisible-by-5.py | tainenko/Leetcode2019 | train | 5 | |
143d299f71aee4db925abcd3c50e62aa9d922b0b | [
"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... | A set of methods for managing Node resources. | NodeServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeServiceServicer:
"""A set of methods for managing Node resources."""
def Execute(self, request, context):
"""Executes deployed Node."""
<|body_0|>
def ExecuteAlias(self, request, context):
"""Executes NodeAlias requests."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k_train_004746 | 4,708 | permissive | [
{
"docstring": "Executes deployed Node.",
"name": "Execute",
"signature": "def Execute(self, request, context)"
},
{
"docstring": "Executes NodeAlias requests.",
"name": "ExecuteAlias",
"signature": "def ExecuteAlias(self, request, context)"
}
] | 2 | null | Implement the Python class `NodeServiceServicer` described below.
Class description:
A set of methods for managing Node resources.
Method signatures and docstrings:
- def Execute(self, request, context): Executes deployed Node.
- def ExecuteAlias(self, request, context): Executes NodeAlias requests. | Implement the Python class `NodeServiceServicer` described below.
Class description:
A set of methods for managing Node resources.
Method signatures and docstrings:
- def Execute(self, request, context): Executes deployed Node.
- def ExecuteAlias(self, request, context): Executes NodeAlias requests.
<|skeleton|>
cla... | b906a014dd893e2697864e1e48e814a8d9fbc48c | <|skeleton|>
class NodeServiceServicer:
"""A set of methods for managing Node resources."""
def Execute(self, request, context):
"""Executes deployed Node."""
<|body_0|>
def ExecuteAlias(self, request, context):
"""Executes NodeAlias requests."""
<|body_1|>
<|end_skeleton|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NodeServiceServicer:
"""A set of methods for managing Node resources."""
def Execute(self, request, context):
"""Executes deployed Node."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not ... | the_stack_v2_python_sparse | yandex/cloud/datasphere/v1/node_service_pb2_grpc.py | yandex-cloud/python-sdk | train | 63 |
7210706fab21256fd9cdf386b88efa37627d262e | [
"def append_params(params, key, value) -> None:\n if key in params:\n params[key] += '|' + value\n else:\n params[key] = value\nkwargs = self._clean_kwargs(kwargs)\nparameters = kwargs['parameters']\nappend_params(parameters, 'prop', 'info|imageinfo|categoryinfo')\nif g_content:\n append_para... | <|body_start_0|>
def append_params(params, key, value) -> None:
if key in params:
params[key] += '|' + value
else:
params[key] = value
kwargs = self._clean_kwargs(kwargs)
parameters = kwargs['parameters']
append_params(parameters, '... | Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page objects. | PageGenerator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PageGenerator:
"""Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page objects."""
def __init__(self, ge... | stack_v2_sparse_classes_36k_train_004747 | 40,132 | permissive | [
{
"docstring": "Initializer. Required and optional parameters are as for ``Request``, except that action=query is assumed and generator is required. :param generator: the \"generator=\" type from api.php :param g_content: if True, retrieve the contents of the current version of each Page (default False)",
"... | 2 | null | Implement the Python class `PageGenerator` described below.
Class description:
Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page... | Implement the Python class `PageGenerator` described below.
Class description:
Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page... | 5c01e6bfcd328bc6eae643e661f1a0ae57612808 | <|skeleton|>
class PageGenerator:
"""Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page objects."""
def __init__(self, ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PageGenerator:
"""Generator for response to a request of type action=query&generator=foo. This class can be used for any of the query types that are listed in the API documentation as being able to be used as a generator. Instances of this class iterate Page objects."""
def __init__(self, generator: str,... | the_stack_v2_python_sparse | pywikibot/data/api/_generators.py | wikimedia/pywikibot | train | 432 |
e9c570e52b40f7fa0a2abe5c2b76d4be7f723168 | [
"self._calc = BVSCalculator()\nself._parset = parset\nself.sig = float(sig)\nself.scaled = bool(scaled)\nreturn",
"stru = self._parset._getSrRealStructure()\nself._calc.eval(stru)\npenalty = self._calc.bvmsdiff\npenalty /= self.sig ** 2\nif self.scaled:\n penalty *= w\nreturn penalty",
"from numpy import nan... | <|body_start_0|>
self._calc = BVSCalculator()
self._parset = parset
self.sig = float(sig)
self.scaled = bool(scaled)
return
<|end_body_0|>
<|body_start_1|>
stru = self._parset._getSrRealStructure()
self._calc.eval(stru)
penalty = self._calc.bvmsdiff
... | Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- The SrRealParSet that created this BVSRestraint. sig -- The uncertainty on the ... | BVSRestraint | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BVSRestraint:
"""Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- The SrRealParSet that created this BVSR... | stack_v2_sparse_classes_36k_train_004748 | 2,963 | no_license | [
{
"docstring": "Initialize the Restraint. parset -- SrRealParSet that creates this BVSRestraint. sig -- The uncertainty on the BVS (default 1). scaled -- A flag indicating if the restraint is scaled (multiplied) by the unrestrained point-average chi^2 (chi^2/numpoints) (bool, default False).",
"name": "__in... | 3 | stack_v2_sparse_classes_30k_train_001322 | Implement the Python class `BVSRestraint` described below.
Class description:
Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- ... | Implement the Python class `BVSRestraint` described below.
Class description:
Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- ... | 303f73c570c1d756106aa69724898d5b119c4ead | <|skeleton|>
class BVSRestraint:
"""Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- The SrRealParSet that created this BVSR... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BVSRestraint:
"""Wrapping of BVSCalculator.bvmsdiff as a Restraint. The restraint penalty is the root-mean-square deviation of the theoretical and calculated bond-valence sum of a structure. Attributes: _calc -- The SrReal BVSCalculator instance. _parset -- The SrRealParSet that created this BVSRestraint. sig... | the_stack_v2_python_sparse | diffpy/srfit/structure/bvsrestraint.py | cfarrow/diffpy.srfit | train | 0 |
13b2c7e4127502516459ea053ff3f14e4f34c150 | [
"if not root:\n return ''\ndata = []\n\ndef helper(root):\n if not root:\n return\n data.append(str(root.val))\n helper(root.left)\n helper(root.right)\n return\nhelper(root)\nreturn ','.join(data)",
"if not data:\n return\ndata = collections.deque([int(i) for i in data.split(',')])\n\... | <|body_start_0|>
if not root:
return ''
data = []
def helper(root):
if not root:
return
data.append(str(root.val))
helper(root.left)
helper(root.right)
return
helper(root)
return ','.join(dat... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_004749 | 1,007 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize",
"signature": "def serialize(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_009187 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree. | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
<|skeleton|>
class Co... | 39bb8598327ab4fec8941c69642fc9114bd9f359 | <|skeleton|>
class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
<|body_0|>
def deserialize(self, data: str) -> TreeNode:
"""Decodes your encoded data to tree."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
if not root:
return ''
data = []
def helper(root):
if not root:
return
data.append(str(root.val))
helper(root.left)
... | the_stack_v2_python_sparse | noodlewhale/Facebook/forgot/49. Serialize and Deserialize BST.py | n0thing233/n0thing233.github.io | train | 1 | |
5ec09f9a78235656bc43bf9d99b4f0996372651b | [
"slow = head\nfast = head.next\nwhile fast:\n slow = slow.next\n fast = fast.next\n if fast:\n fast = fast.next\nreturn slow",
"fast = slow = head\nwhile fast and fast.next:\n fast = fast.next.next\n slow = slow.next\nreturn slow",
"slow = fast = head\nwhile fast and fast.next:\n slow =... | <|body_start_0|>
slow = head
fast = head.next
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
return slow
<|end_body_0|>
<|body_start_1|>
fast = slow = head
while fast and fast.next:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Jan 07, 2022 18:37"""
<|body_0|>
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Dec 11, 2022 16:00"""
<|body_1|>
def middleNode(self, head: Optio... | stack_v2_sparse_classes_36k_train_004750 | 2,072 | no_license | [
{
"docstring": "Jan 07, 2022 18:37",
"name": "middleNode",
"signature": "def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]"
},
{
"docstring": "Dec 11, 2022 16:00",
"name": "middleNode",
"signature": "def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]"... | 3 | stack_v2_sparse_classes_30k_train_010738 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: Jan 07, 2022 18:37
- def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: Dec 11, 2022 16:0... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: Jan 07, 2022 18:37
- def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: Dec 11, 2022 16:0... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Jan 07, 2022 18:37"""
<|body_0|>
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Dec 11, 2022 16:00"""
<|body_1|>
def middleNode(self, head: Optio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""Jan 07, 2022 18:37"""
slow = head
fast = head.next
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
return slow
... | the_stack_v2_python_sparse | leetcode/solved/908_Middle_of_the_Linked_List/solution.py | sungminoh/algorithms | train | 0 | |
a15e53dbdfe9cb99250bd2d7636d4f3dc9ad6251 | [
"self.device = device\nself.title = entry.title\nself.entry = entry\nself.force_next_update = False\nsuper().__init__(hass, _LOGGER, name=self.device.ipaddr, update_interval=timedelta(seconds=10), request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False), always_update=Fals... | <|body_start_0|>
self.device = device
self.title = entry.title
self.entry = entry
self.force_next_update = False
super().__init__(hass, _LOGGER, name=self.device.ipaddr, update_interval=timedelta(seconds=10), request_refresh_debouncer=Debouncer(hass, _LOGGER, cooldown=REQUEST_REF... | DataUpdateCoordinator to gather data for a specific flux_led device. | FluxLedUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FluxLedUpdateCoordinator:
"""DataUpdateCoordinator to gather data for a specific flux_led device."""
def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None:
"""Initialize DataUpdateCoordinator to gather data for specific device."""
<|body_... | stack_v2_sparse_classes_36k_train_004751 | 1,824 | permissive | [
{
"docstring": "Initialize DataUpdateCoordinator to gather data for specific device.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None"
},
{
"docstring": "Fetch all device and sensor data from api.",
"name": "_asyn... | 2 | null | Implement the Python class `FluxLedUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator to gather data for a specific flux_led device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None: Initialize DataUpdateCoordinat... | Implement the Python class `FluxLedUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator to gather data for a specific flux_led device.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None: Initialize DataUpdateCoordinat... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class FluxLedUpdateCoordinator:
"""DataUpdateCoordinator to gather data for a specific flux_led device."""
def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None:
"""Initialize DataUpdateCoordinator to gather data for specific device."""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FluxLedUpdateCoordinator:
"""DataUpdateCoordinator to gather data for a specific flux_led device."""
def __init__(self, hass: HomeAssistant, device: AIOWifiLedBulb, entry: ConfigEntry) -> None:
"""Initialize DataUpdateCoordinator to gather data for specific device."""
self.device = device... | the_stack_v2_python_sparse | homeassistant/components/flux_led/coordinator.py | home-assistant/core | train | 35,501 |
931ab00fbfe99149c48ee3889a1ddbcc7120216f | [
"self.port = 8303\nself.processCommand()\ntry:\n responseSchema = open('addResponse_schema.json', 'rU').read()\n errorSchema = open('addError_schema.json', 'rU').read()\nexcept IOError as e:\n print('Error loading schema: ' + e.strerror)\n sys.exit(1)\ntry:\n self.responseSchema = loads(responseSchem... | <|body_start_0|>
self.port = 8303
self.processCommand()
try:
responseSchema = open('addResponse_schema.json', 'rU').read()
errorSchema = open('addError_schema.json', 'rU').read()
except IOError as e:
print('Error loading schema: ' + e.strerror)
... | Start client for addition service. | AdditionClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdditionClient:
"""Start client for addition service."""
def __init__(self):
"""Set port and start client"""
<|body_0|>
def processCommand(self):
"""Get port from command line arguments."""
<|body_1|>
def makeRequests(self):
"""Make requests ... | stack_v2_sparse_classes_36k_train_004752 | 3,713 | permissive | [
{
"docstring": "Set port and start client",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Get port from command line arguments.",
"name": "processCommand",
"signature": "def processCommand(self)"
},
{
"docstring": "Make requests with valid and invalid c... | 4 | stack_v2_sparse_classes_30k_train_008285 | Implement the Python class `AdditionClient` described below.
Class description:
Start client for addition service.
Method signatures and docstrings:
- def __init__(self): Set port and start client
- def processCommand(self): Get port from command line arguments.
- def makeRequests(self): Make requests with valid and ... | Implement the Python class `AdditionClient` described below.
Class description:
Start client for addition service.
Method signatures and docstrings:
- def __init__(self): Set port and start client
- def processCommand(self): Get port from command line arguments.
- def makeRequests(self): Make requests with valid and ... | d6e8ca06c70e31bff0e56f7d94bfa0bd835bf61c | <|skeleton|>
class AdditionClient:
"""Start client for addition service."""
def __init__(self):
"""Set port and start client"""
<|body_0|>
def processCommand(self):
"""Get port from command line arguments."""
<|body_1|>
def makeRequests(self):
"""Make requests ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdditionClient:
"""Start client for addition service."""
def __init__(self):
"""Set port and start client"""
self.port = 8303
self.processCommand()
try:
responseSchema = open('addResponse_schema.json', 'rU').read()
errorSchema = open('addError_schem... | the_stack_v2_python_sparse | chapter7/additionClient.py | MikeBeaulieu/ujs-book-materials | train | 0 |
244437b8afbe5873d9918e7369ad48d5232f3df4 | [
"args = parser.parse_args(request)\nrole = self.get_object(role_id)\nif 'include' in args and args.get('include') == 'permissions':\n schema = RoleWithPermissionSchema()\n serialized_roles = schema.dump(role)\nelse:\n serialized_roles = self.schema.dump(role)\nreturn response(serialized_roles, SUCCESS_MESS... | <|body_start_0|>
args = parser.parse_args(request)
role = self.get_object(role_id)
if 'include' in args and args.get('include') == 'permissions':
schema = RoleWithPermissionSchema()
serialized_roles = schema.dump(role)
else:
serialized_roles = self.sch... | Roles Resource | RoleResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleResource:
"""Roles Resource"""
def get(self, role_id):
"""Get a role"""
<|body_0|>
def patch(self, role_id):
"""Update a role"""
<|body_1|>
def delete(self, role_id):
"""Delete a role"""
<|body_2|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_004753 | 7,412 | permissive | [
{
"docstring": "Get a role",
"name": "get",
"signature": "def get(self, role_id)"
},
{
"docstring": "Update a role",
"name": "patch",
"signature": "def patch(self, role_id)"
},
{
"docstring": "Delete a role",
"name": "delete",
"signature": "def delete(self, role_id)"
}
... | 3 | stack_v2_sparse_classes_30k_train_021332 | Implement the Python class `RoleResource` described below.
Class description:
Roles Resource
Method signatures and docstrings:
- def get(self, role_id): Get a role
- def patch(self, role_id): Update a role
- def delete(self, role_id): Delete a role | Implement the Python class `RoleResource` described below.
Class description:
Roles Resource
Method signatures and docstrings:
- def get(self, role_id): Get a role
- def patch(self, role_id): Update a role
- def delete(self, role_id): Delete a role
<|skeleton|>
class RoleResource:
"""Roles Resource"""
def g... | c5cf6baf60e95a7790156c85e37c76c697efd585 | <|skeleton|>
class RoleResource:
"""Roles Resource"""
def get(self, role_id):
"""Get a role"""
<|body_0|>
def patch(self, role_id):
"""Update a role"""
<|body_1|>
def delete(self, role_id):
"""Delete a role"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleResource:
"""Roles Resource"""
def get(self, role_id):
"""Get a role"""
args = parser.parse_args(request)
role = self.get_object(role_id)
if 'include' in args and args.get('include') == 'permissions':
schema = RoleWithPermissionSchema()
serializ... | the_stack_v2_python_sparse | src/views/role.py | Nardri/rbac-service | train | 0 |
d3b5daa677faa8560d7471e25695676446ec9b57 | [
"super(ConvertVideoTask, self).__init__(*args, **kwargs)\nself.setOption('videoArgs', self.__defaultVideoArgs)\nself.setOption('audioArgs', self.__defaultAudioArgs)\nself.setOption('bitRate', self.__defaultBitRate)",
"videoArgs = self.option('videoArgs')\naudioArgs = self.option('audioArgs')\nbitRate = self.optio... | <|body_start_0|>
super(ConvertVideoTask, self).__init__(*args, **kwargs)
self.setOption('videoArgs', self.__defaultVideoArgs)
self.setOption('audioArgs', self.__defaultAudioArgs)
self.setOption('bitRate', self.__defaultBitRate)
<|end_body_0|>
<|body_start_1|>
videoArgs = self.op... | Convert a video using ffmpeg. | ConvertVideoTask | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(ConvertVide... | stack_v2_sparse_classes_36k_train_004754 | 2,356 | permissive | [
{
"docstring": "Create a convert video object.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Perform the task.",
"name": "_perform",
"signature": "def _perform(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002355 | Implement the Python class `ConvertVideoTask` described below.
Class description:
Convert a video using ffmpeg.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a convert video object.
- def _perform(self): Perform the task. | Implement the Python class `ConvertVideoTask` described below.
Class description:
Convert a video using ffmpeg.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Create a convert video object.
- def _perform(self): Perform the task.
<|skeleton|>
class ConvertVideoTask:
"""Convert a video u... | 046dbb0c1b4ff20ea5f2e1679f8d89f3089b6aa4 | <|skeleton|>
class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
<|body_0|>
def _perform(self):
"""Perform the task."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConvertVideoTask:
"""Convert a video using ffmpeg."""
def __init__(self, *args, **kwargs):
"""Create a convert video object."""
super(ConvertVideoTask, self).__init__(*args, **kwargs)
self.setOption('videoArgs', self.__defaultVideoArgs)
self.setOption('audioArgs', self.__d... | the_stack_v2_python_sparse | src/lib/kombi/Task/Video/ConvertVideoTask.py | kombiHQ/kombi | train | 2 |
a3d4a6ea94c95d0a12a0a2f8ed6f999bfcd4cbbf | [
"self.pump = Pump('127.0.0.1', 1)\nself.sensor = Sensor('127.0.0.2', 2)\nself.decider = Decider(300, 0.1)\nself.controller = Controller(self.sensor, self.pump, self.decider)",
"self.sensor.measure = MagicMock(return_value=200)\nself.pump.get_state = MagicMock(return_value=Pump.PUMP_OFF)\nself.pump.set_state = Mag... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 1)
self.sensor = Sensor('127.0.0.2', 2)
self.decider = Decider(300, 0.1)
self.controller = Controller(self.sensor, self.pump, self.decider)
<|end_body_0|>
<|body_start_1|>
self.sensor.measure = MagicMock(return_value=200)
se... | Unit tests for the Controller class | ControllerTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
<|body_0|>
def test_tick(self):
"""test for controller"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump... | stack_v2_sparse_classes_36k_train_004755 | 2,566 | no_license | [
{
"docstring": "Just some example syntax that you might use",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test for controller",
"name": "test_tick",
"signature": "def test_tick(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018097 | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Just some example syntax that you might use
- def test_tick(self): test for controller | Implement the Python class `ControllerTests` described below.
Class description:
Unit tests for the Controller class
Method signatures and docstrings:
- def setUp(self): Just some example syntax that you might use
- def test_tick(self): test for controller
<|skeleton|>
class ControllerTests:
"""Unit tests for th... | b1fea0309b3495b3e1dc167d7029bc9e4b6f00f1 | <|skeleton|>
class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
<|body_0|>
def test_tick(self):
"""test for controller"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ControllerTests:
"""Unit tests for the Controller class"""
def setUp(self):
"""Just some example syntax that you might use"""
self.pump = Pump('127.0.0.1', 1)
self.sensor = Sensor('127.0.0.2', 2)
self.decider = Decider(300, 0.1)
self.controller = Controller(self.se... | the_stack_v2_python_sparse | students/AurelP/lesson6/water-regulation/waterregulation/test.py | UWPCE-PythonCert-ClassRepos/SP_Online_Course2_2018 | train | 4 |
a23d46dae8f7fa8e308afb94d8a8828e7accd9d7 | [
"if not root:\n return None\n\ndef helper(root):\n if not root:\n return None\n if root.val == val:\n return root\n elif root.val > val:\n return helper(root.left)\n else:\n return helper(root.right)\nreturn helper(root)",
"if not root:\n return None\nwhile root and r... | <|body_start_0|>
if not root:
return None
def helper(root):
if not root:
return None
if root.val == val:
return root
elif root.val > val:
return helper(root.left)
else:
return hel... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
"""递归法"""
<|body_0|>
def searchBST_1(self, root: TreeNode, val: int) -> TreeNode:
"""迭代法"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return None
... | stack_v2_sparse_classes_36k_train_004756 | 1,373 | no_license | [
{
"docstring": "递归法",
"name": "searchBST",
"signature": "def searchBST(self, root: TreeNode, val: int) -> TreeNode"
},
{
"docstring": "迭代法",
"name": "searchBST_1",
"signature": "def searchBST_1(self, root: TreeNode, val: int) -> TreeNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_010488 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root: TreeNode, val: int) -> TreeNode: 递归法
- def searchBST_1(self, root: TreeNode, val: int) -> TreeNode: 迭代法 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root: TreeNode, val: int) -> TreeNode: 递归法
- def searchBST_1(self, root: TreeNode, val: int) -> TreeNode: 迭代法
<|skeleton|>
class Solution:
def searchBST... | 3508e1ce089131b19603c3206aab4cf43023bb19 | <|skeleton|>
class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
"""递归法"""
<|body_0|>
def searchBST_1(self, root: TreeNode, val: int) -> TreeNode:
"""迭代法"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def searchBST(self, root: TreeNode, val: int) -> TreeNode:
"""递归法"""
if not root:
return None
def helper(root):
if not root:
return None
if root.val == val:
return root
elif root.val > val:
... | the_stack_v2_python_sparse | algorithm/leetcode/tree/19-二叉搜索树中的搜索.py | lxconfig/UbuntuCode_bak | train | 0 | |
827cd099c8f5140244a89fb7d64e6fab41ed1134 | [
"data = {}\nfor n in nums:\n data[n] = 1\nfor key in data:\n self.forward(data, key)\nif not data:\n return 0\nelse:\n return max(data.values())",
"if n not in data:\n return 0\ncnt = data[n]\nif cnt > 1:\n return cnt\nelse:\n if n + 1 in data:\n cnt = self.forward(data, n + 1) + 1\n ... | <|body_start_0|>
data = {}
for n in nums:
data[n] = 1
for key in data:
self.forward(data, key)
if not data:
return 0
else:
return max(data.values())
<|end_body_0|>
<|body_start_1|>
if n not in data:
return 0
... | hash, and recursion to build the path | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def forward(self, data, n):
"""length of the consecutive sequence starting from n"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_004757 | 1,871 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "longestConsecutive",
"signature": "def longestConsecutive(self, nums)"
},
{
"docstring": "length of the consecutive sequence starting from n",
"name": "forward",
"signature": "def forward(self, data, n)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
hash, and recursion to build the path
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def forward(self, data, n): length of the consecutive sequence starting from n | Implement the Python class `Solution` described below.
Class description:
hash, and recursion to build the path
Method signatures and docstrings:
- def longestConsecutive(self, nums): :type nums: List[int] :rtype: int
- def forward(self, data, n): length of the consecutive sequence starting from n
<|skeleton|>
class... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def forward(self, data, n):
"""length of the consecutive sequence starting from n"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""hash, and recursion to build the path"""
def longestConsecutive(self, nums):
""":type nums: List[int] :rtype: int"""
data = {}
for n in nums:
data[n] = 1
for key in data:
self.forward(data, key)
if not data:
return 0... | the_stack_v2_python_sparse | hashtable/prob128.py | binchen15/leet-python | train | 1 |
6f955c1c786d79144506860ca372e4b06bae7a05 | [
"if num == 1:\n return False\ncell = num // 2\nk = 2\nsum = 1\nwhile k < cell:\n high = num // k\n cell = high + 1\n if num % k == 0:\n sum += high + k\n k += 1\nreturn sum == num",
"res = 0\nbase = 1\nif num <= 0:\n return False\nif num % 10 == 6 or num % 10 == 8:\n if num == 6:\n ... | <|body_start_0|>
if num == 1:
return False
cell = num // 2
k = 2
sum = 1
while k < cell:
high = num // k
cell = high + 1
if num % k == 0:
sum += high + k
k += 1
return sum == num
<|end_body_0|>
<... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool 65MS"""
<|body_0|>
def checkPerfectNumber_1(self, num):
""":type num: int :rtype: bool 36MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if num == 1:
return F... | stack_v2_sparse_classes_36k_train_004758 | 1,226 | no_license | [
{
"docstring": ":type num: int :rtype: bool 65MS",
"name": "checkPerfectNumber",
"signature": "def checkPerfectNumber(self, num)"
},
{
"docstring": ":type num: int :rtype: bool 36MS",
"name": "checkPerfectNumber_1",
"signature": "def checkPerfectNumber_1(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPerfectNumber(self, num): :type num: int :rtype: bool 65MS
- def checkPerfectNumber_1(self, num): :type num: int :rtype: bool 36MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def checkPerfectNumber(self, num): :type num: int :rtype: bool 65MS
- def checkPerfectNumber_1(self, num): :type num: int :rtype: bool 36MS
<|skeleton|>
class Solution:
def... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool 65MS"""
<|body_0|>
def checkPerfectNumber_1(self, num):
""":type num: int :rtype: bool 36MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def checkPerfectNumber(self, num):
""":type num: int :rtype: bool 65MS"""
if num == 1:
return False
cell = num // 2
k = 2
sum = 1
while k < cell:
high = num // k
cell = high + 1
if num % k == 0:
... | the_stack_v2_python_sparse | PerfectNumber_507.py | 953250587/leetcode-python | train | 2 | |
2a06cf1341322e2c8efa87523974debe7f763dd1 | [
"ans = 0\nn = len(s)\n\ndef count(l, r):\n cnt = 0\n while l >= 0 and r < n and (s[l] == s[r]):\n cnt += 1\n l -= 1\n r += 1\n return cnt\nfor i in range(n):\n ans += count(i, i)\n ans += count(i - 1, i)\nreturn ans",
"n, res = (len(s), 0)\ndp = [[False for _ in range(n)] for _... | <|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
for i in range(n):
ans += count(i, i)
ans... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = 0
n = len(s)
def count(l, r):
... | stack_v2_sparse_classes_36k_train_004759 | 1,573 | no_license | [
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstrings",
"signature": "def countSubstrings(self, s)"
},
{
"docstring": ":type s: str :rtype: int",
"name": "countSubstringsDP",
"signature": "def countSubstringsDP(self, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000333 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countSubstrings(self, s): :type s: str :rtype: int
- def countSubstringsDP(self, s): :type s: str :rtype: int
<|skeleton|>
class Solution:
def countSubstrings(self, s):... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
<|body_0|>
def countSubstringsDP(self, s):
""":type s: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def countSubstrings(self, s):
""":type s: str :rtype: int"""
ans = 0
n = len(s)
def count(l, r):
cnt = 0
while l >= 0 and r < n and (s[l] == s[r]):
cnt += 1
l -= 1
r += 1
return cnt
... | the_stack_v2_python_sparse | P/PalindromicSubstrings.py | bssrdf/pyleet | train | 2 | |
6560ba37def48e912cf9b073b06f85e48ba63057 | [
"smach.State.__init__(self, outcomes=['done'])\nself._robot = robot\nself._entity_designator = entity_designator",
"entity_to_inspect = self._entity_designator.resolve()\nlook_at_segmentation_area(self._robot, entity_to_inspect)\ntime.sleep(0.5)\nres = self._robot.ed.update_kinect('{}'.format(entity_to_inspect.uu... | <|body_start_0|>
smach.State.__init__(self, outcomes=['done'])
self._robot = robot
self._entity_designator = entity_designator
<|end_body_0|>
<|body_start_1|>
entity_to_inspect = self._entity_designator.resolve()
look_at_segmentation_area(self._robot, entity_to_inspect)
... | Look at an entity and updates its pose. This assumes the robot is already in front of the object | UpdateEntityPose | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateEntityPose:
"""Look at an entity and updates its pose. This assumes the robot is already in front of the object"""
def __init__(self, robot, entity_designator):
"""Constructor :param robot: robot object :param entity_designator: EdEntityDesignator indicating the object for whic... | stack_v2_sparse_classes_36k_train_004760 | 13,519 | no_license | [
{
"docstring": "Constructor :param robot: robot object :param entity_designator: EdEntityDesignator indicating the object for which the pose should be updated",
"name": "__init__",
"signature": "def __init__(self, robot, entity_designator)"
},
{
"docstring": "Looks at the entity and updates its ... | 2 | null | Implement the Python class `UpdateEntityPose` described below.
Class description:
Look at an entity and updates its pose. This assumes the robot is already in front of the object
Method signatures and docstrings:
- def __init__(self, robot, entity_designator): Constructor :param robot: robot object :param entity_desi... | Implement the Python class `UpdateEntityPose` described below.
Class description:
Look at an entity and updates its pose. This assumes the robot is already in front of the object
Method signatures and docstrings:
- def __init__(self, robot, entity_designator): Constructor :param robot: robot object :param entity_desi... | 092a354315b9b2c08e32cdc049791d82dfd47745 | <|skeleton|>
class UpdateEntityPose:
"""Look at an entity and updates its pose. This assumes the robot is already in front of the object"""
def __init__(self, robot, entity_designator):
"""Constructor :param robot: robot object :param entity_designator: EdEntityDesignator indicating the object for whic... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UpdateEntityPose:
"""Look at an entity and updates its pose. This assumes the robot is already in front of the object"""
def __init__(self, robot, entity_designator):
"""Constructor :param robot: robot object :param entity_designator: EdEntityDesignator indicating the object for which the pose sh... | the_stack_v2_python_sparse | robot_smach_states/src/robot_smach_states/world_model/world_model.py | tue-robotics/tue_robocup | train | 39 |
79fd783e07972dd497efd314089114f536ced46f | [
"logger.info('Get a specific role by Id', data=uuid)\nrole = Role.query.get(uuid)\nreturn role_schema.jsonify(role)",
"logger.info('Update role')\nrole_obj = Role.query.get(uuid)\nif role_obj is None:\n return ({'message': 'Role not found'}, 404)\njson_data = request.get_json(force=True)\nif not json_data:\n ... | <|body_start_0|>
logger.info('Get a specific role by Id', data=uuid)
role = Role.query.get(uuid)
return role_schema.jsonify(role)
<|end_body_0|>
<|body_start_1|>
logger.info('Update role')
role_obj = Role.query.get(uuid)
if role_obj is None:
return ({'message... | Role detail funtions written | RoleDetail | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleDetail:
"""Role detail funtions written"""
def get(self, uuid):
"""Get a specific role by id"""
<|body_0|>
def put(self, uuid):
"""Update role"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
logger.info('Get a specific role by Id', data=uuid... | stack_v2_sparse_classes_36k_train_004761 | 3,667 | no_license | [
{
"docstring": "Get a specific role by id",
"name": "get",
"signature": "def get(self, uuid)"
},
{
"docstring": "Update role",
"name": "put",
"signature": "def put(self, uuid)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016917 | Implement the Python class `RoleDetail` described below.
Class description:
Role detail funtions written
Method signatures and docstrings:
- def get(self, uuid): Get a specific role by id
- def put(self, uuid): Update role | Implement the Python class `RoleDetail` described below.
Class description:
Role detail funtions written
Method signatures and docstrings:
- def get(self, uuid): Get a specific role by id
- def put(self, uuid): Update role
<|skeleton|>
class RoleDetail:
"""Role detail funtions written"""
def get(self, uuid)... | 4dc5f5e816e3c461b8a60c5f61c7eafc08050579 | <|skeleton|>
class RoleDetail:
"""Role detail funtions written"""
def get(self, uuid):
"""Get a specific role by id"""
<|body_0|>
def put(self, uuid):
"""Update role"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleDetail:
"""Role detail funtions written"""
def get(self, uuid):
"""Get a specific role by id"""
logger.info('Get a specific role by Id', data=uuid)
role = Role.query.get(uuid)
return role_schema.jsonify(role)
def put(self, uuid):
"""Update role"""
... | the_stack_v2_python_sparse | app/api/role.py | ekramulmostafa/ms-auth | train | 0 |
2fb96cca7f489ffaae3de606d587648b62c70f0d | [
"extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')\ntitles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upper Limit</i>']\nreturn f\"\\n {extents}\\n {current.table(titles[0]... | <|body_start_0|>
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')
titles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upper Limit</i>']
return f"\n {extents}\n ... | _CleanStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
<|body_0|>
def _diff(self, _, changed):
"""yield the changes"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + ... | stack_v2_sparse_classes_36k_train_004762 | 15,492 | no_license | [
{
"docstring": "return the tabs",
"name": "tabs",
"signature": "def tabs(current) -> str"
},
{
"docstring": "yield the changes",
"name": "_diff",
"signature": "def _diff(self, _, changed)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003729 | Implement the Python class `_CleanStore` described below.
Class description:
Implement the _CleanStore class.
Method signatures and docstrings:
- def tabs(current) -> str: return the tabs
- def _diff(self, _, changed): yield the changes | Implement the Python class `_CleanStore` described below.
Class description:
Implement the _CleanStore class.
Method signatures and docstrings:
- def tabs(current) -> str: return the tabs
- def _diff(self, _, changed): yield the changes
<|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return... | f9534e4fff9775ff45d08d401de61015d4a69e76 | <|skeleton|>
class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
<|body_0|>
def _diff(self, _, changed):
"""yield the changes"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CleanStore:
def tabs(current) -> str:
"""return the tabs"""
extents = current.table(NAMES['extent'], 'clean.task.minextent', '.3F', '< ' + NAMES['extent'] + ' <', None, 'clean.task.maxextent', '.3F')
titles = [NAMES['population'] + ' <i>Lower Limit</i>', NAMES['saturation'] + ' <i>Upp... | the_stack_v2_python_sparse | src/peakcalling/view/_widgets/_tasks.py | depixusgenome/trackanalysis | train | 0 | |
25be437d79fc955409a8918e6c92106e0f29d1f0 | [
"Frame.__init__(self, master)\nself.pack()\nself.createArtistWidgets()",
"Album_Frame = Frame(self)\nArtist_Frame = Frame(self)\nType_Frame = Frame(self)\nGenre_Frame = Frame(self)\nself.labelInputAlbum = Label(Album_Frame, text='Delete Album Name')\nself.labelResult = Label(Album_Frame, text='Result Album')\nsel... | <|body_start_0|>
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
<|end_body_0|>
<|body_start_1|>
Album_Frame = Frame(self)
Artist_Frame = Frame(self)
Type_Frame = Frame(self)
Genre_Frame = Frame(self)
self.labelInputAlbum = Label(Album... | Application main window class. | Application | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k_train_004763 | 2,125 | no_license | [
{
"docstring": "Main frame initialization (mostly delegated)",
"name": "__init__",
"signature": "def __init__(self, master=None)"
},
{
"docstring": "Add all the widgets to the main frame.",
"name": "createArtistWidgets",
"signature": "def createArtistWidgets(self)"
},
{
"docstrin... | 3 | stack_v2_sparse_classes_30k_train_012679 | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | Implement the Python class `Application` described below.
Class description:
Application main window class.
Method signatures and docstrings:
- def __init__(self, master=None): Main frame initialization (mostly delegated)
- def createArtistWidgets(self): Add all the widgets to the main frame.
- def handle(self): Hand... | 2dba11861f91e4bdc1ef28279132a6d8dd4ccf54 | <|skeleton|>
class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
<|body_0|>
def createArtistWidgets(self):
"""Add all the widgets to the main frame."""
<|body_1|>
def handle(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Application:
"""Application main window class."""
def __init__(self, master=None):
"""Main frame initialization (mostly delegated)"""
Frame.__init__(self, master)
self.pack()
self.createArtistWidgets()
def createArtistWidgets(self):
"""Add all the widgets to t... | the_stack_v2_python_sparse | Mux_Gui/Delete_Album_Gui.py | rduvalwa5/Mux | train | 0 |
39b2110306ffbf176b3fc00fee4e37696b58f44c | [
"observed = data\nn = sum(observed)\nexpected = np.ones(6) * n / 6\ntest_stat = sum(abs(observed - expected))\nreturn test_stat",
"n = sum(self.data)\nvalues = [1, 2, 3, 4, 5, 6]\nrolls = np.random.choice(values, n, replace=True)\nhist = thinkstats2.Hist(rolls)\nfreqs = hist.Freqs(values)\nreturn freqs"
] | <|body_start_0|>
observed = data
n = sum(observed)
expected = np.ones(6) * n / 6
test_stat = sum(abs(observed - expected))
return test_stat
<|end_body_0|>
<|body_start_1|>
n = sum(self.data)
values = [1, 2, 3, 4, 5, 6]
rolls = np.random.choice(values, n, ... | Tests whether a six-sided die is fair. | DiceTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiceTest:
"""Tests whether a six-sided die is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: list of frequencies"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
<|body_1|... | stack_v2_sparse_classes_36k_train_004764 | 10,162 | permissive | [
{
"docstring": "Computes the test statistic. data: list of frequencies",
"name": "TestStatistic",
"signature": "def TestStatistic(self, data)"
},
{
"docstring": "Run the model of the null hypothesis. returns: simulated data",
"name": "RunModel",
"signature": "def RunModel(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000764 | Implement the Python class `DiceTest` described below.
Class description:
Tests whether a six-sided die is fair.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: list of frequencies
- def RunModel(self): Run the model of the null hypothesis. returns: simulated data | Implement the Python class `DiceTest` described below.
Class description:
Tests whether a six-sided die is fair.
Method signatures and docstrings:
- def TestStatistic(self, data): Computes the test statistic. data: list of frequencies
- def RunModel(self): Run the model of the null hypothesis. returns: simulated data... | 30a85d5137db95e01461ad21519bc1bdf294044b | <|skeleton|>
class DiceTest:
"""Tests whether a six-sided die is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: list of frequencies"""
<|body_0|>
def RunModel(self):
"""Run the model of the null hypothesis. returns: simulated data"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiceTest:
"""Tests whether a six-sided die is fair."""
def TestStatistic(self, data):
"""Computes the test statistic. data: list of frequencies"""
observed = data
n = sum(observed)
expected = np.ones(6) * n / 6
test_stat = sum(abs(observed - expected))
retu... | the_stack_v2_python_sparse | CompStats/hypothesis.py | sunny2309/scipy_conf_notebooks | train | 2 |
4d9c5447d5c09557490f1a6f16236ecb19bf0b34 | [
"self.distinct_tags = [MagicMock(id=1), MagicMock(id=2), MagicMock(id=3)]\nself.profiles = [MagicMock(tags=MagicMock(), id=2), MagicMock(tags=MagicMock(), id=3)]\nself.social_link = MagicMock(spec=SocialLink, account=MagicMock(spec=SocialAccount, expert=MagicMock(spec=Expert, userbase=MagicMock(id=1), id=1)), exper... | <|body_start_0|>
self.distinct_tags = [MagicMock(id=1), MagicMock(id=2), MagicMock(id=3)]
self.profiles = [MagicMock(tags=MagicMock(), id=2), MagicMock(tags=MagicMock(), id=3)]
self.social_link = MagicMock(spec=SocialLink, account=MagicMock(spec=SocialAccount, expert=MagicMock(spec=Expert, userb... | Test case for PushFeeds | TestPushFeeds | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestPushFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_feeds_to_streamfeed(self, mock_expert_publish_content, mock_parent_tags):
"""test case for method push_feeds_to_streamfeed"""
<|body_1|... | stack_v2_sparse_classes_36k_train_004765 | 20,391 | no_license | [
{
"docstring": "SetUp method for test case",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "test case for method push_feeds_to_streamfeed",
"name": "test_push_feeds_to_streamfeed",
"signature": "def test_push_feeds_to_streamfeed(self, mock_expert_publish_content, mock... | 4 | stack_v2_sparse_classes_30k_train_018610 | Implement the Python class `TestPushFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_feeds_to_streamfeed(self, mock_expert_publish_content, mock_parent_tags): test case for method push_feeds_to_streamfeed... | Implement the Python class `TestPushFeeds` described below.
Class description:
Test case for PushFeeds
Method signatures and docstrings:
- def setUp(self): SetUp method for test case
- def test_push_feeds_to_streamfeed(self, mock_expert_publish_content, mock_parent_tags): test case for method push_feeds_to_streamfeed... | 248a7b406686c0c98e944319a6eca08485104f5d | <|skeleton|>
class TestPushFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
<|body_0|>
def test_push_feeds_to_streamfeed(self, mock_expert_publish_content, mock_parent_tags):
"""test case for method push_feeds_to_streamfeed"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestPushFeeds:
"""Test case for PushFeeds"""
def setUp(self):
"""SetUp method for test case"""
self.distinct_tags = [MagicMock(id=1), MagicMock(id=2), MagicMock(id=3)]
self.profiles = [MagicMock(tags=MagicMock(), id=2), MagicMock(tags=MagicMock(), id=3)]
self.social_link =... | the_stack_v2_python_sparse | common/feeds/tests.py | skshivammahajan/DRFChat | train | 0 |
3c7c38dd151c1eb4d8cf1969f3039ea20487b1ce | [
"self.lambtha = float(lambtha)\nif data is None:\n if lambtha <= 0:\n raise ValueError('lambtha must be a positive value')\nelif isinstance(data, list):\n if len(data) > 1:\n self.data = data\n self.lambtha = float(1 / (sum(self.data) / len(self.data)))\n else:\n raise ValueErro... | <|body_start_0|>
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
raise ValueError('lambtha must be a positive value')
elif isinstance(data, list):
if len(data) > 1:
self.data = data
self.lambtha = float(1 / (... | Class to calculate Exponential distribution | Exponential | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Exponential:
"""Class to calculate Exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p"""
<|body_0|>
def pdf(self, k):
"""Calculates the Probability Dens... | stack_v2_sparse_classes_36k_train_004766 | 1,696 | no_license | [
{
"docstring": "Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p",
"name": "__init__",
"signature": "def __init__(self, data=None, lambtha=1.0)"
},
{
"docstring": "Calculates the Probability Density Function of the distribution. f(x;λ) = λe^(-λx) Args: k (in... | 3 | null | Implement the Python class `Exponential` described below.
Class description:
Class to calculate Exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p
- def pdf(self, k): Calculates... | Implement the Python class `Exponential` described below.
Class description:
Class to calculate Exponential distribution
Method signatures and docstrings:
- def __init__(self, data=None, lambtha=1.0): Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p
- def pdf(self, k): Calculates... | 5aff923277cfe9f2b5324a773e4e5c3cac810a0c | <|skeleton|>
class Exponential:
"""Class to calculate Exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p"""
<|body_0|>
def pdf(self, k):
"""Calculates the Probability Dens... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Exponential:
"""Class to calculate Exponential distribution"""
def __init__(self, data=None, lambtha=1.0):
"""Constructor of Poisson Args: data (list): dataset of distribution lambtha (float): n*p"""
self.lambtha = float(lambtha)
if data is None:
if lambtha <= 0:
... | the_stack_v2_python_sparse | math/0x03-probability/exponential.py | cmmolanos1/holbertonschool-machine_learning | train | 1 |
36bda5d5fc290a7b62a1eb5ac80651ca5b5e2988 | [
"section = 'trajmods'\nself.con['DampCent'] = self.config.getfloat(section, 'DampCent')\nself.con['DampSlop'] = self.config.getfloat(section, 'DampSlop')\ntargHeigStr = self.config.get(section, 'TargHeig')\ntargHeigStr = targHeigStr.split(', ')\ntargHeig = list()\nfor nStr in targHeigStr:\n targHeig.append(float... | <|body_start_0|>
section = 'trajmods'
self.con['DampCent'] = self.config.getfloat(section, 'DampCent')
self.con['DampSlop'] = self.config.getfloat(section, 'DampSlop')
targHeigStr = self.config.get(section, 'TargHeig')
targHeigStr = targHeigStr.split(', ')
targHeig = list... | problemConfigurationSGRA | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class problemConfigurationSGRA:
def trajmods(self):
"""Trajectory modification parameters. This should not interfere with the itsme functioning at all."""
<|body_0|>
def accel(self):
"""Acceleration limitation parameters. This should not interfere with the itsme functionin... | stack_v2_sparse_classes_36k_train_004767 | 7,957 | no_license | [
{
"docstring": "Trajectory modification parameters. This should not interfere with the itsme functioning at all.",
"name": "trajmods",
"signature": "def trajmods(self)"
},
{
"docstring": "Acceleration limitation parameters. This should not interfere with the itsme functioning at all.",
"name... | 3 | null | Implement the Python class `problemConfigurationSGRA` described below.
Class description:
Implement the problemConfigurationSGRA class.
Method signatures and docstrings:
- def trajmods(self): Trajectory modification parameters. This should not interfere with the itsme functioning at all.
- def accel(self): Accelerati... | Implement the Python class `problemConfigurationSGRA` described below.
Class description:
Implement the problemConfigurationSGRA class.
Method signatures and docstrings:
- def trajmods(self): Trajectory modification parameters. This should not interfere with the itsme functioning at all.
- def accel(self): Accelerati... | 5556459e13177fac4f0f64eb629ae233f64a17a7 | <|skeleton|>
class problemConfigurationSGRA:
def trajmods(self):
"""Trajectory modification parameters. This should not interfere with the itsme functioning at all."""
<|body_0|>
def accel(self):
"""Acceleration limitation parameters. This should not interfere with the itsme functionin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class problemConfigurationSGRA:
def trajmods(self):
"""Trajectory modification parameters. This should not interfere with the itsme functioning at all."""
section = 'trajmods'
self.con['DampCent'] = self.config.getfloat(section, 'DampCent')
self.con['DampSlop'] = self.config.getfloat... | the_stack_v2_python_sparse | itsme.py | ronaldochaves/SOAR | train | 0 | |
998aa55810260dea73e270537da3353663e4032a | [
"host, port = self.input.split(':')\n\ndef connectionSuccess(protocol):\n protocol.transport.loseConnection()\n log.debug('Got a connection to %s' % self.input)\n self.report['connection'] = 'success'\n\ndef connectionFailed(failure):\n self.report['connection'] = handleAllFailures(failure)\nfrom twiste... | <|body_start_0|>
host, port = self.input.split(':')
def connectionSuccess(protocol):
protocol.transport.loseConnection()
log.debug('Got a connection to %s' % self.input)
self.report['connection'] = 'success'
def connectionFailed(failure):
self.re... | TCPConnectTest | [
"BSD-2-Clause-Views"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TCPConnectTest:
def test_connect(self):
"""This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has succeeded, or the reason for the failure if it has failed."""
<|body_0|>
def inputProcessor(... | stack_v2_sparse_classes_36k_train_004768 | 2,430 | permissive | [
{
"docstring": "This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has succeeded, or the reason for the failure if it has failed.",
"name": "test_connect",
"signature": "def test_connect(self)"
},
{
"docstring":... | 2 | null | Implement the Python class `TCPConnectTest` described below.
Class description:
Implement the TCPConnectTest class.
Method signatures and docstrings:
- def test_connect(self): This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has su... | Implement the Python class `TCPConnectTest` described below.
Class description:
Implement the TCPConnectTest class.
Method signatures and docstrings:
- def test_connect(self): This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has su... | 2764cc2bca9fc60f978b3361ab2e8de372bc5af6 | <|skeleton|>
class TCPConnectTest:
def test_connect(self):
"""This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has succeeded, or the reason for the failure if it has failed."""
<|body_0|>
def inputProcessor(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TCPConnectTest:
def test_connect(self):
"""This test performs a TCP connection to the remote host on the specified port. The report will contains the string 'success' if the test has succeeded, or the reason for the failure if it has failed."""
host, port = self.input.split(':')
def c... | the_stack_v2_python_sparse | ooni/nettests/blocking/tcp_connect.py | hellais/ooni-probe | train | 1 | |
d3dd88cb08d0f53335d53af3d6c1000101e69745 | [
"super(Lexer, self).__init__(TOKENS, TokenNamespace)\nif t_regexp is None:\n unique = {}\n for token in tokens:\n token.compile(alphabet)\n self._debug(fmt('Token: {0}', token))\n unique[token.id_] = token\n t_regexp = Compiler.multiple(alphabet, [(t.id_, t.regexp) for t in unique.valu... | <|body_start_0|>
super(Lexer, self).__init__(TOKENS, TokenNamespace)
if t_regexp is None:
unique = {}
for token in tokens:
token.compile(alphabet)
self._debug(fmt('Token: {0}', token))
unique[token.id_] = token
t_regexp ... | This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user. | Lexer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, m... | stack_v2_sparse_classes_36k_train_004769 | 6,369 | no_license | [
{
"docstring": "matcher is the head of the original matcher graph, which will be called with a tokenised stream. tokens is the set of `Token` instances that define the lexer. alphabet is the alphabet for which the regexps are defined. discard is the regular expression for spaces (which are silently dropped if n... | 4 | stack_v2_sparse_classes_30k_train_018497 | Implement the Python class `Lexer` described below.
Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by... | Implement the Python class `Lexer` described below.
Class description:
This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by... | 0603505f187acc3c7da2e1a6083833a201f8b061 | <|skeleton|>
class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Lexer:
"""This takes a set of regular expressions and provides a matcher that converts a stream into a stream of tokens, passing the new stream to the embedded matcher. It is added to the matcher graph by the lexer_rewriter; it is not specified explicitly by the user."""
def __init__(self, matcher, token... | the_stack_v2_python_sparse | src/lepl/lexer/lexer.py | nyimbi/LEPL | train | 2 |
6c1da9345165ade720dcbaeb60ed5621c82b38ec | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SubjectRightsRequestHistory()",
"from .identity_set import IdentitySet\nfrom .subject_rights_request_stage import SubjectRightsRequestStage\nfrom .subject_rights_request_stage_status import SubjectRightsRequestStageStatus\nfrom .identi... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SubjectRightsRequestHistory()
<|end_body_0|>
<|body_start_1|>
from .identity_set import IdentitySet
from .subject_rights_request_stage import SubjectRightsRequestStage
from .subj... | SubjectRightsRequestHistory | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubjectRightsRequestHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubjectRightsRequestHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_36k_train_004770 | 4,440 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SubjectRightsRequestHistory",
"name": "create_from_discriminator_value",
"signature": "def create_from_discr... | 3 | stack_v2_sparse_classes_30k_train_012103 | Implement the Python class `SubjectRightsRequestHistory` described below.
Class description:
Implement the SubjectRightsRequestHistory class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubjectRightsRequestHistory: Creates a new instance of the appr... | Implement the Python class `SubjectRightsRequestHistory` described below.
Class description:
Implement the SubjectRightsRequestHistory class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubjectRightsRequestHistory: Creates a new instance of the appr... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SubjectRightsRequestHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubjectRightsRequestHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubjectRightsRequestHistory:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SubjectRightsRequestHistory:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ... | the_stack_v2_python_sparse | msgraph/generated/models/subject_rights_request_history.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
39abb1dc2cd8f1a890694b6df1e563c8d65c7a50 | [
"self.fifo = []\nself.counter = {}\nself.maxC = 0\nself.maxMsg = ''",
"self.fifo.append(msg)\nif msg not in self.counter:\n self.counter[msg] = 1\nelse:\n self.counter[msg] = self.counter[msg] + 1\n if self.counter[msg] > self.maxC:\n self.maxC = self.counter[msg]\n self.maxMsg = msg\nif le... | <|body_start_0|>
self.fifo = []
self.counter = {}
self.maxC = 0
self.maxMsg = ''
<|end_body_0|>
<|body_start_1|>
self.fifo.append(msg)
if msg not in self.counter:
self.counter[msg] = 1
else:
self.counter[msg] = self.counter[msg] + 1
... | Spams together with chat. | Spam | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Spam:
"""Spams together with chat."""
def __init__(self, _):
"""Initialize variables."""
<|body_0|>
def match(self, bot, user, msg, tag_info):
"""Add message to queue. Match if a message was spammed more than NECESSARY_SPAM."""
<|body_1|>
def run(sel... | stack_v2_sparse_classes_36k_train_004771 | 1,352 | permissive | [
{
"docstring": "Initialize variables.",
"name": "__init__",
"signature": "def __init__(self, _)"
},
{
"docstring": "Add message to queue. Match if a message was spammed more than NECESSARY_SPAM.",
"name": "match",
"signature": "def match(self, bot, user, msg, tag_info)"
},
{
"doc... | 3 | null | Implement the Python class `Spam` described below.
Class description:
Spams together with chat.
Method signatures and docstrings:
- def __init__(self, _): Initialize variables.
- def match(self, bot, user, msg, tag_info): Add message to queue. Match if a message was spammed more than NECESSARY_SPAM.
- def run(self, b... | Implement the Python class `Spam` described below.
Class description:
Spams together with chat.
Method signatures and docstrings:
- def __init__(self, _): Initialize variables.
- def match(self, bot, user, msg, tag_info): Add message to queue. Match if a message was spammed more than NECESSARY_SPAM.
- def run(self, b... | 6bef453bf5042401ecdafcdda404452dfd982ecf | <|skeleton|>
class Spam:
"""Spams together with chat."""
def __init__(self, _):
"""Initialize variables."""
<|body_0|>
def match(self, bot, user, msg, tag_info):
"""Add message to queue. Match if a message was spammed more than NECESSARY_SPAM."""
<|body_1|>
def run(sel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Spam:
"""Spams together with chat."""
def __init__(self, _):
"""Initialize variables."""
self.fifo = []
self.counter = {}
self.maxC = 0
self.maxMsg = ''
def match(self, bot, user, msg, tag_info):
"""Add message to queue. Match if a message was spammed ... | the_stack_v2_python_sparse | bot/commands/spam.py | ghostduck/monkalot | train | 0 |
c4283acfd717a08df6924e388d70454ad65d1d31 | [
"pre = ''\nmin_length = 0\nif len(strs) != 0:\n min_length = min((len(ele) for ele in strs))\nfor x in range(min_length):\n for y in range(len(strs) - 1):\n if strs[y][0:x + 1] != strs[y + 1][0:x + 1]:\n return pre\n pre = strs[0][0:x + 1]\nreturn pre",
"res = ''\nif len(strs) == 0:\n ... | <|body_start_0|>
pre = ''
min_length = 0
if len(strs) != 0:
min_length = min((len(ele) for ele in strs))
for x in range(min_length):
for y in range(len(strs) - 1):
if strs[y][0:x + 1] != strs[y + 1][0:x + 1]:
return pre
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
pre = ''
min_length =... | stack_v2_sparse_classes_36k_train_004772 | 977 | no_license | [
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
},
{
"docstring": ":type strs: List[str] :rtype: str",
"name": "longestCommonPrefix",
"signature": "def longestCommonPrefix(self, strs)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
- def longestCommonPrefix(self, strs): :type strs: List[str] :rtype: str
<|skeleton|>
class Solution:
... | a509b383a42f54313970168d9faa11f088f18708 | <|skeleton|>
class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_0|>
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def longestCommonPrefix(self, strs):
""":type strs: List[str] :rtype: str"""
pre = ''
min_length = 0
if len(strs) != 0:
min_length = min((len(ele) for ele in strs))
for x in range(min_length):
for y in range(len(strs) - 1):
... | the_stack_v2_python_sparse | 0014_Longest_Common_Prefix.py | bingli8802/leetcode | train | 0 | |
35547125c232762908edb988350b5da0d62f80ef | [
"self._lowercase_text = lowercase_text\nself._remove_punctuation = remove_punctuation\nself._max_token_length = max_token_length\nself._remove_nonascii_character = remove_nonascii_character",
"text = text.strip()\nif self._lowercase_text:\n text = text.lower()\ntokens = nltk.word_tokenize(text)\nif self._remov... | <|body_start_0|>
self._lowercase_text = lowercase_text
self._remove_punctuation = remove_punctuation
self._max_token_length = max_token_length
self._remove_nonascii_character = remove_nonascii_character
<|end_body_0|>
<|body_start_1|>
text = text.strip()
if self._lowerca... | Tokenizer using NLTK with a few additional options. | Tokenizer | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tokenizer:
"""Tokenizer using NLTK with a few additional options."""
def __init__(self, lowercase_text=False, remove_punctuation=False, remove_nonascii_character=False, max_token_length=-1):
"""Constructor. Args: lowercase_text: If True, convert text to lower case before tokenization... | stack_v2_sparse_classes_36k_train_004773 | 9,596 | permissive | [
{
"docstring": "Constructor. Args: lowercase_text: If True, convert text to lower case before tokenization. remove_punctuation: If True, remove punctuation in the tokens. remove_nonascii_character: If True, remove non-ascii characters within a token. max_token_length: Remove tokens with length larger than this ... | 2 | stack_v2_sparse_classes_30k_train_003499 | Implement the Python class `Tokenizer` described below.
Class description:
Tokenizer using NLTK with a few additional options.
Method signatures and docstrings:
- def __init__(self, lowercase_text=False, remove_punctuation=False, remove_nonascii_character=False, max_token_length=-1): Constructor. Args: lowercase_text... | Implement the Python class `Tokenizer` described below.
Class description:
Tokenizer using NLTK with a few additional options.
Method signatures and docstrings:
- def __init__(self, lowercase_text=False, remove_punctuation=False, remove_nonascii_character=False, max_token_length=-1): Constructor. Args: lowercase_text... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class Tokenizer:
"""Tokenizer using NLTK with a few additional options."""
def __init__(self, lowercase_text=False, remove_punctuation=False, remove_nonascii_character=False, max_token_length=-1):
"""Constructor. Args: lowercase_text: If True, convert text to lower case before tokenization... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Tokenizer:
"""Tokenizer using NLTK with a few additional options."""
def __init__(self, lowercase_text=False, remove_punctuation=False, remove_nonascii_character=False, max_token_length=-1):
"""Constructor. Args: lowercase_text: If True, convert text to lower case before tokenization. remove_punc... | the_stack_v2_python_sparse | screen2words/create_tf_example_main.py | Jimmy-INL/google-research | train | 1 |
2a32338f98b7476505ae5ffbe6b6b1c8063729ed | [
"Block.__init__(self, parent, idevice)\nself.idevice = idevice\nself.questionElements = []\nfor question in idevice.questions:\n self.questionElements.append(SelectquestionElement(question))",
"Block.process(self, request)\nif 'addQuestion' + self.id in request.args:\n self.idevice.addQuestion()\n self.i... | <|body_start_0|>
Block.__init__(self, parent, idevice)
self.idevice = idevice
self.questionElements = []
for question in idevice.questions:
self.questionElements.append(SelectquestionElement(question))
<|end_body_0|>
<|body_start_1|>
Block.process(self, request)
... | MultiSelectBlock can render and process MultiSelectIdevices as XHTML | MultiSelectBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSelectBlock:
"""MultiSelectBlock can render and process MultiSelectIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server"""
... | stack_v2_sparse_classes_36k_train_004774 | 3,405 | no_license | [
{
"docstring": "Initialize a new Block object",
"name": "__init__",
"signature": "def __init__(self, parent, idevice)"
},
{
"docstring": "Process the request arguments from the web server",
"name": "process",
"signature": "def process(self, request)"
},
{
"docstring": "Returns an... | 5 | null | Implement the Python class `MultiSelectBlock` described below.
Class description:
MultiSelectBlock can render and process MultiSelectIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize a new Block object
- def process(self, request): Process the request arguments from... | Implement the Python class `MultiSelectBlock` described below.
Class description:
MultiSelectBlock can render and process MultiSelectIdevices as XHTML
Method signatures and docstrings:
- def __init__(self, parent, idevice): Initialize a new Block object
- def process(self, request): Process the request arguments from... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class MultiSelectBlock:
"""MultiSelectBlock can render and process MultiSelectIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
<|body_0|>
def process(self, request):
"""Process the request arguments from the web server"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiSelectBlock:
"""MultiSelectBlock can render and process MultiSelectIdevices as XHTML"""
def __init__(self, parent, idevice):
"""Initialize a new Block object"""
Block.__init__(self, parent, idevice)
self.idevice = idevice
self.questionElements = []
for questio... | the_stack_v2_python_sparse | eXe/rev2735-2877/base-trunk-2735/exe/webui/multiselectblock.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
6c62ead65026947d3a9b8bb74f816de0c6c4e482 | [
"BaseType.__init__(self, cle)\nself.nom_singulier = 'un cadavre'\nself.nom_pluriel = 'cadavres'\nself.etat_singulier = 'repose ici'\nself.etat_pluriel = 'reposent ici'\nself._attributs = {'pnj': Attribut(), 'apparition': Attribut(datetime.now)}",
"ajout = ''\ndiff = 0\nif hasattr(self, 'apparition'):\n diff = ... | <|body_start_0|>
BaseType.__init__(self, cle)
self.nom_singulier = 'un cadavre'
self.nom_pluriel = 'cadavres'
self.etat_singulier = 'repose ici'
self.etat_pluriel = 'reposent ici'
self._attributs = {'pnj': Attribut(), 'apparition': Attribut(datetime.now)}
<|end_body_0|>
... | Type d'objet: cadavre. | Cadavre | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cadavre:
"""Type d'objet: cadavre."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def get_nom(self, nombre=1, pluriels=True):
"""Retourne le nom complet en fonction du nombre. Par exemple : Si nombre == 1 : retourne le nom singulier Sinon... | stack_v2_sparse_classes_36k_train_004775 | 3,627 | permissive | [
{
"docstring": "Constructeur de l'objet",
"name": "__init__",
"signature": "def __init__(self, cle='')"
},
{
"docstring": "Retourne le nom complet en fonction du nombre. Par exemple : Si nombre == 1 : retourne le nom singulier Sinon : retourne le nombre et le nom pluriel",
"name": "get_nom",... | 2 | null | Implement the Python class `Cadavre` described below.
Class description:
Type d'objet: cadavre.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def get_nom(self, nombre=1, pluriels=True): Retourne le nom complet en fonction du nombre. Par exemple : Si nombre == 1 : retourne l... | Implement the Python class `Cadavre` described below.
Class description:
Type d'objet: cadavre.
Method signatures and docstrings:
- def __init__(self, cle=''): Constructeur de l'objet
- def get_nom(self, nombre=1, pluriels=True): Retourne le nom complet en fonction du nombre. Par exemple : Si nombre == 1 : retourne l... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class Cadavre:
"""Type d'objet: cadavre."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
<|body_0|>
def get_nom(self, nombre=1, pluriels=True):
"""Retourne le nom complet en fonction du nombre. Par exemple : Si nombre == 1 : retourne le nom singulier Sinon... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Cadavre:
"""Type d'objet: cadavre."""
def __init__(self, cle=''):
"""Constructeur de l'objet"""
BaseType.__init__(self, cle)
self.nom_singulier = 'un cadavre'
self.nom_pluriel = 'cadavres'
self.etat_singulier = 'repose ici'
self.etat_pluriel = 'reposent ici... | the_stack_v2_python_sparse | src/primaires/objet/types/cadavre.py | vincent-lg/tsunami | train | 5 |
26b631a4916ee177d32dd8431a81b122d892479d | [
"self.m = m\np_style = json.loads((ss.JSON_DIR / 'progress_bar.json').read_text())\nself.w_loading = sw.ProgressLinear(indeterminate=False, background_color=color.menu, color=p_style['color'][v.theme.dark])\nself.tile = sw.Tile('nested', '')\nkwargs.setdefault('position', 'topright')\nsuper().__init__(icon_content=... | <|body_start_0|>
self.m = m
p_style = json.loads((ss.JSON_DIR / 'progress_bar.json').read_text())
self.w_loading = sw.ProgressLinear(indeterminate=False, background_color=color.menu, color=p_style['color'][v.theme.dark])
self.tile = sw.Tile('nested', '')
kwargs.setdefault('positi... | LayersControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayersControl:
def __init__(self, m: Map, **kwargs) -> None:
"""Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the user can adapt the alpha channel or even hide it completely Args: m: the map to display the layers kw... | stack_v2_sparse_classes_36k_train_004776 | 8,901 | permissive | [
{
"docstring": "Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the user can adapt the alpha channel or even hide it completely Args: m: the map to display the layers kwargs: optional extra parameters for the ipyleaflet.WidgetControl",
"... | 2 | stack_v2_sparse_classes_30k_train_011672 | Implement the Python class `LayersControl` described below.
Class description:
Implement the LayersControl class.
Method signatures and docstrings:
- def __init__(self, m: Map, **kwargs) -> None: Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the... | Implement the Python class `LayersControl` described below.
Class description:
Implement the LayersControl class.
Method signatures and docstrings:
- def __init__(self, m: Map, **kwargs) -> None: Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the... | b26c7d698659d5c5a2029d02fc94dcd9daf0df98 | <|skeleton|>
class LayersControl:
def __init__(self, m: Map, **kwargs) -> None:
"""Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the user can adapt the alpha channel or even hide it completely Args: m: the map to display the layers kw... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LayersControl:
def __init__(self, m: Map, **kwargs) -> None:
"""Richer layerControl to add some controls over the lyers displayed on the map. Each layer is associated to a line where the user can adapt the alpha channel or even hide it completely Args: m: the map to display the layers kwargs: optional... | the_stack_v2_python_sparse | sepal_ui/mapping/layers_control.py | 12rambau/sepal_ui | train | 17 | |
3cc96578da0545df70725468ca2bafd41298e1c8 | [
"super(CopyFiles, self).__init__()\nself.filenames = filenames\nself.storage = storage\nself.subdir = subdir\nreturn",
"for name in self.filenames:\n self.logger.debug('Copying {0}'.format(name))\n self.storage.copy(name, self.subdir)\nreturn"
] | <|body_start_0|>
super(CopyFiles, self).__init__()
self.filenames = filenames
self.storage = storage
self.subdir = subdir
return
<|end_body_0|>
<|body_start_1|>
for name in self.filenames:
self.logger.debug('Copying {0}'.format(name))
self.storage... | A tool to copy files to storage. | CopyFiles | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CopyFiles:
"""A tool to copy files to storage."""
def __init__(self, filenames, storage, subdir=None):
""":param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the storage folder to send copy to"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_004777 | 815 | permissive | [
{
"docstring": ":param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the storage folder to send copy to",
"name": "__init__",
"signature": "def __init__(self, filenames, storage, subdir=None)"
},
{
"docstring": "Copies the files in filen... | 2 | null | Implement the Python class `CopyFiles` described below.
Class description:
A tool to copy files to storage.
Method signatures and docstrings:
- def __init__(self, filenames, storage, subdir=None): :param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the stora... | Implement the Python class `CopyFiles` described below.
Class description:
A tool to copy files to storage.
Method signatures and docstrings:
- def __init__(self, filenames, storage, subdir=None): :param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the stora... | b4d1c77e1d611fe2b30768b42bdc7493afb0ea95 | <|skeleton|>
class CopyFiles:
"""A tool to copy files to storage."""
def __init__(self, filenames, storage, subdir=None):
""":param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the storage folder to send copy to"""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CopyFiles:
"""A tool to copy files to storage."""
def __init__(self, filenames, storage, subdir=None):
""":param: - `filenames`: an iterator of filenames to copy - `storage`: The copier. - `subdir`: A sub-directory in the storage folder to send copy to"""
super(CopyFiles, self).__init__()... | the_stack_v2_python_sparse | apetools/tools/copyfiles.py | russell-n/oldape | train | 0 |
6ddaaea2cfe58ad123a32643a94de2806d72fd49 | [
"image_id = self._create_image()\nmember = self.image_member_client.create_image_member(image_id, member=self.alt_tenant_id)\nself.assertEqual(member['status'], 'pending')\nself.assertRaises(lib_exc.BadRequest, self.alt_image_member_client.update_image_member, image_id, self.alt_tenant_id, status='notavalidstatus')... | <|body_start_0|>
image_id = self._create_image()
member = self.image_member_client.create_image_member(image_id, member=self.alt_tenant_id)
self.assertEqual(member['status'], 'pending')
self.assertRaises(lib_exc.BadRequest, self.alt_image_member_client.update_image_member, image_id, self... | Negative tests of image members | ImagesMemberNegativeTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImagesMemberNegativeTest:
"""Negative tests of image members"""
def test_image_share_invalid_status(self):
"""Test updating image member status to invalid status should fail"""
<|body_0|>
def test_image_share_owner_cannot_accept(self):
"""Test that image owner ca... | stack_v2_sparse_classes_36k_train_004778 | 2,236 | permissive | [
{
"docstring": "Test updating image member status to invalid status should fail",
"name": "test_image_share_invalid_status",
"signature": "def test_image_share_invalid_status(self)"
},
{
"docstring": "Test that image owner can't accept image shared to other member",
"name": "test_image_share... | 2 | null | Implement the Python class `ImagesMemberNegativeTest` described below.
Class description:
Negative tests of image members
Method signatures and docstrings:
- def test_image_share_invalid_status(self): Test updating image member status to invalid status should fail
- def test_image_share_owner_cannot_accept(self): Tes... | Implement the Python class `ImagesMemberNegativeTest` described below.
Class description:
Negative tests of image members
Method signatures and docstrings:
- def test_image_share_invalid_status(self): Test updating image member status to invalid status should fail
- def test_image_share_owner_cannot_accept(self): Tes... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class ImagesMemberNegativeTest:
"""Negative tests of image members"""
def test_image_share_invalid_status(self):
"""Test updating image member status to invalid status should fail"""
<|body_0|>
def test_image_share_owner_cannot_accept(self):
"""Test that image owner ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImagesMemberNegativeTest:
"""Negative tests of image members"""
def test_image_share_invalid_status(self):
"""Test updating image member status to invalid status should fail"""
image_id = self._create_image()
member = self.image_member_client.create_image_member(image_id, member=s... | the_stack_v2_python_sparse | tempest/api/image/v2/test_images_member_negative.py | openstack/tempest | train | 270 |
472ff4ef152cd76d3430fd4f7f11710d92ca1950 | [
"self.width = width\nself.height = height\nself.board = []\nfor i in range(height):\n row = []\n for j in range(width):\n row.append('.')\n self.board.append(row)",
"random.seed(seed_number)\nfor i in range(self.height):\n for j in range(self.width):\n random_number = random.randint(0, 1... | <|body_start_0|>
self.width = width
self.height = height
self.board = []
for i in range(height):
row = []
for j in range(width):
row.append('.')
self.board.append(row)
<|end_body_0|>
<|body_start_1|>
random.seed(seed_number)
... | Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-negative integer. Attribute board: the board of the game world. Invaria... | Life | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Life:
"""Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-negative integer. Attribute board: the ... | stack_v2_sparse_classes_36k_train_004779 | 4,872 | no_license | [
{
"docstring": "Initializes the Game of Life with the given width and height. Also initializes the attribute board to be of the right size, and with all cells dead. Precondition: width and height are nonnegative integers.",
"name": "__init__",
"signature": "def __init__(self, width, height)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_012914 | Implement the Python class `Life` described below.
Class description:
Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-... | Implement the Python class `Life` described below.
Class description:
Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-... | 0b4b957720710d7ace0c12dffda5331fadbe2653 | <|skeleton|>
class Life:
"""Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-negative integer. Attribute board: the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Life:
"""Describes the world of Conway's Game of Life. Attribute width: the width of the game world in number of cells. Invariant: width is a non-negative integer. Attribute height: the height of the game world in number of cells. Invariant: height is a non-negative integer. Attribute board: the board of the ... | the_stack_v2_python_sparse | Assignments/a5/skeleton/a5.py | futuregoogle/CS1110 | train | 0 |
9255d3e6c8a5225f3c6444051b220bf9674194dd | [
"sn = self.env['stock.production.lot'].search([])\nfor record in sn:\n if record.qty_location:\n record.qty_location = [(5, 0, 0)]",
"self.clear_all_previous_sn_locations()\nstock = self.env['stock.quant'].search([('quantity', '>', 0)])\nsn = self.env['stock.production.lot'].search([])\nfor line in stoc... | <|body_start_0|>
sn = self.env['stock.production.lot'].search([])
for record in sn:
if record.qty_location:
record.qty_location = [(5, 0, 0)]
<|end_body_0|>
<|body_start_1|>
self.clear_all_previous_sn_locations()
stock = self.env['stock.quant'].search([('quan... | class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga | FlspStockProductionLotFilterSn | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlspStockProductionLotFilterSn:
"""class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def clear_all_previous_sn_locations(self):
"... | stack_v2_sparse_classes_36k_train_004780 | 7,672 | no_license | [
{
"docstring": "Purpose: To clear all the previous sn/lot locations info",
"name": "clear_all_previous_sn_locations",
"signature": "def clear_all_previous_sn_locations(self)"
},
{
"docstring": "Purpose: To check stock_quant for all lots/sn with qty >0 Writes the stock_qty location on the serial ... | 2 | stack_v2_sparse_classes_30k_train_006333 | Implement the Python class `FlspStockProductionLotFilterSn` described below.
Class description:
class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga
Method signatures an... | Implement the Python class `FlspStockProductionLotFilterSn` described below.
Class description:
class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga
Method signatures an... | 4a82cd5cfd1898c6da860cb68dff3a14e037bbad | <|skeleton|>
class FlspStockProductionLotFilterSn:
"""class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def clear_all_previous_sn_locations(self):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlspStockProductionLotFilterSn:
"""class_name: FlspStockProductionLotFilterSn inherit: stock.production.lot Purpose: To add a check box on stock_production_lot when the qty is greater than 1 Date: Mar/29th/2021/M Author: Sami Byaruhanga"""
def clear_all_previous_sn_locations(self):
"""Purpose: To... | the_stack_v2_python_sparse | flsp_mrp_filter_sn/models/filter_sn_method.py | odoo-smg/firstlight | train | 3 |
5fb0b698b9051fbda07caa7376a96c5c9d1227cd | [
"self.data = nums[0:]\nself.size = int(math.sqrt(len(nums)))\nself.block = [0] * int(math.ceil(len(nums) / float(self.size)))\nfor i in range(0, len(nums)):\n self.block[i / self.size] += nums[i]",
"delta = val - self.data[i]\nself.block[i / self.size] += delta\nself.data[i] = val",
"start = i / self.size\ne... | <|body_start_0|>
self.data = nums[0:]
self.size = int(math.sqrt(len(nums)))
self.block = [0] * int(math.ceil(len(nums) / float(self.size)))
for i in range(0, len(nums)):
self.block[i / self.size] += nums[i]
<|end_body_0|>
<|body_start_1|>
delta = val - self.data[i]
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k_train_004781 | 1,240 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: None",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | stack_v2_sparse_classes_30k_train_008052 | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: None
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 176cc1db3291843fb068f06d0180766dd8c3122c | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: None"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.data = nums[0:]
self.size = int(math.sqrt(len(nums)))
self.block = [0] * int(math.ceil(len(nums) / float(self.size)))
for i in range(0, len(nums)):
self.block[i / self.size] += nums[i]
... | the_stack_v2_python_sparse | 2019/segment_tree/range_sum_query_mutable_307_new.py | yehongyu/acode | train | 0 | |
94a556304f27fdee0e84739c0b9736213dedd478 | [
"raise NotImplementedError('This feature is extremely depricated and probably does not work properly anymore.')\nsuper(NormFiringRates, self).__init__(*args, **kwargs)\nimport time\nself.starttime = time.time()\nself.elapsedtime = 0\nself.count = 0\nself.mFR = None\nself.mFR2 = None\nself.sdFR = None\nself.updated ... | <|body_start_0|>
raise NotImplementedError('This feature is extremely depricated and probably does not work properly anymore.')
super(NormFiringRates, self).__init__(*args, **kwargs)
import time
self.starttime = time.time()
self.elapsedtime = 0
self.count = 0
self... | Docstring | NormFiringRates | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NormFiringRates:
"""Docstring"""
def __init__(self, *args, **kwargs):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def update_fr_vals(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_1|>
def update_cursor(self):... | stack_v2_sparse_classes_36k_train_004782 | 8,107 | permissive | [
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Docstring Parameters ---------- Returns -------",
"name": "update_fr_vals",
"signature": "def update_fr_vals(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_002377 | Implement the Python class `NormFiringRates` described below.
Class description:
Docstring
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Docstring Parameters ---------- Returns -------
- def update_fr_vals(self): Docstring Parameters ---------- Returns -------
- def update_cursor(self): Doc... | Implement the Python class `NormFiringRates` described below.
Class description:
Docstring
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Docstring Parameters ---------- Returns -------
- def update_fr_vals(self): Docstring Parameters ---------- Returns -------
- def update_cursor(self): Doc... | a0e296aa663b49e767c9ebb274defb54b301eb12 | <|skeleton|>
class NormFiringRates:
"""Docstring"""
def __init__(self, *args, **kwargs):
"""Docstring Parameters ---------- Returns -------"""
<|body_0|>
def update_fr_vals(self):
"""Docstring Parameters ---------- Returns -------"""
<|body_1|>
def update_cursor(self):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NormFiringRates:
"""Docstring"""
def __init__(self, *args, **kwargs):
"""Docstring Parameters ---------- Returns -------"""
raise NotImplementedError('This feature is extremely depricated and probably does not work properly anymore.')
super(NormFiringRates, self).__init__(*args, *... | the_stack_v2_python_sparse | features/bmi_task_features.py | carmenalab/brain-python-interface | train | 9 |
2c1a39263c8aabf0ed5134fc355ffb55a65dfce9 | [
"log.trace('Getting the diff for roles.')\nroles = await self.bot.api_client.get('bot/roles')\ndb_roles = {_Role(**role_dict) for role_dict in roles}\nguild_roles = {_Role(id=role.id, name=role.name, colour=role.colour.value, permissions=role.permissions.value, position=role.position) for role in guild.roles}\nguil... | <|body_start_0|>
log.trace('Getting the diff for roles.')
roles = await self.bot.api_client.get('bot/roles')
db_roles = {_Role(**role_dict) for role_dict in roles}
guild_roles = {_Role(id=role.id, name=role.name, colour=role.colour.value, permissions=role.permissions.value, position=role... | Synchronise the database with roles in the cache. | RoleSyncer | [
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RoleSyncer:
"""Synchronise the database with roles in the cache."""
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of roles between the cache of `guild` and the database."""
<|body_0|>
async def _sync(self, diff: _Diff) -> None:
"""Syn... | stack_v2_sparse_classes_36k_train_004783 | 14,281 | permissive | [
{
"docstring": "Return the difference of roles between the cache of `guild` and the database.",
"name": "_get_diff",
"signature": "async def _get_diff(self, guild: Guild) -> _Diff"
},
{
"docstring": "Synchronise the database with the role cache of `guild`.",
"name": "_sync",
"signature":... | 2 | null | Implement the Python class `RoleSyncer` described below.
Class description:
Synchronise the database with roles in the cache.
Method signatures and docstrings:
- async def _get_diff(self, guild: Guild) -> _Diff: Return the difference of roles between the cache of `guild` and the database.
- async def _sync(self, diff... | Implement the Python class `RoleSyncer` described below.
Class description:
Synchronise the database with roles in the cache.
Method signatures and docstrings:
- async def _get_diff(self, guild: Guild) -> _Diff: Return the difference of roles between the cache of `guild` and the database.
- async def _sync(self, diff... | 232cc68b0a0ef210027beacb9b4f50ffeeaddd00 | <|skeleton|>
class RoleSyncer:
"""Synchronise the database with roles in the cache."""
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of roles between the cache of `guild` and the database."""
<|body_0|>
async def _sync(self, diff: _Diff) -> None:
"""Syn... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RoleSyncer:
"""Synchronise the database with roles in the cache."""
async def _get_diff(self, guild: Guild) -> _Diff:
"""Return the difference of roles between the cache of `guild` and the database."""
log.trace('Getting the diff for roles.')
roles = await self.bot.api_client.get(... | the_stack_v2_python_sparse | bot/cogs/sync/syncers.py | pormes/bot | train | 2 |
9114cf43474c93569c6cf8a41b6809c979fc0696 | [
"self.card_holder_name = card_holder_name\nself.account_number = account_number\nself.cvv = cvv\nself.expiration_month = expiration_month\nself.expiration_year = expiration_year\nself.billing_address = billing_address",
"if dictionary is None:\n return None\ncard_holder_name = dictionary.get('cardHolderName')\... | <|body_start_0|>
self.card_holder_name = card_holder_name
self.account_number = account_number
self.cvv = cvv
self.expiration_month = expiration_month
self.expiration_year = expiration_year
self.billing_address = billing_address
<|end_body_0|>
<|body_start_1|>
if... | Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type description here. billing_address (Addr... | Card | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type descrip... | stack_v2_sparse_classes_36k_train_004784 | 2,891 | permissive | [
{
"docstring": "Constructor for the Card class",
"name": "__init__",
"signature": "def __init__(self, card_holder_name=None, account_number=None, cvv=None, expiration_month=None, expiration_year=None, billing_address=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary A... | 2 | stack_v2_sparse_classes_30k_train_018487 | Implement the Python class `Card` described below.
Class description:
Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expir... | Implement the Python class `Card` described below.
Class description:
Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expir... | e1ca52116aabfcdb2f36c24ebd866cf00bb5c6c9 | <|skeleton|>
class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type descrip... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Card:
"""Implementation of the 'Card' model. Debit or Credit Card Attributes: card_holder_name (string): TODO: type description here. account_number (string): Card number. cvv (string): 3-4 digits expiration_month (string): TODO: type description here. expiration_year (string): TODO: type description here. bi... | the_stack_v2_python_sparse | plastiqpublicapi/models/card.py | jeffkynaston/sdk-spike-python-apimatic | train | 0 |
9fdc965a8da50427be46cfc887b7949c7913fa02 | [
"TaskManager.__init__(self)\nif task_result_timeout is None:\n task_result_timeout = 0\ntask.props[_KEY_DYNAMIC_TARGETS] = dynamic_targets\ntask.props[_KEY_TASK_RESULT_TIMEOUT] = task_result_timeout\ntask.props[_KEY_SEND_TARGET_COUNTS] = {}\ntask.props[_KEY_PENDING_CLIENT] = None",
"client_name = client_task.c... | <|body_start_0|>
TaskManager.__init__(self)
if task_result_timeout is None:
task_result_timeout = 0
task.props[_KEY_DYNAMIC_TARGETS] = dynamic_targets
task.props[_KEY_TASK_RESULT_TIMEOUT] = task_result_timeout
task.props[_KEY_SEND_TARGET_COUNTS] = {}
task.prop... | AnyRelayTaskManager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AnyRelayTaskManager:
def __init__(self, task: Task, task_result_timeout, dynamic_targets):
"""Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of Task task_result_timeout (int): timeout value on reply of one client dynamic_targets (bool): allow clients t... | stack_v2_sparse_classes_36k_train_004785 | 6,797 | permissive | [
{
"docstring": "Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of Task task_result_timeout (int): timeout value on reply of one client dynamic_targets (bool): allow clients to join after this task starts",
"name": "__init__",
"signature": "def __init__(self, task: Tas... | 4 | null | Implement the Python class `AnyRelayTaskManager` described below.
Class description:
Implement the AnyRelayTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, task_result_timeout, dynamic_targets): Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of ... | Implement the Python class `AnyRelayTaskManager` described below.
Class description:
Implement the AnyRelayTaskManager class.
Method signatures and docstrings:
- def __init__(self, task: Task, task_result_timeout, dynamic_targets): Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of ... | 1433290c203bd23f34c29e11795ce592bc067888 | <|skeleton|>
class AnyRelayTaskManager:
def __init__(self, task: Task, task_result_timeout, dynamic_targets):
"""Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of Task task_result_timeout (int): timeout value on reply of one client dynamic_targets (bool): allow clients t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AnyRelayTaskManager:
def __init__(self, task: Task, task_result_timeout, dynamic_targets):
"""Task manager for relay controller on SendOrder.ANY. Args: task (Task): an instance of Task task_result_timeout (int): timeout value on reply of one client dynamic_targets (bool): allow clients to join after t... | the_stack_v2_python_sparse | nvflare/apis/impl/any_relay_manager.py | NVIDIA/NVFlare | train | 442 | |
20aedacc18cc7f0f03310d3cbe740c73290aea06 | [
"TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)\nself.data = parse_product(self)\nself.afos = f'CWA{self.source[1:]}'",
"data = self.data\nif data is None:\n return\nif data.is_corrected:\n txn.execute('DELETE from cwas where issue = %s and num = %s and center = %s', (data.issue, dat... | <|body_start_0|>
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = parse_product(self)
self.afos = f'CWA{self.source[1:]}'
<|end_body_0|>
<|body_start_1|>
data = self.data
if data is None:
return
if data.is_corrected:
... | Represents a Center Weather Advsiory (CWA) product. | CWAProduct | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Do SQL related stuff that is required"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_004786 | 9,359 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None)"
},
{
"docstring": "Do SQL related stuff that is required",
"name": "sql",
"signature": "def sql(self, txn)"
},
{
"docstring": "Return the... | 3 | stack_v2_sparse_classes_30k_train_014262 | Implement the Python class `CWAProduct` described below.
Class description:
Represents a Center Weather Advsiory (CWA) product.
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Do SQL related stuff that is required
- d... | Implement the Python class `CWAProduct` described below.
Class description:
Represents a Center Weather Advsiory (CWA) product.
Method signatures and docstrings:
- def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None): constructor
- def sql(self, txn): Do SQL related stuff that is required
- d... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
<|body_0|>
def sql(self, txn):
"""Do SQL related stuff that is required"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CWAProduct:
"""Represents a Center Weather Advsiory (CWA) product."""
def __init__(self, text, utcnow=None, ugc_provider=None, nwsli_provider=None):
"""constructor"""
TextProduct.__init__(self, text, utcnow, ugc_provider, nwsli_provider)
self.data = parse_product(self)
sel... | the_stack_v2_python_sparse | src/pyiem/nws/products/cwa.py | akrherz/pyIEM | train | 38 |
be7f35f4965cd3444bb23533ab5e812ab1bee08e | [
"assert isinstance(name, str)\nassert max_level in (3, 5)\nassert isinstance(damage_type, DamageType)\nif co_mp is None:\n co_mp = [0, 0]\nself.name, self.max_level = (name, max_level)\nself.co_ad, self.co_ap, self.co_hp, self.co_mp = (co_ad, co_ap, co_hp, co_mp)\nself.damage_type = damage_type\nself.extra_func ... | <|body_start_0|>
assert isinstance(name, str)
assert max_level in (3, 5)
assert isinstance(damage_type, DamageType)
if co_mp is None:
co_mp = [0, 0]
self.name, self.max_level = (name, max_level)
self.co_ad, self.co_ap, self.co_hp, self.co_mp = (co_ad, co_ap, c... | 技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种 | Ability | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Ability:
"""技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种"""
def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=None, damage_type=DamageType.ad, extra_func=None):
""":param name: :param max_level: :param co_ad: :param co_ap: :param co_hp: :param rare_da... | stack_v2_sparse_classes_36k_train_004787 | 13,336 | no_license | [
{
"docstring": ":param name: :param max_level: :param co_ad: :param co_ap: :param co_hp: :param rare_damage: :param co_mp: :param co_all: :param damage_type: :param extra_func:",
"name": "__init__",
"signature": "def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=No... | 3 | stack_v2_sparse_classes_30k_train_001159 | Implement the Python class `Ability` described below.
Class description:
技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种
Method signatures and docstrings:
- def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=None, damage_type=DamageType.ad, extra_func=None): :param name: :param max_level:... | Implement the Python class `Ability` described below.
Class description:
技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种
Method signatures and docstrings:
- def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=None, damage_type=DamageType.ad, extra_func=None): :param name: :param max_level:... | e240a800bfd11ffc1ef78e02aaff4682e65e09ad | <|skeleton|>
class Ability:
"""技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种"""
def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=None, damage_type=DamageType.ad, extra_func=None):
""":param name: :param max_level: :param co_ad: :param co_ap: :param co_hp: :param rare_da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Ability:
"""技能 描述技能的裸伤害(无装备) 系数加成 伤害类型 目前伤害类型只能是一种"""
def __init__(self, name, max_level, co_ad, co_ap, co_hp, rare_damage, co_mp=None, co_all=None, damage_type=DamageType.ad, extra_func=None):
""":param name: :param max_level: :param co_ad: :param co_ap: :param co_hp: :param rare_damage: :param ... | the_stack_v2_python_sparse | lol/unitmodel.py | war16641/python | train | 0 |
661ef93ab5d89d74b9428ea2840a4849108ccc77 | [
"if origin is None:\n origin = ((shape[0] - 1) / 2.0, (shape[1] - 1) / 2.0)\nif r_map is None:\n r_map = radial_grid(origin, shape)\nphi_map = angle_grid(origin, shape)\nself.expected_shape = tuple(shape)\nif mask is not None:\n if mask.shape != self.expected_shape:\n raise ValueError('\"mask\" has ... | <|body_start_0|>
if origin is None:
origin = ((shape[0] - 1) / 2.0, (shape[1] - 1) / 2.0)
if r_map is None:
r_map = radial_grid(origin, shape)
phi_map = angle_grid(origin, shape)
self.expected_shape = tuple(shape)
if mask is not None:
if mask.s... | Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi. | RPhiBinnedStatistic | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. sha... | stack_v2_sparse_classes_36k_train_004788 | 33,902 | permissive | [
{
"docstring": "Parameters: ----------- shape : tuple of ints of length 2. shape of image. bins : int or [int, int] or array_like or [array, array], optional The bin specification: * number of bins for the two dimensions (nr=nphi=bins), * number of bins in each dimension (nr, nphi = bins), * bin edges for the t... | 2 | stack_v2_sparse_classes_30k_test_000353 | Implement the Python class `RPhiBinnedStatistic` described below.
Class description:
Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi.
Method signatures and docstrings:
- def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Param... | Implement the Python class `RPhiBinnedStatistic` described below.
Class description:
Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi.
Method signatures and docstrings:
- def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'): Param... | 0e54357c360b0784b8ee279a8ebf7f9fe011a3d6 | <|skeleton|>
class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. sha... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RPhiBinnedStatistic:
"""Create a 2-dimensional histogram by binning a 2-dimensional image in both radius and phi."""
def __init__(self, shape, bins=10, range=None, origin=None, mask=None, r_map=None, statistic='mean'):
"""Parameters: ----------- shape : tuple of ints of length 2. shape of image. ... | the_stack_v2_python_sparse | skbeam/core/accumulators/binned_statistic.py | scikit-beam/scikit-beam | train | 77 |
20bfdff837f91a53e7a3e0f6b4adf174d2d99eba | [
"installed = dpkg.installed()\nopenmpi = ('openmpi-bin', 'libopenmpi-dev')\nmissing = [pkg for pkg in openmpi if pkg not in installed]\nif not missing:\n yield (OpenMPI.flavor, openmpi)\nmpich = ('mpich', 'libmpich-dev')\nmissing = [pkg for pkg in mpich if pkg not in installed]\nif not missing:\n yield (MPICH... | <|body_start_0|>
installed = dpkg.installed()
openmpi = ('openmpi-bin', 'libopenmpi-dev')
missing = [pkg for pkg in openmpi if pkg not in installed]
if not missing:
yield (OpenMPI.flavor, openmpi)
mpich = ('mpich', 'libmpich-dev')
missing = [pkg for pkg in mpi... | The package manager for MPI packages | MPI | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide alternative compatible implementations of python on dpkg mach... | stack_v2_sparse_classes_36k_train_004789 | 10,213 | permissive | [
{
"docstring": "Identify the default implementation of MPI on dpkg machines",
"name": "dpkgAlternatives",
"signature": "def dpkgAlternatives(cls, dpkg)"
},
{
"docstring": "Provide alternative compatible implementations of python on dpkg machines, starting with the package the user has selected a... | 3 | stack_v2_sparse_classes_30k_train_005232 | Implement the Python class `MPI` described below.
Class description:
The package manager for MPI packages
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Identify the default implementation of MPI on dpkg machines
- def dpkgPackages(cls, packager): Provide alternative compatible implementations o... | Implement the Python class `MPI` described below.
Class description:
The package manager for MPI packages
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Identify the default implementation of MPI on dpkg machines
- def dpkgPackages(cls, packager): Provide alternative compatible implementations o... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide alternative compatible implementations of python on dpkg mach... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MPI:
"""The package manager for MPI packages"""
def dpkgAlternatives(cls, dpkg):
"""Identify the default implementation of MPI on dpkg machines"""
installed = dpkg.installed()
openmpi = ('openmpi-bin', 'libopenmpi-dev')
missing = [pkg for pkg in openmpi if pkg not in insta... | the_stack_v2_python_sparse | packages/pyre/externals/MPI.py | pyre/pyre | train | 27 |
d0e720246d040ced0da514017004dac13330ac59 | [
"self.log = log\nself.boto3_factory = boto3_factory\nself.batch_client = boto3_factory.get_client('batch')",
"jobs = self.batch_client.describe_jobs(jobs=job_ids)['jobs']\nself.log.debug(jobs)\nif len(jobs) != len(job_ids):\n available_job_ids = []\n for job in jobs:\n available_job_ids.append(job['j... | <|body_start_0|>
self.log = log
self.boto3_factory = boto3_factory
self.batch_client = boto3_factory.get_client('batch')
<|end_body_0|>
<|body_start_1|>
jobs = self.batch_client.describe_jobs(jobs=job_ids)['jobs']
self.log.debug(jobs)
if len(jobs) != len(job_ids):
... | awsbkill command. | AWSBkillCommand | [
"Python-2.0",
"GPL-1.0-or-later",
"MPL-2.0",
"MIT",
"LicenseRef-scancode-python-cwi",
"BSD-3-Clause",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-free-unknown",
"Apache-2.0",
"MIT-0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AWSBkillCommand:
"""awsbkill command."""
def __init__(self, log, boto3_factory):
"""Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object"""
<|body_0|>
def run(self, job_ids, reason):
"""Kill/cancel the jobs. :param... | stack_v2_sparse_classes_36k_train_004790 | 4,777 | permissive | [
{
"docstring": "Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object",
"name": "__init__",
"signature": "def __init__(self, log, boto3_factory)"
},
{
"docstring": "Kill/cancel the jobs. :param job_ids: list of job ids :param reason: optional reaso... | 3 | null | Implement the Python class `AWSBkillCommand` described below.
Class description:
awsbkill command.
Method signatures and docstrings:
- def __init__(self, log, boto3_factory): Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object
- def run(self, job_ids, reason): Kill/ca... | Implement the Python class `AWSBkillCommand` described below.
Class description:
awsbkill command.
Method signatures and docstrings:
- def __init__(self, log, boto3_factory): Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object
- def run(self, job_ids, reason): Kill/ca... | a213978a09ea7fc80855bf55c539861ea95259f9 | <|skeleton|>
class AWSBkillCommand:
"""awsbkill command."""
def __init__(self, log, boto3_factory):
"""Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object"""
<|body_0|>
def run(self, job_ids, reason):
"""Kill/cancel the jobs. :param... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AWSBkillCommand:
"""awsbkill command."""
def __init__(self, log, boto3_factory):
"""Initialize the object. :param log: log :param boto3_factory: an initialized Boto3ClientFactory object"""
self.log = log
self.boto3_factory = boto3_factory
self.batch_client = boto3_factory.... | the_stack_v2_python_sparse | awsbatch-cli/src/awsbatch/awsbkill.py | aws/aws-parallelcluster | train | 520 |
76df1c8a78ae4796fcd7597418d950ae2b4fa5c1 | [
"if not arr:\n return []\nimport heapq\nreturn heapq.nsmallest(k, arr)",
"if not arr:\n return []\n\ndef __sroted(arr):\n p = arr[0]\n left_arr = [i for i in arr if i < p]\n right_arr = [i for i in arr if i >= p]\n return left_arr + [p] + right_arr\nsk = __sroted(arr)\nreturn sk[:k]"
] | <|body_start_0|>
if not arr:
return []
import heapq
return heapq.nsmallest(k, arr)
<|end_body_0|>
<|body_start_1|>
if not arr:
return []
def __sroted(arr):
p = arr[0]
left_arr = [i for i in arr if i < p]
right_arr = [i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def get_least_numbers_heap(arr, k):
""":type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值"""
<|body_0|>
def get_least_numbers_sort(arr, k):
"""用快排先排序arr, 再取出来前K个数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not ... | stack_v2_sparse_classes_36k_train_004791 | 1,038 | no_license | [
{
"docstring": ":type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值",
"name": "get_least_numbers_heap",
"signature": "def get_least_numbers_heap(arr, k)"
},
{
"docstring": "用快排先排序arr, 再取出来前K个数",
"name": "get_least_numbers_sort",
"signature": "def get_least_numbers_sor... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_least_numbers_heap(arr, k): :type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值
- def get_least_numbers_sort(arr, k): 用快排先排序arr, 再取出来前K个数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def get_least_numbers_heap(arr, k): :type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值
- def get_least_numbers_sort(arr, k): 用快排先排序arr, 再取出来前K个数
<|skeleton|... | a3a1556abc5adb9325de54d64f9814e64b96db0f | <|skeleton|>
class Solution:
def get_least_numbers_heap(arr, k):
""":type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值"""
<|body_0|>
def get_least_numbers_sort(arr, k):
"""用快排先排序arr, 再取出来前K个数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def get_least_numbers_heap(arr, k):
""":type arr: List[int] :type k: int :rtype: List[int] 加入到heap中,从堆顶依次取出K个值"""
if not arr:
return []
import heapq
return heapq.nsmallest(k, arr)
def get_least_numbers_sort(arr, k):
"""用快排先排序arr, 再取出来前K个数"""
... | the_stack_v2_python_sparse | offer/40.py | BigerWANG/geek_algorithm | train | 0 | |
c11179133354dad7ac0f741aa0f833edd005f689 | [
"super().__init__(coordinator)\nself._attr_unique_id = f'{device.address}-signal-strength'\nself._attr_device_info = device_info",
"if (data := self.coordinator.data):\n return data.rssi\nreturn None"
] | <|body_start_0|>
super().__init__(coordinator)
self._attr_unique_id = f'{device.address}-signal-strength'
self._attr_device_info = device_info
<|end_body_0|>
<|body_start_1|>
if (data := self.coordinator.data):
return data.rssi
return None
<|end_body_1|>
| Sensor device. | RssiSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
<|... | stack_v2_sparse_classes_36k_train_004792 | 2,180 | permissive | [
{
"docstring": "Init sensor.",
"name": "__init__",
"signature": "def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None"
},
{
"docstring": "Return the value reported by the sensor.",
"name": "native_value",
"signature": "def native_value(... | 2 | stack_v2_sparse_classes_30k_train_015913 | Implement the Python class `RssiSensor` described below.
Class description:
Sensor device.
Method signatures and docstrings:
- def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None: Init sensor.
- def native_value(self) -> StateType: Return the value reported by the ... | Implement the Python class `RssiSensor` described below.
Class description:
Sensor device.
Method signatures and docstrings:
- def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None: Init sensor.
- def native_value(self) -> StateType: Return the value reported by the ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
<|body_0|>
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RssiSensor:
"""Sensor device."""
def __init__(self, coordinator: FjaraskupanCoordinator, device: Device, device_info: DeviceInfo) -> None:
"""Init sensor."""
super().__init__(coordinator)
self._attr_unique_id = f'{device.address}-signal-strength'
self._attr_device_info = d... | the_stack_v2_python_sparse | homeassistant/components/fjaraskupan/sensor.py | home-assistant/core | train | 35,501 |
8e8882f1ef437e2cf4589b6cb9190bc70df1a60c | [
"if postorder:\n root = TreeNode(postorder.pop())\n ind = inorder.index(root.val)\n root.left = self.buildTree(inorder[:ind], postorder[:ind])\n root.right = self.buildTree(inorder[ind + 1:], postorder[ind:])\n return root\nreturn None",
"temp = []\nnodes = []\ncurrent = root\nwhile current:\n i... | <|body_start_0|>
if postorder:
root = TreeNode(postorder.pop())
ind = inorder.index(root.val)
root.left = self.buildTree(inorder[:ind], postorder[:ind])
root.right = self.buildTree(inorder[ind + 1:], postorder[ind:])
return root
return None
<|e... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_36k_train_004793 | 1,501 | no_license | [
{
"docstring": ":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode",
"name": "buildTree",
"signature": "def buildTree(self, inorder, postorder)"
},
{
"docstring": ":type root: TreeNode :rtype: List[int]",
"name": "inorderTraversal",
"signature": "def inorderTraversal(se... | 2 | stack_v2_sparse_classes_30k_train_010007 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
- def inorderTraversal(self, root): :type root: TreeNode :rtype: Lis... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def buildTree(self, inorder, postorder): :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode
- def inorderTraversal(self, root): :type root: TreeNode :rtype: Lis... | 6e4129d7c092be933497da2156680d25f72e42a4 | <|skeleton|>
class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
<|body_0|>
def inorderTraversal(self, root):
""":type root: TreeNode :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def buildTree(self, inorder, postorder):
""":type inorder: List[int] :type postorder: List[int] :rtype: TreeNode"""
if postorder:
root = TreeNode(postorder.pop())
ind = inorder.index(root.val)
root.left = self.buildTree(inorder[:ind], postorder[:in... | the_stack_v2_python_sparse | 106_construct-binary-tree-from-inorder-and-postorder-traversal.py | setu4993/LeetCode | train | 0 | |
3d29bcdbd59ee0b29efafa888eb1d4d34507566d | [
"logger.debug('Visiting %s', self.novel_url)\nsoup = self.get_soup(self.novel_url)\npossible_title = soup.select_one('li.text1')\nfor span in possible_title.select('span'):\n span.extract()\nself.novel_title = possible_title.text.strip()\nlogger.info('Novel title: %s', self.novel_title)\nself.novel_cover = self.... | <|body_start_0|>
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
possible_title = soup.select_one('li.text1')
for span in possible_title.select('span'):
span.extract()
self.novel_title = possible_title.text.strip()
logger.info(... | LightNovelWorldCrawler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LightNovelWorldCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_004794 | 2,135 | permissive | [
{
"docstring": "Get novel title, autor, cover etc",
"name": "read_novel_info",
"signature": "def read_novel_info(self)"
},
{
"docstring": "Download body of a single chapter and return as clean html format.",
"name": "download_chapter_body",
"signature": "def download_chapter_body(self, c... | 2 | null | Implement the Python class `LightNovelWorldCrawler` described below.
Class description:
Implement the LightNovelWorldCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return ... | Implement the Python class `LightNovelWorldCrawler` described below.
Class description:
Implement the LightNovelWorldCrawler class.
Method signatures and docstrings:
- def read_novel_info(self): Get novel title, autor, cover etc
- def download_chapter_body(self, chapter): Download body of a single chapter and return ... | 451e816ab03c8466be90f6f0b3eaa52d799140ce | <|skeleton|>
class LightNovelWorldCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
<|body_0|>
def download_chapter_body(self, chapter):
"""Download body of a single chapter and return as clean html format."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LightNovelWorldCrawler:
def read_novel_info(self):
"""Get novel title, autor, cover etc"""
logger.debug('Visiting %s', self.novel_url)
soup = self.get_soup(self.novel_url)
possible_title = soup.select_one('li.text1')
for span in possible_title.select('span'):
... | the_stack_v2_python_sparse | lncrawl/sources/lightnovelworld.py | NNTin/lightnovel-crawler | train | 2 | |
3340300629ab60347694e3c68aee243a7e36c304 | [
"super(Derender, self).__init__()\nresnet = resnet34(pretrained=True)\nresnet_layers = list(resnet.children())\nresnet_layers.pop()\nresnet_layers.pop(0)\nresnet_layers.insert(0, nn.Conv2d(cfg.MODEL.IN_CHANNELS, 64, kernel_size=3, stride=2, padding=1))\nresnet_layers[-1] = nn.AvgPool2d(kernel_size=cfg.MODEL.POOLING... | <|body_start_0|>
super(Derender, self).__init__()
resnet = resnet34(pretrained=True)
resnet_layers = list(resnet.children())
resnet_layers.pop()
resnet_layers.pop(0)
resnet_layers.insert(0, nn.Conv2d(cfg.MODEL.IN_CHANNELS, 64, kernel_size=3, stride=2, padding=1))
... | Neural Network used for obtaining object-centric representations from scenes | Derender | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
<|body_0|>
def forward... | stack_v2_sparse_classes_36k_train_004795 | 2,428 | no_license | [
{
"docstring": "Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters",
"name": "__init__",
"signature": "def __init__(self, cfg, attributes)"
},
{
"docstring": "Derenderer's forward pass Args: inputs: Inputs to compute forward pass on c... | 2 | stack_v2_sparse_classes_30k_train_008872 | Implement the Python class `Derender` described below.
Class description:
Neural Network used for obtaining object-centric representations from scenes
Method signatures and docstrings:
- def __init__(self, cfg, attributes): Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with exp... | Implement the Python class `Derender` described below.
Class description:
Neural Network used for obtaining object-centric representations from scenes
Method signatures and docstrings:
- def __init__(self, cfg, attributes): Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with exp... | 424cbf65fd65e912430cb99d942e2fa69235aa61 | <|skeleton|>
class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
<|body_0|>
def forward... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Derender:
"""Neural Network used for obtaining object-centric representations from scenes"""
def __init__(self, cfg, attributes):
"""Initializes basic network topology (based on Resnet 34) Args: cfg: YACS configuration with experiment parameters"""
super(Derender, self).__init__()
... | the_stack_v2_python_sparse | models/derender.py | AdejuwonF/intphys-renderer | train | 0 |
ec063cd14334c23fb34906cd7d818c34383cdc3a | [
"self.settings = settings\nself.database = database\nself.table_reader: TableReader = None\nTable.__init__(self, competition_folder, self.settings['clubs_template'])",
"filename = filename or self.settings['clubs_output']\ntry:\n self.table_reader = TableReader.from_settings(self, self.settings, 'clubs')\n ... | <|body_start_0|>
self.settings = settings
self.database = database
self.table_reader: TableReader = None
Table.__init__(self, competition_folder, self.settings['clubs_template'])
<|end_body_0|>
<|body_start_1|>
filename = filename or self.settings['clubs_output']
try:
... | Tabelle der Vereinsübersicht | ClubReportTable | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClubReportTable:
"""Tabelle der Vereinsübersicht"""
def __init__(self, competition_folder: str, settings: SettingsTable, database: Database):
"""Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenban... | stack_v2_sparse_classes_36k_train_004796 | 2,301 | no_license | [
{
"docstring": "Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank",
"name": "__init__",
"signature": "def __init__(self, competition_folder: str, settings: SettingsTable, database: Database)"
},
{
"docstri... | 3 | stack_v2_sparse_classes_30k_train_010363 | Implement the Python class `ClubReportTable` described below.
Class description:
Tabelle der Vereinsübersicht
Method signatures and docstrings:
- def __init__(self, competition_folder: str, settings: SettingsTable, database: Database): Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (Se... | Implement the Python class `ClubReportTable` described below.
Class description:
Tabelle der Vereinsübersicht
Method signatures and docstrings:
- def __init__(self, competition_folder: str, settings: SettingsTable, database: Database): Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (Se... | 349aad3f5a71374f062a7a3b50d827dbf8e99bfe | <|skeleton|>
class ClubReportTable:
"""Tabelle der Vereinsübersicht"""
def __init__(self, competition_folder: str, settings: SettingsTable, database: Database):
"""Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenban... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ClubReportTable:
"""Tabelle der Vereinsübersicht"""
def __init__(self, competition_folder: str, settings: SettingsTable, database: Database):
"""Konstruktor. Args: competition_folder (str): Ordner der Veranstaltung settings (SettingsTable): Einstellungen database (Database): Datenbank"""
... | the_stack_v2_python_sparse | reports/club_report_table.py | RobFro96/Talentiadeverwaltung | train | 0 |
e4e13fd5a382134fe7a18818309cac94063877b0 | [
"if not isinstance(input, MultivariateNormal):\n raise RuntimeError('BernoulliLikelihood expects a multi-variate normally distributed latent function to make predictions')\nmean = input.mean\nvar = input.variance\nlink = mean.div(torch.sqrt(1 + var))\noutput_probs = normal_cdf(link)\nreturn Bernoulli(probs=outpu... | <|body_start_0|>
if not isinstance(input, MultivariateNormal):
raise RuntimeError('BernoulliLikelihood expects a multi-variate normally distributed latent function to make predictions')
mean = input.mean
var = input.variance
link = mean.div(torch.sqrt(1 + var))
output... | Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can write the likelihood compactly as: p(Y=y|f)=\\Phi(yf) | BernoulliLikelihood | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BernoulliLikelihood:
"""Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can write the likelihood compactly as: p(Y=y|f... | stack_v2_sparse_classes_36k_train_004797 | 2,102 | permissive | [
{
"docstring": "Computes predictive distributions p(y|x) given a latent distribution p(f|x). To do this, we solve the integral: p(y|x) = \\\\int p(y|f)p(f|x) df Given that p(y=1|f) = \\\\Phi(f), this integral is analytically tractable, and if \\\\mu_f and \\\\sigma^2_f are the mean and variance of p(f|x), the s... | 2 | stack_v2_sparse_classes_30k_train_013145 | Implement the Python class `BernoulliLikelihood` described below.
Class description:
Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can wri... | Implement the Python class `BernoulliLikelihood` described below.
Class description:
Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can wri... | 3ca5b375e1347c74e36845fc89bb1dacf6c85deb | <|skeleton|>
class BernoulliLikelihood:
"""Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can write the likelihood compactly as: p(Y=y|f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BernoulliLikelihood:
"""Implements the Bernoulli likelihood used for GP classification, using Probit regression (i.e., the latent function is warped to be in [0,1] using the standard Normal CDF \\Phi(x)). Given the identity \\Phi(-x) = 1-\\Phi(x), we can write the likelihood compactly as: p(Y=y|f)=\\Phi(yf)""... | the_stack_v2_python_sparse | gpytorch/likelihoods/bernoulli_likelihood.py | ChengyueGongR/gpytorch | train | 2 |
3c1fc9cc997a8de36aca6059919bbeb5160e556e | [
"guess = ext.extract_output(frame, order) if guess is None else guess\nguess_id = utils.from_categorical(guess)\nframe = frame.sort_values(order)\nframe = frame.assign(guess_id=guess_id, index=frame.index)\nself.frame = utils.remove_padding(frame)\nself.order = order\nself.fig = plt.figure()\nself.leg = None\nself.... | <|body_start_0|>
guess = ext.extract_output(frame, order) if guess is None else guess
guess_id = utils.from_categorical(guess)
frame = frame.sort_values(order)
frame = frame.assign(guess_id=guess_id, index=frame.index)
self.frame = utils.remove_padding(frame)
self.order =... | A plot of the data. | Plot3D | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plot3D:
"""A plot of the data."""
def __init__(self, frame: pd.DataFrame, order: List[str], guess: Optional[np.ndarray]=None) -> None:
"""Initialize a 3D plot. :param frame: The frame containing a single event's data. :param order: The ordering of the frame. :param guess: The predict... | stack_v2_sparse_classes_36k_train_004798 | 13,646 | no_license | [
{
"docstring": "Initialize a 3D plot. :param frame: The frame containing a single event's data. :param order: The ordering of the frame. :param guess: The prediction assignment for the hits to a track. If this is None, then the hits will be assigned to tracks based on their correct assignment. :return: None",
... | 3 | stack_v2_sparse_classes_30k_train_016851 | Implement the Python class `Plot3D` described below.
Class description:
A plot of the data.
Method signatures and docstrings:
- def __init__(self, frame: pd.DataFrame, order: List[str], guess: Optional[np.ndarray]=None) -> None: Initialize a 3D plot. :param frame: The frame containing a single event's data. :param or... | Implement the Python class `Plot3D` described below.
Class description:
A plot of the data.
Method signatures and docstrings:
- def __init__(self, frame: pd.DataFrame, order: List[str], guess: Optional[np.ndarray]=None) -> None: Initialize a 3D plot. :param frame: The frame containing a single event's data. :param or... | 3621bfefd04d4209cacb57d2dda886f6b421a570 | <|skeleton|>
class Plot3D:
"""A plot of the data."""
def __init__(self, frame: pd.DataFrame, order: List[str], guess: Optional[np.ndarray]=None) -> None:
"""Initialize a 3D plot. :param frame: The frame containing a single event's data. :param order: The ordering of the frame. :param guess: The predict... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plot3D:
"""A plot of the data."""
def __init__(self, frame: pd.DataFrame, order: List[str], guess: Optional[np.ndarray]=None) -> None:
"""Initialize a 3D plot. :param frame: The frame containing a single event's data. :param order: The ordering of the frame. :param guess: The prediction assignmen... | the_stack_v2_python_sparse | tracking3d/tracker/visuals.py | honorpeter/heptrx-examples | train | 1 |
7b33fe307fdbbc9836558e2e4d3ef26a2805a86d | [
"class TestEntryType(structures.Entry):\n pass\nstructures.TypeRegistry.register('test', TestEntryType)\nparse_entry('@test{name, title={test}}')",
"class TestEntryType(object):\n pass\nself.assertRaises(exceptions.InvalidEntryType, structures.TypeRegistry.register, 'test', TestEntryType)"
] | <|body_start_0|>
class TestEntryType(structures.Entry):
pass
structures.TypeRegistry.register('test', TestEntryType)
parse_entry('@test{name, title={test}}')
<|end_body_0|>
<|body_start_1|>
class TestEntryType(object):
pass
self.assertRaises(exceptions.In... | Tests for the customization features. | CustomizationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomizationTests:
"""Tests for the customization features."""
def test_global_typeregistry(self):
"""Check if it's possible to globally register a new Entry type."""
<|body_0|>
def test_invalid_entryclass(self):
"""Make sure that the new Entry type is a subclas... | stack_v2_sparse_classes_36k_train_004799 | 7,830 | no_license | [
{
"docstring": "Check if it's possible to globally register a new Entry type.",
"name": "test_global_typeregistry",
"signature": "def test_global_typeregistry(self)"
},
{
"docstring": "Make sure that the new Entry type is a subclass of Entry.",
"name": "test_invalid_entryclass",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_014297 | Implement the Python class `CustomizationTests` described below.
Class description:
Tests for the customization features.
Method signatures and docstrings:
- def test_global_typeregistry(self): Check if it's possible to globally register a new Entry type.
- def test_invalid_entryclass(self): Make sure that the new En... | Implement the Python class `CustomizationTests` described below.
Class description:
Tests for the customization features.
Method signatures and docstrings:
- def test_global_typeregistry(self): Check if it's possible to globally register a new Entry type.
- def test_invalid_entryclass(self): Make sure that the new En... | 0fda7b0d3b195ab2b2ed7071a3214c355187c14f | <|skeleton|>
class CustomizationTests:
"""Tests for the customization features."""
def test_global_typeregistry(self):
"""Check if it's possible to globally register a new Entry type."""
<|body_0|>
def test_invalid_entryclass(self):
"""Make sure that the new Entry type is a subclas... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomizationTests:
"""Tests for the customization features."""
def test_global_typeregistry(self):
"""Check if it's possible to globally register a new Entry type."""
class TestEntryType(structures.Entry):
pass
structures.TypeRegistry.register('test', TestEntryType)
... | the_stack_v2_python_sparse | src/bibtexParser/tests.py | tomteman/research-assistant | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.