blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 467 8.64k | id stringlengths 40 40 | length_bytes int64 515 49.7k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 160 3.93k | prompted_full_text stringlengths 681 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.09k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 331 8.3k | source stringclasses 1
value | source_path stringlengths 5 177 | source_repo stringlengths 6 88 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4056743ea5fa42f82439e8c8c0ab8eb0d8410d83 | [
"logger.debug('Get repo: %s/%s permissions for team %s', namespace_name, repository_name, teamname)\nrole = model.get_repo_role_for_team(teamname, namespace_name, repository_name)\nreturn role.to_dict()",
"new_permission = request.get_json()\nlogger.debug('Setting permission to: %s for team %s', new_permission['r... | <|body_start_0|>
logger.debug('Get repo: %s/%s permissions for team %s', namespace_name, repository_name, teamname)
role = model.get_repo_role_for_team(teamname, namespace_name, repository_name)
return role.to_dict()
<|end_body_0|>
<|body_start_1|>
new_permission = request.get_json()
... | Resource for managing individual team permissions. | RepositoryTeamPermission | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RepositoryTeamPermission:
"""Resource for managing individual team permissions."""
def get(self, namespace_name, repository_name, teamname):
"""Fetch the permission for the specified team."""
<|body_0|>
def put(self, namespace_name, repository_name, teamname):
""... | stack_v2_sparse_classes_10k_train_002500 | 8,862 | permissive | [
{
"docstring": "Fetch the permission for the specified team.",
"name": "get",
"signature": "def get(self, namespace_name, repository_name, teamname)"
},
{
"docstring": "Update the existing team permission.",
"name": "put",
"signature": "def put(self, namespace_name, repository_name, team... | 3 | stack_v2_sparse_classes_30k_val_000184 | Implement the Python class `RepositoryTeamPermission` described below.
Class description:
Resource for managing individual team permissions.
Method signatures and docstrings:
- def get(self, namespace_name, repository_name, teamname): Fetch the permission for the specified team.
- def put(self, namespace_name, reposi... | Implement the Python class `RepositoryTeamPermission` described below.
Class description:
Resource for managing individual team permissions.
Method signatures and docstrings:
- def get(self, namespace_name, repository_name, teamname): Fetch the permission for the specified team.
- def put(self, namespace_name, reposi... | e400a0c22c5f89dd35d571654b13d262b1f6e3b3 | <|skeleton|>
class RepositoryTeamPermission:
"""Resource for managing individual team permissions."""
def get(self, namespace_name, repository_name, teamname):
"""Fetch the permission for the specified team."""
<|body_0|>
def put(self, namespace_name, repository_name, teamname):
""... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class RepositoryTeamPermission:
"""Resource for managing individual team permissions."""
def get(self, namespace_name, repository_name, teamname):
"""Fetch the permission for the specified team."""
logger.debug('Get repo: %s/%s permissions for team %s', namespace_name, repository_name, teamname... | the_stack_v2_python_sparse | endpoints/api/permission.py | quay/quay | train | 2,363 |
5f22af9a5bdcbd5cdec51e744c1f7117ba3c64b3 | [
"slower = head\nfaster = head\nwhile faster and faster.next:\n slower = slower.next\n faster = faster.next.next\n if faster == slower:\n return True\nreturn False",
"listSet = set()\nwhile head:\n if head == None:\n return False\n elif head in listSet:\n return True\n else:\... | <|body_start_0|>
slower = head
faster = head
while faster and faster.next:
slower = slower.next
faster = faster.next.next
if faster == slower:
return True
return False
<|end_body_0|>
<|body_start_1|>
listSet = set()
whi... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
slower = head
faster = head
while ... | stack_v2_sparse_classes_10k_train_002501 | 1,012 | no_license | [
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle",
"signature": "def hasCycle(self, head)"
},
{
"docstring": ":type head: ListNode :rtype: bool",
"name": "hasCycle1",
"signature": "def hasCycle1(self, head)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003615 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle1(self, head): :type head: ListNode :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasCycle(self, head): :type head: ListNode :rtype: bool
- def hasCycle1(self, head): :type head: ListNode :rtype: bool
<|skeleton|>
class Solution:
def hasCycle(self, h... | 639f4686308522d59cd8b818247d70ce57dc5c10 | <|skeleton|>
class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
<|body_0|>
def hasCycle1(self, head):
""":type head: ListNode :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def hasCycle(self, head):
""":type head: ListNode :rtype: bool"""
slower = head
faster = head
while faster and faster.next:
slower = slower.next
faster = faster.next.next
if faster == slower:
return True
retu... | the_stack_v2_python_sparse | src/141. Linked List Cycle.py | YoungXueya/LeetcodeSolution | train | 0 | |
5db23eaa1b0877bb3f8a64464088b32f5883fe49 | [
"lis = []\n\ndef trav(root):\n if root.right:\n trav(root.right)\n lis.append(root.val)\n if root.left:\n trav(root.left)\ntrav(root)\nreturn min((bigger - big for bigger, big in zip(lis, lis[1:])))",
"cur = pre = residual = None\n\ndef trav(root):\n nonlocal cur, pre, residual\n if r... | <|body_start_0|>
lis = []
def trav(root):
if root.right:
trav(root.right)
lis.append(root.val)
if root.left:
trav(root.left)
trav(root)
return min((bigger - big for bigger, big in zip(lis, lis[1:])))
<|end_body_0|>
<|b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
lis = []
def trav(ro... | stack_v2_sparse_classes_10k_train_002502 | 2,046 | no_license | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "getMinimumDifference",
"signature": "def getMinimumDifference(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "getMinimumDifference",
"signature": "def getMinimumDifference(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004098 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int
- def getMinimumDifference(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
... | 9f2fca7fc3926a5c18c95bb49dcecfc7900b681c | <|skeleton|>
class Solution:
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def getMinimumDifference(self, root):
""":type root: TreeNode :rtype: int"""
lis = []
def trav(root):
if root.right:
trav(root.right)
lis.append(root.val)
if root.left:
trav(root.left)
trav(root)
... | the_stack_v2_python_sparse | 530. Minimum Absolute Difference in BST.py | WindChimeRan/leetcode-codewars | train | 0 | |
3fd0f8a80e2687472efde5a91ec8037e95c57006 | [
"data = self.data\nid_ = data['entity']['id']\nreturn f'{PLATFORM_URL}orders/{id_}'",
"available = super().available\ndata = self.data\nfrom_role = data['author_role']\nto_role = data['to_role']\nreturn from_role == 'customer_user' and to_role == 'project_manager' and available"
] | <|body_start_0|>
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
<|end_body_0|>
<|body_start_1|>
available = super().available
data = self.data
from_role = data['author_role']
to_role = data['to_role']
return from_role == ... | Email to PM on comment created. | CommentCreatedByCustomerToPM | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
data... | stack_v2_sparse_classes_10k_train_002503 | 5,020 | no_license | [
{
"docstring": "Action URL.",
"name": "action_url",
"signature": "def action_url(self) -> str"
},
{
"docstring": "Check if this action is available.",
"name": "available",
"signature": "def available(self) -> bool"
}
] | 2 | stack_v2_sparse_classes_30k_train_000393 | Implement the Python class `CommentCreatedByCustomerToPM` described below.
Class description:
Email to PM on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available. | Implement the Python class `CommentCreatedByCustomerToPM` described below.
Class description:
Email to PM on comment created.
Method signatures and docstrings:
- def action_url(self) -> str: Action URL.
- def available(self) -> bool: Check if this action is available.
<|skeleton|>
class CommentCreatedByCustomerToPM:... | cca179f55ebc3c420426eff59b23d7c8963ca9a3 | <|skeleton|>
class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
<|body_0|>
def available(self) -> bool:
"""Check if this action is available."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CommentCreatedByCustomerToPM:
"""Email to PM on comment created."""
def action_url(self) -> str:
"""Action URL."""
data = self.data
id_ = data['entity']['id']
return f'{PLATFORM_URL}orders/{id_}'
def available(self) -> bool:
"""Check if this action is availabl... | the_stack_v2_python_sparse | src/briefy/choreographer/actions/mail/leica/comment.py | BriefyHQ/briefy.choreographer | train | 0 |
97a1a0e68ec3b3f2029ead4eafaeaecc280acde9 | [
"ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)\nself.maximum_number_of_particles = max_number_particles\nself.sum_likelihoods_threshold = sum_likelihoods_threshold",
"new_particles = []\nsum_likelihoods = 0\nnumber_of_new_particles = 0\nwhile sum_likelihoods < self.s... | <|body_start_0|>
ParticleFilter.__init__(self, number_of_particles, limits, process_noise, measurement_noise)
self.maximum_number_of_particles = max_number_particles
self.sum_likelihoods_threshold = sum_likelihoods_threshold
<|end_body_0|>
<|body_start_1|>
new_particles = []
sum... | Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min) | AdaptiveParticleFilterSl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaptiveParticleFilterSl:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, process... | stack_v2_sparse_classes_10k_train_002504 | 3,982 | no_license | [
{
"docstring": "Initialize the adaptive particle filter using sum of likelihoods sampling proposed explained in [1,2]. [1] Straka, Ondrej, and Miroslav Simandl. \"A survey of sample size adaptation techniques for particle filters.\" IFAC Proceedings Volumes 42.10 (2009): 1358-1363. [2] Koller, Daphne, and Raya ... | 2 | stack_v2_sparse_classes_30k_train_001470 | Implement the Python class `AdaptiveParticleFilterSl` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and d... | Implement the Python class `AdaptiveParticleFilterSl` described below.
Class description:
Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)
Method signatures and d... | 4e5197c38a9d241d9ea06c06ab9fc893ffb8c70b | <|skeleton|>
class AdaptiveParticleFilterSl:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, process... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AdaptiveParticleFilterSl:
"""Notes: * State is (x, y, heading), where x and y are in meters and heading in radians * State space assumed limited size in each dimension, world is cyclic (hence leaving at x_max means entering at x_min)"""
def __init__(self, number_of_particles, limits, process_noise, measu... | the_stack_v2_python_sparse | core/particle_filters/adaptive_particle_filter_sl.py | eternalamit5/Learning-Nuggets | train | 0 |
112bd54e132238a576080c3513b04b305a3b5eec | [
"content = request.GET\ntoday = datetime.datetime.today()\ndf = content.get('df', None)\ndt = content.get('dt', None)\ncategory = content.get('choose_category', 0)\ntitle = '产品分类统计'\ndf = datetime.datetime.strptime(df, '%Y-%m-%d') if df is not None else today - datetime.timedelta(days=7)\ndt = datetime.datetime.str... | <|body_start_0|>
content = request.GET
today = datetime.datetime.today()
df = content.get('df', None)
dt = content.get('dt', None)
category = content.get('choose_category', 0)
title = '产品分类统计'
df = datetime.datetime.strptime(df, '%Y-%m-%d') if df is not None else ... | CategoryStatViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CategoryStatViewSet:
def get(self, request):
"""总结过滤时间段的分类统计数据"""
<|body_0|>
def calculate_by_queryset(self, queryset):
"""计算"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
content = request.GET
today = datetime.datetime.today()
df ... | stack_v2_sparse_classes_10k_train_002505 | 4,462 | no_license | [
{
"docstring": "总结过滤时间段的分类统计数据",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "计算",
"name": "calculate_by_queryset",
"signature": "def calculate_by_queryset(self, queryset)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004817 | Implement the Python class `CategoryStatViewSet` described below.
Class description:
Implement the CategoryStatViewSet class.
Method signatures and docstrings:
- def get(self, request): 总结过滤时间段的分类统计数据
- def calculate_by_queryset(self, queryset): 计算 | Implement the Python class `CategoryStatViewSet` described below.
Class description:
Implement the CategoryStatViewSet class.
Method signatures and docstrings:
- def get(self, request): 总结过滤时间段的分类统计数据
- def calculate_by_queryset(self, queryset): 计算
<|skeleton|>
class CategoryStatViewSet:
def get(self, request):... | be58dc8f1f0630d3a04e551911f66d9091bedc45 | <|skeleton|>
class CategoryStatViewSet:
def get(self, request):
"""总结过滤时间段的分类统计数据"""
<|body_0|>
def calculate_by_queryset(self, queryset):
"""计算"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CategoryStatViewSet:
def get(self, request):
"""总结过滤时间段的分类统计数据"""
content = request.GET
today = datetime.datetime.today()
df = content.get('df', None)
dt = content.get('dt', None)
category = content.get('choose_category', 0)
title = '产品分类统计'
df =... | the_stack_v2_python_sparse | shopback/categorys/views_stats.py | nidepuzi/ndpuzsys | train | 1 | |
d177b7651982ec05e6d12cc2bb899d3f6663a8b0 | [
"result = self.versions_client.list_versions()\nversions = result['versions']\nself.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')",
"result = self.versions_client.list_versions()\nversions = result['versions']\nfor version in versions:\n links = [x for x in version['links'] ... | <|body_start_0|>
result = self.versions_client.list_versions()
versions = result['versions']
self.assertEqual(versions[0]['id'], 'v2.0', 'The first listed version should be v2.0')
<|end_body_0|>
<|body_start_1|>
result = self.versions_client.list_versions()
versions = result['ve... | TestVersions | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_10k_train_002506 | 3,232 | permissive | [
{
"docstring": "Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. It's important that this is available to API c... | 2 | null | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | Implement the Python class `TestVersions` described below.
Class description:
Implement the TestVersions class.
Method signatures and docstrings:
- def test_list_api_versions(self): Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on th... | 3932a799e620a20d7abf7b89e21b520683a1809b | <|skeleton|>
class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestVersions:
def test_list_api_versions(self):
"""Test that a get of the unversioned url returns the choices doc. A key feature in OpenStack services is the idea that you can GET / on the service and get a list of the versioned endpoints that you can access. This comes back as a status 300 request. I... | the_stack_v2_python_sparse | tempest/api/compute/test_versions.py | openstack/tempest | train | 270 | |
0a6288b606c944ac81a5bfbe86f16af96ece6757 | [
"cookie = set()\nhref = ''\nneed_redirect = False\nfor line in response.text.splitlines():\n line = line.strip()\n if line.startswith('Redirecting'):\n logging.debug('Redirecting with document.cookie')\n need_redirect = True\n search_result = re.search('document\\\\.cookie=\\\\\"(.*)\\\\\";',... | <|body_start_0|>
cookie = set()
href = ''
need_redirect = False
for line in response.text.splitlines():
line = line.strip()
if line.startswith('Redirecting'):
logging.debug('Redirecting with document.cookie')
need_redirect = True
... | 通过web请求形式获取release tags | HttpReleaseTagsMixin | [
"LicenseRef-scancode-mulanpsl-2.0-en",
"MulanPSL-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpReleaseTagsMixin:
"""通过web请求形式获取release tags"""
def get_redirect_resp(self, url, response):
"""获取重定向的url和cookie return: bool, str, list"""
<|body_0|>
def get_request_response(self, url, timeout=30, headers=None):
"""获取url请求获取response return: reponse"""
... | stack_v2_sparse_classes_10k_train_002507 | 16,868 | permissive | [
{
"docstring": "获取重定向的url和cookie return: bool, str, list",
"name": "get_redirect_resp",
"signature": "def get_redirect_resp(self, url, response)"
},
{
"docstring": "获取url请求获取response return: reponse",
"name": "get_request_response",
"signature": "def get_request_response(self, url, timeo... | 2 | stack_v2_sparse_classes_30k_train_001270 | Implement the Python class `HttpReleaseTagsMixin` described below.
Class description:
通过web请求形式获取release tags
Method signatures and docstrings:
- def get_redirect_resp(self, url, response): 获取重定向的url和cookie return: bool, str, list
- def get_request_response(self, url, timeout=30, headers=None): 获取url请求获取response retu... | Implement the Python class `HttpReleaseTagsMixin` described below.
Class description:
通过web请求形式获取release tags
Method signatures and docstrings:
- def get_redirect_resp(self, url, response): 获取重定向的url和cookie return: bool, str, list
- def get_request_response(self, url, timeout=30, headers=None): 获取url请求获取response retu... | 6b088eb29a53510eb441338804da79ad6d0623ab | <|skeleton|>
class HttpReleaseTagsMixin:
"""通过web请求形式获取release tags"""
def get_redirect_resp(self, url, response):
"""获取重定向的url和cookie return: bool, str, list"""
<|body_0|>
def get_request_response(self, url, timeout=30, headers=None):
"""获取url请求获取response return: reponse"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class HttpReleaseTagsMixin:
"""通过web请求形式获取release tags"""
def get_redirect_resp(self, url, response):
"""获取重定向的url和cookie return: bool, str, list"""
cookie = set()
href = ''
need_redirect = False
for line in response.text.splitlines():
line = line.strip()
... | the_stack_v2_python_sparse | src/ac/acl/package_yaml/check_repo.py | openeuler-mirror/openeuler-jenkins | train | 2 |
a8c9f5438970f8a96db50e9077261a9652e32f19 | [
"C = self.COEFFS[imt]\nmean = self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_style_of_faulting_term(C, rup.rake) + self._get_site_scaling_term(C, sites.vs30)\nstddevs = self._get_stddevs(imt, rup.mag, len(dists.rrup), stddev_types)\nreturn (mean, s... | <|body_start_0|>
C = self.COEFFS[imt]
mean = self._get_magnitude_scaling_term(C, rup.mag) + self._get_distance_scaling_term(C, rup.mag, dists.rrup) + self._get_style_of_faulting_term(C, rup.rake) + self._get_site_scaling_term(C, sites.vs30)
stddevs = self._get_stddevs(imt, rup.mag, len(dists.rru... | Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for the case in which Vs30 >= 450 m/s. In t... | Idriss2014 | [
"AGPL-3.0-only",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for t... | stack_v2_sparse_classes_10k_train_002508 | 8,985 | permissive | [
{
"docstring": "See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types)"
},
{
"docstring": "Returns the magnitu... | 6 | null | Implement the Python class `Idriss2014` described below.
Class description:
Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Id... | Implement the Python class `Idriss2014` described below.
Class description:
Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Id... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for t... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Idriss2014:
"""Implements GMPE developed by Idriss 2014 and published as "An NGA-West2 Empirical Model for Estimating the Horizontal Spectral Values Generated by Shallow Crustal Earthquakes. (2014, Earthquake Spectra, Volume 30, No. 3, pages 1155 - 1177). Idriss (2014) defines the GMPE only for the case in wh... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/idriss_2014.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
26df45b81150901138efa1be5520e595c816a1e9 | [
"log.info('Initialising user ' + username)\nself.__username = username\nself.__passwd_change_token = ''\nself.__request_header = {'content-type': 'application/json'}",
"log.info('Creating new user with username : ' + self.__username)\npath = 'user'\nsignup_info = {'user_name': self.__username, 'password': passwor... | <|body_start_0|>
log.info('Initialising user ' + username)
self.__username = username
self.__passwd_change_token = ''
self.__request_header = {'content-type': 'application/json'}
<|end_body_0|>
<|body_start_1|>
log.info('Creating new user with username : ' + self.__username)
... | User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str | User | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class User:
"""User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str"""
def __init__(self, username):
"""Instantiate user with username."""
<|body_0|>
def signup_request(self, passwor... | stack_v2_sparse_classes_10k_train_002509 | 8,311 | permissive | [
{
"docstring": "Instantiate user with username.",
"name": "__init__",
"signature": "def __init__(self, username)"
},
{
"docstring": "Sign up request of new User for ESP Rainmaker. :param password: Password to set for new user :type password: str :raises NetworkError: If there is a network connec... | 5 | stack_v2_sparse_classes_30k_train_002010 | Implement the Python class `User` described below.
Class description:
User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str
Method signatures and docstrings:
- def __init__(self, username): Instantiate user with username.
- ... | Implement the Python class `User` described below.
Class description:
User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str
Method signatures and docstrings:
- def __init__(self, username): Instantiate user with username.
- ... | 6a8c62d8a5d3b45acc4620bc47f475a1ec0d0493 | <|skeleton|>
class User:
"""User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str"""
def __init__(self, username):
"""Instantiate user with username."""
<|body_0|>
def signup_request(self, passwor... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class User:
"""User class used to instantiate instances of user to perform various user signup/login operations. :param username: Name of User :type username: str"""
def __init__(self, username):
"""Instantiate user with username."""
log.info('Initialising user ' + username)
self.__user... | the_stack_v2_python_sparse | cli/rmaker_lib/user.py | ashmagin/esp-rainmaker | train | 0 |
99965fb78ed65b5e8eb72500fedfe4844f100ad4 | [
"app = Application.objects.as_owner(self.request.user, app_id)\nusers = AccessToken.objects.values('user').filter(application=app).distinct().count()\nreturn super(ApplicationSettings, self).get_context_data(application=app, users=users, **kwargs)",
"context = self.get_context_data(app_id)\napp = context.pop('app... | <|body_start_0|>
app = Application.objects.as_owner(self.request.user, app_id)
users = AccessToken.objects.values('user').filter(application=app).distinct().count()
return super(ApplicationSettings, self).get_context_data(application=app, users=users, **kwargs)
<|end_body_0|>
<|body_start_1|>
... | Displays the Application Settings page. `/admin/apps/settings` | ApplicationSettings | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApplicationSettings:
"""Displays the Application Settings page. `/admin/apps/settings`"""
def get_context_data(self, app_id, **kwargs):
"""Returns the context to render the view. Overwrites the method to add the application to the context. Parameters ---------- app_id : int ID identi... | stack_v2_sparse_classes_10k_train_002510 | 8,135 | permissive | [
{
"docstring": "Returns the context to render the view. Overwrites the method to add the application to the context. Parameters ---------- app_id : int ID identifying the the app in the database. Returns ------- dict context",
"name": "get_context_data",
"signature": "def get_context_data(self, app_id, ... | 2 | stack_v2_sparse_classes_30k_train_006664 | Implement the Python class `ApplicationSettings` described below.
Class description:
Displays the Application Settings page. `/admin/apps/settings`
Method signatures and docstrings:
- def get_context_data(self, app_id, **kwargs): Returns the context to render the view. Overwrites the method to add the application to ... | Implement the Python class `ApplicationSettings` described below.
Class description:
Displays the Application Settings page. `/admin/apps/settings`
Method signatures and docstrings:
- def get_context_data(self, app_id, **kwargs): Returns the context to render the view. Overwrites the method to add the application to ... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class ApplicationSettings:
"""Displays the Application Settings page. `/admin/apps/settings`"""
def get_context_data(self, app_id, **kwargs):
"""Returns the context to render the view. Overwrites the method to add the application to the context. Parameters ---------- app_id : int ID identi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ApplicationSettings:
"""Displays the Application Settings page. `/admin/apps/settings`"""
def get_context_data(self, app_id, **kwargs):
"""Returns the context to render the view. Overwrites the method to add the application to the context. Parameters ---------- app_id : int ID identifying the the... | the_stack_v2_python_sparse | geokey/applications/views.py | NeolithEra/geokey | train | 0 |
779e6839dc10c3c81f54eb477406e822a2a8eb44 | [
"super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)\nself.user_dic = user_dic or config.get('janome_userdic') if config else None\nif self.user_dic:\n self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')\nelse:\n self.tokenizer = Tokenizer()",
"if self.validate(te... | <|body_start_0|>
super().__init__(logger=logger, config=config, timezone=timezone, max_length=max_length)
self.user_dic = user_dic or config.get('janome_userdic') if config else None
if self.user_dic:
self.tokenizer = Tokenizer(self.user_dic, udic_enc='utf8')
else:
... | Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger | JanomeTagger | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_10k_train_002511 | 3,694 | permissive | [
{
"docstring": "Parameters ---------- config : Config, default None Configuration timezone : timezone, default None Timezone logger : Logger, default None Logger max_length : int, default 1000 Max length of the text to parse user_dic : str, default None Path to user dictionary (MeCab IPADIC format)",
"name"... | 2 | stack_v2_sparse_classes_30k_train_000493 | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | Implement the Python class `JanomeTagger` described below.
Class description:
Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger
Method signatures and docstrings:
- def __init__(self, config=None, timezone=None, logger=None,... | dd8cd7d244b6e6e4133c8e73d637ded8a8c6846f | <|skeleton|>
class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class JanomeTagger:
"""Tagger using Janome Attributes ---------- config : minette.Config Configuration timezone : pytz.timezone Timezone logger : logging.Logger Logger"""
def __init__(self, config=None, timezone=None, logger=None, *, max_length=Tagger.MAX_LENGTH, user_dic=None, **kwargs):
"""Parameters... | the_stack_v2_python_sparse | minette/tagger/janometagger.py | uezo/minette-python | train | 33 |
439092842f45eac0e5acdf36221db19a811828e0 | [
"self.mixing_ratio = np.array([0.1, 0.2, 0.3], dtype=np.float32)\nself.specific_heat = np.array([1089.5, 1174.0, 1258.5], dtype=np.float32)\nself.latent_heat = np.array([2531771.0, 2508371.0, 2484971.0], dtype=np.float32)\nself.temperature = np.array([185.0, 260.65, 338.15], dtype=np.float32)",
"expected = np.arr... | <|body_start_0|>
self.mixing_ratio = np.array([0.1, 0.2, 0.3], dtype=np.float32)
self.specific_heat = np.array([1089.5, 1174.0, 1258.5], dtype=np.float32)
self.latent_heat = np.array([2531771.0, 2508371.0, 2484971.0], dtype=np.float32)
self.temperature = np.array([185.0, 260.65, 338.15],... | Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc | Test_psychrometric_variables | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_psychrometric_variables:
"""Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc"""
def setUp(self):
"""Set up shared input data"""
<|body_0|>
def test_calculate_specific_heat(self):
"""Test specific heat calculation"""
... | stack_v2_sparse_classes_10k_train_002512 | 11,562 | permissive | [
{
"docstring": "Set up shared input data",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Test specific heat calculation",
"name": "test_calculate_specific_heat",
"signature": "def test_calculate_specific_heat(self)"
},
{
"docstring": "Basic calculation of som... | 4 | stack_v2_sparse_classes_30k_train_006247 | Implement the Python class `Test_psychrometric_variables` described below.
Class description:
Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc
Method signatures and docstrings:
- def setUp(self): Set up shared input data
- def test_calculate_specific_heat(self): Test specific heat ... | Implement the Python class `Test_psychrometric_variables` described below.
Class description:
Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc
Method signatures and docstrings:
- def setUp(self): Set up shared input data
- def test_calculate_specific_heat(self): Test specific heat ... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_psychrometric_variables:
"""Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc"""
def setUp(self):
"""Set up shared input data"""
<|body_0|>
def test_calculate_specific_heat(self):
"""Test specific heat calculation"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test_psychrometric_variables:
"""Test calculations of one-line variables: svp in air, latent heat, mixing ratios, etc"""
def setUp(self):
"""Set up shared input data"""
self.mixing_ratio = np.array([0.1, 0.2, 0.3], dtype=np.float32)
self.specific_heat = np.array([1089.5, 1174.0, 1... | the_stack_v2_python_sparse | improver_tests/psychrometric_calculations/wet_bulb_temperature/test_WetBulbTemperature.py | metoppv/improver | train | 101 |
435f48322403ca8e571f3bccfe8cc3a0a1677b7e | [
"super().__init__()\ncheck_boundaries(boundaries)\nself.filling = filling\nself.mode = mode\nself.boundaries = boundaries",
"self.randomize(None)\nself.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries[1])\nlength = signal.shape[1]\nshift_idx = round(self.magnitude * length)\nsig = convert_d... | <|body_start_0|>
super().__init__()
check_boundaries(boundaries)
self.filling = filling
self.mode = mode
self.boundaries = boundaries
<|end_body_0|>
<|body_start_1|>
self.randomize(None)
self.magnitude = self.R.uniform(low=self.boundaries[0], high=self.boundaries... | Apply a random shift on a signal | SignalRandShift | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignalRandShift:
"""Apply a random shift on a signal"""
def __init__(self, mode: str | None='wrap', filling: float | None=0.0, boundaries: Sequence[float]=(-1.0, 1.0)) -> None:
"""Args: mode: define how the extension of the input array is done beyond its boundaries, see for more deta... | stack_v2_sparse_classes_10k_train_002513 | 16,322 | permissive | [
{
"docstring": "Args: mode: define how the extension of the input array is done beyond its boundaries, see for more details : https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.shift.html. filling: value to fill past edges of input if mode is ‘constant’. Default is 0.0. see for mode details : ht... | 2 | stack_v2_sparse_classes_30k_train_001167 | Implement the Python class `SignalRandShift` described below.
Class description:
Apply a random shift on a signal
Method signatures and docstrings:
- def __init__(self, mode: str | None='wrap', filling: float | None=0.0, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: Args: mode: define how the extension of the inp... | Implement the Python class `SignalRandShift` described below.
Class description:
Apply a random shift on a signal
Method signatures and docstrings:
- def __init__(self, mode: str | None='wrap', filling: float | None=0.0, boundaries: Sequence[float]=(-1.0, 1.0)) -> None: Args: mode: define how the extension of the inp... | e48c3e2c741fa3fc705c4425d17ac4a5afac6c47 | <|skeleton|>
class SignalRandShift:
"""Apply a random shift on a signal"""
def __init__(self, mode: str | None='wrap', filling: float | None=0.0, boundaries: Sequence[float]=(-1.0, 1.0)) -> None:
"""Args: mode: define how the extension of the input array is done beyond its boundaries, see for more deta... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SignalRandShift:
"""Apply a random shift on a signal"""
def __init__(self, mode: str | None='wrap', filling: float | None=0.0, boundaries: Sequence[float]=(-1.0, 1.0)) -> None:
"""Args: mode: define how the extension of the input array is done beyond its boundaries, see for more details : https:/... | the_stack_v2_python_sparse | monai/transforms/signal/array.py | Project-MONAI/MONAI | train | 4,805 |
dba4b6386680fd1a6827e97d1680475c6be4da78 | [
"self.aurora_params = aurora_params\nself.custom_tag_vec = custom_tag_vec\nself.instance_type = instance_type\nself.key_pair_name = key_pair_name\nself.network_security_groups = network_security_groups\nself.proxy_vm_subnet = proxy_vm_subnet\nself.proxy_vm_vpc = proxy_vm_vpc\nself.rds_params = rds_params\nself.regi... | <|body_start_0|>
self.aurora_params = aurora_params
self.custom_tag_vec = custom_tag_vec
self.instance_type = instance_type
self.key_pair_name = key_pair_name
self.network_security_groups = network_security_groups
self.proxy_vm_subnet = proxy_vm_subnet
self.proxy_... | Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This field will be populated for Aurora restores. Proto containing the parameters required for r... | DeployVMsToAWSParams | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeployVMsToAWSParams:
"""Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This field will be populated for Aurora restores... | stack_v2_sparse_classes_10k_train_002514 | 6,685 | permissive | [
{
"docstring": "Constructor for the DeployVMsToAWSParams class",
"name": "__init__",
"signature": "def __init__(self, aurora_params=None, custom_tag_vec=None, instance_type=None, key_pair_name=None, network_security_groups=None, proxy_vm_subnet=None, proxy_vm_vpc=None, rds_params=None, region=None, subn... | 2 | null | Implement the Python class `DeployVMsToAWSParams` described below.
Class description:
Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This fiel... | Implement the Python class `DeployVMsToAWSParams` described below.
Class description:
Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This fiel... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class DeployVMsToAWSParams:
"""Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This field will be populated for Aurora restores... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DeployVMsToAWSParams:
"""Implementation of the 'DeployVMsToAWSParams' model. Contains AWS specific information needed to identify various resources when converting and deploying a VM to AWS. Attributes: aurora_params (DeployDBInstancesToRDSParams): This field will be populated for Aurora restores. Proto conta... | the_stack_v2_python_sparse | cohesity_management_sdk/models/deploy_vms_to_aws_params.py | cohesity/management-sdk-python | train | 24 |
6fe4fe9f1625e7364064de6f835293781fcab788 | [
"Calculator.__init__(self, name)\nself._model = model\nfrom diffpy.srfit.sas.sasparameter import SASParameter\nfor parname in model.params:\n par = SASParameter(parname, model)\n self.addParameter(par)\nfor parname in model.dispersion:\n name = parname + '_width'\n parname += '.width'\n par = SASPara... | <|body_start_0|>
Calculator.__init__(self, name)
self._model = model
from diffpy.srfit.sas.sasparameter import SASParameter
for parname in model.params:
par = SASParameter(parname, model)
self.addParameter(par)
for parname in model.dispersion:
... | Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. Attributes: _model -- BaseModel ob... | SASCF | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. A... | stack_v2_sparse_classes_10k_train_002515 | 10,746 | no_license | [
{
"docstring": "Initialize the generator. name -- A name for the SASCF model -- SASModel object this adapts.",
"name": "__init__",
"signature": "def __init__(self, name, model)"
},
{
"docstring": "Calculate the characteristic function from the transform of the BaseModel.",
"name": "__call__"... | 2 | stack_v2_sparse_classes_30k_train_006120 | Implement the Python class `SASCF` described below.
Class description:
Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" r... | Implement the Python class `SASCF` described below.
Class description:
Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" r... | 303f73c570c1d756106aa69724898d5b119c4ead | <|skeleton|>
class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. A... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SASCF:
"""Calculator class for characteristic functions from sans-models. This class wraps a sans.models.BaseModel to calculate I(Q) related to nanoparticle shape. This I(Q) is inverted to f(r) according to: f(r) = 1 / (4 pi r) * SINFT(I(Q)), where "SINFT" represents the sine Fourier transform. Attributes: _m... | the_stack_v2_python_sparse | diffpy/srfit/pdf/characteristicfunctions.py | cfarrow/diffpy.srfit | train | 0 |
7b3dc8838ab8abd0d0562fc642e1246bb223135f | [
"member_id = self.alt_tenant_id\nimage = self.images_behavior.create_image_via_task()\nresponse = self.images_client.add_member(image.id_, member_id)\nself.assertEqual(response.status_code, 200)\nmember = response.entity\nresponse = self.images_client.get_member(image.id_, member.member_id)\nself.assertEqual(respon... | <|body_start_0|>
member_id = self.alt_tenant_id
image = self.images_behavior.create_image_via_task()
response = self.images_client.add_member(image.id_, member_id)
self.assertEqual(response.status_code, 200)
member = response.entity
response = self.images_client.get_membe... | TestGetImageMember | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
<|b... | stack_v2_sparse_classes_10k_train_002516 | 2,773 | permissive | [
{
"docstring": "@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data",
"name": "test_get_image_member",
"signature": "def test_get_image_me... | 2 | null | Implement the Python class `TestGetImageMember` described below.
Class description:
Implement the TestGetImageMember class.
Method signatures and docstrings:
- def test_get_image_member(self): @summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5)... | Implement the Python class `TestGetImageMember` described below.
Class description:
Implement the TestGetImageMember class.
Method signatures and docstrings:
- def test_get_image_member(self): @summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5)... | 30f0e64672676c3f90b4a582fe90fac6621475b3 | <|skeleton|>
class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestGetImageMember:
def test_get_image_member(self):
"""@summary: Get image member 1) Create image 2) Add image member 3) Verify that the response code is 200 4) Get image member 5) Verify that the response code is 200 6) Verify that the response contains the expected data"""
member_id = self.... | the_stack_v2_python_sparse | cloudroast/images/v2/functional/test_get_image_member.py | RULCSoft/cloudroast | train | 1 | |
f7bdb6108aed4a3403073ef98caac9239016aab4 | [
"self.model = model\nself.layer_output = LayerOutput(model=model, dir_path=dir_path)\nself.save_input_output = SaveInputOutput(dir_path, 'NCHW')",
"logger.info('Generating layer-outputs for %d input instances', len(input_batch))\ninput_dict = create_input_dict(self.model, input_batch)\nlayer_output_dict = self.la... | <|body_start_0|>
self.model = model
self.layer_output = LayerOutput(model=model, dir_path=dir_path)
self.save_input_output = SaveInputOutput(dir_path, 'NCHW')
<|end_body_0|>
<|body_start_1|>
logger.info('Generating layer-outputs for %d input instances', len(input_batch))
input_d... | Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim) | LayerOutputUtil | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LayerOutputUtil:
"""Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim)"""
def __init__(self, model: onnx_pb.ModelProto, dir_path: str):
"""Constructor - It initializes the utility classes that captures and saves layer-outputs :param model: ON... | stack_v2_sparse_classes_10k_train_002517 | 6,602 | permissive | [
{
"docstring": "Constructor - It initializes the utility classes that captures and saves layer-outputs :param model: ONNX model :param dir_path: Directory wherein layer-outputs will be saved",
"name": "__init__",
"signature": "def __init__(self, model: onnx_pb.ModelProto, dir_path: str)"
},
{
"d... | 2 | stack_v2_sparse_classes_30k_train_005330 | Implement the Python class `LayerOutputUtil` described below.
Class description:
Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim)
Method signatures and docstrings:
- def __init__(self, model: onnx_pb.ModelProto, dir_path: str): Constructor - It initializes the utility class... | Implement the Python class `LayerOutputUtil` described below.
Class description:
Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim)
Method signatures and docstrings:
- def __init__(self, model: onnx_pb.ModelProto, dir_path: str): Constructor - It initializes the utility class... | 5a406e657082b6a4f6e4bf48f0e46e085cb1e351 | <|skeleton|>
class LayerOutputUtil:
"""Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim)"""
def __init__(self, model: onnx_pb.ModelProto, dir_path: str):
"""Constructor - It initializes the utility classes that captures and saves layer-outputs :param model: ON... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LayerOutputUtil:
"""Implementation to capture and save outputs of intermediate layers of a model (fp32/quantsim)"""
def __init__(self, model: onnx_pb.ModelProto, dir_path: str):
"""Constructor - It initializes the utility classes that captures and saves layer-outputs :param model: ONNX model :par... | the_stack_v2_python_sparse | TrainingExtensions/onnx/src/python/aimet_onnx/layer_output_utils.py | quic/aimet | train | 1,676 |
fbf59c87144cded7349c7f078e03a87f0319f63d | [
"users = User.query.all()\nusersJSON = []\nfor u in users:\n usersJSON.append({'id': u.id, 'admin': u.admin})\nreturn {'users': usersJSON}",
"args = usr_parser.parse_args()\nif isinstance(args, current_app.response_class):\n return args\nadmin = False if 'admin' not in args else args['admin']\nif args['uid'... | <|body_start_0|>
users = User.query.all()
usersJSON = []
for u in users:
usersJSON.append({'id': u.id, 'admin': u.admin})
return {'users': usersJSON}
<|end_body_0|>
<|body_start_1|>
args = usr_parser.parse_args()
if isinstance(args, current_app.response_class... | Class for endpoints responsible for providing information about users and creating a new user | Users | [
"Apache-2.0",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
<|b... | stack_v2_sparse_classes_10k_train_002518 | 5,124 | permissive | [
{
"docstring": "Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Create a new user account endpoint To create, access token and admin p... | 2 | stack_v2_sparse_classes_30k_train_005086 | Implement the Python class `Users` described below.
Class description:
Class for endpoints responsible for providing information about users and creating a new user
Method signatures and docstrings:
- def get(self): Get info of all users endpoint To access, access token and admin permissions are required Returns: obj... | Implement the Python class `Users` described below.
Class description:
Class for endpoints responsible for providing information about users and creating a new user
Method signatures and docstrings:
- def get(self): Get info of all users endpoint To access, access token and admin permissions are required Returns: obj... | 4be6f7d951ba0d707a84a2cf8cbfc36689b85a3c | <|skeleton|>
class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
<|b... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Users:
"""Class for endpoints responsible for providing information about users and creating a new user"""
def get(self):
"""Get info of all users endpoint To access, access token and admin permissions are required Returns: obj: a list of existing users with their info"""
users = User.que... | the_stack_v2_python_sparse | idlak-server/app/endpoints/user.py | Idlak/idlak | train | 65 |
c76a056c9bbde16bc6d50fadcb44081f3c54c2fd | [
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')",
"context.set_code(grpc.StatusCode.UNIMPLEMENTED)\ncontext.set_details('Method not implemented!')\nraise NotImplementedError('Method not implemented!')"
] | <|body_start_0|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
<|end_body_0|>
<|body_start_1|>
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not im... | Proto file describing the Shared Set service. Service to manage shared sets. | SharedSetServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SharedSetServiceServicer:
"""Proto file describing the Shared Set service. Service to manage shared sets."""
def GetSharedSet(self, request, context):
"""Returns the requested shared set in full detail."""
<|body_0|>
def MutateSharedSets(self, request, context):
... | stack_v2_sparse_classes_10k_train_002519 | 5,356 | permissive | [
{
"docstring": "Returns the requested shared set in full detail.",
"name": "GetSharedSet",
"signature": "def GetSharedSet(self, request, context)"
},
{
"docstring": "Creates, updates, or removes shared sets. Operation statuses are returned.",
"name": "MutateSharedSets",
"signature": "def... | 2 | stack_v2_sparse_classes_30k_test_000262 | Implement the Python class `SharedSetServiceServicer` described below.
Class description:
Proto file describing the Shared Set service. Service to manage shared sets.
Method signatures and docstrings:
- def GetSharedSet(self, request, context): Returns the requested shared set in full detail.
- def MutateSharedSets(s... | Implement the Python class `SharedSetServiceServicer` described below.
Class description:
Proto file describing the Shared Set service. Service to manage shared sets.
Method signatures and docstrings:
- def GetSharedSet(self, request, context): Returns the requested shared set in full detail.
- def MutateSharedSets(s... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class SharedSetServiceServicer:
"""Proto file describing the Shared Set service. Service to manage shared sets."""
def GetSharedSet(self, request, context):
"""Returns the requested shared set in full detail."""
<|body_0|>
def MutateSharedSets(self, request, context):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SharedSetServiceServicer:
"""Proto file describing the Shared Set service. Service to manage shared sets."""
def GetSharedSet(self, request, context):
"""Returns the requested shared set in full detail."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/shared_set_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
2363ea0624994509c0db45eb0750b4349b05baff | [
"assert not isinstance(model, Iterable), 'interleaving schedule is not supported for inference'\nmodel.eval()\nself.model = model\nself.inference_params = InferenceParams(max_batch_size, max_sequence_length)\nargs = get_args()\nself.pipeline_size_larger_than_one = args.pipeline_model_parallel_size > 1\nself.pipelin... | <|body_start_0|>
assert not isinstance(model, Iterable), 'interleaving schedule is not supported for inference'
model.eval()
self.model = model
self.inference_params = InferenceParams(max_batch_size, max_sequence_length)
args = get_args()
self.pipeline_size_larger_than_on... | Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller. | ForwardStep | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
<|bod... | stack_v2_sparse_classes_10k_train_002520 | 6,677 | permissive | [
{
"docstring": "Set values so we don't need to do it multiple times.",
"name": "__init__",
"signature": "def __init__(self, model, max_batch_size, max_sequence_length)"
},
{
"docstring": "Invocation of the forward methods. Note that self.inference_params is being modified by the forward step.",
... | 2 | stack_v2_sparse_classes_30k_train_002524 | Implement the Python class `ForwardStep` described below.
Class description:
Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller.
Method signatures and docstrings:
- def __init__(self, model, max_batch_size, max_sequence_length): Set values s... | Implement the Python class `ForwardStep` described below.
Class description:
Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller.
Method signatures and docstrings:
- def __init__(self, model, max_batch_size, max_sequence_length): Set values s... | 99b044bff07f8e5d48b45223ed4bb11bd4e884e6 | <|skeleton|>
class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
<|bod... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ForwardStep:
"""Forward step function with all the communications. We use a class here to hide the inference parameters from the outside caller."""
def __init__(self, model, max_batch_size, max_sequence_length):
"""Set values so we don't need to do it multiple times."""
assert not isinsta... | the_stack_v2_python_sparse | megatron/text_generation/forward_step.py | NVIDIA/Megatron-LM | train | 6,315 |
2f5863d346a6f805b6c5c395172234271d5ddc0f | [
"self._step = tf.train.get_or_create_global_step() if step is None else step\nself._scope = scope\nself._verbose = verbose\nself._enable_tf = enable_tf",
"step = self._step if step is None else step\nif self._scope:\n name = self._scope + name\nif self._enable_tf:\n tf_summary.scalar(name, value, step=step)... | <|body_start_0|>
self._step = tf.train.get_or_create_global_step() if step is None else step
self._scope = scope
self._verbose = verbose
self._enable_tf = enable_tf
<|end_body_0|>
<|body_start_1|>
step = self._step if step is None else step
if self._scope:
na... | Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assign_add(1) | ScalarSummary | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScalarSummary:
"""Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assign_add(1)"""
def __init__(self, ste... | stack_v2_sparse_classes_10k_train_002521 | 2,338 | permissive | [
{
"docstring": "Creates an instance of this class. Args: step: An optional `tf.Variable` for tracking the logging step. If `None`, will use the global Tensorflow step variable. scope: An optional string that is prepended to metric names passed to `__call__`. enable_tf: Whether to create a TF summary. verbose: W... | 2 | stack_v2_sparse_classes_30k_train_000983 | Implement the Python class `ScalarSummary` described below.
Class description:
Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assig... | Implement the Python class `ScalarSummary` described below.
Class description:
Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assig... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class ScalarSummary:
"""Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assign_add(1)"""
def __init__(self, ste... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ScalarSummary:
"""Enables logging a scalar metric to Tensorboard. Example: num_rounds = tf.Variable(0, dtype=tf.int64, trainable=False) summary = ScalarSummary() Anywhere in your code: summary('summary_name', summary_value) After each round: num_rounds.assign_add(1)"""
def __init__(self, step=None, scope... | the_stack_v2_python_sparse | protein_lm/logging.py | Jimmy-INL/google-research | train | 1 |
c871ee0b8913b833c51cd0620584ba5f3495db75 | [
"lines = ['foobar'] + PRESUBMIT.ARC_COMPILE_GUARD\nmock_input = PRESUBMIT_test_mocks.MockInputApi()\nmock_input.files = [PRESUBMIT_test_mocks.MockFile('ios/path/foo_controller.mm', lines), PRESUBMIT_test_mocks.MockFile('ios/path/foo_controller.m', lines)]\nmock_output = PRESUBMIT_test_mocks.MockOutputApi()\nerrors ... | <|body_start_0|>
lines = ['foobar'] + PRESUBMIT.ARC_COMPILE_GUARD
mock_input = PRESUBMIT_test_mocks.MockInputApi()
mock_input.files = [PRESUBMIT_test_mocks.MockFile('ios/path/foo_controller.mm', lines), PRESUBMIT_test_mocks.MockFile('ios/path/foo_controller.m', lines)]
mock_output = PRES... | Test the _CheckARCCompilationGuard presubmit check. | CheckARCCompilationGuardTest | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckARCCompilationGuardTest:
"""Test the _CheckARCCompilationGuard presubmit check."""
def testGoodImplementationFiles(self):
"""Test that .m and .mm files with a guard don't raise any errors."""
<|body_0|>
def testBadImplementationFiles(self):
"""Test that .m a... | stack_v2_sparse_classes_10k_train_002522 | 3,527 | permissive | [
{
"docstring": "Test that .m and .mm files with a guard don't raise any errors.",
"name": "testGoodImplementationFiles",
"signature": "def testGoodImplementationFiles(self)"
},
{
"docstring": "Test that .m and .mm files without a guard raise an error.",
"name": "testBadImplementationFiles",
... | 3 | null | Implement the Python class `CheckARCCompilationGuardTest` described below.
Class description:
Test the _CheckARCCompilationGuard presubmit check.
Method signatures and docstrings:
- def testGoodImplementationFiles(self): Test that .m and .mm files with a guard don't raise any errors.
- def testBadImplementationFiles(... | Implement the Python class `CheckARCCompilationGuardTest` described below.
Class description:
Test the _CheckARCCompilationGuard presubmit check.
Method signatures and docstrings:
- def testGoodImplementationFiles(self): Test that .m and .mm files with a guard don't raise any errors.
- def testBadImplementationFiles(... | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | <|skeleton|>
class CheckARCCompilationGuardTest:
"""Test the _CheckARCCompilationGuard presubmit check."""
def testGoodImplementationFiles(self):
"""Test that .m and .mm files with a guard don't raise any errors."""
<|body_0|>
def testBadImplementationFiles(self):
"""Test that .m a... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CheckARCCompilationGuardTest:
"""Test the _CheckARCCompilationGuard presubmit check."""
def testGoodImplementationFiles(self):
"""Test that .m and .mm files with a guard don't raise any errors."""
lines = ['foobar'] + PRESUBMIT.ARC_COMPILE_GUARD
mock_input = PRESUBMIT_test_mocks.M... | the_stack_v2_python_sparse | ios/PRESUBMIT_test.py | Samsung/Castanets | train | 58 |
3ecae1d38f71ea8151ab3d05b937391931f0081c | [
"self.fname = fname\nself.testing = testing\nself.fname_short = fname[fname.rfind('/') + 1:]\nwith open(fname, 'r') as f:\n data = f.readlines()\nself.knapsack_size = int(data[0].split()[0])\nself.num_items = int(data[0].split()[1])\nself.values = [0]\nself.weights = [0]\nself.max_weight = 0\nfor item in data[1:... | <|body_start_0|>
self.fname = fname
self.testing = testing
self.fname_short = fname[fname.rfind('/') + 1:]
with open(fname, 'r') as f:
data = f.readlines()
self.knapsack_size = int(data[0].split()[0])
self.num_items = int(data[0].split()[1])
self.value... | Class defining a knapsack | Knapsack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
<|body_0|>
def naive_solution(self):
"""Find and return the optimal total value of items that can fit in the knapsac... | stack_v2_sparse_classes_10k_train_002523 | 6,784 | no_license | [
{
"docstring": "Read in the input from fname and the solution if testing",
"name": "__init__",
"signature": "def __init__(self, fname, testing=False)"
},
{
"docstring": "Find and return the optimal total value of items that can fit in the knapsack. Use the naive method filling out the 2d array",... | 4 | stack_v2_sparse_classes_30k_train_001045 | Implement the Python class `Knapsack` described below.
Class description:
Class defining a knapsack
Method signatures and docstrings:
- def __init__(self, fname, testing=False): Read in the input from fname and the solution if testing
- def naive_solution(self): Find and return the optimal total value of items that c... | Implement the Python class `Knapsack` described below.
Class description:
Class defining a knapsack
Method signatures and docstrings:
- def __init__(self, fname, testing=False): Read in the input from fname and the solution if testing
- def naive_solution(self): Find and return the optimal total value of items that c... | 2a9b795d3bbcccd5b1fce83d3ed431ec54d084a7 | <|skeleton|>
class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
<|body_0|>
def naive_solution(self):
"""Find and return the optimal total value of items that can fit in the knapsac... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Knapsack:
"""Class defining a knapsack"""
def __init__(self, fname, testing=False):
"""Read in the input from fname and the solution if testing"""
self.fname = fname
self.testing = testing
self.fname_short = fname[fname.rfind('/') + 1:]
with open(fname, 'r') as f:
... | the_stack_v2_python_sparse | course3/assignment4_q1.py | denck007/Algorithms_specialization | train | 1 |
ee4e995382a917b0dc4c4e5936c6dcc6011607e8 | [
"query = Session.query(Movie).filter(Movie.title == item.title)\nresult = query.first()\nreturn result",
"query = Session.query(Movie.title)\nresult = query.all()\ntitle_list = [title for title, in result]\none_item = process.extractOne(title, title_list)\nif one_item:\n result_title, ratio = one_item\nelse:\n... | <|body_start_0|>
query = Session.query(Movie).filter(Movie.title == item.title)
result = query.first()
return result
<|end_body_0|>
<|body_start_1|>
query = Session.query(Movie.title)
result = query.all()
title_list = [title for title, in result]
one_item = proce... | Movie | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Movie:
def get_movie_if_exist(item):
"""Get movie if exists else return None. Judged by title"""
<|body_0|>
def get_by_title(title):
"""fuzzy search movie item from database"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
query = Session.query(Movie... | stack_v2_sparse_classes_10k_train_002524 | 1,242 | permissive | [
{
"docstring": "Get movie if exists else return None. Judged by title",
"name": "get_movie_if_exist",
"signature": "def get_movie_if_exist(item)"
},
{
"docstring": "fuzzy search movie item from database",
"name": "get_by_title",
"signature": "def get_by_title(title)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007262 | Implement the Python class `Movie` described below.
Class description:
Implement the Movie class.
Method signatures and docstrings:
- def get_movie_if_exist(item): Get movie if exists else return None. Judged by title
- def get_by_title(title): fuzzy search movie item from database | Implement the Python class `Movie` described below.
Class description:
Implement the Movie class.
Method signatures and docstrings:
- def get_movie_if_exist(item): Get movie if exists else return None. Judged by title
- def get_by_title(title): fuzzy search movie item from database
<|skeleton|>
class Movie:
def... | 67c7b963914565589f64dd1bcf18839a4160ea34 | <|skeleton|>
class Movie:
def get_movie_if_exist(item):
"""Get movie if exists else return None. Judged by title"""
<|body_0|>
def get_by_title(title):
"""fuzzy search movie item from database"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Movie:
def get_movie_if_exist(item):
"""Get movie if exists else return None. Judged by title"""
query = Session.query(Movie).filter(Movie.title == item.title)
result = query.first()
return result
def get_by_title(title):
"""fuzzy search movie item from database"""... | the_stack_v2_python_sparse | scrapyproject/models/movie.py | gas1121/JapanCinemaStatusSpider | train | 2 | |
6935dc59aa34a239d16476df23ff05ec16a72ac9 | [
"super(FactorizedReduce, self).__init__()\nassert C_out % 2 == 0\nself.relu = nn.ReLU(inplace=False)\nself.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\nself.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)\nself.bn = nn.BatchNorm2d(C_out, affine=affine)",
"x = ... | <|body_start_0|>
super(FactorizedReduce, self).__init__()
assert C_out % 2 == 0
self.relu = nn.ReLU(inplace=False)
self.conv_1 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)
self.conv_2 = nn.Conv2d(C_in, C_out // 2, 1, stride=2, padding=0, bias=False)
s... | Factorized reduce block. | FactorizedReduce | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_10k_train_002525 | 5,408 | permissive | [
{
"docstring": "Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN",
"name": "__init__",
"signature": "def __init__(self, C_in, C_out, affine=True)"
},
{
"docstring": "Do an inference on FactorizedReduce. :param x:... | 2 | null | Implement the Python class `FactorizedReduce` described below.
Class description:
Factorized reduce block.
Method signatures and docstrings:
- def __init__(self, C_in, C_out, affine=True): Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in... | Implement the Python class `FactorizedReduce` described below.
Class description:
Factorized reduce block.
Method signatures and docstrings:
- def __init__(self, C_in, C_out, affine=True): Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in... | df51ed9c1d6dbde1deef63f2a037a369f8554406 | <|skeleton|>
class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
<|body_0|>
def forward(self, x):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FactorizedReduce:
"""Factorized reduce block."""
def __init__(self, C_in, C_out, affine=True):
"""Construct FactorizedReduce class. :param C_in: input channel :param C_out: output channel :param affine: whether to use affine in BN"""
super(FactorizedReduce, self).__init__()
assert... | the_stack_v2_python_sparse | built-in/TensorFlow/Research/cv/image_classification/Cars_for_TensorFlow/automl/vega/search_space/fine_grained_space/operators/functional.py | Huawei-Ascend/modelzoo | train | 1 |
06a7abd0107ebca69d22dbd381ca2f4f2e8831c0 | [
"model = GAT(n_tasks=n_tasks, graph_attention_layers=graph_attention_layers, n_attention_heads=n_attention_heads, agg_modes=agg_modes, activation=activation, residual=residual, dropout=dropout, alpha=alpha, predictor_hidden_feats=predictor_hidden_feats, predictor_dropout=predictor_dropout, mode=mode, number_atom_fe... | <|body_start_0|>
model = GAT(n_tasks=n_tasks, graph_attention_layers=graph_attention_layers, n_attention_heads=n_attention_heads, agg_modes=agg_modes, activation=activation, residual=residual, dropout=dropout, alpha=alpha, predictor_hidden_feats=predictor_hidden_feats, predictor_dropout=predictor_dropout, mode=... | Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weights are computed by applyin... | GATModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GATModel:
"""Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where... | stack_v2_sparse_classes_10k_train_002526 | 15,845 | permissive | [
{
"docstring": "Parameters ---------- n_tasks: int Number of tasks. graph_attention_layers: list of int Width of channels per attention head for GAT layers. graph_attention_layers[i] gives the width of channel for each attention head for the i-th GAT layer. If both ``graph_attention_layers`` and ``agg_modes`` a... | 2 | null | Implement the Python class `GATModel` described below.
Class description:
Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the n... | Implement the Python class `GATModel` described below.
Class description:
Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the n... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class GATModel:
"""Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class GATModel:
"""Model for Graph Property Prediction Based on Graph Attention Networks (GAT). This model proceeds as follows: * Update node representations in graphs with a variant of GAT * For each graph, compute its representation by 1) a weighted sum of the node representations in the graph, where the weights ... | the_stack_v2_python_sparse | deepchem/models/torch_models/gat.py | deepchem/deepchem | train | 4,876 |
0b8be7d632a87860456d1394f85d567a4941313f | [
"if not nums:\n return 0\nif len(nums) < 3:\n return max(nums)\nres = max(self.helper(nums[1:]), self.helper(nums[:-1]))\nreturn res",
"max_ = [nums[0], max(nums[:2])]\nfor i in range(2, len(nums)):\n max_.append(max(nums[i] + max_[i - 2], max_[i - 1]))\nreturn max_[-1]"
] | <|body_start_0|>
if not nums:
return 0
if len(nums) < 3:
return max(nums)
res = max(self.helper(nums[1:]), self.helper(nums[:-1]))
return res
<|end_body_0|>
<|body_start_1|>
max_ = [nums[0], max(nums[:2])]
for i in range(2, len(nums)):
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
if len(nums) < 3... | stack_v2_sparse_classes_10k_train_002527 | 1,303 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "helper",
"signature": "def helper(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004207 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def helper(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
... | d181f2075c6c3881772dfbf54df3ac3390936079 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def helper(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
if len(nums) < 3:
return max(nums)
res = max(self.helper(nums[1:]), self.helper(nums[:-1]))
return res
def helper(self, nums):
""":type nums... | the_stack_v2_python_sparse | 213. House Robber II.py | melekoktay/Leetcode-Practice | train | 0 | |
8f9c390c5648cab114bb016c6e322e21d6bbc6b8 | [
"user = UserModel.objects.create_user(username='saimer')\nself.assertEqual(user.email, '')\nself.assertEqual(user.username, 'saimer')\nself.assertFalse(user.has_usable_password())",
"self.test_user_creation()\nwith self.assertRaisesMessage(IntegrityError, 'UNIQUE constraint failed: auths_user.username'):\n Use... | <|body_start_0|>
user = UserModel.objects.create_user(username='saimer')
self.assertEqual(user.email, '')
self.assertEqual(user.username, 'saimer')
self.assertFalse(user.has_usable_password())
<|end_body_0|>
<|body_start_1|>
self.test_user_creation()
with self.assertRais... | Test case to create user. | UserCreationTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
<|body_0|>
def test_user_recreate(self):
"""Testing to re-create same user. Expected result: - Raise e... | stack_v2_sparse_classes_10k_train_002528 | 1,526 | no_license | [
{
"docstring": "Testing to create a user. Expected result: - User created successfully",
"name": "test_user_creation",
"signature": "def test_user_creation(self)"
},
{
"docstring": "Testing to re-create same user. Expected result: - Raise exception IntegrityError",
"name": "test_user_recreat... | 3 | stack_v2_sparse_classes_30k_train_004654 | Implement the Python class `UserCreationTestCase` described below.
Class description:
Test case to create user.
Method signatures and docstrings:
- def test_user_creation(self): Testing to create a user. Expected result: - User created successfully
- def test_user_recreate(self): Testing to re-create same user. Expec... | Implement the Python class `UserCreationTestCase` described below.
Class description:
Test case to create user.
Method signatures and docstrings:
- def test_user_creation(self): Testing to create a user. Expected result: - User created successfully
- def test_user_recreate(self): Testing to re-create same user. Expec... | 7312cf04599fbc3575764b8d14fa88353a6d0baa | <|skeleton|>
class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
<|body_0|>
def test_user_recreate(self):
"""Testing to re-create same user. Expected result: - Raise e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class UserCreationTestCase:
"""Test case to create user."""
def test_user_creation(self):
"""Testing to create a user. Expected result: - User created successfully"""
user = UserModel.objects.create_user(username='saimer')
self.assertEqual(user.email, '')
self.assertEqual(user.u... | the_stack_v2_python_sparse | src/auths/tests.py | saimer/core | train | 0 |
48915b02fde39b705ceae53fb5e7533d051eb798 | [
"nodeValuePairs = self.fetch('nodeValuePairs', None)\nfor nodeValuePair in nodeValuePairs:\n node = nodeValuePair[0]\n value = nodeValuePair[1]\n self.setNodeDatum(node, value)\nself.puts(success=True)\nreturn",
"if not cmds.attributeQuery('datum', node=node, exists=True):\n cmds.addAttr(node, longNam... | <|body_start_0|>
nodeValuePairs = self.fetch('nodeValuePairs', None)
for nodeValuePair in nodeValuePairs:
node = nodeValuePair[0]
value = nodeValuePair[1]
self.setNodeDatum(node, value)
self.puts(success=True)
return
<|end_body_0|>
<|body_start_1|>
... | A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False | SetNodeDatum | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_10k_train_002529 | 1,869 | no_license | [
{
"docstring": "Sets the prev and next links for a list of node-value pairs that provide information about the prev and next to each specified node.",
"name": "run",
"signature": "def run(self, *args, **kwargs)"
},
{
"docstring": "Sets the node's datum value, creating the attribute if not alread... | 2 | stack_v2_sparse_classes_30k_train_004367 | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | Implement the Python class `SetNodeDatum` described below.
Class description:
A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed els... | c795ed7cfab512ad340ff88c8c0e67237ac2dfc5 | <|skeleton|>
class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SetNodeDatum:
"""A remote script class for setting the prev and next links for a given set of nodes, passed in as a list of 'nodeLinks'. Each is a tuple (thisNode, prevNode, nextNode). --- RETURNS --- success: True if at least one track node is processed else False"""
def run(self, *args, **kwargs):
... | the_stack_v2_python_sparse | src/cadence/mayan/trackway/SetNodeDatum.py | satello/Cadence | train | 0 |
0d39505d764ef2db2de46b5a1c68261771d11340 | [
"dp = [0] * len(nums)\ndp[0] = 1\nfor index in range(1, len(nums)):\n dp[index] = 1\n for i in range(index):\n if nums[index] > nums[i]:\n dp[index] = max(dp[index], dp[i] + 1)\nreturn max(dp)",
"dp = [[0, 0] for _ in range(len(nums))]\ndp[0][0] = 0\ndp[0][1] = 1\nfor index in range(1, len... | <|body_start_0|>
dp = [0] * len(nums)
dp[0] = 1
for index in range(1, len(nums)):
dp[index] = 1
for i in range(index):
if nums[index] > nums[i]:
dp[index] = max(dp[index], dp[i] + 1)
return max(dp)
<|end_body_0|>
<|body_start_1... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
dp = [0] * len(nums)
dp[0] = 1
... | stack_v2_sparse_classes_10k_train_002530 | 974 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS",
"signature": "def lengthOfLIS(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "lengthOfLIS1",
"signature": "def lengthOfLIS1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000227 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(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 lengthOfLIS(self, nums): :type nums: List[int] :rtype: int
- def lengthOfLIS1(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def lengthOfLI... | 9d394cd2862703cfb7a7b505b35deda7450a692e | <|skeleton|>
class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def lengthOfLIS1(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def lengthOfLIS(self, nums):
""":type nums: List[int] :rtype: int"""
dp = [0] * len(nums)
dp[0] = 1
for index in range(1, len(nums)):
dp[index] = 1
for i in range(index):
if nums[index] > nums[i]:
dp[index] =... | the_stack_v2_python_sparse | 300.最长递增子序列.py | Ezi4Zy/leetcode | train | 0 | |
58223a5755289cb41d090f31f16a1f492c9f3b46 | [
"sampleAtom = atoms[-1]\nself.atoms = []\nself.name = sampleAtom.resName\nself.chainID = sampleAtom.chainID\nself.resSeq = sampleAtom.resSeq\nself.iCode = sampleAtom.iCode\nself.fixed = 0\nself.ffname = 'WAT'\nself.map = {}\nself.reference = ref\nfor a in atoms:\n if a.name in ref.altnames:\n a.name = ref... | <|body_start_0|>
sampleAtom = atoms[-1]
self.atoms = []
self.name = sampleAtom.resName
self.chainID = sampleAtom.chainID
self.resSeq = sampleAtom.resSeq
self.iCode = sampleAtom.iCode
self.fixed = 0
self.ffname = 'WAT'
self.map = {}
self.ref... | Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class. | LIG | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002531 | 22,508 | permissive | [
{
"docstring": "Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)",
"name": "__init__",
"signature": "def __init__(self, atoms, ref)"
},
{
"docstring": "Create a water atom. Note the HETATM field. Parameters atomname: The name of the atom (string) ne... | 3 | null | Implement the Python class `LIG` described below.
Class description:
Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to... | Implement the Python class `LIG` described below.
Class description:
Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class.
Method signatures and docstrings:
- def __init__(self, atoms, ref): Initialize the class Parameters atoms: A list of Atom objects to... | a50f0b2f7104007c730baa51b4ec65c891008c47 | <|skeleton|>
class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LIG:
"""Generic ligand class This class gives data about the generic ligand object, and inherits off the base residue class."""
def __init__(self, atoms, ref):
"""Initialize the class Parameters atoms: A list of Atom objects to be stored in this class (list)"""
sampleAtom = atoms[-1]
... | the_stack_v2_python_sparse | mscreen/autodocktools_prepare_py3k/MolKit/pdb2pqr/src/aa.py | e-mayo/mscreen | train | 10 |
75a72f3c4620e35791b30f21c7947145cf108eee | [
"super(lstm_decoder, self).__init__()\nself.input_size = input_size\nself.hidden_size = hidden_size\nself.num_layers = num_layers\nself.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)\nself.linear = nn.Linear(hidden_size, input_size)",
"lstm_out, self.hidden = self.lstm(x_inp... | <|body_start_0|>
super(lstm_decoder, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.num_layers = num_layers
self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers)
self.linear = nn.Linear(hidden_size, i... | Decodes hidden state output by encoder | lstm_decoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent... | stack_v2_sparse_classes_10k_train_002532 | 30,872 | permissive | [
{
"docstring": ": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent layers (i.e., 2 means there are : 2 stacked LSTMs)",
"name": "__init__",
"signature": "def __init__(self, input_size, hidden... | 2 | stack_v2_sparse_classes_30k_train_003549 | Implement the Python class `lstm_decoder` described below.
Class description:
Decodes hidden state output by encoder
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers=1): : param input_size: the number of features in the input X : param hidden_size: the number of features in t... | Implement the Python class `lstm_decoder` described below.
Class description:
Decodes hidden state output by encoder
Method signatures and docstrings:
- def __init__(self, input_size, hidden_size, num_layers=1): : param input_size: the number of features in the input X : param hidden_size: the number of features in t... | b047384acff7b6a8399e839a9fa7053f548ff271 | <|skeleton|>
class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class lstm_decoder:
"""Decodes hidden state output by encoder"""
def __init__(self, input_size, hidden_size, num_layers=1):
""": param input_size: the number of features in the input X : param hidden_size: the number of features in the hidden state h : param num_layers: number of recurrent layers (i.e.... | the_stack_v2_python_sparse | demo/Emotion/em_network/models/model.py | szgtvt/OpenRadar | train | 0 |
b857f4095cf36042baa38810ad2a0995c717e324 | [
"warnings.warn('AlternateSequentialWeaveGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)\nself.graph = tf.Graph()\nself.batch_size = batch_size\nself.max_atoms = max_atoms\nself.n_atom_feat = n_atom_feat\nself.n_pair_feat = n_pair_feat\nwith self.graph.as_default():\n self.graph_topolo... | <|body_start_0|>
warnings.warn('AlternateSequentialWeaveGraph is deprecated. Will be removed in DeepChem 1.4.', DeprecationWarning)
self.graph = tf.Graph()
self.batch_size = batch_size
self.max_atoms = max_atoms
self.n_atom_feat = n_atom_feat
self.n_pair_feat = n_pair_fea... | Alternate implementation of SequentialGraph for Weave models | AlternateSequentialWeaveGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AlternateSequentialWeaveGraph:
"""Alternate implementation of SequentialGraph for Weave models"""
def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- batch_size: int number of molecules in a batch max_atoms: int, optional Maximum num... | stack_v2_sparse_classes_10k_train_002533 | 11,824 | permissive | [
{
"docstring": "Parameters ---------- batch_size: int number of molecules in a batch max_atoms: int, optional Maximum number of atoms in a molecule, should be defined based on dataset n_atom_feat: int, optional Number of features per atom. n_pair_feat: int, optional Number of features per pair of atoms.",
"... | 2 | null | Implement the Python class `AlternateSequentialWeaveGraph` described below.
Class description:
Alternate implementation of SequentialGraph for Weave models
Method signatures and docstrings:
- def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14): Parameters ---------- batch_size: int number of ... | Implement the Python class `AlternateSequentialWeaveGraph` described below.
Class description:
Alternate implementation of SequentialGraph for Weave models
Method signatures and docstrings:
- def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14): Parameters ---------- batch_size: int number of ... | ee6e67ebcf7bf04259cf13aff6388e2b791fea3d | <|skeleton|>
class AlternateSequentialWeaveGraph:
"""Alternate implementation of SequentialGraph for Weave models"""
def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- batch_size: int number of molecules in a batch max_atoms: int, optional Maximum num... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AlternateSequentialWeaveGraph:
"""Alternate implementation of SequentialGraph for Weave models"""
def __init__(self, batch_size, max_atoms=50, n_atom_feat=75, n_pair_feat=14):
"""Parameters ---------- batch_size: int number of molecules in a batch max_atoms: int, optional Maximum number of atoms ... | the_stack_v2_python_sparse | contrib/one_shot_models/graph_models.py | deepchem/deepchem | train | 4,876 |
a72f672b4466b2e25908879f1c929d6864afdc91 | [
"if isinstance(key, int):\n return AccessType(key)\nif key not in AccessType._member_map_:\n return extend_enum(AccessType, key, default)\nreturn AccessType[key]",
"if not (isinstance(value, int) and 0 <= value <= 255):\n raise ValueError('%r is not a valid %s' % (value, cls.__name__))\nif 14 <= value <=... | <|body_start_0|>
if isinstance(key, int):
return AccessType(key)
if key not in AccessType._member_map_:
return extend_enum(AccessType, key, default)
return AccessType[key]
<|end_body_0|>
<|body_start_1|>
if not (isinstance(value, int) and 0 <= value <= 255):
... | [AccessType] Access Technology Type Option Type Values | AccessType | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_10k_train_002534 | 2,583 | permissive | [
{
"docstring": "Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:",
"name": "get",
"signature": "def get(key: 'int | str', default: 'int'=-1) -> 'AccessType'"
},
{
"docstring": "Lookup function used when value is not found. ... | 2 | stack_v2_sparse_classes_30k_val_000275 | Implement the Python class `AccessType` described below.
Class description:
[AccessType] Access Technology Type Option Type Values
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'AccessType': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | Implement the Python class `AccessType` described below.
Class description:
[AccessType] Access Technology Type Option Type Values
Method signatures and docstrings:
- def get(key: 'int | str', default: 'int'=-1) -> 'AccessType': Backport support for original codes. Args: key: Key to get enum item. default: Default va... | a6fe49ec58f09e105bec5a00fb66d9b3f22730d9 | <|skeleton|>
class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
<|body_0|>
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class AccessType:
"""[AccessType] Access Technology Type Option Type Values"""
def get(key: 'int | str', default: 'int'=-1) -> 'AccessType':
"""Backport support for original codes. Args: key: Key to get enum item. default: Default value if not found. :meta private:"""
if isinstance(key, int):
... | the_stack_v2_python_sparse | pcapkit/const/mh/access_type.py | JarryShaw/PyPCAPKit | train | 204 |
495ea9650af5820adf8a7f0505a7ae39d2714c15 | [
"super(DLAUp, self).__init__()\nself.startp = startp\nif norm_func is None:\n norm_func = nn.BatchNorm2d\nif in_channels is None:\n in_channels = channels\nself.channels = channels\nchannels = list(channels)\nscales = np.array(scales, dtype=int)\nfor i in range(len(channels) - 1):\n j = -i - 2\n setattr... | <|body_start_0|>
super(DLAUp, self).__init__()
self.startp = startp
if norm_func is None:
norm_func = nn.BatchNorm2d
if in_channels is None:
in_channels = channels
self.channels = channels
channels = list(channels)
scales = np.array(scales,... | DLA Up module | DLAUp | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DLAUp:
"""DLA Up module"""
def __init__(self, startp, channels, scales, in_channels=None, norm_func=None):
"""DLA Up module"""
<|body_0|>
def forward(self, layers):
"""forward"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(DLAUp, self).__... | stack_v2_sparse_classes_10k_train_002535 | 16,229 | permissive | [
{
"docstring": "DLA Up module",
"name": "__init__",
"signature": "def __init__(self, startp, channels, scales, in_channels=None, norm_func=None)"
},
{
"docstring": "forward",
"name": "forward",
"signature": "def forward(self, layers)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000529 | Implement the Python class `DLAUp` described below.
Class description:
DLA Up module
Method signatures and docstrings:
- def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): DLA Up module
- def forward(self, layers): forward | Implement the Python class `DLAUp` described below.
Class description:
DLA Up module
Method signatures and docstrings:
- def __init__(self, startp, channels, scales, in_channels=None, norm_func=None): DLA Up module
- def forward(self, layers): forward
<|skeleton|>
class DLAUp:
"""DLA Up module"""
def __init... | f6f10c403763ea58aceccc0486b6e37ffa902989 | <|skeleton|>
class DLAUp:
"""DLA Up module"""
def __init__(self, startp, channels, scales, in_channels=None, norm_func=None):
"""DLA Up module"""
<|body_0|>
def forward(self, layers):
"""forward"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DLAUp:
"""DLA Up module"""
def __init__(self, startp, channels, scales, in_channels=None, norm_func=None):
"""DLA Up module"""
super(DLAUp, self).__init__()
self.startp = startp
if norm_func is None:
norm_func = nn.BatchNorm2d
if in_channels is None:
... | the_stack_v2_python_sparse | PaddleCV/3d_vision/SMOKE/smoke/models/backbones/dla.py | ranchlai/models | train | 2 |
545fed3f1a27a00c8da8f7b56d5a0ab5ff200dce | [
"self.urlroot = urlroot\nself.headers = headers or {}\nself.cookies = cookies or {}",
"url = self.urlroot + path\nif self.headers:\n if 'headers' in kwargs:\n headers = self.headers.copy()\n headers.update(kwargs['headers'])\n else:\n headers = self.headers\n kwargs['headers'] = head... | <|body_start_0|>
self.urlroot = urlroot
self.headers = headers or {}
self.cookies = cookies or {}
<|end_body_0|>
<|body_start_1|>
url = self.urlroot + path
if self.headers:
if 'headers' in kwargs:
headers = self.headers.copy()
headers.... | Proxy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Proxy:
def __init__(self, urlroot, headers=None, cookies=None):
""":param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典"""
<|body_0|>
def post(self, path, data=None, json=None, **kwargs):
"""Sends a POST request. :p... | stack_v2_sparse_classes_10k_train_002536 | 4,472 | no_license | [
{
"docstring": ":param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典",
"name": "__init__",
"signature": "def __init__(self, urlroot, headers=None, cookies=None)"
},
{
"docstring": "Sends a POST request. :param path: 接口路径(比如 \"/account/profile\"... | 3 | stack_v2_sparse_classes_30k_train_005748 | Implement the Python class `Proxy` described below.
Class description:
Implement the Proxy class.
Method signatures and docstrings:
- def __init__(self, urlroot, headers=None, cookies=None): :param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典
- def post(self, path,... | Implement the Python class `Proxy` described below.
Class description:
Implement the Proxy class.
Method signatures and docstrings:
- def __init__(self, urlroot, headers=None, cookies=None): :param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典
- def post(self, path,... | 1f08cbfccc1ae2123d92670c0afed9b59ae645b8 | <|skeleton|>
class Proxy:
def __init__(self, urlroot, headers=None, cookies=None):
""":param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典"""
<|body_0|>
def post(self, path, data=None, json=None, **kwargs):
"""Sends a POST request. :p... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Proxy:
def __init__(self, urlroot, headers=None, cookies=None):
""":param urlroot: 平台接口根路径(比如 http://mapi.m.jxtbkt.com) :param headers: 自定义头部字典 :param cookies: 自定义cookie字典"""
self.urlroot = urlroot
self.headers = headers or {}
self.cookies = cookies or {}
def post(self, pa... | the_stack_v2_python_sparse | tbkt/libs/utils/tbktapi.py | GUAN-YE/hd_api_djs | train | 1 | |
fe1b68be12c5b5606e3c516dd1543be259d091e3 | [
"date_formatter = self.request.locale.dates.getFormatter('date', 'short')\n\ndef _q_data_item(q):\n item = {}\n item['qid'] = 'q_%s' % q.question_id\n if q.question_number:\n item['subject'] = u'Q %s %s' % (q.question_number, q.short_name)\n else:\n item['subject'] = q.short_name\n item... | <|body_start_0|>
date_formatter = self.request.locale.dates.getFormatter('date', 'short')
def _q_data_item(q):
item = {}
item['qid'] = 'q_%s' % q.question_id
if q.question_number:
item['subject'] = u'Q %s %s' % (q.question_number, q.short_name)
... | QuestionInStateViewlet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QuestionInStateViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
date_formatter = self.request.locale.dates.getFormatter('date', 'short')
... | stack_v2_sparse_classes_10k_train_002537 | 35,739 | no_license | [
{
"docstring": "return the data of the query",
"name": "getData",
"signature": "def getData(self)"
},
{
"docstring": "refresh the query",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `QuestionInStateViewlet` described below.
Class description:
Implement the QuestionInStateViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query | Implement the Python class `QuestionInStateViewlet` described below.
Class description:
Implement the QuestionInStateViewlet class.
Method signatures and docstrings:
- def getData(self): return the data of the query
- def update(self): refresh the query
<|skeleton|>
class QuestionInStateViewlet:
def getData(sel... | 5cf0ba31dfbff8d2c1b4aa8ab6f69c7a0ae9870d | <|skeleton|>
class QuestionInStateViewlet:
def getData(self):
"""return the data of the query"""
<|body_0|>
def update(self):
"""refresh the query"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class QuestionInStateViewlet:
def getData(self):
"""return the data of the query"""
date_formatter = self.request.locale.dates.getFormatter('date', 'short')
def _q_data_item(q):
item = {}
item['qid'] = 'q_%s' % q.question_id
if q.question_number:
... | the_stack_v2_python_sparse | bungeni.buildout/branches/bungeni.buildout-refactor-2010-06-02/src/bungeni.main/bungeni/ui/viewlets/workspace.py | malangalanga/bungeni-portal | train | 0 | |
3a190a21cd5d7bf18adb6f16b73d18c3546493da | [
"assert cloud_name in equation.field_names, f'Field {cloud_name} does not exist in the equation set'\nassert rain_name in equation.field_names, f'Field {rain_name} does not exist in the equation set'\nself.cloud_idx = equation.field_names.index(cloud_name)\nself.rain_idx = equation.field_names.index(rain_name)\nVcl... | <|body_start_0|>
assert cloud_name in equation.field_names, f'Field {cloud_name} does not exist in the equation set'
assert rain_name in equation.field_names, f'Field {rain_name} does not exist in the equation set'
self.cloud_idx = equation.field_names.index(cloud_name)
self.rain_idx = e... | Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain concentration, and auto-accumulation, which is accelerated by the existence of rain... | Coalescence | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Coalescence:
"""Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain concentration, and auto-accumulation, which ... | stack_v2_sparse_classes_10k_train_002538 | 46,841 | permissive | [
{
"docstring": "Args: equation (:class:`PrognosticEquationSet`): the model's equation. cloud_name (str, optional): name of the cloud variable. Defaults to 'cloud_water'. rain_name (str, optional): name of the rain variable. Defaults to 'rain'. accretion (bool, optional): whether to include the accretion process... | 2 | stack_v2_sparse_classes_30k_train_001855 | Implement the Python class `Coalescence` described below.
Class description:
Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain conce... | Implement the Python class `Coalescence` described below.
Class description:
Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain conce... | ab93672a84d4a71019abad4249529403e4b0c8d7 | <|skeleton|>
class Coalescence:
"""Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain concentration, and auto-accumulation, which ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Coalescence:
"""Represents the coalescence of cloud droplets to form rain droplets. Coalescence is the process of forming rain droplets from cloud droplets. This scheme performs that process, using two parts: accretion, which is independent of the rain concentration, and auto-accumulation, which is accelerate... | the_stack_v2_python_sparse | gusto/physics.py | firedrakeproject/gusto | train | 10 |
f96a5f183c0fc2c46190ada3e960a5908db37d6b | [
"name = 'rc_wiki.preprocessed'\ndescription = _RC_DESCRIPTION\nsuper(BigBirdTriviaQAConfig, self).__init__(name=name, description=description, version=tfds.core.Version('1.1.1'), **kwargs)\nself.unfiltered = False\nself.exclude_context = False",
"self.sentencepiece_model_path = sentencepiece_model_path\nself.sequ... | <|body_start_0|>
name = 'rc_wiki.preprocessed'
description = _RC_DESCRIPTION
super(BigBirdTriviaQAConfig, self).__init__(name=name, description=description, version=tfds.core.Version('1.1.1'), **kwargs)
self.unfiltered = False
self.exclude_context = False
<|end_body_0|>
<|body_s... | BuilderConfig for TriviaQA. | BigBirdTriviaQAConfig | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BigBirdTriviaQAConfig:
"""BuilderConfig for TriviaQA."""
def __init__(self, **kwargs):
"""BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super."""
<|body_0|>
def configure(self, sentencepiece_model_path, sequence_length, stride, global_sequenc... | stack_v2_sparse_classes_10k_train_002539 | 16,324 | permissive | [
{
"docstring": "BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super.",
"name": "__init__",
"signature": "def __init__(self, **kwargs)"
},
{
"docstring": "Configures additional user-specified arguments.",
"name": "configure",
"signature": "def configure(self, ... | 3 | null | Implement the Python class `BigBirdTriviaQAConfig` described below.
Class description:
BuilderConfig for TriviaQA.
Method signatures and docstrings:
- def __init__(self, **kwargs): BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super.
- def configure(self, sentencepiece_model_path, sequenc... | Implement the Python class `BigBirdTriviaQAConfig` described below.
Class description:
BuilderConfig for TriviaQA.
Method signatures and docstrings:
- def __init__(self, **kwargs): BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super.
- def configure(self, sentencepiece_model_path, sequenc... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class BigBirdTriviaQAConfig:
"""BuilderConfig for TriviaQA."""
def __init__(self, **kwargs):
"""BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super."""
<|body_0|>
def configure(self, sentencepiece_model_path, sequence_length, stride, global_sequenc... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BigBirdTriviaQAConfig:
"""BuilderConfig for TriviaQA."""
def __init__(self, **kwargs):
"""BuilderConfig for TriviaQA. Args: **kwargs: keyword arguments forwarded to super."""
name = 'rc_wiki.preprocessed'
description = _RC_DESCRIPTION
super(BigBirdTriviaQAConfig, self).__i... | the_stack_v2_python_sparse | models/official/nlp/projects/triviaqa/dataset.py | aboerzel/German_License_Plate_Recognition | train | 34 |
cd28321bee27e31fc01550fcf8b6375382792433 | [
"prev, curr = (None, head)\nwhile curr.val < node.val:\n prev, curr = (curr, curr.next)\nif not prev:\n head = node\nelse:\n prev.next = node\nnode.next = curr\nreturn head",
"if not head or not head.next:\n return head\ntail = head\ncurr = head.next\nwhile curr:\n if curr.val < tail.val:\n ... | <|body_start_0|>
prev, curr = (None, head)
while curr.val < node.val:
prev, curr = (curr, curr.next)
if not prev:
head = node
else:
prev.next = node
node.next = curr
return head
<|end_body_0|>
<|body_start_1|>
if not head or no... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def insert_node(self, head, node):
"""Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
<|body_0|>
def insertionSortList(self, head):
"""Sorts input linked list using insertion sort. Time complexi... | stack_v2_sparse_classes_10k_train_002540 | 1,473 | no_license | [
{
"docstring": "Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list).",
"name": "insert_node",
"signature": "def insert_node(self, head, node)"
},
{
"docstring": "Sorts input linked list using insertion sort. Time complexity: O(n ^ 2). Space ... | 2 | stack_v2_sparse_classes_30k_train_001349 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert_node(self, head, node): Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list).
- def insertionSortList(self, head)... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def insert_node(self, head, node): Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list).
- def insertionSortList(self, head)... | 71b722ddfe8da04572e527b055cf8723d5c87bbf | <|skeleton|>
class Solution:
def insert_node(self, head, node):
"""Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
<|body_0|>
def insertionSortList(self, head):
"""Sorts input linked list using insertion sort. Time complexi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def insert_node(self, head, node):
"""Inserts node in a sorted linked list. Time complexity: O(n). Space complexity: O(1), n is len(linked list)."""
prev, curr = (None, head)
while curr.val < node.val:
prev, curr = (curr, curr.next)
if not prev:
... | the_stack_v2_python_sparse | Linked_Lists/insertion_sort_list.py | vladn90/Algorithms | train | 0 | |
c2325c19d82323e374c65c6de9fe5b1ceb86f727 | [
"if not root:\n return root\nqueue = deque([root, None])\npre_node = None\nwhile len(queue) > 0:\n node = queue.popleft()\n if node:\n if not pre_node:\n pre_node = node\n else:\n pre_node.next = node\n pre_node = node\n if node.left:\n queue... | <|body_start_0|>
if not root:
return root
queue = deque([root, None])
pre_node = None
while len(queue) > 0:
node = queue.popleft()
if node:
if not pre_node:
pre_node = node
else:
p... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def connect(self, root: Node) -> Node:
"""BFS(一次遍历)。"""
<|body_0|>
def connect2(self, root: Node) -> Node:
"""层序遍历(迭代)。"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not root:
return root
queue = deque([root, None]... | stack_v2_sparse_classes_10k_train_002541 | 6,787 | no_license | [
{
"docstring": "BFS(一次遍历)。",
"name": "connect",
"signature": "def connect(self, root: Node) -> Node"
},
{
"docstring": "层序遍历(迭代)。",
"name": "connect2",
"signature": "def connect2(self, root: Node) -> Node"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: Node) -> Node: BFS(一次遍历)。
- def connect2(self, root: Node) -> Node: 层序遍历(迭代)。 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def connect(self, root: Node) -> Node: BFS(一次遍历)。
- def connect2(self, root: Node) -> Node: 层序遍历(迭代)。
<|skeleton|>
class Solution:
def connect(self, root: Node) -> Node:
... | 6932d69353b94ec824dd0ddc86a92453f6673232 | <|skeleton|>
class Solution:
def connect(self, root: Node) -> Node:
"""BFS(一次遍历)。"""
<|body_0|>
def connect2(self, root: Node) -> Node:
"""层序遍历(迭代)。"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def connect(self, root: Node) -> Node:
"""BFS(一次遍历)。"""
if not root:
return root
queue = deque([root, None])
pre_node = None
while len(queue) > 0:
node = queue.popleft()
if node:
if not pre_node:
... | the_stack_v2_python_sparse | 0116_populating-next-right-pointers-in-each-node.py | Nigirimeshi/leetcode | train | 0 | |
3fa5d64b61e3b70681364fe428f0faada1c2c08d | [
"self.startFormatted = self.context.start.strftime('%-d %B %Y')\nself.endFormatted = self.context.end.strftime('%-d %B %Y')\nself.period = self.startFormatted + ' - ' + self.endFormatted\nif self.context.start.year == self.context.end.year:\n if self.context.start.month == self.context.end.month:\n self.p... | <|body_start_0|>
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.context.end.strftime('%-d %B %Y')
self.period = self.startFormatted + ' - ' + self.endFormatted
if self.context.start.year == self.context.end.year:
if self.context.start.... | Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt. | View | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_10k_train_002542 | 3,830 | no_license | [
{
"docstring": "Prepare information for the template",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Return catalog search results of images to show",
"name": "images",
"signature": "def images(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006788 | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | Implement the Python class `View` described below.
Class description:
Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt.
Method signatures and docstrings:
- def update(self): Prepare information for the template
- def images(self): Return catalog search... | da53064c6e09573676ca1cc6f0a3397808c5329f | <|skeleton|>
class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
<|body_0|>
def images(self):
"""Return catalog search results of images to... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class View:
"""Default view (called "@@view"") for a exhibition. The associated template is found in exhibition_templates/view.pt."""
def update(self):
"""Prepare information for the template"""
self.startFormatted = self.context.start.strftime('%-d %B %Y')
self.endFormatted = self.cont... | the_stack_v2_python_sparse | irwilot.content/irwilot/content/exhibition.py | kbat/obonato | train | 0 |
19397c86fc47d3b7898c6c19774b885bbc921971 | [
"self.surface = pygame.Surface(dim)\nself.particles = []\nfor counter in range(count):\n pos = pygame.Vector2(random.randint(0, self.surface.get_width()), random.randint(0, self.surface.get_height()))\n direction = pygame.Vector2(10 * (random.random() - 0.5), 10 * (random.random() - 0.5))\n color = pygame.... | <|body_start_0|>
self.surface = pygame.Surface(dim)
self.particles = []
for counter in range(count):
pos = pygame.Vector2(random.randint(0, self.surface.get_width()), random.randint(0, self.surface.get_height()))
direction = pygame.Vector2(10 * (random.random() - 0.5), 10... | Particles | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Particles:
def __init__(self, dim: tuple, count: int):
"""clas to draw some particles :param surface: surface to draw on :param count: number of particles"""
<|body_0|>
def update(self):
"""update every frame"""
<|body_1|>
def collide(self, p1, p2):
... | stack_v2_sparse_classes_10k_train_002543 | 5,061 | no_license | [
{
"docstring": "clas to draw some particles :param surface: surface to draw on :param count: number of particles",
"name": "__init__",
"signature": "def __init__(self, dim: tuple, count: int)"
},
{
"docstring": "update every frame",
"name": "update",
"signature": "def update(self)"
},
... | 3 | stack_v2_sparse_classes_30k_train_005840 | Implement the Python class `Particles` described below.
Class description:
Implement the Particles class.
Method signatures and docstrings:
- def __init__(self, dim: tuple, count: int): clas to draw some particles :param surface: surface to draw on :param count: number of particles
- def update(self): update every fr... | Implement the Python class `Particles` described below.
Class description:
Implement the Particles class.
Method signatures and docstrings:
- def __init__(self, dim: tuple, count: int): clas to draw some particles :param surface: surface to draw on :param count: number of particles
- def update(self): update every fr... | 1fd421195a2888c0588a49f5a043a1110eedcdbf | <|skeleton|>
class Particles:
def __init__(self, dim: tuple, count: int):
"""clas to draw some particles :param surface: surface to draw on :param count: number of particles"""
<|body_0|>
def update(self):
"""update every frame"""
<|body_1|>
def collide(self, p1, p2):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Particles:
def __init__(self, dim: tuple, count: int):
"""clas to draw some particles :param surface: surface to draw on :param count: number of particles"""
self.surface = pygame.Surface(dim)
self.particles = []
for counter in range(count):
pos = pygame.Vector2(ran... | the_stack_v2_python_sparse | effects/Particle.py | gunny26/pygame | train | 5 | |
c71c032412700226315383387f592948204f24a5 | [
"def match(s1, s2) -> bool:\n if len(s1) != len(s2):\n return False\n m = {}\n r = {}\n for a, b in zip(s1, s2):\n if a not in m and b not in r:\n m[a] = b\n r[b] = a\n if m.get(a) != b:\n return False\n return True\nreturn [word for word in words... | <|body_start_0|>
def match(s1, s2) -> bool:
if len(s1) != len(s2):
return False
m = {}
r = {}
for a, b in zip(s1, s2):
if a not in m and b not in r:
m[a] = b
r[b] = a
if m.get(... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
"""06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)"""
<|body_0|>
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
"""08/06/2022 22:55"... | stack_v2_sparse_classes_10k_train_002544 | 2,854 | no_license | [
{
"docstring": "06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)",
"name": "findAndReplacePattern",
"signature": "def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]"
},
{
"docstring": "08/06/2022 22:55",
"name": "findAndReplacePattern",
"signature... | 2 | stack_v2_sparse_classes_30k_train_001859 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: 06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)
- def findAndReplacePattern(self, wo... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]: 06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)
- def findAndReplacePattern(self, wo... | 1389a009a02e90e8700a7a00e0b7f797c129cdf4 | <|skeleton|>
class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
"""06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)"""
<|body_0|>
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
"""08/06/2022 22:55"... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
"""06/02/2021 07:12 Time complexity: O(n*l) Space complexity: O(l)"""
def match(s1, s2) -> bool:
if len(s1) != len(s2):
return False
m = {}
r = {}
... | the_stack_v2_python_sparse | leetcode/solved/926_Find_and_Replace_Pattern/solution.py | sungminoh/algorithms | train | 0 | |
614d94f1a5d86a22086afd8a228b1981f59d1b8c | [
"super().__init__(columns=columns, rows=rows, spacing=spacing, ref_cell=device, origin=origin, rotation=rotation, magnification=magnification, x_reflection=x_reflection, ignore_missing=False)\nself.parent = device\nself.owner = None",
"bbox = self.get_bounding_box()\nif bbox is None:\n bbox = ((0, 0), (0, 0))\... | <|body_start_0|>
super().__init__(columns=columns, rows=rows, spacing=spacing, ref_cell=device, origin=origin, rotation=rotation, magnification=magnification, x_reflection=x_reflection, ignore_missing=False)
self.parent = device
self.owner = None
<|end_body_0|>
<|body_start_1|>
bbox = s... | Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacent rows. origin : array-like[2] of int... | CellArray | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacen... | stack_v2_sparse_classes_10k_train_002545 | 30,147 | permissive | [
{
"docstring": "Initialize CellArray.",
"name": "__init__",
"signature": "def __init__(self, device, columns, rows, spacing, origin=(0, 0), rotation=0, magnification=None, x_reflection=False)"
},
{
"docstring": "Returns the bounding box of the CellArray.",
"name": "bbox",
"signature": "d... | 5 | stack_v2_sparse_classes_30k_train_003930 | Implement the Python class `CellArray` described below.
Class description:
Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distanc... | Implement the Python class `CellArray` described below.
Class description:
Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distanc... | aa7fb0d33ee888a3fa9e865fd8796d8c6ce73db1 | <|skeleton|>
class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacen... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CellArray:
"""Multiple references to an existing cell in an array format. Args: device : Component The referenced Component. columns : int Number of columns in the array. rows : int Number of rows in the array. spacing : array-like[2] of int or float Distances between adjacent columns and adjacent rows. origi... | the_stack_v2_python_sparse | gdsfactory/component_layout.py | JonathanCauchon/gdsfactory | train | 0 |
620d3176dc92fcc9c95323c4a6a2069b136f9749 | [
"self.name = name\nself.output_format = output_format\nself.parameters = parameters\nself.subject_line = subject_line\nself.mtype = mtype",
"if dictionary is None:\n return None\nname = dictionary.get('name')\noutput_format = dictionary.get('outputFormat')\nparameters = cohesity_management_sdk.models.scheduler... | <|body_start_0|>
self.name = name
self.output_format = output_format
self.parameters = parameters
self.subject_line = subject_line
self.mtype = mtype
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
name = dictionary.get('name')
... | Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_format (string): Specifies the output format of the report. parameters ( SchedulerProto_SchedulerJob_Sche... | SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_fo... | stack_v2_sparse_classes_10k_train_002546 | 2,862 | permissive | [
{
"docstring": "Constructor for the SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report class",
"name": "__init__",
"signature": "def __init__(self, name=None, output_format=None, parameters=None, subject_line=None, mtype=None)"
},
{
"docstring": "Creates an instance of t... | 2 | null | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string... | Implement the Python class `SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report` described below.
Class description:
Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_fo... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report:
"""Implementation of the 'SchedulerProto_SchedulerJob_ScheduleJobParameters_ReportJobParameter_Report' model. Specifies the type and parameters of a report. Attributes: name (string): Specifies the report name. output_format (string)... | the_stack_v2_python_sparse | cohesity_management_sdk/models/scheduler_proto_scheduler_job_schedule__report.py | cohesity/management-sdk-python | train | 24 |
37a00cc28e9012c07ef55ced741290f62404f5c8 | [
"classes = [cls]\nparameterschema = {'type': 'object', 'additionalProperties': False}\nwhile len(classes):\n curr_cls = classes.pop(0)\n classes.extend(curr_cls.__bases__)\n if not hasattr(curr_cls, 'arguments_structure'):\n continue\n add_parameterschema_argument(parameterschema, curr_cls.argume... | <|body_start_0|>
classes = [cls]
parameterschema = {'type': 'object', 'additionalProperties': False}
while len(classes):
curr_cls = classes.pop(0)
classes.extend(curr_cls.__bases__)
if not hasattr(curr_cls, 'arguments_structure'):
continue
... | Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config. | ArgumentsHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def for... | stack_v2_sparse_classes_10k_train_002547 | 17,901 | permissive | [
{
"docstring": "Creates parameter schema based on `arguments_structure` of class and its all parent classes. Returns ------- Dict : Parameter schema for the class.",
"name": "form_parameterschema",
"signature": "def form_parameterschema(cls) -> Dict"
},
{
"docstring": "Creates argparse parser ba... | 2 | stack_v2_sparse_classes_30k_train_006667 | Implement the Python class `ArgumentsHandler` described below.
Class description:
Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line ar... | Implement the Python class `ArgumentsHandler` described below.
Class description:
Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line ar... | 9ec31ca0da1ba4d3445b98c08a8de4da45a198a8 | <|skeleton|>
class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def for... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ArgumentsHandler:
"""Class responsible for creating parsers for arguments from command line or json configs. The child class should define its own `arguments_structure` and from_argparse/from_json methods so that it could be instantiated from command line arguments or json config."""
def form_parametersc... | the_stack_v2_python_sparse | kenning/utils/args_manager.py | antmicro/kenning | train | 55 |
8404f2fa5e730c2f4fabfb99f1919574d48586fb | [
"super(NumpyDeserializer, self).__init__(accept=accept)\nself.dtype = dtype\nself.allow_pickle = allow_pickle",
"try:\n if content_type == 'text/csv':\n return np.genfromtxt(codecs.getreader('utf-8')(stream), delimiter=',', dtype=self.dtype)\n if content_type == 'application/json':\n return np... | <|body_start_0|>
super(NumpyDeserializer, self).__init__(accept=accept)
self.dtype = dtype
self.allow_pickle = allow_pickle
<|end_body_0|>
<|body_start_1|>
try:
if content_type == 'text/csv':
return np.genfromtxt(codecs.getreader('utf-8')(stream), delimiter='... | Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array. | NumpyDeserializer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumpyDeserializer:
"""Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array."... | stack_v2_sparse_classes_10k_train_002548 | 12,360 | permissive | [
{
"docstring": "Initialize a ``NumpyDeserializer`` instance. Args: dtype (str): The dtype of the data (default: None). accept (union[str, tuple[str]]): The MIME type (or tuple of allowable MIME types) that is expected from the inference endpoint (default: \"application/x-npy\"). allow_pickle (bool): Allow loadi... | 2 | stack_v2_sparse_classes_30k_train_000118 | Implement the Python class `NumpyDeserializer` described below.
Class description:
Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.... | Implement the Python class `NumpyDeserializer` described below.
Class description:
Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class NumpyDeserializer:
"""Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumpyDeserializer:
"""Deserialize a stream of data in .npy, .npz or UTF-8 CSV/JSON format to a numpy array. Note that when using application/x-npz archive format, the result will usually be a dictionary-like object containing multiple arrays (as per ``numpy.load()``) - instead of a single array."""
def _... | the_stack_v2_python_sparse | src/sagemaker/base_deserializers.py | aws/sagemaker-python-sdk | train | 2,050 |
5270ca0a778c4850095a8808f8d62875333fae87 | [
"if len(key) not in key_size:\n raise ValueError('Incorrect key length for Salsa20 (%d bytes)' % len(key))\nif len(nonce) != 8:\n raise ValueError('Incorrect nonce length for Salsa20 (%d bytes)' % len(nonce))\nself.nonce = _copy_bytes(None, None, nonce)\nself._state = VoidPointer()\nresult = _raw_salsa20_lib.... | <|body_start_0|>
if len(key) not in key_size:
raise ValueError('Incorrect key length for Salsa20 (%d bytes)' % len(key))
if len(nonce) != 8:
raise ValueError('Incorrect nonce length for Salsa20 (%d bytes)' % len(nonce))
self.nonce = _copy_bytes(None, None, nonce)
... | Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string | Salsa20Cipher | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Salsa20Cipher:
"""Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string"""
def __init__(self, key, nonce):
"""Initialize a Salsa20 cipher object See also `new()` at the module level."""
<|... | stack_v2_sparse_classes_10k_train_002549 | 6,349 | permissive | [
{
"docstring": "Initialize a Salsa20 cipher object See also `new()` at the module level.",
"name": "__init__",
"signature": "def __init__(self, key, nonce)"
},
{
"docstring": "Encrypt a piece of data. Args: plaintext(bytes/bytearray/memoryview): The data to encrypt, of any size. Keyword Args: ou... | 3 | stack_v2_sparse_classes_30k_train_004408 | Implement the Python class `Salsa20Cipher` described below.
Class description:
Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string
Method signatures and docstrings:
- def __init__(self, key, nonce): Initialize a Salsa20 cipher o... | Implement the Python class `Salsa20Cipher` described below.
Class description:
Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string
Method signatures and docstrings:
- def __init__(self, key, nonce): Initialize a Salsa20 cipher o... | fa82044a2dc2f0f1f7454f5394e6d68fa923c289 | <|skeleton|>
class Salsa20Cipher:
"""Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string"""
def __init__(self, key, nonce):
"""Initialize a Salsa20 cipher object See also `new()` at the module level."""
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Salsa20Cipher:
"""Salsa20 cipher object. Do not create it directly. Use :py:func:`new` instead. :var nonce: The nonce with length 8 :vartype nonce: byte string"""
def __init__(self, key, nonce):
"""Initialize a Salsa20 cipher object See also `new()` at the module level."""
if len(key) not... | the_stack_v2_python_sparse | venv/lib/python3.6/site-packages/Crypto/Cipher/Salsa20.py | masora1030/eigoyurusan | train | 11 |
e86996029344122fdd30dd244ea136e42ec54dd9 | [
"domains = validated_data.pop('domains', None)\nvalidated_data.pop('id', None)\nprovider = models.EmailProvider.objects.create(**validated_data)\nif domains:\n to_create = []\n for domain in domains:\n to_create.append(models.EmailProviderDomain(provider=provider, **domain))\n models.EmailProviderDo... | <|body_start_0|>
domains = validated_data.pop('domains', None)
validated_data.pop('id', None)
provider = models.EmailProvider.objects.create(**validated_data)
if domains:
to_create = []
for domain in domains:
to_create.append(models.EmailProviderDo... | Serializer class for EmailProvider. | EmailProviderSerializer | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EmailProviderSerializer:
"""Serializer class for EmailProvider."""
def create(self, validated_data):
"""Create provider and domains."""
<|body_0|>
def update(self, instance, validated_data):
"""Update provider and domains."""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_002550 | 4,683 | permissive | [
{
"docstring": "Create provider and domains.",
"name": "create",
"signature": "def create(self, validated_data)"
},
{
"docstring": "Update provider and domains.",
"name": "update",
"signature": "def update(self, instance, validated_data)"
}
] | 2 | null | Implement the Python class `EmailProviderSerializer` described below.
Class description:
Serializer class for EmailProvider.
Method signatures and docstrings:
- def create(self, validated_data): Create provider and domains.
- def update(self, instance, validated_data): Update provider and domains. | Implement the Python class `EmailProviderSerializer` described below.
Class description:
Serializer class for EmailProvider.
Method signatures and docstrings:
- def create(self, validated_data): Create provider and domains.
- def update(self, instance, validated_data): Update provider and domains.
<|skeleton|>
class... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class EmailProviderSerializer:
"""Serializer class for EmailProvider."""
def create(self, validated_data):
"""Create provider and domains."""
<|body_0|>
def update(self, instance, validated_data):
"""Update provider and domains."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EmailProviderSerializer:
"""Serializer class for EmailProvider."""
def create(self, validated_data):
"""Create provider and domains."""
domains = validated_data.pop('domains', None)
validated_data.pop('id', None)
provider = models.EmailProvider.objects.create(**validated_d... | the_stack_v2_python_sparse | modoboa/imap_migration/api/v2/serializers.py | modoboa/modoboa | train | 2,201 |
13b0eed2dab0ff1bf0b6253d6586e39df5f6bf3c | [
"dicts = {}\nfor i, char in enumerate(order):\n dicts[char] = chr(ord('a') + i)\nnew_words = []\nfor word in words:\n lists = list(word)\n new_words.append(''.join([dicts[i] for i in lists]))\nreturn new_words == sorted(new_words)",
"def is_valid(a, b, alphabet):\n for i, char in enumerate(a):\n ... | <|body_start_0|>
dicts = {}
for i, char in enumerate(order):
dicts[char] = chr(ord('a') + i)
new_words = []
for word in words:
lists = list(word)
new_words.append(''.join([dicts[i] for i in lists]))
return new_words == sorted(new_words)
<|end_b... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
<|body_0|>
def isAlienSorted_1(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 24MS"""
<|body_1|>
<|end_skeleton|>
... | stack_v2_sparse_classes_10k_train_002551 | 3,046 | no_license | [
{
"docstring": ":type words: List[str] :type order: str :rtype: bool 48 ms",
"name": "isAlienSorted",
"signature": "def isAlienSorted(self, words, order)"
},
{
"docstring": ":type words: List[str] :type order: str :rtype: bool 24MS",
"name": "isAlienSorted_1",
"signature": "def isAlienSo... | 2 | stack_v2_sparse_classes_30k_train_006324 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool 48 ms
- def isAlienSorted_1(self, words, order): :type words: List[str] :type order: s... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isAlienSorted(self, words, order): :type words: List[str] :type order: str :rtype: bool 48 ms
- def isAlienSorted_1(self, words, order): :type words: List[str] :type order: s... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
<|body_0|>
def isAlienSorted_1(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 24MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def isAlienSorted(self, words, order):
""":type words: List[str] :type order: str :rtype: bool 48 ms"""
dicts = {}
for i, char in enumerate(order):
dicts[char] = chr(ord('a') + i)
new_words = []
for word in words:
lists = list(word)
... | the_stack_v2_python_sparse | VerifyingAnAlienDictionary_953.py | 953250587/leetcode-python | train | 2 | |
5eaaaf7a891fe628366957175dac812bb10f7455 | [
"l = 0\nr = len(List) - 1\nif l > r:\n return None\nif l == r:\n return TreeNode(List[l])\nmid = int((l + r) / 2)\nroot = TreeNode(List[mid])\nroot.left = self.build_tree(List[:mid])\nroot.right = self.build_tree(List[mid + 1:])\nreturn root",
"if not root:\n return []\nqueue = []\nresult = []\nqueue.app... | <|body_start_0|>
l = 0
r = len(List) - 1
if l > r:
return None
if l == r:
return TreeNode(List[l])
mid = int((l + r) / 2)
root = TreeNode(List[mid])
root.left = self.build_tree(List[:mid])
root.right = self.build_tree(List[mid + 1:]... | 二叉树结构类 | BinaryTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归"""
<|body_0|>
def PrintFromTopToBottom(self, root):
"""从上往下打印二叉树——层序遍历"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_002552 | 4,104 | no_license | [
{
"docstring": "构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归",
"name": "build_tree",
"signature": "def build_tree(self, List)"
},
{
"docstring": "从上往下打印二叉树——层序遍历",
"name": "PrintFromTopToBottom",
"signature": "def PrintFromTopToBottom(self, root)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003077 | Implement the Python class `BinaryTree` described below.
Class description:
二叉树结构类
Method signatures and docstrings:
- def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归
- def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历 | Implement the Python class `BinaryTree` described below.
Class description:
二叉树结构类
Method signatures and docstrings:
- def build_tree(self, List): 构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归
- def PrintFromTopToBottom(self, root): 从上往下打印二叉树——层序遍历
<|skeleton|>
class BinaryTree:
"... | 4e4f739402b95691f6c91411da26d7d3bfe042b6 | <|skeleton|>
class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归"""
<|body_0|>
def PrintFromTopToBottom(self, root):
"""从上往下打印二叉树——层序遍历"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BinaryTree:
"""二叉树结构类"""
def build_tree(self, List):
"""构建一棵平衡二叉树,数组必须为排序好地数组,才能使得是平衡二叉树 前提:输入中序遍历,该列表必须满足一棵满二叉树,才能取中间结点为根结点,然后左右子树递归"""
l = 0
r = len(List) - 1
if l > r:
return None
if l == r:
return TreeNode(List[l])
mid = int((l +... | the_stack_v2_python_sparse | 剑指offer/17.树的子结构.py | hugechuanqi/Algorithms-and-Data-Structures | train | 3 |
0e126b37e59623155c6c2fb8d4bbf9035a7d4d9e | [
"max_index = 0\nfor idx, n in enumerate(nums):\n if idx > max_index:\n return False\n max_index = max(max_index, idx + nums[idx])\nreturn True",
"start, destination = (0, len(nums) - 1)\nfrontier_backtrack_index = destination\nfor idx in range(len(nums) - 2, -1, -1):\n if idx + nums[idx] >= fronti... | <|body_start_0|>
max_index = 0
for idx, n in enumerate(nums):
if idx > max_index:
return False
max_index = max(max_index, idx + nums[idx])
return True
<|end_body_0|>
<|body_start_1|>
start, destination = (0, len(nums) - 1)
frontier_backtra... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def canJump(self, nums: list[int]) -> bool:
"""Greedy :param nums: :return:"""
<|body_0|>
def canJump(self, nums: list[int]) -> bool:
"""Back tracking :param nums: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
max_index = 0
... | stack_v2_sparse_classes_10k_train_002553 | 894 | no_license | [
{
"docstring": "Greedy :param nums: :return:",
"name": "canJump",
"signature": "def canJump(self, nums: list[int]) -> bool"
},
{
"docstring": "Back tracking :param nums: :return:",
"name": "canJump",
"signature": "def canJump(self, nums: list[int]) -> bool"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: list[int]) -> bool: Greedy :param nums: :return:
- def canJump(self, nums: list[int]) -> bool: Back tracking :param nums: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def canJump(self, nums: list[int]) -> bool: Greedy :param nums: :return:
- def canJump(self, nums: list[int]) -> bool: Back tracking :param nums: :return:
<|skeleton|>
class Sol... | e50dc0642f087f37ab3234390be3d8a0ed48fe62 | <|skeleton|>
class Solution:
def canJump(self, nums: list[int]) -> bool:
"""Greedy :param nums: :return:"""
<|body_0|>
def canJump(self, nums: list[int]) -> bool:
"""Back tracking :param nums: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def canJump(self, nums: list[int]) -> bool:
"""Greedy :param nums: :return:"""
max_index = 0
for idx, n in enumerate(nums):
if idx > max_index:
return False
max_index = max(max_index, idx + nums[idx])
return True
def canJum... | the_stack_v2_python_sparse | Leetcode/55. Jump Game.py | brlala/Educative-Grokking-Coding-Exercise | train | 3 | |
0d9e1d4253fe178e671114902d4f4eb1f8813bc1 | [
"if relationship_type not in REQUEST_RELATIONSHIPS:\n return make_response('Invalid relationship type entered', 404)\nif valid_email(requester_email) == None:\n return make_response('', 422)\nif valid_email(request_recipient_email) == None:\n return make_response('', 422)\ns_node_label = e_node_label = 'Pe... | <|body_start_0|>
if relationship_type not in REQUEST_RELATIONSHIPS:
return make_response('Invalid relationship type entered', 404)
if valid_email(requester_email) == None:
return make_response('', 422)
if valid_email(request_recipient_email) == None:
return ma... | Request | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Request:
def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response:
"""Create a request relationship."""
<|body_0|>
def delete(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response:
... | stack_v2_sparse_classes_10k_train_002554 | 3,073 | no_license | [
{
"docstring": "Create a request relationship.",
"name": "post",
"signature": "def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response"
},
{
"docstring": "Delete request relationship, effectively denying the request.",
"name": "delete",
"sig... | 2 | stack_v2_sparse_classes_30k_train_001614 | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response: Create a request relationship.
- def delete(self, relationship_type: str, re... | Implement the Python class `Request` described below.
Class description:
Implement the Request class.
Method signatures and docstrings:
- def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response: Create a request relationship.
- def delete(self, relationship_type: str, re... | 2c71a26d1efbee85d04ce9c51b209c8b97f0ec06 | <|skeleton|>
class Request:
def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response:
"""Create a request relationship."""
<|body_0|>
def delete(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response:
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Request:
def post(self, relationship_type: str, requester_email: str, request_recipient_email: str) -> Response:
"""Create a request relationship."""
if relationship_type not in REQUEST_RELATIONSHIPS:
return make_response('Invalid relationship type entered', 404)
if valid_e... | the_stack_v2_python_sparse | backend/graph/graph_api/apis/request.py | WilliamZard/PintroAppSEG-Major | train | 0 | |
790cac03cc5eae07c54741f3bc0e008689f3ffd8 | [
"self.table: typing.Dict[str, typing.Dict[int, typing.List[DnsResource]]] = {}\nself.ptrs: typing.Dict[str, str] = {}\nself._cache: typing.Optional[typing.List[Service]] = None",
"self._cache = None\nfor record in message.answers + message.resources:\n if record.qtype == QueryType.PTR and record.qname.startswi... | <|body_start_0|>
self.table: typing.Dict[str, typing.Dict[int, typing.List[DnsResource]]] = {}
self.ptrs: typing.Dict[str, str] = {}
self._cache: typing.Optional[typing.List[Service]] = None
<|end_body_0|>
<|body_start_1|>
self._cache = None
for record in message.answers + messa... | Parse zeroconf services from records in DNS messages. | ServiceParser | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ServiceParser:
"""Parse zeroconf services from records in DNS messages."""
def __init__(self) -> None:
"""Initialize a new ServiceParser instance."""
<|body_0|>
def add_message(self, message: DnsMessage) -> 'ServiceParser':
"""Add message to with records to parse... | stack_v2_sparse_classes_10k_train_002555 | 18,548 | permissive | [
{
"docstring": "Initialize a new ServiceParser instance.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Add message to with records to parse.",
"name": "add_message",
"signature": "def add_message(self, message: DnsMessage) -> 'ServiceParser'"
},
{... | 3 | stack_v2_sparse_classes_30k_train_002921 | Implement the Python class `ServiceParser` described below.
Class description:
Parse zeroconf services from records in DNS messages.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize a new ServiceParser instance.
- def add_message(self, message: DnsMessage) -> 'ServiceParser': Add message to ... | Implement the Python class `ServiceParser` described below.
Class description:
Parse zeroconf services from records in DNS messages.
Method signatures and docstrings:
- def __init__(self) -> None: Initialize a new ServiceParser instance.
- def add_message(self, message: DnsMessage) -> 'ServiceParser': Add message to ... | 05ca46d2a8bbc8e725ad63794d14b2d1fb9913fa | <|skeleton|>
class ServiceParser:
"""Parse zeroconf services from records in DNS messages."""
def __init__(self) -> None:
"""Initialize a new ServiceParser instance."""
<|body_0|>
def add_message(self, message: DnsMessage) -> 'ServiceParser':
"""Add message to with records to parse... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ServiceParser:
"""Parse zeroconf services from records in DNS messages."""
def __init__(self) -> None:
"""Initialize a new ServiceParser instance."""
self.table: typing.Dict[str, typing.Dict[int, typing.List[DnsResource]]] = {}
self.ptrs: typing.Dict[str, str] = {}
self._c... | the_stack_v2_python_sparse | pyatv/core/mdns.py | postlund/pyatv | train | 749 |
460ca86277d582b476ee991bc598709640996d3b | [
"super().__init__(name, property_set, price)\nself.house_price = house_price\nself.rents = rents\nself.number_of_houses = 0",
"if self.number_of_houses == 0:\n rent = self.rents[0]\n owner = self.owner\n if self.property_set in owner.state.owned_unmortgaged_sets:\n rent *= 2\nelse:\n rent = sel... | <|body_start_0|>
super().__init__(name, property_set, price)
self.house_price = house_price
self.rents = rents
self.number_of_houses = 0
<|end_body_0|>
<|body_start_1|>
if self.number_of_houses == 0:
rent = self.rents[0]
owner = self.owner
if ... | A type of Property representing a street. Manages rents, house-building and so on. | Street | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
... | stack_v2_sparse_classes_10k_train_002556 | 1,609 | permissive | [
{
"docstring": "The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]",
"name": "__init__",
"signature": "def __init__(self, name, property_set, price, house_price, rents)"
},
{
"docstring": "The player has landed on a square owned by anot... | 2 | stack_v2_sparse_classes_30k_train_004868 | Implement the Python class `Street` described below.
Class description:
A type of Property representing a street. Manages rents, house-building and so on.
Method signatures and docstrings:
- def __init__(self, name, property_set, price, house_price, rents): The 'constructor'. rents: passed in as a list: [base, one_ho... | Implement the Python class `Street` described below.
Class description:
A type of Property representing a street. Manages rents, house-building and so on.
Method signatures and docstrings:
- def __init__(self, name, property_set, price, house_price, rents): The 'constructor'. rents: passed in as a list: [base, one_ho... | 0460f2452c83846b6b9e3b234be411e12a86d69c | <|skeleton|>
class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Street:
"""A type of Property representing a street. Manages rents, house-building and so on."""
def __init__(self, name, property_set, price, house_price, rents):
"""The 'constructor'. rents: passed in as a list: [base, one_house, two_houses, three_houses, four_houses, hotel]"""
super().... | the_stack_v2_python_sparse | monopyly/squares/street.py | YSabarad/monopyly | train | 0 |
2844b5ac8b823775a8675ba32e0092b1e34b8671 | [
"self.S = 0.5 * (self.R + self.L)\nself.D = 0.5 * (self.R - self.L)\nreturn self",
"m_e = gamma * cgs.me\nm_i = cgs.mp\nn_i = n_e\nomega = 2 * np.pi * ghz * 1000000000.0\nom_pe = omega_plasma(n_e, m_e)\nom_pi = omega_plasma(n_i, m_i)\nom_ce = omega_cyclotron(-1, B, m_e)\nom_ci = omega_cyclotron(+1, B, m_i)\nalpha... | <|body_start_0|>
self.S = 0.5 * (self.R + self.L)
self.D = 0.5 * (self.R - self.L)
return self
<|end_body_0|>
<|body_start_1|>
m_e = gamma * cgs.me
m_i = cgs.mp
n_i = n_e
omega = 2 * np.pi * ghz * 1000000000.0
om_pe = omega_plasma(n_e, m_e)
om_pi ... | Parameters | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Parameters:
def _finish(self):
"""Stix equation 1-19."""
<|body_0|>
def new_basic(cls, ghz, n_e, B, gamma=1.0):
"""Set up plasma parameters for an electron-proton plasma in the standard cold approximation. ghz The oscillation frequency of the modes to consider, in GH... | stack_v2_sparse_classes_10k_train_002557 | 10,768 | permissive | [
{
"docstring": "Stix equation 1-19.",
"name": "_finish",
"signature": "def _finish(self)"
},
{
"docstring": "Set up plasma parameters for an electron-proton plasma in the standard cold approximation. ghz The oscillation frequency of the modes to consider, in GHz. (Note that ideally we'd express ... | 4 | stack_v2_sparse_classes_30k_train_006700 | Implement the Python class `Parameters` described below.
Class description:
Implement the Parameters class.
Method signatures and docstrings:
- def _finish(self): Stix equation 1-19.
- def new_basic(cls, ghz, n_e, B, gamma=1.0): Set up plasma parameters for an electron-proton plasma in the standard cold approximation... | Implement the Python class `Parameters` described below.
Class description:
Implement the Parameters class.
Method signatures and docstrings:
- def _finish(self): Stix equation 1-19.
- def new_basic(cls, ghz, n_e, B, gamma=1.0): Set up plasma parameters for an electron-proton plasma in the standard cold approximation... | 9dd52d813722d0932195723cf8c37a5dd2fd0d25 | <|skeleton|>
class Parameters:
def _finish(self):
"""Stix equation 1-19."""
<|body_0|>
def new_basic(cls, ghz, n_e, B, gamma=1.0):
"""Set up plasma parameters for an electron-proton plasma in the standard cold approximation. ghz The oscillation frequency of the modes to consider, in GH... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Parameters:
def _finish(self):
"""Stix equation 1-19."""
self.S = 0.5 * (self.R + self.L)
self.D = 0.5 * (self.R - self.L)
return self
def new_basic(cls, ghz, n_e, B, gamma=1.0):
"""Set up plasma parameters for an electron-proton plasma in the standard cold approxi... | the_stack_v2_python_sparse | vernon/plasma.py | pkgw/vernon | train | 1 | |
cc640326ba527eaa4489e82a9f2443a69ed8f359 | [
"ObjectManager.__init__(self)\nself.setters.update({'name': 'set_general', 'resources': 'set_many', 'sessiontemplateresourcetypereqs': 'set_many', 'sessionresourcetyperequirements': 'set_many'})\nself.getters.update({'name': 'get_general', 'resources': 'get_many_to_many', 'sessionresourcetyperequirements': 'get_man... | <|body_start_0|>
ObjectManager.__init__(self)
self.setters.update({'name': 'set_general', 'resources': 'set_many', 'sessiontemplateresourcetypereqs': 'set_many', 'sessionresourcetyperequirements': 'set_many'})
self.getters.update({'name': 'get_general', 'resources': 'get_many_to_many', 'sessionr... | Manage ResourceTypes in the Power Reg system | ResourceTypeManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceTypeManager:
"""Manage ResourceTypes in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name):
"""Create a new ResourceType @param name name of the ResourceType @return isntance of ResourceType"""
... | stack_v2_sparse_classes_10k_train_002558 | 1,443 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Create a new ResourceType @param name name of the ResourceType @return isntance of ResourceType",
"name": "create",
"signature": "def create(self, auth_token, name)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001346 | Implement the Python class `ResourceTypeManager` described below.
Class description:
Manage ResourceTypes in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name): Create a new ResourceType @param name name of the ResourceType @return isntance of... | Implement the Python class `ResourceTypeManager` described below.
Class description:
Manage ResourceTypes in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name): Create a new ResourceType @param name name of the ResourceType @return isntance of... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class ResourceTypeManager:
"""Manage ResourceTypes in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name):
"""Create a new ResourceType @param name name of the ResourceType @return isntance of ResourceType"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ResourceTypeManager:
"""Manage ResourceTypes in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.setters.update({'name': 'set_general', 'resources': 'set_many', 'sessiontemplateresourcetypereqs': 'set_many', 'sessionresourcetyperequir... | the_stack_v2_python_sparse | pr_services/resource_system/resource_type_manager.py | ninemoreminutes/openassign-server | train | 0 |
68d3022df6a0e7b227195cf70677aa33c8a96290 | [
"self.specs = specs\nself.has_exclusions = specs.has_exclusions()\nself.has_all_inclusions = specs.has_all_inclusions()\nself.indexer = Indexer(self.specs.specs_final)\nself.indexer.builder()\nself.index = self.indexer.index\nself.includes_out_of_order = self.indexer.includes_out_of_order\nself.includes_repeats = s... | <|body_start_0|>
self.specs = specs
self.has_exclusions = specs.has_exclusions()
self.has_all_inclusions = specs.has_all_inclusions()
self.indexer = Indexer(self.specs.specs_final)
self.indexer.builder()
self.index = self.indexer.index
self.includes_out_of_order =... | Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs. | SpecProcessor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpecProcessor:
"""Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs."""
def __init__(self, specs) -> None:
"""Args: specs: a L... | stack_v2_sparse_classes_10k_train_002559 | 23,596 | permissive | [
{
"docstring": "Args: specs: a List of SpecRecords Public Methods: specs_evaluator: evaluates an offset against the list of specs Notes: Automatically generates self.index - which is a list of offsets. This supports a fast alternative method of evaluating cols & recs.",
"name": "__init__",
"signature": ... | 3 | stack_v2_sparse_classes_30k_train_000386 | Implement the Python class `SpecProcessor` described below.
Class description:
Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs.
Method signatures and docstrin... | Implement the Python class `SpecProcessor` described below.
Class description:
Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs.
Method signatures and docstrin... | 133e927d150fa05317784246df69591dada648bb | <|skeleton|>
class SpecProcessor:
"""Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs."""
def __init__(self, specs) -> None:
"""Args: specs: a L... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SpecProcessor:
"""Manages the evaluation of record numbers against spec for a single spec_type It uses the Specification List[SpecRecord] structure as input and supports the evaluation of col or row numbers aginst these specs."""
def __init__(self, specs) -> None:
"""Args: specs: a List of SpecRe... | the_stack_v2_python_sparse | datagristle/slice_specs.py | kenfar/DataGristle | train | 91 |
7050232e10778ce64fa8e2d01ca53b627caf067b | [
"if len(height) == 2:\n return min(height[1], height[0])\nmax_area = 0\nfor i in range(len(height)):\n for j in range(1, len(height)):\n max_area = max(max_area, min(height[i], height[j]) * abs(j - i))\nreturn max_area",
"if len(height) == 2:\n return min(height[1], height[0])\nleft = 0\nright = l... | <|body_start_0|>
if len(height) == 2:
return min(height[1], height[0])
max_area = 0
for i in range(len(height)):
for j in range(1, len(height)):
max_area = max(max_area, min(height[i], height[j]) * abs(j - i))
return max_area
<|end_body_0|>
<|body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxArea_TLE(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(height) == 2:
return m... | stack_v2_sparse_classes_10k_train_002560 | 1,903 | no_license | [
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea_TLE",
"signature": "def maxArea_TLE(self, height)"
},
{
"docstring": ":type height: List[int] :rtype: int",
"name": "maxArea",
"signature": "def maxArea(self, height)"
}
] | 2 | stack_v2_sparse_classes_30k_train_003162 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_TLE(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxArea_TLE(self, height): :type height: List[int] :rtype: int
- def maxArea(self, height): :type height: List[int] :rtype: int
<|skeleton|>
class Solution:
def maxArea... | 2d5fa4cd696d5035ea8859befeadc5cc436959c9 | <|skeleton|>
class Solution:
def maxArea_TLE(self, height):
""":type height: List[int] :rtype: int"""
<|body_0|>
def maxArea(self, height):
""":type height: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def maxArea_TLE(self, height):
""":type height: List[int] :rtype: int"""
if len(height) == 2:
return min(height[1], height[0])
max_area = 0
for i in range(len(height)):
for j in range(1, len(height)):
max_area = max(max_area, mi... | the_stack_v2_python_sparse | SourceCode/Python/Problem/00011.Container With Most Water.py | roger6blog/LeetCode | train | 0 | |
b8af26faeb4444367f05b43d3ffe9fba193942e1 | [
"if PDT_OT_ModalDrawOperator._handle is None:\n PDT_OT_ModalDrawOperator._handle = SpaceView3D.draw_handler_add(draw_callback_3d, (self, context), 'WINDOW', 'POST_VIEW')\n context.window_manager.pdt_run_opengl = True",
"if PDT_OT_ModalDrawOperator._handle is not None:\n SpaceView3D.draw_handler_remove(PD... | <|body_start_0|>
if PDT_OT_ModalDrawOperator._handle is None:
PDT_OT_ModalDrawOperator._handle = SpaceView3D.draw_handler_add(draw_callback_3d, (self, context), 'WINDOW', 'POST_VIEW')
context.window_manager.pdt_run_opengl = True
<|end_body_0|>
<|body_start_1|>
if PDT_OT_ModalDra... | Show/Hide Pivot Point | PDT_OT_ModalDrawOperator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PDT_OT_ModalDrawOperator:
"""Show/Hide Pivot Point"""
def handle_add(self, context):
"""Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def handle_remove(sel... | stack_v2_sparse_classes_10k_train_002561 | 13,734 | permissive | [
{
"docstring": "Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: Nothing.",
"name": "handle_add",
"signature": "def handle_add(self, context)"
},
{
"docstring": "Remove Pivot Point Graphic if displayed. Not... | 3 | null | Implement the Python class `PDT_OT_ModalDrawOperator` described below.
Class description:
Show/Hide Pivot Point
Method signatures and docstrings:
- def handle_add(self, context): Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: ... | Implement the Python class `PDT_OT_ModalDrawOperator` described below.
Class description:
Show/Hide Pivot Point
Method signatures and docstrings:
- def handle_add(self, context): Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: ... | 4d5c304878c1e0018d97c1b07bcaa3981632265a | <|skeleton|>
class PDT_OT_ModalDrawOperator:
"""Show/Hide Pivot Point"""
def handle_add(self, context):
"""Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: Nothing."""
<|body_0|>
def handle_remove(sel... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PDT_OT_ModalDrawOperator:
"""Show/Hide Pivot Point"""
def handle_add(self, context):
"""Draw Pivot Point Graphic if not displayed. Note: Draws 7 element Pivot Point Graphic Args: context: Blender bpy.context instance. Returns: Nothing."""
if PDT_OT_ModalDrawOperator._handle is None:
... | the_stack_v2_python_sparse | src/bpy/3.6/scripts/addons/precision_drawing_tools/pdt_pivot_point.py | RnoB/3DVisualSwarm | train | 0 |
d4d0081531fe0da503738abd16ff13fff8f9bc23 | [
"if self == InfoPageActionControl.UNKNOWN:\n return False\nif self == InfoPageActionControl.DETACH:\n return target_uid is not None\nif self == InfoPageActionControl.DELETE:\n return True\nraise NotImplementedError()",
"if s == 'detach':\n return InfoPageActionControl.DETACH\nif s == 'delete':\n re... | <|body_start_0|>
if self == InfoPageActionControl.UNKNOWN:
return False
if self == InfoPageActionControl.DETACH:
return target_uid is not None
if self == InfoPageActionControl.DELETE:
return True
raise NotImplementedError()
<|end_body_0|>
<|body_start... | Enum to represent the type of action to be performed. | InfoPageActionControl | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :... | stack_v2_sparse_classes_10k_train_002562 | 7,451 | permissive | [
{
"docstring": "Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :raises NotImplementedError: if the validating action is not yet implemented",
"name": "is_argument_valid",
"signature": "def is_argument_va... | 4 | null | Implement the Python class `InfoPageActionControl` described below.
Class description:
Enum to represent the type of action to be performed.
Method signatures and docstrings:
- def is_argument_valid(self, target_uid) -> bool: Check if the argument for the action is valid. :param target_uid: UID of the profile action ... | Implement the Python class `InfoPageActionControl` described below.
Class description:
Enum to represent the type of action to be performed.
Method signatures and docstrings:
- def is_argument_valid(self, target_uid) -> bool: Check if the argument for the action is valid. :param target_uid: UID of the profile action ... | c7da1e91783dce3a2b71b955b3a22b68db9056cf | <|skeleton|>
class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class InfoPageActionControl:
"""Enum to represent the type of action to be performed."""
def is_argument_valid(self, target_uid) -> bool:
"""Check if the argument for the action is valid. :param target_uid: UID of the profile action target :return: if the argument for the action is valid :raises NotImp... | the_stack_v2_python_sparse | JellyBot/views/info/profile.py | RxJellyBot/Jelly-Bot | train | 5 |
fe8fb2713f503e8047df614596d39cf51a68a3d5 | [
"if annotation_file:\n if annotation_file.startswith('gs://'):\n _, local_val_json = tempfile.mkstemp(suffix='.json')\n tf.gfile.Remove(local_val_json)\n tf.gfile.Copy(annotation_file, local_val_json)\n atexit.register(tf.gfile.Remove, local_val_json)\n else:\n local_val_jso... | <|body_start_0|>
if annotation_file:
if annotation_file.startswith('gs://'):
_, local_val_json = tempfile.mkstemp(suffix='.json')
tf.gfile.Remove(local_val_json)
tf.gfile.Copy(annotation_file, local_val_json)
atexit.register(tf.gfile.Re... | LVIS evaluation metric class. | LVISEvaluator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LVISEvaluator:
"""LVIS evaluation metric class."""
def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False):
"""Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes dete... | stack_v2_sparse_classes_10k_train_002563 | 20,065 | permissive | [
{
"docstring": "Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from each image and push them to self.detections. The _evaluate() loads a JSON file in LVIS annotation format as the groundtruths and runs LVIS evaluation. Args: an... | 2 | null | Implement the Python class `LVISEvaluator` described below.
Class description:
LVIS evaluation metric class.
Method signatures and docstrings:
- def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): Constructs LVIS evaluation class. The class provides the interface t... | Implement the Python class `LVISEvaluator` described below.
Class description:
LVIS evaluation metric class.
Method signatures and docstrings:
- def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False): Constructs LVIS evaluation class. The class provides the interface t... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class LVISEvaluator:
"""LVIS evaluation metric class."""
def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False):
"""Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes dete... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LVISEvaluator:
"""LVIS evaluation metric class."""
def __init__(self, annotation_file, include_mask, need_rescale_bboxes=True, per_category_metrics=False):
"""Constructs LVIS evaluation class. The class provides the interface to metrics_fn in TPUEstimator. The _update_op() takes detections from e... | the_stack_v2_python_sparse | models/official/detection/evaluation/coco_evaluator.py | tensorflow/tpu | train | 5,627 |
8e6a0b28979fb257c95520192126fd5b03d53b6c | [
"if self.filters:\n category_filter = self.filters.get(str(field.category.id), None)\n if category_filter:\n field_filter = category_filter.pop(field.key, None)\n if field_filter:\n self.save()",
"self.where_clause = None\nif self.filters is not None:\n queries = []\n for key ... | <|body_start_0|>
if self.filters:
category_filter = self.filters.get(str(field.category.id), None)
if category_filter:
field_filter = category_filter.pop(field.key, None)
if field_filter:
self.save()
<|end_body_0|>
<|body_start_1|>
... | A mixin for filter. | FilterMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilterMixin:
"""A mixin for filter."""
def remove_filter_field(self, field):
"""Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category."""
<|body_0|>
def save(self, *args, **kwargs):
"""Over... | stack_v2_sparse_classes_10k_train_002564 | 1,197 | permissive | [
{
"docstring": "Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.",
"name": "remove_filter_field",
"signature": "def remove_filter_field(self, field)"
},
{
"docstring": "Overwrite `save` to implement integrity ensuran... | 2 | stack_v2_sparse_classes_30k_train_002575 | Implement the Python class `FilterMixin` described below.
Class description:
A mixin for filter.
Method signatures and docstrings:
- def remove_filter_field(self, field): Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.
- def save(self, *... | Implement the Python class `FilterMixin` described below.
Class description:
A mixin for filter.
Method signatures and docstrings:
- def remove_filter_field(self, field): Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category.
- def save(self, *... | 16d31b5207de9f699fc01054baad1fe65ad1c3ca | <|skeleton|>
class FilterMixin:
"""A mixin for filter."""
def remove_filter_field(self, field):
"""Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category."""
<|body_0|>
def save(self, *args, **kwargs):
"""Over... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FilterMixin:
"""A mixin for filter."""
def remove_filter_field(self, field):
"""Remove a field from the filter. Parameters ---------- field : geokey.categories.models.Field Represents the field of a category."""
if self.filters:
category_filter = self.filters.get(str(field.cat... | the_stack_v2_python_sparse | geokey/core/mixins.py | NeolithEra/geokey | train | 0 |
183370fde921c6500c31865d9ff4823138b107f8 | [
"args = dict(is_add=True, eid=LispEid.create_eid(eid, prefix_len), locator_set_name=locator_set_name, vni=int(vni))\ncmd = u'lisp_add_del_local_eid'\nerr_msg = f\"Failed to add local eid on host {node[u'host']}\"\nwith PapiSocketExecutor(node) as papi_exec:\n papi_exec.add(cmd, **args).get_reply(err_msg)",
"ar... | <|body_start_0|>
args = dict(is_add=True, eid=LispEid.create_eid(eid, prefix_len), locator_set_name=locator_set_name, vni=int(vni))
cmd = u'lisp_add_del_local_eid'
err_msg = f"Failed to add local eid on host {node[u'host']}"
with PapiSocketExecutor(node) as papi_exec:
papi_ex... | Class for Lisp local eid API. | LispLocalEid | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LispLocalEid:
"""Class for Lisp local eid API."""
def vpp_add_lisp_local_eid(node, locator_set_name, vni, eid, prefix_len=None):
"""Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_name: Name of the locator_set. :param vni: Vni value. :param... | stack_v2_sparse_classes_10k_train_002565 | 14,690 | permissive | [
{
"docstring": "Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_name: Name of the locator_set. :param vni: Vni value. :param eid: Eid value. :param prefix_len: Prefix len if the eid is IP address. :type node: dict :type locator_set_name: str :type vni: int :type eid: ... | 2 | stack_v2_sparse_classes_30k_train_002337 | Implement the Python class `LispLocalEid` described below.
Class description:
Class for Lisp local eid API.
Method signatures and docstrings:
- def vpp_add_lisp_local_eid(node, locator_set_name, vni, eid, prefix_len=None): Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_nam... | Implement the Python class `LispLocalEid` described below.
Class description:
Class for Lisp local eid API.
Method signatures and docstrings:
- def vpp_add_lisp_local_eid(node, locator_set_name, vni, eid, prefix_len=None): Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_nam... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class LispLocalEid:
"""Class for Lisp local eid API."""
def vpp_add_lisp_local_eid(node, locator_set_name, vni, eid, prefix_len=None):
"""Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_name: Name of the locator_set. :param vni: Vni value. :param... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class LispLocalEid:
"""Class for Lisp local eid API."""
def vpp_add_lisp_local_eid(node, locator_set_name, vni, eid, prefix_len=None):
"""Set lisp eid address on the VPP node in topology. :param node: VPP node. :param locator_set_name: Name of the locator_set. :param vni: Vni value. :param eid: Eid val... | the_stack_v2_python_sparse | resources/libraries/python/LispSetup.py | FDio/csit | train | 28 |
34cf7eaf13e5ddd7a3f842239df3205ec206b19b | [
"p_list = list(p)\np[0] = p[1]\np[0]['base_type'] = p[2]\np[0]['properties'] = {}\nif p[0]['base_type'] == 'ENUM':\n p[0]['properties']['values'] = p_list[4]",
"p_list = list(p)\np[0] = {}\nif '.' not in p_list:\n p[0]['schema'] = None\nelse:\n p[0]['schema'] = p[3]\np[0]['domain_name'] = p_list[-2]"
] | <|body_start_0|>
p_list = list(p)
p[0] = p[1]
p[0]['base_type'] = p[2]
p[0]['properties'] = {}
if p[0]['base_type'] == 'ENUM':
p[0]['properties']['values'] = p_list[4]
<|end_body_0|>
<|body_start_1|>
p_list = list(p)
p[0] = {}
if '.' not in p_... | Domain | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Domain:
def p_expression_domain_as(self, p: List) -> None:
"""expr : domain_name id LP pid RP"""
<|body_0|>
def p_domain_name(self, p: List) -> None:
"""domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id"""
... | stack_v2_sparse_classes_10k_train_002566 | 42,571 | permissive | [
{
"docstring": "expr : domain_name id LP pid RP",
"name": "p_expression_domain_as",
"signature": "def p_expression_domain_as(self, p: List) -> None"
},
{
"docstring": "domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id",
"name": "p_dom... | 2 | stack_v2_sparse_classes_30k_train_005599 | Implement the Python class `Domain` described below.
Class description:
Implement the Domain class.
Method signatures and docstrings:
- def p_expression_domain_as(self, p: List) -> None: expr : domain_name id LP pid RP
- def p_domain_name(self, p: List) -> None: domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DO... | Implement the Python class `Domain` described below.
Class description:
Implement the Domain class.
Method signatures and docstrings:
- def p_expression_domain_as(self, p: List) -> None: expr : domain_name id LP pid RP
- def p_domain_name(self, p: List) -> None: domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DO... | 8f69c9c3b58990f0d47dbe868fe4a572d51e2de7 | <|skeleton|>
class Domain:
def p_expression_domain_as(self, p: List) -> None:
"""expr : domain_name id LP pid RP"""
<|body_0|>
def p_domain_name(self, p: List) -> None:
"""domain_name : CREATE DOMAIN id AS | CREATE DOMAIN id DOT id AS | CREATE DOMAIN id DOT id | CREATE DOMAIN id"""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Domain:
def p_expression_domain_as(self, p: List) -> None:
"""expr : domain_name id LP pid RP"""
p_list = list(p)
p[0] = p[1]
p[0]['base_type'] = p[2]
p[0]['properties'] = {}
if p[0]['base_type'] == 'ENUM':
p[0]['properties']['values'] = p_list[4]
... | the_stack_v2_python_sparse | simple_ddl_parser/dialects/sql.py | bjmc/simple-ddl-parser | train | 0 | |
93c2a19630fc4ac0443167238cd4246ab2a8b58b | [
"super(CredentialDialog, self).__init__()\nself.askpassword = askpassword\nself.initUI(context)",
"self.formlayout = QtWidgets.QFormLayout(self)\nself.username_le = QtWidgets.QLineEdit(self)\nself.username_le.returnPressed.connect(self.accept)\nif self.askpassword:\n self.formlayout.addRow('Användarnamn:', sel... | <|body_start_0|>
super(CredentialDialog, self).__init__()
self.askpassword = askpassword
self.initUI(context)
<|end_body_0|>
<|body_start_1|>
self.formlayout = QtWidgets.QFormLayout(self)
self.username_le = QtWidgets.QLineEdit(self)
self.username_le.returnPressed.connect... | Asks for credentials. | CredentialDialog | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CredentialDialog:
"""Asks for credentials."""
def __init__(self, context='', askpassword=True):
"""Creates a dialog that asks for username and optionally password."""
<|body_0|>
def initUI(self, context):
"""Creates the UI widgets. context -- String to set as win... | stack_v2_sparse_classes_10k_train_002567 | 15,052 | permissive | [
{
"docstring": "Creates a dialog that asks for username and optionally password.",
"name": "__init__",
"signature": "def __init__(self, context='', askpassword=True)"
},
{
"docstring": "Creates the UI widgets. context -- String to set as windowtitle.",
"name": "initUI",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_000016 | Implement the Python class `CredentialDialog` described below.
Class description:
Asks for credentials.
Method signatures and docstrings:
- def __init__(self, context='', askpassword=True): Creates a dialog that asks for username and optionally password.
- def initUI(self, context): Creates the UI widgets. context --... | Implement the Python class `CredentialDialog` described below.
Class description:
Asks for credentials.
Method signatures and docstrings:
- def __init__(self, context='', askpassword=True): Creates a dialog that asks for username and optionally password.
- def initUI(self, context): Creates the UI widgets. context --... | b9aeca845d65d6de07b3dbef4dafccacc6a81cc4 | <|skeleton|>
class CredentialDialog:
"""Asks for credentials."""
def __init__(self, context='', askpassword=True):
"""Creates a dialog that asks for username and optionally password."""
<|body_0|>
def initUI(self, context):
"""Creates the UI widgets. context -- String to set as win... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class CredentialDialog:
"""Asks for credentials."""
def __init__(self, context='', askpassword=True):
"""Creates a dialog that asks for username and optionally password."""
super(CredentialDialog, self).__init__()
self.askpassword = askpassword
self.initUI(context)
def init... | the_stack_v2_python_sparse | passwordsafe.py | Teknologforeningen/svaksvat | train | 0 |
f163413944d747da568e3daa022813b03070f873 | [
"if not kwargs.get('obj_ids'):\n obj_model = facade.get_vlan_by_search(self.search)\n vlans = obj_model['query_set']\n only_main_property = False\nelse:\n obj_ids = kwargs['obj_ids'].split(';')\n vlans = facade.get_vlan_by_ids(obj_ids)\n obj_model = None\n only_main_property = True\nserializer_... | <|body_start_0|>
if not kwargs.get('obj_ids'):
obj_model = facade.get_vlan_by_search(self.search)
vlans = obj_model['query_set']
only_main_property = False
else:
obj_ids = kwargs['obj_ids'].split(';')
vlans = facade.get_vlan_by_ids(obj_ids)
... | VlanDBView | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VlanDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of vlans with details by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Creates list of vlans."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_10k_train_002568 | 6,313 | permissive | [
{
"docstring": "Returns a list of vlans with details by ids ou dict.",
"name": "get",
"signature": "def get(self, request, *args, **kwargs)"
},
{
"docstring": "Creates list of vlans.",
"name": "post",
"signature": "def post(self, request, *args, **kwargs)"
},
{
"docstring": "Upda... | 4 | stack_v2_sparse_classes_30k_train_004589 | Implement the Python class `VlanDBView` described below.
Class description:
Implement the VlanDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of vlans with details by ids ou dict.
- def post(self, request, *args, **kwargs): Creates list of vlans.
- def put(sel... | Implement the Python class `VlanDBView` described below.
Class description:
Implement the VlanDBView class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Returns a list of vlans with details by ids ou dict.
- def post(self, request, *args, **kwargs): Creates list of vlans.
- def put(sel... | eb27e1d977a1c4bb1fee8fb51b8d8050c64696d9 | <|skeleton|>
class VlanDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of vlans with details by ids ou dict."""
<|body_0|>
def post(self, request, *args, **kwargs):
"""Creates list of vlans."""
<|body_1|>
def put(self, request, *args, **kwargs):
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class VlanDBView:
def get(self, request, *args, **kwargs):
"""Returns a list of vlans with details by ids ou dict."""
if not kwargs.get('obj_ids'):
obj_model = facade.get_vlan_by_search(self.search)
vlans = obj_model['query_set']
only_main_property = False
... | the_stack_v2_python_sparse | networkapi/api_vlan/views/v3.py | globocom/GloboNetworkAPI | train | 86 | |
929415e28cd27f08856ade898c069d066e6a7851 | [
"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. | BfRuntimeServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
<|body_0|>
def Read(self, request, context):
"""Read one or more P4 entities from the target."... | stack_v2_sparse_classes_10k_train_002569 | 9,014 | permissive | [
{
"docstring": "Update one or more P4 entities on the target.",
"name": "Write",
"signature": "def Write(self, request, context)"
},
{
"docstring": "Read one or more P4 entities from the target.",
"name": "Read",
"signature": "def Read(self, request, context)"
},
{
"docstring": "... | 5 | stack_v2_sparse_classes_30k_train_002667 | Implement the Python class `BfRuntimeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Write(self, request, context): Update one or more P4 entities on the target.
- def Read(self, request, context): Read one or more P4 entit... | Implement the Python class `BfRuntimeServicer` described below.
Class description:
Missing associated documentation comment in .proto file.
Method signatures and docstrings:
- def Write(self, request, context): Update one or more P4 entities on the target.
- def Read(self, request, context): Read one or more P4 entit... | a9fea4d7e48de05e17b9da14e5c31455a9f00f9d | <|skeleton|>
class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
<|body_0|>
def Read(self, request, context):
"""Read one or more P4 entities from the target."... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BfRuntimeServicer:
"""Missing associated documentation comment in .proto file."""
def Write(self, request, context):
"""Update one or more P4 entities on the target."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise Not... | the_stack_v2_python_sparse | stamper_targets/Wedge100B65/bfrt_grpc/bfruntime_pb2_grpc.py | ralfkundel/P4STA | train | 27 |
9ea1c2746cd676d8a16df87e9b920ae9f6c52dd6 | [
"num_classes = 2\nseq_length = 4\nxlnet_base = _get_xlnet_base()\nxlnet_trainer_model = xlnet.XLNetClassifier(network=xlnet_base, num_classes=num_classes, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), summary_type='last', dropout_rate=0.1)\ninputs = dict(input_word_ids=tf.keras.layers.Input(shape=(seq... | <|body_start_0|>
num_classes = 2
seq_length = 4
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetClassifier(network=xlnet_base, num_classes=num_classes, initializer=tf.keras.initializers.RandomNormal(stddev=0.1), summary_type='last', dropout_rate=0.1)
inputs = dict... | XLNetClassifierTest | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class XLNetClassifierTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self, num_classes):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserial... | stack_v2_sparse_classes_10k_train_002570 | 13,124 | permissive | [
{
"docstring": "Validate that the Keras object can be created.",
"name": "test_xlnet_trainer",
"signature": "def test_xlnet_trainer(self)"
},
{
"docstring": "Validates that the Keras object can be invoked.",
"name": "test_xlnet_tensor_call",
"signature": "def test_xlnet_tensor_call(self,... | 3 | stack_v2_sparse_classes_30k_test_000174 | Implement the Python class `XLNetClassifierTest` described below.
Class description:
Implement the XLNetClassifierTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validate that the Keras object can be created.
- def test_xlnet_tensor_call(self, num_classes): Validates that the Keras objec... | Implement the Python class `XLNetClassifierTest` described below.
Class description:
Implement the XLNetClassifierTest class.
Method signatures and docstrings:
- def test_xlnet_trainer(self): Validate that the Keras object can be created.
- def test_xlnet_tensor_call(self, num_classes): Validates that the Keras objec... | 6fc53292b1d3ce3c0340ce724c2c11c77e663d27 | <|skeleton|>
class XLNetClassifierTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
<|body_0|>
def test_xlnet_tensor_call(self, num_classes):
"""Validates that the Keras object can be invoked."""
<|body_1|>
def test_serialize_deserial... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class XLNetClassifierTest:
def test_xlnet_trainer(self):
"""Validate that the Keras object can be created."""
num_classes = 2
seq_length = 4
xlnet_base = _get_xlnet_base()
xlnet_trainer_model = xlnet.XLNetClassifier(network=xlnet_base, num_classes=num_classes, initializer=tf.... | the_stack_v2_python_sparse | models/official/nlp/modeling/models/xlnet_test.py | aboerzel/German_License_Plate_Recognition | train | 34 | |
5eda071cd9233e924464d81ffef01b0d406a58b7 | [
"vals = []\n\ndef preorder(node):\n if node:\n vals.append(str(node.val))\n for child in node.children:\n preorder(child)\n vals.append('#')\npreorder(root)\nreturn ' '.join(vals)",
"if not data:\n return None\nstream = iter(data.split())\nval = int(next(stream))\nroot = Node... | <|body_start_0|>
vals = []
def preorder(node):
if node:
vals.append(str(node.val))
for child in node.children:
preorder(child)
vals.append('#')
preorder(root)
return ' '.join(vals)
<|end_body_0|>
<|body_sta... | Codec | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_10k_train_002571 | 1,297 | permissive | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def deserialize(self, ... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 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: Node :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype: Nod... | 3719f5cb059eefd66b83eb8ae990652f4b7fd124 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
vals = []
def preorder(node):
if node:
vals.append(str(node.val))
for child in node.children:
preorder(child)
... | the_stack_v2_python_sparse | Python3/0428-Serialize-and-Deserialize-N-ary-Tree/soln-1.py | wyaadarsh/LeetCode-Solutions | train | 0 | |
219ed1de8394893a3800d36cb6697bb83613d252 | [
"self.bits = 0.0\nif self.size < 1:\n return\nif self.max_value <= 0.0:\n raise ValueError(f'Invalid max value: {self!r}')\nmax_value = self.max_value / self.unit\navg = self.avg / self.unit\nself.bits += math.log(self.size * (self.size + 1), 2)\nif self.prev_avg is None:\n self.bits += math.log(max_value ... | <|body_start_0|>
self.bits = 0.0
if self.size < 1:
return
if self.max_value <= 0.0:
raise ValueError(f'Invalid max value: {self!r}')
max_value = self.max_value / self.unit
avg = self.avg / self.unit
self.bits += math.log(self.size * (self.size + 1)... | Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data itself is stored elsewhere. The coding needs to know the previous average, and a ma... | BitCountingStats | [
"GPL-1.0-or-later",
"CC-BY-4.0",
"Apache-2.0",
"LicenseRef-scancode-dco-1.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BitCountingStats:
"""Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data itself is stored elsewhere. The coding ... | stack_v2_sparse_classes_10k_train_002572 | 6,742 | permissive | [
{
"docstring": "Construct the stats object by computing from the values needed. The None values are allowed for stats for zero size data, but such stats can report arbitrary avg and max_value. Stats for nonzero size data cannot contain None, else ValueError is raised. The max_value needs to be numeric for nonze... | 2 | stack_v2_sparse_classes_30k_train_002901 | Implement the Python class `BitCountingStats` described below.
Class description:
Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data ... | Implement the Python class `BitCountingStats` described below.
Class description:
Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data ... | 947057d7310cd1602119258c6b82fbb25fe1b79d | <|skeleton|>
class BitCountingStats:
"""Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data itself is stored elsewhere. The coding ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BitCountingStats:
"""Class for statistics which include information content of a group. The information content is based on an assumption that the data consists of independent random values from a normal distribution. Instances are only statistics, the data itself is stored elsewhere. The coding needs to know... | the_stack_v2_python_sparse | resources/libraries/python/jumpavg/bit_counting_stats.py | FDio/csit | train | 28 |
eaeb84405f61cd96cef3f102fd390e44f2dd989e | [
"self.ensure_one()\nres = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'account_id': self.product_id.product_tmpl_id._get_product_accounts()['stock_input'].id, 'price_unit': self.price_unit, 'quantity': qty, 'uom_id': self.product_uom.id, 'product_id': self.product_id.id or False, 'i... | <|body_start_0|>
self.ensure_one()
res = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'account_id': self.product_id.product_tmpl_id._get_product_accounts()['stock_input'].id, 'price_unit': self.price_unit, 'quantity': qty, 'uom_id': self.product_uom.id, 'product_id': self... | PurchaseOrderLine | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
<|body_0|>
def invoice_line_create(self, invoice_id, qty):
"""Create an invoice line... | stack_v2_sparse_classes_10k_train_002573 | 6,989 | no_license | [
{
"docstring": "Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice",
"name": "_prepare_invoice_line",
"signature": "def _prepare_invoice_line(self, qty)"
},
{
"docstring": "Create an invoice line. The quantity to invoice can be... | 2 | stack_v2_sparse_classes_30k_train_005774 | Implement the Python class `PurchaseOrderLine` described below.
Class description:
Implement the PurchaseOrderLine class.
Method signatures and docstrings:
- def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice
- ... | Implement the Python class `PurchaseOrderLine` described below.
Class description:
Implement the PurchaseOrderLine class.
Method signatures and docstrings:
- def _prepare_invoice_line(self, qty): Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice
- ... | c355e18aeb3e7123fe184fcc7ec06485ab498343 | <|skeleton|>
class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
<|body_0|>
def invoice_line_create(self, invoice_id, qty):
"""Create an invoice line... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class PurchaseOrderLine:
def _prepare_invoice_line(self, qty):
"""Prepare the dict of values to create the new invoice line for a sales order line. :param qty: float quantity to invoice"""
self.ensure_one()
res = {'name': self.name, 'sequence': self.sequence, 'origin': self.order_id.name, 'a... | the_stack_v2_python_sparse | deliver_auto_invoice/models/purchase_order.py | rythe77/odoo11_customized | train | 5 | |
95262f2ab4e171626936426643c895fbd331eeeb | [
"mapper = {}\nleft = max_len = 0\nfor right, char in enumerate(s):\n if char in mapper:\n left = max(left, mapper[char] + 1)\n max_len = max(max_len, right - left + 1)\n mapper[char] = right\nreturn max_len",
"mapper = {}\nleft = max_len = 0\nfor right, char in enumerate(s):\n if char in mapper... | <|body_start_0|>
mapper = {}
left = max_len = 0
for right, char in enumerate(s):
if char in mapper:
left = max(left, mapper[char] + 1)
max_len = max(max_len, right - left + 1)
mapper[char] = right
return max_len
<|end_body_0|>
<|body_s... | String | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
<|body_0|>
def longest_substring_without_repetition(self, s: str) -> int:
"""Approach:... | stack_v2_sparse_classes_10k_train_002574 | 3,182 | no_license | [
{
"docstring": "Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:",
"name": "longest_substring_without_repetition_",
"signature": "def longest_substring_without_repetition_(self, s: str) -> int"
},
{
"docstring": "Approach: Sliding Window Time... | 4 | null | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_substring_without_repetition_(self, s: str) -> int: Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:
- def longest_s... | Implement the Python class `String` described below.
Class description:
Implement the String class.
Method signatures and docstrings:
- def longest_substring_without_repetition_(self, s: str) -> int: Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:
- def longest_s... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
<|body_0|>
def longest_substring_without_repetition(self, s: str) -> int:
"""Approach:... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class String:
def longest_substring_without_repetition_(self, s: str) -> int:
"""Approach: Sliding Window using max fun Time Complexity: O(n) Space Complexity: O(m) :param s: :return:"""
mapper = {}
left = max_len = 0
for right, char in enumerate(s):
if char in mapper:
... | the_stack_v2_python_sparse | revisited/math_and_strings/strings/longest_substring_without_repeating_chars.py | Shiv2157k/leet_code | train | 1 | |
be318ebe530e734eed8edd9677075437a2022935 | [
"self.fp = fp\nself._line_len = 0\nself.tell = fp.tell",
"try:\n pos = s.index('\\n')\n rpos = s.rindex('\\n')\nexcept ValueError:\n pos = len(s)\n rpos = None\nif self._line_len + pos > self.TARGET_LINE_LEN - 1:\n self.fp.write('\\n ')\n self._line_len = 1\nself.fp.write(s)\nif rpos is not None... | <|body_start_0|>
self.fp = fp
self._line_len = 0
self.tell = fp.tell
<|end_body_0|>
<|body_start_1|>
try:
pos = s.index('\n')
rpos = s.rindex('\n')
except ValueError:
pos = len(s)
rpos = None
if self._line_len + pos > self.... | _WidthLimitedFile | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying ... | stack_v2_sparse_classes_10k_train_002575 | 12,988 | permissive | [
{
"docstring": "Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying the line length requirement of LP files for all inputs. This design h... | 2 | stack_v2_sparse_classes_30k_train_002961 | Implement the Python class `_WidthLimitedFile` described below.
Class description:
Implement the _WidthLimitedFile class.
Method signatures and docstrings:
- def __init__(self, fp: typing.TextIO): Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done ... | Implement the Python class `_WidthLimitedFile` described below.
Class description:
Implement the _WidthLimitedFile class.
Method signatures and docstrings:
- def __init__(self, fp: typing.TextIO): Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done ... | 8433f221a1e79101e1db0d80968ab5a2f59b865d | <|skeleton|>
class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying ... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class _WidthLimitedFile:
def __init__(self, fp: typing.TextIO):
"""Wrap a file-like object to provide a custom `write` method that inserts line breaks into the output stream. This is done to generate attractive output (e.g. lines that are not extremely short) for most inputs, while satisfying the line lengt... | the_stack_v2_python_sparse | dimod/lp.py | dwavesystems/dimod | train | 118 | |
53df62dd3d3b94ed5e2f30602c9400c8a9033310 | [
"self.nums, prev = (list(), 0)\nfor num in nums:\n prev += num\n self.nums.append(prev)",
"if i > 0:\n return self.nums[j] - self.nums[i - 1]\nelse:\n return self.nums[j]"
] | <|body_start_0|>
self.nums, prev = (list(), 0)
for num in nums:
prev += num
self.nums.append(prev)
<|end_body_0|>
<|body_start_1|>
if i > 0:
return self.nums[j] - self.nums[i - 1]
else:
return self.nums[j]
<|end_body_1|>
| NumArray | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.nums, prev = (list(), 0)
for num in nums:
... | stack_v2_sparse_classes_10k_train_002576 | 1,007 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
"name": "sumRange",
"signature": "def sumRange(self, i, j)"
}
] | 2 | null | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int | Implement the Python class `NumArray` described below.
Class description:
Implement the NumArray class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def sumRange(self, i, j): :type i: int :type j: int :rtype: int
<|skeleton|>
class NumArray:
def __init__(self, nums):
... | 6e4894c2d80413b13dc247d1783afd709ad984c8 | <|skeleton|>
class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NumArray:
def __init__(self, nums):
""":type nums: List[int]"""
self.nums, prev = (list(), 0)
for num in nums:
prev += num
self.nums.append(prev)
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
if i > 0:
ret... | the_stack_v2_python_sparse | leet_code303.py | tejamupparaju/LeetCode_Python | train | 2 | |
c3a23ee226772d5c6d815ae7ca121c06ad347718 | [
"used = set()\n\ndef dfs(start):\n count = 0\n while nums[start] not in used:\n start = nums[start]\n used.add(start)\n count += 1\n return count\nself.m = 0\nfor i in nums:\n self.m = max(dfs(i), self.m)\nreturn self.m",
"n = len(nums)\nvisited = [False] * n\nres = 0\nfor i in nu... | <|body_start_0|>
used = set()
def dfs(start):
count = 0
while nums[start] not in used:
start = nums[start]
used.add(start)
count += 1
return count
self.m = 0
for i in nums:
self.m = max(dfs(i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def arrayNesting(self, nums):
""":type nums: List[int] :rtype: int 106MS"""
<|body_0|>
def arrayNesting_1(self, nums):
""":type nums: List[int] :rtype: int 82MS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
used = set()
def dfs(... | stack_v2_sparse_classes_10k_train_002577 | 1,863 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 106MS",
"name": "arrayNesting",
"signature": "def arrayNesting(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 82MS",
"name": "arrayNesting_1",
"signature": "def arrayNesting_1(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000834 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arrayNesting(self, nums): :type nums: List[int] :rtype: int 106MS
- def arrayNesting_1(self, nums): :type nums: List[int] :rtype: int 82MS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def arrayNesting(self, nums): :type nums: List[int] :rtype: int 106MS
- def arrayNesting_1(self, nums): :type nums: List[int] :rtype: int 82MS
<|skeleton|>
class Solution:
... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def arrayNesting(self, nums):
""":type nums: List[int] :rtype: int 106MS"""
<|body_0|>
def arrayNesting_1(self, nums):
""":type nums: List[int] :rtype: int 82MS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def arrayNesting(self, nums):
""":type nums: List[int] :rtype: int 106MS"""
used = set()
def dfs(start):
count = 0
while nums[start] not in used:
start = nums[start]
used.add(start)
count += 1
... | the_stack_v2_python_sparse | ArrayNesting_MID_565.py | 953250587/leetcode-python | train | 2 | |
ea97491740fdb756629ae14602b1db028a3c93fa | [
"leoTkinterDialog.__init__(self, title, resizeable)\nself.text = text\nself.createTopFrame()\nself.top.bind('<Key>', self.onKey)\nif message:\n self.createMessageFrame(message)\nbuttons = ({'text': text, 'command': self.okButton, 'default': True},)\nself.createButtons(buttons)",
"ch = event.char.lower()\nif ch... | <|body_start_0|>
leoTkinterDialog.__init__(self, title, resizeable)
self.text = text
self.createTopFrame()
self.top.bind('<Key>', self.onKey)
if message:
self.createMessageFrame(message)
buttons = ({'text': text, 'command': self.okButton, 'default': True},)
... | A class that creates a Tkinter dialog with a single OK button. | tkinterAskOk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class tkinterAskOk:
"""A class that creates a Tkinter dialog with a single OK button."""
def __init__(self, title, message=None, text='Ok', resizeable=False):
"""Create a dialog with one button"""
<|body_0|>
def onKey(self, event):
"""Handle Key events in askOk dialogs... | stack_v2_sparse_classes_10k_train_002578 | 25,997 | no_license | [
{
"docstring": "Create a dialog with one button",
"name": "__init__",
"signature": "def __init__(self, title, message=None, text='Ok', resizeable=False)"
},
{
"docstring": "Handle Key events in askOk dialogs.",
"name": "onKey",
"signature": "def onKey(self, event)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000383 | Implement the Python class `tkinterAskOk` described below.
Class description:
A class that creates a Tkinter dialog with a single OK button.
Method signatures and docstrings:
- def __init__(self, title, message=None, text='Ok', resizeable=False): Create a dialog with one button
- def onKey(self, event): Handle Key ev... | Implement the Python class `tkinterAskOk` described below.
Class description:
A class that creates a Tkinter dialog with a single OK button.
Method signatures and docstrings:
- def __init__(self, title, message=None, text='Ok', resizeable=False): Create a dialog with one button
- def onKey(self, event): Handle Key ev... | 28c22721e1bc313c120a8a6c288893bc566a5c67 | <|skeleton|>
class tkinterAskOk:
"""A class that creates a Tkinter dialog with a single OK button."""
def __init__(self, title, message=None, text='Ok', resizeable=False):
"""Create a dialog with one button"""
<|body_0|>
def onKey(self, event):
"""Handle Key events in askOk dialogs... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class tkinterAskOk:
"""A class that creates a Tkinter dialog with a single OK button."""
def __init__(self, title, message=None, text='Ok', resizeable=False):
"""Create a dialog with one button"""
leoTkinterDialog.__init__(self, title, resizeable)
self.text = text
self.createTop... | the_stack_v2_python_sparse | Projects/jyleo/src/leoTkinterDialog.py | leo-editor/leo-editor-contrib | train | 6 |
9821d940be97e381ae7302beef25763b15159b80 | [
"if password is None or len(password) == 0:\n raise InvalidPasswordLengthError(_('Input password has invalid length.'))\ndecrypted_password = password\nis_encrypted = options.get('is_encrypted', False)\nif is_encrypted is True:\n decrypted_password = encryption_services.decrypt(password)\nhashed_password = ha... | <|body_start_0|>
if password is None or len(password) == 0:
raise InvalidPasswordLengthError(_('Input password has invalid length.'))
decrypted_password = password
is_encrypted = options.get('is_encrypted', False)
if is_encrypted is True:
decrypted_password = encr... | security manager class. | SecurityManager | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SecurityManager:
"""security manager class."""
def get_password_hash(self, password, **options):
"""gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that given password is encrypted. defaults to False if not provide... | stack_v2_sparse_classes_10k_train_002579 | 1,861 | permissive | [
{
"docstring": "gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that given password is encrypted. defaults to False if not provided. :raises InvalidPasswordLengthError: invalid password length error. :rtype: str",
"name": "get_password_ha... | 2 | null | Implement the Python class `SecurityManager` described below.
Class description:
security manager class.
Method signatures and docstrings:
- def get_password_hash(self, password, **options): gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that give... | Implement the Python class `SecurityManager` described below.
Class description:
security manager class.
Method signatures and docstrings:
- def get_password_hash(self, password, **options): gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that give... | 9d4776498225de4f3d16a4600b5b19212abe8562 | <|skeleton|>
class SecurityManager:
"""security manager class."""
def get_password_hash(self, password, **options):
"""gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that given password is encrypted. defaults to False if not provide... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class SecurityManager:
"""security manager class."""
def get_password_hash(self, password, **options):
"""gets the given password's hash. :param str password: password to get it's hash. :keyword bool is_encrypted: specifies that given password is encrypted. defaults to False if not provided. :raises In... | the_stack_v2_python_sparse | src/pyrin/security/manager.py | mononobi/pyrin | train | 20 |
c3f47c0ac5b6c2f827576ccf4bbdd145f2cf0d45 | [
"user = get_current_user()\nif not data_source_id:\n return json_response(message='参数错误', status=400)\ndata_source = db.session.query(DataSource).filter(DataSource.id == data_source_id).first()\norg = org_exists(data_source.org_id)\nif not org:\n return json_response(message=f'组织ID错误', status=403)\nstaff = db... | <|body_start_0|>
user = get_current_user()
if not data_source_id:
return json_response(message='参数错误', status=400)
data_source = db.session.query(DataSource).filter(DataSource.id == data_source_id).first()
org = org_exists(data_source.org_id)
if not org:
r... | DataSourceModifyResource | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSourceModifyResource:
def delete(self, data_source_id):
"""删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) examples: response: {"data": null, "message": "添加成功"}"""
<|body_0|>
def put(self, data_source_id, **kwa... | stack_v2_sparse_classes_10k_train_002580 | 9,491 | permissive | [
{
"docstring": "删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) examples: response: {\"data\": null, \"message\": \"添加成功\"}",
"name": "delete",
"signature": "def delete(self, data_source_id)"
},
{
"docstring": "修改数据源 --- tags: - 数据源 pa... | 2 | stack_v2_sparse_classes_30k_train_005200 | Implement the Python class `DataSourceModifyResource` described below.
Class description:
Implement the DataSourceModifyResource class.
Method signatures and docstrings:
- def delete(self, data_source_id): 删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) exa... | Implement the Python class `DataSourceModifyResource` described below.
Class description:
Implement the DataSourceModifyResource class.
Method signatures and docstrings:
- def delete(self, data_source_id): 删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) exa... | de894e8f8c163cb5aafe360dc146d1a4ded20ddb | <|skeleton|>
class DataSourceModifyResource:
def delete(self, data_source_id):
"""删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) examples: response: {"data": null, "message": "添加成功"}"""
<|body_0|>
def put(self, data_source_id, **kwa... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class DataSourceModifyResource:
def delete(self, data_source_id):
"""删除数据源 --- tags: - 数据源 parameters: responses: 200: description: A list of colors (may be filtered by palette) examples: response: {"data": null, "message": "添加成功"}"""
user = get_current_user()
if not data_source_id:
... | the_stack_v2_python_sparse | arrplat/resources/data_source/views.py | zhengdeding/tefact-engine | train | 0 | |
3a17d5c7c623b19132abad782912d51801a6d057 | [
"dp = [-1] * (target + 1)\ndp[0] = 1\n\ndef helper(target):\n if dp[target] != -1:\n return dp[target]\n res = 0\n for i in range(len(nums)):\n if target >= nums[i]:\n res += helper(target - nums[i])\n dp[target] = res\n return res\nreturn helper(target)",
"dp = [0] * (targ... | <|body_start_0|>
dp = [-1] * (target + 1)
dp[0] = 1
def helper(target):
if dp[target] != -1:
return dp[target]
res = 0
for i in range(len(nums)):
if target >= nums[i]:
res += helper(target - nums[i])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def combinationSum4DP(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_10k_train_002581 | 2,101 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "combinationSum4",
"signature": "def combinationSum4(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "combinationSum4DP",
"signature": "def combinationSum4D... | 2 | stack_v2_sparse_classes_30k_train_003782 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def combinationSum4DP(self, nums, target): :type nums: List[int] :type target: int ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combinationSum4(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def combinationSum4DP(self, nums, target): :type nums: List[int] :type target: int ... | 810575368ecffa97677bdb51744d1f716140bbb1 | <|skeleton|>
class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def combinationSum4DP(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def combinationSum4(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
dp = [-1] * (target + 1)
dp[0] = 1
def helper(target):
if dp[target] != -1:
return dp[target]
res = 0
for i in range... | the_stack_v2_python_sparse | C/CombinationSumIV.py | bssrdf/pyleet | train | 2 | |
8ebb020c43dfdd23c350639369c67e66cba91f43 | [
"self.body_dict = body_dict\nself.file_s3_uri = file_s3_uri\nself.kms_key = kms_key\nself.session = sagemaker_session",
"if new_save_location_s3_uri is not None:\n self.file_s3_uri = new_save_location_s3_uri\nreturn s3.S3Uploader.upload_string_as_file_body(body=json.dumps(self.body_dict), desired_s3_uri=self.f... | <|body_start_0|>
self.body_dict = body_dict
self.file_s3_uri = file_s3_uri
self.kms_key = kms_key
self.session = sagemaker_session
<|end_body_0|>
<|body_start_1|>
if new_save_location_s3_uri is not None:
self.file_s3_uri = new_save_location_s3_uri
return s3.S... | Represents a file with a body and an S3 uri. | ModelMonitoringFile | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON fi... | stack_v2_sparse_classes_10k_train_002582 | 20,253 | permissive | [
{
"docstring": "Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON file. kms_key (str): The kms key to be used to decrypt the file in S3. sagemaker_session (sagemaker.session.Session): A SageMaker Session object, used for SageMa... | 2 | null | Implement the Python class `ModelMonitoringFile` described below.
Class description:
Represents a file with a body and an S3 uri.
Method signatures and docstrings:
- def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session): Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of... | Implement the Python class `ModelMonitoringFile` described below.
Class description:
Represents a file with a body and an S3 uri.
Method signatures and docstrings:
- def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session): Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of... | 8d5d7fd8ae1a917ed3e2b988d5e533bce244fd85 | <|skeleton|>
class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON fi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ModelMonitoringFile:
"""Represents a file with a body and an S3 uri."""
def __init__(self, body_dict, file_s3_uri, kms_key, sagemaker_session):
"""Initializes a file with a body and an S3 uri. Args: body_dict (str): The body of the JSON file. file_s3_uri (str): The uri of the JSON file. kms_key (... | the_stack_v2_python_sparse | src/sagemaker/model_monitor/monitoring_files.py | aws/sagemaker-python-sdk | train | 2,050 |
896d982665ddacfd00e271fcae2e6ee926006087 | [
"args = self._gcloud_command\nlogging.info('Testapp sent: %s', ' '.join(args))\nresult = subprocess.run(args=args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False)\nlogging.info('Finished: %s\\n%s', ' '.join(args), result.stdout)\nif result.returncode:\n logging.error('gCloud returned no... | <|body_start_0|>
args = self._gcloud_command
logging.info('Testapp sent: %s', ' '.join(args))
result = subprocess.run(args=args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False)
logging.info('Finished: %s\n%s', ' '.join(args), result.stdout)
if result.ret... | Holds data related to the testing of one testapp. | Test | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test:
"""Holds data related to the testing of one testapp."""
def run(self):
"""Send the testapp to FTL for testing and wait for it to finish."""
<|body_0|>
def _gcloud_command(self):
"""Returns the args to send this testapp to FTL on the command line."""
... | stack_v2_sparse_classes_10k_train_002583 | 11,722 | permissive | [
{
"docstring": "Send the testapp to FTL for testing and wait for it to finish.",
"name": "run",
"signature": "def run(self)"
},
{
"docstring": "Returns the args to send this testapp to FTL on the command line.",
"name": "_gcloud_command",
"signature": "def _gcloud_command(self)"
},
{... | 3 | null | Implement the Python class `Test` described below.
Class description:
Holds data related to the testing of one testapp.
Method signatures and docstrings:
- def run(self): Send the testapp to FTL for testing and wait for it to finish.
- def _gcloud_command(self): Returns the args to send this testapp to FTL on the com... | Implement the Python class `Test` described below.
Class description:
Holds data related to the testing of one testapp.
Method signatures and docstrings:
- def run(self): Send the testapp to FTL for testing and wait for it to finish.
- def _gcloud_command(self): Returns the args to send this testapp to FTL on the com... | 2cb4b45dd14a230aa0e800042e893f8dfb23beda | <|skeleton|>
class Test:
"""Holds data related to the testing of one testapp."""
def run(self):
"""Send the testapp to FTL for testing and wait for it to finish."""
<|body_0|>
def _gcloud_command(self):
"""Returns the args to send this testapp to FTL on the command line."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Test:
"""Holds data related to the testing of one testapp."""
def run(self):
"""Send the testapp to FTL for testing and wait for it to finish."""
args = self._gcloud_command
logging.info('Testapp sent: %s', ' '.join(args))
result = subprocess.run(args=args, stdout=subproce... | the_stack_v2_python_sparse | MY_REPOS/misc-experiments/_FIREBFIRE/firebase-unity-sdk/scripts/gha/test_lab.py | bgoonz/UsefulResourceRepo2.0 | train | 10 |
6fa0e727342da59ddf1910e47a2e3312a0cfb782 | [
"self.config_entry = config_entry\nself.data = dict(self.config_entry.data)\nself._all_region_codes_sorted: dict[str, str] = {}\nself.regions: dict[str, dict[str, Any]] = {}\nfor name in CONST_REGIONS:\n self.regions[name] = {}\n if name not in self.data:\n self.data[name] = []",
"errors: dict[str, A... | <|body_start_0|>
self.config_entry = config_entry
self.data = dict(self.config_entry.data)
self._all_region_codes_sorted: dict[str, str] = {}
self.regions: dict[str, dict[str, Any]] = {}
for name in CONST_REGIONS:
self.regions[name] = {}
if name not in sel... | Handle a option flow for nut. | OptionsFlowHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OptionsFlowHandler:
"""Handle a option flow for nut."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Handle options flow."""
<|body_1|>... | stack_v2_sparse_classes_10k_train_002584 | 9,354 | permissive | [
{
"docstring": "Initialize options flow.",
"name": "__init__",
"signature": "def __init__(self, config_entry: config_entries.ConfigEntry) -> None"
},
{
"docstring": "Handle options flow.",
"name": "async_step_init",
"signature": "async def async_step_init(self, user_input=None)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000099 | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle a option flow for nut.
Method signatures and docstrings:
- def __init__(self, config_entry: config_entries.ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input=None): Handle options flow. | Implement the Python class `OptionsFlowHandler` described below.
Class description:
Handle a option flow for nut.
Method signatures and docstrings:
- def __init__(self, config_entry: config_entries.ConfigEntry) -> None: Initialize options flow.
- async def async_step_init(self, user_input=None): Handle options flow.
... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class OptionsFlowHandler:
"""Handle a option flow for nut."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
<|body_0|>
async def async_step_init(self, user_input=None):
"""Handle options flow."""
<|body_1|>... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OptionsFlowHandler:
"""Handle a option flow for nut."""
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
"""Initialize options flow."""
self.config_entry = config_entry
self.data = dict(self.config_entry.data)
self._all_region_codes_sorted: dict[str, s... | the_stack_v2_python_sparse | homeassistant/components/nina/config_flow.py | home-assistant/core | train | 35,501 |
0eb89f9958d583727ed838f03b7d621dacf19dca | [
"super(StageToRedshiftOperator, self).__init__(*args, **kwargs)\nself.arn = arn\nself.aws_credentials_id = aws_credentials_id\nself.conn_id = conn_id\nself.execution_date = kwargs.get('execution_date')\nself.jsonformat = jsonformat\nself.s3_bucket = s3_bucket\nself.s3_key = s3_key\nself.region = region\nself.table ... | <|body_start_0|>
super(StageToRedshiftOperator, self).__init__(*args, **kwargs)
self.arn = arn
self.aws_credentials_id = aws_credentials_id
self.conn_id = conn_id
self.execution_date = kwargs.get('execution_date')
self.jsonformat = jsonformat
self.s3_bucket = s3_b... | Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM. | StageToRedshiftOperator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StageToRedshiftOperator:
"""Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM."""
def __init__(self, arn='', aws_credentials_id='', conn_id='', reg... | stack_v2_sparse_classes_10k_train_002585 | 3,004 | no_license | [
{
"docstring": "Args: arn (str): name of ARN role assumed by the Redshift cluster aws_credentials_id (str): AWS credentials in Airflow s3_bucket (str): path to file(s) s3_key (str): path to file(s) conn_id (str): Redshift connection ID in Airflow region (str): AWS region table (str): Redshift table name **kwarg... | 2 | stack_v2_sparse_classes_30k_train_001987 | Implement the Python class `StageToRedshiftOperator` described below.
Class description:
Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.
Method signatures and docstrings:... | Implement the Python class `StageToRedshiftOperator` described below.
Class description:
Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM.
Method signatures and docstrings:... | ec7f881b6e11d7e3294176128290fdd1ad684fc0 | <|skeleton|>
class StageToRedshiftOperator:
"""Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM."""
def __init__(self, arn='', aws_credentials_id='', conn_id='', reg... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StageToRedshiftOperator:
"""Copy Data from S3 onto Redshift Props: - arn, path, conn_id, region, table: see __init__ docstring - qf_truncate: SQL to TRUNCATE the table. Qf means Query Formatted. - qf_copy: SQL to COPY FROM."""
def __init__(self, arn='', aws_credentials_id='', conn_id='', region='', s3_bu... | the_stack_v2_python_sparse | p5_pipeline_airflow/airflowcode/plugins/operators/stage_redshift.py | ogierpaul/Udacity-Data-Engineer-NanoDegree | train | 1 |
c8139875b737aa6b776a36d2c056ddf6f4ea052a | [
"self.v1 = v1\nself.v2 = v2\nself.lenv1 = len(v1)\nself.lenv2 = len(v2)\nself.min2len = 2 * min(len(v1), len(v2))\nself.alllen = len(v1) + len(v2)\nself.cnt = 0\nself.pos = 0\nif len(v1) > len(v2):\n self.remainlist = v1[len(v2):len(v1)]\nelse:\n self.remainlist = v2[len(v1):len(v2)]\nself.remaincnt = 0",
"... | <|body_start_0|>
self.v1 = v1
self.v2 = v2
self.lenv1 = len(v1)
self.lenv2 = len(v2)
self.min2len = 2 * min(len(v1), len(v2))
self.alllen = len(v1) + len(v2)
self.cnt = 0
self.pos = 0
if len(v1) > len(v2):
self.remainlist = v1[len(v2):l... | ZigzagIterator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k_train_002586 | 1,340 | no_license | [
{
"docstring": "Initialize your data structure here. :type v1: List[int] :type v2: List[int]",
"name": "__init__",
"signature": "def __init__(self, v1, v2)"
},
{
"docstring": ":rtype: int",
"name": "next",
"signature": "def next(self)"
},
{
"docstring": ":rtype: bool",
"name"... | 3 | stack_v2_sparse_classes_30k_train_005451 | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | Implement the Python class `ZigzagIterator` described below.
Class description:
Implement the ZigzagIterator class.
Method signatures and docstrings:
- def __init__(self, v1, v2): Initialize your data structure here. :type v1: List[int] :type v2: List[int]
- def next(self): :rtype: int
- def hasNext(self): :rtype: bo... | cd0341341a0216ac39850727804411e4cf5e4a67 | <|skeleton|>
class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
<|body_0|>
def next(self):
""":rtype: int"""
<|body_1|>
def hasNext(self):
""":rtype: bool"""
<|body_2|>
<|end... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ZigzagIterator:
def __init__(self, v1, v2):
"""Initialize your data structure here. :type v1: List[int] :type v2: List[int]"""
self.v1 = v1
self.v2 = v2
self.lenv1 = len(v1)
self.lenv2 = len(v2)
self.min2len = 2 * min(len(v1), len(v2))
self.alllen = len(... | the_stack_v2_python_sparse | 281. Zigzag Iterator_google.py | cclain/LeetCode-Problem-Solution | train | 0 | |
ddf2baa5a550fa6ca0af7901032aefe2bab0d429 | [
"self.write_root(root)\nfor child in root.children():\n n = child.level()\n for p in child.self_and_subtree():\n if g.app.force_at_auto_sentinels:\n self.put_node_sentinel(p, '#')\n indent = '\\t' * (p.level() - n)\n self.put('%s%s' % (indent, p.h))\n for s in p.b.splitl... | <|body_start_0|>
self.write_root(root)
for child in root.children():
n = child.level()
for p in child.self_and_subtree():
if g.app.force_at_auto_sentinels:
self.put_node_sentinel(p, '#')
indent = '\t' * (p.level() - n)
... | The writer class for .otl files. | OtlWriter | [
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OtlWriter:
"""The writer class for .otl files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-otl node."""
<|body_0|>
def write_root(self, root: Position) -> None:
"""Write the root @auto-org node."""
<|body_1|>
<|... | stack_v2_sparse_classes_10k_train_002587 | 1,620 | permissive | [
{
"docstring": "Write all the *descendants* of an @auto-otl node.",
"name": "write",
"signature": "def write(self, root: Position) -> None"
},
{
"docstring": "Write the root @auto-org node.",
"name": "write_root",
"signature": "def write_root(self, root: Position) -> None"
}
] | 2 | null | Implement the Python class `OtlWriter` described below.
Class description:
The writer class for .otl files.
Method signatures and docstrings:
- def write(self, root: Position) -> None: Write all the *descendants* of an @auto-otl node.
- def write_root(self, root: Position) -> None: Write the root @auto-org node. | Implement the Python class `OtlWriter` described below.
Class description:
The writer class for .otl files.
Method signatures and docstrings:
- def write(self, root: Position) -> None: Write all the *descendants* of an @auto-otl node.
- def write_root(self, root: Position) -> None: Write the root @auto-org node.
<|s... | a3f6c3ebda805dc40cd93123948f153a26eccee5 | <|skeleton|>
class OtlWriter:
"""The writer class for .otl files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-otl node."""
<|body_0|>
def write_root(self, root: Position) -> None:
"""Write the root @auto-org node."""
<|body_1|>
<|... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class OtlWriter:
"""The writer class for .otl files."""
def write(self, root: Position) -> None:
"""Write all the *descendants* of an @auto-otl node."""
self.write_root(root)
for child in root.children():
n = child.level()
for p in child.self_and_subtree():
... | the_stack_v2_python_sparse | leo/plugins/writers/otl.py | leo-editor/leo-editor | train | 1,671 |
0341adbcc9667e041ccd24776d3d8b1a0d8eb714 | [
"super().__init__(**kwargs)\nself.alpha = alpha\nself.gamma = gamma\nself.label_smoothing = label_smoothing",
"normalizer, y_true = y\nalpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)\ngamma = tf.convert_to_tensor(self.gamma, dtype=y_pred.dtype)\npositive_label_mask = tf.equal(y_true, 1.0)\nnegative_p... | <|body_start_0|>
super().__init__(**kwargs)
self.alpha = alpha
self.gamma = gamma
self.label_smoothing = label_smoothing
<|end_body_0|>
<|body_start_1|>
normalizer, y_true = y
alpha = tf.convert_to_tensor(self.alpha, dtype=y_pred.dtype)
gamma = tf.convert_to_tens... | Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r = gamma, and p_t = sigmod(x) for positive sa... | StableFocalLoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r =... | stack_v2_sparse_classes_10k_train_002588 | 17,443 | permissive | [
{
"docstring": "Initialize focal loss. Args: alpha: A float32 scalar multiplying alpha to the loss from positive examples and (1-alpha) to the loss from negative examples. gamma: A float32 scalar modulating loss from hard and easy examples. label_smoothing: Float in [0, 1]. If > `0` then smooth the labels. **kw... | 2 | null | Implement the Python class `StableFocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For br... | Implement the Python class `StableFocalLoss` described below.
Class description:
Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For br... | a5388a45f71a949639b35cc5b990bd130d2d8164 | <|skeleton|>
class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r =... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class StableFocalLoss:
"""Compute the focal loss between `logits` and the golden `target` values. Focal loss = -(1-pt)^gamma * log(pt) where pt is the probability of being classified to the true class. Below are comments/derivations for computing modulator. For brevity, let x = logits, z = targets, r = gamma, and p... | the_stack_v2_python_sparse | TensorFlow2/Detection/Efficientdet/utils/train_lib.py | NVIDIA/DeepLearningExamples | train | 11,838 |
c20cf7df1dd74892db6cac5698b0ac339e9c016d | [
"self.height = height\nself.width = width\nself.channels = channels\nself.discount = discount\nself.actions = actions\nself.env = env\nself.loss = loss\nself.epoch_num = 0\nself.model_dir = model_dir\nself.max_reward = 0\nself.cur_reward = 0\nself.reward_tensor = K.variable(value=0)\nif model_dir is not None:\n ... | <|body_start_0|>
self.height = height
self.width = width
self.channels = channels
self.discount = discount
self.actions = actions
self.env = env
self.loss = loss
self.epoch_num = 0
self.model_dir = model_dir
self.max_reward = 0
self... | Agent object which initalizes and trains the keras model. | Agent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
"""Agent object which initalizes and trains the keras model."""
def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None):
"""Initializes the parameters of the model. Args: height: Height of the image width: Wi... | stack_v2_sparse_classes_10k_train_002589 | 7,927 | permissive | [
{
"docstring": "Initializes the parameters of the model. Args: height: Height of the image width: Width of the image channels: Number of channels, history of past frame discount: Discount_Factor for Q Learning update",
"name": "__init__",
"signature": "def __init__(self, actions, height=80, width=80, ch... | 5 | null | Implement the Python class `Agent` described below.
Class description:
Agent object which initalizes and trains the keras model.
Method signatures and docstrings:
- def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): Initializes the parameters ... | Implement the Python class `Agent` described below.
Class description:
Agent object which initalizes and trains the keras model.
Method signatures and docstrings:
- def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None): Initializes the parameters ... | 975a95032ce5b7012d1772c7f1f5cfe606eae839 | <|skeleton|>
class Agent:
"""Agent object which initalizes and trains the keras model."""
def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None):
"""Initializes the parameters of the model. Args: height: Height of the image width: Wi... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Agent:
"""Agent object which initalizes and trains the keras model."""
def __init__(self, actions, height=80, width=80, channels=1, discount=0.95, loss='huber', env='Breakout-v0', model_dir=None):
"""Initializes the parameters of the model. Args: height: Height of the image width: Width of the im... | the_stack_v2_python_sparse | blogs/rl-on-gcp/DQN_Breakout/rl_on_gcp/trainer/model.py | GoogleCloudPlatform/training-data-analyst | train | 7,311 |
5d90fa9f1f0ddc8d3ed429e0c1c6aeebe6064125 | [
"super().__init__(name=name)\nself.alpha = alpha\nself.adjust = adjust\nself.initial_value = initial_value",
"mean = hk.get_state('mean', shape=x.shape, dtype=x.dtype, init=lambda shape, dtype: jnp.full(shape, self.initial_value, dtype))\ncount = hk.get_state('count', shape=x.shape, dtype=x.dtype, init=lambda sha... | <|body_start_0|>
super().__init__(name=name)
self.alpha = alpha
self.adjust = adjust
self.initial_value = initial_value
<|end_body_0|>
<|body_start_1|>
mean = hk.get_state('mean', shape=x.shape, dtype=x.dtype, init=lambda shape, dtype: jnp.full(shape, self.initial_value, dtype))... | Compute exponentioal moving average. | EWMA | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EWMA:
"""Compute exponentioal moving average."""
def __init__(self, alpha: float, adjust: bool=True, initial_value=jnp.nan, name: str=None):
"""Initialize module. Args: alpha: alpha parameter of the exponential moving average. adjust: if true, implement a non-stationary filter with e... | stack_v2_sparse_classes_10k_train_002590 | 2,834 | permissive | [
{
"docstring": "Initialize module. Args: alpha: alpha parameter of the exponential moving average. adjust: if true, implement a non-stationary filter with exponential initialization scheme. If \"linear\", implement a non-stationary filter with linear initialization. initial_value: initial value for the state. n... | 2 | stack_v2_sparse_classes_30k_train_002027 | Implement the Python class `EWMA` described below.
Class description:
Compute exponentioal moving average.
Method signatures and docstrings:
- def __init__(self, alpha: float, adjust: bool=True, initial_value=jnp.nan, name: str=None): Initialize module. Args: alpha: alpha parameter of the exponential moving average. ... | Implement the Python class `EWMA` described below.
Class description:
Compute exponentioal moving average.
Method signatures and docstrings:
- def __init__(self, alpha: float, adjust: bool=True, initial_value=jnp.nan, name: str=None): Initialize module. Args: alpha: alpha parameter of the exponential moving average. ... | ab18e064f9fa1c95458978f501efb6cde9ab64d5 | <|skeleton|>
class EWMA:
"""Compute exponentioal moving average."""
def __init__(self, alpha: float, adjust: bool=True, initial_value=jnp.nan, name: str=None):
"""Initialize module. Args: alpha: alpha parameter of the exponential moving average. adjust: if true, implement a non-stationary filter with e... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class EWMA:
"""Compute exponentioal moving average."""
def __init__(self, alpha: float, adjust: bool=True, initial_value=jnp.nan, name: str=None):
"""Initialize module. Args: alpha: alpha parameter of the exponential moving average. adjust: if true, implement a non-stationary filter with exponential in... | the_stack_v2_python_sparse | wax/modules/ewma.py | zggl/wax-ml | train | 0 |
24644bc5f431cba1d0ff807e16cd3a880a99781d | [
"test = application.orm.get_test(test_id)\ntest_schema = TestsSchema()\nif test is None:\n return fail_response('Test is not found', code=404)\nres = test_schema.dump(test)\nquestions = []\nquestions_schema = QuestionsSchema()\nfor question_id in res.data['questions_tests']:\n obj = application.orm.get_questi... | <|body_start_0|>
test = application.orm.get_test(test_id)
test_schema = TestsSchema()
if test is None:
return fail_response('Test is not found', code=404)
res = test_schema.dump(test)
questions = []
questions_schema = QuestionsSchema()
for question_id ... | TestManagement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestManagement:
def get(self, test_id):
"""--- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer required: true description: Numeric ID of the user to get responses: 200: description: OK content: applicat... | stack_v2_sparse_classes_10k_train_002591 | 12,238 | no_license | [
{
"docstring": "--- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer required: true description: Numeric ID of the user to get responses: 200: description: OK content: application/json: schema: TestsSchema example: { \"archived... | 3 | stack_v2_sparse_classes_30k_train_005252 | Implement the Python class `TestManagement` described below.
Class description:
Implement the TestManagement class.
Method signatures and docstrings:
- def get(self, test_id): --- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer requ... | Implement the Python class `TestManagement` described below.
Class description:
Implement the TestManagement class.
Method signatures and docstrings:
- def get(self, test_id): --- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer requ... | 171f990754f1c89cefe2b416001d1b7e3a6a430d | <|skeleton|>
class TestManagement:
def get(self, test_id):
"""--- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer required: true description: Numeric ID of the user to get responses: 200: description: OK content: applicat... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class TestManagement:
def get(self, test_id):
"""--- summary: Get test by id description: All test questions with test metainfo parameters: - in: path name: user_id schema: type: integer required: true description: Numeric ID of the user to get responses: 200: description: OK content: application/json: sche... | the_stack_v2_python_sparse | backend/api/test.py | ssd-courseproject/adminssion-forms-backend | train | 0 | |
b66469a6636cfa67f8d3717ae2806c874b7b2c53 | [
"if not root:\n return '[]'\nqueue = collections.deque()\nqueue.append(root)\nres = []\nwhile queue:\n size = len(queue)\n for i in range(size):\n cur = queue.popleft()\n if cur:\n res.append(str(cur.val))\n else:\n res.append('null')\n if cur:\n ... | <|body_start_0|>
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
size = len(queue)
for i in range(size):
cur = queue.popleft()
if cur:
res.append(... | 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|>
def deserialize(self,... | stack_v2_sparse_classes_10k_train_002592 | 3,278 | 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... | 3 | stack_v2_sparse_classes_30k_val_000081 | 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:... | f1bbd6b3197cd9ac4f0d35a37539c11b02272065 | <|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|>
def deserialize(self,... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return '[]'
queue = collections.deque()
queue.append(root)
res = []
while queue:
size = len(queue)
for i ... | the_stack_v2_python_sparse | leetcode/高频面试/树/297. 二叉树的序列化与反序列化 hard 细节上存在问题/Codec.py | guohaoyuan/algorithms-for-work | train | 2 | |
8c62399eef4cef5a5f4b58d009a3a47feaaea1fd | [
"self.dx = dx\nself.grid_size_y = grid_size_y\nself.grid_size_x = grid_size_x\nself.real_t = real_t\nself.bc_type = bc_type\npoisson_matrix_x, poisson_matrix_y = self._construct_poisson_matrices()\nself._apply_boundary_conds_to_poisson_matrices(poisson_matrix_x, poisson_matrix_y)\nself._compute_spectral_decomp_of_p... | <|body_start_0|>
self.dx = dx
self.grid_size_y = grid_size_y
self.grid_size_x = grid_size_x
self.real_t = real_t
self.bc_type = bc_type
poisson_matrix_x, poisson_matrix_y = self._construct_poisson_matrices()
self._apply_boundary_conds_to_poisson_matrices(poisson_m... | Class for Poisson solver in 2D via Fast Diagonalisation. | FastDiagPoissonSolver2D | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FastDiagPoissonSolver2D:
"""Class for Poisson solver in 2D via Fast Diagonalisation."""
def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy']='homogenous_neumann_along_xy') -> None:
"""Class initiali... | stack_v2_sparse_classes_10k_train_002593 | 4,807 | permissive | [
{
"docstring": "Class initialiser.",
"name": "__init__",
"signature": "def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy']='homogenous_neumann_along_xy') -> None"
},
{
"docstring": "Construct the finite differ... | 5 | stack_v2_sparse_classes_30k_train_001913 | Implement the Python class `FastDiagPoissonSolver2D` described below.
Class description:
Class for Poisson solver in 2D via Fast Diagonalisation.
Method signatures and docstrings:
- def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy... | Implement the Python class `FastDiagPoissonSolver2D` described below.
Class description:
Class for Poisson solver in 2D via Fast Diagonalisation.
Method signatures and docstrings:
- def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy... | 99a094e0d6e635e5b2385a69bdee239a4d1fb530 | <|skeleton|>
class FastDiagPoissonSolver2D:
"""Class for Poisson solver in 2D via Fast Diagonalisation."""
def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy']='homogenous_neumann_along_xy') -> None:
"""Class initiali... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class FastDiagPoissonSolver2D:
"""Class for Poisson solver in 2D via Fast Diagonalisation."""
def __init__(self, grid_size_y: int, grid_size_x: int, dx: float, real_t: type=np.float64, bc_type: Literal['homogenous_neumann_along_xy']='homogenous_neumann_along_xy') -> None:
"""Class initialiser."""
... | the_stack_v2_python_sparse | sopht/numeric/eulerian_grid_ops/poisson_solver_2d/FastDiagPoissonSolver2D.py | SophT-Team/SophT | train | 2 |
26c2ba4bbae3bfc813c1a0e97c7c435e9dfb8ff5 | [
"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... | Proto file describing the BatchJobService. Service to manage batch jobs. | BatchJobServiceServicer | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BatchJobServiceServicer:
"""Proto file describing the BatchJobService. Service to manage batch jobs."""
def MutateBatchJob(self, request, context):
"""Mutates a batch job."""
<|body_0|>
def GetBatchJob(self, request, context):
"""Returns the batch job."""
... | stack_v2_sparse_classes_10k_train_002594 | 11,564 | permissive | [
{
"docstring": "Mutates a batch job.",
"name": "MutateBatchJob",
"signature": "def MutateBatchJob(self, request, context)"
},
{
"docstring": "Returns the batch job.",
"name": "GetBatchJob",
"signature": "def GetBatchJob(self, request, context)"
},
{
"docstring": "Returns the resu... | 5 | stack_v2_sparse_classes_30k_train_000669 | Implement the Python class `BatchJobServiceServicer` described below.
Class description:
Proto file describing the BatchJobService. Service to manage batch jobs.
Method signatures and docstrings:
- def MutateBatchJob(self, request, context): Mutates a batch job.
- def GetBatchJob(self, request, context): Returns the ... | Implement the Python class `BatchJobServiceServicer` described below.
Class description:
Proto file describing the BatchJobService. Service to manage batch jobs.
Method signatures and docstrings:
- def MutateBatchJob(self, request, context): Mutates a batch job.
- def GetBatchJob(self, request, context): Returns the ... | 969eff5b6c3cec59d21191fa178cffb6270074c3 | <|skeleton|>
class BatchJobServiceServicer:
"""Proto file describing the BatchJobService. Service to manage batch jobs."""
def MutateBatchJob(self, request, context):
"""Mutates a batch job."""
<|body_0|>
def GetBatchJob(self, request, context):
"""Returns the batch job."""
... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class BatchJobServiceServicer:
"""Proto file describing the BatchJobService. Service to manage batch jobs."""
def MutateBatchJob(self, request, context):
"""Mutates a batch job."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
rai... | the_stack_v2_python_sparse | google/ads/google_ads/v6/proto/services/batch_job_service_pb2_grpc.py | VincentFritzsche/google-ads-python | train | 0 |
beb3aa7398d745119f4e74b9b240dfcc23efad51 | [
"self.name = 'connectome_stage'\nself.bids_dir = bids_dir\nself.output_dir = output_dir\nself.config = ConnectomeConfig()\nself.inputs = ['roi_volumes_registered', 'func_file', 'FD', 'DVARS', 'parcellation_scheme', 'atlas_info', 'roi_graphMLs']\nself.outputs = ['connectivity_matrices', 'avg_timeseries']",
"cmtk_c... | <|body_start_0|>
self.name = 'connectome_stage'
self.bids_dir = bids_dir
self.output_dir = output_dir
self.config = ConnectomeConfig()
self.inputs = ['roi_volumes_registered', 'func_file', 'FD', 'DVARS', 'parcellation_scheme', 'atlas_info', 'roi_graphMLs']
self.outputs = ... | Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.fMRI.fMRIPipeline cmp.stages.connectome.fmri_connectome.ConnectomeConfig | ConnectomeStage | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConnectomeStage:
"""Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.fMRI.fMRIPipeline cmp.stages.connectome... | stack_v2_sparse_classes_10k_train_002595 | 7,737 | permissive | [
{
"docstring": "Constructor of a :class:`~cmp.stages.connectome.fmri_connectome.Connectome` instance.",
"name": "__init__",
"signature": "def __init__(self, bids_dir, output_dir)"
},
{
"docstring": "Create the stage worflow. Parameters ---------- flow : nipype.pipeline.engine.Workflow The nipype... | 3 | stack_v2_sparse_classes_30k_train_006310 | Implement the Python class `ConnectomeStage` described below.
Class description:
Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.... | Implement the Python class `ConnectomeStage` described below.
Class description:
Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.... | 35cb2ee7be2e73896061359a6cd0a10503fadd42 | <|skeleton|>
class ConnectomeStage:
"""Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.fMRI.fMRIPipeline cmp.stages.connectome... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class ConnectomeStage:
"""Class that represents the connectome building stage of a :class:`~cmp.pipelines.functional.fMRI.fMRIPipeline`. Methods ------- create_workflow() Create the workflow of the fMRI `ConnectomeStage` See Also -------- cmp.pipelines.functional.fMRI.fMRIPipeline cmp.stages.connectome.fmri_connect... | the_stack_v2_python_sparse | cmp/stages/connectome/fmri_connectome.py | jwirsich/connectomemapper3 | train | 0 |
662b8a407c6d6b1050f1a85a54564417cc339699 | [
"cfac = 2 / np.sqrt(3)\nself.pnt = cfac * np.array([[0.5, 0.5, 0.5], [0.5, 0.5, -0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, -0.5, -0.5], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, -1.0]])\nself.plan... | <|body_start_0|>
cfac = 2 / np.sqrt(3)
self.pnt = cfac * np.array([[0.5, 0.5, 0.5], [0.5, 0.5, -0.5], [0.5, -0.5, 0.5], [-0.5, 0.5, 0.5], [0.5, -0.5, -0.5], [-0.5, 0.5, -0.5], [-0.5, -0.5, 0.5], [-0.5, -0.5, -0.5], [1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0], [0... | Defines points that fall within the unit cell of a bcc lattice | NanoBcc | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NanoBcc:
"""Defines points that fall within the unit cell of a bcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
<|body_0|>
def check_point(self... | stack_v2_sparse_classes_10k_train_002596 | 4,924 | no_license | [
{
"docstring": "The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell",
"name": "__init__",
"signature": "def __init__(self, radius)"
},
{
"docstring": "Checks whether a point is within the unit cell :param pnt: given poin... | 2 | stack_v2_sparse_classes_30k_train_001926 | Implement the Python class `NanoBcc` described below.
Class description:
Defines points that fall within the unit cell of a bcc lattice
Method signatures and docstrings:
- def __init__(self, radius): The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of ... | Implement the Python class `NanoBcc` described below.
Class description:
Defines points that fall within the unit cell of a bcc lattice
Method signatures and docstrings:
- def __init__(self, radius): The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of ... | 351fde195f54d9af205e8abad217751121b25e6c | <|skeleton|>
class NanoBcc:
"""Defines points that fall within the unit cell of a bcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
<|body_0|>
def check_point(self... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class NanoBcc:
"""Defines points that fall within the unit cell of a bcc lattice"""
def __init__(self, radius):
"""The constructor particles are assumed to have diameter 1. All units are relative to this one :param radius: radius of unit cell"""
cfac = 2 / np.sqrt(3)
self.pnt = cfac * n... | the_stack_v2_python_sparse | build/particles/nanoparticle_core.py | nathanhorst/MD | train | 0 |
92a26ea192637dcdf422b462a446a22806887140 | [
"super().__init__()\nself.in_channels = in_channels\nself.out_channels = out_channels\nself.num_filters = num_filters\nself.num_pool_layers = num_pool_layers\nself.dropout_probability = dropout_probability\nself.down_sample_layers = nn.ModuleList([MultiDomainConvBlock(forward_operator, backward_operator, in_channel... | <|body_start_0|>
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.num_filters = num_filters
self.num_pool_layers = num_pool_layers
self.dropout_probability = dropout_probability
self.down_sample_layers = nn.ModuleList([MultiD... | Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge. | MultiDomainUnet2d | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiDomainUnet2d:
"""Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: in... | stack_v2_sparse_classes_10k_train_002597 | 11,794 | permissive | [
{
"docstring": "Parameters ---------- forward_operator: Callable Forward Operator. backward_operator: Callable Backward Operator. in_channels: int Number of input channels to the u-net. out_channels: int Number of output channels to the u-net. num_filters: int Number of output channels of the first convolutiona... | 2 | stack_v2_sparse_classes_30k_val_000393 | Implement the Python class `MultiDomainUnet2d` described below.
Class description:
Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_cha... | Implement the Python class `MultiDomainUnet2d` described below.
Class description:
Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge.
Method signatures and docstrings:
- def __init__(self, forward_operator: Callable, backward_operator: Callable, in_cha... | 2a4c29342bc52a404aae097bc2654fb4323e1ac8 | <|skeleton|>
class MultiDomainUnet2d:
"""Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: in... | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class MultiDomainUnet2d:
"""Unet modification to be used with Multi-domain network as in AIRS Medical submission to the Fast MRI 2020 challenge."""
def __init__(self, forward_operator: Callable, backward_operator: Callable, in_channels: int, out_channels: int, num_filters: int, num_pool_layers: int, dropout_pr... | the_stack_v2_python_sparse | direct/nn/multidomainnet/multidomain.py | NKI-AI/direct | train | 151 |
5dd58f907904443936d9e2b5a898853b4399a81d | [
"@functools.lru_cache()\ndef recur(m, n):\n if m == 1 and n == 1:\n return grid[0][0]\n elif m == 0 or n == 0:\n return float('inf')\n return grid[m - 1][n - 1] + min(recur(m - 1, n), recur(m, n - 1))\nreturn recur(len(grid), len(grid[0]))",
"grid = [[float('inf')] + x for x in grid]\ngrid.... | <|body_start_0|>
@functools.lru_cache()
def recur(m, n):
if m == 1 and n == 1:
return grid[0][0]
elif m == 0 or n == 0:
return float('inf')
return grid[m - 1][n - 1] + min(recur(m - 1, n), recur(m, n - 1))
return recur(len(grid)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
"""递归思想, 这一题中,递归方法会慢很多; :param grid: :return:"""
<|body_0|>
def minPathSum_2(self, grid: List[List[int]]) -> int:
"""动态规划思想 :param grid: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_10k_train_002598 | 1,164 | no_license | [
{
"docstring": "递归思想, 这一题中,递归方法会慢很多; :param grid: :return:",
"name": "minPathSum",
"signature": "def minPathSum(self, grid: List[List[int]]) -> int"
},
{
"docstring": "动态规划思想 :param grid: :return:",
"name": "minPathSum_2",
"signature": "def minPathSum_2(self, grid: List[List[int]]) -> in... | 2 | stack_v2_sparse_classes_30k_train_007163 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid: List[List[int]]) -> int: 递归思想, 这一题中,递归方法会慢很多; :param grid: :return:
- def minPathSum_2(self, grid: List[List[int]]) -> int: 动态规划思想 :param grid: :return... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def minPathSum(self, grid: List[List[int]]) -> int: 递归思想, 这一题中,递归方法会慢很多; :param grid: :return:
- def minPathSum_2(self, grid: List[List[int]]) -> int: 动态规划思想 :param grid: :return... | f2c162654a83c51495ebd161f42a1d0b69caf72d | <|skeleton|>
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
"""递归思想, 这一题中,递归方法会慢很多; :param grid: :return:"""
<|body_0|>
def minPathSum_2(self, grid: List[List[int]]) -> int:
"""动态规划思想 :param grid: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
"""递归思想, 这一题中,递归方法会慢很多; :param grid: :return:"""
@functools.lru_cache()
def recur(m, n):
if m == 1 and n == 1:
return grid[0][0]
elif m == 0 or n == 0:
return float('in... | the_stack_v2_python_sparse | 64 minPathSum.py | ABenxj/leetcode | train | 1 | |
4b612ccddcca123d374e51540159ac2215f18f3c | [
"user = User.query.get(id)\nif not user:\n api.abort(code=404, message='User not found')\nreturn {'data': user.__jsonapi__()}",
"current_identity = import_user()\nuser = User.query.get(id)\nif not user:\n api.abort(code=404, message='User not found')\ndata = request.get_json()['data']\nif 'name' in data['at... | <|body_start_0|>
user = User.query.get(id)
if not user:
api.abort(code=404, message='User not found')
return {'data': user.__jsonapi__()}
<|end_body_0|>
<|body_start_1|>
current_identity = import_user()
user = User.query.get(id)
if not user:
api.a... | Users | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Users:
def get(self, id):
"""Get user"""
<|body_0|>
def put(self, id):
"""Update user"""
<|body_1|>
def delete(self, id):
"""Delete user"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
user = User.query.get(id)
if not us... | stack_v2_sparse_classes_10k_train_002599 | 46,738 | permissive | [
{
"docstring": "Get user",
"name": "get",
"signature": "def get(self, id)"
},
{
"docstring": "Update user",
"name": "put",
"signature": "def put(self, id)"
},
{
"docstring": "Delete user",
"name": "delete",
"signature": "def delete(self, id)"
}
] | 3 | stack_v2_sparse_classes_30k_train_000941 | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self, id): Get user
- def put(self, id): Update user
- def delete(self, id): Delete user | Implement the Python class `Users` described below.
Class description:
Implement the Users class.
Method signatures and docstrings:
- def get(self, id): Get user
- def put(self, id): Update user
- def delete(self, id): Delete user
<|skeleton|>
class Users:
def get(self, id):
"""Get user"""
<|bod... | 3439a2dd0bd527c5d604801fec3a5aac904a72e2 | <|skeleton|>
class Users:
def get(self, id):
"""Get user"""
<|body_0|>
def put(self, id):
"""Update user"""
<|body_1|>
def delete(self, id):
"""Delete user"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_10k | data/stack_v2_sparse_classes_30k | class Users:
def get(self, id):
"""Get user"""
user = User.query.get(id)
if not user:
api.abort(code=404, message='User not found')
return {'data': user.__jsonapi__()}
def put(self, id):
"""Update user"""
current_identity = import_user()
user ... | the_stack_v2_python_sparse | app/views.py | taidos/lxc-rest | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.