blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 6.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 438 7.52k | id stringlengths 40 40 | length_bytes int64 506 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.25k | prompted_full_text stringlengths 645 10.7k | revision_id stringlengths 40 40 | skeleton stringlengths 162 4.34k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | solution stringlengths 302 7.33k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b9add11459d960549a2b1989ae8d8133ca596257 | [
"start = s\nwhile start:\n if start.next != None and start.val <= node.val and (start.next.val >= node.val):\n temp = start.next\n start.next = node\n node.next = temp\n break\n if start.next == None and start.val <= node.val:\n node.next = None\n start.next = node\n ... | <|body_start_0|>
start = s
while start:
if start.next != None and start.val <= node.val and (start.next.val >= node.val):
temp = start.next
start.next = node
node.next = temp
break
if start.next == None and start.val... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def InsertNode(self, s, node):
""":type start: ListNode node: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start = s
while star... | stack_v2_sparse_classes_36k_train_004500 | 1,582 | no_license | [
{
"docstring": ":type start: ListNode node: ListNode",
"name": "InsertNode",
"signature": "def InsertNode(self, s, node)"
},
{
"docstring": ":type lists: List[ListNode] :rtype: ListNode",
"name": "mergeKLists",
"signature": "def mergeKLists(self, lists)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015805 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def InsertNode(self, s, node): :type start: ListNode node: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def InsertNode(self, s, node): :type start: ListNode node: ListNode
- def mergeKLists(self, lists): :type lists: List[ListNode] :rtype: ListNode
<|skeleton|>
class Solution:
... | b6d0e2ff481e26372d0c8e5f15812a8613af6f0b | <|skeleton|>
class Solution:
def InsertNode(self, s, node):
""":type start: ListNode node: ListNode"""
<|body_0|>
def mergeKLists(self, lists):
""":type lists: List[ListNode] :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def InsertNode(self, s, node):
""":type start: ListNode node: ListNode"""
start = s
while start:
if start.next != None and start.val <= node.val and (start.next.val >= node.val):
temp = start.next
start.next = node
n... | the_stack_v2_python_sparse | mergeKLists.py | DemonZhou/leetcode | train | 0 | |
e4e6c95dbddcb2a4554a2f5fa037d9cc66abd132 | [
"cognito_user = get_cognito_user(request)\nrequested_status = [None]\nif 'status' in args:\n requested_status = ['approved', 'denied', 'failed', 'cancelled', 'closed'] if args['status'] == 'archived' else [args['status']]\nmy_account: List[Account] = accountsService.get_by_owner(cognito_user.sub)\nfoundAppReques... | <|body_start_0|>
cognito_user = get_cognito_user(request)
requested_status = [None]
if 'status' in args:
requested_status = ['approved', 'denied', 'failed', 'cancelled', 'closed'] if args['status'] == 'archived' else [args['status']]
my_account: List[Account] = accountsServic... | RequestResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RequestResource:
def get(self, args: dict) -> List[AppRequest]:
"""Returns requests that a user raised or can approve"""
<|body_0|>
def post(self):
"""Submit a request"""
<|body_1|>
def put(self, args: dict):
"""Update a request"""
<|body... | stack_v2_sparse_classes_36k_train_004501 | 4,030 | no_license | [
{
"docstring": "Returns requests that a user raised or can approve",
"name": "get",
"signature": "def get(self, args: dict) -> List[AppRequest]"
},
{
"docstring": "Submit a request",
"name": "post",
"signature": "def post(self)"
},
{
"docstring": "Update a request",
"name": "... | 3 | stack_v2_sparse_classes_30k_train_011602 | Implement the Python class `RequestResource` described below.
Class description:
Implement the RequestResource class.
Method signatures and docstrings:
- def get(self, args: dict) -> List[AppRequest]: Returns requests that a user raised or can approve
- def post(self): Submit a request
- def put(self, args: dict): Up... | Implement the Python class `RequestResource` described below.
Class description:
Implement the RequestResource class.
Method signatures and docstrings:
- def get(self, args: dict) -> List[AppRequest]: Returns requests that a user raised or can approve
- def post(self): Submit a request
- def put(self, args: dict): Up... | dd7733d42010452123afbce83d748236dd86ce56 | <|skeleton|>
class RequestResource:
def get(self, args: dict) -> List[AppRequest]:
"""Returns requests that a user raised or can approve"""
<|body_0|>
def post(self):
"""Submit a request"""
<|body_1|>
def put(self, args: dict):
"""Update a request"""
<|body... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RequestResource:
def get(self, args: dict) -> List[AppRequest]:
"""Returns requests that a user raised or can approve"""
cognito_user = get_cognito_user(request)
requested_status = [None]
if 'status' in args:
requested_status = ['approved', 'denied', 'failed', 'canc... | the_stack_v2_python_sparse | app/requests/controller.py | njaiswal/idcrypt-backend | train | 0 | |
71534e1658e74b28b9807e2dabc914c65f59002f | [
"self.aws_region = aws_region\nself.bucket_name = bucket_name\nself.key_prefix = key_prefix",
"if dictionary is None:\n return None\naws_region = dictionary.get('awsRegion')\nbucket_name = dictionary.get('bucketName')\nkey_prefix = dictionary.get('keyPrefix')\nreturn cls(aws_region, bucket_name, key_prefix)"
] | <|body_start_0|>
self.aws_region = aws_region
self.bucket_name = bucket_name
self.key_prefix = key_prefix
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
aws_region = dictionary.get('awsRegion')
bucket_name = dictionary.get('bucketName')
... | Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s3 bucket. This job will create all keys within the given key prefix. | S3BucketInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3BucketInfo:
"""Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s3 bucket. This job will create all keys... | stack_v2_sparse_classes_36k_train_004502 | 1,870 | permissive | [
{
"docstring": "Constructor for the S3BucketInfo class",
"name": "__init__",
"signature": "def __init__(self, aws_region=None, bucket_name=None, key_prefix=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of ... | 2 | stack_v2_sparse_classes_30k_test_000995 | Implement the Python class `S3BucketInfo` described below.
Class description:
Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s... | Implement the Python class `S3BucketInfo` described below.
Class description:
Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class S3BucketInfo:
"""Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s3 bucket. This job will create all keys... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3BucketInfo:
"""Implementation of the 'S3BucketInfo' model. TODO: type description here. Attributes: aws_region (string): AWS region of the S3 bucket. bucket_name (string): Name of the S3 bucket. key_prefix (string): Complete path of the sub folder in the s3 bucket. This job will create all keys within the g... | the_stack_v2_python_sparse | cohesity_management_sdk/models/s3_bucket_info.py | cohesity/management-sdk-python | train | 24 |
8a455ef22298060884f981e930fb915b43e43357 | [
"tf.set_random_seed(0)\nwindow = 580\nbatch_size = 36\nnum_pairs = batch_size // 2\nnum_views = 2\nseq_len = 600\n_, a_view_indices, p_view_indices = data_providers.get_tcn_anchor_pos_indices(seq_len, num_views, num_pairs, window)\nwith self.test_session() as sess:\n np_a_view_indices, np_p_view_indices = sess.r... | <|body_start_0|>
tf.set_random_seed(0)
window = 580
batch_size = 36
num_pairs = batch_size // 2
num_views = 2
seq_len = 600
_, a_view_indices, p_view_indices = data_providers.get_tcn_anchor_pos_indices(seq_len, num_views, num_pairs, window)
with self.test_... | DataTest | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataTest:
def testMVTripletIndices(self):
"""Ensures anchor/pos indices for a TCN batch are valid."""
<|body_0|>
def testSVTripletIndices(self):
"""Ensures time indices for a SV triplet batch are valid."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004503 | 2,501 | permissive | [
{
"docstring": "Ensures anchor/pos indices for a TCN batch are valid.",
"name": "testMVTripletIndices",
"signature": "def testMVTripletIndices(self)"
},
{
"docstring": "Ensures time indices for a SV triplet batch are valid.",
"name": "testSVTripletIndices",
"signature": "def testSVTriple... | 2 | null | Implement the Python class `DataTest` described below.
Class description:
Implement the DataTest class.
Method signatures and docstrings:
- def testMVTripletIndices(self): Ensures anchor/pos indices for a TCN batch are valid.
- def testSVTripletIndices(self): Ensures time indices for a SV triplet batch are valid. | Implement the Python class `DataTest` described below.
Class description:
Implement the DataTest class.
Method signatures and docstrings:
- def testMVTripletIndices(self): Ensures anchor/pos indices for a TCN batch are valid.
- def testSVTripletIndices(self): Ensures time indices for a SV triplet batch are valid.
<|... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class DataTest:
def testMVTripletIndices(self):
"""Ensures anchor/pos indices for a TCN batch are valid."""
<|body_0|>
def testSVTripletIndices(self):
"""Ensures time indices for a SV triplet batch are valid."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DataTest:
def testMVTripletIndices(self):
"""Ensures anchor/pos indices for a TCN batch are valid."""
tf.set_random_seed(0)
window = 580
batch_size = 36
num_pairs = batch_size // 2
num_views = 2
seq_len = 600
_, a_view_indices, p_view_indices = d... | the_stack_v2_python_sparse | models/research/tcn/data_providers_test.py | finnickniu/tensorflow_object_detection_tflite | train | 60 | |
5aff9dcca0dfbba27d8c2bd168a82c44f8dbace3 | [
"self.width = width - 1\nself.height = height - 1\nself.food = deque(food)\nself.snake = deque([[0, 0]])",
"i, j = self.snake[0]\nif direction == 'U':\n i -= 1\nelif direction == 'R':\n j += 1\nelif direction == 'L':\n j -= 1\nelif direction == 'D':\n i += 1\nif i < 0 or i > self.height or j < 0 or (j... | <|body_start_0|>
self.width = width - 1
self.height = height - 1
self.food = deque(food)
self.snake = deque([[0, 0]])
<|end_body_0|>
<|body_start_1|>
i, j = self.snake[0]
if direction == 'U':
i -= 1
elif direction == 'R':
j += 1
el... | 스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다. | SnakeGame | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height:... | stack_v2_sparse_classes_36k_train_004504 | 3,893 | no_license | [
{
"docstring": "Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0].",
"name": "__init__",
"signature": "def __init__(self, widt... | 2 | stack_v2_sparse_classes_30k_train_009695 | Implement the Python class `SnakeGame` described below.
Class description:
스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다.
Method... | Implement the Python class `SnakeGame` described below.
Class description:
스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다.
Method... | 1c9528e26752b723e1d128b020f6c5291ed5ca19 | <|skeleton|>
class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SnakeGame:
"""스네이크 게임을 디자인한다. 화면 크기 = 너비 x 높이의 장치에서 플레이한다. 뱀은 처음에 길이 = 1 인 상태로, 왼쪽 상단 모서리에 위치한다. 음식의 위치 목록을 행-열 순서대로 받는다. 뱀이 음식을 먹으면 길이와 게임의 점수가 모두 1씩 증가한다. 각각의 음식이 화면에 하나씩 나타난다. 첫 번째 음식을 뱀이 먹으면 두 번째 음식이 나타난다. 화면에 음식이 나타날 때, 뱀이 점유한 블록에는 음식이 나타나지 않는다."""
def __init__(self, width: int, height: int, food: L... | the_stack_v2_python_sparse | system_design/353_design_snake_game.py | eunjungchoi/algorithm | train | 1 |
8ab5fde7dc22ffb2a66a1e25808eb47e4ed4855d | [
"dic = {}\nfor n in nums:\n dic[n] = dic.get(n, 0) + 1\n if dic[n] == 2:\n del dic[n]\nreturn dic.keys()[0]",
"res = 0\nfor n in nums:\n res ^= n\nreturn res"
] | <|body_start_0|>
dic = {}
for n in nums:
dic[n] = dic.get(n, 0) + 1
if dic[n] == 2:
del dic[n]
return dic.keys()[0]
<|end_body_0|>
<|body_start_1|>
res = 0
for n in nums:
res ^= n
return res
<|end_body_1|>
| Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber1(self, nums):
""":type nums: List[int] :rtype: int 思路 限制线性时间复杂度且不使用额外空间。采用位运算异或^。 交换律 a^b=b^a 结合律 (a^b)^c=a^(b^c) 与本身异或等于0 a^a=0 与0异或等于本身 a^0=a 例如 4^1^2^1^2=4^... | stack_v2_sparse_classes_36k_train_004505 | 1,026 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 思路 限制线性时间复杂度且不使用额外空间。采用位运算异或^。 交换律 a^b=b^a 结合律 (a^b)^c=a^(b^c) 与本身异或等于0 a^a=0 与0异或等于本身 a^0=a 例如 4^1^2^1^2=4^1^1^2^2=4^(1^1)... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber1(self, nums): :type nums: List[int] :rtype: int 思路 限制线性时间复杂度且不使用额外空间。采用位运算异或^。 交换律 a^b=b^a 结合律 ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber1(self, nums): :type nums: List[int] :rtype: int 思路 限制线性时间复杂度且不使用额外空间。采用位运算异或^。 交换律 a^b=b^a 结合律 ... | 069bb0b751ef7f469036b9897436eb5d138ffa24 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber1(self, nums):
""":type nums: List[int] :rtype: int 思路 限制线性时间复杂度且不使用额外空间。采用位运算异或^。 交换律 a^b=b^a 结合律 (a^b)^c=a^(b^c) 与本身异或等于0 a^a=0 与0异或等于本身 a^0=a 例如 4^1^2^1^2=4^... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
dic = {}
for n in nums:
dic[n] = dic.get(n, 0) + 1
if dic[n] == 2:
del dic[n]
return dic.keys()[0]
def singleNumber1(self, nums):
""":type nums: ... | the_stack_v2_python_sparse | 算法/位运算/只出现一次的数字.py | RichieSong/algorithm | train | 0 | |
2f8bbdecf9bd5bc4c77073d30b9d80e8b9f96885 | [
"res = []\ni = 0\nfor item in pushed:\n res.append(item)\n while len(res) > 0 and res[-1] == popped[i]:\n res.pop()\n i += 1\nreturn i == len(popped)",
"i = 0\nres = []\nfor item in pushed:\n res.append(item)\n while len(res) > 0 and res[-1] == popped[i]:\n res.pop()\n i +=... | <|body_start_0|>
res = []
i = 0
for item in pushed:
res.append(item)
while len(res) > 0 and res[-1] == popped[i]:
res.pop()
i += 1
return i == len(popped)
<|end_body_0|>
<|body_start_1|>
i = 0
res = []
for i... | https://leetcode.com/problems/validate-stack-sequences/ | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/validate-stack-sequences/"""
def validateStackSequences(self, pushed, popped):
""":type pushed: List[int] :type popped: List[int] :rtype: bool"""
<|body_0|>
def validateStackSequences2(self, pushed, popped):
""":type pus... | stack_v2_sparse_classes_36k_train_004506 | 1,038 | no_license | [
{
"docstring": ":type pushed: List[int] :type popped: List[int] :rtype: bool",
"name": "validateStackSequences",
"signature": "def validateStackSequences(self, pushed, popped)"
},
{
"docstring": ":type pushed: List[int] :type popped: List[int] :rtype: bool",
"name": "validateStackSequences2"... | 2 | null | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/validate-stack-sequences/
Method signatures and docstrings:
- def validateStackSequences(self, pushed, popped): :type pushed: List[int] :type popped: List[int] :rtype: bool
- def validateStackSequences2(self, pushe... | Implement the Python class `Solution` described below.
Class description:
https://leetcode.com/problems/validate-stack-sequences/
Method signatures and docstrings:
- def validateStackSequences(self, pushed, popped): :type pushed: List[int] :type popped: List[int] :rtype: bool
- def validateStackSequences2(self, pushe... | 54d3d9530b25272d4a2e5dc33e7035c44f506dc5 | <|skeleton|>
class Solution:
"""https://leetcode.com/problems/validate-stack-sequences/"""
def validateStackSequences(self, pushed, popped):
""":type pushed: List[int] :type popped: List[int] :rtype: bool"""
<|body_0|>
def validateStackSequences2(self, pushed, popped):
""":type pus... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
"""https://leetcode.com/problems/validate-stack-sequences/"""
def validateStackSequences(self, pushed, popped):
""":type pushed: List[int] :type popped: List[int] :rtype: bool"""
res = []
i = 0
for item in pushed:
res.append(item)
while le... | the_stack_v2_python_sparse | old/Session002/General/ValidateStackSequences.py | MaxIakovliev/algorithms | train | 0 |
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_36k_train_004507 | 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 | stack_v2_sparse_classes_30k_train_020045 | 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_36k | 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 |
09d65b5be1b07a2551bf3a00905228414f181efa | [
"if solution_name == 'src':\n return ''\nelse:\n root_solution_name = 'src/'\n assert solution_name.startswith(root_solution_name)\n return solution_name[len(root_solution_name):]",
"solution_name = solution_name.replace('\\\\', '/')\nrepo_dir = self._calculate_repo_dir(solution_name)\ncwd = self.m.pa... | <|body_start_0|>
if solution_name == 'src':
return ''
else:
root_solution_name = 'src/'
assert solution_name.startswith(root_solution_name)
return solution_name[len(root_solution_name):]
<|end_body_0|>
<|body_start_1|>
solution_name = solution_nam... | FinditApi | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
<|body_0|>
def files_changed_by_revision(self, revision, solution_name='src'):
"""Returns the files changed by the given revision. Args:... | stack_v2_sparse_classes_36k_train_004508 | 3,160 | permissive | [
{
"docstring": "Returns the relative path of the solution checkout to the root one.",
"name": "_calculate_repo_dir",
"signature": "def _calculate_repo_dir(self, solution_name)"
},
{
"docstring": "Returns the files changed by the given revision. Args: revision (str): the git hash of a commit. sol... | 3 | stack_v2_sparse_classes_30k_train_003482 | Implement the Python class `FinditApi` described below.
Class description:
Implement the FinditApi class.
Method signatures and docstrings:
- def _calculate_repo_dir(self, solution_name): Returns the relative path of the solution checkout to the root one.
- def files_changed_by_revision(self, revision, solution_name=... | Implement the Python class `FinditApi` described below.
Class description:
Implement the FinditApi class.
Method signatures and docstrings:
- def _calculate_repo_dir(self, solution_name): Returns the relative path of the solution checkout to the root one.
- def files_changed_by_revision(self, revision, solution_name=... | 22e3872f14dbf367cd787caa638f3ac948eac7d7 | <|skeleton|>
class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
<|body_0|>
def files_changed_by_revision(self, revision, solution_name='src'):
"""Returns the files changed by the given revision. Args:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FinditApi:
def _calculate_repo_dir(self, solution_name):
"""Returns the relative path of the solution checkout to the root one."""
if solution_name == 'src':
return ''
else:
root_solution_name = 'src/'
assert solution_name.startswith(root_solution_na... | the_stack_v2_python_sparse | scripts/slave/recipe_modules/findit/api.py | bopopescu/chromium_build | train | 0 | |
70d535de072d410aca07738cce8ab66c13c0bdfc | [
"parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)\n_NETWORK_ARG.AddArgument(parser)\n_VPN_GATEWAY_ARG.AddArgument(parser, operation_type='create')\nflags.GetDescriptionFlag().AddToParser(parser)\nparser.display_info.AddCacheUpdater(flags.VpnGatewaysCompleter)",
"holder = base_classes.ComputeApiHolder(self... | <|body_start_0|>
parser.display_info.AddFormat(flags.DEFAULT_LIST_FORMAT)
_NETWORK_ARG.AddArgument(parser)
_VPN_GATEWAY_ARG.AddArgument(parser, operation_type='create')
flags.GetDescriptionFlag().AddToParser(parser)
parser.display_info.AddCacheUpdater(flags.VpnGatewaysCompleter)
... | Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Target VPN Gateway. Highly Available VPN gateways are simply referred to as V... | Create | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Create:
"""Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Target VPN Gateway. Highly Available VPN ga... | stack_v2_sparse_classes_36k_train_004509 | 3,239 | permissive | [
{
"docstring": "Set up arguments for this command.",
"name": "Args",
"signature": "def Args(parser)"
},
{
"docstring": "Issues the request to create a new VPN gateway.",
"name": "Run",
"signature": "def Run(self, args)"
}
] | 2 | null | Implement the Python class `Create` described below.
Class description:
Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Targ... | Implement the Python class `Create` described below.
Class description:
Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Targ... | 85bb264e273568b5a0408f733b403c56373e2508 | <|skeleton|>
class Create:
"""Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Target VPN Gateway. Highly Available VPN ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Create:
"""Create a new Google Compute Engine Highly Available VPN gateway. *{command}* creates a new Highly Available VPN gateway. Highly Available VPN Gateway provides a means to create a VPN solution with a higher availability SLA compared to Classic Target VPN Gateway. Highly Available VPN gateways are si... | the_stack_v2_python_sparse | google-cloud-sdk/lib/surface/compute/vpn_gateways/create.py | bopopescu/socialliteapp | train | 0 |
fd8d36cc17b7958f40f803b6c9c6fcd3294a2454 | [
"self.user.email = 'Hello@magnet.cl'\nself.user.save()\nself.assertEqual(self.user.email, 'hello@magnet.cl')",
"url = reverse('password_change')\nresponse = self.client.get(url)\nself.assertEqual(response.status_code, 200)\nself.user.force_logout()\nresponse = self.client.get(url)\nself.assertEqual(response.statu... | <|body_start_0|>
self.user.email = 'Hello@magnet.cl'
self.user.save()
self.assertEqual(self.user.email, 'hello@magnet.cl')
<|end_body_0|>
<|body_start_1|>
url = reverse('password_change')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
... | UserTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
<|body_0|>
def test_force_logout(self):
"""Tests that users are created with lower case emails"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sel... | stack_v2_sparse_classes_36k_train_004510 | 878 | permissive | [
{
"docstring": "Tests that users are created with lower case emails",
"name": "test_lower_case_emails",
"signature": "def test_lower_case_emails(self)"
},
{
"docstring": "Tests that users are created with lower case emails",
"name": "test_force_logout",
"signature": "def test_force_logou... | 2 | stack_v2_sparse_classes_30k_train_001301 | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_lower_case_emails(self): Tests that users are created with lower case emails
- def test_force_logout(self): Tests that users are created with lower case emails | Implement the Python class `UserTests` described below.
Class description:
Implement the UserTests class.
Method signatures and docstrings:
- def test_lower_case_emails(self): Tests that users are created with lower case emails
- def test_force_logout(self): Tests that users are created with lower case emails
<|skel... | 3520a95900c7e84a467b4b07db4a47008575a2be | <|skeleton|>
class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
<|body_0|>
def test_force_logout(self):
"""Tests that users are created with lower case emails"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserTests:
def test_lower_case_emails(self):
"""Tests that users are created with lower case emails"""
self.user.email = 'Hello@magnet.cl'
self.user.save()
self.assertEqual(self.user.email, 'hello@magnet.cl')
def test_force_logout(self):
"""Tests that users are cre... | the_stack_v2_python_sparse | users/tests.py | magnet-cl/django-project-template | train | 9 | |
a95ea3813044c0b715c83e1e550b8135df71c2ed | [
"super(WallBoxShape, self).__init__(oid, pose, orient, dims)\nself.name = 'WallBox'\nself.height = 3.75\nself.radius = 0.35",
"if point[2] <= self.height:\n dist = CubeShape._euclidean(array(point[:2]), self.pose[:2]) - self.radius\nelse:\n centr = array(self.pose) + array([0, 0, self.height])\n dist = C... | <|body_start_0|>
super(WallBoxShape, self).__init__(oid, pose, orient, dims)
self.name = 'WallBox'
self.height = 3.75
self.radius = 0.35
<|end_body_0|>
<|body_start_1|>
if point[2] <= self.height:
dist = CubeShape._euclidean(array(point[:2]), self.pose[:2]) - self.ra... | WallBoxShape | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WallBoxShape:
def __init__(self, oid, pose, orient=[0.0, 0.0, 0.0], dims=['0.2', '5.0', '2.5']):
""":param oid: Object ID, usually the unique name used in the .world file :param pose: A tuple (x,y,z) being the centered centroid of the box :param orient: A tuple (pitch, yaw, roll) being t... | stack_v2_sparse_classes_36k_train_004511 | 1,326 | no_license | [
{
"docstring": ":param oid: Object ID, usually the unique name used in the .world file :param pose: A tuple (x,y,z) being the centered centroid of the box :param orient: A tuple (pitch, yaw, roll) being the box orientation :param dims: A tuple (dim_x, dim_y, dim_z) of the box geometry. By default it is _____",
... | 2 | stack_v2_sparse_classes_30k_train_015939 | Implement the Python class `WallBoxShape` described below.
Class description:
Implement the WallBoxShape class.
Method signatures and docstrings:
- def __init__(self, oid, pose, orient=[0.0, 0.0, 0.0], dims=['0.2', '5.0', '2.5']): :param oid: Object ID, usually the unique name used in the .world file :param pose: A t... | Implement the Python class `WallBoxShape` described below.
Class description:
Implement the WallBoxShape class.
Method signatures and docstrings:
- def __init__(self, oid, pose, orient=[0.0, 0.0, 0.0], dims=['0.2', '5.0', '2.5']): :param oid: Object ID, usually the unique name used in the .world file :param pose: A t... | a40407c2d8818f46eb66e36aad9664f94339db23 | <|skeleton|>
class WallBoxShape:
def __init__(self, oid, pose, orient=[0.0, 0.0, 0.0], dims=['0.2', '5.0', '2.5']):
""":param oid: Object ID, usually the unique name used in the .world file :param pose: A tuple (x,y,z) being the centered centroid of the box :param orient: A tuple (pitch, yaw, roll) being t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WallBoxShape:
def __init__(self, oid, pose, orient=[0.0, 0.0, 0.0], dims=['0.2', '5.0', '2.5']):
""":param oid: Object ID, usually the unique name used in the .world file :param pose: A tuple (x,y,z) being the centered centroid of the box :param orient: A tuple (pitch, yaw, roll) being the box orienta... | the_stack_v2_python_sparse | gazebo_world_gen/models/wall_box.py | Houman-HM/anafi_tools | train | 0 | |
2dc2cd219f0bd334ac091048068923c8f2d645bf | [
"if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:\n tango.Except.throw_exception(f'StartScan() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke StartScan command on cspsubarrayleafnode.', 'cspsubarrayleafnode.StartScan()', tango.ErrSeverity.ERR)... | <|body_start_0|>
if self.state_model.op_state in [DevState.FAULT, DevState.UNKNOWN, DevState.DISABLE]:
tango.Except.throw_exception(f'StartScan() is not allowed in current state {self.state_model.op_state}', 'Failed to invoke StartScan command on cspsubarrayleafnode.', 'cspsubarrayleafnode.StartScan... | A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY. | StartScanCommand | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StartScanCommand:
"""A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY."""
def check_allowed(self):
"""Checks whether the... | stack_v2_sparse_classes_36k_train_004512 | 5,057 | permissive | [
{
"docstring": "Checks whether the command is allowed to be run in the current state :return: True if this command is allowed to be run in current device state :rtype: boolean :raises: DevFailed if this command is not allowed to be run in current device state",
"name": "check_allowed",
"signature": "def... | 3 | null | Implement the Python class `StartScanCommand` described below.
Class description:
A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY.
Method signatures and ... | Implement the Python class `StartScanCommand` described below.
Class description:
A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY.
Method signatures and ... | 7ee65a9c8dada9b28893144b372a398bd0646195 | <|skeleton|>
class StartScanCommand:
"""A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY."""
def check_allowed(self):
"""Checks whether the... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StartScanCommand:
"""A class for CspSubarrayLeafNode's StartScan() command. StartScan command is inherited from BaseCommand. This command invokes Scan command on CSP Subarray. It is allowed only when CSP Subarray is in ObsState READY."""
def check_allowed(self):
"""Checks whether the command is a... | the_stack_v2_python_sparse | temp_src/ska_tmc_cspsubarrayleafnode_mid/scan_command.py | ska-telescope/tmc-prototype | train | 4 |
b376105dc380f41b6006b1a698b0c4a0f93540f6 | [
"self.config = self.trainer.config\nif vega.is_npu_device():\n count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()\nelse:\n count_input = torch.FloatTensor(1, 3, 1024, 1024).cuda()\nflops_count, params_count = calc_model_flops_params(self.trainer.model, count_input)\nself.flops_count, self.params_count = ... | <|body_start_0|>
self.config = self.trainer.config
if vega.is_npu_device():
count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()
else:
count_input = torch.FloatTensor(1, 3, 1024, 1024).cuda()
flops_count, params_count = calc_model_flops_params(self.trainer.mode... | Construct the trainer of Adelaide-EA. | SegmentationEATrainerCallback | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k_train_004513 | 1,941 | permissive | [
{
"docstring": "Be called before the training process.",
"name": "before_train",
"signature": "def before_train(self, logs=None)"
},
{
"docstring": "Update flops and params.",
"name": "after_epoch",
"signature": "def after_epoch(self, epoch, logs=None)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016847 | Implement the Python class `SegmentationEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params. | Implement the Python class `SegmentationEATrainerCallback` described below.
Class description:
Construct the trainer of Adelaide-EA.
Method signatures and docstrings:
- def before_train(self, logs=None): Be called before the training process.
- def after_epoch(self, epoch, logs=None): Update flops and params.
<|skel... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
<|body_0|>
def after_epoch(self, epoch, logs=None):
"""Update flops and params."""
<|body_1|>
<|end... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SegmentationEATrainerCallback:
"""Construct the trainer of Adelaide-EA."""
def before_train(self, logs=None):
"""Be called before the training process."""
self.config = self.trainer.config
if vega.is_npu_device():
count_input = torch.FloatTensor(1, 3, 1024, 1024).npu()... | the_stack_v2_python_sparse | vega/algorithms/nas/segmentation_ea/segmentation_ea_trainercallback.py | huawei-noah/vega | train | 850 |
64e15fa9ce188436ace05bcf08ff0538a4dc409f | [
"form_kwargs = super().get_form_kwargs()\nform_kwargs['workflow'] = self.workflow\nform_kwargs['user'] = self.request.user\nreturn form_kwargs",
"self.workflow.shared.add(form.user_obj)\nself.workflow.save()\nself.workflow.log(self.request.user, models.Log.WORKFLOW_SHARE_ADD, share_email=form.user_obj.email)\nret... | <|body_start_0|>
form_kwargs = super().get_form_kwargs()
form_kwargs['workflow'] = self.workflow
form_kwargs['user'] = self.request.user
return form_kwargs
<|end_body_0|>
<|body_start_1|>
self.workflow.shared.add(form.user_obj)
self.workflow.save()
self.workflow.... | View to create a new "share" user in the workflow. | WorkflowShareCreateView | [
"LGPL-2.0-or-later",
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"LGPL-2.1-only",
"Python-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WorkflowShareCreateView:
"""View to create a new "share" user in the workflow."""
def get_form_kwargs(self) -> Dict:
"""Store workflow and 'request.user' in kwargs"""
<|body_0|>
def form_valid(self, form) -> http.JsonResponse:
"""Store the new shared user"""
... | stack_v2_sparse_classes_36k_train_004514 | 2,685 | permissive | [
{
"docstring": "Store workflow and 'request.user' in kwargs",
"name": "get_form_kwargs",
"signature": "def get_form_kwargs(self) -> Dict"
},
{
"docstring": "Store the new shared user",
"name": "form_valid",
"signature": "def form_valid(self, form) -> http.JsonResponse"
}
] | 2 | stack_v2_sparse_classes_30k_train_009592 | Implement the Python class `WorkflowShareCreateView` described below.
Class description:
View to create a new "share" user in the workflow.
Method signatures and docstrings:
- def get_form_kwargs(self) -> Dict: Store workflow and 'request.user' in kwargs
- def form_valid(self, form) -> http.JsonResponse: Store the ne... | Implement the Python class `WorkflowShareCreateView` described below.
Class description:
View to create a new "share" user in the workflow.
Method signatures and docstrings:
- def get_form_kwargs(self) -> Dict: Store workflow and 'request.user' in kwargs
- def form_valid(self, form) -> http.JsonResponse: Store the ne... | c432745dfff932cbe7397100422d49df78f0a882 | <|skeleton|>
class WorkflowShareCreateView:
"""View to create a new "share" user in the workflow."""
def get_form_kwargs(self) -> Dict:
"""Store workflow and 'request.user' in kwargs"""
<|body_0|>
def form_valid(self, form) -> http.JsonResponse:
"""Store the new shared user"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WorkflowShareCreateView:
"""View to create a new "share" user in the workflow."""
def get_form_kwargs(self) -> Dict:
"""Store workflow and 'request.user' in kwargs"""
form_kwargs = super().get_form_kwargs()
form_kwargs['workflow'] = self.workflow
form_kwargs['user'] = self... | the_stack_v2_python_sparse | ontask/workflow/views/share.py | abelardopardo/ontask_b | train | 43 |
f2acc81bdafcb72dbc9753477a78cbbdaf72742f | [
"s = pandas.HDFStore(path_or_buf)\ngroups = s.groups()\nif len(groups) == 0:\n raise ValueError('No dataset in HDF5 file.')\ncandidate_only_group = groups[0]\nformat = getattr(candidate_only_group._v_attrs, 'table_type', None)\ns.close()\nreturn format",
"if cls._validate_hdf_format(path_or_buf=path_or_buf) is... | <|body_start_0|>
s = pandas.HDFStore(path_or_buf)
groups = s.groups()
if len(groups) == 0:
raise ValueError('No dataset in HDF5 file.')
candidate_only_group = groups[0]
format = getattr(candidate_only_group._v_attrs, 'table_type', None)
s.close()
retur... | Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class. | HDFDispatcher | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group ... | stack_v2_sparse_classes_36k_train_004515 | 3,478 | permissive | [
{
"docstring": "Validate `path_or_buf` and then return `table_type` parameter of store group attribute. Parameters ---------- path_or_buf : str, buffer or path object Path to the file to open, or an open :class:`pandas.HDFStore` object. Returns ------- str `table_type` parameter of store group attribute.",
... | 2 | stack_v2_sparse_classes_30k_train_008512 | Implement the Python class `HDFDispatcher` described below.
Class description:
Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class.
Method signatures and docstrings:
- def _validate_hdf_format(cls, path_or_buf): Validate `path_or_bu... | Implement the Python class `HDFDispatcher` described below.
Class description:
Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class.
Method signatures and docstrings:
- def _validate_hdf_format(cls, path_or_buf): Validate `path_or_bu... | 8f6e00378e095817deccd25f4140406c5ee6c992 | <|skeleton|>
class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HDFDispatcher:
"""Class handles utils for reading hdf data. Inherits some common for columnar store files util functions from `ColumnStoreDispatcher` class."""
def _validate_hdf_format(cls, path_or_buf):
"""Validate `path_or_buf` and then return `table_type` parameter of store group attribute. Pa... | the_stack_v2_python_sparse | modin/core/io/column_stores/hdf_dispatcher.py | modin-project/modin | train | 9,241 |
c120acd5af964ec3df331bad4fdbd6ba6a8889a2 | [
"super(BertOutput, self).__init__()\nself.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)\nself.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)\nself.dropout = nn.Dropout(p=config.hidden_dropout_prob)\nself.cast = ... | <|body_start_0|>
super(BertOutput, self).__init__()
self.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.layer_norm_eps).to_float(mindspore.float16)
self.dropout = nn.Dropout(p=... | bert output | BertOutput | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(BertOutput, self).__init__()
sel... | stack_v2_sparse_classes_36k_train_004516 | 16,172 | permissive | [
{
"docstring": "init fun",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "construct fun",
"name": "construct",
"signature": "def construct(self, hidden_states, input_tensor)"
}
] | 2 | null | Implement the Python class `BertOutput` described below.
Class description:
bert output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun | Implement the Python class `BertOutput` described below.
Class description:
bert output
Method signatures and docstrings:
- def __init__(self, config): init fun
- def construct(self, hidden_states, input_tensor): construct fun
<|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
... | eab643f51336dbf7d711f02d27e6516e5affee59 | <|skeleton|>
class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
<|body_0|>
def construct(self, hidden_states, input_tensor):
"""construct fun"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class BertOutput:
"""bert output"""
def __init__(self, config):
"""init fun"""
super(BertOutput, self).__init__()
self.dense = nn.Dense(config.intermediate_size, config.hidden_size).to_float(mindspore.float16)
self.LayerNorm = nn.LayerNorm((config.hidden_size,), epsilon=config.l... | the_stack_v2_python_sparse | research/nlp/luke/src/luke/robert.py | mindspore-ai/models | train | 301 |
1dec232c998054ac9519fe01670fda0fc2c3a33b | [
"Account = apps.get_model('finance', 'Account')\nUser = apps.get_model('web', 'User')\nfor user in User.objects.filter(is_closed_account=False):\n fs = user.get_funding_source_account()\n if not fs:\n continue\n sum = user.get_not_processed_roundup_sum()\n if sum >= settings.TRANSFER_TO_DONKIES_M... | <|body_start_0|>
Account = apps.get_model('finance', 'Account')
User = apps.get_model('web', 'User')
for user in User.objects.filter(is_closed_account=False):
fs = user.get_funding_source_account()
if not fs:
continue
sum = user.get_not_process... | TransferPrepareManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransferPrepareManager:
def process_roundups(self):
"""Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send transfer to Donkies LLC. Called by celery scheduled task. Processes all roundups for all users to TransferPrep... | stack_v2_sparse_classes_36k_train_004517 | 4,116 | no_license | [
{
"docstring": "Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send transfer to Donkies LLC. Called by celery scheduled task. Processes all roundups for all users to TransferPrepare. 1) If user didn't set funding source, do not process user.... | 2 | null | Implement the Python class `TransferPrepareManager` described below.
Class description:
Implement the TransferPrepareManager class.
Method signatures and docstrings:
- def process_roundups(self): Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send... | Implement the Python class `TransferPrepareManager` described below.
Class description:
Implement the TransferPrepareManager class.
Method signatures and docstrings:
- def process_roundups(self): Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send... | 289513320714ee6b75391cce4143e957eb232e30 | <|skeleton|>
class TransferPrepareManager:
def process_roundups(self):
"""Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send transfer to Donkies LLC. Called by celery scheduled task. Processes all roundups for all users to TransferPrep... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransferPrepareManager:
def process_roundups(self):
"""Roundup transfer rule - by amount. As soon as collected roundup is more than settings.TRANSFER_TO_DONKIES_MIN_AMOUNT, send transfer to Donkies LLC. Called by celery scheduled task. Processes all roundups for all users to TransferPrepare. 1) If use... | the_stack_v2_python_sparse | donkies/finance/models/transfer_prepare.py | ryanam26/DonkiesAPI | train | 0 | |
5ed5229d66f2a4e7401fb96394fabbc2f3965c93 | [
"super().__init__(env, name, seed)\nself.buffer_processing_matrix = env.job_generator.buffer_processing_matrix\nself.safety_stock = safety_stock",
"_, num_activities = self.constituency_matrix.shape\naction = np.zeros((num_activities, 1))\nfor constituency_s, boundary_constraint_matrix_s in zip(self.constituency_... | <|body_start_0|>
super().__init__(env, name, seed)
self.buffer_processing_matrix = env.job_generator.buffer_processing_matrix
self.safety_stock = safety_stock
<|end_body_0|>
<|body_start_1|>
_, num_activities = self.constituency_matrix.shape
action = np.zeros((num_activities, 1)... | LongestBufferPriorityAgent | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers,... | stack_v2_sparse_classes_36k_train_004518 | 3,606 | permissive | [
{
"docstring": "Non-idling policy such that every resource works on the buffer with largest amount of customers, and that are above the specified safety_stock. If there are multiple buffers with the same largest size and/or multiple activities, each resource chooses among them randomly. :param env: the environm... | 2 | stack_v2_sparse_classes_30k_train_019407 | Implement the Python class `LongestBufferPriorityAgent` described below.
Class description:
Implement the LongestBufferPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[i... | Implement the Python class `LongestBufferPriorityAgent` described below.
Class description:
Implement the LongestBufferPriorityAgent class.
Method signatures and docstrings:
- def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[i... | b067eebaa5b57a96efdaed5796aca9f157d32214 | <|skeleton|>
class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LongestBufferPriorityAgent:
def __init__(self, env: crw.ControlledRandomWalk, safety_stock: Optional[float]=10.0, name: str='LongestBufferPriorityAgent', seed: Optional[int]=None) -> None:
"""Non-idling policy such that every resource works on the buffer with largest amount of customers, and that are ... | the_stack_v2_python_sparse | src/snc/agents/general_heuristics/longest_buffer_priority_agent.py | stochasticnetworkcontrol/snc | train | 9 | |
c4c84fc9aa825bbe3ee887aae9f3d14c89e9b7f8 | [
"new_urls = set()\nlinks = soup.find_all('a', href=re.compile('/item/'))\nfor link in links:\n new_url = link['href']\n new_full_url = 'http://baike.baidu.com' + new_url\n new_urls.add(new_full_url)\nreturn new_urls",
"res_data = dict()\nres_data['url'] = page_url\ntitle_node = soup.find('dd', class_='le... | <|body_start_0|>
new_urls = set()
links = soup.find_all('a', href=re.compile('/item/'))
for link in links:
new_url = link['href']
new_full_url = 'http://baike.baidu.com' + new_url
new_urls.add(new_full_url)
return new_urls
<|end_body_0|>
<|body_start_... | HtmlParser | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
<|body_0|>
def __get_new_data(self, page_url, soup):
"""获取内容"""
<|body_1|>
def parse(self, page_url, html_content):
"""解析 html"""
<|body_2|>
<|end_skeleton|>
<|body_sta... | stack_v2_sparse_classes_36k_train_004519 | 1,465 | no_license | [
{
"docstring": "发现新的url",
"name": "__get_new_urls",
"signature": "def __get_new_urls(self, page_url, soup)"
},
{
"docstring": "获取内容",
"name": "__get_new_data",
"signature": "def __get_new_data(self, page_url, soup)"
},
{
"docstring": "解析 html",
"name": "parse",
"signature... | 3 | stack_v2_sparse_classes_30k_train_008978 | Implement the Python class `HtmlParser` described below.
Class description:
Implement the HtmlParser class.
Method signatures and docstrings:
- def __get_new_urls(self, page_url, soup): 发现新的url
- def __get_new_data(self, page_url, soup): 获取内容
- def parse(self, page_url, html_content): 解析 html | Implement the Python class `HtmlParser` described below.
Class description:
Implement the HtmlParser class.
Method signatures and docstrings:
- def __get_new_urls(self, page_url, soup): 发现新的url
- def __get_new_data(self, page_url, soup): 获取内容
- def parse(self, page_url, html_content): 解析 html
<|skeleton|>
class Html... | 98e41ebf5eb3ab2335c82bcc78d8171fd7e8d460 | <|skeleton|>
class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
<|body_0|>
def __get_new_data(self, page_url, soup):
"""获取内容"""
<|body_1|>
def parse(self, page_url, html_content):
"""解析 html"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HtmlParser:
def __get_new_urls(self, page_url, soup):
"""发现新的url"""
new_urls = set()
links = soup.find_all('a', href=re.compile('/item/'))
for link in links:
new_url = link['href']
new_full_url = 'http://baike.baidu.com' + new_url
new_urls.ad... | the_stack_v2_python_sparse | spider004/html_parser.py | geeksuperbin/newspider | train | 0 | |
dfb5b6fe25698cbcd0a53a4baddd0cee6eb25db0 | [
"self.SetStartDate(2013, 1, 7)\nself.SetEndDate(2013, 12, 11)\nself.EnableAutomaticIndicatorWarmUp = True\nself.AddEquity('SPY', Resolution.Daily)\nself.arima = self.ARIMA('SPY', 1, 1, 1, 50)\nself.ar = self.ARIMA('SPY', 1, 1, 0, 50)",
"if self.arima.IsReady:\n if abs(self.arima.Current.Value - self.ar.Current... | <|body_start_0|>
self.SetStartDate(2013, 1, 7)
self.SetEndDate(2013, 12, 11)
self.EnableAutomaticIndicatorWarmUp = True
self.AddEquity('SPY', Resolution.Daily)
self.arima = self.ARIMA('SPY', 1, 1, 1, 50)
self.ar = self.ARIMA('SPY', 1, 1, 0, 50)
<|end_body_0|>
<|body_star... | AutoRegressiveIntegratedMovingAverageRegressionAlgorithm | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnDat... | stack_v2_sparse_classes_36k_train_004520 | 2,150 | permissive | [
{
"docstring": "Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.",
"name": "Initialize",
"signature": "def Initialize(self)"
},
{
"docstring": "OnData event is the primary entry point for your algorithm. Eac... | 2 | null | Implement the Python class `AutoRegressiveIntegratedMovingAverageRegressionAlgorithm` described below.
Class description:
Implement the AutoRegressiveIntegratedMovingAverageRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the ... | Implement the Python class `AutoRegressiveIntegratedMovingAverageRegressionAlgorithm` described below.
Class description:
Implement the AutoRegressiveIntegratedMovingAverageRegressionAlgorithm class.
Method signatures and docstrings:
- def Initialize(self): Initialise the data and resolution required, as well as the ... | b33dd3bc140e14b883f39ecf848a793cf7292277 | <|skeleton|>
class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
<|body_0|>
def OnData(self, data):
"""OnDat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AutoRegressiveIntegratedMovingAverageRegressionAlgorithm:
def Initialize(self):
"""Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized."""
self.SetStartDate(2013, 1, 7)
self.SetEndDate(2013, 12, 11)
... | the_stack_v2_python_sparse | Algorithm.Python/AutoRegressiveIntegratedMovingAverageRegressionAlgorithm.py | Capnode/Algoloop | train | 87 | |
55169e4fd536e744475f8442c4d55a4938ea1469 | [
"super(TripletLoss, self).__init__()\nif margin:\n self.parser = margin_ranking_loss_parser\n self.loss = nn.MarginRankingLoss(margin=margin, reduction=reduction)\nelse:\n self.parser = soft_margin_loss_parser\n self.loss = nn.SoftMarginLoss(reduction=reduction)",
"if mask is not None:\n pos_output... | <|body_start_0|>
super(TripletLoss, self).__init__()
if margin:
self.parser = margin_ranking_loss_parser
self.loss = nn.MarginRankingLoss(margin=margin, reduction=reduction)
else:
self.parser = soft_margin_loss_parser
self.loss = nn.SoftMarginLoss(... | TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in this package. For the calculation, the ... | TripletLoss | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in ... | stack_v2_sparse_classes_36k_train_004521 | 9,218 | permissive | [
{
"docstring": "Initialize TripletLoss Args: margin (float, optional): size of margin. Defaults to 1.0. reduction (str, optional): method of reduction. Defaults to None.",
"name": "__init__",
"signature": "def __init__(self, margin: float=1.0, reduction: str=None)"
},
{
"docstring": "Forward cal... | 2 | stack_v2_sparse_classes_30k_train_019949 | Implement the Python class `TripletLoss` described below.
Class description:
TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling m... | Implement the Python class `TripletLoss` described below.
Class description:
TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling m... | 07a6a38c7eb44225f2b22f332081f697c3b92894 | <|skeleton|>
class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TripletLoss:
"""TripletLoss is a pairwise ranking loss which is used in FaceNet at first, and implemented by PyTorch in module\\: torch.nn.MarginRankingLoss and torch.nn.SoftMarginLoss. This module is an integration of those losses as a standardize calling method with other losses implemented in this package.... | the_stack_v2_python_sparse | torecsys/losses/ltr/pairwise_ranking_loss.py | zwcdp/torecsys | train | 0 |
660b936bb405bc12c066732d03058e4cf5acc6e3 | [
"if durations is None or len(durations) < 2:\n return [-1, -1]\nduration_list = []\nindex = 0\nfor duration in durations:\n duration_list.append((duration, index))\n index += 1\nduration_list.sort(key=lambda x: x[0])\nmax_sum = -sys.maxsize - 1\nres = [-1, -1]\nstart, end = (0, len(duration_list) - 1)\ntar... | <|body_start_0|>
if durations is None or len(durations) < 2:
return [-1, -1]
duration_list = []
index = 0
for duration in durations:
duration_list.append((duration, index))
index += 1
duration_list.sort(key=lambda x: x[0])
max_sum = -sy... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def twoSumCloest(self, durations, k):
""":param durations: movie list, :param k: integer flight time :return: [,]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k_train_004522 | 4,285 | no_license | [
{
"docstring": ":param durations: movie list, :param k: integer flight time :return: [,]",
"name": "twoSumCloest",
"signature": "def twoSumCloest(self, durations, k)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[int]",
"name": "twoSum",
"signature": "def twoSum... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSumCloest(self, durations, k): :param durations: movie list, :param k: integer flight time :return: [,]
- def twoSum(self, nums, target): :type nums: List[int] :type targe... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def twoSumCloest(self, durations, k): :param durations: movie list, :param k: integer flight time :return: [,]
- def twoSum(self, nums, target): :type nums: List[int] :type targe... | f6df35359b223cdd1635c287455032ae1463906f | <|skeleton|>
class Solution:
def twoSumCloest(self, durations, k):
""":param durations: movie list, :param k: integer flight time :return: [,]"""
<|body_0|>
def twoSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[int]"""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def twoSumCloest(self, durations, k):
""":param durations: movie list, :param k: integer flight time :return: [,]"""
if durations is None or len(durations) < 2:
return [-1, -1]
duration_list = []
index = 0
for duration in durations:
dur... | the_stack_v2_python_sparse | LeetCode/src/0TwoSumClosest.py | jinwei15/java-PythonSyntax-Leetcode | train | 0 | |
6d2985562a8594e5cc50ded9c4306dd4f971c9f0 | [
"self.num_points = num_points\nself.x_values = [0]\nself.y_values = [0]",
"while len(self.x_values) < self.num_points:\n x_direction = choice([1, -1])\n x_distance = choice([0, 1, 2, 3, 4])\n x_step = x_direction * x_distance\n y_direction = choice([1, -1])\n y_distance = choice([0, 1, 2, 3, 4])\n ... | <|body_start_0|>
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
<|end_body_0|>
<|body_start_1|>
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_step = x_direction *... | Uma classe para gerar passeios aleatórios | RandomWalk | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RandomWalk:
"""Uma classe para gerar passeios aleatórios"""
def __init__(self, num_points=5000):
"""Inicializa os atributos de um passeio."""
<|body_0|>
def fill_walk(self):
"""Calcula todos os pontos do passeio, aleatoriamente."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k_train_004523 | 1,757 | no_license | [
{
"docstring": "Inicializa os atributos de um passeio.",
"name": "__init__",
"signature": "def __init__(self, num_points=5000)"
},
{
"docstring": "Calcula todos os pontos do passeio, aleatoriamente.",
"name": "fill_walk",
"signature": "def fill_walk(self)"
}
] | 2 | null | Implement the Python class `RandomWalk` described below.
Class description:
Uma classe para gerar passeios aleatórios
Method signatures and docstrings:
- def __init__(self, num_points=5000): Inicializa os atributos de um passeio.
- def fill_walk(self): Calcula todos os pontos do passeio, aleatoriamente. | Implement the Python class `RandomWalk` described below.
Class description:
Uma classe para gerar passeios aleatórios
Method signatures and docstrings:
- def __init__(self, num_points=5000): Inicializa os atributos de um passeio.
- def fill_walk(self): Calcula todos os pontos do passeio, aleatoriamente.
<|skeleton|>... | 6f89b5f1080c79eb5fa6718d037ca4132977569d | <|skeleton|>
class RandomWalk:
"""Uma classe para gerar passeios aleatórios"""
def __init__(self, num_points=5000):
"""Inicializa os atributos de um passeio."""
<|body_0|>
def fill_walk(self):
"""Calcula todos os pontos do passeio, aleatoriamente."""
<|body_1|>
<|end_skele... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RandomWalk:
"""Uma classe para gerar passeios aleatórios"""
def __init__(self, num_points=5000):
"""Inicializa os atributos de um passeio."""
self.num_points = num_points
self.x_values = [0]
self.y_values = [0]
def fill_walk(self):
"""Calcula todos os pontos d... | the_stack_v2_python_sparse | 15_Dados/random_walk.py | washingtoncandeia/PyCrashCourse | train | 0 |
71db27f636a271be95aa3d6e307147f95f194316 | [
"self.modelLocation = os.path.join(routes.routePDM, 'models', str('%03d' % modelNum))\nself.outputDir = os.path.join(self.modelLocation, str('%03d' % modelNum) + '_output' + str(simNum))\nself.trajFile = os.path.join(self.outputDir, 'sTraj' + str(trajNum) + '.p')\nself.trajectory = (modelNum, simNum, trajNum)\nif l... | <|body_start_0|>
self.modelLocation = os.path.join(routes.routePDM, 'models', str('%03d' % modelNum))
self.outputDir = os.path.join(self.modelLocation, str('%03d' % modelNum) + '_output' + str(simNum))
self.trajFile = os.path.join(self.outputDir, 'sTraj' + str(trajNum) + '.p')
self.traje... | This class analyzes various aspects of stochastic simulations in the pdmmod framework | ShapeTrajectory | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ShapeTrajectory:
"""This class analyzes various aspects of stochastic simulations in the pdmmod framework"""
def __init__(self, modelNum, simNum, trajNum, load=False):
"""Arguments: - modelNum -- int, number of the model - simuNum -- int, number of the simulation, simulations within ... | stack_v2_sparse_classes_36k_train_004524 | 1,898 | no_license | [
{
"docstring": "Arguments: - modelNum -- int, number of the model - simuNum -- int, number of the simulation, simulations within one model are usually differ by different parameters - trajNum -- int, number of trajectory. A simulation with a given set of the parameters can be run for several times to form an en... | 2 | stack_v2_sparse_classes_30k_train_004988 | Implement the Python class `ShapeTrajectory` described below.
Class description:
This class analyzes various aspects of stochastic simulations in the pdmmod framework
Method signatures and docstrings:
- def __init__(self, modelNum, simNum, trajNum, load=False): Arguments: - modelNum -- int, number of the model - simu... | Implement the Python class `ShapeTrajectory` described below.
Class description:
This class analyzes various aspects of stochastic simulations in the pdmmod framework
Method signatures and docstrings:
- def __init__(self, modelNum, simNum, trajNum, load=False): Arguments: - modelNum -- int, number of the model - simu... | ab81b6f7a8660c2d989e97a43fc7e663a646d18c | <|skeleton|>
class ShapeTrajectory:
"""This class analyzes various aspects of stochastic simulations in the pdmmod framework"""
def __init__(self, modelNum, simNum, trajNum, load=False):
"""Arguments: - modelNum -- int, number of the model - simuNum -- int, number of the simulation, simulations within ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ShapeTrajectory:
"""This class analyzes various aspects of stochastic simulations in the pdmmod framework"""
def __init__(self, modelNum, simNum, trajNum, load=False):
"""Arguments: - modelNum -- int, number of the model - simuNum -- int, number of the simulation, simulations within one model are... | the_stack_v2_python_sparse | shapeTrajectory.py | gelisa/pdmmod | train | 0 |
c27ed9954d6fe65a5b6744be342aa351e8c941dd | [
"index1 = index2 = -1\nmin_distance = len(words)\nfor idx in range(len(words)):\n if words[idx] == word1:\n index1 = idx\n elif words[idx] == word2:\n index2 = idx\n if index1 != -1 and index2 != -1:\n min_distance = min(min_distance, abs(index1 - index2))\nreturn min_distance",
"min... | <|body_start_0|>
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(words)):
if words[idx] == word1:
index1 = idx
elif words[idx] == word2:
index2 = idx
if index1 != -1 and index2 != -1:
min_dist... | Words | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_36k_train_004525 | 1,554 | no_license | [
{
"docstring": "Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:",
"name": "shortest_distance",
"signature": "def shortest_distance(self, words: List[str], word1: str, word2: str) -> int"
},
{
"docstring": "Approach: Brute For... | 2 | stack_v2_sparse_classes_30k_train_016477 | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | Implement the Python class `Words` described below.
Class description:
Implement the Words class.
Method signatures and docstrings:
- def shortest_distance(self, words: List[str], word1: str, word2: str) -> int: Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param wor... | 65cc78b5afa0db064f9fe8f06597e3e120f7363d | <|skeleton|>
class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
<|body_0|>
def shortest_distance_(self, words: List[str], word1: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Words:
def shortest_distance(self, words: List[str], word1: str, word2: str) -> int:
"""Approach: One Pass Time Complexity: O(N * M) Space Complexity: O(1) :param words: :param word1: :param word2: :return:"""
index1 = index2 = -1
min_distance = len(words)
for idx in range(len(... | the_stack_v2_python_sparse | revisited_2021/arrays/shortest_word_distance.py | Shiv2157k/leet_code | train | 1 | |
2d3a94dbdbc69e3eff3d48c6b51c8e2a3c56d0ac | [
"self.length = len(nums)\nself.st = [0] * self.length\nself.st.extend(nums)\nfor i in range(self.length - 1, 0, -1):\n self.st[i] = self.st[2 * i] + self.st[2 * i + 1]",
"if -1 < i < self.length:\n p = i + self.length\n self.st[p] = val\n while p > 1:\n self.st[p // 2] = self.st[p] + self.st[p ... | <|body_start_0|>
self.length = len(nums)
self.st = [0] * self.length
self.st.extend(nums)
for i in range(self.length - 1, 0, -1):
self.st[i] = self.st[2 * i] + self.st[2 * i + 1]
<|end_body_0|>
<|body_start_1|>
if -1 < i < self.length:
p = i + self.length... | NumArray_SegmentTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
... | stack_v2_sparse_classes_36k_train_004526 | 4,069 | no_license | [
{
"docstring": ":type nums: List[int]",
"name": "__init__",
"signature": "def __init__(self, nums)"
},
{
"docstring": ":type i: int :type val: int :rtype: void",
"name": "update",
"signature": "def update(self, i, val)"
},
{
"docstring": ":type i: int :type j: int :rtype: int",
... | 3 | null | Implement the Python class `NumArray_SegmentTree` described below.
Class description:
Implement the NumArray_SegmentTree class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: ... | Implement the Python class `NumArray_SegmentTree` described below.
Class description:
Implement the NumArray_SegmentTree class.
Method signatures and docstrings:
- def __init__(self, nums): :type nums: List[int]
- def update(self, i, val): :type i: int :type val: int :rtype: void
- def sumRange(self, i, j): :type i: ... | 635af6e22aa8eef8e7920a585d43a45a891a8157 | <|skeleton|>
class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
<|body_0|>
def update(self, i, val):
""":type i: int :type val: int :rtype: void"""
<|body_1|>
def sumRange(self, i, j):
""":type i: int :type j: int :rtype: int"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NumArray_SegmentTree:
def __init__(self, nums):
""":type nums: List[int]"""
self.length = len(nums)
self.st = [0] * self.length
self.st.extend(nums)
for i in range(self.length - 1, 0, -1):
self.st[i] = self.st[2 * i] + self.st[2 * i + 1]
def update(self... | the_stack_v2_python_sparse | code307RangeSumQueryMutable.py | cybelewang/leetcode-python | train | 0 | |
5e93b102f770ee548406da7a6f30135a4fd1a2e9 | [
"xlen = len(matrix[0])\nylen = len(matrix)\nxy_dict = self.toXYDict(matrix)\ndiagonal_starts = self.getStarts(xlen, ylen)\nall_diags = self.getDiags(xy_dict, diagonal_starts)\nreturn all([all((items[0] == item for item in items)) for items in all_diags])",
"xy_dict = {}\nfor row_ix in range(len(matrix)):\n for... | <|body_start_0|>
xlen = len(matrix[0])
ylen = len(matrix)
xy_dict = self.toXYDict(matrix)
diagonal_starts = self.getStarts(xlen, ylen)
all_diags = self.getDiags(xy_dict, diagonal_starts)
return all([all((items[0] == item for item in items)) for items in all_diags])
<|end_... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isToeplitzMatrix(self, matrix):
"""Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool"""
<|body_0|>
def toXYDict(self, matrix):
"""Converts a 2D array into xy-coord dict :type matrix: List[List[i... | stack_v2_sparse_classes_36k_train_004527 | 2,477 | no_license | [
{
"docstring": "Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool",
"name": "isToeplitzMatrix",
"signature": "def isToeplitzMatrix(self, matrix)"
},
{
"docstring": "Converts a 2D array into xy-coord dict :type matrix: List[List[int]] :rt... | 4 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isToeplitzMatrix(self, matrix): Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool
- def toXYDict(self, matrix): Con... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isToeplitzMatrix(self, matrix): Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool
- def toXYDict(self, matrix): Con... | 308889e57e71c369aa8516fba8a2064f6a26abee | <|skeleton|>
class Solution:
def isToeplitzMatrix(self, matrix):
"""Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool"""
<|body_0|>
def toXYDict(self, matrix):
"""Converts a 2D array into xy-coord dict :type matrix: List[List[i... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isToeplitzMatrix(self, matrix):
"""Determines if every value within a matrix's diagonals is the same :type matrix: List[List[int]] :rtype: bool"""
xlen = len(matrix[0])
ylen = len(matrix)
xy_dict = self.toXYDict(matrix)
diagonal_starts = self.getStarts(xle... | the_stack_v2_python_sparse | leet_766.py | mike-jolliffe/Learning | train | 0 | |
4c4f953022ed05a2f2777264260b767d4f898a40 | [
"min = 1 << 31\nmax = -(1 << 31)\nif len(arr) % 2 != 0:\n min = arr[0]\n max = arr[0]\nfor i in range(0, len(arr) - 1, 2):\n if arr[i] > arr[i + 1]:\n if max < arr[i]:\n max = arr[i]\n if min > arr[i + 1]:\n min = arr[i + 1]\n else:\n if max < arr[i + 1]:\n ... | <|body_start_0|>
min = 1 << 31
max = -(1 << 31)
if len(arr) % 2 != 0:
min = arr[0]
max = arr[0]
for i in range(0, len(arr) - 1, 2):
if arr[i] > arr[i + 1]:
if max < arr[i]:
max = arr[i]
if min > arr[i... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def min_max(self, arr):
"""faster min/max algorithm, using only 3/2*n comparisons"""
<|body_0|>
def maximumGap(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
min = 1 << 31
max = -(... | stack_v2_sparse_classes_36k_train_004528 | 2,218 | no_license | [
{
"docstring": "faster min/max algorithm, using only 3/2*n comparisons",
"name": "min_max",
"signature": "def min_max(self, arr)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "maximumGap",
"signature": "def maximumGap(self, nums)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def min_max(self, arr): faster min/max algorithm, using only 3/2*n comparisons
- def maximumGap(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 min_max(self, arr): faster min/max algorithm, using only 3/2*n comparisons
- def maximumGap(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 22f34f2d7c43945e2bf787092de887c3dff64768 | <|skeleton|>
class Solution:
def min_max(self, arr):
"""faster min/max algorithm, using only 3/2*n comparisons"""
<|body_0|>
def maximumGap(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def min_max(self, arr):
"""faster min/max algorithm, using only 3/2*n comparisons"""
min = 1 << 31
max = -(1 << 31)
if len(arr) % 2 != 0:
min = arr[0]
max = arr[0]
for i in range(0, len(arr) - 1, 2):
if arr[i] > arr[i + 1]:
... | the_stack_v2_python_sparse | 164_maximum_gap/main.py | EMIAOZANG/leetcode_questions | train | 0 | |
cb86a359d698192bb8914a16af1ec0009f912cc3 | [
"super().__init__()\nself.name = 'MatplotlibViewer'\nself.embedded = False\nself.plotter = None\nself.layout = 'grid'\nself.max_plot = None\nself.title = title\nself.share_axes = 'both'",
"if not self.display_data:\n self.close()\n return\nif self.plotter is None or not self.plotter.isVisible():\n self.p... | <|body_start_0|>
super().__init__()
self.name = 'MatplotlibViewer'
self.embedded = False
self.plotter = None
self.layout = 'grid'
self.max_plot = None
self.title = title
self.share_axes = 'both'
<|end_body_0|>
<|body_start_1|>
if not self.display_... | MatplotlibViewer | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MatplotlibViewer:
def __init__(self, title=None):
"""Basic Matplotlib viewer."""
<|body_0|>
def display(self):
"""Display a plot in a Matplotlib canvas."""
<|body_1|>
def close(self):
"""Close the viewer."""
<|body_2|>
<|end_skeleton|>
... | stack_v2_sparse_classes_36k_train_004529 | 10,277 | permissive | [
{
"docstring": "Basic Matplotlib viewer.",
"name": "__init__",
"signature": "def __init__(self, title=None)"
},
{
"docstring": "Display a plot in a Matplotlib canvas.",
"name": "display",
"signature": "def display(self)"
},
{
"docstring": "Close the viewer.",
"name": "close",... | 3 | null | Implement the Python class `MatplotlibViewer` described below.
Class description:
Implement the MatplotlibViewer class.
Method signatures and docstrings:
- def __init__(self, title=None): Basic Matplotlib viewer.
- def display(self): Display a plot in a Matplotlib canvas.
- def close(self): Close the viewer. | Implement the Python class `MatplotlibViewer` described below.
Class description:
Implement the MatplotlibViewer class.
Method signatures and docstrings:
- def __init__(self, title=None): Basic Matplotlib viewer.
- def display(self): Display a plot in a Matplotlib canvas.
- def close(self): Close the viewer.
<|skele... | 493700340cd34d5f319af6f3a562a82135bb30dd | <|skeleton|>
class MatplotlibViewer:
def __init__(self, title=None):
"""Basic Matplotlib viewer."""
<|body_0|>
def display(self):
"""Display a plot in a Matplotlib canvas."""
<|body_1|>
def close(self):
"""Close the viewer."""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MatplotlibViewer:
def __init__(self, title=None):
"""Basic Matplotlib viewer."""
super().__init__()
self.name = 'MatplotlibViewer'
self.embedded = False
self.plotter = None
self.layout = 'grid'
self.max_plot = None
self.title = title
self... | the_stack_v2_python_sparse | sofia_redux/pipeline/gui/matplotlib_viewer.py | SOFIA-USRA/sofia_redux | train | 12 | |
75510f50adcfbc81e7942916c7397b2afb03e646 | [
"options = super()._default_options()\noptions.plotter.set_figure_options(xlabel='Delay', ylabel='P(1)', xval_unit='s')\noptions.result_parameters = [curve.ParameterRepr('tau', 'T1', 's')]\nreturn options",
"amp = fit_data.ufloat_params['amp']\ntau = fit_data.ufloat_params['tau']\nbase = fit_data.ufloat_params['b... | <|body_start_0|>
options = super()._default_options()
options.plotter.set_figure_options(xlabel='Delay', ylabel='P(1)', xval_unit='s')
options.result_parameters = [curve.ParameterRepr('tau', 'T1', 's')]
return options
<|end_body_0|>
<|body_start_1|>
amp = fit_data.ufloat_params[... | A class to analyze T1 experiments. | T1Analysis | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class T1Analysis:
"""A class to analyze T1 experiments."""
def _default_options(cls) -> Options:
"""Default analysis options."""
<|body_0|>
def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:
"""Algorithmic criteria for whether the fit is g... | stack_v2_sparse_classes_36k_train_004530 | 4,817 | permissive | [
{
"docstring": "Default analysis options.",
"name": "_default_options",
"signature": "def _default_options(cls) -> Options"
},
{
"docstring": "Algorithmic criteria for whether the fit is good or bad. A good fit has: - a reduced chi-squared lower than three - absolute amp is within [0.9, 1.1] - b... | 2 | null | Implement the Python class `T1Analysis` described below.
Class description:
A class to analyze T1 experiments.
Method signatures and docstrings:
- def _default_options(cls) -> Options: Default analysis options.
- def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]: Algorithmic criteria for... | Implement the Python class `T1Analysis` described below.
Class description:
A class to analyze T1 experiments.
Method signatures and docstrings:
- def _default_options(cls) -> Options: Default analysis options.
- def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]: Algorithmic criteria for... | a387675a3fe817cef05b968bbf3e05799a09aaae | <|skeleton|>
class T1Analysis:
"""A class to analyze T1 experiments."""
def _default_options(cls) -> Options:
"""Default analysis options."""
<|body_0|>
def _evaluate_quality(self, fit_data: curve.CurveFitResult) -> Union[str, None]:
"""Algorithmic criteria for whether the fit is g... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class T1Analysis:
"""A class to analyze T1 experiments."""
def _default_options(cls) -> Options:
"""Default analysis options."""
options = super()._default_options()
options.plotter.set_figure_options(xlabel='Delay', ylabel='P(1)', xval_unit='s')
options.result_parameters = [cur... | the_stack_v2_python_sparse | qiskit_experiments/library/characterization/analysis/t1_analysis.py | oliverdial/qiskit-experiments | train | 0 |
2b5dfb686d9c171a41895ab370823ccbb514b542 | [
"installed = dpkg.installed()\nrgx = '^gcc-(?P<version>(?P<major>[0-9]+)(\\\\.(?P<minor>[0-9]+))?)$'\nscanner = re.compile(rgx)\nfor key in installed.keys():\n match = scanner.match(key)\n if match:\n version = ''.join(match.group('version').split('.'))\n name = 'gcc' + version\n packages... | <|body_start_0|>
installed = dpkg.installed()
rgx = '^gcc-(?P<version>(?P<major>[0-9]+)(\\.(?P<minor>[0-9]+))?)$'
scanner = re.compile(rgx)
for key in installed.keys():
match = scanner.match(key)
if match:
version = ''.join(match.group('version').s... | The package manager for GCC installations | GCC | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GCC:
"""The package manager for GCC installations"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide al... | stack_v2_sparse_classes_36k_train_004531 | 9,096 | permissive | [
{
"docstring": "Go through the installed packages and identify those that are relevant for providing support for my installations",
"name": "dpkgAlternatives",
"signature": "def dpkgAlternatives(cls, dpkg)"
},
{
"docstring": "Provide alternative compatible implementations of python on dpkg machi... | 3 | null | Implement the Python class `GCC` described below.
Class description:
The package manager for GCC installations
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Go through the installed packages and identify those that are relevant for providing support for my installations
- def dpkgPackages(cls, ... | Implement the Python class `GCC` described below.
Class description:
The package manager for GCC installations
Method signatures and docstrings:
- def dpkgAlternatives(cls, dpkg): Go through the installed packages and identify those that are relevant for providing support for my installations
- def dpkgPackages(cls, ... | d741c44ffb3e9e1f726bf492202ac8738bb4aa1c | <|skeleton|>
class GCC:
"""The package manager for GCC installations"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
<|body_0|>
def dpkgPackages(cls, packager):
"""Provide al... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GCC:
"""The package manager for GCC installations"""
def dpkgAlternatives(cls, dpkg):
"""Go through the installed packages and identify those that are relevant for providing support for my installations"""
installed = dpkg.installed()
rgx = '^gcc-(?P<version>(?P<major>[0-9]+)(\\.(... | the_stack_v2_python_sparse | packages/pyre/externals/GCC.py | pyre/pyre | train | 27 |
f4f03e866c42bf94d805bf71f7dc9344cdee5485 | [
"old_allowed_ids = set(old_flow.get_attribute('allowed_campaigns') if old_flow else [])\nold_next_id = old_flow.get_attribute('next_campaign') if old_flow else None\nnew_allowed_ids = set(new_flow.get_attribute('allowed_campaigns') if new_flow else [])\nnew_next_id = new_flow.get_attribute('next_campaign') if new_f... | <|body_start_0|>
old_allowed_ids = set(old_flow.get_attribute('allowed_campaigns') if old_flow else [])
old_next_id = old_flow.get_attribute('next_campaign') if old_flow else None
new_allowed_ids = set(new_flow.get_attribute('allowed_campaigns') if new_flow else [])
new_next_id = new_flo... | FlowRESTResource | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FlowRESTResource:
def update_derived_objects(self, old_flow, new_flow):
"""Update campaigns' "Next" attribute"""
<|body_0|>
def set_default_request_parameters(self, flow):
"""Add a skeleton of the sequences of the next campaign"""
<|body_1|>
def check_ca... | stack_v2_sparse_classes_36k_train_004532 | 17,938 | no_license | [
{
"docstring": "Update campaigns' \"Next\" attribute",
"name": "update_derived_objects",
"signature": "def update_derived_objects(self, old_flow, new_flow)"
},
{
"docstring": "Add a skeleton of the sequences of the next campaign",
"name": "set_default_request_parameters",
"signature": "d... | 3 | null | Implement the Python class `FlowRESTResource` described below.
Class description:
Implement the FlowRESTResource class.
Method signatures and docstrings:
- def update_derived_objects(self, old_flow, new_flow): Update campaigns' "Next" attribute
- def set_default_request_parameters(self, flow): Add a skeleton of the s... | Implement the Python class `FlowRESTResource` described below.
Class description:
Implement the FlowRESTResource class.
Method signatures and docstrings:
- def update_derived_objects(self, old_flow, new_flow): Update campaigns' "Next" attribute
- def set_default_request_parameters(self, flow): Add a skeleton of the s... | c33efec52909e68a3096e4c81900f1becad8713a | <|skeleton|>
class FlowRESTResource:
def update_derived_objects(self, old_flow, new_flow):
"""Update campaigns' "Next" attribute"""
<|body_0|>
def set_default_request_parameters(self, flow):
"""Add a skeleton of the sequences of the next campaign"""
<|body_1|>
def check_ca... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FlowRESTResource:
def update_derived_objects(self, old_flow, new_flow):
"""Update campaigns' "Next" attribute"""
old_allowed_ids = set(old_flow.get_attribute('allowed_campaigns') if old_flow else [])
old_next_id = old_flow.get_attribute('next_campaign') if old_flow else None
ne... | the_stack_v2_python_sparse | mcm/rest_api/FlowActions.py | cms-PdmV/cmsPdmV | train | 4 | |
dd27a33ce525b8bf1a2bba73e26bdf4147ee267b | [
"self._source_file_path = source_file_path\nself._particle_data_handler = particle_data_handler\nself._parser_config = parser_config",
"log = get_logger()\nwith open(self._source_file_path, 'rb') as file_handle:\n\n def exception_callback(exception):\n log.debug('Exception %s', exception)\n self.... | <|body_start_0|>
self._source_file_path = source_file_path
self._particle_data_handler = particle_data_handler
self._parser_config = parser_config
<|end_body_0|>
<|body_start_1|>
log = get_logger()
with open(self._source_file_path, 'rb') as file_handle:
def exceptio... | GliderEngineeringDriver | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GliderEngineeringDriver:
def __init__(self, source_file_path, particle_data_handler, parser_config):
"""Initialize glider engineering driver @param source_file_path - source file from Java @param particle_data_handler - particle data handler object from Java @param parser_config - parser... | stack_v2_sparse_classes_36k_train_004533 | 1,760 | permissive | [
{
"docstring": "Initialize glider engineering driver @param source_file_path - source file from Java @param particle_data_handler - particle data handler object from Java @param parser_config - parser configuration dictionary",
"name": "__init__",
"signature": "def __init__(self, source_file_path, parti... | 2 | null | Implement the Python class `GliderEngineeringDriver` described below.
Class description:
Implement the GliderEngineeringDriver class.
Method signatures and docstrings:
- def __init__(self, source_file_path, particle_data_handler, parser_config): Initialize glider engineering driver @param source_file_path - source fi... | Implement the Python class `GliderEngineeringDriver` described below.
Class description:
Implement the GliderEngineeringDriver class.
Method signatures and docstrings:
- def __init__(self, source_file_path, particle_data_handler, parser_config): Initialize glider engineering driver @param source_file_path - source fi... | bdbf01f5614e7188ce19596704794466e5683b30 | <|skeleton|>
class GliderEngineeringDriver:
def __init__(self, source_file_path, particle_data_handler, parser_config):
"""Initialize glider engineering driver @param source_file_path - source file from Java @param particle_data_handler - particle data handler object from Java @param parser_config - parser... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GliderEngineeringDriver:
def __init__(self, source_file_path, particle_data_handler, parser_config):
"""Initialize glider engineering driver @param source_file_path - source file from Java @param particle_data_handler - particle data handler object from Java @param parser_config - parser configuration... | the_stack_v2_python_sparse | mi/dataset/driver/moas/gl/engineering/driver_common.py | oceanobservatories/mi-instrument | 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_36k_train_004534 | 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_008359 | 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_36k | 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 |
f85c099dc0c43dee4ba490e8ee3b5163a8c91df4 | [
"self.streamer = streamer\nself.dictionary = dictionary\nself.doc_id = doc_id\nself.limit = limit",
"token_stream = self.streamer.token_stream(doc_id=self.doc_id, limit=self.limit, cache_list=['doc_id'])\nfor token_list in token_stream:\n yield self.dictionary.doc2bow(token_list)",
"corpora.SvmLightCorpus.se... | <|body_start_0|>
self.streamer = streamer
self.dictionary = dictionary
self.doc_id = doc_id
self.limit = limit
<|end_body_0|>
<|body_start_1|>
token_stream = self.streamer.token_stream(doc_id=self.doc_id, limit=self.limit, cache_list=['doc_id'])
for token_list in token_s... | A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensim.corpora.SvmLightCorpus.serialize(path, self) | StreamerCorpus | [
"BSD-3-Clause",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StreamerCorpus:
"""A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensim.corpora.SvmLightCorpus.serialize(path... | stack_v2_sparse_classes_36k_train_004535 | 6,861 | permissive | [
{
"docstring": "Stream token lists from pre-defined path lists. Parameters ---------- streamer : Streamer compatible object. Method streamer.token_stream() returns a stream of lists of words. dictionary : gensim.corpora.Dictionary object doc_id : Iterable over strings Limit all streaming results to docs with th... | 3 | stack_v2_sparse_classes_30k_train_014891 | Implement the Python class `StreamerCorpus` described below.
Class description:
A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensi... | Implement the Python class `StreamerCorpus` described below.
Class description:
A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensi... | 0753f0173d087b742ff1a0e56771075479e611bd | <|skeleton|>
class StreamerCorpus:
"""A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensim.corpora.SvmLightCorpus.serialize(path... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StreamerCorpus:
"""A "corpus type" object built with token streams and dictionaries. Depending on your method for streaming tokens, this could be slow... Before modeling, it's usually better to serialize this corpus using: self.to_corpus_plus(fname) or gensim.corpora.SvmLightCorpus.serialize(path, self)"""
... | the_stack_v2_python_sparse | rosetta/text/gensim_helpers.py | columbia-applied-data-science/rosetta | train | 136 |
ae789d532023699d096f984ec84114769e19ac1e | [
"super().__init__(cfg, input_channels)\nself.confidence_model_cfg = DensePoseConfidenceModelConfig.from_cfg(cfg)\nself._initialize_confidence_estimation_layers(cfg, input_channels)\nself._registry = {}\ninitialize_module_params(self)",
"dim_out_patches = cfg.MODEL.ROI_DENSEPOSE_HEAD.NUM_PATCHES + 1\nkernel_size =... | <|body_start_0|>
super().__init__(cfg, input_channels)
self.confidence_model_cfg = DensePoseConfidenceModelConfig.from_cfg(cfg)
self._initialize_confidence_estimation_layers(cfg, input_channels)
self._registry = {}
initialize_module_params(self)
<|end_body_0|>
<|body_start_1|>
... | Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tensors estimated by some base predictor. Several assumptions need to hold for the base predictor: 1) the `fo... | DensePoseChartConfidencePredictorMixin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DensePoseChartConfidencePredictorMixin:
"""Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tensors estimated by some base predictor. S... | stack_v2_sparse_classes_36k_train_004536 | 8,373 | permissive | [
{
"docstring": "Initialize confidence predictor using configuration options. Args: cfg (CfgNode): configuration options input_channels (int): number of input channels",
"name": "__init__",
"signature": "def __init__(self, cfg: CfgNode, input_channels: int)"
},
{
"docstring": "Initialize confiden... | 4 | stack_v2_sparse_classes_30k_train_011264 | Implement the Python class `DensePoseChartConfidencePredictorMixin` described below.
Class description:
Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tens... | Implement the Python class `DensePoseChartConfidencePredictorMixin` described below.
Class description:
Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tens... | 80307d2d5e06f06a8a677cc2653f23a4c56402ac | <|skeleton|>
class DensePoseChartConfidencePredictorMixin:
"""Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tensors estimated by some base predictor. S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DensePoseChartConfidencePredictorMixin:
"""Predictor contains the last layers of a DensePose model that take DensePose head outputs as an input and produce model outputs. Confidence predictor mixin is used to generate confidences for segmentation and UV tensors estimated by some base predictor. Several assump... | the_stack_v2_python_sparse | projects/DensePose/densepose/modeling/predictors/chart_confidence.py | facebookresearch/detectron2 | train | 27,469 |
4858a9549fc3f93813d908fa881e61a3b3fc413c | [
"super().__init__()\nself.ffm = FFMLayer(num_fields=num_fields, dropout_p=ffm_dropout_p)\ninputs_size = combination(num_fields, 2)\ninputs_size *= embed_size\nself.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dropout_p=deep_dropout_p, activation=deep_activatio... | <|body_start_0|>
super().__init__()
self.ffm = FFMLayer(num_fields=num_fields, dropout_p=ffm_dropout_p)
inputs_size = combination(num_fields, 2)
inputs_size *= embed_size
self.deep = DNNLayer(inputs_size=inputs_size, output_size=deep_output_size, layer_sizes=deep_layer_sizes, dro... | Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware Factorization Machine (NFFM), and was described and renamed to Deep Field-aware Factorization Machine in ... | DeepFieldAwareFactorizationMachineModel | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DeepFieldAwareFactorizationMachineModel:
"""Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware Factorization Machine (NFFM), and was ... | stack_v2_sparse_classes_36k_train_004537 | 5,693 | permissive | [
{
"docstring": "Initialize DeepFieldAwareFactorizationMachineModel Args: embed_size (int): size of embedding tensor num_fields (int): number of inputs' fields deep_output_size (int): output size of dense network deep_layer_sizes (List[int]): layer sizes of dense network ffm_dropout_p (float, optional): probabil... | 2 | stack_v2_sparse_classes_30k_train_021321 | Implement the Python class `DeepFieldAwareFactorizationMachineModel` described below.
Class description:
Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware... | Implement the Python class `DeepFieldAwareFactorizationMachineModel` described below.
Class description:
Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware... | 751a43b9cd35e951d81c0d9cf46507b1777bb7ff | <|skeleton|>
class DeepFieldAwareFactorizationMachineModel:
"""Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware Factorization Machine (NFFM), and was ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DeepFieldAwareFactorizationMachineModel:
"""Model class of Deep Field-aware Factorization Machine (Deep FFM). Deep Field-aware Factorization Machine was proposed by Yang et al. in Tencent Social Ads competition 2017. This was called as Network on Field-aware Factorization Machine (NFFM), and was described and... | the_stack_v2_python_sparse | torecsys/models/ctr/deep_ffm.py | p768lwy3/torecsys | train | 98 |
71cb7560329bfaa4a7626ebc3e96b75016849a9b | [
"super(AtomEmbedding, self).__init__()\nself._dim = dim\nself._type_num = type_num\nif pre_train is not None:\n self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0)\nelse:\n self.embedding = nn.Embedding(type_num, dim, padding_idx=0)",
"atom_list = g.ndata['nodes']\ng.ndata[p_name] = self... | <|body_start_0|>
super(AtomEmbedding, self).__init__()
self._dim = dim
self._type_num = type_num
if pre_train is not None:
self.embedding = nn.Embedding.from_pretrained(pre_train, padding_idx=0)
else:
self.embedding = nn.Embedding(type_num, dim, padding_id... | Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding. | AtomEmbedding | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the la... | stack_v2_sparse_classes_36k_train_004538 | 12,339 | no_license | [
{
"docstring": "Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic number of atoms in the dataset pre_train: the pre_trained embeddings",
"name": "__init__",
"signature": "def __init__(self, dim=128, type_num=100, pre_train=None)"
},
{
"docstring"... | 2 | stack_v2_sparse_classes_30k_train_005485 | Implement the Python class `AtomEmbedding` described below.
Class description:
Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding.
Method signatures and docstrings:
- def __init__(self, dim=128, type_num=100, pre_train=None): Randomly init the element embe... | Implement the Python class `AtomEmbedding` described below.
Class description:
Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding.
Method signatures and docstrings:
- def __init__(self, dim=128, type_num=100, pre_train=None): Randomly init the element embe... | 721c54bb79914275dd3bb8718b78d67ff362f0cb | <|skeleton|>
class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the la... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AtomEmbedding:
"""Convert the atom(node) list to atom embeddings. The atom with the same element share the same initial embeddding."""
def __init__(self, dim=128, type_num=100, pre_train=None):
"""Randomly init the element embeddings. Args: dim: the dim of embeddings type_num: the largest atomic ... | the_stack_v2_python_sparse | bayes_al/mm_sch.py | qkqkfldis1/improved_asgn | train | 1 |
3de7e65d8aff5eeabe000b15a93114d834d21ec2 | [
"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... | The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, the action cache addresses the [ActionResult][goo... | ActionCacheServicer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, th... | stack_v2_sparse_classes_36k_train_004539 | 24,490 | no_license | [
{
"docstring": "Retrieve a cached execution result. Errors: * `NOT_FOUND`: The requested `ActionResult` is not in the cache.",
"name": "GetActionResult",
"signature": "def GetActionResult(self, request, context)"
},
{
"docstring": "Upload a new execution result. This method is intended for serve... | 2 | stack_v2_sparse_classes_30k_train_006608 | Implement the Python class `ActionCacheServicer` described below.
Class description:
The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which a... | Implement the Python class `ActionCacheServicer` described below.
Class description:
The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which a... | d7424d21aa0dc121acc4d64b427ba365a3581a20 | <|skeleton|>
class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, th... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ActionCacheServicer:
"""The action cache API is used to query whether a given action has already been performed and, if so, retrieve its result. Unlike the [ContentAddressableStorage][google.devtools.remoteexecution.v1test.ContentAddressableStorage], which addresses blobs by their own content, the action cach... | the_stack_v2_python_sparse | google/devtools/remoteexecution/v1test/remote_execution_pb2_grpc.py | msachtler/bazel-event-protocol-parser | train | 1 |
a09f246871ea9ee863c1c38b107766e371933e16 | [
"self.elements = []\nself.points = points\nself.length_of_row = length_of_row\nself.length_of_column = length_of_column\nself.padding = padding\nself.type = 'table'\nself.stroke_width = stroke_width\nself.parent_element = parent_element\nself.relative = relative\nself.type_of_element = 'table'\nself.id = 1 + RootEl... | <|body_start_0|>
self.elements = []
self.points = points
self.length_of_row = length_of_row
self.length_of_column = length_of_column
self.padding = padding
self.type = 'table'
self.stroke_width = stroke_width
self.parent_element = parent_element
se... | Table with code quality metrics. | Table | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Table:
"""Table with code quality metrics."""
def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True):
"""Initialize the table."""
<|body_0|>
def build(self, dwg):
"""Build the table on drawing.""... | stack_v2_sparse_classes_36k_train_004540 | 15,115 | permissive | [
{
"docstring": "Initialize the table.",
"name": "__init__",
"signature": "def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True)"
},
{
"docstring": "Build the table on drawing.",
"name": "build",
"signature": "def build(... | 2 | stack_v2_sparse_classes_30k_train_009643 | Implement the Python class `Table` described below.
Class description:
Table with code quality metrics.
Method signatures and docstrings:
- def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True): Initialize the table.
- def build(self, dwg): Build th... | Implement the Python class `Table` described below.
Class description:
Table with code quality metrics.
Method signatures and docstrings:
- def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True): Initialize the table.
- def build(self, dwg): Build th... | a763c5534d601f2f40a0f02c02914c49ea23669d | <|skeleton|>
class Table:
"""Table with code quality metrics."""
def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True):
"""Initialize the table."""
<|body_0|>
def build(self, dwg):
"""Build the table on drawing.""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Table:
"""Table with code quality metrics."""
def __init__(self, points, length_of_row, length_of_column, padding=5, stroke_width=2, parent_element=None, relative=True):
"""Initialize the table."""
self.elements = []
self.points = points
self.length_of_row = length_of_row
... | the_stack_v2_python_sparse | dashboard/src/code_quality_label.py | fabric8-analytics/fabric8-analytics-common | train | 6 |
62070fd6e42f8506df69401c77000a1b752d4cd7 | [
"self.is_full_team_required = is_full_team_required\nself.object = object\nself.source_channel_vec = source_channel_vec",
"if dictionary is None:\n return None\nis_full_team_required = dictionary.get('isFullTeamRequired')\nobject = cohesity_management_sdk.models.restore_object.RestoreObject.from_dictionary(dic... | <|body_start_0|>
self.is_full_team_required = is_full_team_required
self.object = object
self.source_channel_vec = source_channel_vec
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
is_full_team_required = dictionary.get('isFullTeamRequired')
... | Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. This will store the details of the MS team to be re... | RestoreO365TeamsParams_MSTeamInfo | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_36k_train_004541 | 2,808 | permissive | [
{
"docstring": "Constructor for the RestoreO365TeamsParams_MSTeamInfo class",
"name": "__init__",
"signature": "def __init__(self, is_full_team_required=None, object=None, source_channel_vec=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionar... | 2 | stack_v2_sparse_classes_30k_test_001083 | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | Implement the Python class `RestoreO365TeamsParams_MSTeamInfo` described below.
Class description:
Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : ... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necess... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RestoreO365TeamsParams_MSTeamInfo:
"""Implementation of the 'RestoreO365TeamsParams_MSTeamInfo' model. TODO: type description here. Attributes: is_full_team_required (bool): Specify if the entire Team is to be restored. object (RestoreObject): Todo(prann) : deprecate this and only keep the necessary info. Thi... | the_stack_v2_python_sparse | cohesity_management_sdk/models/restore_o_365_teams_params_ms_team_info.py | cohesity/management-sdk-python | train | 24 |
3e6a63db5f6e37635bbc84bf7ca5c8c630e9fc3e | [
"rt = self.rt\ninstances = self.instances\ngsi = rt['pcms']['gsi']\ngsi_state = rt['gsi_state']\ni8259_irq = gsi_state['i8259_irq']\nioapic_irq = gsi_state['ioapic_irq']\nfor i in range(24):\n gsi_addr = gsi[i].fetch_pointer()\n gsi_inst = instances[gsi_addr]\n self._MachineWatcher__notify_irq_split_create... | <|body_start_0|>
rt = self.rt
instances = self.instances
gsi = rt['pcms']['gsi']
gsi_state = rt['gsi_state']
i8259_irq = gsi_state['i8259_irq']
ioapic_irq = gsi_state['ioapic_irq']
for i in range(24):
gsi_addr = gsi[i].fetch_pointer()
gsi_i... | Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts). | PCMachineWatcher | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PCMachineWatcher:
"""Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts)."""
def on_pc_piix_gsi(self):
"""pc_piix.c:301 v2.12.0 1"""
<|body_0|>
def on_piix4_pm_gsi(self):
"""acpi/piix4.c:539 v5.1.0 acpi/piix4.c:578 v2.1... | stack_v2_sparse_classes_36k_train_004542 | 26,519 | permissive | [
{
"docstring": "pc_piix.c:301 v2.12.0 1",
"name": "on_pc_piix_gsi",
"signature": "def on_pc_piix_gsi(self)"
},
{
"docstring": "acpi/piix4.c:539 v5.1.0 acpi/piix4.c:578 v2.12.0",
"name": "on_piix4_pm_gsi",
"signature": "def on_piix4_pm_gsi(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_015195 | Implement the Python class `PCMachineWatcher` described below.
Class description:
Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts).
Method signatures and docstrings:
- def on_pc_piix_gsi(self): pc_piix.c:301 v2.12.0 1
- def on_piix4_pm_gsi(self): acpi/piix4.c:539 v5.1.0 ... | Implement the Python class `PCMachineWatcher` described below.
Class description:
Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts).
Method signatures and docstrings:
- def on_pc_piix_gsi(self): pc_piix.c:301 v2.12.0 1
- def on_piix4_pm_gsi(self): acpi/piix4.c:539 v5.1.0 ... | 93e03c2b3f880f5c7c9f90e1ba5593dbf602bdb9 | <|skeleton|>
class PCMachineWatcher:
"""Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts)."""
def on_pc_piix_gsi(self):
"""pc_piix.c:301 v2.12.0 1"""
<|body_0|>
def on_piix4_pm_gsi(self):
"""acpi/piix4.c:539 v5.1.0 acpi/piix4.c:578 v2.1... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PCMachineWatcher:
"""Support for non-standard IRQ creation of PC i440fx based machines (Global Signaling Interrupts)."""
def on_pc_piix_gsi(self):
"""pc_piix.c:301 v2.12.0 1"""
rt = self.rt
instances = self.instances
gsi = rt['pcms']['gsi']
gsi_state = rt['gsi_stat... | the_stack_v2_python_sparse | qemu/qemu_watcher.py | ispras/qdt | train | 38 |
42992f185c943abe534ab86eb968e04530cb33fc | [
"SAM_res = SAMResource(sites, tech, self.time_index, means=means)\nsites = SAM_res.sites_slice\nSAM_res['meta'] = self['meta', sites]\nif clearsky:\n SAM_res.set_clearsky()\nSAM_res.check_irradiance_datasets(self.datasets, clearsky=clearsky)\nif not downscale:\n for var in SAM_res.var_list:\n if var in... | <|body_start_0|>
SAM_res = SAMResource(sites, tech, self.time_index, means=means)
sites = SAM_res.sites_slice
SAM_res['meta'] = self['meta', sites]
if clearsky:
SAM_res.set_clearsky()
SAM_res.check_irradiance_datasets(self.datasets, clearsky=clearsky)
if not d... | Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class | NSRDB | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NSRDB:
"""Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class"""
def _preload_SAM(self, sites, tech='pvwattsv7', clearsky=False, downscale=None, means=False):
"""Pre-load project_points for SAM Parameters ---------- sites : list List of sites to be prov... | stack_v2_sparse_classes_36k_train_004543 | 43,525 | permissive | [
{
"docstring": "Pre-load project_points for SAM Parameters ---------- sites : list List of sites to be provided to SAM tech : str, optional SAM technology string, by default 'pvwattsv7' clearsky : bool Boolean flag to pull clearsky instead of real irradiance downscale : NoneType | str Option for NSRDB resource ... | 2 | stack_v2_sparse_classes_30k_train_012925 | Implement the Python class `NSRDB` described below.
Class description:
Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _preload_SAM(self, sites, tech='pvwattsv7', clearsky=False, downscale=None, means=False): Pre-load project_points for SAM Pa... | Implement the Python class `NSRDB` described below.
Class description:
Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class
Method signatures and docstrings:
- def _preload_SAM(self, sites, tech='pvwattsv7', clearsky=False, downscale=None, means=False): Pre-load project_points for SAM Pa... | ca598da8bbcd9983fb1355fe3b67d58273eef5c6 | <|skeleton|>
class NSRDB:
"""Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class"""
def _preload_SAM(self, sites, tech='pvwattsv7', clearsky=False, downscale=None, means=False):
"""Pre-load project_points for SAM Parameters ---------- sites : list List of sites to be prov... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NSRDB:
"""Class to handle NSRDB .h5 files See Also -------- resource.Resource : Parent class"""
def _preload_SAM(self, sites, tech='pvwattsv7', clearsky=False, downscale=None, means=False):
"""Pre-load project_points for SAM Parameters ---------- sites : list List of sites to be provided to SAM t... | the_stack_v2_python_sparse | rex/renewable_resource.py | aidanbharath/rex | train | 0 |
e8b12d44519e5dec08d1b11b0d3100cfca71fd4c | [
"super().__init__()\nself.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])\nlayer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])\nself.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])\nself.output = nn.Linear(hidden_layers[-1], output_size)\nself.dropout = nn.Dropout(p... | <|body_start_0|>
super().__init__()
self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])
layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])
self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])
self.output = nn.Linear(hidden_layer... | Network | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the si... | stack_v2_sparse_classes_36k_train_004544 | 4,436 | no_license | [
{
"docstring": "Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hidden layers drop_p: float between 0 and 1, dropout probability",
"name": "_... | 2 | null | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | Implement the Python class `Network` described below.
Class description:
Implement the Network class.
Method signatures and docstrings:
- def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5): Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of ... | 768edc4a5526c8972fec66c6a71a38c0b24a1451 | <|skeleton|>
class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the si... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Network:
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
"""Builds a feedforward network with arbitrary hidden layers. Arguments --------- input_size: integer, size of the input output_size: integer, size of the output layer hidden_layers: list of integers, the sizes of the hid... | the_stack_v2_python_sparse | 人工智能/python人工智能课程/part_4_Neural_Networks/learning_with_PyTorch/p4_Inference and Validation.py | faker-hong/testOne | train | 1 | |
bb23e9faaf55c9dc2505fc0ca36fd20f31300a6d | [
"super().__init__(ambient, mac_address, station_name, description)\nif description.key == TYPE_SOLARRADIATION_LX:\n self.entity_id = f'sensor.{station_name}_solar_rad_lx'",
"key = self.entity_description.key\nraw = self._ambient.stations[self._mac_address][ATTR_LAST_DATA][key]\nif key == TYPE_LASTRAIN:\n se... | <|body_start_0|>
super().__init__(ambient, mac_address, station_name, description)
if description.key == TYPE_SOLARRADIATION_LX:
self.entity_id = f'sensor.{station_name}_solar_rad_lx'
<|end_body_0|>
<|body_start_1|>
key = self.entity_description.key
raw = self._ambient.stati... | Define an Ambient sensor. | AmbientWeatherSensor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AmbientWeatherSensor:
"""Define an Ambient sensor."""
def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update_from_latest_data(self) -> None:
"""F... | stack_v2_sparse_classes_36k_train_004545 | 24,902 | permissive | [
{
"docstring": "Initialize the sensor.",
"name": "__init__",
"signature": "def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None"
},
{
"docstring": "Fetch new state data for the sensor.",
"name": "update_from_latest_data",
... | 2 | stack_v2_sparse_classes_30k_train_002526 | Implement the Python class `AmbientWeatherSensor` described below.
Class description:
Define an Ambient sensor.
Method signatures and docstrings:
- def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None: Initialize the sensor.
- def update_from_latest_... | Implement the Python class `AmbientWeatherSensor` described below.
Class description:
Define an Ambient sensor.
Method signatures and docstrings:
- def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None: Initialize the sensor.
- def update_from_latest_... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class AmbientWeatherSensor:
"""Define an Ambient sensor."""
def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None:
"""Initialize the sensor."""
<|body_0|>
def update_from_latest_data(self) -> None:
"""F... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AmbientWeatherSensor:
"""Define an Ambient sensor."""
def __init__(self, ambient: AmbientStation, mac_address: str, station_name: str, description: EntityDescription) -> None:
"""Initialize the sensor."""
super().__init__(ambient, mac_address, station_name, description)
if descrip... | the_stack_v2_python_sparse | homeassistant/components/ambient_station/sensor.py | home-assistant/core | train | 35,501 |
1ee3e1395dee58c16774f54cd8adb21df5225f24 | [
"super().__init__(*args, **kwargs)\nself.gx = gx\nself.gy = gy\nself.gz = gz",
"if gridpoi == 'x':\n self.background_color = BCKGRND_CLR\nelif type(gridpoi) == list:\n if gridpoi[0] == 'D':\n self.background_color = [1, 1, 0, 1]\n elif gridpoi[0] == 'M':\n self.background_color = [1, 0, 1, ... | <|body_start_0|>
super().__init__(*args, **kwargs)
self.gx = gx
self.gy = gy
self.gz = gz
<|end_body_0|>
<|body_start_1|>
if gridpoi == 'x':
self.background_color = BCKGRND_CLR
elif type(gridpoi) == list:
if gridpoi[0] == 'D':
self... | Square | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Square:
def __init__(self, gx, gy, gz, *args, **kwargs):
"""params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate"""
<|body_0|>
def update_square(self, gx, gy, gz, gridpoi):
"""params:- gx : int : grid x coordinate, used to w... | stack_v2_sparse_classes_36k_train_004546 | 6,851 | no_license | [
{
"docstring": "params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate",
"name": "__init__",
"signature": "def __init__(self, gx, gy, gz, *args, **kwargs)"
},
{
"docstring": "params:- gx : int : grid x coordinate, used to workout black or white square gy ... | 2 | stack_v2_sparse_classes_30k_train_011849 | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def __init__(self, gx, gy, gz, *args, **kwargs): params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate
- def update_square(self, gx, gy, gz,... | Implement the Python class `Square` described below.
Class description:
Implement the Square class.
Method signatures and docstrings:
- def __init__(self, gx, gy, gz, *args, **kwargs): params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate
- def update_square(self, gx, gy, gz,... | 020a6f05e17fd9ef8d8a10f22a0482352d18ddd5 | <|skeleton|>
class Square:
def __init__(self, gx, gy, gz, *args, **kwargs):
"""params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate"""
<|body_0|>
def update_square(self, gx, gy, gz, gridpoi):
"""params:- gx : int : grid x coordinate, used to w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Square:
def __init__(self, gx, gy, gz, *args, **kwargs):
"""params:- gx : int : grid x coordinate gy : int : grid y coordinate gz : int : grid z coordinate"""
super().__init__(*args, **kwargs)
self.gx = gx
self.gy = gy
self.gz = gz
def update_square(self, gx, gy, g... | the_stack_v2_python_sparse | bin/Visualliser/visualliser.py | HarryBurge/StarTrekChessAI | train | 0 | |
d0e3acb1d013fcc27018b59927418b96b423a2fc | [
"ObjectManager.__init__(self)\nself.getters.update({'address': 'get_address', 'contact': 'get_general', 'events': 'get_many_to_one', 'hours_of_operation': 'get_general', 'name': 'get_general', 'owner': 'get_foreign_key', 'phone': 'get_general', 'region': 'get_foreign_key', 'rooms': 'get_many_to_one'})\nself.setters... | <|body_start_0|>
ObjectManager.__init__(self)
self.getters.update({'address': 'get_address', 'contact': 'get_general', 'events': 'get_many_to_one', 'hours_of_operation': 'get_general', 'name': 'get_general', 'owner': 'get_foreign_key', 'phone': 'get_general', 'region': 'get_foreign_key', 'rooms': 'get_m... | Manage Venues in the Power Reg system | VenueManager | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VenueManager:
"""Manage Venues in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, phone, region, optional_attributes=None):
"""Common method for Venue creation Makes sure that the old address does not ge... | stack_v2_sparse_classes_36k_train_004547 | 2,577 | permissive | [
{
"docstring": "constructor",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Common method for Venue creation Makes sure that the old address does not get orphaned. @param auth_token The actor's authentication token @param name Name for the Venue @param phone Phone numb... | 2 | null | Implement the Python class `VenueManager` described below.
Class description:
Manage Venues in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, phone, region, optional_attributes=None): Common method for Venue creation Makes sure that the ol... | Implement the Python class `VenueManager` described below.
Class description:
Manage Venues in the Power Reg system
Method signatures and docstrings:
- def __init__(self): constructor
- def create(self, auth_token, name, phone, region, optional_attributes=None): Common method for Venue creation Makes sure that the ol... | a59457bc37f0501aea1f54d006a6de94ff80511c | <|skeleton|>
class VenueManager:
"""Manage Venues in the Power Reg system"""
def __init__(self):
"""constructor"""
<|body_0|>
def create(self, auth_token, name, phone, region, optional_attributes=None):
"""Common method for Venue creation Makes sure that the old address does not ge... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VenueManager:
"""Manage Venues in the Power Reg system"""
def __init__(self):
"""constructor"""
ObjectManager.__init__(self)
self.getters.update({'address': 'get_address', 'contact': 'get_general', 'events': 'get_many_to_one', 'hours_of_operation': 'get_general', 'name': 'get_gene... | the_stack_v2_python_sparse | pr_services/resource_system/venue_manager.py | ninemoreminutes/openassign-server | train | 0 |
5a22377024926bb3632b4f0c81c3320d1c0b3639 | [
"super(LogicalSwitchListSchema, self).__init__()\nself.table = [LogicalSwitchEntrySchema()]\nif py_dict is not None:\n self.get_object_from_py_dict(py_dict)",
"payload = self._parser.get_parsed_data(raw_payload)\npy_dict = {'table': payload}\nreturn self.get_object_from_py_dict(py_dict)"
] | <|body_start_0|>
super(LogicalSwitchListSchema, self).__init__()
self.table = [LogicalSwitchEntrySchema()]
if py_dict is not None:
self.get_object_from_py_dict(py_dict)
<|end_body_0|>
<|body_start_1|>
payload = self._parser.get_parsed_data(raw_payload)
py_dict = {'ta... | LogicalSwitchListSchema | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
<|body_0|>
def set_data_raw(self, raw_payload):
"""Convert raw data to py_dict based on the class parser and assign the py_dict to class element so t... | stack_v2_sparse_classes_36k_train_004548 | 1,832 | no_license | [
{
"docstring": "Constructor to create LogicalSwitchListSchema object",
"name": "__init__",
"signature": "def __init__(self, py_dict=None)"
},
{
"docstring": "Convert raw data to py_dict based on the class parser and assign the py_dict to class element so that get_object_from_py_dict() can take i... | 2 | null | Implement the Python class `LogicalSwitchListSchema` described below.
Class description:
Implement the LogicalSwitchListSchema class.
Method signatures and docstrings:
- def __init__(self, py_dict=None): Constructor to create LogicalSwitchListSchema object
- def set_data_raw(self, raw_payload): Convert raw data to py... | Implement the Python class `LogicalSwitchListSchema` described below.
Class description:
Implement the LogicalSwitchListSchema class.
Method signatures and docstrings:
- def __init__(self, py_dict=None): Constructor to create LogicalSwitchListSchema object
- def set_data_raw(self, raw_payload): Convert raw data to py... | 5b55817c050b637e2747084290f6206d2e622938 | <|skeleton|>
class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
<|body_0|>
def set_data_raw(self, raw_payload):
"""Convert raw data to py_dict based on the class parser and assign the py_dict to class element so t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LogicalSwitchListSchema:
def __init__(self, py_dict=None):
"""Constructor to create LogicalSwitchListSchema object"""
super(LogicalSwitchListSchema, self).__init__()
self.table = [LogicalSwitchEntrySchema()]
if py_dict is not None:
self.get_object_from_py_dict(py_di... | the_stack_v2_python_sparse | SystemTesting/pylib/nsx/vsm/centralized_cli/schema/logicalswitch_list_schema.py | Cloudxtreme/MyProject | train | 0 | |
f5f843a69390cc74b707c545b188cfb366cc5986 | [
"now = datetime.datetime.now()\nres = prefix + now.strftime('%Y%m%d%H%M%S')\nres += get_random_string(length - len(res))\nreturn res",
"if not trade_no:\n trade_no = None\nupdate = PayOrder.objects.filter(id=self.id).exclude(status=STATUS_SUCCESS).update(close_time=timezone.now(), trade_no=trade_no, status=STA... | <|body_start_0|>
now = datetime.datetime.now()
res = prefix + now.strftime('%Y%m%d%H%M%S')
res += get_random_string(length - len(res))
return res
<|end_body_0|>
<|body_start_1|>
if not trade_no:
trade_no = None
update = PayOrder.objects.filter(id=self.id).exc... | 支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11 | PayOrder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PayOrder:
"""支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11"""
def create_flag(self, prefix, length=50):
"""生成支付ID,前缀 by: 范俊伟 at:2015-03-07 :param prefix:id前缀 :param length: :return:"""
<... | stack_v2_sparse_classes_36k_train_004549 | 16,344 | no_license | [
{
"docstring": "生成支付ID,前缀 by: 范俊伟 at:2015-03-07 :param prefix:id前缀 :param length: :return:",
"name": "create_flag",
"signature": "def create_flag(self, prefix, length=50)"
},
{
"docstring": "支付成功操作 by: 范俊伟 at:2015-03-07 优化,在trade_no为空字串时设置为None by: 范俊伟 at:2015-03-08 :param trade_no: :return:",
... | 2 | null | Implement the Python class `PayOrder` described below.
Class description:
支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11
Method signatures and docstrings:
- def create_flag(self, prefix, length=50): 生成支付ID,前缀 by: 范俊伟 at:2015-03-0... | Implement the Python class `PayOrder` described below.
Class description:
支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11
Method signatures and docstrings:
- def create_flag(self, prefix, length=50): 生成支付ID,前缀 by: 范俊伟 at:2015-03-0... | f8b5cb3adcb8c907834ec3fad1f82bf36be688b7 | <|skeleton|>
class PayOrder:
"""支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11"""
def create_flag(self, prefix, length=50):
"""生成支付ID,前缀 by: 范俊伟 at:2015-03-07 :param prefix:id前缀 :param length: :return:"""
<... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PayOrder:
"""支付订单,每次点击支付按钮基于Order表创建 by: 范俊伟 at:2015-03-07 修改字段 by: 范俊伟 at:2015-03-07 trade_no初始值为空 by: 范俊伟 at:2015-03-08 修改字段 by: 范俊伟 at:2015-06-11"""
def create_flag(self, prefix, length=50):
"""生成支付ID,前缀 by: 范俊伟 at:2015-03-07 :param prefix:id前缀 :param length: :return:"""
now = datetime... | the_stack_v2_python_sparse | webhtml/models.py | cash2one/ESNS | train | 0 |
5482ea890058dd9d6966b92d08deaa00355055ce | [
"msg = ''\nfor number_i in x_casinos:\n for number_j in range(1, x_player_number + 1):\n if x_casinos[number_i]['player' + str(number_j)] == 0:\n continue\n temp_number = x_casinos[number_i]['player' + str(number_j)]\n temp_player = number_j\n for number_k in range(number_j... | <|body_start_0|>
msg = ''
for number_i in x_casinos:
for number_j in range(1, x_player_number + 1):
if x_casinos[number_i]['player' + str(number_j)] == 0:
continue
temp_number = x_casinos[number_i]['player' + str(number_j)]
... | 用于结算 | LV_Settlement | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LV_Settlement:
"""用于结算"""
def check_duplicate(x_casinos, x_player_number):
"""x_casinos就是tabletop.casinos"""
<|body_0|>
def comparison(x_casinos, x_player_number):
"""doc"""
<|body_1|>
def money_assignment(x_compared, x_casinos, x_players, x_player_n... | stack_v2_sparse_classes_36k_train_004550 | 3,869 | no_license | [
{
"docstring": "x_casinos就是tabletop.casinos",
"name": "check_duplicate",
"signature": "def check_duplicate(x_casinos, x_player_number)"
},
{
"docstring": "doc",
"name": "comparison",
"signature": "def comparison(x_casinos, x_player_number)"
},
{
"docstring": "这里的x_compared是compar... | 3 | stack_v2_sparse_classes_30k_val_001203 | Implement the Python class `LV_Settlement` described below.
Class description:
用于结算
Method signatures and docstrings:
- def check_duplicate(x_casinos, x_player_number): x_casinos就是tabletop.casinos
- def comparison(x_casinos, x_player_number): doc
- def money_assignment(x_compared, x_casinos, x_players, x_player_numbe... | Implement the Python class `LV_Settlement` described below.
Class description:
用于结算
Method signatures and docstrings:
- def check_duplicate(x_casinos, x_player_number): x_casinos就是tabletop.casinos
- def comparison(x_casinos, x_player_number): doc
- def money_assignment(x_compared, x_casinos, x_players, x_player_numbe... | fdbf11c6a7686165dd712d70a454b9f3ff6d838d | <|skeleton|>
class LV_Settlement:
"""用于结算"""
def check_duplicate(x_casinos, x_player_number):
"""x_casinos就是tabletop.casinos"""
<|body_0|>
def comparison(x_casinos, x_player_number):
"""doc"""
<|body_1|>
def money_assignment(x_compared, x_casinos, x_players, x_player_n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LV_Settlement:
"""用于结算"""
def check_duplicate(x_casinos, x_player_number):
"""x_casinos就是tabletop.casinos"""
msg = ''
for number_i in x_casinos:
for number_j in range(1, x_player_number + 1):
if x_casinos[number_i]['player' + str(number_j)] == 0:
... | the_stack_v2_python_sparse | 07/LasVegasSettlement.py | deneuralyzer/laofuzi | train | 1 |
bfa466c23686fa68977400e011a6e42ccaacdf1a | [
"form = super(ParticipanteNaatCreateView, self).get_form(form_class)\nif self.request.user.groups.filter(name='naat_facilitador').exists():\n qs_proceso = form.fields['proceso'].queryset\n qs_proceso = qs_proceso.filter(capacitador=self.request.user)\n form.fields['proceso'].queryset = qs_proceso\nreturn f... | <|body_start_0|>
form = super(ParticipanteNaatCreateView, self).get_form(form_class)
if self.request.user.groups.filter(name='naat_facilitador').exists():
qs_proceso = form.fields['proceso'].queryset
qs_proceso = qs_proceso.filter(capacitador=self.request.user)
form.f... | Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos. | ParticipanteNaatCreateView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ParticipanteNaatCreateView:
"""Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos."""
def get_form(self, form_class=None):
"""Para filtra las opciones di... | stack_v2_sparse_classes_36k_train_004551 | 7,670 | no_license | [
{
"docstring": "Para filtra las opciones disponibles para elegir a `proceso` en el formulario",
"name": "get_form",
"signature": "def get_form(self, form_class=None)"
},
{
"docstring": "Se debe validar que el UDI de la :class:`Escuela` exista para asignarla al :class:`Participante` que se está c... | 2 | stack_v2_sparse_classes_30k_train_007790 | Implement the Python class `ParticipanteNaatCreateView` described below.
Class description:
Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos.
Method signatures and docstrings:
- def get... | Implement the Python class `ParticipanteNaatCreateView` described below.
Class description:
Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos.
Method signatures and docstrings:
- def get... | 0e37786d7173abe820fd10b094ffcc2db9593a9c | <|skeleton|>
class ParticipanteNaatCreateView:
"""Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos."""
def get_form(self, form_class=None):
"""Para filtra las opciones di... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ParticipanteNaatCreateView:
"""Vista para crear un nuevo :class:`Participante` y una :class:`AsignacionNaat` asociada al mismo. La validación de que no exista un dato duplicado se realiza a nivel de base de datos."""
def get_form(self, form_class=None):
"""Para filtra las opciones disponibles par... | the_stack_v2_python_sparse | src/apps/naat/views.py | jinchuika/app-suni | train | 7 |
b94d743e46925af66f2e46b73afaaf62b752212d | [
"super(ScatterAnimation, self).__init__()\nself.fps = 5\nself.x_limits = x_limits\nself.y_limits = y_limits\nself.z_limits = z_limits\nself.x_label = None\nself.y_label = None\nself.z_label = None\nself.density = True\nself._plotter = ScatterPlotter()",
"self._plotter.add_point(x, y, z)\nbuf = io.BytesIO()\nself.... | <|body_start_0|>
super(ScatterAnimation, self).__init__()
self.fps = 5
self.x_limits = x_limits
self.y_limits = y_limits
self.z_limits = z_limits
self.x_label = None
self.y_label = None
self.z_label = None
self.density = True
self._plotter ... | This class ... | ScatterAnimation | [
"GPL-1.0-or-later",
"AGPL-3.0-only",
"AGPL-3.0-or-later",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-philippe-de-muyter",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ScatterAnimation:
"""This class ..."""
def __init__(self, x_limits, y_limits, z_limits):
"""The constructor ..."""
<|body_0|>
def add_point(self, x, y, z):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(Scatt... | stack_v2_sparse_classes_36k_train_004552 | 2,526 | permissive | [
{
"docstring": "The constructor ...",
"name": "__init__",
"signature": "def __init__(self, x_limits, y_limits, z_limits)"
},
{
"docstring": "This function ... :return:",
"name": "add_point",
"signature": "def add_point(self, x, y, z)"
}
] | 2 | null | Implement the Python class `ScatterAnimation` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, x_limits, y_limits, z_limits): The constructor ...
- def add_point(self, x, y, z): This function ... :return: | Implement the Python class `ScatterAnimation` described below.
Class description:
This class ...
Method signatures and docstrings:
- def __init__(self, x_limits, y_limits, z_limits): The constructor ...
- def add_point(self, x, y, z): This function ... :return:
<|skeleton|>
class ScatterAnimation:
"""This class ... | 62b2339beb2eb956565e1605d44d92f934361ad7 | <|skeleton|>
class ScatterAnimation:
"""This class ..."""
def __init__(self, x_limits, y_limits, z_limits):
"""The constructor ..."""
<|body_0|>
def add_point(self, x, y, z):
"""This function ... :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ScatterAnimation:
"""This class ..."""
def __init__(self, x_limits, y_limits, z_limits):
"""The constructor ..."""
super(ScatterAnimation, self).__init__()
self.fps = 5
self.x_limits = x_limits
self.y_limits = y_limits
self.z_limits = z_limits
self.... | the_stack_v2_python_sparse | CAAPR/CAAPR_AstroMagic/PTS/pts/magic/animation/scatter.py | Stargrazer82301/CAAPR | train | 8 |
d3ce4470d603bdb670ffd903ac853a6263e70f47 | [
"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... | Service to manage texture studio servers cluster. | TextureStudioManagerServiceServicer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
<|body_0|>
def GetServers(self, request, context):
"""Get all existing servers"""
... | stack_v2_sparse_classes_36k_train_004553 | 9,913 | permissive | [
{
"docstring": "Create a new texture studio server.",
"name": "CreateServer",
"signature": "def CreateServer(self, request, context)"
},
{
"docstring": "Get all existing servers",
"name": "GetServers",
"signature": "def GetServers(self, request, context)"
},
{
"docstring": "Get t... | 5 | stack_v2_sparse_classes_30k_test_000967 | Implement the Python class `TextureStudioManagerServiceServicer` described below.
Class description:
Service to manage texture studio servers cluster.
Method signatures and docstrings:
- def CreateServer(self, request, context): Create a new texture studio server.
- def GetServers(self, request, context): Get all exi... | Implement the Python class `TextureStudioManagerServiceServicer` described below.
Class description:
Service to manage texture studio servers cluster.
Method signatures and docstrings:
- def CreateServer(self, request, context): Create a new texture studio server.
- def GetServers(self, request, context): Get all exi... | 2a640f7667d23f39e50ccc9ba73c98138c6839b5 | <|skeleton|>
class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
<|body_0|>
def GetServers(self, request, context):
"""Get all existing servers"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TextureStudioManagerServiceServicer:
"""Service to manage texture studio servers cluster."""
def CreateServer(self, request, context):
"""Create a new texture studio server."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
r... | the_stack_v2_python_sparse | texturestudio/texturestudio_manage_pb2_grpc.py | MruV-RP/mruv-pb_python | train | 0 |
d22cc28a5835a2111c7646ab5cf33c708abc3e5f | [
"if not root:\n return False\nif not root.left and (not root.right):\n return root.val == targetSum\nleft = self.hasPathSum(root.left, targetSum - root.val)\nright = self.hasPathSum(root.right, targetSum - root.val)\nreturn left or right",
"if not root:\n return False\n\ndef traverse(root, count):\n i... | <|body_start_0|>
if not root:
return False
if not root.left and (not root.right):
return root.val == targetSum
left = self.hasPathSum(root.left, targetSum - root.val)
right = self.hasPathSum(root.right, targetSum - root.val)
return left or right
<|end_body... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
<|body_0|>
def hasPathSum(self, root, targetSum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_36k_train_004554 | 2,781 | no_license | [
{
"docstring": ":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。",
"name": "hasPathSum1",
"signature": "def hasPathSum1(self, root, targetSum)"
},
{
"docstring": ":type root: TreeNode :type targetSum: int :rtype:... | 3 | stack_v2_sparse_classes_30k_train_016846 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum1(self, root, targetSum): :type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。
- def... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPathSum1(self, root, targetSum): :type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。
- def... | 6e18c5d257840489cc3fb1079ae3804c743982a4 | <|skeleton|>
class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
<|body_0|>
def hasPathSum(self, root, targetSum):
""":type root: TreeNode :typ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hasPathSum1(self, root, targetSum):
""":type root: TreeNode :type targetSum: int :rtype: bool 递归,如果需要搜索整颗二叉树,那么递归函数就不要返回值, 如果要搜索其中一条符合条件的路径,递归函数就需要返回值, 因为遇到符合条件的路径了就要及时返回。"""
if not root:
return False
if not root.left and (not root.right):
return r... | the_stack_v2_python_sparse | 112.路径总和.py | yangyuxiang1996/leetcode | train | 0 | |
7da045574d75dc059612e12a489a9812428e9ba9 | [
"super().__init__()\nself.num_tokens = config['num_tokens']\nself.token_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=self.num_tokens)\nself.pos_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=config['seq_length'])\nself.unify_embeddings = nn.Linear(2 * config['emb'], con... | <|body_start_0|>
super().__init__()
self.num_tokens = config['num_tokens']
self.token_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=self.num_tokens)
self.pos_embedding = nn.Embedding(embedding_dim=config['emb'], num_embeddings=config['seq_length'])
self.uni... | Transformer for generating text (character based) | GTransformer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
<|body_0|>
def forward(self, x):
"""x is a batch of seq_length vectors of token indices"""
<|body_... | stack_v2_sparse_classes_36k_train_004555 | 1,553 | no_license | [
{
"docstring": "config has emb, heads, depth, seq_length, num_tokens",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "x is a batch of seq_length vectors of token indices",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_012043 | Implement the Python class `GTransformer` described below.
Class description:
Transformer for generating text (character based)
Method signatures and docstrings:
- def __init__(self, config): config has emb, heads, depth, seq_length, num_tokens
- def forward(self, x): x is a batch of seq_length vectors of token indic... | Implement the Python class `GTransformer` described below.
Class description:
Transformer for generating text (character based)
Method signatures and docstrings:
- def __init__(self, config): config has emb, heads, depth, seq_length, num_tokens
- def forward(self, x): x is a batch of seq_length vectors of token indic... | ef253f9f465a04a3de9d859d816eb913f896fa09 | <|skeleton|>
class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
<|body_0|>
def forward(self, x):
"""x is a batch of seq_length vectors of token indices"""
<|body_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GTransformer:
"""Transformer for generating text (character based)"""
def __init__(self, config):
"""config has emb, heads, depth, seq_length, num_tokens"""
super().__init__()
self.num_tokens = config['num_tokens']
self.token_embedding = nn.Embedding(embedding_dim=config['... | the_stack_v2_python_sparse | Attention/transformers.py | gadm21/AI | train | 0 |
d9443142bd2d6b9b3d1921aea4d69dc5a0bb3845 | [
"super(RSSFeed, self).__init__(config_section)\nself.url = app.config.get(config_section, 'url')\nself.interval = app.config.get_default(config_section, 'interval', 60, int)\nself.enabled = app.config.getboolean(config_section, 'enabled')",
"for entry in feedparser.parse(self.url).get('entries', {}):\n torrent... | <|body_start_0|>
super(RSSFeed, self).__init__(config_section)
self.url = app.config.get(config_section, 'url')
self.interval = app.config.get_default(config_section, 'interval', 60, int)
self.enabled = app.config.getboolean(config_section, 'enabled')
<|end_body_0|>
<|body_start_1|>
... | Provides a RSS service to use as a backend retrieval source | RSSFeed | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RSSFeed:
"""Provides a RSS service to use as a backend retrieval source"""
def __init__(self, config_section):
""":param config_section: Configuration section name :type config_section: string"""
<|body_0|>
def fetch_releases(self, session):
"""Parse the feed yie... | stack_v2_sparse_classes_36k_train_004556 | 3,121 | no_license | [
{
"docstring": ":param config_section: Configuration section name :type config_section: string",
"name": "__init__",
"signature": "def __init__(self, config_section)"
},
{
"docstring": "Parse the feed yielding valid release data to be added to the torrent backend. This will attempt to fetch prop... | 3 | stack_v2_sparse_classes_30k_train_018293 | Implement the Python class `RSSFeed` described below.
Class description:
Provides a RSS service to use as a backend retrieval source
Method signatures and docstrings:
- def __init__(self, config_section): :param config_section: Configuration section name :type config_section: string
- def fetch_releases(self, session... | Implement the Python class `RSSFeed` described below.
Class description:
Provides a RSS service to use as a backend retrieval source
Method signatures and docstrings:
- def __init__(self, config_section): :param config_section: Configuration section name :type config_section: string
- def fetch_releases(self, session... | 4eb22cdd35e01afad9f0e86f67290cdd69c4653a | <|skeleton|>
class RSSFeed:
"""Provides a RSS service to use as a backend retrieval source"""
def __init__(self, config_section):
""":param config_section: Configuration section name :type config_section: string"""
<|body_0|>
def fetch_releases(self, session):
"""Parse the feed yie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RSSFeed:
"""Provides a RSS service to use as a backend retrieval source"""
def __init__(self, config_section):
""":param config_section: Configuration section name :type config_section: string"""
super(RSSFeed, self).__init__(config_section)
self.url = app.config.get(config_sectio... | the_stack_v2_python_sparse | tranny/provider/rss.py | kannibalox/tranny | train | 4 |
dd164961fb119d4d5b4b64a4abf351c86c212b8a | [
"self.oldid = None\nif form.oldid is None or form.oldid == form.newid:\n obj.save()\n return\nwith transaction.atomic():\n migrated = []\n for t in Dive.objects.filter(levels__in=[form.oldid]):\n t.levels.remove(Level.objects.get(id=form.oldid))\n t.save()\n migrated.append(t)\n ... | <|body_start_0|>
self.oldid = None
if form.oldid is None or form.oldid == form.newid:
obj.save()
return
with transaction.atomic():
migrated = []
for t in Dive.objects.filter(levels__in=[form.oldid]):
t.levels.remove(Level.objects.ge... | LevelAdmin | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LevelAdmin:
def save_model(self, request, obj, form, change):
"""Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id."""
<|body_0|>
def response_change(self, request, obj):
"""If id was changed, always returns to the ... | stack_v2_sparse_classes_36k_train_004557 | 5,126 | permissive | [
{
"docstring": "Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id.",
"name": "save_model",
"signature": "def save_model(self, request, obj, form, change)"
},
{
"docstring": "If id was changed, always returns to the list (prevent 404). Otherwise... | 2 | null | Implement the Python class `LevelAdmin` described below.
Class description:
Implement the LevelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id.
- def response_change... | Implement the Python class `LevelAdmin` described below.
Class description:
Implement the LevelAdmin class.
Method signatures and docstrings:
- def save_model(self, request, obj, form, change): Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id.
- def response_change... | a91b75261a876be51ad2a693618629900bea6003 | <|skeleton|>
class LevelAdmin:
def save_model(self, request, obj, form, change):
"""Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id."""
<|body_0|>
def response_change(self, request, obj):
"""If id was changed, always returns to the ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LevelAdmin:
def save_model(self, request, obj, form, change):
"""Allows to change Level id from Admin form. It will migrate all dives using these levels to the new id."""
self.oldid = None
if form.oldid is None or form.oldid == form.newid:
obj.save()
return
... | the_stack_v2_python_sparse | geotrek/diving/admin.py | GeotrekCE/Geotrek-admin | train | 71 | |
10be8be9aa9584969a9e4ae55e924e0d0cdd8c9a | [
"junk_Decor.print_sep()\nt_items = cur.execute(' SELECT * FROM details WHERE %s = ?' % data, (value,))\nlist_db = []\nfor item in t_items:\n list_db.append(item)\njunk_Decor.print_sep()\nreturn list_db",
"junk_Decor.print_sep()\nt_items = cur.execute(' SELECT * FROM details WHERE %s > ?' % data, (value,))\nlis... | <|body_start_0|>
junk_Decor.print_sep()
t_items = cur.execute(' SELECT * FROM details WHERE %s = ?' % data, (value,))
list_db = []
for item in t_items:
list_db.append(item)
junk_Decor.print_sep()
return list_db
<|end_body_0|>
<|body_start_1|>
junk_Dec... | MIS_calculations | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MIS_calculations:
def separate_data_equal(data, value):
"""data will contain the data part ex "sl_no" or "name" or "e_mail etc." value will conatin the value of the data to be separated or sorted out from based on equality!"""
<|body_0|>
def separate_data_greater(data, value... | stack_v2_sparse_classes_36k_train_004558 | 10,620 | permissive | [
{
"docstring": "data will contain the data part ex \"sl_no\" or \"name\" or \"e_mail etc.\" value will conatin the value of the data to be separated or sorted out from based on equality!",
"name": "separate_data_equal",
"signature": "def separate_data_equal(data, value)"
},
{
"docstring": "data ... | 4 | null | Implement the Python class `MIS_calculations` described below.
Class description:
Implement the MIS_calculations class.
Method signatures and docstrings:
- def separate_data_equal(data, value): data will contain the data part ex "sl_no" or "name" or "e_mail etc." value will conatin the value of the data to be separat... | Implement the Python class `MIS_calculations` described below.
Class description:
Implement the MIS_calculations class.
Method signatures and docstrings:
- def separate_data_equal(data, value): data will contain the data part ex "sl_no" or "name" or "e_mail etc." value will conatin the value of the data to be separat... | 8d4c16b9e960d352a7775786ea60290b29b30143 | <|skeleton|>
class MIS_calculations:
def separate_data_equal(data, value):
"""data will contain the data part ex "sl_no" or "name" or "e_mail etc." value will conatin the value of the data to be separated or sorted out from based on equality!"""
<|body_0|>
def separate_data_greater(data, value... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MIS_calculations:
def separate_data_equal(data, value):
"""data will contain the data part ex "sl_no" or "name" or "e_mail etc." value will conatin the value of the data to be separated or sorted out from based on equality!"""
junk_Decor.print_sep()
t_items = cur.execute(' SELECT * FRO... | the_stack_v2_python_sparse | python_gui_tkinter/KALU/Version 0.1/MISman.py | Jimut123/code-backup | train | 9 | |
c64bf9ad1b0ed6a9c98fce6714301bc0819ad185 | [
"def memoize(N: int) -> int:\n if N <= 1:\n return N\n if N in self.cache.keys():\n return self.cache[N]\n self.cache[N] = memoize(N - 1) + memoize(N - 2)\n return memoize(N)\nself.cache = {0: 0, 1: 1}\nreturn memoize(N)",
"if N < 2:\n return N\ndp = [0] * (N + 1)\ndp[0], dp[1] = (0, ... | <|body_start_0|>
def memoize(N: int) -> int:
if N <= 1:
return N
if N in self.cache.keys():
return self.cache[N]
self.cache[N] = memoize(N - 1) + memoize(N - 2)
return memoize(N)
self.cache = {0: 0, 1: 1}
return memo... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fib(self, N: int) -> int:
"""递归超时,记忆化递归实现(数组/哈希表)"""
<|body_0|>
def fib1(self, N: int) -> int:
"""递归(自上而下)超时,循环实现(自下而上)"""
<|body_1|>
def fib2(self, N: int) -> int:
"""空间复杂度:O(1)"""
<|body_2|>
<|end_skeleton|>
<|body_start... | stack_v2_sparse_classes_36k_train_004559 | 1,986 | permissive | [
{
"docstring": "递归超时,记忆化递归实现(数组/哈希表)",
"name": "fib",
"signature": "def fib(self, N: int) -> int"
},
{
"docstring": "递归(自上而下)超时,循环实现(自下而上)",
"name": "fib1",
"signature": "def fib1(self, N: int) -> int"
},
{
"docstring": "空间复杂度:O(1)",
"name": "fib2",
"signature": "def fib2... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: int) -> int: 递归超时,记忆化递归实现(数组/哈希表)
- def fib1(self, N: int) -> int: 递归(自上而下)超时,循环实现(自下而上)
- def fib2(self, N: int) -> int: 空间复杂度:O(1) | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fib(self, N: int) -> int: 递归超时,记忆化递归实现(数组/哈希表)
- def fib1(self, N: int) -> int: 递归(自上而下)超时,循环实现(自下而上)
- def fib2(self, N: int) -> int: 空间复杂度:O(1)
<|skeleton|>
class Solution... | e8a1c6cae6547cbcb6e8494be6df685f3e7c837c | <|skeleton|>
class Solution:
def fib(self, N: int) -> int:
"""递归超时,记忆化递归实现(数组/哈希表)"""
<|body_0|>
def fib1(self, N: int) -> int:
"""递归(自上而下)超时,循环实现(自下而上)"""
<|body_1|>
def fib2(self, N: int) -> int:
"""空间复杂度:O(1)"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fib(self, N: int) -> int:
"""递归超时,记忆化递归实现(数组/哈希表)"""
def memoize(N: int) -> int:
if N <= 1:
return N
if N in self.cache.keys():
return self.cache[N]
self.cache[N] = memoize(N - 1) + memoize(N - 2)
ret... | the_stack_v2_python_sparse | 509-fibonacci-number.py | yuenliou/leetcode | train | 0 | |
57ea7dafdaca53dff495a7638cab08a7220f54a2 | [
"super().__init__()\nself.sprint = sprint or self._get_sprint_number()\nself._parser = JiraParser()",
"sprint = get_value_from_redis('sprint-number')\nif not sprint:\n sprint = JIRA_SPRINT\nreturn int(sprint)",
"endpoint_path = f'agile/1.0/sprint/{self.sprint}/issue'\ndata = {'jql': 'status=\"In Review\"', '... | <|body_start_0|>
super().__init__()
self.sprint = sprint or self._get_sprint_number()
self._parser = JiraParser()
<|end_body_0|>
<|body_start_1|>
sprint = get_value_from_redis('sprint-number')
if not sprint:
sprint = JIRA_SPRINT
return int(sprint)
<|end_body_... | An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/ | JiraAdapter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JiraAdapter:
"""An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/"""
def __init__(self, sprint: int=None):
"""Initialize."""
<|body_0|>
def _get_sprint_number() -> int:
"""Get sprint numb... | stack_v2_sparse_classes_36k_train_004560 | 4,564 | permissive | [
{
"docstring": "Initialize.",
"name": "__init__",
"signature": "def __init__(self, sprint: int=None)"
},
{
"docstring": "Get sprint number from Redis. If it doesn't exist, return a default number from .env.",
"name": "_get_sprint_number",
"signature": "def _get_sprint_number() -> int"
... | 5 | stack_v2_sparse_classes_30k_train_010377 | Implement the Python class `JiraAdapter` described below.
Class description:
An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/
Method signatures and docstrings:
- def __init__(self, sprint: int=None): Initialize.
- def _get_sprint_number() ->... | Implement the Python class `JiraAdapter` described below.
Class description:
An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/
Method signatures and docstrings:
- def __init__(self, sprint: int=None): Initialize.
- def _get_sprint_number() ->... | daea921a03f4798c9acd689fc9bc6010e72cf886 | <|skeleton|>
class JiraAdapter:
"""An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/"""
def __init__(self, sprint: int=None):
"""Initialize."""
<|body_0|>
def _get_sprint_number() -> int:
"""Get sprint numb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JiraAdapter:
"""An adapter to communicate with the JIRA API. API Documentation: https://docs.atlassian.com/software/jira/docs/api/REST/8.1.2/"""
def __init__(self, sprint: int=None):
"""Initialize."""
super().__init__()
self.sprint = sprint or self._get_sprint_number()
sel... | the_stack_v2_python_sparse | reporter/adapters.py | itsdkey/workreporter | train | 0 |
7d96dfa1689dbd19f6c00abe9da23a14f7436c5d | [
"log.info('Starting Infrastructure Layer...')\nself.topology = None\nsuper(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)",
"log.debug('Initializing Infrastructure Layer...')\nCONFIG.set_layer_loaded(self._core_name)\nmn_opts = CONFIG.get_mn_network_opts()\noptional_topo = getattr(self, '_topo', Non... | <|body_start_0|>
log.info('Starting Infrastructure Layer...')
self.topology = None
super(InfrastructureLayerAPI, self).__init__(standalone, **kwargs)
<|end_body_0|>
<|body_start_1|>
log.debug('Initializing Infrastructure Layer...')
CONFIG.set_layer_loaded(self._core_name)
... | Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point. | InfrastructureLayerAPI | [
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_36k_train_004561 | 4,274 | permissive | [
{
"docstring": ".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractAPI.__init__>`",
"name": "__init__",
"signature": "def __init__(self, standalone=False, **kwargs)"
},
{
"docstring": ".. seealso:: :func:`AbstractAPI.initialize() <escape.util.api.AbstractAPI.initialize>`",
"... | 4 | null | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | Implement the Python class `InfrastructureLayerAPI` described below.
Class description:
Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point.
Method signatures and docstrings:
- def __init__(self, standalone=False, **kwargs):... | 21b95843aa9308a5d3689bc2d30b2752b7121117 | <|skeleton|>
class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InfrastructureLayerAPI:
"""Entry point for Infrastructure Layer (IL). Maintain the contact with other UNIFY layers. Implement a specific part of the Co - Rm reference point."""
def __init__(self, standalone=False, **kwargs):
""".. seealso:: :func:`AbstractAPI.__init__() <escape.util.api.AbstractA... | the_stack_v2_python_sparse | escape/escape/infr/il_API.py | JerryLX/escape | train | 0 |
525b89718f0cf20d6405bb53f40bf60e0f5a28e4 | [
"if not head or k == 0 or (not head.next):\n return head\nt = head\nn = 0\nwhile t:\n n += 1\n t = t.next\nif k % n == 0:\n return head\np = head\nfor i in range(n - k % n - 1):\n p = p.next\nnewhead = p.next\nq = newhead\nfor i in range(k % n - 1):\n q = q.next\nq.next = head\np.next = None\nretu... | <|body_start_0|>
if not head or k == 0 or (not head.next):
return head
t = head
n = 0
while t:
n += 1
t = t.next
if k % n == 0:
return head
p = head
for i in range(n - k % n - 1):
p = p.next
newhe... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotateRight(self, head: ListNode, k) -> ListNode:
"""第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:"""
<|body_0|>
def rotateRight2(self, head, k):
"""20190718 :type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k_train_004562 | 2,150 | no_license | [
{
"docstring": "第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:",
"name": "rotateRight",
"signature": "def rotateRight(self, head: ListNode, k) -> ListNode"
},
{
"docstring": "20190718 :type head: ListNode :type k: int :rtype: ListNode",
"name": "rotateRight2",
"signature": ... | 2 | stack_v2_sparse_classes_30k_train_000603 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head: ListNode, k) -> ListNode: 第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:
- def rotateRight2(self, head, k): 20190718 :type head: ListNod... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotateRight(self, head: ListNode, k) -> ListNode: 第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:
- def rotateRight2(self, head, k): 20190718 :type head: ListNod... | 5d3574ccd282d0146c83c286ae28d8baaabd4910 | <|skeleton|>
class Solution:
def rotateRight(self, head: ListNode, k) -> ListNode:
"""第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:"""
<|body_0|>
def rotateRight2(self, head, k):
"""20190718 :type head: ListNode :type k: int :rtype: ListNode"""
<|body_1|>
<|end_... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotateRight(self, head: ListNode, k) -> ListNode:
"""第n-k个数的next节点指向None 尾节点指向头结点 :param head: :param k: :return:"""
if not head or k == 0 or (not head.next):
return head
t = head
n = 0
while t:
n += 1
t = t.next
... | the_stack_v2_python_sparse | 61_旋转链表.py | lovehhf/LeetCode | train | 0 | |
9315fa507033fe98749a343224ffdaa28fe43dda | [
"table = self.tables[table_name]\nupdate_dict = _clean_dict(update_dict, table.schema)\ntb_func = getattr(self.tensorboard, 'add_%s' % summary_type)\nstep = step if step else table.nrows\nfor name, value in update_dict.items():\n tb_func('/'.join([table_name, name]), value, step)",
"table = self.tables[table_n... | <|body_start_0|>
table = self.tables[table_name]
update_dict = _clean_dict(update_dict, table.schema)
tb_func = getattr(self.tensorboard, 'add_%s' % summary_type)
step = step if step else table.nrows
for name, value in update_dict.items():
tb_func('/'.join([table_name... | The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree. | CustomStore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, ta... | stack_v2_sparse_classes_36k_train_004563 | 3,794 | no_license | [
{
"docstring": "Log to only tensorboard. Args: table_name (str) : which table to log to update_dict (dict) : values to log and store as a dictionary of column mapping to value. summary_type (str) : what type of summary to log to tensorboard as step: which step index to insert datapoint",
"name": "log_tb",
... | 3 | stack_v2_sparse_classes_30k_train_016234 | Implement the Python class `CustomStore` described below.
Class description:
The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this s... | Implement the Python class `CustomStore` described below.
Class description:
The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this s... | 978de314897904c9014209d479c03dc3509f7dc0 | <|skeleton|>
class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, ta... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomStore:
"""The following class is derived from cox. https://github.com/MadryLab/cox/blob/master/cox/store.py Copyright (c) 2018 Andrew Ilyas, Logan Engstrom, licensed under the MIT license, cf. 3rd-party-licenses.txt file in the root directory of this source tree."""
def log_tb(self, table_name, upd... | the_stack_v2_python_sparse | playground/trl/projections/custom_store.py | NiklasFreymuth/bayesian-aggregation-for-swarm-reinforcement-learning | train | 0 |
cd3573f0dfa867d336d395af0fa81e99a4782534 | [
"res = []\n\ndef helper(root):\n if not root:\n return\n res.append(str(root.val))\n res.append(str(len(root.children)))\n for ch in root.children:\n helper(ch)\nhelper(root)\nreturn ','.join(res)",
"if not data:\n return\ndata = iter(data.split(','))\n\ndef helper():\n tmp = int(n... | <|body_start_0|>
res = []
def helper(root):
if not root:
return
res.append(str(root.val))
res.append(str(len(root.children)))
for ch in root.children:
helper(ch)
helper(root)
return ','.join(res)
<|end_body_... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k_train_004564 | 2,421 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_val_000895 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root: 'Node') -> str: Encodes a tree to a single string. :type root: Node :rtype: str
- def deserialize(self, data: str) -> 'Node': Decodes your encoded data to tre... | 631df2ce6892a6fbb3e435f57e90d85f8200d125 | <|skeleton|>
class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
<|body_0|>
def deserialize(self, data: str) -> 'Node':
"""Decodes your encoded data to tree. :type data: str :rtype: Node"""
<|body_1|>
<|e... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def helper(root):
if not root:
return
res.append(str(root.val))
res.append(str(len(root.children)))
... | the_stack_v2_python_sparse | 428. Serialize and Deserialize N-ary Tree.py | c940606/leetcode | train | 3 | |
8d347b892476e3a91037b5378078f7523935d34a | [
"edits = self.StrategyName[0] + '/state'\nclient = Http_client()\nclient.put(url=url + edits, json={'locked': True}, header=headers)\ncomm = CommonDocPolicyMgnt()\nStrategyState = comm.selectStrategyState(self.StrategyName[0])\nassert client.status_code == checkpoint['status_code']\nassert StrategyState == 1\nasser... | <|body_start_0|>
edits = self.StrategyName[0] + '/state'
client = Http_client()
client.put(url=url + edits, json={'locked': True}, header=headers)
comm = CommonDocPolicyMgnt()
StrategyState = comm.selectStrategyState(self.StrategyName[0])
assert client.status_code == chec... | Test_EditStrategyState200 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_EditStrategyState200:
def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint):
"""用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_EditStrategyTrues00(self, url, jsondata, headers, checkpoint):
... | stack_v2_sparse_classes_36k_train_004565 | 4,617 | no_license | [
{
"docstring": "用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查",
"name": "test_EditStrategyTrue200",
"signature": "def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint)"
},
{
"docstring": "用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用... | 4 | null | Implement the Python class `Test_EditStrategyState200` described below.
Class description:
Implement the Test_EditStrategyState200 class.
Method signatures and docstrings:
- def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint): 用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同... | Implement the Python class `Test_EditStrategyState200` described below.
Class description:
Implement the Test_EditStrategyState200 class.
Method signatures and docstrings:
- def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint): 用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同... | ab922c82c2454a3397ddbf4cd0771067734e1111 | <|skeleton|>
class Test_EditStrategyState200:
def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint):
"""用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
<|body_0|>
def test_EditStrategyTrues00(self, url, jsondata, headers, checkpoint):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Test_EditStrategyState200:
def test_EditStrategyTrue200(self, url, jsondata, headers, checkpoint):
"""用例描述:test_EditStrategyState200方法用于设置策略状态接口 json数据包含禅道上多条用例的校验,具体对body中不同功能的传参检查"""
edits = self.StrategyName[0] + '/state'
client = Http_client()
client.put(url=url + edits, js... | the_stack_v2_python_sparse | Case/AS/Http/DocPolicyMgnt/test_EditStrategyState200.py | GWenPeng/Apitest_framework | train | 0 | |
caa92c21d7a913169603d0c83b7c0f139421dac4 | [
"if not toolkit.request.method == 'POST':\n raise toolkit.abort(400, 'Expected POST method')\nuser = toolkit.c.userobj\nif not user:\n raise toolkit.NotAuthorized('Membership request requires an user')\ndataset = Package.by_name(dataset_name)\nname_width = min(len(dataset.name), 88)\nforked_name = '{name}-for... | <|body_start_0|>
if not toolkit.request.method == 'POST':
raise toolkit.abort(400, 'Expected POST method')
user = toolkit.c.userobj
if not user:
raise toolkit.NotAuthorized('Membership request requires an user')
dataset = Package.by_name(dataset_name)
name... | YouckanDatasetController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class YouckanDatasetController:
def fork(self, dataset_name):
"""Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the original will have a new related reference to the fork."""
<|body_0|>
def alert(self, dataset_name):
... | stack_v2_sparse_classes_36k_train_004566 | 4,983 | no_license | [
{
"docstring": "Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the original will have a new related reference to the fork.",
"name": "fork",
"signature": "def fork(self, dataset_name)"
},
{
"docstring": "Put an alert aka. a signaleme... | 3 | stack_v2_sparse_classes_30k_test_000241 | Implement the Python class `YouckanDatasetController` described below.
Class description:
Implement the YouckanDatasetController class.
Method signatures and docstrings:
- def fork(self, dataset_name): Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the or... | Implement the Python class `YouckanDatasetController` described below.
Class description:
Implement the YouckanDatasetController class.
Method signatures and docstrings:
- def fork(self, dataset_name): Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the or... | 8303e94363805a49d3cf93ee5216c7135b22e481 | <|skeleton|>
class YouckanDatasetController:
def fork(self, dataset_name):
"""Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the original will have a new related reference to the fork."""
<|body_0|>
def alert(self, dataset_name):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class YouckanDatasetController:
def fork(self, dataset_name):
"""Fork this package by duplicating it. The new owner will be the user parameter. The new package is created and the original will have a new related reference to the fork."""
if not toolkit.request.method == 'POST':
raise too... | the_stack_v2_python_sparse | ckanext/youckan/controllers/dataset.py | morty/ckanext-youckan | train | 0 | |
f143ab870b4a94aaaca38a8ba58c508148bdc5ea | [
"t = np.arange(0, 5, 0.5)\nP = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 16.1, 16.2])\nOH = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 7, 2])\nCO = OH * 0.9\nt_ign = find_ignition_delay(t, P)\nself.assertEqual(t_ign, 2.75)\nt_ign = find_ignition_delay(t, OH, 'maxHalfConcentration')\nself.assertEqual(t_ign, 3)\nt_i... | <|body_start_0|>
t = np.arange(0, 5, 0.5)
P = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 16.1, 16.2])
OH = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 7, 2])
CO = OH * 0.9
t_ign = find_ignition_delay(t, P)
self.assertEqual(t_ign, 2.75)
t_ign = find_ignition_delay(t... | CanteraTest | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CanteraTest:
def test_ignition_delay(self):
"""Test that find_ignition_delay() works."""
<|body_0|>
def test_repr(self):
"""Test that the repr function for a CanteraCondition object can reconstitute the same object"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_004567 | 5,853 | permissive | [
{
"docstring": "Test that find_ignition_delay() works.",
"name": "test_ignition_delay",
"signature": "def test_ignition_delay(self)"
},
{
"docstring": "Test that the repr function for a CanteraCondition object can reconstitute the same object",
"name": "test_repr",
"signature": "def test... | 2 | null | Implement the Python class `CanteraTest` described below.
Class description:
Implement the CanteraTest class.
Method signatures and docstrings:
- def test_ignition_delay(self): Test that find_ignition_delay() works.
- def test_repr(self): Test that the repr function for a CanteraCondition object can reconstitute the ... | Implement the Python class `CanteraTest` described below.
Class description:
Implement the CanteraTest class.
Method signatures and docstrings:
- def test_ignition_delay(self): Test that find_ignition_delay() works.
- def test_repr(self): Test that the repr function for a CanteraCondition object can reconstitute the ... | 349a4af759cf8877197772cd7eaca1e51d46eff5 | <|skeleton|>
class CanteraTest:
def test_ignition_delay(self):
"""Test that find_ignition_delay() works."""
<|body_0|>
def test_repr(self):
"""Test that the repr function for a CanteraCondition object can reconstitute the same object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CanteraTest:
def test_ignition_delay(self):
"""Test that find_ignition_delay() works."""
t = np.arange(0, 5, 0.5)
P = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 16.1, 16.2])
OH = np.array([0, 0.33, 0.5, 0.9, 2, 4, 15, 16, 7, 2])
CO = OH * 0.9
t_ign = find_igniti... | the_stack_v2_python_sparse | rmgpy/tools/canteramodelTest.py | CanePan-cc/CanePanWorkshop | train | 2 | |
96a055279e043c2c22f6d9762cd74471e4bfa8c4 | [
"self.L = L\nself.W = W\nself.Q = np.zeros((L, W, 4))\nself.model = {}\nself.tau = np.zeros((L, W, 4))",
"self.Q[x, y, action] += alpha * (reward + gamma * max(self.Q[new_x][new_y]) - self.Q[x, y, action])\nself.tau[x, y, action] = t\nself.model[x, y, action] = (new_x, new_y, reward)\nfor action in range(4):\n ... | <|body_start_0|>
self.L = L
self.W = W
self.Q = np.zeros((L, W, 4))
self.model = {}
self.tau = np.zeros((L, W, 4))
<|end_body_0|>
<|body_start_1|>
self.Q[x, y, action] += alpha * (reward + gamma * max(self.Q[new_x][new_y]) - self.Q[x, y, action])
self.tau[x, y, a... | Dyna-Q agent that attempts to learn the optimal policy. | Agent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
<|body_0|>
def updateQ(self, x, y, action, reward, new_x, new_y, alpha, ga... | stack_v2_sparse_classes_36k_train_004568 | 9,439 | permissive | [
{
"docstring": "Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.",
"name": "__init__",
"signature": "def __init__(self, L, W)"
},
{
"docstring": "Performs the direct RL update in the Dyna-Q algorithm and updates the learned model based on a real int... | 4 | stack_v2_sparse_classes_30k_train_004742 | Implement the Python class `Agent` described below.
Class description:
Dyna-Q agent that attempts to learn the optimal policy.
Method signatures and docstrings:
- def __init__(self, L, W): Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.
- def updateQ(self, x, y, action,... | Implement the Python class `Agent` described below.
Class description:
Dyna-Q agent that attempts to learn the optimal policy.
Method signatures and docstrings:
- def __init__(self, L, W): Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid.
- def updateQ(self, x, y, action,... | 127d3fe10fe5774be7f8db3b00f6737f3eed363d | <|skeleton|>
class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
<|body_0|>
def updateQ(self, x, y, action, reward, new_x, new_y, alpha, ga... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Agent:
"""Dyna-Q agent that attempts to learn the optimal policy."""
def __init__(self, L, W):
"""Initializes the agent. @type L: int The length of the grid. @type W: int The width of the grid."""
self.L = L
self.W = W
self.Q = np.zeros((L, W, 4))
self.model = {}
... | the_stack_v2_python_sparse | Ch8/dynaQ.py | lolcharles2/Reinforcement_learning_book_implementations | train | 0 |
9a6248b7639a9ff6d7f3e638405a88ff7b222123 | [
"self.timeout = config('DEFAULT_TIMEOUT')\nif 'timeout' in kwargs:\n self.timeout = kwargs['timeout']\n del kwargs['timeout']\nsuper().__init__(*args, **kwargs)",
"timeout_ = kwargs.get('timeout')\nif timeout_ is None:\n kwargs['timeout'] = self.timeout\nreturn super().send(request, **kwargs)"
] | <|body_start_0|>
self.timeout = config('DEFAULT_TIMEOUT')
if 'timeout' in kwargs:
self.timeout = kwargs['timeout']
del kwargs['timeout']
super().__init__(*args, **kwargs)
<|end_body_0|>
<|body_start_1|>
timeout_ = kwargs.get('timeout')
if timeout_ is None... | Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas (▀̿̿Ĺ̯̿▀̿ ̿) | TimeoutHTTPAdapter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TimeoutHTTPAdapter:
"""Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas (▀̿̿Ĺ̯̿▀̿ ̿)"""
def __init__(self,... | stack_v2_sparse_classes_36k_train_004569 | 21,914 | no_license | [
{
"docstring": "nome: __init__ :param args: tuple, Any :param kwargs: str",
"name": "__init__",
"signature": "def __init__(self, *args, **kwargs)"
},
{
"docstring": "nome: send :param request: request :param kwargs: str :return: super().send(request, **kwargs)",
"name": "send",
"signatur... | 2 | null | Implement the Python class `TimeoutHTTPAdapter` described below.
Class description:
Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas ... | Implement the Python class `TimeoutHTTPAdapter` described below.
Class description:
Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas ... | b976114c78099c0b949ba915c636e111b9120884 | <|skeleton|>
class TimeoutHTTPAdapter:
"""Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas (▀̿̿Ĺ̯̿▀̿ ̿)"""
def __init__(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TimeoutHTTPAdapter:
"""Nome : TimeoutHTTPAdapter Parametro_1 : HTTPAdapter Criada : junho-2021 Descrição : faz... ____________________________________________________________________________________________________ Todos direitos reservados à Magna Sistemas (▀̿̿Ĺ̯̿▀̿ ̿)"""
def __init__(self, *args, **kwa... | the_stack_v2_python_sparse | api/utilities.py | maccaconta/orquestradora | train | 0 |
34111399be25279218275ead78c5ab8a74d7af9c | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId()",
"from .entity import Entity\nfrom .entity import Entity\nfields: Dict[str, Callable[[Any], None]] = {'appCrashCount': lambda n: setattr(self, 'app_crash_count', n.g... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .entity import Entity
fields: Dict[str, Calla... | The user experience analytics application performance entity contains application performance by application version device id. | UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienc... | stack_v2_sparse_classes_36k_train_004570 | 4,506 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId",
"name": "create_from_discriminator_value",
... | 3 | stack_v2_sparse_classes_30k_train_006310 | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version device id.
Method signatures and docstrings:
- def create_from_discri... | Implement the Python class `UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId` described below.
Class description:
The user experience analytics application performance entity contains application performance by application version device id.
Method signatures and docstrings:
- def create_from_discri... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserExperienceAnalyticsAppHealthAppPerformanceByAppVersionDeviceId:
"""The user experience analytics application performance entity contains application performance by application version device id."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsApp... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_app_health_app_performance_by_app_version_device_id.py | microsoftgraph/msgraph-sdk-python | train | 135 |
b59c1d34326e3f1876702753ebb9aff28d485e1f | [
"result_particles = []\nnd_timestamp, non_data, non_start, non_end = self._chunker.get_next_non_data_with_index(clean=False)\ntimestamp, chunk, start, end = self._chunker.get_next_data_with_index(clean=True)\nself.handle_non_data(non_data, non_end, start)\nwhile chunk is not None:\n header_match = SIO_HEADER_MAT... | <|body_start_0|>
result_particles = []
nd_timestamp, non_data, non_start, non_end = self._chunker.get_next_non_data_with_index(clean=False)
timestamp, chunk, start, end = self._chunker.get_next_data_with_index(clean=True)
self.handle_non_data(non_data, non_end, start)
while chunk... | Abstract Class for parsing Sio Eng Sio files | SioEngSioParser | [
"BSD-2-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SioEngSioParser:
"""Abstract Class for parsing Sio Eng Sio files"""
def parse_chunks(self):
"""Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a li... | stack_v2_sparse_classes_36k_train_004571 | 6,504 | permissive | [
{
"docstring": "Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples with sample particles encountered in this parsing, plus the state. An empty list of nothing wa... | 2 | null | Implement the Python class `SioEngSioParser` described below.
Class description:
Abstract Class for parsing Sio Eng Sio files
Method signatures and docstrings:
- def parse_chunks(self): Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. ... | Implement the Python class `SioEngSioParser` described below.
Class description:
Abstract Class for parsing Sio Eng Sio files
Method signatures and docstrings:
- def parse_chunks(self): Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. ... | bdbf01f5614e7188ce19596704794466e5683b30 | <|skeleton|>
class SioEngSioParser:
"""Abstract Class for parsing Sio Eng Sio files"""
def parse_chunks(self):
"""Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a li... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SioEngSioParser:
"""Abstract Class for parsing Sio Eng Sio files"""
def parse_chunks(self):
"""Parse out any pending data chunks in the chunker. If it is a valid data piece, build a particle, update the position and timestamp. Go until the chunker has no more valid data. @retval a list of tuples ... | the_stack_v2_python_sparse | mi/dataset/parser/sio_eng_sio.py | oceanobservatories/mi-instrument | train | 1 |
c8d60afff504245edf0668c4fbfb985f725afdc6 | [
"data = ConfigStore.get_config()\nif 'power_profiles' not in data:\n return ([], 200)\nreturn (data['power_profiles'], 200)",
"json_data = request.get_json()\ntry:\n schema, resolver = ConfigStore().load_json_schema('add_power.json')\n jsonschema.validate(json_data, schema, resolver=resolver)\nexcept (js... | <|body_start_0|>
data = ConfigStore.get_config()
if 'power_profiles' not in data:
return ([], 200)
return (data['power_profiles'], 200)
<|end_body_0|>
<|body_start_1|>
json_data = request.get_json()
try:
schema, resolver = ConfigStore().load_json_schema('... | Handles /power_profiles HTTP requests | Powers | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Powers:
"""Handles /power_profiles HTTP requests"""
def get():
"""Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code"""
<|body_0|>
def post():
"""Handles HTTP POST /power_profiles request. Add a ne... | stack_v2_sparse_classes_36k_train_004572 | 7,986 | permissive | [
{
"docstring": "Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code",
"name": "get",
"signature": "def get()"
},
{
"docstring": "Handles HTTP POST /power_profiles request. Add a new Power Profile Raises BadRequest Returns: response... | 2 | stack_v2_sparse_classes_30k_train_007294 | Implement the Python class `Powers` described below.
Class description:
Handles /power_profiles HTTP requests
Method signatures and docstrings:
- def get(): Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code
- def post(): Handles HTTP POST /power_profi... | Implement the Python class `Powers` described below.
Class description:
Handles /power_profiles HTTP requests
Method signatures and docstrings:
- def get(): Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code
- def post(): Handles HTTP POST /power_profi... | 86883b2b5cc71ee543b39878f37b5a6f533594fa | <|skeleton|>
class Powers:
"""Handles /power_profiles HTTP requests"""
def get():
"""Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code"""
<|body_0|>
def post():
"""Handles HTTP POST /power_profiles request. Add a ne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Powers:
"""Handles /power_profiles HTTP requests"""
def get():
"""Handles HTTP GET /power_profiles request. Retrieve all power profiles Raises NotFound Returns: response, status code"""
data = ConfigStore.get_config()
if 'power_profiles' not in data:
return ([], 200)
... | the_stack_v2_python_sparse | appqos/appqos/rest/rest_power.py | intel/intel-cmt-cat | train | 528 |
54dc020b654c45e79beb5dc933e373a4f0e71d80 | [
"super(GAT, self).__init__()\nself.dropout = dropout\nself.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]\nfor i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\nself.out_att = GraphAttentionLayer(... | <|body_start_0|>
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i),... | GAT | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GAT:
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
"""Dense version of GAT."""
<|body_0|>
def forward(self, x, adj):
"""Input: [node, nfeat], output: [node, nclass]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
super(GAT, self).... | stack_v2_sparse_classes_36k_train_004573 | 8,391 | no_license | [
{
"docstring": "Dense version of GAT.",
"name": "__init__",
"signature": "def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads)"
},
{
"docstring": "Input: [node, nfeat], output: [node, nclass]",
"name": "forward",
"signature": "def forward(self, x, adj)"
}
] | 2 | stack_v2_sparse_classes_30k_train_005572 | Implement the Python class `GAT` described below.
Class description:
Implement the GAT class.
Method signatures and docstrings:
- def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads): Dense version of GAT.
- def forward(self, x, adj): Input: [node, nfeat], output: [node, nclass] | Implement the Python class `GAT` described below.
Class description:
Implement the GAT class.
Method signatures and docstrings:
- def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads): Dense version of GAT.
- def forward(self, x, adj): Input: [node, nfeat], output: [node, nclass]
<|skeleton|>
class GAT:
... | c0b1e44be34b763622dac60ae8525803432fd52e | <|skeleton|>
class GAT:
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
"""Dense version of GAT."""
<|body_0|>
def forward(self, x, adj):
"""Input: [node, nfeat], output: [node, nclass]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GAT:
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):
"""Dense version of GAT."""
super(GAT, self).__init__()
self.dropout = dropout
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]
fo... | the_stack_v2_python_sparse | engineer/models/common/GCNattention.py | LittleFlyFish/Motion-Cycle-GCN | train | 0 | |
704706d003f1e05df39d8147592a79739121dfad | [
"organization_id = request.query_params.get('organization_id', None)\norg = Organization.objects.get(pk=organization_id)\ncolumn_mappings = []\nfor cm in ColumnMapping.objects.filter(super_organization=org):\n column_mappings.append(cm.to_dict())\nreturn JsonResponse({'status': 'success', 'column_mappings': colu... | <|body_start_0|>
organization_id = request.query_params.get('organization_id', None)
org = Organization.objects.get(pk=organization_id)
column_mappings = []
for cm in ColumnMapping.objects.filter(super_organization=org):
column_mappings.append(cm.to_dict())
return Jso... | ColumnMappingViewSet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ColumnMappingViewSet:
def list(self, request):
"""Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either success or error column_mappings: required: true type: array[column] description: Returns an array where each ite... | stack_v2_sparse_classes_36k_train_004574 | 14,162 | no_license | [
{
"docstring": "Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either success or error column_mappings: required: true type: array[column] description: Returns an array where each item is a full column_mapping structure, including keys ''nam... | 3 | null | Implement the Python class `ColumnMappingViewSet` described below.
Class description:
Implement the ColumnMappingViewSet class.
Method signatures and docstrings:
- def list(self, request): Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either succ... | Implement the Python class `ColumnMappingViewSet` described below.
Class description:
Implement the ColumnMappingViewSet class.
Method signatures and docstrings:
- def list(self, request): Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either succ... | 9e003b344d0c89f416d23651d1e1ce2a624dc599 | <|skeleton|>
class ColumnMappingViewSet:
def list(self, request):
"""Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either success or error column_mappings: required: true type: array[column] description: Returns an array where each ite... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ColumnMappingViewSet:
def list(self, request):
"""Retrieves all column mappings for the user's organization. --- type: status: required: true type: string description: Either success or error column_mappings: required: true type: array[column] description: Returns an array where each item is a full co... | the_stack_v2_python_sparse | seed/views/columns.py | 353388947/seed | train | 1 | |
489f02def2ac5b3e94619dd971be18c8e82a4d98 | [
"if verbose:\n print('SQL Database type %s verbose=%s' % (db_dict, verbose))\nsuper(SQLCompaniesTable, self).__init__(db_dict, dbtype, verbose)\nself.connection = None",
"try:\n print('Database characteristics')\n for key in self.db_dict:\n print('%s: %s' % key, self.db_dict[key])\nexcept ValueEr... | <|body_start_0|>
if verbose:
print('SQL Database type %s verbose=%s' % (db_dict, verbose))
super(SQLCompaniesTable, self).__init__(db_dict, dbtype, verbose)
self.connection = None
<|end_body_0|>
<|body_start_1|>
try:
print('Database characteristics')
... | " Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized. | SQLCompaniesTable | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SQLCompaniesTable:
"""" Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(self):
... | stack_v2_sparse_classes_36k_train_004575 | 9,313 | permissive | [
{
"docstring": "Pass through to SQL",
"name": "__init__",
"signature": "def __init__(self, db_dict, dbtype, verbose)"
},
{
"docstring": "Display the db info and Return info on the database used as a dictionary.",
"name": "db_info",
"signature": "def db_info(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007369 | Implement the Python class `SQLCompaniesTable` described below.
Class description:
" Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pass throu... | Implement the Python class `SQLCompaniesTable` described below.
Class description:
" Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized.
Method signatures and docstrings:
- def __init__(self, db_dict, dbtype, verbose): Pass throu... | 9c60b3489f02592bd9099b8719ca23ae43a9eaa5 | <|skeleton|>
class SQLCompaniesTable:
"""" Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
<|body_0|>
def db_info(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SQLCompaniesTable:
"""" Table representing the Companies database table This table supports a single dictionary that contains the data when the table is intialized."""
def __init__(self, db_dict, dbtype, verbose):
"""Pass through to SQL"""
if verbose:
print('SQL Database type ... | the_stack_v2_python_sparse | smipyping/_companiestable.py | KSchopmeyer/smipyping | train | 0 |
ef10982b6e273e7456dff909c70456075cd34d19 | [
"logs.log_info('You are using the inward rectifying K+ channel: Kir2p1')\nself.time_unit = 1000.0\nself.vrev = -70.6\nself.m = 1 / (1 + np.exp((V - -96.48) / 23.26))\nself.h = 1 / (1 + np.exp((V - -168.28) / -44.13))\nself._mpower = 1\nself._hpower = 2",
"self._mInf = 1 / (1 + np.exp((V - -96.48) / 23.26))\nself.... | <|body_start_0|>
logs.log_info('You are using the inward rectifying K+ channel: Kir2p1')
self.time_unit = 1000.0
self.vrev = -70.6
self.m = 1 / (1 + np.exp((V - -96.48) / 23.26))
self.h = 1 / (1 + np.exp((V - -168.28) / -44.13))
self._mpower = 1
self._hpower = 2
<... | Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues. Mutations in this gene have been associated with Andersen syndrome, whic... | Kir2p1 | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Kir2p1:
"""Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues. Mutations in this gene have been assoc... | stack_v2_sparse_classes_36k_train_004576 | 24,227 | no_license | [
{
"docstring": "Run initialization calculation for m and h gates of the channel at starting Vmem value.",
"name": "_init_state",
"signature": "def _init_state(self, V)"
},
{
"docstring": "Update the state of m and h gates of the channel given their present value and present simulation Vmem.",
... | 2 | null | Implement the Python class `Kir2p1` described below.
Class description:
Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues.... | Implement the Python class `Kir2p1` described below.
Class description:
Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues.... | dd03ff5e3df3ef48d887a6566a6286fcd168880b | <|skeleton|>
class Kir2p1:
"""Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues. Mutations in this gene have been assoc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Kir2p1:
"""Kir 2.1 model from Makary et al. This channel has a greater tendency to allow potassium to flow into a cell rather than out of a cell, probably participates in establishing action potential waveform and excitability of neuronal and muscle tissues. Mutations in this gene have been associated with An... | the_stack_v2_python_sparse | betse/science/channels/vg_k.py | R-Stefano/betse-ml | train | 0 |
838ff06db59e93d4ec6524cd3ce07924d4f6491d | [
"self.id = id\nself.name = name\nself.status = status\nself.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None\nself.updated_at = APIHelper.RFC3339DateTime(updated_at) if updated_at else None\nself.pricing_scheme = pricing_scheme\nself.description = description\nself.plan = plan\nself.quanti... | <|body_start_0|>
self.id = id
self.name = name
self.status = status
self.created_at = APIHelper.RFC3339DateTime(created_at) if created_at else None
self.updated_at = APIHelper.RFC3339DateTime(updated_at) if updated_at else None
self.pricing_scheme = pricing_scheme
... | Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): TODO: type description here. updated_at (datetime): TODO: type des... | PlansItemsResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PlansItemsResponse:
"""Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): TODO: type descripti... | stack_v2_sparse_classes_36k_train_004577 | 4,446 | permissive | [
{
"docstring": "Constructor for the PlansItemsResponse class",
"name": "__init__",
"signature": "def __init__(self, id=None, name=None, status=None, created_at=None, updated_at=None, pricing_scheme=None, description=None, plan=None, quantity=None, cycles=None, deleted_at=None)"
},
{
"docstring":... | 2 | stack_v2_sparse_classes_30k_train_007679 | Implement the Python class `PlansItemsResponse` described below.
Class description:
Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. crea... | Implement the Python class `PlansItemsResponse` described below.
Class description:
Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. crea... | 95c80c35dd57bb2a238faeaf30d1e3b4544d2298 | <|skeleton|>
class PlansItemsResponse:
"""Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): TODO: type descripti... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PlansItemsResponse:
"""Implementation of the 'Plans Items Response' model. TODO: type model description here. Attributes: id (string): TODO: type description here. name (string): TODO: type description here. status (string): TODO: type description here. created_at (datetime): TODO: type description here. upda... | the_stack_v2_python_sparse | mundiapi/models/plans_items_response.py | mundipagg/MundiAPI-PYTHON | train | 10 |
54478c202509058514035cf7f88d25a00312b5bc | [
"Integrator.setup_integrator(self)\nself.setup_cl(context)\nself.cl_precision = self.particles.get_cl_precision()",
"self.context = context\nfor calc in self.calcs:\n calc.setup_cl(context)\nroot = get_pysph_root()\nsrc = cl_read(path.join(root, 'solver/integrator.cl'), self.particles.get_cl_precision())\nself... | <|body_start_0|>
Integrator.setup_integrator(self)
self.setup_cl(context)
self.cl_precision = self.particles.get_cl_precision()
<|end_body_0|>
<|body_start_1|>
self.context = context
for calc in self.calcs:
calc.setup_cl(context)
root = get_pysph_root()
... | CLIntegrator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CLIntegrator:
def setup_integrator(self, context):
"""Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs must be called when all particle properties on the particle array are created. This is important as all ... | stack_v2_sparse_classes_36k_train_004578 | 9,164 | permissive | [
{
"docstring": "Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs must be called when all particle properties on the particle array are created. This is important as all device buffers will created.",
"name": "setup_integrator",... | 6 | stack_v2_sparse_classes_30k_test_000694 | Implement the Python class `CLIntegrator` described below.
Class description:
Implement the CLIntegrator class.
Method signatures and docstrings:
- def setup_integrator(self, context): Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs mus... | Implement the Python class `CLIntegrator` described below.
Class description:
Implement the CLIntegrator class.
Method signatures and docstrings:
- def setup_integrator(self, context): Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs mus... | 5bb1fc46a9c84aefd42758356a9986689db05454 | <|skeleton|>
class CLIntegrator:
def setup_integrator(self, context):
"""Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs must be called when all particle properties on the particle array are created. This is important as all ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CLIntegrator:
def setup_integrator(self, context):
"""Setup the additional particle arrays for integration. Parameters: ----------- context -- the OpenCL context setup_cl on the calcs must be called when all particle properties on the particle array are created. This is important as all device buffers... | the_stack_v2_python_sparse | source/pysph/solver/cl_integrator.py | pankajp/pysph | train | 1 | |
ada817b3f8fdebc8821fd6a3a0eb91bdafbca42b | [
"song_vote = get_object_or_404(SongVote, pk=song_vote_id)\nserializer = SongVoteSerializerUpdate(song_vote, data=request.data, context={'request': request}, partial=True)\nif serializer.is_valid():\n serializer.save()\n return Response(SongVoteSerializer(serializer.instance).data)\nreturn Response(serializer.... | <|body_start_0|>
song_vote = get_object_or_404(SongVote, pk=song_vote_id)
serializer = SongVoteSerializerUpdate(song_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_valid():
serializer.save()
return Response(SongVoteSerializer(seriali... | SongVoteDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SongVoteDetail:
def patch(request, song_vote_id):
"""Update song vote"""
<|body_0|>
def delete(request, song_vote_id):
"""Delete song vote"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
song_vote = get_object_or_404(SongVote, pk=song_vote_id)
... | stack_v2_sparse_classes_36k_train_004579 | 1,744 | permissive | [
{
"docstring": "Update song vote",
"name": "patch",
"signature": "def patch(request, song_vote_id)"
},
{
"docstring": "Delete song vote",
"name": "delete",
"signature": "def delete(request, song_vote_id)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004372 | Implement the Python class `SongVoteDetail` described below.
Class description:
Implement the SongVoteDetail class.
Method signatures and docstrings:
- def patch(request, song_vote_id): Update song vote
- def delete(request, song_vote_id): Delete song vote | Implement the Python class `SongVoteDetail` described below.
Class description:
Implement the SongVoteDetail class.
Method signatures and docstrings:
- def patch(request, song_vote_id): Update song vote
- def delete(request, song_vote_id): Delete song vote
<|skeleton|>
class SongVoteDetail:
def patch(request, s... | b93fa2fea8d45df9f19c3c58037e59dad4981921 | <|skeleton|>
class SongVoteDetail:
def patch(request, song_vote_id):
"""Update song vote"""
<|body_0|>
def delete(request, song_vote_id):
"""Delete song vote"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SongVoteDetail:
def patch(request, song_vote_id):
"""Update song vote"""
song_vote = get_object_or_404(SongVote, pk=song_vote_id)
serializer = SongVoteSerializerUpdate(song_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_valid():
... | the_stack_v2_python_sparse | v1/votes/views/song_vote.py | lawiz22/PLOUC-Backend-master | train | 0 | |
4b4163e1eca0a5a521cd743c8ecbe6d1c932fdd9 | [
"self.vartypes = vartypes\nself.kertypes = dict(c=config.conti_kertype, o=config.ordered_kertype, u=config.unordered_kertype)\nself.bw_methods = dict(c=config.conti_bw_method, o=config.ordered_bw_method, u=config.unordered_bw_method)\nself.conti_bw_temperature = config.conti_bw_temperature\nself._fit(data_ref)",
... | <|body_start_0|>
self.vartypes = vartypes
self.kertypes = dict(c=config.conti_kertype, o=config.ordered_kertype, u=config.unordered_kertype)
self.bw_methods = dict(c=config.conti_bw_method, o=config.ordered_bw_method, u=config.unordered_bw_method)
self.conti_bw_temperature = config.conti... | Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html | VanillaProductKernel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VanillaProductKernel:
"""Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html"""
def __init__(self, data_ref: np.ndarray, vartypes: str, config: VanillaProductKernelConf... | stack_v2_sparse_classes_36k_train_004580 | 9,714 | permissive | [
{
"docstring": "Constructor. Parameters: data_ref : Reference data points for which the kernel values are computed. vartypes : The variable type ('c': continuous, 'o': ordered, 'u': unordered). Example: ``'ccou'``. product_kernel_config : the configuration object.",
"name": "__init__",
"signature": "def... | 3 | stack_v2_sparse_classes_30k_train_009033 | Implement the Python class `VanillaProductKernel` described below.
Class description:
Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html
Method signatures and docstrings:
- def __init__(self, d... | Implement the Python class `VanillaProductKernel` described below.
Class description:
Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html
Method signatures and docstrings:
- def __init__(self, d... | 11eb7b4bb9c39672ece6177e321f63ce205e0307 | <|skeleton|>
class VanillaProductKernel:
"""Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html"""
def __init__(self, data_ref: np.ndarray, vartypes: str, config: VanillaProductKernelConf... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class VanillaProductKernel:
"""Product kernel object. Notes: Bandwidth methods: ``statsmodels.nonparametric.bandwidths``: https://www.statsmodels.org/devel/_modules/statsmodels/nonparametric/bandwidths.html"""
def __init__(self, data_ref: np.ndarray, vartypes: str, config: VanillaProductKernelConfig=VanillaPro... | the_stack_v2_python_sparse | causal_data_augmentation/causal_data_augmentation/augmenter/admg_tian_augmenter/util/weight_computer/kernel_fn/vanilla.py | diadochos/incorporating-causal-graphical-prior-knowledge-into-predictive-modeling-via-simple-data-augmentation | train | 0 |
a314e9d42e749bc9a4413b8e445c96c4ab1a3ace | [
"super(InTimeToArrivalToLocation, self).__init__(name)\nself.logger.debug('%s.__init__()' % self.__class__.__name__)\nself._actor = actor\nself._time = time\nself._target_location = location",
"new_status = py_trees.common.Status.RUNNING\ncurrent_location = CarlaDataProvider.get_location(self._actor)\nif current_... | <|body_start_0|>
super(InTimeToArrivalToLocation, self).__init__(name)
self.logger.debug('%s.__init__()' % self.__class__.__name__)
self._actor = actor
self._time = time
self._target_location = location
<|end_body_0|>
<|body_start_1|>
new_status = py_trees.common.Status.... | This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - location: Location to be checked in this behavior The condi... | InTimeToArrivalToLocation | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - locati... | stack_v2_sparse_classes_36k_train_004581 | 18,494 | permissive | [
{
"docstring": "Setup parameters",
"name": "__init__",
"signature": "def __init__(self, actor, time, location, name='TimeToArrival')"
},
{
"docstring": "Check if the actor can arrive at target_location within time",
"name": "update",
"signature": "def update(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_007348 | Implement the Python class `InTimeToArrivalToLocation` described below.
Class description:
This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA ... | Implement the Python class `InTimeToArrivalToLocation` described below.
Class description:
This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA ... | 8ab0894b92e1f994802a218002021ee075c405bf | <|skeleton|>
class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - locati... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class InTimeToArrivalToLocation:
"""This class contains a check if a actor arrives within a given time at a given location. Important parameters: - actor: CARLA actor to execute the behavior - name: Name of the condition - time: The behavior is successful, if TTA is less than _time_ in seconds - location: Location ... | the_stack_v2_python_sparse | carla_rllib/carla_rllib-prak_evaluator-carla_rllib-prak_evaluator/carla_rllib/prak_evaluator/srunner/scenarioconfigs/scenariomanager/scenarioatomics/atomic_trigger_conditions.py | TinaMenke/Deep-Reinforcement-Learning | train | 9 |
43debd58cd0ea6ce7012740db86698eda79cfb55 | [
"if self.domain and self.suffix:\n return self.domain + '.' + self.suffix\nreturn ''",
"if self.domain and self.suffix:\n return '.'.join((i for i in self if i))\nreturn ''",
"if not (self.suffix or self.subdomain) and IP_RE.match(self.domain):\n return self.domain\nreturn ''"
] | <|body_start_0|>
if self.domain and self.suffix:
return self.domain + '.' + self.suffix
return ''
<|end_body_0|>
<|body_start_1|>
if self.domain and self.suffix:
return '.'.join((i for i in self if i))
return ''
<|end_body_1|>
<|body_start_2|>
if not (se... | namedtuple of a URL's subdomain, domain, and suffix. | ExtractResult | [
"GPL-3.0-only",
"Python-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ExtractResult:
"""namedtuple of a URL's subdomain, domain, and suffix."""
def registered_domain(self):
"""Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_domain 'bbc.co.uk' >>> extract('http://localhost:8080').regi... | stack_v2_sparse_classes_36k_train_004582 | 7,568 | permissive | [
{
"docstring": "Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_domain 'bbc.co.uk' >>> extract('http://localhost:8080').registered_domain ''",
"name": "registered_domain",
"signature": "def registered_domain(self)"
},
{
"docst... | 3 | stack_v2_sparse_classes_30k_test_000131 | Implement the Python class `ExtractResult` described below.
Class description:
namedtuple of a URL's subdomain, domain, and suffix.
Method signatures and docstrings:
- def registered_domain(self): Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_dom... | Implement the Python class `ExtractResult` described below.
Class description:
namedtuple of a URL's subdomain, domain, and suffix.
Method signatures and docstrings:
- def registered_domain(self): Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_dom... | b6edb06fc4e53a90c756459d7c03f8b33692b42b | <|skeleton|>
class ExtractResult:
"""namedtuple of a URL's subdomain, domain, and suffix."""
def registered_domain(self):
"""Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_domain 'bbc.co.uk' >>> extract('http://localhost:8080').regi... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ExtractResult:
"""namedtuple of a URL's subdomain, domain, and suffix."""
def registered_domain(self):
"""Joins the domain and suffix fields with a dot, if they're both set. >>> extract('http://forums.bbc.co.uk').registered_domain 'bbc.co.uk' >>> extract('http://localhost:8080').registered_domain... | the_stack_v2_python_sparse | python/app/thirdparty/oneforall/common/tldextract.py | taomujian/linbing | train | 545 |
aaff995ffa4966888ef6a26f9bd5a84e65e7fd97 | [
"super().__init__(event)\nself.user = IDNamePair(event['user_id'], event['user_name'])\nself.channel = IDNamePair(event['channel_id'], event['channel_name'])\nself.team = IDNamePair(event['team_id'], event['team_domain'])\nself.trigger_id = event['trigger_id']\nself.command = event['command']\nself.text = event['te... | <|body_start_0|>
super().__init__(event)
self.user = IDNamePair(event['user_id'], event['user_name'])
self.channel = IDNamePair(event['channel_id'], event['channel_name'])
self.team = IDNamePair(event['team_id'], event['team_domain'])
self.trigger_id = event['trigger_id']
... | SlashCommandInteractiveEvent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SlashCommandInteractiveEvent:
def __init__(self, event: dict):
"""Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary"""
<|body_0|>
def create_reply(message, ephemeral=False) -> dict:
"""Create a reply suitable... | stack_v2_sparse_classes_36k_train_004583 | 4,539 | permissive | [
{
"docstring": "Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary",
"name": "__init__",
"signature": "def __init__(self, event: dict)"
},
{
"docstring": "Create a reply suitable to send directly back to the invoking HTTP request Args: me... | 2 | stack_v2_sparse_classes_30k_train_014911 | Implement the Python class `SlashCommandInteractiveEvent` described below.
Class description:
Implement the SlashCommandInteractiveEvent class.
Method signatures and docstrings:
- def __init__(self, event: dict): Convenience class to parse a slash command payload from the events API Args: event: the raw event diction... | Implement the Python class `SlashCommandInteractiveEvent` described below.
Class description:
Implement the SlashCommandInteractiveEvent class.
Method signatures and docstrings:
- def __init__(self, event: dict): Convenience class to parse a slash command payload from the events API Args: event: the raw event diction... | 4b026da33695b25033c7667679f3cf552c4bf3b5 | <|skeleton|>
class SlashCommandInteractiveEvent:
def __init__(self, event: dict):
"""Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary"""
<|body_0|>
def create_reply(message, ephemeral=False) -> dict:
"""Create a reply suitable... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SlashCommandInteractiveEvent:
def __init__(self, event: dict):
"""Convenience class to parse a slash command payload from the events API Args: event: the raw event dictionary"""
super().__init__(event)
self.user = IDNamePair(event['user_id'], event['user_name'])
self.channel = ... | the_stack_v2_python_sparse | terraform/stacks/bot/lambdas/python/slack_automation_bot/slack/web/classes/interactions.py | cloud-sniper/cloud-sniper | train | 184 | |
9f72e88cdefabc290adf054b3e0f3888329ee8c0 | [
"self.action_dim = action_dim_\nself.active_as_idx = active_as_idx_\nself.weights = weights_\nself.logger = logger_\nself.init_action = np.zeros(self.action_dim)\nself.init_action[self.active_as_idx] = self.weights[::-1]\nif active_:\n self.get_action = self.get_action_active\nelse:\n self.get_action = self.a... | <|body_start_0|>
self.action_dim = action_dim_
self.active_as_idx = active_as_idx_
self.weights = weights_
self.logger = logger_
self.init_action = np.zeros(self.action_dim)
self.init_action[self.active_as_idx] = self.weights[::-1]
if active_:
self.get... | @brief: WCMP mechanism | Weighted | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Weighted:
"""@brief: WCMP mechanism"""
def __init__(self, active_as_idx_, weights_, action_dim_, active_=False, logger_=None):
"""@brief: This class generate actions (weights) based on features gathered by reservoir sampling @param: feature_name: the feature name that we use to calcu... | stack_v2_sparse_classes_36k_train_004584 | 5,229 | permissive | [
{
"docstring": "@brief: This class generate actions (weights) based on features gathered by reservoir sampling @param: feature_name: the feature name that we use to calculate weights (choose amongst sm.FEATURE_AS_ALL) map_func: map function e.g. reciprocal or negative alpha: parameter for soft weights update lo... | 3 | stack_v2_sparse_classes_30k_train_014521 | Implement the Python class `Weighted` described below.
Class description:
@brief: WCMP mechanism
Method signatures and docstrings:
- def __init__(self, active_as_idx_, weights_, action_dim_, active_=False, logger_=None): @brief: This class generate actions (weights) based on features gathered by reservoir sampling @p... | Implement the Python class `Weighted` described below.
Class description:
@brief: WCMP mechanism
Method signatures and docstrings:
- def __init__(self, active_as_idx_, weights_, action_dim_, active_=False, logger_=None): @brief: This class generate actions (weights) based on features gathered by reservoir sampling @p... | df5f7c890b09defb88bdb71ccb653033a7ce97dd | <|skeleton|>
class Weighted:
"""@brief: WCMP mechanism"""
def __init__(self, active_as_idx_, weights_, action_dim_, active_=False, logger_=None):
"""@brief: This class generate actions (weights) based on features gathered by reservoir sampling @param: feature_name: the feature name that we use to calcu... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Weighted:
"""@brief: WCMP mechanism"""
def __init__(self, active_as_idx_, weights_, action_dim_, active_=False, logger_=None):
"""@brief: This class generate actions (weights) based on features gathered by reservoir sampling @param: feature_name: the feature name that we use to calculate weights ... | the_stack_v2_python_sparse | src/lb/wcmp.py | ZhiyuanYaoJ/Aquarius | train | 0 |
e71cfa4eb58e07d16d27a714b41879b1c0d02cf6 | [
"fast = self.helper(self.helper(n))\nslow = self.helper(n)\nwhile slow != fast:\n fast = self.helper(self.helper(fast))\n slow = self.helper(slow)\nreturn slow == 1",
"res = 0\nwhile n:\n res += (n % 10) ** 2\n n //= 10\nreturn res"
] | <|body_start_0|>
fast = self.helper(self.helper(n))
slow = self.helper(n)
while slow != fast:
fast = self.helper(self.helper(fast))
slow = self.helper(slow)
return slow == 1
<|end_body_0|>
<|body_start_1|>
res = 0
while n:
res += (n % ... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
<|body_0|>
def helper(self, n):
"""Args: n: int Return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
fast = self.helper(self.helper(n))
slow = self.helper(n)
whil... | stack_v2_sparse_classes_36k_train_004585 | 1,351 | no_license | [
{
"docstring": "Args: n: int Return: bool",
"name": "isHappy",
"signature": "def isHappy(self, n)"
},
{
"docstring": "Args: n: int Return: int",
"name": "helper",
"signature": "def helper(self, n)"
}
] | 2 | stack_v2_sparse_classes_30k_train_016346 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): Args: n: int Return: bool
- def helper(self, n): Args: n: int Return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isHappy(self, n): Args: n: int Return: bool
- def helper(self, n): Args: n: int Return: int
<|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int R... | 101bce2fac8b188a4eb2f5e017293d21ad0ecb21 | <|skeleton|>
class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
<|body_0|>
def helper(self, n):
"""Args: n: int Return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def isHappy(self, n):
"""Args: n: int Return: bool"""
fast = self.helper(self.helper(n))
slow = self.helper(n)
while slow != fast:
fast = self.helper(self.helper(fast))
slow = self.helper(slow)
return slow == 1
def helper(self, n):... | the_stack_v2_python_sparse | code/202. 快乐数.py | AiZhanghan/Leetcode | train | 0 | |
4f7a8b5187514bd123d4c09e9b2e17c8487f6ae1 | [
"self.issue = issue\nself.expire = expire\nself.day = day\nself.outlooks = []",
"if not self.outlooks or outlook.level is None:\n self.outlooks.append(outlook)\n return\nif self.outlooks[-1].level is not None and outlook.level > self.outlooks[-1].level:\n self.outlooks.append(outlook)\n return\nfor id... | <|body_start_0|>
self.issue = issue
self.expire = expire
self.day = day
self.outlooks = []
<|end_body_0|>
<|body_start_1|>
if not self.outlooks or outlook.level is None:
self.outlooks.append(outlook)
return
if self.outlooks[-1].level is not None a... | A collection of outlooks for a single 'day' | SPCOutlookCollection | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SPCOutlookCollection:
"""A collection of outlooks for a single 'day'"""
def __init__(self, issue, expire, day):
"""Constructor"""
<|body_0|>
def add_outlook(self, outlook):
"""We insert an outlook in an ordered manner."""
<|body_1|>
def get_categorie... | stack_v2_sparse_classes_36k_train_004586 | 24,645 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, issue, expire, day)"
},
{
"docstring": "We insert an outlook in an ordered manner.",
"name": "add_outlook",
"signature": "def add_outlook(self, outlook)"
},
{
"docstring": "Return list of categorie... | 4 | null | Implement the Python class `SPCOutlookCollection` described below.
Class description:
A collection of outlooks for a single 'day'
Method signatures and docstrings:
- def __init__(self, issue, expire, day): Constructor
- def add_outlook(self, outlook): We insert an outlook in an ordered manner.
- def get_categories(se... | Implement the Python class `SPCOutlookCollection` described below.
Class description:
A collection of outlooks for a single 'day'
Method signatures and docstrings:
- def __init__(self, issue, expire, day): Constructor
- def add_outlook(self, outlook): We insert an outlook in an ordered manner.
- def get_categories(se... | 460f44394be05e1b655111595a3d7de3f7e47757 | <|skeleton|>
class SPCOutlookCollection:
"""A collection of outlooks for a single 'day'"""
def __init__(self, issue, expire, day):
"""Constructor"""
<|body_0|>
def add_outlook(self, outlook):
"""We insert an outlook in an ordered manner."""
<|body_1|>
def get_categorie... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SPCOutlookCollection:
"""A collection of outlooks for a single 'day'"""
def __init__(self, issue, expire, day):
"""Constructor"""
self.issue = issue
self.expire = expire
self.day = day
self.outlooks = []
def add_outlook(self, outlook):
"""We insert an ... | the_stack_v2_python_sparse | src/pyiem/nws/products/spcpts.py | akrherz/pyIEM | train | 38 |
1f5d64b7205ee9cc053295eba3336519b435210f | [
"try:\n cls = self.visitor.builder.current.contents[node.name]\nexcept KeyError:\n return\nassert isinstance(cls, model.Class)\ngetDeprecated(cls, node.decorator_list)",
"try:\n func = self.visitor.builder.current.contents[node.name]\nexcept KeyError:\n return\nassert isinstance(func, (model.Function,... | <|body_start_0|>
try:
cls = self.visitor.builder.current.contents[node.name]
except KeyError:
return
assert isinstance(cls, model.Class)
getDeprecated(cls, node.decorator_list)
<|end_body_0|>
<|body_start_1|>
try:
func = self.visitor.builder.c... | ModuleVisitor | [
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-other-permissive"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleVisitor:
def depart_ClassDef(self, node: ast.ClassDef) -> None:
"""Called after a class definition is visited."""
<|body_0|>
def depart_FunctionDef(self, node: ast.FunctionDef) -> None:
"""Called after a function definition is visited."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k_train_004587 | 6,998 | permissive | [
{
"docstring": "Called after a class definition is visited.",
"name": "depart_ClassDef",
"signature": "def depart_ClassDef(self, node: ast.ClassDef) -> None"
},
{
"docstring": "Called after a function definition is visited.",
"name": "depart_FunctionDef",
"signature": "def depart_Functio... | 2 | stack_v2_sparse_classes_30k_val_000634 | Implement the Python class `ModuleVisitor` described below.
Class description:
Implement the ModuleVisitor class.
Method signatures and docstrings:
- def depart_ClassDef(self, node: ast.ClassDef) -> None: Called after a class definition is visited.
- def depart_FunctionDef(self, node: ast.FunctionDef) -> None: Called... | Implement the Python class `ModuleVisitor` described below.
Class description:
Implement the ModuleVisitor class.
Method signatures and docstrings:
- def depart_ClassDef(self, node: ast.ClassDef) -> None: Called after a class definition is visited.
- def depart_FunctionDef(self, node: ast.FunctionDef) -> None: Called... | 965ed955efde6178cb68f0882a02c34a90204447 | <|skeleton|>
class ModuleVisitor:
def depart_ClassDef(self, node: ast.ClassDef) -> None:
"""Called after a class definition is visited."""
<|body_0|>
def depart_FunctionDef(self, node: ast.FunctionDef) -> None:
"""Called after a function definition is visited."""
<|body_1|>
<|... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ModuleVisitor:
def depart_ClassDef(self, node: ast.ClassDef) -> None:
"""Called after a class definition is visited."""
try:
cls = self.visitor.builder.current.contents[node.name]
except KeyError:
return
assert isinstance(cls, model.Class)
getDep... | the_stack_v2_python_sparse | pydoctor/extensions/deprecate.py | twisted/pydoctor | train | 149 | |
e1735026bbc5fd6e4f2be9efeefb13d4913c6494 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"w = self.W(s_prev)\nu = self.U(hidden_states)\nw = tf.expand_dims(w, axis=1)\ne = self.V(tf.nn.tanh(w + u))\nattention = tf.nn.softmax(e, axis=1)\nc = tf.reduc... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
w = self.W(s_prev)
u = self.U(hidden_states)
w = tf.expand_dims(w,... | SelfAttention part of the translation model | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""SelfAttention part of the translation model"""
def __init__(self, units):
"""initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer with units units, to be applied to the previous decoder h... | stack_v2_sparse_classes_36k_train_004588 | 1,875 | no_license | [
{
"docstring": "initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer with units units, to be applied to the previous decoder hidden state - U: Dense layer with units units, to be applied to the encoder hidden states - V: Dense layer ... | 2 | stack_v2_sparse_classes_30k_train_015728 | Implement the Python class `SelfAttention` described below.
Class description:
SelfAttention part of the translation model
Method signatures and docstrings:
- def __init__(self, units): initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer ... | Implement the Python class `SelfAttention` described below.
Class description:
SelfAttention part of the translation model
Method signatures and docstrings:
- def __init__(self, units): initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer ... | 1d86c9606371697854878b833b810d73c9af7ee7 | <|skeleton|>
class SelfAttention:
"""SelfAttention part of the translation model"""
def __init__(self, units):
"""initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer with units units, to be applied to the previous decoder h... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SelfAttention:
"""SelfAttention part of the translation model"""
def __init__(self, units):
"""initialized the variables Arg: - units: int the number of hidden units in the RNN cell Public instance attributes: - W: Dense layer with units units, to be applied to the previous decoder hidden state -... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | macoyulloa/holbertonschool-machine_learning | train | 0 |
b5a33f6450019fff4535086ce66fb17a23707776 | [
"context = context or {}\nids = isinstance(ids, (int, long)) and [ids] or ids\ncr_date = time.strftime('%Y-%m-%d')\nsp_brw = self.browse(cur, uid, ids[0], context=context)\nif not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_contract_expiry) or context.get('force_expiry_pic... | <|body_start_0|>
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.strftime('%Y-%m-%d')
sp_brw = self.browse(cur, uid, ids[0], context=context)
if not sp_brw.date_contract_expiry or (sp_brw.date_contract_expiry and cr_date <= sp_brw.date_c... | StockPicking | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StockPicking:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy the da... | stack_v2_sparse_classes_36k_train_004589 | 5,912 | no_license | [
{
"docstring": "overwrite the method to add a verification of the contract due date before process the stock picking.",
"name": "action_process",
"signature": "def action_process(self, cur, uid, ids, context=None)"
},
{
"docstring": "Ovwerwrite the copy method to also copy the date_contract_expi... | 2 | null | Implement the Python class `StockPicking` described below.
Class description:
Implement the StockPicking class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking.
- def copy(se... | Implement the Python class `StockPicking` described below.
Class description:
Implement the StockPicking class.
Method signatures and docstrings:
- def action_process(self, cur, uid, ids, context=None): overwrite the method to add a verification of the contract due date before process the stock picking.
- def copy(se... | 511dc410b4eba1f8ea939c6af02a5adea5122c92 | <|skeleton|>
class StockPicking:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking."""
<|body_0|>
def copy(self, default=None):
"""Ovwerwrite the copy method to also copy the da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StockPicking:
def action_process(self, cur, uid, ids, context=None):
"""overwrite the method to add a verification of the contract due date before process the stock picking."""
context = context or {}
ids = isinstance(ids, (int, long)) and [ids] or ids
cr_date = time.strftime('... | the_stack_v2_python_sparse | stock_purchase_expiry/model/stock.py | yelizariev/addons-vauxoo | train | 3 | |
c97e40fa3f228c914cc5a5ba9ca5208279559bcb | [
"instance_type = ContentType.objects.get_for_model(instance)\ndocument = prov.model.ProvDocument(namespaces={'piot': 'http://www.pedasi-iot.org/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'xsd': 'http://www.w3.org/2001/XMLSchema#'})\nentity = document.entity('piot:e-' + slugify(instance_type.model) + str(instance.pk),... | <|body_start_0|>
instance_type = ContentType.objects.get_for_model(instance)
document = prov.model.ProvDocument(namespaces={'piot': 'http://www.pedasi-iot.org/', 'foaf': 'http://xmlns.com/foaf/0.1/', 'xsd': 'http://www.w3.org/2001/XMLSchema#'})
entity = document.entity('piot:e-' + slugify(instan... | Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document. | ProvEntry | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activit... | stack_v2_sparse_classes_36k_train_004590 | 10,004 | permissive | [
{
"docstring": "Build a PROV document representing a particular activity within PEDASI. :param instance: Application or DataSource which is the object of the activity :param user_uri: URI of user who performed the activity :param application: Application which the user used to perform the activity :param activi... | 2 | null | Implement the Python class `ProvEntry` described below.
Class description:
Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document.
Method signatures and docstrings:
- def create_prov(cls, instance: BaseAppDataModel, user_uri: s... | Implement the Python class `ProvEntry` described below.
Class description:
Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document.
Method signatures and docstrings:
- def create_prov(cls, instance: BaseAppDataModel, user_uri: s... | 25a111ac7cf4b23fee50ad8eac6ea21564954859 | <|skeleton|>
class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activit... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProvEntry:
"""Stored PROV record for a single action. e.g. Update a model's metadata, use a model. These will be referred to by a :class:`ProvWrapper` document."""
def create_prov(cls, instance: BaseAppDataModel, user_uri: str, application: typing.Optional[ProvApplicationModel]=None, activity_type: typin... | the_stack_v2_python_sparse | provenance/models.py | PEDASI/PEDASI | train | 0 |
ede9c63961b57ffeb799529acf0a31289c35348a | [
"def sort_key(aggregated_activity):\n aggregated_activity_ids = [a.object_id for a in aggregated_activity.activities]\n return max(aggregated_activity_ids)\naggregated_activities.sort(key=sort_key)\nreturn aggregated_activities",
"verb = activity.verb.id\ndate = activity.time.date()\ngroup = '%s-%s' % (verb... | <|body_start_0|>
def sort_key(aggregated_activity):
aggregated_activity_ids = [a.object_id for a in aggregated_activity.activities]
return max(aggregated_activity_ids)
aggregated_activities.sort(key=sort_key)
return aggregated_activities
<|end_body_0|>
<|body_start_1|>
... | Aggregates based on the same verb and same time period | RecentVerbAggregator | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RecentVerbAggregator:
"""Aggregates based on the same verb and same time period"""
def rank(self, aggregated_activities):
"""The ranking logic, for sorting aggregated activities"""
<|body_0|>
def get_group(self, activity):
"""Returns a group based on the day and ... | stack_v2_sparse_classes_36k_train_004591 | 3,581 | permissive | [
{
"docstring": "The ranking logic, for sorting aggregated activities",
"name": "rank",
"signature": "def rank(self, aggregated_activities)"
},
{
"docstring": "Returns a group based on the day and verb",
"name": "get_group",
"signature": "def get_group(self, activity)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000420 | Implement the Python class `RecentVerbAggregator` described below.
Class description:
Aggregates based on the same verb and same time period
Method signatures and docstrings:
- def rank(self, aggregated_activities): The ranking logic, for sorting aggregated activities
- def get_group(self, activity): Returns a group ... | Implement the Python class `RecentVerbAggregator` described below.
Class description:
Aggregates based on the same verb and same time period
Method signatures and docstrings:
- def rank(self, aggregated_activities): The ranking logic, for sorting aggregated activities
- def get_group(self, activity): Returns a group ... | f3824b95cefc360ebbfc2d2166b53a5505f49fbc | <|skeleton|>
class RecentVerbAggregator:
"""Aggregates based on the same verb and same time period"""
def rank(self, aggregated_activities):
"""The ranking logic, for sorting aggregated activities"""
<|body_0|>
def get_group(self, activity):
"""Returns a group based on the day and ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RecentVerbAggregator:
"""Aggregates based on the same verb and same time period"""
def rank(self, aggregated_activities):
"""The ranking logic, for sorting aggregated activities"""
def sort_key(aggregated_activity):
aggregated_activity_ids = [a.object_id for a in aggregated_ac... | the_stack_v2_python_sparse | feedly/aggregators/base.py | atefzed/Feedly | train | 0 |
fddfd490915390b073799abc5ff476de86978f4a | [
"if self.context.digitally_available:\n manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)\n if manager:\n return manager.is_checkout_allowed()\nreturn False",
"manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)\nif manager:\n return ... | <|body_start_0|>
if self.context.digitally_available:
manager = queryMultiAdapter((self.context, self.request), ICheckinCheckoutManager)
if manager:
return manager.is_checkout_allowed()
return False
<|end_body_0|>
<|body_start_1|>
manager = queryMultiAdap... | The controller view gives infos about the current document concerning checkin / checkout. | CheckinCheckoutController | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
<|body_0|>
def is_checkin_allowed(self):
"""Checks whether c... | stack_v2_sparse_classes_36k_train_004592 | 1,632 | no_license | [
{
"docstring": "Checks whether checkout is allowed or not.",
"name": "is_checkout_allowed",
"signature": "def is_checkout_allowed(self)"
},
{
"docstring": "Checks whether checkin is allowed or not.",
"name": "is_checkin_allowed",
"signature": "def is_checkin_allowed(self)"
},
{
"... | 4 | null | Implement the Python class `CheckinCheckoutController` described below.
Class description:
The controller view gives infos about the current document concerning checkin / checkout.
Method signatures and docstrings:
- def is_checkout_allowed(self): Checks whether checkout is allowed or not.
- def is_checkin_allowed(se... | Implement the Python class `CheckinCheckoutController` described below.
Class description:
The controller view gives infos about the current document concerning checkin / checkout.
Method signatures and docstrings:
- def is_checkout_allowed(self): Checks whether checkout is allowed or not.
- def is_checkin_allowed(se... | a01bec6c00d203c21a1b0449f8d489d0033c02b7 | <|skeleton|>
class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
<|body_0|>
def is_checkin_allowed(self):
"""Checks whether c... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CheckinCheckoutController:
"""The controller view gives infos about the current document concerning checkin / checkout."""
def is_checkout_allowed(self):
"""Checks whether checkout is allowed or not."""
if self.context.digitally_available:
manager = queryMultiAdapter((self.con... | the_stack_v2_python_sparse | opengever/document/checkout/controller.py | 4teamwork/opengever.core | train | 19 |
5d34bd06a6c6d25ddb1504b9a11774fa159c88f1 | [
"super(DiffSmoothedCELoss, self).__init__(**kw)\nself.reduction, self.ignore_indices = (reduction, ignore_index)\nself.mode = mode\nself.alpha, self.beta = (alpha, beta)\nself.kl = torch.nn.KLDivLoss(reduction='none')\nself.logsm = torch.nn.LogSoftmax(-1) if self.mode == 'logits' else None\nself.sm = torch.nn.Softm... | <|body_start_0|>
super(DiffSmoothedCELoss, self).__init__(**kw)
self.reduction, self.ignore_indices = (reduction, ignore_index)
self.mode = mode
self.alpha, self.beta = (alpha, beta)
self.kl = torch.nn.KLDivLoss(reduction='none')
self.logsm = torch.nn.LogSoftmax(-1) if se... | DiffSmoothedCELoss | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform... | stack_v2_sparse_classes_36k_train_004593 | 20,169 | permissive | [
{
"docstring": ":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform distribution when mixing target for incorrectly predicted tokens (normal label smoothing) :param mode: :param kw:",
"name": "... | 2 | stack_v2_sparse_classes_30k_test_000390 | Implement the Python class `DiffSmoothedCELoss` described below.
Class description:
Implement the DiffSmoothedCELoss class.
Method signatures and docstrings:
- def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw): :param reduction: :param ignore_index: :param alpha: weight... | Implement the Python class `DiffSmoothedCELoss` described below.
Class description:
Implement the DiffSmoothedCELoss class.
Method signatures and docstrings:
- def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw): :param reduction: :param ignore_index: :param alpha: weight... | 8cf2e697830ef09dca40692e7d254b61f9ffdf8d | <|skeleton|>
class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DiffSmoothedCELoss:
def __init__(self, reduction='mean', ignore_index=-100, alpha=0.7, beta=0.2, mode='logits', **kw):
""":param reduction: :param ignore_index: :param alpha: weight of predicted distribution when mixing target for correctly predicted tokens :param beta: weight of uniform distribution ... | the_stack_v2_python_sparse | kbcqa/method_ir/grounding/semantic_matching/qelos/loss.py | BayLee001/SkeletonKBQA | train | 0 | |
417b9b528c2094cfe363a25775d3a80970f89dbf | [
"nums.sort()\nresults = []\nself.findNsum(nums, target, 4, [], results)\nreturn results",
"if len(nums) < N or N < 2:\n return\nif N == 2:\n l, r = (0, len(nums) - 1)\n while l < r:\n if nums[l] + nums[r] == target:\n results.append(result + [nums[l], nums[r]])\n l += 1\n ... | <|body_start_0|>
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
<|end_body_0|>
<|body_start_1|>
if len(nums) < N or N < 2:
return
if N == 2:
l, r = (0, len(nums) - 1)
while l < r:
if... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def findNsum(self, nums, target, N, result, results):
"""nums is a sorted arr"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004594 | 2,791 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: List[List[int]]",
"name": "fourSum",
"signature": "def fourSum(self, nums, target)"
},
{
"docstring": "nums is a sorted arr",
"name": "findNsum",
"signature": "def findNsum(self, nums, target, N, result, results)"
}
] | 2 | stack_v2_sparse_classes_30k_train_010160 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def findNsum(self, nums, target, N, result, results): nums is a sorted arr | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def fourSum(self, nums, target): :type nums: List[int] :type target: int :rtype: List[List[int]]
- def findNsum(self, nums, target, N, result, results): nums is a sorted arr
<|s... | 801beb43235872b2419a92b11c4eb05f7ea2adab | <|skeleton|>
class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
<|body_0|>
def findNsum(self, nums, target, N, result, results):
"""nums is a sorted arr"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def fourSum(self, nums, target):
""":type nums: List[int] :type target: int :rtype: List[List[int]]"""
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results
def findNsum(self, nums, target, N, result, results):
"""num... | the_stack_v2_python_sparse | Python/018__4Sum.py | FIRESTROM/Leetcode | train | 2 | |
1f98ad9d262a5d9ad2fd1f24d6e3e82f65ca0dc5 | [
"self._colors = list(map(mcolors.to_rgba, colors))\nself._segment_colors = [(self._colors[0], self._colors[0]), (self._colors[0], self._colors[1]), (self._colors[1], self._colors[1]), (self._colors[1], self._colors[0])]\nsuper().__init__(color=self._colors[0], **kwargs)",
"gcs = [self._override_gc(renderer, gc, f... | <|body_start_0|>
self._colors = list(map(mcolors.to_rgba, colors))
self._segment_colors = [(self._colors[0], self._colors[0]), (self._colors[0], self._colors[1]), (self._colors[1], self._colors[1]), (self._colors[1], self._colors[0])]
super().__init__(color=self._colors[0], **kwargs)
<|end_body_... | Draw a weakening stationary front.. | StationaryFrontolysis | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StationaryFrontolysis:
"""Draw a weakening stationary front.."""
def __init__(self, colors=('red', 'blue'), **kwargs):
"""Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold front symbol. Parameters ---------- colors : Sequence[st... | stack_v2_sparse_classes_36k_train_004595 | 43,343 | permissive | [
{
"docstring": "Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold front symbol. Parameters ---------- colors : Sequence[str] or Sequence[tuple[float]] Matplotlib color identifiers to cycle between on the two different front styles. Defaults to alternating ... | 2 | stack_v2_sparse_classes_30k_train_004865 | Implement the Python class `StationaryFrontolysis` described below.
Class description:
Draw a weakening stationary front..
Method signatures and docstrings:
- def __init__(self, colors=('red', 'blue'), **kwargs): Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold... | Implement the Python class `StationaryFrontolysis` described below.
Class description:
Draw a weakening stationary front..
Method signatures and docstrings:
- def __init__(self, colors=('red', 'blue'), **kwargs): Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold... | c7124e6f375eb5810ce49d53c9d5501c2efdfb75 | <|skeleton|>
class StationaryFrontolysis:
"""Draw a weakening stationary front.."""
def __init__(self, colors=('red', 'blue'), **kwargs):
"""Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold front symbol. Parameters ---------- colors : Sequence[st... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StationaryFrontolysis:
"""Draw a weakening stationary front.."""
def __init__(self, colors=('red', 'blue'), **kwargs):
"""Initialize a weakening stationary front path effect. This effect alternates between a warm front and cold front symbol. Parameters ---------- colors : Sequence[str] or Sequenc... | the_stack_v2_python_sparse | src/metpy/plots/patheffects.py | Unidata/MetPy | train | 1,041 |
4b39b8b4b0423f2f2323110d0c239d5dae00631f | [
"if channel_state == live_state:\n return True\nif channel_state in ['creating', 'recovering', 'updating', 'deleting']:\n return True\nif channel_state == IDLE and live_state in [STOPPED, IDLE]:\n return True\nreturn False",
"now = timezone.now()\nstamp = to_timestamp(now)\nlive_state = live.live_state\n... | <|body_start_0|>
if channel_state == live_state:
return True
if channel_state in ['creating', 'recovering', 'updating', 'deleting']:
return True
if channel_state == IDLE and live_state in [STOPPED, IDLE]:
return True
return False
<|end_body_0|>
<|body... | Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video states. This can let us with media channel "IDLE", while in our side, the vid... | Command | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Command:
"""Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video states. This can let us with media channel... | stack_v2_sparse_classes_36k_train_004596 | 4,478 | permissive | [
{
"docstring": "Check if channel state and video state are sync. Medialive channel states are not exactly 1-1 with video states: - Creating - Deleting - Idle -> IDLE - Recovering - Running -> RUNNING - Starting -> STARTING - Stopping -> STOPPING - Updating",
"name": "is_channel_sync_with_video",
"signat... | 3 | null | Implement the Python class `Command` described below.
Class description:
Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video sta... | Implement the Python class `Command` described below.
Class description:
Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video sta... | f767f1bdc12c9712f26ea17cb8b19f536389f0ed | <|skeleton|>
class Command:
"""Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video states. This can let us with media channel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Command:
"""Once a live started, video states becomes indirectly linked to medialive channel state. There is a risk that sometimes, states are not sync for an unknown reason, for example, the api was down when aws was calling our callback to update video states. This can let us with media channel "IDLE", whil... | the_stack_v2_python_sparse | src/backend/marsha/core/management/commands/sync_medialive_video.py | openfun/marsha | train | 92 |
71a020d9d757b3eb1849b22354a0ec5c2ef98d7b | [
"myserver = msw.MSWInfo('mymsw')\nvportObject = VportsResource('/tmp/')\nvportDict = vportObject.getSnapshot(ResourceTest.myserver)\nself.assertNotEqual(vportDict['avlbl vports'], None)\nself.assertNotEqual(vportDict['used vports'], None)\nself.assertNotEqual(vportDict['media avlbl vports'], None)\nself.assertNotEq... | <|body_start_0|>
myserver = msw.MSWInfo('mymsw')
vportObject = VportsResource('/tmp/')
vportDict = vportObject.getSnapshot(ResourceTest.myserver)
self.assertNotEqual(vportDict['avlbl vports'], None)
self.assertNotEqual(vportDict['used vports'], None)
self.assertNotEqual(v... | Unittest class for testing the main parts of resourcewatch.py code. | ResourceTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResourceTest:
"""Unittest class for testing the main parts of resourcewatch.py code."""
def testVports(self):
"""testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command"""
<|body_0|>
def testCallCache(self):
"""... | stack_v2_sparse_classes_36k_train_004597 | 13,834 | no_license | [
{
"docstring": "testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command",
"name": "testVports",
"signature": "def testVports(self)"
},
{
"docstring": "testCallCache tests the snapshot capability of CallcacheResource and the result format of the... | 2 | null | Implement the Python class `ResourceTest` described below.
Class description:
Unittest class for testing the main parts of resourcewatch.py code.
Method signatures and docstrings:
- def testVports(self): testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command
- def ... | Implement the Python class `ResourceTest` described below.
Class description:
Unittest class for testing the main parts of resourcewatch.py code.
Method signatures and docstrings:
- def testVports(self): testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command
- def ... | 9974760ae41ea26d4d8b6a483b246f09ae38298e | <|skeleton|>
class ResourceTest:
"""Unittest class for testing the main parts of resourcewatch.py code."""
def testVports(self):
"""testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command"""
<|body_0|>
def testCallCache(self):
"""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ResourceTest:
"""Unittest class for testing the main parts of resourcewatch.py code."""
def testVports(self):
"""testVports tests the snapshot capability of VportsResource and the result format of the 'cli lstat' command"""
myserver = msw.MSWInfo('mymsw')
vportObject = VportsResou... | the_stack_v2_python_sparse | Nextest_12.xOS-bkup_2_21/opt/nextest/lib/python-old/site-packages/resourcewatch.py | gvsurenderreddy/Automation | train | 0 |
0f151b71a7b8f9c3a278970d886a37ee2d5bfa21 | [
"base64_str = cv2.imencode('.jpg', mat_img)[1]\nbase64_code = base64.b64encode(base64_str)\nreturn str(base64_code, encoding='utf-8')",
"b64_data = base_img.split(',')[1]\nimg_string = base64.b64decode(b64_data)\nnp_arr = np.fromstring(img_string, np.uint8)\nimage = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)\nreturn ... | <|body_start_0|>
base64_str = cv2.imencode('.jpg', mat_img)[1]
base64_code = base64.b64encode(base64_str)
return str(base64_code, encoding='utf-8')
<|end_body_0|>
<|body_start_1|>
b64_data = base_img.split(',')[1]
img_string = base64.b64decode(b64_data)
np_arr = np.froms... | ImgConversion | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ImgConversion:
def cv2_base64(mat_img):
"""cv2格式=>base64格式=>str :param mat_img: :return:"""
<|body_0|>
def base64_cv2(base_img):
"""字符串=>base64=>cv2 :param base_img: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
base64_str = cv2.imencode(... | stack_v2_sparse_classes_36k_train_004598 | 884 | no_license | [
{
"docstring": "cv2格式=>base64格式=>str :param mat_img: :return:",
"name": "cv2_base64",
"signature": "def cv2_base64(mat_img)"
},
{
"docstring": "字符串=>base64=>cv2 :param base_img: :return:",
"name": "base64_cv2",
"signature": "def base64_cv2(base_img)"
}
] | 2 | stack_v2_sparse_classes_30k_val_000312 | Implement the Python class `ImgConversion` described below.
Class description:
Implement the ImgConversion class.
Method signatures and docstrings:
- def cv2_base64(mat_img): cv2格式=>base64格式=>str :param mat_img: :return:
- def base64_cv2(base_img): 字符串=>base64=>cv2 :param base_img: :return: | Implement the Python class `ImgConversion` described below.
Class description:
Implement the ImgConversion class.
Method signatures and docstrings:
- def cv2_base64(mat_img): cv2格式=>base64格式=>str :param mat_img: :return:
- def base64_cv2(base_img): 字符串=>base64=>cv2 :param base_img: :return:
<|skeleton|>
class ImgCon... | 8fcd4046bb2acbc3487d59106abb1a40a642cc1f | <|skeleton|>
class ImgConversion:
def cv2_base64(mat_img):
"""cv2格式=>base64格式=>str :param mat_img: :return:"""
<|body_0|>
def base64_cv2(base_img):
"""字符串=>base64=>cv2 :param base_img: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ImgConversion:
def cv2_base64(mat_img):
"""cv2格式=>base64格式=>str :param mat_img: :return:"""
base64_str = cv2.imencode('.jpg', mat_img)[1]
base64_code = base64.b64encode(base64_str)
return str(base64_code, encoding='utf-8')
def base64_cv2(base_img):
"""字符串=>base64=>... | the_stack_v2_python_sparse | common_module/base_tool/image_base64.py | zhangruipython/ai_platform | train | 5 | |
bfd1fb0d4fd65293c73bfa1179a27243f5dcd20e | [
"store = goldman.sess.store\nlogin = store.find(cls.RTYPE, 'username', username)\nif not login:\n msg = 'No login found by that username. Spelling error?'\n raise AuthRejected(**{'detail': msg})\nelif login.locked:\n msg = 'The login account is currently locked out.'\n raise AuthRejected(**{'detail': ms... | <|body_start_0|>
store = goldman.sess.store
login = store.find(cls.RTYPE, 'username', username)
if not login:
msg = 'No login found by that username. Spelling error?'
raise AuthRejected(**{'detail': msg})
elif login.locked:
msg = 'The login account is ... | Login model | Model | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Model:
"""Login model"""
def auth_creds(cls, username, password):
"""Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it. :return: string token"""
... | stack_v2_sparse_classes_36k_train_004599 | 4,962 | permissive | [
{
"docstring": "Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it. :return: string token",
"name": "auth_creds",
"signature": "def auth_creds(cls, username, password)"
... | 4 | stack_v2_sparse_classes_30k_train_005407 | Implement the Python class `Model` described below.
Class description:
Login model
Method signatures and docstrings:
- def auth_creds(cls, username, password): Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization m... | Implement the Python class `Model` described below.
Class description:
Login model
Method signatures and docstrings:
- def auth_creds(cls, username, password): Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization m... | b72540c9ad06b5c68aadb1b4fa8cb0b716260bf2 | <|skeleton|>
class Model:
"""Login model"""
def auth_creds(cls, username, password):
"""Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it. :return: string token"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Model:
"""Login model"""
def auth_creds(cls, username, password):
"""Validate a username & password A token is returned if auth is successful & can be used to authorize future requests or ignored entirely if the authorization mechanizm does not need it. :return: string token"""
store = go... | the_stack_v2_python_sparse | goldman/models/login.py | sassoo/goldman | train | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.