blob_id stringlengths 40 40 | bodies listlengths 2 6 | bodies_text stringlengths 196 7.73k | class_docstring stringlengths 0 700 | class_name stringlengths 1 86 | detected_licenses listlengths 0 45 | format_version stringclasses 1
value | full_text stringlengths 378 8.64k | id stringlengths 44 44 | length_bytes int64 505 50k | license_type stringclasses 2
values | methods listlengths 2 6 | n_methods int64 2 6 | original_id stringlengths 38 40 ⌀ | prompt stringlengths 153 4.88k | prompted_full_text stringlengths 565 12.5k | revision_id stringlengths 40 40 | skeleton stringlengths 162 5.05k | snapshot_name stringclasses 1
value | snapshot_source_dir stringclasses 1
value | snapshot_total_rows int64 75.8k 75.8k | solution stringlengths 242 8.3k | source stringclasses 1
value | source_path stringlengths 4 177 | source_repo stringlengths 6 110 | split stringclasses 1
value | star_events_count int64 0 209k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6cdf915258455a18823aacfc0f5707833847915a | [
"lo, hi = (0, len(nums) - 1)\nwhile lo < hi:\n mid = int((lo + hi) / 2)\n if (nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]):\n lo = mid + 1\n else:\n hi = mid\nreturn lo if target in nums[lo:lo + 1] else -1",
"p1, p2 = (0, len(nums) - 1)\nif p2 == -1 or (target < nums[p1]... | <|body_start_0|>
lo, hi = (0, len(nums) - 1)
while lo < hi:
mid = int((lo + hi) / 2)
if (nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]):
lo = mid + 1
else:
hi = mid
return lo if target in nums[lo:lo + 1] else -... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def search_best(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_myfirst(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|... | stack_v2_sparse_classes_75kplus_train_073600 | 1,768 | no_license | [
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search_best",
"signature": "def search_best(self, nums, target)"
},
{
"docstring": ":type nums: List[int] :type target: int :rtype: int",
"name": "search_myfirst",
"signature": "def search_myfirst(self, nums, ... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_best(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_myfirst(self, nums, target): :type nums: List[int] :type target: int :rtype:... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def search_best(self, nums, target): :type nums: List[int] :type target: int :rtype: int
- def search_myfirst(self, nums, target): :type nums: List[int] :type target: int :rtype:... | f0d9070fa292ca36971a465a805faddb12025482 | <|skeleton|>
class Solution:
def search_best(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_0|>
def search_myfirst(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def search_best(self, nums, target):
""":type nums: List[int] :type target: int :rtype: int"""
lo, hi = (0, len(nums) - 1)
while lo < hi:
mid = int((lo + hi) / 2)
if (nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]):
lo ... | the_stack_v2_python_sparse | 33.SearchInRotatedSortedArray.py | JerryRoc/leetcode | train | 0 | |
fefe23097db9a3c2abe05d1d4ed62dd5585ba8b9 | [
"if matrix == None or rows < 1 or cols < 1 or (path == None):\n return False\nvisited = [0] * (rows * cols)\npath_length = 0\nfor row in range(rows):\n for col in range(cols):\n if self.hasPathCore(matrix, rows, cols, row, col, path, path_length, visited):\n return True\nreturn False",
"if... | <|body_start_0|>
if matrix == None or rows < 1 or cols < 1 or (path == None):
return False
visited = [0] * (rows * cols)
path_length = 0
for row in range(rows):
for col in range(cols):
if self.hasPathCore(matrix, rows, cols, row, col, path, path_le... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
""":param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径"""
<|body_0|>
def hasPathCore(self, matrix, rows, cols, row, col, path, path_length, visited):
""":param matrix... | stack_v2_sparse_classes_75kplus_train_073601 | 3,129 | no_license | [
{
"docstring": ":param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径",
"name": "hasPath",
"signature": "def hasPath(self, matrix, rows, cols, path)"
},
{
"docstring": ":param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param row: 当前访问坐标的行 ... | 2 | stack_v2_sparse_classes_30k_test_002880 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): :param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径
- def hasPathCore(self, matrix, row... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasPath(self, matrix, rows, cols, path): :param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径
- def hasPathCore(self, matrix, row... | 14fb97af36c5fb1d69439585adb0db0ce9eae45d | <|skeleton|>
class Solution:
def hasPath(self, matrix, rows, cols, path):
""":param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径"""
<|body_0|>
def hasPathCore(self, matrix, rows, cols, row, col, path, path_length, visited):
""":param matrix... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasPath(self, matrix, rows, cols, path):
""":param matrix: 二维矩阵 :param rows: 二维矩阵的行数 :param cols: 二维矩阵的列数 :param path: 目标路径 :return: 是否包含目标路径"""
if matrix == None or rows < 1 or cols < 1 or (path == None):
return False
visited = [0] * (rows * cols)
pat... | the_stack_v2_python_sparse | 矩阵中的路径.py | zhanvwei/targetoffer | train | 0 | |
fc70f7dc34cbe37fba5b3385e8f662113ac0c637 | [
"call_command('populate_db')\ndb_customers_count = Customer.objects.all().count()\ndb_locations_count = Location.objects.all().count()\nself.assertEqual(db_customers_count, 1000)\nself.assertEqual(db_locations_count, 1000)",
"with patch('django.db.utils.ConnectionHandler.__getitem__') as gi:\n gi.return_value ... | <|body_start_0|>
call_command('populate_db')
db_customers_count = Customer.objects.all().count()
db_locations_count = Location.objects.all().count()
self.assertEqual(db_customers_count, 1000)
self.assertEqual(db_locations_count, 1000)
<|end_body_0|>
<|body_start_1|>
with... | Tests custom django commands | CommandTests | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class CommandTests:
"""Tests custom django commands"""
def test_populate_customers(self):
"""Tests if the populate_customers command is populating the Customers table"""
<|body_0|>
def test_wait_for_db(self, ts):
"""Tests if the api is waiting for the db to be ready"""... | stack_v2_sparse_classes_75kplus_train_073602 | 1,041 | permissive | [
{
"docstring": "Tests if the populate_customers command is populating the Customers table",
"name": "test_populate_customers",
"signature": "def test_populate_customers(self)"
},
{
"docstring": "Tests if the api is waiting for the db to be ready",
"name": "test_wait_for_db",
"signature":... | 2 | stack_v2_sparse_classes_30k_train_039107 | Implement the Python class `CommandTests` described below.
Class description:
Tests custom django commands
Method signatures and docstrings:
- def test_populate_customers(self): Tests if the populate_customers command is populating the Customers table
- def test_wait_for_db(self, ts): Tests if the api is waiting for ... | Implement the Python class `CommandTests` described below.
Class description:
Tests custom django commands
Method signatures and docstrings:
- def test_populate_customers(self): Tests if the populate_customers command is populating the Customers table
- def test_wait_for_db(self, ts): Tests if the api is waiting for ... | 7e15b707bc7f1ae1fd7a091e64c41a6f7c8092c3 | <|skeleton|>
class CommandTests:
"""Tests custom django commands"""
def test_populate_customers(self):
"""Tests if the populate_customers command is populating the Customers table"""
<|body_0|>
def test_wait_for_db(self, ts):
"""Tests if the api is waiting for the db to be ready"""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class CommandTests:
"""Tests custom django commands"""
def test_populate_customers(self):
"""Tests if the populate_customers command is populating the Customers table"""
call_command('populate_db')
db_customers_count = Customer.objects.all().count()
db_locations_count = Location... | the_stack_v2_python_sparse | api/core/tests.py | mf-tech-solutions/cusgeo | train | 0 |
be1ecde43a6e23c84228a0aa929c8f5c0a6702ae | [
"if not nums:\n return 0\ndp = [0] * (len(nums) + 1)\ndp[1] = nums[0]\nfor i in range(2, len(nums) + 1):\n dp[i] = dp[i - 1]\n dp[i] = max(dp[i], nums[i - 1] + dp[i - 2])\nreturn dp[-1]",
"if not nums:\n return 0\nlast, now = (0, nums[0])\nfor i in range(2, len(nums) + 1):\n now, last = (max(now, n... | <|body_start_0|>
if not nums:
return 0
dp = [0] * (len(nums) + 1)
dp[1] = nums[0]
for i in range(2, len(nums) + 1):
dp[i] = dp[i - 1]
dp[i] = max(dp[i], nums[i - 1] + dp[i - 2])
return dp[-1]
<|end_body_0|>
<|body_start_1|>
if not nums... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not nums:
return 0
dp = [0] * (len(num... | stack_v2_sparse_classes_75kplus_train_073603 | 804 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "rob",
"signature": "def rob(self, nums)"
}
] | 2 | stack_v2_sparse_classes_30k_train_002979 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def rob(self, nums): :type nums: List[int] :rtype: int
- def rob(self, nums): :type nums: List[int] :rtype: int
<|skeleton|>
class Solution:
def rob(self, nums):
""... | 63b7eedc720c1ce14880b80744dcd5ef7107065c | <|skeleton|>
class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def rob(self, nums):
""":type nums: List[int] :rtype: int"""
if not nums:
return 0
dp = [0] * (len(nums) + 1)
dp[1] = nums[0]
for i in range(2, len(nums) + 1):
dp[i] = dp[i - 1]
dp[i] = max(dp[i], nums[i - 1] + dp[i - 2])
... | the_stack_v2_python_sparse | problems/rob.py | joddiy/leetcode | train | 1 | |
9bbc8678f4b4d6ac46012154bada29bf864fe457 | [
"self.error_message = error_message\nself.ipmi_ip = ipmi_ip\nself.node_id = node_id\nself.node_ip = node_ip",
"if dictionary is None:\n return None\nerror_message = dictionary.get('errorMessage')\nipmi_ip = dictionary.get('ipmiIp')\nnode_id = dictionary.get('nodeId')\nnode_ip = dictionary.get('nodeIp')\nreturn... | <|body_start_0|>
self.error_message = error_message
self.ipmi_ip = ipmi_ip
self.node_id = node_id
self.node_ip = node_ip
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
return None
error_message = dictionary.get('errorMessage')
ipmi_ip = dictio... | Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_id (long|int): Specifies the ID of the ... | NodeStatus | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_i... | stack_v2_sparse_classes_75kplus_train_073604 | 2,119 | permissive | [
{
"docstring": "Constructor for the NodeStatus class",
"name": "__init__",
"signature": "def __init__(self, error_message=None, ipmi_ip=None, node_id=None, node_ip=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representa... | 2 | stack_v2_sparse_classes_30k_train_000455 | Implement the Python class `NodeStatus` described below.
Class description:
Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of... | Implement the Python class `NodeStatus` described below.
Class description:
Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_i... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NodeStatus:
"""Implementation of the 'NodeStatus' model. Specifies the status of each node in the cluster being created. Attributes: error_message (string): Specifies an optional message relating to the node status. ipmi_ip (string): Specifies the IPMI IP of the node (if physical cluster). node_id (long|int):... | the_stack_v2_python_sparse | cohesity_management_sdk/models/node_status.py | cohesity/management-sdk-python | train | 24 |
2f39b9d719ea09ba74b24719b46f9376603362a3 | [
"super(AniReportCore, self).__init__(parent=parent_win)\nself.app_vars = pyani.core.appvars.AppVars()\nself.font_family = pyani.core.ui.FONT_FAMILY\nself.font_size_heading_1 = '20'\nself.font_size_heading_2 = '16'\nself.font_size_heading_3 = '11'\nself.font_size_body = '10'\nself.h_line_img = 'C:\\\\PyAniTools\\\\c... | <|body_start_0|>
super(AniReportCore, self).__init__(parent=parent_win)
self.app_vars = pyani.core.appvars.AppVars()
self.font_family = pyani.core.ui.FONT_FAMILY
self.font_size_heading_1 = '20'
self.font_size_heading_2 = '16'
self.font_size_heading_3 = '11'
self.f... | Core functionality for all reports, takes the parent window and a title | AniReportCore | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AniReportCore:
"""Core functionality for all reports, takes the parent window and a title"""
def __init__(self, parent_win, title, width=800, height=900):
""":param parent_win: window opening this window"""
<|body_0|>
def show_content(self, html_content):
"""Sets... | stack_v2_sparse_classes_75kplus_train_073605 | 36,645 | no_license | [
{
"docstring": ":param parent_win: window opening this window",
"name": "__init__",
"signature": "def __init__(self, parent_win, title, width=800, height=900)"
},
{
"docstring": "Sets the content to display in the pyqt Text edit widget and fires a finished signal :param html_content: a string of... | 2 | stack_v2_sparse_classes_30k_train_029188 | Implement the Python class `AniReportCore` described below.
Class description:
Core functionality for all reports, takes the parent window and a title
Method signatures and docstrings:
- def __init__(self, parent_win, title, width=800, height=900): :param parent_win: window opening this window
- def show_content(self... | Implement the Python class `AniReportCore` described below.
Class description:
Core functionality for all reports, takes the parent window and a title
Method signatures and docstrings:
- def __init__(self, parent_win, title, width=800, height=900): :param parent_win: window opening this window
- def show_content(self... | 07df9ca11f1f98a7704ae5864ddf458c011830d8 | <|skeleton|>
class AniReportCore:
"""Core functionality for all reports, takes the parent window and a title"""
def __init__(self, parent_win, title, width=800, height=900):
""":param parent_win: window opening this window"""
<|body_0|>
def show_content(self, html_content):
"""Sets... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AniReportCore:
"""Core functionality for all reports, takes the parent window and a title"""
def __init__(self, parent_win, title, width=800, height=900):
""":param parent_win: window opening this window"""
super(AniReportCore, self).__init__(parent=parent_win)
self.app_vars = pya... | the_stack_v2_python_sparse | pyani/core/mngr/ui/core.py | pobrien11/PyAniLib | train | 1 |
5813ed64b3e34c849f7232d11b6e443349441a0a | [
"super(Output, self).__init__(dim)\nself.grid_nodes = grid_nodes\nself.deformation_value = deformation_value\nself.output_size = output_size\nif output_spacing is not None:\n self.output_spacing = output_spacing\nelse:\n self.output_spacing = [1] * self.dim\nself.spline_order = spline_order",
"origin = [0] ... | <|body_start_0|>
super(Output, self).__init__(dim)
self.grid_nodes = grid_nodes
self.deformation_value = deformation_value
self.output_size = output_size
if output_spacing is not None:
self.output_spacing = output_spacing
else:
self.output_spacing ... | A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin. | Output | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Output:
"""A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin."""
def __init__(self, dim, grid_nodes, deformation_value, outpu... | stack_v2_sparse_classes_75kplus_train_073606 | 7,621 | no_license | [
{
"docstring": "Initializer. :param dim: The dimension. :param grid_nodes: A list of grid nodes per dimension. :param deformation_value: The maximum deformation value. :param output_size: The output image size in pixels. :param output_spacing: The output image spacing in mm. :param spline_order: The spline orde... | 2 | stack_v2_sparse_classes_30k_train_016691 | Implement the Python class `Output` described below.
Class description:
A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin.
Method signatures and docstr... | Implement the Python class `Output` described below.
Class description:
A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin.
Method signatures and docstr... | ef6cee91264ba1fe6b40d9823a07647b95bcc2c4 | <|skeleton|>
class Output:
"""A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin."""
def __init__(self, dim, grid_nodes, deformation_value, outpu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Output:
"""A deformation transformation in the output image physical domain. Randomly transforms points on an image grid and interpolates with splines. Before this transformation, the image origin must be at the physical origin."""
def __init__(self, dim, grid_nodes, deformation_value, output_size, outpu... | the_stack_v2_python_sparse | transformations/spatial/deformation.py | XiaoweiXu/MedicalDataAugmentationTool | train | 1 |
e08c88b0a372285a099f16444df6daf2e114867f | [
"self.set_header('content-type', 'application/json')\ntry:\n group_dao = GroupDao()\n group_list = group_dao.get_group_detail_list()\n manage_groups = group_dao.get_manage_groups(self.group.id)\n result = [group for group in group_list if group['id'] in manage_groups]\n self.finish(json_dumps({'statu... | <|body_start_0|>
self.set_header('content-type', 'application/json')
try:
group_dao = GroupDao()
group_list = group_dao.get_group_detail_list()
manage_groups = group_dao.get_manage_groups(self.group.id)
result = [group for group in group_list if group['id'... | GroupListHandler | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GroupListHandler:
def get(self):
"""list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '#/definitions/UserGroup' default: description: Unexcepted error schema: $ref: '#/definitions/Error'"""
... | stack_v2_sparse_classes_75kplus_train_073607 | 7,762 | permissive | [
{
"docstring": "list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '#/definitions/UserGroup' default: description: Unexcepted error schema: $ref: '#/definitions/Error'",
"name": "get",
"signature": "def get(se... | 2 | null | Implement the Python class `GroupListHandler` described below.
Class description:
Implement the GroupListHandler class.
Method signatures and docstrings:
- def get(self): list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '... | Implement the Python class `GroupListHandler` described below.
Class description:
Implement the GroupListHandler class.
Method signatures and docstrings:
- def get(self): list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '... | 2e32e6e7b225e0bd87ee8c847c22862f12c51bb1 | <|skeleton|>
class GroupListHandler:
def get(self):
"""list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '#/definitions/UserGroup' default: description: Unexcepted error schema: $ref: '#/definitions/Error'"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GroupListHandler:
def get(self):
"""list all groups @API summary: list all groups notes: get details for groups tags: - auth responses: '200': description: user groups schema: $ref: '#/definitions/UserGroup' default: description: Unexcepted error schema: $ref: '#/definitions/Error'"""
self.set... | the_stack_v2_python_sparse | nebula/views/group.py | threathunterX/nebula_web | train | 2 | |
7bf94723357d75790a5614d990d0a1c7e3b1b865 | [
"kwargs['default'] = default\nkwargs['types'] = (Gradient, Palette, str, tuple, list)\nsuper().__init__(**kwargs)",
"if isinstance(value, Gradient):\n return value\nvalue = super().parse(value)\nif value is UNDEF or value is None:\n return value\nif callable(value):\n return value\nreturn Gradient.create... | <|body_start_0|>
kwargs['default'] = default
kwargs['types'] = (Gradient, Palette, str, tuple, list)
super().__init__(**kwargs)
<|end_body_0|>
<|body_start_1|>
if isinstance(value, Gradient):
return value
value = super().parse(value)
if value is UNDEF or valu... | Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name. | GradientProperty | [
"LicenseRef-scancode-philippe-de-muyter",
"LicenseRef-scancode-commercial-license",
"AGPL-3.0-or-later",
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init_... | stack_v2_sparse_classes_75kplus_train_073608 | 4,576 | permissive | [
{
"docstring": "Initializes a new instance of GradientProperty.",
"name": "__init__",
"signature": "def __init__(self, default=UNDEF, **kwargs)"
},
{
"docstring": "Validates and converts given value.",
"name": "parse",
"signature": "def parse(self, value)"
}
] | 2 | stack_v2_sparse_classes_30k_train_051518 | Implement the Python class `GradientProperty` described below.
Class description:
Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palett... | Implement the Python class `GradientProperty` described below.
Class description:
Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palett... | d59b1bc056f3037b7b7ab635b6deb41120612965 | <|skeleton|>
class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GradientProperty:
"""Defines a color gradient property, which simplifies a gradient definition by automatically creating a pero.Gradient instance from various input options such as a list of supported pero.Color definitions, pero.Palette or registered palette or gradient name."""
def __init__(self, defau... | the_stack_v2_python_sparse | pero/properties/special.py | xxao/pero | train | 31 |
d6a4440331948ff7d52af14c55df04062ca752f9 | [
"if n == 1:\n return True\nelse:\n tmp = bin(n)[2:]\n if tmp[0] == '1' and tmp.count('1') == 1:\n return True\n else:\n return False",
"if n <= 0:\n return False\nelif n & n - 1 == 0:\n return True\nreturn False",
"exp = 0\nans = 1\nwhile ans < n:\n ans *= 2\n exp += 1\nif ... | <|body_start_0|>
if n == 1:
return True
else:
tmp = bin(n)[2:]
if tmp[0] == '1' and tmp.count('1') == 1:
return True
else:
return False
<|end_body_0|>
<|body_start_1|>
if n <= 0:
return False
eli... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo1(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
def isPowerOfTwo2(self, n):
""":type n: int :rtype: bool"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus_train_073609 | 967 | no_license | [
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo",
"signature": "def isPowerOfTwo(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name": "isPowerOfTwo1",
"signature": "def isPowerOfTwo1(self, n)"
},
{
"docstring": ":type n: int :rtype: bool",
"name"... | 3 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo1(self, n): :type n: int :rtype: bool
- def isPowerOfTwo2(self, n): :type n: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def isPowerOfTwo(self, n): :type n: int :rtype: bool
- def isPowerOfTwo1(self, n): :type n: int :rtype: bool
- def isPowerOfTwo2(self, n): :type n: int :rtype: bool
<|skeleton|>... | 96dd15210bcf9efe1f8cf31ce0566a7eabb3e221 | <|skeleton|>
class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
<|body_0|>
def isPowerOfTwo1(self, n):
""":type n: int :rtype: bool"""
<|body_1|>
def isPowerOfTwo2(self, n):
""":type n: int :rtype: bool"""
<|body_2|>
<|end_skeleton|... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def isPowerOfTwo(self, n):
""":type n: int :rtype: bool"""
if n == 1:
return True
else:
tmp = bin(n)[2:]
if tmp[0] == '1' and tmp.count('1') == 1:
return True
else:
return False
def isPowerOf... | the_stack_v2_python_sparse | Python/Power of Two.py | abhi-verma/LeetCode-Algo | train | 0 | |
7459bf368f52e8b797d29f33a7371d6430d4c245 | [
"if x1 is None:\n return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self.input_ndim])\ndiffs = x0 - x1\nif scale_factors is not None:\n diffs *= scale_factors\nreturn jnp.sum(diffs ** 2, axis=tuple(range(-self.input_ndim, 0)))",
"if x1 is None:\n return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self... | <|body_start_0|>
if x1 is None:
return jnp.zeros_like(x0, shape=x0.shape[:x0.ndim - self.input_ndim])
diffs = x0 - x1
if scale_factors is not None:
diffs *= scale_factors
return jnp.sum(diffs ** 2, axis=tuple(range(-self.input_ndim, 0)))
<|end_body_0|>
<|body_sta... | JaxIsotropicMixin | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs... | stack_v2_sparse_classes_75kplus_train_073610 | 5,768 | permissive | [
{
"docstring": "Implementation of the squared (modified) Euclidean distance, which supports scalar inputs, an optional second argument, and different scale factors along all input dimensions.",
"name": "_squared_euclidean_distances_jax",
"signature": "def _squared_euclidean_distances_jax(self: JaxCovari... | 2 | stack_v2_sparse_classes_30k_train_023392 | Implement the Python class `JaxIsotropicMixin` described below.
Class description:
Implement the JaxIsotropicMixin class.
Method signatures and docstrings:
- def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None)... | Implement the Python class `JaxIsotropicMixin` described below.
Class description:
Implement the JaxIsotropicMixin class.
Method signatures and docstrings:
- def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None)... | 5036ae949f0d435395b496bbf88ebc5157b67ba9 | <|skeleton|>
class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class JaxIsotropicMixin:
def _squared_euclidean_distances_jax(self: JaxCovarianceFunctionMixin, x0: jnp.ndarray, x1: Optional[jnp.ndarray], *, scale_factors: Optional[jnp.ndarray]=None) -> jnp.ndarray:
"""Implementation of the squared (modified) Euclidean distance, which supports scalar inputs, an optional ... | the_stack_v2_python_sparse | src/linpde_gp/randprocs/covfuncs/_jax.py | marvinpfoertner/linpde-gp | train | 15 | |
e85e146b6da17ff5b9efeb4c044d6b3c5e360557 | [
"if not parse_node:\n raise TypeError('parse_node cannot be null.')\nreturn UserExperienceAnalyticsBaseline()",
"from .entity import Entity\nfrom .user_experience_analytics_category import UserExperienceAnalyticsCategory\nfrom .entity import Entity\nfrom .user_experience_analytics_category import UserExperienc... | <|body_start_0|>
if not parse_node:
raise TypeError('parse_node cannot be null.')
return UserExperienceAnalyticsBaseline()
<|end_body_0|>
<|body_start_1|>
from .entity import Entity
from .user_experience_analytics_category import UserExperienceAnalyticsCategory
from ... | The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores. | UserExperienceAnalyticsBaseline | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"... | stack_v2_sparse_classes_75kplus_train_073611 | 6,064 | permissive | [
{
"docstring": "Creates a new instance of the appropriate class based on discriminator value Args: parse_node: The parse node to use to read the discriminator value and create the object Returns: UserExperienceAnalyticsBaseline",
"name": "create_from_discriminator_value",
"signature": "def create_from_d... | 3 | stack_v2_sparse_classes_30k_train_015549 | Implement the Python class `UserExperienceAnalyticsBaseline` described below.
Class description:
The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Opt... | Implement the Python class `UserExperienceAnalyticsBaseline` described below.
Class description:
The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores.
Method signatures and docstrings:
- def create_from_discriminator_value(parse_node: Opt... | 27de7ccbe688d7614b2f6bde0fdbcda4bc5cc949 | <|skeleton|>
class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserExperienceAnalyticsBaseline:
"""The user experience analytics baseline entity contains baseline values against which to compare the user experience analytics scores."""
def create_from_discriminator_value(parse_node: Optional[ParseNode]=None) -> UserExperienceAnalyticsBaseline:
"""Creates a n... | the_stack_v2_python_sparse | msgraph/generated/models/user_experience_analytics_baseline.py | microsoftgraph/msgraph-sdk-python | train | 135 |
32823a1bc17d31398adf4dd83dd0f50127a45e62 | [
"del kwargs\nsleep(1)\nreturn read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type)",
"if isinstance(results, pd.DataFrame):\n return results\nreturn pd.DataFrame()"
] | <|body_start_0|>
del kwargs
sleep(1)
return read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type)
<|end_body_0|>
<|body_start_1|>
if isinstance(results, pd.DataFrame):
return results
return pd.DataFrame()
<|end_body_1|>
| TILookup demo class. | TILookupDemo | [
"LicenseRef-scancode-generic-cla",
"LGPL-3.0-only",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"ISC",
"LGPL-2.0-or-later",
"PSF-2.0",
"Apache-2.0",
"BSD-2-Clause",
"LGPL-2.1-only",
"Unlicense",
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"MIT",
"LGPL-2.1-or-later",
"GPL-2.... | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TILookupDemo:
"""TILookup demo class."""
def lookup_ioc(self, ioc_type, **kwargs):
"""Lookup single IoC."""
<|body_0|>
def result_to_df(results):
"""Convert IoC results to DataFrame."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
del kwargs
... | stack_v2_sparse_classes_75kplus_train_073612 | 7,922 | permissive | [
{
"docstring": "Lookup single IoC.",
"name": "lookup_ioc",
"signature": "def lookup_ioc(self, ioc_type, **kwargs)"
},
{
"docstring": "Convert IoC results to DataFrame.",
"name": "result_to_df",
"signature": "def result_to_df(results)"
}
] | 2 | stack_v2_sparse_classes_30k_train_045582 | Implement the Python class `TILookupDemo` described below.
Class description:
TILookup demo class.
Method signatures and docstrings:
- def lookup_ioc(self, ioc_type, **kwargs): Lookup single IoC.
- def result_to_df(results): Convert IoC results to DataFrame. | Implement the Python class `TILookupDemo` described below.
Class description:
TILookup demo class.
Method signatures and docstrings:
- def lookup_ioc(self, ioc_type, **kwargs): Lookup single IoC.
- def result_to_df(results): Convert IoC results to DataFrame.
<|skeleton|>
class TILookupDemo:
"""TILookup demo clas... | 44b1a390510f9be2772ec62cb95d0fc67dfc234b | <|skeleton|>
class TILookupDemo:
"""TILookup demo class."""
def lookup_ioc(self, ioc_type, **kwargs):
"""Lookup single IoC."""
<|body_0|>
def result_to_df(results):
"""Convert IoC results to DataFrame."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TILookupDemo:
"""TILookup demo class."""
def lookup_ioc(self, ioc_type, **kwargs):
"""Lookup single IoC."""
del kwargs
sleep(1)
return read_pd_df(self._DATA_DEFS.get(ioc_type), ioc_type)
def result_to_df(results):
"""Convert IoC results to DataFrame."""
... | the_stack_v2_python_sparse | tools/mp_demo_data.py | RiskIQ/msticpy | train | 1 |
e97c5af2fca50d6b0009fec6db050729fc0f31f4 | [
"super(MaskRCNNBoxHead, self).__init__(name=name)\nself._is_training = is_training\nself._num_classes = num_classes\nself._fc_hyperparams = fc_hyperparams\nself._freeze_batchnorm = freeze_batchnorm\nself._use_dropout = use_dropout\nself._dropout_keep_prob = dropout_keep_prob\nself._box_code_size = box_code_size\nse... | <|body_start_0|>
super(MaskRCNNBoxHead, self).__init__(name=name)
self._is_training = is_training
self._num_classes = num_classes
self._fc_hyperparams = fc_hyperparams
self._freeze_batchnorm = freeze_batchnorm
self._use_dropout = use_dropout
self._dropout_keep_pro... | Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870 | MaskRCNNBoxHead | [
"MIT",
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MaskRCNNBoxHead:
"""Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870"""
def __init__(self, is_training, num_classes, fc_hyperparams, freeze_batchnorm, use_dropout, d... | stack_v2_sparse_classes_75kplus_train_073613 | 13,680 | permissive | [
{
"docstring": "Constructor. Args: is_training: Indicates whether the BoxPredictor is in training mode. num_classes: number of classes. Note that num_classes *does not* include the background category, so if groundtruth labels take values in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the assigned ... | 2 | stack_v2_sparse_classes_30k_train_017431 | Implement the Python class `MaskRCNNBoxHead` described below.
Class description:
Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870
Method signatures and docstrings:
- def __init__(self, is_tra... | Implement the Python class `MaskRCNNBoxHead` described below.
Class description:
Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870
Method signatures and docstrings:
- def __init__(self, is_tra... | a115d918f6894a69586174653172be0b5d1de952 | <|skeleton|>
class MaskRCNNBoxHead:
"""Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870"""
def __init__(self, is_training, num_classes, fc_hyperparams, freeze_batchnorm, use_dropout, d... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MaskRCNNBoxHead:
"""Box prediction head. This is a piece of Mask RCNN which is responsible for predicting just the box encodings. Please refer to Mask RCNN paper: https://arxiv.org/abs/1703.06870"""
def __init__(self, is_training, num_classes, fc_hyperparams, freeze_batchnorm, use_dropout, dropout_keep_p... | the_stack_v2_python_sparse | models/research/object_detection/predictors/heads/keras_box_head.py | finnickniu/tensorflow_object_detection_tflite | train | 60 |
8eee1227609593abc4ee63e3084f6fc297e1eb1e | [
"super().__init__(**kwargs)\nself.__iteration_number = kwargs.get('iteration_number', 10)\nself.__fireflies = [Firefly(**kwargs, bit_generator=self._random) for _ in range(kwargs['firefly_number'])]\nself._visualizer = BaseVisualizer(**kwargs)\nself._visualizer.add_data(positions=[firefly.position for firefly in se... | <|body_start_0|>
super().__init__(**kwargs)
self.__iteration_number = kwargs.get('iteration_number', 10)
self.__fireflies = [Firefly(**kwargs, bit_generator=self._random) for _ in range(kwargs['firefly_number'])]
self._visualizer = BaseVisualizer(**kwargs)
self._visualizer.add_da... | FireflyProblem | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FireflyProblem:
def __init__(self, **kwargs):
"""Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `function` -- The 2D evaluation function. Its input is a 2D numpy.array `upper_boundary` -- Upper boundar... | stack_v2_sparse_classes_75kplus_train_073614 | 2,863 | permissive | [
{
"docstring": "Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `function` -- The 2D evaluation function. Its input is a 2D numpy.array `upper_boundary` -- Upper boundary of the function (default 4) `lower_boundary` -- Lower b... | 2 | null | Implement the Python class `FireflyProblem` described below.
Class description:
Implement the FireflyProblem class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `f... | Implement the Python class `FireflyProblem` described below.
Class description:
Implement the FireflyProblem class.
Method signatures and docstrings:
- def __init__(self, **kwargs): Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `f... | 044b10be5694359900495403cc9f0e84d38a9e88 | <|skeleton|>
class FireflyProblem:
def __init__(self, **kwargs):
"""Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `function` -- The 2D evaluation function. Its input is a 2D numpy.array `upper_boundary` -- Upper boundar... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FireflyProblem:
def __init__(self, **kwargs):
"""Initializes a new instance of the `FireflyProblem` class. Keyword arguments: `firefly_number` -- Number of fireflies used for solving `function` -- The 2D evaluation function. Its input is a 2D numpy.array `upper_boundary` -- Upper boundary of the funct... | the_stack_v2_python_sparse | swarmlib/fireflyalgorithm/firefly_problem.py | huizhi-li/swarmlib | train | 0 | |
22d6dcb228cee966c56580f5b83c4fdbfee308c6 | [
"super(SelfAttention, self).__init__()\nself.W = tf.keras.layers.Dense(units)\nself.U = tf.keras.layers.Dense(units)\nself.V = tf.keras.layers.Dense(1)",
"decW = tf.expand_dims(s_prev, 1)\ndecW = self.W(decW)\nencU = self.U(hidden_states)\noutV = self.V(tf.nn.tanh(decW + encU))\nweights = tf.nn.softmax(outV, axis... | <|body_start_0|>
super(SelfAttention, self).__init__()
self.W = tf.keras.layers.Dense(units)
self.U = tf.keras.layers.Dense(units)
self.V = tf.keras.layers.Dense(1)
<|end_body_0|>
<|body_start_1|>
decW = tf.expand_dims(s_prev, 1)
decW = self.W(decW)
encU = self.U... | Self Attention Class | SelfAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ... | stack_v2_sparse_classes_75kplus_train_073615 | 1,669 | no_license | [
{
"docstring": "Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ro the encoder hidden states :V - Dense layer units=1 applied to the tanh of the sum... | 2 | stack_v2_sparse_classes_30k_train_010518 | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention Class
Method signatures and docstrings:
- def __init__(self, units): Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decode... | Implement the Python class `SelfAttention` described below.
Class description:
Self Attention Class
Method signatures and docstrings:
- def __init__(self, units): Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decode... | 4ac942126918c7acaa9ef88d18efe299b2f726fe | <|skeleton|>
class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SelfAttention:
"""Self Attention Class"""
def __init__(self, units):
"""Initiailize variables :param units: int representing num of hidden units Public Instances :W - Dense layer with units=units, applied to the previous decoder hidden state :U - Dense layer with units=units applied ro the encode... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/1-self_attention.py | DracoMindz/holbertonschool-machine_learning | train | 2 |
93be7f01e7aaba9b4ce7a662b95a11163411ea2e | [
"print('Admin Verification Test')\nlogin = 'admin1'\nself.assertEqual(testVerifyLogin(login, login), True)",
"print('Login Verification Test')\nlogin = 'Engineer1'\nself.assertEqual(testCred(login, login), True)",
"print('Search Car By ID Test')\ncarID = '1'\nself.assertEqual(testCarID(carID), True)"
] | <|body_start_0|>
print('Admin Verification Test')
login = 'admin1'
self.assertEqual(testVerifyLogin(login, login), True)
<|end_body_0|>
<|body_start_1|>
print('Login Verification Test')
login = 'Engineer1'
self.assertEqual(testCred(login, login), True)
<|end_body_1|>
<|... | Function runs all Engineer Related Tests | TestStringMethods | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
<|body_0|>
def test_cred(self):
"""Function runs test to verify Engineer Login"""
<|body_1|>
def test_carID(self):
... | stack_v2_sparse_classes_75kplus_train_073616 | 2,875 | no_license | [
{
"docstring": "Function runs test to verify Admin login",
"name": "test_login",
"signature": "def test_login(self)"
},
{
"docstring": "Function runs test to verify Engineer Login",
"name": "test_cred",
"signature": "def test_cred(self)"
},
{
"docstring": "Function runs test to f... | 3 | stack_v2_sparse_classes_30k_train_049236 | Implement the Python class `TestStringMethods` described below.
Class description:
Function runs all Engineer Related Tests
Method signatures and docstrings:
- def test_login(self): Function runs test to verify Admin login
- def test_cred(self): Function runs test to verify Engineer Login
- def test_carID(self): Func... | Implement the Python class `TestStringMethods` described below.
Class description:
Function runs all Engineer Related Tests
Method signatures and docstrings:
- def test_login(self): Function runs test to verify Admin login
- def test_cred(self): Function runs test to verify Engineer Login
- def test_carID(self): Func... | 0beee478e7a95ed052feb262d1e9fa9c0bf27981 | <|skeleton|>
class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
<|body_0|>
def test_cred(self):
"""Function runs test to verify Engineer Login"""
<|body_1|>
def test_carID(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestStringMethods:
"""Function runs all Engineer Related Tests"""
def test_login(self):
"""Function runs test to verify Admin login"""
print('Admin Verification Test')
login = 'admin1'
self.assertEqual(testVerifyLogin(login, login), True)
def test_cred(self):
... | the_stack_v2_python_sparse | engineerTest.py | rmit-s3602584-peter-moorhead/IoTAssignment2 | train | 0 |
ca117939614bb542310f08fcb5cf6c50951fc763 | [
"tri = []\nfor i in range(numRows):\n temp = [None for _ in range(i + 1)]\n temp[0], temp[-1] = (1, 1)\n for j in range(1, i):\n temp[j] = tri[i - 1][j - 1] + tri[i - 1][j]\n tri.append(temp)\nreturn tri",
"tri = [[1] * i for i in range(1, numRows + 1)]\nfor i in range(2, len(tri)):\n for j ... | <|body_start_0|>
tri = []
for i in range(numRows):
temp = [None for _ in range(i + 1)]
temp[0], temp[-1] = (1, 1)
for j in range(1, i):
temp[j] = tri[i - 1][j - 1] + tri[i - 1][j]
tri.append(temp)
return tri
<|end_body_0|>
<|body_s... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateA(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generateB(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
tri = []
for i in... | stack_v2_sparse_classes_75kplus_train_073617 | 1,146 | no_license | [
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generateA",
"signature": "def generateA(self, numRows)"
},
{
"docstring": ":type numRows: int :rtype: List[List[int]]",
"name": "generateB",
"signature": "def generateB(self, numRows)"
}
] | 2 | stack_v2_sparse_classes_30k_train_049479 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateA(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generateB(self, numRows): :type numRows: int :rtype: List[List[int]] | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateA(self, numRows): :type numRows: int :rtype: List[List[int]]
- def generateB(self, numRows): :type numRows: int :rtype: List[List[int]]
<|skeleton|>
class Solution:
... | 813235789ce422a3bab198317aafc46fbc61625e | <|skeleton|>
class Solution:
def generateA(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_0|>
def generateB(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateA(self, numRows):
""":type numRows: int :rtype: List[List[int]]"""
tri = []
for i in range(numRows):
temp = [None for _ in range(i + 1)]
temp[0], temp[-1] = (1, 1)
for j in range(1, i):
temp[j] = tri[i - 1][j - 1... | the_stack_v2_python_sparse | 17.DYNAMIC PROGRAMMING/118_pascals_triangle/solution.py | kimmyoo/python_leetcode | train | 1 | |
210a883c9e0e30bbb529c6beffe693473f7175cb | [
"self.publisher = rospy.Publisher(output_speech_command_topic, Classification2D, queue_size=10)\nrospy.Subscriber(input_audio_topic, AudioData, self.callback)\nself.bridge = ROSBridge()\nself.buffer_size = buffer_size\nself.data_buffer = np.zeros((1, 1))\nif model == 'matchboxnet':\n self.learner = MatchboxNetLe... | <|body_start_0|>
self.publisher = rospy.Publisher(output_speech_command_topic, Classification2D, queue_size=10)
rospy.Subscriber(input_audio_topic, AudioData, self.callback)
self.bridge = ROSBridge()
self.buffer_size = buffer_size
self.data_buffer = np.zeros((1, 1))
if mo... | SpeechRecognitionNode | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SpeechRecognitionNode:
def __init__(self, input_audio_topic='/audio/audio', output_speech_command_topic='/opendr/speech_recognition', buffer_size=1.5, model='matchboxnet', model_path=None, device='cuda'):
"""Creates a ROS Node for speech command recognition :param input_audio_topic: Topi... | stack_v2_sparse_classes_75kplus_train_073618 | 6,051 | permissive | [
{
"docstring": "Creates a ROS Node for speech command recognition :param input_audio_topic: Topic from which the audio data is received :type input_audio_topic: str :param output_speech_command_topic: Topic to which the predictions are published :type output_speech_command_topic: str :param buffer_size: Length ... | 3 | stack_v2_sparse_classes_30k_test_000984 | Implement the Python class `SpeechRecognitionNode` described below.
Class description:
Implement the SpeechRecognitionNode class.
Method signatures and docstrings:
- def __init__(self, input_audio_topic='/audio/audio', output_speech_command_topic='/opendr/speech_recognition', buffer_size=1.5, model='matchboxnet', mod... | Implement the Python class `SpeechRecognitionNode` described below.
Class description:
Implement the SpeechRecognitionNode class.
Method signatures and docstrings:
- def __init__(self, input_audio_topic='/audio/audio', output_speech_command_topic='/opendr/speech_recognition', buffer_size=1.5, model='matchboxnet', mod... | b3d6ce670cdf63469fc5766630eb295d67b3d788 | <|skeleton|>
class SpeechRecognitionNode:
def __init__(self, input_audio_topic='/audio/audio', output_speech_command_topic='/opendr/speech_recognition', buffer_size=1.5, model='matchboxnet', model_path=None, device='cuda'):
"""Creates a ROS Node for speech command recognition :param input_audio_topic: Topi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SpeechRecognitionNode:
def __init__(self, input_audio_topic='/audio/audio', output_speech_command_topic='/opendr/speech_recognition', buffer_size=1.5, model='matchboxnet', model_path=None, device='cuda'):
"""Creates a ROS Node for speech command recognition :param input_audio_topic: Topic from which t... | the_stack_v2_python_sparse | projects/opendr_ws/src/opendr_perception/scripts/speech_command_recognition_node.py | opendr-eu/opendr | train | 535 | |
da15541a5be3e9a130de1526ee7cd7695a33253b | [
"ans = []\n\ndef _generate(s='', l=0, r=0):\n if len(s) == 2 * n:\n ans.append(s)\n return\n if l < n:\n _generate(s + '(', l + 1, r)\n if r < l:\n _generate(s + ')', l, r + 1)\n_generate()\nreturn ans",
"from collections import deque\nans = []\nqueue = deque([('', 0, 0)])\nwh... | <|body_start_0|>
ans = []
def _generate(s='', l=0, r=0):
if len(s) == 2 * n:
ans.append(s)
return
if l < n:
_generate(s + '(', l + 1, r)
if r < l:
_generate(s + ')', l, r + 1)
_generate()
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""1. 递归 KEY:关键点是生成括号的合法性的判断!!!"""
<|body_0|>
def generateParenthesis2(self, n: int) -> List[str]:
"""2. 队列:记录当前子串状态及左右括号的数量"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
ans = []
... | stack_v2_sparse_classes_75kplus_train_073619 | 2,017 | no_license | [
{
"docstring": "1. 递归 KEY:关键点是生成括号的合法性的判断!!!",
"name": "generateParenthesis",
"signature": "def generateParenthesis(self, n: int) -> List[str]"
},
{
"docstring": "2. 队列:记录当前子串状态及左右括号的数量",
"name": "generateParenthesis2",
"signature": "def generateParenthesis2(self, n: int) -> List[str]"
... | 2 | stack_v2_sparse_classes_30k_train_050132 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 1. 递归 KEY:关键点是生成括号的合法性的判断!!!
- def generateParenthesis2(self, n: int) -> List[str]: 2. 队列:记录当前子串状态及左右括号的数量 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis(self, n: int) -> List[str]: 1. 递归 KEY:关键点是生成括号的合法性的判断!!!
- def generateParenthesis2(self, n: int) -> List[str]: 2. 队列:记录当前子串状态及左右括号的数量
<|skeleton|>
class... | 4732fb80710a08a715c3e7080c394f5298b8326d | <|skeleton|>
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""1. 递归 KEY:关键点是生成括号的合法性的判断!!!"""
<|body_0|>
def generateParenthesis2(self, n: int) -> List[str]:
"""2. 队列:记录当前子串状态及左右括号的数量"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
"""1. 递归 KEY:关键点是生成括号的合法性的判断!!!"""
ans = []
def _generate(s='', l=0, r=0):
if len(s) == 2 * n:
ans.append(s)
return
if l < n:
_generate(s + '(', l + 1,... | the_stack_v2_python_sparse | .leetcode/22.括号生成.py | xiaoruijiang/algorithm | train | 0 | |
ad52bcf2421ecf7d5eae95fa47e6a8b278fdd443 | [
"if 'password' not in configuration:\n logger.info('Must be passed a password in the message')\n return False\nif os.getuid() != 0:\n logger.info('This command must be run as uid 0!')\n return False\nself._chpasswd_path = None\ntry:\n self._chpasswd_path = subprocess.check_output('which chpasswd', sh... | <|body_start_0|>
if 'password' not in configuration:
logger.info('Must be passed a password in the message')
return False
if os.getuid() != 0:
logger.info('This command must be run as uid 0!')
return False
self._chpasswd_path = None
try:
... | PasswordConfigurator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PasswordConfigurator:
def runnable(self, configuration):
"""True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ----------- configuration | Configuration items to be applied (dict) ### Description We should be able to run if th... | stack_v2_sparse_classes_75kplus_train_073620 | 2,527 | no_license | [
{
"docstring": "True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ----------- configuration | Configuration items to be applied (dict) ### Description We should be able to run if the following conditions are true: * Running as root * Can find the pa... | 2 | stack_v2_sparse_classes_30k_train_049081 | Implement the Python class `PasswordConfigurator` described below.
Class description:
Implement the PasswordConfigurator class.
Method signatures and docstrings:
- def runnable(self, configuration): True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ------... | Implement the Python class `PasswordConfigurator` described below.
Class description:
Implement the PasswordConfigurator class.
Method signatures and docstrings:
- def runnable(self, configuration): True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ------... | 600f864628743472226755ad0fe7a4c7a0d2ef28 | <|skeleton|>
class PasswordConfigurator:
def runnable(self, configuration):
"""True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ----------- configuration | Configuration items to be applied (dict) ### Description We should be able to run if th... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PasswordConfigurator:
def runnable(self, configuration):
"""True if configurator can run on this system and in this context. ### Arguments Argument | Description -------- | ----------- configuration | Configuration items to be applied (dict) ### Description We should be able to run if the following co... | the_stack_v2_python_sparse | singularity/configurators/password.py | alunduil/singularity | train | 1 | |
94e1b171130a75e8d09c4fea7088f43c1a23a2f3 | [
"self.colored = colored\nself.formatter_chain = formatter_chain or []\nself.formatter_chain.append(LogsFormatter._pretty_print_event)",
"for operation in self.formatter_chain:\n partial_op = functools.partial(operation, colored=self.colored)\n event_iterable = imap(partial_op, event_iterable)\nreturn event_... | <|body_start_0|>
self.colored = colored
self.formatter_chain = formatter_chain or []
self.formatter_chain.append(LogsFormatter._pretty_print_event)
<|end_body_0|>
<|body_start_1|>
for operation in self.formatter_chain:
partial_op = functools.partial(operation, colored=self.c... | Formats log messages returned by CloudWatch Logs service. | LogsFormatter | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and retu... | stack_v2_sparse_classes_75kplus_train_073621 | 6,494 | permissive | [
{
"docstring": "``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and return the same object back. This allows us to easily chain formatter methods one after another. This class will apply all the formatters from this l... | 3 | stack_v2_sparse_classes_30k_val_000333 | Implement the Python class `LogsFormatter` described below.
Class description:
Formats log messages returned by CloudWatch Logs service.
Method signatures and docstrings:
- def __init__(self, colored, formatter_chain=None): ``formatter_chain`` is a list of methods that can format an event. Each method must take an ``... | Implement the Python class `LogsFormatter` described below.
Class description:
Formats log messages returned by CloudWatch Logs service.
Method signatures and docstrings:
- def __init__(self, colored, formatter_chain=None): ``formatter_chain`` is a list of methods that can format an event. Each method must take an ``... | 9b13e9390d0ae10bf0d3cdfaf3f449cde9b460b7 | <|skeleton|>
class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and retu... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LogsFormatter:
"""Formats log messages returned by CloudWatch Logs service."""
def __init__(self, colored, formatter_chain=None):
"""``formatter_chain`` is a list of methods that can format an event. Each method must take an ``samcli.lib.logs.event.LogEvent`` object as input and return the same o... | the_stack_v2_python_sparse | samcli/lib/logs/formatter.py | keetonian/aws-sam-cli | train | 1 |
705c8bf714e209925eb090768edaf146d34df95f | [
"print('----ADMINISTRATOR MENU----')\nadministrator_menu = OrderedDict([('1', Applicant.display_applicants), ('2', InterviewSlot.display_interviews)])\nchoice = None\nwhile choice != 'q':\n print(\"Press 'q' to exit menu\")\n for key, value in administrator_menu.items():\n print('{}) {}'.format(key, va... | <|body_start_0|>
print('----ADMINISTRATOR MENU----')
administrator_menu = OrderedDict([('1', Applicant.display_applicants), ('2', InterviewSlot.display_interviews)])
choice = None
while choice != 'q':
print("Press 'q' to exit menu")
for key, value in administrator... | Menu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Menu:
def administrator_menu_loop():
"""Administrator menu."""
<|body_0|>
def applicant_menu_loop():
"""Applicant menu."""
<|body_1|>
def mentor_menu_loop():
"""Mentor menu."""
<|body_2|>
def menu_loop(cls):
"""Displays menu.... | stack_v2_sparse_classes_75kplus_train_073622 | 2,710 | no_license | [
{
"docstring": "Administrator menu.",
"name": "administrator_menu_loop",
"signature": "def administrator_menu_loop()"
},
{
"docstring": "Applicant menu.",
"name": "applicant_menu_loop",
"signature": "def applicant_menu_loop()"
},
{
"docstring": "Mentor menu.",
"name": "mentor... | 4 | stack_v2_sparse_classes_30k_train_017750 | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def administrator_menu_loop(): Administrator menu.
- def applicant_menu_loop(): Applicant menu.
- def mentor_menu_loop(): Mentor menu.
- def menu_loop(cls): Displays menu. | Implement the Python class `Menu` described below.
Class description:
Implement the Menu class.
Method signatures and docstrings:
- def administrator_menu_loop(): Administrator menu.
- def applicant_menu_loop(): Applicant menu.
- def mentor_menu_loop(): Mentor menu.
- def menu_loop(cls): Displays menu.
<|skeleton|>
... | 2e22078100af8d33c536ee89bf2a4e7d7710ac93 | <|skeleton|>
class Menu:
def administrator_menu_loop():
"""Administrator menu."""
<|body_0|>
def applicant_menu_loop():
"""Applicant menu."""
<|body_1|>
def mentor_menu_loop():
"""Mentor menu."""
<|body_2|>
def menu_loop(cls):
"""Displays menu.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Menu:
def administrator_menu_loop():
"""Administrator menu."""
print('----ADMINISTRATOR MENU----')
administrator_menu = OrderedDict([('1', Applicant.display_applicants), ('2', InterviewSlot.display_interviews)])
choice = None
while choice != 'q':
print("Pres... | the_stack_v2_python_sparse | menu.py | CodecoolBP20161/python-school-system-with-orm-chill_coders | train | 0 | |
c6290ad3be936fdfe4d4639d6c5cb815eafe4559 | [
"self.CELL_SIZE = 20\nself.CONTROL_FRAME_HEIGHT = 100\nself.SCORE_FRAME_WIDTH = 200\nself.num_rows = num_rows\nself.num_cols = num_cols\nself.window = tk.Tk()\nself.window.title('Snake')\nself.grid_frame = tk.Frame(self.window, height=num_rows * self.CELL_SIZE, width=num_cols * self.CELL_SIZE)\nself.grid_frame.grid... | <|body_start_0|>
self.CELL_SIZE = 20
self.CONTROL_FRAME_HEIGHT = 100
self.SCORE_FRAME_WIDTH = 200
self.num_rows = num_rows
self.num_cols = num_cols
self.window = tk.Tk()
self.window.title('Snake')
self.grid_frame = tk.Frame(self.window, height=num_rows * s... | SnakeView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
<|body_0|>
def add_cells(self):
"""Add cells to the grid frame"""
<|body_1|>
def add_control(self):
"""Create control buttons and slider, and add them to the con... | stack_v2_sparse_classes_75kplus_train_073623 | 7,107 | no_license | [
{
"docstring": "Initialize view of the game",
"name": "__init__",
"signature": "def __init__(self, num_rows, num_cols)"
},
{
"docstring": "Add cells to the grid frame",
"name": "add_cells",
"signature": "def add_cells(self)"
},
{
"docstring": "Create control buttons and slider, a... | 4 | stack_v2_sparse_classes_30k_train_023590 | Implement the Python class `SnakeView` described below.
Class description:
Implement the SnakeView class.
Method signatures and docstrings:
- def __init__(self, num_rows, num_cols): Initialize view of the game
- def add_cells(self): Add cells to the grid frame
- def add_control(self): Create control buttons and slide... | Implement the Python class `SnakeView` described below.
Class description:
Implement the SnakeView class.
Method signatures and docstrings:
- def __init__(self, num_rows, num_cols): Initialize view of the game
- def add_cells(self): Add cells to the grid frame
- def add_control(self): Create control buttons and slide... | 8b2dd5340a82ef1964fcf07b9638e0c57632536b | <|skeleton|>
class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
<|body_0|>
def add_cells(self):
"""Add cells to the grid frame"""
<|body_1|>
def add_control(self):
"""Create control buttons and slider, and add them to the con... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SnakeView:
def __init__(self, num_rows, num_cols):
"""Initialize view of the game"""
self.CELL_SIZE = 20
self.CONTROL_FRAME_HEIGHT = 100
self.SCORE_FRAME_WIDTH = 200
self.num_rows = num_rows
self.num_cols = num_cols
self.window = tk.Tk()
self.win... | the_stack_v2_python_sparse | Simple Snake/snake4.py | ndelafuente/class-projects | train | 0 | |
ce8649d1b91ac614597ad01cfa9db7983495ad0f | [
"node = self._getObjectNode('index')\nfor value in self.context.getIndexSourceNames():\n child = self._doc.createElement('indexed_attr')\n child.setAttribute('value', value)\n node.appendChild(child)\nreturn node",
"indexed_attrs = []\n_before = getattr(self.context, 'indexed_attrs', [])\nfor child in no... | <|body_start_0|>
node = self._getObjectNode('index')
for value in self.context.getIndexSourceNames():
child = self._doc.createElement('indexed_attr')
child.setAttribute('value', value)
node.appendChild(child)
return node
<|end_body_0|>
<|body_start_1|>
... | Node im- and exporter for FieldIndex, KeywordIndex. | PluggableIndexNodeAdapter | [
"ZPL-2.1"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class PluggableIndexNodeAdapter:
"""Node im- and exporter for FieldIndex, KeywordIndex."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus_train_073624 | 6,397 | permissive | [
{
"docstring": "Export the object as a DOM node.",
"name": "_exportNode",
"signature": "def _exportNode(self)"
},
{
"docstring": "Import the object from the DOM node.",
"name": "_importNode",
"signature": "def _importNode(self, node)"
}
] | 2 | stack_v2_sparse_classes_30k_train_053591 | Implement the Python class `PluggableIndexNodeAdapter` described below.
Class description:
Node im- and exporter for FieldIndex, KeywordIndex.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node. | Implement the Python class `PluggableIndexNodeAdapter` described below.
Class description:
Node im- and exporter for FieldIndex, KeywordIndex.
Method signatures and docstrings:
- def _exportNode(self): Export the object as a DOM node.
- def _importNode(self, node): Import the object from the DOM node.
<|skeleton|>
c... | 44891e10fc83abb6626dffec3334247e8de7a9a0 | <|skeleton|>
class PluggableIndexNodeAdapter:
"""Node im- and exporter for FieldIndex, KeywordIndex."""
def _exportNode(self):
"""Export the object as a DOM node."""
<|body_0|>
def _importNode(self, node):
"""Import the object from the DOM node."""
<|body_1|>
<|end_skeleto... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class PluggableIndexNodeAdapter:
"""Node im- and exporter for FieldIndex, KeywordIndex."""
def _exportNode(self):
"""Export the object as a DOM node."""
node = self._getObjectNode('index')
for value in self.context.getIndexSourceNames():
child = self._doc.createElement('inde... | the_stack_v2_python_sparse | src/Products/GenericSetup/PluginIndexes/exportimport.py | zopefoundation/Products.GenericSetup | train | 4 |
2362728ec7b09bf6ea191d763ee72257f6423bd5 | [
"super().__init__()\nif seq is None:\n seq = []\nfor el in seq:\n self.count(el)",
"self[item] = self.get(item, 0) + f\nif self[item] == 0:\n del self[item]"
] | <|body_start_0|>
super().__init__()
if seq is None:
seq = []
for el in seq:
self.count(el)
<|end_body_0|>
<|body_start_1|>
self[item] = self.get(item, 0) + f
if self[item] == 0:
del self[item]
<|end_body_1|>
| A map from each item to its frequency. | Hist | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Hist:
"""A map from each item to its frequency."""
def __init__(self, seq=None):
"""Creates a new histogram starting with the items in sequence."""
<|body_0|>
def count(self, item, f=1):
"""Increments the counter associated with item."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus_train_073625 | 5,544 | no_license | [
{
"docstring": "Creates a new histogram starting with the items in sequence.",
"name": "__init__",
"signature": "def __init__(self, seq=None)"
},
{
"docstring": "Increments the counter associated with item.",
"name": "count",
"signature": "def count(self, item, f=1)"
}
] | 2 | stack_v2_sparse_classes_30k_train_037629 | Implement the Python class `Hist` described below.
Class description:
A map from each item to its frequency.
Method signatures and docstrings:
- def __init__(self, seq=None): Creates a new histogram starting with the items in sequence.
- def count(self, item, f=1): Increments the counter associated with item. | Implement the Python class `Hist` described below.
Class description:
A map from each item to its frequency.
Method signatures and docstrings:
- def __init__(self, seq=None): Creates a new histogram starting with the items in sequence.
- def count(self, item, f=1): Increments the counter associated with item.
<|skel... | 490333f19b463973c05abc734ac3e9dc4e6d019a | <|skeleton|>
class Hist:
"""A map from each item to its frequency."""
def __init__(self, seq=None):
"""Creates a new histogram starting with the items in sequence."""
<|body_0|>
def count(self, item, f=1):
"""Increments the counter associated with item."""
<|body_1|>
<|end... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Hist:
"""A map from each item to its frequency."""
def __init__(self, seq=None):
"""Creates a new histogram starting with the items in sequence."""
super().__init__()
if seq is None:
seq = []
for el in seq:
self.count(el)
def count(self, item, ... | the_stack_v2_python_sparse | 18-inheritance/ex_18_12_3.py | akshirapov/think-python | train | 0 |
b537a6987e7ad0bf2b0219a41dc24ce1bcc2927a | [
"nums.sort()\nre = []\nre.append(nums[:])\nf = self.nextPermutation(nums)\nfor i in f:\n re.append(i[:])\nreturn re",
"while True:\n if len(num) == 0 or len(num) == 1:\n return num\n else:\n i = len(num) - 1\n if num[i] > num[i - 1]:\n num[i], num[i - 1] = (num[i - 1], num... | <|body_start_0|>
nums.sort()
re = []
re.append(nums[:])
f = self.nextPermutation(nums)
for i in f:
re.append(i[:])
return re
<|end_body_0|>
<|body_start_1|>
while True:
if len(num) == 0 or len(num) == 1:
return num
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def nextPermutation(self, num):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|>
<|bo... | stack_v2_sparse_classes_75kplus_train_073626 | 2,093 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: List[List[int]]",
"name": "permute",
"signature": "def permute(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead.",
"name": "nextPermutation",
"signature": "def nextPermuta... | 2 | stack_v2_sparse_classes_30k_train_004159 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def nextPermutation(self, num): :type nums: List[int] :rtype: void Do not return anything, modify nums in... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def permute(self, nums): :type nums: List[int] :rtype: List[List[int]]
- def nextPermutation(self, num): :type nums: List[int] :rtype: void Do not return anything, modify nums in... | 7f9f53bd35ed5855f3aeb56b21dcc4933abdac1a | <|skeleton|>
class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
<|body_0|>
def nextPermutation(self, num):
""":type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def permute(self, nums):
""":type nums: List[int] :rtype: List[List[int]]"""
nums.sort()
re = []
re.append(nums[:])
f = self.nextPermutation(nums)
for i in f:
re.append(i[:])
return re
def nextPermutation(self, num):
""... | the_stack_v2_python_sparse | 46. Permutations.py | 57ing/leetcode | train | 3 | |
71acd4f2bd72096c0689bf9ff28488e6c3e89043 | [
"del platform_config\nsuper().__init__(executor_spec)\nbeam_executor_spec = cast(executable_spec_pb2.BeamExecutableSpec, self._executor_spec)\nself._executor_cls = import_utils.import_class_by_path(beam_executor_spec.python_executor_spec.class_path)\nself.extra_flags = []\nself.extra_flags.extend(beam_executor_spec... | <|body_start_0|>
del platform_config
super().__init__(executor_spec)
beam_executor_spec = cast(executable_spec_pb2.BeamExecutableSpec, self._executor_spec)
self._executor_cls = import_utils.import_class_by_path(beam_executor_spec.python_executor_spec.class_path)
self.extra_flags ... | BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. The flags passed in when starting the program by users or by other systems. The interpret... | BeamExecutorOperator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BeamExecutorOperator:
"""BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. The flags passed in when starting the pro... | stack_v2_sparse_classes_75kplus_train_073627 | 4,594 | permissive | [
{
"docstring": "Initializes a BeamExecutorOperator. Args: executor_spec: The specification of how to initialize the executor. platform_config: The specification of how to allocate resource for the executor.",
"name": "__init__",
"signature": "def __init__(self, executor_spec: message.Message, platform_c... | 2 | null | Implement the Python class `BeamExecutorOperator` described below.
Class description:
BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. Th... | Implement the Python class `BeamExecutorOperator` described below.
Class description:
BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. Th... | 1b328504fa08a70388691e4072df76f143631325 | <|skeleton|>
class BeamExecutorOperator:
"""BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. The flags passed in when starting the pro... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BeamExecutorOperator:
"""BeamExecutorOperator handles Beam based executor's init and execution. Attributes: extra_flags: Extra flags that will pass to Beam executors. It come from two sources in the order: 1. The `extra_flags` set in the executor spec. 2. The flags passed in when starting the program by users... | the_stack_v2_python_sparse | tfx/orchestration/portable/beam_executor_operator.py | tensorflow/tfx | train | 2,116 |
984852c5437f7df9f316e8f9c4e9208941e588ca | [
"if model._meta.app_label in self._apps:\n return getattr(model, '_db_alias', model._meta.app_label)\nreturn None",
"if model._meta.app_label in self._apps:\n return getattr(model, '_db_alias', model._meta.app_label)\nreturn None",
"if getattr(obj1, '_db_alias', obj1._meta.app_label) == getattr(obj2, '_db... | <|body_start_0|>
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return None
<|end_body_0|>
<|body_start_1|>
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_label)
return... | Route all queries to self._apps to their own db_alias by the same name. | AppRouter | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AppRouter:
"""Route all queries to self._apps to their own db_alias by the same name."""
def db_for_read(self, model, **hints):
"""If the app has its own database, use it for reads"""
<|body_0|>
def db_for_write(self, model, **hints):
"""If the app has its own da... | stack_v2_sparse_classes_75kplus_train_073628 | 5,376 | permissive | [
{
"docstring": "If the app has its own database, use it for reads",
"name": "db_for_read",
"signature": "def db_for_read(self, model, **hints)"
},
{
"docstring": "If the app has its own database, use it for writes",
"name": "db_for_write",
"signature": "def db_for_write(self, model, **hi... | 4 | stack_v2_sparse_classes_30k_train_009046 | Implement the Python class `AppRouter` described below.
Class description:
Route all queries to self._apps to their own db_alias by the same name.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): If the app has its own database, use it for reads
- def db_for_write(self, model, **hints): If t... | Implement the Python class `AppRouter` described below.
Class description:
Route all queries to self._apps to their own db_alias by the same name.
Method signatures and docstrings:
- def db_for_read(self, model, **hints): If the app has its own database, use it for reads
- def db_for_write(self, model, **hints): If t... | 55678b08755a55366ce18e7d3b8ea8fa4491ab04 | <|skeleton|>
class AppRouter:
"""Route all queries to self._apps to their own db_alias by the same name."""
def db_for_read(self, model, **hints):
"""If the app has its own database, use it for reads"""
<|body_0|>
def db_for_write(self, model, **hints):
"""If the app has its own da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AppRouter:
"""Route all queries to self._apps to their own db_alias by the same name."""
def db_for_read(self, model, **hints):
"""If the app has its own database, use it for reads"""
if model._meta.app_label in self._apps:
return getattr(model, '_db_alias', model._meta.app_la... | the_stack_v2_python_sparse | pug/dj/db_routers.py | hobson/pug-dj | train | 0 |
b99ef3f10853928c3655a3ac4350334d6f6eb16b | [
"self.CHC = Abstract_Channel_Creator\nself.em_gain = ccd_operation_mode['em_gain']\nself.binn = ccd_operation_mode['binn']\nself.t_exp = ccd_operation_mode['t_exp']\nself.image_size = ccd_operation_mode['image_size']\nself.ccd_gain = ccd_gain",
"t_exp = self.t_exp\nem_gain = self.em_gain\nccd_gain = self.ccd_gain... | <|body_start_0|>
self.CHC = Abstract_Channel_Creator
self.em_gain = ccd_operation_mode['em_gain']
self.binn = ccd_operation_mode['binn']
self.t_exp = ccd_operation_mode['t_exp']
self.image_size = ccd_operation_mode['image_size']
self.ccd_gain = ccd_gain
<|end_body_0|>
<|... | Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the contribution of the atmosphere, the telescope, and the SPARC4 are considered as a function o... | Point_Spread_Function | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Point_Spread_Function:
"""Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the contribution of the atmosphere, the telesco... | stack_v2_sparse_classes_75kplus_train_073629 | 3,709 | permissive | [
{
"docstring": "Initialize the class.",
"name": "__init__",
"signature": "def __init__(self, Abstract_Channel_Creator, ccd_operation_mode, ccd_gain)"
},
{
"docstring": "Create the star point spread function. Parameters ---------- star_coordinates: tuple XY star coordinates in the image. gaussian... | 2 | stack_v2_sparse_classes_30k_train_007897 | Implement the Python class `Point_Spread_Function` described below.
Class description:
Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the cont... | Implement the Python class `Point_Spread_Function` described below.
Class description:
Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the cont... | 6f75bbfd52a7b6684ad04002f9818b4d8e7d2c96 | <|skeleton|>
class Point_Spread_Function:
"""Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the contribution of the atmosphere, the telesco... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Point_Spread_Function:
"""Point Spread Function Class. This class creates the image of the star. The PSF of the object is based on a 2D gaussian distribution. Initially, the star flux is calculated using the library Flux_Calculation. Over this flux, the contribution of the atmosphere, the telescope, and the S... | the_stack_v2_python_sparse | AIS/Point_Spread_Function/point_spread_function.py | juliotux/AIS | train | 0 |
788dd9e219e8832d8b47e041309b14f230464e18 | [
"AgentThread.__init__(self, threadMgr, cat=[manifestutil.serviceCat('agent')], name='delete_module', parentId=parentId)\nself.__module = module\nself.__service = 'agent'",
"try:\n deleted = True\n path = manifestutil.modulePath(self.__service, self.__module)\n try:\n manifestutil.processModule(sel... | <|body_start_0|>
AgentThread.__init__(self, threadMgr, cat=[manifestutil.serviceCat('agent')], name='delete_module', parentId=parentId)
self.__module = module
self.__service = 'agent'
<|end_body_0|>
<|body_start_1|>
try:
deleted = True
path = manifestutil.moduleP... | All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr. | ModuleDelete | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ModuleDelete:
"""All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr."""
def __init__(self, threadMgr, module, parentId=None):
"""Constructor"""
<|body_0|>
def doRun(self):
... | stack_v2_sparse_classes_75kplus_train_073630 | 2,279 | permissive | [
{
"docstring": "Constructor",
"name": "__init__",
"signature": "def __init__(self, threadMgr, module, parentId=None)"
},
{
"docstring": "Main body of the thread",
"name": "doRun",
"signature": "def doRun(self)"
}
] | 2 | null | Implement the Python class `ModuleDelete` described below.
Class description:
All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr.
Method signatures and docstrings:
- def __init__(self, threadMgr, module, parentId=None): Constru... | Implement the Python class `ModuleDelete` described below.
Class description:
All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr.
Method signatures and docstrings:
- def __init__(self, threadMgr, module, parentId=None): Constru... | 955c0ff83bcc0ff3ef599c767d96efce37493cec | <|skeleton|>
class ModuleDelete:
"""All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr."""
def __init__(self, threadMgr, module, parentId=None):
"""Constructor"""
<|body_0|>
def doRun(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ModuleDelete:
"""All threads used by the agent should be of type agent thread. This thread will be used to generate ids, provide categories for the thread mgr."""
def __init__(self, threadMgr, module, parentId=None):
"""Constructor"""
AgentThread.__init__(self, threadMgr, cat=[manifestuti... | the_stack_v2_python_sparse | agent/agent/lib/agent_thread/module_delete.py | parallec/cronusagent | train | 0 |
0d89b6ad268c77f86a2d09380b09db92df2e67b7 | [
"super().__init__()\nif pre_nonlinear not in ('sigmoid', 'prelu', 'relu', 'tanh', 'linear'):\n raise ValueError('Not supporting pre_nonlinear={}'.format(pre_nonlinear))\nif nonlinear not in ('sigmoid', 'relu', 'tanh', 'linear'):\n raise ValueError('Not supporting nonlinear={}'.format(nonlinear))\nself.tcn = T... | <|body_start_0|>
super().__init__()
if pre_nonlinear not in ('sigmoid', 'prelu', 'relu', 'tanh', 'linear'):
raise ValueError('Not supporting pre_nonlinear={}'.format(pre_nonlinear))
if nonlinear not in ('sigmoid', 'relu', 'tanh', 'linear'):
raise ValueError('Not supportin... | TDSpeakerBeamExtractor | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_ty... | stack_v2_sparse_classes_75kplus_train_073631 | 6,590 | permissive | [
{
"docstring": "Time-Domain SpeakerBeam Extractor. Args: input_dim: input feature dimension layer: int, number of layers in each stack stack: int, number of stacks bottleneck_dim: bottleneck dimension hidden_dim: number of convolution channel skip_dim: int, number of skip connection channels kernel: int, kernel... | 2 | stack_v2_sparse_classes_30k_train_008357 | Implement the Python class `TDSpeakerBeamExtractor` described below.
Class description:
Implement the TDSpeakerBeamExtractor class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal:... | Implement the Python class `TDSpeakerBeamExtractor` described below.
Class description:
Implement the TDSpeakerBeamExtractor class.
Method signatures and docstrings:
- def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal:... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_ty... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TDSpeakerBeamExtractor:
def __init__(self, input_dim: int, layer: int=8, stack: int=3, bottleneck_dim: int=128, hidden_dim: int=512, skip_dim: int=128, kernel: int=3, causal: bool=False, norm_type: str='gLN', pre_nonlinear: str='prelu', nonlinear: str='relu', i_adapt_layer: int=7, adapt_layer_type: str='mul',... | the_stack_v2_python_sparse | espnet2/enh/extractor/td_speakerbeam_extractor.py | espnet/espnet | train | 7,242 | |
97c3b1dd333d1bdf484b216dd99c4f7975a506a1 | [
"self.IndivWord_Dic = IndivWordDict\nself.WordTag_Dic = WordTagDict\nself.TagWord_Dic = TagWordDict\nTemplateDict = collections.defaultdict(list)\nself.Template_Dic = TemplateDict\nself.indivword_path = indivword_path\nself.featureword_path = featureword_path\nself.template_path = template_path\nif indivword_path !... | <|body_start_0|>
self.IndivWord_Dic = IndivWordDict
self.WordTag_Dic = WordTagDict
self.TagWord_Dic = TagWordDict
TemplateDict = collections.defaultdict(list)
self.Template_Dic = TemplateDict
self.indivword_path = indivword_path
self.featureword_path = featureword... | Initial_Dict_Load | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Initial_Dict_Load:
def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''):
"""初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模... | stack_v2_sparse_classes_75kplus_train_073632 | 5,984 | no_license | [
{
"docstring": "初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模板词典 :param indivword_path: 个体词读取路径 :param featureword_path: 功能词读取路径 :param template_path: 复述模板读取路径",
"name": "__init__",
"signature": "def __init__(self, IndivWordDict... | 4 | stack_v2_sparse_classes_30k_train_045158 | Implement the Python class `Initial_Dict_Load` described below.
Class description:
Implement the Initial_Dict_Load class.
Method signatures and docstrings:
- def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): 初始化操作 :param In... | Implement the Python class `Initial_Dict_Load` described below.
Class description:
Implement the Initial_Dict_Load class.
Method signatures and docstrings:
- def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''): 初始化操作 :param In... | 829cb826df2de502ac38ef28cac623d868e66ead | <|skeleton|>
class Initial_Dict_Load:
def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''):
"""初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Initial_Dict_Load:
def __init__(self, IndivWordDict={}, WordTagDict={}, TagWordDict={}, TemplateDict={}, indivword_path='', featureword_path='', template_path=''):
"""初始化操作 :param IndivWordDict: 个体词-标签词典 :param WordTagDict: 功能词-标签词典 :param TagWordDict: 标签-功能词列表词典 :param TemplateDict: 复述模板词典 :param ind... | the_stack_v2_python_sparse | SentenceParaphrase/TemplateMatching/InitializeDict.py | astronstar/LearningJournal-Code | train | 0 | |
c9dcaf594759f452499c06ef3cabc2c2e7d25385 | [
"assert order > 0, 'order must be 1 or more.'\nassert smooth > 2, 'term must be 3 or more.'\nself.__smooth = smooth\nself.__order = order\nself.__r = r\nself.__threshold = threshold",
"detector = Prospective(self.__r, self.__order, self.__smooth)\nscores = []\nfor i in X:\n score = detector.update(i)\n scor... | <|body_start_0|>
assert order > 0, 'order must be 1 or more.'
assert smooth > 2, 'term must be 3 or more.'
self.__smooth = smooth
self.__order = order
self.__r = r
self.__threshold = threshold
<|end_body_0|>
<|body_start_1|>
detector = Prospective(self.__r, self.... | ChangeFinder (Retrospective) | Retrospective | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters t... | stack_v2_sparse_classes_75kplus_train_073633 | 7,176 | permissive | [
{
"docstring": "Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters threshold: threshold for alarms.",
"name": "__init__",
"signature": "def __init__(self, r=0.5, order=1, smooth=7, thr... | 3 | stack_v2_sparse_classes_30k_val_000770 | Implement the Python class `Retrospective` described below.
Class description:
ChangeFinder (Retrospective)
Method signatures and docstrings:
- def __init__(self, r=0.5, order=1, smooth=7, threshold=1): Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second sta... | Implement the Python class `Retrospective` described below.
Class description:
ChangeFinder (Retrospective)
Method signatures and docstrings:
- def __init__(self, r=0.5, order=1, smooth=7, threshold=1): Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second sta... | 7faf99f36ac012799602f32b359dcda089bcd119 | <|skeleton|>
class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Retrospective:
"""ChangeFinder (Retrospective)"""
def __init__(self, r=0.5, order=1, smooth=7, threshold=1):
"""Args: r: sequential discounting coefficient. order: AR model's order. smooth: smoothing window size. The second stage's window size is smooth/2 to reduce hyper parameters threshold: thr... | the_stack_v2_python_sparse | changefinder/changefinder.py | IbarakikenYukishi/two-stage-MDL | train | 4 |
b94b0d8ca71f2b118e6a0fac5e411a128b329a6f | [
"def helper(pre, l, r) -> List[str]:\n \"\"\"Helper function\n :param l: Number of left parenthesis that can be used.\n :param r: Number of right parenthesis that can be used.\n \"\"\"\n if l == 0 and r == 0:\n return [pre]\n output = []\n if l > 0:\n outpu... | <|body_start_0|>
def helper(pre, l, r) -> List[str]:
"""Helper function
:param l: Number of left parenthesis that can be used.
:param r: Number of right parenthesis that can be used.
"""
if l == 0 and r == 0:
ret... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
<|body_0|>
def generateParenthesis_v2(self, n: int) -> List[str]:
"""Pass the output list to the helper."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
def... | stack_v2_sparse_classes_75kplus_train_073634 | 1,877 | no_license | [
{
"docstring": "Helper return a list.",
"name": "generateParenthesis_v1",
"signature": "def generateParenthesis_v1(self, n: int) -> List[str]"
},
{
"docstring": "Pass the output list to the helper.",
"name": "generateParenthesis_v2",
"signature": "def generateParenthesis_v2(self, n: int)... | 2 | stack_v2_sparse_classes_30k_train_005936 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_v1(self, n: int) -> List[str]: Helper return a list.
- def generateParenthesis_v2(self, n: int) -> List[str]: Pass the output list to the helper. | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def generateParenthesis_v1(self, n: int) -> List[str]: Helper return a list.
- def generateParenthesis_v2(self, n: int) -> List[str]: Pass the output list to the helper.
<|skele... | 97a2386f5e3adbd7138fd123810c3232bdf7f622 | <|skeleton|>
class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
<|body_0|>
def generateParenthesis_v2(self, n: int) -> List[str]:
"""Pass the output list to the helper."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def generateParenthesis_v1(self, n: int) -> List[str]:
"""Helper return a list."""
def helper(pre, l, r) -> List[str]:
"""Helper function
:param l: Number of left parenthesis that can be used.
:param r: Number of right parenthesis t... | the_stack_v2_python_sparse | python3/recursion/generat_parentheses.py | victorchu/algorithms | train | 0 | |
185ba61c3bfed4b42b8272f8317ac3c7c6ee3149 | [
"self.dns_root = dns_root\nself.forest = forest\nself.identity = identity\nself.netbios_name = netbios_name\nself.parent_domain = parent_domain\nself.tombstone_days = tombstone_days",
"if dictionary is None:\n return None\ndns_root = dictionary.get('dnsRoot')\nforest = dictionary.get('forest')\nidentity = cohe... | <|body_start_0|>
self.dns_root = dns_root
self.forest = forest
self.identity = identity
self.netbios_name = netbios_name
self.parent_domain = parent_domain
self.tombstone_days = tombstone_days
<|end_body_0|>
<|body_start_1|>
if dictionary is None:
ret... | Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies AD NetBIOS name. parent_domain (stri... | AdDomain | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies ... | stack_v2_sparse_classes_75kplus_train_073635 | 2,708 | permissive | [
{
"docstring": "Constructor for the AdDomain class",
"name": "__init__",
"signature": "def __init__(self, dns_root=None, forest=None, identity=None, netbios_name=None, parent_domain=None, tombstone_days=None)"
},
{
"docstring": "Creates an instance of this model from a dictionary Args: dictionar... | 2 | stack_v2_sparse_classes_30k_train_009572 | Implement the Python class `AdDomain` described below.
Class description:
Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the do... | Implement the Python class `AdDomain` described below.
Class description:
Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the do... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdDomain:
"""Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainIdentity): Specifies Identity information of the domain. netbios_name (string): Specifies AD NetBIOS na... | the_stack_v2_python_sparse | cohesity_management_sdk/models/ad_domain.py | cohesity/management-sdk-python | train | 24 |
013483d4a643c55c498b227c40ec580e8a9e4a0a | [
"df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)\ndefinepersample_code = '\\n if(rdfsampleinfo_.Contains(\"{}\")) return 1;\\n else if (rdfsampleinfo_.Contains(\"{}\")) return 2;\\n else if (rdfsampleinfo_.Contains(\"{}\")) return 3;\\n else return 0;\\n... | <|body_start_0|>
df = Spark.RDataFrame(self.maintreename, self.filenames, sparkcontext=connection)
definepersample_code = '\n if(rdfsampleinfo_.Contains("{}")) return 1;\n else if (rdfsampleinfo_.Contains("{}")) return 2;\n else if (rdfsampleinfo_.Contains("{}")) return 3;\n ... | Check the working of merge operations in the reducer function. | TestDefinePerSample | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
<|body_0|>
def test_definepersample... | stack_v2_sparse_classes_75kplus_train_073636 | 4,549 | no_license | [
{
"docstring": "Test DefinePerSample operation on three samples using a predefined string of operations.",
"name": "test_definepersample_simple",
"signature": "def test_definepersample_simple(self, connection)"
},
{
"docstring": "Test DefinePerSample operation on three samples using C++ function... | 2 | stack_v2_sparse_classes_30k_train_028560 | Implement the Python class `TestDefinePerSample` described below.
Class description:
Check the working of merge operations in the reducer function.
Method signatures and docstrings:
- def test_definepersample_simple(self, connection): Test DefinePerSample operation on three samples using a predefined string of operat... | Implement the Python class `TestDefinePerSample` described below.
Class description:
Check the working of merge operations in the reducer function.
Method signatures and docstrings:
- def test_definepersample_simple(self, connection): Test DefinePerSample operation on three samples using a predefined string of operat... | 134508460915282a5d82d6cbbb6e6afa14653413 | <|skeleton|>
class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
<|body_0|>
def test_definepersample... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestDefinePerSample:
"""Check the working of merge operations in the reducer function."""
def test_definepersample_simple(self, connection):
"""Test DefinePerSample operation on three samples using a predefined string of operations."""
df = Spark.RDataFrame(self.maintreename, self.filenam... | the_stack_v2_python_sparse | python/distrdf/spark/check_definepersample.py | root-project/roottest | train | 41 |
416ae4d2524997a7965cb59f11d03659ee016ba3 | [
"dict = Counter(nums)\nfor val in dict:\n if dict[val] == 1:\n return val",
"elements = set(nums)\nele = (sum(elements) * 3 - sum(nums)) // 2\nreturn ele",
"low = high = 0\nfor val in nums:\n low = (low ^ val) & ~high\n high = (high ^ val) & ~low\nreturn low"
] | <|body_start_0|>
dict = Counter(nums)
for val in dict:
if dict[val] == 1:
return val
<|end_body_0|>
<|body_start_1|>
elements = set(nums)
ele = (sum(elements) * 3 - sum(nums)) // 2
return ele
<|end_body_1|>
<|body_start_2|>
low = high = 0
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus_train_073637 | 1,101 | no_license | [
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber",
"signature": "def singleNumber(self, nums)"
},
{
"docstring": ":type nums: List[int] :rtype: int",
"name": "singleNumber2",
"signature": "def singleNumber2(self, nums)"
},
{
"docstring": ":type nums: List... | 3 | stack_v2_sparse_classes_30k_train_000395 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def singleNumber(self, nums): :type nums: List[int] :rtype: int
- def singleNumber2(self, nums): :type nums: List[int] :rtype: int
- def singleNumber3(self, nums): :type nums: Li... | 0fc4c7af59246e3064db41989a45d9db413a624b | <|skeleton|>
class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_0|>
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
<|body_1|>
def singleNumber3(self, nums):
""":type nums: List[int] :rtype: int"""
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def singleNumber(self, nums):
""":type nums: List[int] :rtype: int"""
dict = Counter(nums)
for val in dict:
if dict[val] == 1:
return val
def singleNumber2(self, nums):
""":type nums: List[int] :rtype: int"""
elements = set(num... | the_stack_v2_python_sparse | 137. Single Number II/sinNum.py | Macielyoung/LeetCode | train | 1 | |
819ac6b07b4b6d8ae5b5c1b0955ec8bee20864f0 | [
"if not isinstance(data, np.ndarray) or len(data.shape) != 2:\n raise TypeError('data must be a 2D numpy.ndarray')\nif data.shape[1] < 2:\n raise ValueError('data must contain multiple data points')\nself.mean = data.mean(axis=1, keepdims=True)\nXi = data - self.mean\nself.cov = np.dot(Xi, Xi.T) / (data.shape... | <|body_start_0|>
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
raise ValueError('data must contain multiple data points')
self.mean = data.mean(axis=1, keepdims=True)
Xi = data... | class that represents a Multivariate Normal distribution | MultiNormal | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiNormal:
"""class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""initialization"""
<|body_0|>
def pdf(self, x):
"""Probability density Function"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if not isinst... | stack_v2_sparse_classes_75kplus_train_073638 | 1,189 | no_license | [
{
"docstring": "initialization",
"name": "__init__",
"signature": "def __init__(self, data)"
},
{
"docstring": "Probability density Function",
"name": "pdf",
"signature": "def pdf(self, x)"
}
] | 2 | stack_v2_sparse_classes_30k_train_033352 | Implement the Python class `MultiNormal` described below.
Class description:
class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): initialization
- def pdf(self, x): Probability density Function | Implement the Python class `MultiNormal` described below.
Class description:
class that represents a Multivariate Normal distribution
Method signatures and docstrings:
- def __init__(self, data): initialization
- def pdf(self, x): Probability density Function
<|skeleton|>
class MultiNormal:
"""class that represe... | d45e18bcbe1898a1585e4b7b61f3a7af9f00e787 | <|skeleton|>
class MultiNormal:
"""class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""initialization"""
<|body_0|>
def pdf(self, x):
"""Probability density Function"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiNormal:
"""class that represents a Multivariate Normal distribution"""
def __init__(self, data):
"""initialization"""
if not isinstance(data, np.ndarray) or len(data.shape) != 2:
raise TypeError('data must be a 2D numpy.ndarray')
if data.shape[1] < 2:
... | the_stack_v2_python_sparse | math/0x06-multivariate_prob/multinormal.py | jlassi1/holbertonschool-machine_learning | train | 1 |
6ae1bd21e9cae7fccd323c8ab969c5cc087db045 | [
"try:\n trips_db_instance = TripsDatabase()\n trip = trips_db_instance.trip_info(user.id, trip_id)\n if not trip:\n return response_404('NoSuchTrip', 'No such trip')\n attr_db_instance = AttractionsDatabase()\n attr_db_instance.add_attraction_to_trip(trip_id, attraction_id)\n attr_db_instan... | <|body_start_0|>
try:
trips_db_instance = TripsDatabase()
trip = trips_db_instance.trip_info(user.id, trip_id)
if not trip:
return response_404('NoSuchTrip', 'No such trip')
attr_db_instance = AttractionsDatabase()
attr_db_instance.add_... | TripAttractionsView | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @a... | stack_v2_sparse_classes_75kplus_train_073639 | 6,473 | no_license | [
{
"docstring": "@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @apiError (NotFound 404) {Object} NoSuchTrip Such trip doesn't exist. @apiError (BadRequest... | 3 | stack_v2_sparse_classes_30k_train_051897 | Implement the Python class `TripAttractionsView` described below.
Class description:
Implement the TripAttractionsView class.
Method signatures and docstrings:
- def post(self, trip_id, attraction_id, user: User=None): @api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @a... | Implement the Python class `TripAttractionsView` described below.
Class description:
Implement the TripAttractionsView class.
Method signatures and docstrings:
- def post(self, trip_id, attraction_id, user: User=None): @api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @a... | 1e89f75c6469dcab9197115eb971780684199987 | <|skeleton|>
class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TripAttractionsView:
def post(self, trip_id, attraction_id, user: User=None):
"""@api {POST} /api/v1/trips/<trip_id>/attractions/<attraction_id> Add Attraction @apiVersion 1.0.0 @apiName AddAttraction @apiGroup Attractions @apiSuccessExample {json} Success-Response: HTTP/1.1 200 OK {} @apiError (NotFo... | the_stack_v2_python_sparse | src/views/trip_attractions.py | Itamichan/Japan-Wanderlust | train | 0 | |
2840ce5a587cc9b03b70d8e20e6a3375534ece61 | [
"logger.info('Creating training loader.')\nassert os.path.isfile(file_path), 'Training HDF5 file {} not found'.format(file_path)\nexamples = []\nwith h5py.File(file_path, 'r') as f:\n samples = 0\n for key in f.keys():\n data_series = torch.Tensor(f[key])\n for i in range(0, data_series.size(0) ... | <|body_start_0|>
logger.info('Creating training loader.')
assert os.path.isfile(file_path), 'Training HDF5 file {} not found'.format(file_path)
examples = []
with h5py.File(file_path, 'r') as f:
samples = 0
for key in f.keys():
data_series = torch.... | Built in embedding data handler for Lorenz system | LorenzDataHandler | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class LorenzDataHandler:
"""Built in embedding data handler for Lorenz system"""
def createTrainingLoader(self, file_path: str, block_size: int, stride: int=1, ndata: int=-1, batch_size: int=32, shuffle: bool=True) -> DataLoader:
"""Creating training data loader for Lorenz system. For a si... | stack_v2_sparse_classes_75kplus_train_073640 | 23,112 | permissive | [
{
"docstring": "Creating training data loader for Lorenz system. For a single training simulation, the total time-series is sub-chunked into smaller blocks for training. Args: file_path (str): Path to HDF5 file with training data block_size (int): The length of time-series blocks stride (int): Stride of each ti... | 2 | stack_v2_sparse_classes_30k_train_002853 | Implement the Python class `LorenzDataHandler` described below.
Class description:
Built in embedding data handler for Lorenz system
Method signatures and docstrings:
- def createTrainingLoader(self, file_path: str, block_size: int, stride: int=1, ndata: int=-1, batch_size: int=32, shuffle: bool=True) -> DataLoader: ... | Implement the Python class `LorenzDataHandler` described below.
Class description:
Built in embedding data handler for Lorenz system
Method signatures and docstrings:
- def createTrainingLoader(self, file_path: str, block_size: int, stride: int=1, ndata: int=-1, batch_size: int=32, shuffle: bool=True) -> DataLoader: ... | eb28d09957641cc594b3e5acf4ace2e4dc193584 | <|skeleton|>
class LorenzDataHandler:
"""Built in embedding data handler for Lorenz system"""
def createTrainingLoader(self, file_path: str, block_size: int, stride: int=1, ndata: int=-1, batch_size: int=32, shuffle: bool=True) -> DataLoader:
"""Creating training data loader for Lorenz system. For a si... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class LorenzDataHandler:
"""Built in embedding data handler for Lorenz system"""
def createTrainingLoader(self, file_path: str, block_size: int, stride: int=1, ndata: int=-1, batch_size: int=32, shuffle: bool=True) -> DataLoader:
"""Creating training data loader for Lorenz system. For a single training... | the_stack_v2_python_sparse | trphysx/embedding/training/enn_data_handler.py | yus-nas/transformer-physx | train | 0 |
109a7f4b043dc9bb993cd3ba83c004b66adc1b9c | [
"plugin = NeighbourSelection()\nsites = [{'projection_x_coordinate': 10000.0, 'projection_y_coordinate': 10000.0}, {'projection_x_coordinate': 100000.0, 'projection_y_coordinate': 50000.0}]\nx_points = np.array([site['projection_x_coordinate'] for site in sites])\ny_points = np.array([site['projection_y_coordinate'... | <|body_start_0|>
plugin = NeighbourSelection()
sites = [{'projection_x_coordinate': 10000.0, 'projection_y_coordinate': 10000.0}, {'projection_x_coordinate': 100000.0, 'projection_y_coordinate': 50000.0}]
x_points = np.array([site['projection_x_coordinate'] for site in sites])
y_points =... | Test the function that removes sites falling outside the model domain from the site list. | Test_check_sites_are_within_domain | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
<|body_0|>
def test_some_invalid(self):
... | stack_v2_sparse_classes_75kplus_train_073641 | 40,371 | permissive | [
{
"docstring": "Test case in which all sites are valid and fall within domain.",
"name": "test_all_valid",
"signature": "def test_all_valid(self)"
},
{
"docstring": "Test case with some sites falling outside the regional domain.",
"name": "test_some_invalid",
"signature": "def test_some_... | 4 | stack_v2_sparse_classes_30k_train_040392 | Implement the Python class `Test_check_sites_are_within_domain` described below.
Class description:
Test the function that removes sites falling outside the model domain from the site list.
Method signatures and docstrings:
- def test_all_valid(self): Test case in which all sites are valid and fall within domain.
- d... | Implement the Python class `Test_check_sites_are_within_domain` described below.
Class description:
Test the function that removes sites falling outside the model domain from the site list.
Method signatures and docstrings:
- def test_all_valid(self): Test case in which all sites are valid and fall within domain.
- d... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
<|body_0|>
def test_some_invalid(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test_check_sites_are_within_domain:
"""Test the function that removes sites falling outside the model domain from the site list."""
def test_all_valid(self):
"""Test case in which all sites are valid and fall within domain."""
plugin = NeighbourSelection()
sites = [{'projection_x_... | the_stack_v2_python_sparse | improver_tests/spotdata/test_NeighbourSelection.py | metoppv/improver | train | 101 |
62e14b898d79e0015140e8288149f809dbcf424c | [
"super(MultiheadedAttention, self).__init__()\nassert model_dimension % number_of_heads == 0\nself.model_dimension = model_dimension\nself.number_of_heads = number_of_heads\nself.d_k = model_dimension // number_of_heads\nself.linears = clone(nn.Linear(model_dimension, model_dimension), 4)",
"B, seq_len, d_model =... | <|body_start_0|>
super(MultiheadedAttention, self).__init__()
assert model_dimension % number_of_heads == 0
self.model_dimension = model_dimension
self.number_of_heads = number_of_heads
self.d_k = model_dimension // number_of_heads
self.linears = clone(nn.Linear(model_dim... | Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal Dense Video Captioning}, booktitle = {Workshop on Multimodal Learning (CVPR Workshop)},... | MultiheadedAttention | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MultiheadedAttention:
"""Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal Dense Video Captioning}, booktitle = {W... | stack_v2_sparse_classes_75kplus_train_073642 | 4,448 | no_license | [
{
"docstring": "Creates 4 copies of linear layer for Query, Key, Value and attention connections. It will help attention to have multiple “representation subspaces” to focus on. This number is equivalent to number_of_heads. 4 Linear layers are used as weights for Query, Key, Value and multihead concatinated att... | 2 | stack_v2_sparse_classes_30k_test_002798 | Implement the Python class `MultiheadedAttention` described below.
Class description:
Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal ... | Implement the Python class `MultiheadedAttention` described below.
Class description:
Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal ... | 921557ee2f63bec10d2d3edfdad32919df3b82cf | <|skeleton|>
class MultiheadedAttention:
"""Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal Dense Video Captioning}, booktitle = {W... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MultiheadedAttention:
"""Multiheaded Attention class. Read more in paper https://arxiv.org/pdf/1706.03762.pdf. And specific to video captioning task from paper @InProceedings{MDVC_Iashin_2020, author = {Iashin, Vladimir and Rahtu, Esa}, title = {Multi-modal Dense Video Captioning}, booktitle = {Workshop on Mu... | the_stack_v2_python_sparse | multiModalDense/src/model/multiheadedAttention.py | VP-0822/Video-Keyword-Extractor | train | 11 |
b0d13f6b66ba9ae9b473da1add3af18cd9da0a8e | [
"self._connection = connection\nself._loginID = loginID\nself._userID = userID\nself._tweetGeneratorMethod = lambda: TweetsTableTools.getTweetsByDate(connection, userID)",
"menu = TweetsMenu(self._connection, self._userID, self._tweetGeneratorMethod)\nresult = menu.showAndGet()\nif result is None:\n return Non... | <|body_start_0|>
self._connection = connection
self._loginID = loginID
self._userID = userID
self._tweetGeneratorMethod = lambda: TweetsTableTools.getTweetsByDate(connection, userID)
<|end_body_0|>
<|body_start_1|>
menu = TweetsMenu(self._connection, self._userID, self._tweetGen... | A menu for viewing a user's tweets | UserTweetsMenu | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class UserTweetsMenu:
"""A menu for viewing a user's tweets"""
def __init__(self, connection, loginID, userID):
"""Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of"""
<|body_0|>
def showAndGet(self):
"""Show the... | stack_v2_sparse_classes_75kplus_train_073643 | 989 | no_license | [
{
"docstring": "Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of",
"name": "__init__",
"signature": "def __init__(self, connection, loginID, userID)"
},
{
"docstring": "Show the menu and return either None (if an exit key was pressed) or ... | 2 | null | Implement the Python class `UserTweetsMenu` described below.
Class description:
A menu for viewing a user's tweets
Method signatures and docstrings:
- def __init__(self, connection, loginID, userID): Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of
- def showA... | Implement the Python class `UserTweetsMenu` described below.
Class description:
A menu for viewing a user's tweets
Method signatures and docstrings:
- def __init__(self, connection, loginID, userID): Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of
- def showA... | 46b7e084234227f925a24ea2eb41ed5d9ac14b7a | <|skeleton|>
class UserTweetsMenu:
"""A menu for viewing a user's tweets"""
def __init__(self, connection, loginID, userID):
"""Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of"""
<|body_0|>
def showAndGet(self):
"""Show the... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class UserTweetsMenu:
"""A menu for viewing a user's tweets"""
def __init__(self, connection, loginID, userID):
"""Arguments: loginID -- the user ID of the signed in user userID -- the ID of the user to view the tweets of"""
self._connection = connection
self._loginID = loginID
... | the_stack_v2_python_sparse | Source/UserTweetsMenu.py | csahmad/291-Mini-Project-1 | train | 0 |
5e84a3217a705093d7824b7b5fdc7a31813134ac | [
"try:\n note = get_single_note(id, self.request.user.id)\n return note\nexcept NotesNotFoundError:\n raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])",
"try:\n note = self.get_object(id)\n return Response({'data': note, 'code': 200, 'msg': response_code[200]})\nexcept RequestObjec... | <|body_start_0|>
try:
note = get_single_note(id, self.request.user.id)
return note
except NotesNotFoundError:
raise RequestObjectDoesNotExixts(code=409, msg=response_code[409])
<|end_body_0|>
<|body_start_1|>
try:
note = self.get_object(id)
... | EditNote | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request... | stack_v2_sparse_classes_75kplus_train_073644 | 9,190 | no_license | [
{
"docstring": "param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts",
"name": "get_object",
"signature": "def get_object(self, id)"
},
{
"docstring": "param request, id: Http request contains user deta... | 3 | stack_v2_sparse_classes_30k_train_007567 | Implement the Python class `EditNote` described below.
Class description:
Implement the EditNote class.
Method signatures and docstrings:
- def get_object(self, id): param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts
- def... | Implement the Python class `EditNote` described below.
Class description:
Implement the EditNote class.
Method signatures and docstrings:
- def get_object(self, id): param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts
- def... | 8513e544cc635c372998cb8ac57bd4c93c431a9a | <|skeleton|>
class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
<|body_0|>
def get(self, request, id=None):
"""param request, id: Http request... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class EditNote:
def get_object(self, id):
"""param id: Note id returns: single note for perticular user if user is authenticated or user in collaborators else raise RequestObjectDoesNotExixts"""
try:
note = get_single_note(id, self.request.user.id)
return note
except ... | the_stack_v2_python_sparse | fundoo/note/views.py | deep-sarkar/keep | train | 0 | |
87acdf4adb9dea268d206d434b48dab8cdec56f2 | [
"plugin = LinearWeights(y0val=20.0, ynval=2.0)\nself.assertEqual(plugin.y0val, 20.0)\nself.assertEqual(plugin.ynval, 2.0)",
"msg = 'y0val must be a float >= 0.0'\nwith self.assertRaisesRegex(ValueError, msg):\n LinearWeights(y0val=-10.0, ynval=2.0)"
] | <|body_start_0|>
plugin = LinearWeights(y0val=20.0, ynval=2.0)
self.assertEqual(plugin.y0val, 20.0)
self.assertEqual(plugin.ynval, 2.0)
<|end_body_0|>
<|body_start_1|>
msg = 'y0val must be a float >= 0.0'
with self.assertRaisesRegex(ValueError, msg):
LinearWeights(y0... | Test the __init__ method. | Test__init__ | [
"BSD-3-Clause",
"LicenseRef-scancode-proprietary-license"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
<|body_0|>
def test_fails_y0val_less_than_zero(self):
"""Test it raises a Value Error if y0val less than zero."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_073645 | 7,404 | permissive | [
{
"docstring": "Test values of y0val and ynval are set correctly",
"name": "test_basic",
"signature": "def test_basic(self)"
},
{
"docstring": "Test it raises a Value Error if y0val less than zero.",
"name": "test_fails_y0val_less_than_zero",
"signature": "def test_fails_y0val_less_than_... | 2 | stack_v2_sparse_classes_30k_test_002067 | Implement the Python class `Test__init__` described below.
Class description:
Test the __init__ method.
Method signatures and docstrings:
- def test_basic(self): Test values of y0val and ynval are set correctly
- def test_fails_y0val_less_than_zero(self): Test it raises a Value Error if y0val less than zero. | Implement the Python class `Test__init__` described below.
Class description:
Test the __init__ method.
Method signatures and docstrings:
- def test_basic(self): Test values of y0val and ynval are set correctly
- def test_fails_y0val_less_than_zero(self): Test it raises a Value Error if y0val less than zero.
<|skele... | cd2c9019944345df1e703bf8f625db537ad9f559 | <|skeleton|>
class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
<|body_0|>
def test_fails_y0val_less_than_zero(self):
"""Test it raises a Value Error if y0val less than zero."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Test__init__:
"""Test the __init__ method."""
def test_basic(self):
"""Test values of y0val and ynval are set correctly"""
plugin = LinearWeights(y0val=20.0, ynval=2.0)
self.assertEqual(plugin.y0val, 20.0)
self.assertEqual(plugin.ynval, 2.0)
def test_fails_y0val_less_... | the_stack_v2_python_sparse | improver_tests/blending/weights/test_ChooseDefaultWeightsLinear.py | metoppv/improver | train | 101 |
1285e8b99dfca4eeb96eb1822f3b4d2e9b585b4a | [
"sv = ['admin']\nfor q in Globals.asterisk.queues:\n sv.append('SV ' + q)\nif not in_any_group(*sv):\n tmpl_context.form = TableForm(submit_text=None)\n flash(u'Accès interdit !', 'error')\n redirect('/')\nchecked = None\nman = Globals.manager.command('database show closed')\nchecked = []\nfor i, r in e... | <|body_start_0|>
sv = ['admin']
for q in Globals.asterisk.queues:
sv.append('SV ' + q)
if not in_any_group(*sv):
tmpl_context.form = TableForm(submit_text=None)
flash(u'Accès interdit !', 'error')
redirect('/')
checked = None
man = ... | Close_ctrl | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Close_ctrl:
def index(self, **kw):
"""Display closed form"""
<|body_0|>
def modify(self, checked=[], **kw):
"""Modify Asterisk database (closed)"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
sv = ['admin']
for q in Globals.asterisk.queues:... | stack_v2_sparse_classes_75kplus_train_073646 | 2,535 | no_license | [
{
"docstring": "Display closed form",
"name": "index",
"signature": "def index(self, **kw)"
},
{
"docstring": "Modify Asterisk database (closed)",
"name": "modify",
"signature": "def modify(self, checked=[], **kw)"
}
] | 2 | stack_v2_sparse_classes_30k_train_054450 | Implement the Python class `Close_ctrl` described below.
Class description:
Implement the Close_ctrl class.
Method signatures and docstrings:
- def index(self, **kw): Display closed form
- def modify(self, checked=[], **kw): Modify Asterisk database (closed) | Implement the Python class `Close_ctrl` described below.
Class description:
Implement the Close_ctrl class.
Method signatures and docstrings:
- def index(self, **kw): Display closed form
- def modify(self, checked=[], **kw): Modify Asterisk database (closed)
<|skeleton|>
class Close_ctrl:
def index(self, **kw):... | 8a923e59de0f8211e051ef94e160539f1debde95 | <|skeleton|>
class Close_ctrl:
def index(self, **kw):
"""Display closed form"""
<|body_0|>
def modify(self, checked=[], **kw):
"""Modify Asterisk database (closed)"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Close_ctrl:
def index(self, **kw):
"""Display closed form"""
sv = ['admin']
for q in Globals.asterisk.queues:
sv.append('SV ' + q)
if not in_any_group(*sv):
tmpl_context.form = TableForm(submit_text=None)
flash(u'Accès interdit !', 'error')
... | the_stack_v2_python_sparse | astportal2/controllers/close.py | sysnux/astportal | train | 0 | |
de794bed6c53bf3f8a5bba503bd35cacb1a375a2 | [
"children = getattr(node, 'children', [])\nfor child in children:\n self.visit(child)",
"method = 'visit_' + node.__class__.__name__\nvisitor = getattr(self, method, self.generic_visit)\nreturn visitor(node)"
] | <|body_start_0|>
children = getattr(node, 'children', [])
for child in children:
self.visit(child)
<|end_body_0|>
<|body_start_1|>
method = 'visit_' + node.__class__.__name__
visitor = getattr(self, method, self.generic_visit)
return visitor(node)
<|end_body_1|>
| This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you are done, you can call `super().generic_visit(node)`, which will visit all the ... | AdaVisitor | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdaVisitor:
"""This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you are done, you can call `super().generic_v... | stack_v2_sparse_classes_75kplus_train_073647 | 1,643 | permissive | [
{
"docstring": "Generically visit some node, recursively visiting its children",
"name": "generic_visit",
"signature": "def generic_visit(self: AdaVisitorT, node: AdaNodeT) -> None"
},
{
"docstring": "Entry point to visit an arbitrary Ada AST node",
"name": "visit",
"signature": "def vis... | 2 | null | Implement the Python class `AdaVisitor` described below.
Class description:
This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you ar... | Implement the Python class `AdaVisitor` described below.
Class description:
This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you ar... | cafce30763b5332106340cc8cbeb8fdac3b8132d | <|skeleton|>
class AdaVisitor:
"""This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you are done, you can call `super().generic_v... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdaVisitor:
"""This is a very simple class you can inherit from to visit the Ada AST. For any node you want to handle, you can define a method `generic_<NodeName>`, which will be called automatically. If you want the visit to continue recursively once you are done, you can call `super().generic_visit(node)`, ... | the_stack_v2_python_sparse | ada/ada_visitor.py | pauls4GE/RACK | train | 0 |
8491bea042761c1fe5bea71615bac113b4e48d83 | [
"Action.__init__(self, p_game_state)\nassert isinstance(p_player_id, int)\nassert PLAYER_PER_TEAM >= p_player_id >= 0\nassert isinstance(p_is_right_goal, bool)\nassert isinstance(p_minimum_distance, (int, float))\nassert isinstance(p_maximum_distance, (int, float)) or p_maximum_distance is None\nif p_maximum_distan... | <|body_start_0|>
Action.__init__(self, p_game_state)
assert isinstance(p_player_id, int)
assert PLAYER_PER_TEAM >= p_player_id >= 0
assert isinstance(p_is_right_goal, bool)
assert isinstance(p_minimum_distance, (int, float))
assert isinstance(p_maximum_distance, (int, flo... | Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action): player_id : L'identifiant du gardien... | ProtectGoal | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ProtectGoal:
"""Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action... | stack_v2_sparse_classes_75kplus_train_073648 | 4,214 | permissive | [
{
"docstring": ":param p_game_state: L'état courant du jeu. :param p_player_id: L'identifiant du joueur qui est le gardien de but. :param p_is_right_goal: Un booléen indiquant si le but à protéger est celui de droite. :param p_minimum_distance: La distance minimale qu'il doit y avoir entre le gardien et le cent... | 2 | stack_v2_sparse_classes_30k_train_017294 | Implement the Python class `ProtectGoal` described below.
Class description:
Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendr... | Implement the Python class `ProtectGoal` described below.
Class description:
Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendr... | 7e20de8b2213d9b9b46be16d6b4800d767da1b00 | <|skeleton|>
class ProtectGoal:
"""Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ProtectGoal:
"""Action ProtectGoal: Action de base pour le gardien de but. Déplace le gardien entre la balle et le centre du but, à une certaine distance de celui-ci, tout en restant dans la zone du gardien. Méthodes: exec(self): Retourne la pose où se rendre. Attributs (en plus de ceux de Action): player_id ... | the_stack_v2_python_sparse | ai/STA/Action/ProtectGoal.py | etibuteau/StrategyIA | train | 0 |
247a7e295102457b0525aba63539d97b050b025a | [
"super().__init__(model, dataset)\nself.entity_id_2_train_samples = {}\nfor h, r, t in dataset.train_samples:\n if h in self.entity_id_2_train_samples:\n self.entity_id_2_train_samples[h].append((h, r, t))\n else:\n self.entity_id_2_train_samples[h] = [(h, r, t)]\n if t in self.entity_id_2_tr... | <|body_start_0|>
super().__init__(model, dataset)
self.entity_id_2_train_samples = {}
for h, r, t in dataset.train_samples:
if h in self.entity_id_2_train_samples:
self.entity_id_2_train_samples[h].append((h, r, t))
else:
self.entity_id_2_t... | The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts . | NoPreFilter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the mode... | stack_v2_sparse_classes_75kplus_train_073649 | 2,543 | no_license | [
{
"docstring": "NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the model",
"name": "__init__",
"signature": "def __init__(self, model: Model, dataset: Dataset)"
},
{
"docstring": "This method extracts the top k promising samples for i... | 2 | stack_v2_sparse_classes_30k_test_001626 | Implement the Python class `NoPreFilter` described below.
Class description:
The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts .
Method signatures and docstrings:
- def __init__(self, model: Model, dataset: Dataset): NoPreFilter object constructor. :param model: the model to e... | Implement the Python class `NoPreFilter` described below.
Class description:
The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts .
Method signatures and docstrings:
- def __init__(self, model: Model, dataset: Dataset): NoPreFilter object constructor. :param model: the model to e... | 9b408d1cef1a10c4bb8a32824eb3f8c90b9a8fb0 | <|skeleton|>
class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the mode... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NoPreFilter:
"""The NoPreFilter object is a fake PreFilter that does not filter away any unpromising facts ."""
def __init__(self, model: Model, dataset: Dataset):
"""NoPreFilter object constructor. :param model: the model to explain :param dataset: the dataset used to train the model"""
... | the_stack_v2_python_sparse | prefilters/no_prefilter.py | AndRossi/Kelpie | train | 45 |
0528402cc2c7e48fa740de49ee4e7ac618ef613c | [
"self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)\nself.awq = AWQ(self.conn)\nself.gmoney = GMoney(min_money=min_money, max_money=max_money)\nself.ops = Operations(self.gmoney)\nself.mutations = Mu... | <|body_start_0|>
self.conn = Connection(password=get_environment_variable('VEN_ADWORDS_PASSWORD'), developer_token=get_environment_variable('VEN_ADWORDS_TOKEN'), account_id=account_id)
self.awq = AWQ(self.conn)
self.gmoney = GMoney(min_money=min_money, max_money=max_money)
self.ops = Ope... | KeywordOperationsBase | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_75kplus_train_073650 | 3,450 | permissive | [
{
"docstring": "Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store",
"name": "__init__",
"signature": "def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.D... | 4 | stack_v2_sparse_classes_30k_train_007292 | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | Implement the Python class `KeywordOperationsBase` described below.
Class description:
Implement the KeywordOperationsBase class.
Method signatures and docstrings:
- def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000): Pass in min and max... | 72dbdf41b0250708ad525030128cc7c3948b3f41 | <|skeleton|>
class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class KeywordOperationsBase:
def __init__(self, account_id='7998744469', store=None, min_money=None, max_money=None, logging_level=logging.DEBUG, chk_size=5000):
"""Pass in min and max (in Euros, NOT micros) based bid if you want to override the GMoney defaults store: storage that acts like an HDF5 store"""... | the_stack_v2_python_sparse | ut/aw/keyword_operations_base.py | thorwhalen/ut | train | 6 | |
3f84159dfdeb5f3793d758bdde0939d5d63e294c | [
"super(FunctionComponent, self).__init__(opts)\noptions = opts.get(SECTION_SCHEDULER, {})\nvalidate_app_config(options)\nself.timezone = options.get('timezone')\nself.scheduler = ResilientScheduler(options.get('db_url'), options.get('datastore_dir'), options.get('thread_max'), options.get('timezone'))\nlog.info('Sc... | <|body_start_0|>
super(FunctionComponent, self).__init__(opts)
options = opts.get(SECTION_SCHEDULER, {})
validate_app_config(options)
self.timezone = options.get('timezone')
self.scheduler = ResilientScheduler(options.get('db_url'), options.get('datastore_dir'), options.get('thre... | Component that polls for new data arriving from Proofpoint TRAP | FunctionComponent | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class FunctionComponent:
"""Component that polls for new data arriving from Proofpoint TRAP"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, sav... | stack_v2_sparse_classes_75kplus_train_073651 | 1,538 | permissive | [
{
"docstring": "constructor provides access to the configuration options",
"name": "__init__",
"signature": "def __init__(self, opts)"
},
{
"docstring": "Configuration options have changed, save new values",
"name": "_reload",
"signature": "def _reload(self, event, opts)"
}
] | 2 | stack_v2_sparse_classes_30k_test_000584 | Implement the Python class `FunctionComponent` described below.
Class description:
Component that polls for new data arriving from Proofpoint TRAP
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration opti... | Implement the Python class `FunctionComponent` described below.
Class description:
Component that polls for new data arriving from Proofpoint TRAP
Method signatures and docstrings:
- def __init__(self, opts): constructor provides access to the configuration options
- def _reload(self, event, opts): Configuration opti... | 3ecdabe6bf2fc08f0f8e58cbe92553270d8da42f | <|skeleton|>
class FunctionComponent:
"""Component that polls for new data arriving from Proofpoint TRAP"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
<|body_0|>
def _reload(self, event, opts):
"""Configuration options have changed, sav... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class FunctionComponent:
"""Component that polls for new data arriving from Proofpoint TRAP"""
def __init__(self, opts):
"""constructor provides access to the configuration options"""
super(FunctionComponent, self).__init__(opts)
options = opts.get(SECTION_SCHEDULER, {})
validat... | the_stack_v2_python_sparse | fn_scheduler/fn_scheduler/components/scheduler_poller.py | neetinkandhare/resilient-community-apps | train | 1 |
d2942c037b9e49d5d943906c1c4791625ff9b8ea | [
"super().__init__(**kwargs)\nif pd_feature_list is None:\n self._pd_feature_list = get_default_pd_feature_list()\nelse:\n self._pd_feature_list = pd_feature_list\nif ed_feature_list is None:\n self._ed_feature_list = get_default_ed_feature_list()\nelse:\n self._ed_feature_list = ed_feature_list\nself._p... | <|body_start_0|>
super().__init__(**kwargs)
if pd_feature_list is None:
self._pd_feature_list = get_default_pd_feature_list()
else:
self._pd_feature_list = pd_feature_list
if ed_feature_list is None:
self._ed_feature_list = get_default_ed_feature_list(... | DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This is the reverse operation performed by DataMerger. Channels that are not present ... | DataSplitter | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class DataSplitter:
"""DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This is the reverse operation performed by Da... | stack_v2_sparse_classes_75kplus_train_073652 | 8,065 | permissive | [
{
"docstring": "Construct a DataSplitter instance. Parameters ---------- pd_feature_list : list, optional List of indices for particle distribution channels that should be generated. Defaults to None, which will use [0,1,2,3,4,5,6] (everything except nuclei). See also src/models/gan/datamerger.py for defaults. ... | 4 | null | Implement the Python class `DataSplitter` described below.
Class description:
DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This i... | Implement the Python class `DataSplitter` described below.
Class description:
DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This i... | 7f0086d2cdec23b49958c5afc0e6d12a08598465 | <|skeleton|>
class DataSplitter:
"""DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This is the reverse operation performed by Da... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class DataSplitter:
"""DataSplitter handles splitting particle distribution and energy deposit data. Because internally, all profile types are treated similarly, this class handles the splitting of selected particle distribution and energy deposit channels. This is the reverse operation performed by DataMerger. Cha... | the_stack_v2_python_sparse | src/models/gan/utils/datamerger.py | image357/conex-generator | train | 0 |
2e5c7a3bbdf192ef756642fc46119a8dc04c18d8 | [
"print('谣言中心检测')\nif self.subgraph.number_of_nodes() == 0:\n print('subgraph.number_of_nodes =0')\n return\nself.reset_centrality()\ncentrality = {}\nfor source in self.subgraph.nodes():\n self.bfs_tree = nx.bfs_tree(self.subgraph, source)\n self.visited.clear()\n self.get_number_in_subtree(source)\n... | <|body_start_0|>
print('谣言中心检测')
if self.subgraph.number_of_nodes() == 0:
print('subgraph.number_of_nodes =0')
return
self.reset_centrality()
centrality = {}
for source in self.subgraph.nodes():
self.bfs_tree = nx.bfs_tree(self.subgraph, source... | detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 38(1): 203-214. | RumorCenter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RumorCenter:
"""detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 38(1): 203-214."""
def detect(self)... | stack_v2_sparse_classes_75kplus_train_073653 | 3,993 | no_license | [
{
"docstring": "detect the source with Rumor Centrality. Returns: @rtype:int the detected source",
"name": "detect",
"signature": "def detect(self)"
},
{
"docstring": "get centralities for all nodes by passing a message from the root to the children. Args: u:",
"name": "get_centrality",
... | 3 | stack_v2_sparse_classes_30k_train_011919 | Implement the Python class `RumorCenter` described below.
Class description:
detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 3... | Implement the Python class `RumorCenter` described below.
Class description:
detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 3... | d9d606f33674f6942b5dc1a56d7738ccea108126 | <|skeleton|>
class RumorCenter:
"""detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 38(1): 203-214."""
def detect(self)... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RumorCenter:
"""detect the source with Rumor Centrality. Please refer to the following paper for more details. Shah D, Zaman T. Detecting sources of computer viruses in networks: theory and experiment[J]. ACM SIGMETRICS Performance Evaluation Review, 2010, 38(1): 203-214."""
def detect(self):
"""... | the_stack_v2_python_sparse | jarden_center/research-master/research-master/SourceDetection/bao/rumor_center.py | 15779235038/mypaper | train | 5 |
1c0221e6e493b7d2f5765608ed371a64e32973e3 | [
"self.total = total\nself.clone_children = clone_children\nif isinstance(inline, tuple):\n inline = [inline]\n_graphs = graphs + tuple((g for g, _, _ in inline))\nself.manager = manage(*_graphs, weak=True)\nself.collect_graphs(graphs, inline)\nself.remapper = remapper_class(graphs=self.graphs, manager=self.manag... | <|body_start_0|>
self.total = total
self.clone_children = clone_children
if isinstance(inline, tuple):
inline = [inline]
_graphs = graphs + tuple((g for g, _, _ in inline))
self.manager = manage(*_graphs, weak=True)
self.collect_graphs(graphs, inline)
... | Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (graph, target_graph, new_params): :graph: The original graph, which we want to c... | GraphCloner | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class GraphCloner:
"""Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (graph, target_graph, new_params): :graph:... | stack_v2_sparse_classes_75kplus_train_073654 | 17,591 | permissive | [
{
"docstring": "Initialize a GraphCloner.",
"name": "__init__",
"signature": "def __init__(self, *graphs, inline=[], total=False, relation='copy', clone_constants=False, clone_children=True, graph_relation=None, graph_repl=None, remapper_class=CloneRemapper)"
},
{
"docstring": "Collect the full ... | 3 | null | Implement the Python class `GraphCloner` described below.
Class description:
Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (gr... | Implement the Python class `GraphCloner` described below.
Class description:
Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (gr... | d7b12c15453079e1a2c4fdae611c5f741574363d | <|skeleton|>
class GraphCloner:
"""Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (graph, target_graph, new_params): :graph:... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class GraphCloner:
"""Facility to clone graphs. To get the clone of a graph, index the GraphCloner with the graph, e.g. `cloned_g = graph_cloner[g]` Arguments: graphs: A set of graphs to clone. inline: A list of graphs to inline. Each entry must be a triple of (graph, target_graph, new_params): :graph: The original... | the_stack_v2_python_sparse | myia/ir/clone.py | breuleux/myia | train | 1 |
d4687cf6e3e6191c1f41034e923b20aa3fbc6356 | [
"super(err_reduction_hook, self).pre_iteration(step, level_number)\nL = step.levels[level_number]\nif step.status.iter == 2 and np.isclose(L.time + L.dt, 0.1):\n P = L.prob\n err = []\n for m in range(L.sweep.coll.num_nodes):\n uex = P.u_exact(L.time + L.dt * L.sweep.coll.nodes[m])\n err.appe... | <|body_start_0|>
super(err_reduction_hook, self).pre_iteration(step, level_number)
L = step.levels[level_number]
if step.status.iter == 2 and np.isclose(L.time + L.dt, 0.1):
P = L.prob
err = []
for m in range(L.sweep.coll.num_nodes):
uex = P.u_... | err_reduction_hook | [
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class err_reduction_hook:
def pre_iteration(self, step, level_number):
"""Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the current level number"""
<|body_0|>
def post_iteration(self, step, level_number):
"""Routi... | stack_v2_sparse_classes_75kplus_train_073655 | 2,170 | permissive | [
{
"docstring": "Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the current level number",
"name": "pre_iteration",
"signature": "def pre_iteration(self, step, level_number)"
},
{
"docstring": "Routine called after each iteration Args: st... | 2 | stack_v2_sparse_classes_30k_train_026922 | Implement the Python class `err_reduction_hook` described below.
Class description:
Implement the err_reduction_hook class.
Method signatures and docstrings:
- def pre_iteration(self, step, level_number): Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the cur... | Implement the Python class `err_reduction_hook` described below.
Class description:
Implement the err_reduction_hook class.
Method signatures and docstrings:
- def pre_iteration(self, step, level_number): Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the cur... | 1a51834bedffd4472e344bed28f4d766614b1537 | <|skeleton|>
class err_reduction_hook:
def pre_iteration(self, step, level_number):
"""Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the current level number"""
<|body_0|>
def post_iteration(self, step, level_number):
"""Routi... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class err_reduction_hook:
def pre_iteration(self, step, level_number):
"""Routine called before iteration starts Args: step (pySDC.Step.step): the current step level_number (int): the current level number"""
super(err_reduction_hook, self).pre_iteration(step, level_number)
L = step.levels[le... | the_stack_v2_python_sparse | pySDC/projects/parallelSDC/ErrReductionHook.py | Parallel-in-Time/pySDC | train | 30 | |
79c3d93e6f2429690e8ac22c61589cb2f73cca17 | [
"self.registrert_dato_field = APIHelper.RFC3339DateTime(registrert_dato_field) if registrert_dato_field else None\nself.beta_gruppe_kode_field = beta_gruppe_kode_field\nself.beta_gruppe_tekst_field = beta_gruppe_tekst_field\nself.beta_type_field = beta_type_field\nself.beta_tekst_field = beta_tekst_field\nself.beta... | <|body_start_0|>
self.registrert_dato_field = APIHelper.RFC3339DateTime(registrert_dato_field) if registrert_dato_field else None
self.beta_gruppe_kode_field = beta_gruppe_kode_field
self.beta_gruppe_tekst_field = beta_gruppe_tekst_field
self.beta_type_field = beta_type_field
sel... | Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (string): TODO: type description here. beta_type_field (string): TODO: type desc... | BetaDetaljer | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BetaDetaljer:
"""Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (string): TODO: type description here. b... | stack_v2_sparse_classes_75kplus_train_073656 | 5,833 | permissive | [
{
"docstring": "Constructor for the BetaDetaljer class",
"name": "__init__",
"signature": "def __init__(self, registrert_dato_field=None, beta_gruppe_kode_field=None, beta_gruppe_tekst_field=None, beta_type_field=None, beta_tekst_field=None, beta_belop_field=None, kilde_kode_field=None, kilde_tekst_fiel... | 2 | stack_v2_sparse_classes_30k_train_015235 | Implement the Python class `BetaDetaljer` described below.
Class description:
Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (... | Implement the Python class `BetaDetaljer` described below.
Class description:
Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (... | fa3918a6c54ea0eedb9146578645b7eb1755b642 | <|skeleton|>
class BetaDetaljer:
"""Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (string): TODO: type description here. b... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BetaDetaljer:
"""Implementation of the 'BetaDetaljer' model. TODO: type model description here. Attributes: registrert_dato_field (datetime): TODO: type description here. beta_gruppe_kode_field (string): TODO: type description here. beta_gruppe_tekst_field (string): TODO: type description here. beta_type_fiel... | the_stack_v2_python_sparse | idfy_rest_client/models/beta_detaljer.py | dealflowteam/Idfy | train | 0 |
1f3b385394e5ff2251ba972809e2e2b06b9b0a1e | [
"inch = 0\ninch = meter * 3.28\nprint(f'{meter}米等于{inch}英尺')",
"meter = 0\nmeter = inch / 3.28\nprint(f'{inch}英尺等于{meter}米')"
] | <|body_start_0|>
inch = 0
inch = meter * 3.28
print(f'{meter}米等于{inch}英尺')
<|end_body_0|>
<|body_start_1|>
meter = 0
meter = inch / 3.28
print(f'{inch}英尺等于{meter}米')
<|end_body_1|>
| 英尺和米制的互换 | Length | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Length:
"""英尺和米制的互换"""
def m_to_inch(self, meter):
"""米换为英尺"""
<|body_0|>
def inch_to_m(self, inch):
"""英尺换为米"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
inch = 0
inch = meter * 3.28
print(f'{meter}米等于{inch}英尺')
<|end_body_0|... | stack_v2_sparse_classes_75kplus_train_073657 | 2,776 | no_license | [
{
"docstring": "米换为英尺",
"name": "m_to_inch",
"signature": "def m_to_inch(self, meter)"
},
{
"docstring": "英尺换为米",
"name": "inch_to_m",
"signature": "def inch_to_m(self, inch)"
}
] | 2 | null | Implement the Python class `Length` described below.
Class description:
英尺和米制的互换
Method signatures and docstrings:
- def m_to_inch(self, meter): 米换为英尺
- def inch_to_m(self, inch): 英尺换为米 | Implement the Python class `Length` described below.
Class description:
英尺和米制的互换
Method signatures and docstrings:
- def m_to_inch(self, meter): 米换为英尺
- def inch_to_m(self, inch): 英尺换为米
<|skeleton|>
class Length:
"""英尺和米制的互换"""
def m_to_inch(self, meter):
"""米换为英尺"""
<|body_0|>
def inch... | 355c7251dda058deefc80f3bffbf6c541d92ad41 | <|skeleton|>
class Length:
"""英尺和米制的互换"""
def m_to_inch(self, meter):
"""米换为英尺"""
<|body_0|>
def inch_to_m(self, inch):
"""英尺换为米"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Length:
"""英尺和米制的互换"""
def m_to_inch(self, meter):
"""米换为英尺"""
inch = 0
inch = meter * 3.28
print(f'{meter}米等于{inch}英尺')
def inch_to_m(self, inch):
"""英尺换为米"""
meter = 0
meter = inch / 3.28
print(f'{inch}英尺等于{meter}米')
| the_stack_v2_python_sparse | 0202obj-pengtao/translator_v1.0.py | echolvan/homework | train | 0 |
f728be0f711ae6e32b730d533feafe9f8bd1b651 | [
"super().__init__()\nself.image = pygame.Surface([largo, alto])\nself.image.fill(color)\nself.rect = self.image.get_rect()\nself.centrar_x = 0\nself.centrar_y = 0\nself.angulo = 0\nself.radio = 0\nself.velocidad = 0.05",
"self.rect.x = self.radio * math.sin(self.angulo) + self.centrar_x\nself.rect.y = self.radio ... | <|body_start_0|>
super().__init__()
self.image = pygame.Surface([largo, alto])
self.image.fill(color)
self.rect = self.image.get_rect()
self.centrar_x = 0
self.centrar_y = 0
self.angulo = 0
self.radio = 0
self.velocidad = 0.05
<|end_body_0|>
<|bod... | Esta clase representa la pelota que se mueve en círculos. | Bloque | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Bloque:
"""Esta clase representa la pelota que se mueve en círculos."""
def __init__(self, color, largo, alto):
"""Constructor que crea la imagen de la pelota."""
<|body_0|>
def update(self):
"""Actualizamos la posición de la pelota."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus_train_073658 | 4,382 | no_license | [
{
"docstring": "Constructor que crea la imagen de la pelota.",
"name": "__init__",
"signature": "def __init__(self, color, largo, alto)"
},
{
"docstring": "Actualizamos la posición de la pelota.",
"name": "update",
"signature": "def update(self)"
}
] | 2 | null | Implement the Python class `Bloque` described below.
Class description:
Esta clase representa la pelota que se mueve en círculos.
Method signatures and docstrings:
- def __init__(self, color, largo, alto): Constructor que crea la imagen de la pelota.
- def update(self): Actualizamos la posición de la pelota. | Implement the Python class `Bloque` described below.
Class description:
Esta clase representa la pelota que se mueve en círculos.
Method signatures and docstrings:
- def __init__(self, color, largo, alto): Constructor que crea la imagen de la pelota.
- def update(self): Actualizamos la posición de la pelota.
<|skele... | b497a94fcc4e79ab23d8d5f06320a80b2b3e0588 | <|skeleton|>
class Bloque:
"""Esta clase representa la pelota que se mueve en círculos."""
def __init__(self, color, largo, alto):
"""Constructor que crea la imagen de la pelota."""
<|body_0|>
def update(self):
"""Actualizamos la posición de la pelota."""
<|body_1|>
<|end_... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Bloque:
"""Esta clase representa la pelota que se mueve en círculos."""
def __init__(self, color, largo, alto):
"""Constructor que crea la imagen de la pelota."""
super().__init__()
self.image = pygame.Surface([largo, alto])
self.image.fill(color)
self.rect = self.... | the_stack_v2_python_sparse | Sprites/sprite_circle_movement.py | Armando123x/JuegosPygame | train | 0 |
8eefa9d990be4da0138d794ebbeba597d2da2706 | [
"all_card_ids_for_deck = Card.objects.filter(deck=kwargs.get('deck_id')).values_list('ID', flat=True)\nif not 'force' in kwargs:\n kwargs['force'] = False\nif kwargs['force']:\n all_practice_for_this_deck = Practice.objects.filter(user=self.request.user, object_id__in=all_card_ids_for_deck).order_by('ended_la... | <|body_start_0|>
all_card_ids_for_deck = Card.objects.filter(deck=kwargs.get('deck_id')).values_list('ID', flat=True)
if not 'force' in kwargs:
kwargs['force'] = False
if kwargs['force']:
all_practice_for_this_deck = Practice.objects.filter(user=self.request.user, object_... | next_practice_item | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class next_practice_item:
def get(self, request, *args, **kwargs):
"""Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards will be displayed according to when he last viewed them starting with the least recent. If the user uses Skip... | stack_v2_sparse_classes_75kplus_train_073659 | 5,360 | permissive | [
{
"docstring": "Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards will be displayed according to when he last viewed them starting with the least recent. If the user uses Skip in this mode, the card will be put at the end of the deck.",
"name"... | 2 | null | Implement the Python class `next_practice_item` described below.
Class description:
Implement the next_practice_item class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards wi... | Implement the Python class `next_practice_item` described below.
Class description:
Implement the next_practice_item class.
Method signatures and docstrings:
- def get(self, request, *args, **kwargs): Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards wi... | e6f9eb61fd06fb31f13f2f0fbdce29ce9d78feaf | <|skeleton|>
class next_practice_item:
def get(self, request, *args, **kwargs):
"""Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards will be displayed according to when he last viewed them starting with the least recent. If the user uses Skip... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class next_practice_item:
def get(self, request, *args, **kwargs):
"""Prepares the items to learn and sorts them differently depending on mode. If the user chooses force mode the cards will be displayed according to when he last viewed them starting with the least recent. If the user uses Skip in this mode,... | the_stack_v2_python_sparse | deckglue/views.py | DummyDivision/Tsune | train | 1 | |
8711cacd47e4ec61718a1afe5a736b487d2e7a1d | [
"self.host = host\nif user:\n self._auth = HTTPBasicAuth(user, password)\nelse:\n self._auth = None\nself.dam = Assets(self)",
"try:\n url = self.host + path\n logging.debug('URL - ' + url)\n result = requests.get(url, auth=self._auth)\n logging.debug('Response from the URL : ' + str(result))\n ... | <|body_start_0|>
self.host = host
if user:
self._auth = HTTPBasicAuth(user, password)
else:
self._auth = None
self.dam = Assets(self)
<|end_body_0|>
<|body_start_1|>
try:
url = self.host + path
logging.debug('URL - ' + url)
... | Connects to and performs the get and post operations on the connected AEM instance | Connector | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Connector:
"""Connects to and performs the get and post operations on the connected AEM instance"""
def __init__(self, host, user, password):
"""Initialize connection to the host with given user and password"""
<|body_0|>
def rawget(self, path):
"""Performs a get... | stack_v2_sparse_classes_75kplus_train_073660 | 3,242 | permissive | [
{
"docstring": "Initialize connection to the host with given user and password",
"name": "__init__",
"signature": "def __init__(self, host, user, password)"
},
{
"docstring": "Performs a get operation to the path and returns the raw response as-is",
"name": "rawget",
"signature": "def ra... | 5 | stack_v2_sparse_classes_30k_train_021566 | Implement the Python class `Connector` described below.
Class description:
Connects to and performs the get and post operations on the connected AEM instance
Method signatures and docstrings:
- def __init__(self, host, user, password): Initialize connection to the host with given user and password
- def rawget(self, ... | Implement the Python class `Connector` described below.
Class description:
Connects to and performs the get and post operations on the connected AEM instance
Method signatures and docstrings:
- def __init__(self, host, user, password): Initialize connection to the host with given user and password
- def rawget(self, ... | 432d802f62da95eaa630cae651dabba56d50029c | <|skeleton|>
class Connector:
"""Connects to and performs the get and post operations on the connected AEM instance"""
def __init__(self, host, user, password):
"""Initialize connection to the host with given user and password"""
<|body_0|>
def rawget(self, path):
"""Performs a get... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Connector:
"""Connects to and performs the get and post operations on the connected AEM instance"""
def __init__(self, host, user, password):
"""Initialize connection to the host with given user and password"""
self.host = host
if user:
self._auth = HTTPBasicAuth(user,... | the_stack_v2_python_sparse | dampy/lib/Connector.py | moonraker46/dampy | train | 0 |
a66426250be6b950f450747e18f07048be518987 | [
"try:\n self.__proc = subprocess.Popen(['4am-remoteexecd', socketurl], stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)\nexcept:\n print('Unables to create the process, is the PATH correct ?' + str(sys.exc_info()[0]), file=sys.stderr)\n raise\nsuper(Proxy, self).__init__([socketurl])",
"super(Proxy... | <|body_start_0|>
try:
self.__proc = subprocess.Popen(['4am-remoteexecd', socketurl], stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr)
except:
print('Unables to create the process, is the PATH correct ?' + str(sys.exc_info()[0]), file=sys.stderr)
raise
su... | This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it. | Proxy | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Proxy:
"""This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it."""
def __init__(self, socketurl):
"""Create a remoteExecuter process. FIXME output should maybe be logged instead of written to stdout. http://mail.python... | stack_v2_sparse_classes_75kplus_train_073661 | 1,460 | no_license | [
{
"docstring": "Create a remoteExecuter process. FIXME output should maybe be logged instead of written to stdout. http://mail.python.org/pipermail/python-list/2008-April/536949.html",
"name": "__init__",
"signature": "def __init__(self, socketurl)"
},
{
"docstring": "Destructor, needs to explic... | 2 | stack_v2_sparse_classes_30k_train_019641 | Implement the Python class `Proxy` described below.
Class description:
This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it.
Method signatures and docstrings:
- def __init__(self, socketurl): Create a remoteExecuter process. FIXME output should maybe b... | Implement the Python class `Proxy` described below.
Class description:
This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it.
Method signatures and docstrings:
- def __init__(self, socketurl): Create a remoteExecuter process. FIXME output should maybe b... | 2b3be364240df3b3393aac79e5c7209edb37286a | <|skeleton|>
class Proxy:
"""This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it."""
def __init__(self, socketurl):
"""Create a remoteExecuter process. FIXME output should maybe be logged instead of written to stdout. http://mail.python... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Proxy:
"""This class is an abstraction of a remoteExecuter process. A rE is launched and the class acts as a proxy to contact it."""
def __init__(self, socketurl):
"""Create a remoteExecuter process. FIXME output should maybe be logged instead of written to stdout. http://mail.python.org/pipermai... | the_stack_v2_python_sparse | lib/remoteexecd/proc.py | sx4it/4am-core-deprecated | train | 0 |
d562dcaefec4053be49970f6baff9ddd09805ae9 | [
"expected_access_levels = (constants.MEMBERS_ACCESS, constants.REGISTERED_ACCESS, constants.PUBLIC_ACCESS)\nowner = self.member1_profile\nviewer = self.member2_profile\nself.assertItemsEqual(expected_access_levels, access_levels(owner, viewer))",
"expected_access_levels = (constants.PUBLIC_ACCESS,)\nowner = self.... | <|body_start_0|>
expected_access_levels = (constants.MEMBERS_ACCESS, constants.REGISTERED_ACCESS, constants.PUBLIC_ACCESS)
owner = self.member1_profile
viewer = self.member2_profile
self.assertItemsEqual(expected_access_levels, access_levels(owner, viewer))
<|end_body_0|>
<|body_start_1... | Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned. | AccessLevelsTestCase | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AccessLevelsTestCase:
"""Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_member_and_member(self):
"""Test correct access levels with a member as owner and a member a... | stack_v2_sparse_classes_75kplus_train_073662 | 10,516 | permissive | [
{
"docstring": "Test correct access levels with a member as owner and a member as a viewer.",
"name": "test_member_and_member",
"signature": "def test_member_and_member(self)"
},
{
"docstring": "Test correct access levels with a member as owner and an anonymous viewer.",
"name": "test_member... | 4 | null | Implement the Python class `AccessLevelsTestCase` described below.
Class description:
Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned.
Method signatures and docstrings:
- def test_member_and_member(self): Test co... | Implement the Python class `AccessLevelsTestCase` described below.
Class description:
Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned.
Method signatures and docstrings:
- def test_member_and_member(self): Test co... | b26e4dd37b095247b15ae087639eedd1a2028247 | <|skeleton|>
class AccessLevelsTestCase:
"""Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_member_and_member(self):
"""Test correct access levels with a member as owner and a member a... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AccessLevelsTestCase:
"""Test the access_levels method in access.py. Test different configurations of owner and viewer, and make sure the correct valid access levels are returned."""
def test_member_and_member(self):
"""Test correct access levels with a member as owner and a member as a viewer.""... | the_stack_v2_python_sparse | HedyNet/profiles/tests.py | SeattleAttic/HedyNet | train | 0 |
8da7f8a42b07cb657c235fa38af23f70d203b439 | [
"super(TopologyStatistics, self).__init__()\nself.internalDict = {'bestFitness': 0.0, 'fitness': 0.0, 'bestPosition': [], 'bestPosDim:': 0.0, 'position': []}\nself.descriptions = {'bestFitness': 'Best Fitness of the best Particle', 'fitness': 'Fitness of the best Particle', 'bestPosition': 'Best Position of the bes... | <|body_start_0|>
super(TopologyStatistics, self).__init__()
self.internalDict = {'bestFitness': 0.0, 'fitness': 0.0, 'bestPosition': [], 'bestPosDim:': 0.0, 'position': []}
self.descriptions = {'bestFitness': 'Best Fitness of the best Particle', 'fitness': 'Fitness of the best Particle', 'bestPo... | Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle **bestPosDim** Best First Dimmension Position ... | TopologyStatistics | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle ... | stack_v2_sparse_classes_75kplus_train_073663 | 5,204 | no_license | [
{
"docstring": "The Topology Statistics Class Creator",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Return a string representation of the statistics",
"name": "__repr__",
"signature": "def __repr__(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_026497 | Implement the Python class `TopologyStatistics` described below.
Class description:
Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and ... | Implement the Python class `TopologyStatistics` described below.
Class description:
Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and ... | ea1ef4cba0b5bddf1b7bf858e53c32aeb859655d | <|skeleton|>
class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TopologyStatistics:
"""Topology Statistics Class - A class bean-like to store the statistics The statistics hold by this class are: **bestFitness, fitness** Best and current fitness scores of the best particle **position, bestPosition** current position and the best position of the best particle **bestPosDim*... | the_stack_v2_python_sparse | 0.12/FloatStatistics.py | ItaloAP/pypso | train | 0 |
545a882fa33cb259f7f4333de38b69f3a526abb0 | [
"if head is None:\n return None\nslow = head\nfast = head\nis_cycle = False\nwhile fast is not None and fast.next is not None:\n slow = slow.next\n fast = fast.next.next\n if slow == fast:\n is_cycle = True\n break\nif is_cycle:\n fast = head\n while fast != slow:\n fast = fas... | <|body_start_0|>
if head is None:
return None
slow = head
fast = head
is_cycle = False
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
is_cycle = True
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle2(self, head):
"""如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|>
<|body_start_... | stack_v2_sparse_classes_75kplus_train_073664 | 2,320 | no_license | [
{
"docstring": ":type head: ListNode :rtype: ListNode",
"name": "detectCycle",
"signature": "def detectCycle(self, head)"
},
{
"docstring": "如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。 :type head: ListNode :rtype: ListNode",
"name": "detectCycle2",
"signature": "def detectCycle2(self... | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle2(self, head): 如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。 :type head: ListNode :rtype: Li... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def detectCycle(self, head): :type head: ListNode :rtype: ListNode
- def detectCycle2(self, head): 如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。 :type head: ListNode :rtype: Li... | 3b13b36f37eb364410b3b5b4f10a1808d8b1111e | <|skeleton|>
class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
<|body_0|>
def detectCycle2(self, head):
"""如果我们用一个 Set 保存已经访问过的节点,我们可以遍历整个列表并返回第一个出现重复的节点。 :type head: ListNode :rtype: ListNode"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def detectCycle(self, head):
""":type head: ListNode :rtype: ListNode"""
if head is None:
return None
slow = head
fast = head
is_cycle = False
while fast is not None and fast.next is not None:
slow = slow.next
fast =... | the_stack_v2_python_sparse | leetcode/142.py | yanggelinux/algorithm-data-structure | train | 0 | |
d2d289db00d2d32425202d8bbe2d40191b8dfbbd | [
"self.headers = HttpResponse.__get_headers(http_response)\nself.status_code = HttpResponse.get_status_code(http_response)\nself.body = HttpResponse.__get_body(http_response)\nself.response = http_response",
"lines = http_response.split('\\n')\nstatus_code = 0\ninteresting_info = None\nfind_interesting_info = Fals... | <|body_start_0|>
self.headers = HttpResponse.__get_headers(http_response)
self.status_code = HttpResponse.get_status_code(http_response)
self.body = HttpResponse.__get_body(http_response)
self.response = http_response
<|end_body_0|>
<|body_start_1|>
lines = http_response.split('... | A simple class representing an HTTP reponse message. | HttpResponse | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HttpResponse:
"""A simple class representing an HTTP reponse message."""
def __init__(self, http_response):
"""Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode namedtuple obtained from the HTTP headers, 3) the HTTP bo... | stack_v2_sparse_classes_75kplus_train_073665 | 5,450 | permissive | [
{
"docstring": "Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode namedtuple obtained from the HTTP headers, 3) the HTTP body of the response, 4) the raw HTTP response as a string The first three attributes may be None if the http_response passed... | 5 | null | Implement the Python class `HttpResponse` described below.
Class description:
A simple class representing an HTTP reponse message.
Method signatures and docstrings:
- def __init__(self, http_response): Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode ... | Implement the Python class `HttpResponse` described below.
Class description:
A simple class representing an HTTP reponse message.
Method signatures and docstrings:
- def __init__(self, http_response): Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode ... | bb825fce99b12c0fba81500ba077143ed81617e2 | <|skeleton|>
class HttpResponse:
"""A simple class representing an HTTP reponse message."""
def __init__(self, http_response):
"""Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode namedtuple obtained from the HTTP headers, 3) the HTTP bo... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HttpResponse:
"""A simple class representing an HTTP reponse message."""
def __init__(self, http_response):
"""Initializes a new HttpResponse. An HttpResponse object contains: 1) the HTTP headers as a string, 2) the StatusCode namedtuple obtained from the HTTP headers, 3) the HTTP body of the res... | the_stack_v2_python_sparse | network/HttpResponse.py | devhid/kumo | train | 2 |
7c752932263eec14bed67847bc4f0a01f3e870f5 | [
"self._value = None\nsuper().__init__(*args, **kwds)\nif truth_values:\n self.truth_values = truth_values\nif false_values:\n self.false_values = false_values",
"try:\n logic_match(value, self.truth_values, self.false_values)\nexcept TypeError as err:\n self.status = err\n return False\nreturn True... | <|body_start_0|>
self._value = None
super().__init__(*args, **kwds)
if truth_values:
self.truth_values = truth_values
if false_values:
self.false_values = false_values
<|end_body_0|>
<|body_start_1|>
try:
logic_match(value, self.truth_values, ... | A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False | BoolV | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BoolV:
"""A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False"""
def __init__(self, *args, truth_values: Set[str]=None, false_values: Set[str]=Non... | stack_v2_sparse_classes_75kplus_train_073666 | 43,940 | no_license | [
{
"docstring": "Create a new instance of the bool CustomVariable.",
"name": "__init__",
"signature": "def __init__(self, *args, truth_values: Set[str]=None, false_values: Set[str]=None, **kwds)"
},
{
"docstring": "Check that value produces a valid boolean. If the value cannot be built into a val... | 5 | stack_v2_sparse_classes_30k_train_008094 | Implement the Python class `BoolV` described below.
Class description:
A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False
Method signatures and docstrings:
- def __init__(... | Implement the Python class `BoolV` described below.
Class description:
A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False
Method signatures and docstrings:
- def __init__(... | a6d3c24f066de2b7270a5ca674887fae071ed4c6 | <|skeleton|>
class BoolV:
"""A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False"""
def __init__(self, *args, truth_values: Set[str]=None, false_values: Set[str]=Non... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BoolV:
"""A True/False CustomVariable. BoolV can be customized to recognize additional true/false inputs: By default, it recognizes: 'YES', 'Y', 'TRUE', 'T', 1 as True 'NO', 'N', 'FALSE', 'F', 0, -1 as False"""
def __init__(self, *args, truth_values: Set[str]=None, false_values: Set[str]=None, **kwds):
... | the_stack_v2_python_sparse | CustomVariableSet/custom_variable_sets.py | GregSal/PyUtilities | train | 2 |
232677560b19ba62325207daf6e8b2025c4067af | [
"if self.user:\n self.render('newpost.html')\nelse:\n error_msg = 'You need to be logged in to author a post'\n self.render('base.html', error=error_msg)",
"if not self.user:\n return self.redirect('/login')\nsubject = self.request.get('subject')\ncontent = self.request.get('content')\nif subject and ... | <|body_start_0|>
if self.user:
self.render('newpost.html')
else:
error_msg = 'You need to be logged in to author a post'
self.render('base.html', error=error_msg)
<|end_body_0|>
<|body_start_1|>
if not self.user:
return self.redirect('/login')
... | NewPost | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NewPost:
def get(self):
"""If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message"""
<|body_0|>
def post(self):
"""If subject and content is present create the post in the database. Otherwise user sees the newpos... | stack_v2_sparse_classes_75kplus_train_073667 | 1,264 | no_license | [
{
"docstring": "If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "If subject and content is present create the post in the database. Otherwise user sees the newpost form w... | 2 | stack_v2_sparse_classes_30k_train_014707 | Implement the Python class `NewPost` described below.
Class description:
Implement the NewPost class.
Method signatures and docstrings:
- def get(self): If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message
- def post(self): If subject and content is present cre... | Implement the Python class `NewPost` described below.
Class description:
Implement the NewPost class.
Method signatures and docstrings:
- def get(self): If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message
- def post(self): If subject and content is present cre... | 1f5b6141e19f673dfb6b06f738c5a49a7d229244 | <|skeleton|>
class NewPost:
def get(self):
"""If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message"""
<|body_0|>
def post(self):
"""If subject and content is present create the post in the database. Otherwise user sees the newpos... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NewPost:
def get(self):
"""If the user is signed in, render newpost.html, otherwise pass users to the basetemplate with an error message"""
if self.user:
self.render('newpost.html')
else:
error_msg = 'You need to be logged in to author a post'
self.r... | the_stack_v2_python_sparse | handlers/newpost.py | StephenOrgan/multi-user-blog | train | 0 | |
2ebe5aacac4291b0e022cb3fc8ce4472a446212d | [
"mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=-0.02)\nstddevs = self._get_stddevs(stddev_types, 10 ** mean)\nmean = self._apply_amplification_factor(mean)\nreturn (mean, stddevs)",
"assert all((stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES for stddev_type in stddev_types))\nstd = n... | <|body_start_0|>
mean = self._get_mean(imt, rup.mag, rup.hypo_depth, dists.rrup, d=-0.02)
stddevs = self._get_stddevs(stddev_types, 10 ** mean)
mean = self._apply_amplification_factor(mean)
return (mean, stddevs)
<|end_body_0|>
<|body_start_1|>
assert all((stddev_type in self.DE... | Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements the equations for 'Subduction Interface' (that's ... | SiMidorikawa1999SInter | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SiMidorikawa1999SInter:
"""Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements... | stack_v2_sparse_classes_75kplus_train_073668 | 15,234 | permissive | [
{
"docstring": "Implements equation 3.5.1-1 page 148 for mean value and equation 3.5.5-1 page 151 for total standard deviation. See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values.",
"name": "get_mean_and_stddevs",
"signature": "def ... | 2 | stack_v2_sparse_classes_30k_train_010237 | Implement the Python class `SiMidorikawa1999SInter` described below.
Class description:
Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan... | Implement the Python class `SiMidorikawa1999SInter` described below.
Class description:
Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan... | 0da9ba5a575360081715e8b90c71d4b16c6687c8 | <|skeleton|>
class SiMidorikawa1999SInter:
"""Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SiMidorikawa1999SInter:
"""Implements GMPE developed by Hongjun Si and Saburoh Midorikawa (1999) as described in "Technical Reports on National Seismic Hazard Maps for Japan" (2009, National Research Institute for Earth Science and Disaster Prevention, Japan, pages 148-151). This class implements the equation... | the_stack_v2_python_sparse | openquake/hazardlib/gsim/si_midorikawa_1999.py | GFZ-Centre-for-Early-Warning/shakyground | train | 1 |
d2e54da7032252c739b65ca584e1a0cf49e51b4e | [
"thres = filters.threshold_otsu(img)\nimg = img > thres\nimg = numpy.invert(img)\nlower = img.shape\nupper = (-1, -1)\nfor x in range(img.shape[0]):\n for y in range(img.shape[1]):\n if not img[x, y]:\n continue\n lower = tuple(map(min, lower, (x, y)))\n upper = tuple(map(max, upp... | <|body_start_0|>
thres = filters.threshold_otsu(img)
img = img > thres
img = numpy.invert(img)
lower = img.shape
upper = (-1, -1)
for x in range(img.shape[0]):
for y in range(img.shape[1]):
if not img[x, y]:
continue
... | Class for preprocessing input data into NN-suitable format. | Preprocessor | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Preprocessor:
"""Class for preprocessing input data into NN-suitable format."""
def get_sample_data_array(cls, img, file_result=None):
"""Processes grayscale array image into binary array NN-suitable sample. Mirrors result to file `file_result` if specified."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus_train_073669 | 2,782 | no_license | [
{
"docstring": "Processes grayscale array image into binary array NN-suitable sample. Mirrors result to file `file_result` if specified.",
"name": "get_sample_data_array",
"signature": "def get_sample_data_array(cls, img, file_result=None)"
},
{
"docstring": "Loads and processes image from files... | 2 | null | Implement the Python class `Preprocessor` described below.
Class description:
Class for preprocessing input data into NN-suitable format.
Method signatures and docstrings:
- def get_sample_data_array(cls, img, file_result=None): Processes grayscale array image into binary array NN-suitable sample. Mirrors result to f... | Implement the Python class `Preprocessor` described below.
Class description:
Class for preprocessing input data into NN-suitable format.
Method signatures and docstrings:
- def get_sample_data_array(cls, img, file_result=None): Processes grayscale array image into binary array NN-suitable sample. Mirrors result to f... | 5a067c48b6a0ba3e4610ab83f82c15c02cd1cdd4 | <|skeleton|>
class Preprocessor:
"""Class for preprocessing input data into NN-suitable format."""
def get_sample_data_array(cls, img, file_result=None):
"""Processes grayscale array image into binary array NN-suitable sample. Mirrors result to file `file_result` if specified."""
<|body_0|>
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Preprocessor:
"""Class for preprocessing input data into NN-suitable format."""
def get_sample_data_array(cls, img, file_result=None):
"""Processes grayscale array image into binary array NN-suitable sample. Mirrors result to file `file_result` if specified."""
thres = filters.threshold_o... | the_stack_v2_python_sparse | app/imgprep/imgprep.py | TimurNurlygayanov/Project451 | train | 1 |
3cd197d1f57ce606da3bb93eedb670b56f14aba6 | [
"all_scans = scan_save_db.objects.all()\nserialized_scans = NetworkScanSerializer(all_scans, many=True)\nreturn Response(serialized_scans.data)",
"serializer = NetworkScanSerializer(data=request.data)\nif serializer.is_valid():\n target_ip = request.data.get('scan_ip')\n project_id = request.data.get('proje... | <|body_start_0|>
all_scans = scan_save_db.objects.all()
serialized_scans = NetworkScanSerializer(all_scans, many=True)
return Response(serialized_scans.data)
<|end_body_0|>
<|body_start_1|>
serializer = NetworkScanSerializer(data=request.data)
if serializer.is_valid():
... | Network Scan API call to perform scan. | NetworkScan | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class NetworkScan:
"""Network Scan API call to perform scan."""
def get(self, request, format=None, **kwargs):
"""Returns a list of all **Network Scans** in the system."""
<|body_0|>
def post(self, request, format=None, **kwargs):
"""Current user's identity endpoint.""... | stack_v2_sparse_classes_75kplus_train_073670 | 6,149 | permissive | [
{
"docstring": "Returns a list of all **Network Scans** in the system.",
"name": "get",
"signature": "def get(self, request, format=None, **kwargs)"
},
{
"docstring": "Current user's identity endpoint.",
"name": "post",
"signature": "def post(self, request, format=None, **kwargs)"
}
] | 2 | null | Implement the Python class `NetworkScan` described below.
Class description:
Network Scan API call to perform scan.
Method signatures and docstrings:
- def get(self, request, format=None, **kwargs): Returns a list of all **Network Scans** in the system.
- def post(self, request, format=None, **kwargs): Current user's... | Implement the Python class `NetworkScan` described below.
Class description:
Network Scan API call to perform scan.
Method signatures and docstrings:
- def get(self, request, format=None, **kwargs): Returns a list of all **Network Scans** in the system.
- def post(self, request, format=None, **kwargs): Current user's... | 6dc84957c76920ed3d133e75d61711a65af52007 | <|skeleton|>
class NetworkScan:
"""Network Scan API call to perform scan."""
def get(self, request, format=None, **kwargs):
"""Returns a list of all **Network Scans** in the system."""
<|body_0|>
def post(self, request, format=None, **kwargs):
"""Current user's identity endpoint.""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class NetworkScan:
"""Network Scan API call to perform scan."""
def get(self, request, format=None, **kwargs):
"""Returns a list of all **Network Scans** in the system."""
all_scans = scan_save_db.objects.all()
serialized_scans = NetworkScanSerializer(all_scans, many=True)
retur... | the_stack_v2_python_sparse | archeryapi/views.py | pabit/archerysec | train | 1 |
74769ddb370198b69f3b0b9aa950255f0798fd88 | [
"self._num_participants = num_participants\nself._counter = 0\nself._flag = False\nself._local_sense = threading.local()\nself._lock = threading.Lock()\nself._condition = threading.Condition()",
"self._local_sense.value = not self._flag\nwith self._lock:\n self._counter += 1\n if self._counter == self._num_... | <|body_start_0|>
self._num_participants = num_participants
self._counter = 0
self._flag = False
self._local_sense = threading.local()
self._lock = threading.Lock()
self._condition = threading.Condition()
<|end_body_0|>
<|body_start_1|>
self._local_sense.value = n... | A reusable barrier class for worker synchronization. | _Barrier | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus_train_073671 | 34,550 | permissive | [
{
"docstring": "Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier.",
"name": "__init__",
"signature": "def __init__(self, num_participants)"
},
{
"docstring": "Waits until all other callers reach the sa... | 2 | stack_v2_sparse_classes_30k_test_000750 | Implement the Python class `_Barrier` described below.
Class description:
A reusable barrier class for worker synchronization.
Method signatures and docstrings:
- def __init__(self, num_participants): Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pa... | Implement the Python class `_Barrier` described below.
Class description:
A reusable barrier class for worker synchronization.
Method signatures and docstrings:
- def __init__(self, num_participants): Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pa... | a7f3934a67900720af3d3b15389551483bee50b8 | <|skeleton|>
class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
<|body_0|>
de... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class _Barrier:
"""A reusable barrier class for worker synchronization."""
def __init__(self, num_participants):
"""Initializes the barrier object. Args: num_participants: an integer which is the expected number of calls of `wait` pass to through this barrier."""
self._num_participants = num_pa... | the_stack_v2_python_sparse | tensorflow/python/distribute/distribute_coordinator.py | tensorflow/tensorflow | train | 208,740 |
bd2d62b575ba83d7af450260d33ff328147a6911 | [
"self.param_format = param_format\nself.optional = optional\nself.mtype = mtype\nself.constant = constant\nself.is_array = is_array\nself.is_stream = is_stream\nself.is_attribute = is_attribute\nself.is_map = is_map\nself.attributes = attributes\nself.nullable = nullable\nself.id = id\nself.name = name\nself.descri... | <|body_start_0|>
self.param_format = param_format
self.optional = optional
self.mtype = mtype
self.constant = constant
self.is_array = is_array
self.is_stream = is_stream
self.is_attribute = is_attribute
self.is_map = is_map
self.attributes = attri... | Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description here. constant (bool): TODO: type description here. is_array (bool): TODO: type des... | ResponseWithEnum | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ResponseWithEnum:
"""Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description here. constant (bool): TODO: type descr... | stack_v2_sparse_classes_75kplus_train_073672 | 4,548 | permissive | [
{
"docstring": "Constructor for the ResponseWithEnum class",
"name": "__init__",
"signature": "def __init__(self, attributes=None, constant=None, description=None, id=None, is_array=None, is_attribute=None, is_map=None, is_stream=None, name=None, nullable=None, optional=None, param_format=None, mtype=No... | 2 | null | Implement the Python class `ResponseWithEnum` described below.
Class description:
Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description ... | Implement the Python class `ResponseWithEnum` described below.
Class description:
Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description ... | 49acc3d416a1dde7ea43b178d070484baf1b7f2b | <|skeleton|>
class ResponseWithEnum:
"""Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description here. constant (bool): TODO: type descr... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ResponseWithEnum:
"""Implementation of the 'response with Enum' model. TODO: type model description here. Attributes: param_format (ParamFormat): TODO: type description here. optional (bool): TODO: type description here. mtype (Type): TODO: type description here. constant (bool): TODO: type description here. ... | the_stack_v2_python_sparse | PYTHON_GENERIC_LIB/tester/models/response_with_enum.py | MaryamAdnan3/Tester1 | train | 0 |
559a330d0eb8e5b21e229671d4302fce6a33b9d0 | [
"try:\n return SendRequest(data)\nexcept Exception as error:\n raise",
"try:\n return SendRequest(data)\nexcept Exception as error:\n raise",
"try:\n return SendRequest(data)\nexcept Exception as error:\n raise"
] | <|body_start_0|>
try:
return SendRequest(data)
except Exception as error:
raise
<|end_body_0|>
<|body_start_1|>
try:
return SendRequest(data)
except Exception as error:
raise
<|end_body_1|>
<|body_start_2|>
try:
return... | HomeService | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class HomeService:
def home_site(cls, data):
"""获取站点信息 :return:"""
<|body_0|>
def home_warehouse(cls, data):
"""获取仓库信息 :return:"""
<|body_1|>
def home_menu(data):
"""获取主页菜单 :return:"""
<|body_2|>
<|end_skeleton|>
<|body_start_0|>
try:... | stack_v2_sparse_classes_75kplus_train_073673 | 750 | no_license | [
{
"docstring": "获取站点信息 :return:",
"name": "home_site",
"signature": "def home_site(cls, data)"
},
{
"docstring": "获取仓库信息 :return:",
"name": "home_warehouse",
"signature": "def home_warehouse(cls, data)"
},
{
"docstring": "获取主页菜单 :return:",
"name": "home_menu",
"signature"... | 3 | stack_v2_sparse_classes_30k_train_010730 | Implement the Python class `HomeService` described below.
Class description:
Implement the HomeService class.
Method signatures and docstrings:
- def home_site(cls, data): 获取站点信息 :return:
- def home_warehouse(cls, data): 获取仓库信息 :return:
- def home_menu(data): 获取主页菜单 :return: | Implement the Python class `HomeService` described below.
Class description:
Implement the HomeService class.
Method signatures and docstrings:
- def home_site(cls, data): 获取站点信息 :return:
- def home_warehouse(cls, data): 获取仓库信息 :return:
- def home_menu(data): 获取主页菜单 :return:
<|skeleton|>
class HomeService:
def ... | 9e7ef765643fe596c06764ce8597dad7747086f3 | <|skeleton|>
class HomeService:
def home_site(cls, data):
"""获取站点信息 :return:"""
<|body_0|>
def home_warehouse(cls, data):
"""获取仓库信息 :return:"""
<|body_1|>
def home_menu(data):
"""获取主页菜单 :return:"""
<|body_2|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class HomeService:
def home_site(cls, data):
"""获取站点信息 :return:"""
try:
return SendRequest(data)
except Exception as error:
raise
def home_warehouse(cls, data):
"""获取仓库信息 :return:"""
try:
return SendRequest(data)
except Excepti... | the_stack_v2_python_sparse | service/home.py | Xuemeizhong/API | train | 0 | |
d24410b51d52fc0801c4a5e82a343c499991e556 | [
"if not root:\n return ''\nret = []\n\ndef postSerialize(root):\n if not root:\n ret.append('# ')\n return\n ret.append(str(root.val) + ' ')\n postSerialize(root.left)\n postSerialize(root.right)\npostSerialize(root)\nreturn ''.join(ret)",
"if not data:\n return None\nsplitData = d... | <|body_start_0|>
if not root:
return ''
ret = []
def postSerialize(root):
if not root:
ret.append('# ')
return
ret.append(str(root.val) + ' ')
postSerialize(root.left)
postSerialize(root.right)
p... | 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_75kplus_train_073674 | 2,764 | 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_032435 | 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:... | af5b37e45c89028aad119b1bc2c684e26dafd6e0 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root):
"""Encodes a tree to a single string. :type root: TreeNode :rtype: str"""
if not root:
return ''
ret = []
def postSerialize(root):
if not root:
ret.append('# ')
return
ret.app... | the_stack_v2_python_sparse | BFS/449.py | LuluFighting/leetCodeEveryday | train | 2 | |
e22bc529b9e26fc88d294a44c3404195a8792069 | [
"self.component = component\nself.description = description\nself.gateway = gateway\nself.id = id\nself.ip = ip\nself.netmask_bits = netmask_bits\nself.netmask_ip_4 = netmask_ip_4\nself.nfs_access = nfs_access\nself.nfs_all_squash = nfs_all_squash\nself.nfs_root_squash = nfs_root_squash\nself.s3_access = s3_access\... | <|body_start_0|>
self.component = component
self.description = description
self.gateway = gateway
self.id = id
self.ip = ip
self.netmask_bits = netmask_bits
self.netmask_ip_4 = netmask_ip_4
self.nfs_access = nfs_access
self.nfs_all_squash = nfs_all... | Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for this subnet. ip (string): ip is subnet IP address giv... | ClusterConfigProto_Subnet | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for ... | stack_v2_sparse_classes_75kplus_train_073675 | 4,337 | permissive | [
{
"docstring": "Constructor for the ClusterConfigProto_Subnet class",
"name": "__init__",
"signature": "def __init__(self, component=None, description=None, gateway=None, id=None, ip=None, netmask_bits=None, netmask_ip_4=None, nfs_access=None, nfs_all_squash=None, nfs_root_squash=None, s3_access=None, s... | 2 | stack_v2_sparse_classes_30k_train_028627 | Implement the Python class `ClusterConfigProto_Subnet` described below.
Class description:
Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Ga... | Implement the Python class `ClusterConfigProto_Subnet` described below.
Class description:
Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Ga... | e4973dfeb836266904d0369ea845513c7acf261e | <|skeleton|>
class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ClusterConfigProto_Subnet:
"""Implementation of the 'ClusterConfigProto_Subnet' model. TODO: type description here. Attributes: component (int): The component that has claimed this subnet. description (string): Description of the subnet. gateway (string): Gateway for the subnet. id (int): ID for this subnet. ... | the_stack_v2_python_sparse | cohesity_management_sdk/models/cluster_config_proto_subnet.py | cohesity/management-sdk-python | train | 24 |
fbe5e4c0490096e7fcd11f70c345f03dc8c228e7 | [
"start_date = (datetime.datetime.now() - datetime.timedelta(days=365)).strftime(FORMAT_DATE)\nend_date = datetime.datetime.now().strftime(FORMAT_DATE)\nself.render('visualize.html', page_title='Visualize', default_start_date=start_date, default_end_date=end_date)",
"query_type = self.get_argument('data-type', Non... | <|body_start_0|>
start_date = (datetime.datetime.now() - datetime.timedelta(days=365)).strftime(FORMAT_DATE)
end_date = datetime.datetime.now().strftime(FORMAT_DATE)
self.render('visualize.html', page_title='Visualize', default_start_date=start_date, default_end_date=end_date)
<|end_body_0|>
<|... | Request handler caring about visualization of rubberband data. | VisualizeView | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class VisualizeView:
"""Request handler caring about visualization of rubberband data."""
def get(self):
"""Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`."""
<|body_0|>
def post(self):
"""Answer t... | stack_v2_sparse_classes_75kplus_train_073676 | 3,395 | permissive | [
{
"docstring": "Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`.",
"name": "get",
"signature": "def get(self)"
},
{
"docstring": "Answer to POST requests. AJAX endpoint from frontend. Invoked after the user clicked on 'submit... | 2 | null | Implement the Python class `VisualizeView` described below.
Class description:
Request handler caring about visualization of rubberband data.
Method signatures and docstrings:
- def get(self): Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`.
- def... | Implement the Python class `VisualizeView` described below.
Class description:
Request handler caring about visualization of rubberband data.
Method signatures and docstrings:
- def get(self): Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`.
- def... | 44bdbe3a397b51a817540b389e79446046e12e90 | <|skeleton|>
class VisualizeView:
"""Request handler caring about visualization of rubberband data."""
def get(self):
"""Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`."""
<|body_0|>
def post(self):
"""Answer t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class VisualizeView:
"""Request handler caring about visualization of rubberband data."""
def get(self):
"""Answer to GET requests. Show the form for the user to enter data that they want to visualize. Renders `visualize.html`."""
start_date = (datetime.datetime.now() - datetime.timedelta(days=... | the_stack_v2_python_sparse | rubberband/handlers/fe/visualize.py | ambros-gleixner/rubberband | train | 4 |
98d9df822fd3b722acdb5e2e0c3f3ee0915146f9 | [
"super().__init__()\nlayers = []\nfor i in range(len(divisors) - 1):\n in_ch = in_channels if i == 0 else hidden_channels // divisors[i - 1]\n out_ch = hidden_channels // divisors[i]\n stride = strides[i]\n layers.append((in_ch, out_ch, stride))\nlayers.append((hidden_channels // divisors[-1], 1, stride... | <|body_start_0|>
super().__init__()
layers = []
for i in range(len(divisors) - 1):
in_ch = in_channels if i == 0 else hidden_channels // divisors[i - 1]
out_ch = hidden_channels // divisors[i]
stride = strides[i]
layers.append((in_ch, out_ch, strid... | BaseFrequenceDiscriminator | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BaseFrequenceDiscriminator:
def __init__(self, in_channels, hidden_channels=512, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
"""Args: in_channels (int): Number of input channels. hidden_channels (int, optional): Number of channels in hidden layers. Defaults to 512. ... | stack_v2_sparse_classes_75kplus_train_073677 | 35,285 | permissive | [
{
"docstring": "Args: in_channels (int): Number of input channels. hidden_channels (int, optional): Number of channels in hidden layers. Defaults to 512. divisors (List[int], optional): List of divisors for the number of channels in each layer. The length of the list determines the number of layers. Defaults to... | 2 | null | Implement the Python class `BaseFrequenceDiscriminator` described below.
Class description:
Implement the BaseFrequenceDiscriminator class.
Method signatures and docstrings:
- def __init__(self, in_channels, hidden_channels=512, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]): Args: in_channels (int)... | Implement the Python class `BaseFrequenceDiscriminator` described below.
Class description:
Implement the BaseFrequenceDiscriminator class.
Method signatures and docstrings:
- def __init__(self, in_channels, hidden_channels=512, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]): Args: in_channels (int)... | bcd20948db7846ee523443ef9fd78c7a1248c95e | <|skeleton|>
class BaseFrequenceDiscriminator:
def __init__(self, in_channels, hidden_channels=512, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
"""Args: in_channels (int): Number of input channels. hidden_channels (int, optional): Number of channels in hidden layers. Defaults to 512. ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BaseFrequenceDiscriminator:
def __init__(self, in_channels, hidden_channels=512, divisors=[32, 16, 8, 4, 2, 1, 1], strides=[1, 2, 1, 2, 1, 2, 1]):
"""Args: in_channels (int): Number of input channels. hidden_channels (int, optional): Number of channels in hidden layers. Defaults to 512. divisors (List... | the_stack_v2_python_sparse | espnet2/gan_svs/visinger2/visinger2_vocoder.py | espnet/espnet | train | 7,242 | |
bf7705923713dd5348732ff520f97f8a79919311 | [
"if graph.is_directed():\n raise ValueError('the graph is directed')\nself.graph = graph\nfor edge in self.graph.iteredges():\n if edge.source == edge.target:\n raise ValueError('a loop detected')\nself.independent_set = set()\nself.cardinality = 0\nself.source = None",
"used = dict(((node, False) fo... | <|body_start_0|>
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target:
raise ValueError('a loop detected')
self.independent_set = set()
self.c... | Find a maximal independent set. | SmallestFirstIndependentSet5 | [
"BSD-3-Clause"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class SmallestFirstIndependentSet5:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
i... | stack_v2_sparse_classes_75kplus_train_073678 | 13,747 | permissive | [
{
"docstring": "The algorithm initialization.",
"name": "__init__",
"signature": "def __init__(self, graph)"
},
{
"docstring": "Executable pseudocode.",
"name": "run",
"signature": "def run(self, source=None)"
}
] | 2 | null | Implement the Python class `SmallestFirstIndependentSet5` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode. | Implement the Python class `SmallestFirstIndependentSet5` described below.
Class description:
Find a maximal independent set.
Method signatures and docstrings:
- def __init__(self, graph): The algorithm initialization.
- def run(self, source=None): Executable pseudocode.
<|skeleton|>
class SmallestFirstIndependentSe... | 0ff4ae303e8824e6bb8474d23b29a7b3e5ed8e60 | <|skeleton|>
class SmallestFirstIndependentSet5:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
<|body_0|>
def run(self, source=None):
"""Executable pseudocode."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class SmallestFirstIndependentSet5:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError('the graph is directed')
self.graph = graph
for edge in self.graph.iteredges():
... | the_stack_v2_python_sparse | graphtheory/independentsets/isetsf.py | kgashok/graphs-dict | train | 0 |
4800874ab142b35f943e2b66ad5316d04ca55b49 | [
"if user_index >= self.num_users or following_index >= self.num_users:\n raise ValueError('Number of users is %d, but indices %d and %d' + ' were requested' % (self.num_users, user_index, following_index))\nif self.user_profiles[following_index, user_index] == 0:\n self.user_profiles[following_index, user_ind... | <|body_start_0|>
if user_index >= self.num_users or following_index >= self.num_users:
raise ValueError('Number of users is %d, but indices %d and %d' + ' were requested' % (self.num_users, user_index, following_index))
if self.user_profiles[following_index, user_index] == 0:
sel... | A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`. | BinarySocialGraph | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_75kplus_train_073679 | 4,979 | permissive | [
{
"docstring": "Method to follow another user -- that is, to create a unidirectional link from one user to the other. Parameters ---------- user_index: int Index of the user initiating the follow. following_index: int Index of the user to be followed. Raises ------ ValueError If either of the user indices does ... | 4 | stack_v2_sparse_classes_30k_train_054505 | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and... | Implement the Python class `BinarySocialGraph` described below.
Class description:
A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`.
Method signatures and... | 21f9861f203df6857e951b060869d97e6027f15a | <|skeleton|>
class BinarySocialGraph:
"""A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class BinarySocialGraph:
"""A mixin for classes with a :attr:`~rec.models.recommender.BaseRecommender.user_profiles` attribute to gain the basic functionality of a binary social graph. It assumes a network adjacency matrix of size `|U|x|U|`."""
def follow(self, user_index, following_index):
"""Method t... | the_stack_v2_python_sparse | rec/components/socialgraph.py | zputech/t-recs | train | 0 |
0eb3423f2f00ffed3d61433f4323e621f4ddc6e0 | [
"super(Plato2, self).__init__()\nargs = self.setup_args()\nif args.num_layers == 24:\n n_head = 16\n hidden_size = 1024\nelif args.num_layers == 32:\n n_head = 32\n hidden_size = 2048\nelse:\n raise ValueError('The pre-trained model only support 24 or 32 layers, but received num_layers=%d.' % args.nu... | <|body_start_0|>
super(Plato2, self).__init__()
args = self.setup_args()
if args.num_layers == 24:
n_head = 16
hidden_size = 1024
elif args.num_layers == 32:
n_head = 32
hidden_size = 2048
else:
raise ValueError('The pre... | Plato2 | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Plato2:
def __init__(self):
"""initialize with the necessary elements"""
<|body_0|>
def setup_args(self):
"""Setup arguments."""
<|body_1|>
def generate(self, texts):
"""Get the robot responses of the input texts. Args: texts(list or str): If not... | stack_v2_sparse_classes_75kplus_train_073680 | 6,991 | permissive | [
{
"docstring": "initialize with the necessary elements",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Setup arguments.",
"name": "setup_args",
"signature": "def setup_args(self)"
},
{
"docstring": "Get the robot responses of the input texts. Args: text... | 5 | stack_v2_sparse_classes_30k_train_048971 | Implement the Python class `Plato2` described below.
Class description:
Implement the Plato2 class.
Method signatures and docstrings:
- def __init__(self): initialize with the necessary elements
- def setup_args(self): Setup arguments.
- def generate(self, texts): Get the robot responses of the input texts. Args: tex... | Implement the Python class `Plato2` described below.
Class description:
Implement the Plato2 class.
Method signatures and docstrings:
- def __init__(self): initialize with the necessary elements
- def setup_args(self): Setup arguments.
- def generate(self, texts): Get the robot responses of the input texts. Args: tex... | b402610a6f0b382a978e82473b541ea1fc6cf09a | <|skeleton|>
class Plato2:
def __init__(self):
"""initialize with the necessary elements"""
<|body_0|>
def setup_args(self):
"""Setup arguments."""
<|body_1|>
def generate(self, texts):
"""Get the robot responses of the input texts. Args: texts(list or str): If not... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Plato2:
def __init__(self):
"""initialize with the necessary elements"""
super(Plato2, self).__init__()
args = self.setup_args()
if args.num_layers == 24:
n_head = 16
hidden_size = 1024
elif args.num_layers == 32:
n_head = 32
... | the_stack_v2_python_sparse | modules/text/text_generation/plato2_en_large/module.py | PaddlePaddle/PaddleHub | train | 12,914 | |
748fb9809f78fc8eac9e2b45c3711fdce7bdbe3f | [
"Base.__init__(self, target, opts)\nself.host, self.port, self.scheme, self.path = self._parse_url(self.target)\nreturn",
"url = self.target\nif self.opts['attack_url']:\n url = self.opts['attack_url']\nif self.opts['login_url']:\n url = self.opts['login_url']\nwith timeout(self.opts['timeout']):\n self.... | <|body_start_0|>
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
<|end_body_0|>
<|body_start_1|>
url = self.target
if self.opts['attack_url']:
url = self.opts['attack_url']
if self.opts['log... | Login Cracker module | Crack | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Crack:
"""Login Cracker module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def crack_http_auth_web(self):
"""DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3"""
<|body_1|>
def crack_tomcat_web(self... | stack_v2_sparse_classes_75kplus_train_073681 | 3,279 | no_license | [
{
"docstring": "init",
"name": "__init__",
"signature": "def __init__(self, target, opts)"
},
{
"docstring": "DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3",
"name": "crack_http_auth_web",
"signature": "def crack_http_auth_web(self)"
},
{
... | 4 | stack_v2_sparse_classes_30k_test_001828 | Implement the Python class `Crack` described below.
Class description:
Login Cracker module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def crack_http_auth_web(self): DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3
- def crack_tomcat_web(self): D... | Implement the Python class `Crack` described below.
Class description:
Login Cracker module
Method signatures and docstrings:
- def __init__(self, target, opts): init
- def crack_http_auth_web(self): DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3
- def crack_tomcat_web(self): D... | ddc052c8d7d43a60fc00ea40d85111d5bd7a282e | <|skeleton|>
class Crack:
"""Login Cracker module"""
def __init__(self, target, opts):
"""init"""
<|body_0|>
def crack_http_auth_web(self):
"""DESCR: Check HTTP auth type (basic, realm, etc.) and crack login. (int) TOOLS: python3"""
<|body_1|>
def crack_tomcat_web(self... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Crack:
"""Login Cracker module"""
def __init__(self, target, opts):
"""init"""
Base.__init__(self, target, opts)
self.host, self.port, self.scheme, self.path = self._parse_url(self.target)
return
def crack_http_auth_web(self):
"""DESCR: Check HTTP auth type (b... | the_stack_v2_python_sparse | src/modules/web/crack.py | noptrix/nullscan | train | 52 |
805bfbf43cf1efe8510ae0c42617b37696836059 | [
"for _, dirty in self.file_list:\n subprocess.call(['../mat-cli', dirty])\n current_file = mat.create_class_file(dirty, False, True)\n self.assertTrue(current_file.is_clean())",
"for clean, _ in self.file_list:\n subprocess.call(['../mat-cli', clean])\n current_file = mat.create_class_file(clean, F... | <|body_start_0|>
for _, dirty in self.file_list:
subprocess.call(['../mat-cli', dirty])
current_file = mat.create_class_file(dirty, False, True)
self.assertTrue(current_file.is_clean())
<|end_body_0|>
<|body_start_1|>
for clean, _ in self.file_list:
subpr... | test if cli correctly remove metadatas | TestRemovecli | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class TestRemovecli:
"""test if cli correctly remove metadatas"""
def test_remove(self):
"""make sure that the cli remove all compromizing meta"""
<|body_0|>
def test_remove_empty(self):
"""Test removal with clean files"""
<|body_1|>
<|end_skeleton|>
<|body_s... | stack_v2_sparse_classes_75kplus_train_073682 | 2,739 | no_license | [
{
"docstring": "make sure that the cli remove all compromizing meta",
"name": "test_remove",
"signature": "def test_remove(self)"
},
{
"docstring": "Test removal with clean files",
"name": "test_remove_empty",
"signature": "def test_remove_empty(self)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020078 | Implement the Python class `TestRemovecli` described below.
Class description:
test if cli correctly remove metadatas
Method signatures and docstrings:
- def test_remove(self): make sure that the cli remove all compromizing meta
- def test_remove_empty(self): Test removal with clean files | Implement the Python class `TestRemovecli` described below.
Class description:
test if cli correctly remove metadatas
Method signatures and docstrings:
- def test_remove(self): make sure that the cli remove all compromizing meta
- def test_remove_empty(self): Test removal with clean files
<|skeleton|>
class TestRemo... | e67b23fc4eb3e50b722a28336f93163946912bac | <|skeleton|>
class TestRemovecli:
"""test if cli correctly remove metadatas"""
def test_remove(self):
"""make sure that the cli remove all compromizing meta"""
<|body_0|>
def test_remove_empty(self):
"""Test removal with clean files"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class TestRemovecli:
"""test if cli correctly remove metadatas"""
def test_remove(self):
"""make sure that the cli remove all compromizing meta"""
for _, dirty in self.file_list:
subprocess.call(['../mat-cli', dirty])
current_file = mat.create_class_file(dirty, False, Tr... | the_stack_v2_python_sparse | data/python/46.py | devsagul/HanabiHack | train | 0 |
8439bd1a2efe41983eb70c316aae4b7cad13718a | [
"queue = []\nlevel = 0\nqueueFront = queueBack = 0\nif root:\n queue.append(root)\n queueFront += 1\n level += 1\nwhile queueBack < queueFront:\n increase = 0\n while queueBack < queueFront:\n node = queue[queueBack]\n queueBack += 1\n if node.left:\n queue.append(node... | <|body_start_0|>
queue = []
level = 0
queueFront = queueBack = 0
if root:
queue.append(root)
queueFront += 1
level += 1
while queueBack < queueFront:
increase = 0
while queueBack < queueFront:
node = queu... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
queue = []
level = 0
queueFront = qu... | stack_v2_sparse_classes_75kplus_train_073683 | 1,203 | permissive | [
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth",
"signature": "def maxDepth(self, root)"
},
{
"docstring": ":type root: TreeNode :rtype: int",
"name": "maxDepth2",
"signature": "def maxDepth2(self, root)"
}
] | 2 | null | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth2(self, root): :type root: TreeNode :rtype: int | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def maxDepth(self, root): :type root: TreeNode :rtype: int
- def maxDepth2(self, root): :type root: TreeNode :rtype: int
<|skeleton|>
class Solution:
def maxDepth(self, roo... | c8bf33af30569177c5276ffcd72a8d93ba4c402a | <|skeleton|>
class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
<|body_0|>
def maxDepth2(self, root):
""":type root: TreeNode :rtype: int"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def maxDepth(self, root):
""":type root: TreeNode :rtype: int"""
queue = []
level = 0
queueFront = queueBack = 0
if root:
queue.append(root)
queueFront += 1
level += 1
while queueBack < queueFront:
increa... | the_stack_v2_python_sparse | 101-200/101-110/104-maxDepthOfBST/maxDepthOfBST-inLevel.py | xuychen/Leetcode | train | 0 | |
d9e619d937e124b73bc3f3704d20d94d20045839 | [
"super(RNNEncoder, self).__init__()\nself.batch = batch\nself.units = units\nself.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)\nself.gru = tf.keras.layers.GRU(units=self.units, recurrent_initializer='glorot_uniform', return_sequences=True, return_state=True)",
"shape = (self.batch,... | <|body_start_0|>
super(RNNEncoder, self).__init__()
self.batch = batch
self.units = units
self.embedding = tf.keras.layers.Embedding(input_dim=vocab, output_dim=embedding)
self.gru = tf.keras.layers.GRU(units=self.units, recurrent_initializer='glorot_uniform', return_sequences=Tr... | Class RNNEncoder | RNNEncoder | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector uni... | stack_v2_sparse_classes_75kplus_train_073684 | 3,356 | permissive | [
{
"docstring": "Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an integer representing the number of hidden units in the RNN cell batch is an integer represent... | 3 | stack_v2_sparse_classes_30k_train_017507 | Implement the Python class `RNNEncoder` described below.
Class description:
Class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer re... | Implement the Python class `RNNEncoder` described below.
Class description:
Class RNNEncoder
Method signatures and docstrings:
- def __init__(self, vocab, embedding, units, batch): Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer re... | eaf23423ec0f412f103f5931d6610fdd67bcc5be | <|skeleton|>
class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector uni... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class RNNEncoder:
"""Class RNNEncoder"""
def __init__(self, vocab, embedding, units, batch):
"""Constructor for Class RNNEncoder Parameters: vocab is an integer representing the size of the input vocabulary embedding is an integer representing the dimensionality of the embedding vector units is an inte... | the_stack_v2_python_sparse | supervised_learning/0x11-attention/0-rnn_encoder.py | ledbagholberton/holbertonschool-machine_learning | train | 1 |
51c5d020c2d28dcfe088718474fb2bc9c8a1c7ac | [
"if not spread:\n id_maps = PipelineTemplate.objects.unfold_subprocess(exec_data)\nelse:\n id_maps = PipelineTemplate.objects.replace_id(exec_data)\ninputs = inputs or {}\nfor key, val in list(inputs.items()):\n if key in exec_data['data']['inputs']:\n exec_data['data']['inputs'][key]['value'] = val... | <|body_start_0|>
if not spread:
id_maps = PipelineTemplate.objects.unfold_subprocess(exec_data)
else:
id_maps = PipelineTemplate.objects.replace_id(exec_data)
inputs = inputs or {}
for key, val in list(inputs.items()):
if key in exec_data['data']['inpu... | InstanceManager | [
"MIT",
"LGPL-2.1-or-later",
"LGPL-3.0-only"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InstanceManager:
def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs):
"""创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_data 是否已经展开 @param kwargs: 其他参数 @param inputs: 自定义输入 @return: 实例对象"""
<|body_0|>
def delete_m... | stack_v2_sparse_classes_75kplus_train_073685 | 28,914 | permissive | [
{
"docstring": "创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_data 是否已经展开 @param kwargs: 其他参数 @param inputs: 自定义输入 @return: 实例对象",
"name": "create_instance",
"signature": "def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs)"
},
{
"do... | 5 | stack_v2_sparse_classes_30k_train_028721 | Implement the Python class `InstanceManager` described below.
Class description:
Implement the InstanceManager class.
Method signatures and docstrings:
- def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs): 创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_da... | Implement the Python class `InstanceManager` described below.
Class description:
Implement the InstanceManager class.
Method signatures and docstrings:
- def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs): 创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_da... | 2d708bd0d869d391456e0fb8d644af3b9f031acf | <|skeleton|>
class InstanceManager:
def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs):
"""创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_data 是否已经展开 @param kwargs: 其他参数 @param inputs: 自定义输入 @return: 实例对象"""
<|body_0|>
def delete_m... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InstanceManager:
def create_instance(self, template, exec_data, spread=False, inputs=None, **kwargs):
"""创建流程实例对象 @param template: 流程模板 @param exec_data: 执行用流程数据 @param spread: exec_data 是否已经展开 @param kwargs: 其他参数 @param inputs: 自定义输入 @return: 实例对象"""
if not spread:
id_maps = Pipel... | the_stack_v2_python_sparse | pipeline/models.py | TencentBlueKing/bk-itsm | train | 100 | |
d7d574cfedebdc55b5c0059f62bf0aa2b3f973fd | [
"output = []\ntemp = []\nfor i in range(1, n):\n temp.append(i)\n for j in range(i + 1, n + 1):\n temp.append(j)\n for k in range(j + 1, n + 1):\n temp.append(k)\n output.append(temp[:])\n temp.pop()\n temp.pop()\n temp.pop()\nreturn output",
"output ... | <|body_start_0|>
output = []
temp = []
for i in range(1, n):
temp.append(i)
for j in range(i + 1, n + 1):
temp.append(j)
for k in range(j + 1, n + 1):
temp.append(k)
output.append(temp[:])
... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def combination(self, n):
"""Example of how to arrange combinations of 3 with numbers 1 -> n"""
<|body_0|>
def combine(self, n, k):
"""Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase ... | stack_v2_sparse_classes_75kplus_train_073686 | 1,918 | no_license | [
{
"docstring": "Example of how to arrange combinations of 3 with numbers 1 -> n",
"name": "combination",
"signature": "def combination(self, n)"
},
{
"docstring": "Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase last slot ... | 3 | stack_v2_sparse_classes_30k_train_028947 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combination(self, n): Example of how to arrange combinations of 3 with numbers 1 -> n
- def combine(self, n, k): Creates all combos of size k using numbers 1 -> n. Does so by... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def combination(self, n): Example of how to arrange combinations of 3 with numbers 1 -> n
- def combine(self, n, k): Creates all combos of size k using numbers 1 -> n. Does so by... | f33d004d7629d46fbc5670f5b384f8a604d7f1e7 | <|skeleton|>
class Solution:
def combination(self, n):
"""Example of how to arrange combinations of 3 with numbers 1 -> n"""
<|body_0|>
def combine(self, n, k):
"""Creates all combos of size k using numbers 1 -> n. Does so by starting with lowest possible values in each slot. Increase ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def combination(self, n):
"""Example of how to arrange combinations of 3 with numbers 1 -> n"""
output = []
temp = []
for i in range(1, n):
temp.append(i)
for j in range(i + 1, n + 1):
temp.append(j)
for k in ran... | the_stack_v2_python_sparse | Combinations.py | aulee888/LeetCode | train | 0 | |
52f1b378cbd7dfbd7193e3a857c9f2e218a079b0 | [
"\"\"\"写法一\n request_list = []\n for page in range(1, 489):\n request = scrapy.Request(\n url=self.base_url.format(page)\n )\n request_list.append(request)\n return request_list\n \"\"\"\n'写法二'\nfor page in range(1, 489):\n yield scrapy.... | <|body_start_0|>
"""写法一
request_list = []
for page in range(1, 489):
request = scrapy.Request(
url=self.base_url.format(page)
)
request_list.append(request)
return request_list
... | ZhaopinSpider | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ZhaopinSpider:
def start_requests(self):
"""引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:"""
<|body_0|>
def parse(self, response):
"""获取响应, 触发解析函数, 提取数据, 提取URL :param response: 下载==>中央引擎==>爬虫 的response对象 :return: 数据 URL"""
<|body_1|>
<|end_skeleton|>
<|body_start_0... | stack_v2_sparse_classes_75kplus_train_073687 | 2,020 | no_license | [
{
"docstring": "引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:",
"name": "start_requests",
"signature": "def start_requests(self)"
},
{
"docstring": "获取响应, 触发解析函数, 提取数据, 提取URL :param response: 下载==>中央引擎==>爬虫 的response对象 :return: 数据 URL",
"name": "parse",
"signature": "def parse(self, response)"
... | 2 | stack_v2_sparse_classes_30k_train_048174 | Implement the Python class `ZhaopinSpider` described below.
Class description:
Implement the ZhaopinSpider class.
Method signatures and docstrings:
- def start_requests(self): 引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:
- def parse(self, response): 获取响应, 触发解析函数, 提取数据, 提取URL :param response: 下载==>中央引擎==>爬虫 的response对象 :retu... | Implement the Python class `ZhaopinSpider` described below.
Class description:
Implement the ZhaopinSpider class.
Method signatures and docstrings:
- def start_requests(self): 引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:
- def parse(self, response): 获取响应, 触发解析函数, 提取数据, 提取URL :param response: 下载==>中央引擎==>爬虫 的response对象 :retu... | 2028638f43172ff2902aa571ad80a30f4cd9737f | <|skeleton|>
class ZhaopinSpider:
def start_requests(self):
"""引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:"""
<|body_0|>
def parse(self, response):
"""获取响应, 触发解析函数, 提取数据, 提取URL :param response: 下载==>中央引擎==>爬虫 的response对象 :return: 数据 URL"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ZhaopinSpider:
def start_requests(self):
"""引擎会自动回调这个方法, 提供给引擎首次请求的URL列表 :return:"""
"""写法一
request_list = []
for page in range(1, 489):
request = scrapy.Request(
url=self.base_url.format(page)
)
... | the_stack_v2_python_sparse | tencent/tencent/spiders/zhaopin_3.py | Pysuper/ScrapyProject | train | 0 | |
483ec10c10cf8d112d187631ee2351c56e42091c | [
"raw_data = ''\nfor item_file_dir in os.listdir(file_dir):\n with open(file_dir + item_file_dir, 'rb') as r:\n item_data = r.read()\n try:\n item_data = item_data.decode('utf-8')\n raw_data += item_data + ' '\n except:\n item_data = item_data.decode('gbk', 'ignore')\n raw... | <|body_start_0|>
raw_data = ''
for item_file_dir in os.listdir(file_dir):
with open(file_dir + item_file_dir, 'rb') as r:
item_data = r.read()
try:
item_data = item_data.decode('utf-8')
raw_data += item_data + ' '
except... | word_index_generator | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class word_index_generator:
def __init__(self, file_dir, model_dir):
"""Read txt file - Arguments - file: str The address"""
<|body_0|>
def save_word_index(self, word, word_index, index_word):
"""Save the data to file"""
<|body_1|>
def word_index(self):
... | stack_v2_sparse_classes_75kplus_train_073688 | 3,659 | no_license | [
{
"docstring": "Read txt file - Arguments - file: str The address",
"name": "__init__",
"signature": "def __init__(self, file_dir, model_dir)"
},
{
"docstring": "Save the data to file",
"name": "save_word_index",
"signature": "def save_word_index(self, word, word_index, index_word)"
},... | 3 | stack_v2_sparse_classes_30k_train_038671 | Implement the Python class `word_index_generator` described below.
Class description:
Implement the word_index_generator class.
Method signatures and docstrings:
- def __init__(self, file_dir, model_dir): Read txt file - Arguments - file: str The address
- def save_word_index(self, word, word_index, index_word): Save... | Implement the Python class `word_index_generator` described below.
Class description:
Implement the word_index_generator class.
Method signatures and docstrings:
- def __init__(self, file_dir, model_dir): Read txt file - Arguments - file: str The address
- def save_word_index(self, word, word_index, index_word): Save... | ec593a62b0a0dbad73de182947e615482f2b6d93 | <|skeleton|>
class word_index_generator:
def __init__(self, file_dir, model_dir):
"""Read txt file - Arguments - file: str The address"""
<|body_0|>
def save_word_index(self, word, word_index, index_word):
"""Save the data to file"""
<|body_1|>
def word_index(self):
... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class word_index_generator:
def __init__(self, file_dir, model_dir):
"""Read txt file - Arguments - file: str The address"""
raw_data = ''
for item_file_dir in os.listdir(file_dir):
with open(file_dir + item_file_dir, 'rb') as r:
item_data = r.read()
t... | the_stack_v2_python_sparse | 【Test】seq2seq/lib/index_word/util.py | zhang23/Laboratory | train | 0 | |
83da63cbc2b338914975f7bf6007038bf1c33364 | [
"dev = data_utils.Subset(dataset, range(len(dataset) * 2 // 10))\ntrain = data_utils.Subset(dataset, range(0, len(dataset) * 9 // 10))\ntest = data_utils.Subset(dataset, range(len(dataset) * 9 // 10 + 1, len(dataset)))\nreturn DataSets(dev=dev, train=train, test=test)",
"split = self.split(dataset)\ndev = data_ut... | <|body_start_0|>
dev = data_utils.Subset(dataset, range(len(dataset) * 2 // 10))
train = data_utils.Subset(dataset, range(0, len(dataset) * 9 // 10))
test = data_utils.Subset(dataset, range(len(dataset) * 9 // 10 + 1, len(dataset)))
return DataSets(dev=dev, train=train, test=test)
<|end_... | Splitter | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Splitter:
def split(self, dataset):
"""Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)"""
<|body_0|>
def loaders(self, dataset, **kwargs):
"""Returns a named tuple of loaders :param kw... | stack_v2_sparse_classes_75kplus_train_073689 | 6,927 | no_license | [
{
"docstring": "Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)",
"name": "split",
"signature": "def split(self, dataset)"
},
{
"docstring": "Returns a named tuple of loaders :param kwargs: same as kwargs for torc... | 2 | stack_v2_sparse_classes_30k_train_015389 | Implement the Python class `Splitter` described below.
Class description:
Implement the Splitter class.
Method signatures and docstrings:
- def split(self, dataset): Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)
- def loaders(self, d... | Implement the Python class `Splitter` described below.
Class description:
Implement the Splitter class.
Method signatures and docstrings:
- def split(self, dataset): Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)
- def loaders(self, d... | a25dd45924495c4dd42fac29c19f6bfe158b6b7f | <|skeleton|>
class Splitter:
def split(self, dataset):
"""Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)"""
<|body_0|>
def loaders(self, dataset, **kwargs):
"""Returns a named tuple of loaders :param kw... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Splitter:
def split(self, dataset):
"""Splits the dataset into dev, train and test :param dataset: the dataset to split :return: DataSets named tupple (dev, train, test)"""
dev = data_utils.Subset(dataset, range(len(dataset) * 2 // 10))
train = data_utils.Subset(dataset, range(0, len(d... | the_stack_v2_python_sparse | mentalitystorm/data.py | DuaneNielsen/mentalitystorm | train | 0 | |
8579647412db756d913232c07cbeb86cc8d2fcd6 | [
"self.u0 = u0.copy()\nself.t0 = 0.0\nself.h = h\nself.dt_max = dt_max\nself.lbnd = lbnd\nself.ubnd = ubnd\nself.f = np.frompyfunc(f, 1, 1)\nself.g = g\nself.cfl = cfl\nself.eps = eps",
"h = self.h\nlbnd = self.lbnd\nubnd = self.ubnd\nf = self.f\ng = self.g\nEPS = self.eps\nt = np.full(n_itr, self.t0)\nu = np.zero... | <|body_start_0|>
self.u0 = u0.copy()
self.t0 = 0.0
self.h = h
self.dt_max = dt_max
self.lbnd = lbnd
self.ubnd = ubnd
self.f = np.frompyfunc(f, 1, 1)
self.g = g
self.cfl = cfl
self.eps = eps
<|end_body_0|>
<|body_start_1|>
h = self.... | 非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max : float 時間刻み幅の最大値.実際の刻み幅は CFL 条件によってこの値超えない範囲で定まる.拡散項による誤差が大きい場合この値で時間刻みを制御すると良い. lbnd :... | AdvectionDiffusion1d | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AdvectionDiffusion1d:
"""非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max : float 時間刻み幅の最大値.実際の刻み幅は CFL 条件によってこの値超... | stack_v2_sparse_classes_75kplus_train_073690 | 4,958 | no_license | [
{
"docstring": "Parameters ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 h : float 空間の刻み幅 dt_max : float 時間刻み幅の最大値.実際の刻み幅は CFL 条件によってこの値超えない範囲で定まる. lbnd : float 境界条件.u(x_0, t) の値.Dirichlet 境界条件において定数が与えられた場合に対応する. ubnd : float 境界条件.u(x_1, t) の値.lbnd と同様. f : callable 支配方程式の f.u(x_i, t_n) をとって実数を返す関数... | 2 | stack_v2_sparse_classes_30k_train_040760 | Implement the Python class `AdvectionDiffusion1d` described below.
Class description:
非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max :... | Implement the Python class `AdvectionDiffusion1d` described below.
Class description:
非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max :... | b989fea731be95b67e8bba9f57aeeb503c4a7ee3 | <|skeleton|>
class AdvectionDiffusion1d:
"""非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max : float 時間刻み幅の最大値.実際の刻み幅は CFL 条件によってこの値超... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AdvectionDiffusion1d:
"""非線形移流拡散方程式のソルバ(1d) 支配方程式: ∂u/∂t + f(u) * ∂u/∂x = g * ∂/∂x(∂u/∂x) 手法: 陽解法(非定常項: 陽的 Euler,移流項: QUICK,拡散項: 中心差分) Attributes ---------- u0 : ndarray, shape (m,) 初期条件.u(x, t_0) を意味する。 t0 : float イテレーション開始時刻を保持する. h : float 空間の刻み幅 dt_max : float 時間刻み幅の最大値.実際の刻み幅は CFL 条件によってこの値超えない範囲で定まる.拡散項... | the_stack_v2_python_sparse | numerical/pde/advection_diffusion_1d.py | kotoji/numerical | train | 0 |
31d6a672af22fe2b9190574254903ff5c38b87e4 | [
"super().__init__()\nself.mse = nn.MSELoss(reduction='sum')\nself.mae = nn.L1Loss(reduction='sum')",
"pred2 = prediction.clone()\ntrue2 = target.clone()\npred2[pred2 < 0] = 0\npred2 = pred2 + 1e-06\ntrue2 = true2 + 1e-06\nl1_ = self.mae(prediction, target)\nl2_ = self.mse(prediction, target)\nl3_ = self.mse(torch... | <|body_start_0|>
super().__init__()
self.mse = nn.MSELoss(reduction='sum')
self.mae = nn.L1Loss(reduction='sum')
<|end_body_0|>
<|body_start_1|>
pred2 = prediction.clone()
true2 = target.clone()
pred2[pred2 < 0] = 0
pred2 = pred2 + 1e-06
true2 = true2 + 1... | MSLE loss negative mix 91. | MSLELossNegMix91 | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class MSLELossNegMix91:
"""MSLE loss negative mix 91."""
def __init__(self):
"""Initialize the loss."""
<|body_0|>
def forward(self, prediction: torch.Tensor, target: torch.Tensor) -> Any:
"""Forward pass in the loss. Args: prediction: predictions. target: groundtruth.... | stack_v2_sparse_classes_75kplus_train_073691 | 6,765 | permissive | [
{
"docstring": "Initialize the loss.",
"name": "__init__",
"signature": "def __init__(self)"
},
{
"docstring": "Forward pass in the loss. Args: prediction: predictions. target: groundtruth. Returns: loss value.",
"name": "forward",
"signature": "def forward(self, prediction: torch.Tensor... | 2 | null | Implement the Python class `MSLELossNegMix91` described below.
Class description:
MSLE loss negative mix 91.
Method signatures and docstrings:
- def __init__(self): Initialize the loss.
- def forward(self, prediction: torch.Tensor, target: torch.Tensor) -> Any: Forward pass in the loss. Args: prediction: predictions.... | Implement the Python class `MSLELossNegMix91` described below.
Class description:
MSLE loss negative mix 91.
Method signatures and docstrings:
- def __init__(self): Initialize the loss.
- def forward(self, prediction: torch.Tensor, target: torch.Tensor) -> Any: Forward pass in the loss. Args: prediction: predictions.... | 0b69b7d5b261f2f9af3984793c1295b9b80cd01a | <|skeleton|>
class MSLELossNegMix91:
"""MSLE loss negative mix 91."""
def __init__(self):
"""Initialize the loss."""
<|body_0|>
def forward(self, prediction: torch.Tensor, target: torch.Tensor) -> Any:
"""Forward pass in the loss. Args: prediction: predictions. target: groundtruth.... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class MSLELossNegMix91:
"""MSLE loss negative mix 91."""
def __init__(self):
"""Initialize the loss."""
super().__init__()
self.mse = nn.MSELoss(reduction='sum')
self.mae = nn.L1Loss(reduction='sum')
def forward(self, prediction: torch.Tensor, target: torch.Tensor) -> Any:
... | the_stack_v2_python_sparse | src/gt4sd/frameworks/granular/ml/models/loss.py | GT4SD/gt4sd-core | train | 239 |
90b763bfa49be06127cd90b70384cd28f72ad5cb | [
"curr_prod = nums[0]\nmax_prod = nums[0]\nfor i in range(1, len(nums)):\n print(f'current elem: {nums[i]}')\n print(f'current product before: {curr_prod}')\n curr_prod = max(nums[i], nums[i] * curr_prod)\n print(f'current product: {curr_prod}')\n if max_prod < curr_prod:\n max_prod = curr_prod... | <|body_start_0|>
curr_prod = nums[0]
max_prod = nums[0]
for i in range(1, len(nums)):
print(f'current elem: {nums[i]}')
print(f'current product before: {curr_prod}')
curr_prod = max(nums[i], nums[i] * curr_prod)
print(f'current product: {curr_prod}... | Solution | [
"MIT"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def max_product(self, nums):
"""Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: List[int] :rtype: int"""
<|body_0|>
def max_product_v2(self, numbers):
"""us... | stack_v2_sparse_classes_75kplus_train_073692 | 1,790 | permissive | [
{
"docstring": "Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: List[int] :rtype: int",
"name": "max_product",
"signature": "def max_product(self, nums)"
},
{
"docstring": "uses curr_max, curr_mi... | 2 | stack_v2_sparse_classes_30k_train_053138 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_product(self, nums): Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: ... | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def max_product(self, nums): Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: ... | 547c200b627c774535bc22880b16d5390183aeba | <|skeleton|>
class Solution:
def max_product(self, nums):
"""Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: List[int] :rtype: int"""
<|body_0|>
def max_product_v2(self, numbers):
"""us... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def max_product(self, nums):
"""Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. :type nums: List[int] :rtype: int"""
curr_prod = nums[0]
max_prod = nums[0]
for i in range(1, len(n... | the_stack_v2_python_sparse | medium/152_max_product_subarray.py | Sukhrobjon/leetcode | train | 0 | |
a82b9c3b0ccd9a8e17c5328e965f7d2e2bc6ce47 | [
"if len(s) < (1 << k) + k - 1:\n return False\ncur = int(s[:k], base=2)\ncodes = set([cur])\nbegin = 0\nend = k\nwhile len(codes) != 2 ** k and end < len(s):\n cur = (cur - 2 ** (k - 1) * int(s[begin]) << 1) + int(s[end])\n codes.add(cur)\n end += 1\n begin += 1\nreturn len(codes) == 2 ** k",
"code... | <|body_start_0|>
if len(s) < (1 << k) + k - 1:
return False
cur = int(s[:k], base=2)
codes = set([cur])
begin = 0
end = k
while len(codes) != 2 ** k and end < len(s):
cur = (cur - 2 ** (k - 1) * int(s[begin]) << 1) + int(s[end])
codes.a... | Solution | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Solution:
def hasAllCodes(self, s, k):
""":type s: str :type k: int :rtype: bool"""
<|body_0|>
def hasAllCodes1(self, s, k):
""":type s: str :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
if len(s) < (1 << k) + k - 1:
... | stack_v2_sparse_classes_75kplus_train_073693 | 1,032 | no_license | [
{
"docstring": ":type s: str :type k: int :rtype: bool",
"name": "hasAllCodes",
"signature": "def hasAllCodes(self, s, k)"
},
{
"docstring": ":type s: str :type k: int :rtype: bool",
"name": "hasAllCodes1",
"signature": "def hasAllCodes1(self, s, k)"
}
] | 2 | stack_v2_sparse_classes_30k_train_020934 | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasAllCodes(self, s, k): :type s: str :type k: int :rtype: bool
- def hasAllCodes1(self, s, k): :type s: str :type k: int :rtype: bool | Implement the Python class `Solution` described below.
Class description:
Implement the Solution class.
Method signatures and docstrings:
- def hasAllCodes(self, s, k): :type s: str :type k: int :rtype: bool
- def hasAllCodes1(self, s, k): :type s: str :type k: int :rtype: bool
<|skeleton|>
class Solution:
def ... | 9d394cd2862703cfb7a7b505b35deda7450a692e | <|skeleton|>
class Solution:
def hasAllCodes(self, s, k):
""":type s: str :type k: int :rtype: bool"""
<|body_0|>
def hasAllCodes1(self, s, k):
""":type s: str :type k: int :rtype: bool"""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Solution:
def hasAllCodes(self, s, k):
""":type s: str :type k: int :rtype: bool"""
if len(s) < (1 << k) + k - 1:
return False
cur = int(s[:k], base=2)
codes = set([cur])
begin = 0
end = k
while len(codes) != 2 ** k and end < len(s):
... | the_stack_v2_python_sparse | 1461.检查一个字符串是否包含所有长度为-k-的二进制子串.py | Ezi4Zy/leetcode | train | 0 | |
5083136297d4204de2f6ffb2a9474a24c32ef1dd | [
"error_message = ''\ntry:\n raise NoneUsernameOrPasswordError()\nexcept NoneUsernameOrPasswordError as error:\n error_message = str(error)\nself.assertEqual(settings.ERROR_MESSAGES['NoneUsernameOrPasswordError'], error_message)",
"error_message = ''\ntry:\n raise UsernameOrPasswordIncorrectError()\nexcep... | <|body_start_0|>
error_message = ''
try:
raise NoneUsernameOrPasswordError()
except NoneUsernameOrPasswordError as error:
error_message = str(error)
self.assertEqual(settings.ERROR_MESSAGES['NoneUsernameOrPasswordError'], error_message)
<|end_body_0|>
<|body_star... | 自定义错误测试 | ErrorsTest | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ErrorsTest:
"""自定义错误测试"""
def test_none_username_or_password_error(self):
"""测试没有发现用户或者密码错误"""
<|body_0|>
def test_username_or_password_incorrect_error(self):
"""测试用户名或者密码错误"""
<|body_1|>
def test_user_is_disable_error(self):
"""测试用户已经被禁用错误""... | stack_v2_sparse_classes_75kplus_train_073694 | 30,268 | no_license | [
{
"docstring": "测试没有发现用户或者密码错误",
"name": "test_none_username_or_password_error",
"signature": "def test_none_username_or_password_error(self)"
},
{
"docstring": "测试用户名或者密码错误",
"name": "test_username_or_password_incorrect_error",
"signature": "def test_username_or_password_incorrect_error... | 3 | stack_v2_sparse_classes_30k_train_040213 | Implement the Python class `ErrorsTest` described below.
Class description:
自定义错误测试
Method signatures and docstrings:
- def test_none_username_or_password_error(self): 测试没有发现用户或者密码错误
- def test_username_or_password_incorrect_error(self): 测试用户名或者密码错误
- def test_user_is_disable_error(self): 测试用户已经被禁用错误 | Implement the Python class `ErrorsTest` described below.
Class description:
自定义错误测试
Method signatures and docstrings:
- def test_none_username_or_password_error(self): 测试没有发现用户或者密码错误
- def test_username_or_password_incorrect_error(self): 测试用户名或者密码错误
- def test_user_is_disable_error(self): 测试用户已经被禁用错误
<|skeleton|>
cl... | 2685e65b8b4493ad25b35234fe6e2eef3bae091a | <|skeleton|>
class ErrorsTest:
"""自定义错误测试"""
def test_none_username_or_password_error(self):
"""测试没有发现用户或者密码错误"""
<|body_0|>
def test_username_or_password_incorrect_error(self):
"""测试用户名或者密码错误"""
<|body_1|>
def test_user_is_disable_error(self):
"""测试用户已经被禁用错误""... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ErrorsTest:
"""自定义错误测试"""
def test_none_username_or_password_error(self):
"""测试没有发现用户或者密码错误"""
error_message = ''
try:
raise NoneUsernameOrPasswordError()
except NoneUsernameOrPasswordError as error:
error_message = str(error)
self.assertEqu... | the_stack_v2_python_sparse | management/tests.py | axu4github/ceudp | train | 1 |
5a1d0de7d4f91f3736ff9955a1dcb67210f7d0c9 | [
"input_tensor_shape = [3, 96, 64, 1]\ninput_tensor = tf.ones(input_tensor_shape, dtype=tf.float32)\nm = tf.keras.Sequential([tf.keras.layers.Input((96, 64, 1)), augmentation.SpecAugment()])\nout = m(input_tensor, training=False)\nself.assertListEqual(list(out.shape), input_tensor_shape)\nself.assertAllEqual(out, in... | <|body_start_0|>
input_tensor_shape = [3, 96, 64, 1]
input_tensor = tf.ones(input_tensor_shape, dtype=tf.float32)
m = tf.keras.Sequential([tf.keras.layers.Input((96, 64, 1)), augmentation.SpecAugment()])
out = m(input_tensor, training=False)
self.assertListEqual(list(out.shape), ... | AugmentationTest | [
"Apache-2.0",
"CC-BY-4.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class AugmentationTest:
def test_spec_augment_inference(self):
"""Verify inference does not do augmentation."""
<|body_0|>
def test_spec_augment_training(self):
"""Verify augmentaion occurs during training."""
<|body_1|>
<|end_skeleton|>
<|body_start_0|>
... | stack_v2_sparse_classes_75kplus_train_073695 | 1,962 | permissive | [
{
"docstring": "Verify inference does not do augmentation.",
"name": "test_spec_augment_inference",
"signature": "def test_spec_augment_inference(self)"
},
{
"docstring": "Verify augmentaion occurs during training.",
"name": "test_spec_augment_training",
"signature": "def test_spec_augme... | 2 | null | Implement the Python class `AugmentationTest` described below.
Class description:
Implement the AugmentationTest class.
Method signatures and docstrings:
- def test_spec_augment_inference(self): Verify inference does not do augmentation.
- def test_spec_augment_training(self): Verify augmentaion occurs during trainin... | Implement the Python class `AugmentationTest` described below.
Class description:
Implement the AugmentationTest class.
Method signatures and docstrings:
- def test_spec_augment_inference(self): Verify inference does not do augmentation.
- def test_spec_augment_training(self): Verify augmentaion occurs during trainin... | 5573d9c5822f4e866b6692769963ae819cb3f10d | <|skeleton|>
class AugmentationTest:
def test_spec_augment_inference(self):
"""Verify inference does not do augmentation."""
<|body_0|>
def test_spec_augment_training(self):
"""Verify augmentaion occurs during training."""
<|body_1|>
<|end_skeleton|> | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class AugmentationTest:
def test_spec_augment_inference(self):
"""Verify inference does not do augmentation."""
input_tensor_shape = [3, 96, 64, 1]
input_tensor = tf.ones(input_tensor_shape, dtype=tf.float32)
m = tf.keras.Sequential([tf.keras.layers.Input((96, 64, 1)), augmentation.S... | the_stack_v2_python_sparse | non_semantic_speech_benchmark/data_prep/augmentation_test.py | Jimmy-INL/google-research | train | 1 | |
a9b4740bf1752bd31c6c6d5e3b7e4f05a655094a | [
"self._n1 = n1\nself._n2 = n2\nself._apex = 0\nself._cluster1 = list(range(1, n1 + 1))\nself._cluster2 = list(range(n1 + 1, n1 + n2 + 1))\nself._bridge = n1 + n2 + 1\ngraph = self._init_graph(p1, p2)\nsuper(ApexBridgeChipFiring, self).__init__(graph, chip_counts=chip_counts)",
"apex_graph = nx.Graph()\napex_graph... | <|body_start_0|>
self._n1 = n1
self._n2 = n2
self._apex = 0
self._cluster1 = list(range(1, n1 + 1))
self._cluster2 = list(range(n1 + 1, n1 + n2 + 1))
self._bridge = n1 + n2 + 1
graph = self._init_graph(p1, p2)
super(ApexBridgeChipFiring, self).__init__(gra... | A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. The two clusters are constructed from the G(n, p) model. | ApexBridgeChipFiring | [] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class ApexBridgeChipFiring:
"""A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. The two clusters are constructed from t... | stack_v2_sparse_classes_75kplus_train_073696 | 9,421 | no_license | [
{
"docstring": "Creates a new ApexBridgeChipFiring graph. This contains the following instance variables. _n1: The number of nodes in the first cluster. _n2: The number of nodes in the second cluster. _cluster1: The nodes in the first cluster. _cluster2: The nodes in the second cluster. _apex: The apex node. _b... | 2 | stack_v2_sparse_classes_30k_train_015495 | Implement the Python class `ApexBridgeChipFiring` described below.
Class description:
A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. ... | Implement the Python class `ApexBridgeChipFiring` described below.
Class description:
A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. ... | d209728c2700439378194fbac27f4d09488c91b4 | <|skeleton|>
class ApexBridgeChipFiring:
"""A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. The two clusters are constructed from t... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class ApexBridgeChipFiring:
"""A Round Based Chip Firing harness where the graph is an apex bridge graph. The apex bridge family of graphs are those with two clusters separated by a bridge node. Every node, including the bridge node is then connected to the apex. The two clusters are constructed from the G(n, p) mo... | the_stack_v2_python_sparse | harness.py | antaresc/sandpile | train | 0 |
c5aa9c70754851c5259b7b9aeb8d1a06c538fa17 | [
"self._dataset = dataset\nself._split_name = split_name\nself._is_training = is_training\nself._model_variant = model_variant\nself._num_readers = 8\nself._num_threads = 64",
"data_provider = dataset_data_provider.DatasetDataProvider(self._dataset, num_readers=self._num_readers, shuffle=self._is_training, num_epo... | <|body_start_0|>
self._dataset = dataset
self._split_name = split_name
self._is_training = is_training
self._model_variant = model_variant
self._num_readers = 8
self._num_threads = 64
<|end_body_0|>
<|body_start_1|>
data_provider = dataset_data_provider.DatasetDa... | Prepares data for TPUEstimator. | InputReader | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used ... | stack_v2_sparse_classes_75kplus_train_073697 | 4,902 | permissive | [
{
"docstring": "Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used for training. model_variant: String, model variant for choosing how to mean-subtract the images.",
"name": "__init__",
"signatu... | 2 | stack_v2_sparse_classes_30k_train_008142 | Implement the Python class `InputReader` described below.
Class description:
Prepares data for TPUEstimator.
Method signatures and docstrings:
- def __init__(self, dataset, split_name, is_training, model_variant): Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/te... | Implement the Python class `InputReader` described below.
Class description:
Prepares data for TPUEstimator.
Method signatures and docstrings:
- def __init__(self, dataset, split_name, is_training, model_variant): Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/te... | 0f7adb97a93ec3e3485c261d030c507eb16b33e4 | <|skeleton|>
class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used ... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class InputReader:
"""Prepares data for TPUEstimator."""
def __init__(self, dataset, split_name, is_training, model_variant):
"""Initializes slim Dataset etc. Args: dataset: slim Dataset. split_name: String, the name of train/eval/test split. is_training: Boolean, whether the data is used for training.... | the_stack_v2_python_sparse | models/experimental/deeplab/data_pipeline.py | tensorflow/tpu | train | 5,627 |
70c485addacd6123b87363181eba8dadd7a8e787 | [
"self._shallow_routes: Dict[str, List[AsyncCallback]] = {}\nself._deep_routes: Dict[str, Dict[str, Dict[Any, List[AsyncCallback]]]] = {}\nfor other_router in other_routers:\n for event_type, callbacks in other_router._shallow_routes.items():\n for callback in callbacks:\n self.add(callback, eve... | <|body_start_0|>
self._shallow_routes: Dict[str, List[AsyncCallback]] = {}
self._deep_routes: Dict[str, Dict[str, Dict[Any, List[AsyncCallback]]]] = {}
for other_router in other_routers:
for event_type, callbacks in other_router._shallow_routes.items():
for callback i... | An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically this is used when each semantic set of features has a router and are then us... | Router | [
"Apache-2.0"
] | stack_v2_sparse_python_classes_v1 | <|skeleton|>
class Router:
"""An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically this is used when each semantic set of fea... | stack_v2_sparse_classes_75kplus_train_073698 | 4,884 | permissive | [
{
"docstring": "Instantiate a new router (possibly from other routers).",
"name": "__init__",
"signature": "def __init__(self, *other_routers: 'Router') -> None"
},
{
"docstring": "Add an asynchronous callback for an event. The *event_type* argument corresponds to the :attr:`gidgetlab.sansio.Eve... | 4 | stack_v2_sparse_classes_30k_train_030972 | Implement the Python class `Router` described below.
Class description:
An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically thi... | Implement the Python class `Router` described below.
Class description:
An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically thi... | ae235f08ba9203f60bc20382d82c35244920977a | <|skeleton|>
class Router:
"""An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically this is used when each semantic set of fea... | stack_v2_sparse_classes_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Router:
"""An object to route a :class:`gidgetlab.sansio.Event` instance to appropriate registered asynchronous callbacks. The initializer for this class takes an arbitrary number of other routers to help build a single router from sub-routers. Typically this is used when each semantic set of features has a r... | the_stack_v2_python_sparse | gidgetlab/routing.py | beenje/gidgetlab | train | 1 |
922e39e75755aeb7f855f2618d22ce33a560477c | [
"res = []\n\ndef helper(node):\n if not node:\n return\n res.append(str(node.val))\n res.append(str(len(node.children)))\n for _ in node.children:\n helper(_)\nhelper(root)\nreturn ','.join(res)",
"if not data:\n return None\n\ndef helper(A):\n val = int(A.popleft())\n size = in... | <|body_start_0|>
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
for _ in node.children:
helper(_)
helper(root)
return ','.join(res)
<|end_body_0|... | 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_75kplus_train_073699 | 1,184 | no_license | [
{
"docstring": "Encodes a tree to a single string. :type root: Node :rtype: str",
"name": "serialize",
"signature": "def serialize(self, root: 'Node') -> str"
},
{
"docstring": "Decodes your encoded data to tree. :type data: str :rtype: Node",
"name": "deserialize",
"signature": "def des... | 2 | stack_v2_sparse_classes_30k_train_047127 | 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... | edff905f63ab95cdd40447b27a9c449c9cefec37 | <|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_75kplus | data/stack_v2_sparse_classes_30k | 75,829 | class Codec:
def serialize(self, root: 'Node') -> str:
"""Encodes a tree to a single string. :type root: Node :rtype: str"""
res = []
def helper(node):
if not node:
return
res.append(str(node.val))
res.append(str(len(node.children)))
... | the_stack_v2_python_sparse | _0428_Serialize_and_Deserialize_N_ary_Tree.py | mingweihe/leetcode | train | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.