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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9a4e3f848a8b6fa38209956794891a2449367305 | [
"artist_vote = get_object_or_404(ArtistVote, pk=artist_vote_id)\nserializer = ArtistVoteSerializerUpdate(artist_vote, data=request.data, context={'request': request}, partial=True)\nif serializer.is_valid():\n serializer.save()\n return Response(ArtistVoteSerializer(serializer.instance).data)\nreturn Response... | <|body_start_0|>
artist_vote = get_object_or_404(ArtistVote, pk=artist_vote_id)
serializer = ArtistVoteSerializerUpdate(artist_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_valid():
serializer.save()
return Response(ArtistVoteSerial... | ArtistVoteDetail | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ArtistVoteDetail:
def patch(request, artist_vote_id):
"""Update artist vote"""
<|body_0|>
def delete(request, artist_vote_id):
"""Delete artist vote"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
artist_vote = get_object_or_404(ArtistVote, pk=artis... | stack_v2_sparse_classes_36k_train_004100 | 1,803 | permissive | [
{
"docstring": "Update artist vote",
"name": "patch",
"signature": "def patch(request, artist_vote_id)"
},
{
"docstring": "Delete artist vote",
"name": "delete",
"signature": "def delete(request, artist_vote_id)"
}
] | 2 | null | Implement the Python class `ArtistVoteDetail` described below.
Class description:
Implement the ArtistVoteDetail class.
Method signatures and docstrings:
- def patch(request, artist_vote_id): Update artist vote
- def delete(request, artist_vote_id): Delete artist vote | Implement the Python class `ArtistVoteDetail` described below.
Class description:
Implement the ArtistVoteDetail class.
Method signatures and docstrings:
- def patch(request, artist_vote_id): Update artist vote
- def delete(request, artist_vote_id): Delete artist vote
<|skeleton|>
class ArtistVoteDetail:
def pa... | b93fa2fea8d45df9f19c3c58037e59dad4981921 | <|skeleton|>
class ArtistVoteDetail:
def patch(request, artist_vote_id):
"""Update artist vote"""
<|body_0|>
def delete(request, artist_vote_id):
"""Delete artist vote"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ArtistVoteDetail:
def patch(request, artist_vote_id):
"""Update artist vote"""
artist_vote = get_object_or_404(ArtistVote, pk=artist_vote_id)
serializer = ArtistVoteSerializerUpdate(artist_vote, data=request.data, context={'request': request}, partial=True)
if serializer.is_val... | the_stack_v2_python_sparse | v1/votes/views/artist_vote.py | lawiz22/PLOUC-Backend-master | train | 0 | |
92c9953ad9d03c95df93fedbe617dce188e06397 | [
"res = []\n\ndef preorder(node):\n if not node:\n return\n res.append(str(node.val))\n for c in node.children:\n preorder(c)\n res.append('#')\npreorder(root)\nreturn ' '.join(res)",
"if not data:\n return None\ndata = deque(data.split())\n\ndef construct():\n root = Node(data.popl... | <|body_start_0|>
res = []
def preorder(node):
if not node:
return
res.append(str(node.val))
for c in node.children:
preorder(c)
res.append('#')
preorder(root)
return ' '.join(res)
<|end_body_0|>
<|body_star... | 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_004101 | 1,425 | 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 | null | 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... | 79d4824879d0faed117eee9d99615cd478432a14 | <|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 preorder(node):
if not node:
return
res.append(str(node.val))
for c in node.children:
... | the_stack_v2_python_sparse | Tree/Q428_Serialize and Deserialize N-ary Tree.py | Luolingwei/LeetCode | train | 0 | |
c9adfed3d855b5e057a9114f9cc857c2a9e0d79b | [
"super(FCNNPytorch, self).__init__()\nself.input_size = args.input_size\nself.num_classes = args.num_classes\nself.in_channels = args.in_channels\nself.dtype = args.dtype\nself.kernel_sizes = kernel_sizes\nself.out_channels = out_channels\nself.strides = strides\nself.conv_type = args.conv_type\nself.is_debug = arg... | <|body_start_0|>
super(FCNNPytorch, self).__init__()
self.input_size = args.input_size
self.num_classes = args.num_classes
self.in_channels = args.in_channels
self.dtype = args.dtype
self.kernel_sizes = kernel_sizes
self.out_channels = out_channels
self.st... | FCNNPytorch | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_siz... | stack_v2_sparse_classes_36k_train_004102 | 3,878 | permissive | [
{
"docstring": "Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_sizes: the sizes of the kernels in each conv layer. :param out_channels: the number of filters for each conv layer. :param str... | 3 | stack_v2_sparse_classes_30k_train_009037 | Implement the Python class `FCNNPytorch` described below.
Class description:
Implement the FCNNPytorch class.
Method signatures and docstrings:
- def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]): Create the FCNN model in PyTorch. :param args: the general arguments (con... | Implement the Python class `FCNNPytorch` described below.
Class description:
Implement the FCNNPytorch class.
Method signatures and docstrings:
- def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]): Create the FCNN model in PyTorch. :param args: the general arguments (con... | 81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a | <|skeleton|>
class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_siz... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FCNNPytorch:
def __init__(self, args, kernel_sizes=[8, 5, 3], out_channels=[128, 256, 128], strides=[1, 1, 1]):
"""Create the FCNN model in PyTorch. :param args: the general arguments (conv type, debug mode, etc). :param dtype: global - the type of pytorch data/weights. :param kernel_sizes: the sizes ... | the_stack_v2_python_sparse | cnns/nnlib/pytorch_architecture/fcnn.py | adam-dziedzic/bandlimited-cnns | train | 17 | |
d7cc49c4b61822c53cbd924a03570099a3fb2345 | [
"self.root = root\nself.write_root(root)\nfor p in root.subtree():\n if hasattr(self.at, 'force_sentinels'):\n self.put_node_sentinel(p, '<!--', delim2='-->')\n self.write_headline(p)\n s = p.b.rstrip() + '\\n\\n'\n lines = s.splitlines(False)\n for s in lines:\n if not g.isDirective(s)... | <|body_start_0|>
self.root = root
self.write_root(root)
for p in root.subtree():
if hasattr(self.at, 'force_sentinels'):
self.put_node_sentinel(p, '<!--', delim2='-->')
self.write_headline(p)
s = p.b.rstrip() + '\n\n'
lines = s.spli... | The writer class for markdown files. | MarkdownWriter | [
"MIT",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root):
"""Write all the *descendants* of an @auto-markdown node."""
<|body_0|>
def write_headline(self, p):
"""Write or skip the headline. New in Leo 5.5: Always write '#' sections. This w... | stack_v2_sparse_classes_36k_train_004103 | 2,368 | permissive | [
{
"docstring": "Write all the *descendants* of an @auto-markdown node.",
"name": "write",
"signature": "def write(self, root)"
},
{
"docstring": "Write or skip the headline. New in Leo 5.5: Always write '#' sections. This will cause perfect import to fail. The alternatives are much worse.",
... | 3 | stack_v2_sparse_classes_30k_train_017264 | Implement the Python class `MarkdownWriter` described below.
Class description:
The writer class for markdown files.
Method signatures and docstrings:
- def write(self, root): Write all the *descendants* of an @auto-markdown node.
- def write_headline(self, p): Write or skip the headline. New in Leo 5.5: Always write... | Implement the Python class `MarkdownWriter` described below.
Class description:
The writer class for markdown files.
Method signatures and docstrings:
- def write(self, root): Write all the *descendants* of an @auto-markdown node.
- def write_headline(self, p): Write or skip the headline. New in Leo 5.5: Always write... | 52d2c4c8684df8d065a494abb62dbf5077075ff9 | <|skeleton|>
class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root):
"""Write all the *descendants* of an @auto-markdown node."""
<|body_0|>
def write_headline(self, p):
"""Write or skip the headline. New in Leo 5.5: Always write '#' sections. This w... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MarkdownWriter:
"""The writer class for markdown files."""
def write(self, root):
"""Write all the *descendants* of an @auto-markdown node."""
self.root = root
self.write_root(root)
for p in root.subtree():
if hasattr(self.at, 'force_sentinels'):
... | the_stack_v2_python_sparse | leo/plugins/writers/markdown.py | alejagapatrick-spec/leo-editor | train | 2 |
8c323b72dd7edd2c71791a50995ce7b5312496e0 | [
"project_numbers_sql = select_data.PROJECT_NUMBERS.format(timestamp)\nrows = self.execute_sql_with_fetch(resource_name, project_numbers_sql, ())\nreturn [row['project_number'] for row in rows]",
"project_policies = {}\ntry:\n cursor = self.conn.cursor()\n cursor.execute(select_data.PROJECT_IAM_POLICIES_RAW.... | <|body_start_0|>
project_numbers_sql = select_data.PROJECT_NUMBERS.format(timestamp)
rows = self.execute_sql_with_fetch(resource_name, project_numbers_sql, ())
return [row['project_number'] for row in rows]
<|end_body_0|>
<|body_start_1|>
project_policies = {}
try:
c... | Data access object (DAO). | ProjectDao | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProjectDao:
"""Data access object (DAO)."""
def get_project_numbers(self, resource_name, timestamp):
"""Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns:... | stack_v2_sparse_classes_36k_train_004104 | 3,777 | permissive | [
{
"docstring": "Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: list of project numbers Raises: MySQLError: An error with MySQL has occurred.",
"name": "get_project_numbers",
... | 2 | stack_v2_sparse_classes_30k_train_014053 | Implement the Python class `ProjectDao` described below.
Class description:
Data access object (DAO).
Method signatures and docstrings:
- def get_project_numbers(self, resource_name, timestamp): Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: Str... | Implement the Python class `ProjectDao` described below.
Class description:
Data access object (DAO).
Method signatures and docstrings:
- def get_project_numbers(self, resource_name, timestamp): Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: Str... | 1fa2e1827a5f4a111062370710470853130e6c8a | <|skeleton|>
class ProjectDao:
"""Data access object (DAO)."""
def get_project_numbers(self, resource_name, timestamp):
"""Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns:... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProjectDao:
"""Data access object (DAO)."""
def get_project_numbers(self, resource_name, timestamp):
"""Select the project numbers from a projects snapshot table. Args: resource_name: String of the resource name. timestamp: String of timestamp, formatted as YYYYMMDDTHHMMSSZ. Returns: list of proj... | the_stack_v2_python_sparse | google/cloud/security/common/data_access/project_dao.py | Kakuye/forseti-security | train | 0 |
7998632cbfd01d286c2deb78ba8febe86d6b0d98 | [
"def pre_order(root):\n out = []\n if root:\n out.append(str(root.val))\n out += pre_order(root.left)\n out += pre_order(root.right)\n return out\nreturn ','.join(pre_order(root))",
"if not data:\n return None\n\ndef build_tree(a, b):\n if not a:\n return None\n mid =... | <|body_start_0|>
def pre_order(root):
out = []
if root:
out.append(str(root.val))
out += pre_order(root.left)
out += pre_order(root.right)
return out
return ','.join(pre_order(root))
<|end_body_0|>
<|body_start_1|>
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_004105 | 1,311 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | null | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | 2fe336e0de336f6d5f67b058ddb5cf50c9f00d4e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
def pre_order(root):
out = []
if root:
out.append(str(root.val))
out += pre_order(root.left)
out += pre_order(root... | the_stack_v2_python_sparse | python/449. Serialize and Deserialize BST.py | rhzx3519/leetcode | train | 3 | |
633aaf05379729fe03bc0a7a99886f2af9fc53bd | [
"if len(nums) < 3:\n return 2147483647\ni, j, k, result, min_diff = (0, 1, len(nums) - 1, 2147483647, 2147483647)\nx = nums[0]\nwhile j < k:\n y = nums[j]\n z = nums[k]\n sum = x + y + z\n if sum == target:\n return sum\n else:\n difference = abs(sum - target)\n if difference ... | <|body_start_0|>
if len(nums) < 3:
return 2147483647
i, j, k, result, min_diff = (0, 1, len(nums) - 1, 2147483647, 2147483647)
x = nums[0]
while j < k:
y = nums[j]
z = nums[k]
sum = x + y + z
if sum == target:
re... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def closest(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2], 3) 3"""
<|body_0|>
def threeSumClosest(self, nums, target):
""":type nums: ... | stack_v2_sparse_classes_36k_train_004106 | 1,743 | no_license | [
{
"docstring": ":param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2], 3) 3",
"name": "closest",
"signature": "def closest(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :r... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closest(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2],... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def closest(self, nums, target): :param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2],... | 3b13a02f9c8273f9794a57b948d2655792707f37 | <|skeleton|>
class Solution:
def closest(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2], 3) 3"""
<|body_0|>
def threeSumClosest(self, nums, target):
""":type nums: ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def closest(self, nums, target):
""":param nums: :param target: :return: >>> s = Solution() >>> s.closest([-4, -1, 1, 2], 1) -1 >>> s.closest([-1, 1, 2], 1) 2 >>> s.closest([0,1,2], 3) 3"""
if len(nums) < 3:
return 2147483647
i, j, k, result, min_diff = (0, 1, len... | the_stack_v2_python_sparse | 3sumclosest.py | gsy/leetcode | train | 1 | |
8cf82579b9009fbccb5335b99d74f667b681244d | [
"super(SubNet, self).__init__()\nself.norm = nn.BatchNorm1d(in_size)\nself.drop = nn.Dropout(p=dropout)\nself.linear_1 = nn.Linear(in_size, hidden_size)\nself.linear_2 = nn.Linear(hidden_size, hidden_size)\nself.linear_3 = nn.Linear(hidden_size, hidden_size)",
"normed = self.norm(x)\ndropped = self.drop(normed)\n... | <|body_start_0|>
super(SubNet, self).__init__()
self.norm = nn.BatchNorm1d(in_size)
self.drop = nn.Dropout(p=dropout)
self.linear_1 = nn.Linear(in_size, hidden_size)
self.linear_2 = nn.Linear(hidden_size, hidden_size)
self.linear_3 = nn.Linear(hidden_size, hidden_size)
<|... | The subnetwork that is used in TFN for video and audio in the pre-fusion stage | SubNet | [
"GPL-1.0-or-later",
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tenso... | stack_v2_sparse_classes_36k_train_004107 | 3,873 | permissive | [
{
"docstring": "Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (batch_size, hidden_size)",
"name": "__init__",
"signature": "def __init__(self, in_size, hidden_size, dropout)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_019856 | Implement the Python class `SubNet` described below.
Class description:
The subnetwork that is used in TFN for video and audio in the pre-fusion stage
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: drop... | Implement the Python class `SubNet` described below.
Class description:
The subnetwork that is used in TFN for video and audio in the pre-fusion stage
Method signatures and docstrings:
- def __init__(self, in_size, hidden_size, dropout): Args: in_size: input dimension hidden_size: hidden layer dimension dropout: drop... | 92acc188d3a0f634de58463b6676e70df83ef808 | <|skeleton|>
class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tenso... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SubNet:
"""The subnetwork that is used in TFN for video and audio in the pre-fusion stage"""
def __init__(self, in_size, hidden_size, dropout):
"""Args: in_size: input dimension hidden_size: hidden layer dimension dropout: dropout probability Output: (return value in forward) a tensor of shape (b... | the_stack_v2_python_sparse | PyTorch/contrib/others/MMSA_ID2979_for_PyTorch/models/subNets/FeatureNets.py | Ascend/ModelZoo-PyTorch | train | 23 |
ec01c324c7c57cc4a8666f2b230aa0e5a6ce8911 | [
"if hasattr(self, 'changes'):\n return [changes.entity_name for changes in self.changes]\nelse:\n raise NoChangesAttribute()",
"manager = self.__versioning_manager__\ntuples = set(manager.version_class_map.items())\nentities = {}\nsession = sa.orm.object_session(self)\nfor class_, version_class in tuples:\n... | <|body_start_0|>
if hasattr(self, 'changes'):
return [changes.entity_name for changes in self.changes]
else:
raise NoChangesAttribute()
<|end_body_0|>
<|body_start_1|>
manager = self.__versioning_manager__
tuples = set(manager.version_class_map.items())
e... | TransactionBase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TransactionBase:
def entity_names(self):
"""Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not exist, most likely because TransactionChangesPlugin is not enabled."""
<|body_0|>
def change... | stack_v2_sparse_classes_36k_train_004108 | 5,800 | permissive | [
{
"docstring": "Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not exist, most likely because TransactionChangesPlugin is not enabled.",
"name": "entity_names",
"signature": "def entity_names(self)"
},
{
"doc... | 2 | stack_v2_sparse_classes_30k_train_004166 | Implement the Python class `TransactionBase` described below.
Class description:
Implement the TransactionBase class.
Method signatures and docstrings:
- def entity_names(self): Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not e... | Implement the Python class `TransactionBase` described below.
Class description:
Implement the TransactionBase class.
Method signatures and docstrings:
- def entity_names(self): Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not e... | a7a6bd7952185b1f82af985c0271834d886a617c | <|skeleton|>
class TransactionBase:
def entity_names(self):
"""Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not exist, most likely because TransactionChangesPlugin is not enabled."""
<|body_0|>
def change... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TransactionBase:
def entity_names(self):
"""Return a list of entity names that changed during this transaction. Raises a NoChangesAttribute exception if the 'changes' column does not exist, most likely because TransactionChangesPlugin is not enabled."""
if hasattr(self, 'changes'):
... | the_stack_v2_python_sparse | sqlalchemy_continuum/transaction.py | kvesteri/sqlalchemy-continuum | train | 479 | |
80041828d3c7bfb550bf00a21e60ecb67fcb0eb7 | [
"Author = AuthorModel.find_by_name(name)\nif Author:\n return Author.json()\nreturn ({'message': 'Author not found'}, 404)",
"if AuthorModel.find_by_name(name):\n return ({'message': \"An Author with name '{}' already exists.\".format(name)}, 400)\ndata = Author.parser.parse_args()\nauthor = AuthorModel(nam... | <|body_start_0|>
Author = AuthorModel.find_by_name(name)
if Author:
return Author.json()
return ({'message': 'Author not found'}, 404)
<|end_body_0|>
<|body_start_1|>
if AuthorModel.find_by_name(name):
return ({'message': "An Author with name '{}' already exists.... | Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> | AuthorName | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AuthorName:
"""Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name>"""
... | stack_v2_sparse_classes_36k_train_004109 | 9,451 | permissive | [
{
"docstring": "GET request that deals with requests that look for a author provided its name",
"name": "get",
"signature": "def get(self, name)"
},
{
"docstring": "POST request that creates an author, provided a name and description, image_url, wiki_url",
"name": "post",
"signature": "d... | 4 | stack_v2_sparse_classes_30k_train_019131 | Implement the Python class `AuthorName` described below.
Class description:
Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET ... | Implement the Python class `AuthorName` described below.
Class description:
Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET ... | 42456ced804a2c9570227b393de662847283c76f | <|skeleton|>
class AuthorName:
"""Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name>"""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AuthorName:
"""Author Name. Resource that helps with dealing with Http request for a author by providing its name. HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name> HTTP POST call : /authors/name/<string:name> HTTP GET call : /authors/name/<string:name>"""
def get(s... | the_stack_v2_python_sparse | resources/author.py | basgir/bibliotek | train | 0 |
8213564301aa39c8f4182908fa25f7539981a669 | [
"toggle = NanpyGPIOToggle(self.mudpi, config)\nif toggle:\n node = self.extension.nodes[config['node']]\n if node:\n toggle.node = node\n self.add_component(toggle)\n else:\n raise MudPiError(f\"Nanpy node {config['node']} not found trying to connect {config['key']}.\")\nreturn True",
... | <|body_start_0|>
toggle = NanpyGPIOToggle(self.mudpi, config)
if toggle:
node = self.extension.nodes[config['node']]
if node:
toggle.node = node
self.add_component(toggle)
else:
raise MudPiError(f"Nanpy node {config['nod... | Interface | [
"BSD-4-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy control config"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
toggle = NanpyGPIOToggle(self.mudpi, confi... | stack_v2_sparse_classes_36k_train_004110 | 5,292 | permissive | [
{
"docstring": "Load Nanpy Toggle components from configs",
"name": "load",
"signature": "def load(self, config)"
},
{
"docstring": "Validate the Nanpy control config",
"name": "validate",
"signature": "def validate(self, config)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006447 | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy Toggle components from configs
- def validate(self, config): Validate the Nanpy control config | Implement the Python class `Interface` described below.
Class description:
Implement the Interface class.
Method signatures and docstrings:
- def load(self, config): Load Nanpy Toggle components from configs
- def validate(self, config): Validate the Nanpy control config
<|skeleton|>
class Interface:
def load(s... | fb206b1136f529c7197f1e6b29629ed05630d377 | <|skeleton|>
class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
<|body_0|>
def validate(self, config):
"""Validate the Nanpy control config"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Interface:
def load(self, config):
"""Load Nanpy Toggle components from configs"""
toggle = NanpyGPIOToggle(self.mudpi, config)
if toggle:
node = self.extension.nodes[config['node']]
if node:
toggle.node = node
self.add_component(... | the_stack_v2_python_sparse | mudpi/extensions/nanpy/toggle.py | mistasp0ck/mudpi-core | train | 0 | |
448c8b2f20d61a4da6f0c5a3a6880ddcbd9e0be0 | [
"self.data = data\nself.regression_function = regression_test_function\nself.test_name = regression_test_name\nself.covars = covars\nself.pheno = pheno\nself.cpgnames = cpgnames",
"output = []\nfor i, site in enumerate(self.data):\n coefs, tstats, p_value = self.regression_function(self.pheno, site, covars=sel... | <|body_start_0|>
self.data = data
self.regression_function = regression_test_function
self.test_name = regression_test_name
self.covars = covars
self.pheno = pheno
self.cpgnames = cpgnames
<|end_body_0|>
<|body_start_1|>
output = []
for i, site in enumera... | regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients | Regression | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Regression:
"""regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients"""
def __init__(self, data, regression_test_name,... | stack_v2_sparse_classes_36k_train_004111 | 15,952 | no_license | [
{
"docstring": "data - the methylation data matrix site by samples cpgnames - the list of cpgnames (sites) in the same order as in data pheno - the phenotypes vector (1D) to use (samples in the same order as in data) covars - the covariates matrix (can be more then 1 covariates) to use, if None- no covariates w... | 2 | stack_v2_sparse_classes_30k_train_010207 | Implement the Python class `Regression` described below.
Class description:
regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients
Method signatu... | Implement the Python class `Regression` described below.
Class description:
regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients
Method signatu... | 13ac554041a3b12ec7990e98452a44a4109904cb | <|skeleton|>
class Regression:
"""regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients"""
def __init__(self, data, regression_test_name,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Regression:
"""regression_test_function - a function that return the coefs, tstats, p_value such that: the value at index -1 describes the site under test the value at index 0 describes the intercept all other values describe the coefficients"""
def __init__(self, data, regression_test_name, regression_t... | the_stack_v2_python_sparse | ewas/GLINT_1/modules/ewas.py | moqri/era_old | train | 1 |
aaa925a9ae2e34e06ea4169268b04819d356d2f5 | [
"snap = super(Notebook, self).snapshot()\nsnap['tab_style'] = self.tab_style\nsnap['tab_position'] = self.tab_position\nsnap['tabs_closable'] = self.tabs_closable\nsnap['tabs_movable'] = self.tabs_movable\nreturn snap",
"super(Notebook, self).bind()\nattrs = ('tab_style', 'tab_position', 'tabs_closable', 'tabs_mo... | <|body_start_0|>
snap = super(Notebook, self).snapshot()
snap['tab_style'] = self.tab_style
snap['tab_position'] = self.tab_position
snap['tabs_closable'] = self.tabs_closable
snap['tabs_movable'] = self.tabs_movable
return snap
<|end_body_0|>
<|body_start_1|>
su... | A component which displays its children as tabbed pages. | Notebook | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Notebook:
"""A component which displays its children as tabbed pages."""
def snapshot(self):
"""Returns the snapshot for the control."""
<|body_0|>
def bind(self):
"""Bind the change handlers for the control."""
<|body_1|>
def _get_pages(self):
... | stack_v2_sparse_classes_36k_train_004112 | 2,869 | permissive | [
{
"docstring": "Returns the snapshot for the control.",
"name": "snapshot",
"signature": "def snapshot(self)"
},
{
"docstring": "Bind the change handlers for the control.",
"name": "bind",
"signature": "def bind(self)"
},
{
"docstring": "The getter for the 'pages' property. Retur... | 3 | stack_v2_sparse_classes_30k_train_005634 | Implement the Python class `Notebook` described below.
Class description:
A component which displays its children as tabbed pages.
Method signatures and docstrings:
- def snapshot(self): Returns the snapshot for the control.
- def bind(self): Bind the change handlers for the control.
- def _get_pages(self): The gette... | Implement the Python class `Notebook` described below.
Class description:
A component which displays its children as tabbed pages.
Method signatures and docstrings:
- def snapshot(self): Returns the snapshot for the control.
- def bind(self): Bind the change handlers for the control.
- def _get_pages(self): The gette... | 424bba29219de58fe9e47196de6763de8b2009f2 | <|skeleton|>
class Notebook:
"""A component which displays its children as tabbed pages."""
def snapshot(self):
"""Returns the snapshot for the control."""
<|body_0|>
def bind(self):
"""Bind the change handlers for the control."""
<|body_1|>
def _get_pages(self):
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Notebook:
"""A component which displays its children as tabbed pages."""
def snapshot(self):
"""Returns the snapshot for the control."""
snap = super(Notebook, self).snapshot()
snap['tab_style'] = self.tab_style
snap['tab_position'] = self.tab_position
snap['tabs_c... | the_stack_v2_python_sparse | enaml/widgets/notebook.py | enthought/enaml | train | 17 |
bb969bacd841f763bdaabace21f8c3e47eb84fde | [
"if os.path.exists(cls.event_saved_local_file):\n shutil.move(cls.event_saved_local_file, cls.event_buffered_local_file)\nif os.path.exists(cls.event_saved_pending_file):\n shutil.move(cls.event_saved_pending_file, cls.event_buffered_pending_file)",
"ret_value = RpdEventOrderedBuffer.read_json(cls.BUFFERED_... | <|body_start_0|>
if os.path.exists(cls.event_saved_local_file):
shutil.move(cls.event_saved_local_file, cls.event_buffered_local_file)
if os.path.exists(cls.event_saved_pending_file):
shutil.move(cls.event_saved_pending_file, cls.event_buffered_pending_file)
<|end_body_0|>
<|bod... | event common operation, such as json file read, write, timestamp conversion. | EventCommonOperation | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EventCommonOperation:
"""event common operation, such as json file read, write, timestamp conversion."""
def restore_log(cls):
"""restore log message."""
<|body_0|>
def read_log(cls, buffered):
"""read log message."""
<|body_1|>
def write_log(cls, da... | stack_v2_sparse_classes_36k_train_004113 | 32,628 | permissive | [
{
"docstring": "restore log message.",
"name": "restore_log",
"signature": "def restore_log(cls)"
},
{
"docstring": "read log message.",
"name": "read_log",
"signature": "def read_log(cls, buffered)"
},
{
"docstring": "write a dict to log file.",
"name": "write_log",
"sig... | 6 | null | Implement the Python class `EventCommonOperation` described below.
Class description:
event common operation, such as json file read, write, timestamp conversion.
Method signatures and docstrings:
- def restore_log(cls): restore log message.
- def read_log(cls, buffered): read log message.
- def write_log(cls, data, ... | Implement the Python class `EventCommonOperation` described below.
Class description:
event common operation, such as json file read, write, timestamp conversion.
Method signatures and docstrings:
- def restore_log(cls): restore log message.
- def read_log(cls, buffered): read log message.
- def write_log(cls, data, ... | 70cf84df92347aba0493f506c0d059c0c041cba8 | <|skeleton|>
class EventCommonOperation:
"""event common operation, such as json file read, write, timestamp conversion."""
def restore_log(cls):
"""restore log message."""
<|body_0|>
def read_log(cls, buffered):
"""read log message."""
<|body_1|>
def write_log(cls, da... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class EventCommonOperation:
"""event common operation, such as json file read, write, timestamp conversion."""
def restore_log(cls):
"""restore log message."""
if os.path.exists(cls.event_saved_local_file):
shutil.move(cls.event_saved_local_file, cls.event_buffered_local_file)
... | the_stack_v2_python_sparse | openrpd/rpd/common/rpd_event_def.py | hujiangyi/or | train | 0 |
cb9fe1aa66539a3e7f70b36de15de47f2ed19484 | [
"minutes_spent = previous_request_time.total_minutes()\nif minutes_spent == 0:\n self._current_range = self.DEFAULT_RANGE_DAYS\nelse:\n days_per_minute = self._current_range / minutes_spent\n next_range = math.floor(days_per_minute / self.REQUEST_PER_MINUTE_LIMIT)\n self._current_range = min(next_range ... | <|body_start_0|>
minutes_spent = previous_request_time.total_minutes()
if minutes_spent == 0:
self._current_range = self.DEFAULT_RANGE_DAYS
else:
days_per_minute = self._current_range / minutes_spent
next_range = math.floor(days_per_minute / self.REQUEST_PER_M... | Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have INITIAL_RANGE_DAYS (30 days) length. 2. When slice is processed by stream this class expect "... | AdjustableSliceGenerator | [
"MIT",
"Elastic-2.0",
"Apache-2.0",
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdjustableSliceGenerator:
"""Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have INITIAL_RANGE_DAYS (30 days) length. 2. W... | stack_v2_sparse_classes_36k_train_004114 | 6,343 | permissive | [
{
"docstring": "Calculate next slice length in days based on previous slice length and processing time.",
"name": "adjust_range",
"signature": "def adjust_range(self, previous_request_time: Period)"
},
{
"docstring": "This method is supposed to be called when slice processing failed. Reset next ... | 3 | stack_v2_sparse_classes_30k_train_008676 | Implement the Python class `AdjustableSliceGenerator` described below.
Class description:
Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have IN... | Implement the Python class `AdjustableSliceGenerator` described below.
Class description:
Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have IN... | 8d5f9a2d49ab8f9e85ccf058cb02c2fda287afc6 | <|skeleton|>
class AdjustableSliceGenerator:
"""Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have INITIAL_RANGE_DAYS (30 days) length. 2. W... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AdjustableSliceGenerator:
"""Generate slices from start_date up to current date. Every next slice could have different range based on was the previous slice processed successfully and how much time it took. The alghorithm is following: 1. First slice have INITIAL_RANGE_DAYS (30 days) length. 2. When slice is ... | the_stack_v2_python_sparse | dts/airbyte/airbyte-integrations/connectors/source-iterable/source_iterable/slice_generators.py | alldatacenter/alldata | train | 774 |
e1262deca0d3f63d0a94a656765dbd59dc3057ef | [
"super(SingleHierarchy, self).__init__()\nself.level = h_level\ninput_dim, embed_dim, graph_dim = dimensions\nk_local, k_graph = k\nself.local_embedder = PointNetEmbedder(input_dim, embed_dim, k=k_local)\nself.graph_embedder = GraphEmbedder(embed_dim, graph_dim, k=k_graph)\nclassifier_dimensions = dimensions[-1:] +... | <|body_start_0|>
super(SingleHierarchy, self).__init__()
self.level = h_level
input_dim, embed_dim, graph_dim = dimensions
k_local, k_graph = k
self.local_embedder = PointNetEmbedder(input_dim, embed_dim, k=k_local)
self.graph_embedder = GraphEmbedder(embed_dim, graph_dim... | SingleHierarchy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SingleHierarchy:
def __init__(self, h_level, dimensions, k, classifier_dimensions=None):
"""Init function"""
<|body_0|>
def forward(self, raw_features, edge_vectors):
"""Forward operation of single hierarchy Parameters ---------- positions_batch : Tensor [BxNx3]. Bat... | stack_v2_sparse_classes_36k_train_004115 | 10,368 | no_license | [
{
"docstring": "Init function",
"name": "__init__",
"signature": "def __init__(self, h_level, dimensions, k, classifier_dimensions=None)"
},
{
"docstring": "Forward operation of single hierarchy Parameters ---------- positions_batch : Tensor [BxNx3]. Batch of tensors containing positions of node... | 2 | stack_v2_sparse_classes_30k_train_011691 | Implement the Python class `SingleHierarchy` described below.
Class description:
Implement the SingleHierarchy class.
Method signatures and docstrings:
- def __init__(self, h_level, dimensions, k, classifier_dimensions=None): Init function
- def forward(self, raw_features, edge_vectors): Forward operation of single h... | Implement the Python class `SingleHierarchy` described below.
Class description:
Implement the SingleHierarchy class.
Method signatures and docstrings:
- def __init__(self, h_level, dimensions, k, classifier_dimensions=None): Init function
- def forward(self, raw_features, edge_vectors): Forward operation of single h... | 908b2bd2c0f8cf3924135e01fcdfc91f2fc086c7 | <|skeleton|>
class SingleHierarchy:
def __init__(self, h_level, dimensions, k, classifier_dimensions=None):
"""Init function"""
<|body_0|>
def forward(self, raw_features, edge_vectors):
"""Forward operation of single hierarchy Parameters ---------- positions_batch : Tensor [BxNx3]. Bat... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SingleHierarchy:
def __init__(self, h_level, dimensions, k, classifier_dimensions=None):
"""Init function"""
super(SingleHierarchy, self).__init__()
self.level = h_level
input_dim, embed_dim, graph_dim = dimensions
k_local, k_graph = k
self.local_embedder = Poin... | the_stack_v2_python_sparse | models/hgcn.py | bkakilli/3d-segmentation | train | 0 | |
ac03c146eeae0160dee0cb85ae9dd11324eccf50 | [
"super().__init__()\nself.average = average\nself.reduce_fn = reduce_fn",
"assert pred.shape == target.shape\nassert len(pred.shape) == 2\npred = pred.cpu().numpy()\ntarget = target.cpu().numpy()\nroc_auc = roc_auc_score(y_true=target, y_score=pred, average=self.average)\nscore = 2 ** 0.5 * norm.ppf(roc_auc)\nsco... | <|body_start_0|>
super().__init__()
self.average = average
self.reduce_fn = reduce_fn
<|end_body_0|>
<|body_start_1|>
assert pred.shape == target.shape
assert len(pred.shape) == 2
pred = pred.cpu().numpy()
target = target.cpu().numpy()
roc_auc = roc_auc_s... | DPrime | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DPrime:
def __init__(self, average: Optional[str]=None, reduce_fn: Callable=torch.mean):
"""DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: sklearn and scipy. :param average: The type of D' score to compute. (default: 'macro') :param re... | stack_v2_sparse_classes_36k_train_004116 | 1,386 | permissive | [
{
"docstring": "DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: sklearn and scipy. :param average: The type of D' score to compute. (default: 'macro') :param reduce_fn: The reduction function to apply. (default: torch.mean)",
"name": "__init__",
"signa... | 2 | stack_v2_sparse_classes_30k_train_015133 | Implement the Python class `DPrime` described below.
Class description:
Implement the DPrime class.
Method signatures and docstrings:
- def __init__(self, average: Optional[str]=None, reduce_fn: Callable=torch.mean): DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: s... | Implement the Python class `DPrime` described below.
Class description:
Implement the DPrime class.
Method signatures and docstrings:
- def __init__(self, average: Optional[str]=None, reduce_fn: Callable=torch.mean): DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: s... | 91aa907a3f820e53902578c3d0110fe9a01c88e7 | <|skeleton|>
class DPrime:
def __init__(self, average: Optional[str]=None, reduce_fn: Callable=torch.mean):
"""DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: sklearn and scipy. :param average: The type of D' score to compute. (default: 'macro') :param re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DPrime:
def __init__(self, average: Optional[str]=None, reduce_fn: Callable=torch.mean):
"""DPrime metric. Note: If score == 0 : bad score, low difference between 'noise' and inputs. Backend: sklearn and scipy. :param average: The type of D' score to compute. (default: 'macro') :param reduce_fn: The r... | the_stack_v2_python_sparse | mlu/metrics/classification/dprime.py | Labbeti/MLU | train | 2 | |
e6536117ba2042f6645e966e8e46f91b7c6292d7 | [
"print()\nprint('Configure Doctors')\nprint(self.name)\ncount = 0\nfor doctor in self.doctor_line:\n doctor.physician.active = doctor.x_active\n count = count + 1\nprint('Finished !')",
"days_inactive = []\nif self.name not in [False]:\n for day in self.day_line:\n if day.holiday:\n day... | <|body_start_0|>
print()
print('Configure Doctors')
print(self.name)
count = 0
for doctor in self.doctor_line:
doctor.physician.active = doctor.x_active
count = count + 1
print('Finished !')
<|end_body_0|>
<|body_start_1|>
days_inactive = ... | Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours. | ConfiguratorEmr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ConfiguratorEmr:
"""Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours."""
def config_doctors(self):
"""Configure Doctors Using config... | stack_v2_sparse_classes_36k_train_004117 | 7,975 | no_license | [
{
"docstring": "Configure Doctors Using configurator data",
"name": "config_doctors",
"signature": "def config_doctors(self)"
},
{
"docstring": "LOD friendly. Gets Inactive Days. From Configurator.",
"name": "get_inactive_days",
"signature": "def get_inactive_days(self)"
},
{
"do... | 3 | stack_v2_sparse_classes_30k_train_011395 | Implement the Python class `ConfiguratorEmr` described below.
Class description:
Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours.
Method signatures and docstrings:
-... | Implement the Python class `ConfiguratorEmr` described below.
Class description:
Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours.
Method signatures and docstrings:
-... | c15f8b146392d47a9040404a4ac8e45a1b062198 | <|skeleton|>
class ConfiguratorEmr:
"""Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours."""
def config_doctors(self):
"""Configure Doctors Using config... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ConfiguratorEmr:
"""Permits Multi Company behavior. Configuration can be done for: - Ticket content. - Electronic Billing, - Laser procedures, - Error validation, - CSV path for product input, - Holidays, - Opening hours."""
def config_doctors(self):
"""Configure Doctors Using configurator data""... | the_stack_v2_python_sparse | models/configurator/configurator_emr.py | gibil5/openhealth | train | 1 |
fd4c86be2a5e849567dc6e97254f3970055695d7 | [
"super().__init__()\nself._port = nconfig().get('port', 8091)\nself._certificate = nconfig().get('certificate', 'cert.pem')\nself._private_key = nconfig().get('privatekey', 'priv.pem')\nself._use_ssl = nconfig().get('use_ssl', True)",
"socket_pair = ('', self._port)\nself._httpd = MultithreadedHTTPServer(socket_p... | <|body_start_0|>
super().__init__()
self._port = nconfig().get('port', 8091)
self._certificate = nconfig().get('certificate', 'cert.pem')
self._private_key = nconfig().get('privatekey', 'priv.pem')
self._use_ssl = nconfig().get('use_ssl', True)
<|end_body_0|>
<|body_start_1|>
... | The HTTP web server. | Webserver | [
"MIT",
"LicenseRef-scancode-public-domain"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
<|body_0|>
def run(self) -> None:
"""Starts the HTTP server in the background."""
<|body_1|>
def stop(self) -> None:
"""Stops the HTTP server if it is runnin... | stack_v2_sparse_classes_36k_train_004118 | 4,037 | permissive | [
{
"docstring": "Constructor.",
"name": "__init__",
"signature": "def __init__(self) -> None"
},
{
"docstring": "Starts the HTTP server in the background.",
"name": "run",
"signature": "def run(self) -> None"
},
{
"docstring": "Stops the HTTP server if it is running.",
"name":... | 4 | stack_v2_sparse_classes_30k_train_015998 | Implement the Python class `Webserver` described below.
Class description:
The HTTP web server.
Method signatures and docstrings:
- def __init__(self) -> None: Constructor.
- def run(self) -> None: Starts the HTTP server in the background.
- def stop(self) -> None: Stops the HTTP server if it is running.
- def _creat... | Implement the Python class `Webserver` described below.
Class description:
The HTTP web server.
Method signatures and docstrings:
- def __init__(self) -> None: Constructor.
- def run(self) -> None: Starts the HTTP server in the background.
- def stop(self) -> None: Stops the HTTP server if it is running.
- def _creat... | 7f7737923e5d8441bbc65cafedf29db14e750860 | <|skeleton|>
class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
<|body_0|>
def run(self) -> None:
"""Starts the HTTP server in the background."""
<|body_1|>
def stop(self) -> None:
"""Stops the HTTP server if it is runnin... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Webserver:
"""The HTTP web server."""
def __init__(self) -> None:
"""Constructor."""
super().__init__()
self._port = nconfig().get('port', 8091)
self._certificate = nconfig().get('certificate', 'cert.pem')
self._private_key = nconfig().get('privatekey', 'priv.pem')... | the_stack_v2_python_sparse | src/nussschale/webserver.py | RealFloorIsJava/KgF | train | 0 |
df88b00bb7546e7d79a2ac618ec0ec15fe4eb668 | [
"if root is None:\n return ''\ncurr_lvl = [root]\nnext_lvl = []\nans = []\nwhile curr_lvl:\n tmp_ans = ','.join((str(node.val) if node is not None else '*' for node in curr_lvl))\n ans.append(tmp_ans)\n nxt_lvl = []\n for each in curr_lvl:\n if each is not None:\n nxt_lvl.append(eac... | <|body_start_0|>
if root is None:
return ''
curr_lvl = [root]
next_lvl = []
ans = []
while curr_lvl:
tmp_ans = ','.join((str(node.val) if node is not None else '*' for node in curr_lvl))
ans.append(tmp_ans)
nxt_lvl = []
... | Codec | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|>
<|body_... | stack_v2_sparse_classes_36k_train_004119 | 1,779 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: TreeNode :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root)"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: TreeNode",
"name": "deserialize",
"signature": "def deserializ... | 2 | stack_v2_sparse_classes_30k_train_000902 | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | Implement the Python class `Codec` described below.
Class description:
Implement the Codec class.
Method signatures and docstrings:
- def serialize(self, root): Encodes a tree to a single string. :type root: TreeNode :rtype: str
- def deserialize(self, data): Decodes your encoded data to tree. :type data: str :rtype:... | eeaa632e4d2b103c79925e823a05072a7264460e | <|skeleton|>
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
<|body_0|>
def deserialize(self, data):
"""Decodes your encoded data to tree. :type data: str :rtype: TreeNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if root is None:
return ''
curr_lvl = [root]
next_lvl = []
ans = []
while curr_lvl:
tmp_ans = ','.join((str(node.val) if node is n... | the_stack_v2_python_sparse | Serialize and Deserialize Binary Tree.py | RiddhiRex/Leetcode | train | 0 | |
03dc3588ef0cd08a895b96f31b0f630a93bc78da | [
"self._manifest_column_headers = ['Source', 'Destination', 'Start', 'End', 'Md5'] + (['UploadId'] if properties.VALUES.storage.run_by_gsutil_shim.GetBool() else []) + ['Source Size', 'Bytes Transferred', 'Result', 'Description']\nself._manifest_path = manifest_path\nif os.path.exists(manifest_path) and os.path.gets... | <|body_start_0|>
self._manifest_column_headers = ['Source', 'Destination', 'Start', 'End', 'Md5'] + (['UploadId'] if properties.VALUES.storage.run_by_gsutil_shim.GetBool() else []) + ['Source Size', 'Bytes Transferred', 'Result', 'Description']
self._manifest_path = manifest_path
if os.path.exis... | Handles writing copy statuses to manifest. | ManifestManager | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ManifestManager:
"""Handles writing copy statuses to manifest."""
def __init__(self, manifest_path):
"""Creates manifest file with correct headers."""
<|body_0|>
def write_row(self, manifest_message, file_progress=None):
"""Writes data to manifest file."""
... | stack_v2_sparse_classes_36k_train_004120 | 5,944 | permissive | [
{
"docstring": "Creates manifest file with correct headers.",
"name": "__init__",
"signature": "def __init__(self, manifest_path)"
},
{
"docstring": "Writes data to manifest file.",
"name": "write_row",
"signature": "def write_row(self, manifest_message, file_progress=None)"
}
] | 2 | null | Implement the Python class `ManifestManager` described below.
Class description:
Handles writing copy statuses to manifest.
Method signatures and docstrings:
- def __init__(self, manifest_path): Creates manifest file with correct headers.
- def write_row(self, manifest_message, file_progress=None): Writes data to man... | Implement the Python class `ManifestManager` described below.
Class description:
Handles writing copy statuses to manifest.
Method signatures and docstrings:
- def __init__(self, manifest_path): Creates manifest file with correct headers.
- def write_row(self, manifest_message, file_progress=None): Writes data to man... | 392abf004b16203030e6efd2f0af24db7c8d669e | <|skeleton|>
class ManifestManager:
"""Handles writing copy statuses to manifest."""
def __init__(self, manifest_path):
"""Creates manifest file with correct headers."""
<|body_0|>
def write_row(self, manifest_message, file_progress=None):
"""Writes data to manifest file."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ManifestManager:
"""Handles writing copy statuses to manifest."""
def __init__(self, manifest_path):
"""Creates manifest file with correct headers."""
self._manifest_column_headers = ['Source', 'Destination', 'Start', 'End', 'Md5'] + (['UploadId'] if properties.VALUES.storage.run_by_gsuti... | the_stack_v2_python_sparse | lib/googlecloudsdk/command_lib/storage/manifest_util.py | google-cloud-sdk-unofficial/google-cloud-sdk | train | 9 |
1b9403bc8b7c474cfe431fa738b299d1bc9be011 | [
"qs = super(SavedSearchAdmin, self).queryset(request)\nif not request.user.is_superuser:\n qs = qs.filter(user=request.user)\nreturn qs",
"has_class_permission = super(SavedSearchAdmin, self).has_change_permission(request, obj)\nif not has_class_permission:\n return False\nif obj is not None and (not reques... | <|body_start_0|>
qs = super(SavedSearchAdmin, self).queryset(request)
if not request.user.is_superuser:
qs = qs.filter(user=request.user)
return qs
<|end_body_0|>
<|body_start_1|>
has_class_permission = super(SavedSearchAdmin, self).has_change_permission(request, obj)
... | SavedSearchAdmin | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SavedSearchAdmin:
def queryset(self, request):
"""The queryset returned for this model admin"""
<|body_0|>
def has_change_permission(self, request, obj=None):
"""Check also if we have the permissions to edit this object"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_004121 | 1,621 | permissive | [
{
"docstring": "The queryset returned for this model admin",
"name": "queryset",
"signature": "def queryset(self, request)"
},
{
"docstring": "Check also if we have the permissions to edit this object",
"name": "has_change_permission",
"signature": "def has_change_permission(self, reques... | 2 | stack_v2_sparse_classes_30k_train_016831 | Implement the Python class `SavedSearchAdmin` described below.
Class description:
Implement the SavedSearchAdmin class.
Method signatures and docstrings:
- def queryset(self, request): The queryset returned for this model admin
- def has_change_permission(self, request, obj=None): Check also if we have the permission... | Implement the Python class `SavedSearchAdmin` described below.
Class description:
Implement the SavedSearchAdmin class.
Method signatures and docstrings:
- def queryset(self, request): The queryset returned for this model admin
- def has_change_permission(self, request, obj=None): Check also if we have the permission... | d134624da9d36c4ba0bea2df8a21698df196bdf6 | <|skeleton|>
class SavedSearchAdmin:
def queryset(self, request):
"""The queryset returned for this model admin"""
<|body_0|>
def has_change_permission(self, request, obj=None):
"""Check also if we have the permissions to edit this object"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SavedSearchAdmin:
def queryset(self, request):
"""The queryset returned for this model admin"""
qs = super(SavedSearchAdmin, self).queryset(request)
if not request.user.is_superuser:
qs = qs.filter(user=request.user)
return qs
def has_change_permission(self, re... | the_stack_v2_python_sparse | civil/apps/search/admin.py | christopinka/django-civil | train | 3 | |
9a56a366f3658d63184978e6817f18980ebaba01 | [
"try:\n responseDict = self.post('nodes/', {'node': addNodesRequest})\n return responseDict.get('addHostSession')\nexcept TortugaException:\n raise\nexcept Exception as ex:\n raise TortugaException(exception=ex)",
"url = 'addhost/{}/status'.format(session)\nurl += '?startMessage={0}&getNodes={1}'.form... | <|body_start_0|>
try:
responseDict = self.post('nodes/', {'node': addNodesRequest})
return responseDict.get('addHostSession')
except TortugaException:
raise
except Exception as ex:
raise TortugaException(exception=ex)
<|end_body_0|>
<|body_start_1... | AddHost WS API class. | AddHostWsApi | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddHostWsApi:
"""AddHost WS API class."""
def addNodes(self, addNodesRequest):
"""Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException"""
<|body_0|>
def getStatus(self, session=None, startMessage=0, getNodes=False):
"... | stack_v2_sparse_classes_36k_train_004122 | 2,317 | permissive | [
{
"docstring": "Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException",
"name": "addNodes",
"signature": "def addNodes(self, addNodesRequest)"
},
{
"docstring": "Get the status of addhost...if session is non-none get info for that session only. Startm... | 2 | null | Implement the Python class `AddHostWsApi` described below.
Class description:
AddHost WS API class.
Method signatures and docstrings:
- def addNodes(self, addNodesRequest): Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException
- def getStatus(self, session=None, startMessa... | Implement the Python class `AddHostWsApi` described below.
Class description:
AddHost WS API class.
Method signatures and docstrings:
- def addNodes(self, addNodesRequest): Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException
- def getStatus(self, session=None, startMessa... | 56d808d7836cd15d6c6748cbf704cdea4407fef6 | <|skeleton|>
class AddHostWsApi:
"""AddHost WS API class."""
def addNodes(self, addNodesRequest):
"""Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException"""
<|body_0|>
def getStatus(self, session=None, startMessage=0, getNodes=False):
"... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddHostWsApi:
"""AddHost WS API class."""
def addNodes(self, addNodesRequest):
"""Main entry point into adding nodes. Returns: addhost session Throws: RuleNotFound TortugaException"""
try:
responseDict = self.post('nodes/', {'node': addNodesRequest})
return respons... | the_stack_v2_python_sparse | src/core/src/tortuga/wsapi/addHostWsApi.py | UnivaCorporation/tortuga | train | 33 |
63168702585b1f378761edd54d74c072f66f09c6 | [
"self.ris_widget = rw\nwidth_estimator = worm_widths.WidthEstimator.from_default_widths(pixels_per_micron=pixels_per_micron)\nself.pose_annotator = pose_annotation.PoseAnnotation(self.ris_widget, width_estimator=width_estimator)\nself.ris_widget.add_annotator([self.pose_annotator])\nload_data = Qt.QPushButton('Load... | <|body_start_0|>
self.ris_widget = rw
width_estimator = worm_widths.WidthEstimator.from_default_widths(pixels_per_micron=pixels_per_micron)
self.pose_annotator = pose_annotation.PoseAnnotation(self.ris_widget, width_estimator=width_estimator)
self.ris_widget.add_annotator([self.pose_anno... | GeneralPoseAnnotator | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's n... | stack_v2_sparse_classes_36k_train_004123 | 4,938 | permissive | [
{
"docstring": "Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's name. Straight worm images are also saved out as png files. If widthes are specified ... | 3 | stack_v2_sparse_classes_30k_train_012639 | Implement the Python class `GeneralPoseAnnotator` described below.
Class description:
Implement the GeneralPoseAnnotator class.
Method signatures and docstrings:
- def __init__(self, rw, pixels_per_micron=1 / 1.3): Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. A... | Implement the Python class `GeneralPoseAnnotator` described below.
Class description:
Implement the GeneralPoseAnnotator class.
Method signatures and docstrings:
- def __init__(self, rw, pixels_per_micron=1 / 1.3): Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. A... | e7ea26dc005f71b50f25230e1d42cdf470859e29 | <|skeleton|>
class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's n... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GeneralPoseAnnotator:
def __init__(self, rw, pixels_per_micron=1 / 1.3):
"""Set up a GUI for annotating poses in an environment that might be different from the one ZP Lab uses. Annotations for each image in the flipbook are loaded an saved into a pickle file named based on the image's name. Straight ... | the_stack_v2_python_sparse | elegant/gui/general_pose_annotator.py | estbiostudent/elegant | train | 0 | |
3cfea16d81c9909cf7fcc639349db321ec994982 | [
"resource = getid(resource)\nif subresource:\n subresource = getid(subresource)\n resource = f'{resource}{self.subresource_path}/{subresource}'\nreturn self._get(f'{self.resource_path}/{resource}/metadata', 'metadata')",
"body = {'metadata': metadata}\nresource = getid(resource)\nif subresource:\n subres... | <|body_start_0|>
resource = getid(resource)
if subresource:
subresource = getid(subresource)
resource = f'{resource}{self.subresource_path}/{subresource}'
return self._get(f'{self.resource_path}/{resource}/metadata', 'metadata')
<|end_body_0|>
<|body_start_1|>
bo... | Provides extended behavior to objects to handle key=value metadata. | MetadataCapableManager | [
"BSD-3-Clause",
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MetadataCapableManager:
"""Provides extended behavior to objects to handle key=value metadata."""
def get_metadata(self, resource, subresource=None):
"""Get metadata of a resource. :param resource: either resource object or text with its ID. :param subresource: either a child resourc... | stack_v2_sparse_classes_36k_train_004124 | 18,336 | permissive | [
{
"docstring": "Get metadata of a resource. :param resource: either resource object or text with its ID. :param subresource: either a child resource object or text with its ID",
"name": "get_metadata",
"signature": "def get_metadata(self, resource, subresource=None)"
},
{
"docstring": "Set or up... | 4 | stack_v2_sparse_classes_30k_train_008757 | Implement the Python class `MetadataCapableManager` described below.
Class description:
Provides extended behavior to objects to handle key=value metadata.
Method signatures and docstrings:
- def get_metadata(self, resource, subresource=None): Get metadata of a resource. :param resource: either resource object or tex... | Implement the Python class `MetadataCapableManager` described below.
Class description:
Provides extended behavior to objects to handle key=value metadata.
Method signatures and docstrings:
- def get_metadata(self, resource, subresource=None): Get metadata of a resource. :param resource: either resource object or tex... | 2cdbf4eccb2bb551c67e8da10c0e6bf5887e663d | <|skeleton|>
class MetadataCapableManager:
"""Provides extended behavior to objects to handle key=value metadata."""
def get_metadata(self, resource, subresource=None):
"""Get metadata of a resource. :param resource: either resource object or text with its ID. :param subresource: either a child resourc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MetadataCapableManager:
"""Provides extended behavior to objects to handle key=value metadata."""
def get_metadata(self, resource, subresource=None):
"""Get metadata of a resource. :param resource: either resource object or text with its ID. :param subresource: either a child resource object or t... | the_stack_v2_python_sparse | manilaclient/base.py | openstack/python-manilaclient | train | 38 |
073961f1b3c7f559cf9b661cbea2c74a2baa1bf4 | [
"try:\n user = getUser(request.session.get('login'))\n ago = request.GET.get('ago')\n page = request.GET.get('page')\n three_month_ago = get_three_month_ago()\n if ago:\n tailwindTake = TailwindTakeOrder.objects.filter(Q(mandatory=user) & Q(create_time__lte=three_month_ago))\n else:\n ... | <|body_start_0|>
try:
user = getUser(request.session.get('login'))
ago = request.GET.get('ago')
page = request.GET.get('page')
three_month_ago = get_three_month_ago()
if ago:
tailwindTake = TailwindTakeOrder.objects.filter(Q(mandatory=u... | 用户对接受单的一系列操作 | UserTailwindTakeOrderView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTailwindTakeOrderView:
"""用户对接受单的一系列操作"""
def get(self, request):
"""获取用户的所有接收单 :param request: :return:"""
<|body_0|>
def put(self, request, rid):
"""用户接单 :param request: :param rid: request id :return:"""
<|body_1|>
def delete(self, request, ri... | stack_v2_sparse_classes_36k_train_004125 | 5,314 | no_license | [
{
"docstring": "获取用户的所有接收单 :param request: :return:",
"name": "get",
"signature": "def get(self, request)"
},
{
"docstring": "用户接单 :param request: :param rid: request id :return:",
"name": "put",
"signature": "def put(self, request, rid)"
},
{
"docstring": "用户撤销接受单 :param request... | 3 | stack_v2_sparse_classes_30k_train_013694 | Implement the Python class `UserTailwindTakeOrderView` described below.
Class description:
用户对接受单的一系列操作
Method signatures and docstrings:
- def get(self, request): 获取用户的所有接收单 :param request: :return:
- def put(self, request, rid): 用户接单 :param request: :param rid: request id :return:
- def delete(self, request, rid): ... | Implement the Python class `UserTailwindTakeOrderView` described below.
Class description:
用户对接受单的一系列操作
Method signatures and docstrings:
- def get(self, request): 获取用户的所有接收单 :param request: :return:
- def put(self, request, rid): 用户接单 :param request: :param rid: request id :return:
- def delete(self, request, rid): ... | bcfbfb71bac696695ec98ac7796fea8262e5af8a | <|skeleton|>
class UserTailwindTakeOrderView:
"""用户对接受单的一系列操作"""
def get(self, request):
"""获取用户的所有接收单 :param request: :return:"""
<|body_0|>
def put(self, request, rid):
"""用户接单 :param request: :param rid: request id :return:"""
<|body_1|>
def delete(self, request, ri... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class UserTailwindTakeOrderView:
"""用户对接受单的一系列操作"""
def get(self, request):
"""获取用户的所有接收单 :param request: :return:"""
try:
user = getUser(request.session.get('login'))
ago = request.GET.get('ago')
page = request.GET.get('page')
three_month_ago = g... | the_stack_v2_python_sparse | App/Account/views/restFul/userTailwindInfo/userTailwindBaseInfo/userTailwindTakeOrderInfo.py | DICKQI/UTime_BackEnd | train | 0 |
c6881ac3ba757298c7ee25369af64002ab0af24e | [
"self.position = pos\nself.direction = direction\nself.right = right",
"u_v = []\nif leaf_type < 0:\n if leaf_type < -3:\n leaf_type = -1\n shape = leaf_geom.blossom(abs(leaf_type + 1))\nelse:\n if leaf_type < 1 or leaf_type > 10:\n leaf_type = 8\n shape = leaf_geom.leaves(leaf_type - 1)... | <|body_start_0|>
self.position = pos
self.direction = direction
self.right = right
<|end_body_0|>
<|body_start_1|>
u_v = []
if leaf_type < 0:
if leaf_type < -3:
leaf_type = -1
shape = leaf_geom.blossom(abs(leaf_type + 1))
else:
... | Class to store data for each leaf in the system | Leaf | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Leaf:
"""Class to store data for each leaf in the system"""
def __init__(self, pos, direction, right):
"""Init method for leaf with position, direction and relative x axis"""
<|body_0|>
def get_shape(cls, leaf_type, g_scale, scale, scale_x):
"""returns the base l... | stack_v2_sparse_classes_36k_train_004126 | 3,470 | no_license | [
{
"docstring": "Init method for leaf with position, direction and relative x axis",
"name": "__init__",
"signature": "def __init__(self, pos, direction, right)"
},
{
"docstring": "returns the base leaf shape mesh",
"name": "get_shape",
"signature": "def get_shape(cls, leaf_type, g_scale,... | 4 | stack_v2_sparse_classes_30k_train_007226 | Implement the Python class `Leaf` described below.
Class description:
Class to store data for each leaf in the system
Method signatures and docstrings:
- def __init__(self, pos, direction, right): Init method for leaf with position, direction and relative x axis
- def get_shape(cls, leaf_type, g_scale, scale, scale_x... | Implement the Python class `Leaf` described below.
Class description:
Class to store data for each leaf in the system
Method signatures and docstrings:
- def __init__(self, pos, direction, right): Init method for leaf with position, direction and relative x axis
- def get_shape(cls, leaf_type, g_scale, scale, scale_x... | 7b796d30dfd22b7706a93e4419ed913d18d29a44 | <|skeleton|>
class Leaf:
"""Class to store data for each leaf in the system"""
def __init__(self, pos, direction, right):
"""Init method for leaf with position, direction and relative x axis"""
<|body_0|>
def get_shape(cls, leaf_type, g_scale, scale, scale_x):
"""returns the base l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Leaf:
"""Class to store data for each leaf in the system"""
def __init__(self, pos, direction, right):
"""Init method for leaf with position, direction and relative x axis"""
self.position = pos
self.direction = direction
self.right = right
def get_shape(cls, leaf_typ... | the_stack_v2_python_sparse | All_In_One/addons/learnbgame/ch_trees/leaf.py | 2434325680/Learnbgame | train | 0 |
906366a11bed81d12b5fb926bdd1d88de7927e6e | [
"stack, res, multi = ([], '', 0)\nfor c in s:\n if c == '[':\n stack.append([multi, res])\n res, multi = ('', 0)\n elif c == ']':\n cur_multi, last_res = stack.pop()\n res = last_res + cur_multi * res\n elif '0' <= c <= '9':\n multi = multi * 10 + int(c)\n else:\n ... | <|body_start_0|>
stack, res, multi = ([], '', 0)
for c in s:
if c == '[':
stack.append([multi, res])
res, multi = ('', 0)
elif c == ']':
cur_multi, last_res = stack.pop()
res = last_res + cur_multi * res
... | Solution | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def decodeString_1(self, s: str) -> str:
"""解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:"""
<|body_0|>
def decodeString_2(self, s: str) -> str:
"""解法二:递归法 时间复杂度 O(N),递归会更新索引,因此实际上还是一次遍历 s; 空间复杂度 O(N),极端情况下递归深度将会达到... | stack_v2_sparse_classes_36k_train_004127 | 2,627 | permissive | [
{
"docstring": "解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:",
"name": "decodeString_1",
"signature": "def decodeString_1(self, s: str) -> str"
},
{
"docstring": "解法二:递归法 时间复杂度 O(N),递归会更新索引,因此实际上还是一次遍历 s; 空间复杂度 O(N),极端情况下递归深度将会达到线性级别。 :param s: :return... | 2 | stack_v2_sparse_classes_30k_train_014256 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString_1(self, s: str) -> str: 解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:
- def decodeString_2(self, s: str) -> str: 解法二:递... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def decodeString_1(self, s: str) -> str: 解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:
- def decodeString_2(self, s: str) -> str: 解法二:递... | 62419b49000e79962bcdc99cd98afd2fb82ea345 | <|skeleton|>
class Solution:
def decodeString_1(self, s: str) -> str:
"""解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:"""
<|body_0|>
def decodeString_2(self, s: str) -> str:
"""解法二:递归法 时间复杂度 O(N),递归会更新索引,因此实际上还是一次遍历 s; 空间复杂度 O(N),极端情况下递归深度将会达到... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def decodeString_1(self, s: str) -> str:
"""解法一:辅助栈法 时间复杂度 O(N),一次遍历 s; 空间复杂度 O(N),辅助栈在极端情况下需要线性空间,例如 2[2[2[a]]]。 :param s: :return:"""
stack, res, multi = ([], '', 0)
for c in s:
if c == '[':
stack.append([multi, res])
res, multi =... | the_stack_v2_python_sparse | LeetCode 热题 HOT 100/decodeString.py | MaoningGuan/LeetCode | train | 3 | |
c1c4996e607f5d40cd9cc038b76dc0dea9f2f652 | [
"Parametre.__init__(self, 'voir', 'view')\nself.schema = '<cle> <nombre>'\nself.aide_courte = \"affiche le détail d'une structure\"\nself.aide_longue = \"Cette commande affiche le détail d'une structure. Vous devez préciser deux paramètres séparés par un espace : le premier est la clé du groupe, le second est l'ide... | <|body_start_0|>
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle> <nombre>'
self.aide_courte = "affiche le détail d'une structure"
self.aide_longue = "Cette commande affiche le détail d'une structure. Vous devez préciser deux paramètres séparés par un espace : le premier est... | Commande 'structures voir' | PrmVoir | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PrmVoir:
"""Commande 'structures voir'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
Pa... | stack_v2_sparse_classes_36k_train_004128 | 4,296 | permissive | [
{
"docstring": "Constructeur du paramètre.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Méthode d'interprétation de commande.",
"name": "interpreter",
"signature": "def interpreter(self, personnage, dic_masques)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006580 | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'structures voir'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande. | Implement the Python class `PrmVoir` described below.
Class description:
Commande 'structures voir'
Method signatures and docstrings:
- def __init__(self): Constructeur du paramètre.
- def interpreter(self, personnage, dic_masques): Méthode d'interprétation de commande.
<|skeleton|>
class PrmVoir:
"""Commande 's... | 7e93bff08cdf891352efba587e89c40f3b4a2301 | <|skeleton|>
class PrmVoir:
"""Commande 'structures voir'"""
def __init__(self):
"""Constructeur du paramètre."""
<|body_0|>
def interpreter(self, personnage, dic_masques):
"""Méthode d'interprétation de commande."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PrmVoir:
"""Commande 'structures voir'"""
def __init__(self):
"""Constructeur du paramètre."""
Parametre.__init__(self, 'voir', 'view')
self.schema = '<cle> <nombre>'
self.aide_courte = "affiche le détail d'une structure"
self.aide_longue = "Cette commande affiche ... | the_stack_v2_python_sparse | src/primaires/scripting/commandes/structure/voir.py | vincent-lg/tsunami | train | 5 |
a5a961f7f44286f480abaced4f2e166e027ac12c | [
"self._residues = []\ncoordinates = []\nself.tree = None\nfor residue, coordinate in generator:\n if len(coordinate) > 0:\n coordinates.append(coordinate)\n self._residues.append(residue)\nif coordinates:\n self.tree = sp.cKDTree(coordinates)",
"if not self.tree:\n return 0\nreturn self.tre... | <|body_start_0|>
self._residues = []
coordinates = []
self.tree = None
for residue, coordinate in generator:
if len(coordinate) > 0:
coordinates.append(coordinate)
self._residues.append(residue)
if coordinates:
self.tree = s... | This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list. | CoordinateTree | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CoordinateTree:
"""This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list."""
def __init__(self, generator):
"""Create a new CoordinateTree. The given generator should yield 2 values each time, the residue and a coordinate to use for it.... | stack_v2_sparse_classes_36k_train_004129 | 10,482 | no_license | [
{
"docstring": "Create a new CoordinateTree. The given generator should yield 2 values each time, the residue and a coordinate to use for it. This may yield the same residue many times but should not duplicate coordinate values. :param iterable generator: The generator to use.",
"name": "__init__",
"sig... | 5 | null | Implement the Python class `CoordinateTree` described below.
Class description:
This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list.
Method signatures and docstrings:
- def __init__(self, generator): Create a new CoordinateTree. The given generator should yield 2 valu... | Implement the Python class `CoordinateTree` described below.
Class description:
This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list.
Method signatures and docstrings:
- def __init__(self, generator): Create a new CoordinateTree. The given generator should yield 2 valu... | fa55c9975ad93a8764b54f99e3d92f52cabc737d | <|skeleton|>
class CoordinateTree:
"""This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list."""
def __init__(self, generator):
"""Create a new CoordinateTree. The given generator should yield 2 values each time, the residue and a coordinate to use for it.... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CoordinateTree:
"""This is a simple wrapper around scipy's KDTree to return components instead of just indexes in a list."""
def __init__(self, generator):
"""Create a new CoordinateTree. The given generator should yield 2 values each time, the residue and a coordinate to use for it. This may yie... | the_stack_v2_python_sparse | fr3d/data/base.py | BGSU-RNA/fr3d-python | train | 14 |
670549b58a047804b987d2372be6a183d349aa92 | [
"couponInfoDict = self.getDictBykey(self.getSellListByPage(parkName), 'tmpName', refundCouponName)\nself.url = '/mgr/coupon/sell/refund.do'\ndata = {'id': couponInfoDict['id'], 'sellMoney': couponInfoDict['sellMoney'], 'payMoney': couponInfoDict['sellMoney'], 'actPayMoney': couponInfoDict['sellMoney'], 'refundMoney... | <|body_start_0|>
couponInfoDict = self.getDictBykey(self.getSellListByPage(parkName), 'tmpName', refundCouponName)
self.url = '/mgr/coupon/sell/refund.do'
data = {'id': couponInfoDict['id'], 'sellMoney': couponInfoDict['sellMoney'], 'payMoney': couponInfoDict['sellMoney'], 'actPayMoney': couponI... | 售卖管理 | SellManage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SellManage:
"""售卖管理"""
def couponRefund(self, parkName, refundCouponName):
"""优惠劵退款"""
<|body_0|>
def __getParkingBaseDataTree(self):
"""获取当前用户车场"""
<|body_1|>
def getSellListByPage(self, parkName):
"""获取售卖记录"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k_train_004130 | 1,722 | no_license | [
{
"docstring": "优惠劵退款",
"name": "couponRefund",
"signature": "def couponRefund(self, parkName, refundCouponName)"
},
{
"docstring": "获取当前用户车场",
"name": "__getParkingBaseDataTree",
"signature": "def __getParkingBaseDataTree(self)"
},
{
"docstring": "获取售卖记录",
"name": "getSellLi... | 3 | stack_v2_sparse_classes_30k_train_018692 | Implement the Python class `SellManage` described below.
Class description:
售卖管理
Method signatures and docstrings:
- def couponRefund(self, parkName, refundCouponName): 优惠劵退款
- def __getParkingBaseDataTree(self): 获取当前用户车场
- def getSellListByPage(self, parkName): 获取售卖记录 | Implement the Python class `SellManage` described below.
Class description:
售卖管理
Method signatures and docstrings:
- def couponRefund(self, parkName, refundCouponName): 优惠劵退款
- def __getParkingBaseDataTree(self): 获取当前用户车场
- def getSellListByPage(self, parkName): 获取售卖记录
<|skeleton|>
class SellManage:
"""售卖管理"""
... | 34c368c109867da26d9256bca85f872b0fac2ea7 | <|skeleton|>
class SellManage:
"""售卖管理"""
def couponRefund(self, parkName, refundCouponName):
"""优惠劵退款"""
<|body_0|>
def __getParkingBaseDataTree(self):
"""获取当前用户车场"""
<|body_1|>
def getSellListByPage(self, parkName):
"""获取售卖记录"""
<|body_2|>
<|end_skel... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SellManage:
"""售卖管理"""
def couponRefund(self, parkName, refundCouponName):
"""优惠劵退款"""
couponInfoDict = self.getDictBykey(self.getSellListByPage(parkName), 'tmpName', refundCouponName)
self.url = '/mgr/coupon/sell/refund.do'
data = {'id': couponInfoDict['id'], 'sellMoney':... | the_stack_v2_python_sparse | Api/parkingManage_service/businessCoupon_service/sellManage.py | oyebino/pomp_api | train | 1 |
0a8afe84745026f03d60ab9a6ad869fabef3488d | [
"self.redshift = float(self.parameters['redshift'])\nif self.redshift < 0.0:\n raise Exception('The redshift provided is negative <{}>.'.format(self.redshift))\nself.universe_age = cosmology.age(self.redshift).value * 1000.0\nif self.redshift == 0.0:\n self.luminosity_distance = 10.0 * parsec\nelse:\n self... | <|body_start_0|>
self.redshift = float(self.parameters['redshift'])
if self.redshift < 0.0:
raise Exception('The redshift provided is negative <{}>.'.format(self.redshift))
self.universe_age = cosmology.age(self.redshift).value * 1000.0
if self.redshift == 0.0:
se... | Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised. | Redshifting | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Redshifting:
"""Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised."""
def _init_code(self):
"""Compute the age of the Universe at a given redshift"""
<|body_0|>
def process(self, sed):
"""Redshift the S... | stack_v2_sparse_classes_36k_train_004131 | 8,027 | no_license | [
{
"docstring": "Compute the age of the Universe at a given redshift",
"name": "_init_code",
"signature": "def _init_code(self)"
},
{
"docstring": "Redshift the SED Parameters ---------- sed: pcigale.sed.SED object",
"name": "process",
"signature": "def process(self, sed)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000877 | Implement the Python class `Redshifting` described below.
Class description:
Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised.
Method signatures and docstrings:
- def _init_code(self): Compute the age of the Universe at a given redshift
- def process(self,... | Implement the Python class `Redshifting` described below.
Class description:
Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised.
Method signatures and docstrings:
- def _init_code(self): Compute the age of the Universe at a given redshift
- def process(self,... | 9ef9b99425537350b8706fddfe90ed47301107a5 | <|skeleton|>
class Redshifting:
"""Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised."""
def _init_code(self):
"""Compute the age of the Universe at a given redshift"""
<|body_0|>
def process(self, sed):
"""Redshift the S... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Redshifting:
"""Redshift a SED This module redshift a rest-frame SED. If the SED is already redshifted, an exception is raised."""
def _init_code(self):
"""Compute the age of the Universe at a given redshift"""
self.redshift = float(self.parameters['redshift'])
if self.redshift < ... | the_stack_v2_python_sparse | pcigale/sed_modules/redshifting.py | JohannesBuchner/cigale | train | 5 |
87f9bc2cc21161147282b950d4db9195437478eb | [
"server = helpers.get_odoo_server_url()\nif server:\n subject = helpers.read_file_first_line('odoo-subject.conf')\n if subject:\n domain = helpers.get_ip().replace('.', '-') + subject.strip('*')\n else:\n domain = helpers.get_ip()\n iot_box = {'name': socket.gethostname(), 'identifier': he... | <|body_start_0|>
server = helpers.get_odoo_server_url()
if server:
subject = helpers.read_file_first_line('odoo-subject.conf')
if subject:
domain = helpers.get_ip().replace('.', '-') + subject.strip('*')
else:
domain = helpers.get_ip()
... | Manager | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Manager:
def send_alldevices(self):
"""This method send IoT Box and devices informations to Odoo database"""
<|body_0|>
def run(self):
"""Thread that will load interfaces and drivers and contact the odoo server with the updates"""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_004132 | 3,557 | permissive | [
{
"docstring": "This method send IoT Box and devices informations to Odoo database",
"name": "send_alldevices",
"signature": "def send_alldevices(self)"
},
{
"docstring": "Thread that will load interfaces and drivers and contact the odoo server with the updates",
"name": "run",
"signatur... | 2 | stack_v2_sparse_classes_30k_train_009730 | Implement the Python class `Manager` described below.
Class description:
Implement the Manager class.
Method signatures and docstrings:
- def send_alldevices(self): This method send IoT Box and devices informations to Odoo database
- def run(self): Thread that will load interfaces and drivers and contact the odoo ser... | Implement the Python class `Manager` described below.
Class description:
Implement the Manager class.
Method signatures and docstrings:
- def send_alldevices(self): This method send IoT Box and devices informations to Odoo database
- def run(self): Thread that will load interfaces and drivers and contact the odoo ser... | 310497a9872db7844b521e6dab5f7a9f61d365a4 | <|skeleton|>
class Manager:
def send_alldevices(self):
"""This method send IoT Box and devices informations to Odoo database"""
<|body_0|>
def run(self):
"""Thread that will load interfaces and drivers and contact the odoo server with the updates"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Manager:
def send_alldevices(self):
"""This method send IoT Box and devices informations to Odoo database"""
server = helpers.get_odoo_server_url()
if server:
subject = helpers.read_file_first_line('odoo-subject.conf')
if subject:
domain = helper... | the_stack_v2_python_sparse | addons/hw_drivers/main.py | SHIVJITH/Odoo_Machine_Test | train | 0 | |
f68265cc4ce80d8d7e6b9f53e3c028ec2315ea9e | [
"self.shoebox_count = shoebox_count\nself.input_directory = input_directory\nself.output_directory = output_directory",
"rank = percentileofscore(overlap_list, overlap)\nif rank < 20:\n label = 'low'\nelif rank < 80:\n label = 'medium'\nelse:\n label = 'high'\nreturn (label, rank)",
"labels = [label_t,... | <|body_start_0|>
self.shoebox_count = shoebox_count
self.input_directory = input_directory
self.output_directory = output_directory
<|end_body_0|>
<|body_start_1|>
rank = percentileofscore(overlap_list, overlap)
if rank < 20:
label = 'low'
elif rank < 80:
... | OverlapClassifier | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OverlapClassifier:
def __init__(self, shoebox_count, input_directory, output_directory):
"""Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the overlaps per shoebox should be classified. (default=True) :param str input_directory: path to input direc... | stack_v2_sparse_classes_36k_train_004133 | 6,503 | permissive | [
{
"docstring": "Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the overlaps per shoebox should be classified. (default=True) :param str input_directory: path to input directory (default=cwd) :param str output_directory: path to output directory (default=cwd)",
"name":... | 6 | stack_v2_sparse_classes_30k_val_000369 | Implement the Python class `OverlapClassifier` described below.
Class description:
Implement the OverlapClassifier class.
Method signatures and docstrings:
- def __init__(self, shoebox_count, input_directory, output_directory): Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the... | Implement the Python class `OverlapClassifier` described below.
Class description:
Implement the OverlapClassifier class.
Method signatures and docstrings:
- def __init__(self, shoebox_count, input_directory, output_directory): Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the... | 064e30d9d7ec8c08f60c486cf9d6c48cca6562b5 | <|skeleton|>
class OverlapClassifier:
def __init__(self, shoebox_count, input_directory, output_directory):
"""Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the overlaps per shoebox should be classified. (default=True) :param str input_directory: path to input direc... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OverlapClassifier:
def __init__(self, shoebox_count, input_directory, output_directory):
"""Initialising an overlap classifier. :param bool shoebox_count: Boolean that decides if the overlaps per shoebox should be classified. (default=True) :param str input_directory: path to input directory (default=... | the_stack_v2_python_sparse | src/iolite/classification/classify_overlaps.py | egrahl/iolite | train | 0 | |
9796a40d6b3946ffeeb4989b72535ce12509c877 | [
"super(HopeNet, self).__init__()\nself.inplanes = 64\nself.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\nself.bn1 = nn.BatchNorm2d(64)\nself.relu = nn.ReLU(inplace=True)\nself.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\nself.layer1 = self._make_layer(block, 64, layers[0])... | <|body_start_0|>
super(HopeNet, self).__init__()
self.inplanes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1... | Implements HopeNet, used for estimating the head pose from media (images and videos). | HopeNet | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HopeNet:
"""Implements HopeNet, used for estimating the head pose from media (images and videos)."""
def __init__(self, block, layers, n_bins):
"""Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of lay... | stack_v2_sparse_classes_36k_train_004134 | 9,784 | no_license | [
{
"docstring": "Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of layer sizes for each ``block`` object. n_bins : int The number of bins in the yaw, pitch, and roll outputs. Increase this number to have a finer estimate. Returns... | 3 | stack_v2_sparse_classes_30k_train_001185 | Implement the Python class `HopeNet` described below.
Class description:
Implements HopeNet, used for estimating the head pose from media (images and videos).
Method signatures and docstrings:
- def __init__(self, block, layers, n_bins): Instantiates a HopeNet object used for estimating head pose from media. Paramete... | Implement the Python class `HopeNet` described below.
Class description:
Implements HopeNet, used for estimating the head pose from media (images and videos).
Method signatures and docstrings:
- def __init__(self, block, layers, n_bins): Instantiates a HopeNet object used for estimating head pose from media. Paramete... | a7c30481822ecb945e3ff6ad184d104361a40ed1 | <|skeleton|>
class HopeNet:
"""Implements HopeNet, used for estimating the head pose from media (images and videos)."""
def __init__(self, block, layers, n_bins):
"""Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of lay... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HopeNet:
"""Implements HopeNet, used for estimating the head pose from media (images and videos)."""
def __init__(self, block, layers, n_bins):
"""Instantiates a HopeNet object used for estimating head pose from media. Parameters ---------- block : layers : list (of ints) List of layer sizes for ... | the_stack_v2_python_sparse | cheapfake/hopenet/models.py | hu-simon/cheapfake | train | 0 |
32f9fc211415533ba735afb2c85b8ad32838755c | [
"options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeholders_data['login_url']}\ncontext = Context(options)\ntemplate = Template(email_template)\nemailContent = template.render(context)\nreturn ... | <|body_start_0|>
options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeholders_data['login_url']}
context = Context(options)
template = Template(email_template)
emailCo... | SendEmailUtil | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
<|body_0|>
def sending_mail(self, user, email_template, subject):
"""sending email"""
<|body_1|>
def generate_reset_password_link(self,... | stack_v2_sparse_classes_36k_train_004135 | 3,262 | no_license | [
{
"docstring": "Preparing email content",
"name": "_get_html_content_for_email",
"signature": "def _get_html_content_for_email(self, email_template, placeholders_data)"
},
{
"docstring": "sending email",
"name": "sending_mail",
"signature": "def sending_mail(self, user, email_template, s... | 3 | null | Implement the Python class `SendEmailUtil` described below.
Class description:
Implement the SendEmailUtil class.
Method signatures and docstrings:
- def _get_html_content_for_email(self, email_template, placeholders_data): Preparing email content
- def sending_mail(self, user, email_template, subject): sending email... | Implement the Python class `SendEmailUtil` described below.
Class description:
Implement the SendEmailUtil class.
Method signatures and docstrings:
- def _get_html_content_for_email(self, email_template, placeholders_data): Preparing email content
- def sending_mail(self, user, email_template, subject): sending email... | 5d5bc4c1eecbf627d38260e4d314d8451d67a4f5 | <|skeleton|>
class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
<|body_0|>
def sending_mail(self, user, email_template, subject):
"""sending email"""
<|body_1|>
def generate_reset_password_link(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SendEmailUtil:
def _get_html_content_for_email(self, email_template, placeholders_data):
"""Preparing email content"""
options = {'name': placeholders_data['recipient_name'], 'action_url': placeholders_data['action_url'], 'support_email': placeholders_data['support_email'], 'login_url': placeh... | the_stack_v2_python_sparse | curation-api/src/users/utils.py | mohanj1919/django_app_test | train | 0 | |
756f0e44b9617e1f4949bf55f8ff00207b2aba13 | [
"self.model_dir = os.path.join(self.directory, 'novel')\nself.conf_file = 'lda.conf'\nself.__engine = InferenceEngine(self.model_dir, self.conf_file)\nself.vocab_path = os.path.join(self.model_dir, 'vocab_info.txt')\nlac = hub.Module(name='lac')\nself.__tokenizer = LACTokenizer(self.vocab_path, lac)\nself.vocabular... | <|body_start_0|>
self.model_dir = os.path.join(self.directory, 'novel')
self.conf_file = 'lda.conf'
self.__engine = InferenceEngine(self.model_dir, self.conf_file)
self.vocab_path = os.path.join(self.model_dir, 'vocab_info.txt')
lac = hub.Module(name='lac')
self.__tokeniz... | TopicModel | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
<|body_0|>
def cal_doc_distance(self, doc_text1, doc_text2):
"""This interface calculates the distance between documents. Args: doc_text1(str): the input document text 1. doc_text2(str):... | stack_v2_sparse_classes_36k_train_004136 | 6,780 | permissive | [
{
"docstring": "Initialize with the necessary elements.",
"name": "_initialize",
"signature": "def _initialize(self)"
},
{
"docstring": "This interface calculates the distance between documents. Args: doc_text1(str): the input document text 1. doc_text2(str): the input document text 2. Returns: ... | 6 | null | Implement the Python class `TopicModel` described below.
Class description:
Implement the TopicModel class.
Method signatures and docstrings:
- def _initialize(self): Initialize with the necessary elements.
- def cal_doc_distance(self, doc_text1, doc_text2): This interface calculates the distance between documents. A... | Implement the Python class `TopicModel` described below.
Class description:
Implement the TopicModel class.
Method signatures and docstrings:
- def _initialize(self): Initialize with the necessary elements.
- def cal_doc_distance(self, doc_text1, doc_text2): This interface calculates the distance between documents. A... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
<|body_0|>
def cal_doc_distance(self, doc_text1, doc_text2):
"""This interface calculates the distance between documents. Args: doc_text1(str): the input document text 1. doc_text2(str):... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TopicModel:
def _initialize(self):
"""Initialize with the necessary elements."""
self.model_dir = os.path.join(self.directory, 'novel')
self.conf_file = 'lda.conf'
self.__engine = InferenceEngine(self.model_dir, self.conf_file)
self.vocab_path = os.path.join(self.model_... | the_stack_v2_python_sparse | modules/text/language_model/lda_novel/module.py | PaddlePaddle/PaddleHub | train | 12,914 | |
367db951532abf6f3aaf919b714383cb3f708cb4 | [
"profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.dimension.html', self)\nself.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Dimension', self, '')\nself.openWikiManualHelpPage = settings.HelpPage().getOpenFromAbsolute('h... | <|body_start_0|>
profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.dimension.html', self)
self.fileNameInput = settings.FileNameInput().getFromFileName(interpret.getGNUTranslatorGcodeFileTypeTuples(), 'Open File for Dimension', self, '')
self.openWikiManualHelpPage = settings... | A class to handle the dimension settings. | DimensionRepository | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DimensionRepository:
"""A class to handle the dimension settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Dimension button has been clicked."""
<|body_1|>
<|end_skeleton|>... | stack_v2_sparse_classes_36k_train_004137 | 10,249 | no_license | [
{
"docstring": "Set the default settings, execute title & settings fileName.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Dimension button has been clicked.",
"name": "execute",
"signature": "def execute(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_006118 | Implement the Python class `DimensionRepository` described below.
Class description:
A class to handle the dimension settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Dimension button has been clicked. | Implement the Python class `DimensionRepository` described below.
Class description:
A class to handle the dimension settings.
Method signatures and docstrings:
- def __init__(self): Set the default settings, execute title & settings fileName.
- def execute(self): Dimension button has been clicked.
<|skeleton|>
clas... | fd69d8e856780c826386dc973ceabcc03623f3e8 | <|skeleton|>
class DimensionRepository:
"""A class to handle the dimension settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
<|body_0|>
def execute(self):
"""Dimension button has been clicked."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DimensionRepository:
"""A class to handle the dimension settings."""
def __init__(self):
"""Set the default settings, execute title & settings fileName."""
profile.addListsToCraftTypeRepository('skeinforge_tools.craft_plugins.dimension.html', self)
self.fileNameInput = settings.Fi... | the_stack_v2_python_sparse | skeinforge_tools/craft_plugins/dimension.py | bmander/skeinforge | train | 34 |
e437b897c6950f2cf3b8d0efc395623b1703cbdb | [
"self.conv3d_k_width = conv3d_k_width\nsuper().__init__(name, hyperparameter_config=hyperparameter_config, spatial_scale=spatial_scale)\nself.setup_children()\npass",
"for blockset in self.children:\n for i, block in enumerate(blockset.children):\n if block.hyperparam('spatial_scale') < 2:\n ... | <|body_start_0|>
self.conv3d_k_width = conv3d_k_width
super().__init__(name, hyperparameter_config=hyperparameter_config, spatial_scale=spatial_scale)
self.setup_children()
pass
<|end_body_0|>
<|body_start_1|>
for blockset in self.children:
for i, block in enumerate(... | Mixed3DEncoderDecoderGene | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Mixed3DEncoderDecoderGene:
def __init__(self, name: str, conv3d_k_width: int=3, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. conv3d_k_width (Sequence[int]): Spatial width of the block-initial con... | stack_v2_sparse_classes_36k_train_004138 | 2,906 | no_license | [
{
"docstring": "Constructor. Args: name (str): This gene's name. conv3d_k_width (Sequence[int]): Spatial width of the block-initial conv3d layer kernels. hyperparameter_config (Optional[mt.HyperparameterConfig]): The HyperparameterConfig governing this Gene's hyperparameters. If none is supplied, use genenet.hy... | 2 | stack_v2_sparse_classes_30k_train_014031 | Implement the Python class `Mixed3DEncoderDecoderGene` described below.
Class description:
Implement the Mixed3DEncoderDecoderGene class.
Method signatures and docstrings:
- def __init__(self, name: str, conv3d_k_width: int=3, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0): Const... | Implement the Python class `Mixed3DEncoderDecoderGene` described below.
Class description:
Implement the Mixed3DEncoderDecoderGene class.
Method signatures and docstrings:
- def __init__(self, name: str, conv3d_k_width: int=3, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0): Const... | 6b78dc5e1e793a206ae3f4860d3a9ac887e663e5 | <|skeleton|>
class Mixed3DEncoderDecoderGene:
def __init__(self, name: str, conv3d_k_width: int=3, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. conv3d_k_width (Sequence[int]): Spatial width of the block-initial con... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Mixed3DEncoderDecoderGene:
def __init__(self, name: str, conv3d_k_width: int=3, hyperparameter_config: Optional[mt.HyperparameterConfig]=None, spatial_scale: int=0):
"""Constructor. Args: name (str): This gene's name. conv3d_k_width (Sequence[int]): Spatial width of the block-initial conv3d layer kern... | the_stack_v2_python_sparse | example1/src/_private/Mixed3DEncoderDecoderGene.py | leapmanlab/examples | train | 1 | |
bb8d606dd6fab92e7a643bd2ffe8a380187e108f | [
"super(SinusoidalPositionEmbedding, self).__init__(name=name)\nself._dim = dim\nself._cache_steps = cache_steps\nself._reverse_order = reverse_order\nself._clamp_len = clamp_len\nself._inv_freq = 1.0 / 10000 ** (jnp.arange(0, dim, 2).astype(jnp.float32) / dim)",
"full_length = timesteps + self._cache_steps\nif se... | <|body_start_0|>
super(SinusoidalPositionEmbedding, self).__init__(name=name)
self._dim = dim
self._cache_steps = cache_steps
self._reverse_order = reverse_order
self._clamp_len = clamp_len
self._inv_freq = 1.0 / 10000 ** (jnp.arange(0, dim, 2).astype(jnp.float32) / dim)
... | Position encoding, using mixture of sinusoidal signals. | SinusoidalPositionEmbedding | [
"Apache-2.0",
"CC-BY-SA-4.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SinusoidalPositionEmbedding:
"""Position encoding, using mixture of sinusoidal signals."""
def __init__(self, dim: int, cache_steps: int=0, reverse_order: bool=False, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""Initialize a SinusoidalPositionEmbedding. Args: dim: Emb... | stack_v2_sparse_classes_36k_train_004139 | 14,391 | permissive | [
{
"docstring": "Initialize a SinusoidalPositionEmbedding. Args: dim: Embedding dimension. cache_steps: The length of the memory. reverse_order: If set to True, position index is reversed. clamp_len: position beyond clamp_len will be reset to clamp_len, default to not clamping. name: Optional name for this Haiku... | 2 | null | Implement the Python class `SinusoidalPositionEmbedding` described below.
Class description:
Position encoding, using mixture of sinusoidal signals.
Method signatures and docstrings:
- def __init__(self, dim: int, cache_steps: int=0, reverse_order: bool=False, clamp_len: Optional[int]=None, name: Optional[str]=None):... | Implement the Python class `SinusoidalPositionEmbedding` described below.
Class description:
Position encoding, using mixture of sinusoidal signals.
Method signatures and docstrings:
- def __init__(self, dim: int, cache_steps: int=0, reverse_order: bool=False, clamp_len: Optional[int]=None, name: Optional[str]=None):... | a6ef8053380d6aa19aaae14b93f013ae9762d057 | <|skeleton|>
class SinusoidalPositionEmbedding:
"""Position encoding, using mixture of sinusoidal signals."""
def __init__(self, dim: int, cache_steps: int=0, reverse_order: bool=False, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""Initialize a SinusoidalPositionEmbedding. Args: dim: Emb... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SinusoidalPositionEmbedding:
"""Position encoding, using mixture of sinusoidal signals."""
def __init__(self, dim: int, cache_steps: int=0, reverse_order: bool=False, clamp_len: Optional[int]=None, name: Optional[str]=None):
"""Initialize a SinusoidalPositionEmbedding. Args: dim: Embedding dimens... | the_stack_v2_python_sparse | wikigraphs/wikigraphs/model/embedding.py | sethuramanio/deepmind-research | train | 1 |
e45b82ff7692afab42642610824cf7c103d911c7 | [
"self.id = 1\nself.title = title\nself._analyzer = analyzer",
"parameter_dict = aggregation.parameters\nif agg_type:\n parameter_dict['supported_charts'] = agg_type\nelse:\n agg_type = parameter_dict.get('supported_charts')\n if not agg_type:\n agg_type = 'table'\n parameter_dict['supported... | <|body_start_0|>
self.id = 1
self.title = title
self._analyzer = analyzer
<|end_body_0|>
<|body_start_1|>
parameter_dict = aggregation.parameters
if agg_type:
parameter_dict['supported_charts'] = agg_type
else:
agg_type = parameter_dict.get('suppo... | Mocked story object. | Story | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_36k_train_004140 | 31,229 | permissive | [
{
"docstring": "Initialize the story.",
"name": "__init__",
"signature": "def __init__(self, analyzer, title)"
},
{
"docstring": "Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add to the story. agg_type (str): string indicating the type of aggregatio... | 5 | stack_v2_sparse_classes_30k_train_004471 | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | Implement the Python class `Story` described below.
Class description:
Mocked story object.
Method signatures and docstrings:
- def __init__(self, analyzer, title): Initialize the story.
- def add_aggregation(self, aggregation, agg_type=''): Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved... | 24f471b58ca4a87cb053961b5f05c07a544ca7b8 | <|skeleton|>
class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
<|body_0|>
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggregation (Aggregation): Saved aggregation to add t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Story:
"""Mocked story object."""
def __init__(self, analyzer, title):
"""Initialize the story."""
self.id = 1
self.title = title
self._analyzer = analyzer
def add_aggregation(self, aggregation, agg_type=''):
"""Add a saved aggregation to the Story. Args: aggr... | the_stack_v2_python_sparse | test_tools/timesketch/lib/analyzers/interface.py | google/timesketch | train | 2,263 |
e04541ffaf3fd42fb9eafd1b284fd6c1cdff0f20 | [
"super(Pan, self).__init__(image=Pan.image, x=games.mouse.x, bottom=games.screen.height)\nself.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10)\ngames.screen.add(self.score)",
"self.x = games.mouse.x\nif self.left < 0:\n self.left = 0\nif self.right > games.screen.w... | <|body_start_0|>
super(Pan, self).__init__(image=Pan.image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value=0, size=25, color=color.black, top=5, right=games.screen.width - 10)
games.screen.add(self.score)
<|end_body_0|>
<|body_start_1|>
self.x = games.mouse.x... | Сковорода, в которую игрок может ловить падающий бургер. | Pan | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Pan:
"""Сковорода, в которую игрок может ловить падающий бургер."""
def __init__(self):
"""Инициализирует объект Рап и создает объект Text для отображения счета"""
<|body_0|>
def update(self):
"""Передвигает объект по горизонтали"""
<|body_1|>
def ch... | stack_v2_sparse_classes_36k_train_004141 | 5,097 | no_license | [
{
"docstring": "Инициализирует объект Рап и создает объект Text для отображения счета",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Передвигает объект по горизонтали",
"name": "update",
"signature": "def update(self)"
},
{
"docstring": "Проверяет, пой... | 3 | stack_v2_sparse_classes_30k_train_018553 | Implement the Python class `Pan` described below.
Class description:
Сковорода, в которую игрок может ловить падающий бургер.
Method signatures and docstrings:
- def __init__(self): Инициализирует объект Рап и создает объект Text для отображения счета
- def update(self): Передвигает объект по горизонтали
- def check_... | Implement the Python class `Pan` described below.
Class description:
Сковорода, в которую игрок может ловить падающий бургер.
Method signatures and docstrings:
- def __init__(self): Инициализирует объект Рап и создает объект Text для отображения счета
- def update(self): Передвигает объект по горизонтали
- def check_... | 19244b259eec779381c5deb348d2ddf5f439a364 | <|skeleton|>
class Pan:
"""Сковорода, в которую игрок может ловить падающий бургер."""
def __init__(self):
"""Инициализирует объект Рап и создает объект Text для отображения счета"""
<|body_0|>
def update(self):
"""Передвигает объект по горизонтали"""
<|body_1|>
def ch... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Pan:
"""Сковорода, в которую игрок может ловить падающий бургер."""
def __init__(self):
"""Инициализирует объект Рап и создает объект Text для отображения счета"""
super(Pan, self).__init__(image=Pan.image, x=games.mouse.x, bottom=games.screen.height)
self.score = games.Text(value... | the_stack_v2_python_sparse | Graphics/burger_panic.py | kononenkoie/CS50_examples_PYTHON | train | 0 |
6713abb09de37e0f79ed7dc0233161525f0f5698 | [
"try:\n data = PolicyManager.get_object_assignments(user_id=user_id, policy_id=uuid, object_id=perimeter_id, category_id=category_id)\nexcept Exception as e:\n LOG.error(e, exc_info=True)\n return ({'result': False, 'error': str(e)}, 500)\nreturn {'object_assignments': data}",
"try:\n data_id = reques... | <|body_start_0|>
try:
data = PolicyManager.get_object_assignments(user_id=user_id, policy_id=uuid, object_id=perimeter_id, category_id=category_id)
except Exception as e:
LOG.error(e, exc_info=True)
return ({'result': False, 'error': str(e)}, 500)
return {'obj... | Endpoint for object assignment requests | ObjectAssignments | [
"Apache-2.0",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ObjectAssignments:
"""Endpoint for object assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all object assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid... | stack_v2_sparse_classes_36k_train_004142 | 14,093 | permissive | [
{
"docstring": "Retrieve all object assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the object :param category_id: uuid of the object category :param data_id: uuid of the object scope :param user_id: user ID who do the request :return: { \"object_data... | 3 | stack_v2_sparse_classes_30k_train_000468 | Implement the Python class `ObjectAssignments` described below.
Class description:
Endpoint for object assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all object assignment or a specific one for a given policy ... | Implement the Python class `ObjectAssignments` described below.
Class description:
Endpoint for object assignment requests
Method signatures and docstrings:
- def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None): Retrieve all object assignment or a specific one for a given policy ... | daaba34fa2ed4426bc0fde359e54a5e1b872208c | <|skeleton|>
class ObjectAssignments:
"""Endpoint for object assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all object assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ObjectAssignments:
"""Endpoint for object assignment requests"""
def get(self, uuid=None, perimeter_id=None, category_id=None, data_id=None, user_id=None):
"""Retrieve all object assignment or a specific one for a given policy :param uuid: uuid of the policy :param perimeter_id: uuid of the objec... | the_stack_v2_python_sparse | moonv4/moon_manager/moon_manager/api/assignments.py | hashnfv/hashnfv-moon | train | 0 |
239dae0e7022a1f2afce594deadbf38e07b11f04 | [
"count = 0\nwhile num != 0:\n if num & 1 == 1:\n count += 1\n num = num >> 1\nreturn count",
"if num == 0:\n return 0\nif num == 1:\n return 1\nm = num // 2\nk = num % 2\nreturn k + self.hammingWeight2(m)"
] | <|body_start_0|>
count = 0
while num != 0:
if num & 1 == 1:
count += 1
num = num >> 1
return count
<|end_body_0|>
<|body_start_1|>
if num == 0:
return 0
if num == 1:
return 1
m = num // 2
k = num % 2... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hammingWeight(self, num):
""":param num: int :return: int"""
<|body_0|>
def hammingWeight2(self, num):
""":param num:int :return: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
count = 0
while num != 0:
if num ... | stack_v2_sparse_classes_36k_train_004143 | 1,039 | no_license | [
{
"docstring": ":param num: int :return: int",
"name": "hammingWeight",
"signature": "def hammingWeight(self, num)"
},
{
"docstring": ":param num:int :return: int",
"name": "hammingWeight2",
"signature": "def hammingWeight2(self, num)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, num): :param num: int :return: int
- def hammingWeight2(self, num): :param num:int :return: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hammingWeight(self, num): :param num: int :return: int
- def hammingWeight2(self, num): :param num:int :return: int
<|skeleton|>
class Solution:
def hammingWeight(self,... | 4f2802d4773eddd2a2e06e61c51463056886b730 | <|skeleton|>
class Solution:
def hammingWeight(self, num):
""":param num: int :return: int"""
<|body_0|>
def hammingWeight2(self, num):
""":param num:int :return: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def hammingWeight(self, num):
""":param num: int :return: int"""
count = 0
while num != 0:
if num & 1 == 1:
count += 1
num = num >> 1
return count
def hammingWeight2(self, num):
""":param num:int :return: int"""
... | the_stack_v2_python_sparse | leetcode/44_hammingweight.py | Yara7L/python_algorithm | train | 0 | |
506bc87af4ebf0c3c567be575c0d006af991f735 | [
"kwargs = {}\ntry:\n for iter_, (user, tenant_id) in enumerate(rutils.iterate_per_tenants(self.context['users'])):\n LOG.debug('Creating context backup for user tenant %s ' % user['tenant_id'])\n tmp_context = {'user': user, 'tenant': self.context['tenants'][tenant_id], 'task': self.context['task']... | <|body_start_0|>
kwargs = {}
try:
for iter_, (user, tenant_id) in enumerate(rutils.iterate_per_tenants(self.context['users'])):
LOG.debug('Creating context backup for user tenant %s ' % user['tenant_id'])
tmp_context = {'user': user, 'tenant': self.context['te... | Create backup for trove instance. | CreateBackupContext | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CreateBackupContext:
"""Create backup for trove instance."""
def setup(self):
"""This method is called before the task start."""
<|body_0|>
def cleanup(self):
"""This method is called after the task finish."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_36k_train_004144 | 2,695 | permissive | [
{
"docstring": "This method is called before the task start.",
"name": "setup",
"signature": "def setup(self)"
},
{
"docstring": "This method is called after the task finish.",
"name": "cleanup",
"signature": "def cleanup(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_004997 | Implement the Python class `CreateBackupContext` described below.
Class description:
Create backup for trove instance.
Method signatures and docstrings:
- def setup(self): This method is called before the task start.
- def cleanup(self): This method is called after the task finish. | Implement the Python class `CreateBackupContext` described below.
Class description:
Create backup for trove instance.
Method signatures and docstrings:
- def setup(self): This method is called before the task start.
- def cleanup(self): This method is called after the task finish.
<|skeleton|>
class CreateBackupCon... | bb52d590d2ff975c3710084297ee26ff8ebe7ef9 | <|skeleton|>
class CreateBackupContext:
"""Create backup for trove instance."""
def setup(self):
"""This method is called before the task start."""
<|body_0|>
def cleanup(self):
"""This method is called after the task finish."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CreateBackupContext:
"""Create backup for trove instance."""
def setup(self):
"""This method is called before the task start."""
kwargs = {}
try:
for iter_, (user, tenant_id) in enumerate(rutils.iterate_per_tenants(self.context['users'])):
LOG.debug('Cr... | the_stack_v2_python_sparse | lhx_rally/Rally/samples/rally_plugins/plugins/context/trove/backups.py | joylhx/Rally | train | 0 |
1b585b2aceb3f79ffa82ffe93720519d8c079ba2 | [
"Simulator.__init__(self, state_set, action_set, modules)\nassert 'auctions' in modules.keys()\nassert 'clicks' in modules.keys()\nassert 'conversions' in modules.keys()\nassert 'revenue' in modules.keys()\nassert 'cpc' in modules.keys()",
"assert a in self.action_set\nhow = self.s_ix\nN_A = self.modules['auction... | <|body_start_0|>
Simulator.__init__(self, state_set, action_set, modules)
assert 'auctions' in modules.keys()
assert 'clicks' in modules.keys()
assert 'conversions' in modules.keys()
assert 'revenue' in modules.keys()
assert 'cpc' in modules.keys()
<|end_body_0|>
<|body_... | Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_set: List of valid actions. :ivar dict modules: Dic... | SimulatorConversionBasedRevenueHoW | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SimulatorConversionBasedRevenueHoW:
"""Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar l... | stack_v2_sparse_classes_36k_train_004145 | 40,659 | permissive | [
{
"docstring": ":param list state_set: List of possible states. :param list action_set: List of valid actions. :param dict modules: Dictionary of modules used to model stochastic variables in the simulator.",
"name": "__init__",
"signature": "def __init__(self, state_set, action_set, modules)"
},
{
... | 2 | null | Implement the Python class `SimulatorConversionBasedRevenueHoW` described below.
Class description:
Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list stat... | Implement the Python class `SimulatorConversionBasedRevenueHoW` described below.
Class description:
Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list stat... | ade886e9dcbde9fcea218a19f0130cc09f81e55e | <|skeleton|>
class SimulatorConversionBasedRevenueHoW:
"""Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar l... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SimulatorConversionBasedRevenueHoW:
"""Auction simulator using hours of week (encoded as a value in the range 0-167) as states and a conversion based revenue (a revenue is based on the number of conversions sampled from the number of clicks). :ivar list state_set: List of possible states. :ivar list action_se... | the_stack_v2_python_sparse | ssa_sim_v2/simulator/simulator.py | donghun2018/adclick-simulator-v2 | train | 0 |
4083b8ab3830d693e4e77761a1185262087fc9ae | [
"logger.info('%s initialization' % obj.name)\nsuper(self.__class__, self).__init__(obj, parent)\nself.local_data['x'] = 0.0\nself.local_data['y'] = 0.0\nself.local_data['z'] = 0.0\nlogger.info('Component initialized')",
"x = self.position_3d.x\ny = self.position_3d.y\nz = self.position_3d.z\nself.local_data['x'] ... | <|body_start_0|>
logger.info('%s initialization' % obj.name)
super(self.__class__, self).__init__(obj, parent)
self.local_data['x'] = 0.0
self.local_data['y'] = 0.0
self.local_data['z'] = 0.0
logger.info('Component initialized')
<|end_body_0|>
<|body_start_1|>
x ... | Class definition for the gyroscope sensor. Sub class of Morse_Object. | GPSClass | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_004146 | 1,160 | permissive | [
{
"docstring": "Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent.",
"name": "__init__",
"signature": "def __init__(self, obj, parent=None)"
},
{
"docstring": "Main function of this component.",
"name": "default_a... | 2 | null | Implement the Python class `GPSClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the... | Implement the Python class `GPSClass` described below.
Class description:
Class definition for the gyroscope sensor. Sub class of Morse_Object.
Method signatures and docstrings:
- def __init__(self, obj, parent=None): Constructor method. Receives the reference to the Blender object. The second parameter should be the... | 07fcb64fea3b58b258e917eb1aed0a585f863418 | <|skeleton|>
class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class GPSClass:
"""Class definition for the gyroscope sensor. Sub class of Morse_Object."""
def __init__(self, obj, parent=None):
"""Constructor method. Receives the reference to the Blender object. The second parameter should be the name of the object's parent."""
logger.info('%s initializatio... | the_stack_v2_python_sparse | src/morse/sensors/gps.py | DefaultUser/morse | train | 2 |
404d5af4f1bbae50ed525e30e2864011f3c4a614 | [
"self.input_coords = np.array([0.0572, -0.0592, 5.1083]) * 1000.0\nself.coords = np.array([[0.0572, -0.0592, 5.1083], [0.0578, -0.0591, 5.0993], [0.0586, -0.0585, 5.0861]]) * 1000.0\nself.long = 4\nself.lat = 2\nself.phi = 0.1\nself.no_pv = 0\nself.yes_pv = 1",
"print('Testing that covarxy_pv returns 1 dimensiona... | <|body_start_0|>
self.input_coords = np.array([0.0572, -0.0592, 5.1083]) * 1000.0
self.coords = np.array([[0.0572, -0.0592, 5.1083], [0.0578, -0.0591, 5.0993], [0.0586, -0.0585, 5.0861]]) * 1000.0
self.long = 4
self.lat = 2
self.phi = 0.1
self.no_pv = 0
self.yes_p... | Test cases for covarxy_pv function | MyTestCase | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MyTestCase:
"""Test cases for covarxy_pv function"""
def setUp(self):
"""Set up for test :return: Nothing"""
<|body_0|>
def test_return_shape(self):
"""Check that the returned covariance matrix is the correct size :return: Nothing"""
<|body_1|>
def t... | stack_v2_sparse_classes_36k_train_004147 | 3,091 | no_license | [
{
"docstring": "Set up for test :return: Nothing",
"name": "setUp",
"signature": "def setUp(self)"
},
{
"docstring": "Check that the returned covariance matrix is the correct size :return: Nothing",
"name": "test_return_shape",
"signature": "def test_return_shape(self)"
},
{
"doc... | 5 | stack_v2_sparse_classes_30k_train_017548 | Implement the Python class `MyTestCase` described below.
Class description:
Test cases for covarxy_pv function
Method signatures and docstrings:
- def setUp(self): Set up for test :return: Nothing
- def test_return_shape(self): Check that the returned covariance matrix is the correct size :return: Nothing
- def test_... | Implement the Python class `MyTestCase` described below.
Class description:
Test cases for covarxy_pv function
Method signatures and docstrings:
- def setUp(self): Set up for test :return: Nothing
- def test_return_shape(self): Check that the returned covariance matrix is the correct size :return: Nothing
- def test_... | 3944e9783d58422d2d10bbc95f9706e168550034 | <|skeleton|>
class MyTestCase:
"""Test cases for covarxy_pv function"""
def setUp(self):
"""Set up for test :return: Nothing"""
<|body_0|>
def test_return_shape(self):
"""Check that the returned covariance matrix is the correct size :return: Nothing"""
<|body_1|>
def t... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MyTestCase:
"""Test cases for covarxy_pv function"""
def setUp(self):
"""Set up for test :return: Nothing"""
self.input_coords = np.array([0.0572, -0.0592, 5.1083]) * 1000.0
self.coords = np.array([[0.0572, -0.0592, 5.1083], [0.0578, -0.0591, 5.0993], [0.0586, -0.0585, 5.0861]]) *... | the_stack_v2_python_sparse | ow_calibration/build_cov/covarxy_pv/covarxy_pv_test.py | gmaze/argodmqc_owc | train | 0 |
e027a9183c2c149dd94aeeaa48900e5a483960bd | [
"super().__init__()\nself._feature_dim = config[0]\nself._hidden_dim = config[1]\nself._output_dim = config[2]\nself._layer_count = config[3]\nself._layers = nn.ModuleList([])\nfor i in range(len(self._filter_sizes)):\n if i == 0:\n self._layers.append(nn.Linear(self._feature_dim, self._hidden_dim))\n ... | <|body_start_0|>
super().__init__()
self._feature_dim = config[0]
self._hidden_dim = config[1]
self._output_dim = config[2]
self._layer_count = config[3]
self._layers = nn.ModuleList([])
for i in range(len(self._filter_sizes)):
if i == 0:
... | Deterministic_Conv_Encoder | Deterministic_FC_Encoder | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Deterministic_FC_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, feature_dim) Return: output :"""
<|body_1|>
<|end_skeleton|>
<|body... | stack_v2_sparse_classes_36k_train_004148 | 18,202 | no_license | [
{
"docstring": "NP",
"name": "__init__",
"signature": "def __init__(self, config)"
},
{
"docstring": "Args: input : imamges (num_tasks, n_way, k_shot, feature_dim) Return: output :",
"name": "forward",
"signature": "def forward(self, inputs)"
}
] | 2 | stack_v2_sparse_classes_30k_train_021237 | Implement the Python class `Deterministic_FC_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, feature_dim) Return: output : | Implement the Python class `Deterministic_FC_Encoder` described below.
Class description:
Deterministic_Conv_Encoder
Method signatures and docstrings:
- def __init__(self, config): NP
- def forward(self, inputs): Args: input : imamges (num_tasks, n_way, k_shot, feature_dim) Return: output :
<|skeleton|>
class Determ... | c7e1bfb49ebaec6937ed7b186689227f95a43e0f | <|skeleton|>
class Deterministic_FC_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config):
"""NP"""
<|body_0|>
def forward(self, inputs):
"""Args: input : imamges (num_tasks, n_way, k_shot, feature_dim) Return: output :"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Deterministic_FC_Encoder:
"""Deterministic_Conv_Encoder"""
def __init__(self, config):
"""NP"""
super().__init__()
self._feature_dim = config[0]
self._hidden_dim = config[1]
self._output_dim = config[2]
self._layer_count = config[3]
self._layers = n... | the_stack_v2_python_sparse | model/MAML/Part/encoder.py | MingyuKim87/MLwM | train | 0 |
d0c3d43a035d6873262e0c381fcc6dd74622f9c8 | [
"tot = 0\nfor evt in evts:\n if isinstance(evt, events.KillEvent):\n assert not self.world.killing_deletes\n if isinstance(self.world.objects[evt.victim], Fish) or isinstance(self.world.objects[evt.victim], Submarine):\n tot += min(90, 20 + 10 * self.world.objects['seachase_player'].num_... | <|body_start_0|>
tot = 0
for evt in evts:
if isinstance(evt, events.KillEvent):
assert not self.world.killing_deletes
if isinstance(self.world.objects[evt.victim], Fish) or isinstance(self.world.objects[evt.victim], Submarine):
tot += min(9... | Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424) | SeachaseJudge | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SeachaseJudge:
"""Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424)"""
def _calculate_reward(self, goals, evts):
"""Calculate rewards for killing things and rescuing divers. Parameters --------... | stack_v2_sparse_classes_36k_train_004149 | 14,247 | permissive | [
{
"docstring": "Calculate rewards for killing things and rescuing divers. Parameters ---------- goals : list[Goal] a list of goals that were achieved during the step events : list[Event] a list of Events that occurred during the step Returns ------- reward : Number the reward to associate with the step",
"n... | 2 | stack_v2_sparse_classes_30k_train_008796 | Implement the Python class `SeachaseJudge` described below.
Class description:
Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424)
Method signatures and docstrings:
- def _calculate_reward(self, goals, evts): Calculate rewards fo... | Implement the Python class `SeachaseJudge` described below.
Class description:
Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424)
Method signatures and docstrings:
- def _calculate_reward(self, goals, evts): Calculate rewards fo... | 4a287e820fbb62bfc2b3b3d08df282329df4c2b1 | <|skeleton|>
class SeachaseJudge:
"""Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424)"""
def _calculate_reward(self, goals, evts):
"""Calculate rewards for killing things and rescuing divers. Parameters --------... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SeachaseJudge:
"""Implements one interpretation of the complicated Seachase scoring rules (see https://atariage.com/manual_html_page.html?SoftwareLabelID=424)"""
def _calculate_reward(self, goals, evts):
"""Calculate rewards for killing things and rescuing divers. Parameters ---------- goals : li... | the_stack_v2_python_sparse | pixelworld/envs/pixelworld/library/world/seachase.py | fenfeibani/pixelworld | train | 0 |
bd8f123d8b33f42fb1aaa42e777d78eccb642692 | [
"WrappingFactory.__init__(self, wrappedFactory)\nif isClient:\n creatorInterface = IOpenSSLClientConnectionCreator\nelse:\n creatorInterface = IOpenSSLServerConnectionCreator\nself._creatorInterface = creatorInterface\nif not creatorInterface.providedBy(contextFactory):\n contextFactory = _ContextFactoryTo... | <|body_start_0|>
WrappingFactory.__init__(self, wrappedFactory)
if isClient:
creatorInterface = IOpenSSLClientConnectionCreator
else:
creatorInterface = IOpenSSLServerConnectionCreator
self._creatorInterface = creatorInterface
if not creatorInterface.provi... | L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a callable which creates an OpenSSL Connection object. @type _connectionCreator: 1-argum... | TLSMemoryBIOFactory | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TLSMemoryBIOFactory:
"""L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a callable which creates an OpenSSL Conne... | stack_v2_sparse_classes_36k_train_004150 | 32,500 | permissive | [
{
"docstring": "Create a L{TLSMemoryBIOFactory}. @param contextFactory: Configuration parameters used to create an OpenSSL connection. In order of preference, what you should pass here should be: 1. L{twisted.internet.ssl.CertificateOptions} (if you're writing a server) or the result of L{twisted.internet.ssl.o... | 4 | stack_v2_sparse_classes_30k_val_000635 | Implement the Python class `TLSMemoryBIOFactory` described below.
Class description:
L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a ... | Implement the Python class `TLSMemoryBIOFactory` described below.
Class description:
L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a ... | 5cee0a8c4180a3108538b4e4ce945a18726595a6 | <|skeleton|>
class TLSMemoryBIOFactory:
"""L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a callable which creates an OpenSSL Conne... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TLSMemoryBIOFactory:
"""L{TLSMemoryBIOFactory} adds TLS to connections. @ivar _creatorInterface: the interface which L{_connectionCreator} is expected to implement. @type _creatorInterface: L{zope.interface.interfaces.IInterface} @ivar _connectionCreator: a callable which creates an OpenSSL Connection object.... | the_stack_v2_python_sparse | venv/Lib/site-packages/twisted/protocols/tls.py | zoelesv/Smathchat | train | 9 |
a4544f2f035e667982d18ca29b7211cdd28be984 | [
"if nums == []:\n return 0\nself.dicts = {}\nself.num = 0\nself.min_length = -1\ncount = 0\nfor i in nums:\n if i not in self.dicts.keys():\n self.dicts[i] = {'start': count, 'end': count, 'time': 1}\n else:\n self.dicts[i]['end'] = count\n self.dicts[i]['time'] += 1\n self.num = ma... | <|body_start_0|>
if nums == []:
return 0
self.dicts = {}
self.num = 0
self.min_length = -1
count = 0
for i in nums:
if i not in self.dicts.keys():
self.dicts[i] = {'start': count, 'end': count, 'time': 1}
else:
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int 658ms"""
<|body_0|>
def findShortestSubArray_1(self, nums):
""":type nums: List[int] :rtype: int 119ms"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if nums == []... | stack_v2_sparse_classes_36k_train_004151 | 2,455 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int 658ms",
"name": "findShortestSubArray",
"signature": "def findShortestSubArray(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int 119ms",
"name": "findShortestSubArray_1",
"signature": "def findShortestSubArray_1(self, nums... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int 658ms
- def findShortestSubArray_1(self, nums): :type nums: List[int] :rtype: int 119ms | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findShortestSubArray(self, nums): :type nums: List[int] :rtype: int 658ms
- def findShortestSubArray_1(self, nums): :type nums: List[int] :rtype: int 119ms
<|skeleton|>
clas... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int 658ms"""
<|body_0|>
def findShortestSubArray_1(self, nums):
""":type nums: List[int] :rtype: int 119ms"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findShortestSubArray(self, nums):
""":type nums: List[int] :rtype: int 658ms"""
if nums == []:
return 0
self.dicts = {}
self.num = 0
self.min_length = -1
count = 0
for i in nums:
if i not in self.dicts.keys():
... | the_stack_v2_python_sparse | DegreeOfAnArray_697.py | 953250587/leetcode-python | train | 2 | |
bd7647ef3faa4e0493ceeeaf97c5d85ee3f6f2bd | [
"super(DropItem, self).__init__()\nif itemType:\n self.device_type = itemType\nself.image = QtGui.QImage(environ['images'] + self.device_type + '.gif')\nif self.image.isNull():\n mainWidgets['log'].append('Unknown node type ' + str(self.device_type))\n return\nself.setCursor(QtCore.Qt.OpenHandCursor)\nif i... | <|body_start_0|>
super(DropItem, self).__init__()
if itemType:
self.device_type = itemType
self.image = QtGui.QImage(environ['images'] + self.device_type + '.gif')
if self.image.isNull():
mainWidgets['log'].append('Unknown node type ' + str(self.device_type))
... | DropItem | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DropItem:
def __init__(self, itemType=None):
"""Create a draggable item, which can be dropped into the canvas."""
<|body_0|>
def paint(self, painter, option, widget):
"""Draw the representation."""
<|body_1|>
def boundingRect(self):
"""Get the bo... | stack_v2_sparse_classes_36k_train_004152 | 14,238 | permissive | [
{
"docstring": "Create a draggable item, which can be dropped into the canvas.",
"name": "__init__",
"signature": "def __init__(self, itemType=None)"
},
{
"docstring": "Draw the representation.",
"name": "paint",
"signature": "def paint(self, painter, option, widget)"
},
{
"docst... | 4 | null | Implement the Python class `DropItem` described below.
Class description:
Implement the DropItem class.
Method signatures and docstrings:
- def __init__(self, itemType=None): Create a draggable item, which can be dropped into the canvas.
- def paint(self, painter, option, widget): Draw the representation.
- def bound... | Implement the Python class `DropItem` described below.
Class description:
Implement the DropItem class.
Method signatures and docstrings:
- def __init__(self, itemType=None): Create a draggable item, which can be dropped into the canvas.
- def paint(self, painter, option, widget): Draw the representation.
- def bound... | d095076113c1e84c33f52ef46a3df1f8bc8ffa43 | <|skeleton|>
class DropItem:
def __init__(self, itemType=None):
"""Create a draggable item, which can be dropped into the canvas."""
<|body_0|>
def paint(self, painter, option, widget):
"""Draw the representation."""
<|body_1|>
def boundingRect(self):
"""Get the bo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DropItem:
def __init__(self, itemType=None):
"""Create a draggable item, which can be dropped into the canvas."""
super(DropItem, self).__init__()
if itemType:
self.device_type = itemType
self.image = QtGui.QImage(environ['images'] + self.device_type + '.gif')
... | the_stack_v2_python_sparse | frontend/src/gbuilder/UI/Node.py | citelab/gini5 | train | 12 | |
c1956712668b79cbb93841e0527c3210a2a2c1a2 | [
"self.backup_file_path = backup_file_path\nself.excluded_file_paths = excluded_file_paths\nself.skip_nested_volumes = skip_nested_volumes",
"if dictionary is None:\n return None\nbackup_file_path = dictionary.get('backupFilePath')\nexcluded_file_paths = dictionary.get('excludedFilePaths')\nskip_nested_volumes ... | <|body_start_0|>
self.backup_file_path = backup_file_path
self.excluded_file_paths = excluded_file_paths
self.skip_nested_volumes = skip_nested_volumes
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
backup_file_path = dictionary.get('backupFilePat... | Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be explicitly excluded. Attributes: backup_file_path (string): Specifies absolute path to a f... | FilePathParameters | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FilePathParameters:
"""Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be explicitly excluded. Attributes: backup_file... | stack_v2_sparse_classes_36k_train_004153 | 2,594 | permissive | [
{
"docstring": "Constructor for the FilePathParameters class",
"name": "__init__",
"signature": "def __init__(self, backup_file_path=None, excluded_file_paths=None, skip_nested_volumes=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A ... | 2 | stack_v2_sparse_classes_30k_train_014967 | Implement the Python class `FilePathParameters` described below.
Class description:
Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be expli... | Implement the Python class `FilePathParameters` described below.
Class description:
Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be expli... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class FilePathParameters:
"""Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be explicitly excluded. Attributes: backup_file... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class FilePathParameters:
"""Implementation of the 'FilePathParameters' model. Specifies a file or a directory to protect in a Physical Server. If a directory is specified, all of its descendants are also backed up. Optionally, files or subdirectories can be explicitly excluded. Attributes: backup_file_path (string... | the_stack_v2_python_sparse | cohesity_management_sdk/models/file_path_parameters.py | cohesity/management-sdk-python | train | 24 |
1c5724bfeb53cfef03c0cda0597e418e2fd95925 | [
"if self.digest_type != self.HashType.SHA256:\n raise rdfvalue.DecodeError('Unsupported digest.')\nif self.signature_type not in [self.SignatureType.RSA_PKCS1v15, self.SignatureType.RSA_PSS]:\n raise rdfvalue.DecodeError('Unsupported signature type.')\ntry:\n public_key.Verify(self.data, self.signature)\ne... | <|body_start_0|>
if self.digest_type != self.HashType.SHA256:
raise rdfvalue.DecodeError('Unsupported digest.')
if self.signature_type not in [self.SignatureType.RSA_PKCS1v15, self.SignatureType.RSA_PSS]:
raise rdfvalue.DecodeError('Unsupported signature type.')
try:
... | A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this. | SignedBlob | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SignedBlob:
"""A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this."""
def Verify(self, public_key):
"""Verify the data in this blob. Args: public_key: The public key to use for verification. Re... | stack_v2_sparse_classes_36k_train_004154 | 27,541 | permissive | [
{
"docstring": "Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True when verification succeeds. Raises: rdfvalue.DecodeError if the data is not suitable verified.",
"name": "Verify",
"signature": "def Verify(self, public_key)"
},
{
"docstring": "... | 2 | stack_v2_sparse_classes_30k_train_016936 | Implement the Python class `SignedBlob` described below.
Class description:
A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this.
Method signatures and docstrings:
- def Verify(self, public_key): Verify the data in this blob. Arg... | Implement the Python class `SignedBlob` described below.
Class description:
A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this.
Method signatures and docstrings:
- def Verify(self, public_key): Verify the data in this blob. Arg... | 44c0eb8c938302098ef7efae8cfd6b90bcfbb2d6 | <|skeleton|>
class SignedBlob:
"""A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this."""
def Verify(self, public_key):
"""Verify the data in this blob. Args: public_key: The public key to use for verification. Re... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SignedBlob:
"""A signed blob. The client can receive and verify a signed blob (e.g. driver or executable binary). Once verified, the client may execute this."""
def Verify(self, public_key):
"""Verify the data in this blob. Args: public_key: The public key to use for verification. Returns: True w... | the_stack_v2_python_sparse | grr/core/grr_response_core/lib/rdfvalues/crypto.py | google/grr | train | 4,683 |
719f7ed9cf64c8acb726cecbd454260f2b0ea3dc | [
"n = len(matrix)\nfor i in range(n):\n for j in range(i, n):\n matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])\nprint(matrix)\nfor i in range(n):\n matrix[i].reverse()\nreturn matrix",
"n = len(matrix)\nfor i in range(n // 2 + n % 2):\n for j in range(n // 2):\n temp = [0] * 4\n ... | <|body_start_0|>
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
print(matrix)
for i in range(n):
matrix[i].reverse()
return matrix
<|end_body_0|>
<|body_start_1|>
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rotate1(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可"""
<|body_0|>
def rotate(self, matrix):
"""针对每个元素的顺时针旋转90度进行处理 对方阵来说,每个元素matrix[i][j], 方阵长度为n*n 轴对称:(对(0,0)(1,1)..(n,n)这条线来说)元素的坐... | stack_v2_sparse_classes_36k_train_004155 | 2,007 | no_license | [
{
"docstring": "Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可",
"name": "rotate1",
"signature": "def rotate1(self, matrix: List[List[int]]) -> None"
},
{
"docstring": "针对每个元素的顺时针旋转90度进行处理 对方阵来说,每个元素matrix[i][j], 方阵长度为n*n 轴对称:(对(0,0)(1,1)..(n,n)这条线来说)元素的坐标为matrix[j][i] ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可
- def rotate(self, matrix): 针对每个元素的顺时针旋转90度进行处理 对方阵来说... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rotate1(self, matrix: List[List[int]]) -> None: Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可
- def rotate(self, matrix): 针对每个元素的顺时针旋转90度进行处理 对方阵来说... | f0f4ba0cb91096e55e21b7a2240afbd347187351 | <|skeleton|>
class Solution:
def rotate1(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可"""
<|body_0|>
def rotate(self, matrix):
"""针对每个元素的顺时针旋转90度进行处理 对方阵来说,每个元素matrix[i][j], 方阵长度为n*n 轴对称:(对(0,0)(1,1)..(n,n)这条线来说)元素的坐... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def rotate1(self, matrix: List[List[int]]) -> None:
"""Do not return anything, modify matrix in-place instead. 先将矩阵转置,再将每一行翻转即可"""
n = len(matrix)
for i in range(n):
for j in range(i, n):
matrix[i][j], matrix[j][i] = (matrix[j][i], matrix[i][j])
... | the_stack_v2_python_sparse | coding_test/48_rotate.py | zhuheng-mark/myDL | train | 2 | |
3bf05480850d895adf242567105d4fedcee74378 | [
"lookup = models.Q(name__icontains=value)\nlookup = lookup | models.Q(title__icontains=value)\nlookup = lookup | models.Q(category__icontains=value)\nreturn queryset.filter(lookup)",
"lookup = models.Q(name__icontains=value)\nlookup = lookup | models.Q(authors__icontains=value)\nlookup = lookup | models.Q(categor... | <|body_start_0|>
lookup = models.Q(name__icontains=value)
lookup = lookup | models.Q(title__icontains=value)
lookup = lookup | models.Q(category__icontains=value)
return queryset.filter(lookup)
<|end_body_0|>
<|body_start_1|>
lookup = models.Q(name__icontains=value)
look... | Filter class for the PluginMeta model. | PluginMetaFilter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluginMetaFilter:
"""Filter class for the PluginMeta model."""
def search_name_title_category(self, queryset, name, value):
"""Custom method to get a filtered queryset with all plugins for which name or title or category matches the search value."""
<|body_0|>
def search... | stack_v2_sparse_classes_36k_train_004156 | 13,969 | permissive | [
{
"docstring": "Custom method to get a filtered queryset with all plugins for which name or title or category matches the search value.",
"name": "search_name_title_category",
"signature": "def search_name_title_category(self, queryset, name, value)"
},
{
"docstring": "Custom method to get a fil... | 2 | null | Implement the Python class `PluginMetaFilter` described below.
Class description:
Filter class for the PluginMeta model.
Method signatures and docstrings:
- def search_name_title_category(self, queryset, name, value): Custom method to get a filtered queryset with all plugins for which name or title or category matche... | Implement the Python class `PluginMetaFilter` described below.
Class description:
Filter class for the PluginMeta model.
Method signatures and docstrings:
- def search_name_title_category(self, queryset, name, value): Custom method to get a filtered queryset with all plugins for which name or title or category matche... | 20d3eedf20610af9182f6cca8db8f0b3546b5336 | <|skeleton|>
class PluginMetaFilter:
"""Filter class for the PluginMeta model."""
def search_name_title_category(self, queryset, name, value):
"""Custom method to get a filtered queryset with all plugins for which name or title or category matches the search value."""
<|body_0|>
def search... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PluginMetaFilter:
"""Filter class for the PluginMeta model."""
def search_name_title_category(self, queryset, name, value):
"""Custom method to get a filtered queryset with all plugins for which name or title or category matches the search value."""
lookup = models.Q(name__icontains=value... | the_stack_v2_python_sparse | chris_backend/plugins/models.py | FNNDSC/ChRIS_ultron_backEnd | train | 36 |
54c4f3520d5d633aec41806b924b17ff1faf61a8 | [
"QtWidgets.QDialog.__init__(self)\nself.resize(1000, 700)\nself.topicList = QtWidgets.QListWidget()\nself.topicList.setFixedWidth(200)\nself.topicList.addItem('General Use')\nself.topicList.addItem('File Menu')\nself.topicList.addItem('Operations')\nself.topicList.currentItemChanged.connect(self.displayHelp)\nself.... | <|body_start_0|>
QtWidgets.QDialog.__init__(self)
self.resize(1000, 700)
self.topicList = QtWidgets.QListWidget()
self.topicList.setFixedWidth(200)
self.topicList.addItem('General Use')
self.topicList.addItem('File Menu')
self.topicList.addItem('Operations')
... | A help wiki to teach the user about the program and how to use it. | HelpModel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
<|body_0|>
def help(self, parent=None):
"""Present knowledge to the user"""
<|body_1|>
... | stack_v2_sparse_classes_36k_train_004157 | 29,548 | no_license | [
{
"docstring": "Initializes the UI and sets the properties.",
"name": "__init__",
"signature": "def __init__(self, parent=None)"
},
{
"docstring": "Present knowledge to the user",
"name": "help",
"signature": "def help(self, parent=None)"
},
{
"docstring": "Gets active selection ... | 3 | stack_v2_sparse_classes_30k_train_007373 | Implement the Python class `HelpModel` described below.
Class description:
A help wiki to teach the user about the program and how to use it.
Method signatures and docstrings:
- def __init__(self, parent=None): Initializes the UI and sets the properties.
- def help(self, parent=None): Present knowledge to the user
- ... | Implement the Python class `HelpModel` described below.
Class description:
A help wiki to teach the user about the program and how to use it.
Method signatures and docstrings:
- def __init__(self, parent=None): Initializes the UI and sets the properties.
- def help(self, parent=None): Present knowledge to the user
- ... | 1a3c5ad967472faf66236a311cc07a5128f5f911 | <|skeleton|>
class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
<|body_0|>
def help(self, parent=None):
"""Present knowledge to the user"""
<|body_1|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HelpModel:
"""A help wiki to teach the user about the program and how to use it."""
def __init__(self, parent=None):
"""Initializes the UI and sets the properties."""
QtWidgets.QDialog.__init__(self)
self.resize(1000, 700)
self.topicList = QtWidgets.QListWidget()
s... | the_stack_v2_python_sparse | datatool/gui/Model.py | scottawalton/datatool | train | 0 |
09c412ec980ed5addea25967b2d5a5a6ef72f1ee | [
"self.pre_t = Trie()\nself.suf_t = Trie()\nfor i, v in enumerate(words):\n self.pre_t.add(v, i)\n self.suf_t.add(v[::-1], i)",
"t1 = self.pre_t\nfor v in prefix:\n if v in t1.next:\n t1 = t1.next[v]\n else:\n return -1\nt2 = self.suf_t\nfor v in suffix[::-1]:\n if v in t2.next:\n ... | <|body_start_0|>
self.pre_t = Trie()
self.suf_t = Trie()
for i, v in enumerate(words):
self.pre_t.add(v, i)
self.suf_t.add(v[::-1], i)
<|end_body_0|>
<|body_start_1|>
t1 = self.pre_t
for v in prefix:
if v in t1.next:
t1 = t1.ne... | WordFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.pre_t = Trie()
self.suf_t = T... | stack_v2_sparse_classes_36k_train_004158 | 2,424 | no_license | [
{
"docstring": ":type words: List[str]",
"name": "__init__",
"signature": "def __init__(self, words)"
},
{
"docstring": ":type prefix: str :type suffix: str :rtype: int",
"name": "f",
"signature": "def f(self, prefix, suffix)"
}
] | 2 | null | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int | Implement the Python class `WordFilter` described below.
Class description:
Implement the WordFilter class.
Method signatures and docstrings:
- def __init__(self, words): :type words: List[str]
- def f(self, prefix, suffix): :type prefix: str :type suffix: str :rtype: int
<|skeleton|>
class WordFilter:
def __in... | 9eb44afa4233fdedc2e5c72be0fdf54b25d1c45c | <|skeleton|>
class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
<|body_0|>
def f(self, prefix, suffix):
""":type prefix: str :type suffix: str :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class WordFilter:
def __init__(self, words):
""":type words: List[str]"""
self.pre_t = Trie()
self.suf_t = Trie()
for i, v in enumerate(words):
self.pre_t.add(v, i)
self.suf_t.add(v[::-1], i)
def f(self, prefix, suffix):
""":type prefix: str :type... | the_stack_v2_python_sparse | Google/Pro745. Prefix and Suffix Search.py | YoyinZyc/Leetcode_Python | train | 0 | |
1036498147f14bccdfa76f5b24674eddbedbc46d | [
"super().__init__()\nself._v_c = nn.Parameter(torch.Tensor(context_dim))\nself._v_s = nn.Parameter(torch.Tensor(state_dim))\nself._v_i = nn.Parameter(torch.Tensor(input_dim))\ninit.uniform_(self._v_c, -INIT, INIT)\ninit.uniform_(self._v_s, -INIT, INIT)\ninit.uniform_(self._v_i, -INIT, INIT)\nif bias:\n self._b =... | <|body_start_0|>
super().__init__()
self._v_c = nn.Parameter(torch.Tensor(context_dim))
self._v_s = nn.Parameter(torch.Tensor(state_dim))
self._v_i = nn.Parameter(torch.Tensor(input_dim))
init.uniform_(self._v_c, -INIT, INIT)
init.uniform_(self._v_s, -INIT, INIT)
... | _CopyLinear | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _CopyLinear:
def __init__(self, context_dim, state_dim, input_dim, bias=True):
"""Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:"""
<|body_0|>
def forward(self, context, state, input_):
"""copy概率计算 :param context: [B,N] ... | stack_v2_sparse_classes_36k_train_004159 | 14,365 | permissive | [
{
"docstring": "Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:",
"name": "__init__",
"signature": "def __init__(self, context_dim, state_dim, input_dim, bias=True)"
},
{
"docstring": "copy概率计算 :param context: [B,N] 由注意力和解码器输出生成context :param state: ... | 2 | stack_v2_sparse_classes_30k_train_012345 | Implement the Python class `_CopyLinear` described below.
Class description:
Implement the _CopyLinear class.
Method signatures and docstrings:
- def __init__(self, context_dim, state_dim, input_dim, bias=True): Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:
- def forwar... | Implement the Python class `_CopyLinear` described below.
Class description:
Implement the _CopyLinear class.
Method signatures and docstrings:
- def __init__(self, context_dim, state_dim, input_dim, bias=True): Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:
- def forwar... | 527f32d49887f06eee357c83bb6a9a21edc69bc5 | <|skeleton|>
class _CopyLinear:
def __init__(self, context_dim, state_dim, input_dim, bias=True):
"""Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:"""
<|body_0|>
def forward(self, context, state, input_):
"""copy概率计算 :param context: [B,N] ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class _CopyLinear:
def __init__(self, context_dim, state_dim, input_dim, bias=True):
"""Pgen生成 :param context_dim: N 256 :param state_dim: N 256 :param input_dim: N 256 :param bias:"""
super().__init__()
self._v_c = nn.Parameter(torch.Tensor(context_dim))
self._v_s = nn.Parameter(tor... | the_stack_v2_python_sparse | src/library/text/modules/copynet.py | inessus/ai-skills | train | 5 | |
aa265bd4e95e6ba6085abec69c4eed3a90493519 | [
"if not digits:\n return []\nphoneMap = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\nlc = ['']\nfor s in digits:\n lc_len = len(lc)\n while lc_len > 0:\n lc_len -= 1\n cur_lc = lc.pop(0)\n for char in phoneMap[s]:\n lc.a... | <|body_start_0|>
if not digits:
return []
phoneMap = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
lc = ['']
for s in digits:
lc_len = len(lc)
while lc_len > 0:
lc_len -= 1
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
"""广度搜索 :param digits: :return:"""
<|body_0|>
def letterCombinations_backtrace(self, digits: str) -> List[str]:
"""回溯法(深度搜索) :param digits: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_star... | stack_v2_sparse_classes_36k_train_004160 | 1,608 | no_license | [
{
"docstring": "广度搜索 :param digits: :return:",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits: str) -> List[str]"
},
{
"docstring": "回溯法(深度搜索) :param digits: :return:",
"name": "letterCombinations_backtrace",
"signature": "def letterCombinations_backtrace... | 2 | stack_v2_sparse_classes_30k_train_021374 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str) -> List[str]: 广度搜索 :param digits: :return:
- def letterCombinations_backtrace(self, digits: str) -> List[str]: 回溯法(深度搜索) :param digits: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str) -> List[str]: 广度搜索 :param digits: :return:
- def letterCombinations_backtrace(self, digits: str) -> List[str]: 回溯法(深度搜索) :param digits: ... | f2c162654a83c51495ebd161f42a1d0b69caf72d | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
"""广度搜索 :param digits: :return:"""
<|body_0|>
def letterCombinations_backtrace(self, digits: str) -> List[str]:
"""回溯法(深度搜索) :param digits: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits: str) -> List[str]:
"""广度搜索 :param digits: :return:"""
if not digits:
return []
phoneMap = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
lc = ['']
for s in dig... | the_stack_v2_python_sparse | 17 letterCombinations.py | ABenxj/leetcode | train | 1 | |
86ecab3aa46cfdb295e821ffec6152cc97045635 | [
"infra_map = self.get_infra_map()\nopenshift_provider_uuids, infra_provider_uuids = self.get_openshift_and_infra_providers_lists(infra_map)\nif self._provider.type == Provider.PROVIDER_OCP and self._provider_uuid not in openshift_provider_uuids:\n infra_map = self._generate_ocp_infra_map_from_sql(start_date, end... | <|body_start_0|>
infra_map = self.get_infra_map()
openshift_provider_uuids, infra_provider_uuids = self.get_openshift_and_infra_providers_lists(infra_map)
if self._provider.type == Provider.PROVIDER_OCP and self._provider_uuid not in openshift_provider_uuids:
infra_map = self._genera... | Class to update OCP report summary data. | OCPCloudReportSummaryUpdater | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class OCPCloudReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_summary_tables(self, start_date, end_date):
"""Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns ... | stack_v2_sparse_classes_36k_train_004161 | 6,579 | permissive | [
{
"docstring": "Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns None",
"name": "update_summary_tables",
"signature": "def update_summary_tables(self, start_date, end_date)"
},
{
"docstring": "Upd... | 3 | null | Implement the Python class `OCPCloudReportSummaryUpdater` described below.
Class description:
Class to update OCP report summary data.
Method signatures and docstrings:
- def update_summary_tables(self, start_date, end_date): Populate the summary tables for reporting. Args: start_date (str) The date to start populati... | Implement the Python class `OCPCloudReportSummaryUpdater` described below.
Class description:
Class to update OCP report summary data.
Method signatures and docstrings:
- def update_summary_tables(self, start_date, end_date): Populate the summary tables for reporting. Args: start_date (str) The date to start populati... | 2979f03fbdd1c20c3abc365a963a1282b426f321 | <|skeleton|>
class OCPCloudReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_summary_tables(self, start_date, end_date):
"""Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class OCPCloudReportSummaryUpdater:
"""Class to update OCP report summary data."""
def update_summary_tables(self, start_date, end_date):
"""Populate the summary tables for reporting. Args: start_date (str) The date to start populating the table. end_date (str) The date to end on. Returns None"""
... | the_stack_v2_python_sparse | koku/masu/processor/ocp/ocp_cloud_summary_updater.py | luisfdez/koku | train | 0 |
d4301495eeef8415cfe8e8f3a17db22338eedde4 | [
"matches = []\nif not isinstance(key, (six.text_type, six.string_types)):\n message = 'DependsOn values should be of string at {0}'\n matches.append(RuleMatch(path, message.format('/'.join(map(str, path)))))\n return matches\nif key not in resources:\n message = 'DependsOn should reference other resourc... | <|body_start_0|>
matches = []
if not isinstance(key, (six.text_type, six.string_types)):
message = 'DependsOn values should be of string at {0}'
matches.append(RuleMatch(path, message.format('/'.join(map(str, path)))))
return matches
if key not in resources:
... | Check Base Resource Configuration | DependsOn | [
"MIT-0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DependsOn:
"""Check Base Resource Configuration"""
def check_value(self, key, path, resources):
"""Check resource names for DependsOn"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation Resources"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_36k_train_004162 | 2,814 | permissive | [
{
"docstring": "Check resource names for DependsOn",
"name": "check_value",
"signature": "def check_value(self, key, path, resources)"
},
{
"docstring": "Check CloudFormation Resources",
"name": "match",
"signature": "def match(self, cfn)"
}
] | 2 | null | Implement the Python class `DependsOn` described below.
Class description:
Check Base Resource Configuration
Method signatures and docstrings:
- def check_value(self, key, path, resources): Check resource names for DependsOn
- def match(self, cfn): Check CloudFormation Resources | Implement the Python class `DependsOn` described below.
Class description:
Check Base Resource Configuration
Method signatures and docstrings:
- def check_value(self, key, path, resources): Check resource names for DependsOn
- def match(self, cfn): Check CloudFormation Resources
<|skeleton|>
class DependsOn:
"""... | 3f5324cfd000e14d9324a242bb7fad528b22a7df | <|skeleton|>
class DependsOn:
"""Check Base Resource Configuration"""
def check_value(self, key, path, resources):
"""Check resource names for DependsOn"""
<|body_0|>
def match(self, cfn):
"""Check CloudFormation Resources"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DependsOn:
"""Check Base Resource Configuration"""
def check_value(self, key, path, resources):
"""Check resource names for DependsOn"""
matches = []
if not isinstance(key, (six.text_type, six.string_types)):
message = 'DependsOn values should be of string at {0}'
... | the_stack_v2_python_sparse | src/cfnlint/rules/resources/DependsOn.py | jlongtine/cfn-python-lint | train | 1 |
3ff0b0de337ea9b48b2a76f6dcfaa9aadc7096a4 | [
"rows = Message.objects.select_related('from_user').filter(read=False, deleted=False, to_user=to_user).order_by('created_at')\nresult = []\nfor row in rows:\n result_row = {}\n result_row['dialog_id'] = row.dialog_id\n result_row['content'] = row.content\n result_row['from_user'] = row.from_user.usernam... | <|body_start_0|>
rows = Message.objects.select_related('from_user').filter(read=False, deleted=False, to_user=to_user).order_by('created_at')
result = []
for row in rows:
result_row = {}
result_row['dialog_id'] = row.dialog_id
result_row['content'] = row.conte... | MessageManager | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MessageManager:
def unread(self, to_user):
"""All unread messages"""
<|body_0|>
def dialog_history(self, dialog: int, offset: int=0):
"""History of dialog"""
<|body_1|>
def dialogs(self, user):
"""Get user dialogs"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k_train_004163 | 4,102 | no_license | [
{
"docstring": "All unread messages",
"name": "unread",
"signature": "def unread(self, to_user)"
},
{
"docstring": "History of dialog",
"name": "dialog_history",
"signature": "def dialog_history(self, dialog: int, offset: int=0)"
},
{
"docstring": "Get user dialogs",
"name": ... | 3 | stack_v2_sparse_classes_30k_val_000385 | Implement the Python class `MessageManager` described below.
Class description:
Implement the MessageManager class.
Method signatures and docstrings:
- def unread(self, to_user): All unread messages
- def dialog_history(self, dialog: int, offset: int=0): History of dialog
- def dialogs(self, user): Get user dialogs | Implement the Python class `MessageManager` described below.
Class description:
Implement the MessageManager class.
Method signatures and docstrings:
- def unread(self, to_user): All unread messages
- def dialog_history(self, dialog: int, offset: int=0): History of dialog
- def dialogs(self, user): Get user dialogs
... | 67ef8219b4c49dd3962509bd481a1c1b8aafc6a3 | <|skeleton|>
class MessageManager:
def unread(self, to_user):
"""All unread messages"""
<|body_0|>
def dialog_history(self, dialog: int, offset: int=0):
"""History of dialog"""
<|body_1|>
def dialogs(self, user):
"""Get user dialogs"""
<|body_2|>
<|end_ske... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MessageManager:
def unread(self, to_user):
"""All unread messages"""
rows = Message.objects.select_related('from_user').filter(read=False, deleted=False, to_user=to_user).order_by('created_at')
result = []
for row in rows:
result_row = {}
result_row['dia... | the_stack_v2_python_sparse | message/models.py | vacuumfull/na | train | 0 | |
b6a8bb005e781aaa1ee126b879c985d0f2cbf794 | [
"_map = {}\nfor query in SUPPORTED_QUERY_TYPES:\n query_obj = getattr(self, query)\n _map[query] = {'name': query, **query_obj.export_dict(include={'display_name', 'enable', 'mode', 'communities'})}\nreturn _map",
"_list = []\nfor query in SUPPORTED_QUERY_TYPES:\n query_obj = getattr(self, query)\n _l... | <|body_start_0|>
_map = {}
for query in SUPPORTED_QUERY_TYPES:
query_obj = getattr(self, query)
_map[query] = {'name': query, **query_obj.export_dict(include={'display_name', 'enable', 'mode', 'communities'})}
return _map
<|end_body_0|>
<|body_start_1|>
_list = [... | Validation model for all query types. | Queries | [
"BSD-3-Clause-Clear"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Queries:
"""Validation model for all query types."""
def map(self):
"""Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries."""
<|body_0|>
def list(self):
"""Return a list of all query display names, inter... | stack_v2_sparse_classes_36k_train_004164 | 7,358 | permissive | [
{
"docstring": "Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries.",
"name": "map",
"signature": "def map(self)"
},
{
"docstring": "Return a list of all query display names, internal names, and enable state. Returns: {list} -- Dict of ... | 3 | stack_v2_sparse_classes_30k_test_000526 | Implement the Python class `Queries` described below.
Class description:
Validation model for all query types.
Method signatures and docstrings:
- def map(self): Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries.
- def list(self): Return a list of all query... | Implement the Python class `Queries` described below.
Class description:
Validation model for all query types.
Method signatures and docstrings:
- def map(self): Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries.
- def list(self): Return a list of all query... | 90c179f46ecc58562dbcd9ec6d761075a8699f79 | <|skeleton|>
class Queries:
"""Validation model for all query types."""
def map(self):
"""Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries."""
<|body_0|>
def list(self):
"""Return a list of all query display names, inter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Queries:
"""Validation model for all query types."""
def map(self):
"""Return a dict of all query display names, internal names, and enable state. Returns: {dict} -- Dict of queries."""
_map = {}
for query in SUPPORTED_QUERY_TYPES:
query_obj = getattr(self, query)
... | the_stack_v2_python_sparse | hyperglass/models/config/queries.py | GeeZeeS/hyperglass | train | 0 |
2b8d87586eb6662c10256fc004b80eaafe221199 | [
"super(PointNetInstanceSeg, self).__init__()\nself.conv1 = nn.Conv1d(n_channel, 64, 1)\nself.conv2 = nn.Conv1d(64, 64, 1)\nself.conv3 = nn.Conv1d(64, 64, 1)\nself.conv4 = nn.Conv1d(64, 128, 1)\nself.conv5 = nn.Conv1d(128, 1024, 1)\nself.bn1 = nn.BatchNorm1d(64)\nself.bn2 = nn.BatchNorm1d(64)\nself.bn3 = nn.BatchNor... | <|body_start_0|>
super(PointNetInstanceSeg, self).__init__()
self.conv1 = nn.Conv1d(n_channel, 64, 1)
self.conv2 = nn.Conv1d(64, 64, 1)
self.conv3 = nn.Conv1d(64, 64, 1)
self.conv4 = nn.Conv1d(64, 128, 1)
self.conv5 = nn.Conv1d(128, 1024, 1)
self.bn1 = nn.BatchNor... | PointNetInstanceSeg | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PointNetInstanceSeg:
def __init__(self, n_classes=3, n_channel=3):
"""v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def forward(self, pts, one_hot_vec):
""":param pts: [bs,4,n]: x,y,z,intensity :return: logits... | stack_v2_sparse_classes_36k_train_004165 | 11,900 | permissive | [
{
"docstring": "v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]",
"name": "__init__",
"signature": "def __init__(self, n_classes=3, n_channel=3)"
},
{
"docstring": ":param pts: [bs,4,n]: x,y,z,intensity :return: logits: [bs,n,2],scores for bkg/clutter an... | 2 | stack_v2_sparse_classes_30k_train_020796 | Implement the Python class `PointNetInstanceSeg` described below.
Class description:
Implement the PointNetInstanceSeg class.
Method signatures and docstrings:
- def __init__(self, n_classes=3, n_channel=3): v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]
- def forward(self, ... | Implement the Python class `PointNetInstanceSeg` described below.
Class description:
Implement the PointNetInstanceSeg class.
Method signatures and docstrings:
- def __init__(self, n_classes=3, n_channel=3): v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]
- def forward(self, ... | 64bcfa4b292dacc91f92f2542e11d489b1fa2c8a | <|skeleton|>
class PointNetInstanceSeg:
def __init__(self, n_classes=3, n_channel=3):
"""v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
<|body_0|>
def forward(self, pts, one_hot_vec):
""":param pts: [bs,4,n]: x,y,z,intensity :return: logits... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PointNetInstanceSeg:
def __init__(self, n_classes=3, n_channel=3):
"""v1 3D Instance Segmentation PointNet :param n_classes:3 :param one_hot_vec:[bs,n_classes]"""
super(PointNetInstanceSeg, self).__init__()
self.conv1 = nn.Conv1d(n_channel, 64, 1)
self.conv2 = nn.Conv1d(64, 64,... | the_stack_v2_python_sparse | frustum_pointnet/models/frustum_pointnets_v1_old.py | ayushjain1144/SeeingByMoving | train | 24 | |
5b3b8c2190d98f9d66c05abb56b88086652fe9d5 | [
"driver.find_element_by_xpath(\"//*[@id='moduleDisplay']/ul/li[3]\").click()\nsleep(1)\na = driver.find_element_by_xpath(\"//*[@id='treeview-1024-record-basicInfoMgtId']\")\nActionChains(driver).double_click(a).perform()\nsleep(1)\ndriver.find_element_by_id('treeview-1024-record-userMgtId').click()\nsleep(1)",
"d... | <|body_start_0|>
driver.find_element_by_xpath("//*[@id='moduleDisplay']/ul/li[3]").click()
sleep(1)
a = driver.find_element_by_xpath("//*[@id='treeview-1024-record-basicInfoMgtId']")
ActionChains(driver).double_click(a).perform()
sleep(1)
driver.find_element_by_id('treevi... | NEWFUNCTION | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NEWFUNCTION:
def LoadingMenues(self):
"""加载菜单"""
<|body_0|>
def NewFunciton(self):
"""新增用户"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
driver.find_element_by_xpath("//*[@id='moduleDisplay']/ul/li[3]").click()
sleep(1)
a = driver.... | stack_v2_sparse_classes_36k_train_004166 | 3,926 | no_license | [
{
"docstring": "加载菜单",
"name": "LoadingMenues",
"signature": "def LoadingMenues(self)"
},
{
"docstring": "新增用户",
"name": "NewFunciton",
"signature": "def NewFunciton(self)"
}
] | 2 | null | Implement the Python class `NEWFUNCTION` described below.
Class description:
Implement the NEWFUNCTION class.
Method signatures and docstrings:
- def LoadingMenues(self): 加载菜单
- def NewFunciton(self): 新增用户 | Implement the Python class `NEWFUNCTION` described below.
Class description:
Implement the NEWFUNCTION class.
Method signatures and docstrings:
- def LoadingMenues(self): 加载菜单
- def NewFunciton(self): 新增用户
<|skeleton|>
class NEWFUNCTION:
def LoadingMenues(self):
"""加载菜单"""
<|body_0|>
def Ne... | 426afef9d0462bb804d1bd3dd33dd6db1e759e0d | <|skeleton|>
class NEWFUNCTION:
def LoadingMenues(self):
"""加载菜单"""
<|body_0|>
def NewFunciton(self):
"""新增用户"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class NEWFUNCTION:
def LoadingMenues(self):
"""加载菜单"""
driver.find_element_by_xpath("//*[@id='moduleDisplay']/ul/li[3]").click()
sleep(1)
a = driver.find_element_by_xpath("//*[@id='treeview-1024-record-basicInfoMgtId']")
ActionChains(driver).double_click(a).perform()
... | the_stack_v2_python_sparse | pye/newfunction.py | CScorpio/lxc_Project | train | 0 | |
0f19f99ae1f59521485aa0c56c44f5cbb97d71f1 | [
"start = 0\nend = len(nums) - 1\nwhile start <= end:\n mid = (start + end) / 2\n if nums[mid - 1] != nums[mid] != nums[mid + 1]:\n return nums[mid]\n elif nums[mid - 1] == nums[mid]:\n end = mid - 1\n else:\n start = mid + 1",
"if len(nums) < 3:\n return nums[0]\nstart = 0\nend... | <|body_start_0|>
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) / 2
if nums[mid - 1] != nums[mid] != nums[mid + 1]:
return nums[mid]
elif nums[mid - 1] == nums[mid]:
end = mid - 1
else:
... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def _singleNonDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNonDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
start = 0
end = len(nu... | stack_v2_sparse_classes_36k_train_004167 | 2,085 | permissive | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "_singleNonDuplicate",
"signature": "def _singleNonDuplicate(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNonDuplicate",
"signature": "def singleNonDuplicate(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_000604 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def _singleNonDuplicate(self, nums): :type nums: List[int] :rtype: int
- def singleNonDuplicate(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 _singleNonDuplicate(self, nums): :type nums: List[int] :rtype: int
- def singleNonDuplicate(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
... | 0dd67edca4e0b0323cb5a7239f02ea46383cd15a | <|skeleton|>
class Solution:
def _singleNonDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNonDuplicate(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 _singleNonDuplicate(self, nums):
""":type nums: List[int] :rtype: int"""
start = 0
end = len(nums) - 1
while start <= end:
mid = (start + end) / 2
if nums[mid - 1] != nums[mid] != nums[mid + 1]:
return nums[mid]
... | the_stack_v2_python_sparse | 540.single-element-in-a-sorted-array.py | windard/leeeeee | train | 0 | |
c368fa9fa4591f43deb08a652ba2c835c5f9d9c1 | [
"self.follow_map = defaultdict(set)\nself.followed_map = defaultdict(set)\nself.tweet_map = defaultdict(list)\nself.post_map = defaultdict(list)\nself.tweet_stamp = 0",
"self.post_map[userId].append((self.tweet_stamp, tweetId))\nfor id in self.followed_map[userId]:\n insort(self.tweet_map[id], (self.tweet_stam... | <|body_start_0|>
self.follow_map = defaultdict(set)
self.followed_map = defaultdict(set)
self.tweet_map = defaultdict(list)
self.post_map = defaultdict(list)
self.tweet_stamp = 0
<|end_body_0|>
<|body_start_1|>
self.post_map[userId].append((self.tweet_stamp, tweetId))
... | Twitter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: None"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k_train_004168 | 3,247 | permissive | [
{
"docstring": "Initialize your data structure here.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Compose a new tweet. :type userId: int :type tweetId: int :rtype: None",
"name": "postTweet",
"signature": "def postTweet(self, userId, tweetId)"
},
{
"... | 5 | null | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: None
- def getNew... | Implement the Python class `Twitter` described below.
Class description:
Implement the Twitter class.
Method signatures and docstrings:
- def __init__(self): Initialize your data structure here.
- def postTweet(self, userId, tweetId): Compose a new tweet. :type userId: int :type tweetId: int :rtype: None
- def getNew... | fc5b1744af7be93f4dd01d6ad58d2bd12f7ed33f | <|skeleton|>
class Twitter:
def __init__(self):
"""Initialize your data structure here."""
<|body_0|>
def postTweet(self, userId, tweetId):
"""Compose a new tweet. :type userId: int :type tweetId: int :rtype: None"""
<|body_1|>
def getNewsFeed(self, userId):
"""Ret... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Twitter:
def __init__(self):
"""Initialize your data structure here."""
self.follow_map = defaultdict(set)
self.followed_map = defaultdict(set)
self.tweet_map = defaultdict(list)
self.post_map = defaultdict(list)
self.tweet_stamp = 0
def postTweet(self, use... | the_stack_v2_python_sparse | 355.Design-Twitter.py | mickey0524/leetcode | train | 27 | |
8c6888f209f3b528e29b704c1fd40a5026779e18 | [
"super(QueryThread, self).__init__()\nself.func_args = []\nself.host = host\nself.port = port\nself.time_cost = -1.0",
"logs = []\nwith socket(AF_INET, SOCK_STREAM) as s:\n try:\n t_start = time.time()\n s.connect((self.host, self.port))\n data = pickle.dumps(self.func_args)\n print... | <|body_start_0|>
super(QueryThread, self).__init__()
self.func_args = []
self.host = host
self.port = port
self.time_cost = -1.0
<|end_body_0|>
<|body_start_1|>
logs = []
with socket(AF_INET, SOCK_STREAM) as s:
try:
t_start = time.time... | QueryThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class QueryThread:
def __init__(self, host, port):
"""Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port: port of query target"""
<|body_0|>
def run(self):
"""Do the query as a single ... | stack_v2_sparse_classes_36k_train_004169 | 5,026 | no_license | [
{
"docstring": "Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port: port of query target",
"name": "__init__",
"signature": "def __init__(self, host, port)"
},
{
"docstring": "Do the query as a single thread... | 2 | stack_v2_sparse_classes_30k_train_009115 | Implement the Python class `QueryThread` described below.
Class description:
Implement the QueryThread class.
Method signatures and docstrings:
- def __init__(self, host, port): Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port:... | Implement the Python class `QueryThread` described below.
Class description:
Implement the QueryThread class.
Method signatures and docstrings:
- def __init__(self, host, port): Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port:... | 147d24d2c520c323c224f73c99da3b79f1278fb0 | <|skeleton|>
class QueryThread:
def __init__(self, host, port):
"""Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port: port of query target"""
<|body_0|>
def run(self):
"""Do the query as a single ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class QueryThread:
def __init__(self, host, port):
"""Define thread for query. :param pattern: query string, e.g. 'a'(raw string), 'a[a-z]b'(regex) :param host: host of query target :param port: port of query target"""
super(QueryThread, self).__init__()
self.func_args = []
self.host... | the_stack_v2_python_sparse | client.py | rexxy-sasori/Area_Constraint_Frequency_Analysis | train | 1 | |
81999fc2bd998aa8c191e3856d329f6d45631c35 | [
"super().__init__(self.PROBLEM_NAME)\nself.input_linked_list1 = input_linked_list1\nself.input_linked_list2 = input_linked_list2",
"print('Solving {} problem ...'.format(self.PROBLEM_NAME))\nnode1 = self.input_linked_list1.head\nnode2 = self.input_linked_list2.head\ncarry = 0\nsum_list = LinkedList()\nwhile node1... | <|body_start_0|>
super().__init__(self.PROBLEM_NAME)
self.input_linked_list1 = input_linked_list1
self.input_linked_list2 = input_linked_list2
<|end_body_0|>
<|body_start_1|>
print('Solving {} problem ...'.format(self.PROBLEM_NAME))
node1 = self.input_linked_list1.head
n... | Add Two Numbers | AddTwoNumbers | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Sol... | stack_v2_sparse_classes_36k_train_004170 | 2,269 | no_license | [
{
"docstring": "Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None",
"name": "__init__",
"signature": "def __init__(self, input_linked_list1, input_linked_list2)"
},
{
"docstring": "Solve the problem Note: O(n) (runtime) ... | 2 | stack_v2_sparse_classes_30k_train_005450 | Implement the Python class `AddTwoNumbers` described below.
Class description:
Add Two Numbers
Method signatures and docstrings:
- def __init__(self, input_linked_list1, input_linked_list2): Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None
-... | Implement the Python class `AddTwoNumbers` described below.
Class description:
Add Two Numbers
Method signatures and docstrings:
- def __init__(self, input_linked_list1, input_linked_list2): Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None
-... | 11f4d25cb211740514c119a60962d075a0817abd | <|skeleton|>
class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
<|body_0|>
def solve(self):
"""Sol... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class AddTwoNumbers:
"""Add Two Numbers"""
def __init__(self, input_linked_list1, input_linked_list2):
"""Add Two Numbers Args: input_linked_list1: First linked list input_linked_list2: Second linked list Returns: None Raises: None"""
super().__init__(self.PROBLEM_NAME)
self.input_linke... | the_stack_v2_python_sparse | python/problems/linked_list/add_two_numbers.py | santhosh-kumar/AlgorithmsAndDataStructures | train | 2 |
067bd797b76284abe461ca42e4932f0cd81dfbff | [
"self.init_data = init_data\nself._description = f'{init_data.name} ({init_data.host})'\nsuper().__init__(hass, _LOGGER, name=f'radiotherm {self.init_data.name}', update_interval=UPDATE_INTERVAL)",
"try:\n return await async_get_data(self.hass, self.init_data.tstat)\nexcept RadiothermTstatError as ex:\n msg... | <|body_start_0|>
self.init_data = init_data
self._description = f'{init_data.name} ({init_data.host})'
super().__init__(hass, _LOGGER, name=f'radiotherm {self.init_data.name}', update_interval=UPDATE_INTERVAL)
<|end_body_0|>
<|body_start_1|>
try:
return await async_get_data(... | DataUpdateCoordinator to gather data for radio thermostats. | RadioThermUpdateCoordinator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RadioThermUpdateCoordinator:
"""DataUpdateCoordinator to gather data for radio thermostats."""
def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None:
"""Initialize DataUpdateCoordinator."""
<|body_0|>
async def _async_update_data(self) -> RadioTh... | stack_v2_sparse_classes_36k_train_004171 | 1,742 | permissive | [
{
"docstring": "Initialize DataUpdateCoordinator.",
"name": "__init__",
"signature": "def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None"
},
{
"docstring": "Update data from the thermostat.",
"name": "_async_update_data",
"signature": "async def _async_update_... | 2 | null | Implement the Python class `RadioThermUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator to gather data for radio thermostats.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None: Initialize DataUpdateCoordinator.
- async def _as... | Implement the Python class `RadioThermUpdateCoordinator` described below.
Class description:
DataUpdateCoordinator to gather data for radio thermostats.
Method signatures and docstrings:
- def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None: Initialize DataUpdateCoordinator.
- async def _as... | 80caeafcb5b6e2f9da192d0ea6dd1a5b8244b743 | <|skeleton|>
class RadioThermUpdateCoordinator:
"""DataUpdateCoordinator to gather data for radio thermostats."""
def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None:
"""Initialize DataUpdateCoordinator."""
<|body_0|>
async def _async_update_data(self) -> RadioTh... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class RadioThermUpdateCoordinator:
"""DataUpdateCoordinator to gather data for radio thermostats."""
def __init__(self, hass: HomeAssistant, init_data: RadioThermInitData) -> None:
"""Initialize DataUpdateCoordinator."""
self.init_data = init_data
self._description = f'{init_data.name} ... | the_stack_v2_python_sparse | homeassistant/components/radiotherm/coordinator.py | home-assistant/core | train | 35,501 |
4fe3ca0bb2fc598d3b2ac0edbdb14627d4b8cabe | [
"if size <= 0:\n raise ValueError('Expected positive integer, got %d' % size)\nif len(radixes) != 0 and (not is_valid_radixes(radixes, size)):\n raise TypeError('Invalid radixes.')\nself.size = size\nself.radixes = tuple(radixes or [2] * size)\nself.utry = UnitaryMatrix.identity(int(np.prod(self.radixes)))\ns... | <|body_start_0|>
if size <= 0:
raise ValueError('Expected positive integer, got %d' % size)
if len(radixes) != 0 and (not is_valid_radixes(radixes, size)):
raise TypeError('Invalid radixes.')
self.size = size
self.radixes = tuple(radixes or [2] * size)
sel... | An Identity (No-OP) Gate. | IdentityGate | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class IdentityGate:
"""An Identity (No-OP) Gate."""
def __init__(self, size: int=1, radixes: Sequence[int]=[]) -> None:
"""Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gate acts on. radixes (Sequence[int]): The number of orthogo... | stack_v2_sparse_classes_36k_train_004172 | 1,580 | permissive | [
{
"docstring": "Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gate acts on. radixes (Sequence[int]): The number of orthogonal states for each qudit. Defaults to qubits.",
"name": "__init__",
"signature": "def __init__(self, size: int=1, radixe... | 2 | null | Implement the Python class `IdentityGate` described below.
Class description:
An Identity (No-OP) Gate.
Method signatures and docstrings:
- def __init__(self, size: int=1, radixes: Sequence[int]=[]) -> None: Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gat... | Implement the Python class `IdentityGate` described below.
Class description:
An Identity (No-OP) Gate.
Method signatures and docstrings:
- def __init__(self, size: int=1, radixes: Sequence[int]=[]) -> None: Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gat... | 3083218c2f4e3c3ce4ba027d12caa30c384d7665 | <|skeleton|>
class IdentityGate:
"""An Identity (No-OP) Gate."""
def __init__(self, size: int=1, radixes: Sequence[int]=[]) -> None:
"""Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gate acts on. radixes (Sequence[int]): The number of orthogo... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class IdentityGate:
"""An Identity (No-OP) Gate."""
def __init__(self, size: int=1, radixes: Sequence[int]=[]) -> None:
"""Creates an IdentityGate, defaulting to a single-qubit identity. Args: size (int) The number of qudits this gate acts on. radixes (Sequence[int]): The number of orthogonal states fo... | the_stack_v2_python_sparse | bqskit/ir/gates/constant/identity.py | mtreinish/bqskit | train | 0 |
06858e122cd77b5879f9ed866db061f9e15a40d8 | [
"if 6 * n < s or n < 1 or s < n:\n return 0\nif n == 1:\n return 1\nreturn self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self.getNSumCount(n - 1, s - 4) + self.getNSumCount(n - 1, s - 5) + self.getNSumCount(n - 1, s - 6)",
"num = [[0 for j in range(6 *... | <|body_start_0|>
if 6 * n < s or n < 1 or s < n:
return 0
if n == 1:
return 1
return self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self.getNSumCount(n - 1, s - 4) + self.getNSumCount(n - 1, s - 5) + self.getNSumCount... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def getNSumCount(self, n, s):
"""递归版本 :param n: :param s: :return:"""
<|body_0|>
def getNSumCountNotRecusion(self, n, s):
"""非递归版本 :param n: :param s: :return:"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if 6 * n < s or n < 1 or s < n:... | stack_v2_sparse_classes_36k_train_004173 | 1,137 | no_license | [
{
"docstring": "递归版本 :param n: :param s: :return:",
"name": "getNSumCount",
"signature": "def getNSumCount(self, n, s)"
},
{
"docstring": "非递归版本 :param n: :param s: :return:",
"name": "getNSumCountNotRecusion",
"signature": "def getNSumCountNotRecusion(self, n, s)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019843 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getNSumCount(self, n, s): 递归版本 :param n: :param s: :return:
- def getNSumCountNotRecusion(self, n, s): 非递归版本 :param n: :param s: :return: | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def getNSumCount(self, n, s): 递归版本 :param n: :param s: :return:
- def getNSumCountNotRecusion(self, n, s): 非递归版本 :param n: :param s: :return:
<|skeleton|>
class Solution:
d... | aec68ce90a9fbceaeb855efc2c83c047acbd53b5 | <|skeleton|>
class Solution:
def getNSumCount(self, n, s):
"""递归版本 :param n: :param s: :return:"""
<|body_0|>
def getNSumCountNotRecusion(self, n, s):
"""非递归版本 :param n: :param s: :return:"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def getNSumCount(self, n, s):
"""递归版本 :param n: :param s: :return:"""
if 6 * n < s or n < 1 or s < n:
return 0
if n == 1:
return 1
return self.getNSumCount(n - 1, s - 1) + self.getNSumCount(n - 1, s - 2) + self.getNSumCount(n - 1, s - 3) + self... | the_stack_v2_python_sparse | offer/offer 60 n个骰子点数.py | clhchtcjj/Algorithm | train | 5 | |
9ed8a01781911ca05be84579409c459c3bf93e1e | [
"super(Monitor, self).__init__()\nDEVICE_ID_LIST = GPUtil.getAvailable(order='memory', limit=1)\nif len(DEVICE_ID_LIST) < 1 or gpu_id is None:\n self.hasgpu = False\nelse:\n self.hasgpu = True\nself.gpu_id = gpu_id\nself.start_time = time.time()\nself.verbose = verbose\nself.stopped = False\nself.delay = dela... | <|body_start_0|>
super(Monitor, self).__init__()
DEVICE_ID_LIST = GPUtil.getAvailable(order='memory', limit=1)
if len(DEVICE_ID_LIST) < 1 or gpu_id is None:
self.hasgpu = False
else:
self.hasgpu = True
self.gpu_id = gpu_id
self.start_time = time.ti... | Monitor Class. | Monitor | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Monitor:
"""Monitor Class."""
def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False):
"""Initialize monitor, log_dir and gpu_id are needed."""
<|body_0|>
def write_cpu_status(self):
"""Write CPU status."""
<|body_1|>
def write_mem_status(self)... | stack_v2_sparse_classes_36k_train_004174 | 6,947 | permissive | [
{
"docstring": "Initialize monitor, log_dir and gpu_id are needed.",
"name": "__init__",
"signature": "def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False)"
},
{
"docstring": "Write CPU status.",
"name": "write_cpu_status",
"signature": "def write_cpu_status(self)"
},
{
... | 6 | stack_v2_sparse_classes_30k_train_020355 | Implement the Python class `Monitor` described below.
Class description:
Monitor Class.
Method signatures and docstrings:
- def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False): Initialize monitor, log_dir and gpu_id are needed.
- def write_cpu_status(self): Write CPU status.
- def write_mem_status(self): Wr... | Implement the Python class `Monitor` described below.
Class description:
Monitor Class.
Method signatures and docstrings:
- def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False): Initialize monitor, log_dir and gpu_id are needed.
- def write_cpu_status(self): Write CPU status.
- def write_mem_status(self): Wr... | 625189d5e1002a3edc27c3e3ce075fddf7ae1c92 | <|skeleton|>
class Monitor:
"""Monitor Class."""
def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False):
"""Initialize monitor, log_dir and gpu_id are needed."""
<|body_0|>
def write_cpu_status(self):
"""Write CPU status."""
<|body_1|>
def write_mem_status(self)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Monitor:
"""Monitor Class."""
def __init__(self, log_dir, delay=1, gpu_id=0, verbose=False):
"""Initialize monitor, log_dir and gpu_id are needed."""
super(Monitor, self).__init__()
DEVICE_ID_LIST = GPUtil.getAvailable(order='memory', limit=1)
if len(DEVICE_ID_LIST) < 1 or... | the_stack_v2_python_sparse | beta_rec/utils/monitor.py | beta-team/beta-recsys | train | 156 |
a84ed7a2f1b197ed4fda658846a507544fc8d388 | [
"if '.csv' not in file_path:\n file_path += '.csv'\nself.file_path = file_path\nself.overwrite = overwrite\nif os.path.exists(file_path):\n print('[WARN]: Log already exist!!')\n if overwrite is True:\n print('[WARN]: Overwriting enabled! This data will be deleted!')\n os.remove(file_path)",
... | <|body_start_0|>
if '.csv' not in file_path:
file_path += '.csv'
self.file_path = file_path
self.overwrite = overwrite
if os.path.exists(file_path):
print('[WARN]: Log already exist!!')
if overwrite is True:
print('[WARN]: Overwriting e... | A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list | CSVLogging | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CSVLogging:
"""A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list"""
def __init__(self, file_path: str, overwrite=False):
"""A Class... | stack_v2_sparse_classes_36k_train_004175 | 2,068 | no_license | [
{
"docstring": "A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list Parameters ---------- file_path : str The path to log the csv file. overwrite : bool A status... | 2 | stack_v2_sparse_classes_30k_train_003472 | Implement the Python class `CSVLogging` described below.
Class description:
A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list
Method signatures and docstrings:
- def... | Implement the Python class `CSVLogging` described below.
Class description:
A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list
Method signatures and docstrings:
- def... | 38da6c8bf47df2d2382d31f04faf63649b7d8ab0 | <|skeleton|>
class CSVLogging:
"""A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list"""
def __init__(self, file_path: str, overwrite=False):
"""A Class... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CSVLogging:
"""A Class to build a callback for logging the given dictionary data in csv files NOTE: The dictionary data's key will be used as column_name and values will be used as column values. Values must be a list"""
def __init__(self, file_path: str, overwrite=False):
"""A Class to build a c... | the_stack_v2_python_sparse | callbacks/__csv_logging.py | JoelRaymann/polyp-segmentation | train | 0 |
c603be224b82cbaeec507fc0990aaa3218ea0e4d | [
"startTime = datetime.datetime.now()\nclient = dml.pymongo.MongoClient()\nrepo = client.repo\nrepo.authenticate('kobesay', 'kobesay')\nrepo.dropCollection('income_infrastructure_pearsonr')\nrepo.createCollection('income_infrastructure_pearsonr')\nincome_infrastructure = repo.kobesay.income_infrastructure.find()\nin... | <|body_start_0|>
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.dropCollection('income_infrastructure_pearsonr')
repo.createCollection('income_infrastructure_pearsonr')
income_... | cal_pearsonr | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class cal_pearsonr:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_36k_train_004176 | 5,352 | no_license | [
{
"docstring": "Retrieve some data sets (not using the API here for the sake of simplicity).",
"name": "execute",
"signature": "def execute(trial=False)"
},
{
"docstring": "Create the provenance document describing everything happening in this script. Each run of the script will generate a new d... | 2 | null | Implement the Python class `cal_pearsonr` described below.
Class description:
Implement the cal_pearsonr class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | Implement the Python class `cal_pearsonr` described below.
Class description:
Implement the cal_pearsonr class.
Method signatures and docstrings:
- def execute(trial=False): Retrieve some data sets (not using the API here for the sake of simplicity).
- def provenance(doc=prov.model.ProvDocument(), startTime=None, end... | 0df485d0469c5451ebdcd684bed2a0960ba3ab84 | <|skeleton|>
class cal_pearsonr:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
<|body_0|>
def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):
"""Create the provenance document describing everything ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class cal_pearsonr:
def execute(trial=False):
"""Retrieve some data sets (not using the API here for the sake of simplicity)."""
startTime = datetime.datetime.now()
client = dml.pymongo.MongoClient()
repo = client.repo
repo.authenticate('kobesay', 'kobesay')
repo.drop... | the_stack_v2_python_sparse | kobesay/cal_pearsonr.py | lingyigu/course-2017-spr-proj | train | 0 | |
754503282e85f93da799d11aaa717818f1a7e263 | [
"super().__init__()\nif padding is None:\n padding = (kernel_size - 1) // 2\nself.depthwise = nn.Conv2d(nin, nin, kernel_size=kernel_size, stride=stride, padding=padding, groups=nin)\nself.pointwise = nn.Conv2d(nin, nout, kernel_size=1)",
"out = self.depthwise(x)\nout = self.pointwise(out)\nreturn out"
] | <|body_start_0|>
super().__init__()
if padding is None:
padding = (kernel_size - 1) // 2
self.depthwise = nn.Conv2d(nin, nin, kernel_size=kernel_size, stride=stride, padding=padding, groups=nin)
self.pointwise = nn.Conv2d(nin, nout, kernel_size=1)
<|end_body_0|>
<|body_start... | Depthwise seperable convolution operation. | depthwise_separable_conv_general | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
... | stack_v2_sparse_classes_36k_train_004177 | 2,586 | permissive | [
{
"docstring": "Initialize depthwise_separable_conv_general.",
"name": "__init__",
"signature": "def __init__(self, nin, nout, stride, kernel_size=3, padding=None)"
},
{
"docstring": "Implement forward.",
"name": "forward",
"signature": "def forward(self, x)"
}
] | 2 | null | Implement the Python class `depthwise_separable_conv_general` described below.
Class description:
Depthwise seperable convolution operation.
Method signatures and docstrings:
- def __init__(self, nin, nout, stride, kernel_size=3, padding=None): Initialize depthwise_separable_conv_general.
- def forward(self, x): Impl... | Implement the Python class `depthwise_separable_conv_general` described below.
Class description:
Depthwise seperable convolution operation.
Method signatures and docstrings:
- def __init__(self, nin, nout, stride, kernel_size=3, padding=None): Initialize depthwise_separable_conv_general.
- def forward(self, x): Impl... | 12e37a1991eb6771a2999fe0a46ddda920c47948 | <|skeleton|>
class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
<|body_0|>
def forward(self, x):
"""Implement forward."""
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class depthwise_separable_conv_general:
"""Depthwise seperable convolution operation."""
def __init__(self, nin, nout, stride, kernel_size=3, padding=None):
"""Initialize depthwise_separable_conv_general."""
super().__init__()
if padding is None:
padding = (kernel_size - 1) ... | the_stack_v2_python_sparse | vega/networks/pytorch/customs/utils/ops.py | huawei-noah/vega | train | 850 |
9ceeaecd6eb28b8e2a803aeca3251367da63b365 | [
"TextStaticPanel.__init__(self, container, *args, **kwargs)\nself.attributes[-1].Destroy()\nself.attributes[-1] = wx.GenericDatePickerCtrl(self, wx.ID_ANY, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)\nself._set_attributes(self.attributes)",
"attributes = []\nfor atr in self.attributes[0:-1]:\n attributes.append(... | <|body_start_0|>
TextStaticPanel.__init__(self, container, *args, **kwargs)
self.attributes[-1].Destroy()
self.attributes[-1] = wx.GenericDatePickerCtrl(self, wx.ID_ANY, style=wx.DP_DROPDOWN | wx.DP_SHOWCENTURY)
self._set_attributes(self.attributes)
<|end_body_0|>
<|body_start_1|>
... | StaticNursePanel | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class StaticNursePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute values."""... | stack_v2_sparse_classes_36k_train_004178 | 11,497 | no_license | [
{
"docstring": "The default constructor container: a data container object",
"name": "__init__",
"signature": "def __init__(self, container, *args, **kwargs)"
},
{
"docstring": "Return a list of all attributes. return: a list, that contains this panel's attribute values.",
"name": "get_attri... | 3 | null | Implement the Python class `StaticNursePanel` described below.
Class description:
Implement the StaticNursePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a list of all attrib... | Implement the Python class `StaticNursePanel` described below.
Class description:
Implement the StaticNursePanel class.
Method signatures and docstrings:
- def __init__(self, container, *args, **kwargs): The default constructor container: a data container object
- def get_attributes(self): Return a list of all attrib... | 781ce419b51b5bd99bbd1b155c03843cb434cb8c | <|skeleton|>
class StaticNursePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
<|body_0|>
def get_attributes(self):
"""Return a list of all attributes. return: a list, that contains this panel's attribute values."""... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class StaticNursePanel:
def __init__(self, container, *args, **kwargs):
"""The default constructor container: a data container object"""
TextStaticPanel.__init__(self, container, *args, **kwargs)
self.attributes[-1].Destroy()
self.attributes[-1] = wx.GenericDatePickerCtrl(self, wx.ID... | the_stack_v2_python_sparse | gui/static_data.py | mcepar1/Scheduler | train | 0 | |
bf4ca549cec0eefcc8df7d96e98d7a0933000892 | [
"super(SenderAddressAPITestCase, cls).setUpTestData()\ncls.localconfig.parameters.set_value('enable_admin_limits', False, app='limits')\ncls.localconfig.save()\nfactories.populate_database()\ncls.sa1 = factories.SenderAddressFactory(address='test@domain.ext', mailbox__user__username='user@test.com', mailbox__addres... | <|body_start_0|>
super(SenderAddressAPITestCase, cls).setUpTestData()
cls.localconfig.parameters.set_value('enable_admin_limits', False, app='limits')
cls.localconfig.save()
factories.populate_database()
cls.sa1 = factories.SenderAddressFactory(address='test@domain.ext', mailbox_... | Check SenderAddress API. | SenderAddressAPITestCase | [
"ISC"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SenderAddressAPITestCase:
"""Check SenderAddress API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_list(self):
"""Retrieve a list of sender addresses."""
<|body_1|>
def test_create(self):
"""Create a new sender addre... | stack_v2_sparse_classes_36k_train_004179 | 33,144 | permissive | [
{
"docstring": "Create test data.",
"name": "setUpTestData",
"signature": "def setUpTestData(cls)"
},
{
"docstring": "Retrieve a list of sender addresses.",
"name": "test_list",
"signature": "def test_list(self)"
},
{
"docstring": "Create a new sender addresses.",
"name": "te... | 6 | stack_v2_sparse_classes_30k_train_021104 | Implement the Python class `SenderAddressAPITestCase` described below.
Class description:
Check SenderAddress API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_list(self): Retrieve a list of sender addresses.
- def test_create(self): Create a new sender addresses.
- def tes... | Implement the Python class `SenderAddressAPITestCase` described below.
Class description:
Check SenderAddress API.
Method signatures and docstrings:
- def setUpTestData(cls): Create test data.
- def test_list(self): Retrieve a list of sender addresses.
- def test_create(self): Create a new sender addresses.
- def tes... | df699aab0799ec1725b6b89be38e56285821c889 | <|skeleton|>
class SenderAddressAPITestCase:
"""Check SenderAddress API."""
def setUpTestData(cls):
"""Create test data."""
<|body_0|>
def test_list(self):
"""Retrieve a list of sender addresses."""
<|body_1|>
def test_create(self):
"""Create a new sender addre... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SenderAddressAPITestCase:
"""Check SenderAddress API."""
def setUpTestData(cls):
"""Create test data."""
super(SenderAddressAPITestCase, cls).setUpTestData()
cls.localconfig.parameters.set_value('enable_admin_limits', False, app='limits')
cls.localconfig.save()
fac... | the_stack_v2_python_sparse | modoboa/admin/api/v1/tests.py | modoboa/modoboa | train | 2,201 |
b0c06c8089ac2768d8801a35de8d06e33cafb50d | [
"self.sum = 0\nself.queue = deque()\nself.size = size",
"if len(self.queue) < self.size:\n self.sum += val\n self.queue.append(val)\nelse:\n self.sum += val - self.queue.popleft()\n self.queue.append(val)\nreturn self.sum / len(self.queue)"
] | <|body_start_0|>
self.sum = 0
self.queue = deque()
self.size = size
<|end_body_0|>
<|body_start_1|>
if len(self.queue) < self.size:
self.sum += val
self.queue.append(val)
else:
self.sum += val - self.queue.popleft()
self.queue.appe... | First version | MovingAverage | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MovingAverage:
"""First version"""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
self.sum = 0
... | stack_v2_sparse_classes_36k_train_004180 | 1,623 | no_license | [
{
"docstring": "Initialize your data structure here. :type size: int",
"name": "__init__",
"signature": "def __init__(self, size)"
},
{
"docstring": ":type val: int :rtype: float",
"name": "next",
"signature": "def next(self, val)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020324 | Implement the Python class `MovingAverage` described below.
Class description:
First version
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float | Implement the Python class `MovingAverage` described below.
Class description:
First version
Method signatures and docstrings:
- def __init__(self, size): Initialize your data structure here. :type size: int
- def next(self, val): :type val: int :rtype: float
<|skeleton|>
class MovingAverage:
"""First version"""... | 27a85e20605393a5eca3f8bd7d42c389612493d5 | <|skeleton|>
class MovingAverage:
"""First version"""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
<|body_0|>
def next(self, val):
""":type val: int :rtype: float"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class MovingAverage:
"""First version"""
def __init__(self, size):
"""Initialize your data structure here. :type size: int"""
self.sum = 0
self.queue = deque()
self.size = size
def next(self, val):
""":type val: int :rtype: float"""
if len(self.queue) < self... | the_stack_v2_python_sparse | Leetcode_Algorithm/Python3/346_Moving_Average_from_Data_Stream.py | ChihYunPai/Data-Structure-and-Algorithms | train | 0 |
e3adbb3aa9890d01f88cb8c6b0df302b8195111a | [
"def default(obj):\n if hasattr(obj, '__json__'):\n return obj.__json__(request)\n obj_iface = providedBy(obj)\n adapters = self.components.adapters\n result = adapters.lookup((obj_iface,), IJSONAdapter, default=_marker)\n if result is _marker:\n obj_repr = repr(obj)\n raise Type... | <|body_start_0|>
def default(obj):
if hasattr(obj, '__json__'):
return obj.__json__(request)
obj_iface = providedBy(obj)
adapters = self.components.adapters
result = adapters.lookup((obj_iface,), IJSONAdapter, default=_marker)
if result... | JSON renderer that inject to_serializable as default for json or simplejson dumps call. | JSONRenderer | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JSONRenderer:
"""JSON renderer that inject to_serializable as default for json or simplejson dumps call."""
def _make_default(self, request: Request):
"""Make default function is not used anymore, just here to explicit it."""
<|body_0|>
def __call__(self, info) -> t.Call... | stack_v2_sparse_classes_36k_train_004181 | 1,750 | no_license | [
{
"docstring": "Make default function is not used anymore, just here to explicit it.",
"name": "_make_default",
"signature": "def _make_default(self, request: Request)"
},
{
"docstring": "Return a plain JSON-encoded string with content-type ``application/json``. The content-type may be overridde... | 2 | stack_v2_sparse_classes_30k_val_000883 | Implement the Python class `JSONRenderer` described below.
Class description:
JSON renderer that inject to_serializable as default for json or simplejson dumps call.
Method signatures and docstrings:
- def _make_default(self, request: Request): Make default function is not used anymore, just here to explicit it.
- de... | Implement the Python class `JSONRenderer` described below.
Class description:
JSON renderer that inject to_serializable as default for json or simplejson dumps call.
Method signatures and docstrings:
- def _make_default(self, request: Request): Make default function is not used anymore, just here to explicit it.
- de... | 324810e0207233e1fdaecdbc6fef1031eac1f6c7 | <|skeleton|>
class JSONRenderer:
"""JSON renderer that inject to_serializable as default for json or simplejson dumps call."""
def _make_default(self, request: Request):
"""Make default function is not used anymore, just here to explicit it."""
<|body_0|>
def __call__(self, info) -> t.Call... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class JSONRenderer:
"""JSON renderer that inject to_serializable as default for json or simplejson dumps call."""
def _make_default(self, request: Request):
"""Make default function is not used anymore, just here to explicit it."""
def default(obj):
if hasattr(obj, '__json__'):
... | the_stack_v2_python_sparse | src/briefy/ws/renderer.py | BriefyHQ/briefy.ws | train | 0 |
c17c6eb7b26c320fa772c98cfe42b53e8fb9f776 | [
"super(Attention, self).__init__()\nself.encoder_att = nn.Linear(encoder_dim, attention_dim)\nself.decoder_att = nn.Linear(decoder_dim, attention_dim)\nself.full_att = nn.Linear(attention_dim, 1)\nself.relu = nn.ReLU()\nself.softmax = nn.Softmax(dim=1)",
"att1 = self.encoder_att(encoder_out)\natt2 = self.decoder_... | <|body_start_0|>
super(Attention, self).__init__()
self.encoder_att = nn.Linear(encoder_dim, attention_dim)
self.decoder_att = nn.Linear(decoder_dim, attention_dim)
self.full_att = nn.Linear(attention_dim, 1)
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1)
<|end_bo... | Attention Network. | Attention | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_36k_train_004182 | 11,050 | permissive | [
{
"docstring": ":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network",
"name": "__init__",
"signature": "def __init__(self, encoder_dim, decoder_dim, attention_dim)"
},
{
"docstring": "Forward propagation... | 2 | stack_v2_sparse_classes_30k_test_000373 | Implement the Python class `Attention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the ... | Implement the Python class `Attention` described below.
Class description:
Attention Network.
Method signatures and docstrings:
- def __init__(self, encoder_dim, decoder_dim, attention_dim): :param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the ... | 8ee91f56cba66f8d66d47f995ea74ff192956cb7 | <|skeleton|>
class Attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
<|body_0|>
def forward(... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Attention:
"""Attention Network."""
def __init__(self, encoder_dim, decoder_dim, attention_dim):
""":param encoder_dim: feature size of encoded images :param decoder_dim: size of decoder's RNN :param attention_dim: size of the attention network"""
super(Attention, self).__init__()
... | the_stack_v2_python_sparse | gan/models/ocr/densenet.py | TIBHannover/formula_gan | train | 14 |
cf4bbfb06789789ee4f34e6ff5a2d6004e0b583c | [
"self.add_class('custom', 1, 'Blue_Marble')\nself.add_class('custom', 2, 'Non_Blue_Marble')\nassert subset in ['train', 'val']\ndataset_dir = os.path.join(dataset_dir, subset)\nannotations = json.load(open(os.path.join(dataset_dir, 'labels/marbles_two_class_VGG_json_format.json')))\nannotations = list(annotations.v... | <|body_start_0|>
self.add_class('custom', 1, 'Blue_Marble')
self.add_class('custom', 2, 'Non_Blue_Marble')
assert subset in ['train', 'val']
dataset_dir = os.path.join(dataset_dir, subset)
annotations = json.load(open(os.path.join(dataset_dir, 'labels/marbles_two_class_VGG_json_f... | CustomDataset | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CustomDataset:
def load_custom(self, dataset_dir, subset):
"""Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val"""
<|body_0|>
def load_mask(self, image_id):
"""Generate instance masks for an image. R... | stack_v2_sparse_classes_36k_train_004183 | 13,370 | no_license | [
{
"docstring": "Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val",
"name": "load_custom",
"signature": "def load_custom(self, dataset_dir, subset)"
},
{
"docstring": "Generate instance masks for an image. Returns: masks: A bool... | 3 | null | Implement the Python class `CustomDataset` described below.
Class description:
Implement the CustomDataset class.
Method signatures and docstrings:
- def load_custom(self, dataset_dir, subset): Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val
- def ... | Implement the Python class `CustomDataset` described below.
Class description:
Implement the CustomDataset class.
Method signatures and docstrings:
- def load_custom(self, dataset_dir, subset): Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val
- def ... | 4b8c0bd4274bc4d5e906a4952988c7f3e8db74c5 | <|skeleton|>
class CustomDataset:
def load_custom(self, dataset_dir, subset):
"""Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val"""
<|body_0|>
def load_mask(self, image_id):
"""Generate instance masks for an image. R... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CustomDataset:
def load_custom(self, dataset_dir, subset):
"""Load a subset of the custom dataset. dataset_dir: Root directory of the dataset. subset: Subset to load: train or val"""
self.add_class('custom', 1, 'Blue_Marble')
self.add_class('custom', 2, 'Non_Blue_Marble')
asser... | the_stack_v2_python_sparse | 286-Object detection using mask RCNN - end to end/286-marbles_maskrcnn_VGG_style_labels.py | bnsreenu/python_for_microscopists | train | 3,010 | |
ceba0d60df7913255f7a2af9a0c5a667f4df4183 | [
"this_dir, this_filename = os.path.split(__file__)\ncylinderpath = Filename.fromOsSpecific(os.path.join(this_dir, 'geomprim', 'cylinder.egg'))\nconepath = Filename.fromOsSpecific(os.path.join(this_dir, 'geomprim', 'sphere.egg'))\nboxpath = Filename.fromOsSpecific(os.path.join(this_dir, 'geomprim', 'box.egg'))\nself... | <|body_start_0|>
this_dir, this_filename = os.path.split(__file__)
cylinderpath = Filename.fromOsSpecific(os.path.join(this_dir, 'geomprim', 'cylinder.egg'))
conepath = Filename.fromOsSpecific(os.path.join(this_dir, 'geomprim', 'sphere.egg'))
boxpath = Filename.fromOsSpecific(os.path.joi... | use class to preload files and generate various models | PandaGeomGen | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PandaGeomGen:
"""use class to preload files and generate various models"""
def __init__(self):
"""prepload the files the models will be instanceTo nodepaths to avoid frequent disk access"""
<|body_0|>
def gendumbbell(self, spos=None, epos=None, length=None, thickness=1.5... | stack_v2_sparse_classes_36k_train_004184 | 31,568 | no_license | [
{
"docstring": "prepload the files the models will be instanceTo nodepaths to avoid frequent disk access",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "generate a dumbbell to plot the stick model of a robot the function is essentially a copy of pandaplotutils/pandageo... | 3 | stack_v2_sparse_classes_30k_train_004920 | Implement the Python class `PandaGeomGen` described below.
Class description:
use class to preload files and generate various models
Method signatures and docstrings:
- def __init__(self): prepload the files the models will be instanceTo nodepaths to avoid frequent disk access
- def gendumbbell(self, spos=None, epos=... | Implement the Python class `PandaGeomGen` described below.
Class description:
use class to preload files and generate various models
Method signatures and docstrings:
- def __init__(self): prepload the files the models will be instanceTo nodepaths to avoid frequent disk access
- def gendumbbell(self, spos=None, epos=... | 60e24c28a6b39621a235187483d9a13cbbffe987 | <|skeleton|>
class PandaGeomGen:
"""use class to preload files and generate various models"""
def __init__(self):
"""prepload the files the models will be instanceTo nodepaths to avoid frequent disk access"""
<|body_0|>
def gendumbbell(self, spos=None, epos=None, length=None, thickness=1.5... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PandaGeomGen:
"""use class to preload files and generate various models"""
def __init__(self):
"""prepload the files the models will be instanceTo nodepaths to avoid frequent disk access"""
this_dir, this_filename = os.path.split(__file__)
cylinderpath = Filename.fromOsSpecific(os... | the_stack_v2_python_sparse | pandaplotutils/pandageom.py | wanweiwei07/pyhiro | train | 7 |
942758d75489765690d5445e08ecc8d21116a1d1 | [
"if people == []:\n return []\nresult = []\nmin_1 = float('inf')\nself.sets = set()\nfor p in people:\n if p[1] == 0:\n min_1 = min(min_1, p[0])\npeople.remove([min_1, 0])\nresult.append([min_1, 0])\nprint(people)\nwhile len(people) > 0:\n min_2 = float('inf')\n for p in people:\n if p[0] ... | <|body_start_0|>
if people == []:
return []
result = []
min_1 = float('inf')
self.sets = set()
for p in people:
if p[1] == 0:
min_1 = min(min_1, p[0])
people.remove([min_1, 0])
result.append([min_1, 0])
print(people)... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue_1(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
def reconstructQueue_2(self,... | stack_v2_sparse_classes_36k_train_004185 | 2,801 | no_license | [
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue",
"signature": "def reconstructQueue(self, people)"
},
{
"docstring": ":type people: List[List[int]] :rtype: List[List[int]]",
"name": "reconstructQueue_1",
"signature": "def reconstructQueu... | 3 | stack_v2_sparse_classes_30k_train_020044 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue_1(self, people): :type people: List[List[int]] :rtype: List[List[... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def reconstructQueue(self, people): :type people: List[List[int]] :rtype: List[List[int]]
- def reconstructQueue_1(self, people): :type people: List[List[int]] :rtype: List[List[... | 679a2b246b8b6bb7fc55ed1c8096d3047d6d4461 | <|skeleton|>
class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_0|>
def reconstructQueue_1(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
<|body_1|>
def reconstructQueue_2(self,... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def reconstructQueue(self, people):
""":type people: List[List[int]] :rtype: List[List[int]]"""
if people == []:
return []
result = []
min_1 = float('inf')
self.sets = set()
for p in people:
if p[1] == 0:
min_1 =... | the_stack_v2_python_sparse | QueueReconstructionByHeight_MID_406.py | 953250587/leetcode-python | train | 2 | |
f86d3a5f61d581359e79d61a791375dde06efb4b | [
"self.interval = interval\nself.files = files\nself.Lases = []\nthread = threading.Thread(target=self.run, args=())\nthread.daemon = True\nthread.start()",
"for f in self.files:\n print('Las being loaded in background')\n self.Lases.append(lasio.read(f))\nprint('Loading complete...')"
] | <|body_start_0|>
self.interval = interval
self.files = files
self.Lases = []
thread = threading.Thread(target=self.run, args=())
thread.daemon = True
thread.start()
<|end_body_0|>
<|body_start_1|>
for f in self.files:
print('Las being loaded in backgr... | Threading example class The run() method will be started and it will run in the background until the application exits. | LasLoadThread | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LasLoadThread:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, files=[], interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
... | stack_v2_sparse_classes_36k_train_004186 | 1,071 | no_license | [
{
"docstring": "Constructor :type interval: int :param interval: Check interval, in seconds",
"name": "__init__",
"signature": "def __init__(self, files=[], interval=1)"
},
{
"docstring": "Method that runs forever",
"name": "run",
"signature": "def run(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_019136 | Implement the Python class `LasLoadThread` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, files=[], interval=1): Constructor :type interval: int :param in... | Implement the Python class `LasLoadThread` described below.
Class description:
Threading example class The run() method will be started and it will run in the background until the application exits.
Method signatures and docstrings:
- def __init__(self, files=[], interval=1): Constructor :type interval: int :param in... | 80893dc7652aa4229d041bc5409548a079a5ec39 | <|skeleton|>
class LasLoadThread:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, files=[], interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
<|body_0|>
... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class LasLoadThread:
"""Threading example class The run() method will be started and it will run in the background until the application exits."""
def __init__(self, files=[], interval=1):
"""Constructor :type interval: int :param interval: Check interval, in seconds"""
self.interval = interval... | the_stack_v2_python_sparse | AutoSplice/LasLoadThread.py | narunbabu/loggy2 | train | 0 |
ca56ef3fd95ed0c317504ca263fe636c0766d284 | [
"instance = self.get_object()\ndata = HojaRutaSerializer(instance).data\ndetalles = DetalleHojaRuta.objects.filter(hoja_ruta=instance).order_by('numero_orden')\ndata['detalle_hoja_ruta'] = DetalleHojaRutaSerializer(detalles, many=True).data\nreturn Response(data)",
"partial = kwargs.pop('partial', False)\ninstanc... | <|body_start_0|>
instance = self.get_object()
data = HojaRutaSerializer(instance).data
detalles = DetalleHojaRuta.objects.filter(hoja_ruta=instance).order_by('numero_orden')
data['detalle_hoja_ruta'] = DetalleHojaRutaSerializer(detalles, many=True).data
return Response(data)
<|en... | HojaRutaRetrieveUpdateAPIView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HojaRutaRetrieveUpdateAPIView:
def retrieve(self, request, *args, **kwargs):
"""Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :param kwargs: :return: Retorna el detalle de contactos asignados a la hoja de ruta"""
<|body_0|>
def upda... | stack_v2_sparse_classes_36k_train_004187 | 16,877 | no_license | [
{
"docstring": "Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :param kwargs: :return: Retorna el detalle de contactos asignados a la hoja de ruta",
"name": "retrieve",
"signature": "def retrieve(self, request, *args, **kwargs)"
},
{
"docstring": "Utiliz... | 2 | stack_v2_sparse_classes_30k_train_017290 | Implement the Python class `HojaRutaRetrieveUpdateAPIView` described below.
Class description:
Implement the HojaRutaRetrieveUpdateAPIView class.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :... | Implement the Python class `HojaRutaRetrieveUpdateAPIView` described below.
Class description:
Implement the HojaRutaRetrieveUpdateAPIView class.
Method signatures and docstrings:
- def retrieve(self, request, *args, **kwargs): Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :... | b9c749842c60fa6b8db33a074d8541a659bb7aa8 | <|skeleton|>
class HojaRutaRetrieveUpdateAPIView:
def retrieve(self, request, *args, **kwargs):
"""Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :param kwargs: :return: Retorna el detalle de contactos asignados a la hoja de ruta"""
<|body_0|>
def upda... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class HojaRutaRetrieveUpdateAPIView:
def retrieve(self, request, *args, **kwargs):
"""Retorna el detalle de contactos asignados a la hoja de ruta :param request: :param args: :param kwargs: :return: Retorna el detalle de contactos asignados a la hoja de ruta"""
instance = self.get_object()
d... | the_stack_v2_python_sparse | hoja_ruta/views.py | rubengocio/ighor | train | 0 | |
1fda3bc8025054e67e219de47d7c8bdfa5750928 | [
"self.access_key = access_key\nself.s3_config = s3_config\nself.secret_key = secret_key\nself.snapshot_prefix_name = snapshot_prefix_name\nself.view_id = view_id",
"if dictionary is None:\n return None\naccess_key = dictionary.get('accessKey')\ns3_config = cohesity_management_sdk.models.s3_bucket_config_proto.... | <|body_start_0|>
self.access_key = access_key
self.s3_config = s3_config
self.secret_key = secret_key
self.snapshot_prefix_name = snapshot_prefix_name
self.view_id = view_id
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
access_key... | Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp for it to for doing all s3 communications. s3_config (S3BucketConfigProto): For source ini... | S3ViewBackupProperties | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class S3ViewBackupProperties:
"""Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp for it to for doing all s3 communication... | stack_v2_sparse_classes_36k_train_004188 | 3,053 | permissive | [
{
"docstring": "Constructor for the S3ViewBackupProperties class",
"name": "__init__",
"signature": "def __init__(self, access_key=None, s3_config=None, secret_key=None, snapshot_prefix_name=None, view_id=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: diction... | 2 | null | Implement the Python class `S3ViewBackupProperties` described below.
Class description:
Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp f... | Implement the Python class `S3ViewBackupProperties` described below.
Class description:
Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp f... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class S3ViewBackupProperties:
"""Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp for it to for doing all s3 communication... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class S3ViewBackupProperties:
"""Implementation of the 'S3ViewBackupProperties' model. TODO: type description here. Attributes: access_key (string): Access key for the buckets which will be created for the source initiated jobs. This needs to be passed to Netapp for it to for doing all s3 communications. s3_config ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/s3_view_backup_properties.py | cohesity/management-sdk-python | train | 24 |
60bebdb674c976fd92bd1d7304e6dd380e1371db | [
"if ctx.config.get('csrf', True):\n headers = request.headers\n provided_token = _extract_token_from_headers(headers)\n if provided_token is None:\n raise CsrfTokenRequired()\n if provided_token not in _get_tokens():\n raise CsrfTokenInvalid()",
"new_token = _generate_token()\n_store_tok... | <|body_start_0|>
if ctx.config.get('csrf', True):
headers = request.headers
provided_token = _extract_token_from_headers(headers)
if provided_token is None:
raise CsrfTokenRequired()
if provided_token not in _get_tokens():
raise Csr... | A CSRF protection plugin for Micron. | Plugin | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
<|body_0|>
def process_response(self, ctx):
"""Generates a new CSRF toke... | stack_v2_sparse_classes_36k_train_004189 | 7,949 | permissive | [
{
"docstring": "Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.",
"name": "check_access",
"signature": "def check_access(self, ctx)"
},
{
"docstring": "Generates a new CSRF token, adds it to the session data and hands over the token to the... | 2 | stack_v2_sparse_classes_30k_train_012938 | Implement the Python class `Plugin` described below.
Class description:
A CSRF protection plugin for Micron.
Method signatures and docstrings:
- def check_access(self, ctx): Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.
- def process_response(self, ctx): Gene... | Implement the Python class `Plugin` described below.
Class description:
A CSRF protection plugin for Micron.
Method signatures and docstrings:
- def check_access(self, ctx): Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token.
- def process_response(self, ctx): Gene... | 1cfa6b021152142556d67a084e01083dbb032dce | <|skeleton|>
class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
<|body_0|>
def process_response(self, ctx):
"""Generates a new CSRF toke... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Plugin:
"""A CSRF protection plugin for Micron."""
def check_access(self, ctx):
"""Checks for an CSRF token in the CSRF token request header and checks if its value is a valid CSRF token."""
if ctx.config.get('csrf', True):
headers = request.headers
provided_token ... | the_stack_v2_python_sparse | ATTIC/csrf-plugin.py | mmakaay/flask_micron | train | 4 |
487778158244c02cbb0cd58d140f553edd0dbea6 | [
"super(CnnOnline_2DFlat, self).__init__()\nself.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros')\nself.lin1 = torch.nn.Linear(int(H), D_out, bias=False)\nself.relu = torch.nn.PReLU(num_parameters=int(H))",
"Current_batchsize = int(x.shape[0])\nd... | <|body_start_0|>
super(CnnOnline_2DFlat, self).__init__()
self.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bias=False, padding_mode='zeros')
self.lin1 = torch.nn.Linear(int(H), D_out, bias=False)
self.relu = torch.nn.PReLU(num_parameters=int(H))
<|... | CnnOnline_2DFlat | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CnnOnline_2DFlat:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Conv1d modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a ... | stack_v2_sparse_classes_36k_train_004190 | 3,350 | no_license | [
{
"docstring": "In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.",
"name": "__init__",
"signature": "def __init__(self, D_in, H, D_out)"
},
{
"docstring": "In the forward function we accept a Tensor of input data and we must return a Tensor of output d... | 2 | stack_v2_sparse_classes_30k_train_012107 | Implement the Python class `CnnOnline_2DFlat` described below.
Class description:
Implement the CnnOnline_2DFlat class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.
- def forward(self, x): In the fo... | Implement the Python class `CnnOnline_2DFlat` described below.
Class description:
Implement the CnnOnline_2DFlat class.
Method signatures and docstrings:
- def __init__(self, D_in, H, D_out): In the constructor we instantiate two nn.Conv1d modules and assign them as member variables.
- def forward(self, x): In the fo... | 2b8566b8b27d35174ec234ecd905c7f284e3af69 | <|skeleton|>
class CnnOnline_2DFlat:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Conv1d modules and assign them as member variables."""
<|body_0|>
def forward(self, x):
"""In the forward function we accept a Tensor of input data and we must return a ... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CnnOnline_2DFlat:
def __init__(self, D_in, H, D_out):
"""In the constructor we instantiate two nn.Conv1d modules and assign them as member variables."""
super(CnnOnline_2DFlat, self).__init__()
self.Conv1 = torch.nn.Conv1d(1, int(H), D_in, stride=1, padding=0, dilation=1, groups=1, bia... | the_stack_v2_python_sparse | src_dir/DiscontinuedNets/cnn_collectionOnline2D_Flat.py | unravel11/GMRES-Learning | train | 0 | |
ee849f3fd15a2326387f9be0dbb3d00b43825a75 | [
"batch, channel, height, width = fmap.shape\nfmap = CenterNetDecoder.pseudo_nms(fmap)\nscores, index, clses, ys, xs = CenterNetDecoder.topk_score(fmap, K=K)\nif reg is not None:\n reg = gather_feature(reg, index, use_transform=True)\n reg = reg.reshape(batch, K, 2)\n xs = xs.view(batch, K, 1) + reg[:, :, 0... | <|body_start_0|>
batch, channel, height, width = fmap.shape
fmap = CenterNetDecoder.pseudo_nms(fmap)
scores, index, clses, ys, xs = CenterNetDecoder.topk_score(fmap, K=K)
if reg is not None:
reg = gather_feature(reg, index, use_transform=True)
reg = reg.reshape(ba... | CenterNetDecoder | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec... | stack_v2_sparse_classes_36k_train_004191 | 21,641 | permissive | [
{
"docstring": "decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec_wh (bool): whether reshape wh tensor. K (int): top k value in score map.",
"name":... | 4 | null | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100): decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature ... | Implement the Python class `CenterNetDecoder` described below.
Class description:
Implement the CenterNetDecoder class.
Method signatures and docstrings:
- def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100): decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature ... | 2deea5dc659371318c8a570c644201d913a83027 | <|skeleton|>
class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class CenterNetDecoder:
def decode(fmap, wh, reg=None, cat_spec_wh=False, K=100):
"""decode feature maps, width height, regression to detections results. Args: fmap (Tensor): input feature map. wh (Tensor): tensor represents (width, height). reg (Tensor): tensor represents regression. cat_spec_wh (bool): wh... | the_stack_v2_python_sparse | cvpods/modeling/meta_arch/centernet.py | Megvii-BaseDetection/cvpods | train | 659 | |
1e6eff52fa27ea52adb976130447f009bf1dcc24 | [
"super().__init__()\nlogger.debug(' {}'.format(self.name))\nlogger.debug(' year FCStack')\nself.year_fc = FCStack(num_layers=1, default_fc_size=1, default_use_bias=use_bias, default_weights_initializer=weights_initializer, default_bias_initializer=bias_initializer, default_weights_regularizer=weights_regularizer, ... | <|body_start_0|>
super().__init__()
logger.debug(' {}'.format(self.name))
logger.debug(' year FCStack')
self.year_fc = FCStack(num_layers=1, default_fc_size=1, default_use_bias=use_bias, default_weights_initializer=weights_initializer, default_bias_initializer=bias_initializer, default_... | DateWave | [
"Apache-2.0",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DateWave:
def __init__(self, fc_layers=None, num_fc_layers=0, fc_size=10, use_bias=True, weights_initializer='glorot_uniform', bias_initializer='zeros', weights_regularizer=None, bias_regularizer=None, activity_regularizer=None, norm=None, norm_params=None, activation='relu', dropout=0, **kwargs... | stack_v2_sparse_classes_36k_train_004192 | 17,612 | permissive | [
{
"docstring": ":param fc_layers: list of dictionaries containing the parameters of all the fully connected layers :type fc_layers: List :param num_fc_layers: Number of stacked fully connected layers :type num_fc_layers: Integer :param fc_size: Size of each layer :type fc_size: Integer :param use_bias: bool det... | 2 | null | Implement the Python class `DateWave` described below.
Class description:
Implement the DateWave class.
Method signatures and docstrings:
- def __init__(self, fc_layers=None, num_fc_layers=0, fc_size=10, use_bias=True, weights_initializer='glorot_uniform', bias_initializer='zeros', weights_regularizer=None, bias_regu... | Implement the Python class `DateWave` described below.
Class description:
Implement the DateWave class.
Method signatures and docstrings:
- def __init__(self, fc_layers=None, num_fc_layers=0, fc_size=10, use_bias=True, weights_initializer='glorot_uniform', bias_initializer='zeros', weights_regularizer=None, bias_regu... | e6abdf9d7c58febfccea7fb8e1ce70b9d4bd2d8a | <|skeleton|>
class DateWave:
def __init__(self, fc_layers=None, num_fc_layers=0, fc_size=10, use_bias=True, weights_initializer='glorot_uniform', bias_initializer='zeros', weights_regularizer=None, bias_regularizer=None, activity_regularizer=None, norm=None, norm_params=None, activation='relu', dropout=0, **kwargs... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class DateWave:
def __init__(self, fc_layers=None, num_fc_layers=0, fc_size=10, use_bias=True, weights_initializer='glorot_uniform', bias_initializer='zeros', weights_regularizer=None, bias_regularizer=None, activity_regularizer=None, norm=None, norm_params=None, activation='relu', dropout=0, **kwargs):
"""... | the_stack_v2_python_sparse | ludwig/encoders/date_encoders.py | litanlitudan/ludwig | train | 1 | |
7d2bf70a1736b50409a315ef6f4f601f3d63e250 | [
"x, z = self._process_cov_inputs(x, z)\nN = x.shape[0]\nM = z.shape[0]\nd = self.active_dims.size\nx = np.asarray(x)[:, self.active_dims].reshape((N, 1, d))\nz = np.asarray(z)[:, self.active_dims].reshape((1, M, d))\nif lengthscale is None:\n lengthscale = np.ones(d, dtype='d')\nelif isinstance(lengthscale, floa... | <|body_start_0|>
x, z = self._process_cov_inputs(x, z)
N = x.shape[0]
M = z.shape[0]
d = self.active_dims.size
x = np.asarray(x)[:, self.active_dims].reshape((N, 1, d))
z = np.asarray(z)[:, self.active_dims].reshape((1, M, d))
if lengthscale is None:
l... | base class for stationary kernels | Stationary | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)... | stack_v2_sparse_classes_36k_train_004193 | 9,047 | no_license | [
{
"docstring": "Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)",
"name": "distances_squared",
"signature": "def distances_squared(self, x, z=None, lengthscale=None)"
},
{
... | 2 | stack_v2_sparse_classes_30k_train_002600 | Implement the Python class `Stationary` described below.
Class description:
base class for stationary kernels
Method signatures and docstrings:
- def distances_squared(self, x, z=None, lengthscale=None): Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optiona... | Implement the Python class `Stationary` described below.
Class description:
base class for stationary kernels
Method signatures and docstrings:
- def distances_squared(self, x, z=None, lengthscale=None): Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optiona... | 1bed882b8a94ee58fd0bde6920ee85f81ffb77bb | <|skeleton|>
class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Stationary:
"""base class for stationary kernels"""
def distances_squared(self, x, z=None, lengthscale=None):
"""Evaluate the distance between points squared. Inputs: x : array of shape (N, d) z : array of shape (M, d) (optional) Outputs: k : matrix of distances of shape shape (N, M)"""
x... | the_stack_v2_python_sparse | gp_grief/kern/stationary.py | scwolof/gp_grief | train | 2 |
1190cb457bf0a06dd83d4b8559b7e173a382a2f8 | [
"self._query = query\nself._table_query = table_query\nself.table_name = table_name",
"table_query = self._table_query\ntable_name = self.table_name\n\nclass MethodWrapper:\n\n def __init__(self, method):\n \"\"\"Hack into query method invocation.\"\"\"\n self._method = method\n\n def __call__... | <|body_start_0|>
self._query = query
self._table_query = table_query
self.table_name = table_name
<|end_body_0|>
<|body_start_1|>
table_query = self._table_query
table_name = self.table_name
class MethodWrapper:
def __init__(self, method):
"... | SmartQuery | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmartQuery:
def __init__(self, query, table_query, table_name):
"""Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced result object. # TODO figure out how to handle filter_by?"""
<|body_0|>
def __getattr__(se... | stack_v2_sparse_classes_36k_train_004194 | 8,735 | no_license | [
{
"docstring": "Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced result object. # TODO figure out how to handle filter_by?",
"name": "__init__",
"signature": "def __init__(self, query, table_query, table_name)"
},
{
"docstring"... | 2 | null | Implement the Python class `SmartQuery` described below.
Class description:
Implement the SmartQuery class.
Method signatures and docstrings:
- def __init__(self, query, table_query, table_name): Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced resu... | Implement the Python class `SmartQuery` described below.
Class description:
Implement the SmartQuery class.
Method signatures and docstrings:
- def __init__(self, query, table_query, table_name): Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced resu... | 6168d7938c72a5a0bb36ca40b96a2a7232021cb5 | <|skeleton|>
class SmartQuery:
def __init__(self, query, table_query, table_name):
"""Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced result object. # TODO figure out how to handle filter_by?"""
<|body_0|>
def __getattr__(se... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class SmartQuery:
def __init__(self, query, table_query, table_name):
"""Improve on querying by returning smarter results. Basically hacks into the query result chain and returns an enhanced result object. # TODO figure out how to handle filter_by?"""
self._query = query
self._table_query = ... | the_stack_v2_python_sparse | migrations/migration_helpers.py | elthran/RPG-Game | train | 0 | |
cb76b087de100e65f6a6729c5614477a6cfa9709 | [
"if not digits:\n return\nmappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}\ncur = []\ndigits = list(digits)\nwhile digits:\n s = digits.pop()\n if cur:\n cur = [b + a for a in cur for b in mappings[s]]\n else:\n cur = list(mappin... | <|body_start_0|>
if not digits:
return
mappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
cur = []
digits = list(digits)
while digits:
s = digits.pop()
if cur:
cur = [b ... | Solution | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
<|body_0|>
def letterCombinations2(self, digits: str):
"""DFS"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not digits:
return
mappings = {'2': 'abc', '... | stack_v2_sparse_classes_36k_train_004195 | 1,850 | permissive | [
{
"docstring": "Backtracking",
"name": "letterCombinations",
"signature": "def letterCombinations(self, digits: str)"
},
{
"docstring": "DFS",
"name": "letterCombinations2",
"signature": "def letterCombinations2(self, digits: str)"
}
] | 2 | stack_v2_sparse_classes_30k_train_001150 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str): Backtracking
- def letterCombinations2(self, digits: str): DFS | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def letterCombinations(self, digits: str): Backtracking
- def letterCombinations2(self, digits: str): DFS
<|skeleton|>
class Solution:
def letterCombinations(self, digits: ... | 49a0b03c55d8a702785888d473ef96539265ce9c | <|skeleton|>
class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
<|body_0|>
def letterCombinations2(self, digits: str):
"""DFS"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def letterCombinations(self, digits: str):
"""Backtracking"""
if not digits:
return
mappings = {'2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz'}
cur = []
digits = list(digits)
while digits:
... | the_stack_v2_python_sparse | leetcode/0017_letter_combinations_of_a_phone_number.py | chaosWsF/Python-Practice | train | 1 | |
3ad5aadddb71767c05c8ae4293677bc1c427a4b4 | [
"root = TreeCollection.Node(collection)\nnodes = [root]\nfor classifier in classifiers:\n nodes = TreeCollectionFactory.makeChildNodes(nodes, classifier)\nreturn TreeCollection(name, root)",
"childNodes = []\nfor node in nodes:\n subCollectionMap = classifier(node.collection, node.ancestry)\n for name, s... | <|body_start_0|>
root = TreeCollection.Node(collection)
nodes = [root]
for classifier in classifiers:
nodes = TreeCollectionFactory.makeChildNodes(nodes, classifier)
return TreeCollection(name, root)
<|end_body_0|>
<|body_start_1|>
childNodes = []
for node in... | A factory class to build Tree and Composite Tree collections | TreeCollectionFactory | [
"MIT",
"BSD-3-Clause",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TreeCollectionFactory:
"""A factory class to build Tree and Composite Tree collections"""
def buildTreeCollection(name, collection, classifiers):
"""Builds a tree collection from base colleciton using a list of classifiers :param name: name of the new Tree Collection :param collectio... | stack_v2_sparse_classes_36k_train_004196 | 8,502 | permissive | [
{
"docstring": "Builds a tree collection from base colleciton using a list of classifiers :param name: name of the new Tree Collection :param collection: The base collection to be classified to build the hierarchical tree collection :param classifiers: The list of classifiers that define the hierarchy",
"na... | 3 | null | Implement the Python class `TreeCollectionFactory` described below.
Class description:
A factory class to build Tree and Composite Tree collections
Method signatures and docstrings:
- def buildTreeCollection(name, collection, classifiers): Builds a tree collection from base colleciton using a list of classifiers :par... | Implement the Python class `TreeCollectionFactory` described below.
Class description:
A factory class to build Tree and Composite Tree collections
Method signatures and docstrings:
- def buildTreeCollection(name, collection, classifiers): Builds a tree collection from base colleciton using a list of classifiers :par... | d6b67e98d4b640c98499a373425f1f009e5b9061 | <|skeleton|>
class TreeCollectionFactory:
"""A factory class to build Tree and Composite Tree collections"""
def buildTreeCollection(name, collection, classifiers):
"""Builds a tree collection from base colleciton using a list of classifiers :param name: name of the new Tree Collection :param collectio... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class TreeCollectionFactory:
"""A factory class to build Tree and Composite Tree collections"""
def buildTreeCollection(name, collection, classifiers):
"""Builds a tree collection from base colleciton using a list of classifiers :param name: name of the new Tree Collection :param collection: The base c... | the_stack_v2_python_sparse | scripts/lib/xpedite/analytics/treeCollections.py | dendisuhubdy/Xpedite | train | 1 |
a02c32247a0d9f2da06aed8fccdb331651a47970 | [
"self.institution_id = i.canonical_name\nself.realms = pyessv.WCRP.cmip6.get_source_realms(s)\nself.source_id = s.canonical_name\nself.wb = None\nself.ws = None\nself.ws_row = 0\nself.CMIP6_MIP_ERA = _CMIP6_MIP_ERA\nself.VERSION = _VERSION",
"for func in (init_workbook, write_frontis, write_example, write_couplin... | <|body_start_0|>
self.institution_id = i.canonical_name
self.realms = pyessv.WCRP.cmip6.get_source_realms(s)
self.source_id = s.canonical_name
self.wb = None
self.ws = None
self.ws_row = 0
self.CMIP6_MIP_ERA = _CMIP6_MIP_ERA
self.VERSION = _VERSION
<|end_b... | Wraps XLS workbook being generated. | ProcessingContext | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProcessingContext:
"""Wraps XLS workbook being generated."""
def __init__(self, i, s):
"""Instance constructor."""
<|body_0|>
def write(self):
"""Write workbook."""
<|body_1|>
def create_format(self, font_size=12):
"""Returns a cell formatter... | stack_v2_sparse_classes_36k_train_004197 | 2,128 | no_license | [
{
"docstring": "Instance constructor.",
"name": "__init__",
"signature": "def __init__(self, i, s)"
},
{
"docstring": "Write workbook.",
"name": "write",
"signature": "def write(self)"
},
{
"docstring": "Returns a cell formatter.",
"name": "create_format",
"signature": "d... | 3 | null | Implement the Python class `ProcessingContext` described below.
Class description:
Wraps XLS workbook being generated.
Method signatures and docstrings:
- def __init__(self, i, s): Instance constructor.
- def write(self): Write workbook.
- def create_format(self, font_size=12): Returns a cell formatter. | Implement the Python class `ProcessingContext` described below.
Class description:
Wraps XLS workbook being generated.
Method signatures and docstrings:
- def __init__(self, i, s): Instance constructor.
- def write(self): Write workbook.
- def create_format(self, font_size=12): Returns a cell formatter.
<|skeleton|>... | 6a1f09d7f723d1fd2bda5119413fc35e0a351649 | <|skeleton|>
class ProcessingContext:
"""Wraps XLS workbook being generated."""
def __init__(self, i, s):
"""Instance constructor."""
<|body_0|>
def write(self):
"""Write workbook."""
<|body_1|>
def create_format(self, font_size=12):
"""Returns a cell formatter... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class ProcessingContext:
"""Wraps XLS workbook being generated."""
def __init__(self, i, s):
"""Instance constructor."""
self.institution_id = i.canonical_name
self.realms = pyessv.WCRP.cmip6.get_source_realms(s)
self.source_id = s.canonical_name
self.wb = None
s... | the_stack_v2_python_sparse | lib/models/init_xls_coupling/__main__.py | ES-DOC/cmip6 | train | 0 |
902ee61d5683264548226d6b0100d4c7726195d0 | [
"if len(words) == 0:\n return []\nroot = TrieNode()\nfor word in words:\n root.add_word(word)\nm = len(board)\nif m == 0:\n return False\nn = len(board[0])\nres = set([])\nfor i in range(m):\n for j in range(n):\n path = []\n searched_pos = []\n self.generate_words(board, m, n, i, j... | <|body_start_0|>
if len(words) == 0:
return []
root = TrieNode()
for word in words:
root.add_word(word)
m = len(board)
if m == 0:
return False
n = len(board[0])
res = set([])
for i in range(m):
for j in range... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def findWords(self, board, words):
""":type board: List[List[str]] :type words: List[str] :rtype: List[str]"""
<|body_0|>
def generate_words(self, board, m, n, i, j, node, path, searched_pos, res):
"""Generate all possible sequence of characters, starting a... | stack_v2_sparse_classes_36k_train_004198 | 3,197 | no_license | [
{
"docstring": ":type board: List[List[str]] :type words: List[str] :rtype: List[str]",
"name": "findWords",
"signature": "def findWords(self, board, words)"
},
{
"docstring": "Generate all possible sequence of characters, starting at position (i,j)",
"name": "generate_words",
"signature... | 2 | stack_v2_sparse_classes_30k_train_011223 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, board, words): :type board: List[List[str]] :type words: List[str] :rtype: List[str]
- def generate_words(self, board, m, n, i, j, node, path, searched_pos, r... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def findWords(self, board, words): :type board: List[List[str]] :type words: List[str] :rtype: List[str]
- def generate_words(self, board, m, n, i, j, node, path, searched_pos, r... | 4fccad3f25732cc41f0f9bfe3d2d98659519a806 | <|skeleton|>
class Solution:
def findWords(self, board, words):
""":type board: List[List[str]] :type words: List[str] :rtype: List[str]"""
<|body_0|>
def generate_words(self, board, m, n, i, j, node, path, searched_pos, res):
"""Generate all possible sequence of characters, starting a... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class Solution:
def findWords(self, board, words):
""":type board: List[List[str]] :type words: List[str] :rtype: List[str]"""
if len(words) == 0:
return []
root = TrieNode()
for word in words:
root.add_word(word)
m = len(board)
if m == 0:
... | the_stack_v2_python_sparse | LeetCode/219. word search II.py | skywalker-lili/codingpractice | train | 0 | |
b01de4ea5e563302e3767e3e496e174375528793 | [
"lb = random.randint(0, int(len(offspring) / 2))\nub = random.randint(lb + 1, len(offspring) - 1)\nnew_offspring = offspring.copy()\nnew_offspring[lb] = offspring[ub]\nnew_offspring[ub] = offspring[lb]\noffspring = np.array(new_offspring)\nreturn offspring",
"lb = random.randint(0, int(len(offspring) / 2))\nub = ... | <|body_start_0|>
lb = random.randint(0, int(len(offspring) / 2))
ub = random.randint(lb + 1, len(offspring) - 1)
new_offspring = offspring.copy()
new_offspring[lb] = offspring[ub]
new_offspring[ub] = offspring[lb]
offspring = np.array(new_offspring)
return offspri... | Permutation - Mutation class | PermMutation | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
<|body_0|>
def insert(offspring):
"""Insert mutation approach... | stack_v2_sparse_classes_36k_train_004199 | 3,795 | no_license | [
{
"docstring": "Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring",
"name": "swap",
"signature": "def swap(offspring)"
},
{
"docstring": "Insert mutation approach Args: offspring (list): Offspring to be mutated Returns: ... | 6 | stack_v2_sparse_classes_30k_train_008154 | Implement the Python class `PermMutation` described below.
Class description:
Permutation - Mutation class
Method signatures and docstrings:
- def swap(offspring): Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring
- def insert(offspring): Ins... | Implement the Python class `PermMutation` described below.
Class description:
Permutation - Mutation class
Method signatures and docstrings:
- def swap(offspring): Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring
- def insert(offspring): Ins... | cd11a700ebcf952f077f44025e83881deee82346 | <|skeleton|>
class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
<|body_0|>
def insert(offspring):
"""Insert mutation approach... | stack_v2_sparse_classes_36k | data/stack_v2_sparse_classes_30k | class PermMutation:
"""Permutation - Mutation class"""
def swap(offspring):
"""Swap mutation approach Args: offspring (list): Offspring to be mutated Returns: new_offspring[numpy.array]: Mutated offspring"""
lb = random.randint(0, int(len(offspring) / 2))
ub = random.randint(lb + 1, len... | the_stack_v2_python_sparse | src/heuristics/game/operators/perm/mutation.py | raphaeldscorrea/GeneticAlgorithmVectorized | train | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.