blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d4b6c0d99c6a16c98ec62635743e9970013b043 | [
"if not root:\n return ''\nprintout = []\n\ndef recurserialize(root):\n if not root:\n printout.append('* ')\n else:\n printout.append(str(root.val) + ' ')\n recurserialize(root.left)\n recurserialize(root.right)\nrecurserialize(root)\nreturn ''.join(printout)[:-1]",
"if not d... | <|body_start_0|>
if not root:
return ''
printout = []
def recurserialize(root):
if not root:
printout.append('* ')
else:
printout.append(str(root.val) + ' ')
recurserialize(root.left)
recurserial... | 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_10k_train_004700 | 3,172 | 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 | stack_v2_sparse_classes_30k_train_004145 | 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:... | 2cc179bdb33a97294a2bf99dbda278e935165943 | <|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_10k | 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 not root:
return ''
printout = []
def recurserialize(root):
if not root:
printout.append('* ')
else:
... | the_stack_v2_python_sparse | leetcode/449.py | Zedmor/hackerrank-puzzles | train | 0 | |
450cb6a00055706bf8a1619a74c026c217cea815 | [
"self.command = command\nif '{' and '}' not in command:\n print('GM命令格式错误,缺少大括号,请重新检查')\n return False\nif ',' not in command:\n print('GM命令格式错误,缺少逗号,请重新检查')\n return False\nreturn True",
"self.command = command\nif self.check_command_is_legal(self.command):\n split = self.command.index(',')\n s... | <|body_start_0|>
self.command = command
if '{' and '}' not in command:
print('GM命令格式错误,缺少大括号,请重新检查')
return False
if ',' not in command:
print('GM命令格式错误,缺少逗号,请重新检查')
return False
return True
<|end_body_0|>
<|body_start_1|>
self.com... | Gmhelper | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
<|body_0|>
def add_item_normal(self, command: str):
"""把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:"""
<|bo... | stack_v2_sparse_classes_10k_train_004701 | 2,781 | permissive | [
{
"docstring": "检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法",
"name": "check_command_is_legal",
"signature": "def check_command_is_legal(self, command: str)"
},
{
"docstring": "把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:",
"name": "add_item_normal... | 4 | stack_v2_sparse_classes_30k_train_003635 | Implement the Python class `Gmhelper` described below.
Class description:
Implement the Gmhelper class.
Method signatures and docstrings:
- def check_command_is_legal(self, command: str): 检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法
- def add_item_normal(self, command: str): 把指定字符串转换成GM命令 :param command... | Implement the Python class `Gmhelper` described below.
Class description:
Implement the Gmhelper class.
Method signatures and docstrings:
- def check_command_is_legal(self, command: str): 检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法
- def add_item_normal(self, command: str): 把指定字符串转换成GM命令 :param command... | 9d9ff9fb0dc4f1b63cdd31d6bbc12f9cd467eb81 | <|skeleton|>
class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
<|body_0|>
def add_item_normal(self, command: str):
"""把指定字符串转换成GM命令 :param command: add_item {{1001 to 1003}},10 这种字符串 :return:"""
<|bo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Gmhelper:
def check_command_is_legal(self, command: str):
"""检查字符串是否符合规定格式 :param command: :return: True表示合法 False表示不合法"""
self.command = command
if '{' and '}' not in command:
print('GM命令格式错误,缺少大括号,请重新检查')
return False
if ',' not in command:
... | the_stack_v2_python_sparse | code/kagamimoe/001/gmhelper.py | jianbing/python-practice-for-game-tester | train | 42 | |
6d6a172d2c448439d52eff39bafe0238b3987da4 | [
"ref = MetricModel.objects.filter(project_id=project_id, pk=metric_id).first()\nif not ref:\n raise error_codes.ResNotFoundError('metric不存在')\nperm = bcs_perm.Metric(request, project_id, metric_id, ref.name)\nperm.can_use(raise_exception=True)\nreturn BKAPIResponse(ref.to_json(), message='获取metric成功')",
"seria... | <|body_start_0|>
ref = MetricModel.objects.filter(project_id=project_id, pk=metric_id).first()
if not ref:
raise error_codes.ResNotFoundError('metric不存在')
perm = bcs_perm.Metric(request, project_id, metric_id, ref.name)
perm.can_use(raise_exception=True)
return BKAPIR... | 单个metric操作 | MetricDetail | [
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"ICU",
"LicenseRef-scancode-unknown-license-reference",
"Artistic-2.0",
"Zlib",
"LicenseRef-scancode-openssl",
"NAIST-2003",
"ISC",
"NTP",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetricDetail:
"""单个metric操作"""
def get(self, request, project_id, metric_id):
"""获取metric"""
<|body_0|>
def put(self, request, project_id, metric_id):
"""更新put"""
<|body_1|>
def get_metric_info(self, project_id, metric_id):
"""获取metric信息"""
... | stack_v2_sparse_classes_10k_train_004702 | 10,522 | permissive | [
{
"docstring": "获取metric",
"name": "get",
"signature": "def get(self, request, project_id, metric_id)"
},
{
"docstring": "更新put",
"name": "put",
"signature": "def put(self, request, project_id, metric_id)"
},
{
"docstring": "获取metric信息",
"name": "get_metric_info",
"signat... | 5 | stack_v2_sparse_classes_30k_train_000758 | Implement the Python class `MetricDetail` described below.
Class description:
单个metric操作
Method signatures and docstrings:
- def get(self, request, project_id, metric_id): 获取metric
- def put(self, request, project_id, metric_id): 更新put
- def get_metric_info(self, project_id, metric_id): 获取metric信息
- def delete(self, ... | Implement the Python class `MetricDetail` described below.
Class description:
单个metric操作
Method signatures and docstrings:
- def get(self, request, project_id, metric_id): 获取metric
- def put(self, request, project_id, metric_id): 更新put
- def get_metric_info(self, project_id, metric_id): 获取metric信息
- def delete(self, ... | 96373cda9d87038aceb0b4858ce89e7873c8e149 | <|skeleton|>
class MetricDetail:
"""单个metric操作"""
def get(self, request, project_id, metric_id):
"""获取metric"""
<|body_0|>
def put(self, request, project_id, metric_id):
"""更新put"""
<|body_1|>
def get_metric_info(self, project_id, metric_id):
"""获取metric信息"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MetricDetail:
"""单个metric操作"""
def get(self, request, project_id, metric_id):
"""获取metric"""
ref = MetricModel.objects.filter(project_id=project_id, pk=metric_id).first()
if not ref:
raise error_codes.ResNotFoundError('metric不存在')
perm = bcs_perm.Metric(request... | the_stack_v2_python_sparse | bcs-app/backend/apps/metric/views.py | freyzheng/bk-bcs-saas | train | 0 |
36fedc0d4d7c9e540837200553580a609fa26f9e | [
"self.error = error\nself.object_status = object_status\nself.resource_pool_id = resource_pool_id\nself.restored_object_id = restored_object_id\nself.source_object_id = source_object_id",
"if dictionary is None:\n return None\nerror = cohesity_management_sdk.models.request_error.RequestError.from_dictionary(di... | <|body_start_0|>
self.error = error
self.object_status = object_status
self.resource_pool_id = resource_pool_id
self.restored_object_id = restored_object_id
self.source_object_id = source_object_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return... | Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatusEnum): Specifies the status of an object during a Restore Task. 'kFilesCloned' indica... | RestoreObjectState | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreObjectState:
"""Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatusEnum): Specifies the status of an objec... | stack_v2_sparse_classes_10k_train_004703 | 4,997 | permissive | [
{
"docstring": "Constructor for the RestoreObjectState class",
"name": "__init__",
"signature": "def __init__(self, error=None, object_status=None, resource_pool_id=None, restored_object_id=None, source_object_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args:... | 2 | stack_v2_sparse_classes_30k_train_005391 | Implement the Python class `RestoreObjectState` described below.
Class description:
Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatus... | Implement the Python class `RestoreObjectState` described below.
Class description:
Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatus... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreObjectState:
"""Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatusEnum): Specifies the status of an objec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestoreObjectState:
"""Implementation of the 'RestoreObjectState' model. Specifies the state of an individual object in a Restore Task. Attributes: error (RequestError): Specifies if an error occurred during the restore operation. object_status (ObjectStatusEnum): Specifies the status of an object during a Re... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_object_state.py | cohesity/management-sdk-python | train | 24 |
c928dcd4069edea1639fd852dc8945f9ed291a77 | [
"user = User()\nuser.username = 'test'\nuser.save()\nprofile = Profile.objects.get(user=user)\nself.assertFalse(profile.activated)\nuser_id = user.id\nuser_token = profile.activation_token\nurl = reverse('userprofile-activate', args=(user_id, user_token))\nself.client.get(url)\nprofile = Profile.objects.get(user=us... | <|body_start_0|>
user = User()
user.username = 'test'
user.save()
profile = Profile.objects.get(user=user)
self.assertFalse(profile.activated)
user_id = user.id
user_token = profile.activation_token
url = reverse('userprofile-activate', args=(user_id, user... | AccountActionvationTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccountActionvationTests:
def test_user_activation(self):
"""Tests if the user activation works"""
<|body_0|>
def test_user_whrong_activation(self):
"""Tests if the user activation works worng"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = U... | stack_v2_sparse_classes_10k_train_004704 | 8,641 | no_license | [
{
"docstring": "Tests if the user activation works",
"name": "test_user_activation",
"signature": "def test_user_activation(self)"
},
{
"docstring": "Tests if the user activation works worng",
"name": "test_user_whrong_activation",
"signature": "def test_user_whrong_activation(self)"
}... | 2 | stack_v2_sparse_classes_30k_train_005402 | Implement the Python class `AccountActionvationTests` described below.
Class description:
Implement the AccountActionvationTests class.
Method signatures and docstrings:
- def test_user_activation(self): Tests if the user activation works
- def test_user_whrong_activation(self): Tests if the user activation works wor... | Implement the Python class `AccountActionvationTests` described below.
Class description:
Implement the AccountActionvationTests class.
Method signatures and docstrings:
- def test_user_activation(self): Tests if the user activation works
- def test_user_whrong_activation(self): Tests if the user activation works wor... | bee916136a67f2203a7ca6078220553ae1ce9c3c | <|skeleton|>
class AccountActionvationTests:
def test_user_activation(self):
"""Tests if the user activation works"""
<|body_0|>
def test_user_whrong_activation(self):
"""Tests if the user activation works worng"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccountActionvationTests:
def test_user_activation(self):
"""Tests if the user activation works"""
user = User()
user.username = 'test'
user.save()
profile = Profile.objects.get(user=user)
self.assertFalse(profile.activated)
user_id = user.id
use... | the_stack_v2_python_sparse | dwarf/userprofile/tests.py | slok/dwarf | train | 1 | |
63168702585b1f378761edd54d74c072f66f09c6 | [
"self.ris_widget = rw\nwidth_estimator = worm_widths.WidthEstimator.from_default_widths(pixels_per_micron=pixels_per_micron)\nself.pose_annotator = pose_annotation.PoseAnnotation(self.ris_widget, width_estimator=width_estimator)\nself.ris_widget.add_annotator([self.pose_annotator])\nload_data = Qt.QPushButton('Load... | <|body_start_0|>
self.ris_widget = rw
width_estimator = worm_widths.WidthEstimator.from_default_widths(pixels_per_micron=pixels_per_micron)
self.pose_annotator = pose_annotation.PoseAnnotation(self.ris_widget, width_estimator=width_estimator)
self.ris_widget.add_annotator([self.pose_anno... | GeneralPoseAnnotator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's n... | stack_v2_sparse_classes_10k_train_004705 | 4,938 | permissive | [
{
"docstring": "Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's name. Straight worm images are also saved out as png files. If widthes are specified ... | 3 | stack_v2_sparse_classes_30k_test_000372 | Implement the Python class `GeneralPoseAnnotator` described below.
Class description:
Implement the GeneralPoseAnnotator class.
Method signatures and docstrings:
- def __init__(self, rw, pixels_per_micron=1 / 1.3): Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. A... | Implement the Python class `GeneralPoseAnnotator` described below.
Class description:
Implement the GeneralPoseAnnotator class.
Method signatures and docstrings:
- def __init__(self, rw, pixels_per_micron=1 / 1.3): Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. A... | e7ea26dc005f71b50f25230e1d42cdf470859e29 | <|skeleton|>
class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's n... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's name. Straight ... | the_stack_v2_python_sparse | elegant/gui/general_pose_annotator.py | estbiostudent/elegant | train | 0 | |
7a08fae5d220f1111339dcec9547605ed1f1adac | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn SynchronizationJob()",
"from .entity import Entity\nfrom .key_value_pair import KeyValuePair\nfrom .synchronization_schedule import SynchronizationSchedule\nfrom .synchronization_schema import SynchronizationSchema\nfrom .synchronizati... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return SynchronizationJob()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .key_value_pair import KeyValuePair
from .synchronization_schedule import SynchronizationSche... | SynchronizationJob | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_10k_train_004706 | 4,015 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: SynchronizationJob",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | null | Implement the Python class `SynchronizationJob` described below.
Class description:
Implement the SynchronizationJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob: Creates a new instance of the appropriate class based on disc... | Implement the Python class `SynchronizationJob` described below.
Class description:
Implement the SynchronizationJob class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob: Creates a new instance of the appropriate class based on disc... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the obje... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SynchronizationJob:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> SynchronizationJob:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: Sy... | the_stack_v2_python_sparse | msgraph/generated/models/synchronization_job.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
62f05792f20bf5cff9761ca23035483296156426 | [
"for image_url in item['image_urls']:\n image_url = 'http:' + image_url\n yield scrapy.Request(image_url)",
"image_paths = [x['path'] for ok, x in results if ok]\nif not image_paths:\n raise DropItem('Item contains no images')\nreturn item"
] | <|body_start_0|>
for image_url in item['image_urls']:
image_url = 'http:' + image_url
yield scrapy.Request(image_url)
<|end_body_0|>
<|body_start_1|>
image_paths = [x['path'] for ok, x in results if ok]
if not image_paths:
raise DropItem('Item contains no ima... | JiandanPipeline | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiandanPipeline:
def get_media_requests(self, item, info):
""":param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:"""
<|body_0|>
def item_completed(self, results, item, info):
""":param results:... | stack_v2_sparse_classes_10k_train_004707 | 2,344 | permissive | [
{
"docstring": ":param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:",
"name": "get_media_requests",
"signature": "def get_media_requests(self, item, info)"
},
{
"docstring": ":param results: :param item: :param info: :retu... | 2 | stack_v2_sparse_classes_30k_train_005960 | Implement the Python class `JiandanPipeline` described below.
Class description:
Implement the JiandanPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): :param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Reque... | Implement the Python class `JiandanPipeline` described below.
Class description:
Implement the JiandanPipeline class.
Method signatures and docstrings:
- def get_media_requests(self, item, info): :param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Reque... | 8933c7a6d444d3d86a173984e6cf4c08dbf84039 | <|skeleton|>
class JiandanPipeline:
def get_media_requests(self, item, info):
""":param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:"""
<|body_0|>
def item_completed(self, results, item, info):
""":param results:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JiandanPipeline:
def get_media_requests(self, item, info):
""":param item: :param info: :return: 在工作流程中可以看到, 管道会得到文件的URL并从项目中下载。 为了这么做,你需要重写 get_media_requests() 方法, 并对各个图片URL返回一个Request:"""
for image_url in item['image_urls']:
image_url = 'http:' + image_url
yield scra... | the_stack_v2_python_sparse | jiandan/jiandan/pipelines.py | MisterZhouZhou/pythonLearn | train | 1 | |
2fe0e8334b63126b2babb56f528f4b2233c8d4ad | [
"raw_value = read_value_from_path(value)\nargs: Dict[str, str] = {}\nif '@' in raw_value:\n args['region'], raw_value = raw_value.split('@', 1)\nmatches = re.findall('([0-9a-zA-z_-]+:[^\\\\s$]+)', raw_value)\nfor match in matches:\n k, v = match.split(':', 1)\n args[k] = v\nreturn (args.pop('name_regex'), ... | <|body_start_0|>
raw_value = read_value_from_path(value)
args: Dict[str, str] = {}
if '@' in raw_value:
args['region'], raw_value = raw_value.split('@', 1)
matches = re.findall('([0-9a-zA-z_-]+:[^\\s$]+)', raw_value)
for match in matches:
k, v = match.spli... | AMI lookup. | AmiLookup | [
"BSD-2-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmiLookup:
"""AMI lookup."""
def parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value passed to a lookup. Returns: The lookup query and a dict ... | stack_v2_sparse_classes_10k_train_004708 | 4,479 | permissive | [
{
"docstring": "Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value passed to a lookup. Returns: The lookup query and a dict of arguments",
"name": "parse",
"signature": "def parse(cls, value: str) -> Tuple[str, Dict[st... | 2 | stack_v2_sparse_classes_30k_train_005078 | Implement the Python class `AmiLookup` described below.
Class description:
AMI lookup.
Method signatures and docstrings:
- def parse(cls, value: str) -> Tuple[str, Dict[str, str]]: Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value ... | Implement the Python class `AmiLookup` described below.
Class description:
AMI lookup.
Method signatures and docstrings:
- def parse(cls, value: str) -> Tuple[str, Dict[str, str]]: Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value ... | 0763b06aee07d2cf3f037a49ca0cb81a048c5deb | <|skeleton|>
class AmiLookup:
"""AMI lookup."""
def parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value passed to a lookup. Returns: The lookup query and a dict ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AmiLookup:
"""AMI lookup."""
def parse(cls, value: str) -> Tuple[str, Dict[str, str]]:
"""Parse the value passed to the lookup. This overrides the default parsing to account for special requirements. Args: value: The raw value passed to a lookup. Returns: The lookup query and a dict of arguments"... | the_stack_v2_python_sparse | runway/cfngin/lookups/handlers/ami.py | onicagroup/runway | train | 156 |
e091e0ffff07df32ce5f80bf0f0bf0b12bca1c8d | [
"TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)\ntreatment_info = TreatmentService.treatment_info(id_treatment)\nreturn JsonResponse(treatment_info)",
"Utils.validate_uuid(id_patient)\nUtils.validate_uuid(id_treatment_cycle)\nUtils.validate_uuid(id_treatment)"
] | <|body_start_0|>
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
treatment_info = TreatmentService.treatment_info(id_treatment)
return JsonResponse(treatment_info)
<|end_body_0|>
<|body_start_1|>
Utils.validate_uuid(id_patient)
Uti... | All endpoints related to treatment info actions | TreatmentInfoView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreatmentInfoView:
"""All endpoints related to treatment info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_trea... | stack_v2_sparse_classes_10k_train_004709 | 3,356 | no_license | [
{
"docstring": "Action when calling the endpoint with GET",
"name": "get",
"signature": "def get(request, id_patient, id_treatment_cycle, id_treatment)"
},
{
"docstring": "Validates the treatment information received in the request body :param id_patient: Id of the patient received :param id_tre... | 2 | stack_v2_sparse_classes_30k_train_004301 | Implement the Python class `TreatmentInfoView` described below.
Class description:
All endpoints related to treatment info actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_pati... | Implement the Python class `TreatmentInfoView` described below.
Class description:
All endpoints related to treatment info actions
Method signatures and docstrings:
- def get(request, id_patient, id_treatment_cycle, id_treatment): Action when calling the endpoint with GET
- def validate_treatment_info_request(id_pati... | 941e8b2870f8724db3d5103dda5157fd597cfcc7 | <|skeleton|>
class TreatmentInfoView:
"""All endpoints related to treatment info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
<|body_0|>
def validate_treatment_info_request(id_patient, id_treatment_cycle, id_trea... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TreatmentInfoView:
"""All endpoints related to treatment info actions"""
def get(request, id_patient, id_treatment_cycle, id_treatment):
"""Action when calling the endpoint with GET"""
TreatmentInfoView.validate_treatment_info_request(id_patient, id_treatment_cycle, id_treatment)
... | the_stack_v2_python_sparse | backend/martin_helder/views/treatment_info_view.py | JoaoAlvaroFerreira/FEUP-LGP | train | 1 |
db5ea1834098e8810cb36df4cdf081282368de0e | [
"dist = dist.coalesce((source,) + (sum(others, ()),) + (target,))\nconstraints = [[0, 2], [1, 2]]\nsuper().__init__(dist, marginals=constraints, rv_mode=rv_mode)\nself._source = {0}\nself._others = {1}\nself._target = {2}",
"cmi = self._conditional_mutual_information(self._source, self._target, self._others)\n\nd... | <|body_start_0|>
dist = dist.coalesce((source,) + (sum(others, ()),) + (target,))
constraints = [[0, 2], [1, 2]]
super().__init__(dist, marginals=constraints, rv_mode=rv_mode)
self._source = {0}
self._others = {1}
self._target = {2}
<|end_body_0|>
<|body_start_1|>
... | Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation. | BROJAOptimizer | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BROJAOptimizer:
"""Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation."""
def __init__(self, dist, source, others, target, rv_mode=None):
"""Initialize the optimizer. Parameters ------... | stack_v2_sparse_classes_10k_train_004710 | 3,870 | permissive | [
{
"docstring": "Initialize the optimizer. Parameters ---------- dist : Distribution The distribution to base the optimization on. source : iterable Variable to treat as the source. others : iterable of iterables The other source variables. target : iterable The target variable. rv_mode : bool Unused, provided f... | 2 | stack_v2_sparse_classes_30k_train_001770 | Implement the Python class `BROJAOptimizer` described below.
Class description:
Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation.
Method signatures and docstrings:
- def __init__(self, dist, source, others, target, r... | Implement the Python class `BROJAOptimizer` described below.
Class description:
Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation.
Method signatures and docstrings:
- def __init__(self, dist, source, others, target, r... | b13c5020a2b8524527a4a0db5a81d8549142228c | <|skeleton|>
class BROJAOptimizer:
"""Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation."""
def __init__(self, dist, source, others, target, rv_mode=None):
"""Initialize the optimizer. Parameters ------... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BROJAOptimizer:
"""Optimizer for computing the max mutual information between inputs and outputs. In the bivariate case, this corresponds to maximizing the coinformation."""
def __init__(self, dist, source, others, target, rv_mode=None):
"""Initialize the optimizer. Parameters ---------- dist : D... | the_stack_v2_python_sparse | dit/pid/measures/ibroja.py | dit/dit | train | 468 |
d7de809cb6ec6c52b1835df62a2df121ee02c79e | [
"author = g.user\nnotes = NoteModel.get_all_notes(author, archive='all')\nif not notes:\n abort(404, error=f'You have no notes yet')\nreturn (notes, 200)",
"author = g.user\nnote = NoteModel(author_id=author.id, **kwargs)\nnote.save()\nreturn (note, 201)"
] | <|body_start_0|>
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have no notes yet')
return (notes, 200)
<|end_body_0|>
<|body_start_1|>
author = g.user
note = NoteModel(author_id=author.id, **kwargs... | NoteListResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_10k_train_004711 | 11,305 | no_license | [
{
"docstring": "Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Создает заметку пользователя. Требуется аутентификация. :param kwargs: параметры для создания заметк... | 2 | stack_v2_sparse_classes_30k_train_002479 | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | Implement the Python class `NoteListResource` described below.
Class description:
Implement the NoteListResource class.
Method signatures and docstrings:
- def get(self): Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки
- def post(self, **kwargs): Созд... | adb9a3f4524ab76e8ba656344e2ed452e87b577c | <|skeleton|>
class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
<|body_0|>
def post(self, **kwargs):
"""Создает заметку пользователя. Требуется аутентификация. :param kwargs: па... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NoteListResource:
def get(self):
"""Возвращает все заметки пользователя. Фильтры поиска не применяются. Требуется аутентификация. :return: все заметки"""
author = g.user
notes = NoteModel.get_all_notes(author, archive='all')
if not notes:
abort(404, error=f'You have... | the_stack_v2_python_sparse | api/resources/note.py | UshakovAleksandr/Blog | train | 1 | |
1c16d3d49b11542b93f0fd51b35f008385499165 | [
"try:\n self.teaClassPractice = dict()\n self.sqlhandler = None\n self.teaId = self.get_argument('teaId')\n print(self.teaId)\n if self.getTeaClass():\n self.write(self.teaClassPractice)\n self.finish()\n else:\n raise RuntimeError\nexcept Exception:\n self.write('error')\n... | <|body_start_0|>
try:
self.teaClassPractice = dict()
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
print(self.teaId)
if self.getTeaClass():
self.write(self.teaClassPractice)
self.finish()
els... | TeaGetClassListRequestHandler | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
<|body_0|>
def getTeaClass(self):
"""返回老师的习题列表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
try:
self.teaClassPractice = dict()
self.sqlhandler = None
... | stack_v2_sparse_classes_10k_train_004712 | 2,285 | no_license | [
{
"docstring": "获取练习题列表,返回给老师客户端",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "返回老师的习题列表",
"name": "getTeaClass",
"signature": "def getTeaClass(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003702 | Implement the Python class `TeaGetClassListRequestHandler` described below.
Class description:
Implement the TeaGetClassListRequestHandler class.
Method signatures and docstrings:
- def get(self): 获取练习题列表,返回给老师客户端
- def getTeaClass(self): 返回老师的习题列表 | Implement the Python class `TeaGetClassListRequestHandler` described below.
Class description:
Implement the TeaGetClassListRequestHandler class.
Method signatures and docstrings:
- def get(self): 获取练习题列表,返回给老师客户端
- def getTeaClass(self): 返回老师的习题列表
<|skeleton|>
class TeaGetClassListRequestHandler:
def get(self)... | b28eb4163b02bd0a931653b94851592f2654b199 | <|skeleton|>
class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
<|body_0|>
def getTeaClass(self):
"""返回老师的习题列表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TeaGetClassListRequestHandler:
def get(self):
"""获取练习题列表,返回给老师客户端"""
try:
self.teaClassPractice = dict()
self.sqlhandler = None
self.teaId = self.get_argument('teaId')
print(self.teaId)
if self.getTeaClass():
self.writ... | the_stack_v2_python_sparse | app/src/main/pythonWork/TeaGetClassListRequestHandler.py | lyh-ADT/edu-app | train | 1 | |
486627b352ed8cae16d3814d8150e2ac4d9c1770 | [
"if field_name in data:\n data = data.copy()\n try:\n data[field_name] = ','.join(data.getlist(field_name))\n except AttributeError:\n data[field_name] = ','.join(data[field_name])\nreturn super(MultiSelectField, self).field_from_native(data, files, field_name, into)",
"for val in value.spl... | <|body_start_0|>
if field_name in data:
data = data.copy()
try:
data[field_name] = ','.join(data.getlist(field_name))
except AttributeError:
data[field_name] = ','.join(data[field_name])
return super(MultiSelectField, self).field_from_n... | MultiSelectField | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
<|body_0|>
def valid_value(self, value):
"""checks for each item if is a valid value"""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_10k_train_004713 | 6,326 | no_license | [
{
"docstring": "convert multiselect data into comma separated string",
"name": "field_from_native",
"signature": "def field_from_native(self, data, files, field_name, into)"
},
{
"docstring": "checks for each item if is a valid value",
"name": "valid_value",
"signature": "def valid_value... | 2 | stack_v2_sparse_classes_30k_train_007339 | Implement the Python class `MultiSelectField` described below.
Class description:
Implement the MultiSelectField class.
Method signatures and docstrings:
- def field_from_native(self, data, files, field_name, into): convert multiselect data into comma separated string
- def valid_value(self, value): checks for each i... | Implement the Python class `MultiSelectField` described below.
Class description:
Implement the MultiSelectField class.
Method signatures and docstrings:
- def field_from_native(self, data, files, field_name, into): convert multiselect data into comma separated string
- def valid_value(self, value): checks for each i... | dd798dc9bd3321b17007ff131e7b1288a2cd3c36 | <|skeleton|>
class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
<|body_0|>
def valid_value(self, value):
"""checks for each item if is a valid value"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiSelectField:
def field_from_native(self, data, files, field_name, into):
"""convert multiselect data into comma separated string"""
if field_name in data:
data = data.copy()
try:
data[field_name] = ','.join(data.getlist(field_name))
exce... | the_stack_v2_python_sparse | controller/apps/api/serializers.py | m00dy/vct-controller | train | 2 | |
7c294c98568c18ef93b773a5b5236442d0469a1a | [
"points = sorted(points, key=lambda x: x[1])\nres, end = (0, -float('inf'))\nfor interval in points:\n if interval[0] > end:\n res += 1\n end = interval[1]\nreturn res",
"if not points:\n return 0\npoints.sort()\nresult = 0\ni = 0\nwhile i < len(points):\n j = i + 1\n right_bound = point... | <|body_start_0|>
points = sorted(points, key=lambda x: x[1])
res, end = (0, -float('inf'))
for interval in points:
if interval[0] > end:
res += 1
end = interval[1]
return res
<|end_body_0|>
<|body_start_1|>
if not points:
r... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def findMinArrowShots2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
points = sor... | stack_v2_sparse_classes_10k_train_004714 | 4,349 | permissive | [
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots",
"signature": "def findMinArrowShots(self, points)"
},
{
"docstring": ":type points: List[List[int]] :rtype: int",
"name": "findMinArrowShots2",
"signature": "def findMinArrowShots2(self, points)"
}... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def findMinArrowShots2(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 findMinArrowShots(self, points): :type points: List[List[int]] :rtype: int
- def findMinArrowShots2(self, points): :type points: List[List[int]] :rtype: int
<|skeleton|>
cla... | 0ba027d9b8bc7c80bc89ce2da3543ce7a49a403c | <|skeleton|>
class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_0|>
def findMinArrowShots2(self, points):
""":type points: List[List[int]] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findMinArrowShots(self, points):
""":type points: List[List[int]] :rtype: int"""
points = sorted(points, key=lambda x: x[1])
res, end = (0, -float('inf'))
for interval in points:
if interval[0] > end:
res += 1
end = inte... | the_stack_v2_python_sparse | cs15211/MinimumNumberOfArrowsToBurstBalloons.py | JulyKikuAkita/PythonPrac | train | 1 | |
4cd8b858327553c6f121ce50b44ec1653d08e330 | [
"self.stdout.write('Re-assigining started', ending='\\n')\nif not args:\n raise CommandError('Param not set. <app model [created_perm]>')\nif len(args) < 3:\n raise CommandError('Param not set. <app model [created_perm]>')\napp = args[0]\nmodel = args[1]\nusername = args[2]\nnew_perms = list(args[3:])\nif use... | <|body_start_0|>
self.stdout.write('Re-assigining started', ending='\n')
if not args:
raise CommandError('Param not set. <app model [created_perm]>')
if len(args) < 3:
raise CommandError('Param not set. <app model [created_perm]>')
app = args[0]
model = ar... | Reassign permission to the model when permissions are changed | Command | [
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
<|body_0|>
def reassign_perms(self, user, app, model, new_perm):
"""Gets all the p... | stack_v2_sparse_classes_10k_train_004715 | 4,631 | permissive | [
{
"docstring": "Reassign permission to the model when permissions are changed",
"name": "handle",
"signature": "def handle(self, *args, **options)"
},
{
"docstring": "Gets all the permissions the user has on objects and assigns the new permission to them :param user: :param app: :param model: :p... | 3 | stack_v2_sparse_classes_30k_train_004071 | Implement the Python class `Command` described below.
Class description:
Reassign permission to the model when permissions are changed
Method signatures and docstrings:
- def handle(self, *args, **options): Reassign permission to the model when permissions are changed
- def reassign_perms(self, user, app, model, new_... | Implement the Python class `Command` described below.
Class description:
Reassign permission to the model when permissions are changed
Method signatures and docstrings:
- def handle(self, *args, **options): Reassign permission to the model when permissions are changed
- def reassign_perms(self, user, app, model, new_... | e5bdec91cb47179172b515bbcb91701262ff3377 | <|skeleton|>
class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
<|body_0|>
def reassign_perms(self, user, app, model, new_perm):
"""Gets all the p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Command:
"""Reassign permission to the model when permissions are changed"""
def handle(self, *args, **options):
"""Reassign permission to the model when permissions are changed"""
self.stdout.write('Re-assigining started', ending='\n')
if not args:
raise CommandError(... | the_stack_v2_python_sparse | onadata/apps/api/management/commands/reassign_permission.py | onaio/onadata | train | 177 |
69cd7a004977df6951dda67690458c86b1397761 | [
"if isinstance(expressions, tuple):\n expressions = [expressions]\nmasks = [list(comp(self.loc[:, method], thr)) for method, comp, thr in expressions]\nif len(masks) > 1:\n masks = numpy.logical_and(*masks)\nelse:\n masks = masks[0]\nreturn CleavageFragmentPredictionResult(self.loc[masks, :])",
"if type(... | <|body_start_0|>
if isinstance(expressions, tuple):
expressions = [expressions]
masks = [list(comp(self.loc[:, method], thr)) for method, comp, thr in expressions]
if len(masks) > 1:
masks = numpy.logical_and(*masks)
else:
masks = masks[0]
retu... | A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object. CleavageFragmentPredictionResult: +--------------+-------... | CleavageFragmentPredictionResult | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CleavageFragmentPredictionResult:
"""A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` objec... | stack_v2_sparse_classes_10k_train_004716 | 14,645 | permissive | [
{
"docstring": "Filters a result data frame based on a specified expression consisting of a list of triple with (method_name, comparator, threshold). The expression is applied to each row. If any of the columns fulfill the criteria the row remains. :param list((str,comparator,float)) expressions: A list of trip... | 2 | null | Implement the Python class `CleavageFragmentPredictionResult` described below.
Class description:
A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :cl... | Implement the Python class `CleavageFragmentPredictionResult` described below.
Class description:
A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :cl... | b3e54c8c4ed12b780b61f74672e9667245a7bb78 | <|skeleton|>
class CleavageFragmentPredictionResult:
"""A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` objec... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CleavageFragmentPredictionResult:
"""A :class:`~Fred2.Core.Result.CleavageFragmentPredictionResult` object is a :class:`pandas.DataFrame` with single-indexing, where column Ids are the prediction scores fo the different prediction methods, and row ID the :class:`~Fred2.Core.Peptide.Peptide` object. CleavageFr... | the_stack_v2_python_sparse | Fred2/Core/Result.py | FRED-2/Fred2 | train | 42 |
567c1b7258acf3cdba3fbf1bb6a97be31e4b58e1 | [
"i = 1\nret = [0] * num_people\nwhile candies > i:\n ret[(i - 1) % num_people] += i\n candies -= i\n i += 1\nret[(i - 1) % num_people] += candies\nreturn ret",
"n = int(math.sqrt(2 * candies + 0.25) - 0.5)\nrows, cols = divmod(n, num_people)\nret = [0] * num_people\nfor i in range(num_people):\n ret[i... | <|body_start_0|>
i = 1
ret = [0] * num_people
while candies > i:
ret[(i - 1) % num_people] += i
candies -= i
i += 1
ret[(i - 1) % num_people] += candies
return ret
<|end_body_0|>
<|body_start_1|>
n = int(math.sqrt(2 * candies + 0.25) -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]:
"""BF."""
<|body_0|>
def distributeCandies_MK2(self, candies: int, num_people: int) -> List[int]:
"""Math."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i = 1
... | stack_v2_sparse_classes_10k_train_004717 | 896 | no_license | [
{
"docstring": "BF.",
"name": "distributeCandies_MK1",
"signature": "def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]"
},
{
"docstring": "Math.",
"name": "distributeCandies_MK2",
"signature": "def distributeCandies_MK2(self, candies: int, num_people: int) -> Li... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]: BF.
- def distributeCandies_MK2(self, candies: int, num_people: int) -> List[int]: Math. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]: BF.
- def distributeCandies_MK2(self, candies: int, num_people: int) -> List[int]: Math.
<|skeleton|... | d7ba416d22becfa8f2a2ae4eee04c86617cd9332 | <|skeleton|>
class Solution:
def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]:
"""BF."""
<|body_0|>
def distributeCandies_MK2(self, candies: int, num_people: int) -> List[int]:
"""Math."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def distributeCandies_MK1(self, candies: int, num_people: int) -> List[int]:
"""BF."""
i = 1
ret = [0] * num_people
while candies > i:
ret[(i - 1) % num_people] += i
candies -= i
i += 1
ret[(i - 1) % num_people] += candies
... | the_stack_v2_python_sparse | 1103. Distribute Candies to People/Solution.py | faterazer/LeetCode | train | 4 | |
51882dccbe33026b38bd5f3cc3dd19223190568a | [
"self.error = error\nself.msg = msg\nself.other = other",
"tab = ' '\ntmp_msg = str(self.error) + ': ' + self.msg\nif len(tmp_msg) > 80:\n tmp_msg = self.error + ':\\n'\n temp = tab + self.msg\n while True:\n if len(temp) > 80:\n idx = temp[:80].rfind(' ')\n half1 = te... | <|body_start_0|>
self.error = error
self.msg = msg
self.other = other
<|end_body_0|>
<|body_start_1|>
tab = ' '
tmp_msg = str(self.error) + ': ' + self.msg
if len(tmp_msg) > 80:
tmp_msg = self.error + ':\n'
temp = tab + self.msg
... | this class is the represntation of a single error | error_instance | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class error_instance:
"""this class is the represntation of a single error"""
def __init__(self, error, msg, other=''):
"""initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (stirng) any other info about error"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_004718 | 9,637 | no_license | [
{
"docstring": "initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (stirng) any other info about error",
"name": "__init__",
"signature": "def __init__(self, error, msg, other='')"
},
{
"docstring": "converts the error to a sting returns:... | 2 | stack_v2_sparse_classes_30k_train_002224 | Implement the Python class `error_instance` described below.
Class description:
this class is the represntation of a single error
Method signatures and docstrings:
- def __init__(self, error, msg, other=''): initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (... | Implement the Python class `error_instance` described below.
Class description:
this class is the represntation of a single error
Method signatures and docstrings:
- def __init__(self, error, msg, other=''): initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (... | 95d0c102d649c5b028d262f5254106f997a7c77a | <|skeleton|>
class error_instance:
"""this class is the represntation of a single error"""
def __init__(self, error, msg, other=''):
"""initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (stirng) any other info about error"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class error_instance:
"""this class is the represntation of a single error"""
def __init__(self, error, msg, other=''):
"""initilizes the error arguments: error: (string) the errors name msg: (string) decription of the error other: (stirng) any other info about error"""
self.error = error
... | the_stack_v2_python_sparse | csv_lib/utility.py | rwspicer/csv_utilities | train | 1 |
346a239096bad2bf87dd82454cc9178ca5cacf84 | [
"self.enabled = enabled\nself.spare_serial = spare_serial\nself.uplink_mode = uplink_mode\nself.virtual_ip_1 = virtual_ip_1\nself.virtual_ip_2 = virtual_ip_2",
"if dictionary is None:\n return None\nenabled = dictionary.get('enabled')\nspare_serial = dictionary.get('spareSerial')\nuplink_mode = dictionary.get(... | <|body_start_0|>
self.enabled = enabled
self.spare_serial = spare_serial
self.uplink_mode = uplink_mode
self.virtual_ip_1 = virtual_ip_1
self.virtual_ip_2 = virtual_ip_2
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
enabled = dict... | Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mode (string): Uplink mode, either virtual or public virtual_ip_1 (string): The WAN 1 shared IP virtual_i... | UpdateNetworkWarmSpareSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateNetworkWarmSpareSettingsModel:
"""Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mode (string): Uplink mode, either virtual... | stack_v2_sparse_classes_10k_train_004719 | 2,514 | permissive | [
{
"docstring": "Constructor for the UpdateNetworkWarmSpareSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, enabled=None, spare_serial=None, uplink_mode=None, virtual_ip_1=None, virtual_ip_2=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Ar... | 2 | stack_v2_sparse_classes_30k_val_000078 | Implement the Python class `UpdateNetworkWarmSpareSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mod... | Implement the Python class `UpdateNetworkWarmSpareSettingsModel` described below.
Class description:
Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mod... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateNetworkWarmSpareSettingsModel:
"""Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mode (string): Uplink mode, either virtual... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateNetworkWarmSpareSettingsModel:
"""Implementation of the 'updateNetworkWarmSpareSettings' model. TODO: type model description here. Attributes: enabled (bool): Enable warm spare spare_serial (string): Serial number of the warm spare appliance uplink_mode (string): Uplink mode, either virtual or public vi... | the_stack_v2_python_sparse | meraki_sdk/models/update_network_warm_spare_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
793e9053b218a4c4ece4d609e02a50cd685bfa1b | [
"super(VggSubsampling, self).__init__()\ncur_channels = 1\nlayers = []\nblock_dims = [32, 64]\nfor block_dim in block_dims:\n layers.append(torch.nn.Conv2d(in_channels=cur_channels, out_channels=block_dim, kernel_size=3, padding=1, stride=1))\n layers.append(torch.nn.ReLU())\n layers.append(torch.nn.Conv2d... | <|body_start_0|>
super(VggSubsampling, self).__init__()
cur_channels = 1
layers = []
block_dims = [32, 64]
for block_dim in block_dims:
layers.append(torch.nn.Conv2d(in_channels=cur_channels, out_channels=block_dim, kernel_size=3, padding=1, stride=1))
lay... | Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension. | VggSubsampling | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, ... | stack_v2_sparse_classes_10k_train_004720 | 33,189 | permissive | [
{
"docstring": "Construct a VggSubsampling object. This uses 2 VGG blocks with 2 Conv2d layers each, subsampling its input by a factor of 4 in the time dimensions. Args: idim: Number of features at input, e.g. 40 or 80 for MFCC (will be treated as the image height). odim: Output dimension (number of features), ... | 2 | stack_v2_sparse_classes_30k_train_002576 | Implement the Python class `VggSubsampling` described below.
Class description:
Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output... | Implement the Python class `VggSubsampling` described below.
Class description:
Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output... | 2dda31e14039a79b77c89bcd3bb96d52cbf60c8a | <|skeleton|>
class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VggSubsampling:
"""Trying to follow the setup described here https://arxiv.org/pdf/1910.09799.pdf This paper is not 100% explicit so I am guessing to some extent, and trying to compare with other VGG implementations. Args: idim: Input dimension. odim: Output dimension."""
def __init__(self, idim: int, od... | the_stack_v2_python_sparse | snowfall/models/transformer.py | csukuangfj/snowfall | train | 0 |
bd0f1abfcf830758fb58ba5e12d93d44f79d7085 | [
"super(LayerNorm, self).__init__()\nself.a_2 = nn.Parameter(torch.ones(features))\nself.b_2 = nn.Parameter(torch.zeros(features))\nself.eps = eps",
"mean = x.mean(-1, keepdim=True)\nstd = x.std(-1, keepdim=True)\nreturn self.a_2 * (x - mean) / (std + self.eps) + self.b_2"
] | <|body_start_0|>
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
<|end_body_0|>
<|body_start_1|>
mean = x.mean(-1, keepdim=True)
std = x.std(-1, keepdim=True)
return sel... | Layer normalization module. | LayerNorm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerNorm:
"""Layer normalization module."""
def __init__(self, features, eps=1e-06):
""":param features: shape of normalized features :param eps: epsilon used for standard deviation"""
<|body_0|>
def forward(self, x):
"""Forward pass through the layer normalizat... | stack_v2_sparse_classes_10k_train_004721 | 21,238 | no_license | [
{
"docstring": ":param features: shape of normalized features :param eps: epsilon used for standard deviation",
"name": "__init__",
"signature": "def __init__(self, features, eps=1e-06)"
},
{
"docstring": "Forward pass through the layer normalization. :param x: input of shape [batch_size, slate_... | 2 | null | Implement the Python class `LayerNorm` described below.
Class description:
Layer normalization module.
Method signatures and docstrings:
- def __init__(self, features, eps=1e-06): :param features: shape of normalized features :param eps: epsilon used for standard deviation
- def forward(self, x): Forward pass through... | Implement the Python class `LayerNorm` described below.
Class description:
Layer normalization module.
Method signatures and docstrings:
- def __init__(self, features, eps=1e-06): :param features: shape of normalized features :param eps: epsilon used for standard deviation
- def forward(self, x): Forward pass through... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class LayerNorm:
"""Layer normalization module."""
def __init__(self, features, eps=1e-06):
""":param features: shape of normalized features :param eps: epsilon used for standard deviation"""
<|body_0|>
def forward(self, x):
"""Forward pass through the layer normalizat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayerNorm:
"""Layer normalization module."""
def __init__(self, features, eps=1e-06):
""":param features: shape of normalized features :param eps: epsilon used for standard deviation"""
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_... | the_stack_v2_python_sparse | generated/test_allegro_allRank.py | jansel/pytorch-jit-paritybench | train | 35 |
6a97a5052d78fbfc93b3b862ecde736778d3a3ab | [
"self.name = name\nself.cover_page_setting = cover_page_setting\nself.add_list_of_signatures_on_last_page_of_existing_pdf = add_list_of_signatures_on_last_page_of_existing_pdf\nself.cover_page_html = cover_page_html\nself.details_page_html = details_page_html\nself.verified_template = verified_template\nself.labels... | <|body_start_0|>
self.name = name
self.cover_page_setting = cover_page_setting
self.add_list_of_signatures_on_last_page_of_existing_pdf = add_list_of_signatures_on_last_page_of_existing_pdf
self.cover_page_html = cover_page_html
self.details_page_html = details_page_html
... | Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or end that show a list of the signers. This settings hides that page or put it first or ... | CreatePdfTemplate | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreatePdfTemplate:
"""Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or end that show a list of the signers. This... | stack_v2_sparse_classes_10k_train_004722 | 5,723 | permissive | [
{
"docstring": "Constructor for the CreatePdfTemplate class",
"name": "__init__",
"signature": "def __init__(self, name=None, cover_page_setting=None, add_list_of_signatures_on_last_page_of_existing_pdf=None, cover_page_html=None, details_page_html=None, verified_template=None, labels=None, include_logo... | 2 | stack_v2_sparse_classes_30k_train_000957 | Implement the Python class `CreatePdfTemplate` described below.
Class description:
Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or en... | Implement the Python class `CreatePdfTemplate` described below.
Class description:
Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or en... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class CreatePdfTemplate:
"""Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or end that show a list of the signers. This... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CreatePdfTemplate:
"""Implementation of the 'CreatePdfTemplate' model. Create a new Pdf template Attributes: name (string): The name of the Pdf template cover_page_setting (CoverPageSetting): Coverpage is the page added to the document at the beginning or end that show a list of the signers. This settings hid... | the_stack_v2_python_sparse | idfy_rest_client/models/create_pdf_template.py | dealflowteam/Idfy | train | 0 |
907f6cc2c0f1fa5aed9e3fabd99b2a87bb4fbf9e | [
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\ndp = [0] * n\ndp[0] = nums[0]\ndp[1] = max(nums[0], nums[1])\nfor i in range(2, n):\n dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])\nreturn dp[n - 1]",
"n = len(nums)\nif n == 0:\n return 0\nif n == 1:\n return nums[0]\nfirst, second... | <|body_start_0|>
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
return dp[n - 1]
<... | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def rob_2(self, nums: List[int]) -> int:
"""动态规划(优化空间)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
n = len(nums)
if n == 0:
return 0
if ... | stack_v2_sparse_classes_10k_train_004723 | 3,605 | no_license | [
{
"docstring": "动态规划。",
"name": "rob",
"signature": "def rob(self, nums: List[int]) -> int"
},
{
"docstring": "动态规划(优化空间)。",
"name": "rob_2",
"signature": "def rob_2(self, nums: List[int]) -> int"
}
] | 2 | null | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 动态规划。
- def rob_2(self, nums: List[int]) -> int: 动态规划(优化空间)。 | Implement the Python class `OfficialSolution` described below.
Class description:
Implement the OfficialSolution class.
Method signatures and docstrings:
- def rob(self, nums: List[int]) -> int: 动态规划。
- def rob_2(self, nums: List[int]) -> int: 动态规划(优化空间)。
<|skeleton|>
class OfficialSolution:
def rob(self, nums:... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
<|body_0|>
def rob_2(self, nums: List[int]) -> int:
"""动态规划(优化空间)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
def rob(self, nums: List[int]) -> int:
"""动态规划。"""
n = len(nums)
if n == 0:
return 0
if n == 1:
return nums[0]
dp = [0] * n
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, n):
... | the_stack_v2_python_sparse | 0198_house-robber.py | Nigirimeshi/leetcode | train | 0 | |
dd8f1f12622561cb2874aba12e32454de84f9840 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DeviceInstallState()",
"from .entity import Entity\nfrom .install_state import InstallState\nfrom .entity import Entity\nfrom .install_state import InstallState\nfields: Dict[str, Callable[[Any], None]] = {'deviceId': lambda n: setattr... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DeviceInstallState()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .install_state import InstallState
from .entity import Entity
from .install_state imp... | Contains properties for the installation state for a device. | DeviceInstallState | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | stack_v2_sparse_classes_10k_train_004724 | 3,783 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DeviceInstallState",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_... | 3 | stack_v2_sparse_classes_30k_train_003191 | Implement the Python class `DeviceInstallState` described below.
Class description:
Contains properties for the installation state for a device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState: Creates a new instance of the appropriat... | Implement the Python class `DeviceInstallState` described below.
Class description:
Contains properties for the installation state for a device.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState: Creates a new instance of the appropriat... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: Th... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeviceInstallState:
"""Contains properties for the installation state for a device."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DeviceInstallState:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node ... | the_stack_v2_python_sparse | msgraph/generated/models/device_install_state.py | microsoftgraph/msgraph-sdk-python | train | 135 |
2ce1ac1110cb38ece8fb709bb976e905e64b62ec | [
"params = book_review_getter.parse_args()\npg_size, pg_num = (int(params['pg-size']), int(params['pg-num']))\nstart = (pg_num - 1) * pg_size\nend = start + pg_size\nnew_records = LiveReview.find_by_asin(asin)\nold_records = OldReview.find_by_asin(asin)\nrecords = old_records + new_records\nif records == [] or start... | <|body_start_0|>
params = book_review_getter.parse_args()
pg_size, pg_num = (int(params['pg-size']), int(params['pg-num']))
start = (pg_num - 1) * pg_size
end = start + pg_size
new_records = LiveReview.find_by_asin(asin)
old_records = OldReview.find_by_asin(asin)
... | BookReview | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BookReview:
def get(self, asin):
"""Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their "old_review" field's value. Page Number starts from 1"""
<|body_0|>
def post(self, asin):
"""JWT required in Headers ... | stack_v2_sparse_classes_10k_train_004725 | 5,907 | no_license | [
{
"docstring": "Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their \"old_review\" field's value. Page Number starts from 1",
"name": "get",
"signature": "def get(self, asin)"
},
{
"docstring": "JWT required in Headers {Authorization:... | 3 | stack_v2_sparse_classes_30k_train_005385 | Implement the Python class `BookReview` described below.
Class description:
Implement the BookReview class.
Method signatures and docstrings:
- def get(self, asin): Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their "old_review" field's value. Page Number... | Implement the Python class `BookReview` described below.
Class description:
Implement the BookReview class.
Method signatures and docstrings:
- def get(self, asin): Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their "old_review" field's value. Page Number... | ef4336ad7a9e8b30281cc3cb828d08ebba9022e5 | <|skeleton|>
class BookReview:
def get(self, asin):
"""Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their "old_review" field's value. Page Number starts from 1"""
<|body_0|>
def post(self, asin):
"""JWT required in Headers ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BookReview:
def get(self, asin):
"""Returns new and old Reviews for the book given asin (B000FA64PK). New and old reviews are differentiated by their "old_review" field's value. Page Number starts from 1"""
params = book_review_getter.parse_args()
pg_size, pg_num = (int(params['pg-size... | the_stack_v2_python_sparse | app/namespaces/book_review.py | FavebookSUTD/favebook_backend | train | 0 | |
6a3450cba10962c35a0546862f425d87c02469fd | [
"out = self.item\nitem = self.next()\nif isletter(out, isatletter):\n while self.uplegal() and isletter(item, isatletter):\n out += item\n item = self.next()\nreturn out",
"comment = ''\nwhile self.uplegal() and '\\n' != self.item:\n comment += self.item\n self.next()\nwhile self.uplegal() ... | <|body_start_0|>
out = self.item
item = self.next()
if isletter(out, isatletter):
while self.uplegal() and isletter(item, isatletter):
out += item
item = self.next()
return out
<|end_body_0|>
<|body_start_1|>
comment = ''
while... | Char_stream | [
"BSL-1.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
<|body_0|>
def scan_comment_token(self):
"""Starts at the comment sign %, assumes that it is scanning a comme... | stack_v2_sparse_classes_10k_train_004726 | 35,480 | permissive | [
{
"docstring": "Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.",
"name": "scan_escape_token",
"signature": "def scan_escape_token(self, isatletter=False)"
},
{
"docstring": "Starts at the comment sign %, assumes that it is scanning a comment. Returns ... | 4 | stack_v2_sparse_classes_30k_train_001359 | Implement the Python class `Char_stream` described below.
Class description:
Implement the Char_stream class.
Method signatures and docstrings:
- def scan_escape_token(self, isatletter=False): Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.
- def scan_comment_token(self): S... | Implement the Python class `Char_stream` described below.
Class description:
Implement the Char_stream class.
Method signatures and docstrings:
- def scan_escape_token(self, isatletter=False): Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string.
- def scan_comment_token(self): S... | 47045aaf7054bc8efe657d1e9e070e6b27652c64 | <|skeleton|>
class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
<|body_0|>
def scan_comment_token(self):
"""Starts at the comment sign %, assumes that it is scanning a comme... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Char_stream:
def scan_escape_token(self, isatletter=False):
"""Starts after the escape sign, assumes that it is scanning a symbol. Returns a token-string."""
out = self.item
item = self.next()
if isletter(out, isatletter):
while self.uplegal() and isletter(item, isa... | the_stack_v2_python_sparse | py-scripts/de-macro | vEnhance/dotfiles | train | 119 | |
7528b1593ce9e0cfa2125032de2a17eaa3044b9a | [
"size = len(flowerbed)\nif sum(flowerbed) + n > size // 2 + size % 2:\n return False\nif len(flowerbed) == 1:\n return True\nplant = 0\nfor i in range(size):\n if flowerbed[i] == 1:\n continue\n if i != 0:\n if flowerbed[i - 1] == 1:\n continue\n if i != size - 1:\n if... | <|body_start_0|>
size = len(flowerbed)
if sum(flowerbed) + n > size // 2 + size % 2:
return False
if len(flowerbed) == 1:
return True
plant = 0
for i in range(size):
if flowerbed[i] == 1:
continue
if i != 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_0|>
def canPlaceFlowers_work(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|b... | stack_v2_sparse_classes_10k_train_004727 | 2,599 | no_license | [
{
"docstring": ":type flowerbed: List[int] :type n: int :rtype: bool",
"name": "canPlaceFlowers",
"signature": "def canPlaceFlowers(self, flowerbed, n)"
},
{
"docstring": ":type flowerbed: List[int] :type n: int :rtype: bool",
"name": "canPlaceFlowers_work",
"signature": "def canPlaceFlo... | 2 | stack_v2_sparse_classes_30k_train_004376 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool
- def canPlaceFlowers_work(self, flowerbed, n): :type flowerbed: List[int] :type n: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canPlaceFlowers(self, flowerbed, n): :type flowerbed: List[int] :type n: int :rtype: bool
- def canPlaceFlowers_work(self, flowerbed, n): :type flowerbed: List[int] :type n: ... | 3f0ffd519404165fd1a735441b212c801fd1ad1e | <|skeleton|>
class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_0|>
def canPlaceFlowers_work(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canPlaceFlowers(self, flowerbed, n):
""":type flowerbed: List[int] :type n: int :rtype: bool"""
size = len(flowerbed)
if sum(flowerbed) + n > size // 2 + size % 2:
return False
if len(flowerbed) == 1:
return True
plant = 0
f... | the_stack_v2_python_sparse | Problems/0600_0699/0605_Can_Place_Flowers/Project_Python3/Can_Place_Flowers.py | NobuyukiInoue/LeetCode | train | 0 | |
028d7388bed546a93689f27f4383985ba897b4f3 | [
"self.type = node.attrib.get('type', 'UserGenerated')\nself.printTag = self.type + ' File'\nself.__linkedModel = node.attrib.get('linkedCode', None)\nself.perturbed = node.attrib.get('perturbable', True)\nself.subDirectory = node.attrib.get('subDirectory', '')\nself.setAbsFile(os.path.join(self.subDirectory, node.t... | <|body_start_0|>
self.type = node.attrib.get('type', 'UserGenerated')
self.printTag = self.type + ' File'
self.__linkedModel = node.attrib.get('linkedCode', None)
self.perturbed = node.attrib.get('perturbable', True)
self.subDirectory = node.attrib.get('subDirectory', '')
... | This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML | UserGenerated | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserGenerated:
"""This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML"""
def _readMoreXML(self, node):
"""reads the xmlNode and sets parameters @ In, xmlNode, XML node @ Out, None"""
<|body_0|>
def __g... | stack_v2_sparse_classes_10k_train_004728 | 17,137 | permissive | [
{
"docstring": "reads the xmlNode and sets parameters @ In, xmlNode, XML node @ Out, None",
"name": "_readMoreXML",
"signature": "def _readMoreXML(self, node)"
},
{
"docstring": "Pickle dump method hook. @ In, None @ Out, stateDict, dict, dict of objets needed to restore instance",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_007196 | Implement the Python class `UserGenerated` described below.
Class description:
This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML
Method signatures and docstrings:
- def _readMoreXML(self, node): reads the xmlNode and sets parameters @ In, xmlNode... | Implement the Python class `UserGenerated` described below.
Class description:
This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML
Method signatures and docstrings:
- def _readMoreXML(self, node): reads the xmlNode and sets parameters @ In, xmlNode... | 2b16e7aa3325fe84cab2477947a951414c635381 | <|skeleton|>
class UserGenerated:
"""This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML"""
def _readMoreXML(self, node):
"""reads the xmlNode and sets parameters @ In, xmlNode, XML node @ Out, None"""
<|body_0|>
def __g... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserGenerated:
"""This class is for file objects that are created and used internally by RAVEN. Initialization is through self._readMoreXML"""
def _readMoreXML(self, node):
"""reads the xmlNode and sets parameters @ In, xmlNode, XML node @ Out, None"""
self.type = node.attrib.get('type', ... | the_stack_v2_python_sparse | ravenframework/Files.py | idaholab/raven | train | 201 |
5279be123f7f6bc9cea2641601a62070ae56e064 | [
"self.net = net\nself.data = data\nself.optimizer = optimizer\nself.loss = loss\nself.step = step\nself.seed = 33",
"paddle.enable_static()\npaddle.disable_static()\npaddle.seed(self.seed)\nnp.random.seed(self.seed)",
"reset(self.seed)\nnet = self.net.get_layer()\nnet.train()\nopt = self.optimizer.get_opt(net=n... | <|body_start_0|>
self.net = net
self.data = data
self.optimizer = optimizer
self.loss = loss
self.step = step
self.seed = 33
<|end_body_0|>
<|body_start_1|>
paddle.enable_static()
paddle.disable_static()
paddle.seed(self.seed)
np.random.se... | 构建Layer训练的通用类 | LayerTrain | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
<|body_0|>
def reset(self):
"""重置模型图 :return:"""
<|body_1|>
def dy_train(self):
"""dygraph train"""
<|body_2|>
def dy_train_dl(self):... | stack_v2_sparse_classes_10k_train_004729 | 4,955 | no_license | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self, net, data, optimizer, loss, step)"
},
{
"docstring": "重置模型图 :return:",
"name": "reset",
"signature": "def reset(self)"
},
{
"docstring": "dygraph train",
"name": "dy_train",
"signature": "def dy_tr... | 6 | null | Implement the Python class `LayerTrain` described below.
Class description:
构建Layer训练的通用类
Method signatures and docstrings:
- def __init__(self, net, data, optimizer, loss, step): 初始化
- def reset(self): 重置模型图 :return:
- def dy_train(self): dygraph train
- def dy_train_dl(self): dygraph train with dataloader
- def dy2... | Implement the Python class `LayerTrain` described below.
Class description:
构建Layer训练的通用类
Method signatures and docstrings:
- def __init__(self, net, data, optimizer, loss, step): 初始化
- def reset(self): 重置模型图 :return:
- def dy_train(self): dygraph train
- def dy_train_dl(self): dygraph train with dataloader
- def dy2... | bd3790ce72a2a26611b5eda3901651b5a809348f | <|skeleton|>
class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
<|body_0|>
def reset(self):
"""重置模型图 :return:"""
<|body_1|>
def dy_train(self):
"""dygraph train"""
<|body_2|>
def dy_train_dl(self):... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayerTrain:
"""构建Layer训练的通用类"""
def __init__(self, net, data, optimizer, loss, step):
"""初始化"""
self.net = net
self.data = data
self.optimizer = optimizer
self.loss = loss
self.step = step
self.seed = 33
def reset(self):
"""重置模型图 :retur... | the_stack_v2_python_sparse | framework/e2e/paddleLT/donotuse/train_origin.py | PaddlePaddle/PaddleTest | train | 42 |
17918a3867b2c5f682070d9f9b862cdfc75b799b | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn DatePostRequestBody()",
"from ........models.json import Json\nfrom ........models.json import Json\nfields: Dict[str, Callable[[Any], None]] = {'day': lambda n: setattr(self, 'day', n.get_object_value(Json)), 'month': lambda n: setatt... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return DatePostRequestBody()
<|end_body_0|>
<|body_start_1|>
from ........models.json import Json
from ........models.json import Json
fields: Dict[str, Callable[[Any], None]] = {'day':... | DatePostRequestBody | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DatePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DatePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_10k_train_004730 | 2,757 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: DatePostRequestBody",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator... | 3 | null | Implement the Python class `DatePostRequestBody` described below.
Class description:
Implement the DatePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DatePostRequestBody: Creates a new instance of the appropriate class based on d... | Implement the Python class `DatePostRequestBody` described below.
Class description:
Implement the DatePostRequestBody class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DatePostRequestBody: Creates a new instance of the appropriate class based on d... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class DatePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DatePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the ob... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DatePostRequestBody:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> DatePostRequestBody:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: ... | the_stack_v2_python_sparse | msgraph/generated/drives/item/items/item/workbook/functions/date/date_post_request_body.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
225b674eb13af0437835abd3138050035b839bd7 | [
"item_list = response.xpath('//div[@class=\"sg-col-inner\"]//a[@class=\"a-link-normal a-text-normal\"]/@href').getall()\nfor item in item_list:\n yield response.follow(item, callback=self.parse_item)\nnext_page = response.xpath('//div[@class=\"a-section a-spacing-none a-padding-base\"]//li[@class=\"a-last\"]/a/@... | <|body_start_0|>
item_list = response.xpath('//div[@class="sg-col-inner"]//a[@class="a-link-normal a-text-normal"]/@href').getall()
for item in item_list:
yield response.follow(item, callback=self.parse_item)
next_page = response.xpath('//div[@class="a-section a-spacing-none a-paddin... | AmazonSpiderSpider | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmazonSpiderSpider:
def parse(self, response):
"""Funcion principal para obtener los elemntos de cada página de Amazon"""
<|body_0|>
def parse_item(self, response):
"""Funcion que obtiene el nombre y el precio de los productos dentro de cada página"""
<|body_... | stack_v2_sparse_classes_10k_train_004731 | 2,170 | permissive | [
{
"docstring": "Funcion principal para obtener los elemntos de cada página de Amazon",
"name": "parse",
"signature": "def parse(self, response)"
},
{
"docstring": "Funcion que obtiene el nombre y el precio de los productos dentro de cada página",
"name": "parse_item",
"signature": "def p... | 2 | stack_v2_sparse_classes_30k_train_002297 | Implement the Python class `AmazonSpiderSpider` described below.
Class description:
Implement the AmazonSpiderSpider class.
Method signatures and docstrings:
- def parse(self, response): Funcion principal para obtener los elemntos de cada página de Amazon
- def parse_item(self, response): Funcion que obtiene el nombr... | Implement the Python class `AmazonSpiderSpider` described below.
Class description:
Implement the AmazonSpiderSpider class.
Method signatures and docstrings:
- def parse(self, response): Funcion principal para obtener los elemntos de cada página de Amazon
- def parse_item(self, response): Funcion que obtiene el nombr... | 24e71616dae692e931e95cd3815ca88fa9b8a46a | <|skeleton|>
class AmazonSpiderSpider:
def parse(self, response):
"""Funcion principal para obtener los elemntos de cada página de Amazon"""
<|body_0|>
def parse_item(self, response):
"""Funcion que obtiene el nombre y el precio de los productos dentro de cada página"""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AmazonSpiderSpider:
def parse(self, response):
"""Funcion principal para obtener los elemntos de cada página de Amazon"""
item_list = response.xpath('//div[@class="sg-col-inner"]//a[@class="a-link-normal a-text-normal"]/@href').getall()
for item in item_list:
yield response... | the_stack_v2_python_sparse | Retos/ScraperAmazon/amazon/amazon/spiders/amazon_spider.py | juanpanu-zz/PM_DataScience | train | 0 | |
45c2183425132b43255f633e938adef96e1c3146 | [
"self.stop = stop\nself.route = route\nself.info = None",
"bridge = BizkaibusData(self.stop, self.route)\nbridge.getNextBus()\nself.info = bridge.info"
] | <|body_start_0|>
self.stop = stop
self.route = route
self.info = None
<|end_body_0|>
<|body_start_1|>
bridge = BizkaibusData(self.stop, self.route)
bridge.getNextBus()
self.info = bridge.info
<|end_body_1|>
| The class for handling the data retrieval. | Bizkaibus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bizkaibus:
"""The class for handling the data retrieval."""
def __init__(self, stop, route):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Retrieve the information from API."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_10k_train_004732 | 2,206 | permissive | [
{
"docstring": "Initialize the data object.",
"name": "__init__",
"signature": "def __init__(self, stop, route)"
},
{
"docstring": "Retrieve the information from API.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `Bizkaibus` described below.
Class description:
The class for handling the data retrieval.
Method signatures and docstrings:
- def __init__(self, stop, route): Initialize the data object.
- def update(self): Retrieve the information from API. | Implement the Python class `Bizkaibus` described below.
Class description:
The class for handling the data retrieval.
Method signatures and docstrings:
- def __init__(self, stop, route): Initialize the data object.
- def update(self): Retrieve the information from API.
<|skeleton|>
class Bizkaibus:
"""The class ... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class Bizkaibus:
"""The class for handling the data retrieval."""
def __init__(self, stop, route):
"""Initialize the data object."""
<|body_0|>
def update(self):
"""Retrieve the information from API."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Bizkaibus:
"""The class for handling the data retrieval."""
def __init__(self, stop, route):
"""Initialize the data object."""
self.stop = stop
self.route = route
self.info = None
def update(self):
"""Retrieve the information from API."""
bridge = Bizk... | the_stack_v2_python_sparse | homeassistant/components/bizkaibus/sensor.py | home-assistant/core | train | 35,501 |
4f82f91ab1f488430fc02cbf2ce83bb80035d80b | [
"if isinstance(key, int):\n return PriorityLevel(key)\nif key not in PriorityLevel._member_map_:\n extend_enum(PriorityLevel, key, default)\nreturn PriorityLevel[key]",
"if not (isinstance(value, int) and 0 <= value <= 7):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nextend_enum(cl... | <|body_start_0|>
if isinstance(key, int):
return PriorityLevel(key)
if key not in PriorityLevel._member_map_:
extend_enum(PriorityLevel, key, default)
return PriorityLevel[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 7):
... | [PriorityLevel] Priority levels defined in IEEE 802.1p. | PriorityLevel | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PriorityLevel:
"""[PriorityLevel] Priority levels defined in IEEE 802.1p."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_10k_train_004733 | 1,411 | permissive | [
{
"docstring": "Backport support for original codes.",
"name": "get",
"signature": "def get(key, default=-1)"
},
{
"docstring": "Lookup function used when value is not found.",
"name": "_missing_",
"signature": "def _missing_(cls, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000542 | Implement the Python class `PriorityLevel` described below.
Class description:
[PriorityLevel] Priority levels defined in IEEE 802.1p.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found. | Implement the Python class `PriorityLevel` described below.
Class description:
[PriorityLevel] Priority levels defined in IEEE 802.1p.
Method signatures and docstrings:
- def get(key, default=-1): Backport support for original codes.
- def _missing_(cls, value): Lookup function used when value is not found.
<|skelet... | 90cd07d67df28d5c5ab0585bc60f467a78d9db33 | <|skeleton|>
class PriorityLevel:
"""[PriorityLevel] Priority levels defined in IEEE 802.1p."""
def get(key, default=-1):
"""Backport support for original codes."""
<|body_0|>
def _missing_(cls, value):
"""Lookup function used when value is not found."""
<|body_1|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PriorityLevel:
"""[PriorityLevel] Priority levels defined in IEEE 802.1p."""
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return PriorityLevel(key)
if key not in PriorityLevel._member_map_:
extend_enum(Priori... | the_stack_v2_python_sparse | pcapkit/const/vlan/priority_level.py | stjordanis/PyPCAPKit | train | 0 |
f9602a8538972ace1e62716b535587ec60962ff6 | [
"super(CNN, self).__init__()\nself.conv1 = nn.Conv2d(3, 32, 3, 1)\nself.conv2 = nn.Conv2d(32, 64, 3, 1)\nself.dropout1 = nn.Dropout2d(0.25)\nself.dropout2 = nn.Dropout2d(0.5)\nself.fc1 = nn.Linear(12544, 128)\nself.fc2 = nn.Linear(128, y_dim)",
"x = F.relu(self.conv1(x))\nx = F.relu(self.conv2(x))\nx = F.max_pool... | <|body_start_0|>
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(12544, 128)
self.fc2 = nn.Linear(128, y_dim)
<|end_body_... | CNN | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
<|body_0|>
def forward(self, x):
"""Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probabi... | stack_v2_sparse_classes_10k_train_004734 | 2,997 | no_license | [
{
"docstring": "Initialize classifier Inputs: - y_dim : number of classes",
"name": "__init__",
"signature": "def __init__(self, y_dim)"
},
{
"docstring": "Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probability ... | 2 | stack_v2_sparse_classes_30k_train_005904 | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, y_dim): Initialize classifier Inputs: - y_dim : number of classes
- def forward(self, x): Perform classification using the CNN classifier Inputs: - x : input data sample... | Implement the Python class `CNN` described below.
Class description:
Implement the CNN class.
Method signatures and docstrings:
- def __init__(self, y_dim): Initialize classifier Inputs: - y_dim : number of classes
- def forward(self, x): Perform classification using the CNN classifier Inputs: - x : input data sample... | 4df31e1670cf56331af7eb3524505d83c2dc98c7 | <|skeleton|>
class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
<|body_0|>
def forward(self, x):
"""Perform classification using the CNN classifier Inputs: - x : input data sample Outputs: - out: unnormalized output - prob_out: probabi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CNN:
def __init__(self, y_dim):
"""Initialize classifier Inputs: - y_dim : number of classes"""
super(CNN, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0... | the_stack_v2_python_sparse | src/model/classifier.py | nick11roberts/manifold-autoencoder-extended | train | 0 | |
5ead8c3eb04e3ece43dccce14b65604bd1d7cf31 | [
"self.taxonomy = kwargs.pop('taxonomy', None)\nself.old_category = kwargs.pop('category', None)\nsuper(FormClass, self).__init__(*args, **kwargs)",
"try:\n verb_cats = VerbCategory.objects.filter(taxonomy=self.taxonomy)\nexcept Taxonomy.DoesNotExist:\n raise Http404('The taxonomy does not exist!')\nelse:\n ... | <|body_start_0|>
self.taxonomy = kwargs.pop('taxonomy', None)
self.old_category = kwargs.pop('category', None)
super(FormClass, self).__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
try:
verb_cats = VerbCategory.objects.filter(taxonomy=self.taxonomy)
except... | A mixin for the verb category forms | VerbCategoryFormMixin | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VerbCategoryFormMixin:
"""A mixin for the verb category forms"""
def initialise(self, FormClass, *args, **kwargs):
"""Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxonomy"""
<|body_0|>
def clean_level_(self):
... | stack_v2_sparse_classes_10k_train_004735 | 3,624 | no_license | [
{
"docstring": "Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxonomy",
"name": "initialise",
"signature": "def initialise(self, FormClass, *args, **kwargs)"
},
{
"docstring": "Ensure the user does not input a level value equal to that of... | 2 | stack_v2_sparse_classes_30k_train_006538 | Implement the Python class `VerbCategoryFormMixin` described below.
Class description:
A mixin for the verb category forms
Method signatures and docstrings:
- def initialise(self, FormClass, *args, **kwargs): Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxono... | Implement the Python class `VerbCategoryFormMixin` described below.
Class description:
A mixin for the verb category forms
Method signatures and docstrings:
- def initialise(self, FormClass, *args, **kwargs): Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxono... | 691a6536718ef496ac603b1c8daee7508b3e8ff2 | <|skeleton|>
class VerbCategoryFormMixin:
"""A mixin for the verb category forms"""
def initialise(self, FormClass, *args, **kwargs):
"""Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxonomy"""
<|body_0|>
def clean_level_(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VerbCategoryFormMixin:
"""A mixin for the verb category forms"""
def initialise(self, FormClass, *args, **kwargs):
"""Overriding a forms' __init__ method to perform validation checks on the verb category level within the taxonomy"""
self.taxonomy = kwargs.pop('taxonomy', None)
sel... | the_stack_v2_python_sparse | verb_categories/forms.py | Aviemusca/curriculum-dev | train | 0 |
6d7e1f8a1a096364cc493ba82661ee7184ab62a9 | [
"super().__init__()\nif out_channels is None:\n out_channels = in_channels\nself.in_channels, self.out_channels = (in_channels, out_channels)\nself.map = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation)",
"x = self.map(input)\nx_gate = torch.sigmo... | <|body_start_0|>
super().__init__()
if out_channels is None:
out_channels = in_channels
self.in_channels, self.out_channels = (in_channels, out_channels)
self.map = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation... | Sigmoid Linear Units for 1D inputs | SiLU1d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiLU1d:
"""Sigmoid Linear Units for 1D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batch_size, in_chan... | stack_v2_sparse_classes_10k_train_004736 | 2,967 | no_license | [
{
"docstring": "Args: in_channels <int> out_channels <int>",
"name": "__init__",
"signature": "def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1)"
},
{
"docstring": "Args: input (batch_size, in_channels, T) Returns: output (batch_size, out_channels, T)",
... | 2 | stack_v2_sparse_classes_30k_train_004730 | Implement the Python class `SiLU1d` described below.
Class description:
Sigmoid Linear Units for 1D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1): Args: in_channels <int> out_channels <int>
- def forward(self, input): Args: input... | Implement the Python class `SiLU1d` described below.
Class description:
Sigmoid Linear Units for 1D inputs
Method signatures and docstrings:
- def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1): Args: in_channels <int> out_channels <int>
- def forward(self, input): Args: input... | 4f7f77406cf580785ebf932d78069e7d6e35b765 | <|skeleton|>
class SiLU1d:
"""Sigmoid Linear Units for 1D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1):
"""Args: in_channels <int> out_channels <int>"""
<|body_0|>
def forward(self, input):
"""Args: input (batch_size, in_chan... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SiLU1d:
"""Sigmoid Linear Units for 1D inputs"""
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1):
"""Args: in_channels <int> out_channels <int>"""
super().__init__()
if out_channels is None:
out_channels = in_channels
... | the_stack_v2_python_sparse | src/models/silu.py | shelly-tang/DNN-based_source_separation | train | 0 |
44e2ba43726040ee56c6fbf0798041758def5295 | [
"self.new_item = {}\nself.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\nself.items_list = ['initial']",
"new_item = Item()\nself.new_item = new_item.ItemDescription(item_sku, item_name, item_price, taxable)\nupdated_order = self.items_list.append(self.new_item)\nreturn updated_order"
] | <|body_start_0|>
self.new_item = {}
self.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.items_list = ['initial']
<|end_body_0|>
<|body_start_1|>
new_item = Item()
self.new_item = new_item.ItemDescription(item_sku, item_name, item_price, taxable)
... | CustomerOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
<|body_0|>
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item description"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.new_item = {}
self.purc... | stack_v2_sparse_classes_10k_train_004737 | 1,220 | no_license | [
{
"docstring": "Instantiate Order object",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create item description",
"name": "AddItem",
"signature": "def AddItem(self, item_sku, item_name, item_price, taxable)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001706 | Implement the Python class `CustomerOrder` described below.
Class description:
Implement the CustomerOrder class.
Method signatures and docstrings:
- def __init__(self): Instantiate Order object
- def AddItem(self, item_sku, item_name, item_price, taxable): Create item description | Implement the Python class `CustomerOrder` described below.
Class description:
Implement the CustomerOrder class.
Method signatures and docstrings:
- def __init__(self): Instantiate Order object
- def AddItem(self, item_sku, item_name, item_price, taxable): Create item description
<|skeleton|>
class CustomerOrder:
... | b3886baac5cacae48251f98ec749b75da9e5b310 | <|skeleton|>
class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
<|body_0|>
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item description"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomerOrder:
def __init__(self):
"""Instantiate Order object"""
self.new_item = {}
self.purchase_date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
self.items_list = ['initial']
def AddItem(self, item_sku, item_name, item_price, taxable):
"""Create item... | the_stack_v2_python_sparse | Class_2018-12-18/Class_Order_New.py | YuliyaKoldayeva/AR_VR_Specialist_Program_Python | train | 0 | |
8b21e392f5d54b43ece8cebe847f55c82b16b411 | [
"self.head = None\nself.tail = None\nself.capacity = capacity\nself.map = {}",
"if key in self.map:\n node = self.map[key]\n if self.tail == node:\n return node.val\n if self.head == node:\n q = node.next\n self.head = q\n q.prev = None\n node.next = None\n node.... | <|body_start_0|>
self.head = None
self.tail = None
self.capacity = capacity
self.map = {}
<|end_body_0|>
<|body_start_1|>
if key in self.map:
node = self.map[key]
if self.tail == node:
return node.val
if self.head == node:
... | LRUCache | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k_train_004738 | 2,729 | no_license | [
{
"docstring": ":type capacity: int",
"name": "__init__",
"signature": "def __init__(self, capacity)"
},
{
"docstring": ":type key: int :rtype: int",
"name": "get",
"signature": "def get(self, key)"
},
{
"docstring": ":type key: int :type value: int :rtype: None",
"name": "pu... | 3 | stack_v2_sparse_classes_30k_train_006195 | 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): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None | 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): :type key: int :rtype: int
- def put(self, key, value): :type key: int :type value: int :rtype: None
<|sk... | 1d8821da01c9c200732a6b7037b8631689e2f7e7 | <|skeleton|>
class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
<|body_0|>
def get(self, key):
""":type key: int :rtype: int"""
<|body_1|>
def put(self, key, value):
""":type key: int :type value: int :rtype: None"""
<|body_2|>
<|end_s... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.head = None
self.tail = None
self.capacity = capacity
self.map = {}
def get(self, key):
""":type key: int :rtype: int"""
if key in self.map:
node = self.map[key]
... | the_stack_v2_python_sparse | Leetcode0146.py | xiaojinghu/Leetcode | train | 0 | |
81152518d7634bb40b1211dd2618335e696f2908 | [
"cnt, currNode = (1, head)\nwhile currNode and cnt < n:\n currNode = currNode.next\n cnt += 1\nif not currNode:\n return None\nnewHead = currNode.next\ncurrNode.next = None\nreturn newHead",
"currNode = preHead\nwhile h1 and h2:\n if h1.val <= h2.val:\n currNode.next, h1 = (h1, h1.next)\n el... | <|body_start_0|>
cnt, currNode = (1, head)
while currNode and cnt < n:
currNode = currNode.next
cnt += 1
if not currNode:
return None
newHead = currNode.next
currNode.next = None
return newHead
<|end_body_0|>
<|body_start_1|>
c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
<|body_0|>
def _merge_list(self, h1: ListNode, h2: ListNode, preHead: ListNode) -> ListNode:
"""Merge two sorted lists a... | stack_v2_sparse_classes_10k_train_004739 | 2,292 | no_license | [
{
"docstring": "Cut the first n node from head and return the head of the remaining list.",
"name": "_cut_list",
"signature": "def _cut_list(self, head: ListNode, n: int) -> ListNode"
},
{
"docstring": "Merge two sorted lists and return the tail of the new list.",
"name": "_merge_list",
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _cut_list(self, head: ListNode, n: int) -> ListNode: Cut the first n node from head and return the head of the remaining list.
- def _merge_list(self, h1: ListNode, h2: ListN... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _cut_list(self, head: ListNode, n: int) -> ListNode: Cut the first n node from head and return the head of the remaining list.
- def _merge_list(self, h1: ListNode, h2: ListN... | edb870f83f0c4568cce0cacec04ee70cf6b545bf | <|skeleton|>
class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
<|body_0|>
def _merge_list(self, h1: ListNode, h2: ListNode, preHead: ListNode) -> ListNode:
"""Merge two sorted lists a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def _cut_list(self, head: ListNode, n: int) -> ListNode:
"""Cut the first n node from head and return the head of the remaining list."""
cnt, currNode = (1, head)
while currNode and cnt < n:
currNode = currNode.next
cnt += 1
if not currNode:
... | the_stack_v2_python_sparse | 2019/sort_list.py | eronekogin/leetcode | train | 0 | |
2a07bcc04983f593bda280931fc8d0c029d486ae | [
"if set(ransomNote) > set(magazine):\n return False\nres = list(ransomNote)\nfor i in list(magazine):\n if i in res:\n res.remove(i)\n else:\n pass\nif len(res) > 0:\n return False\nelse:\n return True",
"if set(ransomNote) > set(magazine):\n return False\nchar_dict = {}\nfor i in ... | <|body_start_0|>
if set(ransomNote) > set(magazine):
return False
res = list(ransomNote)
for i in list(magazine):
if i in res:
res.remove(i)
else:
pass
if len(res) > 0:
return False
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canConstruct(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_0|>
def canConstruct2(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_1|>
def can... | stack_v2_sparse_classes_10k_train_004740 | 2,064 | no_license | [
{
"docstring": ":type ransomNote: str :type magazine: str :rtype: bool",
"name": "canConstruct",
"signature": "def canConstruct(self, ransomNote, magazine)"
},
{
"docstring": ":type ransomNote: str :type magazine: str :rtype: bool",
"name": "canConstruct2",
"signature": "def canConstruct... | 3 | stack_v2_sparse_classes_30k_train_004548 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canConstruct(self, ransomNote, magazine): :type ransomNote: str :type magazine: str :rtype: bool
- def canConstruct2(self, ransomNote, magazine): :type ransomNote: str :type ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canConstruct(self, ransomNote, magazine): :type ransomNote: str :type magazine: str :rtype: bool
- def canConstruct2(self, ransomNote, magazine): :type ransomNote: str :type ... | 829f918a0d4d94da5fd3004768421974fbe056e7 | <|skeleton|>
class Solution:
def canConstruct(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_0|>
def canConstruct2(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
<|body_1|>
def can... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canConstruct(self, ransomNote, magazine):
""":type ransomNote: str :type magazine: str :rtype: bool"""
if set(ransomNote) > set(magazine):
return False
res = list(ransomNote)
for i in list(magazine):
if i in res:
res.remove(... | the_stack_v2_python_sparse | leetcode/easy/easy 201-400/383_赎金信.py | Weikoi/OJ_Python | train | 0 | |
c23ce6598da18687bd7ae46d14cb5d4914c503b6 | [
"self._basis_name = 'Kazhdan-Lusztig'\nCombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))\nE = M.E()\nphi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lower', unitriangular=True, key=M._lattice.... | <|body_start_0|>
self._basis_name = 'Kazhdan-Lusztig'
CombinatorialFreeModule.__init__(self, M.base_ring(), tuple(M._lattice), prefix=prefix, category=MoebiusAlgebraBases(M))
E = M.E()
phi = self.module_morphism(self._to_natural_basis, codomain=E, category=self.category(), triangular='lo... | The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW14]_. EXAMPLES: W... | KL | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ... | stack_v2_sparse_classes_10k_train_004741 | 26,467 | no_license | [
{
"docstring": "Initialize ``self``. TESTS:: sage: L = posets.BooleanLattice(4) sage: M = L.quantum_moebius_algebra() sage: TestSuite(M.KL()).run() # long time",
"name": "__init__",
"signature": "def __init__(self, M, prefix='KL')"
},
{
"docstring": "Convert the element indexed by ``x`` to the n... | 2 | null | Implement the Python class `KL` described below.
Class description:
The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn... | Implement the Python class `KL` described below.
Class description:
The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polyn... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class KL:
"""The Kazhdan-Lusztig basis of a quantum Möbius algebra. The Kazhdan-Lusztig basis `\\{ B_x \\mid x \\in L \\}` of `M_L` for some lattice `L` is defined by .. MATH:: B_x = \\sum_{y \\geq x} P_{x,y}(q) E_a, where `P_{x,y}(q)` is the Kazhdan-Lusztig polynomial of `L`, following the definition given in [EPW... | the_stack_v2_python_sparse | sage/src/sage/combinat/posets/moebius_algebra.py | bopopescu/geosci | train | 0 |
e97b4472dca75bd28c03c1898b4212599b78f3b3 | [
"self.B = 1.0 * 11.96\nself.energy = lambda j: self.B * j * (j + 1)\nself.degeneracy = lambda j: 2 * j + 1\nself.n0 = 0",
"t_list = np.array([300, 500, 1000, 1500, 2000])\nq_exp_list = np.array([208.8907, 347.9285, 695.5234, 1043.118, 1390.713])\nfor temperature, q_exp in zip(t_list, q_exp_list):\n q_act = get... | <|body_start_0|>
self.B = 1.0 * 11.96
self.energy = lambda j: self.B * j * (j + 1)
self.degeneracy = lambda j: 2 * j + 1
self.n0 = 0
<|end_body_0|>
<|body_start_1|>
t_list = np.array([300, 500, 1000, 1500, 2000])
q_exp_list = np.array([208.8907, 347.9285, 695.5234, 1043.... | Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1. | TestSchrodinger | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit... | stack_v2_sparse_classes_10k_train_004742 | 6,011 | permissive | [
{
"docstring": "A function run before each unit test in this class.",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test the get_partition_function() method.",
"name": "test_get_partition_function",
"signature": "def test_get_partition_function(self)"
},
{
"d... | 6 | stack_v2_sparse_classes_30k_train_007002 | Implement the Python class `TestSchrodinger` described below.
Class description:
Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1.
Method signatures and docst... | Implement the Python class `TestSchrodinger` described below.
Class description:
Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1.
Method signatures and docst... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestSchrodinger:
"""Contains unit tests of the various methods of the :mod:`schrodinger` module. The solution to the Schrodinger equation used for these tests is that of a linear rigid rotor with a rotational constant of 1 cm^-1."""
def setUp(self):
"""A function run before each unit test in this... | the_stack_v2_python_sparse | rmgpy/statmech/schrodingerTest.py | CanePan-cc/CanePanWorkshop | train | 2 |
93be7f01e7aaba9b4ce7a662b95a11163411ea2e | [
"print('Admin Verification Test')\nlogin = 'admin1'\nself.assertEqual(testVerifyLogin(login, login), True)",
"print('Login Verification Test')\nlogin = 'Engineer1'\nself.assertEqual(testCred(login, login), True)",
"print('Search Car By ID Test')\ncarID = '1'\nself.assertEqual(testCarID(carID), True)"
] | <|body_start_0|>
print('Admin Verification Test')
login = 'admin1'
self.assertEqual(testVerifyLogin(login, login), True)
<|end_body_0|>
<|body_start_1|>
print('Login Verification Test')
login = 'Engineer1'
self.assertEqual(testCred(login, login), True)
<|end_body_1|>
<|... | Function runs all Engineer Related Tests | TestStringMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
<|body_0|>
def test_cred(self):
"""Function runs test to verify Engineer Login"""
<|body_1|>
def test_carID(self):
... | stack_v2_sparse_classes_10k_train_004743 | 2,875 | no_license | [
{
"docstring": "Function runs test to verify Admin login",
"name": "test_login",
"signature": "def test_login(self)"
},
{
"docstring": "Function runs test to verify Engineer Login",
"name": "test_cred",
"signature": "def test_cred(self)"
},
{
"docstring": "Function runs test to f... | 3 | stack_v2_sparse_classes_30k_train_002452 | Implement the Python class `TestStringMethods` described below.
Class description:
Function runs all Engineer Related Tests
Method signatures and docstrings:
- def test_login(self): Function runs test to verify Admin login
- def test_cred(self): Function runs test to verify Engineer Login
- def test_carID(self): Func... | Implement the Python class `TestStringMethods` described below.
Class description:
Function runs all Engineer Related Tests
Method signatures and docstrings:
- def test_login(self): Function runs test to verify Admin login
- def test_cred(self): Function runs test to verify Engineer Login
- def test_carID(self): Func... | 0beee478e7a95ed052feb262d1e9fa9c0bf27981 | <|skeleton|>
class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
<|body_0|>
def test_cred(self):
"""Function runs test to verify Engineer Login"""
<|body_1|>
def test_carID(self):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
print('Admin Verification Test')
login = 'admin1'
self.assertEqual(testVerifyLogin(login, login), True)
def test_cred(self):
... | the_stack_v2_python_sparse | engineerTest.py | rmit-s3602584-peter-moorhead/IoTAssignment2 | train | 0 |
532d9299a3f8185a48be23a7104d3ab6ec0ee574 | [
"res = [0]\nfor i in range(1, num + 1):\n res.append((i & 1) + res[i >> 1])\nreturn res",
"s = [0]\nwhile len(s) <= num:\n s.extend([x + 1 for x in s])\nreturn s[:num + 1]"
] | <|body_start_0|>
res = [0]
for i in range(1, num + 1):
res.append((i & 1) + res[i >> 1])
return res
<|end_body_0|>
<|body_start_1|>
s = [0]
while len(s) <= num:
s.extend([x + 1 for x in s])
return s[:num + 1]
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = [0]
for i in range(1, num + 1):
... | stack_v2_sparse_classes_10k_train_004744 | 1,377 | no_license | [
{
"docstring": ":type num: int :rtype: List[int]",
"name": "countBits",
"signature": "def countBits(self, num)"
},
{
"docstring": ":type num: int :rtype: List[int]",
"name": "countBits2",
"signature": "def countBits2(self, num)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006020 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def countBits2(self, num): :type num: int :rtype: List[int] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def countBits(self, num): :type num: int :rtype: List[int]
- def countBits2(self, num): :type num: int :rtype: List[int]
<|skeleton|>
class Solution:
def countBits(self, nu... | 05e8f5a4e39d448eb333c813093fc7c1df4fc05e | <|skeleton|>
class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
<|body_0|>
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def countBits(self, num):
""":type num: int :rtype: List[int]"""
res = [0]
for i in range(1, num + 1):
res.append((i & 1) + res[i >> 1])
return res
def countBits2(self, num):
""":type num: int :rtype: List[int]"""
s = [0]
while... | the_stack_v2_python_sparse | leetcode_python/Math/counting-bits.py | DataEngDev/CS_basics | train | 0 | |
7517a3815c19aec69e44c85c554b61f4c07b5197 | [
"name = name.lower()\nproperties = filter(lambda property_: property_.name.lower() == name, self.property)\nif properties:\n return properties[0].value",
"name = name.lower()\nproperties = filter(lambda property_: property_.name.lower() == name, self.property)\nreturn properties and properties[0] or self._Empt... | <|body_start_0|>
name = name.lower()
properties = filter(lambda property_: property_.name.lower() == name, self.property)
if properties:
return properties[0].value
<|end_body_0|>
<|body_start_1|>
name = name.lower()
properties = filter(lambda property_: property_.nam... | Pattern class to be used as a base for xml node to py object translation | _ObjectifiedXmlNode_ | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _ObjectifiedXmlNode_:
"""Pattern class to be used as a base for xml node to py object translation"""
def getPropertyValueByName(self, name):
"""@types: str -> _ObjectifiedXmlNode_ or _EmptyCollection"""
<|body_0|>
def getPropertyByName(self, name):
"""Utility met... | stack_v2_sparse_classes_10k_train_004745 | 39,195 | no_license | [
{
"docstring": "@types: str -> _ObjectifiedXmlNode_ or _EmptyCollection",
"name": "getPropertyValueByName",
"signature": "def getPropertyValueByName(self, name)"
},
{
"docstring": "Utility method making it easy to grab properties defined in such manner <properties> <property name=\"n1\" value=\"... | 2 | null | Implement the Python class `_ObjectifiedXmlNode_` described below.
Class description:
Pattern class to be used as a base for xml node to py object translation
Method signatures and docstrings:
- def getPropertyValueByName(self, name): @types: str -> _ObjectifiedXmlNode_ or _EmptyCollection
- def getPropertyByName(sel... | Implement the Python class `_ObjectifiedXmlNode_` described below.
Class description:
Pattern class to be used as a base for xml node to py object translation
Method signatures and docstrings:
- def getPropertyValueByName(self, name): @types: str -> _ObjectifiedXmlNode_ or _EmptyCollection
- def getPropertyByName(sel... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class _ObjectifiedXmlNode_:
"""Pattern class to be used as a base for xml node to py object translation"""
def getPropertyValueByName(self, name):
"""@types: str -> _ObjectifiedXmlNode_ or _EmptyCollection"""
<|body_0|>
def getPropertyByName(self, name):
"""Utility met... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _ObjectifiedXmlNode_:
"""Pattern class to be used as a base for xml node to py object translation"""
def getPropertyValueByName(self, name):
"""@types: str -> _ObjectifiedXmlNode_ or _EmptyCollection"""
name = name.lower()
properties = filter(lambda property_: property_.name.lower... | the_stack_v2_python_sparse | reference/ucmdb/discovery/glassfish_discoverer.py | madmonkyang/cda-record | train | 0 |
ed92b882459bb173298447219338286e8d89f537 | [
"self._bytes_per_callback = start_bytes_per_callback\nself._callback_func = callback_func\nself._calls_per_exponent = calls_per_exponent\nself._max_bytes_per_callback = max_bytes_per_callback\nself._total_size = total_size\nself._bytes_processed_since_callback = 0\nself._callbacks_made = 0\nself._total_bytes_proces... | <|body_start_0|>
self._bytes_per_callback = start_bytes_per_callback
self._callback_func = callback_func
self._calls_per_exponent = calls_per_exponent
self._max_bytes_per_callback = max_bytes_per_callback
self._total_size = total_size
self._bytes_processed_since_callback ... | Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output. | ProgressCallbackWithBackoff | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBAC... | stack_v2_sparse_classes_10k_train_004746 | 7,111 | permissive | [
{
"docstring": "Initializes the callback with backoff. Args: total_size: Total bytes to process. If this is None, size is not known at the outset. callback_func: Func of (int: processed_so_far, int: total_bytes) used to make callbacks. start_bytes_per_callback: Lower bound of bytes per callback. max_bytes_per_c... | 2 | stack_v2_sparse_classes_30k_train_004783 | Implement the Python class `ProgressCallbackWithBackoff` described below.
Class description:
Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output.
Method signatures and docstrings:
- def __init__(self, total_size, callback_func, start_bytes_per_callback=_STA... | Implement the Python class `ProgressCallbackWithBackoff` described below.
Class description:
Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output.
Method signatures and docstrings:
- def __init__(self, total_size, callback_func, start_bytes_per_callback=_STA... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBAC... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ProgressCallbackWithBackoff:
"""Makes progress callbacks with exponential backoff to a maximum value. This prevents excessive log message output."""
def __init__(self, total_size, callback_func, start_bytes_per_callback=_START_BYTES_PER_CALLBACK, max_bytes_per_callback=_MAX_BYTES_PER_CALLBACK, calls_per_... | the_stack_v2_python_sparse | third_party/catapult/third_party/gsutil/gslib/progress_callback.py | metux/chromium-suckless | train | 5 |
fdb1d69cd5a706c1121f30d91d518436ba5b954c | [
"k %= len(nums)\nwhile k > 0:\n pre = nums[len(nums) - 1]\n for i in range(len(nums)):\n nums[i], pre = (pre, nums[i])\n k -= 1",
"k %= len(nums)\nwhile k > 0:\n e = nums.pop()\n nums.insert(0, e)\n k -= 1",
"def reverse(a, i, j):\n \"\"\"\n 数组反转操作\n a:数... | <|body_start_0|>
k %= len(nums)
while k > 0:
pre = nums[len(nums) - 1]
for i in range(len(nums)):
nums[i], pre = (pre, nums[i])
k -= 1
<|end_body_0|>
<|body_start_1|>
k %= len(nums)
while k > 0:
e = nums.pop()
n... | 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。 要求使用空... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可... | stack_v2_sparse_classes_10k_train_004747 | 3,307 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything, modify nums in-place instead. 时间复杂度:O(k * n) 空间复杂度:O(1)",
"name": "rotate1",
"signature": "def rotate1(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: None Do not return anything... | 3 | null | Implement the Python class `Solution` described below.
Class description:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,... | Implement the Python class `Solution` described below.
Class description:
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,... | 2c534185854c1a6f5ffdb2698f9db9989f30a25b | <|skeleton|>
class Solution:
"""给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
"""给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3 输出: [5,6,7,1,2,3,4] 解释: 向右旋转 1 步: [7,1,2,3,4,5,6] 向右旋转 2 步: [6,7,1,2,3,4,5] 向右旋转 3 步: [5,6,7,1,2,3,4] 示例 2: 输入: [-1,-100,3,99] 和 k = 2 输出: [3,99,-1,-100] 解释: 向右旋转 1 步: [99,-1,-100,3] 向右旋转 2 步: [3,99,-1,-100] 说明: 尽可能想出更多的解决方案,至少... | the_stack_v2_python_sparse | Week 01/id_668/leetcode_189_668.py | Carryours/algorithm004-03 | train | 2 |
82ba59cb5ccc331af05d3cf2014a300eebea8f3e | [
"if not (obj and len(Variable.objects.filter(version=obj))):\n return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)\nelse:\n return ((None, {'fields': ('name', 'application'), 'description': '<div style=\"font-size: 16px;color: red;\">This version will be deleted when all linked variables will be del... | <|body_start_0|>
if not (obj and len(Variable.objects.filter(version=obj))):
return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)
else:
return ((None, {'fields': ('name', 'application'), 'description': '<div style="font-size: 16px;color: red;">This version will be delete... | VersionAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Do not display delete button if some tests / variables are linked to thi... | stack_v2_sparse_classes_10k_train_004748 | 21,881 | permissive | [
{
"docstring": "Display error message when it's impossible to delete the version",
"name": "get_fieldsets",
"signature": "def get_fieldsets(self, request, obj=None)"
},
{
"docstring": "Do not display delete button if some tests / variables are linked to this application",
"name": "has_delete... | 3 | stack_v2_sparse_classes_30k_train_004897 | Implement the Python class `VersionAdmin` described below.
Class description:
Implement the VersionAdmin class.
Method signatures and docstrings:
- def get_fieldsets(self, request, obj=None): Display error message when it's impossible to delete the version
- def has_delete_permission(self, request, obj=None): Do not ... | Implement the Python class `VersionAdmin` described below.
Class description:
Implement the VersionAdmin class.
Method signatures and docstrings:
- def get_fieldsets(self, request, obj=None): Display error message when it's impossible to delete the version
- def has_delete_permission(self, request, obj=None): Do not ... | 590c84d5078fee4021fa23956390eb612b5f123d | <|skeleton|>
class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
<|body_0|>
def has_delete_permission(self, request, obj=None):
"""Do not display delete button if some tests / variables are linked to thi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VersionAdmin:
def get_fieldsets(self, request, obj=None):
"""Display error message when it's impossible to delete the version"""
if not (obj and len(Variable.objects.filter(version=obj))):
return admin.ModelAdmin.get_fieldsets(self, request, obj=obj)
else:
retur... | the_stack_v2_python_sparse | variableServer/admin.py | bhecquet/seleniumRobot-server | train | 0 | |
d2d24f980e2cb83970763d43d62afb750cbadbbb | [
"if cartan_type is None:\n cartan_type = parent.domain().cartan_type()\nif isinstance(on_gens, dict):\n gens = on_gens.keys()\nI = cartan_type.index_set()\nif gens is None:\n if cartan_type == parent.domain().cartan_type():\n gens = parent.domain().highest_weight_vectors()\n else:\n gens =... | <|body_start_0|>
if cartan_type is None:
cartan_type = parent.domain().cartan_type()
if isinstance(on_gens, dict):
gens = on_gens.keys()
I = cartan_type.index_set()
if gens is None:
if cartan_type == parent.domain().cartan_type():
gens ... | A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the domain under ``self`` - ``cartan_type`` -- (optional) a ... | HighestWeightCrystalMorphism | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the ... | stack_v2_sparse_classes_10k_train_004749 | 27,195 | no_license | [
{
"docstring": "Construct a crystal morphism. TESTS:: sage: B = crystals.infinity.Tableaux(['B',2]) sage: C = crystals.infinity.NakajimaMonomials(['B',2]) sage: psi = B.crystal_morphism(C.module_generators) sage: B = crystals.Tableaux(['B',3], shape=[1]) sage: C = crystals.Tableaux(['D',4], shape=[2]) sage: H =... | 2 | null | Implement the Python class `HighestWeightCrystalMorphism` described below.
Class description:
A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order o... | Implement the Python class `HighestWeightCrystalMorphism` described below.
Class description:
A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order o... | 0d9eacbf74e2acffefde93e39f8bcbec745cdaba | <|skeleton|>
class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HighestWeightCrystalMorphism:
"""A virtual crystal morphism whose domain is a highest weight crystal. INPUT: - ``parent`` -- a homset - ``on_gens`` -- a function or list that determines the image of the generators (if given a list, then this uses the order of the generators of the domain) of the domain under ... | the_stack_v2_python_sparse | sage/src/sage/categories/highest_weight_crystals.py | bopopescu/geosci | train | 0 |
3fd0f8a80e2687472efde5a91ec8037e95c57006 | [
"data = self.data\nid_ = data['entity']['id']\nreturn f'{PLATFORM_URL}assignments/{id_}'",
"available = super().available\ndata = self.data\nto_role = data['to_role']\nreturn to_role == 'professional_user' and available"
] | <|body_start_0|>
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}assignments/{id_}'
<|end_body_0|>
<|body_start_1|>
available = super().available
data = self.data
to_role = data['to_role']
return to_role == 'professional_user' and available
<|e... | Email to creative on new comment created. | CommentCreatedToCreative | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004750 | 5,020 | no_license | [
{
"docstring": "Action URL.",
"name": "action_url",
"signature": "def action_url(self) -> str"
},
{
"docstring": "Check if this action is available.",
"name": "available",
"signature": "def available(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_003773 | Implement the Python class `CommentCreatedToCreative` described below.
Class description:
Email to creative on new comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available. | Implement the Python class `CommentCreatedToCreative` described below.
Class description:
Email to creative on new comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available.
<|skeleton|>
class CommentCreatedToCreativ... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentCreatedToCreative:
"""Email to creative on new comment created."""
def action_url(self) -> str:
"""Action URL."""
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}assignments/{id_}'
def available(self) -> bool:
"""Check if this action ... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/leica/comment.py | BriefyHQ/briefy.choreographer | train | 0 |
117e75740ee7c71cd1e74773aeb9b69bb94cdc61 | [
"opts = SCons.Variables.Variables()\nopts.Add(SCons.Variables.BoolVariable('test', 'test option help', False))\no = opts.options[0]\nassert o.key == 'test', o.key\nassert o.help == 'test option help (yes|no)', o.help\nassert o.default == 0, o.default\nassert o.validator is not None, o.validator\nassert o.converter ... | <|body_start_0|>
opts = SCons.Variables.Variables()
opts.Add(SCons.Variables.BoolVariable('test', 'test option help', False))
o = opts.options[0]
assert o.key == 'test', o.key
assert o.help == 'test option help (yes|no)', o.help
assert o.default == 0, o.default
as... | BoolVariableTestCase | [
"MIT",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoolVariableTestCase:
def test_BoolVariable(self) -> None:
"""Test BoolVariable creation"""
<|body_0|>
def test_converter(self) -> None:
"""Test the BoolVariable converter"""
<|body_1|>
def test_validator(self) -> None:
"""Test the BoolVariable v... | stack_v2_sparse_classes_10k_train_004751 | 3,899 | permissive | [
{
"docstring": "Test BoolVariable creation",
"name": "test_BoolVariable",
"signature": "def test_BoolVariable(self) -> None"
},
{
"docstring": "Test the BoolVariable converter",
"name": "test_converter",
"signature": "def test_converter(self) -> None"
},
{
"docstring": "Test the ... | 3 | null | Implement the Python class `BoolVariableTestCase` described below.
Class description:
Implement the BoolVariableTestCase class.
Method signatures and docstrings:
- def test_BoolVariable(self) -> None: Test BoolVariable creation
- def test_converter(self) -> None: Test the BoolVariable converter
- def test_validator(s... | Implement the Python class `BoolVariableTestCase` described below.
Class description:
Implement the BoolVariableTestCase class.
Method signatures and docstrings:
- def test_BoolVariable(self) -> None: Test BoolVariable creation
- def test_converter(self) -> None: Test the BoolVariable converter
- def test_validator(s... | b2a7d7066a2b854460a334a5fe737ea389655e6e | <|skeleton|>
class BoolVariableTestCase:
def test_BoolVariable(self) -> None:
"""Test BoolVariable creation"""
<|body_0|>
def test_converter(self) -> None:
"""Test the BoolVariable converter"""
<|body_1|>
def test_validator(self) -> None:
"""Test the BoolVariable v... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BoolVariableTestCase:
def test_BoolVariable(self) -> None:
"""Test BoolVariable creation"""
opts = SCons.Variables.Variables()
opts.Add(SCons.Variables.BoolVariable('test', 'test option help', False))
o = opts.options[0]
assert o.key == 'test', o.key
assert o.he... | the_stack_v2_python_sparse | SCons/Variables/BoolVariableTests.py | SCons/scons | train | 1,827 | |
52e8eaf16312bf980de315a05168cab3f1770839 | [
"self.numbers = nums\nself.length = len(self.numbers)\nif self.length > 0:\n self.seglength = 2 ** (int(math.log(self.length << 1, 2)) + 1) - 1\n print(self.seglength)\nelse:\n self.seglength = 0\nself.segtree = [0] * self.seglength\n\ndef seg_tree():\n\n def __seg_tree(seg, i, s, e, a, n):\n if ... | <|body_start_0|>
self.numbers = nums
self.length = len(self.numbers)
if self.length > 0:
self.seglength = 2 ** (int(math.log(self.length << 1, 2)) + 1) - 1
print(self.seglength)
else:
self.seglength = 0
self.segtree = [0] * self.seglength
... | NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k_train_004752 | 2,826 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: int :type j: int :rtype:... | 3bfee704adb1d94efc8e531b732cf06c4f8aef0f | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_2|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.numbers = nums
self.length = len(self.numbers)
if self.length > 0:
self.seglength = 2 ** (int(math.log(self.length << 1, 2)) + 1) - 1
print(self.seglength)
else:
sel... | the_stack_v2_python_sparse | rangequery.py | zopepy/leetcode | train | 0 | |
bea53f239bec18e6712a642e62da2a2be538149a | [
"for font in fonts:\n if font not in cls._fonts:\n cls._fonts[font] = _Font()\n cls._fonts[font].replace(cls._create_font(fonts[font], 16))\nif not cls._fonts['widget']:\n cls._fonts['widget'].replace(cls._create_font('Arial', 16))\nif not cls._fonts['title']:\n name = fonts['widget'] if 'widget'... | <|body_start_0|>
for font in fonts:
if font not in cls._fonts:
cls._fonts[font] = _Font()
cls._fonts[font].replace(cls._create_font(fonts[font], 16))
if not cls._fonts['widget']:
cls._fonts['widget'].replace(cls._create_font('Arial', 16))
if no... | Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r,g,b) tuple, containing the default font colour. | Font | [
"MIT",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Font:
"""Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r,g,b) tuple, containing the default fon... | stack_v2_sparse_classes_10k_train_004753 | 13,593 | permissive | [
{
"docstring": "Set fonts to a specific font. If a font exists, it will be replaced, otherwise it will be newly created. Args: fonts: Dictionary containing fonts to use. Key should be name of font. Value should be string naming either custom FreeType or a system font.",
"name": "set_fonts",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_001112 | Implement the Python class `Font` described below.
Class description:
Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r... | Implement the Python class `Font` described below.
Class description:
Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r... | 95cb53b664f312e0830f010c0c96be94d4a4db90 | <|skeleton|>
class Font:
"""Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r,g,b) tuple, containing the default fon... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Font:
"""Class containing fonts available for use. Index class to get fonts, such as ``Font["widget"]`` for the widget font. The default fonts are: widget: The default font for widgets. title: A larger title font. mono: A monospaced font. Attributes: col: (r,g,b) tuple, containing the default font colour."""
... | the_stack_v2_python_sparse | pygame/GUI- widgets-SGC/sgc3/widgets/_locals.py | furas/python-examples | train | 176 |
4d7be19923471af86b84cb5846e86b47593db6ef | [
"self.model = ViewCls()\nif weight_path:\n self.model.load_weights(weight_path)\nself.labels = ['PA', 'Lateral', 'Others']",
"imgo = np.squeeze(sitk.GetArrayFromImage(sitk.ReadImage(path)))\nimg = cv2.resize(imgo, (512, 512), interpolation=cv2.INTER_LINEAR)\nimg = img.astype(np.float32)\nimg -= np.min(img)\nim... | <|body_start_0|>
self.model = ViewCls()
if weight_path:
self.model.load_weights(weight_path)
self.labels = ['PA', 'Lateral', 'Others']
<|end_body_0|>
<|body_start_1|>
imgo = np.squeeze(sitk.GetArrayFromImage(sitk.ReadImage(path)))
img = cv2.resize(imgo, (512, 512), i... | ViewpointClassifier | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
<|body_0|>
def _preprocessing(self, path: str) -> Tuple[np.array, np.array]:
"""Args: (str... | stack_v2_sparse_classes_10k_train_004754 | 13,351 | permissive | [
{
"docstring": "Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)",
"name": "__init__",
"signature": "def __init__(self, weight_path: Optional[str]=None)"
},
{
"docstring": "Args: (string) path : dicom path Return: (numpy ndarray) imgo : original im... | 3 | stack_v2_sparse_classes_30k_train_000291 | Implement the Python class `ViewpointClassifier` described below.
Class description:
Implement the ViewpointClassifier class.
Method signatures and docstrings:
- def __init__(self, weight_path: Optional[str]=None): Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)
- def ... | Implement the Python class `ViewpointClassifier` described below.
Class description:
Implement the ViewpointClassifier class.
Method signatures and docstrings:
- def __init__(self, weight_path: Optional[str]=None): Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)
- def ... | 158a74985074f95fcd6a345c310903936dd2adbe | <|skeleton|>
class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
<|body_0|>
def _preprocessing(self, path: str) -> Tuple[np.array, np.array]:
"""Args: (str... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ViewpointClassifier:
def __init__(self, weight_path: Optional[str]=None):
"""Classifying PA / Lateral / Others Args: (string) weight_path : pretrained weight path (optional)"""
self.model = ViewCls()
if weight_path:
self.model.load_weights(weight_path)
self.labels =... | the_stack_v2_python_sparse | medimodule/Chest/module.py | mi2rl/MI2RLNet | train | 13 | |
28d6a9a10a0b274e648341250c3e7fd98ebf4bd5 | [
"self.profile_id = profile_id\nself.motion_based_retention_enabled = motion_based_retention_enabled\nself.audio_recording_enabled = audio_recording_enabled\nself.restricted_bandwidth_mode_enabled = restricted_bandwidth_mode_enabled\nself.quality = quality\nself.resolution = resolution",
"if dictionary is None:\n ... | <|body_start_0|>
self.profile_id = profile_id
self.motion_based_retention_enabled = motion_based_retention_enabled
self.audio_recording_enabled = audio_recording_enabled
self.restricted_bandwidth_mode_enabled = restricted_bandwidth_mode_enabled
self.quality = quality
self... | Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the camera. The profile's settings will override all of the per-camera quality and retention settings. If the value of t... | UpdateDeviceCameraQualityAndRetentionSettingsModel | [
"MIT",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UpdateDeviceCameraQualityAndRetentionSettingsModel:
"""Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the camera. The profile's settings will ov... | stack_v2_sparse_classes_10k_train_004755 | 4,063 | permissive | [
{
"docstring": "Constructor for the UpdateDeviceCameraQualityAndRetentionSettingsModel class",
"name": "__init__",
"signature": "def __init__(self, profile_id=None, motion_based_retention_enabled=None, audio_recording_enabled=None, restricted_bandwidth_mode_enabled=None, quality=None, resolution=None)"
... | 2 | null | Implement the Python class `UpdateDeviceCameraQualityAndRetentionSettingsModel` described below.
Class description:
Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the... | Implement the Python class `UpdateDeviceCameraQualityAndRetentionSettingsModel` described below.
Class description:
Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the... | 9894089eb013318243ae48869cc5130eb37f80c0 | <|skeleton|>
class UpdateDeviceCameraQualityAndRetentionSettingsModel:
"""Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the camera. The profile's settings will ov... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UpdateDeviceCameraQualityAndRetentionSettingsModel:
"""Implementation of the 'updateDeviceCameraQualityAndRetentionSettings' model. TODO: type model description here. Attributes: profile_id (string): The ID of a quality and retention profile to assign to the camera. The profile's settings will override all of... | the_stack_v2_python_sparse | meraki_sdk/models/update_device_camera_quality_and_retention_settings_model.py | RaulCatalano/meraki-python-sdk | train | 1 |
2e04aaffcde30da03f3a82872653c079825cd4bc | [
"if not sonority_hierarchy and lang == 'en':\n sonority_hierarchy = ['aeiouy', 'lmnrw', 'zvsf', 'bcdgtkpqxhj']\nself.vowels = sonority_hierarchy[0]\nself.phoneme_map = {}\nfor i, level in enumerate(sonority_hierarchy):\n for c in level:\n sonority_level = len(sonority_hierarchy) - i\n self.phone... | <|body_start_0|>
if not sonority_hierarchy and lang == 'en':
sonority_hierarchy = ['aeiouy', 'lmnrw', 'zvsf', 'bcdgtkpqxhj']
self.vowels = sonority_hierarchy[0]
self.phoneme_map = {}
for i, level in enumerate(sonority_hierarchy):
for c in level:
so... | Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', 'ca', 'tion'] >>> text = "This is a foobar-like sentence." >>> [SSP.tokenize(token) f... | SyllableTokenizer | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-NC-ND-3.0",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SyllableTokenizer:
"""Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', 'ca', 'tion'] >>> text = "This is a foob... | stack_v2_sparse_classes_10k_train_004756 | 7,545 | permissive | [
{
"docstring": ":param lang: Language parameter, default is English, 'en' :type lang: str :param sonority_hierarchy: Sonority hierarchy according to the Sonority Sequencing Principle. :type sonority_hierarchy: list(str)",
"name": "__init__",
"signature": "def __init__(self, lang='en', sonority_hierarchy... | 4 | null | Implement the Python class `SyllableTokenizer` described below.
Class description:
Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', '... | Implement the Python class `SyllableTokenizer` described below.
Class description:
Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', '... | 582e6e35f0e6c984b44ec49dcb8846d9c011d0a8 | <|skeleton|>
class SyllableTokenizer:
"""Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', 'ca', 'tion'] >>> text = "This is a foob... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SyllableTokenizer:
"""Syllabifies words based on the Sonority Sequencing Principle (SSP). >>> from nltk.tokenize import SyllableTokenizer >>> from nltk import word_tokenize >>> SSP = SyllableTokenizer() >>> SSP.tokenize('justification') ['jus', 'ti', 'fi', 'ca', 'tion'] >>> text = "This is a foobar-like sente... | the_stack_v2_python_sparse | nltk/tokenize/sonority_sequencing.py | nltk/nltk | train | 11,860 |
b01de4ea5e563302e3767e3e496e174375528793 | [
"lb = random.randint(0, int(len(offspring) / 2))\nub = random.randint(lb + 1, len(offspring) - 1)\nnew_offspring = offspring.copy()\nnew_offspring[lb] = offspring[ub]\nnew_offspring[ub] = offspring[lb]\noffspring = np.array(new_offspring)\nreturn offspring",
"lb = random.randint(0, int(len(offspring) / 2))\nub = ... | <|body_start_0|>
lb = random.randint(0, int(len(offspring) / 2))
ub = random.randint(lb + 1, len(offspring) - 1)
new_offspring = offspring.copy()
new_offspring[lb] = offspring[ub]
new_offspring[ub] = offspring[lb]
offspring = np.array(new_offspring)
return offspri... | Permutation - Mutation class | PermMutation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
<|body_0|>
def insert(offspring):
"""Insert mutation approach... | stack_v2_sparse_classes_10k_train_004757 | 3,795 | no_license | [
{
"docstring": "Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring",
"name": "swap",
"signature": "def swap(offspring)"
},
{
"docstring": "Insert mutation approach Args: offspring (list): Offspring to be mutated Returns: ... | 6 | stack_v2_sparse_classes_30k_train_006860 | Implement the Python class `PermMutation` described below.
Class description:
Permutation - Mutation class
Method signatures and docstrings:
- def swap(offspring): Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring
- def insert(offspring): Ins... | Implement the Python class `PermMutation` described below.
Class description:
Permutation - Mutation class
Method signatures and docstrings:
- def swap(offspring): Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring
- def insert(offspring): Ins... | cd11a700ebcf952f077f44025e83881deee82346 | <|skeleton|>
class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
<|body_0|>
def insert(offspring):
"""Insert mutation approach... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
lb = random.randint(0, int(len(offspring) / 2))
ub = random.randint(lb + 1, len... | the_stack_v2_python_sparse | src/heuristics/game/operators/perm/mutation.py | raphaeldscorrea/GeneticAlgorithmVectorized | train | 0 |
93b2672e00d2ecace8046d2daca17449173d9003 | [
"super(PositionEmbedding, self).__init__()\nself.dim = dim\nself.freq = freq",
"device = inputs.device\nmax_length = inputs.shape[1]\nembedding_store = PositionEmbedding._embeddings.__dict__\ndevice_store = embedding_store.get(device, {})\nif not device_store or self.dim not in device_store or device_store[self.d... | <|body_start_0|>
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
<|end_body_0|>
<|body_start_1|>
device = inputs.device
max_length = inputs.shape[1]
embedding_store = PositionEmbedding._embeddings.__dict__
device_store = embedding_store.... | Produce position embeddings | PositionEmbedding | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_10k_train_004758 | 3,716 | permissive | [
{
"docstring": "Initialize the PositionEmbedding",
"name": "__init__",
"signature": "def __init__(self, dim, freq=10000.0)"
},
{
"docstring": "Implement the forward pass of the embedding",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006657 | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding | Implement the Python class `PositionEmbedding` described below.
Class description:
Produce position embeddings
Method signatures and docstrings:
- def __init__(self, dim, freq=10000.0): Initialize the PositionEmbedding
- def forward(self, inputs): Implement the forward pass of the embedding
<|skeleton|>
class Positi... | 0fa4adffa825af4a62b6e739b59c4125a7b6698e | <|skeleton|>
class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
<|body_0|>
def forward(self, inputs):
"""Implement the forward pass of the embedding"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PositionEmbedding:
"""Produce position embeddings"""
def __init__(self, dim, freq=10000.0):
"""Initialize the PositionEmbedding"""
super(PositionEmbedding, self).__init__()
self.dim = dim
self.freq = freq
def forward(self, inputs):
"""Implement the forward pas... | the_stack_v2_python_sparse | models/embeddings.py | fallcat/synst | train | 1 |
00c14cb5bd0632b595243826eff880a6fc1add65 | [
"self.pump = Pump('127.0.0.1', 8000)\nself.decider = Decider(100, 0.05)\nself.sensor = Sensor('127.0.0.1', '8001')\nself.controller = Controller(self.sensor, self.pump, self.decider)\nself.actions = self.controller.actions",
"self.assertEqual(self.decider.decide(90, self.actions['PUMP_OFF'], self.actions), self.a... | <|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.sensor = Sensor('127.0.0.1', '8001')
self.controller = Controller(self.sensor, self.pump, self.decider)
self.actions = self.controller.actions
<|end_body_0|>
<|body_start_1|>
self... | Unit tests for the Decider class | DeciderTests | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
<|body_0|>
def test_decider(self):
"""Decider tests"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pump = Pump('127.0.0.1', 8000)
self.decider = Deci... | stack_v2_sparse_classes_10k_train_004759 | 3,712 | no_license | [
{
"docstring": "setup",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Decider tests",
"name": "test_decider",
"signature": "def test_decider(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001589 | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def setUp(self): setup
- def test_decider(self): Decider tests | Implement the Python class `DeciderTests` described below.
Class description:
Unit tests for the Decider class
Method signatures and docstrings:
- def setUp(self): setup
- def test_decider(self): Decider tests
<|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"... | 263685ca90110609bfd05d621516727f8cd0028f | <|skeleton|>
class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
<|body_0|>
def test_decider(self):
"""Decider tests"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeciderTests:
"""Unit tests for the Decider class"""
def setUp(self):
"""setup"""
self.pump = Pump('127.0.0.1', 8000)
self.decider = Decider(100, 0.05)
self.sensor = Sensor('127.0.0.1', '8001')
self.controller = Controller(self.sensor, self.pump, self.decider)
... | the_stack_v2_python_sparse | students/msirisha/lesson06/water-regulation/waterregulation/tests.py | aurel1212/Sp2018-Online | train | 0 |
240396d6192d944ea6a8f39385c0ecbd62e67128 | [
"super(_HashDropZones, self).__init__(parent)\npen = qt.QPen()\npen.setColor(qt.QColor('#D0D0D0'))\npen.setStyle(qt.Qt.DotLine)\npen.setWidth(2)\nself.__dropPen = pen",
"displayDropZone = False\nif index.isValid():\n model = index.model()\n rowIndex = model.index(index.row(), 0, index.parent())\n rowItem... | <|body_start_0|>
super(_HashDropZones, self).__init__(parent)
pen = qt.QPen()
pen.setColor(qt.QColor('#D0D0D0'))
pen.setStyle(qt.Qt.DotLine)
pen.setWidth(2)
self.__dropPen = pen
<|end_body_0|>
<|body_start_1|>
displayDropZone = False
if index.isValid():
... | Delegate item displaying a drop zone when the item do not contains dataset. | _HashDropZones | [
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"CC0-1.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _HashDropZones:
"""Delegate item displaying a drop zone when the item do not contains dataset."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def paint(self, painter, option, index):
"""Paint the item :param qt.QPainter painter: A painter :param... | stack_v2_sparse_classes_10k_train_004760 | 34,928 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Paint the item :param qt.QPainter painter: A painter :param qt.QStyleOptionViewItem option: Options of the item to paint :param qt.QModelIndex index: Index of the item to paint",
... | 2 | null | Implement the Python class `_HashDropZones` described below.
Class description:
Delegate item displaying a drop zone when the item do not contains dataset.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def paint(self, painter, option, index): Paint the item :param qt.QPainter pain... | Implement the Python class `_HashDropZones` described below.
Class description:
Delegate item displaying a drop zone when the item do not contains dataset.
Method signatures and docstrings:
- def __init__(self, parent=None): Constructor
- def paint(self, painter, option, index): Paint the item :param qt.QPainter pain... | 5e33cb69afd2a8b1cfe3183282acdd8b34c1a74f | <|skeleton|>
class _HashDropZones:
"""Delegate item displaying a drop zone when the item do not contains dataset."""
def __init__(self, parent=None):
"""Constructor"""
<|body_0|>
def paint(self, painter, option, index):
"""Paint the item :param qt.QPainter painter: A painter :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _HashDropZones:
"""Delegate item displaying a drop zone when the item do not contains dataset."""
def __init__(self, parent=None):
"""Constructor"""
super(_HashDropZones, self).__init__(parent)
pen = qt.QPen()
pen.setColor(qt.QColor('#D0D0D0'))
pen.setStyle(qt.Qt.D... | the_stack_v2_python_sparse | src/silx/app/view/CustomNxdataWidget.py | silx-kit/silx | train | 120 |
c7482a4492bc592cc99600fee56a50122fb06b53 | [
"self.kw = kwargs\nStep.__init__(self, *args, routine=routine, **kwargs)\nt1_settings = self.parse_settings(self.get_requested_settings())\nqbcal.T1.__init__(self, dev=self.dev, **t1_settings)",
"kwargs = {}\ntask_list = []\nfor qb in self.qubits:\n task = {}\n task_list_fields = requested_kwargs['task_list... | <|body_start_0|>
self.kw = kwargs
Step.__init__(self, *args, routine=routine, **kwargs)
t1_settings = self.parse_settings(self.get_requested_settings())
qbcal.T1.__init__(self, dev=self.dev, **t1_settings)
<|end_body_0|>
<|body_start_1|>
kwargs = {}
task_list = []
... | A wrapper class for the T1 experiment. | T1Step | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T1Step:
"""A wrapper class for the T1 experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits to b... | stack_v2_sparse_classes_10k_train_004761 | 48,290 | permissive | [
{
"docstring": "Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits to be used in the routine. Configuration parameters (coming from the configuration parameter dictionary): transition_n... | 4 | stack_v2_sparse_classes_30k_train_000238 | Implement the Python class `T1Step` described below.
Class description:
A wrapper class for the T1 experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent ... | Implement the Python class `T1Step` described below.
Class description:
A wrapper class for the T1 experiment.
Method signatures and docstrings:
- def __init__(self, routine, *args, **kwargs): Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent ... | bc6733d774fe31a23f4c7e73e5eb0beed8d30e7d | <|skeleton|>
class T1Step:
"""A wrapper class for the T1 experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits to b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class T1Step:
"""A wrapper class for the T1 experiment."""
def __init__(self, routine, *args, **kwargs):
"""Initializes the T1Step class, which also includes initialization of the T1 experiment. Arguments: routine (Step): The parent routine. Keyword args: qubits (list): List of qubits to be used in the... | the_stack_v2_python_sparse | pycqed/measurement/calibration/automatic_calibration_routines/single_qubit_routines.py | QudevETH/PycQED_py3 | train | 8 |
98684cecab5835f9a205d111dc364250334865dd | [
"super(L2Norm, self).__init__()\nself.n_dims = n_dims\nself.weight = nn.Parameter(torch.Tensor(self.n_dims))\nself.eps = eps\nself.scale = scale",
"x_float = x.float()\nnorm = x_float.pow(2).sum(1, keepdim=True).sqrt() + self.eps\nreturn (self.weight[None, :, None, None].float().expand_as(x_float) * x_float / nor... | <|body_start_0|>
super(L2Norm, self).__init__()
self.n_dims = n_dims
self.weight = nn.Parameter(torch.Tensor(self.n_dims))
self.eps = eps
self.scale = scale
<|end_body_0|>
<|body_start_1|>
x_float = x.float()
norm = x_float.pow(2).sum(1, keepdim=True).sqrt() + se... | L2Norm | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
<|body_0|>
d... | stack_v2_sparse_classes_10k_train_004762 | 4,901 | permissive | [
{
"docstring": "L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10.",
"name": "__init__",
"signature": "def __init__(self, n_dims, scale=20.0, eps=1e-10)"
}... | 2 | null | Implement the Python class `L2Norm` described below.
Class description:
Implement the L2Norm class.
Method signatures and docstrings:
- def __init__(self, n_dims, scale=20.0, eps=1e-10): L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (fl... | Implement the Python class `L2Norm` described below.
Class description:
Implement the L2Norm class.
Method signatures and docstrings:
- def __init__(self, n_dims, scale=20.0, eps=1e-10): L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (fl... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
<|body_0|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class L2Norm:
def __init__(self, n_dims, scale=20.0, eps=1e-10):
"""L2 normalization layer. Args: n_dims (int): Number of dimensions to be normalized scale (float, optional): Defaults to 20.. eps (float, optional): Used to avoid division by zero. Defaults to 1e-10."""
super(L2Norm, self).__init__()
... | the_stack_v2_python_sparse | ai/mmdetection/mmdet/models/necks/ssd_neck.py | alldatacenter/alldata | train | 774 | |
366ee082bf2e77b2a20dd99b7e2885ca3111e68a | [
"self.is_system_defined = is_system_defined\nself.name = name\nself.pattern = pattern\nself.pattern_type = pattern_type",
"if dictionary is None:\n return None\nis_system_defined = dictionary.get('isSystemDefined')\nname = dictionary.get('name')\npattern = dictionary.get('pattern')\npattern_type = dictionary.g... | <|body_start_0|>
self.is_system_defined = is_system_defined
self.name = name
self.pattern = pattern
self.pattern_type = pattern_type
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_system_defined = dictionary.get('isSystemDefined')
... | Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether the pattern has been defined by the system or the user. name (string): Specifies t... | SupportedPattern | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SupportedPattern:
"""Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether the pattern has been defined by the sy... | stack_v2_sparse_classes_10k_train_004763 | 2,430 | permissive | [
{
"docstring": "Constructor for the SupportedPattern class",
"name": "__init__",
"signature": "def __init__(self, is_system_defined=None, name=None, pattern=None, pattern_type=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionar... | 2 | stack_v2_sparse_classes_30k_train_003244 | Implement the Python class `SupportedPattern` described below.
Class description:
Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether... | Implement the Python class `SupportedPattern` described below.
Class description:
Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SupportedPattern:
"""Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether the pattern has been defined by the sy... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SupportedPattern:
"""Implementation of the 'SupportedPattern' model. Specifies details of the pattern available for search available in an application such as Pattern Finder within Analytics Work Bench. Attributes: is_system_defined (bool): Specifies whether the pattern has been defined by the system or the u... | the_stack_v2_python_sparse | cohesity_management_sdk/models/supported_pattern.py | cohesity/management-sdk-python | train | 24 |
c9adfed3d855b5e057a9114f9cc857c2a9e0d79b | [
"super(FCNNPytorch, self).__init__()\nself.input_size = args.input_size\nself.num_classes = args.num_classes\nself.in_channels = args.in_channels\nself.dtype = args.dtype\nself.kernel_sizes = kernel_sizes\nself.out_channels = out_channels\nself.strides = strides\nself.conv_type = args.conv_type\nself.is_debug = arg... | <|body_start_0|>
super(FCNNPytorch, self).__init__()
self.input_size = args.input_size
self.num_classes = args.num_classes
self.in_channels = args.in_channels
self.dtype = args.dtype
self.kernel_sizes = kernel_sizes
self.out_channels = out_channels
self.st... | FCNNPytorch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_siz... | stack_v2_sparse_classes_10k_train_004764 | 3,878 | permissive | [
{
"docstring": "Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_sizes: the sizes of the kernels in each conv layer. :param out_channels: the number of filters for each conv layer. :param str... | 3 | stack_v2_sparse_classes_30k_train_006893 | Implement the Python class `FCNNPytorch` described below.
Class description:
Implement the FCNNPytorch class.
Method signatures and docstrings:
- def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]): Create the FCNN model in PyTorch. :param args: the general arguments (con... | Implement the Python class `FCNNPytorch` described below.
Class description:
Implement the FCNNPytorch class.
Method signatures and docstrings:
- def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]): Create the FCNN model in PyTorch. :param args: the general arguments (con... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_siz... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_sizes: the sizes ... | the_stack_v2_python_sparse | cnns/nnlib/pytorch_architecture/fcnn.py | adam-dziedzic/bandlimited-cnns | train | 17 | |
1ace4b9bce81e93bee6f6edea43cc175547d7e26 | [
"if params:\n assert param_types is not None\nreturn cls(is_sql=True, is_table=False, read_operation='process_query_batch', kwargs={'sql': sql, 'params': params, 'param_types': param_types})",
"keyset = keyset or KeySet(all_=True)\nif not isinstance(keyset, KeySet):\n raise ValueError('keyset must be an ins... | <|body_start_0|>
if params:
assert param_types is not None
return cls(is_sql=True, is_table=False, read_operation='process_query_batch', kwargs={'sql': sql, 'params': params, 'param_types': param_types})
<|end_body_0|>
<|body_start_1|>
keyset = keyset or KeySet(all_=True)
if... | Encapsulates a spanner read operation. | ReadOperation | [
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"Apache-2.0",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ReadOperation:
"""Encapsulates a spanner read operation."""
def query(cls, sql, params=None, param_types=None):
"""A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional) values for parameter replacement. Keys must match the na... | stack_v2_sparse_classes_10k_train_004765 | 48,677 | permissive | [
{
"docstring": "A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional) values for parameter replacement. Keys must match the names used in sql param_types: (optional) maps explicit types for one or more param values; required if parameters are passed.",
... | 2 | null | Implement the Python class `ReadOperation` described below.
Class description:
Encapsulates a spanner read operation.
Method signatures and docstrings:
- def query(cls, sql, params=None, param_types=None): A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional)... | Implement the Python class `ReadOperation` described below.
Class description:
Encapsulates a spanner read operation.
Method signatures and docstrings:
- def query(cls, sql, params=None, param_types=None): A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional)... | 6d5048e05087ea54abc889ce402ae2a0abb9252b | <|skeleton|>
class ReadOperation:
"""Encapsulates a spanner read operation."""
def query(cls, sql, params=None, param_types=None):
"""A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional) values for parameter replacement. Keys must match the na... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ReadOperation:
"""Encapsulates a spanner read operation."""
def query(cls, sql, params=None, param_types=None):
"""A convenient method to construct ReadOperation from sql query. Args: sql: SQL query statement params: (optional) values for parameter replacement. Keys must match the names used in s... | the_stack_v2_python_sparse | sdks/python/apache_beam/io/gcp/experimental/spannerio.py | apache/beam | train | 7,061 |
25ce15be7231d55da089be86209917d1678b4e51 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\ntry:\n mapping_value = parse_node.get_child_node('@odata.type').get_str_value()\nexcept AttributeError:\n mapping_value = None\nif mapping_value and mapping_value.casefold() == '#microsoft.graph.documentSetVersion'.casefold():\n from .... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
try:
mapping_value = parse_node.get_child_node('@odata.type').get_str_value()
except AttributeError:
mapping_value = None
if mapping_value and mapping_value.casefold() ==... | BaseItemVersion | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_10k_train_004766 | 4,284 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BaseItemVersion",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminator_val... | 3 | null | Implement the Python class `BaseItemVersion` described below.
Class description:
Implement the BaseItemVersion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion: Creates a new instance of the appropriate class based on discriminator... | Implement the Python class `BaseItemVersion` described below.
Class description:
Implement the BaseItemVersion class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion: Creates a new instance of the appropriate class based on discriminator... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Ret... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BaseItemVersion:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> BaseItemVersion:
"""Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: BaseItem... | the_stack_v2_python_sparse | msgraph/generated/models/base_item_version.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
df1ef78c6479f5da68addb41e3f82c2f3815efa1 | [
"if not v:\n raise InvalidOrderData(order_id='order_id is required')\nif type(v) != int:\n raise InvalidOrderData(order_id='order_id must be integer')\nif v < 0 or v > 9223372036854775807:\n raise InvalidOrderData(order_id='order_id out of allowed range')\nreturn v",
"if not v:\n raise InvalidOrderDat... | <|body_start_0|>
if not v:
raise InvalidOrderData(order_id='order_id is required')
if type(v) != int:
raise InvalidOrderData(order_id='order_id must be integer')
if v < 0 or v > 9223372036854775807:
raise InvalidOrderData(order_id='order_id out of allowed rang... | Структура данных, описывающая заказ | OrderDataModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
<|body_0|>
def validate_region(cls, v):
"""Валидирует регион заказа"""
<|body_1|>
def validate_weight(cls, v):
... | stack_v2_sparse_classes_10k_train_004767 | 8,762 | no_license | [
{
"docstring": "Валидирует order_id заказа",
"name": "validate_order_id",
"signature": "def validate_order_id(cls, v: int) -> int"
},
{
"docstring": "Валидирует регион заказа",
"name": "validate_region",
"signature": "def validate_region(cls, v)"
},
{
"docstring": "Валидирует вес... | 5 | stack_v2_sparse_classes_30k_train_000050 | Implement the Python class `OrderDataModel` described below.
Class description:
Структура данных, описывающая заказ
Method signatures and docstrings:
- def validate_order_id(cls, v: int) -> int: Валидирует order_id заказа
- def validate_region(cls, v): Валидирует регион заказа
- def validate_weight(cls, v): Валидируе... | Implement the Python class `OrderDataModel` described below.
Class description:
Структура данных, описывающая заказ
Method signatures and docstrings:
- def validate_order_id(cls, v: int) -> int: Валидирует order_id заказа
- def validate_region(cls, v): Валидирует регион заказа
- def validate_weight(cls, v): Валидируе... | f1a908e5d6b30b826c38d24c52a721764f056fde | <|skeleton|>
class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
<|body_0|>
def validate_region(cls, v):
"""Валидирует регион заказа"""
<|body_1|>
def validate_weight(cls, v):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OrderDataModel:
"""Структура данных, описывающая заказ"""
def validate_order_id(cls, v: int) -> int:
"""Валидирует order_id заказа"""
if not v:
raise InvalidOrderData(order_id='order_id is required')
if type(v) != int:
raise InvalidOrderData(order_id='order... | the_stack_v2_python_sparse | candyapi/orders/validators.py | IntAlgambra/candyapi | train | 0 |
dabfa70bb3b8814b1a7d6b475c103f3d3302e625 | [
"assert self.substitute_func == torch.nn.functional.linear\nnode_kind = 'call_function'\nnode_target = self.substitute_func\nnode_args = (input_proxy, other_proxy)\nnode_kwargs = {}\nnon_bias_func_proxy = self.tracer.create_proxy(node_kind, node_target, node_args, node_kwargs)\nreturn non_bias_func_proxy",
"bias_... | <|body_start_0|>
assert self.substitute_func == torch.nn.functional.linear
node_kind = 'call_function'
node_target = self.substitute_func
node_args = (input_proxy, other_proxy)
node_kwargs = {}
non_bias_func_proxy = self.tracer.create_proxy(node_kind, node_target, node_ar... | This class is used to construct the restructure computation graph for call_func node based on F.linear. | LinearBasedBiasFunc | [
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LinearBasedBiasFunc:
"""This class is used to construct the restructure computation graph for call_func node based on F.linear."""
def create_non_bias_func_proxy(self, input_proxy, other_proxy):
"""This method is used to create the non_bias_func proxy, the node created by this proxy ... | stack_v2_sparse_classes_10k_train_004768 | 4,471 | permissive | [
{
"docstring": "This method is used to create the non_bias_func proxy, the node created by this proxy will compute the main computation, such as convolution, with bias option banned.",
"name": "create_non_bias_func_proxy",
"signature": "def create_non_bias_func_proxy(self, input_proxy, other_proxy)"
}... | 2 | null | Implement the Python class `LinearBasedBiasFunc` described below.
Class description:
This class is used to construct the restructure computation graph for call_func node based on F.linear.
Method signatures and docstrings:
- def create_non_bias_func_proxy(self, input_proxy, other_proxy): This method is used to create... | Implement the Python class `LinearBasedBiasFunc` described below.
Class description:
This class is used to construct the restructure computation graph for call_func node based on F.linear.
Method signatures and docstrings:
- def create_non_bias_func_proxy(self, input_proxy, other_proxy): This method is used to create... | c7b60f75470f067d1342705708810a660eabd684 | <|skeleton|>
class LinearBasedBiasFunc:
"""This class is used to construct the restructure computation graph for call_func node based on F.linear."""
def create_non_bias_func_proxy(self, input_proxy, other_proxy):
"""This method is used to create the non_bias_func proxy, the node created by this proxy ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LinearBasedBiasFunc:
"""This class is used to construct the restructure computation graph for call_func node based on F.linear."""
def create_non_bias_func_proxy(self, input_proxy, other_proxy):
"""This method is used to create the non_bias_func proxy, the node created by this proxy will compute ... | the_stack_v2_python_sparse | colossalai/fx/tracer/bias_addition_patch/patched_bias_addition_function/bias_addition_function.py | hpcaitech/ColossalAI | train | 32,044 |
f0f300220b2bd977230a1bebc78964fdb4ef6279 | [
"try:\n from rdkit import Chem\n import pubchempy as pcp\nexcept ModuleNotFoundError:\n raise ImportError('This class requires PubChemPy to be installed.')\nself.get_pubchem_compounds = pcp.get_compounds",
"try:\n from rdkit import Chem\n import pubchempy as pcp\nexcept ModuleNotFoundError:\n ra... | <|body_start_0|>
try:
from rdkit import Chem
import pubchempy as pcp
except ModuleNotFoundError:
raise ImportError('This class requires PubChemPy to be installed.')
self.get_pubchem_compounds = pcp.get_compounds
<|end_body_0|>
<|body_start_1|>
try:
... | PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----- This class requires RDKit and PubChemPy to b... | PubChemFingerprint | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----... | stack_v2_sparse_classes_10k_train_004769 | 2,258 | permissive | [
{
"docstring": "Initialize this featurizer.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Calculate PubChem fingerprint. Parameters ---------- datapoint: rdkit.Chem.rdchem.Mol RDKit Mol object Returns ------- np.ndarray 1D array of RDKit descriptors for `mol`. The le... | 2 | null | Implement the Python class `PubChemFingerprint` described below.
Class description:
PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specificat... | Implement the Python class `PubChemFingerprint` described below.
Class description:
PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specificat... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PubChemFingerprint:
"""PubChem Fingerprint. The PubChem fingerprint is a 881 bit structural key, which is used by PubChem for similarity searching. Please confirm the details in [1]_. References ---------- .. [1] ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem_fingerprints.pdf Note ----- This class ... | the_stack_v2_python_sparse | deepchem/feat/molecule_featurizers/pubchem_fingerprint.py | deepchem/deepchem | train | 4,876 |
493d26bfc4332a1be146beae6d8285858fa1e047 | [
"self._buffer = None\nself._page_size = page_size\nself._search = search",
"if not self._buffer:\n self._buffer = await self._search.fetch(self._page_size) or []\ntry:\n return self._buffer.pop(0)\nexcept IndexError:\n raise StopAsyncIteration"
] | <|body_start_0|>
self._buffer = None
self._page_size = page_size
self._search = search
<|end_body_0|>
<|body_start_1|>
if not self._buffer:
self._buffer = await self._search.fetch(self._page_size) or []
try:
return self._buffer.pop(0)
except Index... | A generic record search async iterator. | IterVCRecordSearch | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
<|body_0|>
async def __anext__(self):
"""Async iterator magic method."""
... | stack_v2_sparse_classes_10k_train_004770 | 4,078 | permissive | [
{
"docstring": "Instantiate a new `IterVCRecordSearch` instance.",
"name": "__init__",
"signature": "def __init__(self, search: VCRecordSearch, page_size: int=None)"
},
{
"docstring": "Async iterator magic method.",
"name": "__anext__",
"signature": "async def __anext__(self)"
}
] | 2 | null | Implement the Python class `IterVCRecordSearch` described below.
Class description:
A generic record search async iterator.
Method signatures and docstrings:
- def __init__(self, search: VCRecordSearch, page_size: int=None): Instantiate a new `IterVCRecordSearch` instance.
- async def __anext__(self): Async iterator ... | Implement the Python class `IterVCRecordSearch` described below.
Class description:
A generic record search async iterator.
Method signatures and docstrings:
- def __init__(self, search: VCRecordSearch, page_size: int=None): Instantiate a new `IterVCRecordSearch` instance.
- async def __anext__(self): Async iterator ... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
<|body_0|>
async def __anext__(self):
"""Async iterator magic method."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IterVCRecordSearch:
"""A generic record search async iterator."""
def __init__(self, search: VCRecordSearch, page_size: int=None):
"""Instantiate a new `IterVCRecordSearch` instance."""
self._buffer = None
self._page_size = page_size
self._search = search
async def __... | the_stack_v2_python_sparse | aries_cloudagent/storage/vc_holder/base.py | hyperledger/aries-cloudagent-python | train | 370 |
a2027fc35fac278eedc0d6b16539ecf32c5ecaa2 | [
"super(ActivationLayer, self).__init__(trainable=trainable, name=name)\nself.num_units = num_units\nself._trainable = trainable\nif activation == 'relu':\n self._activation = relu\n self._beta_initializer = 'glorot_uniform'\nelif activation == 'exu':\n self._activation = lambda x, weight, bias: relu_n(exu(... | <|body_start_0|>
super(ActivationLayer, self).__init__(trainable=trainable, name=name)
self.num_units = num_units
self._trainable = trainable
if activation == 'relu':
self._activation = relu
self._beta_initializer = 'glorot_uniform'
elif activation == 'exu... | Custom activation Layer to support ExU hidden units. | ActivationLayer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. a... | stack_v2_sparse_classes_10k_train_004771 | 10,796 | permissive | [
{
"docstring": "Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. activation: Activation to use. The default value of `None` corresponds to using the ReLU-1 activation with ExU units while `relu` would use standard hidden units with R... | 3 | null | Implement the Python class `ActivationLayer` described below.
Class description:
Custom activation Layer to support ExU hidden units.
Method signatures and docstrings:
- def __init__(self, num_units, name=None, activation='exu', trainable=True): Initializes ActivationLayer hyperparameters. Args: num_units: Number of ... | Implement the Python class `ActivationLayer` described below.
Class description:
Custom activation Layer to support ExU hidden units.
Method signatures and docstrings:
- def __init__(self, num_units, name=None, activation='exu', trainable=True): Initializes ActivationLayer hyperparameters. Args: num_units: Number of ... | 727ec399ad17b4dd1f71ce69a26fc3b0371d9fa7 | <|skeleton|>
class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ActivationLayer:
"""Custom activation Layer to support ExU hidden units."""
def __init__(self, num_units, name=None, activation='exu', trainable=True):
"""Initializes ActivationLayer hyperparameters. Args: num_units: Number of hidden units in the layer. name: The name of the layer. activation: Ac... | the_stack_v2_python_sparse | neural_additive_models/models.py | Ayoob7/google-research | train | 2 |
bec1bea47957fa8706724c3fc3d6578a2f692a87 | [
"self.arch_id = None\nself.netlist_id = None\nself.name = None\nself.instance = None\nself.ports = {'inputs': [], 'outputs': [], 'clocks': []}\nself.blocks = {}",
"assert root.tag == 'block', root.tag\nnetlist = PackedNetlist()\nnetlist.name = root.attrib['name']\nnetlist.instance = root.attrib['instance']\nnetli... | <|body_start_0|>
self.arch_id = None
self.netlist_id = None
self.name = None
self.instance = None
self.ports = {'inputs': [], 'outputs': [], 'clocks': []}
self.blocks = {}
<|end_body_0|>
<|body_start_1|>
assert root.tag == 'block', root.tag
netlist = Pack... | A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a PackedNetlist instance refer to individual placeable CLBs. | PackedNetlist | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PackedNetlist:
"""A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a PackedNetlist instance refer to individu... | stack_v2_sparse_classes_10k_train_004772 | 21,179 | permissive | [
{
"docstring": "Basic constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Reads the packed netlist from the given element tree",
"name": "from_etree",
"signature": "def from_etree(root)"
},
{
"docstring": "Builds an element tree (XML) that repre... | 3 | stack_v2_sparse_classes_30k_train_002521 | Implement the Python class `PackedNetlist` described below.
Class description:
A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a P... | Implement the Python class `PackedNetlist` described below.
Class description:
A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a P... | 835a40534f9efd70770d74f56f25fef6cfc6ebc6 | <|skeleton|>
class PackedNetlist:
"""A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a PackedNetlist instance refer to individu... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PackedNetlist:
"""A VPR Packed netlist representation. The packed netlist is organized as one huge block representing the whole FPGA with all placeable blocks (CLBs) as its children. Here we store the top-level block implicitly so all blocks mentioned in a PackedNetlist instance refer to individual placeable ... | the_stack_v2_python_sparse | f4pga/utils/quicklogic/repacker/packed_netlist.py | f4pga/f4pga | train | 19 |
ba6fd91c54e210ed43e57d736d374dae86e6042c | [
"if cache is None:\n cache = cmsis_pack_manager.Cache(True, True)\nresults = []\nfor pack in cache.packs_for_devices(cache.index.values()):\n pack_path = os.path.join(cache.data_path, pack.get_pack_name())\n if os.path.isfile(pack_path):\n results.append(pack)\nreturn results",
"if cache is None:\... | <|body_start_0|>
if cache is None:
cache = cmsis_pack_manager.Cache(True, True)
results = []
for pack in cache.packs_for_devices(cache.index.values()):
pack_path = os.path.join(cache.data_path, pack.get_pack_name())
if os.path.isfile(pack_path):
... | @brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified by the user. | ManagedPacksImpl | [
"CC-BY-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManagedPacksImpl:
"""@brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified by the user."""
def get_installed... | stack_v2_sparse_classes_10k_train_004773 | 29,452 | permissive | [
{
"docstring": "@brief Return a list containing CmsisPackRef objects for all installed packs.",
"name": "get_installed_packs",
"signature": "def get_installed_packs(cache: Optional[cmsis_pack_manager.Cache]=None) -> List[CmsisPackRef]"
},
{
"docstring": "@brief Return a list of CmsisPackDevice o... | 3 | stack_v2_sparse_classes_30k_test_000068 | Implement the Python class `ManagedPacksImpl` described below.
Class description:
@brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified... | Implement the Python class `ManagedPacksImpl` described below.
Class description:
@brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified... | 9253740baf46ebf4eacbce6bf3369150c5fb8ee0 | <|skeleton|>
class ManagedPacksImpl:
"""@brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified by the user."""
def get_installed... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ManagedPacksImpl:
"""@brief Namespace for managed CMSIS-Pack utilities. By managed, we mean managed by the cmsis-pack-manager package. All the methods on this class apply only to those packs managed by cmsis-pack-manager, not any targets from packs specified by the user."""
def get_installed_packs(cache:... | the_stack_v2_python_sparse | pyocd/target/pack/pack_target.py | pyocd/pyOCD | train | 507 |
88bc474550e4e52120e4360b9f2804dda95201cd | [
"self.links = links\nself.email_config = email_config\nself.additional_properties = additional_properties",
"if dictionary is None:\n return None\nlinks = dictionary.get('links')\nemail_config = dictionary.get('emailConfig')\nfor key in cls._names.values():\n if key in dictionary:\n del dictionary[ke... | <|body_start_0|>
self.links = links
self.email_config = email_config
self.additional_properties = additional_properties
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
links = dictionary.get('links')
email_config = dictionary.get('emailConf... | Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config (object): The configuration used to generate the Connect email. | GenerateConnectEmailResponseMultipleBorrowers | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GenerateConnectEmailResponseMultipleBorrowers:
"""Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config (object): The configuration used to gen... | stack_v2_sparse_classes_10k_train_004774 | 2,061 | permissive | [
{
"docstring": "Constructor for the GenerateConnectEmailResponseMultipleBorrowers class",
"name": "__init__",
"signature": "def __init__(self, links=None, email_config=None, additional_properties={})"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictio... | 2 | stack_v2_sparse_classes_30k_train_002084 | Implement the Python class `GenerateConnectEmailResponseMultipleBorrowers` described below.
Class description:
Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config ... | Implement the Python class `GenerateConnectEmailResponseMultipleBorrowers` described below.
Class description:
Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config ... | b2ab1ded435db75c78d42261f5e4acd2a3061487 | <|skeleton|>
class GenerateConnectEmailResponseMultipleBorrowers:
"""Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config (object): The configuration used to gen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GenerateConnectEmailResponseMultipleBorrowers:
"""Implementation of the 'Generate Connect Email Response Multiple borrowers' model. TODO: type model description here. Attributes: links (list of string): The URL generated to send a Connect email email_config (object): The configuration used to generate the Con... | the_stack_v2_python_sparse | finicityapi/models/generate_connect_email_response_multiple_borrowers.py | monarchmoney/finicity-python | train | 0 |
204f82a9599ec110d50bb4c7cb36ef39c4489c3c | [
"self.input_data_description = input_data_description\nself.times_sigma = times_sigma\nself.name = 'outlier_clipping'",
"try:\n X_transf = []\n X = np.array(X)\n for kinput in range(self.input_data_description['NI']):\n if self.input_data_description['input_types'][kinput]['type'] == 'num':\n ... | <|body_start_0|>
self.input_data_description = input_data_description
self.times_sigma = times_sigma
self.name = 'outlier_clipping'
<|end_body_0|>
<|body_start_1|>
try:
X_transf = []
X = np.array(X)
for kinput in range(self.input_data_description['NI'... | outlier_clipping_model | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class outlier_clipping_model:
def __init__(self, input_data_description, times_sigma):
"""Parameters ---------- input_data_description: dict Description of the input features times_sigma: float Maximal allowed variation with respect to data standard deviation"""
<|body_0|>
def tra... | stack_v2_sparse_classes_10k_train_004775 | 2,648 | permissive | [
{
"docstring": "Parameters ---------- input_data_description: dict Description of the input features times_sigma: float Maximal allowed variation with respect to data standard deviation",
"name": "__init__",
"signature": "def __init__(self, input_data_description, times_sigma)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_002307 | Implement the Python class `outlier_clipping_model` described below.
Class description:
Implement the outlier_clipping_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description, times_sigma): Parameters ---------- input_data_description: dict Description of the input features times_si... | Implement the Python class `outlier_clipping_model` described below.
Class description:
Implement the outlier_clipping_model class.
Method signatures and docstrings:
- def __init__(self, input_data_description, times_sigma): Parameters ---------- input_data_description: dict Description of the input features times_si... | ccc0a7674a04ae0d00bedc38893b33184c5f68c6 | <|skeleton|>
class outlier_clipping_model:
def __init__(self, input_data_description, times_sigma):
"""Parameters ---------- input_data_description: dict Description of the input features times_sigma: float Maximal allowed variation with respect to data standard deviation"""
<|body_0|>
def tra... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class outlier_clipping_model:
def __init__(self, input_data_description, times_sigma):
"""Parameters ---------- input_data_description: dict Description of the input features times_sigma: float Maximal allowed variation with respect to data standard deviation"""
self.input_data_description = input_d... | the_stack_v2_python_sparse | MMLL/preprocessors/outlier_clipping.py | Musketeer-H2020/MMLL-Robust | train | 0 | |
e341edb681b88c6efbd65316388ccf6a01b326f3 | [
"type = kwargs['type']\nfile = kwargs['file']\nwith open(file, 'r') as data_file:\n for line in data_file:\n line = line[:-1]\n items_dict = ast.literal_eval(line)\n item = type.from_dict(items_dict)\n self.add_item(item, lambda i: i.uid)",
"file = kwargs['file']\nwith open(file, 'w... | <|body_start_0|>
type = kwargs['type']
file = kwargs['file']
with open(file, 'r') as data_file:
for line in data_file:
line = line[:-1]
items_dict = ast.literal_eval(line)
item = type.from_dict(items_dict)
self.add_item(... | RepositoryText | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryText:
def load_data(self, **kwargs):
"""Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:"""
<|body_0|>
def save_data(self, **kwargs):
"""Save repository to txt file. :param kwargs: file ... | stack_v2_sparse_classes_10k_train_004776 | 1,259 | no_license | [
{
"docstring": "Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:",
"name": "load_data",
"signature": "def load_data(self, **kwargs)"
},
{
"docstring": "Save repository to txt file. :param kwargs: file - file to load the data ... | 2 | stack_v2_sparse_classes_30k_train_001648 | Implement the Python class `RepositoryText` described below.
Class description:
Implement the RepositoryText class.
Method signatures and docstrings:
- def load_data(self, **kwargs): Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:
- def save_data... | Implement the Python class `RepositoryText` described below.
Class description:
Implement the RepositoryText class.
Method signatures and docstrings:
- def load_data(self, **kwargs): Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:
- def save_data... | 206b049700d8a3e03b52e57960cd44f85c415fe8 | <|skeleton|>
class RepositoryText:
def load_data(self, **kwargs):
"""Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:"""
<|body_0|>
def save_data(self, **kwargs):
"""Save repository to txt file. :param kwargs: file ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RepositoryText:
def load_data(self, **kwargs):
"""Load repository from txt file. :param kwargs: file - file to load the data from type - the type of the objects :return:"""
type = kwargs['type']
file = kwargs['file']
with open(file, 'r') as data_file:
for line in da... | the_stack_v2_python_sparse | semester_1/fp/assignment_09/src/repositories/repository_text.py | caprapaul/assignments | train | 0 | |
d441b85e15392c2057bfe64dde8c30c8d627129b | [
"title = self.data['title']\nslug_es = slugify(title.es)\nslug_en = slugify(title.en)\nquery = Q(slug_es=slug_es) | Q(slug_en=slug_en)\nquery = Category.objects.filter(query)\nif self.instance.id:\n query = query.exclude(id=self.instance.id)\nif query.exists():\n raise forms.ValidationError(INVALID_CATEGORY_N... | <|body_start_0|>
title = self.data['title']
slug_es = slugify(title.es)
slug_en = slugify(title.en)
query = Q(slug_es=slug_es) | Q(slug_en=slug_en)
query = Category.objects.filter(query)
if self.instance.id:
query = query.exclude(id=self.instance.id)
i... | Form to create a category from admin | AdminCreateCategoryForm | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
<|body_0|>
def clean(self):
"""validate form"""
<|body_1|>
def save(self, commit=True):
"""Save form"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k_train_004777 | 8,911 | no_license | [
{
"docstring": "Validate title_es",
"name": "clean_title",
"signature": "def clean_title(self)"
},
{
"docstring": "validate form",
"name": "clean",
"signature": "def clean(self)"
},
{
"docstring": "Save form",
"name": "save",
"signature": "def save(self, commit=True)"
}... | 3 | stack_v2_sparse_classes_30k_train_000092 | Implement the Python class `AdminCreateCategoryForm` described below.
Class description:
Form to create a category from admin
Method signatures and docstrings:
- def clean_title(self): Validate title_es
- def clean(self): validate form
- def save(self, commit=True): Save form | Implement the Python class `AdminCreateCategoryForm` described below.
Class description:
Form to create a category from admin
Method signatures and docstrings:
- def clean_title(self): Validate title_es
- def clean(self): validate form
- def save(self, commit=True): Save form
<|skeleton|>
class AdminCreateCategoryFo... | 4dc6362ef624eb6591aad9d5c7de95eee40a01c9 | <|skeleton|>
class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
<|body_0|>
def clean(self):
"""validate form"""
<|body_1|>
def save(self, commit=True):
"""Save form"""
<|body_2|>
<|e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdminCreateCategoryForm:
"""Form to create a category from admin"""
def clean_title(self):
"""Validate title_es"""
title = self.data['title']
slug_es = slugify(title.es)
slug_en = slugify(title.en)
query = Q(slug_es=slug_es) | Q(slug_en=slug_en)
query = Cat... | the_stack_v2_python_sparse | app/offers/forms.py | arielMilan1899/orbita-api | train | 0 |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')\nsuper().__init__(*args, **kwargs)\nif InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):\n self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attrs={'type': 'email', 'placeholder': _('Ema... | <|body_start_0|>
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if InvenTreeSetting.get_setting('LOGIN_SIGNUP_MAIL_TWICE'):
self.fields['email2'] = forms.EmailField(label=_('Email (again)'), widget=forms.TextInput(attr... | Override to use dynamic settings. | CustomSignupForm | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_10k_train_004778 | 12,546 | permissive | [
{
"docstring": "Check settings to influence which fields are needed.",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "Make sure the supllied emails match if enabled in settings.",
"name": "clean",
"signature": "def clean(self)"
}
] | 2 | null | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | Implement the Python class `CustomSignupForm` described below.
Class description:
Override to use dynamic settings.
Method signatures and docstrings:
- def __init__(self, *args, **kwargs): Check settings to influence which fields are needed.
- def clean(self): Make sure the supllied emails match if enabled in setting... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
<|body_0|>
def clean(self):
"""Make sure the supllied emails match if enabled in settings."""
<|body_... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CustomSignupForm:
"""Override to use dynamic settings."""
def __init__(self, *args, **kwargs):
"""Check settings to influence which fields are needed."""
kwargs['email_required'] = InvenTreeSetting.get_setting('LOGIN_MAIL_REQUIRED')
super().__init__(*args, **kwargs)
if Inv... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
973014ada78ac62a8b1c58f59d1ac5619de47fee | [
"import matplotlib.pyplot\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = matplotlib.pyplot.figure()\naxs = fig.add_subplot(1, 1, 1, projection='3d')\naxs.plot_trisurf(V[:, 0], V[:, 1], V[:, 2], triangles=F)\naxs.set_xlabel('x')\naxs.set_ylabel('y')\naxs.set_zlabel('z')\naxs.axis('equal')\nmatplotlib.pyplot.show()\... | <|body_start_0|>
import matplotlib.pyplot
from mpl_toolkits.mplot3d import Axes3D
fig = matplotlib.pyplot.figure()
axs = fig.add_subplot(1, 1, 1, projection='3d')
axs.plot_trisurf(V[:, 0], V[:, 1], V[:, 2], triangles=F)
axs.set_xlabel('x')
axs.set_ylabel('y')
... | Define all of my functions within a class to keep the global name space clean. | myfuncs | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy arr... | stack_v2_sparse_classes_10k_train_004779 | 2,695 | permissive | [
{
"docstring": "Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy array of faces (V1, V2, V3) V : Nx3 NumPy array of vertexes ( X, Y, Z)",
"name": "qp",
"signature": "def qp(F, V)"
}... | 2 | stack_v2_sparse_classes_30k_test_000305 | Implement the Python class `myfuncs` described below.
Class description:
Define all of my functions within a class to keep the global name space clean.
Method signatures and docstrings:
- def qp(F, V): Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is ... | Implement the Python class `myfuncs` described below.
Class description:
Define all of my functions within a class to keep the global name space clean.
Method signatures and docstrings:
- def qp(F, V): Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is ... | c4fbebe26b09dde93249293ce3db2e71936a894b | <|skeleton|>
class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy arr... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class myfuncs:
"""Define all of my functions within a class to keep the global name space clean."""
def qp(F, V):
"""Quickly plot a surface defined by a face and vertex list, F and V respectively. The faces are colored blue. This is simply a rewrite of Ken's qp in MATLAB. F : Nx3 NumPy array of faces (... | the_stack_v2_python_sparse | ipython/profile_default/startup/50_myfuncs.py | kprussing/dotfiles | train | 1 |
bb2df406d51564812edf99357cb4881afb6069a8 | [
"if request.user.is_authenticated():\n return True\nreturn False",
"if request.user.is_authenticated():\n if request.user.is_staff:\n return True\n return account.username == request.user.username\nreturn False"
] | <|body_start_0|>
if request.user.is_authenticated():
return True
return False
<|end_body_0|>
<|body_start_1|>
if request.user.is_authenticated():
if request.user.is_staff:
return True
return account.username == request.user.username
re... | Returns true if the request.user is owner of the account or Admin | IsAdminOrAccountOwner | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IsAdminOrAccountOwner:
"""Returns true if the request.user is owner of the account or Admin"""
def has_permission(self, request, view):
"""Returns true or false if the user has the permission :param view: View set :return: Boolean with the user permission"""
<|body_0|>
d... | stack_v2_sparse_classes_10k_train_004780 | 1,273 | no_license | [
{
"docstring": "Returns true or false if the user has the permission :param view: View set :return: Boolean with the user permission",
"name": "has_permission",
"signature": "def has_permission(self, request, view)"
},
{
"docstring": "Returns `True` if permission is granted, `False` otherwise.",... | 2 | stack_v2_sparse_classes_30k_train_005165 | Implement the Python class `IsAdminOrAccountOwner` described below.
Class description:
Returns true if the request.user is owner of the account or Admin
Method signatures and docstrings:
- def has_permission(self, request, view): Returns true or false if the user has the permission :param view: View set :return: Bool... | Implement the Python class `IsAdminOrAccountOwner` described below.
Class description:
Returns true if the request.user is owner of the account or Admin
Method signatures and docstrings:
- def has_permission(self, request, view): Returns true or false if the user has the permission :param view: View set :return: Bool... | 9635d7ac37da6b705f6c95803d98956cfbd30ec4 | <|skeleton|>
class IsAdminOrAccountOwner:
"""Returns true if the request.user is owner of the account or Admin"""
def has_permission(self, request, view):
"""Returns true or false if the user has the permission :param view: View set :return: Boolean with the user permission"""
<|body_0|>
d... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class IsAdminOrAccountOwner:
"""Returns true if the request.user is owner of the account or Admin"""
def has_permission(self, request, view):
"""Returns true or false if the user has the permission :param view: View set :return: Boolean with the user permission"""
if request.user.is_authenticat... | the_stack_v2_python_sparse | trashradar-api/accounts/permissions.py | kahihia/trashradar-api | train | 0 |
bb37afd52d3794544c9db054d1051e4e0b485807 | [
"def atMostK(k: int) -> int:\n \"\"\"子数组的最大值不大于k的子数组个数\"\"\"\n res, dp = (0, 0)\n for num in nums:\n if num <= k:\n dp += 1\n else:\n dp = 0\n res += dp\n return res\nreturn (atMostK(right) - atMostK(left - 1)) % MOD",
"n = len(nums)\nres = 0\npos1, pos2 = (-... | <|body_start_0|>
def atMostK(k: int) -> int:
"""子数组的最大值不大于k的子数组个数"""
res, dp = (0, 0)
for num in nums:
if num <= k:
dp += 1
else:
dp = 0
res += dp
return res
return (at... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
"""解法1:容斥"""
<|body_0|>
def numSubarrayBoundedMax2(self, nums: List[int], lower: int, upper: int) -> int:
"""解法2:定界子数组"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_004781 | 1,422 | no_license | [
{
"docstring": "解法1:容斥",
"name": "numSubarrayBoundedMax",
"signature": "def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int"
},
{
"docstring": "解法2:定界子数组",
"name": "numSubarrayBoundedMax2",
"signature": "def numSubarrayBoundedMax2(self, nums: List[int], lower: ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: 解法1:容斥
- def numSubarrayBoundedMax2(self, nums: List[int], lower: int, upper: int) -> int: 解法2:定界子... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int: 解法1:容斥
- def numSubarrayBoundedMax2(self, nums: List[int], lower: int, upper: int) -> int: 解法2:定界子... | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | <|skeleton|>
class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
"""解法1:容斥"""
<|body_0|>
def numSubarrayBoundedMax2(self, nums: List[int], lower: int, upper: int) -> int:
"""解法2:定界子数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayBoundedMax(self, nums: List[int], left: int, right: int) -> int:
"""解法1:容斥"""
def atMostK(k: int) -> int:
"""子数组的最大值不大于k的子数组个数"""
res, dp = (0, 0)
for num in nums:
if num <= k:
dp += 1
... | the_stack_v2_python_sparse | 22_专题/atMoskK/最大值在范围内的子数组个数.py | 981377660LMT/algorithm-study | train | 225 | |
1c585f5c401c87591a6dd2ac654fcc2390ee2943 | [
"self.snake = deque()\nself.snake.append([0, 0])\nself.snake_set = set()\nself.snake_set.add((0, 0))\nself.score = 0\nself.food = deque()\nfor ele in food:\n self.food.append(ele)\nself.width = width\nself.height = height\nself.directions = {'U': [-1, 0], 'L': [0, -1], 'R': [0, 1], 'D': [1, 0]}",
"head = self.... | <|body_start_0|>
self.snake = deque()
self.snake.append([0, 0])
self.snake_set = set()
self.snake_set.add((0, 0))
self.score = 0
self.food = deque()
for ele in food:
self.food.append(ele)
self.width = width
self.height = height
... | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_10k_train_004782 | 2,425 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | null | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | Implement the Python class `SnakeGame` described below.
Class description:
Implement the SnakeGame class.
Method signatures and docstrings:
- def __init__(self, width: int, height: int, food: List[List[int]]): Initialize your data structure here. @param width - screen width @param height - screen height @param food -... | 9b38a7742a819ac3795ea295e371e26bb5bfc28c | <|skeleton|>
class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SnakeGame:
def __init__(self, width: int, height: int, food: List[List[int]]):
"""Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is a... | the_stack_v2_python_sparse | 353. Design Snake Game.py | dundunmao/LeetCode2019 | train | 0 | |
599471fca4ccb4ca24191a09dc5ffa6db27b94f2 | [
"super().__init__(validate)\nself._n_shots = None\nself._n_circuits = None\nself._memory_allocation = memory_allocation",
"self._n_shots = len(data[0])\nself._n_circuits = len(data)\nif self._validate:\n if data.shape[:2] != (self._n_circuits, self._n_shots):\n raise DataProcessorError(f'The datum given... | <|body_start_0|>
super().__init__(validate)
self._n_shots = None
self._n_circuits = None
self._memory_allocation = memory_allocation
<|end_body_0|>
<|body_start_1|>
self._n_shots = len(data[0])
self._n_circuits = len(data)
if self._validate:
if data.s... | An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circuit. Restless measurements therefore require special data processing nodes that a... | RestlessNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestlessNode:
"""An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circuit. Restless measurements therefore requ... | stack_v2_sparse_classes_10k_train_004783 | 42,185 | permissive | [
{
"docstring": "Initialize a restless node. Args: validate: If set to True the node will validate its input. memory_allocation: If set to \"c\" the node assumes that the backend subsequently first measures all circuits and then repeats this n times, where n is the total number of shots. The default value is \"c... | 3 | stack_v2_sparse_classes_30k_train_005024 | Implement the Python class `RestlessNode` described below.
Class description:
An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circui... | Implement the Python class `RestlessNode` described below.
Class description:
An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circui... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class RestlessNode:
"""An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circuit. Restless measurements therefore requ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RestlessNode:
"""An abstract node for restless data processing nodes. In restless measurements, the qubit is not reset after each measurement. Instead, the outcome of the previous quantum non-demolition measurement is the initial state for the current circuit. Restless measurements therefore require special d... | the_stack_v2_python_sparse | qiskit_experiments/data_processing/nodes.py | oliverdial/qiskit-experiments | train | 0 |
2ab13633ed9ab7e66881f3a37c375bac3c180d64 | [
"scannable = len(configuration.get('url', []))\nif scannable is 0:\n return False\nscanned = 0\nif configuration.get('hour'):\n if datetime.datetime.utcnow().hour != int(configuration.get('hour')):\n return True\nif configuration.get('minute'):\n if datetime.datetime.utcnow().minute != int(configura... | <|body_start_0|>
scannable = len(configuration.get('url', []))
if scannable is 0:
return False
scanned = 0
if configuration.get('hour'):
if datetime.datetime.utcnow().hour != int(configuration.get('hour')):
return True
if configuration.get(... | Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run 'exe_env': 'general', # <... | URLParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class URLParser:
"""Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you ... | stack_v2_sparse_classes_10k_train_004784 | 4,446 | permissive | [
{
"docstring": "This will make a GET request to all URL's in the list provided by your configuration Args: configuration (dict): Configuration of Source. See Class Documentation above for more info Returns: bool: If True data will be scheduled for ingestion after deduplication. If False the engine will bail out... | 2 | stack_v2_sparse_classes_30k_train_006233 | Implement the Python class `URLParser` described below.
Class description:
Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name '... | Implement the Python class `URLParser` described below.
Class description:
Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name '... | 7ebf3df71d5c80a8ed9df44d9b64b735a9d0f899 | <|skeleton|>
class URLParser:
"""Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class URLParser:
"""Monitor URL's as a source of information This source is designed to provide source data on the URL's configured for a GREASE sourcing cluster. A generic configuration looks like this for a url_source:: { 'name': 'example_source', # <-- A name 'job': 'example_job', # <-- Any job you want to run '... | the_stack_v2_python_sparse | tgt_grease/enterprise/Sources/UrlParser.py | target/grease | train | 46 |
18b112c31fd0e296ea4d961051746ba8d8a7e86f | [
"headers = []\nfor field in self.get_export_fields():\n field_model = AidProject._meta.get_field(field.column_name)\n headers.append(field_model.verbose_name)\nreturn headers",
"field_name = self.get_field_name(field)\nmethod = getattr(self, 'dehydrate_%s' % field_name, None)\nif method is not None:\n re... | <|body_start_0|>
headers = []
for field in self.get_export_fields():
field_model = AidProject._meta.get_field(field.column_name)
headers.append(field_model.verbose_name)
return headers
<|end_body_0|>
<|body_start_1|>
field_name = self.get_field_name(field)
... | Resource for Export AidProject. | AidProjectResource | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AidProjectResource:
"""Resource for Export AidProject."""
def get_export_headers(self):
"""override get_export_headers() to translate field names."""
<|body_0|>
def export_field(self, field, obj):
"""override export_field() to translate field values."""
<... | stack_v2_sparse_classes_10k_train_004785 | 13,586 | permissive | [
{
"docstring": "override get_export_headers() to translate field names.",
"name": "get_export_headers",
"signature": "def get_export_headers(self)"
},
{
"docstring": "override export_field() to translate field values.",
"name": "export_field",
"signature": "def export_field(self, field, ... | 2 | null | Implement the Python class `AidProjectResource` described below.
Class description:
Resource for Export AidProject.
Method signatures and docstrings:
- def get_export_headers(self): override get_export_headers() to translate field names.
- def export_field(self, field, obj): override export_field() to translate field... | Implement the Python class `AidProjectResource` described below.
Class description:
Resource for Export AidProject.
Method signatures and docstrings:
- def get_export_headers(self): override get_export_headers() to translate field names.
- def export_field(self, field, obj): override export_field() to translate field... | af9f6e6e8b1918363793fbf291f3518ef1454169 | <|skeleton|>
class AidProjectResource:
"""Resource for Export AidProject."""
def get_export_headers(self):
"""override get_export_headers() to translate field names."""
<|body_0|>
def export_field(self, field, obj):
"""override export_field() to translate field values."""
<... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AidProjectResource:
"""Resource for Export AidProject."""
def get_export_headers(self):
"""override get_export_headers() to translate field names."""
headers = []
for field in self.get_export_fields():
field_model = AidProject._meta.get_field(field.column_name)
... | the_stack_v2_python_sparse | src/aids/resources.py | MTES-MCT/aides-territoires | train | 21 |
b9ff1d46ae3c554191dbefca37085bd0d8db7ccd | [
"self.input_directory = Path(input_directory)\nself.output_directory = Path(output_directory)\nself.output_directory.mkdir(parents=True, exist_ok=False)",
"dataset_gdf = pd.concat(dataset)\ndataset_gdf['original_file'] = dataset_gdf['original_file'].astype(str)\ndataset_gdf.to_file(str(self.output_directory / f'f... | <|body_start_0|>
self.input_directory = Path(input_directory)
self.output_directory = Path(output_directory)
self.output_directory.mkdir(parents=True, exist_ok=False)
<|end_body_0|>
<|body_start_1|>
dataset_gdf = pd.concat(dataset)
dataset_gdf['original_file'] = dataset_gdf['ori... | The GeoDataFrame generator class that turns txt files into geojson. | GeoDataGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeoDataGenerator:
"""The GeoDataFrame generator class that turns txt files into geojson."""
def __init__(self, input_directory, output_directory):
"""Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geoj... | stack_v2_sparse_classes_10k_train_004786 | 5,325 | no_license | [
{
"docstring": "Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geojson files.",
"name": "__init__",
"signature": "def __init__(self, input_directory, output_directory)"
},
{
"docstring": "Save a block of images. A... | 5 | stack_v2_sparse_classes_30k_train_000966 | Implement the Python class `GeoDataGenerator` described below.
Class description:
The GeoDataFrame generator class that turns txt files into geojson.
Method signatures and docstrings:
- def __init__(self, input_directory, output_directory): Initialize the GeoDataGenerator. Args: input_directory (str): Directory with ... | Implement the Python class `GeoDataGenerator` described below.
Class description:
The GeoDataFrame generator class that turns txt files into geojson.
Method signatures and docstrings:
- def __init__(self, input_directory, output_directory): Initialize the GeoDataGenerator. Args: input_directory (str): Directory with ... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class GeoDataGenerator:
"""The GeoDataFrame generator class that turns txt files into geojson."""
def __init__(self, input_directory, output_directory):
"""Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geoj... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GeoDataGenerator:
"""The GeoDataFrame generator class that turns txt files into geojson."""
def __init__(self, input_directory, output_directory):
"""Initialize the GeoDataGenerator. Args: input_directory (str): Directory with images. output_directory (str): Target directory for geojson files."""... | the_stack_v2_python_sparse | fmlwright/dataset_builder/GeoDataGenerator.py | rgresia-umd/fml-wright | train | 0 |
7c9c7c0f46469cd613145f619274e4bf3ddfa473 | [
"self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')\nself.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')\nself.image_resume_not_mouseover = pygame.image.load('images/resume_not_mouseover.png')\nself.image_resume_mouseover = pygame.image.load('images/resume_... | <|body_start_0|>
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')
self.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')
self.image_resume_not_mouseover = pygame.image.load('images/resume_not_mouseover.png')
self.image_resume_mous... | 暂停按钮类 | PauseButton | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0|>
def switch_image(self, event):
"""切换暂停按钮的图片"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseo... | stack_v2_sparse_classes_10k_train_004787 | 2,550 | no_license | [
{
"docstring": "初始化暂停按钮",
"name": "__init__",
"signature": "def __init__(self, window)"
},
{
"docstring": "切换暂停按钮的图片",
"name": "switch_image",
"signature": "def switch_image(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005115 | Implement the Python class `PauseButton` described below.
Class description:
暂停按钮类
Method signatures and docstrings:
- def __init__(self, window): 初始化暂停按钮
- def switch_image(self, event): 切换暂停按钮的图片 | Implement the Python class `PauseButton` described below.
Class description:
暂停按钮类
Method signatures and docstrings:
- def __init__(self, window): 初始化暂停按钮
- def switch_image(self, event): 切换暂停按钮的图片
<|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0... | 66f7f801e1395207778484e1543ea26309d4b354 | <|skeleton|>
class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
<|body_0|>
def switch_image(self, event):
"""切换暂停按钮的图片"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PauseButton:
"""暂停按钮类"""
def __init__(self, window):
"""初始化暂停按钮"""
self.image_pause_not_mouseover = pygame.image.load('images/pause_not_mouseover.png')
self.image_pause_mouseover = pygame.image.load('images/pause_mouseover.png')
self.image_resume_not_mouseover = pygame.ima... | the_stack_v2_python_sparse | python/practise/PlaneWar/pause_button.py | anzhihe/learning | train | 1,443 |
d9f6a35397f6ce6322b9c00943e454a47cf8b79a | [
"super().__init__()\nself._Z = Z\nself._layers, dim = (nn.ModuleList(), [M + self._Z] + hidden_size)\nfor d_in, d_out in zip(dim[:-1], dim[1:]):\n self._layers.append(nn.Sequential(nn.Linear(d_in, d_out), g))\nlayer = nn.Sequential(nn.Linear(dim[-1], M), nn.Sigmoid())\nself._layers.append(layer)",
"if z is Non... | <|body_start_0|>
super().__init__()
self._Z = Z
self._layers, dim = (nn.ModuleList(), [M + self._Z] + hidden_size)
for d_in, d_out in zip(dim[:-1], dim[1:]):
self._layers.append(nn.Sequential(nn.Linear(d_in, d_out), g))
layer = nn.Sequential(nn.Linear(dim[-1], M), nn.... | MalGAN generator block | Generator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :p... | stack_v2_sparse_classes_10k_train_004788 | 2,566 | permissive | [
{
"docstring": "Generator Constructor :param M: Dimension of the feature vector \\\\p m :param Z: Dimension of the noise vector \\\\p z :param hidden_size: Width of the hidden layer(s) :param g: Activation function",
"name": "__init__",
"signature": "def __init__(self, M: int, Z: int, hidden_size: List[... | 2 | stack_v2_sparse_classes_30k_train_000196 | Implement the Python class `Generator` described below.
Class description:
MalGAN generator block
Method signatures and docstrings:
- def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module): Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector ... | Implement the Python class `Generator` described below.
Class description:
MalGAN generator block
Method signatures and docstrings:
- def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module): Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector ... | c36647d1b3ba86a9a4e6e1a0bda2a371d8875781 | <|skeleton|>
class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Generator:
"""MalGAN generator block"""
def __init__(self, M: int, Z: int, hidden_size: List[int], g: nn.Module):
"""Generator Constructor :param M: Dimension of the feature vector \\p m :param Z: Dimension of the noise vector \\p z :param hidden_size: Width of the hidden layer(s) :param g: Activ... | the_stack_v2_python_sparse | malgan/generator.py | CyberForce/Pesidious | train | 119 |
37cf30dadce3f1ff1c8fb8ef0e729a578a2cbdd8 | [
"self.auth = auth\nif isinstance(rid, FaceUDistinguishRecord):\n self.record = rid\nelse:\n self.record = self.get_record_model(rid)",
"if not rid:\n return None\nrecord = FaceUDistinguishRecord.objects.get_once(pk=rid)\nif not record:\n raise FaceURecordInfoExcept.record_is_not_exists()\nreturn recor... | <|body_start_0|>
self.auth = auth
if isinstance(rid, FaceUDistinguishRecord):
self.record = rid
else:
self.record = self.get_record_model(rid)
<|end_body_0|>
<|body_start_1|>
if not rid:
return None
record = FaceUDistinguishRecord.objects.get_... | FaceURecordLogic | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FaceURecordLogic:
def __init__(self, auth, rid=''):
"""INIT :param auth: :param rid:"""
<|body_0|>
def get_record_model(self, rid):
"""获取记录model :param rid: :return:"""
<|body_1|>
def get_record_info(self):
"""获取记录信息 :return:"""
<|body_2|... | stack_v2_sparse_classes_10k_train_004789 | 1,633 | no_license | [
{
"docstring": "INIT :param auth: :param rid:",
"name": "__init__",
"signature": "def __init__(self, auth, rid='')"
},
{
"docstring": "获取记录model :param rid: :return:",
"name": "get_record_model",
"signature": "def get_record_model(self, rid)"
},
{
"docstring": "获取记录信息 :return:",
... | 3 | stack_v2_sparse_classes_30k_train_000968 | Implement the Python class `FaceURecordLogic` described below.
Class description:
Implement the FaceURecordLogic class.
Method signatures and docstrings:
- def __init__(self, auth, rid=''): INIT :param auth: :param rid:
- def get_record_model(self, rid): 获取记录model :param rid: :return:
- def get_record_info(self): 获取记... | Implement the Python class `FaceURecordLogic` described below.
Class description:
Implement the FaceURecordLogic class.
Method signatures and docstrings:
- def __init__(self, auth, rid=''): INIT :param auth: :param rid:
- def get_record_model(self, rid): 获取记录model :param rid: :return:
- def get_record_info(self): 获取记... | 7467cd66e1fc91f0b3a264f8fc9b93f22f09fe7b | <|skeleton|>
class FaceURecordLogic:
def __init__(self, auth, rid=''):
"""INIT :param auth: :param rid:"""
<|body_0|>
def get_record_model(self, rid):
"""获取记录model :param rid: :return:"""
<|body_1|>
def get_record_info(self):
"""获取记录信息 :return:"""
<|body_2|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FaceURecordLogic:
def __init__(self, auth, rid=''):
"""INIT :param auth: :param rid:"""
self.auth = auth
if isinstance(rid, FaceUDistinguishRecord):
self.record = rid
else:
self.record = self.get_record_model(rid)
def get_record_model(self, rid):
... | the_stack_v2_python_sparse | FireHydrant/server/faceU/logic/record.py | shoogoome/FireHydrant | train | 4 | |
d37c5a53aa46a706f3d0e7d54fde0c7ed069cf97 | [
"if root is None:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST(root.left, val)\nelse:\n return self.searchBST(root.right, val)",
"if not root:\n return None\nif root.val == val:\n return root\nelif val < root.val:\n return self.searchBST2(root... | <|body_start_0|>
if root is None:
return None
if root.val == val:
return root
elif val < root.val:
return self.searchBST(root.left, val)
else:
return self.searchBST(root.right, val)
<|end_body_0|>
<|body_start_1|>
if not root:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def searchBST2(self, root, val):
""":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)"""
<|body_1|>
<|end_skeleton|>
<|bod... | stack_v2_sparse_classes_10k_train_004790 | 2,333 | no_license | [
{
"docstring": ":type root: TreeNode :type val: int :rtype: TreeNode",
"name": "searchBST",
"signature": "def searchBST(self, root, val)"
},
{
"docstring": ":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)",
"name": "searchBST2",
"signature": "def searchBST2(self,... | 2 | stack_v2_sparse_classes_30k_train_000012 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def searchBST(self, root, val): :type root: TreeNode :type val: int :rtype: TreeNode
- def searchBST2(self, root, val): :param root: :param val: :return: Recursion Space: O(logn)... | a5b02044ef39154b6a8d32eb57682f447e1632ba | <|skeleton|>
class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
<|body_0|>
def searchBST2(self, root, val):
""":param root: :param val: :return: Recursion Space: O(logn) Time: O(logn)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def searchBST(self, root, val):
""":type root: TreeNode :type val: int :rtype: TreeNode"""
if root is None:
return None
if root.val == val:
return root
elif val < root.val:
return self.searchBST(root.left, val)
else:
... | the_stack_v2_python_sparse | algo/tree/search_in_binary_search_tree.py | xys234/coding-problems | train | 0 | |
5888a0f645d40a3f46b1ce61a5b8e82af6d9bcb6 | [
"mmax = {'max': 0}\n\ndef dfs(node, cnt):\n if node:\n cnt += 1\n else:\n return\n if not node.left and (not node.right):\n mmax['max'] = max(mmax['max'], cnt)\n if node.left:\n dfs(node.left, cnt)\n if node.right:\n dfs(node.right, cnt)\ndfs(root, 0)\nreturn mmax['... | <|body_start_0|>
mmax = {'max': 0}
def dfs(node, cnt):
if node:
cnt += 1
else:
return
if not node.left and (not node.right):
mmax['max'] = max(mmax['max'], cnt)
if node.left:
dfs(node.left, c... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rewrite2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
mmax = {'max': 0}
def dfs(node, cnt):
... | stack_v2_sparse_classes_10k_train_004791 | 1,811 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "rewrite2",
"signature": "def rewrite2(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006410 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def rewrite2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def rewrite2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, root... | 6350568d16b0f8c49a020f055bb6d72e2705ea56 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def rewrite2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
mmax = {'max': 0}
def dfs(node, cnt):
if node:
cnt += 1
else:
return
if not node.left and (not node.right):
mmax['max'] = max(... | the_stack_v2_python_sparse | co_linkedin/104_Maximum_Depth_of_Binary_Tree.py | vsdrun/lc_public | train | 6 | |
f75fcb224e5b2562f7f0a73d60a59430b7b0ef59 | [
"if not callable(self.val):\n raise TypeError('val must be callable')\nif not issubclass(ex, BaseException):\n raise TypeError('given arg must be exception')\nreturn self.builder(self.val, self.description, self.kind, ex)",
"if not self.expected:\n raise TypeError('expected exception not set, raises() mu... | <|body_start_0|>
if not callable(self.val):
raise TypeError('val must be callable')
if not issubclass(ex, BaseException):
raise TypeError('given arg must be exception')
return self.builder(self.val, self.description, self.kind, ex)
<|end_body_0|>
<|body_start_1|>
... | Expected exception mixin. | ExceptionMixin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExceptionMixin:
"""Expected exception mixin."""
def raises(self, ex):
"""Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must chain to :meth:`~when_called_with` to invoke ``val()``. Ar... | stack_v2_sparse_classes_10k_train_004792 | 4,692 | permissive | [
{
"docstring": "Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must chain to :meth:`~when_called_with` to invoke ``val()``. Args: ex: the expected exception Examples: Usage:: assert_that(some_func).raises(Runtim... | 2 | stack_v2_sparse_classes_30k_train_002379 | Implement the Python class `ExceptionMixin` described below.
Class description:
Expected exception mixin.
Method signatures and docstrings:
- def raises(self, ex): Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must c... | Implement the Python class `ExceptionMixin` described below.
Class description:
Expected exception mixin.
Method signatures and docstrings:
- def raises(self, ex): Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must c... | 4f830045d78004946db562536b0c875b1a2180c4 | <|skeleton|>
class ExceptionMixin:
"""Expected exception mixin."""
def raises(self, ex):
"""Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must chain to :meth:`~when_called_with` to invoke ``val()``. Ar... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ExceptionMixin:
"""Expected exception mixin."""
def raises(self, ex):
"""Asserts that val is callable and set the expected exception. Just sets the expected exception, but never calls val, and therefore never failes. You must chain to :meth:`~when_called_with` to invoke ``val()``. Args: ex: the e... | the_stack_v2_python_sparse | assertpy/exception.py | assertpy/assertpy | train | 222 |
0925e414371759d5af758e6e43d449ec059a1df8 | [
"if model._meta.app_label in self.route_app_labels:\n return model._meta.app_label\nreturn None",
"if model._meta.app_label in self.route_app_labels:\n return model._meta.app_label\nreturn None",
"if obj1._meta.app_label == obj2._meta.app_label:\n return True\nelse:\n return None",
"if app_label i... | <|body_start_0|>
if model._meta.app_label in self.route_app_labels:
return model._meta.app_label
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in self.route_app_labels:
return model._meta.app_label
return None
<|end_body_1|>
<|body_start_2... | A router to control all database operations on models e Models go to db with same name than his app | EncuestasRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncuestasRouter:
"""A router to control all database operations on models e Models go to db with same name than his app"""
def db_for_read(self, model, **hints):
"""Attempts to read models"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write... | stack_v2_sparse_classes_10k_train_004793 | 1,158 | no_license | [
{
"docstring": "Attempts to read models",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write models",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hints)"
},
{
"docstring": "Allow relations if ... | 4 | stack_v2_sparse_classes_30k_train_006766 | Implement the Python class `EncuestasRouter` described below.
Class description:
A router to control all database operations on models e Models go to db with same name than his app
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read models
- def db_for_write(self, model, **hint... | Implement the Python class `EncuestasRouter` described below.
Class description:
A router to control all database operations on models e Models go to db with same name than his app
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read models
- def db_for_write(self, model, **hint... | ea41397bbee7c204f590d39569a9060f1410a819 | <|skeleton|>
class EncuestasRouter:
"""A router to control all database operations on models e Models go to db with same name than his app"""
def db_for_read(self, model, **hints):
"""Attempts to read models"""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EncuestasRouter:
"""A router to control all database operations on models e Models go to db with same name than his app"""
def db_for_read(self, model, **hints):
"""Attempts to read models"""
if model._meta.app_label in self.route_app_labels:
return model._meta.app_label
... | the_stack_v2_python_sparse | django/tfmsurveysapp/router.py | dsm9/TreballFiMaster | train | 0 |
debb9729a7b4c1d5c8836b55546794931979aaaf | [
"if n == 0:\n return 1\nelif n > 0:\n return self.pow_pos(x, n)\nelse:\n return 1.0 / self.pow_pos(x, abs(n))",
"num = x\nresult = 1\nwhile n > 0:\n if n & 1 == 1:\n result *= num\n num = num * num\n n = n >> 1\nreturn result"
] | <|body_start_0|>
if n == 0:
return 1
elif n > 0:
return self.pow_pos(x, n)
else:
return 1.0 / self.pow_pos(x, abs(n))
<|end_body_0|>
<|body_start_1|>
num = x
result = 1
while n > 0:
if n & 1 == 1:
result *= ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def my_pow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def pow_pos(self, x, n):
"""n: 是正整数"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if n == 0:
return 1
elif n > 0:
return s... | stack_v2_sparse_classes_10k_train_004794 | 1,687 | no_license | [
{
"docstring": ":type x: float :type n: int :rtype: float",
"name": "my_pow",
"signature": "def my_pow(self, x, n)"
},
{
"docstring": "n: 是正整数",
"name": "pow_pos",
"signature": "def pow_pos(self, x, n)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000091 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def my_pow(self, x, n): :type x: float :type n: int :rtype: float
- def pow_pos(self, x, n): n: 是正整数 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def my_pow(self, x, n): :type x: float :type n: int :rtype: float
- def pow_pos(self, x, n): n: 是正整数
<|skeleton|>
class Solution:
def my_pow(self, x, n):
""":type x... | dd917b6eba48eef42f1086a54880bab6cd1fbf07 | <|skeleton|>
class Solution:
def my_pow(self, x, n):
""":type x: float :type n: int :rtype: float"""
<|body_0|>
def pow_pos(self, x, n):
"""n: 是正整数"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def my_pow(self, x, n):
""":type x: float :type n: int :rtype: float"""
if n == 0:
return 1
elif n > 0:
return self.pow_pos(x, n)
else:
return 1.0 / self.pow_pos(x, abs(n))
def pow_pos(self, x, n):
"""n: 是正整数"""
... | the_stack_v2_python_sparse | algorithms/BAT-algorithms/Math/pow(x,n).py | williamsyb/mycookbook | train | 2 | |
e3f1e91a022165a526299378047d7249c65a6eaa | [
"username = request.GET.get('username', None)\nif username is not None:\n tutor = get_object_or_404(Tutor, user__username=username)\n serializer = TutorSerializer(tutor)\n return JsonResponse({'tutors': [serializer.data]}, safe=False)\nelse:\n tutors = Tutor.objects.all()\n serializer = TutorSerializ... | <|body_start_0|>
username = request.GET.get('username', None)
if username is not None:
tutor = get_object_or_404(Tutor, user__username=username)
serializer = TutorSerializer(tutor)
return JsonResponse({'tutors': [serializer.data]}, safe=False)
else:
... | 导员view | Tutors | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_0|>
def post(self, request):
"""增加导员"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
username = request.GET.get(... | stack_v2_sparse_classes_10k_train_004795 | 16,053 | permissive | [
{
"docstring": "查询导员",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "增加导员",
"name": "post",
"signature": "def post(self, request)"
},
{
"docstring": "删除导员",
"name": "delete",
"signature": "def delete(self, request)"
}
] | 3 | stack_v2_sparse_classes_30k_train_004034 | Implement the Python class `Tutors` described below.
Class description:
导员view
Method signatures and docstrings:
- def get(self, request): 查询导员
- def post(self, request): 增加导员
- def delete(self, request): 删除导员 | Implement the Python class `Tutors` described below.
Class description:
导员view
Method signatures and docstrings:
- def get(self, request): 查询导员
- def post(self, request): 增加导员
- def delete(self, request): 删除导员
<|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_... | 7aaa1be773718de1beb3ce0080edca7c4114b7ad | <|skeleton|>
class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
<|body_0|>
def post(self, request):
"""增加导员"""
<|body_1|>
def delete(self, request):
"""删除导员"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Tutors:
"""导员view"""
def get(self, request):
"""查询导员"""
username = request.GET.get('username', None)
if username is not None:
tutor = get_object_or_404(Tutor, user__username=username)
serializer = TutorSerializer(tutor)
return JsonResponse({'tut... | the_stack_v2_python_sparse | user/views.py | MIXISAMA/MIS-backend | train | 0 |
c0938f07b1ab9c2e08d49e1fe41c9444a815eb9b | [
"res = 0\nwhile n > 0:\n res += n & 1\n n = n >> 1\nreturn res",
"res = 0\nwhile n > 0:\n res += n & n - 1\n n = n >> 1\nreturn res"
] | <|body_start_0|>
res = 0
while n > 0:
res += n & 1
n = n >> 1
return res
<|end_body_0|>
<|body_start_1|>
res = 0
while n > 0:
res += n & n - 1
n = n >> 1
return res
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
res = 0
while n > 0:
res += n & 1
... | stack_v2_sparse_classes_10k_train_004796 | 1,531 | no_license | [
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
},
{
"docstring": ":type n: int :rtype: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007142 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight(self, n): :type n: int :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, n): :type n: int :rtype: int
- def hammingWeight(self, n): :type n: int :rtype: int
<|skeleton|>
class Solution:
def hammingWeight(self, n):
... | 03ec8138fc1fe955a8b00c2b519f33f20cc4a435 | <|skeleton|>
class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_0|>
def hammingWeight(self, n):
""":type n: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, n):
""":type n: int :rtype: int"""
res = 0
while n > 0:
res += n & 1
n = n >> 1
return res
def hammingWeight(self, n):
""":type n: int :rtype: int"""
res = 0
while n > 0:
res += n... | the_stack_v2_python_sparse | 6-12leetcode/面试题15二进制中1的个数.py | Wang663/leetcode | train | 1 | |
688e4ff0f0c1c6dd0ea62cbcc21c85b52de289e2 | [
"super().__init__()\nself.repository = repository\nself.commit_only = commit_only\nself.brain = Brain(repository)",
"if '/.' in event.src_path:\n return\nupdated_file = os.path.relpath(event.src_path, self.repository.original_path)\nif not updated_file or updated_file in self.repository.ignored_files or (not u... | <|body_start_0|>
super().__init__()
self.repository = repository
self.commit_only = commit_only
self.brain = Brain(repository)
<|end_body_0|>
<|body_start_1|>
if '/.' in event.src_path:
return
updated_file = os.path.relpath(event.src_path, self.repository.ori... | Is notified every time an event occurs on the fileystem and will snapshot the change | ChangeWatchdog | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ChangeWatchdog:
"""Is notified every time an event occurs on the fileystem and will snapshot the change"""
def __init__(self, repository, commit_only: bool):
"""Create a ChangeWatchdog instance"""
<|body_0|>
def on_any_event(self, event):
"""Catches all events"""... | stack_v2_sparse_classes_10k_train_004797 | 4,518 | no_license | [
{
"docstring": "Create a ChangeWatchdog instance",
"name": "__init__",
"signature": "def __init__(self, repository, commit_only: bool)"
},
{
"docstring": "Catches all events",
"name": "on_any_event",
"signature": "def on_any_event(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006101 | Implement the Python class `ChangeWatchdog` described below.
Class description:
Is notified every time an event occurs on the fileystem and will snapshot the change
Method signatures and docstrings:
- def __init__(self, repository, commit_only: bool): Create a ChangeWatchdog instance
- def on_any_event(self, event): ... | Implement the Python class `ChangeWatchdog` described below.
Class description:
Is notified every time an event occurs on the fileystem and will snapshot the change
Method signatures and docstrings:
- def __init__(self, repository, commit_only: bool): Create a ChangeWatchdog instance
- def on_any_event(self, event): ... | b669eab9abecfaf8310f0668a7e5f95b2308d885 | <|skeleton|>
class ChangeWatchdog:
"""Is notified every time an event occurs on the fileystem and will snapshot the change"""
def __init__(self, repository, commit_only: bool):
"""Create a ChangeWatchdog instance"""
<|body_0|>
def on_any_event(self, event):
"""Catches all events"""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ChangeWatchdog:
"""Is notified every time an event occurs on the fileystem and will snapshot the change"""
def __init__(self, repository, commit_only: bool):
"""Create a ChangeWatchdog instance"""
super().__init__()
self.repository = repository
self.commit_only = commit_on... | the_stack_v2_python_sparse | bug_buddy/watcher.py | NathanBWaters/bug_buddy | train | 0 |
2d004ee7d91609d7ab695d23f0b696d5beacdda4 | [
"super().__init__(router, description)\nself._partition = partition\nself._attr_name = f\"{partition['label']} {description.name}\"\nself._attr_unique_id = f\"{router.mac} {description.key} {disk['id']} {partition['id']}\"\nself._attr_device_info = DeviceInfo(identifiers={(DOMAIN, disk['id'])}, model=disk['model'],... | <|body_start_0|>
super().__init__(router, description)
self._partition = partition
self._attr_name = f"{partition['label']} {description.name}"
self._attr_unique_id = f"{router.mac} {description.key} {disk['id']} {partition['id']}"
self._attr_device_info = DeviceInfo(identifiers=... | Representation of a Freebox disk sensor. | FreeboxDiskSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FreeboxDiskSensor:
"""Representation of a Freebox disk sensor."""
def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None:
"""Initialize a Freebox disk sensor."""
<|body_0|>
def async_update... | stack_v2_sparse_classes_10k_train_004798 | 7,660 | permissive | [
{
"docstring": "Initialize a Freebox disk sensor.",
"name": "__init__",
"signature": "def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None"
},
{
"docstring": "Update the Freebox disk sensor.",
"name": "async_... | 2 | null | Implement the Python class `FreeboxDiskSensor` described below.
Class description:
Representation of a Freebox disk sensor.
Method signatures and docstrings:
- def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None: Initialize a Freebox... | Implement the Python class `FreeboxDiskSensor` described below.
Class description:
Representation of a Freebox disk sensor.
Method signatures and docstrings:
- def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None: Initialize a Freebox... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class FreeboxDiskSensor:
"""Representation of a Freebox disk sensor."""
def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None:
"""Initialize a Freebox disk sensor."""
<|body_0|>
def async_update... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FreeboxDiskSensor:
"""Representation of a Freebox disk sensor."""
def __init__(self, router: FreeboxRouter, disk: dict[str, Any], partition: dict[str, Any], description: SensorEntityDescription) -> None:
"""Initialize a Freebox disk sensor."""
super().__init__(router, description)
... | the_stack_v2_python_sparse | homeassistant/components/freebox/sensor.py | home-assistant/core | train | 35,501 |
3e56e0bc6a88cfed99a3b9a024311f14daa90b10 | [
"super(Cont_RDB, self).__init__()\nself.InChan = InChannel\nself.OutChan = OutChannel\nself.G = growRate\nself.C = nConvLayers\nif self.InChan != self.G:\n self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)\nif self.OutChan != self.G and self.OutChan != self.InChan:\n self.OutConv = nn.Conv2... | <|body_start_0|>
super(Cont_RDB, self).__init__()
self.InChan = InChannel
self.OutChan = OutChannel
self.G = growRate
self.C = nConvLayers
if self.InChan != self.G:
self.InConv = nn.Conv2d(self.InChan, self.G, 1, padding=0, stride=1)
if self.OutChan !=... | Contextual residual dense block. | Cont_RDB | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param gro... | stack_v2_sparse_classes_10k_train_004799 | 13,650 | permissive | [
{
"docstring": "Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth rate of block :type growRate: int :param nConvLayers: the number of convlution layer :type nConvLayers: int :param kSize: ker... | 2 | null | Implement the Python class `Cont_RDB` described below.
Class description:
Contextual residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ... | Implement the Python class `Cont_RDB` described below.
Class description:
Contextual residual dense block.
Method signatures and docstrings:
- def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3): Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: ... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param gro... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Cont_RDB:
"""Contextual residual dense block."""
def __init__(self, InChannel, OutChannel, growRate, nConvLayers, kSize=3):
"""Initialize Block. :param InChannel: channel number of input :type InChannel: int :param OutChannel: channel number of output :type OutChannel: int :param growRate: growth... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Darts_for_TensorFlow/automl/vega/search_space/networks/pytorch/esrbodys/erdb_esr.py | Huawei-Ascend/modelzoo | train | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.