blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a1648c1a2bb9f3e5b92a87bc73a7821785155aea | [
"encryption_validator = EncryptionValidationHandler()\nencryption_processor = EncryptionProccessorHandler()\nencryption_resulter = EncryptionResultHandler()\nencryption_validator.set_handler(encryption_processor)\nencryption_processor.set_handler(encryption_resulter)\ndecryption_validator = DecryptionValidationHand... | <|body_start_0|>
encryption_validator = EncryptionValidationHandler()
encryption_processor = EncryptionProccessorHandler()
encryption_resulter = EncryptionResultHandler()
encryption_validator.set_handler(encryption_processor)
encryption_processor.set_handler(encryption_resulter)
... | Crypto | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
<|body_0|>
def execute_request(self, request: Request):
"""Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to h... | stack_v2_sparse_classes_36k_train_031800 | 11,978 | no_license | [
{
"docstring": "Sets up the chain of responsibility.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to handlers. :return:",
"name":... | 2 | stack_v2_sparse_classes_30k_train_006158 | Implement the Python class `Crypto` described below.
Class description:
Implement the Crypto class.
Method signatures and docstrings:
- def __init__(self): Sets up the chain of responsibility.
- def execute_request(self, request: Request): Execute the corrrect chain of responsibility handler depending on Encryption o... | Implement the Python class `Crypto` described below.
Class description:
Implement the Crypto class.
Method signatures and docstrings:
- def __init__(self): Sets up the chain of responsibility.
- def execute_request(self, request: Request): Execute the corrrect chain of responsibility handler depending on Encryption o... | 00fb890bb9d39859af2211db1f2bd783fcb04d2d | <|skeleton|>
class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
<|body_0|>
def execute_request(self, request: Request):
"""Execute the corrrect chain of responsibility handler depending on Encryption or Decryption Mode. :param request: the Request to pass to h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Crypto:
def __init__(self):
"""Sets up the chain of responsibility."""
encryption_validator = EncryptionValidationHandler()
encryption_processor = EncryptionProccessorHandler()
encryption_resulter = EncryptionResultHandler()
encryption_validator.set_handler(encryption_p... | the_stack_v2_python_sparse | Labs/Lab9/crypto.py | ZenenHornstein/3522_A01185704 | train | 0 | |
9e9f4b553b7151b0c0db0cdc26ceb86dd82f278a | [
"if not root:\n return 0\n\ndef recur(node: TreeNode, min_ancestor: int, max_ancestor: int) -> int:\n max_diff = max(abs(node.val - min_ancestor), abs(node.val - max_ancestor))\n min_ancestor = min(min_ancestor, node.val)\n max_ancestor = max(max_ancestor, node.val)\n if node.left:\n max_diff ... | <|body_start_0|>
if not root:
return 0
def recur(node: TreeNode, min_ancestor: int, max_ancestor: int) -> int:
max_diff = max(abs(node.val - min_ancestor), abs(node.val - max_ancestor))
min_ancestor = min(min_ancestor, node.val)
max_ancestor = max(max_anc... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
"""When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the diff When going up (end of recursion): - look at the max difference on left and right - take the m... | stack_v2_sparse_classes_36k_train_031801 | 2,439 | no_license | [
{
"docstring": "When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the diff When going up (end of recursion): - look at the max difference on left and right - take the max with own difference with above Complexity is O(N)",
"name": "max... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAncestorDiff(self, root: TreeNode) -> int: When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the d... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAncestorDiff(self, root: TreeNode) -> int: When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the d... | 3ffcfee5cedf421d5de6d0dec4ba53b0eecbbff8 | <|skeleton|>
class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
"""When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the diff When going up (end of recursion): - look at the max difference on left and right - take the m... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAncestorDiff(self, root: TreeNode) -> int:
"""When going down the descendants: - keep the minimum value of ancestor - keep the maximum value of ancestor => Allows to do the diff When going up (end of recursion): - look at the max difference on left and right - take the max with own di... | the_stack_v2_python_sparse | binary_tree/MaxDifferenceBetweenNodeAndAncestor.py | QuentinDuval/PythonExperiments | train | 3 | |
a9ae5737be86447d65aa330a9d86e17a84683af3 | [
"user = self.ss.get_user()\ngroups = list(self.gs.list(user))\nreturn groups",
"v = Validator(group_schema)\nargs = v.validated(request.get_json())\nif args is None:\n return ApiResponse(status=4001, errors=v.errors)\nname = args.get(u'name')\ndescription = args.get(u'description', u'')\nuser = self.ss.get_use... | <|body_start_0|>
user = self.ss.get_user()
groups = list(self.gs.list(user))
return groups
<|end_body_0|>
<|body_start_1|>
v = Validator(group_schema)
args = v.validated(request.get_json())
if args is None:
return ApiResponse(status=4001, errors=v.errors)
... | GroupsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupsAPI:
def get(self):
"""Return groups by user. :return:"""
<|body_0|>
def post(self):
"""Create new group :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
user = self.ss.get_user()
groups = list(self.gs.list(user))
retur... | stack_v2_sparse_classes_36k_train_031802 | 3,884 | permissive | [
{
"docstring": "Return groups by user. :return:",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create new group :return:",
"name": "post",
"signature": "def post(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004979 | Implement the Python class `GroupsAPI` described below.
Class description:
Implement the GroupsAPI class.
Method signatures and docstrings:
- def get(self): Return groups by user. :return:
- def post(self): Create new group :return: | Implement the Python class `GroupsAPI` described below.
Class description:
Implement the GroupsAPI class.
Method signatures and docstrings:
- def get(self): Return groups by user. :return:
- def post(self): Create new group :return:
<|skeleton|>
class GroupsAPI:
def get(self):
"""Return groups by user. ... | 9a336d1e467d08c6b3875bd8b83dea0dc3b9236d | <|skeleton|>
class GroupsAPI:
def get(self):
"""Return groups by user. :return:"""
<|body_0|>
def post(self):
"""Create new group :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GroupsAPI:
def get(self):
"""Return groups by user. :return:"""
user = self.ss.get_user()
groups = list(self.gs.list(user))
return groups
def post(self):
"""Create new group :return:"""
v = Validator(group_schema)
args = v.validated(request.get_json... | the_stack_v2_python_sparse | we-web/api/resources/groups/groups.py | avatar29A/wordeater-web | train | 0 | |
353968c3a6343a5c194548a6c34c8e34bf14885a | [
"super().__init__()\nself.use_adapter = use_adapter\nself.adapter_reduce_dim = adapter_reduce_dim\nif use_adapter:\n self.adapter = ResBlockAudio(dim)\n if adapter_reduce_dim:\n self.down = nn.Conv2d(dim, dim, 4, (2, 2), 1)\n self.up = nn.ConvTranspose2d(dim, dim, 4, (2, 2), 1)\nself.decoder = n... | <|body_start_0|>
super().__init__()
self.use_adapter = use_adapter
self.adapter_reduce_dim = adapter_reduce_dim
if use_adapter:
self.adapter = ResBlockAudio(dim)
if adapter_reduce_dim:
self.down = nn.Conv2d(dim, dim, 4, (2, 2), 1)
s... | Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or equivalently number of neurons at the output per timestep) num_classes : int N... | PsiOptimized | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PsiOptimized:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or equivalently number of neurons at the ... | stack_v2_sparse_classes_36k_train_031803 | 11,147 | permissive | [
{
"docstring": "Computes NMF activations from hidden state.",
"name": "__init__",
"signature": "def __init__(self, dim=128, K=100, numclasses=50, use_adapter=False, adapter_reduce_dim=True)"
},
{
"docstring": "Computes forward step. Arguments ------- hs : torch.Tensor Latent representations (inp... | 2 | stack_v2_sparse_classes_30k_train_008971 | Implement the Python class `PsiOptimized` described below.
Class description:
Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or... | Implement the Python class `PsiOptimized` described below.
Class description:
Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class PsiOptimized:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or equivalently number of neurons at the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PsiOptimized:
"""Convolutional Layers to estimate NMF Activations from Classifier Representations, optimized for log-spectra. Arguments --------- dim: int Dimension of the hidden representations (input to the classifier). K : int Number of NMF components (or equivalently number of neurons at the output per ti... | the_stack_v2_python_sparse | PyTorch/dev/perf/speechbrain-tdnn/speechbrain/lobes/models/L2I.py | Ascend/ModelZoo-PyTorch | train | 23 |
18666b57d4e0a04ddbc436b831c77eac9fc0fd0a | [
"self._api_key = api_key\nself._device_id = device_id\nself._device_ids = device_ids\nself._device_names = device_names",
"title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)\ndata = kwargs.get(ATTR_DATA) or {}\nsend_notification(device_id=self._device_id, device_ids=self._device_ids, device_names=self._device_nam... | <|body_start_0|>
self._api_key = api_key
self._device_id = device_id
self._device_ids = device_ids
self._device_names = device_names
<|end_body_0|>
<|body_start_1|>
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
data = kwargs.get(ATTR_DATA) or {}
send_notific... | Implement the notification service for Join. | JoinNotificationService | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a user."""
... | stack_v2_sparse_classes_36k_train_031804 | 3,006 | permissive | [
{
"docstring": "Initialize the service.",
"name": "__init__",
"signature": "def __init__(self, api_key, device_id, device_ids, device_names)"
},
{
"docstring": "Send a message to a user.",
"name": "send_message",
"signature": "def send_message(self, message='', **kwargs)"
}
] | 2 | null | Implement the Python class `JoinNotificationService` described below.
Class description:
Implement the notification service for Join.
Method signatures and docstrings:
- def __init__(self, api_key, device_id, device_ids, device_names): Initialize the service.
- def send_message(self, message='', **kwargs): Send a mes... | Implement the Python class `JoinNotificationService` described below.
Class description:
Implement the notification service for Join.
Method signatures and docstrings:
- def __init__(self, api_key, device_id, device_ids, device_names): Initialize the service.
- def send_message(self, message='', **kwargs): Send a mes... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
<|body_0|>
def send_message(self, message='', **kwargs):
"""Send a message to a user."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JoinNotificationService:
"""Implement the notification service for Join."""
def __init__(self, api_key, device_id, device_ids, device_names):
"""Initialize the service."""
self._api_key = api_key
self._device_id = device_id
self._device_ids = device_ids
self._devic... | the_stack_v2_python_sparse | homeassistant/components/joaoapps_join/notify.py | home-assistant/core | train | 35,501 |
ab6158bb9d8295e9e040df8aa0ce354f8a050ac7 | [
"net = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)\ngateway = str(netaddr.IPAddress(net.first + 2))\nnetwork = self.create_network()\nsubnet = self.create_subnet(network, gateway)\nself.assertEqual(subnet['gateway_ip'], gateway)",
"net = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)\ngateway... | <|body_start_0|>
net = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)
gateway = str(netaddr.IPAddress(net.first + 2))
network = self.create_network()
subnet = self.create_subnet(network, gateway)
self.assertEqual(subnet['gateway_ip'], gateway)
<|end_body_0|>
<|body_star... | NetworksIpV6Test | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworksIpV6Test:
def test_create_delete_subnet_with_gw(self):
"""Verify creating and deleting subnet with gateway"""
<|body_0|>
def test_create_delete_subnet_with_default_gw(self):
"""Verify creating and deleting subnet without specified gateway"""
<|body_1|... | stack_v2_sparse_classes_36k_train_031805 | 31,379 | permissive | [
{
"docstring": "Verify creating and deleting subnet with gateway",
"name": "test_create_delete_subnet_with_gw",
"signature": "def test_create_delete_subnet_with_gw(self)"
},
{
"docstring": "Verify creating and deleting subnet without specified gateway",
"name": "test_create_delete_subnet_wit... | 3 | null | Implement the Python class `NetworksIpV6Test` described below.
Class description:
Implement the NetworksIpV6Test class.
Method signatures and docstrings:
- def test_create_delete_subnet_with_gw(self): Verify creating and deleting subnet with gateway
- def test_create_delete_subnet_with_default_gw(self): Verify creati... | Implement the Python class `NetworksIpV6Test` described below.
Class description:
Implement the NetworksIpV6Test class.
Method signatures and docstrings:
- def test_create_delete_subnet_with_gw(self): Verify creating and deleting subnet with gateway
- def test_create_delete_subnet_with_default_gw(self): Verify creati... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class NetworksIpV6Test:
def test_create_delete_subnet_with_gw(self):
"""Verify creating and deleting subnet with gateway"""
<|body_0|>
def test_create_delete_subnet_with_default_gw(self):
"""Verify creating and deleting subnet without specified gateway"""
<|body_1|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NetworksIpV6Test:
def test_create_delete_subnet_with_gw(self):
"""Verify creating and deleting subnet with gateway"""
net = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)
gateway = str(netaddr.IPAddress(net.first + 2))
network = self.create_network()
subnet = s... | the_stack_v2_python_sparse | tempest/api/network/test_networks.py | openstack/tempest | train | 270 | |
5c20b2f84bb4c04d8a273c447b6eb80ceede38c0 | [
"print('压缩 %s 到 %s' % (source_dir, target_jar))\nfilex.check_and_create_dir(target_jar)\ntranslation_file_list = []\nfor root, dirs, files in os.walk(source_dir):\n for file_name in files:\n path = root + '/' + file_name\n translation_file_list.append(path.replace(source_dir, '').replace('\\\\', '/... | <|body_start_0|>
print('压缩 %s 到 %s' % (source_dir, target_jar))
filex.check_and_create_dir(target_jar)
translation_file_list = []
for root, dirs, files in os.walk(source_dir):
for file_name in files:
path = root + '/' + file_name
translation_fi... | ZipTools | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZipTools:
def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False):
"""压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:"""
<|body_0|>
def extra_file(zip_file_path, file_path, output, print_msg=True):
"""解压文件"""
... | stack_v2_sparse_classes_36k_train_031806 | 37,444 | no_license | [
{
"docstring": "压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:",
"name": "zip_jar",
"signature": "def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False)"
},
{
"docstring": "解压文件",
"name": "extra_file",
"signature": "def extra_fil... | 2 | stack_v2_sparse_classes_30k_train_020868 | Implement the Python class `ZipTools` described below.
Class description:
Implement the ZipTools class.
Method signatures and docstrings:
- def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False): 压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:
- def extra_file... | Implement the Python class `ZipTools` described below.
Class description:
Implement the ZipTools class.
Method signatures and docstrings:
- def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False): 压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:
- def extra_file... | efea806d49f07d78e3db0390696778d4a7fc6c28 | <|skeleton|>
class ZipTools:
def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False):
"""压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:"""
<|body_0|>
def extra_file(zip_file_path, file_path, output, print_msg=True):
"""解压文件"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZipTools:
def zip_jar(source_dir, target_jar, rename_cn=False, rename_tips=False):
"""压缩文件夹 :param source_dir: :param target_jar: :param rename_cn: 是否将 _zh_CN 重命名再压缩 :return:"""
print('压缩 %s 到 %s' % (source_dir, target_jar))
filex.check_and_create_dir(target_jar)
translation_fi... | the_stack_v2_python_sparse | ToolsX/tool/android/android_studio_translator/jet_brains_translator/jet_brains_translator.py | JunLei-MI/PythonX | train | 0 | |
a4d7dedd52736b68b3c913b5fde707957af23d54 | [
"def f1():\n return 1\n\ndef f2():\n return 2\n\ndef f3():\n pass\nreturn_values = parallel.RunParallelSteps([f1, f2, f3], return_values=True)\nself.assertEquals(return_values, [1, 2, None])",
"def f1():\n return ret_value\nret_value = ''\nfor _ in xrange(10000):\n ret_value += 'This will be repeat... | <|body_start_0|>
def f1():
return 1
def f2():
return 2
def f3():
pass
return_values = parallel.RunParallelSteps([f1, f2, f3], return_values=True)
self.assertEquals(return_values, [1, 2, None])
<|end_body_0|>
<|body_start_1|>
def f1()... | Tests for RunParallelSteps. | TestRunParallelSteps | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRunParallelSteps:
"""Tests for RunParallelSteps."""
def testReturnValues(self):
"""Test that we pass return values through when requested."""
<|body_0|>
def testLargeReturnValues(self):
"""Test that the managed queue prevents hanging on large return values.""... | stack_v2_sparse_classes_36k_train_031807 | 19,222 | permissive | [
{
"docstring": "Test that we pass return values through when requested.",
"name": "testReturnValues",
"signature": "def testReturnValues(self)"
},
{
"docstring": "Test that the managed queue prevents hanging on large return values.",
"name": "testLargeReturnValues",
"signature": "def tes... | 2 | null | Implement the Python class `TestRunParallelSteps` described below.
Class description:
Tests for RunParallelSteps.
Method signatures and docstrings:
- def testReturnValues(self): Test that we pass return values through when requested.
- def testLargeReturnValues(self): Test that the managed queue prevents hanging on l... | Implement the Python class `TestRunParallelSteps` described below.
Class description:
Tests for RunParallelSteps.
Method signatures and docstrings:
- def testReturnValues(self): Test that we pass return values through when requested.
- def testLargeReturnValues(self): Test that the managed queue prevents hanging on l... | 72a05af97787001756bae2511b7985e61498c965 | <|skeleton|>
class TestRunParallelSteps:
"""Tests for RunParallelSteps."""
def testReturnValues(self):
"""Test that we pass return values through when requested."""
<|body_0|>
def testLargeReturnValues(self):
"""Test that the managed queue prevents hanging on large return values.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestRunParallelSteps:
"""Tests for RunParallelSteps."""
def testReturnValues(self):
"""Test that we pass return values through when requested."""
def f1():
return 1
def f2():
return 2
def f3():
pass
return_values = parallel.Run... | the_stack_v2_python_sparse | third_party/chromite/lib/parallel_unittest.py | metux/chromium-suckless | train | 5 |
d191a3c94fd9cac867ab027a39160e086c449eb3 | [
"timestamp = []\nfor trip in trips:\n timestamp.append([trip[1], trip[0]])\n timestamp.append([trip[2], -trip[0]])\ntimestamp.sort()\nused_capacity = 0\nfor time, passenger_change in timestamp:\n used_capacity += passenger_change\n if used_capacity > capacity:\n return False\nreturn True",
"tim... | <|body_start_0|>
timestamp = []
for trip in trips:
timestamp.append([trip[1], trip[0]])
timestamp.append([trip[2], -trip[0]])
timestamp.sort()
used_capacity = 0
for time, passenger_change in timestamp:
used_capacity += passenger_change
... | == Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort approach. | OfficialSolution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OfficialSolution:
"""== Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort approach."""
def carPoolingApproach1... | stack_v2_sparse_classes_36k_train_031808 | 4,273 | no_license | [
{
"docstring": "== Approach 1: Time Stamp == == Intuition == A simple idea is to go through from the start to end, and check if the actual capacity exceeds `capacity`. To know the actual capacity, we just need the number of passengers changed at each timestamp. We can save the number of passengers changed at ea... | 2 | null | Implement the Python class `OfficialSolution` described below.
Class description:
== Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort ap... | Implement the Python class `OfficialSolution` described below.
Class description:
== Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort ap... | 221f0cb3105e4ccaec40cd1d37b9d7d5e218c731 | <|skeleton|>
class OfficialSolution:
"""== Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort approach."""
def carPoolingApproach1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OfficialSolution:
"""== Overview == It is one of the classical problems related to intervals, and we have some similar problems such as Meeting Rooms II at LeetCode. Below, two approaches are introduced: the simple Time Stamp approach, and the Bucket Sort approach."""
def carPoolingApproach1(self, trips:... | the_stack_v2_python_sparse | problems/car_pooling.py | saubhik/leetcode | train | 3 |
08cfdcc97016edc56b3a099c5f01cd65edbe7b3d | [
"Part = self.old_state.apps.get_model('part', 'part')\nPart.objects.create(name='A', description='My part A')\nPart.objects.create(name='B', description='My part B')\nPart.objects.create(name='C', description='My part C')\nPart.objects.create(name='D', description='My part D')\nPart.objects.create(name='E', descrip... | <|body_start_0|>
Part = self.old_state.apps.get_model('part', 'part')
Part.objects.create(name='A', description='My part A')
Part.objects.create(name='B', description='My part B')
Part.objects.create(name='C', description='My part C')
Part.objects.create(name='D', description='My... | Test entire schema migration sequence for the part app. | TestForwardMigrations | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestForwardMigrations:
"""Test entire schema migration sequence for the part app."""
def prepare(self):
"""Create initial data."""
<|body_0|>
def test_models_exist(self):
"""Test that the Part model can still be accessed at the end of schema migration"""
... | stack_v2_sparse_classes_36k_train_031809 | 8,200 | permissive | [
{
"docstring": "Create initial data.",
"name": "prepare",
"signature": "def prepare(self)"
},
{
"docstring": "Test that the Part model can still be accessed at the end of schema migration",
"name": "test_models_exist",
"signature": "def test_models_exist(self)"
}
] | 2 | null | Implement the Python class `TestForwardMigrations` described below.
Class description:
Test entire schema migration sequence for the part app.
Method signatures and docstrings:
- def prepare(self): Create initial data.
- def test_models_exist(self): Test that the Part model can still be accessed at the end of schema ... | Implement the Python class `TestForwardMigrations` described below.
Class description:
Test entire schema migration sequence for the part app.
Method signatures and docstrings:
- def prepare(self): Create initial data.
- def test_models_exist(self): Test that the Part model can still be accessed at the end of schema ... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class TestForwardMigrations:
"""Test entire schema migration sequence for the part app."""
def prepare(self):
"""Create initial data."""
<|body_0|>
def test_models_exist(self):
"""Test that the Part model can still be accessed at the end of schema migration"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TestForwardMigrations:
"""Test entire schema migration sequence for the part app."""
def prepare(self):
"""Create initial data."""
Part = self.old_state.apps.get_model('part', 'part')
Part.objects.create(name='A', description='My part A')
Part.objects.create(name='B', desc... | the_stack_v2_python_sparse | InvenTree/part/test_migrations.py | inventree/InvenTree | train | 3,077 |
76e19e0a0f53cb4c3e9880f58f7a117fcc228f41 | [
"for name, field in self.fields.items():\n if field.dump_only:\n data.pop(name, None)\nreturn data",
"value = getattr(obj, attr, default)\nif attr == 'default_preview' and (not value):\n return default\nreturn value"
] | <|body_start_0|>
for name, field in self.fields.items():
if field.dump_only:
data.pop(name, None)
return data
<|end_body_0|>
<|body_start_1|>
value = getattr(obj, attr, default)
if attr == 'default_preview' and (not value):
return default
... | Files metadata schema. | FilesSchema | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilesSchema:
"""Files metadata schema."""
def clean(self, data, **kwargs):
"""Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues."""
<|body_0|>
def get_attribute(self, obj, attr... | stack_v2_sparse_classes_36k_train_031810 | 2,614 | permissive | [
{
"docstring": "Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues.",
"name": "clean",
"signature": "def clean(self, data, **kwargs)"
},
{
"docstring": "Override how attributes are retrieved when dumpin... | 2 | null | Implement the Python class `FilesSchema` described below.
Class description:
Files metadata schema.
Method signatures and docstrings:
- def clean(self, data, **kwargs): Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues.
- d... | Implement the Python class `FilesSchema` described below.
Class description:
Files metadata schema.
Method signatures and docstrings:
- def clean(self, data, **kwargs): Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues.
- d... | c41f1ce4ee1ae876baf931bd392712d21ce87680 | <|skeleton|>
class FilesSchema:
"""Files metadata schema."""
def clean(self, data, **kwargs):
"""Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues."""
<|body_0|>
def get_attribute(self, obj, attr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilesSchema:
"""Files metadata schema."""
def clean(self, data, **kwargs):
"""Removes dump_only fields. Why: We want to allow the output of a Schema dump, to be a valid input to a Schema load without causing strange issues."""
for name, field in self.fields.items():
if field.d... | the_stack_v2_python_sparse | invenio_rdm_records/services/schemas/files.py | fenekku/invenio-rdm-records | train | 0 |
22b6ac03284d7553dc7ebc05b88178067999b489 | [
"super(SimpleSession, self).__init__()\nself.sess_callable = sess_callable\nself.args = args\nself.kwargs = kwargs",
"w = self.sess_callable(*self.args, **self.kwargs)\nif isinstance(w, Iterable):\n self.windows.extend(w)\nelse:\n self.windows.append(w)"
] | <|body_start_0|>
super(SimpleSession, self).__init__()
self.sess_callable = sess_callable
self.args = args
self.kwargs = kwargs
<|end_body_0|>
<|body_start_1|>
w = self.sess_callable(*self.args, **self.kwargs)
if isinstance(w, Iterable):
self.windows.extend(w... | A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s). | SimpleSession | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimpleSession:
"""A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s)."""
def __init__(self, sess_callable, *args, **kwargs):
"""Initialize the session with the callable and arguments."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k_train_031811 | 4,027 | permissive | [
{
"docstring": "Initialize the session with the callable and arguments.",
"name": "__init__",
"signature": "def __init__(self, sess_callable, *args, **kwargs)"
},
{
"docstring": "Create the view from the callable",
"name": "on_open",
"signature": "def on_open(self)"
}
] | 2 | null | Implement the Python class `SimpleSession` described below.
Class description:
A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s).
Method signatures and docstrings:
- def __init__(self, sess_callable, *args, **kwargs): Initialize the session with th... | Implement the Python class `SimpleSession` described below.
Class description:
A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s).
Method signatures and docstrings:
- def __init__(self, sess_callable, *args, **kwargs): Initialize the session with th... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class SimpleSession:
"""A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s)."""
def __init__(self, sess_callable, *args, **kwargs):
"""Initialize the session with the callable and arguments."""
<|body_0|>
def ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimpleSession:
"""A concrete Session class that receives a callable, positional, and keyword arguments and creates the associated view(s)."""
def __init__(self, sess_callable, *args, **kwargs):
"""Initialize the session with the callable and arguments."""
super(SimpleSession, self).__init... | the_stack_v2_python_sparse | enaml/stdlib/sessions.py | enthought/enaml | train | 17 |
cc38e48cb8b5603abdfca0d2efe7236cc18a449c | [
"super().__init__(solver_name)\nself.comp_bench = comp_bench\nself.reset_bench_on_fail = reset_bench_on_fail\nself.make_bench = make_bench",
"super().run_sim()\nresult = 0\nif self.comp_bench:\n result = self.compare_to_benchmark(rtol)\nif self.make_bench or (result != 0 and self.reset_bench_on_fail):\n sel... | <|body_start_0|>
super().__init__(solver_name)
self.comp_bench = comp_bench
self.reset_bench_on_fail = reset_bench_on_fail
self.make_bench = make_bench
<|end_body_0|>
<|body_start_1|>
super().run_sim()
result = 0
if self.comp_bench:
result = self.comp... | A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines. | PyroBenchmark | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PyroBenchmark:
"""A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines."""
def __init__(self, solver_name, comp_bench=False, reset_bench_on_fail=False, make_bench=False):
"""Constructor Parameters ---------- solver_name : str Name of solv... | stack_v2_sparse_classes_36k_train_031812 | 11,814 | permissive | [
{
"docstring": "Constructor Parameters ---------- solver_name : str Name of solver to use comp_bench : bool Are we comparing to a benchmark? reset_bench_on_fail : bool Do we reset the benchmark on fail? make_bench : bool Are we storing a benchmark?",
"name": "__init__",
"signature": "def __init__(self, ... | 4 | stack_v2_sparse_classes_30k_train_009940 | Implement the Python class `PyroBenchmark` described below.
Class description:
A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines.
Method signatures and docstrings:
- def __init__(self, solver_name, comp_bench=False, reset_bench_on_fail=False, make_bench=False): Constru... | Implement the Python class `PyroBenchmark` described below.
Class description:
A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines.
Method signatures and docstrings:
- def __init__(self, solver_name, comp_bench=False, reset_bench_on_fail=False, make_bench=False): Constru... | f91789a319caa98dfbc3f496e9953756e6ee3ca9 | <|skeleton|>
class PyroBenchmark:
"""A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines."""
def __init__(self, solver_name, comp_bench=False, reset_bench_on_fail=False, make_bench=False):
"""Constructor Parameters ---------- solver_name : str Name of solv... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PyroBenchmark:
"""A subclass of Pyro for benchmarking. Inherits everything from pyro, but adds benchmarking routines."""
def __init__(self, solver_name, comp_bench=False, reset_bench_on_fail=False, make_bench=False):
"""Constructor Parameters ---------- solver_name : str Name of solver to use com... | the_stack_v2_python_sparse | pyro/pyro_sim.py | python-hydro/pyro2 | train | 202 |
5f440a899da988eee813e52019ee88b6be330be3 | [
"params = {} if params is None else params\nparams.update({'type': params.get('type', 'hive')})\nwith self.post(create_url('/v3/schedule/create/{name}', name=name), params) as res:\n code, body = (res.status, res.read())\n if code != 200:\n self.raise_error('Create schedule failed', res, body)\n js ... | <|body_start_0|>
params = {} if params is None else params
params.update({'type': params.get('type', 'hive')})
with self.post(create_url('/v3/schedule/create/{name}', name=name), params) as res:
code, body = (res.status, res.read())
if code != 200:
self.ra... | Access to Schedule API This class is inherited by :class:`tdclient.api.API`. | ScheduleAPI | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - ... | stack_v2_sparse_classes_36k_train_031813 | 9,750 | permissive | [
{
"docstring": "Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - type (str): Query type. {\"presto\", \"hive\"}. Default: \"hive\" - database (str): Target database name. - timezone (str): Scheduled query's timezone. e.g. ... | 6 | stack_v2_sparse_classes_30k_train_013475 | Implement the Python class `ScheduleAPI` described below.
Class description:
Access to Schedule API This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def create_schedule(self, name, params=None): Create a new scheduled query with the specified name. Args: name (str): Scheduled ... | Implement the Python class `ScheduleAPI` described below.
Class description:
Access to Schedule API This class is inherited by :class:`tdclient.api.API`.
Method signatures and docstrings:
- def create_schedule(self, name, params=None): Create a new scheduled query with the specified name. Args: name (str): Scheduled ... | aa6b1ffe886483cf4a41557d7e72063e49d6c787 | <|skeleton|>
class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScheduleAPI:
"""Access to Schedule API This class is inherited by :class:`tdclient.api.API`."""
def create_schedule(self, name, params=None):
"""Create a new scheduled query with the specified name. Args: name (str): Scheduled query name. params (dict, optional): Extra parameters. - type (str): Q... | the_stack_v2_python_sparse | tdclient/schedule_api.py | treasure-data/td-client-python | train | 41 |
18d9407899c3a13db0b2936d10926bef712404e3 | [
"self.typology = 'ComplexFault'\nself.id = identifier\nself.name = name\nself.trt = trt\nself.geometry = geometry\nself.fault_edges = None\nself.mag_scale_rel = mag_scale_rel\nself.rupt_aspect_ratio = rupt_aspect_ratio\nself.mfd = mfd\nself.rake = rake\nself.upper_depth = None\nself.lower_depth = None\nself.catalog... | <|body_start_0|>
self.typology = 'ComplexFault'
self.id = identifier
self.name = name
self.trt = trt
self.geometry = geometry
self.fault_edges = None
self.mag_scale_rel = mag_scale_rel
self.rupt_aspect_ratio = rupt_aspect_ratio
self.mfd = mfd
... | New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex_fault.ComplexFaultSource :param str mag_scale_rel: Magnitude scaling relationsip :param... | mtkComplexFaultSource | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class mtkComplexFaultSource:
"""New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex_fault.ComplexFaultSource :param str ma... | stack_v2_sparse_classes_36k_train_031814 | 9,358 | permissive | [
{
"docstring": "Instantiate class with just the basic attributes: identifier and name",
"name": "__init__",
"signature": "def __init__(self, identifier, name, trt=None, geometry=None, mag_scale_rel=None, rupt_aspect_ratio=None, mfd=None, rake=None)"
},
{
"docstring": "If geometry is defined as a... | 5 | null | Implement the Python class `mtkComplexFaultSource` described below.
Class description:
New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex... | Implement the Python class `mtkComplexFaultSource` described below.
Class description:
New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class mtkComplexFaultSource:
"""New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex_fault.ComplexFaultSource :param str ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class mtkComplexFaultSource:
"""New class to describe the mtk complex fault source object :param str identifier: ID code for the source :param str name: Source name :param str trt: Tectonic region type :param geometry: Instance of :class: nhlib.geo.surface.complex_fault.ComplexFaultSource :param str mag_scale_rel: ... | the_stack_v2_python_sparse | openquake/hmtk/sources/complex_fault_source.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
a7a709e0f0bd6f3b2c007b79f6dc5f872caa74b3 | [
"if not matrix or not matrix[0]:\n self.rmq = None\nelse:\n self.rmq = [[0] * (len(matrix[0]) + 1)] + [[0] + matrix[r] for r in range(len(matrix))]\n for row in range(1, len(matrix) + 1):\n for col in range(1, len(matrix[0]) + 1):\n self.rmq[row][col] += self.rmq[row][col - 1]\n for co... | <|body_start_0|>
if not matrix or not matrix[0]:
self.rmq = None
else:
self.rmq = [[0] * (len(matrix[0]) + 1)] + [[0] + matrix[r] for r in range(len(matrix))]
for row in range(1, len(matrix) + 1):
for col in range(1, len(matrix[0]) + 1):
... | NumMatrix | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>... | stack_v2_sparse_classes_36k_train_031815 | 1,226 | permissive | [
{
"docstring": ":type matrix: List[List[int]]",
"name": "__init__",
"signature": "def __init__(self, matrix)"
},
{
"docstring": ":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int",
"name": "sumRegion",
"signature": "def sumRegion(self, row1, col1, row2, col2)"
... | 2 | stack_v2_sparse_classes_30k_train_013567 | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | Implement the Python class `NumMatrix` described below.
Class description:
Implement the NumMatrix class.
Method signatures and docstrings:
- def __init__(self, matrix): :type matrix: List[List[int]]
- def sumRegion(self, row1, col1, row2, col2): :type row1: int :type col1: int :type row2: int :type col2: int :rtype:... | ba84c192fb9995dd48ddc6d81c3153488dd3c698 | <|skeleton|>
class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
<|body_0|>
def sumRegion(self, row1, col1, row2, col2):
""":type row1: int :type col1: int :type row2: int :type col2: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumMatrix:
def __init__(self, matrix):
""":type matrix: List[List[int]]"""
if not matrix or not matrix[0]:
self.rmq = None
else:
self.rmq = [[0] * (len(matrix[0]) + 1)] + [[0] + matrix[r] for r in range(len(matrix))]
for row in range(1, len(matrix) +... | the_stack_v2_python_sparse | Python/range-sum-query-2d-immutable.py | phucle2411/LeetCode | train | 0 | |
6ef460057cfc559e9960e95515b2d97ea8f1a9ee | [
"self.old = self.ListNode('dummy', 'dummy')\nself.new = self.ListNode('dummy', 'dummy')\nself.old.next, self.new.prev = (self.new, self.old)\nself.d = {}\nself.capacity = capacity",
"if key not in self.d:\n return -1\nnode = self.d[key]\nif node.prev and node.next:\n node.prev.next, node.next.prev = (node.n... | <|body_start_0|>
self.old = self.ListNode('dummy', 'dummy')
self.new = self.ListNode('dummy', 'dummy')
self.old.next, self.new.prev = (self.new, self.old)
self.d = {}
self.capacity = capacity
<|end_body_0|>
<|body_start_1|>
if key not in self.d:
return -1
... | 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_36k_train_031816 | 1,730 | 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 | null | 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... | a9314896fbe703d74c744e92226d09a4961690f0 | <|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_36k | data/stack_v2_sparse_classes_30k | class LRUCache:
def __init__(self, capacity):
""":type capacity: int"""
self.old = self.ListNode('dummy', 'dummy')
self.new = self.ListNode('dummy', 'dummy')
self.old.next, self.new.prev = (self.new, self.old)
self.d = {}
self.capacity = capacity
def get(self, ke... | the_stack_v2_python_sparse | lc_problems/146.LRUCache.py | itsmenick212/algorithm-in-leetcode | train | 0 | |
c5e1140aa3afe8582da06e1fefc21c04fb37f411 | [
"content2path = {}\nfor item in paths:\n fields = item.split(sep=' ')\n dir_path = fields[0]\n for file in fields[1:]:\n subfields = file.split(sep='.')\n fname = subfields[0]\n content = subfields[1][4:-1]\n if content in content2path:\n content2path[content].append(... | <|body_start_0|>
content2path = {}
for item in paths:
fields = item.split(sep=' ')
dir_path = fields[0]
for file in fields[1:]:
subfields = file.split(sep='.')
fname = subfields[0]
content = subfields[1][4:-1]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findDuplicate(self, paths):
"""HashTable :type paths: List[str] :rtype: List[List[str]]"""
<|body_0|>
def findDuplicate2(self, paths):
"""HashTable :type paths: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_031817 | 1,937 | no_license | [
{
"docstring": "HashTable :type paths: List[str] :rtype: List[List[str]]",
"name": "findDuplicate",
"signature": "def findDuplicate(self, paths)"
},
{
"docstring": "HashTable :type paths: List[str] :rtype: List[List[str]]",
"name": "findDuplicate2",
"signature": "def findDuplicate2(self,... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, paths): HashTable :type paths: List[str] :rtype: List[List[str]]
- def findDuplicate2(self, paths): HashTable :type paths: List[str] :rtype: List[List[str... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findDuplicate(self, paths): HashTable :type paths: List[str] :rtype: List[List[str]]
- def findDuplicate2(self, paths): HashTable :type paths: List[str] :rtype: List[List[str... | 143aa25f92f3827aa379f29c67a9b7ec3757fef9 | <|skeleton|>
class Solution:
def findDuplicate(self, paths):
"""HashTable :type paths: List[str] :rtype: List[List[str]]"""
<|body_0|>
def findDuplicate2(self, paths):
"""HashTable :type paths: List[str] :rtype: List[List[str]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findDuplicate(self, paths):
"""HashTable :type paths: List[str] :rtype: List[List[str]]"""
content2path = {}
for item in paths:
fields = item.split(sep=' ')
dir_path = fields[0]
for file in fields[1:]:
subfields = file.s... | the_stack_v2_python_sparse | py/leetcode_py/609.py | imsure/tech-interview-prep | train | 0 | |
e40f5045801c93b12e4d43bfa759099f3993db0d | [
"directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]\n\n@lru_cache(None)\ndef _rec(i, j, k):\n if k == 0:\n return 0\n cnt = 0\n if i == 0:\n cnt += 1\n if i == m - 1:\n cnt += 1\n if j == 0:\n cnt += 1\n if j == n - 1:\n cnt += 1\n for dx, dy in directions:\n ... | <|body_start_0|>
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
@lru_cache(None)
def _rec(i, j, k):
if k == 0:
return 0
cnt = 0
if i == 0:
cnt += 1
if i == m - 1:
cnt += 1
if j == 0:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
"""06/13/2020 01:04"""
<|body_0|>
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
"""DP Time complexity: O(m*n*maxMove) Space complexity: O(m*n*ma... | stack_v2_sparse_classes_36k_train_031818 | 4,228 | no_license | [
{
"docstring": "06/13/2020 01:04",
"name": "findPaths",
"signature": "def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int"
},
{
"docstring": "DP Time complexity: O(m*n*maxMove) Space complexity: O(m*n*maxMove)",
"name": "findPaths",
"signature": "def findPaths(self, m: int... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int: 06/13/2020 01:04
- def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int: 06/13/2020 01:04
- def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int: ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
"""06/13/2020 01:04"""
<|body_0|>
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
"""DP Time complexity: O(m*n*maxMove) Space complexity: O(m*n*ma... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
"""06/13/2020 01:04"""
directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]
@lru_cache(None)
def _rec(i, j, k):
if k == 0:
return 0
cnt = 0
if i == 0:
... | the_stack_v2_python_sparse | leetcode/solved/576_Out_of_Boundary_Paths/solution.py | sungminoh/algorithms | train | 0 | |
f1d83757e80d1b5229afb869b35ddbd8d9df6dad | [
"player_id = current_user.get('player_id')\nticket = flexmatch.get_player_ticket(player_id)\nif ticket:\n return {'ticket_url': url_for('flexmatch.ticket', ticket_id=ticket['TicketId'], _external=True), 'ticket_id': ticket['TicketId'], 'ticket_status': ticket['Status'], 'matchmaker': ticket['ConfigurationName']}... | <|body_start_0|>
player_id = current_user.get('player_id')
ticket = flexmatch.get_player_ticket(player_id)
if ticket:
return {'ticket_url': url_for('flexmatch.ticket', ticket_id=ticket['TicketId'], _external=True), 'ticket_id': ticket['TicketId'], 'ticket_status': ticket['Status'], '... | FlexMatchTicketsAPI | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlexMatchTicketsAPI:
def get():
"""Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found."""
<|body_0|>
def post(args):
"""Insert a matchmaking ticket for the requesting player or his party. R... | stack_v2_sparse_classes_36k_train_031819 | 11,779 | permissive | [
{
"docstring": "Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found.",
"name": "get",
"signature": "def get()"
},
{
"docstring": "Insert a matchmaking ticket for the requesting player or his party. Returns a ticket.",
... | 2 | stack_v2_sparse_classes_30k_train_000966 | Implement the Python class `FlexMatchTicketsAPI` described below.
Class description:
Implement the FlexMatchTicketsAPI class.
Method signatures and docstrings:
- def get(): Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found.
- def post(args... | Implement the Python class `FlexMatchTicketsAPI` described below.
Class description:
Implement the FlexMatchTicketsAPI class.
Method signatures and docstrings:
- def get(): Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found.
- def post(args... | 2771bb46db7fd331448f9db3cfb257fab7f89bcc | <|skeleton|>
class FlexMatchTicketsAPI:
def get():
"""Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found."""
<|body_0|>
def post(args):
"""Insert a matchmaking ticket for the requesting player or his party. R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlexMatchTicketsAPI:
def get():
"""Returns the URL to the active matchmaking ticket for the requesting player or his party, or empty dict if no such thing is found."""
player_id = current_user.get('player_id')
ticket = flexmatch.get_player_ticket(player_id)
if ticket:
... | the_stack_v2_python_sparse | driftbase/api/matchmakers/flexmatch.py | directivegames/drift-base | train | 1 | |
66c80d772005e6c5fda4ef7b04e1896d84f7e453 | [
"if not self._cmdpath:\n raise AvahiNotFound('avahi-publish-service not available')\nself._process = None\nself._svc_name = svc_name\nif not (svc_type.startswith('_') and svc_type.endswith('_tcp')):\n self._svc_type = '_%s._tcp' % svc_type\nelse:\n self._svc_type = svc_type\nself._svc_port = svc_port",
"... | <|body_start_0|>
if not self._cmdpath:
raise AvahiNotFound('avahi-publish-service not available')
self._process = None
self._svc_name = svc_name
if not (svc_type.startswith('_') and svc_type.endswith('_tcp')):
self._svc_type = '_%s._tcp' % svc_type
else:
... | A simple class wrapping service publishing and unpublishing. | AvahiService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AvahiService:
"""A simple class wrapping service publishing and unpublishing."""
def __init__(self, svc_name, svc_type, svc_port):
"""Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service. The leading '_' and trailing '._tcp' suffix can be omitt... | stack_v2_sparse_classes_36k_train_031820 | 4,211 | no_license | [
{
"docstring": "Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service. The leading '_' and trailing '._tcp' suffix can be omitted for readability's sake. They will be added automatically if needed.",
"name": "__init__",
"signature": "def __init__(self, svc_name, sv... | 3 | stack_v2_sparse_classes_30k_test_000930 | Implement the Python class `AvahiService` described below.
Class description:
A simple class wrapping service publishing and unpublishing.
Method signatures and docstrings:
- def __init__(self, svc_name, svc_type, svc_port): Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service.... | Implement the Python class `AvahiService` described below.
Class description:
A simple class wrapping service publishing and unpublishing.
Method signatures and docstrings:
- def __init__(self, svc_name, svc_type, svc_port): Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service.... | bded78fd278408ccd04480c3bb6abce533fc9501 | <|skeleton|>
class AvahiService:
"""A simple class wrapping service publishing and unpublishing."""
def __init__(self, svc_name, svc_type, svc_port):
"""Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service. The leading '_' and trailing '._tcp' suffix can be omitt... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AvahiService:
"""A simple class wrapping service publishing and unpublishing."""
def __init__(self, svc_name, svc_type, svc_port):
"""Constructor. Parameters: svc_name: the name of the service svc_type: the type of the service. The leading '_' and trailing '._tcp' suffix can be omitted for readab... | the_stack_v2_python_sparse | pybot/avahi_utils.py | pobot/PyBot | train | 0 |
2dfab900e499be7cdca312690e8e338fc11f5091 | [
"for item in os.listdir(source):\n if os.path.isfile(os.path.join(source, item)):\n self.put(os.path.join(source, item), '%s/%s' % (target, item))\n else:\n self.mkdir('%s/%s' % (target, item), ignore_existing=True)\n self.put_dir(os.path.join(source, item), '%s/%s' % (target, item))",
... | <|body_start_0|>
for item in os.listdir(source):
if os.path.isfile(os.path.join(source, item)):
self.put(os.path.join(source, item), '%s/%s' % (target, item))
else:
self.mkdir('%s/%s' % (target, item), ignore_existing=True)
self.put_dir(os.... | RSFTPClient | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSFTPClient:
def put_dir(self, source, target):
"""Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target."""
<|body_0|>
def mkdir(self, path, mode=511, ignore_existing=Fals... | stack_v2_sparse_classes_36k_train_031821 | 43,347 | permissive | [
{
"docstring": "Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target.",
"name": "put_dir",
"signature": "def put_dir(self, source, target)"
},
{
"docstring": "Augments mkdir by adding an optio... | 2 | stack_v2_sparse_classes_30k_train_004768 | Implement the Python class `RSFTPClient` described below.
Class description:
Implement the RSFTPClient class.
Method signatures and docstrings:
- def put_dir(self, source, target): Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are c... | Implement the Python class `RSFTPClient` described below.
Class description:
Implement the RSFTPClient class.
Method signatures and docstrings:
- def put_dir(self, source, target): Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are c... | 981afa736547ad08e48a11137788fba5b8980cd9 | <|skeleton|>
class RSFTPClient:
def put_dir(self, source, target):
"""Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target."""
<|body_0|>
def mkdir(self, path, mode=511, ignore_existing=Fals... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSFTPClient:
def put_dir(self, source, target):
"""Uploads the contents of the source directory to the target path. The target directory needs to exists. All subdirectories in source are created under target."""
for item in os.listdir(source):
if os.path.isfile(os.path.join(source,... | the_stack_v2_python_sparse | src/riaps/ctrl/ctrl.py | RIAPS/riaps-pycom | train | 7 | |
65ad7f9d4589d9752e1106a1e30545d8a5dc0d50 | [
"super(EncoderBlock, self).__init__()\nself.mha = MultiHeadAttention(dm, h)\nself.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')\nself.dense_output = tf.keras.layers.Dense(dm)\nself.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)\nself.layernorm2 = tf.keras.layers.LayerNormalization(... | <|body_start_0|>
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
self.dense_output = tf.keras.layers.Dense(dm)
self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-06)
... | class that instantiates an Encoder block | EncoderBlock | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EncoderBlock:
"""class that instantiates an Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, training, mask=None):
"""function that builds the Encoder block"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031822 | 2,028 | no_license | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self, dm, h, hidden, drop_rate=0.1)"
},
{
"docstring": "function that builds the Encoder block",
"name": "call",
"signature": "def call(self, x, training, mask=None)"
}
] | 2 | null | Implement the Python class `EncoderBlock` described below.
Class description:
class that instantiates an Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): constructor
- def call(self, x, training, mask=None): function that builds the Encoder block | Implement the Python class `EncoderBlock` described below.
Class description:
class that instantiates an Encoder block
Method signatures and docstrings:
- def __init__(self, dm, h, hidden, drop_rate=0.1): constructor
- def call(self, x, training, mask=None): function that builds the Encoder block
<|skeleton|>
class ... | 7d3b348aec3b20da25b162b71f150c87c7c28d71 | <|skeleton|>
class EncoderBlock:
"""class that instantiates an Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
<|body_0|>
def call(self, x, training, mask=None):
"""function that builds the Encoder block"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EncoderBlock:
"""class that instantiates an Encoder block"""
def __init__(self, dm, h, hidden, drop_rate=0.1):
"""constructor"""
super(EncoderBlock, self).__init__()
self.mha = MultiHeadAttention(dm, h)
self.dense_hidden = tf.keras.layers.Dense(hidden, activation='relu')
... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/7-transformer_encoder_block.py | dacastanogo/holbertonschool-machine_learning | train | 0 |
0cd749904aaf54fac18d4bd9ccfae52f98167463 | [
"self.data = []\n\ndef helper(node):\n if node is None:\n self.data.append(None)\n else:\n self.data.append(node.val)\n helper(node.left)\n helper(node.right)\nhelper(root)\nreturn self.data",
"def rebuild(data):\n if len(data) > 0:\n val = data.pop(0)\n if val i... | <|body_start_0|>
self.data = []
def helper(node):
if node is None:
self.data.append(None)
else:
self.data.append(node.val)
helper(node.left)
helper(node.right)
helper(root)
return self.data
<|end_bod... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_031823 | 1,286 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 355c0dbd32ad201800901f1bcc110550696bc96d | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
self.data = []
def helper(node):
if node is None:
self.data.append(None)
else:
self.data.append(node.val)
... | the_stack_v2_python_sparse | LeetCode/codes/297.py | adreena/MyStudyCorner | train | 0 | |
66d48f70366d861b7748b9658c10c5f4ddd8be9e | [
"super(RunAggregator, self).__init__()\nself.exec_num = 0.0\nself.output_names = get_outputs(self)\nself.outputs = {}\nfor output_name in self.output_names:\n self.outputs[output_name] = np.array([])",
"self.inputs = get_input_values(self)\nfor input, output in zip(self.inputs, self.outputs):\n self.outputs... | <|body_start_0|>
super(RunAggregator, self).__init__()
self.exec_num = 0.0
self.output_names = get_outputs(self)
self.outputs = {}
for output_name in self.output_names:
self.outputs[output_name] = np.array([])
<|end_body_0|>
<|body_start_1|>
self.inputs = get... | RunAggregator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunAggregator:
def __init__(self):
"""Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and initialize the dict to store the samples over time. :return: Initialized OpenMDAO component object"""
... | stack_v2_sparse_classes_36k_train_031824 | 6,454 | no_license | [
{
"docstring": "Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and initialize the dict to store the samples over time. :return: Initialized OpenMDAO component object",
"name": "__init__",
"signature": "def __i... | 2 | stack_v2_sparse_classes_30k_train_010407 | Implement the Python class `RunAggregator` described below.
Class description:
Implement the RunAggregator class.
Method signatures and docstrings:
- def __init__(self): Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and in... | Implement the Python class `RunAggregator` described below.
Class description:
Implement the RunAggregator class.
Method signatures and docstrings:
- def __init__(self): Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and in... | 5b650decfafbe8b8b5e3298a3a2da9f2db5e1daa | <|skeleton|>
class RunAggregator:
def __init__(self):
"""Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and initialize the dict to store the samples over time. :return: Initialized OpenMDAO component object"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunAggregator:
def __init__(self):
"""Extend the OpenMDAO component init method only so that we can keep track of the execution state, collect the names of our configured outputs, and initialize the dict to store the samples over time. :return: Initialized OpenMDAO component object"""
super(Ru... | the_stack_v2_python_sparse | Common/RunAggregator/RunAggregator.py | rothnic/GeorgiaAquarium | train | 0 | |
0a46c7526d8d56caa1a48c676d720ed4c18c5295 | [
"ServerInterface.__init__(self)\nself.handlers_map = {}\nself.sock_map = {}\nself.protocol_factories = {}",
"logger.info('register_handler: msg: %s addr: %s', msg_type, addr)\nscheme, host, port, _, _, path, _ = parse_addr_url(addr)\nif host is None:\n host = ''\nif scheme not in self.SUPPORTED_SCHEMES:\n l... | <|body_start_0|>
ServerInterface.__init__(self)
self.handlers_map = {}
self.sock_map = {}
self.protocol_factories = {}
<|end_body_0|>
<|body_start_1|>
logger.info('register_handler: msg: %s addr: %s', msg_type, addr)
scheme, host, port, _, _, path, _ = parse_addr_url(add... | Asyncore tcp server | AsyncoreTcpServer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AsyncoreTcpServer:
"""Asyncore tcp server"""
def __init__(self):
"""Asyncore tcp server init"""
<|body_0|>
def register_handler(self, addr, msg_type, protocol_handler, ssl_args=None):
"""Register protocol handler :type addr: :class:`str` :param addr: addr url :ty... | stack_v2_sparse_classes_36k_train_031825 | 17,211 | no_license | [
{
"docstring": "Asyncore tcp server init",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Register protocol handler :type addr: :class:`str` :param addr: addr url :type msg_type: :class:`str` :param msg_type: protocol message type :type protocol_handler: :class:`vmware.... | 4 | stack_v2_sparse_classes_30k_train_006033 | Implement the Python class `AsyncoreTcpServer` described below.
Class description:
Asyncore tcp server
Method signatures and docstrings:
- def __init__(self): Asyncore tcp server init
- def register_handler(self, addr, msg_type, protocol_handler, ssl_args=None): Register protocol handler :type addr: :class:`str` :par... | Implement the Python class `AsyncoreTcpServer` described below.
Class description:
Asyncore tcp server
Method signatures and docstrings:
- def __init__(self): Asyncore tcp server init
- def register_handler(self, addr, msg_type, protocol_handler, ssl_args=None): Register protocol handler :type addr: :class:`str` :par... | 5d395700ab3d0d1d45b497e48beab8c366fca9f5 | <|skeleton|>
class AsyncoreTcpServer:
"""Asyncore tcp server"""
def __init__(self):
"""Asyncore tcp server init"""
<|body_0|>
def register_handler(self, addr, msg_type, protocol_handler, ssl_args=None):
"""Register protocol handler :type addr: :class:`str` :param addr: addr url :ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AsyncoreTcpServer:
"""Asyncore tcp server"""
def __init__(self):
"""Asyncore tcp server init"""
ServerInterface.__init__(self)
self.handlers_map = {}
self.sock_map = {}
self.protocol_factories = {}
def register_handler(self, addr, msg_type, protocol_handler, s... | the_stack_v2_python_sparse | alexa-program/vmware/vapi/server/asyncore_server.py | taromurata/TDP2018_VMCAPI | train | 1 |
6c952ce6ef498b3213542d60cb26c72a2df90e6d | [
"self.X = X\nself.fs = fs\nself.N = 2 * (len(self.X) - 1)",
"x = np.zeros(self.N)\nfor n in range(self.N):\n x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j * 2 * cmath.pi * 0 * n / self.N)\n for k in range(1, int(self.N / 2)):\n x[n] = x[n] + 1 / np.sqrt(self.N) * self.X[k] * np.exp(1j * 2 * cmat... | <|body_start_0|>
self.X = X
self.fs = fs
self.N = 2 * (len(self.X) - 1)
<|end_body_0|>
<|body_start_1|>
x = np.zeros(self.N)
for n in range(self.N):
x[n] = 1 / np.sqrt(self.N) * self.X[0] * np.exp(1j * 2 * cmath.pi * 0 * n / self.N)
for k in range(1, int(... | idft Inverse Discrete Fourier transform. | idft_p11 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficie... | stack_v2_sparse_classes_36k_train_031826 | 25,417 | no_license | [
{
"docstring": ":param X: Input DFT X :param fs: Input integer fs contains the sample frequency",
"name": "__init__",
"signature": "def __init__(self, X, fs)"
},
{
"docstring": "\\\\\\\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficients :return iDFT x of duration N from partial DFT ... | 2 | stack_v2_sparse_classes_30k_train_003879 | Implement the Python class `idft_p11` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute the iDFT with trun... | Implement the Python class `idft_p11` described below.
Class description:
idft Inverse Discrete Fourier transform.
Method signatures and docstrings:
- def __init__(self, X, fs): :param X: Input DFT X :param fs: Input integer fs contains the sample frequency
- def solve(self): \\\\\\ METHOD: Compute the iDFT with trun... | b72322cfc6d81c996117cea2160ee312da62d3ed | <|skeleton|>
class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
<|body_0|>
def solve(self):
"""\\\\\\ METHOD: Compute the iDFT with truncated N/2+1 coefficie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class idft_p11:
"""idft Inverse Discrete Fourier transform."""
def __init__(self, X, fs):
""":param X: Input DFT X :param fs: Input integer fs contains the sample frequency"""
self.X = X
self.fs = fs
self.N = 2 * (len(self.X) - 1)
def solve(self):
"""\\\\\\ METHOD: ... | the_stack_v2_python_sparse | Inverse Discrete Fourier Transform/iDFT_main.py | FG-14/Signals-and-Information-Processing-DSP- | train | 0 |
e5f61a9891cdc8fb69ab5624893f5fad019af30d | [
"dic = {}\nfor i, v in enumerate(nums):\n val = target - v\n if val in dic:\n return [dic[val], i]\n else:\n dic[v] = i",
"dic = {}\nfor i, v in enumerate(nums):\n if v not in dic:\n dic[v] = [i]\n else:\n dic[v].append(i)\nfor i, v in enumerate(nums):\n val = target ... | <|body_start_0|>
dic = {}
for i, v in enumerate(nums):
val = target - v
if val in dic:
return [dic[val], i]
else:
dic[v] = i
<|end_body_0|>
<|body_start_1|>
dic = {}
for i, v in enumerate(nums):
if v not in ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum2(self, nums, targe... | stack_v2_sparse_classes_36k_train_031827 | 2,021 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum3",
"signature": "def twoSum3(self, nums, target)"
}... | 4 | stack_v2_sparse_classes_30k_test_000680 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum3(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[int]
- def twoSum3(self, nums, target): :type nums: List[int] :type target: int :rtype: List[... | 3ded7bd0f046e8f87c9b9b9bce81e52ab1bdcdac | <|skeleton|>
class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_0|>
def twoSum3(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
def twoSum2(self, nums, targe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
dic = {}
for i, v in enumerate(nums):
val = target - v
if val in dic:
return [dic[val], i]
else:
dic[v] = i
... | the_stack_v2_python_sparse | leetcode/arrays/two_sum.py | JeanChrist/Algorithms | train | 0 | |
3e5b49fdb5714214cece74f14a7424f72d69b453 | [
"if not nums or len(nums) == 0:\n return 0\nelif len(nums) == 1:\n return nums[0]\nmax_previous = nums[0]\nmax_current = max(max_previous, nums[1])\nfor i in range(2, len(nums)):\n max_previous, max_current = (max_current, max(nums[i] + max_previous, max_current))\nreturn max_current",
"if not nums and l... | <|body_start_0|>
if not nums or len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
max_previous = nums[0]
max_current = max(max_previous, nums[1])
for i in range(2, len(nums)):
max_previous, max_current = (max_current, max(nums[i] + m... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_dp(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums or len(nums) == 0:
return 0
... | stack_v2_sparse_classes_36k_train_031828 | 2,232 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob_dp",
"signature": "def rob_dp(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_dp(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob_dp(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob_dp(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums or len(nums) == 0:
return 0
elif len(nums) == 1:
return nums[0]
max_previous = nums[0]
max_current = max(max_previous, nums[1])
for i in range(2, len(nums)... | the_stack_v2_python_sparse | src/lt_198.py | oxhead/CodingYourWay | train | 0 | |
354bf43e403d1e54cac76c21082af39a39f11656 | [
"super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)\nif flag_values['image'].present:\n config_values['image'] = flag_values.image\nif flag_values['static_container_image'].present:\n config_values['static_image'] = flag_values.static_container_image",
"result = super(ContainerSpec, cls)._Get... | <|body_start_0|>
super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['image'].present:
config_values['image'] = flag_values.image
if flag_values['static_container_image'].present:
config_values['static_image'] = flag_values.static_container_im... | Class containing options for creating containers. | ContainerSpec | [
"Classpath-exception-2.0",
"BSD-3-Clause",
"AGPL-3.0-only",
"MIT",
"GPL-2.0-only",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
<|body_0|>
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor a... | stack_v2_sparse_classes_36k_train_031829 | 34,074 | permissive | [
{
"docstring": "Apply flag settings to the container spec.",
"name": "_ApplyFlags",
"signature": "def _ApplyFlags(cls, config_values, flag_values)"
},
{
"docstring": "Gets decoder classes and constructor args for each configurable option. Can be overridden by derived classes to add options or im... | 2 | stack_v2_sparse_classes_30k_train_017464 | Implement the Python class `ContainerSpec` described below.
Class description:
Class containing options for creating containers.
Method signatures and docstrings:
- def _ApplyFlags(cls, config_values, flag_values): Apply flag settings to the container spec.
- def _GetOptionDecoderConstructions(cls): Gets decoder clas... | Implement the Python class `ContainerSpec` described below.
Class description:
Class containing options for creating containers.
Method signatures and docstrings:
- def _ApplyFlags(cls, config_values, flag_values): Apply flag settings to the container spec.
- def _GetOptionDecoderConstructions(cls): Gets decoder clas... | d0699f32998898757b036704fba39e5471641f01 | <|skeleton|>
class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
<|body_0|>
def _GetOptionDecoderConstructions(cls):
"""Gets decoder classes and constructor a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContainerSpec:
"""Class containing options for creating containers."""
def _ApplyFlags(cls, config_values, flag_values):
"""Apply flag settings to the container spec."""
super(ContainerSpec, cls)._ApplyFlags(config_values, flag_values)
if flag_values['image'].present:
... | the_stack_v2_python_sparse | perfkitbenchmarker/container_service.py | GoogleCloudPlatform/PerfKitBenchmarker | train | 1,923 |
a43cfac00faeef26915e339301d1118a0b5a8b3c | [
"gdf1.crs = 'epsg:4326'\ngdf2.crs = 'epsg:4326'\nreturn gpd.sjoin(gdf1, gdf2).drop('index_right', axis=1)",
"AREA_SIZE_DIVIDER = 25000\nMIN_BUFFER_SIZE = 3\nMAX_BUFFER_SIZE = 10\nwall_gdf = relevant_floorplan_gdf.loc[relevant_floorplan_gdf['category'] == 'wall'].copy()\narea = wall_gdf.unary_union.buffer(0.01).co... | <|body_start_0|>
gdf1.crs = 'epsg:4326'
gdf2.crs = 'epsg:4326'
return gpd.sjoin(gdf1, gdf2).drop('index_right', axis=1)
<|end_body_0|>
<|body_start_1|>
AREA_SIZE_DIVIDER = 25000
MIN_BUFFER_SIZE = 3
MAX_BUFFER_SIZE = 10
wall_gdf = relevant_floorplan_gdf.loc[releva... | Image structure generator class, to generate windows and doors in walls. | ImageStructureGenerator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImageStructureGenerator:
"""Image structure generator class, to generate windows and doors in walls."""
def find_overlap(self, gdf1, gdf2):
"""Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to have the overlapping elements returned gdf2: geodataframe... | stack_v2_sparse_classes_36k_train_031830 | 3,582 | no_license | [
{
"docstring": "Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to have the overlapping elements returned gdf2: geodataframe that the overlap needs to be found against.",
"name": "find_overlap",
"signature": "def find_overlap(self, gdf1, gdf2)"
},
{
"docstring": ... | 3 | stack_v2_sparse_classes_30k_train_018262 | Implement the Python class `ImageStructureGenerator` described below.
Class description:
Image structure generator class, to generate windows and doors in walls.
Method signatures and docstrings:
- def find_overlap(self, gdf1, gdf2): Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to ... | Implement the Python class `ImageStructureGenerator` described below.
Class description:
Image structure generator class, to generate windows and doors in walls.
Method signatures and docstrings:
- def find_overlap(self, gdf1, gdf2): Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to ... | 1b953d87968dac46ebbc9b1d5c254ea9493ee328 | <|skeleton|>
class ImageStructureGenerator:
"""Image structure generator class, to generate windows and doors in walls."""
def find_overlap(self, gdf1, gdf2):
"""Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to have the overlapping elements returned gdf2: geodataframe... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImageStructureGenerator:
"""Image structure generator class, to generate windows and doors in walls."""
def find_overlap(self, gdf1, gdf2):
"""Find overlap between 2 geodataframes. Args: gdf1: geodataframe of which you want to have the overlapping elements returned gdf2: geodataframe that the ove... | the_stack_v2_python_sparse | fmlwright/dataset_builder/ImageStructureGenerator.py | rgresia-umd/fml-wright | train | 0 |
86ba83744f81d71215b2b1f364b173e0174f51b4 | [
"if not isinstance(ssh_known_hosts_file, str):\n raise TypeError(f'`ssh_config_file` expected str, got {type(ssh_known_hosts_file)}')\nself.ssh_known_hosts_file = os.path.expanduser(ssh_known_hosts_file)\nif self.ssh_known_hosts_file:\n with open(self.ssh_known_hosts_file, 'r') as f:\n self.ssh_known_h... | <|body_start_0|>
if not isinstance(ssh_known_hosts_file, str):
raise TypeError(f'`ssh_config_file` expected str, got {type(ssh_known_hosts_file)}')
self.ssh_known_hosts_file = os.path.expanduser(ssh_known_hosts_file)
if self.ssh_known_hosts_file:
with open(self.ssh_known_... | SSHKnownHosts | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts ... | stack_v2_sparse_classes_36k_train_031831 | 13,310 | permissive | [
{
"docstring": "Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts file Returns: N/A # noqa: DAR202 Raises: TypeError: if non-string value provided ... | 2 | stack_v2_sparse_classes_30k_train_002222 | Implement the Python class `SSHKnownHosts` described below.
Class description:
Implement the SSHKnownHosts class.
Method signatures and docstrings:
- def __init__(self, ssh_known_hosts_file: str) -> None: Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in ... | Implement the Python class `SSHKnownHosts` described below.
Class description:
Implement the SSHKnownHosts class.
Method signatures and docstrings:
- def __init__(self, ssh_known_hosts_file: str) -> None: Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in ... | eeaa8f2ff5e54771c02335d7c2099d56d88b8cdc | <|skeleton|>
class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SSHKnownHosts:
def __init__(self, ssh_known_hosts_file: str) -> None:
"""Initialize SSHKnownHosts Object Parse OpenSSH known hosts file Try to load the following data for all entries in known hosts file: Host Key Type Public Key Args: ssh_known_hosts_file: string path to ssh known hosts file Returns: ... | the_stack_v2_python_sparse | scrapli/ssh_config.py | Ferhub255/scrapli | train | 1 | |
fc63e69a02c228ba2121691b51d8be44b8102992 | [
"self._title = Text('Scrabble!', (330, 65), 58)\nself._keyText = Text('Key!', (630, 60), 18)\nself._keyBox = Rectangle(120, 130, (630, 100))\nself._keyBox.setFillColor('pink')\nself._key1 = Rectangle(10, 10, (580, 70))\nself._key1.setFillColor('green')\nself._text1 = Text(' Start Tile', (630, 75), 10)\nself._key2 =... | <|body_start_0|>
self._title = Text('Scrabble!', (330, 65), 58)
self._keyText = Text('Key!', (630, 60), 18)
self._keyBox = Rectangle(120, 130, (630, 100))
self._keyBox.setFillColor('pink')
self._key1 = Rectangle(10, 10, (580, 70))
self._key1.setFillColor('green')
... | A class primarily for the graphical objects that make up the "Key" for the game | Key | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Key:
"""A class primarily for the graphical objects that make up the "Key" for the game"""
def __init__(self):
"""Creates the following attributes that are all graphical objects for the game's Key"""
<|body_0|>
def addTo(self, win):
"""Adds each graphical object ... | stack_v2_sparse_classes_36k_train_031832 | 23,085 | no_license | [
{
"docstring": "Creates the following attributes that are all graphical objects for the game's Key",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Adds each graphical object to the window by looping through a list of the objects",
"name": "addTo",
"signature": ... | 2 | null | Implement the Python class `Key` described below.
Class description:
A class primarily for the graphical objects that make up the "Key" for the game
Method signatures and docstrings:
- def __init__(self): Creates the following attributes that are all graphical objects for the game's Key
- def addTo(self, win): Adds e... | Implement the Python class `Key` described below.
Class description:
A class primarily for the graphical objects that make up the "Key" for the game
Method signatures and docstrings:
- def __init__(self): Creates the following attributes that are all graphical objects for the game's Key
- def addTo(self, win): Adds e... | e5d96a65fc84481b85072cfb55dea9a0666634b5 | <|skeleton|>
class Key:
"""A class primarily for the graphical objects that make up the "Key" for the game"""
def __init__(self):
"""Creates the following attributes that are all graphical objects for the game's Key"""
<|body_0|>
def addTo(self, win):
"""Adds each graphical object ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Key:
"""A class primarily for the graphical objects that make up the "Key" for the game"""
def __init__(self):
"""Creates the following attributes that are all graphical objects for the game's Key"""
self._title = Text('Scrabble!', (330, 65), 58)
self._keyText = Text('Key!', (630,... | the_stack_v2_python_sparse | Games-2017/21/Game.py | paulmagnus/CSPy | train | 0 |
cca5af8132e068d043a998b1f3287aac3f8b94f2 | [
"super(Transformer, self).__init__()\nself.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)\nself.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)\nself.linear = tf.keras.layers.Dense(target_vocab)",
"enc_output = self.encoder(inputs, training, encoder_mask)\n... | <|body_start_0|>
super(Transformer, self).__init__()
self.encoder = Encoder(N, dm, h, hidden, input_vocab, max_seq_input, drop_rate)
self.decoder = Decoder(N, dm, h, hidden, target_vocab, max_seq_target, drop_rate)
self.linear = tf.keras.layers.Dense(target_vocab)
<|end_body_0|>
<|body_... | class Transformer | Transformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Constructor @params N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads ... | stack_v2_sparse_classes_36k_train_031833 | 2,755 | no_license | [
{
"docstring": "Constructor @params N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the number of hidden units in the fully connected layers input_vocab - the size of the input vocabulary target_vocab - the size of the target vocabulary m... | 2 | null | Implement the Python class `Transformer` described below.
Class description:
class Transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Constructor @params N - the number of blocks in the encoder and decoder dm -... | Implement the Python class `Transformer` described below.
Class description:
class Transformer
Method signatures and docstrings:
- def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1): Constructor @params N - the number of blocks in the encoder and decoder dm -... | ff1af62484620b599cc3813068770db03b37036d | <|skeleton|>
class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Constructor @params N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Transformer:
"""class Transformer"""
def __init__(self, N, dm, h, hidden, input_vocab, target_vocab, max_seq_input, max_seq_target, drop_rate=0.1):
"""Constructor @params N - the number of blocks in the encoder and decoder dm - the dimensionality of the model h - the number of heads hidden - the ... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/11-transformer.py | paurbano/holbertonschool-machine_learning | train | 0 |
b632dbf1e1178ebd500131ba99b9a46c11156921 | [
"if not grid or not grid[0]:\n return 0\nX = len(grid)\nY = len(grid[0])\ndirections = [(-1, 0), (1, 0), (0, -1), (0, 1)]\n\ndef dfs(x, y):\n if grid[x][y] == 0:\n return 0\n ret = 1\n grid[x][y] = 0\n for dx, dy in directions:\n _x, _y = (x + dx, y + dy)\n if 0 <= _x < X and 0 <... | <|body_start_0|>
if not grid or not grid[0]:
return 0
X = len(grid)
Y = len(grid[0])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(x, y):
if grid[x][y] == 0:
return 0
ret = 1
grid[x][y] = 0
for... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""08/29/2020 16:41"""
<|body_0|>
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""06/20/2021 09:07 DFS Time complexity: O(n*m) Space complexity: O(n*m)"""
<|body_1|>
def maxAr... | stack_v2_sparse_classes_36k_train_031834 | 3,899 | no_license | [
{
"docstring": "08/29/2020 16:41",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(self, grid: List[List[int]]) -> int"
},
{
"docstring": "06/20/2021 09:07 DFS Time complexity: O(n*m) Space complexity: O(n*m)",
"name": "maxAreaOfIsland",
"signature": "def maxAreaOfIsland(sel... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 08/29/2020 16:41
- def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 06/20/2021 09:07 DFS Time complexity: O(n*m) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 08/29/2020 16:41
- def maxAreaOfIsland(self, grid: List[List[int]]) -> int: 06/20/2021 09:07 DFS Time complexity: O(n*m) ... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""08/29/2020 16:41"""
<|body_0|>
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""06/20/2021 09:07 DFS Time complexity: O(n*m) Space complexity: O(n*m)"""
<|body_1|>
def maxAr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
"""08/29/2020 16:41"""
if not grid or not grid[0]:
return 0
X = len(grid)
Y = len(grid[0])
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def dfs(x, y):
if grid[x][y] ==... | the_stack_v2_python_sparse | leetcode/solved/695_Max_Area_of_Island/solution.py | sungminoh/algorithms | train | 0 | |
74287659e00de320b5cca17a048fd0f1914775ec | [
"chans = self._get_chans(spec_data.metadata.chans)\nlogger.info(f'Calibrating channels {chans}')\nmessages = [f'Calibrating channels {chans}']\ndata = {x: np.array(y) for x, y in spec_data.data.items()}\nfor chan in chans:\n logger.info(f'Looking for sensor calibration data for channel {chan}')\n cal_data = s... | <|body_start_0|>
chans = self._get_chans(spec_data.metadata.chans)
logger.info(f'Calibrating channels {chans}')
messages = [f'Calibrating channels {chans}']
data = {x: np.array(y) for x, y in spec_data.data.items()}
for chan in chans:
logger.info(f'Looking for sensor ... | SensorCalibrator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SensorCalibrator:
def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData:
"""Calibrate Spectra data"""
<|body_0|>
def _get_cal_data(self, dir_path: Path, metadata: SpectraMetadata, chan: str) -> Union[CalibrationData, None]:
"""Get the calibration data"... | stack_v2_sparse_classes_36k_train_031835 | 18,607 | permissive | [
{
"docstring": "Calibrate Spectra data",
"name": "run",
"signature": "def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData"
},
{
"docstring": "Get the calibration data",
"name": "_get_cal_data",
"signature": "def _get_cal_data(self, dir_path: Path, metadata: SpectraMetada... | 2 | stack_v2_sparse_classes_30k_train_018508 | Implement the Python class `SensorCalibrator` described below.
Class description:
Implement the SensorCalibrator class.
Method signatures and docstrings:
- def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData: Calibrate Spectra data
- def _get_cal_data(self, dir_path: Path, metadata: SpectraMetadata, ... | Implement the Python class `SensorCalibrator` described below.
Class description:
Implement the SensorCalibrator class.
Method signatures and docstrings:
- def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData: Calibrate Spectra data
- def _get_cal_data(self, dir_path: Path, metadata: SpectraMetadata, ... | cba60747803b6c582eaaf1a670a7f455f5724ebd | <|skeleton|>
class SensorCalibrator:
def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData:
"""Calibrate Spectra data"""
<|body_0|>
def _get_cal_data(self, dir_path: Path, metadata: SpectraMetadata, chan: str) -> Union[CalibrationData, None]:
"""Get the calibration data"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SensorCalibrator:
def run(self, dir_path: Path, spec_data: SpectraData) -> SpectraData:
"""Calibrate Spectra data"""
chans = self._get_chans(spec_data.metadata.chans)
logger.info(f'Calibrating channels {chans}')
messages = [f'Calibrating channels {chans}']
data = {x: np... | the_stack_v2_python_sparse | resistics/calibrate.py | resistics/resistics | train | 47 | |
ece006920db4388d52ed29a8bd006bcf620d36d4 | [
"if not root:\n return True\nreturn self.isMirror(root.left, root.right)",
"if not s and (not t):\n return True\nif not s or not t:\n return False\nreturn s.val == t.val and self.isMirror(s.left, t.right) and self.isMirror(s.right, t.left)"
] | <|body_start_0|>
if not root:
return True
return self.isMirror(root.left, root.right)
<|end_body_0|>
<|body_start_1|>
if not s and (not t):
return True
if not s or not t:
return False
return s.val == t.val and self.isMirror(s.left, t.right) an... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, s, t):
"""test if tree s and t are mirror reflections to each other"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
... | stack_v2_sparse_classes_36k_train_031836 | 622 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: bool",
"name": "isSymmetric",
"signature": "def isSymmetric(self, root)"
},
{
"docstring": "test if tree s and t are mirror reflections to each other",
"name": "isMirror",
"signature": "def isMirror(self, s, t)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, s, t): test if tree s and t are mirror reflections to each other | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isSymmetric(self, root): :type root: TreeNode :rtype: bool
- def isMirror(self, s, t): test if tree s and t are mirror reflections to each other
<|skeleton|>
class Solution:... | e00cf94c5b86c8cca27e3bee69ad21e727b7679b | <|skeleton|>
class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
<|body_0|>
def isMirror(self, s, t):
"""test if tree s and t are mirror reflections to each other"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isSymmetric(self, root):
""":type root: TreeNode :rtype: bool"""
if not root:
return True
return self.isMirror(root.left, root.right)
def isMirror(self, s, t):
"""test if tree s and t are mirror reflections to each other"""
if not s and (n... | the_stack_v2_python_sparse | tree/prob101.py | binchen15/leet-python | train | 1 | |
e1dcd597813897649453c77834bb00ad67677135 | [
"data: type_data = {'x': [0.0], 'y': [0.0]}\nself.__dynamic = True\nself.__points_connected = True\nself.__limit = [-10.0, 10.0, -10.0, 10.0]\nself.__max_points = 10\nsuper().__init__(data, item)",
"self._ax.clear()\nself._ax.get_xaxis().set_major_formatter(func_format)\nself._ax.get_yaxis().set_major_formatter(f... | <|body_start_0|>
data: type_data = {'x': [0.0], 'y': [0.0]}
self.__dynamic = True
self.__points_connected = True
self.__limit = [-10.0, 10.0, -10.0, 10.0]
self.__max_points = 10
super().__init__(data, item)
<|end_body_0|>
<|body_start_1|>
self._ax.clear()
... | this class represents a dual diagram | DualDiagram | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DualDiagram:
"""this class represents a dual diagram"""
def __init__(self, item: DualDiagramItem):
"""Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item"""
<|body_0|>
def _draw_diagram(self) -> NoReturn:
"""draws a diagram with its... | stack_v2_sparse_classes_36k_train_031837 | 9,833 | permissive | [
{
"docstring": "Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item",
"name": "__init__",
"signature": "def __init__(self, item: DualDiagramItem)"
},
{
"docstring": "draws a diagram with its labels and title",
"name": "_draw_diagram",
"signature": "def _dra... | 4 | null | Implement the Python class `DualDiagram` described below.
Class description:
this class represents a dual diagram
Method signatures and docstrings:
- def __init__(self, item: DualDiagramItem): Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item
- def _draw_diagram(self) -> NoReturn: dra... | Implement the Python class `DualDiagram` described below.
Class description:
this class represents a dual diagram
Method signatures and docstrings:
- def __init__(self, item: DualDiagramItem): Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item
- def _draw_diagram(self) -> NoReturn: dra... | 5c4f19b1dbce8facd87919dc81d7d1eccb16b552 | <|skeleton|>
class DualDiagram:
"""this class represents a dual diagram"""
def __init__(self, item: DualDiagramItem):
"""Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item"""
<|body_0|>
def _draw_diagram(self) -> NoReturn:
"""draws a diagram with its... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DualDiagram:
"""this class represents a dual diagram"""
def __init__(self, item: DualDiagramItem):
"""Initialising an DualDiagram object Args: item (DualDiagramItem): plot diagram item"""
data: type_data = {'x': [0.0], 'y': [0.0]}
self.__dynamic = True
self.__points_connec... | the_stack_v2_python_sparse | phypigui/python/src/view/DiagramField/DiagramView.py | osl2/PhyPiDAQ | train | 3 |
9ee4d1db58379165f03abebc0be7773a761e1afe | [
"if not l1:\n return l2\nif not l2:\n return l1\nif l1.val < l2.val:\n l1.next = self.mergeTwoLists(l1.next, l2)\n return l1\nelse:\n l2.next = self.mergeTwoLists(l1, l2.next)\n return l2",
"pre_node = dummy_node = ListNode(-1)\nwhile l1 and l2:\n if l1.val < l2.val:\n pre_node.next = ... | <|body_start_0|>
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
<|end_body_0|>
<|body_star... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_0|>
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""遍历链表"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not l1:
return l2... | stack_v2_sparse_classes_36k_train_031838 | 1,408 | no_license | [
{
"docstring": "递归",
"name": "mergeTwoLists2",
"signature": "def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode"
},
{
"docstring": "遍历链表",
"name": "mergeTwoLists",
"signature": "def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode"
}
] | 2 | stack_v2_sparse_classes_30k_train_004756 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 遍历链表 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode: 递归
- def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: 遍历链表
<|skeleton|>
class Solution:
de... | c0dd577481b46129d950354d567d332a4d091137 | <|skeleton|>
class Solution:
def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
<|body_0|>
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
"""遍历链表"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def mergeTwoLists2(self, l1: ListNode, l2: ListNode) -> ListNode:
"""递归"""
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.ne... | the_stack_v2_python_sparse | leetcode/剑指offer/剑指 Offer 25. 合并两个排序的链表.py | tenqaz/crazy_arithmetic | train | 0 | |
13975bb4bf117af6d12835a2a501fadc5a650aea | [
"if not prices:\n return 0\nn = len(prices)\ndp = [0] * n\nmin_vals = [[0] * n for _ in range(n)]\nfor i in range(n - 1):\n min_price = 2147483647\n for j in range(i, n):\n if min_price > prices[j]:\n min_price = prices[j]\n min_vals[i][j] = min_price\nfor i in range(k):\n dp2 =... | <|body_start_0|>
if not prices:
return 0
n = len(prices)
dp = [0] * n
min_vals = [[0] * n for _ in range(n)]
for i in range(n - 1):
min_price = 2147483647
for j in range(i, n):
if min_price > prices[j]:
min_p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxProfit1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit(self, k, prices):
""":ty... | stack_v2_sparse_classes_36k_train_031839 | 5,158 | no_license | [
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit1",
"signature": "def maxProfit1(self, k, prices)"
},
{
"docstring": ":type k: int :type prices: List[int] :rtype: int",
"name": "maxProfit2",
"signature": "def maxProfit2(self, k, prices)"
},
{
... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit2(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxPro... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxProfit1(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxProfit2(self, k, prices): :type k: int :type prices: List[int] :rtype: int
- def maxPro... | 4a1747b6497305f3821612d9c358a6795b1690da | <|skeleton|>
class Solution:
def maxProfit1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_0|>
def maxProfit2(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
<|body_1|>
def maxProfit(self, k, prices):
""":ty... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxProfit1(self, k, prices):
""":type k: int :type prices: List[int] :rtype: int"""
if not prices:
return 0
n = len(prices)
dp = [0] * n
min_vals = [[0] * n for _ in range(n)]
for i in range(n - 1):
min_price = 2147483647
... | the_stack_v2_python_sparse | DynamicProgramming/q188_best_time_to_buy_and_sell_stock_iv.py | sevenhe716/LeetCode | train | 0 | |
6abbf73930f39df1d48f300e17ef5f448ef025a8 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UnifiedRoleAssignment()",
"from .app_scope import AppScope\nfrom .directory_object import DirectoryObject\nfrom .entity import Entity\nfrom .unified_role_definition import UnifiedRoleDefinition\nfrom .app_scope import AppScope\nfrom .d... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UnifiedRoleAssignment()
<|end_body_0|>
<|body_start_1|>
from .app_scope import AppScope
from .directory_object import DirectoryObject
from .entity import Entity
from .uni... | UnifiedRoleAssignment | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""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 th... | stack_v2_sparse_classes_36k_train_031840 | 5,634 | 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: UnifiedRoleAssignment",
"name": "create_from_discriminator_value",
"signature": "def create_from_discriminat... | 3 | null | Implement the Python class `UnifiedRoleAssignment` described below.
Class description:
Implement the UnifiedRoleAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment: Creates a new instance of the appropriate class base... | Implement the Python class `UnifiedRoleAssignment` described below.
Class description:
Implement the UnifiedRoleAssignment class.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment: Creates a new instance of the appropriate class base... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""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 th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UnifiedRoleAssignment:
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UnifiedRoleAssignment:
"""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 Retur... | the_stack_v2_python_sparse | msgraph/generated/models/unified_role_assignment.py | microsoftgraph/msgraph-sdk-python | train | 135 | |
0cd5a0d7f314d129b496aa9f8c49df0a7c44b05d | [
"super(ZNB_VNA_detector, self).__init__()\nself.VNA = VNA\nself.value_names = ['ampl', 'phase', 'real', 'imag', 'ampl_dB']\nself.value_units = ['', 'radians', '', '', 'dB']",
"self.VNA.start_sweep_all()\nself.VNA.wait_to_continue()\nself.VNA.autoscale_trace()\nreal_data, imag_data = self.VNA.get_real_imaginary_da... | <|body_start_0|>
super(ZNB_VNA_detector, self).__init__()
self.VNA = VNA
self.value_names = ['ampl', 'phase', 'real', 'imag', 'ampl_dB']
self.value_units = ['', 'radians', '', '', 'dB']
<|end_body_0|>
<|body_start_1|>
self.VNA.start_sweep_all()
self.VNA.wait_to_continue(... | ZNB_VNA_detector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZNB_VNA_detector:
def __init__(self, VNA, **kw):
"""Detector function for the Rohde & Schwarz ZNB VNA"""
<|body_0|>
def get_values(self):
"""Start a measurement, wait untill the end and retrive data. Return real and imaginary transmission coefficients + amplitude (li... | stack_v2_sparse_classes_36k_train_031841 | 17,128 | permissive | [
{
"docstring": "Detector function for the Rohde & Schwarz ZNB VNA",
"name": "__init__",
"signature": "def __init__(self, VNA, **kw)"
},
{
"docstring": "Start a measurement, wait untill the end and retrive data. Return real and imaginary transmission coefficients + amplitude (linear) and phase (d... | 2 | null | Implement the Python class `ZNB_VNA_detector` described below.
Class description:
Implement the ZNB_VNA_detector class.
Method signatures and docstrings:
- def __init__(self, VNA, **kw): Detector function for the Rohde & Schwarz ZNB VNA
- def get_values(self): Start a measurement, wait untill the end and retrive data... | Implement the Python class `ZNB_VNA_detector` described below.
Class description:
Implement the ZNB_VNA_detector class.
Method signatures and docstrings:
- def __init__(self, VNA, **kw): Detector function for the Rohde & Schwarz ZNB VNA
- def get_values(self): Start a measurement, wait untill the end and retrive data... | 4fc56396ad603bbe61e6d548f66b818d51a3301b | <|skeleton|>
class ZNB_VNA_detector:
def __init__(self, VNA, **kw):
"""Detector function for the Rohde & Schwarz ZNB VNA"""
<|body_0|>
def get_values(self):
"""Start a measurement, wait untill the end and retrive data. Return real and imaginary transmission coefficients + amplitude (li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ZNB_VNA_detector:
def __init__(self, VNA, **kw):
"""Detector function for the Rohde & Schwarz ZNB VNA"""
super(ZNB_VNA_detector, self).__init__()
self.VNA = VNA
self.value_names = ['ampl', 'phase', 'real', 'imag', 'ampl_dB']
self.value_units = ['', 'radians', '', '', 'd... | the_stack_v2_python_sparse | pycqed/measurement/detector_functions.py | DiCarloLab-Delft/PycQED_py3 | train | 72 | |
759ff7c3d203a7ee35183d86cd5b3115d714edc0 | [
"count, base, length = ([0] * 26, ord('a'), 0)\nfor i in range(len(p)):\n if i > 0 and ord(p[i]) - ord(p[i - 1]) in (1, -25):\n length += 1\n else:\n length = 1\n index = ord(p[i]) - base\n count[index] = max(count[index], length)\nprint(count)\nreturn sum(count)",
"i, j, res = (0, 1, 0)... | <|body_start_0|>
count, base, length = ([0] * 26, ord('a'), 0)
for i in range(len(p)):
if i > 0 and ord(p[i]) - ord(p[i - 1]) in (1, -25):
length += 1
else:
length = 1
index = ord(p[i]) - base
count[index] = max(count[index]... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findSubstringInWraproundString(self, p):
""":type p: str :rtype: int"""
<|body_0|>
def findSubstringInWraproundString2(self, p):
""":type p: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count, base, length = ([0] * 2... | stack_v2_sparse_classes_36k_train_031842 | 2,158 | no_license | [
{
"docstring": ":type p: str :rtype: int",
"name": "findSubstringInWraproundString",
"signature": "def findSubstringInWraproundString(self, p)"
},
{
"docstring": ":type p: str :rtype: int",
"name": "findSubstringInWraproundString2",
"signature": "def findSubstringInWraproundString2(self,... | 2 | stack_v2_sparse_classes_30k_train_004431 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstringInWraproundString(self, p): :type p: str :rtype: int
- def findSubstringInWraproundString2(self, p): :type p: str :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findSubstringInWraproundString(self, p): :type p: str :rtype: int
- def findSubstringInWraproundString2(self, p): :type p: str :rtype: int
<|skeleton|>
class Solution:
... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class Solution:
def findSubstringInWraproundString(self, p):
""":type p: str :rtype: int"""
<|body_0|>
def findSubstringInWraproundString2(self, p):
""":type p: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findSubstringInWraproundString(self, p):
""":type p: str :rtype: int"""
count, base, length = ([0] * 26, ord('a'), 0)
for i in range(len(p)):
if i > 0 and ord(p[i]) - ord(p[i - 1]) in (1, -25):
length += 1
else:
leng... | the_stack_v2_python_sparse | code467UniqueSubstringsInWraparoundString.py | cybelewang/leetcode-python | train | 0 | |
55df499f3a894abe9e7ebbb892d2afced08cc094 | [
"self._display_width = display_size_mm[0]\nself._display_height = display_size_mm[1]\nself._display_x_resolution = display_res_pix[0]\nself._display_y_resolution = display_res_pix[1]\nself._eye_distance_mm = eye_distance_mm",
"if self._eye_distance_mm is None and eye_distance_mm is None:\n raise ValueError('Th... | <|body_start_0|>
self._display_width = display_size_mm[0]
self._display_height = display_size_mm[1]
self._display_x_resolution = display_res_pix[0]
self._display_y_resolution = display_res_pix[1]
self._eye_distance_mm = eye_distance_mm
<|end_body_0|>
<|body_start_1|>
if ... | VisualAngleCalc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualAngleCalc:
def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None):
"""Used to store calibrated area information and eye distance to screen data so that pixel data values can be converted to visual degree values. The pix2deg method is vectorized, meaning that is ... | stack_v2_sparse_classes_36k_train_031843 | 7,223 | no_license | [
{
"docstring": "Used to store calibrated area information and eye distance to screen data so that pixel data values can be converted to visual degree values. The pix2deg method is vectorized, meaning that is will perform the pixel to angle calculations on all elements of the provided pixel position numpy arrays... | 2 | null | Implement the Python class `VisualAngleCalc` described below.
Class description:
Implement the VisualAngleCalc class.
Method signatures and docstrings:
- def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None): Used to store calibrated area information and eye distance to screen data so that pixel ... | Implement the Python class `VisualAngleCalc` described below.
Class description:
Implement the VisualAngleCalc class.
Method signatures and docstrings:
- def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None): Used to store calibrated area information and eye distance to screen data so that pixel ... | 0ef5a2a618b30b87ecb390757c456681957b313c | <|skeleton|>
class VisualAngleCalc:
def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None):
"""Used to store calibrated area information and eye distance to screen data so that pixel data values can be converted to visual degree values. The pix2deg method is vectorized, meaning that is ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VisualAngleCalc:
def __init__(self, display_size_mm, display_res_pix, eye_distance_mm=None):
"""Used to store calibrated area information and eye distance to screen data so that pixel data values can be converted to visual degree values. The pix2deg method is vectorized, meaning that is will perform t... | the_stack_v2_python_sparse | References for PsychoPy/ECEM_Python_materials/python_source/data_visualization/common_workshop_functions.py | hejibo/Python-for-Psychologist | train | 4 | |
8d6a9f254f5f172d59c528d8e8f6dd584e13f435 | [
"tk.Tk.__init__(self)\nself.title('CPPN playground')\ncontainer = tk.Frame(self)\ncontainer.pack(side='top', fill='both', expand=True)\ncontainer.grid_rowconfigure(0, weight=1)\ncontainer.grid_columnconfigure(0, weight=1)\nmenubar = tk.Menu(self)\nfilemenu = tk.Menu(menubar)\nfilemenu.add_command(label='Main Page',... | <|body_start_0|>
tk.Tk.__init__(self)
self.title('CPPN playground')
container = tk.Frame(self)
container.pack(side='top', fill='both', expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
menubar = tk.Menu(self)
... | Main class that contains all handlers for the Tkinter GUI | Playground | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Playground:
"""Main class that contains all handlers for the Tkinter GUI"""
def __init__(self, genotype):
"""Contructer for main GUI container/handler"""
<|body_0|>
def raise_frame(self, page_name, container):
"""Raise a certain frame to the front of the GUI base... | stack_v2_sparse_classes_36k_train_031844 | 11,786 | no_license | [
{
"docstring": "Contructer for main GUI container/handler",
"name": "__init__",
"signature": "def __init__(self, genotype)"
},
{
"docstring": "Raise a certain frame to the front of the GUI based on its page_name",
"name": "raise_frame",
"signature": "def raise_frame(self, page_name, cont... | 2 | stack_v2_sparse_classes_30k_train_017164 | Implement the Python class `Playground` described below.
Class description:
Main class that contains all handlers for the Tkinter GUI
Method signatures and docstrings:
- def __init__(self, genotype): Contructer for main GUI container/handler
- def raise_frame(self, page_name, container): Raise a certain frame to the ... | Implement the Python class `Playground` described below.
Class description:
Main class that contains all handlers for the Tkinter GUI
Method signatures and docstrings:
- def __init__(self, genotype): Contructer for main GUI container/handler
- def raise_frame(self, page_name, container): Raise a certain frame to the ... | 317b615e39df5999f2fd3d5e7dd0af7d54aee6c8 | <|skeleton|>
class Playground:
"""Main class that contains all handlers for the Tkinter GUI"""
def __init__(self, genotype):
"""Contructer for main GUI container/handler"""
<|body_0|>
def raise_frame(self, page_name, container):
"""Raise a certain frame to the front of the GUI base... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Playground:
"""Main class that contains all handlers for the Tkinter GUI"""
def __init__(self, genotype):
"""Contructer for main GUI container/handler"""
tk.Tk.__init__(self)
self.title('CPPN playground')
container = tk.Frame(self)
container.pack(side='top', fill='... | the_stack_v2_python_sparse | FULL_CPPN_playground.py | wolfecameron/CPPN_springopt | train | 4 |
c622b540bf1dd239a0105723f377b41127112991 | [
"data = super(SubprocessWorkflow, self).__getstate__()\ndata['notification_listeners'] = []\nreturn data",
"log.info('Spawning subprocess: {}'.format(command))\nenv = {**os.environ, 'ETS_TOOLKIT': 'null'}\nprocess = subprocess.Popen(command, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subproces... | <|body_start_0|>
data = super(SubprocessWorkflow, self).__getstate__()
data['notification_listeners'] = []
return data
<|end_body_0|>
<|body_start_1|>
log.info('Spawning subprocess: {}'.format(command))
env = {**os.environ, 'ETS_TOOLKIT': 'null'}
process = subprocess.Pop... | A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point. | SubprocessWorkflow | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def __getstate__(self):
"""Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners instances are serialised. Allowing so would cause duplicate me... | stack_v2_sparse_classes_36k_train_031845 | 4,769 | permissive | [
{
"docstring": "Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners instances are serialised. Allowing so would cause duplicate messages to be sent to the UI from a single socket when the force_bdss is run on a new process.",
"name": "__getstate__",
"signature": "def _... | 4 | null | Implement the Python class `SubprocessWorkflow` described below.
Class description:
A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point.
Method signatures and docstrings:
- def __getstate__(self): Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners insta... | Implement the Python class `SubprocessWorkflow` described below.
Class description:
A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point.
Method signatures and docstrings:
- def __getstate__(self): Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners insta... | c56d47521233e369d42fe82282ed8e113a3747f7 | <|skeleton|>
class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def __getstate__(self):
"""Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners instances are serialised. Allowing so would cause duplicate me... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubprocessWorkflow:
"""A subclass of WorkflowSolver that spawns a subprocess to evaluate a single point."""
def __getstate__(self):
"""Overloads the Workflow.__getstate__ method to ensure that no BaseNotificationListeners instances are serialised. Allowing so would cause duplicate messages to be ... | the_stack_v2_python_sparse | enthought_example/example_evaluator/subprocess_workflow.py | force-h2020/force-bdss-plugin-enthought-example | train | 0 |
a0c6018c312b11a6b278142d093cf8b6655f6e15 | [
"super().__init__()\nself.voxel_size = torch.Tensor(voxel_size)\nself.point_cloud_range = point_cloud_range\nself.points_range_min = torch.Tensor(point_cloud_range[:3])\nself.points_range_max = torch.Tensor(point_cloud_range[3:])\nself.max_num_points = max_num_points\nif isinstance(max_voxels, tuple) or isinstance(... | <|body_start_0|>
super().__init__()
self.voxel_size = torch.Tensor(voxel_size)
self.point_cloud_range = point_cloud_range
self.points_range_min = torch.Tensor(point_cloud_range[:3])
self.points_range_max = torch.Tensor(point_cloud_range[3:])
self.max_num_points = max_num_... | PointPillarsVoxelization | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointPillarsVoxelization:
def __init__(self, voxel_size, point_cloud_range, max_num_points=32, max_voxels=[16000, 40000]):
"""Voxelization layer for the PointPillars model. Args: voxel_size: voxel edge lengths with format [x, y, z]. point_cloud_range: The valid range of point coordinates... | stack_v2_sparse_classes_36k_train_031846 | 39,137 | permissive | [
{
"docstring": "Voxelization layer for the PointPillars model. Args: voxel_size: voxel edge lengths with format [x, y, z]. point_cloud_range: The valid range of point coordinates as [x_min, y_min, z_min, x_max, y_max, z_max]. max_num_points: The maximum number of points per voxel. max_voxels: The maximum number... | 2 | null | Implement the Python class `PointPillarsVoxelization` described below.
Class description:
Implement the PointPillarsVoxelization class.
Method signatures and docstrings:
- def __init__(self, voxel_size, point_cloud_range, max_num_points=32, max_voxels=[16000, 40000]): Voxelization layer for the PointPillars model. Ar... | Implement the Python class `PointPillarsVoxelization` described below.
Class description:
Implement the PointPillarsVoxelization class.
Method signatures and docstrings:
- def __init__(self, voxel_size, point_cloud_range, max_num_points=32, max_voxels=[16000, 40000]): Voxelization layer for the PointPillars model. Ar... | 51482281dc180786e7563c73c12ac5df89289748 | <|skeleton|>
class PointPillarsVoxelization:
def __init__(self, voxel_size, point_cloud_range, max_num_points=32, max_voxels=[16000, 40000]):
"""Voxelization layer for the PointPillars model. Args: voxel_size: voxel edge lengths with format [x, y, z]. point_cloud_range: The valid range of point coordinates... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointPillarsVoxelization:
def __init__(self, voxel_size, point_cloud_range, max_num_points=32, max_voxels=[16000, 40000]):
"""Voxelization layer for the PointPillars model. Args: voxel_size: voxel edge lengths with format [x, y, z]. point_cloud_range: The valid range of point coordinates as [x_min, y_... | the_stack_v2_python_sparse | ml3d/torch/models/point_pillars.py | CosmosHua/Open3D-ML | train | 0 | |
bafe83223e850a684a0f0b9cc2ca17bfaaa162e5 | [
"response = self.api_handler.respond(self.path)\nif response:\n self.send_response(200)\n self.send_header('Content-type', 'application/json')\n self.end_headers()\n self.wfile.write(response.encode())\nelse:\n self.send_response(404)",
"response = self.static_handler.respond(self.path)\nif respons... | <|body_start_0|>
response = self.api_handler.respond(self.path)
if response:
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(response.encode())
else:
self.send_response(40... | Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned. | RootRequestHandler | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RootRequestHandler:
"""Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned."""
def handle_api_request(self):
"""Responds to JSON API requests"""
<|body_0|>
def handle_static_request(self):
"""Responds... | stack_v2_sparse_classes_36k_train_031847 | 3,469 | permissive | [
{
"docstring": "Responds to JSON API requests",
"name": "handle_api_request",
"signature": "def handle_api_request(self)"
},
{
"docstring": "Responds to static file requests",
"name": "handle_static_request",
"signature": "def handle_static_request(self)"
},
{
"docstring": "Root ... | 3 | stack_v2_sparse_classes_30k_val_000872 | Implement the Python class `RootRequestHandler` described below.
Class description:
Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned.
Method signatures and docstrings:
- def handle_api_request(self): Responds to JSON API requests
- def handle_static_re... | Implement the Python class `RootRequestHandler` described below.
Class description:
Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned.
Method signatures and docstrings:
- def handle_api_request(self): Responds to JSON API requests
- def handle_static_re... | a0ec86f1d51ae8d2538ff3404dad46eb302f9b4f | <|skeleton|>
class RootRequestHandler:
"""Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned."""
def handle_api_request(self):
"""Responds to JSON API requests"""
<|body_0|>
def handle_static_request(self):
"""Responds... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RootRequestHandler:
"""Forwards requests to the static or api request handler if the path is defined correctly. Otherwise 404 is returned."""
def handle_api_request(self):
"""Responds to JSON API requests"""
response = self.api_handler.respond(self.path)
if response:
s... | the_stack_v2_python_sparse | scripts/component_graph/server/__main__.py | winksaville/fuchsia | train | 3 |
2c34e4914b679a22ff6b4d9d53fa1d08d2a6396c | [
"super().__init__()\nsigma = 0.5 * (scale ** 2 - 1) ** 0.5\nsize = int(1 + 2 * 2.5 * sigma)\nif size % 2 == 0:\n size += 1\nrng = torch.arange(size, dtype=torch.get_default_dtype()) - size // 2\nx = rng.reshape(size, 1, 1).expand(size, size, size)\ny = rng.reshape(1, size, 1).expand(size, size, size)\nz = rng.re... | <|body_start_0|>
super().__init__()
sigma = 0.5 * (scale ** 2 - 1) ** 0.5
size = int(1 + 2 * 2.5 * sigma)
if size % 2 == 0:
size += 1
rng = torch.arange(size, dtype=torch.get_default_dtype()) - size // 2
x = rng.reshape(size, 1, 1).expand(size, size, size)
... | LowPassFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LowPassFilter:
def __init__(self, scale, stride=1):
""":param float scale: :param int stride:"""
<|body_0|>
def forward(self, image):
""":param tensor image: [..., x, y, z, channel]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
... | stack_v2_sparse_classes_36k_train_031848 | 1,703 | permissive | [
{
"docstring": ":param float scale: :param int stride:",
"name": "__init__",
"signature": "def __init__(self, scale, stride=1)"
},
{
"docstring": ":param tensor image: [..., x, y, z, channel]",
"name": "forward",
"signature": "def forward(self, image)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010125 | Implement the Python class `LowPassFilter` described below.
Class description:
Implement the LowPassFilter class.
Method signatures and docstrings:
- def __init__(self, scale, stride=1): :param float scale: :param int stride:
- def forward(self, image): :param tensor image: [..., x, y, z, channel] | Implement the Python class `LowPassFilter` described below.
Class description:
Implement the LowPassFilter class.
Method signatures and docstrings:
- def __init__(self, scale, stride=1): :param float scale: :param int stride:
- def forward(self, image): :param tensor image: [..., x, y, z, channel]
<|skeleton|>
class... | 447ccb253061a50b29f3a05c6eeffba34cca2c14 | <|skeleton|>
class LowPassFilter:
def __init__(self, scale, stride=1):
""":param float scale: :param int stride:"""
<|body_0|>
def forward(self, image):
""":param tensor image: [..., x, y, z, channel]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LowPassFilter:
def __init__(self, scale, stride=1):
""":param float scale: :param int stride:"""
super().__init__()
sigma = 0.5 * (scale ** 2 - 1) ** 0.5
size = int(1 + 2 * 2.5 * sigma)
if size % 2 == 0:
size += 1
rng = torch.arange(size, dtype=torch... | the_stack_v2_python_sparse | e3nn/image/filter.py | libubu11/e3nn | train | 0 | |
5b6552326f394609dc964d7565ef0af170ff4018 | [
"name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()\ngetpindao(self.driver)\nfor i in range(1):\n BasePage.Base(self.driver).do_swipe(self.driver, 'up')\n try:\n self.assertTrue(VideoPage.Video(self.driver).find_video_cover())\n self.assertTrue(VideoPage.Video(self.drive... | <|body_start_0|>
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpindao(self.driver)
for i in range(1):
BasePage.Base(self.driver).do_swipe(self.driver, 'up')
try:
self.assertTrue(VideoPage.Video(self.driver).find_video_cover... | nologin_video | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
<|body_0|>
def test_02_invideos(self):
"""视频内页信息流UI测试"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpind... | stack_v2_sparse_classes_36k_train_031849 | 2,158 | no_license | [
{
"docstring": "视频信息流UI测试",
"name": "test_01_video",
"signature": "def test_01_video(self)"
},
{
"docstring": "视频内页信息流UI测试",
"name": "test_02_invideos",
"signature": "def test_02_invideos(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004525 | Implement the Python class `nologin_video` described below.
Class description:
Implement the nologin_video class.
Method signatures and docstrings:
- def test_01_video(self): 视频信息流UI测试
- def test_02_invideos(self): 视频内页信息流UI测试 | Implement the Python class `nologin_video` described below.
Class description:
Implement the nologin_video class.
Method signatures and docstrings:
- def test_01_video(self): 视频信息流UI测试
- def test_02_invideos(self): 视频内页信息流UI测试
<|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
... | 7ce47cda6ac03b7eb707929dd2e0428132ff255f | <|skeleton|>
class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
<|body_0|>
def test_02_invideos(self):
"""视频内页信息流UI测试"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class nologin_video:
def test_01_video(self):
"""视频信息流UI测试"""
name1 = self.__class__.__name__ + '.' + GetName.get_current_function_name()
getpindao(self.driver)
for i in range(1):
BasePage.Base(self.driver).do_swipe(self.driver, 'up')
try:
self... | the_stack_v2_python_sparse | android_warning/android_warning/apptest/TestCase/nologin_testVideo.py | xiaominwanglast/uiautomator | train | 0 | |
045dc540da8922e0930a894f135d0b493e4607dd | [
"self.project = kwargs.pop('project', 'unknown')\nself.version = kwargs.pop('version', 'unknown')\nlogging.Formatter.__init__(self, *args, **kwargs)",
"if not isinstance(record.msg, six.text_type):\n record.msg = six.text_type(record.msg)\nrecord.project = self.project\nrecord.version = self.version\ncontext =... | <|body_start_0|>
self.project = kwargs.pop('project', 'unknown')
self.version = kwargs.pop('version', 'unknown')
logging.Formatter.__init__(self, *args, **kwargs)
<|end_body_0|>
<|body_start_1|>
if not isinstance(record.msg, six.text_type):
record.msg = six.text_type(record.... | A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug. For information about what variables are av... | ContextFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContextFormatter:
"""A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug.... | stack_v2_sparse_classes_36k_train_031850 | 26,597 | permissive | [
{
"docstring": "Initialize ContextFormatter instance Takes additional keyword arguments which can be used in the message format string. :keyword project: project name :type project: string :keyword version: project version :type version: string",
"name": "__init__",
"signature": "def __init__(self, *arg... | 3 | null | Implement the Python class `ContextFormatter` described below.
Class description:
A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extr... | Implement the Python class `ContextFormatter` described below.
Class description:
A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extr... | d2fabf40119267164b9e765e59e3f99cd61fdcef | <|skeleton|>
class ContextFormatter:
"""A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContextFormatter:
"""A context.RequestContext aware formatter configured through flags. The flags used to set format strings are: logging_context_format_string and logging_default_format_string. You can also specify logging_debug_format_suffix to append extra formatting if the log level is debug. For informat... | the_stack_v2_python_sparse | cloudbaseinit/openstack/common/log.py | pellaeon/bsd-cloudinit | train | 75 |
a7ab3aabceb547572fb8e06a82ebcd2483ace55f | [
"if not is_iterable(pass_sequences):\n bad_type = type(pass_sequences)\n raise TypeError(f'Expected sequence of workflows, got {bad_type}.')\nif not callable(less_than):\n bad_type = type(less_than)\n msg = f'Expected callable function for less_than, got {bad_type}'\n raise TypeError(msg)\nself.workf... | <|body_start_0|>
if not is_iterable(pass_sequences):
bad_type = type(pass_sequences)
raise TypeError(f'Expected sequence of workflows, got {bad_type}.')
if not callable(less_than):
bad_type = type(less_than)
msg = f'Expected callable function for less_than... | The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering. | ParallelDo | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParallelDo:
"""The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering."""
def __init__(self, pass_sequences: Iterable[WorkflowLike], less_than: Call... | stack_v2_sparse_classes_36k_train_031851 | 3,330 | permissive | [
{
"docstring": "Construct a ParallelDo. Args: pass_sequences (Iterable[WorkflowLike]): The group of workflows to run in parallel. less_than (Callable[[Circuit, Circuit], bool]): Return True if the first circuit is preferred to the second one. This will be used to determine which output circuit to select. pick_f... | 2 | stack_v2_sparse_classes_30k_train_006629 | Implement the Python class `ParallelDo` described below.
Class description:
The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering.
Method signatures and docstrings:
- def __... | Implement the Python class `ParallelDo` described below.
Class description:
The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering.
Method signatures and docstrings:
- def __... | c89112d15072e8ffffb68cf1757b184e2aeb3dc8 | <|skeleton|>
class ParallelDo:
"""The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering."""
def __init__(self, pass_sequences: Iterable[WorkflowLike], less_than: Call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParallelDo:
"""The ParallelDo class. This is a control pass that executes a sequence of workflows in parallel. The branch that is accepted can either be the first to complete or one selected by a provided ordering."""
def __init__(self, pass_sequences: Iterable[WorkflowLike], less_than: Callable[[Circuit... | the_stack_v2_python_sparse | bqskit/passes/control/paralleldo.py | BQSKit/bqskit | train | 54 |
805767f5fae8ca93f420da4113ac35b6d2bd5821 | [
"self._model_file = os.path.join(self._model_path, f'{self._model_name}.pkl')\nif not os.path.exists(self._model_file):\n raise mlrun.errors.MLRunNotFoundError(f\"The model file '{self._model_name}.pkl' was not found within the given 'model_path': '{self._model_path}'\")",
"super(SKLearnModelHandler, self).sav... | <|body_start_0|>
self._model_file = os.path.join(self._model_path, f'{self._model_name}.pkl')
if not os.path.exists(self._model_file):
raise mlrun.errors.MLRunNotFoundError(f"The model file '{self._model_name}.pkl' was not found within the given 'model_path': '{self._model_path}'")
<|end_bod... | Class for handling a SciKitLearn model, enabling loading and saving it during runs. | SKLearnModelHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SKLearnModelHandler:
"""Class for handling a SciKitLearn model, enabling loading and saving it during runs."""
def _collect_files_from_local_path(self):
"""If the model path given is of a local path, search for the needed model files and collect them into this handler for later loadi... | stack_v2_sparse_classes_36k_train_031852 | 4,745 | permissive | [
{
"docstring": "If the model path given is of a local path, search for the needed model files and collect them into this handler for later loading the model. :raise MLRunNotFoundError: If the model file was not found.",
"name": "_collect_files_from_local_path",
"signature": "def _collect_files_from_loca... | 4 | null | Implement the Python class `SKLearnModelHandler` described below.
Class description:
Class for handling a SciKitLearn model, enabling loading and saving it during runs.
Method signatures and docstrings:
- def _collect_files_from_local_path(self): If the model path given is of a local path, search for the needed model... | Implement the Python class `SKLearnModelHandler` described below.
Class description:
Class for handling a SciKitLearn model, enabling loading and saving it during runs.
Method signatures and docstrings:
- def _collect_files_from_local_path(self): If the model path given is of a local path, search for the needed model... | b5fe0c05ae7f5818a4a5a5a40245c851ff9b2c77 | <|skeleton|>
class SKLearnModelHandler:
"""Class for handling a SciKitLearn model, enabling loading and saving it during runs."""
def _collect_files_from_local_path(self):
"""If the model path given is of a local path, search for the needed model files and collect them into this handler for later loadi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SKLearnModelHandler:
"""Class for handling a SciKitLearn model, enabling loading and saving it during runs."""
def _collect_files_from_local_path(self):
"""If the model path given is of a local path, search for the needed model files and collect them into this handler for later loading the model.... | the_stack_v2_python_sparse | mlrun/frameworks/sklearn/model_handler.py | mlrun/mlrun | train | 1,093 |
88222474a8a8f12aeccd72e2bc79b6497b2f7a08 | [
"name_only = 'name_only' in self.request\nsearch_str = self.request.get('search_str', None)\nresults = []\nif search_str is None:\n return results\nfor name, iface in self.context.items():\n if search_str in name or (not name_only and search_str in getAllTextOfInterface(iface)):\n results.append({'name... | <|body_start_0|>
name_only = 'name_only' in self.request
search_str = self.request.get('search_str', None)
results = []
if search_str is None:
return results
for name, iface in self.context.items():
if search_str in name or (not name_only and search_str in... | Menu for the Interface Documentation Module. | Menu | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
"""Menu for the Interface Documentation Module."""
def findInterfaces(self):
"""Find the interface that match any text in the documentation strings or a partial path."""
<|body_0|>
def findAllInterfaces(self):
"""Find all interfaces."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_031853 | 2,473 | permissive | [
{
"docstring": "Find the interface that match any text in the documentation strings or a partial path.",
"name": "findInterfaces",
"signature": "def findInterfaces(self)"
},
{
"docstring": "Find all interfaces.",
"name": "findAllInterfaces",
"signature": "def findAllInterfaces(self)"
}... | 2 | stack_v2_sparse_classes_30k_val_000725 | Implement the Python class `Menu` described below.
Class description:
Menu for the Interface Documentation Module.
Method signatures and docstrings:
- def findInterfaces(self): Find the interface that match any text in the documentation strings or a partial path.
- def findAllInterfaces(self): Find all interfaces. | Implement the Python class `Menu` described below.
Class description:
Menu for the Interface Documentation Module.
Method signatures and docstrings:
- def findInterfaces(self): Find the interface that match any text in the documentation strings or a partial path.
- def findAllInterfaces(self): Find all interfaces.
<... | ea7814831c279422b982c553866ceac6b442de68 | <|skeleton|>
class Menu:
"""Menu for the Interface Documentation Module."""
def findInterfaces(self):
"""Find the interface that match any text in the documentation strings or a partial path."""
<|body_0|>
def findAllInterfaces(self):
"""Find all interfaces."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Menu:
"""Menu for the Interface Documentation Module."""
def findInterfaces(self):
"""Find the interface that match any text in the documentation strings or a partial path."""
name_only = 'name_only' in self.request
search_str = self.request.get('search_str', None)
results... | the_stack_v2_python_sparse | src/zope/app/apidoc/ifacemodule/menu.py | zopefoundation/zope.app.apidoc | train | 0 |
4f8407779d883247c345a44237bd44db4b901387 | [
"super().__init__()\nself.vgg2l = torch.nn.Sequential(torch.nn.Conv2d(1, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(64, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.MaxPool2d((3, 2)), torch.nn.Conv2d(64, 128, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(128, 128, 3, stride=... | <|body_start_0|>
super().__init__()
self.vgg2l = torch.nn.Sequential(torch.nn.Conv2d(1, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.Conv2d(64, 64, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.MaxPool2d((3, 2)), torch.nn.Conv2d(64, 128, 3, stride=1, padding=1), torch.nn.ReLU(), torch.nn.... | VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs | VGG2L | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VGG2L:
"""VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs"""
def __init__(self, idim, odim):
"""Construct a VGG2L object."""
<|body_0|>
def forward(self, x, x_mask):
"""VGG2L forward for x. Args: x (tor... | stack_v2_sparse_classes_36k_train_031854 | 2,036 | permissive | [
{
"docstring": "Construct a VGG2L object.",
"name": "__init__",
"signature": "def __init__(self, idim, odim)"
},
{
"docstring": "VGG2L forward for x. Args: x (torch.Tensor): input torch (B, T, idim) x_mask (torch.Tensor): (B, 1, T) Returns: x (torch.Tensor): input torch (B, sub(T), attention_dim... | 3 | stack_v2_sparse_classes_30k_train_017739 | Implement the Python class `VGG2L` described below.
Class description:
VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs
Method signatures and docstrings:
- def __init__(self, idim, odim): Construct a VGG2L object.
- def forward(self, x, x_mask): VGG2L forwar... | Implement the Python class `VGG2L` described below.
Class description:
VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs
Method signatures and docstrings:
- def __init__(self, idim, odim): Construct a VGG2L object.
- def forward(self, x, x_mask): VGG2L forwar... | 6ecde88045e1b706b2390f98eb1950ce4075a07d | <|skeleton|>
class VGG2L:
"""VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs"""
def __init__(self, idim, odim):
"""Construct a VGG2L object."""
<|body_0|>
def forward(self, x, x_mask):
"""VGG2L forward for x. Args: x (tor... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VGG2L:
"""VGG2L module for transformer encoder. Args: idim (int): dimension of inputs odim (int): dimension of outputs"""
def __init__(self, idim, odim):
"""Construct a VGG2L object."""
super().__init__()
self.vgg2l = torch.nn.Sequential(torch.nn.Conv2d(1, 64, 3, stride=1, padding... | the_stack_v2_python_sparse | espnet/nets/pytorch_backend/transducer/vgg2l.py | sw005320/espnet-1 | train | 4 |
76e5e18798833f0d92b248d62497bf2c09a966ab | [
"instance = super().create(seller=seller, **kwargs)\ninstance.categories.add(*categories)\ninstance.geo_regions.add(*geo_regions)\ninstance.languages.add(*languages)\ninstance.data_types.add(*data_types)\ninstance.data_formats.add(*data_formats)\ninstance.data_delivery_types.add(*data_delivery_types)\ninstance.save... | <|body_start_0|>
instance = super().create(seller=seller, **kwargs)
instance.categories.add(*categories)
instance.geo_regions.add(*geo_regions)
instance.languages.add(*languages)
instance.data_types.add(*data_types)
instance.data_formats.add(*data_formats)
instanc... | Class representing seller products manager | SellerProductManager | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SellerProductManager:
"""Class representing seller products manager"""
def create(self, seller: int, categories: tp.List[int], geo_regions: tp.List[int], languages: tp.List[int], data_types: tp.List[int], data_formats: tp.List[int], data_delivery_types: tp.List[int], **kwargs):
"""Cr... | stack_v2_sparse_classes_36k_train_031855 | 9,696 | permissive | [
{
"docstring": "Create seller product manager. Attributes: seller (int): seller id categories (list): categories list geo_regions (list): geo regions list languages (list): languages list data_types (list): data types list data_formats (list): data formats list data_delivery_types (list): data delivery types li... | 2 | stack_v2_sparse_classes_30k_train_019039 | Implement the Python class `SellerProductManager` described below.
Class description:
Class representing seller products manager
Method signatures and docstrings:
- def create(self, seller: int, categories: tp.List[int], geo_regions: tp.List[int], languages: tp.List[int], data_types: tp.List[int], data_formats: tp.Li... | Implement the Python class `SellerProductManager` described below.
Class description:
Class representing seller products manager
Method signatures and docstrings:
- def create(self, seller: int, categories: tp.List[int], geo_regions: tp.List[int], languages: tp.List[int], data_types: tp.List[int], data_formats: tp.Li... | f8930ff1c009ad18e522ab29680b4bcd50a6020e | <|skeleton|>
class SellerProductManager:
"""Class representing seller products manager"""
def create(self, seller: int, categories: tp.List[int], geo_regions: tp.List[int], languages: tp.List[int], data_types: tp.List[int], data_formats: tp.List[int], data_delivery_types: tp.List[int], **kwargs):
"""Cr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SellerProductManager:
"""Class representing seller products manager"""
def create(self, seller: int, categories: tp.List[int], geo_regions: tp.List[int], languages: tp.List[int], data_types: tp.List[int], data_formats: tp.List[int], data_delivery_types: tp.List[int], **kwargs):
"""Create seller p... | the_stack_v2_python_sparse | src/seller_products/managers.py | evis-market/web-interface-backend | train | 2 |
d4390ce07060dae71802e4f66d530590f9c87795 | [
"beg, end = (0, len(nums) - 1)\nwhile beg <= end:\n while beg < end and nums[beg] == nums[beg + 1]:\n beg += 1\n while end > beg and nums[end] == nums[end - 1]:\n end -= 1\n if beg == end:\n return nums[beg]\n mid = (beg + end) / 2\n if nums[mid] > nums[end]:\n beg = mid +... | <|body_start_0|>
beg, end = (0, len(nums) - 1)
while beg <= end:
while beg < end and nums[beg] == nums[beg + 1]:
beg += 1
while end > beg and nums[end] == nums[end - 1]:
end -= 1
if beg == end:
return nums[beg]
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
beg, end = (0, len(nums) - 1)
while beg <= e... | stack_v2_sparse_classes_36k_train_031856 | 1,558 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin",
"signature": "def findMin(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "findMin2",
"signature": "def findMin2(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004540 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findMin(self, nums): :type nums: List[int] :rtype: int
- def findMin2(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def findMin(self, nums... | 2526f8c0dec7101123123740e146ee4081e979ee | <|skeleton|>
class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def findMin2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findMin(self, nums):
""":type nums: List[int] :rtype: int"""
beg, end = (0, len(nums) - 1)
while beg <= end:
while beg < end and nums[beg] == nums[beg + 1]:
beg += 1
while end > beg and nums[end] == nums[end - 1]:
en... | the_stack_v2_python_sparse | 154. Find Minimum in Rotated Sorted Array II.py | zhangpengGenedock/leetcode_python | train | 1 | |
c227b804195482a4554a9325e1cd0c0dc3531e31 | [
"from po.test_web_wexin.page.add_member_page import AddMemberPage\nself.wait((By.CSS_SELECTOR, '.ww_operationBar .js_add_member'))\nself.find(By.CSS_SELECTOR, '.ww_operationBar .js_add_member').click()\nreturn AddMemberPage(self.driver)",
"self.wait((By.CSS_SELECTOR, self._localhost_member))\nmembers = self.drive... | <|body_start_0|>
from po.test_web_wexin.page.add_member_page import AddMemberPage
self.wait((By.CSS_SELECTOR, '.ww_operationBar .js_add_member'))
self.find(By.CSS_SELECTOR, '.ww_operationBar .js_add_member').click()
return AddMemberPage(self.driver)
<|end_body_0|>
<|body_start_1|>
... | ContactPage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员 :return:"""
<|body_0|>
def get_member(self):
"""获取成员列表,用来做断言 :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
from po.test_web_wexin.page.add_member_page import AddMemberPage
self.wait(... | stack_v2_sparse_classes_36k_train_031857 | 1,114 | no_license | [
{
"docstring": "添加成员 :return:",
"name": "goto_add_member",
"signature": "def goto_add_member(self)"
},
{
"docstring": "获取成员列表,用来做断言 :return:",
"name": "get_member",
"signature": "def get_member(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021380 | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员 :return:
- def get_member(self): 获取成员列表,用来做断言 :return: | Implement the Python class `ContactPage` described below.
Class description:
Implement the ContactPage class.
Method signatures and docstrings:
- def goto_add_member(self): 添加成员 :return:
- def get_member(self): 获取成员列表,用来做断言 :return:
<|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员 :ret... | cac9f66f8df0d61c828a635061e01288943828b5 | <|skeleton|>
class ContactPage:
def goto_add_member(self):
"""添加成员 :return:"""
<|body_0|>
def get_member(self):
"""获取成员列表,用来做断言 :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ContactPage:
def goto_add_member(self):
"""添加成员 :return:"""
from po.test_web_wexin.page.add_member_page import AddMemberPage
self.wait((By.CSS_SELECTOR, '.ww_operationBar .js_add_member'))
self.find(By.CSS_SELECTOR, '.ww_operationBar .js_add_member').click()
return AddM... | the_stack_v2_python_sparse | po/test_web_wexin/page/contact_page.py | mengdg/Hogwarts-mengdegong-16 | train | 0 | |
4dbd6f9a9560fcc80842e38cdf9741d712215c77 | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"conte... | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Missing associated documentation comment in .proto file. | AzureStorageServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AzureStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listAzureStorage(self, request, context):
"""Storage"""
<|body_0|>
def getAzureStorage(self, request, context):
"""Missing associated documentation comment in .proto f... | stack_v2_sparse_classes_36k_train_031858 | 9,910 | permissive | [
{
"docstring": "Storage",
"name": "listAzureStorage",
"signature": "def listAzureStorage(self, request, context)"
},
{
"docstring": "Missing associated documentation comment in .proto file.",
"name": "getAzureStorage",
"signature": "def getAzureStorage(self, request, context)"
},
{
... | 5 | stack_v2_sparse_classes_30k_train_006775 | Implement the Python class `AzureStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listAzureStorage(self, request, context): Storage
- def getAzureStorage(self, request, context): Missing associated documentatio... | Implement the Python class `AzureStorageServiceServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def listAzureStorage(self, request, context): Storage
- def getAzureStorage(self, request, context): Missing associated documentatio... | c69e14b409add099d151434b9add711e41f41b20 | <|skeleton|>
class AzureStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listAzureStorage(self, request, context):
"""Storage"""
<|body_0|>
def getAzureStorage(self, request, context):
"""Missing associated documentation comment in .proto f... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AzureStorageServiceServicer:
"""Missing associated documentation comment in .proto file."""
def listAzureStorage(self, request, context):
"""Storage"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError(... | the_stack_v2_python_sparse | python-sdk/src/airavata_mft_sdk/azure/AzureStorageService_pb2_grpc.py | apache/airavata-mft | train | 23 |
beff3fb198e8dd59fcae4ed8bed7e32aeaa4832d | [
"if model._meta.app_label in self.route_app_labels:\n return 'subexsecure_auth'\nreturn None",
"if model._meta.app_label in self.route_app_labels:\n return 'subexsecure_auth'\nreturn None",
"if obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels:\n return True... | <|body_start_0|>
if model._meta.app_label in self.route_app_labels:
return 'subexsecure_auth'
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in self.route_app_labels:
return 'subexsecure_auth'
return None
<|end_body_1|>
<|body_start_2|>
... | AuthRouter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthRouter:
def db_for_read(self, model, **hints):
"""Attempts to read auth and contenttypes models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth and contenttypes models go to subexsecure_auth."""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_031859 | 1,487 | no_license | [
{
"docstring": "Attempts to read auth and contenttypes models go to auth_db.",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "Attempts to write auth and contenttypes models go to subexsecure_auth.",
"name": "db_for_write",
"signature": "def... | 4 | stack_v2_sparse_classes_30k_train_004317 | Implement the Python class `AuthRouter` described below.
Class description:
Implement the AuthRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth and contenttypes models go to auth_db.
- def db_for_write(self, model, **hints): Attempts to write auth and conte... | Implement the Python class `AuthRouter` described below.
Class description:
Implement the AuthRouter class.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): Attempts to read auth and contenttypes models go to auth_db.
- def db_for_write(self, model, **hints): Attempts to write auth and conte... | f34c7173eb9108605ccc6016bc0fc1df2901ece3 | <|skeleton|>
class AuthRouter:
def db_for_read(self, model, **hints):
"""Attempts to read auth and contenttypes models go to auth_db."""
<|body_0|>
def db_for_write(self, model, **hints):
"""Attempts to write auth and contenttypes models go to subexsecure_auth."""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthRouter:
def db_for_read(self, model, **hints):
"""Attempts to read auth and contenttypes models go to auth_db."""
if model._meta.app_label in self.route_app_labels:
return 'subexsecure_auth'
return None
def db_for_write(self, model, **hints):
"""Attempts to... | the_stack_v2_python_sparse | honeypot_dashboard/database_router/AuthRouter.py | manavchawla2012/honeypot_dashboard | train | 0 | |
fdf8a45b3f361f4f1b0e262ccea0ee3a712a9582 | [
"headers = headers\npostdata = params\nresponse = requests.get(url, postdata, headers=headers, timeout=5)\ntry:\n if response.status_code == 200:\n return response.json()\n else:\n print(response.status_code)\n return\nexcept BaseException as e:\n print('httpGet failed, detail is:%s,%s... | <|body_start_0|>
headers = headers
postdata = params
response = requests.get(url, postdata, headers=headers, timeout=5)
try:
if response.status_code == 200:
return response.json()
else:
print(response.status_code)
re... | http通信器 | HttpCommunicator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Conten... | stack_v2_sparse_classes_36k_train_031860 | 2,864 | no_license | [
{
"docstring": "http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Content-type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1;... | 2 | stack_v2_sparse_classes_30k_train_017767 | Implement the Python class `HttpCommunicator` described below.
Class description:
http通信器
Method signatures and docstrings:
- def http_get(self, url, params, headers): http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1... | Implement the Python class `HttpCommunicator` described below.
Class description:
http通信器
Method signatures and docstrings:
- def http_get(self, url, params, headers): http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1... | 1bc744a6d331b4b733f6b6658b8310eb0c30524e | <|skeleton|>
class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Conten... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HttpCommunicator:
"""http通信器"""
def http_get(self, url, params, headers):
"""http通信器get请求方法 :param url: 请求接口地址 字符串类型 例如:'https://api.huobi.pro/market/history/kline' :param params: 请求参数 字典类型 例如:{'symbol': 'btcusdt', 'period': '1min', 'size': 150} :param headers: 请求头信息 字典类型 例如:{'Content-type': 'app... | the_stack_v2_python_sparse | investment/api/communicators.py | cliicy/vtrade | train | 0 |
dc57a050f05c2b12b0a41236602f2d30d052bae1 | [
"if x < 0:\n return False\nx_str = str(x)\nlength = len(x_str)\nstart, end = (0, length - 1)\nwhile start < end:\n if x_str[start] != x_str[end]:\n return False\n else:\n start += 1\n end -= 1\nreturn True",
"if x < 0:\n return False\nx_lis = []\ntmp = x\ni = 0\nwhile tmp > 0:\n ... | <|body_start_0|>
if x < 0:
return False
x_str = str(x)
length = len(x_str)
start, end = (0, length - 1)
while start < end:
if x_str[start] != x_str[end]:
return False
else:
start += 1
end -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPalindrome(self, x):
"""Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool"""
<|body_0|>
def isPalindrome2(self, x):
"""Determine whether an integer is a palindrome In... | stack_v2_sparse_classes_36k_train_031861 | 1,369 | no_license | [
{
"docstring": "Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool",
"name": "isPalindrome",
"signature": "def isPalindrome(self, x)"
},
{
"docstring": "Determine whether an integer is a palindrome In this method... | 2 | stack_v2_sparse_classes_30k_train_014718 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool
- def isPalindro... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPalindrome(self, x): Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool
- def isPalindro... | 32bc5a7082a57e5f3dde2eb8b371a987ef892d4d | <|skeleton|>
class Solution:
def isPalindrome(self, x):
"""Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool"""
<|body_0|>
def isPalindrome2(self, x):
"""Determine whether an integer is a palindrome In... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isPalindrome(self, x):
"""Determine whether an integer is a palindrome In this method, the Integer inputted is changed into a string :param x: int :return: bool"""
if x < 0:
return False
x_str = str(x)
length = len(x_str)
start, end = (0, lengt... | the_stack_v2_python_sparse | 9_isPalindrome.py | APotatoBoy/Leetcode | train | 1 | |
f65384cc394e2e461ed884509507564d34bb7a0c | [
"if not data.get('schema_name'):\n business_schema_claims = (data.get('eq_id'), data.get('form_type'))\n if not all(business_schema_claims):\n raise ValidationError(\"Either 'schema_name' or 'eq_id' and 'form_type' must be defined\")",
"if data.get('schema_name'):\n logger.info('Using schema_name ... | <|body_start_0|>
if not data.get('schema_name'):
business_schema_claims = (data.get('eq_id'), data.get('form_type'))
if not all(business_schema_claims):
raise ValidationError("Either 'schema_name' or 'eq_id' and 'form_type' must be defined")
<|end_body_0|>
<|body_start_1... | Metadata which is required for the operation of runner itself | RunnerMetadataSchema | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RunnerMetadataSchema:
"""Metadata which is required for the operation of runner itself"""
def validate_schema_name(self, data, **kwargs):
"""Function to validate the business schema parameters"""
<|body_0|>
def update_schema_name(self, data, **kwargs):
"""Functio... | stack_v2_sparse_classes_36k_train_031862 | 7,792 | permissive | [
{
"docstring": "Function to validate the business schema parameters",
"name": "validate_schema_name",
"signature": "def validate_schema_name(self, data, **kwargs)"
},
{
"docstring": "Function to transform parameters into a business schema",
"name": "update_schema_name",
"signature": "def... | 3 | null | Implement the Python class `RunnerMetadataSchema` described below.
Class description:
Metadata which is required for the operation of runner itself
Method signatures and docstrings:
- def validate_schema_name(self, data, **kwargs): Function to validate the business schema parameters
- def update_schema_name(self, dat... | Implement the Python class `RunnerMetadataSchema` described below.
Class description:
Metadata which is required for the operation of runner itself
Method signatures and docstrings:
- def validate_schema_name(self, data, **kwargs): Function to validate the business schema parameters
- def update_schema_name(self, dat... | 5412ef4c2cb2008a32b426362a5d2dc386caf7cc | <|skeleton|>
class RunnerMetadataSchema:
"""Metadata which is required for the operation of runner itself"""
def validate_schema_name(self, data, **kwargs):
"""Function to validate the business schema parameters"""
<|body_0|>
def update_schema_name(self, data, **kwargs):
"""Functio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RunnerMetadataSchema:
"""Metadata which is required for the operation of runner itself"""
def validate_schema_name(self, data, **kwargs):
"""Function to validate the business schema parameters"""
if not data.get('schema_name'):
business_schema_claims = (data.get('eq_id'), data... | the_stack_v2_python_sparse | app/utilities/metadata_parser.py | pricem14pc/eq-questionnaire-runner | train | 0 |
c475f91975fc5c7382c11142e7a0df106e06df1f | [
"agent_now = request.user.userinfo.agent\nu_type = request.query_params.get('u_type')\nfilter_data = dict()\nif u_type and u_type in ['center', 'monitor', 'scan', 'defense', 'cloud_defense', 'hids', 'nids']:\n filter_data['u_type'] = u_type\nupgrade_tasks = models.SystemUpgradeTask.objects.filter(agent=agent_now... | <|body_start_0|>
agent_now = request.user.userinfo.agent
u_type = request.query_params.get('u_type')
filter_data = dict()
if u_type and u_type in ['center', 'monitor', 'scan', 'defense', 'cloud_defense', 'hids', 'nids']:
filter_data['u_type'] = u_type
upgrade_tasks = ... | 升级处理 | SystemUpgradeList | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SystemUpgradeList:
"""升级处理"""
def get(self, request):
"""升级列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""添加升级 { { "file_id": 1, "u_type": "center", "targets": [ {"uuid": "uuid-1", "id": 1}, {"uuid": "uuid-2", "id": 2} ] } } :param request:... | stack_v2_sparse_classes_36k_train_031863 | 15,651 | no_license | [
{
"docstring": "升级列表 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "添加升级 { { \"file_id\": 1, \"u_type\": \"center\", \"targets\": [ {\"uuid\": \"uuid-1\", \"id\": 1}, {\"uuid\": \"uuid-2\", \"id\": 2} ] } } :param request: :return:",
"name"... | 2 | stack_v2_sparse_classes_30k_train_019836 | Implement the Python class `SystemUpgradeList` described below.
Class description:
升级处理
Method signatures and docstrings:
- def get(self, request): 升级列表 :param request: :return:
- def post(self, request): 添加升级 { { "file_id": 1, "u_type": "center", "targets": [ {"uuid": "uuid-1", "id": 1}, {"uuid": "uuid-2", "id": 2} ... | Implement the Python class `SystemUpgradeList` described below.
Class description:
升级处理
Method signatures and docstrings:
- def get(self, request): 升级列表 :param request: :return:
- def post(self, request): 添加升级 { { "file_id": 1, "u_type": "center", "targets": [ {"uuid": "uuid-1", "id": 1}, {"uuid": "uuid-2", "id": 2} ... | d6e025d7e9d9e3aecfd399c77f376130edd8a2df | <|skeleton|>
class SystemUpgradeList:
"""升级处理"""
def get(self, request):
"""升级列表 :param request: :return:"""
<|body_0|>
def post(self, request):
"""添加升级 { { "file_id": 1, "u_type": "center", "targets": [ {"uuid": "uuid-1", "id": 1}, {"uuid": "uuid-2", "id": 2} ] } } :param request:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SystemUpgradeList:
"""升级处理"""
def get(self, request):
"""升级列表 :param request: :return:"""
agent_now = request.user.userinfo.agent
u_type = request.query_params.get('u_type')
filter_data = dict()
if u_type and u_type in ['center', 'monitor', 'scan', 'defense', 'clou... | the_stack_v2_python_sparse | soc_system/views/upgrade_views.py | sundw2015/841 | train | 4 |
c25d5a3ac36b0e478a4671a3dd44f197d517eaf1 | [
"softwareOsh = InstalledSoftwareBuilder().build(software)\nsoftwareOsh.setContainer(hostOsh)\nreturn softwareOsh",
"softwareOshv = ObjectStateHolderVector()\nif softwareList:\n for software in softwareList:\n softwareOsh = self.report(software, hostOsh)\n softwareOshv.add(softwareOsh)\nreturn sof... | <|body_start_0|>
softwareOsh = InstalledSoftwareBuilder().build(software)
softwareOsh.setContainer(hostOsh)
return softwareOsh
<|end_body_0|>
<|body_start_1|>
softwareOshv = ObjectStateHolderVector()
if softwareList:
for software in softwareList:
soft... | InstalledSoftwareReporter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstalledSoftwareReporter:
def report(self, software, hostOsh):
"""Builds software OSH and links host OSH to it. Returns OSH"""
<|body_0|>
def reportAll(self, softwareList, hostOsh):
"""Creates software OSHV with links to host OSH. Returns OSHV"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_031864 | 19,816 | no_license | [
{
"docstring": "Builds software OSH and links host OSH to it. Returns OSH",
"name": "report",
"signature": "def report(self, software, hostOsh)"
},
{
"docstring": "Creates software OSHV with links to host OSH. Returns OSHV",
"name": "reportAll",
"signature": "def reportAll(self, software... | 2 | null | Implement the Python class `InstalledSoftwareReporter` described below.
Class description:
Implement the InstalledSoftwareReporter class.
Method signatures and docstrings:
- def report(self, software, hostOsh): Builds software OSH and links host OSH to it. Returns OSH
- def reportAll(self, softwareList, hostOsh): Cre... | Implement the Python class `InstalledSoftwareReporter` described below.
Class description:
Implement the InstalledSoftwareReporter class.
Method signatures and docstrings:
- def report(self, software, hostOsh): Builds software OSH and links host OSH to it. Returns OSH
- def reportAll(self, softwareList, hostOsh): Cre... | c431e809e8d0f82e1bca7e3429dd0245560b5680 | <|skeleton|>
class InstalledSoftwareReporter:
def report(self, software, hostOsh):
"""Builds software OSH and links host OSH to it. Returns OSH"""
<|body_0|>
def reportAll(self, softwareList, hostOsh):
"""Creates software OSHV with links to host OSH. Returns OSHV"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InstalledSoftwareReporter:
def report(self, software, hostOsh):
"""Builds software OSH and links host OSH to it. Returns OSH"""
softwareOsh = InstalledSoftwareBuilder().build(software)
softwareOsh.setContainer(hostOsh)
return softwareOsh
def reportAll(self, softwareList, h... | the_stack_v2_python_sparse | reference/ucmdb/discovery/hostresource.py | madmonkyang/cda-record | train | 0 | |
c820c3c7e7dcfe12689941e64853d6cfd77af07a | [
"RadianceMaterial.__init__(self, name, materialType='glow', modifier='void')\nself.red = red\n'A positive value for the Red channel of the glow'\nself.green = green\n'A positive value for the Green channel of the glow'\nself.blue = blue\n'A positive value for the Blue channel of the glow'\nself.maxRadius = maxRadiu... | <|body_start_0|>
RadianceMaterial.__init__(self, name, materialType='glow', modifier='void')
self.red = red
'A positive value for the Red channel of the glow'
self.green = green
'A positive value for the Green channel of the glow'
self.blue = blue
'A positive valu... | Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue channel of the glow maxRadius: ---. | GlowMaterial | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GlowMaterial:
"""Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue chann... | stack_v2_sparse_classes_36k_train_031865 | 2,004 | permissive | [
{
"docstring": "Init Glow material.",
"name": "__init__",
"signature": "def __init__(self, name, red=0, green=0, blue=0, maxRadius=0)"
},
{
"docstring": "Return full Radiance definition",
"name": "toRadString",
"signature": "def toRadString(self, minimal=False)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010236 | Implement the Python class `GlowMaterial` described below.
Class description:
Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow bl... | Implement the Python class `GlowMaterial` described below.
Class description:
Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow bl... | 983fccc934e5546082557f6c2d1f2d9e00eba332 | <|skeleton|>
class GlowMaterial:
"""Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue chann... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GlowMaterial:
"""Create glow material. Attributes: name: Material name as a string. The name should not have whitespaces or special characters. red: A positive value for the Red channel of the glow green: A positive value for the Green channel of the glow blue: A positive value for the Blue channel of the glo... | the_stack_v2_python_sparse | honeybee/radiance/material/glow.py | ladybug-tools/honeybee-server | train | 7 |
0bdfd8ed0b72a16ece6a44d157bb397f34e7033f | [
"if not head:\n return None\nslow, fast = (head, head)\nwhile fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n while head != slow:\n head = head.next\n slow = slow.next\n return head\nreturn None",
"if not headA or not headB:\n ... | <|body_start_0|>
if not head:
return None
slow, fast = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
while head != slow:
head = head.next
slow ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getCycleEntry(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not head... | stack_v2_sparse_classes_36k_train_031866 | 1,552 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "getCycleEntry",
"signature": "def getCycleEntry(self, head)"
},
{
"docstring": ":type head1, head1: ListNode :rtype: ListNode",
"name": "getIntersectionNode",
"signature": "def getIntersectionNode(self, headA, headB)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getCycleEntry(self, head): :type head: ListNode :rtype: ListNode
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getCycleEntry(self, head): :type head: ListNode :rtype: ListNode
- def getIntersectionNode(self, headA, headB): :type head1, head1: ListNode :rtype: ListNode
<|skeleton|>
cl... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def getCycleEntry(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def getIntersectionNode(self, headA, headB):
""":type head1, head1: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getCycleEntry(self, head):
""":type head: ListNode :rtype: ListNode"""
if not head:
return None
slow, fast = (head, head)
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
... | the_stack_v2_python_sparse | 16. LINKED LIST/160_intersection_of_2_linked_lists/solution.py | kimmyoo/python_leetcode | train | 1 | |
c377090f48a4ed5ad7e380a62919aff933334352 | [
"self.dtype = dtype\nself.dim = dim\nself.units = units",
"if self.dtype is None:\n return False\nelif self.dtype == dtype:\n return False\nelse:\n return True",
"if self.dim is None:\n return False\nelif self.dim == dim:\n return False\nelse:\n return True",
"if self.units is None:\n ret... | <|body_start_0|>
self.dtype = dtype
self.dim = dim
self.units = units
<|end_body_0|>
<|body_start_1|>
if self.dtype is None:
return False
elif self.dtype == dtype:
return False
else:
return True
<|end_body_1|>
<|body_start_2|>
... | A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. units : str Expected units attribute of the variable. None for no expected uni... | Variable | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Variable:
"""A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. units : str Expected units attribute of th... | stack_v2_sparse_classes_36k_train_031867 | 40,072 | permissive | [
{
"docstring": "initalize the object.",
"name": "__init__",
"signature": "def __init__(self, dtype=None, dim=None, units=None)"
},
{
"docstring": "True if the provided dtype does not match the expected dtype.",
"name": "dtype_bad",
"signature": "def dtype_bad(self, dtype)"
},
{
"... | 4 | stack_v2_sparse_classes_30k_train_013974 | Implement the Python class `Variable` described below.
Class description:
A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. uni... | Implement the Python class `Variable` described below.
Class description:
A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. uni... | 172bbcf1cf3bcdb953c76ebae72c27c95dc2e606 | <|skeleton|>
class Variable:
"""A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. units : str Expected units attribute of th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Variable:
"""A class for holding and checking netCDF variables. Parameters ---------- dtype : type or None Expected dtype of the variable, None for no expected type. dim : tuple of str Expected dimensions of the variable, None for no expected dimensions. units : str Expected units attribute of the variable. N... | the_stack_v2_python_sparse | scripts/check_cfradial | ARM-DOE/pyart | train | 455 |
5ab9d65e6ca1b72b2a485763ee4a015f5db71c3f | [
"rospy.init_node('clop_generator_client_aka_clopper')\nself.client = actionlib.SimpleActionClient(topic, MoveBaseAction)\nself.client.wait_for_server()",
"msg.header.stamp = Time.now()\nself.client.send_goal(msg)\nprint('Wait for goal...')\nself.client.wait_for_result()\nprint('Result: ' + str(self.client.get_res... | <|body_start_0|>
rospy.init_node('clop_generator_client_aka_clopper')
self.client = actionlib.SimpleActionClient(topic, MoveBaseAction)
self.client.wait_for_server()
<|end_body_0|>
<|body_start_1|>
msg.header.stamp = Time.now()
self.client.send_goal(msg)
print('Wait for ... | sweetie_bot_clop_generator MoveBase aclionlib client. | Clopper | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Clopper:
"""sweetie_bot_clop_generator MoveBase aclionlib client."""
def __init__(self, topic):
"""Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib topic"""
<|body_0|>
def invokeClopGenerator(... | stack_v2_sparse_classes_36k_train_031868 | 6,478 | no_license | [
{
"docstring": "Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib topic",
"name": "__init__",
"signature": "def __init__(self, topic)"
},
{
"docstring": "Send MoveBaseGoal to gait generator and print result. Keyword ar... | 2 | null | Implement the Python class `Clopper` described below.
Class description:
sweetie_bot_clop_generator MoveBase aclionlib client.
Method signatures and docstrings:
- def __init__(self, topic): Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib ... | Implement the Python class `Clopper` described below.
Class description:
sweetie_bot_clop_generator MoveBase aclionlib client.
Method signatures and docstrings:
- def __init__(self, topic): Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib ... | f15f9cb01f2763d0b9d62624a400a01961609762 | <|skeleton|>
class Clopper:
"""sweetie_bot_clop_generator MoveBase aclionlib client."""
def __init__(self, topic):
"""Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib topic"""
<|body_0|>
def invokeClopGenerator(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Clopper:
"""sweetie_bot_clop_generator MoveBase aclionlib client."""
def __init__(self, topic):
"""Init ROS node and connect to sweetie_bot_clop_generator.msg.MoveBaseAction action server. Keyword arguments: topic -- actionlib topic"""
rospy.init_node('clop_generator_client_aka_clopper')
... | the_stack_v2_python_sparse | behavior/sweetie_bot_clop_generator/pysrc/sweetie_bot_clop_generator/clopper.py | sweetie-bot-project/sweetie_bot | train | 9 |
e9e36d86ba5386da6568bc453d6f7cf6dac307b0 | [
"if len(chs) < 2:\n return chs\narrs = list(chs)\ni = 0\nj = len(chs) - 1\nwhile i < j:\n if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():\n self.swap(arrs, i, j)\n i += 1\n j -= 1\n elif str(arrs[i]).isalpha():\n j -= 1\n elif str(arrs[j]).isalpha():\n i += 1\n ... | <|body_start_0|>
if len(chs) < 2:
return chs
arrs = list(chs)
i = 0
j = len(chs) - 1
while i < j:
if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():
self.swap(arrs, i, j)
i += 1
j -= 1
elif str... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
<|body_0|>
def swap(self, chs: List[str], i: int, j: int) -> None:
"""交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031869 | 2,439 | permissive | [
{
"docstring": "反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串",
"name": "reverse_only_letters",
"signature": "def reverse_only_letters(self, chs: str) -> str"
},
{
"docstring": "交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组",
"name": "swap",
"signature": "def swap(self, chs: List[str], i... | 2 | stack_v2_sparse_classes_30k_train_018772 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_only_letters(self, chs: str) -> str: 反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串
- def swap(self, chs: List[str], i: int, j: int) -> None: 交换数组位置 Args: chs: 数组 i: 位置i j: 位... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reverse_only_letters(self, chs: str) -> str: 反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串
- def swap(self, chs: List[str], i: int, j: int) -> None: 交换数组位置 Args: chs: 数组 i: 位置i j: 位... | 50f35eef6a0ad63173efed10df3c835b1dceaa3f | <|skeleton|>
class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
<|body_0|>
def swap(self, chs: List[str], i: int, j: int) -> None:
"""交换数组位置 Args: chs: 数组 i: 位置i j: 位置j Returns: 交换位置后的数组"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reverse_only_letters(self, chs: str) -> str:
"""反转字符串 Args: chs: 字符串数组 Returns: 反转后字符串"""
if len(chs) < 2:
return chs
arrs = list(chs)
i = 0
j = len(chs) - 1
while i < j:
if str(arrs[i]).isalpha() and str(arrs[j]).isalpha():... | the_stack_v2_python_sparse | src/leetcodepython/string/reverse_only_letters_917.py | zhangyu345293721/leetcode | train | 101 | |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"super(RBF, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)\nlogger.debug('Initializing %s kernel.' % self.name)\nassert np.size(variance) == 1\nassert np.size(lengthscale) == 1\nself.variance = np.float64(variance)\nself.lengthscale = np.float64(lengthscale)\nself.parameter_list = ['variance', 'l... | <|body_start_0|>
super(RBF, self).__init__(n_dims=n_dims, active_dims=active_dims, name=name)
logger.debug('Initializing %s kernel.' % self.name)
assert np.size(variance) == 1
assert np.size(lengthscale) == 1
self.variance = np.float64(variance)
self.lengthscale = np.floa... | squared exponential kernel with the same shape parameter in each dimension | RBF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RBF:
"""squared exponential kernel with the same shape parameter in each dimension"""
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: (very much the same as in GPy.kern.RBF) n_dims : number of dimensions va... | stack_v2_sparse_classes_36k_train_031870 | 9,047 | no_license | [
{
"docstring": "squared exponential kernel Inputs: (very much the same as in GPy.kern.RBF) n_dims : number of dimensions variance : kernel variance lengthscale : kernel lengthscale active_dims : all dims active by default, subset can be specified",
"name": "__init__",
"signature": "def __init__(self, n_... | 2 | stack_v2_sparse_classes_30k_train_007876 | Implement the Python class `RBF` described below.
Class description:
squared exponential kernel with the same shape parameter in each dimension
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: (very much the ... | Implement the Python class `RBF` described below.
Class description:
squared exponential kernel with the same shape parameter in each dimension
Method signatures and docstrings:
- def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None): squared exponential kernel Inputs: (very much the ... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class RBF:
"""squared exponential kernel with the same shape parameter in each dimension"""
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: (very much the same as in GPy.kern.RBF) n_dims : number of dimensions va... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RBF:
"""squared exponential kernel with the same shape parameter in each dimension"""
def __init__(self, n_dims, variance=1.0, lengthscale=1.0, active_dims=None, name=None):
"""squared exponential kernel Inputs: (very much the same as in GPy.kern.RBF) n_dims : number of dimensions variance : kern... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 |
44adf6b7c95b2729066649d9ead599fb3c4afeb3 | [
"self.iterator = iterator\nself._tag = False\nself._lastnum = 0",
"if not self._tag:\n self._tag = True\n self._lastnum = self.iterator.next()\nreturn self._lastnum",
"if not self._tag:\n self._lastnum = self.iterator.next()\nself._tag = False\nreturn self._lastnum",
"if not self._tag:\n return se... | <|body_start_0|>
self.iterator = iterator
self._tag = False
self._lastnum = 0
<|end_body_0|>
<|body_start_1|>
if not self._tag:
self._tag = True
self._lastnum = self.iterator.next()
return self._lastnum
<|end_body_1|>
<|body_start_2|>
if not self... | PeekingIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_36k_train_031871 | 1,759 | no_license | [
{
"docstring": "Initialize your data structure here. :type iterator: Iterator",
"name": "__init__",
"signature": "def __init__(self, iterator)"
},
{
"docstring": "Returns the next element in the iteration without advancing the iterator. :rtype: int",
"name": "peek",
"signature": "def pee... | 4 | stack_v2_sparse_classes_30k_train_013675 | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | Implement the Python class `PeekingIterator` described below.
Class description:
Implement the PeekingIterator class.
Method signatures and docstrings:
- def __init__(self, iterator): Initialize your data structure here. :type iterator: Iterator
- def peek(self): Returns the next element in the iteration without adva... | c55892c27abcd6f23a86a76e4c42351695470459 | <|skeleton|>
class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
<|body_0|>
def peek(self):
"""Returns the next element in the iteration without advancing the iterator. :rtype: int"""
<|body_1|>
def next(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PeekingIterator:
def __init__(self, iterator):
"""Initialize your data structure here. :type iterator: Iterator"""
self.iterator = iterator
self._tag = False
self._lastnum = 0
def peek(self):
"""Returns the next element in the iteration without advancing the iterat... | the_stack_v2_python_sparse | src/algorithms/python/Peeking_Iterator.py | brickgao/leetcode | train | 1 | |
bc8fd341094527f2720baf0db05139280f8ee4d6 | [
"extension = os.path.splitext(data_file)[-1]\nif extension == '.json':\n self.vocab_set = set(json.load(open(data_file, encoding='utf-8')))\nelif extension == '.csv':\n self.vocab_df = pd.read_csv(data_file).set_index('WORD')\n self.vocab_set = set(self.vocab_df.index)\nelse:\n print('XlitError: Only Js... | <|body_start_0|>
extension = os.path.splitext(data_file)[-1]
if extension == '.json':
self.vocab_set = set(json.load(open(data_file, encoding='utf-8')))
elif extension == '.csv':
self.vocab_df = pd.read_csv(data_file).set_index('WORD')
self.vocab_set = set(sel... | VocabSanitizer | [
"CC-BY-4.0",
"CC-BY-SA-3.0",
"CC-BY-SA-4.0",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VocabSanitizer:
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
<|body_0|>
def reposition(self, word_list):
"""Reorder Words in list"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
extension = os.path.splitext... | stack_v2_sparse_classes_36k_train_031872 | 30,029 | permissive | [
{
"docstring": "data_file: path to file conatining vocabulary list",
"name": "__init__",
"signature": "def __init__(self, data_file)"
},
{
"docstring": "Reorder Words in list",
"name": "reposition",
"signature": "def reposition(self, word_list)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007452 | Implement the Python class `VocabSanitizer` described below.
Class description:
Implement the VocabSanitizer class.
Method signatures and docstrings:
- def __init__(self, data_file): data_file: path to file conatining vocabulary list
- def reposition(self, word_list): Reorder Words in list | Implement the Python class `VocabSanitizer` described below.
Class description:
Implement the VocabSanitizer class.
Method signatures and docstrings:
- def __init__(self, data_file): data_file: path to file conatining vocabulary list
- def reposition(self, word_list): Reorder Words in list
<|skeleton|>
class VocabSa... | 0e0dd8139c75477346c985201b51315b3a4e4f48 | <|skeleton|>
class VocabSanitizer:
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
<|body_0|>
def reposition(self, word_list):
"""Reorder Words in list"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VocabSanitizer:
def __init__(self, data_file):
"""data_file: path to file conatining vocabulary list"""
extension = os.path.splitext(data_file)[-1]
if extension == '.json':
self.vocab_set = set(json.load(open(data_file, encoding='utf-8')))
elif extension == '.csv':
... | the_stack_v2_python_sparse | apps/ai4bharat/transliteration/xlit_src.py | JosephGeoBenjamin/IndianNLP-Transliteration | train | 2 | |
4a0521e733d7580ef3eba6519f3e26a369b68637 | [
"super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)\nself.sequence_length = sequence_length\nn_pixels = self.laps[0].size(0)\nn_features = self.encoder.enc_l0.spherical_cheb.chebconv.in_channels\nself.lstm_l0 = nn.LSTM(input_size=n_pixels * n_features, hidden_size=n_pixels * n_features, b... | <|body_start_0|>
super().__init__(pooling_class, N, depth, laplacian_type, kernel_size, ratio)
self.sequence_length = sequence_length
n_pixels = self.laps[0].size(0)
n_features = self.encoder.enc_l0.spherical_cheb.chebconv.in_channels
self.lstm_l0 = nn.LSTM(input_size=n_pixels * ... | Sphericall GCNN Autoencoder with LSTM. | SphericalUNetTemporalLSTM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SphericalUNetTemporalLSTM:
"""Sphericall GCNN Autoencoder with LSTM."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels ... | stack_v2_sparse_classes_36k_train_031873 | 41,403 | no_license | [
{
"docstring": "Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input image depth (int): The depth of the UNet, which is bounded by the N and the type of pooling sequence_length (int): The number of images used per sample kernel_size (int): che... | 2 | stack_v2_sparse_classes_30k_val_000806 | Implement the Python class `SphericalUNetTemporalLSTM` described below.
Class description:
Sphericall GCNN Autoencoder with LSTM.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initialization. Args: pooling_class (obj): One of th... | Implement the Python class `SphericalUNetTemporalLSTM` described below.
Class description:
Sphericall GCNN Autoencoder with LSTM.
Method signatures and docstrings:
- def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1): Initialization. Args: pooling_class (obj): One of th... | 7e55a422588c1d1e00f35a3d3a3ff896cce59e18 | <|skeleton|>
class SphericalUNetTemporalLSTM:
"""Sphericall GCNN Autoencoder with LSTM."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SphericalUNetTemporalLSTM:
"""Sphericall GCNN Autoencoder with LSTM."""
def __init__(self, pooling_class, N, depth, laplacian_type, sequence_length, kernel_size, ratio=1):
"""Initialization. Args: pooling_class (obj): One of three classes of pooling methods N (int): Number of pixels in the input ... | the_stack_v2_python_sparse | generated/test_deepsphere_deepsphere_pytorch.py | jansel/pytorch-jit-paritybench | train | 35 |
83435ec322fe9868ea19f6f0d2ee0ab93e2a9001 | [
"stack = []\nvals = []\nnode = root\nwhile stack or node:\n while node:\n stack.append(node)\n node = node.left\n node = stack.pop()\n vals.append(node.val)\n node = node.right\nvals.sort()\nnode = root\ni = 0\nwhile stack or node:\n while node:\n stack.append(node)\n node... | <|body_start_0|>
stack = []
vals = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
vals.append(node.val)
node = node.right
vals.sort()
no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree2(self, root: Optional[TreeNode]) -> None:
"""Do not return anything, modify root in-place instead."""
<|b... | stack_v2_sparse_classes_36k_train_031874 | 2,570 | no_license | [
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "recoverTree",
"signature": "def recoverTree(self, root: Optional[TreeNode]) -> None"
},
{
"docstring": "Do not return anything, modify root in-place instead.",
"name": "recoverTree2",
"signature": "def recov... | 3 | stack_v2_sparse_classes_30k_train_020497 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root: Optional[TreeNode]) -> None: Do not return anything, modify root in-place instead.
- def recoverTree2(self, root: Optional[TreeNode]) -> None: Do not ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def recoverTree(self, root: Optional[TreeNode]) -> None: Do not return anything, modify root in-place instead.
- def recoverTree2(self, root: Optional[TreeNode]) -> None: Do not ... | 7f8145f0c7ffdf18c557f01d221087b10443156e | <|skeleton|>
class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""Do not return anything, modify root in-place instead."""
<|body_0|>
def recoverTree2(self, root: Optional[TreeNode]) -> None:
"""Do not return anything, modify root in-place instead."""
<|b... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def recoverTree(self, root: Optional[TreeNode]) -> None:
"""Do not return anything, modify root in-place instead."""
stack = []
vals = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.le... | the_stack_v2_python_sparse | tree/099 Recover Binary Search Tree.py | mofei952/leetcode_python | train | 0 | |
b0f090d8d6bccfc8b9b3978fd70c35cbf27e1045 | [
"super().__init__(coordinator=coordinator)\nself._service_key = service_key\nself.entity_id = f'{SENSOR_DOMAIN}.{service_key}_{description.key}'\nself.entity_description = description\nself._attr_unique_id = f'{entry_id}_{service_key}_{description.key}'\nself._attr_device_info = {ATTR_IDENTIFIERS: {(DOMAIN, f'{entr... | <|body_start_0|>
super().__init__(coordinator=coordinator)
self._service_key = service_key
self.entity_id = f'{SENSOR_DOMAIN}.{service_key}_{description.key}'
self.entity_description = description
self._attr_unique_id = f'{entry_id}_{service_key}_{description.key}'
self._... | Defines an Ambee sensor. | AmbeeSensorEntity | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmbeeSensorEntity:
"""Defines an Ambee sensor."""
def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None:
"""Initialize Ambee sensor."""
<|body_0|>
def native_value(self) -> S... | stack_v2_sparse_classes_36k_train_031875 | 2,449 | permissive | [
{
"docstring": "Initialize Ambee sensor.",
"name": "__init__",
"signature": "def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None"
},
{
"docstring": "Return the state of the sensor.",
"name": "n... | 2 | null | Implement the Python class `AmbeeSensorEntity` described below.
Class description:
Defines an Ambee sensor.
Method signatures and docstrings:
- def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None: Initialize Ambee senso... | Implement the Python class `AmbeeSensorEntity` described below.
Class description:
Defines an Ambee sensor.
Method signatures and docstrings:
- def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None: Initialize Ambee senso... | 8de7966104911bca6f855a1755a6d71a07afb9de | <|skeleton|>
class AmbeeSensorEntity:
"""Defines an Ambee sensor."""
def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None:
"""Initialize Ambee sensor."""
<|body_0|>
def native_value(self) -> S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmbeeSensorEntity:
"""Defines an Ambee sensor."""
def __init__(self, *, coordinator: DataUpdateCoordinator, entry_id: str, description: SensorEntityDescription, service_key: str, service: str) -> None:
"""Initialize Ambee sensor."""
super().__init__(coordinator=coordinator)
self._... | the_stack_v2_python_sparse | homeassistant/components/ambee/sensor.py | AlexxIT/home-assistant | train | 9 |
a8676b5998bb1b608fafcde4ca8234d7245ad1cd | [
"super().__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"s_prev = tf.expand_dims(s_prev, 1)\ne = self.V(tf.nn.tanh(self.W(s_prev) + self.U(hidden_states)))\na = tf.nn.softmax(e, axis=1)\nc = a * hidden_states\nc = tf.reduce_sum(c, axis... | <|body_start_0|>
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
s_prev = tf.expand_dims(s_prev, 1)
e = self.V(tf.nn.tanh(self.W(s_prev) + self.U(hidden_state... | Self Attention class | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self Attention class"""
def __init__(self, units):
"""Class constructor"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Call Method"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super().__init__()
self.W = tf.... | stack_v2_sparse_classes_36k_train_031876 | 686 | no_license | [
{
"docstring": "Class constructor",
"name": "__init__",
"signature": "def __init__(self, units)"
},
{
"docstring": "Call Method",
"name": "call",
"signature": "def call(self, s_prev, hidden_states)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020068 | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention class
Method signatures and docstrings:
- def __init__(self, units): Class constructor
- def call(self, s_prev, hidden_states): Call Method | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention class
Method signatures and docstrings:
- def __init__(self, units): Class constructor
- def call(self, s_prev, hidden_states): Call Method
<|skeleton|>
class SelfAttention:
"""Self Attention class"""
def __init__(... | 131be8fcf61aafb5a4ddc0b3853ba625560eb786 | <|skeleton|>
class SelfAttention:
"""Self Attention class"""
def __init__(self, units):
"""Class constructor"""
<|body_0|>
def call(self, s_prev, hidden_states):
"""Call Method"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""Self Attention class"""
def __init__(self, units):
"""Class constructor"""
super().__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
def call(self, s_prev, hidden_states):... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | zahraaassaad/holbertonschool-machine_learning | train | 1 |
66fd1e94308a90fcc9030a979f26c054d3fe6061 | [
"super().__init__(**kwargs)\nself.label = label\nself.did = did\nself.recipient_keys = list(recipient_keys) if recipient_keys else None\nself.endpoint = endpoint\nself.routing_keys = list(routing_keys) if routing_keys else None\nself.image_url = image_url",
"c_json = self.to_json()\nc_i = bytes_to_b64(c_json.enco... | <|body_start_0|>
super().__init__(**kwargs)
self.label = label
self.did = did
self.recipient_keys = list(recipient_keys) if recipient_keys else None
self.endpoint = endpoint
self.routing_keys = list(routing_keys) if routing_keys else None
self.image_url = image_ur... | Class representing a connection invitation. | ConnectionInvitation | [
"LicenseRef-scancode-dco-1.1",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation ... | stack_v2_sparse_classes_36k_train_031877 | 5,648 | permissive | [
{
"docstring": "Initialize connection invitation object. Args: label: Optional label for connection invitation did: DID for this connection invitation recipient_keys: List of recipient keys endpoint: Endpoint which this agent can be reached at routing_keys: List of routing keys image_url: Optional image URL for... | 3 | stack_v2_sparse_classes_30k_val_000527 | Implement the Python class `ConnectionInvitation` described below.
Class description:
Class representing a connection invitation.
Method signatures and docstrings:
- def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur... | Implement the Python class `ConnectionInvitation` described below.
Class description:
Class representing a connection invitation.
Method signatures and docstrings:
- def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_ur... | 39cac36d8937ce84a9307ce100aaefb8bc05ec04 | <|skeleton|>
class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConnectionInvitation:
"""Class representing a connection invitation."""
def __init__(self, *, label: str=None, did: str=None, recipient_keys: Sequence[str]=None, endpoint: str=None, routing_keys: Sequence[str]=None, image_url: str=None, **kwargs):
"""Initialize connection invitation object. Args:... | the_stack_v2_python_sparse | aries_cloudagent/protocols/connections/v1_0/messages/connection_invitation.py | hyperledger/aries-cloudagent-python | train | 370 |
cf5c1fd6e2d2e9aef798b5b7a9a9c3a268927d3d | [
"add_wikis = self.browse(cr, uid, ids, context=context)\nfor add_wiki in add_wikis:\n selected_wikis = self.pool.get('wiki.wiki').search(cr, uid, [('tags', 'ilike', add_wiki.keyword)])\n self.write(cr, uid, ids, {'course_wiki_pages_wizard_ids': [(6, 0, selected_wikis)]}, context=context)\nreturn self.write(cr... | <|body_start_0|>
add_wikis = self.browse(cr, uid, ids, context=context)
for add_wiki in add_wikis:
selected_wikis = self.pool.get('wiki.wiki').search(cr, uid, [('tags', 'ilike', add_wiki.keyword)])
self.write(cr, uid, ids, {'course_wiki_pages_wizard_ids': [(6, 0, selected_wikis)]... | training_course_add_wiki_wizard | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class training_course_add_wiki_wizard:
def selectWikis(self, cr, uid, ids, data, context={}):
"""Add wiki doc to training course"""
<|body_0|>
def addWikis(self, cr, uid, ids, data, context={}):
"""Add wiki doc to training course"""
<|body_1|>
<|end_skeleton|>
<|... | stack_v2_sparse_classes_36k_train_031878 | 2,982 | no_license | [
{
"docstring": "Add wiki doc to training course",
"name": "selectWikis",
"signature": "def selectWikis(self, cr, uid, ids, data, context={})"
},
{
"docstring": "Add wiki doc to training course",
"name": "addWikis",
"signature": "def addWikis(self, cr, uid, ids, data, context={})"
}
] | 2 | null | Implement the Python class `training_course_add_wiki_wizard` described below.
Class description:
Implement the training_course_add_wiki_wizard class.
Method signatures and docstrings:
- def selectWikis(self, cr, uid, ids, data, context={}): Add wiki doc to training course
- def addWikis(self, cr, uid, ids, data, cont... | Implement the Python class `training_course_add_wiki_wizard` described below.
Class description:
Implement the training_course_add_wiki_wizard class.
Method signatures and docstrings:
- def selectWikis(self, cr, uid, ids, data, context={}): Add wiki doc to training course
- def addWikis(self, cr, uid, ids, data, cont... | 1081f3a5ff8864a31b2dcd89406fac076a908e78 | <|skeleton|>
class training_course_add_wiki_wizard:
def selectWikis(self, cr, uid, ids, data, context={}):
"""Add wiki doc to training course"""
<|body_0|>
def addWikis(self, cr, uid, ids, data, context={}):
"""Add wiki doc to training course"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class training_course_add_wiki_wizard:
def selectWikis(self, cr, uid, ids, data, context={}):
"""Add wiki doc to training course"""
add_wikis = self.browse(cr, uid, ids, context=context)
for add_wiki in add_wikis:
selected_wikis = self.pool.get('wiki.wiki').search(cr, uid, [('tag... | the_stack_v2_python_sparse | extra-addons/training_doc/wizard/training_doc_wizard.py | sgeerish/sirr_production | train | 0 | |
f9704242a4cf79534323fa8c824f8e11e5ec28b3 | [
"len_a = len(arr)\nif len_a <= 1:\n return len_a\ndp = [[1, 1] for i in range(len_a)]\nres = 1\nfor i in range(1, len_a):\n if arr[i] < arr[i - 1]:\n dp[i][0] = dp[i - 1][1] + 1\n res = max(res, dp[i][0])\n elif arr[i - 1] < arr[i]:\n dp[i][1] = dp[i - 1][0] + 1\n res = max(res,... | <|body_start_0|>
len_a = len(arr)
if len_a <= 1:
return len_a
dp = [[1, 1] for i in range(len_a)]
res = 1
for i in range(1, len_a):
if arr[i] < arr[i - 1]:
dp[i][0] = dp[i - 1][1] + 1
res = max(res, dp[i][0])
eli... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
<|body_0|>
def maxTurbulenceSize1(self, arr: List[int]) -> int:
"""执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用... | stack_v2_sparse_classes_36k_train_031879 | 2,439 | no_license | [
{
"docstring": "执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户",
"name": "maxTurbulenceSize",
"signature": "def maxTurbulenceSize(self, arr: List[int]) -> int"
},
{
"docstring": "执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用户 内存消耗: 18 MB , 在所有 Python3 提交中击... | 2 | stack_v2_sparse_classes_30k_train_017062 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr: List[int]) -> int: 执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户
- def maxTurbulenceSize1(self, arr: L... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxTurbulenceSize(self, arr: List[int]) -> int: 执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户
- def maxTurbulenceSize1(self, arr: L... | d613ed8a5a2c15ace7d513965b372d128845d66a | <|skeleton|>
class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
<|body_0|>
def maxTurbulenceSize1(self, arr: List[int]) -> int:
"""执行用时: 140 ms , 在所有 Python3 提交中击败了 84.72% 的用... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def maxTurbulenceSize(self, arr: List[int]) -> int:
"""执行用时: 312 ms , 在所有 Python3 提交中击败了 5.02% 的用户 内存消耗: 19.6 MB , 在所有 Python3 提交中击败了 8.85% 的用户"""
len_a = len(arr)
if len_a <= 1:
return len_a
dp = [[1, 1] for i in range(len_a)]
res = 1
for ... | the_stack_v2_python_sparse | 最长湍流子数组.py | nomboy/leetcode | train | 0 | |
0d3f930d073c1590558a69d556e3016cff47fc7a | [
"self.k = k\nself.nm_samples = len(trainset)\nself.indices = list(range(self.nm_samples))\nself.trainset = trainset\nself.batch_size = batch_size\nself.use_gpu = use_gpu",
"for i in range(self.k):\n train_idx = [idx for j, idx in enumerate(self.indices) if j % self.k != i]\n valid_idx = [idx for j, idx in e... | <|body_start_0|>
self.k = k
self.nm_samples = len(trainset)
self.indices = list(range(self.nm_samples))
self.trainset = trainset
self.batch_size = batch_size
self.use_gpu = use_gpu
<|end_body_0|>
<|body_start_1|>
for i in range(self.k):
train_idx = [i... | CrossValidation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
<|body_0|>
def kfold(self):
"""k-fold split"""
... | stack_v2_sparse_classes_36k_train_031880 | 4,783 | no_license | [
{
"docstring": "k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus",
"name": "__init__",
"signature": "def __init__(self, k, batch_size, trainset, use_gpu)"
},
{
"docstring": "k-fold split",
"name": "kfold"... | 4 | null | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, k, batch_size, trainset, use_gpu): k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: bo... | Implement the Python class `CrossValidation` described below.
Class description:
Implement the CrossValidation class.
Method signatures and docstrings:
- def __init__(self, k, batch_size, trainset, use_gpu): k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: bo... | 0d2e07ad43790b39aa038272ec42accedda89683 | <|skeleton|>
class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
<|body_0|>
def kfold(self):
"""k-fold split"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CrossValidation:
def __init__(self, k, batch_size, trainset, use_gpu):
"""k: number of folds batch_size: batch size for training trainset: training data as pytorch iterator use_gpu: boolean variable to use gpus"""
self.k = k
self.nm_samples = len(trainset)
self.indices = list(r... | the_stack_v2_python_sparse | Session2/kfold.py | MdAsifKhan/cudavision | train | 1 | |
b6d751bee3e871bce59453d32b8c4bb19b1aa645 | [
"self.parser = reqparse.RequestParser()\nself.parser.add_argument('token')\nsuper(Log, self).__init__()",
"args = self.parser.parse_args()\ntoken = args['token']\ndata = me.getLog()\nl = [o.__dict__ for o in data]\nreturn {'result_code': 'success', 'data': l}"
] | <|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(Log, self).__init__()
<|end_body_0|>
<|body_start_1|>
args = self.parser.parse_args()
token = args['token']
data = me.getLog()
l = [o.__dict__ for o in data]
r... | 日志 | Log | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Log:
"""日志"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""查询"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(Log, self).__init__()
<|en... | stack_v2_sparse_classes_36k_train_031881 | 24,002 | permissive | [
{
"docstring": "初始化",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "查询",
"name": "get",
"signature": "def get(self)"
}
] | 2 | stack_v2_sparse_classes_30k_test_001023 | Implement the Python class `Log` described below.
Class description:
日志
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 查询 | Implement the Python class `Log` described below.
Class description:
日志
Method signatures and docstrings:
- def __init__(self): 初始化
- def get(self): 查询
<|skeleton|>
class Log:
"""日志"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""查询"""
<|body_1|>
<|end_ske... | c316649161086da2543d39bf0455d0f793cdd08f | <|skeleton|>
class Log:
"""日志"""
def __init__(self):
"""初始化"""
<|body_0|>
def get(self):
"""查询"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Log:
"""日志"""
def __init__(self):
"""初始化"""
self.parser = reqparse.RequestParser()
self.parser.add_argument('token')
super(Log, self).__init__()
def get(self):
"""查询"""
args = self.parser.parse_args()
token = args['token']
data = me.get... | the_stack_v2_python_sparse | WebTrader/webServer.py | webclinic017/riskBacktestingPlatform | train | 0 |
8499be1a694470e4a3fa762f3bf11f1f89ac8d32 | [
"self.board = None\nself.game_over = False\nself.winner = None\nself.x_player = None\nself.o_player = None\nself.moves_remaining = 9",
"self.board = Board()\nself.select_players()\nwhile not self.game_over:\n self.play_round()\nself.board.print_board()\nself.declare_winner()",
"self.x_player = Console('X', i... | <|body_start_0|>
self.board = None
self.game_over = False
self.winner = None
self.x_player = None
self.o_player = None
self.moves_remaining = 9
<|end_body_0|>
<|body_start_1|>
self.board = Board()
self.select_players()
while not self.game_over:
... | Game | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Game:
def __init__(self):
"""game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game"""
<|body_0|>
def play(self):
"""initializes a Board plays the game"""
<|body_1|>
def select_players(self):
... | stack_v2_sparse_classes_36k_train_031882 | 6,641 | no_license | [
{
"docstring": "game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "initializes a Board plays the game",
"name": "play",
"signature": "def play(self)"
... | 6 | stack_v2_sparse_classes_30k_train_002876 | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self): game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game
- def play(self): initializes a Board plays the game... | Implement the Python class `Game` described below.
Class description:
Implement the Game class.
Method signatures and docstrings:
- def __init__(self): game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game
- def play(self): initializes a Board plays the game... | 79b17bac6da98826a9eeba176472412ee98d15a3 | <|skeleton|>
class Game:
def __init__(self):
"""game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game"""
<|body_0|>
def play(self):
"""initializes a Board plays the game"""
<|body_1|>
def select_players(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Game:
def __init__(self):
"""game has two players, x & o, and a board may or may not have a winner need to keep track of the state of the game"""
self.board = None
self.game_over = False
self.winner = None
self.x_player = None
self.o_player = None
self.m... | the_stack_v2_python_sparse | software_design/misc/TicTacToe.py | AlyssaYelle/python_practice | train | 2 | |
f5428f29ec127bbb92eccb4e5c65ea1e4deba769 | [
"Attachment = self.env['ir.attachment']\ninputs = Attachment.browse()\nif path.path not in conn:\n return\nnot_consumed = []\nfor _r, fs in batched(conn[path.path], self._BATCH_SIZE):\n attachment_data = []\n for f in fs:\n if not fnmatch.fnmatch(f['name'], path.glob):\n not_consumed.appe... | <|body_start_0|>
Attachment = self.env['ir.attachment']
inputs = Attachment.browse()
if path.path not in conn:
return
not_consumed = []
for _r, fs in batched(conn[path.path], self._BATCH_SIZE):
attachment_data = []
for f in fs:
... | EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface. | EdiConnectionXMLRPC | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EdiConnectionXMLRPC:
"""EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface."""
def receive_inputs(self, conn, path, _transfer):
"""Receive input attachments"""
<|body_0|>
def send_outputs(self, conn, path, transf... | stack_v2_sparse_classes_36k_train_031883 | 2,798 | no_license | [
{
"docstring": "Receive input attachments",
"name": "receive_inputs",
"signature": "def receive_inputs(self, conn, path, _transfer)"
},
{
"docstring": "Send output attachments",
"name": "send_outputs",
"signature": "def send_outputs(self, conn, path, transfer)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004497 | Implement the Python class `EdiConnectionXMLRPC` described below.
Class description:
EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface.
Method signatures and docstrings:
- def receive_inputs(self, conn, path, _transfer): Receive input attachments
- def send_... | Implement the Python class `EdiConnectionXMLRPC` described below.
Class description:
EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface.
Method signatures and docstrings:
- def receive_inputs(self, conn, path, _transfer): Receive input attachments
- def send_... | d6d55fbf8abecb0b8201384921833868ae849920 | <|skeleton|>
class EdiConnectionXMLRPC:
"""EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface."""
def receive_inputs(self, conn, path, _transfer):
"""Receive input attachments"""
<|body_0|>
def send_outputs(self, conn, path, transf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EdiConnectionXMLRPC:
"""EDI XML-RPC connection An EDI XML-RPC connection is initiated by external code via the Odoo XML-RPC interface."""
def receive_inputs(self, conn, path, _transfer):
"""Receive input attachments"""
Attachment = self.env['ir.attachment']
inputs = Attachment.bro... | the_stack_v2_python_sparse | addons/edi/models/edi_connection_xmlrpc.py | unipartdigital/odoo-edi | train | 9 |
7518ec57cee1db9011db43c2edee61b1aaee2e03 | [
"if settings.EMAIL_HOST:\n try:\n result = super().send_mail(template_prefix, email, context)\n except Exception:\n log_error('account email')\n result = False\n return result\nreturn False",
"from InvenTree.helpers_model import construct_absolute_url\nurl = super().get_email_confirm... | <|body_start_0|>
if settings.EMAIL_HOST:
try:
result = super().send_mail(template_prefix, email, context)
except Exception:
log_error('account email')
result = False
return result
return False
<|end_body_0|>
<|body_star... | Override of adapter to use dynamic settings. | CustomAccountAdapter | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomAccountAdapter:
"""Override of adapter to use dynamic settings."""
def send_mail(self, template_prefix, email, context):
"""Only send mail if backend configured."""
<|body_0|>
def get_email_confirmation_url(self, request, emailconfirmation):
"""Construct th... | stack_v2_sparse_classes_36k_train_031884 | 12,546 | permissive | [
{
"docstring": "Only send mail if backend configured.",
"name": "send_mail",
"signature": "def send_mail(self, template_prefix, email, context)"
},
{
"docstring": "Construct the email confirmation url",
"name": "get_email_confirmation_url",
"signature": "def get_email_confirmation_url(se... | 2 | stack_v2_sparse_classes_30k_train_021526 | Implement the Python class `CustomAccountAdapter` described below.
Class description:
Override of adapter to use dynamic settings.
Method signatures and docstrings:
- def send_mail(self, template_prefix, email, context): Only send mail if backend configured.
- def get_email_confirmation_url(self, request, emailconfir... | Implement the Python class `CustomAccountAdapter` described below.
Class description:
Override of adapter to use dynamic settings.
Method signatures and docstrings:
- def send_mail(self, template_prefix, email, context): Only send mail if backend configured.
- def get_email_confirmation_url(self, request, emailconfir... | e88a8e99a5f0b201c67a95cba097c729f090d5e2 | <|skeleton|>
class CustomAccountAdapter:
"""Override of adapter to use dynamic settings."""
def send_mail(self, template_prefix, email, context):
"""Only send mail if backend configured."""
<|body_0|>
def get_email_confirmation_url(self, request, emailconfirmation):
"""Construct th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomAccountAdapter:
"""Override of adapter to use dynamic settings."""
def send_mail(self, template_prefix, email, context):
"""Only send mail if backend configured."""
if settings.EMAIL_HOST:
try:
result = super().send_mail(template_prefix, email, context)
... | the_stack_v2_python_sparse | InvenTree/InvenTree/forms.py | inventree/InvenTree | train | 3,077 |
385ef34a2f14e971caa2756b9ef50679dd9034b2 | [
"length = len(nums)\nans = []\ni = 0\nwhile i < length:\n j = i\n res = str(nums[i])\n while i + 1 < length and nums[i + 1] - nums[i] == 1:\n i += 1\n if i > j:\n res += '->' + str(nums[i])\n ans.append(res)\n i += 1\nreturn ans",
"tmp = []\nfor i in nums:\n if not tmp:\n ... | <|body_start_0|>
length = len(nums)
ans = []
i = 0
while i < length:
j = i
res = str(nums[i])
while i + 1 < length and nums[i + 1] - nums[i] == 1:
i += 1
if i > j:
res += '->' + str(nums[i])
ans.a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def summaryRanges(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def summaryRanges_O_n(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
length = len(nums)
... | stack_v2_sparse_classes_36k_train_031885 | 1,973 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "summaryRanges",
"signature": "def summaryRanges(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: List[str]",
"name": "summaryRanges_O_n",
"signature": "def summaryRanges_O_n(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012872 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def summaryRanges(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_O_n(self, nums): :type nums: List[int] :rtype: List[str] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def summaryRanges(self, nums): :type nums: List[int] :rtype: List[str]
- def summaryRanges_O_n(self, nums): :type nums: List[int] :rtype: List[str]
<|skeleton|>
class Solution:
... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def summaryRanges(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_0|>
def summaryRanges_O_n(self, nums):
""":type nums: List[int] :rtype: List[str]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def summaryRanges(self, nums):
""":type nums: List[int] :rtype: List[str]"""
length = len(nums)
ans = []
i = 0
while i < length:
j = i
res = str(nums[i])
while i + 1 < length and nums[i + 1] - nums[i] == 1:
i... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00228.Summary Ranges.py | roger6blog/LeetCode | train | 0 | |
916bce609f4149b34e1f62d412adb7e3769776af | [
"match = COURSE_REGEX.match(request.build_absolute_uri())\ncourse_id = None\nif match:\n course_id = match.group('course_id')\n try:\n course_key = CourseKey.from_string(course_id)\n except InvalidKeyError:\n course_id = None\n course_key = None\ncontext = {}\nif course_id:\n contex... | <|body_start_0|>
match = COURSE_REGEX.match(request.build_absolute_uri())
course_id = None
if match:
course_id = match.group('course_id')
try:
course_key = CourseKey.from_string(course_id)
except InvalidKeyError:
course_id = Non... | Middleware that adds a user's tags to tracking event context. | UserTagsEventContextMiddleware | [
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTagsEventContextMiddleware:
"""Middleware that adds a user's tags to tracking event context."""
def process_request(self, request):
"""Add a user's tags to the tracking event context."""
<|body_0|>
def process_response(self, request, response):
"""Exit the co... | stack_v2_sparse_classes_36k_train_031886 | 1,845 | permissive | [
{
"docstring": "Add a user's tags to the tracking event context.",
"name": "process_request",
"signature": "def process_request(self, request)"
},
{
"docstring": "Exit the context if it exists.",
"name": "process_response",
"signature": "def process_response(self, request, response)"
}... | 2 | null | Implement the Python class `UserTagsEventContextMiddleware` described below.
Class description:
Middleware that adds a user's tags to tracking event context.
Method signatures and docstrings:
- def process_request(self, request): Add a user's tags to the tracking event context.
- def process_response(self, request, r... | Implement the Python class `UserTagsEventContextMiddleware` described below.
Class description:
Middleware that adds a user's tags to tracking event context.
Method signatures and docstrings:
- def process_request(self, request): Add a user's tags to the tracking event context.
- def process_response(self, request, r... | 5809eaca7079a15ee56b0b7fcfea425337046c97 | <|skeleton|>
class UserTagsEventContextMiddleware:
"""Middleware that adds a user's tags to tracking event context."""
def process_request(self, request):
"""Add a user's tags to the tracking event context."""
<|body_0|>
def process_response(self, request, response):
"""Exit the co... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserTagsEventContextMiddleware:
"""Middleware that adds a user's tags to tracking event context."""
def process_request(self, request):
"""Add a user's tags to the tracking event context."""
match = COURSE_REGEX.match(request.build_absolute_uri())
course_id = None
if match... | the_stack_v2_python_sparse | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/user_api/middleware.py | luque/better-ways-of-thinking-about-software | train | 3 |
554b788837ee12faadfb83dbfd911477862c8604 | [
"super().__init__()\ntext = text or PADDING_TEXT\nself.text_tokens = text.split()\nif special_end_token is not None:\n self.text_tokens.append(special_end_token)\nself.text_len = len(self.text_tokens)",
"transformed_sentences = []\ntransformed_target_ids = []\nfor sentence, target_id in zip(sentences, target_i... | <|body_start_0|>
super().__init__()
text = text or PADDING_TEXT
self.text_tokens = text.split()
if special_end_token is not None:
self.text_tokens.append(special_end_token)
self.text_len = len(self.text_tokens)
<|end_body_0|>
<|body_start_1|>
transformed_sent... | PadTextPreprocessor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PadTextPreprocessor:
def __init__(self, text: Optional[str]=None, special_end_token: Optional[str]=None):
"""Preprocessor that pads original sentence with some pre-defined text. Args: text: text that would be padded to the original sentence. special_end_token: this token would be added r... | stack_v2_sparse_classes_36k_train_031887 | 9,230 | permissive | [
{
"docstring": "Preprocessor that pads original sentence with some pre-defined text. Args: text: text that would be padded to the original sentence. special_end_token: this token would be added right at the end of a tokenized text, e.g. <eod> for XLNet.",
"name": "__init__",
"signature": "def __init__(s... | 2 | stack_v2_sparse_classes_30k_train_011199 | Implement the Python class `PadTextPreprocessor` described below.
Class description:
Implement the PadTextPreprocessor class.
Method signatures and docstrings:
- def __init__(self, text: Optional[str]=None, special_end_token: Optional[str]=None): Preprocessor that pads original sentence with some pre-defined text. Ar... | Implement the Python class `PadTextPreprocessor` described below.
Class description:
Implement the PadTextPreprocessor class.
Method signatures and docstrings:
- def __init__(self, text: Optional[str]=None, special_end_token: Optional[str]=None): Preprocessor that pads original sentence with some pre-defined text. Ar... | c87f67e5fe51fc8307b5d5ff8f404f202f17ab5e | <|skeleton|>
class PadTextPreprocessor:
def __init__(self, text: Optional[str]=None, special_end_token: Optional[str]=None):
"""Preprocessor that pads original sentence with some pre-defined text. Args: text: text that would be padded to the original sentence. special_end_token: this token would be added r... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PadTextPreprocessor:
def __init__(self, text: Optional[str]=None, special_end_token: Optional[str]=None):
"""Preprocessor that pads original sentence with some pre-defined text. Args: text: text that would be padded to the original sentence. special_end_token: this token would be added right at the en... | the_stack_v2_python_sparse | lexsubgen/pre_processors/base_preprocessors.py | agoel00/LexSubGen | train | 0 | |
b39c2636ecc0a419bab3a42117f8392ed86c90ea | [
"if not isinstance(q, np.ndarray):\n q = np.array(q)\nif q[0] != 0.0 or q[-1] != 1.0:\n raise RuntimeError('Invalid quantiles boundaries [' + ','.join([str(q[i]) for i in range(q.shape[0])]) + ']')\nif np.any(q[:-1] > q[1:]):\n raise RuntimeError('Quantile edges not increasing [' + ','.join([str(q[i]) for ... | <|body_start_0|>
if not isinstance(q, np.ndarray):
q = np.array(q)
if q[0] != 0.0 or q[-1] != 1.0:
raise RuntimeError('Invalid quantiles boundaries [' + ','.join([str(q[i]) for i in range(q.shape[0])]) + ']')
if np.any(q[:-1] > q[1:]):
raise RuntimeError('Quan... | Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized | Quantile | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
<|body_0|>
def rebin_method(x, ... | stack_v2_sparse_classes_36k_train_031888 | 35,100 | no_license | [
{
"docstring": "h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]",
"name": "__init__",
"signature": "def __init__(self, h, q)"
},
{
"docstring": "x: bin centers w: bin heights (bin content) q: quantiles",
"name": "rebin_method",
"signature": "def rebin_method(x, w, q)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004971 | Implement the Python class `Quantile` described below.
Class description:
Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized
Method signatures and docstrings:
- def __init__(self, h, q): h : either TH1 or list of TH1 q : quantiles list [0... | Implement the Python class `Quantile` described below.
Class description:
Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized
Method signatures and docstrings:
- def __init__(self, h, q): h : either TH1 or list of TH1 q : quantiles list [0... | 30df434202df51017309b5bf88a1d9b94041b6ef | <|skeleton|>
class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
<|body_0|>
def rebin_method(x, ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Quantile:
"""Applies quantile binning -> provide quantile boundaries and bin histogram accordingly list of quantile values need to be optimized"""
def __init__(self, h, q):
"""h : either TH1 or list of TH1 q : quantiles list [0 , ... 1]"""
if not isinstance(q, np.ndarray):
q =... | the_stack_v2_python_sparse | ZAStatAnalysis/Rebinning.py | kjaffel/ZA_FullAnalysis | train | 11 |
5925875f72848916fcb282858aae0bdf3e1ab559 | [
"bitmask = 0\nfor e in value:\n bitmask = bitmask | e.value\nreturn bitmask",
"masks = list()\nif value:\n for e in enums.CryptographicUsageMask:\n if e.value & value:\n masks.append(e)\nreturn masks"
] | <|body_start_0|>
bitmask = 0
for e in value:
bitmask = bitmask | e.value
return bitmask
<|end_body_0|>
<|body_start_1|>
masks = list()
if value:
for e in enums.CryptographicUsageMask:
if e.value & value:
masks.append(e)... | Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.CryptographicUsageMask Enums. | UsageMaskType | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UsageMaskType:
"""Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.CryptographicUsageMask Enums."""
def pr... | stack_v2_sparse_classes_36k_train_031889 | 5,593 | permissive | [
{
"docstring": "Returns the integer value of the usage mask bitmask. This value is stored in the database. Args: value(list<enums.CryptographicUsageMask>): list of enums in the usage mask dialect(string): SQL dialect",
"name": "process_bind_param",
"signature": "def process_bind_param(self, value, diale... | 2 | stack_v2_sparse_classes_30k_train_007391 | Implement the Python class `UsageMaskType` described below.
Class description:
Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.Crypt... | Implement the Python class `UsageMaskType` described below.
Class description:
Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.Crypt... | f0a44b26ce902d8b9c330634d5b3603959edf1d4 | <|skeleton|>
class UsageMaskType:
"""Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.CryptographicUsageMask Enums."""
def pr... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UsageMaskType:
"""Converts a list of enums.CryptographicUsageMask Enums in an integer bitmask. This allows the database to only store an integer instead of a list of enumbs. This also does the reverse of converting an integer bit mask into a list enums.CryptographicUsageMask Enums."""
def process_bind_pa... | the_stack_v2_python_sparse | kmip/pie/sqltypes.py | OpenKMIP/PyKMIP | train | 232 |
197218acd377297b9572b9c6ee16525240f327c6 | [
"if target < candidates[0]:\n return set()\nif target == candidates[0]:\n return {(target,)}\ns = set()\nr1 = self.combinationSum(candidates[1:], target)\ns.update(r1)\nr2 = {(candidates[0],) + e for e in self.combinationSum(candidates, target - candidates[0])}\ns.update(r2)\nreturn s",
"if candidates == []... | <|body_start_0|>
if target < candidates[0]:
return set()
if target == candidates[0]:
return {(target,)}
s = set()
r1 = self.combinationSum(candidates[1:], target)
s.update(r1)
r2 = {(candidates[0],) + e for e in self.combinationSum(candidates, targ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
<|body_0|>
def combinationSum(self, candidates, target):
... | stack_v2_sparse_classes_36k_train_031890 | 1,708 | no_license | [
{
"docstring": ":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])",
"name": "combinationSumSorted",
"signature": "def combinationSumSorted(self, candidates, target)"
},
{
"docstring": ":type candid... | 2 | stack_v2_sparse_classes_30k_train_009181 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSumSorted(self, candidates, target): :type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSumSorted(self, candidates, target): :type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) ... | d2e8b2dca40fc955045eb62e576c776bad8ee5f1 | <|skeleton|>
class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
<|body_0|>
def combinationSum(self, candidates, target):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSumSorted(self, candidates, target):
""":type candidates: List[int] :type target: int :rtype: Set(List[int]) >>> s = Solution() >>> s.combinationSum([2, 3, 6, 7], 7) set([(7,), (2, 2, 3)])"""
if target < candidates[0]:
return set()
if target == cand... | the_stack_v2_python_sparse | combination-sum/combination-sum.py | childe/leetcode | train | 2 | |
3c7bdc850057c41c974cdbde9b7520b4d45d43d1 | [
"if k <= 1:\n return 0\ncount, prod, start = (0, 1, 0)\nfor i, n in enumerate(nums):\n prod *= n\n while prod >= k:\n prod //= nums[start]\n start += 1\n count += i - start + 1\nreturn count",
"count = 0\nfor i, n in enumerate(nums):\n if n < k:\n count += 1\n for j in range... | <|body_start_0|>
if k <= 1:
return 0
count, prod, start = (0, 1, 0)
for i, n in enumerate(nums):
prod *= n
while prod >= k:
prod //= nums[start]
start += 1
count += i - start + 1
return count
<|end_body_0|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK_naive(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_031891 | 1,995 | no_license | [
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK",
"signature": "def numSubarrayProductLessThanK(self, nums, k)"
},
{
"docstring": ":type nums: List[int] :type k: int :rtype: int",
"name": "numSubarrayProductLessThanK_naive",
"signatur... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK_naive(self, nums, k): :type nums: List[int] :type... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def numSubarrayProductLessThanK(self, nums, k): :type nums: List[int] :type k: int :rtype: int
- def numSubarrayProductLessThanK_naive(self, nums, k): :type nums: List[int] :type... | e60ba45fe2f2e5e3b3abfecec3db76f5ce1fde59 | <|skeleton|>
class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_0|>
def numSubarrayProductLessThanK_naive(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def numSubarrayProductLessThanK(self, nums, k):
""":type nums: List[int] :type k: int :rtype: int"""
if k <= 1:
return 0
count, prod, start = (0, 1, 0)
for i, n in enumerate(nums):
prod *= n
while prod >= k:
prod //=... | the_stack_v2_python_sparse | src/lt_713.py | oxhead/CodingYourWay | train | 0 | |
afab072d028e633909d53df385b6a919bc4d9495 | [
"if not email:\n raise ValueError('Users must have an email address')\nuser = self.model(email=self.normalize_email(email), name=name)\nuser.set_password(password)\nuser.save(using=self._db)\nreturn user",
"user = self.create_user(email, password=password, name=name)\nuser.is_admin = True\nuser.save(using=self... | <|body_start_0|>
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), name=name)
user.set_password(password)
user.save(using=self._db)
return user
<|end_body_0|>
<|body_start_1|>
user = self.c... | UserProfileManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k_train_031892 | 16,515 | no_license | [
{
"docstring": "Creates and saves a User with the given email, date of birth and password.",
"name": "create_user",
"signature": "def create_user(self, email, name, password=None)"
},
{
"docstring": "Creates and saves a superuser with the given email, date of birth and password.",
"name": "c... | 2 | null | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | Implement the Python class `UserProfileManager` described below.
Class description:
Implement the UserProfileManager class.
Method signatures and docstrings:
- def create_user(self, email, name, password=None): Creates and saves a User with the given email, date of birth and password.
- def create_superuser(self, ema... | 4d497a6261de17cc2fc058cea50e127e885e5095 | <|skeleton|>
class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
<|body_0|>
def create_superuser(self, email, name, password):
"""Creates and saves a superuser with the given email... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserProfileManager:
def create_user(self, email, name, password=None):
"""Creates and saves a User with the given email, date of birth and password."""
if not email:
raise ValueError('Users must have an email address')
user = self.model(email=self.normalize_email(email), na... | the_stack_v2_python_sparse | Project2_PerfectCRM/PerfectCRM/crm/models.py | phully/PythonHomeWork | train | 0 | |
aad84e06b525fb85da65bf0f0062826fee0fb34f | [
"super().__init__()\nself.config = deepcopy(base_config)\nself.config.update(args)\nself.model = model\nself.dist_fam = dist_fam\nself.device = torch.device('cpu')\nif self.config['device'] != 'cpu':\n self.device = torch.cuda.current_device()\nfeatures, classifier = self.config['features_and_classifier'](model)... | <|body_start_0|>
super().__init__()
self.config = deepcopy(base_config)
self.config.update(args)
self.model = model
self.dist_fam = dist_fam
self.device = torch.device('cpu')
if self.config['device'] != 'cpu':
self.device = torch.cuda.current_device()
... | Wraps a trained model with functionality for adding epistemic uncertainty estimation. | Mahalanobis | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mahalanobis:
"""Wraps a trained model with functionality for adding epistemic uncertainty estimation."""
def __init__(self, model, dist_fam, args={}):
"""model: base DNN to equip with an uncertainty metric dist_fam: distributions.DistFam object representing how to interpret output of... | stack_v2_sparse_classes_36k_train_031893 | 4,234 | permissive | [
{
"docstring": "model: base DNN to equip with an uncertainty metric dist_fam: distributions.DistFam object representing how to interpret output of model args: configuration variables - defaults are in base_config",
"name": "__init__",
"signature": "def __init__(self, model, dist_fam, args={})"
},
{
... | 3 | null | Implement the Python class `Mahalanobis` described below.
Class description:
Wraps a trained model with functionality for adding epistemic uncertainty estimation.
Method signatures and docstrings:
- def __init__(self, model, dist_fam, args={}): model: base DNN to equip with an uncertainty metric dist_fam: distributio... | Implement the Python class `Mahalanobis` described below.
Class description:
Wraps a trained model with functionality for adding epistemic uncertainty estimation.
Method signatures and docstrings:
- def __init__(self, model, dist_fam, args={}): model: base DNN to equip with an uncertainty metric dist_fam: distributio... | 6a569734d3e246e25c53c0dff97e4e83690087d4 | <|skeleton|>
class Mahalanobis:
"""Wraps a trained model with functionality for adding epistemic uncertainty estimation."""
def __init__(self, model, dist_fam, args={}):
"""model: base DNN to equip with an uncertainty metric dist_fam: distributions.DistFam object representing how to interpret output of... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mahalanobis:
"""Wraps a trained model with functionality for adding epistemic uncertainty estimation."""
def __init__(self, model, dist_fam, args={}):
"""model: base DNN to equip with an uncertainty metric dist_fam: distributions.DistFam object representing how to interpret output of model args: ... | the_stack_v2_python_sparse | nn_ood/posteriors/maha.py | StanfordASL/SCOD | train | 17 |
4292920a43e7f1b3d1e24ad3671b7d819c7b143e | [
"while left <= right:\n mid = (left + right) // 2\n if target_set[mid] == value:\n return mid\n elif target_set[mid] > value:\n right = mid - 1\n else:\n left = mid + 1",
"dict_s = {}\ndict_t = {}\nfor ch in s:\n dict_s[ch] = dict_s.get(ch, 0) + 1\nfor ch in t:\n dict_t[ch] ... | <|body_start_0|>
while left <= right:
mid = (left + right) // 2
if target_set[mid] == value:
return mid
elif target_set[mid] > value:
right = mid - 1
else:
left = mid + 1
<|end_body_0|>
<|body_start_1|>
dict... | 查找相关的算法题 | SearchExercise | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SearchExercise:
"""查找相关的算法题"""
def binary_search(target_set, left, right, value):
"""二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引"""
<|body_0|>
def exercise_demo01(s, t):
"""给两个字符串s,t,判断t是否为s的重新排列组合后的单词 s = 'anagram' t = 'nagaram' 返回true :return:"... | stack_v2_sparse_classes_36k_train_031894 | 3,969 | no_license | [
{
"docstring": "二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引",
"name": "binary_search",
"signature": "def binary_search(target_set, left, right, value)"
},
{
"docstring": "给两个字符串s,t,判断t是否为s的重新排列组合后的单词 s = 'anagram' t = 'nagaram' 返回true :return:",
"name": "exercise_demo01",
... | 4 | stack_v2_sparse_classes_30k_train_000965 | Implement the Python class `SearchExercise` described below.
Class description:
查找相关的算法题
Method signatures and docstrings:
- def binary_search(target_set, left, right, value): 二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引
- def exercise_demo01(s, t): 给两个字符串s,t,判断t是否为s的重新排列组合后的单词 s = 'anagram' t = 'naga... | Implement the Python class `SearchExercise` described below.
Class description:
查找相关的算法题
Method signatures and docstrings:
- def binary_search(target_set, left, right, value): 二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引
- def exercise_demo01(s, t): 给两个字符串s,t,判断t是否为s的重新排列组合后的单词 s = 'anagram' t = 'naga... | 894137bacf0305b8afdd74302f416b2715e216fd | <|skeleton|>
class SearchExercise:
"""查找相关的算法题"""
def binary_search(target_set, left, right, value):
"""二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引"""
<|body_0|>
def exercise_demo01(s, t):
"""给两个字符串s,t,判断t是否为s的重新排列组合后的单词 s = 'anagram' t = 'nagaram' 返回true :return:"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SearchExercise:
"""查找相关的算法题"""
def binary_search(target_set, left, right, value):
"""二分查找 :param target_set: 目标集合 :param value: 要查找的值 :return: 索引"""
while left <= right:
mid = (left + right) // 2
if target_set[mid] == value:
return mid
e... | the_stack_v2_python_sparse | data_struct/search_exec.py | dxc13762525628/concurrent | train | 0 |
24a98631f87f41fd6d4bfa5878846e671d8f5814 | [
"QtGui.QLabel.__init__(self, parent)\nself.setAutoFillBackground(True)\nself.setScaledContents(True)\nself.setMargin(0)\nself.setFocusPolicy(QtCore.Qt.ClickFocus)\nself.cellWidget = None\nlayout = QtGui.QGridLayout(self)\nlayout.setSpacing(2)\nlayout.setMargin(self.margin())\nlayout.setRowStretch(1, 1)\nself.setLay... | <|body_start_0|>
QtGui.QLabel.__init__(self, parent)
self.setAutoFillBackground(True)
self.setScaledContents(True)
self.setMargin(0)
self.setFocusPolicy(QtCore.Qt.ClickFocus)
self.cellWidget = None
layout = QtGui.QGridLayout(self)
layout.setSpacing(2)
... | QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom | QCellPresenter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QCellPresenter:
"""QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom"""
def __init__(self, parent=None):
"""QCellPresenter(parent: QWidget) -> QCellPresenter Create the layout of the widget"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_031895 | 43,413 | permissive | [
{
"docstring": "QCellPresenter(parent: QWidget) -> QCellPresenter Create the layout of the widget",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "updateFromCellWidget(cellWidget: QWidget) -> None Assign a cell widget to this presenter",
"name": "assign... | 5 | null | Implement the Python class `QCellPresenter` described below.
Class description:
QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom
Method signatures and docstrings:
- def __init__(self, parent=None): QCellPresenter(parent: QWidget) -> QCellPresente... | Implement the Python class `QCellPresenter` described below.
Class description:
QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom
Method signatures and docstrings:
- def __init__(self, parent=None): QCellPresenter(parent: QWidget) -> QCellPresente... | 23ef56ec24b85c82416e1437a08381635328abe5 | <|skeleton|>
class QCellPresenter:
"""QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom"""
def __init__(self, parent=None):
"""QCellPresenter(parent: QWidget) -> QCellPresenter Create the layout of the widget"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QCellPresenter:
"""QCellPresenter represents a cell in the Editing Mode. It has an info bar on top and control dragable icons on the bottom"""
def __init__(self, parent=None):
"""QCellPresenter(parent: QWidget) -> QCellPresenter Create the layout of the widget"""
QtGui.QLabel.__init__(sel... | the_stack_v2_python_sparse | vistrails_current/vistrails/packages/spreadsheet/spreadsheet_cell.py | lumig242/VisTrailsRecommendation | train | 3 |
0582fe1d0c3100afd8d4baa29f0fbca1dbf47097 | [
"super(LegacyGaussianEmbedder, self).__init__(name=name)\nself.embedder_mean = embedding_mean_layer\nself.embedder_stddev = embedding_stddev_layer\nself.sampling = Sampling()",
"z_mean = self.embedder_mean(inputs)\nif training:\n z_stddev = tf.nn.elu(self.embedder_stddev(inputs)) + 1.0\n epsilon = tf.random... | <|body_start_0|>
super(LegacyGaussianEmbedder, self).__init__(name=name)
self.embedder_mean = embedding_mean_layer
self.embedder_stddev = embedding_stddev_layer
self.sampling = Sampling()
<|end_body_0|>
<|body_start_1|>
z_mean = self.embedder_mean(inputs)
if training:
... | Implements a Gaussian embedder. | LegacyGaussianEmbedder | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LegacyGaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_stddev_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_stddev_layer: A `tf.keras.Layer` o... | stack_v2_sparse_classes_36k_train_031896 | 30,548 | permissive | [
{
"docstring": "Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_stddev_layer: A `tf.keras.Layer` object for the stddev of the embedding. name: A string for the name of the layer.",
"name": "__init__",
"signature": "def __init__(self, embedding_... | 2 | null | Implement the Python class `LegacyGaussianEmbedder` described below.
Class description:
Implements a Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, embedding_mean_layer, embedding_stddev_layer, name=None): Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of th... | Implement the Python class `LegacyGaussianEmbedder` described below.
Class description:
Implements a Gaussian embedder.
Method signatures and docstrings:
- def __init__(self, embedding_mean_layer, embedding_stddev_layer, name=None): Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of th... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class LegacyGaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_stddev_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_stddev_layer: A `tf.keras.Layer` o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LegacyGaussianEmbedder:
"""Implements a Gaussian embedder."""
def __init__(self, embedding_mean_layer, embedding_stddev_layer, name=None):
"""Initializer. Args: embedding_mean_layer: A `tf.keras.Layer` object for the mean of the embedding. embedding_stddev_layer: A `tf.keras.Layer` object for the... | the_stack_v2_python_sparse | poem/cv_mim/models.py | Jimmy-INL/google-research | train | 1 |
11ffc652f007e0182aa10995303ce88299e7e5ac | [
"if 'reduction' in kwargs:\n raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')\nsuper().__init__(reduction='none', **kwargs)\nif topk < 0 or topk > 1:\n raise ValueError('topk needs to be in the range [0, 1].')\nself.topk = topk\nself.loss_weight = loss_weight",
"l... | <|body_start_0|>
if 'reduction' in kwargs:
raise ValueError('Reduction is not supported in TopKLoss.This will always return the mean!')
super().__init__(reduction='none', **kwargs)
if topk < 0 or topk > 1:
raise ValueError('topk needs to be in the range [0, 1].')
... | TopKLoss | [
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
<|body_... | stack_v2_sparse_classes_36k_train_031897 | 8,471 | permissive | [
{
"docstring": "Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses",
"name": "__init__",
"signature": "def __init__(self, topk: float, loss_weight: float=1.0, **kwar... | 2 | stack_v2_sparse_classes_30k_train_012686 | Implement the Python class `TopKLoss` described below.
Class description:
Implement the TopKLoss class.
Method signatures and docstrings:
- def __init__(self, topk: float, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entr... | Implement the Python class `TopKLoss` described below.
Class description:
Implement the TopKLoss class.
Method signatures and docstrings:
- def __init__(self, topk: float, loss_weight: float=1.0, **kwargs): Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entr... | 4f41faa7536dcef8fca7b647dcdca25360e5b58a | <|skeleton|>
class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopKLoss:
def __init__(self, topk: float, loss_weight: float=1.0, **kwargs):
"""Uses topk percent of values to compute CE loss (expects pre softmax logits!) Args: topk: percentage of all entries to use for loss computation loss_weight: scalar to balance multiple losses"""
if 'reduction' in kwa... | the_stack_v2_python_sparse | nndet/losses/segmentation.py | dboun/nnDetection | train | 1 | |
77a05df04ddd22f5c609b32ceda10e6d7b02046a | [
"user = User.objects.create(username='testuser', password='qwerty12345Q!')\nrecruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last_name='last_recruiter', email='recruiter4@mail.com')\ncandidate = User.objects.create(username='candidate4', first_name='first_candidate', last_name='... | <|body_start_0|>
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last_name='last_recruiter', email='recruiter4@mail.com')
candidate = User.objects.create(username='candidate4', first_n... | Test GET request Comments app | CommentsGetTestCases | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_get_valid_comments(self):
"""Test for GET Comments with id"""
<|body_1|>
def test_get_invalid_comments(self):
... | stack_v2_sparse_classes_36k_train_031898 | 13,494 | no_license | [
{
"docstring": "Create new data in in linked tables",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test for GET Comments with id",
"name": "test_get_valid_comments",
"signature": "def test_get_valid_comments(self)"
},
{
"docstring": "Test for GET not existin... | 3 | null | Implement the Python class `CommentsGetTestCases` described below.
Class description:
Test GET request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_get_valid_comments(self): Test for GET Comments with id
- def test_get_invalid_comments(self): Test fo... | Implement the Python class `CommentsGetTestCases` described below.
Class description:
Test GET request Comments app
Method signatures and docstrings:
- def setUp(self): Create new data in in linked tables
- def test_get_valid_comments(self): Test for GET Comments with id
- def test_get_invalid_comments(self): Test fo... | f448ec0453818d55c5c9d30aaa4f19e1d7ca5867 | <|skeleton|>
class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
<|body_0|>
def test_get_valid_comments(self):
"""Test for GET Comments with id"""
<|body_1|>
def test_get_invalid_comments(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CommentsGetTestCases:
"""Test GET request Comments app"""
def setUp(self):
"""Create new data in in linked tables"""
user = User.objects.create(username='testuser', password='qwerty12345Q!')
recruiter = User.objects.create(username='recruiter4', first_name='first4_recruiter', last... | the_stack_v2_python_sparse | Portfolio/tech-interview/techinterview/feedback/test_feedback.py | HeCToR74/Python | train | 1 |
03724c667175bcbfb72facb13582e5978b0b1b46 | [
"user = request.user\nif user.is_authenticated:\n return redirect(reverse('mapper:index'))\nuser_form = UserForm()\nreturn render(request, self.template_name, {'user_form': user_form})",
"user_form = UserForm(request.POST)\nif user_form.is_valid():\n new_user = user_form.save(commit=False)\n new_user.set... | <|body_start_0|>
user = request.user
if user.is_authenticated:
return redirect(reverse('mapper:index'))
user_form = UserForm()
return render(request, self.template_name, {'user_form': user_form})
<|end_body_0|>
<|body_start_1|>
user_form = UserForm(request.POST)
... | Handles register view | RegisterView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RegisterView:
"""Handles register view"""
def get(self, request, *args, **kwargs):
"""Loads the register view if there is no logged in user"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Checks validity of posted data and either creates the new user o... | stack_v2_sparse_classes_36k_train_031899 | 3,240 | no_license | [
{
"docstring": "Loads the register view if there is no logged in user",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Checks validity of posted data and either creates the new user or renders the form again with errors",
"name": "post",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_008443 | Implement the Python class `RegisterView` described below.
Class description:
Handles register view
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Loads the register view if there is no logged in user
- def post(self, request, *args, **kwargs): Checks validity of posted data and either c... | Implement the Python class `RegisterView` described below.
Class description:
Handles register view
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Loads the register view if there is no logged in user
- def post(self, request, *args, **kwargs): Checks validity of posted data and either c... | ce8a83cea5fe7232b6746ad9708688c23d486e99 | <|skeleton|>
class RegisterView:
"""Handles register view"""
def get(self, request, *args, **kwargs):
"""Loads the register view if there is no logged in user"""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Checks validity of posted data and either creates the new user o... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RegisterView:
"""Handles register view"""
def get(self, request, *args, **kwargs):
"""Loads the register view if there is no logged in user"""
user = request.user
if user.is_authenticated:
return redirect(reverse('mapper:index'))
user_form = UserForm()
... | the_stack_v2_python_sparse | users/views.py | johnjudeh/Rendez-Vous-Py | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.