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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
71d503e84a0743a8f8f43d6d9543ff185a4f3995 | [
"super(BiLSTM, self).__init__()\nself.tag_to_id = tag_to_id\nself.tag_size = len(tag_to_id)\nself.embedding_size = input_feature_size\nself.hidden_size = hidden_size // 2\nself.batch_size = batch_size\nself.sentence_length = sentence_length\nself.batch_first = batch_first\nself.num_layers = num_layers\nself.embeddi... | <|body_start_0|>
super(BiLSTM, self).__init__()
self.tag_to_id = tag_to_id
self.tag_size = len(tag_to_id)
self.embedding_size = input_feature_size
self.hidden_size = hidden_size // 2
self.batch_size = batch_size
self.sentence_length = sentence_length
self.... | description: BiLSTM 模型定义 | BiLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BiLSTM:
"""description: BiLSTM 模型定义"""
def __init__(self, vocab_size, tag_to_id, input_feature_size, hidden_size, batch_size, sentence_length, num_layers=1, batch_first=True):
"""description: 模型初始化 :param vocab_size: 所有文本的字符数量 :param tag_to_id: 标签与 id 对照表 :param input_feature_size: 输... | stack_v2_sparse_classes_36k_train_000400 | 7,635 | no_license | [
{
"docstring": "description: 模型初始化 :param vocab_size: 所有文本的字符数量 :param tag_to_id: 标签与 id 对照表 :param input_feature_size: 输入的维度,字嵌入维度( 即LSTM输入层维度 input_size ) :param hidden_size: 隐藏层向量维度 :param batch_size: 批训练大小 :param sentence_length: 句子长度的限制 :param num_layers: LSTM 层数大小 :param batch_first: 是否将batch_size放置到矩阵的第一... | 2 | null | Implement the Python class `BiLSTM` described below.
Class description:
description: BiLSTM 模型定义
Method signatures and docstrings:
- def __init__(self, vocab_size, tag_to_id, input_feature_size, hidden_size, batch_size, sentence_length, num_layers=1, batch_first=True): description: 模型初始化 :param vocab_size: 所有文本的字符数量 ... | Implement the Python class `BiLSTM` described below.
Class description:
description: BiLSTM 模型定义
Method signatures and docstrings:
- def __init__(self, vocab_size, tag_to_id, input_feature_size, hidden_size, batch_size, sentence_length, num_layers=1, batch_first=True): description: 模型初始化 :param vocab_size: 所有文本的字符数量 ... | 04abc1de495e29fbdfc3dc953c3b77d8d4f3f7e7 | <|skeleton|>
class BiLSTM:
"""description: BiLSTM 模型定义"""
def __init__(self, vocab_size, tag_to_id, input_feature_size, hidden_size, batch_size, sentence_length, num_layers=1, batch_first=True):
"""description: 模型初始化 :param vocab_size: 所有文本的字符数量 :param tag_to_id: 标签与 id 对照表 :param input_feature_size: 输... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BiLSTM:
"""description: BiLSTM 模型定义"""
def __init__(self, vocab_size, tag_to_id, input_feature_size, hidden_size, batch_size, sentence_length, num_layers=1, batch_first=True):
"""description: 模型初始化 :param vocab_size: 所有文本的字符数量 :param tag_to_id: 标签与 id 对照表 :param input_feature_size: 输入的维度,字嵌入维度( 即... | the_stack_v2_python_sparse | off_line/ner_model/bilistm.py | 1193700079/ai_doctor | train | 16 |
2b443793f5bf241d46a269834fe49d972471e80b | [
"sale_schema = SaleSchema()\nsale_data = request.get_json()\nvalidated_sale_data, errors = sale_schema.load(sale_data)\nif errors:\n return (dict(status='fail', message=errors), 400)\nsale = Sale(**validated_sale_data)\nsaved_sale = sale.save()\nif not saved_sale:\n return (dict(status='fail', message='Intern... | <|body_start_0|>
sale_schema = SaleSchema()
sale_data = request.get_json()
validated_sale_data, errors = sale_schema.load(sale_data)
if errors:
return (dict(status='fail', message=errors), 400)
sale = Sale(**validated_sale_data)
saved_sale = sale.save()
... | SaleView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SaleView:
def post(self):
"""Creating an Sale ad"""
<|body_0|>
def get(self):
"""Getting All sales"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sale_schema = SaleSchema()
sale_data = request.get_json()
validated_sale_data, errors ... | stack_v2_sparse_classes_36k_train_000401 | 2,917 | no_license | [
{
"docstring": "Creating an Sale ad",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Getting All sales",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001079 | Implement the Python class `SaleView` described below.
Class description:
Implement the SaleView class.
Method signatures and docstrings:
- def post(self): Creating an Sale ad
- def get(self): Getting All sales | Implement the Python class `SaleView` described below.
Class description:
Implement the SaleView class.
Method signatures and docstrings:
- def post(self): Creating an Sale ad
- def get(self): Getting All sales
<|skeleton|>
class SaleView:
def post(self):
"""Creating an Sale ad"""
<|body_0|>
... | 015d70b8f79df6c1a5629add35767cee52f424f5 | <|skeleton|>
class SaleView:
def post(self):
"""Creating an Sale ad"""
<|body_0|>
def get(self):
"""Getting All sales"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SaleView:
def post(self):
"""Creating an Sale ad"""
sale_schema = SaleSchema()
sale_data = request.get_json()
validated_sale_data, errors = sale_schema.load(sale_data)
if errors:
return (dict(status='fail', message=errors), 400)
sale = Sale(**validat... | the_stack_v2_python_sparse | app/controllers/sale.py | MutegekiHenry/project-cohort-backend | train | 0 | |
727f70fb22f30954acfd58df6e8a17a5c806acab | [
"if self.action in ['retrieve', 'update', 'partial_update']:\n permission_classes = [permissions.IsOrganizationAdmin]\nelif self.action in ['list']:\n permission_classes = [permissions.UserIsAuthenticated]\nelse:\n try:\n permission_classes = getattr(self, self.action).kwargs.get('permission_classes... | <|body_start_0|>
if self.action in ['retrieve', 'update', 'partial_update']:
permission_classes = [permissions.IsOrganizationAdmin]
elif self.action in ['list']:
permission_classes = [permissions.UserIsAuthenticated]
else:
try:
permission_class... | ViewSet for all organization-related interactions. | OrganizationViewSet | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000402 | 8,277 | permissive | [
{
"docstring": "Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions.",
"name": "get_permissions",
"signature": "def get_permissions(self)"
},
{
"docstring": "override get_queryset based on the request... | 2 | null | Implement the Python class `OrganizationViewSet` described below.
Class description:
ViewSet for all organization-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the V... | Implement the Python class `OrganizationViewSet` described below.
Class description:
ViewSet for all organization-related interactions.
Method signatures and docstrings:
- def get_permissions(self): Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the V... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OrganizationViewSet:
"""ViewSet for all organization-related interactions."""
def get_permissions(self):
"""Manage permissions for built-in DRF methods. Default to the actions' self defined permissions if applicable or to the ViewSet's default permissions."""
if self.action in ['retrieve'... | the_stack_v2_python_sparse | src/backend/marsha/core/api/account.py | openfun/marsha | train | 92 |
e2395ed4e68bec28ab9be57fc17f35d51a8d832e | [
"self.analysis = analysis\nself.model = model\nself.fom_is_log_likelihood = fom_is_log_likelihood\nself.resample_figure_of_merit = resample_figure_of_merit\nself.convert_to_chi_squared = convert_to_chi_squared",
"try:\n instance = self.model.instance_from_vector(vector=parameters)\n log_likelihood = self.an... | <|body_start_0|>
self.analysis = analysis
self.model = model
self.fom_is_log_likelihood = fom_is_log_likelihood
self.resample_figure_of_merit = resample_figure_of_merit
self.convert_to_chi_squared = convert_to_chi_squared
<|end_body_0|>
<|body_start_1|>
try:
... | Fitness | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Fitness:
def __init__(self, model, analysis, fom_is_log_likelihood: bool=True, resample_figure_of_merit: float=-np.inf, convert_to_chi_squared: bool=False):
"""Interfaces with any non-linear in order to fit a model to the data and return a log likelihood via an `Analysis` class. The inte... | stack_v2_sparse_classes_36k_train_000403 | 5,042 | permissive | [
{
"docstring": "Interfaces with any non-linear in order to fit a model to the data and return a log likelihood via an `Analysis` class. The interface of a non-linear search and a fitness function can be summarized as follows: 1) The non-linear search chooses a new set of parameters for the model, which are pass... | 2 | null | Implement the Python class `Fitness` described below.
Class description:
Implement the Fitness class.
Method signatures and docstrings:
- def __init__(self, model, analysis, fom_is_log_likelihood: bool=True, resample_figure_of_merit: float=-np.inf, convert_to_chi_squared: bool=False): Interfaces with any non-linear i... | Implement the Python class `Fitness` described below.
Class description:
Implement the Fitness class.
Method signatures and docstrings:
- def __init__(self, model, analysis, fom_is_log_likelihood: bool=True, resample_figure_of_merit: float=-np.inf, convert_to_chi_squared: bool=False): Interfaces with any non-linear i... | 434d140675d63150456380d466c0b8084fe5b288 | <|skeleton|>
class Fitness:
def __init__(self, model, analysis, fom_is_log_likelihood: bool=True, resample_figure_of_merit: float=-np.inf, convert_to_chi_squared: bool=False):
"""Interfaces with any non-linear in order to fit a model to the data and return a log likelihood via an `Analysis` class. The inte... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Fitness:
def __init__(self, model, analysis, fom_is_log_likelihood: bool=True, resample_figure_of_merit: float=-np.inf, convert_to_chi_squared: bool=False):
"""Interfaces with any non-linear in order to fit a model to the data and return a log likelihood via an `Analysis` class. The interface of a non... | the_stack_v2_python_sparse | autofit/non_linear/fitness.py | rhayes777/PyAutoFit | train | 56 | |
c8e8eead69db9b51e606aef7138788aea108fbd9 | [
"self._session = session_obj\nself._ctx_ks = KeyStore(self._session)\nself._ctx_key = KeyObject(self._ctx_ks)",
"status, object_type, cipher_type = self._ctx_key.get_handle(key_id)\nif status != apis.kStatus_SSS_Success:\n return status\nstatus = self._ctx_ks.erase_key(self._ctx_key)\nself._ctx_key.free()\nret... | <|body_start_0|>
self._session = session_obj
self._ctx_ks = KeyStore(self._session)
self._ctx_key = KeyObject(self._ctx_ks)
<|end_body_0|>
<|body_start_1|>
status, object_type, cipher_type = self._ctx_key.get_handle(key_id)
if status != apis.kStatus_SSS_Success:
retu... | Erase key operation | Erase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Erase:
"""Erase key operation"""
def __init__(self, session_obj):
"""constuctor :param session_obj: Instance of session"""
<|body_0|>
def erase_key(self, key_id):
"""Erase key operation :param key_id: Key index :return: Status"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_000404 | 975 | permissive | [
{
"docstring": "constuctor :param session_obj: Instance of session",
"name": "__init__",
"signature": "def __init__(self, session_obj)"
},
{
"docstring": "Erase key operation :param key_id: Key index :return: Status",
"name": "erase_key",
"signature": "def erase_key(self, key_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_008348 | Implement the Python class `Erase` described below.
Class description:
Erase key operation
Method signatures and docstrings:
- def __init__(self, session_obj): constuctor :param session_obj: Instance of session
- def erase_key(self, key_id): Erase key operation :param key_id: Key index :return: Status | Implement the Python class `Erase` described below.
Class description:
Erase key operation
Method signatures and docstrings:
- def __init__(self, session_obj): constuctor :param session_obj: Instance of session
- def erase_key(self, key_id): Erase key operation :param key_id: Key index :return: Status
<|skeleton|>
c... | ab42459602787e9a557c3a00df40b20a52879fc7 | <|skeleton|>
class Erase:
"""Erase key operation"""
def __init__(self, session_obj):
"""constuctor :param session_obj: Instance of session"""
<|body_0|>
def erase_key(self, key_id):
"""Erase key operation :param key_id: Key index :return: Status"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Erase:
"""Erase key operation"""
def __init__(self, session_obj):
"""constuctor :param session_obj: Instance of session"""
self._session = session_obj
self._ctx_ks = KeyStore(self._session)
self._ctx_key = KeyObject(self._ctx_ks)
def erase_key(self, key_id):
"... | the_stack_v2_python_sparse | src/salt/base/state/secure_element/se05x_sss/sss/erasekey.py | autopi-io/autopi-core | train | 141 |
fa20c07710d0aa57ffd1170e57531d70b5bd753e | [
"self.args = args\nself.starts = args[1]\nself.ends = args[2]",
"sum = 0\nfor y in range(1, self.N + 2):\n for x in range(1, self.N + 2):\n for start, end in zip(self.starts, self.ends):\n inside = x >= start[0] and y >= start[1] and (x <= end[0]) and (y <= end[1])\n if inside:\n ... | <|body_start_0|>
self.args = args
self.starts = args[1]
self.ends = args[2]
<|end_body_0|>
<|body_start_1|>
sum = 0
for y in range(1, self.N + 2):
for x in range(1, self.N + 2):
for start, end in zip(self.starts, self.ends):
inside... | Table representation | Table | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table representation"""
def __init__(self, args):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.args = args
self.starts ... | stack_v2_sparse_classes_36k_train_000405 | 2,981 | permissive | [
{
"docstring": "Default constructor",
"name": "__init__",
"signature": "def __init__(self, args)"
},
{
"docstring": "Main calcualtion function of the class",
"name": "calculate",
"signature": "def calculate(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019013 | Implement the Python class `Table` described below.
Class description:
Table representation
Method signatures and docstrings:
- def __init__(self, args): Default constructor
- def calculate(self): Main calcualtion function of the class | Implement the Python class `Table` described below.
Class description:
Table representation
Method signatures and docstrings:
- def __init__(self, args): Default constructor
- def calculate(self): Main calcualtion function of the class
<|skeleton|>
class Table:
"""Table representation"""
def __init__(self, ... | ae02ea872ca91ef98630cc172a844b82cc56f621 | <|skeleton|>
class Table:
"""Table representation"""
def __init__(self, args):
"""Default constructor"""
<|body_0|>
def calculate(self):
"""Main calcualtion function of the class"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""Table representation"""
def __init__(self, args):
"""Default constructor"""
self.args = args
self.starts = args[1]
self.ends = args[2]
def calculate(self):
"""Main calcualtion function of the class"""
sum = 0
for y in range(1, self.N ... | the_stack_v2_python_sparse | codeforces/552A_table.py | snsokolov/contests | train | 1 |
ae79bf3327ff9e665d8177d85461e20ef100b9ce | [
"self.last_day_num_job_errors = last_day_num_job_errors\nself.last_day_num_job_runs = last_day_num_job_runs\nself.last_day_num_job_sla_violations = last_day_num_job_sla_violations\nself.num_job_running = num_job_running\nself.objects_protected_by_policy = objects_protected_by_policy",
"if dictionary is None:\n ... | <|body_start_0|>
self.last_day_num_job_errors = last_day_num_job_errors
self.last_day_num_job_runs = last_day_num_job_runs
self.last_day_num_job_sla_violations = last_day_num_job_sla_violations
self.num_job_running = num_job_running
self.objects_protected_by_policy = objects_prot... | Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violations in the last 24 hours. num_job_runni... | JobRunsTile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violati... | stack_v2_sparse_classes_36k_train_000406 | 3,291 | permissive | [
{
"docstring": "Constructor for the JobRunsTile class",
"name": "__init__",
"signature": "def __init__(self, last_day_num_job_errors=None, last_day_num_job_runs=None, last_day_num_job_sla_violations=None, num_job_running=None, objects_protected_by_policy=None)"
},
{
"docstring": "Creates an inst... | 2 | stack_v2_sparse_classes_30k_train_011168 | Implement the Python class `JobRunsTile` described below.
Class description:
Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_... | Implement the Python class `JobRunsTile` described below.
Class description:
Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JobRunsTile:
"""Implementation of the 'JobRunsTile' model. Jon Runs information. Attributes: last_day_num_job_errors (int): Number of Error runs in the last 24 hours. last_day_num_job_runs (int): Number of Job Runs in the last 24 hours. last_day_num_job_sla_violations (int): Number of SLA Violations in the la... | the_stack_v2_python_sparse | cohesity_management_sdk/models/job_runs_tile.py | cohesity/management-sdk-python | train | 24 |
85ad0465045f6ea901e9c578c0571fc07211101f | [
"if question.data == '':\n raise ValidationError('必須です。')\nif len(question.data) > 255:\n raise ValidationError('255文字以内で入力してください。')",
"if answer.data == '':\n raise ValidationError('必須です。')\nif len(answer.data) > 1000:\n raise ValidationError('1000文字以内で入力してください。')"
] | <|body_start_0|>
if question.data == '':
raise ValidationError('必須です。')
if len(question.data) > 255:
raise ValidationError('255文字以内で入力してください。')
<|end_body_0|>
<|body_start_1|>
if answer.data == '':
raise ValidationError('必須です。')
if len(answer.data) > ... | FaqForm | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaqForm:
def validate_question(self, question):
"""バリデーション - 必須 - 文字数の上限は255文字"""
<|body_0|>
def validate_answer(self, answer):
"""バリデーション - 必須 - 文字数の上限は1000文字"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if question.data == '':
raise... | stack_v2_sparse_classes_36k_train_000407 | 965 | permissive | [
{
"docstring": "バリデーション - 必須 - 文字数の上限は255文字",
"name": "validate_question",
"signature": "def validate_question(self, question)"
},
{
"docstring": "バリデーション - 必須 - 文字数の上限は1000文字",
"name": "validate_answer",
"signature": "def validate_answer(self, answer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020036 | Implement the Python class `FaqForm` described below.
Class description:
Implement the FaqForm class.
Method signatures and docstrings:
- def validate_question(self, question): バリデーション - 必須 - 文字数の上限は255文字
- def validate_answer(self, answer): バリデーション - 必須 - 文字数の上限は1000文字 | Implement the Python class `FaqForm` described below.
Class description:
Implement the FaqForm class.
Method signatures and docstrings:
- def validate_question(self, question): バリデーション - 必須 - 文字数の上限は255文字
- def validate_answer(self, answer): バリデーション - 必須 - 文字数の上限は1000文字
<|skeleton|>
class FaqForm:
def validate_... | 8751fcb7fb9d46b023bd1fe33d734c58332d77e9 | <|skeleton|>
class FaqForm:
def validate_question(self, question):
"""バリデーション - 必須 - 文字数の上限は255文字"""
<|body_0|>
def validate_answer(self, answer):
"""バリデーション - 必須 - 文字数の上限は1000文字"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FaqForm:
def validate_question(self, question):
"""バリデーション - 必須 - 文字数の上限は255文字"""
if question.data == '':
raise ValidationError('必須です。')
if len(question.data) > 255:
raise ValidationError('255文字以内で入力してください。')
def validate_answer(self, answer):
"""バリ... | the_stack_v2_python_sparse | chatbot/admin/helpers/forms/FaqForm.py | hysakhr/flask_chatbot | train | 3 | |
ed69f45d0c7982adb4373f59664faf1ee052a169 | [
"if X is not None:\n raise NotImplementedError('Exogenous variables `X` are not yet supported.')\nself._set_y_X(y, X)\nself._set_fh(fh)\nself.step_length_ = check_step_length(self.step_length)\nself.window_length_ = check_window_length(self.window_length)\nself._cv = SlidingWindowSplitter(fh=1, window_length=sel... | <|body_start_0|>
if X is not None:
raise NotImplementedError('Exogenous variables `X` are not yet supported.')
self._set_y_X(y, X)
self._set_fh(fh)
self.step_length_ = check_step_length(self.step_length)
self.window_length_ = check_window_length(self.window_length)
... | _RecursiveReducer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _RecursiveReducer:
def fit(self, y, X=None, fh=None):
"""Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) The forecasters horizon with the steps ahead to to predict. X : pd.Dat... | stack_v2_sparse_classes_36k_train_000408 | 20,187 | permissive | [
{
"docstring": "Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) The forecasters horizon with the steps ahead to to predict. X : pd.DataFrame, optional (default=None) Exogenous variables are ignored R... | 2 | null | Implement the Python class `_RecursiveReducer` described below.
Class description:
Implement the _RecursiveReducer class.
Method signatures and docstrings:
- def fit(self, y, X=None, fh=None): Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list o... | Implement the Python class `_RecursiveReducer` described below.
Class description:
Implement the _RecursiveReducer class.
Method signatures and docstrings:
- def fit(self, y, X=None, fh=None): Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list o... | 012d11e6b879d29b0a36c7e2e7172355992348f3 | <|skeleton|>
class _RecursiveReducer:
def fit(self, y, X=None, fh=None):
"""Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) The forecasters horizon with the steps ahead to to predict. X : pd.Dat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _RecursiveReducer:
def fit(self, y, X=None, fh=None):
"""Fit to training data. Parameters ---------- y : pd.Series Target time series to which to fit the forecaster. fh : int, list or np.array, optional (default=None) The forecasters horizon with the steps ahead to to predict. X : pd.DataFrame, option... | the_stack_v2_python_sparse | sktime/forecasting/compose/_reduce.py | earthinversion/sktime | train | 1 | |
49f2e174fbf2637c804b32be6ad184a0cbf75946 | [
"self.population = None\nself.this_chain = None\nself.other_chains = None\nreturn super().__init__(vars, shared, blocked)",
"self.population = population\nself.this_chain = chain_index\nself.other_chains = [c for c in range(len(population)) if c != chain_index]\nif not len(self.other_chains) > 1:\n raise Value... | <|body_start_0|>
self.population = None
self.this_chain = None
self.other_chains = None
return super().__init__(vars, shared, blocked)
<|end_body_0|>
<|body_start_1|>
self.population = population
self.this_chain = chain_index
self.other_chains = [c for c in range... | Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated. | PopulationArrayStepShared | [
"Apache-2.0",
"AFL-2.1",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PopulationArrayStepShared:
"""Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated."""
def __init__(self, vars, shared, blocked=True):
"""Parameters -------... | stack_v2_sparse_classes_36k_train_000409 | 7,034 | permissive | [
{
"docstring": "Parameters ---------- vars: list of sampling value variables shared: dict of PyTensor variable -> shared variable blocked: Boolean (default True)",
"name": "__init__",
"signature": "def __init__(self, vars, shared, blocked=True)"
},
{
"docstring": "Links the sampler to the popula... | 2 | stack_v2_sparse_classes_30k_train_012236 | Implement the Python class `PopulationArrayStepShared` described below.
Class description:
Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated.
Method signatures and docstrings:
- def __ini... | Implement the Python class `PopulationArrayStepShared` described below.
Class description:
Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated.
Method signatures and docstrings:
- def __ini... | ddd1d4bf05a72895c67265f541585ae02bd338a3 | <|skeleton|>
class PopulationArrayStepShared:
"""Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated."""
def __init__(self, vars, shared, blocked=True):
"""Parameters -------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PopulationArrayStepShared:
"""Version of ArrayStepShared that allows samplers to access the states of other chains in the population. Works by linking a list of Points that is updated as the chains are iterated."""
def __init__(self, vars, shared, blocked=True):
"""Parameters ---------- vars: lis... | the_stack_v2_python_sparse | pymc/step_methods/arraystep.py | pymc-devs/pymc | train | 1,046 |
b4366f722d23349d7cf676f58cdb9eb8b97f11ae | [
"lti_user = LTIUser(user_id=self.user.id, lti_consumer=self.lti_consumer, extra_data=json.dumps(self.headers), django_user=self.user)\nlti_user.save()\nself.role1.delete()\nself.assertFalse(lti_user.is_enrolled('student', self.course.id))",
"lti_user = LTIUser(user_id=self.user.id, lti_consumer=self.lti_consumer,... | <|body_start_0|>
lti_user = LTIUser(user_id=self.user.id, lti_consumer=self.lti_consumer, extra_data=json.dumps(self.headers), django_user=self.user)
lti_user.save()
self.role1.delete()
self.assertFalse(lti_user.is_enrolled('student', self.course.id))
<|end_body_0|>
<|body_start_1|>
... | Test model LTIUser. | ModelTest | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelTest:
"""Test model LTIUser."""
def test_lti_user_not_enrolled(self):
"""Test that user not enrolled yet"""
<|body_0|>
def test_lti_user(self):
"""Test enrollment process"""
<|body_1|>
def test_lti_user_create_links(self):
"""Creating LT... | stack_v2_sparse_classes_36k_train_000410 | 21,335 | permissive | [
{
"docstring": "Test that user not enrolled yet",
"name": "test_lti_user_not_enrolled",
"signature": "def test_lti_user_not_enrolled(self)"
},
{
"docstring": "Test enrollment process",
"name": "test_lti_user",
"signature": "def test_lti_user(self)"
},
{
"docstring": "Creating LTI... | 3 | null | Implement the Python class `ModelTest` described below.
Class description:
Test model LTIUser.
Method signatures and docstrings:
- def test_lti_user_not_enrolled(self): Test that user not enrolled yet
- def test_lti_user(self): Test enrollment process
- def test_lti_user_create_links(self): Creating LTIUser without D... | Implement the Python class `ModelTest` described below.
Class description:
Test model LTIUser.
Method signatures and docstrings:
- def test_lti_user_not_enrolled(self): Test that user not enrolled yet
- def test_lti_user(self): Test enrollment process
- def test_lti_user_create_links(self): Creating LTIUser without D... | 2e7dd9d2ec687f68ca8ca341cf5f1b3b8809c820 | <|skeleton|>
class ModelTest:
"""Test model LTIUser."""
def test_lti_user_not_enrolled(self):
"""Test that user not enrolled yet"""
<|body_0|>
def test_lti_user(self):
"""Test enrollment process"""
<|body_1|>
def test_lti_user_create_links(self):
"""Creating LT... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModelTest:
"""Test model LTIUser."""
def test_lti_user_not_enrolled(self):
"""Test that user not enrolled yet"""
lti_user = LTIUser(user_id=self.user.id, lti_consumer=self.lti_consumer, extra_data=json.dumps(self.headers), django_user=self.user)
lti_user.save()
self.role1.... | the_stack_v2_python_sparse | mysite/lti/integration_tests.py | cjlee112/socraticqs2 | train | 8 |
1ab47f31e7f5c7a58b9712232d5a075a35518333 | [
"indexes = []\nfor collection_name in self.collections():\n if collection and collection != collection_name:\n continue\n for index_name in self.db[collection_name].index_information():\n if index_name != '_id_':\n indexes.append(index_name)\nreturn indexes",
"LOG.info(f'Adding inde... | <|body_start_0|>
indexes = []
for collection_name in self.collections():
if collection and collection != collection_name:
continue
for index_name in self.db[collection_name].index_information():
if index_name != '_id_':
indexes.... | IndexHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IndexHandler:
def indexes(self, collection=None):
"""Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)"""
<|body_0|>
def load_indexes(self, collections=[]):
"""Add the proper indexes to the scout insta... | stack_v2_sparse_classes_36k_train_000411 | 3,577 | permissive | [
{
"docstring": "Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)",
"name": "indexes",
"signature": "def indexes(self, collection=None)"
},
{
"docstring": "Add the proper indexes to the scout instance. Args: collections(list): lis... | 4 | stack_v2_sparse_classes_30k_train_010331 | Implement the Python class `IndexHandler` described below.
Class description:
Implement the IndexHandler class.
Method signatures and docstrings:
- def indexes(self, collection=None): Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)
- def load_indexes... | Implement the Python class `IndexHandler` described below.
Class description:
Implement the IndexHandler class.
Method signatures and docstrings:
- def indexes(self, collection=None): Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)
- def load_indexes... | 1e6a633ba0a83495047ee7b66db1ebf690ee465f | <|skeleton|>
class IndexHandler:
def indexes(self, collection=None):
"""Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)"""
<|body_0|>
def load_indexes(self, collections=[]):
"""Add the proper indexes to the scout insta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IndexHandler:
def indexes(self, collection=None):
"""Return a list with the current indexes Skip the mandatory _id_ indexes Args: collection(str) Returns: indexes(list)"""
indexes = []
for collection_name in self.collections():
if collection and collection != collection_nam... | the_stack_v2_python_sparse | scout/adapter/mongo/index.py | Clinical-Genomics/scout | train | 143 | |
7c8327445b8ddf28b651adb05d63f5c6bd502aee | [
"self.tasks = tasks\nself.task_types = task_types\nself.input_sets = input_sets or {'GGA Structure Optimization': 'MPRelaxSet', 'GGA+U Structure Optimization': 'MPRelaxSet'}\nself.kpts_tolerance = kpts_tolerance\nself.LDAU_fields = LDAU_fields\nself._input_sets = {name: load_class('pymatgen.io.vasp.sets', inp_set) ... | <|body_start_0|>
self.tasks = tasks
self.task_types = task_types
self.input_sets = input_sets or {'GGA Structure Optimization': 'MPRelaxSet', 'GGA+U Structure Optimization': 'MPRelaxSet'}
self.kpts_tolerance = kpts_tolerance
self.LDAU_fields = LDAU_fields
self._input_sets... | TaskTagger | [
"LicenseRef-scancode-hdf5",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TaskTagger:
def __init__(self, tasks, task_types, input_sets=None, kpts_tolerance=0.9, LDAU_fields=['LDAUU', 'LDAUJ', 'LDAUL'], **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks (Store): Store of task documents task_types (Store): Store of task_types for tasks ... | stack_v2_sparse_classes_36k_train_000412 | 8,208 | permissive | [
{
"docstring": "Creates task_types from tasks and type definitions Args: tasks (Store): Store of task documents task_types (Store): Store of task_types for tasks input_sets (Dict): dictionary of task_type and pymatgen input set to validate against kpts_tolerance (float): the minimum kpt density as dictated by t... | 2 | stack_v2_sparse_classes_30k_train_021197 | Implement the Python class `TaskTagger` described below.
Class description:
Implement the TaskTagger class.
Method signatures and docstrings:
- def __init__(self, tasks, task_types, input_sets=None, kpts_tolerance=0.9, LDAU_fields=['LDAUU', 'LDAUJ', 'LDAUL'], **kwargs): Creates task_types from tasks and type definiti... | Implement the Python class `TaskTagger` described below.
Class description:
Implement the TaskTagger class.
Method signatures and docstrings:
- def __init__(self, tasks, task_types, input_sets=None, kpts_tolerance=0.9, LDAU_fields=['LDAUU', 'LDAUJ', 'LDAUL'], **kwargs): Creates task_types from tasks and type definiti... | 2540fd8f6905be7290ead1b8a9dadca84d5d03fa | <|skeleton|>
class TaskTagger:
def __init__(self, tasks, task_types, input_sets=None, kpts_tolerance=0.9, LDAU_fields=['LDAUU', 'LDAUJ', 'LDAUL'], **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks (Store): Store of task documents task_types (Store): Store of task_types for tasks ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TaskTagger:
def __init__(self, tasks, task_types, input_sets=None, kpts_tolerance=0.9, LDAU_fields=['LDAUU', 'LDAUJ', 'LDAUL'], **kwargs):
"""Creates task_types from tasks and type definitions Args: tasks (Store): Store of task documents task_types (Store): Store of task_types for tasks input_sets (Di... | the_stack_v2_python_sparse | emmet/vasp/task_tagger.py | jerrymlin/emmet | train | 2 | |
5f888b1aa8e61be010460c720f3e345b6d7137f4 | [
"result = ['#']\nq = deque([root])\nwhile q:\n now = q.popleft()\n if now:\n result.append(str(now.val))\n q.append(now.left)\n q.append(now.right)\n else:\n result.append('#')\nreturn ' '.join(result)",
"data = list(data.split())\nif data[1] == '#':\n return None\nroot = T... | <|body_start_0|>
result = ['#']
q = deque([root])
while q:
now = q.popleft()
if now:
result.append(str(now.val))
q.append(now.left)
q.append(now.right)
else:
result.append('#')
return ' '.... | 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_000413 | 1,848 | 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:... | f5d9bc468cab8de07b9853c97c3db983e6965d8f | <|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"""
result = ['#']
q = deque([root])
while q:
now = q.popleft()
if now:
result.append(str(now.val))
q.append(now.left)... | the_stack_v2_python_sparse | 파이썬 알고리즘 인터뷰/ch14 트리/47.이진 트리의 직렬화 & 역직렬화.py | leejongcheal/algorithm_python | train | 1 | |
39d11a695ff0f1ee07a91ec1314cb681594e2e73 | [
"nn.Module.__init__(self)\nsuper().__init__(net_spec, in_dim, out_dim)\nutil.set_attr(self, dict(out_layer_activation=None, cell_type='GRU', rnn_num_layers=1, bidirectional=False, init_fn=None, clip_grad_val=None, loss_spec={'name': 'MSELoss'}, optim_spec={'name': 'Adam'}, lr_scheduler_spec=None, update_type='repla... | <|body_start_0|>
nn.Module.__init__(self)
super().__init__(net_spec, in_dim, out_dim)
util.set_attr(self, dict(out_layer_activation=None, cell_type='GRU', rnn_num_layers=1, bidirectional=False, init_fn=None, clip_grad_val=None, loss_spec={'name': 'MSELoss'}, optim_spec={'name': 'Adam'}, lr_sched... | Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three parts: 1. self.fc_model (state processing) 2. self.rnn_model 3. self.model_tails ... | RecurrentNet | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecurrentNet:
"""Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three parts: 1. self.fc_model (state processing... | stack_v2_sparse_classes_36k_train_000414 | 6,331 | permissive | [
{
"docstring": "net_spec: cell_type: any of RNN, LSTM, GRU fc_hid_layers: list of fc layers preceeding the RNN layers hid_layers_activation: activation function for the fc hidden layers out_layer_activation: activation function for the output layer, same shape as out_dim rnn_hidden_size: rnn hidden_size rnn_num... | 2 | stack_v2_sparse_classes_30k_train_018516 | Implement the Python class `RecurrentNet` described below.
Class description:
Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three pa... | Implement the Python class `RecurrentNet` described below.
Class description:
Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three pa... | 9102ff923d7a3e9c579edc18c6547cce94a7b77a | <|skeleton|>
class RecurrentNet:
"""Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three parts: 1. self.fc_model (state processing... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecurrentNet:
"""Class for generating arbitrary sized recurrent neural networks which take a sequence of states as input. Assumes that a single input example is organized into a 3D tensor batch_size x seq_len x state_dim The entire model consists of three parts: 1. self.fc_model (state processing) 2. self.rnn... | the_stack_v2_python_sparse | slm_lab/agent/net/recurrent.py | kengz/SLM-Lab | train | 1,221 |
a54a5916a46a898e5d6d80341137857198466822 | [
"\"\"\"\n Make sure you do not delete the following line. If you would like to\n use Manhattan distances instead of maze distances in order to save\n on initialization time, please take a look at\n CaptureAgent.registerInitialState in captureAgents.py.\n \"\"\"\nCaptureAgent.registerInitialState(self... | <|body_start_0|>
"""
Make sure you do not delete the following line. If you would like to
use Manhattan distances instead of maze distances in order to save
on initialization time, please take a look at
CaptureAgent.registerInitialState in captureAgents.py.
... | A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum. | DummyAgent | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup o... | stack_v2_sparse_classes_36k_train_000415 | 16,102 | no_license | [
{
"docstring": "This method handles the initial setup of the agent to populate useful fields (such as what team we're on). A distanceCalculator instance caches the maze distances between each pair of positions, so your agents can use: self.distancer.getDistance(p1, p2) IMPORTANT: This method may run for at most... | 2 | stack_v2_sparse_classes_30k_train_002185 | Implement the Python class `DummyAgent` described below.
Class description:
A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum.
Method signatures and docstrings:
- def registerInitialState(... | Implement the Python class `DummyAgent` described below.
Class description:
A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum.
Method signatures and docstrings:
- def registerInitialState(... | ab9498434599568bdb8263122fb95f390f155b85 | <|skeleton|>
class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DummyAgent:
"""A Dummy agent to serve as an example of the necessary agent structure. You should look at baselineTeam.py for more details about how to create an agent as this is the bare minimum."""
def registerInitialState(self, gameState):
"""This method handles the initial setup of the agent t... | the_stack_v2_python_sparse | pacman-contest/dogeTeam.py | mylzsd/comp90054-pacman | train | 0 |
79aad45ef61218c8380c83007aadef65c25a546d | [
"self.viewport_name = viewport_name\nself.adhoc_media_pool_publisher = adhoc_media_pool_publisher\nself.media_type = media_type",
"adhoc_medias = self._extract_adhoc_media(data)\nlogger.info('Publishing AdhocMedias: %s' % adhoc_medias)\nself.adhoc_media_pool_publisher.publish(adhoc_medias)",
"medias = extract_f... | <|body_start_0|>
self.viewport_name = viewport_name
self.adhoc_media_pool_publisher = adhoc_media_pool_publisher
self.media_type = media_type
<|end_body_0|>
<|body_start_1|>
adhoc_medias = self._extract_adhoc_media(data)
logger.info('Publishing AdhocMedias: %s' % adhoc_medias)
... | Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mplayer_pool_publisher` | DirectorMediaBridge | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_36k_train_000416 | 4,045 | permissive | [
{
"docstring": "MediaDirectorBridge should be configured per each viewport to properly translate director geometry to viewport geometry and provide separation and service granularity.",
"name": "__init__",
"signature": "def __init__(self, adhoc_media_pool_publisher, viewport_name, media_type='video')"
... | 5 | stack_v2_sparse_classes_30k_train_018267 | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | Implement the Python class `DirectorMediaBridge` described below.
Class description:
Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on direc... | 90233b939bb4873c00a72e84ab3f8d1a776edee8 | <|skeleton|>
class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias mess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DirectorMediaBridge:
"""Bridge between director and MplayerPool or BrowserPlayerPool on specified viewport_name Depending on activity name, messages will contain `media_type` of `video` (mplayer) or `browser_player` (browser e.g. popcorn.js) Listens on director messages and emits AdhocMedias messages via `mpl... | the_stack_v2_python_sparse | lg_media/src/lg_media/director_media_bridge.py | EndPointCorp/lg_ros_nodes | train | 18 |
de5cc6767c3f9066a3bc76aa323be54addad780c | [
"try:\n firewallController = FirewallController()\n json_data = json.loads(request.data.decode())\n firewallController.configure_interface(json_data)\n return Response(status=202)\nexcept Exception as err:\n return Response(json.dumps(str(err)), status=500, mimetype='application/json')",
"try:\n ... | <|body_start_0|>
try:
firewallController = FirewallController()
json_data = json.loads(request.data.decode())
firewallController.configure_interface(json_data)
return Response(status=202)
except Exception as err:
return Response(json.dumps(str(... | Interface_ifEntry | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface_ifEntry:
def post(self):
"""Configure an interface"""
<|body_0|>
def get(self, id=None):
"""Get the configuration of an interface"""
<|body_1|>
def put(self, id):
"""Update the configuration of an interface"""
<|body_2|>
de... | stack_v2_sparse_classes_36k_train_000417 | 12,460 | no_license | [
{
"docstring": "Configure an interface",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Get the configuration of an interface",
"name": "get",
"signature": "def get(self, id=None)"
},
{
"docstring": "Update the configuration of an interface",
"name": "put",
... | 4 | null | Implement the Python class `Interface_ifEntry` described below.
Class description:
Implement the Interface_ifEntry class.
Method signatures and docstrings:
- def post(self): Configure an interface
- def get(self, id=None): Get the configuration of an interface
- def put(self, id): Update the configuration of an inter... | Implement the Python class `Interface_ifEntry` described below.
Class description:
Implement the Interface_ifEntry class.
Method signatures and docstrings:
- def post(self): Configure an interface
- def get(self, id=None): Get the configuration of an interface
- def put(self, id): Update the configuration of an inter... | 6070e3cb6bf957e04f5d8267db11f3296410e18e | <|skeleton|>
class Interface_ifEntry:
def post(self):
"""Configure an interface"""
<|body_0|>
def get(self, id=None):
"""Get the configuration of an interface"""
<|body_1|>
def put(self, id):
"""Update the configuration of an interface"""
<|body_2|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface_ifEntry:
def post(self):
"""Configure an interface"""
try:
firewallController = FirewallController()
json_data = json.loads(request.data.decode())
firewallController.configure_interface(json_data)
return Response(status=202)
exc... | the_stack_v2_python_sparse | configuration-agent/firewall/rest_api/resources/interface.py | ReliableLion/frog4-configurable-vnf | train | 0 | |
215b74cafe6e62706a6365c119a6769207ae42ce | [
"super(FACHead, self).__init__(name=name)\nself.vid_to_hid = tf.keras.layers.Dense(vid_to_aud_txt_kwargs['d_model'], use_bias=False, name='vid_to_hid')\nself.hid_to_va = mlp_lib.ReluDenseBN(pre_bn=True, d_model=vid_to_aud_txt_kwargs['d_model'], bn_config=bn_config, use_xreplica_bn=use_xreplica_bn, name='hid_to_va')... | <|body_start_0|>
super(FACHead, self).__init__(name=name)
self.vid_to_hid = tf.keras.layers.Dense(vid_to_aud_txt_kwargs['d_model'], use_bias=False, name='vid_to_hid')
self.hid_to_va = mlp_lib.ReluDenseBN(pre_bn=True, d_model=vid_to_aud_txt_kwargs['d_model'], bn_config=bn_config, use_xreplica_bn=... | MLP-based Head to bridge audio, text and video with a FAC style. | FACHead | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_co... | stack_v2_sparse_classes_36k_train_000418 | 6,829 | permissive | [
{
"docstring": "Initialize the Fine-to-Coarse head class. Args: bn_config: batchnorm configuration args use_xreplica_bn: whether to use cross-replica bn stats or not vid_to_aud_txt_kwargs: vid2rest MLP args aud_to_vid_txt_kwargs: aud2rest MLP args txt_to_vid_aud_kwargs: txt2rest MLP args name: graph name. **kwa... | 2 | stack_v2_sparse_classes_30k_train_018209 | Implement the Python class `FACHead` described below.
Class description:
MLP-based Head to bridge audio, text and video with a FAC style.
Method signatures and docstrings:
- def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwarg... | Implement the Python class `FACHead` described below.
Class description:
MLP-based Head to bridge audio, text and video with a FAC style.
Method signatures and docstrings:
- def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwarg... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FACHead:
"""MLP-based Head to bridge audio, text and video with a FAC style."""
def __init__(self, bn_config, use_xreplica_bn, vid_to_aud_txt_kwargs, aud_to_vid_txt_kwargs, txt_to_vid_aud_kwargs, name='mlp_fac_head', **kwargs):
"""Initialize the Fine-to-Coarse head class. Args: bn_config: batchno... | the_stack_v2_python_sparse | vatt/modeling/heads/bridge.py | Jimmy-INL/google-research | train | 1 |
d2cc412e30fb8ab6432776ebfa83e70e630a5bec | [
"super().__init__(cv)\nself.y = 500\nif isinstance(x, list) and len(x) > 1:\n self.x = x[0]\n self.y = x[1]\nelse:\n self.x = x\nself.pps = pps\nself.colors = colors\nself._tospawn = 0\nself._pos = pos\nself._speed = speed\nself._timer = timer\nself._time = 0\nself._done = False\nself._doneDone = False\nse... | <|body_start_0|>
super().__init__(cv)
self.y = 500
if isinstance(x, list) and len(x) > 1:
self.x = x[0]
self.y = x[1]
else:
self.x = x
self.pps = pps
self.colors = colors
self._tospawn = 0
self._pos = pos
self._s... | Rocket | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Rocket:
def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25):
"""Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonderful display is painted x {int} -- the position of the rocketrocket pps {int} -- pixels per sec... | stack_v2_sparse_classes_36k_train_000419 | 16,427 | permissive | [
{
"docstring": "Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonderful display is painted x {int} -- the position of the rocketrocket pps {int} -- pixels per second (the speed of the particles) colors {str} -- the color of the particles pos {int} -- t... | 2 | stack_v2_sparse_classes_30k_train_016024 | Implement the Python class `Rocket` described below.
Class description:
Implement the Rocket class.
Method signatures and docstrings:
- def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25): Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonde... | Implement the Python class `Rocket` described below.
Class description:
Implement the Rocket class.
Method signatures and docstrings:
- def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25): Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonde... | c6b6d80e9d59f5d115ca8b8fc020fcd6cb030af8 | <|skeleton|>
class Rocket:
def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25):
"""Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonderful display is painted x {int} -- the position of the rocketrocket pps {int} -- pixels per sec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Rocket:
def __init__(self, cv, x, pps, colors, pos, speed, timer, angle=0.25):
"""Shoots a rocket into the sky which then explodes. Arguments: cv {idontknow} -- the canvas upon which this wonderful display is painted x {int} -- the position of the rocketrocket pps {int} -- pixels per second (the speed... | the_stack_v2_python_sparse | scripts/sheet9/9.2.py | LennartElbe/PythOnline | train | 0 | |
81b570a06834af71ea1dfd95ba2cd5303640d7b1 | [
"ids = self.get_tasks_ids()\nsucc = {}\nfor id in ids:\n succ[id] = []\nreturn succ",
"ids = self.get_tasks_ids()\nprec = {}\nfor id in ids:\n prec[id] = []\nreturn prec"
] | <|body_start_0|>
ids = self.get_tasks_ids()
succ = {}
for id in ids:
succ[id] = []
return succ
<|end_body_0|>
<|body_start_1|>
ids = self.get_tasks_ids()
prec = {}
for id in ids:
prec[id] = []
return prec
<|end_body_1|>
| A domain must inherit this class if there are no predecence constraints between tasks. | WithoutPrecedence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WithoutPrecedence:
"""A domain must inherit this class if there are no predecence constraints between tasks."""
def _get_successors(self) -> Dict[int, List[int]]:
"""Return the successors of the tasks. Successors are given as a list for a task given as a key."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000420 | 3,835 | permissive | [
{
"docstring": "Return the successors of the tasks. Successors are given as a list for a task given as a key.",
"name": "_get_successors",
"signature": "def _get_successors(self) -> Dict[int, List[int]]"
},
{
"docstring": "Return the successors of the tasks. Successors are given as a list for a ... | 2 | null | Implement the Python class `WithoutPrecedence` described below.
Class description:
A domain must inherit this class if there are no predecence constraints between tasks.
Method signatures and docstrings:
- def _get_successors(self) -> Dict[int, List[int]]: Return the successors of the tasks. Successors are given as a... | Implement the Python class `WithoutPrecedence` described below.
Class description:
A domain must inherit this class if there are no predecence constraints between tasks.
Method signatures and docstrings:
- def _get_successors(self) -> Dict[int, List[int]]: Return the successors of the tasks. Successors are given as a... | d4c5ae70cbe8b4c943eafa8439348291ed07dec1 | <|skeleton|>
class WithoutPrecedence:
"""A domain must inherit this class if there are no predecence constraints between tasks."""
def _get_successors(self) -> Dict[int, List[int]]:
"""Return the successors of the tasks. Successors are given as a list for a task given as a key."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WithoutPrecedence:
"""A domain must inherit this class if there are no predecence constraints between tasks."""
def _get_successors(self) -> Dict[int, List[int]]:
"""Return the successors of the tasks. Successors are given as a list for a task given as a key."""
ids = self.get_tasks_ids()... | the_stack_v2_python_sparse | skdecide/builders/domain/scheduling/precedence.py | walter-bd/scikit-decide | train | 0 |
318c2b630d4160945c7c93b5968e91e28e6a0e46 | [
"tmp = nums[:len(nums) - k]\nnums[:len(nums) - k] = []\nnums += tmp",
"tmp = nums[len(nums) - k:]\nnums[len(nums) - k:] = []\nnums[:0] = tmp",
"k %= len(nums)\ntmp = nums * 2\ndel nums[:]\nnums[:] = tmp[len(nums) - k:2 * len(nums) - k]",
"k %= len(nums)\nnums.reverse()\nnums[:k] = reversed(nums[:k])\nnums[k:]... | <|body_start_0|>
tmp = nums[:len(nums) - k]
nums[:len(nums) - k] = []
nums += tmp
<|end_body_0|>
<|body_start_1|>
tmp = nums[len(nums) - k:]
nums[len(nums) - k:] = []
nums[:0] = tmp
<|end_body_1|>
<|body_start_2|>
k %= len(nums)
tmp = nums * 2
de... | Do not return anything, modify nums in-place instead. | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""Do not return anything, modify nums in-place instead."""
def rotate1(self, nums, k):
"""move the first term (52ms)"""
<|body_0|>
def rotate2(self, nums, k):
"""move the last term (52ms)"""
<|body_1|>
def rotate3(self, nums, k):
"... | stack_v2_sparse_classes_36k_train_000421 | 2,073 | permissive | [
{
"docstring": "move the first term (52ms)",
"name": "rotate1",
"signature": "def rotate1(self, nums, k)"
},
{
"docstring": "move the last term (52ms)",
"name": "rotate2",
"signature": "def rotate2(self, nums, k)"
},
{
"docstring": "copy the list (56ms)",
"name": "rotate3",
... | 5 | stack_v2_sparse_classes_30k_val_001149 | Implement the Python class `Solution` described below.
Class description:
Do not return anything, modify nums in-place instead.
Method signatures and docstrings:
- def rotate1(self, nums, k): move the first term (52ms)
- def rotate2(self, nums, k): move the last term (52ms)
- def rotate3(self, nums, k): copy the list... | Implement the Python class `Solution` described below.
Class description:
Do not return anything, modify nums in-place instead.
Method signatures and docstrings:
- def rotate1(self, nums, k): move the first term (52ms)
- def rotate2(self, nums, k): move the last term (52ms)
- def rotate3(self, nums, k): copy the list... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
"""Do not return anything, modify nums in-place instead."""
def rotate1(self, nums, k):
"""move the first term (52ms)"""
<|body_0|>
def rotate2(self, nums, k):
"""move the last term (52ms)"""
<|body_1|>
def rotate3(self, nums, k):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""Do not return anything, modify nums in-place instead."""
def rotate1(self, nums, k):
"""move the first term (52ms)"""
tmp = nums[:len(nums) - k]
nums[:len(nums) - k] = []
nums += tmp
def rotate2(self, nums, k):
"""move the last term (52ms)"""
... | the_stack_v2_python_sparse | leetcode/0189_rotate_array.py | chaosWsF/Python-Practice | train | 1 |
33537e9c37f439bbf482f47b17a6903cdbbc60ec | [
"op_info = operation.Info(**kw)\n_validate_timedelta_arg('backend_time', backend_time)\n_validate_timedelta_arg('overhead_time', overhead_time)\n_validate_timedelta_arg('request_time', request_time)\n_validate_int_arg('request_size', request_size)\n_validate_int_arg('response_size', response_size)\nif not isinstanc... | <|body_start_0|>
op_info = operation.Info(**kw)
_validate_timedelta_arg('backend_time', backend_time)
_validate_timedelta_arg('overhead_time', overhead_time)
_validate_timedelta_arg('request_time', request_time)
_validate_int_arg('request_size', request_size)
_validate_in... | Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): the api version auth_issuer (string): the auth issuer auth_audience (stri... | Info | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Info:
"""Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): the api version auth_issuer (string): the... | stack_v2_sparse_classes_36k_train_000422 | 18,948 | permissive | [
{
"docstring": "Invokes the base constructor with default values.",
"name": "__new__",
"signature": "def __new__(cls, api_name='', api_method='', api_version='', auth_issuer='', auth_audience='', backend_time=None, error_cause=ErrorCause.internal, location='', log_message='', method='', overhead_time=No... | 3 | null | Implement the Python class `Info` described below.
Class description:
Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): th... | Implement the Python class `Info` described below.
Class description:
Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): th... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class Info:
"""Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): the api version auth_issuer (string): the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Info:
"""Holds the information necessary to fill in a ReportRequest. In the attribute descriptions below, N/A means 'not available' Attributes: api_name (string): the api name and version api_method (string): the full api method name api_version (string): the api version auth_issuer (string): the auth issuer ... | the_stack_v2_python_sparse | third_party/google-endpoints/google/api/control/report_request.py | catapult-project/catapult | train | 2,032 |
e21b7563baf81356f0b7c7bf365e74eda5cd6748 | [
"while root and number_of_times:\n l1 = ListNode(None)\n head = l1\n size_of_each_1 = size_of_each\n while root and size_of_each_1:\n l1.next = ListNode(root.val)\n l1 = l1.next\n root = root.next\n size_of_each_1 -= 1\n self.ans.append(head.next)\n number_of_times -= 1... | <|body_start_0|>
while root and number_of_times:
l1 = ListNode(None)
head = l1
size_of_each_1 = size_of_each
while root and size_of_each_1:
l1.next = ListNode(root.val)
l1 = l1.next
root = root.next
s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def addLists(self, number_of_times, size_of_each, root):
"""Create linkedList of "size_of_each" size and append to the ans list "number_of_times" this many number of times and return the changed root"""
<|body_0|>
def splitListToParts(self, root, k):
""":ty... | stack_v2_sparse_classes_36k_train_000423 | 1,704 | no_license | [
{
"docstring": "Create linkedList of \"size_of_each\" size and append to the ans list \"number_of_times\" this many number of times and return the changed root",
"name": "addLists",
"signature": "def addLists(self, number_of_times, size_of_each, root)"
},
{
"docstring": ":type root: ListNode :ty... | 2 | stack_v2_sparse_classes_30k_train_013335 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addLists(self, number_of_times, size_of_each, root): Create linkedList of "size_of_each" size and append to the ans list "number_of_times" this many number of times and retur... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def addLists(self, number_of_times, size_of_each, root): Create linkedList of "size_of_each" size and append to the ans list "number_of_times" this many number of times and retur... | 9f5dcd8e04920d07beaf6aa234b9804339f58770 | <|skeleton|>
class Solution:
def addLists(self, number_of_times, size_of_each, root):
"""Create linkedList of "size_of_each" size and append to the ans list "number_of_times" this many number of times and return the changed root"""
<|body_0|>
def splitListToParts(self, root, k):
""":ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def addLists(self, number_of_times, size_of_each, root):
"""Create linkedList of "size_of_each" size and append to the ans list "number_of_times" this many number of times and return the changed root"""
while root and number_of_times:
l1 = ListNode(None)
head ... | the_stack_v2_python_sparse | 725. Split Linked List in Parts.py | ashish-c-naik/leetcode_submission | train | 0 | |
bc4a76be250a78a13ddcde2d44befe79ba0eae72 | [
"self.small = 1e-90\nself.a1 = 0.2137\nself.c0 = 0.031091\nself.c1 = 0.046644\nself.b1 = 1.0 / 2.0 / self.c0 * np.exp(-self.c1 / 2.0 / self.c0)\nself.b2 = 2 * self.c0 * self.b1 ** 2\nself.b3 = 1.6382\nself.b4 = 0.49294",
"if n < self.small:\n return 0.0\nelse:\n return self.e_x(n, der=der) + self.e_corr(n, ... | <|body_start_0|>
self.small = 1e-90
self.a1 = 0.2137
self.c0 = 0.031091
self.c1 = 0.046644
self.b1 = 1.0 / 2.0 / self.c0 * np.exp(-self.c1 / 2.0 / self.c0)
self.b2 = 2 * self.c0 * self.b1 ** 2
self.b3 = 1.6382
self.b4 = 0.49294
<|end_body_0|>
<|body_start... | XC_PW92 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XC_PW92:
def __init__(self):
"""The Perdew-Wang 1992 LDA exchange-correlation functional."""
<|body_0|>
def exc(self, n, der=0):
"""Exchange-correlation with electron density n."""
<|body_1|>
def e_x(self, n, der=0):
"""Exchange."""
<|bod... | stack_v2_sparse_classes_36k_train_000424 | 1,566 | no_license | [
{
"docstring": "The Perdew-Wang 1992 LDA exchange-correlation functional.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Exchange-correlation with electron density n.",
"name": "exc",
"signature": "def exc(self, n, der=0)"
},
{
"docstring": "Exchange."... | 5 | stack_v2_sparse_classes_30k_train_000365 | Implement the Python class `XC_PW92` described below.
Class description:
Implement the XC_PW92 class.
Method signatures and docstrings:
- def __init__(self): The Perdew-Wang 1992 LDA exchange-correlation functional.
- def exc(self, n, der=0): Exchange-correlation with electron density n.
- def e_x(self, n, der=0): Ex... | Implement the Python class `XC_PW92` described below.
Class description:
Implement the XC_PW92 class.
Method signatures and docstrings:
- def __init__(self): The Perdew-Wang 1992 LDA exchange-correlation functional.
- def exc(self, n, der=0): Exchange-correlation with electron density n.
- def e_x(self, n, der=0): Ex... | d249c4f2a01f58a96083bac2377309c05f652907 | <|skeleton|>
class XC_PW92:
def __init__(self):
"""The Perdew-Wang 1992 LDA exchange-correlation functional."""
<|body_0|>
def exc(self, n, der=0):
"""Exchange-correlation with electron density n."""
<|body_1|>
def e_x(self, n, der=0):
"""Exchange."""
<|bod... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class XC_PW92:
def __init__(self):
"""The Perdew-Wang 1992 LDA exchange-correlation functional."""
self.small = 1e-90
self.a1 = 0.2137
self.c0 = 0.031091
self.c1 = 0.046644
self.b1 = 1.0 / 2.0 / self.c0 * np.exp(-self.c1 / 2.0 / self.c0)
self.b2 = 2 * self.c0 ... | the_stack_v2_python_sparse | HOTBIT/atom_only/XC_PW92.py | f-fathurrahman/ffr-python-stuffs | train | 0 | |
83b90a0c45cac5449281001cdfbe5fe513e5e3e4 | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwini_gdukuray_justini_utdesai')\nurlNumFirms = 'https://www.mbda.gov/csv_data_export?year=2012&industry=All%20Sectors%20%280%29&minority_group=Total%20Minority&metr... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwini_gdukuray_justini_utdesai')
urlNumFirms = 'https://www.mbda.gov/csv_data_export?year=2012&industry=All%20Sector... | mbdaData | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_36k_train_000425 | 5,207 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | stack_v2_sparse_classes_30k_train_020785 | Implement the Python class `mbdaData` described below.
Class description:
Implement the mbdaData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | Implement the Python class `mbdaData` described below.
Class description:
Implement the mbdaData class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=Non... | 90284cf3debbac36eead07b8d2339cdd191b86cf | <|skeleton|>
class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything happ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mbdaData:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('ashwini_gdukuray_justini_utdesai', 'ashwin... | the_stack_v2_python_sparse | ashwini_gdukuray_justini_utdesai/mbdaData.py | maximega/course-2019-spr-proj | train | 2 | |
10f21d25b9e811384312d2f88d6027eb285a6efc | [
"for crd in temperature.coords(dim_coords=True):\n try:\n if crd != lapse_rate.coord(crd.name()):\n raise ValueError('Lapse rate cube coordinate \"{}\" does not match temperature cube coordinate'.format(crd.name()))\n except CoordinateNotFoundError:\n raise ValueError('Lapse rate cube... | <|body_start_0|>
for crd in temperature.coords(dim_coords=True):
try:
if crd != lapse_rate.coord(crd.name()):
raise ValueError('Lapse rate cube coordinate "{}" does not match temperature cube coordinate'.format(crd.name()))
except CoordinateNotFoundErr... | Class to apply a lapse rate adjustment to a temperature data forecast | ApplyGriddedLapseRate | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplyGriddedLapseRate:
"""Class to apply a lapse rate adjustment to a temperature data forecast"""
def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None:
"""Throw an error if the dimension coordinates are not the same for temperature and lapse rate cubes Args: temperatur... | stack_v2_sparse_classes_36k_train_000426 | 20,482 | permissive | [
{
"docstring": "Throw an error if the dimension coordinates are not the same for temperature and lapse rate cubes Args: temperature lapse_rate",
"name": "_check_dim_coords",
"signature": "def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None"
},
{
"docstring": "Get difference in oro... | 3 | stack_v2_sparse_classes_30k_train_002551 | Implement the Python class `ApplyGriddedLapseRate` described below.
Class description:
Class to apply a lapse rate adjustment to a temperature data forecast
Method signatures and docstrings:
- def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None: Throw an error if the dimension coordinates are not the s... | Implement the Python class `ApplyGriddedLapseRate` described below.
Class description:
Class to apply a lapse rate adjustment to a temperature data forecast
Method signatures and docstrings:
- def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None: Throw an error if the dimension coordinates are not the s... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class ApplyGriddedLapseRate:
"""Class to apply a lapse rate adjustment to a temperature data forecast"""
def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None:
"""Throw an error if the dimension coordinates are not the same for temperature and lapse rate cubes Args: temperatur... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ApplyGriddedLapseRate:
"""Class to apply a lapse rate adjustment to a temperature data forecast"""
def _check_dim_coords(temperature: Cube, lapse_rate: Cube) -> None:
"""Throw an error if the dimension coordinates are not the same for temperature and lapse rate cubes Args: temperature lapse_rate"... | the_stack_v2_python_sparse | improver/lapse_rate.py | metoppv/improver | train | 101 |
3297759d1589d178b8e093cda55dfb05b68b0d0a | [
"if categoria_id:\n categoria = Categoria.objects.get(pk=categoria_id)\n form = FormCategoria(instance=categoria)\nelse:\n form = FormCategoria()\nreturn render(request, self.template, {'form': form})",
"if categoria_id:\n categoria = Categoria.objects.get(pk=categoria_id)\n form = FormCategoria(in... | <|body_start_0|>
if categoria_id:
categoria = Categoria.objects.get(pk=categoria_id)
form = FormCategoria(instance=categoria)
else:
form = FormCategoria()
return render(request, self.template, {'form': form})
<|end_body_0|>
<|body_start_1|>
if categor... | Cadastra as categorias | CadastroCategoriaView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
<|body_0|>
def post(self, request, categoria_id=None):
"""Envia para o servidor a nova categoria cadast... | stack_v2_sparse_classes_36k_train_000427 | 4,955 | no_license | [
{
"docstring": "Pega o formulário para cadastrar e atualizar uma categoria",
"name": "get",
"signature": "def get(self, request, categoria_id=None)"
},
{
"docstring": "Envia para o servidor a nova categoria cadastrada ou atualizada",
"name": "post",
"signature": "def post(self, request, ... | 2 | null | Implement the Python class `CadastroCategoriaView` described below.
Class description:
Cadastra as categorias
Method signatures and docstrings:
- def get(self, request, categoria_id=None): Pega o formulário para cadastrar e atualizar uma categoria
- def post(self, request, categoria_id=None): Envia para o servidor a ... | Implement the Python class `CadastroCategoriaView` described below.
Class description:
Cadastra as categorias
Method signatures and docstrings:
- def get(self, request, categoria_id=None): Pega o formulário para cadastrar e atualizar uma categoria
- def post(self, request, categoria_id=None): Envia para o servidor a ... | 7b799a71380aca342e879c5556cc24fcebdac1ca | <|skeleton|>
class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
<|body_0|>
def post(self, request, categoria_id=None):
"""Envia para o servidor a nova categoria cadast... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CadastroCategoriaView:
"""Cadastra as categorias"""
def get(self, request, categoria_id=None):
"""Pega o formulário para cadastrar e atualizar uma categoria"""
if categoria_id:
categoria = Categoria.objects.get(pk=categoria_id)
form = FormCategoria(instance=categor... | the_stack_v2_python_sparse | detransapp/views/categoria.py | brunowber/transnote2 | train | 0 |
fa9de7798949f2f0f67aca60208f2739418f3dc6 | [
"mock_device = mock.Mock(spec=device_utils.DeviceUtils)\nmock_device.adb = mock.Mock(spec=adb_wrapper.AdbWrapper)\ntype(mock_device).build_version_sdk = mock.PropertyMock(return_value=version_codes.LOLLIPOP)\nsystem_props = {}\n\ndef dict_setprop(prop_name, value):\n system_props[prop_name] = value\n\ndef dict_g... | <|body_start_0|>
mock_device = mock.Mock(spec=device_utils.DeviceUtils)
mock_device.adb = mock.Mock(spec=adb_wrapper.AdbWrapper)
type(mock_device).build_version_sdk = mock.PropertyMock(return_value=version_codes.LOLLIPOP)
system_props = {}
def dict_setprop(prop_name, value):
... | SystemAppTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemAppTest:
def testDoubleEnableModification(self):
"""Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should not need to perform any of the expensive modification logic."""
<|body_0|>
def test_GetAppl... | stack_v2_sparse_classes_36k_train_000428 | 4,889 | permissive | [
{
"docstring": "Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should not need to perform any of the expensive modification logic.",
"name": "testDoubleEnableModification",
"signature": "def testDoubleEnableModification(self)"
},
... | 5 | null | Implement the Python class `SystemAppTest` described below.
Class description:
Implement the SystemAppTest class.
Method signatures and docstrings:
- def testDoubleEnableModification(self): Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should no... | Implement the Python class `SystemAppTest` described below.
Class description:
Implement the SystemAppTest class.
Method signatures and docstrings:
- def testDoubleEnableModification(self): Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should no... | 53102de187a48ac2cfc241fef54dcbc29c453a8e | <|skeleton|>
class SystemAppTest:
def testDoubleEnableModification(self):
"""Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should not need to perform any of the expensive modification logic."""
<|body_0|>
def test_GetAppl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemAppTest:
def testDoubleEnableModification(self):
"""Ensures that system app modification logic isn't repeated. If EnableSystemAppModification uses are nested, inner calls should not need to perform any of the expensive modification logic."""
mock_device = mock.Mock(spec=device_utils.Devi... | the_stack_v2_python_sparse | devil/devil/android/tools/system_app_test.py | catapult-project/catapult | train | 2,032 | |
bcad9a059d3f5d5d63688c9fe42f9867532b904d | [
"self.any_permission = any_permission\nself.add_permission = add_permission\nself.change_permission = change_permission\nself.delete_permission = delete_permission",
"add_name = self.get_full_permission_string('add')\nchange_name = self.get_full_permission_string('change')\ndelete_name = self.get_full_permission_... | <|body_start_0|>
self.any_permission = any_permission
self.add_permission = add_permission
self.change_permission = change_permission
self.delete_permission = delete_permission
<|end_body_0|>
<|body_start_1|>
add_name = self.get_full_permission_string('add')
change_name ... | Permission logic class for role based permission system It is checked by user_obj.role | BaseRolePermissionLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission ... | stack_v2_sparse_classes_36k_train_000429 | 6,884 | no_license | [
{
"docstring": "Constructor Parameters ---------- any_permission : boolean True for give any permission of the specified object or model to the role. Default value will be `False` add_permission : boolean True for give add permission of the specified model to the role. Default value will be 'False' change_permi... | 2 | stack_v2_sparse_classes_30k_train_003185 | Implement the Python class `BaseRolePermissionLogic` described below.
Class description:
Permission logic class for role based permission system It is checked by user_obj.role
Method signatures and docstrings:
- def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=... | Implement the Python class `BaseRolePermissionLogic` described below.
Class description:
Permission logic class for role based permission system It is checked by user_obj.role
Method signatures and docstrings:
- def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=... | 8f9a850c4df41b0fc1da5b73189772552d5cd531 | <|skeleton|>
class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BaseRolePermissionLogic:
"""Permission logic class for role based permission system It is checked by user_obj.role"""
def __init__(self, any_permission=False, add_permission=False, change_permission=False, delete_permission=False):
"""Constructor Parameters ---------- any_permission : boolean Tru... | the_stack_v2_python_sparse | src/kawaz/core/personas/perms.py | kawazrepos/Kawaz3rd | train | 7 |
8688f2fd9b8440b73bae969de90c2bde95ceddaa | [
"self.d = {}\nself.cap = capacity\nself.l = []",
"if key in self.d:\n self.l[self.d[key]][1] += 1\n p = self.d[key]\n while p > 0:\n if self.l[p][1] >= self.l[p - 1][1]:\n self.l[p], self.l[p - 1] = (self.l[p - 1], self.l[p])\n p -= 1\n else:\n self.d[key] =... | <|body_start_0|>
self.d = {}
self.cap = capacity
self.l = []
<|end_body_0|>
<|body_start_1|>
if key in self.d:
self.l[self.d[key]][1] += 1
p = self.d[key]
while p > 0:
if self.l[p][1] >= self.l[p - 1][1]:
self.l[p],... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_000430 | 1,141 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: nothing",
"name": "set",
"sig... | 3 | stack_v2_sparse_classes_30k_train_006672 | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing | Implement the Python class `LRUCache` described below.
Class description:
Implement the LRUCache class.
Method signatures and docstrings:
- def __init__(self, capacity): :type capacity: int
- def get(self, key): :rtype: int
- def set(self, key, value): :type key: int :type value: int :rtype: nothing
<|skeleton|>
cla... | d61363f99de3d591ebc8cd94f62544a31a026d55 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":rtype: int"""
<|body_1|>
def set(self, key, value):
""":type key: int :type value: int :rtype: nothing"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.d = {}
self.cap = capacity
self.l = []
def get(self, key):
""":rtype: int"""
if key in self.d:
self.l[self.d[key]][1] += 1
p = self.d[key]
while p > 0... | the_stack_v2_python_sparse | 146_LRU_Cache_Alter.py | nlfox/leetcode | train | 2 | |
db78845e26e90421164181e7742dcb33ccad6673 | [
"def transform(node):\n if node:\n vals.append(str(node.val))\n transform(node.left)\n transform(node.right)\nvals = []\ntransform(root)\nreturn ' '.join(vals)",
"def helper(lower=float('-inf'), upper=float('inf')):\n if not queue or queue[0] < lower or queue[0] > upper:\n return... | <|body_start_0|>
def transform(node):
if node:
vals.append(str(node.val))
transform(node.left)
transform(node.right)
vals = []
transform(root)
return ' '.join(vals)
<|end_body_0|>
<|body_start_1|>
def helper(lower=float... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize1(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|>
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_36k_train_000431 | 3,487 | no_license | [
{
"docstring": "Encodes a tree to a single string.",
"name": "serialize1",
"signature": "def serialize1(self, root: TreeNode) -> str"
},
{
"docstring": "Decodes your encoded data to tree.",
"name": "deserialize",
"signature": "def deserialize(self, data: str) -> TreeNode"
},
{
"d... | 5 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize1(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
- def serialize(self,... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize1(self, root: TreeNode) -> str: Encodes a tree to a single string.
- def deserialize(self, data: str) -> TreeNode: Decodes your encoded data to tree.
- def serialize(self,... | 502e121cc25fcd81afe3d029145aeee56db794f0 | <|skeleton|>
class Codec:
def serialize1(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|>
def serialize(self, root: TreeNode) -> str:
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize1(self, root: TreeNode) -> str:
"""Encodes a tree to a single string."""
def transform(node):
if node:
vals.append(str(node.val))
transform(node.left)
transform(node.right)
vals = []
transform(root)... | the_stack_v2_python_sparse | 449serialize.py | qinzhouhit/leetcode | train | 0 | |
edcc61e45f7fc0cdd277139836e0289542f451c4 | [
"comments = list(_get_comments(dependency_results))\nsimple_keywords_regex = re.compile('(' + '|'.join((re.escape(key) for key in keywords)) + ')', re.IGNORECASE)\nmessage = \"The line contains the keyword '{}'.\"\nyield from self.check_keywords(filename, file, comments, simple_keywords_regex, message)\nif regex_ke... | <|body_start_0|>
comments = list(_get_comments(dependency_results))
simple_keywords_regex = re.compile('(' + '|'.join((re.escape(key) for key in keywords)) + ')', re.IGNORECASE)
message = "The line contains the keyword '{}'."
yield from self.check_keywords(filename, file, comments, simpl... | KeywordBear | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordBear:
def run(self, filename, file, keywords: list=['todo', 'fixme'], regex_keyword: str='', dependency_results: dict=None):
"""Checks the code files for given keywords. :param keywords: A list of keywords to search for (case insensitive). Default are TODO and FIXME. :param regex_... | stack_v2_sparse_classes_36k_train_000432 | 5,129 | no_license | [
{
"docstring": "Checks the code files for given keywords. :param keywords: A list of keywords to search for (case insensitive). Default are TODO and FIXME. :param regex_keyword: A regular expression to search for matching keywords in a file.",
"name": "run",
"signature": "def run(self, filename, file, k... | 2 | null | Implement the Python class `KeywordBear` described below.
Class description:
Implement the KeywordBear class.
Method signatures and docstrings:
- def run(self, filename, file, keywords: list=['todo', 'fixme'], regex_keyword: str='', dependency_results: dict=None): Checks the code files for given keywords. :param keyw... | Implement the Python class `KeywordBear` described below.
Class description:
Implement the KeywordBear class.
Method signatures and docstrings:
- def run(self, filename, file, keywords: list=['todo', 'fixme'], regex_keyword: str='', dependency_results: dict=None): Checks the code files for given keywords. :param keyw... | 278e4f6f8ce4677e213150716704330d83debf9f | <|skeleton|>
class KeywordBear:
def run(self, filename, file, keywords: list=['todo', 'fixme'], regex_keyword: str='', dependency_results: dict=None):
"""Checks the code files for given keywords. :param keywords: A list of keywords to search for (case insensitive). Default are TODO and FIXME. :param regex_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class KeywordBear:
def run(self, filename, file, keywords: list=['todo', 'fixme'], regex_keyword: str='', dependency_results: dict=None):
"""Checks the code files for given keywords. :param keywords: A list of keywords to search for (case insensitive). Default are TODO and FIXME. :param regex_keyword: A reg... | the_stack_v2_python_sparse | ve/Lib/site-packages/bears/general/KeywordBear.py | lugnitdgp/avskr2.0 | train | 4 | |
a33bdddcffcce6efe2444dec4a27a3771ce80926 | [
"self.logger = logger.SecureTeaLogger(__name__, debug=debug)\nself.system_log_map = {'debian': ['/etc/passwd', '/etc/shadow']}\nos_name = utils.categorize_os()\nself.log_file = None\nif os_name:\n try:\n self.log_file = self.system_log_map[os_name]\n except KeyError:\n self.logger.log('Could not... | <|body_start_0|>
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.system_log_map = {'debian': ['/etc/passwd', '/etc/shadow']}
os_name = utils.categorize_os()
self.log_file = None
if os_name:
try:
self.log_file = self.system_log_map[os_n... | CheckSync Class. | CheckSync | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckSync:
"""CheckSync Class."""
def __init__(self, debug=False):
"""Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def parse_log_file(self):
"""Parse the log files to get the list of usernames. Args: No... | stack_v2_sparse_classes_36k_train_000433 | 3,710 | permissive | [
{
"docstring": "Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False)"
},
{
"docstring": "Parse the log files to get the list of usernames. Args: None Raises: None Returns: None",
"name"... | 4 | stack_v2_sparse_classes_30k_train_007860 | Implement the Python class `CheckSync` described below.
Class description:
CheckSync Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def parse_log_file(self): Parse the log files to get the list o... | Implement the Python class `CheckSync` described below.
Class description:
CheckSync Class.
Method signatures and docstrings:
- def __init__(self, debug=False): Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def parse_log_file(self): Parse the log files to get the list o... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class CheckSync:
"""CheckSync Class."""
def __init__(self, debug=False):
"""Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def parse_log_file(self):
"""Parse the log files to get the list of usernames. Args: No... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckSync:
"""CheckSync Class."""
def __init__(self, debug=False):
"""Initialize CheckSync. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = logger.SecureTeaLogger(__name__, debug=debug)
self.system_log_map = {'debian': ['/etc/passwd', '/etc/s... | the_stack_v2_python_sparse | securetea/lib/log_monitor/system_log/check_sync.py | rejahrehim/SecureTea-Project | train | 1 |
d2a6f8dc4e547da16687647c34836464b9ae8293 | [
"self.layer = layer\nself.template = Template(template)\nself.referer = referer\nself.source_projection = source_projection\nself.timeout = timeout",
"kwargs = {'template': config_dict['template']}\nif 'referer' in config_dict:\n kwargs['referer'] = config_dict['referer']\nif 'source projection' in config_dict... | <|body_start_0|>
self.layer = layer
self.template = Template(template)
self.referer = referer
self.source_projection = source_projection
self.timeout = timeout
<|end_body_0|>
<|body_start_1|>
kwargs = {'template': config_dict['template']}
if 'referer' in config_d... | Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in string.Template. - referer (optional) String to use in the "Referer" header when... | UrlTemplate | [
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UrlTemplate:
"""Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in string.Template. - referer (optional) Str... | stack_v2_sparse_classes_36k_train_000434 | 11,802 | permissive | [
{
"docstring": "Initialize a UrlTemplate provider with layer and template string. http://docs.python.org/library/string.html#template-strings",
"name": "__init__",
"signature": "def __init__(self, layer, template, referer=None, source_projection=None, timeout=None)"
},
{
"docstring": "Convert co... | 3 | null | Implement the Python class `UrlTemplate` described below.
Class description:
Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in st... | Implement the Python class `UrlTemplate` described below.
Class description:
Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in st... | 0c10a32df428dab719d1a0333854fccdbab3309b | <|skeleton|>
class UrlTemplate:
"""Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in string.Template. - referer (optional) Str... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UrlTemplate:
"""Built-in URL Template provider. Proxies map images from WMS servers. This provider is identified by the name "url template" in the TileStache config. Additional arguments: - template (required) String with substitutions suitable for use in string.Template. - referer (optional) String to use in... | the_stack_v2_python_sparse | ch10/TileStache-master/TileStache/Providers.py | mdiener21/python-geospatial-analysis-cookbook | train | 124 |
139f5b5db448db070ce0d67f60eaf5204aa9b04a | [
"super(Session, self).__init__()\nself.aborted = False\nself.analysis_reports_counter = collections.Counter()\nself.artifact_filters = None\nself.command_line_arguments = None\nself.completion_time = None\nself.debug_mode = False\nself.enabled_parser_names = None\nself.event_labels_counter = collections.Counter()\n... | <|body_start_0|>
super(Session, self).__init__()
self.aborted = False
self.analysis_reports_counter = collections.Counter()
self.artifact_filters = None
self.command_line_arguments = None
self.completion_time = None
self.debug_mode = False
self.enabled_par... | Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions that are used for filtering file system and Windows Registry key paths. co... | Session | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Session:
"""Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions that are used for filtering file system... | stack_v2_sparse_classes_36k_train_000435 | 9,343 | permissive | [
{
"docstring": "Initializes a session attribute container.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Copies attributes from a session completion. Args: session_completion (SessionCompletion): session completion attribute container. Raises: ValueError: if the iden... | 5 | stack_v2_sparse_classes_30k_train_013980 | Implement the Python class `Session` described below.
Class description:
Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions ... | Implement the Python class `Session` described below.
Class description:
Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions ... | 9f8e05f21fa23793bfdade6af1d617e9dd092531 | <|skeleton|>
class Session:
"""Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions that are used for filtering file system... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Session:
"""Session attribute container. Attributes: aborted (bool): True if the session was aborted. analysis_reports_counter (collections.Counter): number of analysis reports per analysis plugin. artifact_filters (list[str]): Names of artifact definitions that are used for filtering file system and Windows ... | the_stack_v2_python_sparse | plaso/containers/sessions.py | joshlemon/plaso | train | 1 |
044d801a230032609e0c3a1915568f9a3aba2acf | [
"parser.add_argument('-u', '--useremail', required=True, help='User email')\nparser.add_argument('-n', '--name', help='Workflow name (only valid if a single file is given)')\nparser.add_argument('-r', dest='replace', action='store_true', help='Replace workflow if it exists')\nparser.add_argument('args', metavar='wo... | <|body_start_0|>
parser.add_argument('-u', '--useremail', required=True, help='User email')
parser.add_argument('-n', '--name', help='Workflow name (only valid if a single file is given)')
parser.add_argument('-r', dest='replace', action='store_true', help='Replace workflow if it exists')
... | Import a given workflot to a given user. | Command | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Import a given workflot to a given user."""
def add_arguments(self, parser):
"""Parse the arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Execute the command to import a workflow."""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_36k_train_000436 | 2,694 | permissive | [
{
"docstring": "Parse the arguments.",
"name": "add_arguments",
"signature": "def add_arguments(self, parser)"
},
{
"docstring": "Execute the command to import a workflow.",
"name": "handle",
"signature": "def handle(self, *args, **options)"
}
] | 2 | null | Implement the Python class `Command` described below.
Class description:
Import a given workflot to a given user.
Method signatures and docstrings:
- def add_arguments(self, parser): Parse the arguments.
- def handle(self, *args, **options): Execute the command to import a workflow. | Implement the Python class `Command` described below.
Class description:
Import a given workflot to a given user.
Method signatures and docstrings:
- def add_arguments(self, parser): Parse the arguments.
- def handle(self, *args, **options): Execute the command to import a workflow.
<|skeleton|>
class Command:
"... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class Command:
"""Import a given workflot to a given user."""
def add_arguments(self, parser):
"""Parse the arguments."""
<|body_0|>
def handle(self, *args, **options):
"""Execute the command to import a workflow."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Import a given workflot to a given user."""
def add_arguments(self, parser):
"""Parse the arguments."""
parser.add_argument('-u', '--useremail', required=True, help='User email')
parser.add_argument('-n', '--name', help='Workflow name (only valid if a single file is gi... | the_stack_v2_python_sparse | ontask/management/commands/workflow_import.py | abelardopardo/ontask_b | train | 43 |
345881d50ce9fb6c2bb01401b2936355477ce3c5 | [
"self.q = []\nself.map = {}\nfor i in nums:\n self.add(i)",
"while len(self.q) > 0 and self.map[self.q[0]] > 1:\n self.q.pop(0)\nif len(self.q) == 0:\n return -1\nelse:\n return self.q[0]",
"if value in self.map:\n self.map[value] += 1\nelse:\n self.map[value] = 1\n self.q.append(value)"
] | <|body_start_0|>
self.q = []
self.map = {}
for i in nums:
self.add(i)
<|end_body_0|>
<|body_start_1|>
while len(self.q) > 0 and self.map[self.q[0]] > 1:
self.q.pop(0)
if len(self.q) == 0:
return -1
else:
return self.q[0]
<|... | FirstUnique | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_000437 | 970 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":rtype: int",
"name": "showFirstUnique",
"signature": "def showFirstUnique(self)"
},
{
"docstring": ":type value: int :rtype: None",
"name": "add",
"sign... | 3 | stack_v2_sparse_classes_30k_train_007298 | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None | Implement the Python class `FirstUnique` described below.
Class description:
Implement the FirstUnique class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def showFirstUnique(self): :rtype: int
- def add(self, value): :type value: int :rtype: None
<|skeleton|>
class FirstUniq... | a7ae22103f56f4f17b79a94725e2f8b9dd1dbfd0 | <|skeleton|>
class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def showFirstUnique(self):
""":rtype: int"""
<|body_1|>
def add(self, value):
""":type value: int :rtype: None"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FirstUnique:
def __init__(self, nums):
""":type nums: List[int]"""
self.q = []
self.map = {}
for i in nums:
self.add(i)
def showFirstUnique(self):
""":rtype: int"""
while len(self.q) > 0 and self.map[self.q[0]] > 1:
self.q.pop(0)
... | the_stack_v2_python_sparse | First Unique Number.py | PrakruthiSomashekar/LeetCode | train | 0 | |
cd72ad29e122bd40c1a4269866af89796484d017 | [
"if value and value.startswith('@'):\n value = value[1:]\nself.data = value",
"self.data = self.data.replace('@', '')\nif not TWITTER_HANDLE_PATTERN.match(self.data):\n raise ValidationError('Not a valid Twitter handle.')",
"if self.data:\n return '@' + self.data\nelse:\n return ''"
] | <|body_start_0|>
if value and value.startswith('@'):
value = value[1:]
self.data = value
<|end_body_0|>
<|body_start_1|>
self.data = self.data.replace('@', '')
if not TWITTER_HANDLE_PATTERN.match(self.data):
raise ValidationError('Not a valid Twitter handle.')
<|... | A field for capturing a Twitter handle. | TwitterField | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TwitterField:
"""A field for capturing a Twitter handle."""
def process_data(self, value):
"""Strip a leading @ on incoming data."""
<|body_0|>
def pre_validate(self, form):
"""Check that the handle conforms to Twitter restrictions."""
<|body_1|>
def... | stack_v2_sparse_classes_36k_train_000438 | 985 | permissive | [
{
"docstring": "Strip a leading @ on incoming data.",
"name": "process_data",
"signature": "def process_data(self, value)"
},
{
"docstring": "Check that the handle conforms to Twitter restrictions.",
"name": "pre_validate",
"signature": "def pre_validate(self, form)"
},
{
"docstr... | 3 | stack_v2_sparse_classes_30k_train_011375 | Implement the Python class `TwitterField` described below.
Class description:
A field for capturing a Twitter handle.
Method signatures and docstrings:
- def process_data(self, value): Strip a leading @ on incoming data.
- def pre_validate(self, form): Check that the handle conforms to Twitter restrictions.
- def _va... | Implement the Python class `TwitterField` described below.
Class description:
A field for capturing a Twitter handle.
Method signatures and docstrings:
- def process_data(self, value): Strip a leading @ on incoming data.
- def pre_validate(self, form): Check that the handle conforms to Twitter restrictions.
- def _va... | 310508c16dabf2ce9aaf0c2624132d725f71143b | <|skeleton|>
class TwitterField:
"""A field for capturing a Twitter handle."""
def process_data(self, value):
"""Strip a leading @ on incoming data."""
<|body_0|>
def pre_validate(self, form):
"""Check that the handle conforms to Twitter restrictions."""
<|body_1|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TwitterField:
"""A field for capturing a Twitter handle."""
def process_data(self, value):
"""Strip a leading @ on incoming data."""
if value and value.startswith('@'):
value = value[1:]
self.data = value
def pre_validate(self, form):
"""Check that the han... | the_stack_v2_python_sparse | pygotham/fields.py | PyGotham/pygotham | train | 19 |
7971ae69eec593041f3bb59c11e8855bb4f0e8ff | [
"for row in matrix:\n if not is_constant_row(row):\n return False\nreturn True",
"rows = []\nfor _ in range(self.num_rows):\n sampled_atom = random_state.choice(self.num_atoms)\n rows.append([sampled_atom] * self.num_cols)\nreturn np.array(rows)"
] | <|body_start_0|>
for row in matrix:
if not is_constant_row(row):
return False
return True
<|end_body_0|>
<|body_start_1|>
rows = []
for _ in range(self.num_rows):
sampled_atom = random_state.choice(self.num_atoms)
rows.append([sampled_... | Relation where rows in the matrix are constant. | ConstantRelation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
<|bo... | stack_v2_sparse_classes_36k_train_000439 | 10,947 | permissive | [
{
"docstring": "Checks whether the matrix satisfies the relation.",
"name": "is_consistent",
"signature": "def is_consistent(matrix)"
},
{
"docstring": "Samples a matrix consistent with the relation.",
"name": "sample",
"signature": "def sample(self, random_state)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014039 | Implement the Python class `ConstantRelation` described below.
Class description:
Relation where rows in the matrix are constant.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with the rela... | Implement the Python class `ConstantRelation` described below.
Class description:
Relation where rows in the matrix are constant.
Method signatures and docstrings:
- def is_consistent(matrix): Checks whether the matrix satisfies the relation.
- def sample(self, random_state): Samples a matrix consistent with the rela... | 73d4b995e88efdd5ffbe98a72e48a620c58f4dc7 | <|skeleton|>
class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
<|body_0|>
def sample(self, random_state):
"""Samples a matrix consistent with the relation."""
<|bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConstantRelation:
"""Relation where rows in the matrix are constant."""
def is_consistent(matrix):
"""Checks whether the matrix satisfies the relation."""
for row in matrix:
if not is_constant_row(row):
return False
return True
def sample(self, ran... | the_stack_v2_python_sparse | disentanglement_lib/evaluation/abstract_reasoning/pgm_utils.py | travers-rhodes/disentanglement_lib | train | 0 |
f9c5d5379db4ae514ea1f2ae3e60001c51a6d01b | [
"self.kubeconfig = kubeconfig\nself.name = sname\nself.namespace = namespace\nself.secrets = secrets\nself.data = {}\nself.create_dict()",
"self.data['apiVersion'] = 'v1'\nself.data['kind'] = 'Secret'\nself.data['metadata'] = {}\nself.data['metadata']['name'] = self.name\nself.data['metadata']['namespace'] = self... | <|body_start_0|>
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.secrets = secrets
self.data = {}
self.create_dict()
<|end_body_0|>
<|body_start_1|>
self.data['apiVersion'] = 'v1'
self.data['kind'] = 'Secret'
self.da... | Handle secret options | SecretConfig | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecretConfig:
"""Handle secret options"""
def __init__(self, sname, namespace, kubeconfig, secrets=None):
"""constructor for handling secret options"""
<|body_0|>
def create_dict(self):
"""return a secret as a dict"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_000440 | 2,639 | permissive | [
{
"docstring": "constructor for handling secret options",
"name": "__init__",
"signature": "def __init__(self, sname, namespace, kubeconfig, secrets=None)"
},
{
"docstring": "return a secret as a dict",
"name": "create_dict",
"signature": "def create_dict(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_013941 | Implement the Python class `SecretConfig` described below.
Class description:
Handle secret options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig, secrets=None): constructor for handling secret options
- def create_dict(self): return a secret as a dict | Implement the Python class `SecretConfig` described below.
Class description:
Handle secret options
Method signatures and docstrings:
- def __init__(self, sname, namespace, kubeconfig, secrets=None): constructor for handling secret options
- def create_dict(self): return a secret as a dict
<|skeleton|>
class SecretC... | e342f6659a4ef1a188ff403e2fc6b06ac6d119c7 | <|skeleton|>
class SecretConfig:
"""Handle secret options"""
def __init__(self, sname, namespace, kubeconfig, secrets=None):
"""constructor for handling secret options"""
<|body_0|>
def create_dict(self):
"""return a secret as a dict"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SecretConfig:
"""Handle secret options"""
def __init__(self, sname, namespace, kubeconfig, secrets=None):
"""constructor for handling secret options"""
self.kubeconfig = kubeconfig
self.name = sname
self.namespace = namespace
self.secrets = secrets
self.dat... | the_stack_v2_python_sparse | ansible/roles/lib_openshift_3.2/build/lib/secret.py | openshift/openshift-tools | train | 170 |
2fefcc8b3acb3c0537d434c5b50a9de32dcdae4b | [
"self.train = []\nself.test = []\nself.k = k\nself.dataset_name = dataset_name\nwith open(url_train) as f:\n t = f.readlines()\n for x in range(len(t)):\n a = t[x].replace('\\n', '').split(',')\n self.train.append(a)\nwith open(url_test) as f:\n t = f.readlines()\n for x in range(len(t)):\... | <|body_start_0|>
self.train = []
self.test = []
self.k = k
self.dataset_name = dataset_name
with open(url_train) as f:
t = f.readlines()
for x in range(len(t)):
a = t[x].replace('\n', '').split(',')
self.train.append(a)
... | This class implements the k-Nearest-Neighbor learner. | knn | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class knn:
"""This class implements the k-Nearest-Neighbor learner."""
def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv', url_test='data/spect-orig.test.csv', k=5):
"""The constructor of the knn instance. :param url_train: the url for the train dataset file :par... | stack_v2_sparse_classes_36k_train_000441 | 4,167 | permissive | [
{
"docstring": "The constructor of the knn instance. :param url_train: the url for the train dataset file :param url_test: the url for the tst dataset file :param k: the k-th nearest neighbor",
"name": "__init__",
"signature": "def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv... | 5 | stack_v2_sparse_classes_30k_train_004834 | Implement the Python class `knn` described below.
Class description:
This class implements the k-Nearest-Neighbor learner.
Method signatures and docstrings:
- def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv', url_test='data/spect-orig.test.csv', k=5): The constructor of the knn instance. ... | Implement the Python class `knn` described below.
Class description:
This class implements the k-Nearest-Neighbor learner.
Method signatures and docstrings:
- def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv', url_test='data/spect-orig.test.csv', k=5): The constructor of the knn instance. ... | 1da22b8560aa0426492288b243bb9d14397927f2 | <|skeleton|>
class knn:
"""This class implements the k-Nearest-Neighbor learner."""
def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv', url_test='data/spect-orig.test.csv', k=5):
"""The constructor of the knn instance. :param url_train: the url for the train dataset file :par... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class knn:
"""This class implements the k-Nearest-Neighbor learner."""
def __init__(self, dataset_name='orig', url_train='data/spect-orig.train.csv', url_test='data/spect-orig.test.csv', k=5):
"""The constructor of the knn instance. :param url_train: the url for the train dataset file :param url_test: ... | the_stack_v2_python_sparse | hw2/knn.py | ovimura/cs541-ai | train | 0 |
903802845f80cf0335662140bae84750609ba452 | [
"flags.AddUsername(parser)\nflags.AddRegion(parser)\nflags.AddCluster(parser, False)\nflags.AddUserPassword(parser, True)",
"client = api_util.AlloyDBClient(self.ReleaseTrack())\nalloydb_client = client.alloydb_client\nalloydb_messages = client.alloydb_messages\nuser_ref = client.resource_parser.Create('alloydb.p... | <|body_start_0|>
flags.AddUsername(parser)
flags.AddRegion(parser)
flags.AddCluster(parser, False)
flags.AddUserPassword(parser, True)
<|end_body_0|>
<|body_start_1|>
client = api_util.AlloyDBClient(self.ReleaseTrack())
alloydb_client = client.alloydb_client
allo... | Update an AlloyDB user's password within a given cluster and region. | Update | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs... | stack_v2_sparse_classes_36k_train_000442 | 2,620 | permissive | [
{
"docstring": "Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.",
"name": "Args",
"signature": "def Args(cls, parser)"
},
{
"docstring": "Constructs and sends request. Args: args: argparse.Namespace, An object that contains the values for... | 2 | stack_v2_sparse_classes_30k_train_021195 | Implement the Python class `Update` described below.
Class description:
Update an AlloyDB user's password within a given cluster and region.
Method signatures and docstrings:
- def Args(cls, parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(se... | Implement the Python class `Update` described below.
Class description:
Update an AlloyDB user's password within a given cluster and region.
Method signatures and docstrings:
- def Args(cls, parser): Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs.
- def Run(se... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
<|body_0|>
def Run(self, args):
"""Constructs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Update:
"""Update an AlloyDB user's password within a given cluster and region."""
def Args(cls, parser):
"""Specifies additional command flags. Args: parser: argparse.Parser: Parser object for command line inputs."""
flags.AddUsername(parser)
flags.AddRegion(parser)
flags... | the_stack_v2_python_sparse | lib/surface/alloydb/users/set_password.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
68701e85faa912f96a4522838bfb046d27af660a | [
"self.api_key = api_key\nself.locale = locale\nself.market = market\nself.currency = currency\nself.logger = get_logger()",
"outbound_date_str = _prepare_date_format(outbound_date)\nquery_url = '{}/{}/{}/{}/{}/{}?apiKey={}'.format(self.market, self.currency, self.locale, start_city, end_city, outbound_date_str, s... | <|body_start_0|>
self.api_key = api_key
self.locale = locale
self.market = market
self.currency = currency
self.logger = get_logger()
<|end_body_0|>
<|body_start_1|>
outbound_date_str = _prepare_date_format(outbound_date)
query_url = '{}/{}/{}/{}/{}/{}?apiKey={}'... | SkyScannerClient | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SkyScannerClient:
def __init__(self, api_key, market, locale, currency):
""":type api_key: str :param market: The users market country, Skyscanner country code :type market: str :param locale: The users selected language, ISO locale code :type locale: str :param currency: The users selec... | stack_v2_sparse_classes_36k_train_000443 | 2,713 | permissive | [
{
"docstring": ":type api_key: str :param market: The users market country, Skyscanner country code :type market: str :param locale: The users selected language, ISO locale code :type locale: str :param currency: The users selected currency, ISO currency code :type currency: str",
"name": "__init__",
"s... | 2 | stack_v2_sparse_classes_30k_train_015110 | Implement the Python class `SkyScannerClient` described below.
Class description:
Implement the SkyScannerClient class.
Method signatures and docstrings:
- def __init__(self, api_key, market, locale, currency): :type api_key: str :param market: The users market country, Skyscanner country code :type market: str :para... | Implement the Python class `SkyScannerClient` described below.
Class description:
Implement the SkyScannerClient class.
Method signatures and docstrings:
- def __init__(self, api_key, market, locale, currency): :type api_key: str :param market: The users market country, Skyscanner country code :type market: str :para... | 1a2ee7c6f6f52ce61754510cd7b59e180565306c | <|skeleton|>
class SkyScannerClient:
def __init__(self, api_key, market, locale, currency):
""":type api_key: str :param market: The users market country, Skyscanner country code :type market: str :param locale: The users selected language, ISO locale code :type locale: str :param currency: The users selec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SkyScannerClient:
def __init__(self, api_key, market, locale, currency):
""":type api_key: str :param market: The users market country, Skyscanner country code :type market: str :param locale: The users selected language, ISO locale code :type locale: str :param currency: The users selected currency, ... | the_stack_v2_python_sparse | clients/clients/sky_scanner.py | emkor/serverless-pwr-inz | train | 2 | |
2b5ae912190d192c9800f906ef4ce1e338138b5b | [
"if value is self.field.missing_value:\n return []\nconverter = self._getConverter(self.field.value_type)\nkey_converter = self._getConverter(self.field.key_type)\nreturn [(key_converter.toWidgetValue(k), converter.toWidgetValue(v)) for k, v in value.items()]",
"if not len(value):\n return self.field.missin... | <|body_start_0|>
if value is self.field.missing_value:
return []
converter = self._getConverter(self.field.value_type)
key_converter = self._getConverter(self.field.key_type)
return [(key_converter.toWidgetValue(k), converter.toWidgetValue(v)) for k, v in value.items()]
<|end... | Data converter for IMultiWidget. | DictMultiConverter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
<|body_0|>
def toFieldValue(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if value is self.fi... | stack_v2_sparse_classes_36k_train_000444 | 15,934 | permissive | [
{
"docstring": "Just dispatch it.",
"name": "toWidgetValue",
"signature": "def toWidgetValue(self, value)"
},
{
"docstring": "Just dispatch it.",
"name": "toFieldValue",
"signature": "def toFieldValue(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_014058 | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def toWidgetValue(self, value): Just dispatch it.
- def toFieldValue(self, value): Just dispatch it. | Implement the Python class `DictMultiConverter` described below.
Class description:
Data converter for IMultiWidget.
Method signatures and docstrings:
- def toWidgetValue(self, value): Just dispatch it.
- def toFieldValue(self, value): Just dispatch it.
<|skeleton|>
class DictMultiConverter:
"""Data converter fo... | aa47e9b109ad2d7de600fc1d4ea7359d8144f356 | <|skeleton|>
class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
<|body_0|>
def toFieldValue(self, value):
"""Just dispatch it."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DictMultiConverter:
"""Data converter for IMultiWidget."""
def toWidgetValue(self, value):
"""Just dispatch it."""
if value is self.field.missing_value:
return []
converter = self._getConverter(self.field.value_type)
key_converter = self._getConverter(self.fiel... | the_stack_v2_python_sparse | src/z3c/form/converter.py | zopefoundation/z3c.form | train | 6 |
37eb6532ab3d33eaa04cc80491e77a523f1140b9 | [
"if fit_data is None and (a is None or b is None):\n raise ValueError('Either all the fit parameters or fit_data must be specified.')\nif not (fit_data is None or a is None or b is None):\n raise ValueError('Cannot specify fit parameters when fit_data is specified.')\nself.a = a\nself.b = b\nself.lower = lowe... | <|body_start_0|>
if fit_data is None and (a is None or b is None):
raise ValueError('Either all the fit parameters or fit_data must be specified.')
if not (fit_data is None or a is None or b is None):
raise ValueError('Cannot specify fit parameters when fit_data is specified.')
... | Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported. | AxisRatioRayleigh | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, l... | stack_v2_sparse_classes_36k_train_000445 | 19,262 | permissive | [
{
"docstring": "Parameters ---------- a : float linear slope of the scale vs. velocity dispersion relation, in (km/s)^-1, i.e. how much the velocity dispersion contributes to average flattening b : float intercept of the scale vs. velocity dispersion relation, i.e. the mean flattening independent of velocity di... | 3 | stack_v2_sparse_classes_30k_train_018247 | Implement the Python class `AxisRatioRayleigh` described below.
Class description:
Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported.
Meth... | Implement the Python class `AxisRatioRayleigh` described below.
Class description:
Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported.
Meth... | 2a9a1b3eafbafef925bedab4b3137a3505a9b750 | <|skeleton|>
class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AxisRatioRayleigh:
"""Represents various scaling relations that the axis ratio can follow with quantities like velocity dispersion, when its PDF is assumed to be a Rayleigh distribution Only the relation with velocity dispersion is currently supported."""
def __init__(self, a=None, b=None, lower=0.2, fit... | the_stack_v2_python_sparse | baobab/bnn_priors/parameter_models.py | jiwoncpark/baobab | train | 9 |
755aa4b96a6eadc95eab446b90f751b4fbaa492b | [
"if root is None:\n return None\nres = [[root.val]]\nnodesCurrLevel = [root]\nwhile nodesCurrLevel != []:\n nodesNextLevel = []\n valueCurrLevel = []\n for node in nodesCurrLevel:\n if node.left is not None:\n nodesNextLevel.append(node.left)\n valueCurrLevel.append(node.lef... | <|body_start_0|>
if root is None:
return None
res = [[root.val]]
nodesCurrLevel = [root]
while nodesCurrLevel != []:
nodesNextLevel = []
valueCurrLevel = []
for node in nodesCurrLevel:
if node.left is not None:
... | 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_000446 | 3,142 | 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:... | ee59b82125f100970c842d5e1245287c484d6649 | <|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"""
if root is None:
return None
res = [[root.val]]
nodesCurrLevel = [root]
while nodesCurrLevel != []:
nodesNextLevel = []
valueC... | the_stack_v2_python_sparse | _CodeTopics/LeetCode_other_problems/面试题/剑指Offer(第2版)/37-h-dup/37_copypaste.py | BIAOXYZ/variousCodes | train | 0 | |
1d901f7bd598d7dc5b301447c7393c9fa26a2667 | [
"def bfs(i, j, grid):\n q = deque()\n visited = set()\n q.append((i, j))\n directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n while q:\n curr_i, curr_j = q.popleft()\n visited.add((curr_i, curr_j))\n for dx, dy in directions:\n if 0 <= curr_i + dx < m and 0 <= curr_j + ... | <|body_start_0|>
def bfs(i, j, grid):
q = deque()
visited = set()
q.append((i, j))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while q:
curr_i, curr_j = q.popleft()
visited.add((curr_i, curr_j))
for d... | Solution | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""Time limitation exceeded"""
<|body_0|>
def numIslands(self, grid: List[List[str]]) -> int:
"""Pass. The island nodes should be marked as '0' before enqueuing, and otherwise it might result in the same n... | stack_v2_sparse_classes_36k_train_000447 | 2,842 | permissive | [
{
"docstring": "Time limitation exceeded",
"name": "numIslands",
"signature": "def numIslands(self, grid: List[List[str]]) -> int"
},
{
"docstring": "Pass. The island nodes should be marked as '0' before enqueuing, and otherwise it might result in the same node enqueues repeatedly.",
"name":... | 2 | stack_v2_sparse_classes_30k_val_000988 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid: List[List[str]]) -> int: Time limitation exceeded
- def numIslands(self, grid: List[List[str]]) -> int: Pass. The island nodes should be marked as '0' ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numIslands(self, grid: List[List[str]]) -> int: Time limitation exceeded
- def numIslands(self, grid: List[List[str]]) -> int: Pass. The island nodes should be marked as '0' ... | 226cecde136531341ce23cdf88529345be1912fc | <|skeleton|>
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""Time limitation exceeded"""
<|body_0|>
def numIslands(self, grid: List[List[str]]) -> int:
"""Pass. The island nodes should be marked as '0' before enqueuing, and otherwise it might result in the same n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""Time limitation exceeded"""
def bfs(i, j, grid):
q = deque()
visited = set()
q.append((i, j))
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
while q:
cu... | the_stack_v2_python_sparse | Leetcode/Intermediate/Tree and graph/200_Number_of_Islands.py | ZR-Huang/AlgorithmsPractices | train | 1 | |
6bb16b612543b0821297c8ed8df68020445d9dd4 | [
"super().__init__(screen)\nself.faction = faction\nif self.faction == Faction.Allied:\n self.base_speed = Settings.player_bullet_base_speed\nelse:\n self.base_speed = Settings.enemy_bullet_base_speed\nself.base_damage = Settings.bullet_base_damage\nself.set_position(starting_position)\nself.angle = starting_a... | <|body_start_0|>
super().__init__(screen)
self.faction = faction
if self.faction == Faction.Allied:
self.base_speed = Settings.player_bullet_base_speed
else:
self.base_speed = Settings.enemy_bullet_base_speed
self.base_damage = Settings.bullet_base_damage
... | A class to manage projectiles fired by anyone. | AbstractProjectile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AbstractProjectile:
"""A class to manage projectiles fired by anyone."""
def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction):
"""Create a projectile at a given position moving through a given angle"""
<|body_0|>
def... | stack_v2_sparse_classes_36k_train_000448 | 1,184 | no_license | [
{
"docstring": "Create a projectile at a given position moving through a given angle",
"name": "__init__",
"signature": "def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction)"
},
{
"docstring": "Move the bullet through the screen.",
"name... | 2 | stack_v2_sparse_classes_30k_train_002724 | Implement the Python class `AbstractProjectile` described below.
Class description:
A class to manage projectiles fired by anyone.
Method signatures and docstrings:
- def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction): Create a projectile at a given position mo... | Implement the Python class `AbstractProjectile` described below.
Class description:
A class to manage projectiles fired by anyone.
Method signatures and docstrings:
- def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction): Create a projectile at a given position mo... | e06bbf5210f653554e22d558558e4bac8f739e4a | <|skeleton|>
class AbstractProjectile:
"""A class to manage projectiles fired by anyone."""
def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction):
"""Create a projectile at a given position moving through a given angle"""
<|body_0|>
def... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AbstractProjectile:
"""A class to manage projectiles fired by anyone."""
def __init__(self, screen, starting_position, starting_angle, damage_multiplier, speed_multiplier, faction):
"""Create a projectile at a given position moving through a given angle"""
super().__init__(screen)
... | the_stack_v2_python_sparse | game_sprites/projectiles/abstract_projectile.py | Mocardo/jogo-ces22 | train | 0 |
50f58364e49b6d0a0627849007e33ec0d04cd4d0 | [
"self.char = char\nself.time = 0\nself.max_ready = 1\nself.isrun = True\nself.log = []\nfor char in self.char:\n char.log = self.log\n for a in char.attrib:\n char.attrib[a].log = self.log\n if 'life' in char.attrib:\n char.life = char.max_life = char.attrib['life'].level\n if 'speed' in c... | <|body_start_0|>
self.char = char
self.time = 0
self.max_ready = 1
self.isrun = True
self.log = []
for char in self.char:
char.log = self.log
for a in char.attrib:
char.attrib[a].log = self.log
if 'life' in char.attrib:
... | Class for battle | Battle | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
<|body_0|>
def run(self):
"""Runs a battle"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_000449 | 1,267 | no_license | [
{
"docstring": "Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])",
"name": "__init__",
"signature": "def __init__(self, char)"
},
{
"docstring": "Runs a battle",
"name": "run",
"signature": "def run(sel... | 2 | stack_v2_sparse_classes_30k_train_018276 | Implement the Python class `Battle` described below.
Class description:
Class for battle
Method signatures and docstrings:
- def __init__(self, char): Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])
- def run(self): Runs a battle | Implement the Python class `Battle` described below.
Class description:
Class for battle
Method signatures and docstrings:
- def __init__(self, char): Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])
- def run(self): Runs a battle
... | 7ba98e5a0c5c3b42b3c3707844daed9b0f4f2856 | <|skeleton|>
class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
<|body_0|>
def run(self):
"""Runs a battle"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Battle:
"""Class for battle"""
def __init__(self, char):
"""Constructor char - list of characters which participate in a battle Example: b = Battle([character, rpgdb.create_monster('mushroom')])"""
self.char = char
self.time = 0
self.max_ready = 1
self.isrun = True... | the_stack_v2_python_sparse | extsea/battle.py | szatkus/durenV | train | 0 |
3ce597e3152c1182e3141e2370e04f1e61f2f2ad | [
"super(SelfAttention, self).__init__(options, is_training)\nif not isinstance(options, graph_network_pb2.SelfAttention):\n raise ValueError('Options has to be an SelfAttention proto.')\nself.add_bi_directional_edges = options.add_bi_directional_edges\nself.add_self_loop_edges = options.add_self_loop_edges",
"n... | <|body_start_0|>
super(SelfAttention, self).__init__(options, is_training)
if not isinstance(options, graph_network_pb2.SelfAttention):
raise ValueError('Options has to be an SelfAttention proto.')
self.add_bi_directional_edges = options.add_bi_directional_edges
self.add_self... | Self attention model using a RNN cell. | SelfAttention | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self attention model using a RNN cell."""
def __init__(self, options, is_training=False):
"""Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training graph."""
<|body_0|>
def _build_graph(self, g... | stack_v2_sparse_classes_36k_train_000450 | 18,418 | permissive | [
{
"docstring": "Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training graph.",
"name": "__init__",
"signature": "def __init__(self, options, is_training=False)"
},
{
"docstring": "Builds graph network. Args: graphs_tuple: A GraphTuple ... | 2 | stack_v2_sparse_classes_30k_train_011373 | Implement the Python class `SelfAttention` described below.
Class description:
Self attention model using a RNN cell.
Method signatures and docstrings:
- def __init__(self, options, is_training=False): Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training g... | Implement the Python class `SelfAttention` described below.
Class description:
Self attention model using a RNN cell.
Method signatures and docstrings:
- def __init__(self, options, is_training=False): Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training g... | 4d20dadffe7584ac2c7f26419960512380b8d06e | <|skeleton|>
class SelfAttention:
"""Self attention model using a RNN cell."""
def __init__(self, options, is_training=False):
"""Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training graph."""
<|body_0|>
def _build_graph(self, g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self attention model using a RNN cell."""
def __init__(self, options, is_training=False):
"""Initializes the graph network. Args: options: proto to store the configs. is_training: if True, build the training graph."""
super(SelfAttention, self).__init__(options, is_train... | the_stack_v2_python_sparse | modeling/modules/graph_networks.py | yekeren/WSSGG | train | 40 |
d2fa7a5f79fefea431b71652c888172e4bd74ad4 | [
"if A != []:\n for j in a[i]:\n if j in A:\n tree[i]['children'].append(j)\n tree[j]['father'] = i\n A.remove(j)\n tree, A = self.get_tree(tree, A, a, j)\nreturn (tree, A)",
"G = nx.Graph()\ndistance = lambda x, y: math.sqrt(np.sum((x - y) ** 2))\nfor i in ran... | <|body_start_0|>
if A != []:
for j in a[i]:
if j in A:
tree[i]['children'].append(j)
tree[j]['father'] = i
A.remove(j)
tree, A = self.get_tree(tree, A, a, j)
return (tree, A)
<|end_body_0|>
<|bod... | Apply Kruskal to a tree structure | Kruskal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
<|body_0|>
def __call__(self, tree):
... | stack_v2_sparse_classes_36k_train_000451 | 1,908 | permissive | [
{
"docstring": "Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A",
"name": "get_tree",
"signature": "def get_tree(self, tree, A, a, i)"
},
{
"docstring": "Use Kruskal :param tree: true structure :retur... | 2 | stack_v2_sparse_classes_30k_train_013371 | Implement the Python class `Kruskal` described below.
Class description:
Apply Kruskal to a tree structure
Method signatures and docstrings:
- def get_tree(self, tree, A, a, i): Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree... | Implement the Python class `Kruskal` described below.
Class description:
Apply Kruskal to a tree structure
Method signatures and docstrings:
- def get_tree(self, tree, A, a, i): Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree... | 91dbb0eebba64f1fa2c18562e2c9f35f532ef7c0 | <|skeleton|>
class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
<|body_0|>
def __call__(self, tree):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kruskal:
"""Apply Kruskal to a tree structure"""
def get_tree(self, tree, A, a, i):
"""Use to convert one tree to another :param tree: original tree :param A: list of nodes :param a: new tree :param i: node number :return: tree, A"""
if A != []:
for j in a[i]:
... | the_stack_v2_python_sparse | src/python_code/compostela/tree_optimization/kruskal.py | ipmach/Thesis2021 | train | 0 |
34d37b27d3f5c365784d98a7cffc17f1f3b4ea9c | [
"if not matrix or not matrix[0]:\n self._summation_matrix = []\n return\nself._summation_matrix = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)]\nfor i in range(len(matrix)):\n for j in range(len(matrix[0])):\n self._summation_matrix[i + 1][j + 1] = matrix[i][j] + self._summation_matri... | <|body_start_0|>
if not matrix or not matrix[0]:
self._summation_matrix = []
return
self._summation_matrix = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)]
for i in range(len(matrix)):
for j in range(len(matrix[0])):
self._summati... | NumMatrix | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_000452 | 1,130 | no_license | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | null | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | 08500c39e14f3bf140db82a3dd2df4ca18705845 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix or not matrix[0]:
self._summation_matrix = []
return
self._summation_matrix = [[0] * (len(matrix[0]) + 1) for _ in range(len(matrix) + 1)]
for i in range(len(matrix)... | the_stack_v2_python_sparse | 2019_round/304_range_sum_query_2D_immutable/solution.py | kfrancischen/leetcode | train | 2 | |
b5256b0fe198c2c8832405b53ac4a10fd5b8be39 | [
"from core.tracing import get_tracer\nself.__tracer = get_tracer('CSVDevice')\nself.__tracer.info('Initializing CSVDevice')\nself.name = name\nself.core = core_services\nself.tracer = get_tracer(name)\nself.tdict = {}\nself.prop_names = []\nself.dm = self.core.get_service('device_driver_manager')\nself.channel_mana... | <|body_start_0|>
from core.tracing import get_tracer
self.__tracer = get_tracer('CSVDevice')
self.__tracer.info('Initializing CSVDevice')
self.name = name
self.core = core_services
self.tracer = get_tracer(name)
self.tdict = {}
self.prop_names = []
... | - name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimited data is then returned to the source's parent driver as new properties na... | CSVDevice | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVDevice:
"""- name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimited data is then returned to the source... | stack_v2_sparse_classes_36k_train_000453 | 9,108 | no_license | [
{
"docstring": "Standard device init function.",
"name": "__init__",
"signature": "def __init__(self, name, core_services)"
},
{
"docstring": "This procedure processes that match the pattern, then subscribes to those channels to continue processing upon updates.",
"name": "start",
"signa... | 5 | stack_v2_sparse_classes_30k_train_012075 | Implement the Python class `CSVDevice` described below.
Class description:
- name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimi... | Implement the Python class `CSVDevice` described below.
Class description:
- name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimi... | f36ba29ef883d70f94b8609ff734b5dcde786c66 | <|skeleton|>
class CSVDevice:
"""- name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimited data is then returned to the source... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSVDevice:
"""- name: CSVDevice driver: devices.csv_device:CSVDevice settings: channel_pattern: "*.csv_input" delimiter: ',' column_names: - "timestamp" - "status" - "error_msg" CSVDevice is a virtual device that parsed a delimited stream of data. The delimited data is then returned to the source's parent dri... | the_stack_v2_python_sparse | src/devices/csv_device.py | bernhara/DigiGateway4Raph | train | 0 |
2cdf75c617166d567c6f8751ac5e11deac24c2ae | [
"def check(mid):\n sums = 0\n cnt = 1\n for num in nums:\n if sums + num > mid:\n sums = num\n cnt += 1\n else:\n sums += num\n return cnt <= m\nleft = 0\nright = 0\nfor num in nums:\n left = max(left, num)\n right += num\nwhile left < right:\n mid... | <|body_start_0|>
def check(mid):
sums = 0
cnt = 1
for num in nums:
if sums + num > mid:
sums = num
cnt += 1
else:
sums += num
return cnt <= m
left = 0
right... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
"""二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:"""
<|body_0|>
def splitArray1(self, nums: List[int], m: int) -> int:
"""动态规划 dp[i][j] 表示数组的前i个数分割为j段所能得到的最大连续子数组和的最小值 dp[i][j] = min(dp[i][j], m... | stack_v2_sparse_classes_36k_train_000454 | 2,808 | no_license | [
{
"docstring": "二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:",
"name": "splitArray",
"signature": "def splitArray(self, nums: List[int], m: int) -> int"
},
{
"docstring": "动态规划 dp[i][j] 表示数组的前i个数分割为j段所能得到的最大连续子数组和的最小值 dp[i][j] = min(dp[i][j], max(dp[k][j - 1], sub(k + 1, i))) :param n... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums: List[int], m: int) -> int: 二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:
- def splitArray1(self, nums: List[int], m: int) -> int: 动态规划 dp[i][... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def splitArray(self, nums: List[int], m: int) -> int: 二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:
- def splitArray1(self, nums: List[int], m: int) -> int: 动态规划 dp[i][... | 9acba92695c06406f12f997a720bfe1deb9464a8 | <|skeleton|>
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
"""二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:"""
<|body_0|>
def splitArray1(self, nums: List[int], m: int) -> int:
"""动态规划 dp[i][j] 表示数组的前i个数分割为j段所能得到的最大连续子数组和的最小值 dp[i][j] = min(dp[i][j], m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
"""二分查找, 左边界为数组最大值,右边界为数组和 :param nums: :param m: :return:"""
def check(mid):
sums = 0
cnt = 1
for num in nums:
if sums + num > mid:
sums = num
... | the_stack_v2_python_sparse | datastructure/dp_exercise/SplitArray.py | yinhuax/leet_code | train | 0 | |
87f0725d49d3d06910e9e1060da4b6e4913f681b | [
"row = source[0]\ncolumn = source[1]\nown_destination = (row, column)\nown_path = (source, own_destination)\nleft_destination = (row, column - 1)\nleft_path = (source, left_destination)\nup_destination = (row - 1, column)\nup_path = (source, up_destination)\nright_destination = (row, column + 1)\nright_path = (sour... | <|body_start_0|>
row = source[0]
column = source[1]
own_destination = (row, column)
own_path = (source, own_destination)
left_destination = (row, column - 1)
left_path = (source, left_destination)
up_destination = (row - 1, column)
up_path = (source, up_de... | BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout | BlueSoldier | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BlueSoldier:
"""BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout"""
def all_destinations_from_source(self, source):
"""All blue soldier destinations from source with paths :param source: [Tuple[int]] Board source coordinate :... | stack_v2_sparse_classes_36k_train_000455 | 6,795 | no_license | [
{
"docstring": "All blue soldier destinations from source with paths :param source: [Tuple[int]] Board source coordinate :return: [Dict[Tuple[int], Tuple[Tuple[int]]]] Destination goes to source to destination path",
"name": "all_destinations_from_source",
"signature": "def all_destinations_from_source(... | 2 | stack_v2_sparse_classes_30k_train_006302 | Implement the Python class `BlueSoldier` described below.
Class description:
BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout
Method signatures and docstrings:
- def all_destinations_from_source(self, source): All blue soldier destinations from source with pa... | Implement the Python class `BlueSoldier` described below.
Class description:
BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout
Method signatures and docstrings:
- def all_destinations_from_source(self, source): All blue soldier destinations from source with pa... | 59ea9a74928ca4c6d9978c3da1ebafeee6330871 | <|skeleton|>
class BlueSoldier:
"""BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout"""
def all_destinations_from_source(self, source):
"""All blue soldier destinations from source with paths :param source: [Tuple[int]] Board source coordinate :... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BlueSoldier:
"""BlueSoldier (Piece) handles finding soldier move destinations from source filtering moves with board layout"""
def all_destinations_from_source(self, source):
"""All blue soldier destinations from source with paths :param source: [Tuple[int]] Board source coordinate :return: [Dict... | the_stack_v2_python_sparse | Soldier.py | davisethan/janggi | train | 0 |
b9eed33de91db854fc9bd164b167cff6259a019b | [
"try:\n ho = HomePage(self.driver)\n ho.small_knowlege()\n so = SmallPage(self.driver)\n so.random_play()\nexcept:\n po = Operation(self.driver)\n po.screenShot()\n raise LocateError()",
"try:\n ho = HomePage(self.driver)\n ho.small_knowlege()\n so = SmallPage(self.driver)\n so.Su... | <|body_start_0|>
try:
ho = HomePage(self.driver)
ho.small_knowlege()
so = SmallPage(self.driver)
so.random_play()
except:
po = Operation(self.driver)
po.screenShot()
raise LocateError()
<|end_body_0|>
<|body_start_1|>
... | SmallTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmallTest:
def test_Arangdom_play(self):
"""首页--小知识--随机播放"""
<|body_0|>
def test_BSubscribe_ok(self):
"""首页--小知识--订阅成功"""
<|body_1|>
def test_CSubscribe_noCancel(self):
"""首页--小知识--暂不取消订阅"""
<|body_2|>
def test_DSubscribe_cancel(self... | stack_v2_sparse_classes_36k_train_000456 | 2,297 | no_license | [
{
"docstring": "首页--小知识--随机播放",
"name": "test_Arangdom_play",
"signature": "def test_Arangdom_play(self)"
},
{
"docstring": "首页--小知识--订阅成功",
"name": "test_BSubscribe_ok",
"signature": "def test_BSubscribe_ok(self)"
},
{
"docstring": "首页--小知识--暂不取消订阅",
"name": "test_CSubscribe... | 5 | stack_v2_sparse_classes_30k_train_003108 | Implement the Python class `SmallTest` described below.
Class description:
Implement the SmallTest class.
Method signatures and docstrings:
- def test_Arangdom_play(self): 首页--小知识--随机播放
- def test_BSubscribe_ok(self): 首页--小知识--订阅成功
- def test_CSubscribe_noCancel(self): 首页--小知识--暂不取消订阅
- def test_DSubscribe_cancel(sel... | Implement the Python class `SmallTest` described below.
Class description:
Implement the SmallTest class.
Method signatures and docstrings:
- def test_Arangdom_play(self): 首页--小知识--随机播放
- def test_BSubscribe_ok(self): 首页--小知识--订阅成功
- def test_CSubscribe_noCancel(self): 首页--小知识--暂不取消订阅
- def test_DSubscribe_cancel(sel... | 1a7d0cafc286963c304219cbf7ac3af0eef2cba4 | <|skeleton|>
class SmallTest:
def test_Arangdom_play(self):
"""首页--小知识--随机播放"""
<|body_0|>
def test_BSubscribe_ok(self):
"""首页--小知识--订阅成功"""
<|body_1|>
def test_CSubscribe_noCancel(self):
"""首页--小知识--暂不取消订阅"""
<|body_2|>
def test_DSubscribe_cancel(self... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmallTest:
def test_Arangdom_play(self):
"""首页--小知识--随机播放"""
try:
ho = HomePage(self.driver)
ho.small_knowlege()
so = SmallPage(self.driver)
so.random_play()
except:
po = Operation(self.driver)
po.screenShot()
... | the_stack_v2_python_sparse | Testcase/SmallTest.py | Hanlen520/AndroidUIautoTest-1 | train | 0 | |
29206b5648a3f2228ce099f871012d145cbc3c66 | [
"self.model = model\nself.dataset = dataset\nself.hyperparameters = hyperparameters\nif prefilter_type == TOPOLOGY_PREFILTER:\n self.prefilter = TopologyPreFilter(model=model, dataset=dataset)\nelif prefilter_type == TYPE_PREFILTER:\n self.prefilter = TypeBasedPreFilter(model=model, dataset=dataset)\nelif pre... | <|body_start_0|>
self.model = model
self.dataset = dataset
self.hyperparameters = hyperparameters
if prefilter_type == TOPOLOGY_PREFILTER:
self.prefilter = TopologyPreFilter(model=model, dataset=dataset)
elif prefilter_type == TYPE_PREFILTER:
self.prefilte... | The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules. | DataPoisoning | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataPoisoning:
"""The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules."""
def __init__(self, model: Model, da... | stack_v2_sparse_classes_36k_train_000457 | 7,836 | no_license | [
{
"docstring": "DataPoisoning object constructor. :param model: the model to explain :param dataset: the dataset used to train the model :param hyperparameters: the hyperparameters of the model and of its optimization process :param prefilter_type: the type of prefilter to employ",
"name": "__init__",
"... | 3 | stack_v2_sparse_classes_30k_train_001844 | Implement the Python class `DataPoisoning` described below.
Class description:
The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules.
Met... | Implement the Python class `DataPoisoning` described below.
Class description:
The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules.
Met... | 9b408d1cef1a10c4bb8a32824eb3f8c90b9a8fb0 | <|skeleton|>
class DataPoisoning:
"""The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules."""
def __init__(self, model: Model, da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataPoisoning:
"""The DataPoisoning object is the overall manager of the Data_poisoning explanation process. It implements the whole explanation pipeline, requesting the suitable operations to the ExplanationEngines and to the entity_similarity modules."""
def __init__(self, model: Model, dataset: Datase... | the_stack_v2_python_sparse | data_poisoning.py | AndRossi/Kelpie | train | 45 |
31cda38ac77e95e8c35e210b14eca1c3d2bb4ac7 | [
"product = [0] * (len(num1) + len(num2))\npos = len(product) - 1\nfor n1 in reversed(num1):\n temp_pos = pos\n for n2 in reversed(num2):\n product[temp_pos] += int(n1) * int(n2)\n product[temp_pos - 1] += product[temp_pos] / 10\n product[temp_pos] %= 10\n temp_pos -= 1\n pos -= ... | <|body_start_0|>
product = [0] * (len(num1) + len(num2))
pos = len(product) - 1
for n1 in reversed(num1):
temp_pos = pos
for n2 in reversed(num2):
product[temp_pos] += int(n1) * int(n2)
product[temp_pos - 1] += product[temp_pos] / 10
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def multiply(num1, num2):
""":param num2: :return: beats 29.37%"""
<|body_0|>
def multiply0(self, num1, num2):
""":type num1: str :type num2: str :rtype: str beats 52.57%"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
product = [0] * (len... | stack_v2_sparse_classes_36k_train_000458 | 1,208 | no_license | [
{
"docstring": ":param num2: :return: beats 29.37%",
"name": "multiply",
"signature": "def multiply(num1, num2)"
},
{
"docstring": ":type num1: str :type num2: str :rtype: str beats 52.57%",
"name": "multiply0",
"signature": "def multiply0(self, num1, num2)"
}
] | 2 | stack_v2_sparse_classes_30k_train_018268 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(num1, num2): :param num2: :return: beats 29.37%
- def multiply0(self, num1, num2): :type num1: str :type num2: str :rtype: str beats 52.57% | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def multiply(num1, num2): :param num2: :return: beats 29.37%
- def multiply0(self, num1, num2): :type num1: str :type num2: str :rtype: str beats 52.57%
<|skeleton|>
class Solut... | 7e0e917c15d3e35f49da3a00ef395bd5ff180d79 | <|skeleton|>
class Solution:
def multiply(num1, num2):
""":param num2: :return: beats 29.37%"""
<|body_0|>
def multiply0(self, num1, num2):
""":type num1: str :type num2: str :rtype: str beats 52.57%"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def multiply(num1, num2):
""":param num2: :return: beats 29.37%"""
product = [0] * (len(num1) + len(num2))
pos = len(product) - 1
for n1 in reversed(num1):
temp_pos = pos
for n2 in reversed(num2):
product[temp_pos] += int(n1) * ... | the_stack_v2_python_sparse | LeetCode/043_multiply_strings.py | yao23/Machine_Learning_Playground | train | 12 | |
81168ae6378687ef9cc35762a243716de2575104 | [
"self.logger = ServerLogger(__name__, debug=debug)\nif test:\n self.REGEX_FILE = 'securetea/lib/log_monitor/server_log/rules/regex/sqli.txt'\n self.PAYLOAD_FILE = 'securetea/lib/log_monitor/server_log/rules/payloads/sqli.txt'\nelse:\n self.PAYLOAD_FILE = '/etc/securetea/log_monitor/server_log/payloads/sqli... | <|body_start_0|>
self.logger = ServerLogger(__name__, debug=debug)
if test:
self.REGEX_FILE = 'securetea/lib/log_monitor/server_log/rules/regex/sqli.txt'
self.PAYLOAD_FILE = 'securetea/lib/log_monitor/server_log/rules/payloads/sqli.txt'
else:
self.PAYLOAD_FILE... | SQLi Class. | SQLi | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLi:
"""SQLi Class."""
def __init__(self, debug=False, test=False):
"""Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_sqli(self, data):
"""Detect possible SQL Injection (sqli) attacks. Use regex ru... | stack_v2_sparse_classes_36k_train_000459 | 4,470 | permissive | [
{
"docstring": "Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None",
"name": "__init__",
"signature": "def __init__(self, debug=False, test=False)"
},
{
"docstring": "Detect possible SQL Injection (sqli) attacks. Use regex rules and string matching to detect S... | 4 | null | Implement the Python class `SQLi` described below.
Class description:
SQLi Class.
Method signatures and docstrings:
- def __init__(self, debug=False, test=False): Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_sqli(self, data): Detect possible SQL Injection (sqli) ... | Implement the Python class `SQLi` described below.
Class description:
SQLi Class.
Method signatures and docstrings:
- def __init__(self, debug=False, test=False): Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None
- def detect_sqli(self, data): Detect possible SQL Injection (sqli) ... | 43dec187e5848b9ced8a6b4957b6e9028d4d43cd | <|skeleton|>
class SQLi:
"""SQLi Class."""
def __init__(self, debug=False, test=False):
"""Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
<|body_0|>
def detect_sqli(self, data):
"""Detect possible SQL Injection (sqli) attacks. Use regex ru... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLi:
"""SQLi Class."""
def __init__(self, debug=False, test=False):
"""Initialize SQLi. Args: debug (bool): Log on terminal or not Raises: None Returns: None"""
self.logger = ServerLogger(__name__, debug=debug)
if test:
self.REGEX_FILE = 'securetea/lib/log_monitor/ser... | the_stack_v2_python_sparse | securetea/lib/log_monitor/server_log/detect/attacks/sqli.py | rejahrehim/SecureTea-Project | train | 1 |
494a613e76dbacf68cf0840eb6dba43f5c1e567d | [
"try:\n params = request._serialize()\n headers = request.headers\n body = self.call('ImageToImage', params, headers=headers)\n response = json.loads(body)\n model = models.ImageToImageResponse()\n model._deserialize(response['Response'])\n return model\nexcept Exception as e:\n if isinstanc... | <|body_start_0|>
try:
params = request._serialize()
headers = request.headers
body = self.call('ImageToImage', params, headers=headers)
response = json.loads(body)
model = models.ImageToImageResponse()
model._deserialize(response['Response'... | AiartClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :para... | stack_v2_sparse_classes_36k_train_000460 | 3,676 | permissive | [
{
"docstring": "智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :param request: Request instance for ImageToImage. :type reque... | 2 | stack_v2_sparse_classes_30k_train_006289 | Implement the Python class `AiartClient` described below.
Class description:
Implement the AiartClient class.
Method signatures and docstrings:
- def ImageToImage(self, request): 智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://... | Implement the Python class `AiartClient` described below.
Class description:
Implement the AiartClient class.
Method signatures and docstrings:
- def ImageToImage(self, request): 智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://... | 6baf00a5a56ba58b6a1123423e0a1422d17a0201 | <|skeleton|>
class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :para... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AiartClient:
def ImageToImage(self, request):
"""智能图生图接口将根据输入的图片及辅助描述文本,智能生成与之相关的结果图。 输入:单边分辨率小于2000、转成 Base64 字符串后小于 5MB 的图片,建议同时输入描述文本。 输出:对应风格及分辨率的 AI 生成图。 可支持的风格详见 [智能图生图风格列表](https://cloud.tencent.com/document/product/1668/86250),请将列表中的“风格编号”传入 Styles 数组,建议选择一种风格。 请求频率限制为1次/秒。 :param request: Req... | the_stack_v2_python_sparse | tencentcloud/aiart/v20221229/aiart_client.py | TencentCloud/tencentcloud-sdk-python | train | 594 | |
52918d175d5bb55d37edbc3a91a9ec1a61768dc1 | [
"if not isinstance(menu, SpyderMenu):\n raise SpyderAPIError('Menu must be an instance of SpyderMenu!')\nmenu.add_action(action_or_menu, section=section, before=before)",
"from spyder.api.widgets.menus import SpyderMenu\nmenu = SpyderMenu(parent=self, title=text)\nif icon is not None:\n menu.menuAction().se... | <|body_start_0|>
if not isinstance(menu, SpyderMenu):
raise SpyderAPIError('Menu must be an instance of SpyderMenu!')
menu.add_action(action_or_menu, section=section, before=before)
<|end_body_0|>
<|body_start_1|>
from spyder.api.widgets.menus import SpyderMenu
menu = Spyder... | Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way. | SpyderMenuMixin | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"LGPL-3.0-only",
"LicenseRef-scancode-free-unknown",
"LGPL-3.0-or-later",
"LicenseRef-scancode-proprietary-license",
"LGPL-2.1-or-later",
"CC-BY-2.5",
"CC-BY-4.0",
"MIT",
"LGPL-2.1-only",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference",
"OF... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the m... | stack_v2_sparse_classes_36k_train_000461 | 20,997 | permissive | [
{
"docstring": "Add a SpyderAction or a QWidget to the menu.",
"name": "add_item_to_menu",
"signature": "def add_item_to_menu(self, action_or_menu, menu, section=None, before=None)"
},
{
"docstring": "Create a menu. Parameters ---------- name: str Unique str identifier. text: str or None Localiz... | 4 | stack_v2_sparse_classes_30k_train_005298 | Implement the Python class `SpyderMenuMixin` described below.
Class description:
Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way.
Method signatures and docstrings:
- def add_item_to_menu(self, action_or_menu, menu, section=Non... | Implement the Python class `SpyderMenuMixin` described below.
Class description:
Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way.
Method signatures and docstrings:
- def add_item_to_menu(self, action_or_menu, menu, section=Non... | 0b4929cef420ba6c625566e52200e959f3566f33 | <|skeleton|>
class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SpyderMenuMixin:
"""Provide methods to create, add and get menus. This mixin uses a custom menu object that allows for the creation of sections in a simple way."""
def add_item_to_menu(self, action_or_menu, menu, section=None, before=None):
"""Add a SpyderAction or a QWidget to the menu."""
... | the_stack_v2_python_sparse | spyder/api/widgets/mixins.py | juanis2112/spyder | train | 1 |
e318c2c5c922960ab49634f1943513ce804a2302 | [
"delay = DelayFilter()\noriginal = delay(0)\nnorm = NormFilter()\nshift = ShiftSWFilter(window_size=2, strict_windows=False, cs=False)\nmean = MeanSWFilter(window_size=25, cs=False)\nstd = StdSWFilter(window_size=25, strict_windows=True)\ndtr = DecisionTreeRegressorSWFilter(window_size=100, strict_windows=True, ove... | <|body_start_0|>
delay = DelayFilter()
original = delay(0)
norm = NormFilter()
shift = ShiftSWFilter(window_size=2, strict_windows=False, cs=False)
mean = MeanSWFilter(window_size=25, cs=False)
std = StdSWFilter(window_size=25, strict_windows=True)
dtr = DecisionT... | ... | DtrEventSelector | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DtrEventSelector:
"""..."""
def seq_filters():
""":return:"""
<|body_0|>
def filter_events(self, event_seq, **kwargs):
"""Should be implemented :param event_seq:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
delay = DelayFilter()
origi... | stack_v2_sparse_classes_36k_train_000462 | 4,290 | permissive | [
{
"docstring": ":return:",
"name": "seq_filters",
"signature": "def seq_filters()"
},
{
"docstring": "Should be implemented :param event_seq:",
"name": "filter_events",
"signature": "def filter_events(self, event_seq, **kwargs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020407 | Implement the Python class `DtrEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def seq_filters(): :return:
- def filter_events(self, event_seq, **kwargs): Should be implemented :param event_seq: | Implement the Python class `DtrEventSelector` described below.
Class description:
...
Method signatures and docstrings:
- def seq_filters(): :return:
- def filter_events(self, event_seq, **kwargs): Should be implemented :param event_seq:
<|skeleton|>
class DtrEventSelector:
"""..."""
def seq_filters():
... | 617ff45c9c3c96bbd9a975aef15f1b2697282b9c | <|skeleton|>
class DtrEventSelector:
"""..."""
def seq_filters():
""":return:"""
<|body_0|>
def filter_events(self, event_seq, **kwargs):
"""Should be implemented :param event_seq:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DtrEventSelector:
"""..."""
def seq_filters():
""":return:"""
delay = DelayFilter()
original = delay(0)
norm = NormFilter()
shift = ShiftSWFilter(window_size=2, strict_windows=False, cs=False)
mean = MeanSWFilter(window_size=25, cs=False)
std = StdS... | the_stack_v2_python_sparse | shot_detector/selectors/event/dtr_event_selector.py | w495/python-video-shot-detector | train | 20 |
e63dfc8b59e9a34d1eff221580db010201a19402 | [
"if not nums:\n return -1\nL = 0\nH = len(nums) - 1\nwhile L <= H:\n M = (L + H) // 2\n low, mid, high = (nums[L], nums[M], nums[H])\n if mid <= high:\n potential_ans = self.binary_search(nums, M, H, target)\n if potential_ans != -1:\n return potential_ans\n else:\n ... | <|body_start_0|>
if not nums:
return -1
L = 0
H = len(nums) - 1
while L <= H:
M = (L + H) // 2
low, mid, high = (nums[L], nums[M], nums[H])
if mid <= high:
potential_ans = self.binary_search(nums, M, H, target)
... | Solution_B | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution_B:
def search(self, nums: List[int], target: int) -> int:
"""Binary search, with help of standard binary search for sorted array"""
<|body_0|>
def binary_search(self, nums: List[int], L: int, H: int, target: int) -> int:
"""helper functin for standard binary... | stack_v2_sparse_classes_36k_train_000463 | 6,251 | permissive | [
{
"docstring": "Binary search, with help of standard binary search for sorted array",
"name": "search",
"signature": "def search(self, nums: List[int], target: int) -> int"
},
{
"docstring": "helper functin for standard binary search in a sorted array at specific range a quick modification to de... | 2 | null | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Binary search, with help of standard binary search for sorted array
- def binary_search(self, nums: List[int], L: int, ... | Implement the Python class `Solution_B` described below.
Class description:
Implement the Solution_B class.
Method signatures and docstrings:
- def search(self, nums: List[int], target: int) -> int: Binary search, with help of standard binary search for sorted array
- def binary_search(self, nums: List[int], L: int, ... | 143422321cbc3715ca08f6c3af8f960a55887ced | <|skeleton|>
class Solution_B:
def search(self, nums: List[int], target: int) -> int:
"""Binary search, with help of standard binary search for sorted array"""
<|body_0|>
def binary_search(self, nums: List[int], L: int, H: int, target: int) -> int:
"""helper functin for standard binary... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution_B:
def search(self, nums: List[int], target: int) -> int:
"""Binary search, with help of standard binary search for sorted array"""
if not nums:
return -1
L = 0
H = len(nums) - 1
while L <= H:
M = (L + H) // 2
low, mid, high ... | the_stack_v2_python_sparse | LeetCode/LC033_search_in_rotated_sorted_array.py | jxie0755/Learning_Python | train | 0 | |
afa5b5f0ba3f13371bd7a8bbaaa101bdb94d0530 | [
"while True:\n r = (rand7() - 1) * 7 + rand7()\n if 40 < r:\n continue\n res = r % 10\n if 0 == res:\n return 10\n return res\nreturn -1",
"r = (rand7() - 1) * 7 + rand7()\nif 1 <= r <= 40:\n res = r % 10\n return 10 if res == 0 else res\nreturn self.rand10()"
] | <|body_start_0|>
while True:
r = (rand7() - 1) * 7 + rand7()
if 40 < r:
continue
res = r % 10
if 0 == res:
return 10
return res
return -1
<|end_body_0|>
<|body_start_1|>
r = (rand7() - 1) * 7 + rand7()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rand10_0(self):
""":rtype: int"""
<|body_0|>
def rand10(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
while True:
r = (rand7() - 1) * 7 + rand7()
if 40 < r:
continue
... | stack_v2_sparse_classes_36k_train_000464 | 876 | no_license | [
{
"docstring": ":rtype: int",
"name": "rand10_0",
"signature": "def rand10_0(self)"
},
{
"docstring": ":rtype: int",
"name": "rand10",
"signature": "def rand10(self)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10_0(self): :rtype: int
- def rand10(self): :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rand10_0(self): :rtype: int
- def rand10(self): :rtype: int
<|skeleton|>
class Solution:
def rand10_0(self):
""":rtype: int"""
<|body_0|>
def rand1... | 5376dd48b1cefb4faba9d2ef6a8a497b6b1d6c67 | <|skeleton|>
class Solution:
def rand10_0(self):
""":rtype: int"""
<|body_0|>
def rand10(self):
""":rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rand10_0(self):
""":rtype: int"""
while True:
r = (rand7() - 1) * 7 + rand7()
if 40 < r:
continue
res = r % 10
if 0 == res:
return 10
return res
return -1
def rand10(self):
... | the_stack_v2_python_sparse | python/problem-math/implement_rand10_using_rand7.py | hyunjun/practice | train | 3 | |
80099bde77aa0a5ad3fce51183e75843a7d7bf11 | [
"if not chars:\n return 0\ni, j, count, last = (1, 1, 1, chars[0])\nfor j in range(1, len(chars)):\n if chars[j] != last:\n if count > 1:\n for digit in str(count):\n chars[i] = digit\n i += 1\n chars[i] = chars[j]\n i += 1\n last = chars[j]... | <|body_start_0|>
if not chars:
return 0
i, j, count, last = (1, 1, 1, chars[0])
for j in range(1, len(chars)):
if chars[j] != last:
if count > 1:
for digit in str(count):
chars[i] = digit
... | 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|>
if not chars:
return 0
i, ... | stack_v2_sparse_classes_36k_train_000465 | 2,800 | 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_016343 | 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... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|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"""
if not chars:
return 0
i, j, count, last = (1, 1, 1, chars[0])
for j in range(1, len(chars)):
if chars[j] != last:
if count > 1:
for digit i... | the_stack_v2_python_sparse | code443StringCompression.py | cybelewang/leetcode-python | train | 0 | |
c820ba42a208446c83f1760cc9bbdaa0c146857f | [
"self.backup_run = backup_run\nself.copy_runs = copy_runs\nself.job_uid = job_uid\nself.next_protection_run_time_usecs = next_protection_run_time_usecs\nself.protection_source = protection_source",
"if dictionary is None:\n return None\nbackup_run = cohesity_management_sdk.models.backup_run_task.BackupRunTask.... | <|body_start_0|>
self.backup_run = backup_run
self.copy_runs = copy_runs
self.job_uid = job_uid
self.next_protection_run_time_usecs = next_protection_run_time_usecs
self.protection_source = protection_source
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
... | Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRunTask): Specifies details about the Backup task for a Jo... | ProtectedSourceSummary | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRunTask)... | stack_v2_sparse_classes_36k_train_000466 | 4,170 | permissive | [
{
"docstring": "Constructor for the ProtectedSourceSummary class",
"name": "__init__",
"signature": "def __init__(self, backup_run=None, copy_runs=None, job_uid=None, next_protection_run_time_usecs=None, protection_source=None)"
},
{
"docstring": "Creates an instance of this model from a diction... | 2 | stack_v2_sparse_classes_30k_train_009858 | Implement the Python class `ProtectedSourceSummary` described below.
Class description:
Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO.... | Implement the Python class `ProtectedSourceSummary` described below.
Class description:
Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO.... | 07c5adee58810979780679065250d82b4b2cdaab | <|skeleton|>
class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRunTask)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProtectedSourceSummary:
"""Implementation of the 'ProtectedSourceSummary' model. ProtectedSourceSummary is the summary of all the Protection Runs for the Protection Jobs using the Specified Protection Policy. This is only populated for a policy of type kRPO. Attributes: backup_run (BackupRunTask): Specifies d... | the_stack_v2_python_sparse | cohesity_management_sdk/models/protected_source_summary.py | hemanshu-cohesity/management-sdk-python | train | 0 |
5cdae14e22c9d41c59f35b62d3d1c03f0e38d6cf | [
"x = pixel % w\ny = pixel // w\nlocation = [x, y]\nlocation.insert(channel_axis, slice(None))\nlocation = tuple(location)\nif np.random.randint(0, 2) == 1:\n value = min_\nelse:\n value = max_\nperturbed[location] = value",
"a = input_or_adv\ndel input_or_adv\ndel label\ndel unpack\nchannel_axis = a.channel... | <|body_start_0|>
x = pixel % w
y = pixel // w
location = [x, y]
location.insert(channel_axis, slice(None))
location = tuple(location)
if np.random.randint(0, 2) == 1:
value = min_
else:
value = max_
perturbed[location] = value
<|end... | Perturbs multiple pixels and sets them to the min or max. | MultiplePixelsAttack | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param ... | stack_v2_sparse_classes_36k_train_000467 | 3,118 | permissive | [
{
"docstring": "Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param min_: the min value to be set :param max_: the max value to be set :param w: the width of the image :param channel_axis: :return:",
"name": "perturb_pixel",
"signature... | 2 | stack_v2_sparse_classes_30k_train_003341 | Implement the Python class `MultiplePixelsAttack` described below.
Class description:
Perturbs multiple pixels and sets them to the min or max.
Method signatures and docstrings:
- def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0): Perturb a :param perturbed: the image to be perturbed :param pix... | Implement the Python class `MultiplePixelsAttack` described below.
Class description:
Perturbs multiple pixels and sets them to the min or max.
Method signatures and docstrings:
- def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0): Perturb a :param perturbed: the image to be perturbed :param pix... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MultiplePixelsAttack:
"""Perturbs multiple pixels and sets them to the min or max."""
def perturb_pixel(self, perturbed, pixel, min_, max_, w, channel_axis=0):
"""Perturb a :param perturbed: the image to be perturbed :param pixel: the pixel number (if the image was flattened) :param min_: the min... | the_stack_v2_python_sparse | cnns/nnlib/attacks/multiple_pixels.py | adam-dziedzic/bandlimited-cnns | train | 17 |
00caa4a1925c26b087b2375c382d02818aa00af0 | [
"obsolete_content = []\nobsolete_translation_suggestion_error_report: List[Dict[str, Union[str, List[Dict[str, str]]]]] = []\ntranslatable_content_ids = exploration.get_translatable_content_ids()\nfor suggestion in suggestions:\n suggestion_change = suggestion.change_cmd\n if not suggestion_change['content_id... | <|body_start_0|>
obsolete_content = []
obsolete_translation_suggestion_error_report: List[Dict[str, Union[str, List[Dict[str, str]]]]] = []
translatable_content_ids = exploration.get_translatable_content_ids()
for suggestion in suggestions:
suggestion_change = suggestion.chan... | Audits translation suggestions for missing content IDs. | AuditTranslationSuggestionsWithMissingContentIdJob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuditTranslationSuggestionsWithMissingContentIdJob:
"""Audits translation suggestions for missing content IDs."""
def _report_suggestions_with_missing_content_ids(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[Dict[str, Union[str, Li... | stack_v2_sparse_classes_36k_train_000468 | 11,707 | permissive | [
{
"docstring": "Audits translation suggestion models for missing content IDs. Reports the following for each exploration: - exploration ID - list of missing content IDs and corresponding state names. Args: suggestions: list(GeneralSuggestionModel). A list of translation suggestion models corresponding to the gi... | 2 | stack_v2_sparse_classes_30k_train_006530 | Implement the Python class `AuditTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Audits translation suggestions for missing content IDs.
Method signatures and docstrings:
- def _report_suggestions_with_missing_content_ids(suggestions: List[suggestion_models.GeneralSuggestionModel], ... | Implement the Python class `AuditTranslationSuggestionsWithMissingContentIdJob` described below.
Class description:
Audits translation suggestions for missing content IDs.
Method signatures and docstrings:
- def _report_suggestions_with_missing_content_ids(suggestions: List[suggestion_models.GeneralSuggestionModel], ... | d16fdf23d790eafd63812bd7239532256e30a21d | <|skeleton|>
class AuditTranslationSuggestionsWithMissingContentIdJob:
"""Audits translation suggestions for missing content IDs."""
def _report_suggestions_with_missing_content_ids(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[Dict[str, Union[str, Li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuditTranslationSuggestionsWithMissingContentIdJob:
"""Audits translation suggestions for missing content IDs."""
def _report_suggestions_with_missing_content_ids(suggestions: List[suggestion_models.GeneralSuggestionModel], exploration: exp_domain.Exploration) -> List[Dict[str, Union[str, List[Dict[str, ... | the_stack_v2_python_sparse | core/jobs/batch_jobs/rejecting_suggestion_for_invalid_content_ids_jobs.py | oppia/oppia | train | 6,172 |
6508d5e107e2478b32d053e70761164229de3964 | [
"if not height or len(height) == 0:\n return 0\nif len(height) == 1:\n return height[0]\ni = 0\nsize = len(height)\nstack = []\nmaxArea = 0\nwhile i < size:\n if len(stack) == 0 or stack[len(stack) - 1] < height[i]:\n stack.append(height[i])\n else:\n j = 1\n while len(stack) != 0 a... | <|body_start_0|>
if not height or len(height) == 0:
return 0
if len(height) == 1:
return height[0]
i = 0
size = len(height)
stack = []
maxArea = 0
while i < size:
if len(stack) == 0 or stack[len(stack) - 1] < height[i]:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, height):
""":type height: List[int] :rtype: int 上面的函数在栈中存放的是高度,这里存放的是索引,这样就可以较快的通过索引差计算面积"""
<|body_1|>
<|end_skeleton|>
<... | stack_v2_sparse_classes_36k_train_000469 | 2,365 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "largestRectangleArea",
"signature": "def largestRectangleArea(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int 上面的函数在栈中存放的是高度,这里存放的是索引,这样就可以较快的通过索引差计算面积",
"name": "largestRectangleArea2",
"signature": "de... | 2 | stack_v2_sparse_classes_30k_train_002374 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int
- def largestRectangleArea2(self, height): :type height: List[int] :rtype: int 上面的函数在栈中存放的是高度,这里存放的是索引... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def largestRectangleArea(self, height): :type height: List[int] :rtype: int
- def largestRectangleArea2(self, height): :type height: List[int] :rtype: int 上面的函数在栈中存放的是高度,这里存放的是索引... | 96adb6c04c344e792e35dc70dc45eb76b5402008 | <|skeleton|>
class Solution:
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def largestRectangleArea2(self, height):
""":type height: List[int] :rtype: int 上面的函数在栈中存放的是高度,这里存放的是索引,这样就可以较快的通过索引差计算面积"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def largestRectangleArea(self, height):
""":type height: List[int] :rtype: int"""
if not height or len(height) == 0:
return 0
if len(height) == 1:
return height[0]
i = 0
size = len(height)
stack = []
maxArea = 0
... | the_stack_v2_python_sparse | JiQiang/leetcode_py/regular/LargestRectangle_in_Histogram84.py | Hearen/AlgorithmHackers | train | 10 | |
68ce7a53cf76a077913937ffdbc42a27b2454adc | [
"n = len(nums)\nsums = nums[:]\nfor i in range(1, n):\n sums[i] = sums[i - 1] + nums[i]\nres = sums[k - 1] / k\nfor i in range(k, n):\n t = sums[i]\n if t > res * (i + 1):\n res = t / (i + 1)\n for j in range(i - k, -1, -1):\n t = sums[i] - sums[j]\n if t > res * (i - j):\n ... | <|body_start_0|>
n = len(nums)
sums = nums[:]
for i in range(1, n):
sums[i] = sums[i - 1] + nums[i]
res = sums[k - 1] / k
for i in range(k, n):
t = sums[i]
if t > res * (i + 1):
res = t / (i + 1)
for j in range(i - k... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMaxAverageTLE(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000470 | 2,141 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: float",
"name": "findMaxAverageTLE",
"signature": "def findMaxAverageTLE(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: float",
"name": "findMaxAverage",
"signature": "def findMaxAverage(self, nums,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverageTLE(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMaxAverageTLE(self, nums, k): :type nums: List[int] :type k: int :rtype: float
- def findMaxAverage(self, nums, k): :type nums: List[int] :type k: int :rtype: float
<|sk... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def findMaxAverageTLE(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_0|>
def findMaxAverage(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMaxAverageTLE(self, nums, k):
""":type nums: List[int] :type k: int :rtype: float"""
n = len(nums)
sums = nums[:]
for i in range(1, n):
sums[i] = sums[i - 1] + nums[i]
res = sums[k - 1] / k
for i in range(k, n):
t = sums... | the_stack_v2_python_sparse | M/MaximumAverageSubarrayII.py | bssrdf/pyleet | train | 2 | |
8eb2b3e03f9e4c3747ea1c30b31574cca396d1f2 | [
"super(MrcnnHead, self).__init__()\nself.in_channel = in_channel\nself.kernel_size = kernel_size\nself.num_classes = num_classes\nself.out_channel_branch1 = out_channel_branch1\nself.out_channel_branch2 = out_channel_branch2\nself.pool_size_h = pool_size_h\nself.pool_size_w = pool_size_w\nself.pool_size_d = pool_si... | <|body_start_0|>
super(MrcnnHead, self).__init__()
self.in_channel = in_channel
self.kernel_size = kernel_size
self.num_classes = num_classes
self.out_channel_branch1 = out_channel_branch1
self.out_channel_branch2 = out_channel_branch2
self.pool_size_h = pool_size... | MrcnnHead | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MrcnnHead:
def __init__(self, in_channel=128, kernel_size=3, num_classes=2, out_channel_branch1=16, out_channel_branch2=16, pool_size_h=7, pool_size_w=7, pool_size_d=7):
"""构造函数 :param in_channel: int, 输入通道大小 :param kernel_size: int, 卷积核大小 :param num_classes: int, 类别数量 :param out_channel... | stack_v2_sparse_classes_36k_train_000471 | 4,244 | permissive | [
{
"docstring": "构造函数 :param in_channel: int, 输入通道大小 :param kernel_size: int, 卷积核大小 :param num_classes: int, 类别数量 :param out_channel_branch1: int, 分支1的输出通道大小 :param out_channel_branch2: int, 分支2的输出通道大小 :param pool_size_h: int, roi align后的高 :param pool_size_w: int, roi align后的宽 :param pool_size_d: int, roi align后... | 2 | stack_v2_sparse_classes_30k_train_020158 | Implement the Python class `MrcnnHead` described below.
Class description:
Implement the MrcnnHead class.
Method signatures and docstrings:
- def __init__(self, in_channel=128, kernel_size=3, num_classes=2, out_channel_branch1=16, out_channel_branch2=16, pool_size_h=7, pool_size_w=7, pool_size_d=7): 构造函数 :param in_ch... | Implement the Python class `MrcnnHead` described below.
Class description:
Implement the MrcnnHead class.
Method signatures and docstrings:
- def __init__(self, in_channel=128, kernel_size=3, num_classes=2, out_channel_branch1=16, out_channel_branch2=16, pool_size_h=7, pool_size_w=7, pool_size_d=7): 构造函数 :param in_ch... | 6fac6929f3bdbc5379854ad392d3dec7b81fb767 | <|skeleton|>
class MrcnnHead:
def __init__(self, in_channel=128, kernel_size=3, num_classes=2, out_channel_branch1=16, out_channel_branch2=16, pool_size_h=7, pool_size_w=7, pool_size_d=7):
"""构造函数 :param in_channel: int, 输入通道大小 :param kernel_size: int, 卷积核大小 :param num_classes: int, 类别数量 :param out_channel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MrcnnHead:
def __init__(self, in_channel=128, kernel_size=3, num_classes=2, out_channel_branch1=16, out_channel_branch2=16, pool_size_h=7, pool_size_w=7, pool_size_d=7):
"""构造函数 :param in_channel: int, 输入通道大小 :param kernel_size: int, 卷积核大小 :param num_classes: int, 类别数量 :param out_channel_branch1: int,... | the_stack_v2_python_sparse | layers/net_head.py | YakuZeng/mask-rcnn-3d | train | 0 | |
f949ffc1bb5c8925ba4edb8f9ed7cd048d61a27c | [
"parser.display_info.AddFormat(\"\\n table(\\n name,\\n createTime.date('%Y-%m-%dT%H:%M:%S%Oz', undefined='-'),\\n status\\n )\\n \")\ntrigger_config = parser.add_mutually_exclusive_group(required=True)\ntrigger_config.add_argument('--trigger-config', metava... | <|body_start_0|>
parser.display_info.AddFormat("\n table(\n name,\n createTime.date('%Y-%m-%dT%H:%M:%S%Oz', undefined='-'),\n status\n )\n ")
trigger_config = parser.add_mutually_exclusive_group(required=True)
trigger_config.add_argument(... | Create a build trigger from a Cloud Source Repository. | CreateCSR | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateCSR:
"""Create a build trigger from a Cloud Source Repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|... | stack_v2_sparse_classes_36k_train_000472 | 5,769 | permissive | [
{
"docstring": "Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "This is what gets called when the... | 2 | null | Implement the Python class `CreateCSR` described below.
Class description:
Create a build trigger from a Cloud Source Repository.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some infor... | Implement the Python class `CreateCSR` described below.
Class description:
Create a build trigger from a Cloud Source Repository.
Method signatures and docstrings:
- def Args(parser): Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some infor... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class CreateCSR:
"""Create a build trigger from a Cloud Source Repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateCSR:
"""Create a build trigger from a Cloud Source Repository."""
def Args(parser):
"""Register flags for this command. Args: parser: An argparse.ArgumentParser-like object. It is mocked out in order to capture some information, but behaves like an ArgumentParser."""
parser.display_... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/builds/triggers/create/cloud_source_repositories.py | bopopescu/socialliteapp | train | 0 |
d27bb502010d57019056d02fc6ba7cfc58611922 | [
"test_cases = (('1001001001', 585), ('001', 4))\nfor test_case in test_cases:\n self.assertEqual(e0036.dec_to_base2(test_case[1]), test_case[0])",
"test_cases = ((True, '585'), (True, '1001001001'), (False, '586'))\nfor test_case in test_cases:\n self.assertEqual(e0036.is_palindromic(test_case[1]), test_cas... | <|body_start_0|>
test_cases = (('1001001001', 585), ('001', 4))
for test_case in test_cases:
self.assertEqual(e0036.dec_to_base2(test_case[1]), test_case[0])
<|end_body_0|>
<|body_start_1|>
test_cases = ((True, '585'), (True, '1001001001'), (False, '586'))
for test_case in t... | Test0036 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test0036:
def test_dec_to_base2(self):
"""test conversion on an example"""
<|body_0|>
def test_is_palindromic(self):
"""test on some examples"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
test_cases = (('1001001001', 585), ('001', 4))
for ... | stack_v2_sparse_classes_36k_train_000473 | 580 | no_license | [
{
"docstring": "test conversion on an example",
"name": "test_dec_to_base2",
"signature": "def test_dec_to_base2(self)"
},
{
"docstring": "test on some examples",
"name": "test_is_palindromic",
"signature": "def test_is_palindromic(self)"
}
] | 2 | null | Implement the Python class `Test0036` described below.
Class description:
Implement the Test0036 class.
Method signatures and docstrings:
- def test_dec_to_base2(self): test conversion on an example
- def test_is_palindromic(self): test on some examples | Implement the Python class `Test0036` described below.
Class description:
Implement the Test0036 class.
Method signatures and docstrings:
- def test_dec_to_base2(self): test conversion on an example
- def test_is_palindromic(self): test on some examples
<|skeleton|>
class Test0036:
def test_dec_to_base2(self):
... | 9687b709385a23d36bd8a24af16aaf7f375f4818 | <|skeleton|>
class Test0036:
def test_dec_to_base2(self):
"""test conversion on an example"""
<|body_0|>
def test_is_palindromic(self):
"""test on some examples"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test0036:
def test_dec_to_base2(self):
"""test conversion on an example"""
test_cases = (('1001001001', 585), ('001', 4))
for test_case in test_cases:
self.assertEqual(e0036.dec_to_base2(test_case[1]), test_case[0])
def test_is_palindromic(self):
"""test on som... | the_stack_v2_python_sparse | problem_0036/python/test.py | mleue/project_euler | train | 0 | |
d5fe262f36fab6d42d649fbc882387158f06b3be | [
"if value.org_unit_type in self.instance.form.org_unit_types.all():\n try:\n return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(pk=value.pk)\n except OrgUnit.DoesNotExist:\n pass\nraise serializers.ValidationError('Org unit type not assigned to this form or... | <|body_start_0|>
if value.org_unit_type in self.instance.form.org_unit_types.all():
try:
return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(pk=value.pk)
except OrgUnit.DoesNotExist:
pass
raise serializers.Vali... | InstanceSerializer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
<|body_0|>
def validate_period(self, value):
"""Check if period is of self.instance.form.period_type."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_000474 | 16,776 | permissive | [
{
"docstring": "Check if user has acces to this org_unit.",
"name": "validate_org_unit",
"signature": "def validate_org_unit(self, value)"
},
{
"docstring": "Check if period is of self.instance.form.period_type.",
"name": "validate_period",
"signature": "def validate_period(self, value)"... | 2 | stack_v2_sparse_classes_30k_train_017160 | Implement the Python class `InstanceSerializer` described below.
Class description:
Implement the InstanceSerializer class.
Method signatures and docstrings:
- def validate_org_unit(self, value): Check if user has acces to this org_unit.
- def validate_period(self, value): Check if period is of self.instance.form.per... | Implement the Python class `InstanceSerializer` described below.
Class description:
Implement the InstanceSerializer class.
Method signatures and docstrings:
- def validate_org_unit(self, value): Check if user has acces to this org_unit.
- def validate_period(self, value): Check if period is of self.instance.form.per... | 4d3a9d3faa6b3ed3a2e08c728cc4f03e5a0bbcb6 | <|skeleton|>
class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
<|body_0|>
def validate_period(self, value):
"""Check if period is of self.instance.form.period_type."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstanceSerializer:
def validate_org_unit(self, value):
"""Check if user has acces to this org_unit."""
if value.org_unit_type in self.instance.form.org_unit_types.all():
try:
return OrgUnit.objects.filter_for_user_and_app_id(self.context['request'].user, None).get(... | the_stack_v2_python_sparse | iaso/api/instances.py | lpontis/iaso | train | 0 | |
46590d1dd33e063bb97bf9fc580a7a033042a7ed | [
"DBFormatter.__init__(self, logger, dbi)\nself.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''\nself.sql = '\\nSELECT S.SITE_ID, S.SITE_NAME\\nFROM %sSITES S \\n' % self.owner",
"sql = self.sql\nif site_name == '':\n result = self.dbi.processData(sql, conn=conn, transaction=transaction)\nelse:\... | <|body_start_0|>
DBFormatter.__init__(self, logger, dbi)
self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''
self.sql = '\nSELECT S.SITE_ID, S.SITE_NAME\nFROM %sSITES S \n' % self.owner
<|end_body_0|>
<|body_start_1|>
sql = self.sql
if site_name == '':
... | PrimaryDSType List DAO class. | List | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class List:
"""PrimaryDSType List DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
<|body_0|>
def execute(self, conn, site_name='', transaction=False):
"""Lists all sites types if site_name is not provided."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_000475 | 1,108 | permissive | [
{
"docstring": "Add schema owner and sql.",
"name": "__init__",
"signature": "def __init__(self, logger, dbi, owner)"
},
{
"docstring": "Lists all sites types if site_name is not provided.",
"name": "execute",
"signature": "def execute(self, conn, site_name='', transaction=False)"
}
] | 2 | null | Implement the Python class `List` described below.
Class description:
PrimaryDSType List DAO class.
Method signatures and docstrings:
- def __init__(self, logger, dbi, owner): Add schema owner and sql.
- def execute(self, conn, site_name='', transaction=False): Lists all sites types if site_name is not provided. | Implement the Python class `List` described below.
Class description:
PrimaryDSType List DAO class.
Method signatures and docstrings:
- def __init__(self, logger, dbi, owner): Add schema owner and sql.
- def execute(self, conn, site_name='', transaction=False): Lists all sites types if site_name is not provided.
<|s... | 14df8bbe8ee8f874fe423399b18afef911fe78c7 | <|skeleton|>
class List:
"""PrimaryDSType List DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
<|body_0|>
def execute(self, conn, site_name='', transaction=False):
"""Lists all sites types if site_name is not provided."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class List:
"""PrimaryDSType List DAO class."""
def __init__(self, logger, dbi, owner):
"""Add schema owner and sql."""
DBFormatter.__init__(self, logger, dbi)
self.owner = '%s.' % owner if not owner in ('', '__MYSQL__') else ''
self.sql = '\nSELECT S.SITE_ID, S.SITE_NAME\nFROM ... | the_stack_v2_python_sparse | Server/Python/src/dbs/dao/Oracle/Site/List.py | vkuznet/DBS | train | 0 |
00aebdf3dfd86c7ea7580ca6118a1db55fb135ab | [
"self.slope = -1.0\nself.last_obs = -1.0\nself.last_obs_ind = -1\nself._fitted = False",
"if X.size != y.size:\n raise ValueError(\"'X' and 'y' size must match.\")\nself.last_obs = y[-1]\nself.last_obs_ind = X[-1]\nif y.size > 1:\n self.slope = (y[-1] - y[0]) / (X[-1] - X[0])\nelse:\n self.slope = 0.0\ns... | <|body_start_0|>
self.slope = -1.0
self.last_obs = -1.0
self.last_obs_ind = -1
self._fitted = False
<|end_body_0|>
<|body_start_1|>
if X.size != y.size:
raise ValueError("'X' and 'y' size must match.")
self.last_obs = y[-1]
self.last_obs_ind = X[-1]
... | Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of the given time-series. | TSNaiveDrift | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last o... | stack_v2_sparse_classes_36k_train_000476 | 12,299 | permissive | [
{
"docstring": "Init a Naive model with drift.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Fit a Naive model with drift. This model calculates the slope of the line crossing the first and last observation of ``y``, and stores it alongside the last observation value... | 3 | stack_v2_sparse_classes_30k_val_000736 | Implement the Python class `TSNaiveDrift` described below.
Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp... | Implement the Python class `TSNaiveDrift` described below.
Class description:
Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp... | 61cc1f63fa055c7466151cfefa7baff8df1702b7 | <|skeleton|>
class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TSNaiveDrift:
"""Naive model with drift for time-series forecasting. In the drift model, the forecasts are equal to the last observation of a given time-series plus an additional value proportional to the forecasted timestamp. The attributed to the timestamp is estimated from the first and last observation of... | the_stack_v2_python_sparse | tspymfe/_models.py | FelSiq/ts-pymfe | train | 9 |
8eccf0e5cf8e669b0ab4df4a7084aa00f6db75bc | [
"num_found = len(metob.retrieve('Atlas', unique_id=to_check, username='*'))\nif num_found == 1:\n return to_check\nif num_found == 0:\n raise ValueError(f\"Atlas with unique_id '{to_check}' not found in database.\")\nraise ValueError(f\"{num_found} copies of atlas with unique_id '{to_check}' in database.\")",... | <|body_start_0|>
num_found = len(metob.retrieve('Atlas', unique_id=to_check, username='*'))
if num_found == 1:
return to_check
if num_found == 0:
raise ValueError(f"Atlas with unique_id '{to_check}' not found in database.")
raise ValueError(f"{num_found} copies of... | Atlas specification | Atlas | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Atlas:
"""Atlas specification"""
def single_unique_id(cls, to_check):
"""Check that unique_id exists in the database"""
<|body_0|>
def altas_name_unique_id_match(cls, to_check, values):
"""test that atlas unique_id and name are consistent"""
<|body_1|>
<... | stack_v2_sparse_classes_36k_train_000477 | 12,746 | permissive | [
{
"docstring": "Check that unique_id exists in the database",
"name": "single_unique_id",
"signature": "def single_unique_id(cls, to_check)"
},
{
"docstring": "test that atlas unique_id and name are consistent",
"name": "altas_name_unique_id_match",
"signature": "def altas_name_unique_id... | 2 | stack_v2_sparse_classes_30k_train_003894 | Implement the Python class `Atlas` described below.
Class description:
Atlas specification
Method signatures and docstrings:
- def single_unique_id(cls, to_check): Check that unique_id exists in the database
- def altas_name_unique_id_match(cls, to_check, values): test that atlas unique_id and name are consistent | Implement the Python class `Atlas` described below.
Class description:
Atlas specification
Method signatures and docstrings:
- def single_unique_id(cls, to_check): Check that unique_id exists in the database
- def altas_name_unique_id_match(cls, to_check, values): test that atlas unique_id and name are consistent
<|... | 909ede3d1fe75fa5d64c6ff1b4c6016dc3df6746 | <|skeleton|>
class Atlas:
"""Atlas specification"""
def single_unique_id(cls, to_check):
"""Check that unique_id exists in the database"""
<|body_0|>
def altas_name_unique_id_match(cls, to_check, values):
"""test that atlas unique_id and name are consistent"""
<|body_1|>
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Atlas:
"""Atlas specification"""
def single_unique_id(cls, to_check):
"""Check that unique_id exists in the database"""
num_found = len(metob.retrieve('Atlas', unique_id=to_check, username='*'))
if num_found == 1:
return to_check
if num_found == 0:
... | the_stack_v2_python_sparse | metatlas/tools/config.py | biorack/metatlas | train | 10 |
234aaf90f155b8336b35011e6e33cd98f3ba6c4b | [
"try:\n self.pVertex_confluence = pVertex_center\n self.aFlowline_upstream = aFlowline_upstream_in\n self.pFlowline_downstream = pFlowline_downstream_in\nexcept:\n print('Initialization of confluence failed!')\nreturn",
"if len(self.aFlowline_upstream) == 2:\n pFlowline1 = self.aFlowline_upstream[0... | <|body_start_0|>
try:
self.pVertex_confluence = pVertex_center
self.aFlowline_upstream = aFlowline_upstream_in
self.pFlowline_downstream = pFlowline_downstream_in
except:
print('Initialization of confluence failed!')
return
<|end_body_0|>
<|body_s... | The pyconfluence class Returns: object: A confluence object | pyconfluence | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class pyconfluence:
"""The pyconfluence class Returns: object: A confluence object"""
def __init__(self, pVertex_center, aFlowline_upstream_in, pFlowline_downstream_in):
"""Initialize a pyconfluence object Args: pVertex_center (pyvertex): The center vertex aFlowline_upstream_in (list [pyfl... | stack_v2_sparse_classes_36k_train_000478 | 3,811 | permissive | [
{
"docstring": "Initialize a pyconfluence object Args: pVertex_center (pyvertex): The center vertex aFlowline_upstream_in (list [pyflowline]): A list of upstream flowlines pFlowline_downstream_in (pyflowline): The downstream flowline",
"name": "__init__",
"signature": "def __init__(self, pVertex_center,... | 3 | null | Implement the Python class `pyconfluence` described below.
Class description:
The pyconfluence class Returns: object: A confluence object
Method signatures and docstrings:
- def __init__(self, pVertex_center, aFlowline_upstream_in, pFlowline_downstream_in): Initialize a pyconfluence object Args: pVertex_center (pyver... | Implement the Python class `pyconfluence` described below.
Class description:
The pyconfluence class Returns: object: A confluence object
Method signatures and docstrings:
- def __init__(self, pVertex_center, aFlowline_upstream_in, pFlowline_downstream_in): Initialize a pyconfluence object Args: pVertex_center (pyver... | d46616d6558ff48feadd83059e0a77b199177f71 | <|skeleton|>
class pyconfluence:
"""The pyconfluence class Returns: object: A confluence object"""
def __init__(self, pVertex_center, aFlowline_upstream_in, pFlowline_downstream_in):
"""Initialize a pyconfluence object Args: pVertex_center (pyvertex): The center vertex aFlowline_upstream_in (list [pyfl... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class pyconfluence:
"""The pyconfluence class Returns: object: A confluence object"""
def __init__(self, pVertex_center, aFlowline_upstream_in, pFlowline_downstream_in):
"""Initialize a pyconfluence object Args: pVertex_center (pyvertex): The center vertex aFlowline_upstream_in (list [pyflowline]): A l... | the_stack_v2_python_sparse | pyflowline/classes/confluence.py | changliao1025/pyflowline | train | 15 |
e04042c5ffbf72824e9a68fd2514ae41abfdc212 | [
"RenderableResource.__init__(self, parent)\nself.localeNames = []\nfor locale, translation in self.config.locales.items():\n localeName = locale + ': '\n langName = translation.info().get('x-exe-language', None)\n if langName == None:\n langName = translation.info().get('x-poedit-language', 'English... | <|body_start_0|>
RenderableResource.__init__(self, parent)
self.localeNames = []
for locale, translation in self.config.locales.items():
localeName = locale + ': '
langName = translation.info().get('x-exe-language', None)
if langName == None:
l... | The PreferencesPage is responsible for managing eXe preferences | PreferencesPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PreferencesPage:
"""The PreferencesPage is responsible for managing eXe preferences"""
def __init__(self, parent):
"""Initialize"""
<|body_0|>
def getChild(self, name, request):
"""Try and find the child for the name given"""
<|body_1|>
def render_GE... | stack_v2_sparse_classes_36k_train_000479 | 3,657 | no_license | [
{
"docstring": "Initialize",
"name": "__init__",
"signature": "def __init__(self, parent)"
},
{
"docstring": "Try and find the child for the name given",
"name": "getChild",
"signature": "def getChild(self, name, request)"
},
{
"docstring": "Render the preferences",
"name": "... | 4 | stack_v2_sparse_classes_30k_train_001922 | Implement the Python class `PreferencesPage` described below.
Class description:
The PreferencesPage is responsible for managing eXe preferences
Method signatures and docstrings:
- def __init__(self, parent): Initialize
- def getChild(self, name, request): Try and find the child for the name given
- def render_GET(se... | Implement the Python class `PreferencesPage` described below.
Class description:
The PreferencesPage is responsible for managing eXe preferences
Method signatures and docstrings:
- def __init__(self, parent): Initialize
- def getChild(self, name, request): Try and find the child for the name given
- def render_GET(se... | 1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad | <|skeleton|>
class PreferencesPage:
"""The PreferencesPage is responsible for managing eXe preferences"""
def __init__(self, parent):
"""Initialize"""
<|body_0|>
def getChild(self, name, request):
"""Try and find the child for the name given"""
<|body_1|>
def render_GE... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PreferencesPage:
"""The PreferencesPage is responsible for managing eXe preferences"""
def __init__(self, parent):
"""Initialize"""
RenderableResource.__init__(self, parent)
self.localeNames = []
for locale, translation in self.config.locales.items():
localeNam... | the_stack_v2_python_sparse | eXe/rev3426-3513/right-branch-3513/exe/webui/preferencespage.py | joliebig/featurehouse_fstmerge_examples | train | 3 |
d25d6816416eee0c16065d6c74c38c2e21cdb1b0 | [
"new = self._clone()\nnew._annotations = new._annotations.union(values)\nnew.__dict__.pop('_annotations_cache_key', None)\nreturn new",
"new = self._clone()\nnew._annotations = util.immutabledict(values)\nnew.__dict__.pop('_annotations_cache_key', None)\nreturn new",
"if clone or self._annotations:\n new = s... | <|body_start_0|>
new = self._clone()
new._annotations = new._annotations.union(values)
new.__dict__.pop('_annotations_cache_key', None)
return new
<|end_body_0|>
<|body_start_1|>
new = self._clone()
new._annotations = util.immutabledict(values)
new.__dict__.pop('... | SupportsCloneAnnotations | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportsCloneAnnotations:
def _annotate(self, values):
"""return a copy of this ClauseElement with annotations updated by the given dictionary."""
<|body_0|>
def _with_annotations(self, values):
"""return a copy of this ClauseElement with annotations replaced by the ... | stack_v2_sparse_classes_36k_train_000480 | 9,973 | permissive | [
{
"docstring": "return a copy of this ClauseElement with annotations updated by the given dictionary.",
"name": "_annotate",
"signature": "def _annotate(self, values)"
},
{
"docstring": "return a copy of this ClauseElement with annotations replaced by the given dictionary.",
"name": "_with_a... | 3 | null | Implement the Python class `SupportsCloneAnnotations` described below.
Class description:
Implement the SupportsCloneAnnotations class.
Method signatures and docstrings:
- def _annotate(self, values): return a copy of this ClauseElement with annotations updated by the given dictionary.
- def _with_annotations(self, v... | Implement the Python class `SupportsCloneAnnotations` described below.
Class description:
Implement the SupportsCloneAnnotations class.
Method signatures and docstrings:
- def _annotate(self, values): return a copy of this ClauseElement with annotations updated by the given dictionary.
- def _with_annotations(self, v... | c3617b7757985287ebec2d8504b23b0c503d0aed | <|skeleton|>
class SupportsCloneAnnotations:
def _annotate(self, values):
"""return a copy of this ClauseElement with annotations updated by the given dictionary."""
<|body_0|>
def _with_annotations(self, values):
"""return a copy of this ClauseElement with annotations replaced by the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SupportsCloneAnnotations:
def _annotate(self, values):
"""return a copy of this ClauseElement with annotations updated by the given dictionary."""
new = self._clone()
new._annotations = new._annotations.union(values)
new.__dict__.pop('_annotations_cache_key', None)
retu... | the_stack_v2_python_sparse | jam/third_party/sqlalchemy/sql/annotation.py | jam-py/jam-py | train | 437 | |
c81c53cd79361700472c1933a65b6161aa507991 | [
"if len(nums) == 1:\n return nums[0]\nreturn max(self.helper(nums[:-1]), self.helper(nums[1:]))",
"if not nums:\n return 0\nif len(nums) == 1:\n return nums[0]\ndp = [0] * len(nums)\ndp[0] = nums[0]\ndp[1] = max(nums[0:2])\nfor i in range(2, len(nums)):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\nr... | <|body_start_0|>
if len(nums) == 1:
return nums[0]
return max(self.helper(nums[:-1]), self.helper(nums[1:]))
<|end_body_0|>
<|body_start_1|>
if not nums:
return 0
if len(nums) == 1:
return nums[0]
dp = [0] * len(nums)
dp[0] = nums[0]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def rob_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|>
de... | stack_v2_sparse_classes_36k_train_000481 | 2,585 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "helper",
"signature": "def helper(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": ... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): :type nums: List[int] :rtype: int
- def rob_1(self, nums): :type nums: List[int] :rtype: int
- de... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): :type nums: List[int] :rtype: int
- def rob_1(self, nums): :type nums: List[int] :rtype: int
- de... | 3d9e0ad2f6ed92ec969556f75d97c51ea4854719 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def rob_1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_2|>
de... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if len(nums) == 1:
return nums[0]
return max(self.helper(nums[:-1]), self.helper(nums[1:]))
def helper(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
r... | the_stack_v2_python_sparse | Solutions/0213_rob.py | YoupengLi/leetcode-sorting | train | 3 | |
44fd550eb28b4d9130dbf0576184c3d845b68210 | [
"f = open('willkommen.txt', 'r')\ntext = f.read()\nf.close()\nwords = text.split()\nself.words = [random.choice(words) for i in range(1000)]",
"try:\n os.remove('testfile.txt')\nexcept:\n pass",
"for w in self.words:\n r = ranking.Ranking('testfile.txt')\n r.add(w)\n r.save()\nfor w in set(self.w... | <|body_start_0|>
f = open('willkommen.txt', 'r')
text = f.read()
f.close()
words = text.split()
self.words = [random.choice(words) for i in range(1000)]
<|end_body_0|>
<|body_start_1|>
try:
os.remove('testfile.txt')
except:
pass
<|end_body... | Belastungstest | TestRanking2 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRanking2:
"""Belastungstest"""
def setUp(self):
"""erzeuge Zufallsliste von Wörtern"""
<|body_0|>
def tearDown(self):
"""Lösche Datei, die durch den Test erzeugt worden ist"""
<|body_1|>
def testAdd(self):
"""Belastungstest"""
<|b... | stack_v2_sparse_classes_36k_train_000482 | 2,660 | no_license | [
{
"docstring": "erzeuge Zufallsliste von Wörtern",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Lösche Datei, die durch den Test erzeugt worden ist",
"name": "tearDown",
"signature": "def tearDown(self)"
},
{
"docstring": "Belastungstest",
"name": "testA... | 3 | null | Implement the Python class `TestRanking2` described below.
Class description:
Belastungstest
Method signatures and docstrings:
- def setUp(self): erzeuge Zufallsliste von Wörtern
- def tearDown(self): Lösche Datei, die durch den Test erzeugt worden ist
- def testAdd(self): Belastungstest | Implement the Python class `TestRanking2` described below.
Class description:
Belastungstest
Method signatures and docstrings:
- def setUp(self): erzeuge Zufallsliste von Wörtern
- def tearDown(self): Lösche Datei, die durch den Test erzeugt worden ist
- def testAdd(self): Belastungstest
<|skeleton|>
class TestRanki... | 6acc4cc3ca1a7ed8143f5533a956d11fc3a76dff | <|skeleton|>
class TestRanking2:
"""Belastungstest"""
def setUp(self):
"""erzeuge Zufallsliste von Wörtern"""
<|body_0|>
def tearDown(self):
"""Lösche Datei, die durch den Test erzeugt worden ist"""
<|body_1|>
def testAdd(self):
"""Belastungstest"""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRanking2:
"""Belastungstest"""
def setUp(self):
"""erzeuge Zufallsliste von Wörtern"""
f = open('willkommen.txt', 'r')
text = f.read()
f.close()
words = text.split()
self.words = [random.choice(words) for i in range(1000)]
def tearDown(self):
... | the_stack_v2_python_sparse | book/kap_25/wort_des_jahres/rankingtest_fortgeschritten.py | Nachtalb/python_book_exercises | train | 0 |
47136e7f2cefb379a4bce939d371d98ccf55f6c5 | [
"self.index = node.getAttribute('N')\nself.url = GetText(node.getElementsByTagName('U')[0])\nself.encoded_url = GetText(node.getElementsByTagName('UE')[0])\ntitles = node.getElementsByTagName('T')\nif len(titles) > 0:\n self.title = GetText(titles[0])\n self.title_no_bold = GetText(node.getElementsByTagName('... | <|body_start_0|>
self.index = node.getAttribute('N')
self.url = GetText(node.getElementsByTagName('U')[0])
self.encoded_url = GetText(node.getElementsByTagName('UE')[0])
titles = node.getElementsByTagName('T')
if len(titles) > 0:
self.title = GetText(titles[0])
... | A wrapper around the XML of an individual result | Result | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Result:
"""A wrapper around the XML of an individual result"""
def __init__(self, node):
"""Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the address of the page matching the request encoded_url: the ... | stack_v2_sparse_classes_36k_train_000483 | 20,975 | no_license | [
{
"docstring": "Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the address of the page matching the request encoded_url: the url-encoded address of the page matching the request title: the title of the page matching the request, ... | 2 | null | Implement the Python class `Result` described below.
Class description:
A wrapper around the XML of an individual result
Method signatures and docstrings:
- def __init__(self, node): Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the a... | Implement the Python class `Result` described below.
Class description:
A wrapper around the XML of an individual result
Method signatures and docstrings:
- def __init__(self, node): Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the a... | 99ad033be03779e9680ce8024cdd7a4bdc5a58bd | <|skeleton|>
class Result:
"""A wrapper around the XML of an individual result"""
def __init__(self, node):
"""Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the address of the page matching the request encoded_url: the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Result:
"""A wrapper around the XML of an individual result"""
def __init__(self, node):
"""Construct a wrapper around an XML search result. Exposes the following properties: index: the index of the result (offset 1) url: the address of the page matching the request encoded_url: the url-encoded a... | the_stack_v2_python_sparse | pubConvGoogle | maximilianh/pubMunch | train | 43 |
2975bcd840ff794d009d0aa801e0024664016fd5 | [
"if save_policy_every_n_steps and policy_save_fn is None:\n raise ValueError('policy_save_fn is required when save_policy_every_n_steps > 0')\nself.max_number_of_steps = max_number_of_steps\nself.num_updates_per_observation = num_updates_per_observation\nself.num_collect_per_update = num_collect_per_update\nself... | <|body_start_0|>
if save_policy_every_n_steps and policy_save_fn is None:
raise ValueError('policy_save_fn is required when save_policy_every_n_steps > 0')
self.max_number_of_steps = max_number_of_steps
self.num_updates_per_observation = num_updates_per_observation
self.num_c... | Handles training step. | TrainStep | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TrainStep:
"""Handles training step."""
def __init__(self, max_number_of_steps=0, num_updates_per_observation=1, num_collect_per_update=1, num_collect_per_meta_update=1, log_every_n_steps=1, policy_save_fn=None, save_policy_every_n_steps=0, should_stop_early=None):
"""Returns a funct... | stack_v2_sparse_classes_36k_train_000484 | 7,027 | permissive | [
{
"docstring": "Returns a function that is executed at each step of slim training. Args: max_number_of_steps: Optional maximum number of train steps to take. num_updates_per_observation: Number of updates per observation. log_every_n_steps: The frequency, in terms of global steps, that the loss and global step ... | 2 | null | Implement the Python class `TrainStep` described below.
Class description:
Handles training step.
Method signatures and docstrings:
- def __init__(self, max_number_of_steps=0, num_updates_per_observation=1, num_collect_per_update=1, num_collect_per_meta_update=1, log_every_n_steps=1, policy_save_fn=None, save_policy_... | Implement the Python class `TrainStep` described below.
Class description:
Handles training step.
Method signatures and docstrings:
- def __init__(self, max_number_of_steps=0, num_updates_per_observation=1, num_collect_per_update=1, num_collect_per_meta_update=1, log_every_n_steps=1, policy_save_fn=None, save_policy_... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class TrainStep:
"""Handles training step."""
def __init__(self, max_number_of_steps=0, num_updates_per_observation=1, num_collect_per_update=1, num_collect_per_meta_update=1, log_every_n_steps=1, policy_save_fn=None, save_policy_every_n_steps=0, should_stop_early=None):
"""Returns a funct... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TrainStep:
"""Handles training step."""
def __init__(self, max_number_of_steps=0, num_updates_per_observation=1, num_collect_per_update=1, num_collect_per_meta_update=1, log_every_n_steps=1, policy_save_fn=None, save_policy_every_n_steps=0, should_stop_early=None):
"""Returns a function that is e... | the_stack_v2_python_sparse | models/research/efficient-hrl/train_utils.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
bd1733748dd9b82f4766d6ca9c63593826e991b7 | [
"threading.Thread.__init__(self)\nself.hass = hass\nself.stopped = threading.Event()\nself.on_receive_vto_event = on_receive_vto_event\nself.client = client\nself.started = False\nself._host = host\nself._port = port\nself._username = username\nself._password = password\nself._is_ssl = False\nself.vto_client = None... | <|body_start_0|>
threading.Thread.__init__(self)
self.hass = hass
self.stopped = threading.Event()
self.on_receive_vto_event = on_receive_vto_event
self.client = client
self.started = False
self._host = host
self._port = port
self._username = usern... | Connects to device and subscribes to events. Mainly to capture motion detection events. | DahuaVtoEventThread | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DahuaVtoEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, username: str, password: str):
"""Construct a thread listening f... | stack_v2_sparse_classes_36k_train_000485 | 5,648 | permissive | [
{
"docstring": "Construct a thread listening for events.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, username: str, password: str)"
},
{
"docstring": "Fetch VTO events",
"name": "run",
"signa... | 3 | null | Implement the Python class `DahuaVtoEventThread` described below.
Class description:
Connects to device and subscribes to events. Mainly to capture motion detection events.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, user... | Implement the Python class `DahuaVtoEventThread` described below.
Class description:
Connects to device and subscribes to events. Mainly to capture motion detection events.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, user... | 1048a33ab025208228ca2b99375f052577514e42 | <|skeleton|>
class DahuaVtoEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, username: str, password: str):
"""Construct a thread listening f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DahuaVtoEventThread:
"""Connects to device and subscribes to events. Mainly to capture motion detection events."""
def __init__(self, hass: HomeAssistant, client: DahuaClient, on_receive_vto_event, host: str, port: int, username: str, password: str):
"""Construct a thread listening for events."""... | the_stack_v2_python_sparse | custom_components/dahua/thread.py | rohankapoorcom/homeassistant-config | train | 1 |
baab6d62438474528699f6d27713580aa22c04b8 | [
"original = gorilla.get_original_attribute(sklearn_api.W2VTransformer, '__init__')\nself.mlinspect_caller_filename = mlinspect_caller_filename\nself.mlinspect_lineno = mlinspect_lineno\nself.mlinspect_optional_code_reference = mlinspect_optional_code_reference\nself.mlinspect_optional_source_code = mlinspect_option... | <|body_start_0|>
original = gorilla.get_original_attribute(sklearn_api.W2VTransformer, '__init__')
self.mlinspect_caller_filename = mlinspect_caller_filename
self.mlinspect_lineno = mlinspect_lineno
self.mlinspect_optional_code_reference = mlinspect_optional_code_reference
self.m... | Patches for healthcare_utils.MyW2VTransformer | SklearnMyW2VTransformerPatching | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SklearnMyW2VTransformerPatching:
"""Patches for healthcare_utils.MyW2VTransformer"""
def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, n... | stack_v2_sparse_classes_36k_train_000486 | 7,957 | permissive | [
{
"docstring": "Patch for ('example_pipelines.healthcare.healthcare_utils', 'MyW2VTransformer')",
"name": "patched__init__",
"signature": "def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negati... | 3 | stack_v2_sparse_classes_30k_train_013744 | Implement the Python class `SklearnMyW2VTransformerPatching` described below.
Class description:
Patches for healthcare_utils.MyW2VTransformer
Method signatures and docstrings:
- def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=... | Implement the Python class `SklearnMyW2VTransformerPatching` described below.
Class description:
Patches for healthcare_utils.MyW2VTransformer
Method signatures and docstrings:
- def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=... | a3e6625e1fd208785544d5f09ab93ed8897cbf3d | <|skeleton|>
class SklearnMyW2VTransformerPatching:
"""Patches for healthcare_utils.MyW2VTransformer"""
def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SklearnMyW2VTransformerPatching:
"""Patches for healthcare_utils.MyW2VTransformer"""
def patched__init__(self, *, size=100, alpha=0.025, window=5, min_count=5, max_vocab_size=None, sample=0.001, seed=1, workers=3, min_alpha=0.0001, sg=0, hs=0, negative=5, cbow_mean=1, hashfxn=hash, iter=5, null_word=0, t... | the_stack_v2_python_sparse | example_pipelines/healthcare/custom_monkeypatching/patch_healthcare_utils.py | stefan-grafberger/mlinspect | train | 63 |
badb5128b9d1680736ce48f5d80ddb2e86b9bd2a | [
"rights = ghop_access.GHOPChecker(params)\nrights['subscribe'] = ['checkIsUser']\nnew_params = {}\nnew_params['logic'] = soc.modules.ghop.logic.models.task_subscription.logic\nnew_params['rights'] = rights\nnew_params['name'] = 'Task Subscription'\nnew_params['module_name'] = 'task_subscription'\nnew_params['module... | <|body_start_0|>
rights = ghop_access.GHOPChecker(params)
rights['subscribe'] = ['checkIsUser']
new_params = {}
new_params['logic'] = soc.modules.ghop.logic.models.task_subscription.logic
new_params['rights'] = rights
new_params['name'] = 'Task Subscription'
new_p... | View methods for the Task Subscriptions. | View | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""View methods for the Task Subscriptions."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View"""
<|body_0|>
def subscribe(self, request, access_type, page_name=... | stack_v2_sparse_classes_36k_train_000487 | 3,795 | permissive | [
{
"docstring": "Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View",
"name": "__init__",
"signature": "def __init__(self, params=None)"
},
{
"docstring": "View that subscribes/unsubscribes an user. This view is accessed by an AJAX ... | 2 | stack_v2_sparse_classes_30k_train_002837 | Implement the Python class `View` described below.
Class description:
View methods for the Task Subscriptions.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View
- def subscribe(self, ... | Implement the Python class `View` described below.
Class description:
View methods for the Task Subscriptions.
Method signatures and docstrings:
- def __init__(self, params=None): Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View
- def subscribe(self, ... | 5c5d50eea89372e967994dac3bd8b06d25b4f0fa | <|skeleton|>
class View:
"""View methods for the Task Subscriptions."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View"""
<|body_0|>
def subscribe(self, request, access_type, page_name=... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class View:
"""View methods for the Task Subscriptions."""
def __init__(self, params=None):
"""Defines the fields and methods required for the task_subscription. Params: params: a dict with params for this View"""
rights = ghop_access.GHOPChecker(params)
rights['subscribe'] = ['checkIsU... | the_stack_v2_python_sparse | src/melange/src/soc/modules/ghop/views/models/task_subscription.py | MatthewWilkes/mw4068-packaging | train | 0 |
066e8d594f796f6fd355e45ad629baa9d50f38d9 | [
"d = collections.defaultdict(int)\nd[0] = 1\nsum = 0\nans = 0\nfor n in nums:\n sum += n\n if sum - k in d:\n ans += d[sum - k]\n d[sum] += 1\nreturn ans",
"d = {0: 1}\nsum, ans = (0, 0)\nfor n in nums:\n sum += n\n if sum - k in d:\n ans += d[sum - k]\n if sum in d:\n d[sum... | <|body_start_0|>
d = collections.defaultdict(int)
d[0] = 1
sum = 0
ans = 0
for n in nums:
sum += n
if sum - k in d:
ans += d[sum - k]
d[sum] += 1
return ans
<|end_body_0|>
<|body_start_1|>
d = {0: 1}
sum... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def subarraySum1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
d = collecti... | stack_v2_sparse_classes_36k_train_000488 | 984 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySum1",
"signature": "def subarraySum1(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "subarraySum",
"signature": "def subarraySum(self, nums, k)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def subarraySum1(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def subarraySum(self, nums, k): :type nums: List[int] :type k: int :rtype: int
<|skeleton|>
cla... | 763674fcbe271af3d21eed790c3968c4d33f7b09 | <|skeleton|>
class Solution:
def subarraySum1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def subarraySum(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def subarraySum1(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
d = collections.defaultdict(int)
d[0] = 1
sum = 0
ans = 0
for n in nums:
sum += n
if sum - k in d:
ans += d[sum - k]
... | the_stack_v2_python_sparse | 560_subarray_sum_equals_k/560.py | guzhoudiaoke/leetcode_python3 | train | 0 | |
a559d65be327d7bc908edd544ad184f2bf88ebe2 | [
"result = []\ndistance = [[0] * len(points) for _ in range(len(points))]\nfor i in range(len(points)):\n for j in range(i):\n distance[i][j] = (points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2\n distance[j][i] = distance[i][j]\n for m in range(i):\n if distan... | <|body_start_0|>
result = []
distance = [[0] * len(points) for _ in range(len(points))]
for i in range(len(points)):
for j in range(i):
distance[i][j] = (points[i][0] - points[j][0]) ** 2 + (points[i][1] - points[j][1]) ** 2
distance[j][i] = distance[i... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
result = [... | stack_v2_sparse_classes_36k_train_000489 | 8,991 | permissive | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "_numberOfBoomerangs",
"signature": "def _numberOfBoomerangs(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "numberOfBoomerangs",
"signature": "def numberOfBoomerangs(self, points)"... | 2 | stack_v2_sparse_classes_30k_train_014170 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int
- def numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int
- def numberOfBoomerangs(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|>
c... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def _numberOfBoomerangs(self, points):
""":type points: List[List[int]] :rtype: int"""
result = []
distance = [[0] * len(points) for _ in range(len(points))]
for i in range(len(points)):
for j in range(i):
distance[i][j] = (points[i][0] - p... | the_stack_v2_python_sparse | 447.number-of-boomerangs.py | windard/leeeeee | train | 0 | |
d54e616f15a919fd618d21a154c2a1446614b9e0 | [
"deltas_map = {}\nfor range in svn_revision_ranges:\n source_lod = range.source_lod\n try:\n deltas = deltas_map[source_lod]\n except:\n deltas = []\n deltas_map[source_lod] = deltas\n deltas.append((range.opening_revnum, +1))\n if range.closing_revnum is not None:\n delta... | <|body_start_0|>
deltas_map = {}
for range in svn_revision_ranges:
source_lod = range.source_lod
try:
deltas = deltas_map[source_lod]
except:
deltas = []
deltas_map[source_lod] = deltas
deltas.append((range.o... | Represent the scores for a range of revisions. | RevisionScores | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RevisionScores:
"""Represent the scores for a range of revisions."""
def __init__(self, svn_revision_ranges):
"""Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of an svn source is defined to be the number of SVNRevisionRa... | stack_v2_sparse_classes_36k_train_000490 | 5,664 | permissive | [
{
"docstring": "Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of an svn source is defined to be the number of SVNRevisionRanges on that LOD that include the revision. A score thus indicates that copying the corresponding revision (or any following ... | 3 | null | Implement the Python class `RevisionScores` described below.
Class description:
Represent the scores for a range of revisions.
Method signatures and docstrings:
- def __init__(self, svn_revision_ranges): Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of a... | Implement the Python class `RevisionScores` described below.
Class description:
Represent the scores for a range of revisions.
Method signatures and docstrings:
- def __init__(self, svn_revision_ranges): Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of a... | 8cd432386e6c412a5b6ed506679185e0766671ff | <|skeleton|>
class RevisionScores:
"""Represent the scores for a range of revisions."""
def __init__(self, svn_revision_ranges):
"""Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of an svn source is defined to be the number of SVNRevisionRa... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RevisionScores:
"""Represent the scores for a range of revisions."""
def __init__(self, svn_revision_ranges):
"""Initialize based on SVN_REVISION_RANGES. SVN_REVISION_RANGES is a list of SVNRevisionRange objects. The score of an svn source is defined to be the number of SVNRevisionRanges on that ... | the_stack_v2_python_sparse | cvs2svn_lib/svn_revision_range.py | mhagger/cvs2svn | train | 67 |
fe1b68be12c5b5606e3c516dd1543be259d091e3 | [
"data_list = []\nresults = self.query.all()\nformatter = self.request.locale.dates.getFormatter('date', 'short')\nfor result in results:\n data = {}\n data['subject'] = result.short_name\n if ICommittee.providedBy(result.group):\n data['url'] = 'committees/obj-%i/calendar/group/sittings/obj-%i/sched... | <|body_start_0|>
data_list = []
results = self.query.all()
formatter = self.request.locale.dates.getFormatter('date', 'short')
for result in results:
data = {}
data['subject'] = result.short_name
if ICommittee.providedBy(result.group):
... | DraftSittingsViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DraftSittingsViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data_list = []
results = self.query.all()
formatter = self.... | stack_v2_sparse_classes_36k_train_000491 | 35,739 | no_license | [
{
"docstring": "return the data of the query",
"name": "getData",
"signature": "def getData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016576 | Implement the Python class `DraftSittingsViewlet` described below.
Class description:
Implement the DraftSittingsViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query | Implement the Python class `DraftSittingsViewlet` described below.
Class description:
Implement the DraftSittingsViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query
<|skeleton|>
class DraftSittingsViewlet:
def getData(self):
... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class DraftSittingsViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DraftSittingsViewlet:
def getData(self):
"""return the data of the query"""
data_list = []
results = self.query.all()
formatter = self.request.locale.dates.getFormatter('date', 'short')
for result in results:
data = {}
data['subject'] = result.sh... | the_stack_v2_python_sparse | bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 | |
6797db71fb9271bec3976bccb308c3408bd17c9c | [
"self.filename = filename\nself.filesize = os.path.getsize(filename)\nstream = open_stream(self.filename)\nself.document_tree = None\nparser = etree.XMLParser()\nself.document_tree = etree.parse(stream, parser)\nself.root_element = self.document_tree.getroot()\nself.root_element_tag = str(self.root_element.tag)\nse... | <|body_start_0|>
self.filename = filename
self.filesize = os.path.getsize(filename)
stream = open_stream(self.filename)
self.document_tree = None
parser = etree.XMLParser()
self.document_tree = etree.parse(stream, parser)
self.root_element = self.document_tree.get... | Object model representation of an XML document. | Document | [
"MIT",
"CC0-1.0",
"CC-BY-4.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Document:
"""Object model representation of an XML document."""
def __init__(self, filename):
"""Constructor. :param filename: XML filename :type: filename: str or unicode"""
<|body_0|>
def query(self, query):
"""Run XPath query. :param query: XPath query :type q... | stack_v2_sparse_classes_36k_train_000492 | 2,360 | permissive | [
{
"docstring": "Constructor. :param filename: XML filename :type: filename: str or unicode",
"name": "__init__",
"signature": "def __init__(self, filename)"
},
{
"docstring": "Run XPath query. :param query: XPath query :type query: str or unicode :return: list of query results or an empty list i... | 3 | null | Implement the Python class `Document` described below.
Class description:
Object model representation of an XML document.
Method signatures and docstrings:
- def __init__(self, filename): Constructor. :param filename: XML filename :type: filename: str or unicode
- def query(self, query): Run XPath query. :param query... | Implement the Python class `Document` described below.
Class description:
Object model representation of an XML document.
Method signatures and docstrings:
- def __init__(self, filename): Constructor. :param filename: XML filename :type: filename: str or unicode
- def query(self, query): Run XPath query. :param query... | d7d2a22c8976fb0b0016cb0a231d4822424f8e88 | <|skeleton|>
class Document:
"""Object model representation of an XML document."""
def __init__(self, filename):
"""Constructor. :param filename: XML filename :type: filename: str or unicode"""
<|body_0|>
def query(self, query):
"""Run XPath query. :param query: XPath query :type q... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Document:
"""Object model representation of an XML document."""
def __init__(self, filename):
"""Constructor. :param filename: XML filename :type: filename: str or unicode"""
self.filename = filename
self.filesize = os.path.getsize(filename)
stream = open_stream(self.filen... | the_stack_v2_python_sparse | defoe/generic_xml/document.py | alan-turing-institute/defoe | train | 16 |
26106f68a025c363d45a752f79cdeef0b771e8ae | [
"self.frequency = _frequency\nself.two_pi_frequency = 2 * pi * _frequency\nself.amplitude = _amplitude\nself.phase = _phase\nself.voltage_offset = voltage_offset\nself.noise_level = noise_level\nself.signal_log = []",
"test_sig = self.amplitude * sin(_t * self.two_pi_frequency + self.phase) + (random.random() * 2... | <|body_start_0|>
self.frequency = _frequency
self.two_pi_frequency = 2 * pi * _frequency
self.amplitude = _amplitude
self.phase = _phase
self.voltage_offset = voltage_offset
self.noise_level = noise_level
self.signal_log = []
<|end_body_0|>
<|body_start_1|>
... | SineSignal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SineSignal:
def __init__(self, _amplitude, _frequency, _phase, noise_level=0, voltage_offset=0):
"""The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave in volts :param _frequency: the frequency of the sine wave in Hz :param _phase: the phase of the s... | stack_v2_sparse_classes_36k_train_000493 | 3,002 | no_license | [
{
"docstring": "The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave in volts :param _frequency: the frequency of the sine wave in Hz :param _phase: the phase of the sine wave in radians :param noise_level: (optional) the absolute noise level of the sine wave (default 0) :pa... | 2 | stack_v2_sparse_classes_30k_train_017307 | Implement the Python class `SineSignal` described below.
Class description:
Implement the SineSignal class.
Method signatures and docstrings:
- def __init__(self, _amplitude, _frequency, _phase, noise_level=0, voltage_offset=0): The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave... | Implement the Python class `SineSignal` described below.
Class description:
Implement the SineSignal class.
Method signatures and docstrings:
- def __init__(self, _amplitude, _frequency, _phase, noise_level=0, voltage_offset=0): The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave... | b8061fe79f88c0892b55c2f4488355a8f68cc957 | <|skeleton|>
class SineSignal:
def __init__(self, _amplitude, _frequency, _phase, noise_level=0, voltage_offset=0):
"""The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave in volts :param _frequency: the frequency of the sine wave in Hz :param _phase: the phase of the s... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SineSignal:
def __init__(self, _amplitude, _frequency, _phase, noise_level=0, voltage_offset=0):
"""The constructor for a sine wave signal. :param _amplitude: the amplitude of the sine wave in volts :param _frequency: the frequency of the sine wave in Hz :param _phase: the phase of the sine wave in ra... | the_stack_v2_python_sparse | lib/signals/TestSignals.py | kevroy314/PLL-Neural-Network | train | 3 | |
434282ec838e774dd4179bb4daff2f03766bc7ff | [
"assert_is_type(data, H2OFrame)\nj = h2o.api('POST /3/Predictions/models/%s/frames/%s' % (self._id, data.frame_id))\nreturn j['model_metrics'][0]['cm']['table']",
"tm = ModelBase._get_metrics(self, train, valid, xval)\nm = {}\nfor k, v in zip(list(tm.keys()), list(tm.values())):\n m[k] = None if v is None else... | <|body_start_0|>
assert_is_type(data, H2OFrame)
j = h2o.api('POST /3/Predictions/models/%s/frames/%s' % (self._id, data.frame_id))
return j['model_metrics'][0]['cm']['table']
<|end_body_0|>
<|body_start_1|>
tm = ModelBase._get_metrics(self, train, valid, xval)
m = {}
for... | H2OOrdinalModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class H2OOrdinalModel:
def confusion_matrix(self, data):
"""Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the prediction results for which the confusion matrix should be extracted."""
<|body_0|>
def hit_r... | stack_v2_sparse_classes_36k_train_000494 | 3,729 | permissive | [
{
"docstring": "Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the prediction results for which the confusion matrix should be extracted.",
"name": "confusion_matrix",
"signature": "def confusion_matrix(self, data)"
},
{
... | 4 | null | Implement the Python class `H2OOrdinalModel` described below.
Class description:
Implement the H2OOrdinalModel class.
Method signatures and docstrings:
- def confusion_matrix(self, data): Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the pre... | Implement the Python class `H2OOrdinalModel` described below.
Class description:
Implement the H2OOrdinalModel class.
Method signatures and docstrings:
- def confusion_matrix(self, data): Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the pre... | d817ab90c8c47f6787604a0b9639b66234158228 | <|skeleton|>
class H2OOrdinalModel:
def confusion_matrix(self, data):
"""Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the prediction results for which the confusion matrix should be extracted."""
<|body_0|>
def hit_r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class H2OOrdinalModel:
def confusion_matrix(self, data):
"""Returns a confusion matrix based on H2O's default prediction threshold for a dataset. :param H2OFrame data: the frame with the prediction results for which the confusion matrix should be extracted."""
assert_is_type(data, H2OFrame)
... | the_stack_v2_python_sparse | h2o-py/h2o/model/models/ordinal.py | h2oai/h2o-3 | train | 6,872 | |
2c81136e442eefe3e7e5191293cc9cfce1aaf241 | [
"user = User.objects.filter(id=pk).first()\njson_str = request.body\njson_str = json_str.decode()\nreq_data = json.loads(json_str)\naccess_token = req_data.get('access_token')\nsec = TJWSSerializer(settings.SECRET_KEY, 300)\ntry:\n data = sec.loads(access_token)\nexcept BadData:\n return Response('非法请求')\nuse... | <|body_start_0|>
user = User.objects.filter(id=pk).first()
json_str = request.body
json_str = json_str.decode()
req_data = json.loads(json_str)
access_token = req_data.get('access_token')
sec = TJWSSerializer(settings.SECRET_KEY, 300)
try:
data = sec.l... | UserPasswordChangeView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserPasswordChangeView:
def post(self, request, pk):
"""1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。"""
<|body_0|>
def put(self, request, pk):
"""1.获取参数并校验,看原密码是否正确,两次密码是否一致。 2.获取当前用户信息,更新到数据库。 3.返回响应。"""
... | stack_v2_sparse_classes_36k_train_000495 | 21,851 | permissive | [
{
"docstring": "1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。",
"name": "post",
"signature": "def post(self, request, pk)"
},
{
"docstring": "1.获取参数并校验,看原密码是否正确,两次密码是否一致。 2.获取当前用户信息,更新到数据库。 3.返回响应。",
"name": "put",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_train_012475 | Implement the Python class `UserPasswordChangeView` described below.
Class description:
Implement the UserPasswordChangeView class.
Method signatures and docstrings:
- def post(self, request, pk): 1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。
- def put(self, req... | Implement the Python class `UserPasswordChangeView` described below.
Class description:
Implement the UserPasswordChangeView class.
Method signatures and docstrings:
- def post(self, request, pk): 1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。
- def put(self, req... | faa4443c11d1534642c8dc9f8262f818f489c554 | <|skeleton|>
class UserPasswordChangeView:
def post(self, request, pk):
"""1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。"""
<|body_0|>
def put(self, request, pk):
"""1.获取参数并校验,看原密码是否正确,两次密码是否一致。 2.获取当前用户信息,更新到数据库。 3.返回响应。"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserPasswordChangeView:
def post(self, request, pk):
"""1.在模型类中实现检验修改密码 token 的方法,取出 data,判断 user_id 是否一样; 2.判断两次密码是否一样,判断是否是当前用户,返回数据; 3.更新密码; 4.返回重置密码成功信息。"""
user = User.objects.filter(id=pk).first()
json_str = request.body
json_str = json_str.decode()
req_data = jso... | the_stack_v2_python_sparse | Ethanyan_mall/Ethanyan_mall/apps/users/views.py | wenmingshuo/E-commerce-sites | train | 0 | |
6ae1bd21e9cae7fccd323c8ab969c5cc087db045 | [
"try:\n trips_db_instance = TripsDatabase()\n trip = trips_db_instance.trip_info(user.id, trip_id)\n if not trip:\n return response_404('NoSuchTrip', 'No such trip')\n attr_db_instance = AttractionsDatabase()\n attr_db_instance.add_attraction_to_trip(trip_id, attraction_id)\n attr_db_instan... | <|body_start_0|>
try:
trips_db_instance = TripsDatabase()
trip = trips_db_instance.trip_info(user.id, trip_id)
if not trip:
return response_404('NoSuchTrip', 'No such trip')
attr_db_instance = AttractionsDatabase()
attr_db_instance.add_... | TripAttractionsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @a... | stack_v2_sparse_classes_36k_train_000496 | 6,473 | no_license | [
{
"docstring": "@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @apiError (NotFound 404) {Object} NoSuchTrip Such trip doesn't exist. @apiError (BadRequest... | 3 | stack_v2_sparse_classes_30k_train_014449 | Implement the Python class `TripAttractionsView` described below.
Class description:
Implement the TripAttractionsView class.
Method signatures and docstrings:
- def post(self, trip_id, attraction_id, user: User=None): @api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @a... | Implement the Python class `TripAttractionsView` described below.
Class description:
Implement the TripAttractionsView class.
Method signatures and docstrings:
- def post(self, trip_id, attraction_id, user: User=None): @api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @a... | 1e89f75c6469dcab9197115eb971780684199987 | <|skeleton|>
class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @apiError (NotFo... | the_stack_v2_python_sparse | src/views/trip_attractions.py | Itamichan/Japan-Wanderlust | train | 0 | |
e29c800a6d75abe9a10d8fe442937273279105e8 | [
"if root == None:\n return '$'\nreturn str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)",
"nodes = data.split(',')\nself.i = 0\n\ndef dfs():\n if self.i == len(nodes) or nodes[self.i] == '$':\n self.i += 1\n return None\n root = TreeNode(int(nodes[self.i]))... | <|body_start_0|>
if root == None:
return '$'
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
<|end_body_0|>
<|body_start_1|>
nodes = data.split(',')
self.i = 0
def dfs():
if self.i == len(nodes) or nodes[self.i] ... | 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_000497 | 2,839 | 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:... | d2037e521a3ee6fdcc14fd5228ea1fd32d57d637 | <|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"""
if root == None:
return '$'
return str(root.val) + ',' + self.serialize(root.left) + ',' + self.serialize(root.right)
def deserialize(self, data):
"""Dec... | the_stack_v2_python_sparse | monthlyChallenge/2020-10(octoberchallenge)/10_09_SerializeAndDeserializeBST.py | phu-n-tran/LeetCode | train | 2 | |
00dae8042704e80640a7e55b555150b0f19433fc | [
"pt_r = np.array([[-1, -3], [0, -2]])\npt_r -= pt_r.min()\npt_c = pt_r.T\npt = np.stack((pt_r, pt_c), axis=0).astype(float)\npt /= pt.max()\ngame = MatrixGame(pt, seed=0)\nsolver = qre_anneal_sym.Solver(temperature=100, proj_grad=False, euclidean=True, lrs=(0.0001, 0.0001), exp_thresh=0.01, rnd_init=True, seed=0)\n... | <|body_start_0|>
pt_r = np.array([[-1, -3], [0, -2]])
pt_r -= pt_r.min()
pt_c = pt_r.T
pt = np.stack((pt_r, pt_c), axis=0).astype(float)
pt /= pt.max()
game = MatrixGame(pt, seed=0)
solver = qre_anneal_sym.Solver(temperature=100, proj_grad=False, euclidean=True, l... | AdidasTest | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdidasTest:
def test_adidas_on_prisoners_dilemma(self):
"""Tests ADIDAS on a 2-player prisoner's dilemma game."""
<|body_0|>
def test_adidas_on_elfarol(self):
"""Test ADIDAS on a 10-player, symmetric El Farol bar game."""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_000498 | 3,284 | permissive | [
{
"docstring": "Tests ADIDAS on a 2-player prisoner's dilemma game.",
"name": "test_adidas_on_prisoners_dilemma",
"signature": "def test_adidas_on_prisoners_dilemma(self)"
},
{
"docstring": "Test ADIDAS on a 10-player, symmetric El Farol bar game.",
"name": "test_adidas_on_elfarol",
"sig... | 2 | stack_v2_sparse_classes_30k_train_000601 | Implement the Python class `AdidasTest` described below.
Class description:
Implement the AdidasTest class.
Method signatures and docstrings:
- def test_adidas_on_prisoners_dilemma(self): Tests ADIDAS on a 2-player prisoner's dilemma game.
- def test_adidas_on_elfarol(self): Test ADIDAS on a 10-player, symmetric El F... | Implement the Python class `AdidasTest` described below.
Class description:
Implement the AdidasTest class.
Method signatures and docstrings:
- def test_adidas_on_prisoners_dilemma(self): Tests ADIDAS on a 2-player prisoner's dilemma game.
- def test_adidas_on_elfarol(self): Test ADIDAS on a 10-player, symmetric El F... | ee149736f7d85e16c119a463eee338c6d4c2ceb0 | <|skeleton|>
class AdidasTest:
def test_adidas_on_prisoners_dilemma(self):
"""Tests ADIDAS on a 2-player prisoner's dilemma game."""
<|body_0|>
def test_adidas_on_elfarol(self):
"""Test ADIDAS on a 10-player, symmetric El Farol bar game."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdidasTest:
def test_adidas_on_prisoners_dilemma(self):
"""Tests ADIDAS on a 2-player prisoner's dilemma game."""
pt_r = np.array([[-1, -3], [0, -2]])
pt_r -= pt_r.min()
pt_c = pt_r.T
pt = np.stack((pt_r, pt_c), axis=0).astype(float)
pt /= pt.max()
game ... | the_stack_v2_python_sparse | open_spiel/python/algorithms/adidas_test.py | lanctot/open_spiel | train | 1 | |
3a7937fa40b0cb6e4bfbcb43b2c22f217451ba53 | [
"formatted_message = self.format_message(message)\nsignature = rsa.RSAServer.decrypt(self, formatted_message)\nreturn signature",
"message_hash = sha256(message).hexdigest()\nsig_block = '00' + SHA256_asn1 + message_hash\nwhile len(sig_block) / 2 < 128 - 2:\n sig_block = 'FF' + sig_block\nsig_block = '0001' + ... | <|body_start_0|>
formatted_message = self.format_message(message)
signature = rsa.RSAServer.decrypt(self, formatted_message)
return signature
<|end_body_0|>
<|body_start_1|>
message_hash = sha256(message).hexdigest()
sig_block = '00' + SHA256_asn1 + message_hash
while le... | Gives capability to sign a message using RSA. Only uses SHA256 for hashing | FakeDSASignatory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FakeDSASignatory:
"""Gives capability to sign a message using RSA. Only uses SHA256 for hashing"""
def sign_message(self, message):
"""generates a rsa signature for a message Args: message (bytes): message to be signed Returns: int: signature of the message"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_000499 | 2,232 | no_license | [
{
"docstring": "generates a rsa signature for a message Args: message (bytes): message to be signed Returns: int: signature of the message",
"name": "sign_message",
"signature": "def sign_message(self, message)"
},
{
"docstring": "Formats a message for signing",
"name": "format_message",
... | 2 | stack_v2_sparse_classes_30k_test_000827 | Implement the Python class `FakeDSASignatory` described below.
Class description:
Gives capability to sign a message using RSA. Only uses SHA256 for hashing
Method signatures and docstrings:
- def sign_message(self, message): generates a rsa signature for a message Args: message (bytes): message to be signed Returns:... | Implement the Python class `FakeDSASignatory` described below.
Class description:
Gives capability to sign a message using RSA. Only uses SHA256 for hashing
Method signatures and docstrings:
- def sign_message(self, message): generates a rsa signature for a message Args: message (bytes): message to be signed Returns:... | 41756ea7bd38f1b31f28ba042ddc79041a6de716 | <|skeleton|>
class FakeDSASignatory:
"""Gives capability to sign a message using RSA. Only uses SHA256 for hashing"""
def sign_message(self, message):
"""generates a rsa signature for a message Args: message (bytes): message to be signed Returns: int: signature of the message"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FakeDSASignatory:
"""Gives capability to sign a message using RSA. Only uses SHA256 for hashing"""
def sign_message(self, message):
"""generates a rsa signature for a message Args: message (bytes): message to be signed Returns: int: signature of the message"""
formatted_message = self.for... | the_stack_v2_python_sparse | cryptopalsmod/ciphers/dsa_fake.py | tbywaters/cryptopals-solutions | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.